app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

extension-scheduler.ts (8216B)


      1 import { canonicalPublicKey } from '../contracts/public-key.ts';
      2 
      3 declare const schedulerBrand: unique symbol;
      4 declare const actionBrand: unique symbol;
      5 export type ExtensionScheduler = Readonly<{ [schedulerBrand]: true }>;
      6 export type ExtensionAction = Readonly<{ [actionBrand]: true }>;
      7 export type ExtensionCallKind = 'key' | 'sign' | 'encrypt' | 'decrypt' | 'auth';
      8 export type ExtensionCapture = Readonly<{
      9   owner: string | null;
     10   session: symbol;
     11   operation: symbol;
     12 }>;
     13 type Phase = 'active' | 'denied' | 'stopped' | 'wait_expired';
     14 export type ExtensionCallResult<T> =
     15   | Readonly<{
     16       status: 'settled';
     17       value: T;
     18       current: boolean;
     19       capture: ExtensionCapture;
     20     }>
     21   | Readonly<{
     22       status: 'invalid' | 'busy' | 'denied' | 'stopped' | 'wait_expired';
     23     }>;
     24 export type ExtensionActionResult<T> =
     25   | Readonly<{
     26       status: 'completed' | 'denied' | 'stopped' | 'wait_expired';
     27       capture: ExtensionCapture;
     28       value?: T;
     29     }>
     30   | Readonly<{ status: 'invalid' | 'busy' }>;
     31 export type ExtensionSchedulerSnapshot =
     32   | Readonly<{ state: 'idle' | 'unavailable' }>
     33   | Readonly<{
     34       state: 'active';
     35       pending: ExtensionCallKind | null;
     36       phase: Phase;
     37     }>;
     38 type ActionController = {
     39   call<T>(
     40     kind: ExtensionCallKind,
     41     invoke: () => Promise<T>
     42   ): Promise<ExtensionCallResult<T>>;
     43   stop(): void;
     44   expire(): void;
     45 };
     46 type SchedulerController = {
     47   run<T>(
     48     capture: ExtensionCapture,
     49     current: () => boolean,
     50     work: (action: ExtensionAction) => Promise<T>
     51   ): Promise<ExtensionActionResult<T>>;
     52   snapshot(): ExtensionSchedulerSnapshot;
     53 };
     54 const schedulers = new WeakMap<ExtensionScheduler, SchedulerController>();
     55 const actions = new WeakMap<ExtensionAction, ActionController>();
     56 // A page-local permission slot, not a server account or cross-tab lock. No
     57 // accessor is called at module load; page destruction ends this realm's state.
     58 let browserScheduler: ExtensionScheduler | undefined;
     59 export function browserExtensionScheduler(): ExtensionScheduler | undefined {
     60   if (typeof window === 'undefined') return undefined;
     61   browserScheduler ??= createExtensionScheduler();
     62   return browserScheduler;
     63 }
     64 export function createExtensionScheduler(): ExtensionScheduler {
     65   let occupied = false;
     66   let view: () => ExtensionSchedulerSnapshot = () => ({ state: 'idle' });
     67   async function run<T>(
     68     input: ExtensionCapture,
     69     fresh: () => boolean,
     70     work: (action: ExtensionAction) => Promise<T>
     71   ): Promise<ExtensionActionResult<T>> {
     72     if (occupied) return { status: 'busy' };
     73     // Reserve before reading an external capture or invoking freshness. Neither
     74     // a getter nor a reentrant callback can admit a second action.
     75     occupied = true;
     76     let phase: Phase = 'active',
     77       closed = false,
     78       accepting = true;
     79     let pending: ExtensionCallKind | null = null;
     80     let settlement: Promise<unknown> | null = null;
     81     function outstanding(): Promise<unknown> | null {
     82       return settlement;
     83     }
     84     view = () => ({ state: 'active', pending, phase });
     85     function current() {
     86       if (closed || phase !== 'active') return false;
     87       let valid = false;
     88       try {
     89         valid = fresh() === true;
     90       } catch {
     91         /* finite stopped state */
     92       }
     93       if (!valid && phase === 'active') phase = 'stopped';
     94       return !closed && phase === 'active' && valid;
     95     }
     96     try {
     97       if (!input || typeof fresh !== 'function' || typeof work !== 'function')
     98         return { status: 'invalid' };
     99       const owner = input.owner,
    100         session = input.session,
    101         operation = input.operation;
    102       if (
    103         (owner !== null &&
    104           (typeof owner !== 'string' || canonicalPublicKey(owner) !== owner)) ||
    105         typeof session !== 'symbol' ||
    106         typeof operation !== 'symbol'
    107       )
    108         return { status: 'invalid' };
    109       // The authoritative capture consists only of immutable lexical primitives.
    110       // Each outward result is a fresh detached copy, never the retained input.
    111       const capture = (): ExtensionCapture => ({ owner, session, operation });
    112       const action = Object.freeze({}) as ExtensionAction;
    113       async function call<V>(
    114         kind: ExtensionCallKind,
    115         invoke: () => Promise<V>
    116       ): Promise<ExtensionCallResult<V>> {
    117         if (!accepting) return { status: 'stopped' };
    118         if (!current())
    119           return {
    120             status: closed ? 'stopped' : phase === 'active' ? 'stopped' : phase
    121           };
    122         if (pending) return { status: 'busy' };
    123         if (
    124           !['key', 'sign', 'encrypt', 'decrypt', 'auth'].includes(kind) ||
    125           typeof invoke !== 'function'
    126         )
    127           return { status: 'invalid' };
    128         // Mark admission before even the callback's synchronous prefix. The
    129         // SDK invocation itself may read provider getters and cannot be revoked.
    130         pending = kind;
    131         const task = (async (): Promise<ExtensionCallResult<V>> => {
    132           try {
    133             const value = await invoke();
    134             return {
    135               status: 'settled',
    136               value,
    137               current: current(),
    138               capture: capture()
    139             };
    140           } catch {
    141             if (current()) phase = 'denied';
    142             return { status: phase === 'active' ? 'denied' : phase };
    143           } finally {
    144             pending = null;
    145           }
    146         })();
    147         settlement = task;
    148         try {
    149           return await task;
    150         } finally {
    151           if (settlement === task) settlement = null;
    152         }
    153       }
    154       actions.set(action, {
    155         call,
    156         stop() {
    157           if (!closed) phase = 'stopped';
    158         },
    159         expire() {
    160           if (!closed && phase === 'active' && pending) phase = 'wait_expired';
    161         }
    162       });
    163       if (!current()) return { status: 'stopped', capture: capture() };
    164       let value: T | undefined;
    165       try {
    166         value = await work(action);
    167       } catch {
    168         if (current()) phase = 'denied';
    169       }
    170       // Even an unawaited admitted call retains the shared slot. No timeout,
    171       // disconnect, batch return or rejection can pretend it was cancelled.
    172       accepting = false;
    173       const waiting = outstanding();
    174       if (waiting) await waiting;
    175       const valid = current();
    176       return {
    177         status: valid ? 'completed' : phase === 'active' ? 'stopped' : phase,
    178         capture: capture(),
    179         value
    180       };
    181     } catch {
    182       return { status: 'invalid' };
    183     } finally {
    184       accepting = false;
    185       const waiting = outstanding();
    186       if (waiting) await waiting;
    187       closed = true;
    188       occupied = false;
    189       view = () => ({ state: 'idle' });
    190     }
    191   }
    192   const scheduler = Object.freeze({}) as ExtensionScheduler;
    193   schedulers.set(scheduler, { run, snapshot: () => view() });
    194   return scheduler;
    195 }
    196 // Low-level orchestration ports only. No signer, event publisher, permission
    197 // fallback or automatic action is created by the scheduler. Product owners must
    198 // independently validate templates/results before persistence or delivery.
    199 export function runExtensionAction<T>(
    200   scheduler: ExtensionScheduler,
    201   capture: ExtensionCapture,
    202   current: () => boolean,
    203   work: (action: ExtensionAction) => Promise<T>
    204 ): Promise<ExtensionActionResult<T>> {
    205   return (
    206     schedulers.get(scheduler)?.run(capture, current, work) ??
    207     Promise.resolve({ status: 'invalid' })
    208   );
    209 }
    210 export function callExtension<T>(
    211   action: ExtensionAction,
    212   kind: ExtensionCallKind,
    213   invoke: () => Promise<T>
    214 ): Promise<ExtensionCallResult<T>> {
    215   return (
    216     actions.get(action)?.call(kind, invoke) ??
    217     Promise.resolve({ status: 'invalid' })
    218   );
    219 }
    220 export function stopExtensionAction(action: ExtensionAction): void {
    221   actions.get(action)?.stop();
    222 }
    223 // The UI supplies its wait-expiration event. This marks slow/pending, pauses the
    224 // batch, and leaves the real promise reserved; it establishes no cancellation.
    225 export function markExtensionWaitExpired(action: ExtensionAction): void {
    226   actions.get(action)?.expire();
    227 }
    228 export function extensionSchedulerSnapshot(
    229   scheduler: ExtensionScheduler
    230 ): ExtensionSchedulerSnapshot {
    231   return schedulers.get(scheduler)?.snapshot() ?? { state: 'unavailable' };
    232 }