import type { GraphApi } from '@astrale-os/sdk/client' import type { GraphStore as GraphStoreValue } from '@astrale-os/sdk/client/store' import type { Shell } from '@astrale-os/shell' import { GraphStore } from '@astrale-os/sdk/client/store' import { useContext } from 'react' import { GraphContext } from './graph.context.js' interface StoreEntry { readonly shell: Shell readonly graph: GraphApi readonly scope: string readonly store: GraphStoreValue readonly owned: boolean retained: number generation: number } const entries = new WeakMap() /** Authority/schema identity. Session ids and Publication ETags are deliberately absent. */ export interface GraphStoreScope { readonly authority: string readonly schemaRevision: string } type StoreIdentity = Awaited> export async function resolveGraphStoreScope( shell: Shell, knownIdentity?: StoreIdentity | null, ): Promise { const [identity, snapshot] = await Promise.all([ knownIdentity === undefined ? shell.kernel.auth.whoami().catch(() => null) : Promise.resolve(knownIdentity), shell.kernel.snapshot(), ]) return Object.freeze({ authority: identity === null ? 'anonymous' : `${identity.issuer}\u0000${identity.subject}\u0000${identity.id}`, schemaRevision: snapshot.publication.schema.revision, }) } export function storeFor(shell: Shell, scope: GraphStoreScope): StoreEntry { const current = entries.get(shell) const scopeKey = `${scope.authority}\u0000${scope.schemaRevision}` if (current !== undefined && current.graph === shell.kernel.graph && current.scope === scopeKey) { return current } const supplied = shell.kernel.store const created: StoreEntry = { shell, graph: shell.kernel.graph, scope: scopeKey, // A supplied Store is trusted only for the KernelClient's first declared scope. A later // authority/revision/GraphApi replacement gets a new Store and cannot inherit old memory. store: current === undefined && supplied !== undefined ? supplied : new GraphStore({ graph: shell.kernel.graph }), owned: current !== undefined || supplied === undefined, retained: 0, generation: 0, } entries.set(shell, created) if (current !== undefined && current.retained === 0 && current.owned) current.store.close() return created } export function retainStore(entry: StoreEntry): () => void { entry.generation += 1 entry.retained += 1 let released = false return () => { if (released) return released = true entry.retained -= 1 const generation = ++entry.generation queueMicrotask(() => { if (entry.retained !== 0 || entry.generation !== generation || !entry.owned) return if (entries.get(entry.shell) === entry) entries.delete(entry.shell) entry.store.close() }) } } /** The exact caller/schema-scoped GraphStore for the current View subtree. */ export function useGraphStore(): GraphStoreValue { const store = useContext(GraphContext) if (store === null) throw new Error('useGraphStore must be used within a ') return store }