app

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

request-result.ts (10339B)


      1 import {
      2   PUBLIC_INGRESS_BUDGETS,
      3   PUBLIC_QUERY_BUDGETS,
      4   PUBLIC_NIP50_BUDGETS
      5 } from '../config/budgets.ts';
      6 import { requireNip50Source } from './search-sources.ts';
      7 import { canonicalPublicKey } from '../contracts/public-key.ts';
      8 import { publicRelayTargets, type RelayPolicy } from '../config/relays.ts';
      9 import {
     10   createObservationContext,
     11   recordPublicObservation,
     12   observationSourceOrigins,
     13   type ObservationJournal,
     14   type ObservationContext
     15 } from '../catalog/observations.ts';
     16 import {
     17   admitPublicEvent,
     18   admitInboxEvent,
     19   publicIngressStats,
     20   type PublicIngress
     21 } from './ingress.ts';
     22 import {
     23   verifiedEnvelopeSnapshot,
     24   type VerifiedEnvelope
     25 } from './verified-envelope.ts';
     26 import { isPublicEnvelopeKind } from './public-store.ts';
     27 import type { PublicPoolMessage } from './exports.ts';
     28 declare const requestBrand: unique symbol;
     29 export type PublicRequestResult = Readonly<{ readonly [requestBrand]: true }>;
     30 export type SourceState =
     31   'pending' | 'eose' | 'closed' | 'error' | 'limit' | 'cancelled';
     32 export type SourceOutcome = Readonly<{
     33   source: string;
     34   state: SourceState;
     35   candidates: number;
     36   accepted: number;
     37   duplicates: number;
     38   rejected: number;
     39 }>;
     40 export type RequestSnapshot = Readonly<{
     41   context: ObservationContext;
     42   sources: readonly SourceOutcome[];
     43   coverage: 'bounded-eose' | 'partial';
     44   definitiveAbsence: false;
     45   inactive: boolean;
     46   inbox?: Readonly<{ author: string; heads: readonly InboxSourceHead[] }>;
     47 }>;
     48 export type InboxSourceHead = Readonly<{
     49   source: string;
     50   id: string;
     51   createdAt: number;
     52 }>;
     53 export type RequestMessageResult =
     54   | Readonly<{
     55       status: 'accepted' | 'duplicate';
     56       value: VerifiedEnvelope;
     57       inboxSource?: string;
     58     }>
     59   | Readonly<{
     60       status:
     61         | 'rejected'
     62         | 'limit'
     63         | 'not_public'
     64         | 'source_unknown'
     65         | 'inactive'
     66         | 'control';
     67     }>;
     68 interface Owner {
     69   readonly handle: (message: PublicPoolMessage) => RequestMessageResult;
     70   readonly snapshot: () => RequestSnapshot;
     71   readonly dispose: () => void;
     72 }
     73 const owners = new WeakMap<PublicRequestResult, Owner>();
     74 const runIngress = new WeakMap<ObservationJournal, PublicIngress>();
     75 // Scalar state remains inside its own closure; unknown Map-returned records
     76 // are never treated as mutable DOM/model receivers by the source guard.
     77 function sourceOwner(source: string) {
     78   let state: SourceState = 'pending';
     79   let candidates = 0;
     80   let accepted = 0;
     81   let duplicates = 0;
     82   let rejected = 0;
     83   return {
     84     state: () => state,
     85     candidate() {
     86       candidates = Math.min(PUBLIC_INGRESS_BUDGETS.deliveries, candidates + 1);
     87     },
     88     reject() {
     89       rejected = Math.min(PUBLIC_INGRESS_BUDGETS.deliveries, rejected + 1);
     90     },
     91     admit(duplicate: boolean) {
     92       if (duplicate) duplicates++;
     93       else accepted++;
     94     },
     95     control(next: 'eose' | 'error' | 'closed' | 'limit') {
     96       if (next === 'limit') state = 'limit';
     97       else if (next === 'eose') {
     98         if (state === 'pending') state = 'eose';
     99       } else if (state !== 'limit' && state !== 'cancelled') state = next;
    100     },
    101     cancel() {
    102       if (state === 'pending') state = 'cancelled';
    103     },
    104     snapshot(): SourceOutcome {
    105       return {
    106         source: source,
    107         state: state,
    108         candidates: candidates,
    109         accepted: accepted,
    110         duplicates: duplicates,
    111         rejected: rejected
    112       };
    113     }
    114   };
    115 }
    116 
    117 // Pure decoded-SDK adapter. Network callbacks bind this opaque logical request;
    118 // HCP032 owns actual deadline/concurrency/generation and browser composition.
    119 export function createPublicRequestResult(
    120   policy: RelayPolicy,
    121   ingress: PublicIngress,
    122   journal: ObservationJournal,
    123   sampleSource?: string
    124 ): PublicRequestResult {
    125   return createResult(policy, ingress, journal, sampleSource);
    126 }
    127 export function createInboxRequestResult(
    128   policy: RelayPolicy,
    129   ingress: PublicIngress,
    130   journal: ObservationJournal,
    131   author: unknown
    132 ): PublicRequestResult {
    133   const key = canonicalPublicKey(author);
    134   if (!key) throw new Error('inbox_author_invalid');
    135   return createResult(policy, ingress, journal, undefined, key);
    136 }
    137 function createResult(
    138   policy: RelayPolicy,
    139   ingress: PublicIngress,
    140   journal: ObservationJournal,
    141   sampleSource?: string,
    142   inboxAuthor?: string
    143 ): PublicRequestResult {
    144   publicIngressStats(ingress);
    145   const allOrigins = publicRelayTargets(policy, 'read');
    146   const expected = observationSourceOrigins(journal);
    147   if (
    148     allOrigins.length !== expected.length ||
    149     !allOrigins.every((origin, index) => origin === expected[index])
    150   )
    151     throw new Error('request_observation_policy_changed');
    152   const origins =
    153     sampleSource === undefined
    154       ? allOrigins
    155       : [requireNip50Source(policy, sampleSource)];
    156   const priorIngress = runIngress.get(journal);
    157   if (priorIngress && priorIngress !== ingress)
    158     throw new Error('public_request_ingress_changed');
    159   const context = createObservationContext(journal);
    160   runIngress.set(journal, ingress);
    161   const sources = new Map<string, ReturnType<typeof sourceOwner>>();
    162   const heads = new Map<string, InboxSourceHead>();
    163   for (const source of origins) sources.set(source, sourceOwner(source));
    164   let inactive = false;
    165   let unknownDelivery = false;
    166   const owner: Owner = {
    167     handle(message) {
    168       if (inactive) return { status: 'inactive' };
    169       // Pinned SDK normalized relay URLs may carry the origin's sole trailing
    170       // slash. Match only the two exact spellings of an already approved origin.
    171       const origin = origins.find(
    172         (value) => message.from === value || message.from === value + '/'
    173       );
    174       const source = origin === undefined ? undefined : sources.get(origin);
    175       if (message.type === 'EVENT') {
    176         const admitted =
    177           inboxAuthor === undefined
    178             ? admitPublicEvent(ingress, message.event)
    179             : admitInboxEvent(ingress, message.event);
    180         if (!source || origin === undefined) {
    181           unknownDelivery = true;
    182           return { status: 'source_unknown' };
    183         }
    184         const pending = source.state() === 'pending';
    185         source.candidate();
    186         // Preserve the inclusive100th admitted delivery, then settle this sample
    187         // alone. Global ingress overflow retains its existing run-wide semantics.
    188         if (
    189           sampleSource !== undefined &&
    190           source.snapshot().candidates >=
    191             PUBLIC_NIP50_BUDGETS.candidatesPerSource
    192         )
    193           source.control('limit');
    194         if (
    195           inboxAuthor !== undefined &&
    196           source.snapshot().candidates >= PUBLIC_QUERY_BUDGETS.requestedPerRelay
    197         )
    198           source.control('limit');
    199         if (admitted.status === 'limit') {
    200           source.control('limit');
    201           return { status: 'limit' };
    202         }
    203         if (admitted.status === 'rejected') {
    204           source.reject();
    205           return { status: 'rejected' };
    206         }
    207         if (!pending) {
    208           source.reject();
    209           return { status: 'inactive' };
    210         }
    211         if (!('value' in admitted)) return { status: 'rejected' };
    212         const event = verifiedEnvelopeSnapshot(admitted.value);
    213         if (
    214           !event ||
    215           (inboxAuthor === undefined
    216             ? !isPublicEnvelopeKind(event.kind)
    217             : event.kind !== 10050 || event.pubkey !== inboxAuthor)
    218         ) {
    219           source.reject();
    220           return { status: 'not_public' };
    221         }
    222         if (
    223           inboxAuthor === undefined &&
    224           !recordPublicObservation(journal, context, origin, admitted.value)
    225         ) {
    226           source.control('limit');
    227           return { status: 'limit' };
    228         }
    229         if (inboxAuthor !== undefined) {
    230           const previous = heads.get(origin);
    231           if (
    232             !previous ||
    233             event.created_at > previous.createdAt ||
    234             (event.created_at === previous.createdAt && event.id < previous.id)
    235           )
    236             heads.set(origin, {
    237               source: origin,
    238               id: event.id,
    239               createdAt: event.created_at
    240             });
    241         }
    242         source.admit(admitted.status === 'duplicate');
    243         // Record exact source evidence BEFORE any caller inserts/deduplicates into
    244         // EventStore. Only verified proof leaves this boundary, never SDK metadata.
    245         return inboxAuthor === undefined
    246           ? admitted
    247           : { ...admitted, inboxSource: origin };
    248       }
    249       if (!source) return { status: 'source_unknown' };
    250       if (message.type === 'EOSE') source.control('eose');
    251       else if (message.type === 'ERROR') source.control('error');
    252       else if (message.type === 'CLOSED') source.control('closed');
    253       // Deliberately do not read message.reason, message.error, filters or IDs.
    254       return { status: 'control' };
    255     },
    256     snapshot() {
    257       const outcomes = Array.from(sources.values(), (row) => row.snapshot());
    258       const complete =
    259         outcomes.length > 0 &&
    260         (inboxAuthor === undefined || !unknownDelivery) &&
    261         outcomes.every((row) => row.state === 'eose' && row.rejected === 0);
    262       return {
    263         context: context,
    264         sources: outcomes,
    265         coverage: complete ? 'bounded-eose' : 'partial',
    266         definitiveAbsence: false,
    267         inactive: inactive,
    268         ...(inboxAuthor === undefined
    269           ? {}
    270           : {
    271               inbox: {
    272                 author: inboxAuthor,
    273                 heads: Array.from(heads.values(), (row) => ({ ...row }))
    274               }
    275             })
    276       };
    277     },
    278     dispose() {
    279       if (inactive) return;
    280       inactive = true;
    281       for (const row of sources.values()) row.cancel();
    282     }
    283   };
    284   const token = Object.freeze({}) as PublicRequestResult;
    285   owners.set(token, owner);
    286   return token;
    287 }
    288 function ownerOf(token: PublicRequestResult): Owner {
    289   const owner = owners.get(token);
    290   if (!owner) throw new Error('public_request_result_invalid');
    291   return owner;
    292 }
    293 export function handlePublicRequestMessage(
    294   owner: PublicRequestResult,
    295   message: PublicPoolMessage
    296 ): RequestMessageResult {
    297   return ownerOf(owner).handle(message);
    298 }
    299 export function publicRequestSnapshot(
    300   owner: PublicRequestResult
    301 ): RequestSnapshot {
    302   return ownerOf(owner).snapshot();
    303 }
    304 export function disposePublicRequestResult(owner: PublicRequestResult): void {
    305   ownerOf(owner).dispose();
    306 }