| 1 | import type { ProjectNode } from "./types"; |
| 2 | import { canonicalProjectSession, projectSessionIdentity, projectSessionKeys } from "./projectSessionIdentity"; |
| 3 | |
| 4 | type Fence = { generation: number; operationId: string; aliases: readonly string[]; canonical?: string }; |
| 5 | |
| 6 | /** Application-owned: remounting the sidebar cannot revive a committed archive. |
| 7 | * An active directory row with a newer lifecycle proves explicit restoration. |
| 8 | * Runtime revisions cannot establish that proof and never release this fence. |
| 9 | */ |
| 10 | export function createSessionLifecycleFences() { |
| 11 | const fences = new Map<string, Fence>(); |
| 12 | return { |
| 13 | archive(node: ProjectNode, receipt: { lifecycleGeneration: number; operationId: string; identityAliases?: string[] }) { |
| 14 | const aliases = [...new Set([...projectSessionKeys(node), ...(receipt.identityAliases ?? [])])]; |
| 15 | const canonical = canonicalProjectSession(node); |
| 16 | const owners = canonical ? [canonical] : aliases.filter(key => key.startsWith("ref\u0000")); |
| 17 | // A source archive may adopt one or more canonical targets. Retain each |
| 18 | // receipt owner separately so restoring one cannot release its siblings. |
| 19 | for (const key of owners.length ? owners : [projectSessionIdentity(node)]) { |
| 20 | const fence = { generation: receipt.lifecycleGeneration, operationId: receipt.operationId, |
| 21 | canonical: owners.length ? key : undefined, |
| 22 | aliases: aliases.filter(alias => !alias.startsWith("ref\u0000") || alias === key) }; |
| 23 | if ((fences.get(key)?.generation ?? -1) <= fence.generation) fences.set(key, fence); |
| 24 | } |
| 25 | }, |
| 26 | observeDirectory(nodes: readonly ProjectNode[]) { |
| 27 | const visit = (node: ProjectNode) => { |
| 28 | const canonical = canonicalProjectSession(node); |
| 29 | for (const key of canonical ? [canonical] : projectSessionKeys(node)) { |
| 30 | const fence = fences.get(key); |
| 31 | if (fence && (!fence.canonical || fence.canonical === canonical) && !node.runtimeOnly && (node.lifecycleGeneration ?? 0) > fence.generation) { |
| 32 | fences.delete(key); |
| 33 | } |
| 34 | } |
| 35 | node.children?.forEach(visit); |
| 36 | }; |
| 37 | nodes.forEach(visit); |
| 38 | }, |
| 39 | keys(): ReadonlySet<string> { return new Set([...fences.values()].flatMap(fence => fence.aliases)); }, |
| 40 | }; |
| 41 | } |
| 42 | |
| 43 | export const sessionLifecycleFences = createSessionLifecycleFences(); |
| 44 |