207 lines
6.0 KiB
TypeScript
207 lines
6.0 KiB
TypeScript
// The Idempotency-Key of the demonstration express start is kept in this
|
|
// tab's sessionStorage, one entry per account. The server answers 409
|
|
// state_conflict to a new start while an express run is active, and replays
|
|
// the stored 201 with the active attempt when the same start is repeated with
|
|
// the key that created it (within 24 hours). Keeping that key lets an
|
|
// unfinished run be resumed after a reload instead of being blocked.
|
|
//
|
|
// The entry holds two keys:
|
|
// - activeKey: the key whose start created the newest known run;
|
|
// - pendingKey: the key of a start whose outcome is not known yet, so a lost
|
|
// response is repeated with the same key after a reload.
|
|
// Storage can be blocked or full, so every access is guarded and the flow
|
|
// works without it (a reload then cannot resume the run).
|
|
|
|
const keyPrefix = "lincodex.assessment-express-start.v1";
|
|
|
|
/** The server keeps an Idempotency-Key for 24 hours; older entries are dropped. */
|
|
export const expressReplayWindowMs = 24 * 60 * 60 * 1000;
|
|
|
|
const idempotencyKeyPattern = /^[A-Za-z0-9._:-]{1,255}$/;
|
|
const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
|
|
export type ExpressStartEntry = {
|
|
activeKey: string | null;
|
|
activeAttemptId: string | null;
|
|
pendingKey: string | null;
|
|
/** Epoch milliseconds of the last write. */
|
|
storedAt: number;
|
|
};
|
|
|
|
type StartStore = Pick<Storage, "getItem" | "setItem" | "removeItem">;
|
|
|
|
function sessionStore(): StartStore | null {
|
|
try {
|
|
return window.sessionStorage;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function entryKey(accountId: string): string {
|
|
return `${keyPrefix}:${accountId}`;
|
|
}
|
|
|
|
function optionalMatch(value: unknown, pattern: RegExp): value is string | null {
|
|
return value === null || (typeof value === "string" && pattern.test(value));
|
|
}
|
|
|
|
function parseEntry(raw: string, now: number): ExpressStartEntry | null {
|
|
let value: unknown;
|
|
try {
|
|
value = JSON.parse(raw);
|
|
} catch {
|
|
return null;
|
|
}
|
|
if (typeof value !== "object" || value === null) return null;
|
|
const entry = value as Record<string, unknown>;
|
|
if (
|
|
!optionalMatch(entry.activeKey, idempotencyKeyPattern) ||
|
|
!optionalMatch(entry.pendingKey, idempotencyKeyPattern) ||
|
|
!optionalMatch(entry.activeAttemptId, uuidPattern) ||
|
|
typeof entry.storedAt !== "number" ||
|
|
!Number.isFinite(entry.storedAt) ||
|
|
now - entry.storedAt > expressReplayWindowMs ||
|
|
entry.storedAt - now > expressReplayWindowMs
|
|
) {
|
|
return null;
|
|
}
|
|
return {
|
|
activeKey: entry.activeKey,
|
|
activeAttemptId: entry.activeAttemptId,
|
|
pendingKey: entry.pendingKey,
|
|
storedAt: entry.storedAt,
|
|
};
|
|
}
|
|
|
|
/** The stored express start of an account, or null when absent, invalid, or older than 24 h. */
|
|
export function readExpressStart(
|
|
accountId: string,
|
|
store: StartStore | null = sessionStore(),
|
|
now = Date.now(),
|
|
): ExpressStartEntry | null {
|
|
if (!store) return null;
|
|
try {
|
|
const raw = store.getItem(entryKey(accountId));
|
|
return raw === null ? null : parseEntry(raw, now);
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function writeEntry(
|
|
accountId: string,
|
|
entry: Omit<ExpressStartEntry, "storedAt">,
|
|
store: StartStore | null,
|
|
now: number,
|
|
): void {
|
|
if (!store) return;
|
|
try {
|
|
if (!entry.activeKey && !entry.pendingKey) {
|
|
store.removeItem(entryKey(accountId));
|
|
return;
|
|
}
|
|
store.setItem(entryKey(accountId), JSON.stringify({ ...entry, storedAt: now }));
|
|
} catch {
|
|
// A full or blocked store keeps the key in memory only.
|
|
}
|
|
}
|
|
|
|
/**
|
|
* The key of the next express start: the start still waiting for an outcome
|
|
* keeps its key, otherwise a fresh one. The chosen key is stored as pending
|
|
* before the request is sent; the key of the known run is kept for a replay.
|
|
*/
|
|
export function beginExpressStart(
|
|
accountId: string,
|
|
inMemoryKey: string | null,
|
|
newKey: () => string,
|
|
store: StartStore | null = sessionStore(),
|
|
now = Date.now(),
|
|
): string {
|
|
const entry = readExpressStart(accountId, store, now);
|
|
const key = inMemoryKey ?? entry?.pendingKey ?? newKey();
|
|
writeEntry(
|
|
accountId,
|
|
{
|
|
activeKey: entry?.activeKey ?? null,
|
|
activeAttemptId: entry?.activeAttemptId ?? null,
|
|
pendingKey: key,
|
|
},
|
|
store,
|
|
now,
|
|
);
|
|
return key;
|
|
}
|
|
|
|
/** The start with this key created (or replayed) this run; it becomes the active one. */
|
|
export function recordExpressRun(
|
|
accountId: string,
|
|
key: string,
|
|
attemptId: string,
|
|
store: StartStore | null = sessionStore(),
|
|
now = Date.now(),
|
|
): void {
|
|
writeEntry(
|
|
accountId,
|
|
{ activeKey: key, activeAttemptId: attemptId, pendingKey: null },
|
|
store,
|
|
now,
|
|
);
|
|
}
|
|
|
|
/**
|
|
* The pending start was answered without a run (for example 409 or 400). The
|
|
* key of the known run, if any, stays for a replay and is returned unless it
|
|
* is the key that was just refused.
|
|
*/
|
|
export function settleRefusedExpressStart(
|
|
accountId: string,
|
|
refusedKey: string,
|
|
store: StartStore | null = sessionStore(),
|
|
now = Date.now(),
|
|
): string | null {
|
|
const entry = readExpressStart(accountId, store, now);
|
|
const activeKey = entry?.activeKey && entry.activeKey !== refusedKey ? entry.activeKey : null;
|
|
writeEntry(
|
|
accountId,
|
|
{
|
|
activeKey,
|
|
activeAttemptId: activeKey ? (entry?.activeAttemptId ?? null) : null,
|
|
pendingKey: null,
|
|
},
|
|
store,
|
|
now,
|
|
);
|
|
return activeKey;
|
|
}
|
|
|
|
/**
|
|
* Forgets the stored start of an account. With an attempt id, only an entry
|
|
* of that run is removed: a finished or expired run cannot be resumed.
|
|
*/
|
|
export function forgetExpressStart(
|
|
accountId: string,
|
|
attemptId?: string,
|
|
store: StartStore | null = sessionStore(),
|
|
now = Date.now(),
|
|
): void {
|
|
if (!store) return;
|
|
const entry = readExpressStart(accountId, store, now);
|
|
if (attemptId !== undefined && entry && entry.activeAttemptId !== attemptId) return;
|
|
if (attemptId !== undefined && entry?.pendingKey) {
|
|
writeEntry(
|
|
accountId,
|
|
{ activeKey: null, activeAttemptId: null, pendingKey: entry.pendingKey },
|
|
store,
|
|
now,
|
|
);
|
|
return;
|
|
}
|
|
try {
|
|
store.removeItem(entryKey(accountId));
|
|
} catch {
|
|
// Nothing to forget when storage is blocked.
|
|
}
|
|
}
|