app

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

public-runtime.ts (17225B)


      1 import { deploymentRelayPolicy } from '../config/deployment-relays.ts';
      2 import { readRelayPolicy, type RelayPolicy } from '../config/relays.ts';
      3 import {
      4   localPublicPublisherAllowed,
      5   subscribeLocalPublicHides,
      6   type LocalPublicHides
      7 } from '../persistence/local-public-hides.ts';
      8 import { qualifiedNip50Sources } from '../nostr/search-sources.ts';
      9 import {
     10   getPublicPool,
     11   subscribePublicPool,
     12   closePublicPool,
     13   type PublicPool
     14 } from '../nostr/public-pool.ts';
     15 import {
     16   getPublicStore,
     17   insertPublicEnvelope,
     18   closePublicStore,
     19   publicStoreRetention,
     20   publicStoreKnownEvidence,
     21   publicStoreEnvelope,
     22   type PublicStore
     23 } from '../nostr/public-store.ts';
     24 import {
     25   createPublicScheduler,
     26   createPublicRun,
     27   openPublicRequest,
     28   openInboxRequest,
     29   disposePublicRun,
     30   closePublicScheduler,
     31   publicRunSnapshot,
     32   type PublicScheduler,
     33   type PublicRun,
     34   type PublicRequest,
     35   type RequestKind,
     36   type RequestClock
     37 } from '../nostr/request-scope.ts';
     38 import type { PublicFilter } from '../nostr/exports.ts';
     39 import { inboxPreferenceQueries } from '../nostr/inbox-queries.ts';
     40 import {
     41   publicHeadEnvelope,
     42   publicHeadSnapshot,
     43   type PublicHead
     44 } from '../catalog/heads.ts';
     45 import type { KnownPublicEvidence } from '../catalog/retention.ts';
     46 import {
     47   verifiedEnvelopeSnapshot,
     48   type VerifiedEnvelope
     49 } from '../nostr/verified-envelope.ts';
     50 declare const contextBrand: unique symbol;
     51 declare const runtimeBrand: unique symbol;
     52 declare const viewBrand: unique symbol;
     53 export type PublicRuntimeContext = Readonly<{ readonly [contextBrand]: true }>;
     54 export type PublicRuntime = Readonly<{ readonly [runtimeBrand]: true }>;
     55 export type PublicView = Readonly<{ readonly [viewBrand]: true }>;
     56 export const PUBLIC_RUNTIME_CONTEXT = 'harvestcircle_public_runtime';
     57 interface RuntimeOwner {
     58   readonly pool: PublicPool;
     59   readonly store: PublicStore;
     60   readonly scheduler: PublicScheduler;
     61   readonly policy: RelayPolicy;
     62   readonly views: Map<PublicView, () => boolean>;
     63   readonly closed: () => boolean;
     64   readonly projectionValid: (retry?: boolean) => boolean;
     65   readonly invalidateProjection: () => void;
     66   readonly close: () => void;
     67 }
     68 interface ContextOwner {
     69   readonly value: () => PublicRuntime | undefined;
     70   readonly mount: (
     71     policy: RelayPolicy,
     72     clock?: RequestClock
     73   ) => PublicRuntime | undefined;
     74   readonly ready: Promise<PublicRuntime | undefined>;
     75   readonly close: () => void;
     76 }
     77 interface ViewOwner {
     78   readonly runtime: RuntimeOwner;
     79   readonly begin: () => PublicRun;
     80   readonly current: (run: PublicRun) => boolean;
     81   readonly settling: () => boolean;
     82   readonly settleWith: (refresh: () => void) => void;
     83   readonly dispose: () => boolean;
     84 }
     85 const runtimeHides = new WeakMap<RuntimeOwner, LocalPublicHides>();
     86 const contexts = new WeakMap<PublicRuntimeContext, ContextOwner>(),
     87   runtimes = new WeakMap<PublicRuntime, RuntimeOwner>(),
     88   views = new WeakMap<PublicView, ViewOwner>();
     89 let browserContext: PublicRuntimeContext | undefined;
     90 function contextOf(token: PublicRuntimeContext): ContextOwner {
     91   const owner = contexts.get(token);
     92   if (!owner) throw new Error('public_runtime_context_invalid');
     93   return owner;
     94 }
     95 function runtimeOf(token: PublicRuntime): RuntimeOwner {
     96   const owner = runtimes.get(token);
     97   if (!owner) throw new Error('public_runtime_invalid');
     98   if (owner.closed()) throw new Error('public_runtime_closed');
     99   return owner;
    100 }
    101 function viewOf(token: PublicView): ViewOwner {
    102   const owner = views.get(token);
    103   if (!owner) throw new Error('public_view_invalid');
    104   return owner;
    105 }
    106 // Context construction is SSR-pure. Root onMount acquires the browser lifetime;
    107 // children can await readiness even when their onMount runs before the root's.
    108 export function createPublicRuntimeContext(): PublicRuntimeContext {
    109   let value: PublicRuntime | undefined,
    110     closed = false;
    111   let ready: (value: PublicRuntime | undefined) => void = () => {};
    112   let selectedClock: RequestClock | undefined;
    113   const promise = new Promise<PublicRuntime | undefined>((resolve) => {
    114     ready = resolve;
    115   });
    116   const owner: ContextOwner = {
    117     value: () => (closed ? undefined : value),
    118     ready: promise,
    119     mount(policy, clock) {
    120       if (closed) throw new Error('public_runtime_closed');
    121       if (typeof window === 'undefined') return undefined;
    122       if (value) {
    123         const prior = runtimes.get(value);
    124         if (!prior || prior.policy !== policy)
    125           throw new Error('public_runtime_policy_changed');
    126         if (clock !== selectedClock)
    127           throw new Error('public_runtime_clock_changed');
    128         return value;
    129       }
    130       if (browserContext && browserContext !== contextToken)
    131         throw new Error('public_runtime_owner_changed');
    132       const pool = getPublicPool(policy),
    133         store = getPublicStore();
    134       if (!pool || !store) return undefined;
    135       const scheduler = createPublicScheduler(clock),
    136         registered = new Map<PublicView, () => boolean>();
    137       let terminal = false,
    138         invalidated = false,
    139         invalidating = false;
    140       const token = Object.freeze({}) as PublicRuntime;
    141       const runtime: RuntimeOwner = {
    142         pool,
    143         store,
    144         scheduler,
    145         policy,
    146         views: registered,
    147         closed: () => terminal,
    148         projectionValid(retry = true) {
    149           const retained = publicStoreRetention(store);
    150           if (retained.stopped || (!terminal && retained.closed))
    151             invalidated = true;
    152           // A settler reads the terminal flag without recursively retrying its
    153           // own disposal. The outer cleanup loop keeps failed controls live.
    154           if (invalidated && retry) runtime.invalidateProjection();
    155           return !invalidated;
    156         },
    157         invalidateProjection() {
    158           invalidated = true;
    159           if (invalidating) return;
    160           invalidating = true;
    161           let failed = false;
    162           try {
    163             for (const dispose of registered.values())
    164               if (!dispose()) failed = true;
    165           } finally {
    166             invalidating = false;
    167           }
    168           if (failed) throw new Error('public_projection_close_failed');
    169         },
    170         close() {
    171           terminal = true;
    172           let failed = false;
    173           for (const dispose of registered.values())
    174             if (!dispose()) failed = true;
    175           // Reentrant or failed settlement cannot preserve a coherent projection
    176           // across store teardown. Terminal uncertainty clears every view.
    177           if (failed) invalidated = true;
    178           try {
    179             closePublicScheduler(scheduler);
    180           } catch {
    181             failed = true;
    182           }
    183           try {
    184             closePublicPool(pool);
    185           } catch {
    186             failed = true;
    187           }
    188           try {
    189             closePublicStore(store);
    190           } catch {
    191             failed = true;
    192           }
    193           if (failed) throw new Error('public_runtime_close_failed');
    194         }
    195       };
    196       runtimes.set(token, runtime);
    197       value = token;
    198       browserContext = contextToken;
    199       selectedClock = clock;
    200       ready(token);
    201       return token;
    202     },
    203     close() {
    204       closed = true;
    205       ready(undefined);
    206       if (value) {
    207         const runtime = runtimes.get(value);
    208         if (runtime) runtime.close();
    209       }
    210     }
    211   };
    212   const contextToken = Object.freeze({}) as PublicRuntimeContext;
    213   contexts.set(contextToken, owner);
    214   return contextToken;
    215 }
    216 export function publicRuntime(
    217   context: PublicRuntimeContext
    218 ): PublicRuntime | undefined {
    219   return contextOf(context).value();
    220 }
    221 export function publicRuntimeReady(
    222   context: PublicRuntimeContext
    223 ): Promise<PublicRuntime | undefined> {
    224   return contextOf(context).ready;
    225 }
    226 // Original runtime policy observation only, never a pool or effect capability.
    227 export function publicRuntimePolicy(
    228   runtime: PublicRuntime
    229 ): RelayPolicy | undefined {
    230   try {
    231     const owner = runtimeOf(runtime);
    232     return !owner.closed() && owner.projectionValid()
    233       ? owner.policy
    234       : undefined;
    235   } catch {
    236     return;
    237   }
    238 }
    239 export function mountPublicRuntime(
    240   context: PublicRuntimeContext,
    241   policy: RelayPolicy = deploymentRelayPolicy,
    242   clock?: RequestClock
    243 ): PublicRuntime | undefined {
    244   return contextOf(context).mount(policy, clock);
    245 }
    246 export function closePublicRuntime(context: PublicRuntimeContext): void {
    247   contextOf(context).close();
    248 }
    249 export function createPublicView(runtime: PublicRuntime): PublicView {
    250   const shared = runtimeOf(runtime);
    251   if (!shared.projectionValid())
    252     throw new Error('public_projection_unavailable');
    253   const token = Object.freeze({}) as PublicView;
    254   let run: PublicRun | undefined,
    255     disposed = false;
    256   let generation = 0,
    257     settler: (() => void) | undefined,
    258     settling = false;
    259   function settle() {
    260     const refresh = settler;
    261     settler = undefined; // Detach before any caller-controlled clock reentry.
    262     if (!refresh) return;
    263     settling = true;
    264     try {
    265       refresh?.();
    266     } catch (error) {
    267       if (!settler) settler = refresh;
    268       throw error;
    269     } finally {
    270       settling = false;
    271     }
    272   }
    273   const owner: ViewOwner = {
    274     runtime: shared,
    275     begin() {
    276       if (disposed || shared.closed() || !shared.projectionValid())
    277         throw new Error('public_view_closed');
    278       const operation = ++generation,
    279         previous = run;
    280       // Generation reserves the transition; keep failed old controls retryable.
    281       try {
    282         settle();
    283       } finally {
    284         if (previous) disposePublicRun(previous);
    285       }
    286       if (
    287         operation !== generation ||
    288         disposed ||
    289         shared.closed() ||
    290         !shared.projectionValid()
    291       )
    292         throw new Error('public_view_run_superseded');
    293       const candidate = createPublicRun(shared.scheduler, shared.policy);
    294       // Run creation samples the injected clock. It may synchronously start a
    295       // newer view generation before returning; never overwrite that owner.
    296       if (
    297         operation !== generation ||
    298         disposed ||
    299         shared.closed() ||
    300         !shared.projectionValid()
    301       ) {
    302         disposePublicRun(candidate);
    303         throw new Error('public_view_run_superseded');
    304       }
    305       run = candidate;
    306       return run;
    307     },
    308     settling: () => settling,
    309     settleWith(refresh) {
    310       const previous = settler;
    311       settler = refresh;
    312       previous?.();
    313     },
    314     current(candidate) {
    315       return !disposed && !shared.closed() && run === candidate;
    316     },
    317     dispose() {
    318       disposed = true;
    319       generation++;
    320       if (settling) return false;
    321       try {
    322         settle();
    323         if (run) disposePublicRun(run);
    324         shared.views.delete(token);
    325         return true;
    326       } catch {
    327         return false;
    328       }
    329     }
    330   };
    331   views.set(token, owner);
    332   shared.views.set(token, () => owner.dispose());
    333   return token;
    334 }
    335 // Root-lifetime original local preference custody, never detached UI keys.
    336 export function bindPublicRuntimeHides(
    337   runtime: PublicRuntime,
    338   hides: LocalPublicHides
    339 ): void {
    340   const owner = runtimeOf(runtime);
    341   if (runtimeHides.has(owner) && runtimeHides.get(owner) !== hides)
    342     throw Error('public_visibility_already_bound');
    343   runtimeHides.set(owner, hides);
    344 }
    345 function publisherAllowed(owner: RuntimeOwner, publisher: string): boolean {
    346   return (
    347     !owner.closed() &&
    348     !readRelayPolicy(owner.policy).operatorDenylist.includes(publisher) &&
    349     (!runtimeHides.has(owner) ||
    350       localPublicPublisherAllowed(runtimeHides.get(owner)!, publisher))
    351   );
    352 }
    353 export function publicViewPublisherAllowed(
    354   view: PublicView,
    355   publisher: string
    356 ): boolean {
    357   const owner = viewOf(view);
    358   return publisherAllowed(owner.runtime, publisher);
    359 }
    360 export function subscribePublicViewVisibility(
    361   view: PublicView,
    362   listener: () => void
    363 ): () => void {
    364   const hides = runtimeHides.get(viewOf(view).runtime);
    365   return hides ? subscribeLocalPublicHides(hides, listener) : () => {};
    366 }
    367 export function beginPublicViewRun(view: PublicView): PublicRun {
    368   return viewOf(view).begin();
    369 }
    370 export function publicViewRunCurrent(
    371   view: PublicView,
    372   run: PublicRun
    373 ): boolean {
    374   return viewOf(view).current(run) && publicRunSnapshot(run).active;
    375 }
    376 // Ownership survives an ordinary deadline so a foreground owner can publish
    377 // its terminal result once. Supersession/disposal/shared closure revoke it.
    378 export function publicViewOwnsRun(view: PublicView, run: PublicRun): boolean {
    379   return viewOf(view).current(run);
    380 }
    381 export function disposePublicView(view: PublicView): void {
    382   if (!viewOf(view).dispose()) throw new Error('public_view_close_failed');
    383 }
    384 export function subscribePublicView(
    385   view: PublicView,
    386   run: PublicRun,
    387   kind: RequestKind,
    388   filters: readonly PublicFilter[],
    389   onVerified: (event: VerifiedEnvelope) => void,
    390   sampleSource?: string
    391 ): PublicRequest {
    392   const owner = viewOf(view);
    393   if (!owner.current(run)) throw new Error('public_view_run_inactive');
    394   // Copy the request template once before SDK effects; caller mutations cannot
    395   // retarget this request. Product filter builders remain HCP038 and later.
    396   const copied = JSON.parse(JSON.stringify(filters)) as PublicFilter[];
    397   const admitted = copied.flatMap((filter) => {
    398     if (!filter.authors) return [filter];
    399     const authors = filter.authors.filter((author) =>
    400       publisherAllowed(owner.runtime, author)
    401     );
    402     return authors.length ? [{ ...filter, authors }] : [];
    403   });
    404   // Refuse known denied author-specific actions before SDK request creation.
    405   // Broad discovery still charges verified ingress before publisher admission.
    406   if (!admitted.length) throw Error('public_content_unavailable');
    407   const frozen = JSON.stringify(admitted);
    408   return openPublicRequest(
    409     run,
    410     kind,
    411     (next) =>
    412       subscribePublicPool(
    413         owner.runtime.pool,
    414         JSON.parse(frozen) as PublicFilter[],
    415         next,
    416         sampleSource
    417       ),
    418     (event) => {
    419       if (!owner.current(run)) return;
    420       const received = verifiedEnvelopeSnapshot(event);
    421       if (!received || !publisherAllowed(owner.runtime, received.pubkey))
    422         return;
    423       const result = insertPublicEnvelope(owner.runtime.store, event);
    424       if (result === 'limit' || result === 'rejected' || result === 'closed') {
    425         owner.runtime.invalidateProjection();
    426         return;
    427       }
    428       if (
    429         (result === 'accepted' || result === 'duplicate') &&
    430         owner.current(run)
    431       )
    432         onVerified(event);
    433     },
    434     sampleSource
    435   );
    436 }
    437 
    438 export function publicViewNip50Sources(view: PublicView): readonly string[] {
    439   return qualifiedNip50Sources(viewOf(view).runtime.policy);
    440 }
    441 
    442 // Public metadata, dedicated ownership: no preference enters the food store.
    443 // Fixed anonymous origins, clocks, scheduler and aggregate ingress stay shared.
    444 export function subscribeInboxPreference(
    445   view: PublicView,
    446   run: PublicRun,
    447   author: unknown,
    448   onVerified: (event: VerifiedEnvelope, inboxSource?: string) => void
    449 ): PublicRequest {
    450   const owner = viewOf(view),
    451     filters = inboxPreferenceQueries(author);
    452   if (!owner.current(run)) throw new Error('public_view_run_inactive');
    453   return openInboxRequest(
    454     run,
    455     author,
    456     (next) => subscribePublicPool(owner.runtime.pool, filters, next),
    457     (event, inboxSource) => {
    458       if (owner.current(run)) onVerified(event, inboxSource);
    459     }
    460   );
    461 }
    462 
    463 // Capacity invalidation differs from ordinary teardown: last-known snapshots
    464 // remain available on normal close, while a breached working set clears all views.
    465 export function publicViewProjectionAvailable(view: PublicView): boolean {
    466   const owner = viewOf(view);
    467   return owner.runtime.projectionValid(!owner.settling());
    468 }
    469 export function publicViewKnownEvidence(
    470   view: PublicView,
    471   head: PublicHead
    472 ): KnownPublicEvidence {
    473   return publicStoreKnownEvidence(viewOf(view).runtime.store, head);
    474 }
    475 export function retainPublicViewHeads(
    476   view: PublicView,
    477   run: PublicRun,
    478   heads: readonly PublicHead[]
    479 ): boolean {
    480   const owner = viewOf(view);
    481   if (!owner.current(run) || !owner.runtime.projectionValid()) return false;
    482   const active = publicRunSnapshot(run).active;
    483   if (!owner.current(run) || !owner.runtime.projectionValid()) return false;
    484   if (!active) {
    485     // Inactive materialization cannot install or charge another event. Require
    486     // every genuine head to have already passed the shared retained cache.
    487     for (const head of heads) {
    488       if (
    489         !publicStoreEnvelope(owner.runtime.store, publicHeadSnapshot(head).id)
    490       )
    491         throw new Error('public_view_uncached_head');
    492     }
    493     return owner.current(run) && owner.runtime.projectionValid();
    494   }
    495   for (const head of heads) {
    496     const result = insertPublicEnvelope(
    497       owner.runtime.store,
    498       publicHeadEnvelope(head)
    499     );
    500     if (result !== 'accepted' && result !== 'duplicate') {
    501       owner.runtime.invalidateProjection();
    502       return false;
    503     }
    504   }
    505   return owner.runtime.projectionValid();
    506 }
    507 
    508 // Trusted model binding holds only the current projection for this view.
    509 // Replacement/disposal settles it while retained shared lifecycle proof is live.
    510 export function settlePublicViewProjection(
    511   view: PublicView,
    512   refresh: () => void
    513 ): void {
    514   viewOf(view).settleWith(refresh);
    515 }