app

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

retention.ts (6299B)


      1 import { PUBLIC_RETENTION_BUDGETS } from '../config/budgets.ts';
      2 import { isPublicEnvelopeKind } from '../nostr/public-kinds.ts';
      3 import {
      4   verifiedEnvelopeSnapshot,
      5   type VerifiedEnvelope
      6 } from '../nostr/verified-envelope.ts';
      7 import {
      8   admitDeletionRequest,
      9   deletionRequestSnapshot,
     10   canonicalDeletionCoordinate,
     11   type DeletionRequest
     12 } from '../nostr/deletion-adapter.ts';
     13 import {
     14   createPublicHeadCandidate,
     15   publicHeadKey,
     16   publicHeadEnvelope,
     17   selectPublicHead,
     18   type PublicHead
     19 } from './heads.ts';
     20 
     21 declare const retentionBrand: unique symbol;
     22 export type PublicRetention = Readonly<{ readonly [retentionBrand]: true }>;
     23 export type RetentionSnapshot = Readonly<{
     24   payloadBytes: number;
     25   events: number;
     26   stopped: boolean;
     27   closed: boolean;
     28   reason: undefined | 'payload_limit' | 'installation_unavailable';
     29 }>;
     30 export type KnownPublicEvidence = Readonly<{
     31   head: PublicHead;
     32   requests: readonly DeletionRequest[];
     33 }>;
     34 type Admission =
     35   'accepted' | 'duplicate' | 'not_public' | 'rejected' | 'limit' | 'closed';
     36 interface Owner {
     37   readonly admit: (
     38     proof: VerifiedEnvelope,
     39     install: () => boolean
     40   ) => Admission;
     41   readonly snapshot: () => RetentionSnapshot;
     42   readonly envelope: (id: string) => VerifiedEnvelope | undefined;
     43   readonly known: (head: PublicHead) => KnownPublicEvidence;
     44   readonly close: () => void;
     45 }
     46 const owners = new WeakMap<PublicRetention, Owner>();
     47 function ownerOf(token: PublicRetention): Owner {
     48   const owner = owners.get(token);
     49   if (!owner) throw new Error('public_retention_invalid');
     50   return owner;
     51 }
     52 export function createPublicRetention(): PublicRetention {
     53   const proofs = new Map<string, VerifiedEnvelope>(),
     54     heads = new Map<string, PublicHead>(),
     55     exact = new Map<string, DeletionRequest>(),
     56     addresses = new Map<string, DeletionRequest>();
     57   let bytes = 0,
     58     closed = false,
     59     reason: RetentionSnapshot['reason'];
     60   const key = (author: string, target: string) =>
     61     JSON.stringify([author, target]);
     62   const owner: Owner = {
     63     admit(proof, install) {
     64       if (closed) return 'closed';
     65       if (reason) return 'limit';
     66       const event = verifiedEnvelopeSnapshot(proof);
     67       if (!event) return 'rejected';
     68       if (!isPublicEnvelopeKind(event.kind)) return 'not_public';
     69       if (proofs.has(event.id)) return 'duplicate';
     70       // Logical serialized public payload, not a JS heap or transport bound.
     71       const charge = new TextEncoder().encode(JSON.stringify(event)).length;
     72       if (charge > PUBLIC_RETENTION_BUDGETS.payloadBytes - bytes) {
     73         reason = 'payload_limit';
     74         return 'limit';
     75       }
     76       // Reserve evidence before a trusted SDK installer can synchronously reenter.
     77       proofs.set(event.id, proof);
     78       bytes += charge;
     79       const candidate = createPublicHeadCandidate(proof);
     80       if (candidate) {
     81         const coordinate = publicHeadKey(candidate);
     82         heads.set(
     83           coordinate,
     84           selectPublicHead(heads.get(coordinate), candidate).head
     85         );
     86       }
     87       if (event.kind === 5) {
     88         const admitted = admitDeletionRequest(proof);
     89         if (admitted.ok) {
     90           const request = deletionRequestSnapshot(admitted.value)!;
     91           for (const target of request.eventTargets) {
     92             const k = key(request.pubkey, target.eventId),
     93               previous = exact.get(k);
     94             if (!previous || request.id < deletionRequestSnapshot(previous)!.id)
     95               exact.set(k, admitted.value);
     96           }
     97           for (const target of request.addressTargets) {
     98             const k = key(request.pubkey, target.coordinate),
     99               previous = addresses.get(k),
    100               row = previous && deletionRequestSnapshot(previous);
    101             if (
    102               !row ||
    103               request.created_at > row.created_at ||
    104               (request.created_at === row.created_at && request.id < row.id)
    105             )
    106               addresses.set(k, admitted.value);
    107           }
    108         }
    109       }
    110       try {
    111         if (!install()) {
    112           reason = 'installation_unavailable';
    113           return closed ? 'closed' : 'rejected';
    114         }
    115       } catch {
    116         reason = 'installation_unavailable';
    117         return closed ? 'closed' : 'rejected';
    118       }
    119       return closed ? 'closed' : reason ? 'limit' : 'accepted';
    120     },
    121     snapshot: () => ({
    122       payloadBytes: bytes,
    123       events: proofs.size,
    124       stopped: reason !== undefined,
    125       closed,
    126       reason
    127     }),
    128     envelope: (id) => (closed ? undefined : proofs.get(id)),
    129     known(input) {
    130       const head = selectPublicHead(
    131         input,
    132         heads.get(publicHeadKey(input)) ?? input
    133       ).head;
    134       const event = verifiedEnvelopeSnapshot(publicHeadEnvelope(head))!;
    135       const identifier =
    136         event.kind === 30402 ? event.tags.find((t) => t[0] === 'd')?.[1] : '';
    137       const coordinate =
    138         identifier === undefined
    139           ? undefined
    140           : canonicalDeletionCoordinate(
    141               `${event.kind}:${event.pubkey}:${identifier}`
    142             );
    143       const e = exact.get(key(event.pubkey, event.id)),
    144         a =
    145           coordinate === undefined
    146             ? undefined
    147             : addresses.get(key(event.pubkey, coordinate));
    148       return {
    149         head,
    150         requests: e ? [e, ...(a && a !== e ? [a] : [])] : a ? [a] : []
    151       };
    152     },
    153     close() {
    154       closed = true;
    155       proofs.clear();
    156       heads.clear();
    157       exact.clear();
    158       addresses.clear();
    159       bytes = 0;
    160     }
    161   };
    162   const token = Object.freeze({}) as PublicRetention;
    163   owners.set(token, owner);
    164   return token;
    165 }
    166 export function retainPublicEnvelope(
    167   owner: PublicRetention,
    168   proof: VerifiedEnvelope,
    169   install: () => boolean = () => true
    170 ): Admission {
    171   return ownerOf(owner).admit(proof, install);
    172 }
    173 export function publicRetentionSnapshot(
    174   owner: PublicRetention
    175 ): RetentionSnapshot {
    176   return ownerOf(owner).snapshot();
    177 }
    178 export function publicRetentionEnvelope(
    179   owner: PublicRetention,
    180   id: string
    181 ): VerifiedEnvelope | undefined {
    182   return ownerOf(owner).envelope(id);
    183 }
    184 export function publicRetentionKnown(
    185   owner: PublicRetention,
    186   head: PublicHead
    187 ): KnownPublicEvidence {
    188   return ownerOf(owner).known(head);
    189 }
    190 export function closePublicRetention(owner: PublicRetention): void {
    191   ownerOf(owner).close();
    192 }