app

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

observations.ts (4976B)


      1 import { PUBLIC_INGRESS_BUDGETS } from '../config/budgets.ts';
      2 import { publicRelayTargets, type RelayPolicy } from '../config/relays.ts';
      3 import {
      4   verifiedEnvelopeSnapshot,
      5   type VerifiedEnvelope
      6 } from '../nostr/verified-envelope.ts';
      7 import { isPublicEnvelopeKind } from '../nostr/public-store.ts';
      8 declare const journalBrand: unique symbol;
      9 declare const contextBrand: unique symbol;
     10 export type ObservationJournal = Readonly<{ readonly [journalBrand]: true }>;
     11 export type ObservationContext = Readonly<{ readonly [contextBrand]: true }>;
     12 export type PublicObservation = Readonly<{
     13   eventId: string;
     14   source: string;
     15   kind: number;
     16 }>;
     17 interface Owner {
     18   readonly origins: () => readonly string[];
     19   readonly context: () => ObservationContext;
     20   readonly record: (
     21     context: ObservationContext,
     22     source: string,
     23     event: VerifiedEnvelope
     24   ) => boolean;
     25   readonly exact: (
     26     context: ObservationContext,
     27     eventId: string,
     28     source: string
     29   ) => boolean;
     30   readonly rows: (context: ObservationContext) => readonly PublicObservation[];
     31   readonly stats: () => Readonly<{ rows: number; closed: boolean }>;
     32   readonly close: () => void;
     33 }
     34 const owners = new WeakMap<ObservationJournal, Owner>();
     35 // One journal belongs to a public run; request tokens are local identities,
     36 // never relay-supplied IDs. No SDK seen-relay metadata or receipt inference.
     37 export function createObservationJournal(
     38   policy: RelayPolicy
     39 ): ObservationJournal {
     40   const origins = publicRelayTargets(policy, 'read');
     41   let contexts = new WeakMap<ObservationContext, Map<string, string>>();
     42   let rows = 0;
     43   let closed = false;
     44   function contextRows(context: ObservationContext): Map<string, string> {
     45     const result = contexts.get(context);
     46     if (!result) throw new Error('observation_context_invalid');
     47     return result;
     48   }
     49   const owner: Owner = {
     50     origins: () => [...origins],
     51     context() {
     52       if (closed) throw new Error('observations_closed');
     53       const token = Object.freeze({}) as ObservationContext;
     54       contexts.set(token, new Map());
     55       return token;
     56     },
     57     record(context, source, event) {
     58       if (closed) return false;
     59       const records = contextRows(context);
     60       if (!origins.includes(source)) return false;
     61       const snapshot = verifiedEnvelopeSnapshot(event);
     62       if (!snapshot || !isPublicEnvelopeKind(snapshot.kind)) return false;
     63       const key = source + '\0' + snapshot.id;
     64       if (records.has(key)) return true;
     65       if (rows >= PUBLIC_INGRESS_BUDGETS.deliveries) return false;
     66       // Retain only exact public ID/kind/source. Private/decrypted metadata and
     67       // full payloads never enter this bounded observation cache.
     68       records.set(
     69         key,
     70         JSON.stringify({
     71           eventId: snapshot.id,
     72           source: source,
     73           kind: snapshot.kind
     74         })
     75       );
     76       rows++;
     77       return true;
     78     },
     79     exact(context, eventId, source) {
     80       if (closed) return false;
     81       const records = contextRows(context);
     82       return (
     83         typeof eventId === 'string' &&
     84         /^[0-9a-f]{64}$/u.test(eventId) &&
     85         origins.includes(source) &&
     86         records.has(source + '\0' + eventId)
     87       );
     88     },
     89     rows(context) {
     90       if (closed) return [];
     91       return Array.from(
     92         contextRows(context).values(),
     93         (raw) => JSON.parse(raw) as PublicObservation
     94       );
     95     },
     96     stats() {
     97       return Object.freeze({ rows: rows, closed: closed });
     98     },
     99     close() {
    100       closed = true;
    101       contexts = new WeakMap();
    102       rows = 0;
    103     }
    104   };
    105   const token = Object.freeze({}) as ObservationJournal;
    106   owners.set(token, owner);
    107   return token;
    108 }
    109 function ownerOf(journal: ObservationJournal): Owner {
    110   const owner = owners.get(journal);
    111   if (!owner) throw new Error('observation_journal_invalid');
    112   return owner;
    113 }
    114 export function createObservationContext(
    115   journal: ObservationJournal
    116 ): ObservationContext {
    117   return ownerOf(journal).context();
    118 }
    119 export function recordPublicObservation(
    120   journal: ObservationJournal,
    121   context: ObservationContext,
    122   source: string,
    123   event: VerifiedEnvelope
    124 ): boolean {
    125   return ownerOf(journal).record(context, source, event);
    126 }
    127 export function exactPublicObservation(
    128   journal: ObservationJournal,
    129   context: ObservationContext,
    130   eventId: string,
    131   source: string
    132 ): boolean {
    133   return ownerOf(journal).exact(context, eventId, source);
    134 }
    135 export function publicObservations(
    136   journal: ObservationJournal,
    137   context: ObservationContext
    138 ): readonly PublicObservation[] {
    139   return ownerOf(journal).rows(context);
    140 }
    141 export function observationJournalStats(
    142   journal: ObservationJournal
    143 ): Readonly<{ rows: number; closed: boolean }> {
    144   return ownerOf(journal).stats();
    145 }
    146 export function closeObservationJournal(journal: ObservationJournal): void {
    147   ownerOf(journal).close();
    148 }
    149 
    150 export function observationSourceOrigins(
    151   journal: ObservationJournal
    152 ): readonly string[] {
    153   return ownerOf(journal).origins();
    154 }