fix(store): hold session texts whose set-aside fails, never overwrite them
This commit is contained in:
1 parent
1312b366b1
commit
e34b7f282e
19 files changed
+1093
-86
No files matched your search
@@ -14,12 +14,13 @@ import type { Report, ReportArchiveEnvelope } from '@faunosteo/core-wasm/types'
|
||||
export interface ReportPersistence {
|
||||
/** The raw draft text, null when there is none. */
|
||||
loadText(): string | null
|
||||
save(report: Report | null): void
|
||||
/** Writes (or removes, for null) the draft; false when the storage refused the write. */
|
||||
save(report: Report | null): boolean
|
||||
}
|
||||
|
||||
export interface ArchivePersistence {
|
||||
loadText(): string | null
|
||||
save(archive: ReportArchiveEnvelope | null): void
|
||||
save(archive: ReportArchiveEnvelope | null): boolean
|
||||
}
|
||||
|
||||
export const DRAFT_KEY = 'osteo:draft'
|
||||
@@ -38,25 +39,49 @@ function storage(): Storage | null {
|
||||
return typeof sessionStorage === 'undefined' ? null : sessionStorage
|
||||
}
|
||||
|
||||
function writeOrRemove(key: string, value: unknown): void {
|
||||
/** A refused write (quota) leaves the previous value in place, as the Storage API does. */
|
||||
function writeOrRemove(key: string, value: unknown): boolean {
|
||||
const store = storage()
|
||||
if (!store) return
|
||||
if (!store) return false
|
||||
if (value === null) {
|
||||
store.removeItem(key)
|
||||
return
|
||||
return true
|
||||
}
|
||||
try {
|
||||
store.setItem(key, JSON.stringify(value))
|
||||
return true
|
||||
} catch (err) {
|
||||
// Quota exceeded: the session goes on, only the mirror is lost.
|
||||
if (import.meta.env.DEV) console.warn(`${key} not saved`, err)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes `raw` into an empty quarantine slot; a slot already holding another text is
|
||||
* never replaced (that earlier text would be lost). Answers whether `raw` is now in
|
||||
* the slot and whether this call wrote it (so a failed pair can undo its own copy).
|
||||
*/
|
||||
function copyToSlot(
|
||||
store: Storage,
|
||||
slot: QuarantineSlot,
|
||||
raw: string,
|
||||
): 'written' | 'present' | 'refused' {
|
||||
const current = store.getItem(QUARANTINE_KEYS[slot])
|
||||
if (current === raw) return 'present'
|
||||
if (current !== null) return 'refused'
|
||||
try {
|
||||
store.setItem(QUARANTINE_KEYS[slot], raw)
|
||||
return 'written'
|
||||
} catch (err) {
|
||||
if (import.meta.env.DEV) console.warn(`${slot} not set aside`, err)
|
||||
return 'refused'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies `raw` into its quarantine slot, then removes `source` (when given)
|
||||
* only if that copy succeeded: a full storage keeps the text where it was.
|
||||
* Returns whether the text is now in quarantine.
|
||||
* only if that copy succeeded: a full storage or an occupied slot keeps the
|
||||
* text where it was. Returns whether the text is now in quarantine.
|
||||
*/
|
||||
export function quarantine(
|
||||
slot: QuarantineSlot,
|
||||
@@ -65,26 +90,49 @@ export function quarantine(
|
||||
): boolean {
|
||||
const store = storage()
|
||||
if (!store) return false
|
||||
try {
|
||||
store.setItem(QUARANTINE_KEYS[slot], raw)
|
||||
} catch (err) {
|
||||
if (import.meta.env.DEV) console.warn(`${slot} not set aside`, err)
|
||||
return false
|
||||
}
|
||||
if (copyToSlot(store, slot, raw) === 'refused') return false
|
||||
if (source) store.removeItem(source)
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets an unreadable draft aside together with the archive kept beside it, so a
|
||||
* later session never removes that archive on its own. Both copies or neither:
|
||||
* when one fails, the copy this call wrote is undone and both texts stay in place.
|
||||
*/
|
||||
export function quarantineSession(draft: string, archive: string | null): boolean {
|
||||
const store = storage()
|
||||
if (!store) return false
|
||||
const draftCopy = copyToSlot(store, 'draft', draft)
|
||||
if (draftCopy === 'refused') return false
|
||||
if (archive !== null && copyToSlot(store, 'archive', archive) === 'refused') {
|
||||
if (draftCopy === 'written') store.removeItem(QUARANTINE_KEYS.draft)
|
||||
return false
|
||||
}
|
||||
store.removeItem(DRAFT_KEY)
|
||||
if (archive !== null) store.removeItem(ARCHIVE_KEY)
|
||||
return true
|
||||
}
|
||||
|
||||
/** The session texts a resolution may download or remove, by their kind. */
|
||||
export const SESSION_KEYS = { draft: DRAFT_KEY, archive: ARCHIVE_KEY } as const
|
||||
export type SessionText = keyof typeof SESSION_KEYS
|
||||
|
||||
export function readSessionText(text: SessionText): string | null {
|
||||
return storage()?.getItem(SESSION_KEYS[text]) ?? null
|
||||
}
|
||||
|
||||
/** Removes a session text: only ever called on the practitioner's confirmed request. */
|
||||
export function removeSessionText(text: SessionText): void {
|
||||
storage()?.removeItem(SESSION_KEYS[text])
|
||||
}
|
||||
|
||||
export const sessionStoragePersistence: ReportPersistence = {
|
||||
loadText: () => storage()?.getItem(DRAFT_KEY) ?? null,
|
||||
save(report) {
|
||||
writeOrRemove(DRAFT_KEY, report)
|
||||
},
|
||||
save: (report) => writeOrRemove(DRAFT_KEY, report),
|
||||
}
|
||||
|
||||
export const sessionStorageArchivePersistence: ArchivePersistence = {
|
||||
loadText: () => storage()?.getItem(ARCHIVE_KEY) ?? null,
|
||||
save(archive) {
|
||||
writeOrRemove(ARCHIVE_KEY, archive)
|
||||
},
|
||||
save: (archive) => writeOrRemove(ARCHIVE_KEY, archive),
|
||||
}
|
||||
@@ -18,12 +18,14 @@ import { nowIso } from '@/lib/dates'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
import {
|
||||
ARCHIVE_KEY,
|
||||
DRAFT_KEY,
|
||||
quarantine,
|
||||
quarantineSession,
|
||||
removeSessionText,
|
||||
sessionStorageArchivePersistence,
|
||||
sessionStoragePersistence,
|
||||
type ArchivePersistence,
|
||||
type ReportPersistence,
|
||||
type SessionText,
|
||||
} from './persistence'
|
||||
|
||||
/**
|
||||
@@ -37,6 +39,9 @@ import {
|
||||
* The per-tab draft is mirrored through the persistence adapter and restored
|
||||
* once the sheet is known; the archive an import brought along is kept
|
||||
* beside the report and written only when the session starts or ends.
|
||||
* A session text this page has not read, or whose safety copy failed, is
|
||||
* never removed or overwritten implicitly: restore holds it, and a new
|
||||
* session (new report, import) is refused until the practitioner resolves it.
|
||||
*/
|
||||
|
||||
export type { NewReportDraft }
|
||||
@@ -48,6 +53,26 @@ export interface ImportedSession {
|
||||
|
||||
export interface ActionResult {
|
||||
ok: boolean
|
||||
/** Refused because a session text is held (it could not be set aside and would be lost). */
|
||||
reason?: 'held'
|
||||
}
|
||||
|
||||
/**
|
||||
* A session text kept in place because its safety copy failed (storage full, or the
|
||||
* quarantine slot already holds an earlier text): `unreadable` by this build, the
|
||||
* archive `companion` of an unreadable draft, or a draft whose `pre_rebase` original
|
||||
* could not be kept before the rebase replaces it.
|
||||
*/
|
||||
export interface HeldText {
|
||||
text: SessionText
|
||||
reason: 'unreadable' | 'companion' | 'pre_rebase'
|
||||
/** UTF-8 size of the stored text, for the resolution panel. */
|
||||
bytes: number
|
||||
}
|
||||
|
||||
export interface RestoreOptions {
|
||||
/** The practitioner confirmed that the rebased draft may replace its original. */
|
||||
replaceOriginal?: boolean
|
||||
}
|
||||
|
||||
/** What a draft restore did; `null` from the action when there was nothing to restore. */
|
||||
@@ -56,10 +81,10 @@ export type RestoreResult =
|
||||
/** The draft is unreadable by this build: set aside, verbatim, under a quarantine key. */
|
||||
| { kind: 'quarantined' }
|
||||
/**
|
||||
* The draft is unreadable but could not be set aside (storage full): it stays in
|
||||
* `osteo:draft`, and the caller must not start anything that would overwrite it.
|
||||
* Texts that could not be set aside stay where they are, nothing is opened, and the
|
||||
* store refuses any new session until they are resolved.
|
||||
*/
|
||||
| { kind: 'unreadable_kept' }
|
||||
| { kind: 'held'; held: HeldText[] }
|
||||
/** The core failed: nothing read, nothing written, the draft is where it was. */
|
||||
| { kind: 'core_unavailable' }
|
||||
|
||||
@@ -68,15 +93,27 @@ export interface ReportStore {
|
||||
/** The envelope of the imported archive, as exported; null otherwise. */
|
||||
archive: ReportArchiveEnvelope | null
|
||||
activeObservationIndex: number
|
||||
initReport: (draft: NewReportDraft, sheet: SheetRef) => ActionResult
|
||||
/** Opens an imported report (read and rebased by the core) with its archive. */
|
||||
hydrateImport: (session: ImportedSession) => void
|
||||
/** The last draft mirror write was refused (storage full): the tab's copy is stale. */
|
||||
saveFailed: boolean
|
||||
/** Starts a report; refused (`held`) while an unread session text cannot be set aside. */
|
||||
initReport: (
|
||||
draft: NewReportDraft,
|
||||
sheet: SheetRef,
|
||||
index: SheetIndex,
|
||||
) => ActionResult
|
||||
/** Opens an imported report (read and rebased by the core) with its archive; same guard. */
|
||||
hydrateImport: (session: ImportedSession, index: SheetIndex) => ActionResult
|
||||
/**
|
||||
* Restores the per-tab draft on the loaded sheet, rebasing it when it was
|
||||
* written on another revision; a no-op (null) when a report is already open
|
||||
* or there is no draft.
|
||||
* or there is nothing to restore.
|
||||
*/
|
||||
restoreDraft: (index: SheetIndex) => RestoreResult | null
|
||||
restoreDraft: (
|
||||
index: SheetIndex,
|
||||
options?: RestoreOptions,
|
||||
) => RestoreResult | null
|
||||
/** Removes a held session text, on the practitioner's confirmed request; no-op once a report is open. */
|
||||
discardSessionText: (text: SessionText) => void
|
||||
addObservation: () => ActionResult
|
||||
removeObservation: (index: number) => ActionResult
|
||||
moveObservationUp: (index: number) => ActionResult
|
||||
@@ -93,13 +130,14 @@ export interface ReportStore {
|
||||
}
|
||||
|
||||
type Patch = Partial<
|
||||
Pick<ReportStore, 'report' | 'archive' | 'activeObservationIndex'>
|
||||
Pick<ReportStore, 'report' | 'archive' | 'activeObservationIndex' | 'saveFailed'>
|
||||
>
|
||||
type Setter = (fn: (s: ReportStore) => Patch | ReportStore) => void
|
||||
type Getter = () => ReportStore
|
||||
|
||||
const OK: ActionResult = { ok: true }
|
||||
const FAILED: ActionResult = { ok: false }
|
||||
const HELD: ActionResult = { ok: false, reason: 'held' }
|
||||
|
||||
function onReport(set: Setter, update: (r: Report, s: ReportStore) => Patch) {
|
||||
set((s) => (s.report ? update(s.report, s) : s))
|
||||
@@ -134,37 +172,94 @@ const UNREADABLE_DRAFT_KINDS: ReadonlySet<string> = new Set([
|
||||
'lone_surrogate',
|
||||
])
|
||||
|
||||
/** Reads the draft through the core; unreadable content goes to quarantine, never away. */
|
||||
function utf8Bytes(text: string): number {
|
||||
return new TextEncoder().encode(text).length
|
||||
}
|
||||
|
||||
function held(text: SessionText, reason: HeldText['reason'], raw: string): HeldText {
|
||||
return { text, reason, bytes: utf8Bytes(raw) }
|
||||
}
|
||||
|
||||
type Restored = { result: RestoreResult; patch?: Patch } | null
|
||||
|
||||
/** An archive with no draft beside it can never be restored: set it aside, or hold it. */
|
||||
function restoreOrphanArchive(archiveText: string | null): Restored {
|
||||
if (archiveText === null || quarantine('archive', archiveText, ARCHIVE_KEY)) return null
|
||||
return { result: { kind: 'held', held: [held('archive', 'companion', archiveText)] } }
|
||||
}
|
||||
|
||||
/** An unreadable draft goes to quarantine with its archive, never away; else both are held. */
|
||||
function setAsideUnreadable(draft: string, archiveText: string | null): Restored {
|
||||
if (quarantineSession(draft, archiveText)) return { result: { kind: 'quarantined' } }
|
||||
const kept = [held('draft', 'unreadable', draft)]
|
||||
if (archiveText !== null) kept.push(held('archive', 'companion', archiveText))
|
||||
return { result: { kind: 'held', held: kept } }
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the draft through the core. Unreadable content goes to quarantine, never away;
|
||||
* a text whose safety copy fails is held in place and nothing is opened (opening would
|
||||
* let the mirror overwrite the draft, or a later session remove the archive).
|
||||
*/
|
||||
function restore(
|
||||
index: SheetIndex,
|
||||
persistence: ReportPersistence,
|
||||
archives: ArchivePersistence,
|
||||
): { result: RestoreResult; patch?: Patch } | null {
|
||||
options: RestoreOptions,
|
||||
): Restored {
|
||||
const draft = persistence.loadText()
|
||||
if (draft === null) return null
|
||||
const archiveText = archives.loadText()
|
||||
if (draft === null) return restoreOrphanArchive(archiveText)
|
||||
const outcome = index.ops.restoreDraft(draft, archiveText)
|
||||
if (!outcome.ok) {
|
||||
// Only an unreadable draft is set aside; a core or sheet failure leaves it in place.
|
||||
if (!UNREADABLE_DRAFT_KINDS.has(outcome.kind)) {
|
||||
return { result: { kind: 'core_unavailable' } }
|
||||
}
|
||||
const setAside = quarantine('draft', draft, DRAFT_KEY)
|
||||
return { result: { kind: setAside ? 'quarantined' : 'unreadable_kept' } }
|
||||
return setAsideUnreadable(draft, archiveText)
|
||||
}
|
||||
const { rebase, archive, archiveRejected } = outcome.value
|
||||
const kept: HeldText[] = []
|
||||
if (archiveRejected && archiveText !== null) {
|
||||
quarantine('archive', archiveText, ARCHIVE_KEY)
|
||||
if (!quarantine('archive', archiveText, ARCHIVE_KEY)) {
|
||||
kept.push(held('archive', 'unreadable', archiveText))
|
||||
}
|
||||
}
|
||||
if (rebase.rebased && rebase.unresolvedZones + rebase.unresolvedFindings > 0) {
|
||||
quarantine('draftPreRebase', draft)
|
||||
const flagged = rebase.unresolvedZones + rebase.unresolvedFindings > 0
|
||||
if (rebase.rebased && flagged && !options.replaceOriginal) {
|
||||
if (!quarantine('draftPreRebase', draft)) {
|
||||
kept.push(held('draft', 'pre_rebase', draft))
|
||||
}
|
||||
}
|
||||
if (kept.length > 0) return { result: { kind: 'held', held: kept } }
|
||||
return {
|
||||
result: { kind: 'restored', rebase },
|
||||
patch: { report: rebase.report, archive, activeObservationIndex: 0 },
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Before a new session replaces texts this page never read: an unreadable draft (and its
|
||||
* archive) or an unreadable archive is set aside first; a readable draft is replaced as
|
||||
* before. False when something could not be set aside, or could not even be read.
|
||||
*/
|
||||
function releaseUnreadSession(
|
||||
index: SheetIndex,
|
||||
persistence: ReportPersistence,
|
||||
archives: ArchivePersistence,
|
||||
): boolean {
|
||||
const draft = persistence.loadText()
|
||||
const archiveText = archives.loadText()
|
||||
if (draft === null) return restoreOrphanArchive(archiveText) === null
|
||||
const outcome = index.ops.restoreDraft(draft, archiveText)
|
||||
if (!outcome.ok) {
|
||||
if (!UNREADABLE_DRAFT_KINDS.has(outcome.kind)) return false
|
||||
return quarantineSession(draft, archiveText)
|
||||
}
|
||||
if (!outcome.value.archiveRejected || archiveText === null) return true
|
||||
return quarantine('archive', archiveText, ARCHIVE_KEY)
|
||||
}
|
||||
|
||||
export function createReportStore(
|
||||
persistence: ReportPersistence,
|
||||
archives: ArchivePersistence,
|
||||
@@ -175,12 +270,19 @@ export function createReportStore(
|
||||
return { ...patch, archive }
|
||||
}
|
||||
|
||||
/** A new session may start: either one is open (its texts are this store's), or none is left unread. */
|
||||
const mayStartSession = (index: SheetIndex) =>
|
||||
store.getState().report !== null ||
|
||||
releaseUnreadSession(index, persistence, archives)
|
||||
|
||||
const store = create<ReportStore>((set, get) => ({
|
||||
report: null,
|
||||
archive: null,
|
||||
activeObservationIndex: 0,
|
||||
saveFailed: false,
|
||||
|
||||
initReport: (draft, sheet) => {
|
||||
initReport: (draft, sheet, index) => {
|
||||
if (!mayStartSession(index)) return HELD
|
||||
const outcome = reportOps.newReport({
|
||||
draft,
|
||||
sheet,
|
||||
@@ -193,17 +295,25 @@ export function createReportStore(
|
||||
return OK
|
||||
},
|
||||
|
||||
hydrateImport: ({ report, archive }) =>
|
||||
set(withArchive({ report, activeObservationIndex: 0 }, archive)),
|
||||
hydrateImport: ({ report, archive }, index) => {
|
||||
if (!mayStartSession(index)) return HELD
|
||||
set(withArchive({ report, activeObservationIndex: 0 }, archive))
|
||||
return OK
|
||||
},
|
||||
|
||||
restoreDraft: (index) => {
|
||||
restoreDraft: (index, options = {}) => {
|
||||
if (get().report) return null
|
||||
const restored = restore(index, persistence, archives)
|
||||
const restored = restore(index, persistence, archives, options)
|
||||
if (!restored) return null
|
||||
if (restored.patch) set(restored.patch)
|
||||
return restored.result
|
||||
},
|
||||
|
||||
discardSessionText: (text) => {
|
||||
if (get().report) return
|
||||
removeSessionText(text)
|
||||
},
|
||||
|
||||
addObservation: () =>
|
||||
applyCore(
|
||||
set,
|
||||
@@ -265,10 +375,18 @@ export function createReportStore(
|
||||
delete rest.nextAppointment
|
||||
return { report: next ? { ...rest, nextAppointment: next } : rest }
|
||||
}),
|
||||
reset: () =>
|
||||
set(withArchive({ report: null, activeObservationIndex: 0 }, null)),
|
||||
// Ends the open session only: with none open, the tab's texts are not this store's.
|
||||
reset: () => {
|
||||
if (!get().report) return
|
||||
set(withArchive({ report: null, activeObservationIndex: 0 }, null))
|
||||
},
|
||||
}))
|
||||
store.subscribe((state) => persistence.save(state.report))
|
||||
// The mirror follows the report only: an unrelated change never writes or removes the draft.
|
||||
store.subscribe((state, prev) => {
|
||||
if (state.report === prev.report) return
|
||||
const failed = !persistence.save(state.report)
|
||||
if (failed !== state.saveFailed) store.setState({ saveFailed: failed })
|
||||
})
|
||||
return store
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user