app

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

resolve-inbox.ts (7807B)


      1 import { canonicalPublicKey } from '../contracts/public-key.ts';
      2 import {
      3   verifiedEnvelopeWire,
      4   type VerifiedEnvelope
      5 } from '../nostr/verified-envelope.ts';
      6 import {
      7   readInboxPreference,
      8   inboxPreferenceSnapshot,
      9   type InboxPreference
     10 } from '../nostr/inbox-preferences.ts';
     11 import {
     12   closePublicRequest,
     13   publicRequestScopeSnapshot,
     14   publicRunObservations,
     15   publicRunSnapshot,
     16   publicRunCurrentAfterSample,
     17   type PublicRun,
     18   type PublicRequest
     19 } from '../nostr/request-scope.ts';
     20 import {
     21   subscribeInboxPreference,
     22   publicViewOwnsRun,
     23   publicViewRunCurrent,
     24   type PublicView
     25 } from '../runtime/public-runtime.ts';
     26 
     27 declare const resolverBrand: unique symbol;
     28 export type InboxResolver = Readonly<{ readonly [resolverBrand]: true }>;
     29 export type InboxResolution = Readonly<{
     30   author: string;
     31   status: 'ready' | 'missing' | 'unsupported' | 'inconclusive';
     32   head: InboxPreference | undefined;
     33   knownBase:
     34     Readonly<{ author: string; id: string; createdAt: number }> | undefined;
     35   request: PublicRequest;
     36   sources: (ReturnType<
     37     typeof publicRequestScopeSnapshot
     38   >['result']['sources'][number] & {
     39     head?: Readonly<{ id: string; createdAt: number }>;
     40   })[];
     41   coverage: 'bounded-eose' | 'partial';
     42   definitiveAbsence: false;
     43   wireProvenance: 'decoded-sdk-json';
     44 }>;
     45 interface Owner {
     46   readonly snapshot: () => InboxResolution;
     47   readonly close: () => void;
     48   readonly currentAfterSample: () => boolean;
     49 }
     50 const owners = new WeakMap<InboxResolver, Owner>();
     51 function ownerOf(token: InboxResolver): Owner {
     52   const owner = owners.get(token);
     53   if (!owner) throw new Error('inbox_resolver_invalid');
     54   return owner;
     55 }
     56 // Trusted request factory, like catalog resolvers. Production binds this to the
     57 // current view and real anonymous pool. UI cannot manufacture request/proof tokens.
     58 export function createInboxResolver(
     59   run: PublicRun,
     60   author: unknown,
     61   subscribe: (onVerified: (event: VerifiedEnvelope) => void) => PublicRequest,
     62   current: () => boolean = () => true
     63 ): InboxResolver {
     64   const key = canonicalPublicKey(author);
     65   if (!key) throw new Error('inbox_author_invalid');
     66   if (!publicRunSnapshot(run).active || !current())
     67     throw new Error('inbox_resolver_inactive');
     68   let head: InboxPreference | undefined,
     69     closed = false,
     70     rejected = false;
     71   const request = subscribe((proof) => {
     72     if (closed || !current()) return;
     73     const result = readInboxPreference(verifiedEnvelopeWire(proof), key);
     74     if (result.status !== 'supported' && result.status !== 'unsupported') {
     75       rejected = true;
     76       return;
     77     }
     78     const candidate = inboxPreferenceSnapshot(result.value)!,
     79       previous = head && inboxPreferenceSnapshot(head);
     80     if (
     81       !previous ||
     82       candidate.createdAt > previous.createdAt ||
     83       (candidate.createdAt === previous.createdAt && candidate.id < previous.id)
     84     )
     85       head = result.value;
     86   });
     87   try {
     88     publicRunObservations(run, request);
     89     const snapshot = publicRequestScopeSnapshot(request);
     90     if (snapshot.kind !== 'inbox' || snapshot.result.inbox?.author !== key)
     91       throw new Error('inbox_resolver_request_owner');
     92   } catch {
     93     closePublicRequest(request);
     94     throw new Error('inbox_resolver_request_owner');
     95   }
     96   const token = Object.freeze({}) as InboxResolver;
     97   owners.set(token, {
     98     snapshot() {
     99       // Sample the external clock first, then recheck generation ownership.
    100       // Clock reentry may supersede this run before it returns an active value.
    101       const active = publicRunSnapshot(run).active;
    102       const available = !closed && current() && active;
    103       const scope = publicRequestScopeSnapshot(request),
    104         saved = head && inboxPreferenceSnapshot(head);
    105       const complete =
    106         available &&
    107         !rejected &&
    108         scope.state === 'eose' &&
    109         scope.inboxSettled === true &&
    110         scope.result.coverage === 'bounded-eose';
    111       const status = !available
    112         ? 'inconclusive'
    113         : saved?.status === 'unsupported'
    114           ? 'unsupported'
    115           : !complete
    116             ? 'inconclusive'
    117             : saved
    118               ? 'ready'
    119               : 'missing';
    120       return {
    121         author: key,
    122         status,
    123         head,
    124         knownBase: saved && {
    125           author: key,
    126           id: saved.id,
    127           createdAt: saved.createdAt
    128         },
    129         request,
    130         sources: scope.result.sources.map((row) => {
    131           const sourceHead = scope.result.inbox?.heads.find(
    132             (h) => h.source === row.source
    133           );
    134           return {
    135             ...row,
    136             ...(sourceHead
    137               ? { head: { id: sourceHead.id, createdAt: sourceHead.createdAt } }
    138               : {})
    139           };
    140         }),
    141         coverage: complete ? 'bounded-eose' : 'partial',
    142         definitiveAbsence: false,
    143         wireProvenance: 'decoded-sdk-json'
    144       };
    145     },
    146     // The trusted generation observer is a pure owner read, like the production
    147     // view port. This final fence deliberately never samples an injected clock.
    148     currentAfterSample: () =>
    149       !closed && current() && publicRunCurrentAfterSample(run),
    150     close() {
    151       closed = true;
    152       closePublicRequest(request);
    153     }
    154   });
    155   return token;
    156 }
    157 // One recipient resolver per run prevents repeated lookups from resetting work.
    158 const viewResolvers = new WeakMap<
    159   PublicRun,
    160   Readonly<{ view: PublicView; author: string; resolver?: InboxResolver }>
    161 >();
    162 export function resolveInboxPreference(
    163   view: PublicView,
    164   run: PublicRun,
    165   author: unknown
    166 ): InboxResolver {
    167   const key = canonicalPublicKey(author);
    168   if (!key) throw new Error('inbox_author_invalid');
    169   const prior = viewResolvers.get(run);
    170   if (prior) {
    171     if (prior.view !== view || prior.author !== key)
    172       throw new Error('inbox_resolver_owner_changed');
    173     if (!prior.resolver) throw new Error('inbox_resolver_opening');
    174     return prior.resolver;
    175   }
    176   // Reserve before clock/subscription acquisition can synchronously reenter.
    177   viewResolvers.set(run, { view, author: key });
    178   try {
    179     if (!publicViewRunCurrent(view, run))
    180       throw new Error('inbox_resolver_inactive');
    181     const resolver = createInboxResolver(
    182       run,
    183       key,
    184       (next) => subscribeInboxPreference(view, run, key, next),
    185       () => publicViewOwnsRun(view, run)
    186     );
    187     viewResolvers.set(run, { view, author: key, resolver });
    188     return resolver;
    189   } catch {
    190     viewResolvers.delete(run);
    191     throw new Error('inbox_resolver_open_failed');
    192   }
    193 }
    194 export function inboxResolutionSnapshot(token: InboxResolver): InboxResolution {
    195   return ownerOf(token).snapshot();
    196 }
    197 export function closeInboxResolver(token: InboxResolver): void {
    198   ownerOf(token).close();
    199 }
    200 
    201 export function inboxResolverCurrentAfterSample(token: InboxResolver): boolean {
    202   return ownerOf(token).currentAfterSample();
    203 }
    204 declare function setTimeout(callback: () => void, milliseconds: number): number;
    205 // Await the same original bounded request, preserving its observed outcome.
    206 // The original clock and owner decide retirement; this never renews a run,
    207 // manufactures EOSE/readiness or grants a signing/publication capability.
    208 export async function settleInboxResolver(
    209   token: InboxResolver,
    210   current: () => boolean = () => true
    211 ): Promise<InboxResolver> {
    212   const owner = ownerOf(token);
    213   try {
    214     for (;;) {
    215       const observed = owner.snapshot();
    216       if (!current() || !owner.currentAfterSample()) {
    217         owner.close();
    218         return token;
    219       }
    220       const scope = publicRequestScopeSnapshot(observed.request);
    221       if (
    222         scope.state !== 'active' &&
    223         (scope.state !== 'eose' || scope.inboxSettled === true)
    224       )
    225         return token;
    226       await new Promise<void>((resolve) => setTimeout(resolve, 50));
    227     }
    228   } catch {
    229     owner.close();
    230     return token;
    231   }
    232 }