| 42 | const MAX_ID_ATTEMPTS = 8; |
| 43 | |
| 44 | export class SessionCronStore { |
| 45 | /** |
| 46 | * Backing map. `Map` preserves insertion order in JS, which we rely on |
| 47 | * for {@link list}. |
| 48 | */ |
| 49 | private readonly tasks = new Map<string, CronTask>(); |
| 50 | |
| 51 | /** |
| 52 | * Generate a fresh 8-hex id and add the task. `createdAt` is set to |
| 53 | * the supplied `nowMs` — the store never reads its own clock. |
| 54 | * |
| 55 | * Throws if the PRNG fails to produce an unused id within |
| 56 | * {@link MAX_ID_ATTEMPTS} attempts. That should be unreachable in |
| 57 | * practice; surfacing it as a throw beats silently retrying forever. |
| 58 | */ |
| 59 | add(init: SessionCronTaskInit, nowMs: number): CronTask { |
| 60 | const id = this.generateUniqueId(); |
| 61 | const task: CronTask = { |
| 62 | ...init, |
| 63 | id, |
| 64 | createdAt: nowMs, |
| 65 | }; |
| 66 | this.tasks.set(id, task); |
| 67 | return task; |
| 68 | } |
| 69 | |
| 70 | /** |
| 71 | * Insert a previously-persisted task verbatim — id and createdAt |
| 72 | * stay as they are on disk. Used by `CronManager.loadFromDisk()` to |
| 73 | * rehydrate the store on resume. Unlike {@link add}, this does NOT |
| 74 | * generate a new id; the caller is responsible for ensuring the id |
| 75 | * matches the expected shape (the persistence layer's regex / |
| 76 | * shape-guard handle this upstream). |
| 77 | * |
| 78 | * Overwrites any existing in-memory task with the same id — reload |
| 79 | * is a "replace" operation, not a "merge". Callers that want merge |
| 80 | * semantics should clear the store first. |
| 81 | */ |
| 82 | adopt(task: CronTask): void { |
| 83 | this.tasks.set(task.id, task); |
| 84 | } |
| 85 | |
| 86 | /** |
| 87 | * Stamp `lastFiredAt` on the in-memory task. Used by the scheduler |
| 88 | * cursor-advance callback so the value flows back to disk via the |
| 89 | * manager's persistence path. Returns the updated record (so the |
| 90 | * manager can hand it straight to the per-id JSON writer), or |
| 91 | * `undefined` when no task with that id is present — the latter |
| 92 | * happens harmlessly if a task was concurrently removed between the |
| 93 | * scheduler's fire and the cursor callback. |
| 94 | */ |
| 95 | markFired(id: string, lastFiredAt: number): CronTask | undefined { |
| 96 | const existing = this.tasks.get(id); |
| 97 | if (existing === undefined) return undefined; |
| 98 | const updated: CronTask = { ...existing, lastFiredAt }; |
| 99 | this.tasks.set(id, updated); |
| 100 | return updated; |
| 101 | } |
nothing calls this directly
no outgoing calls
no test coverage detected