app

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

listing-operation-view.ts (10168B)


      1 import { canonicalLocalId } from '../private-handles.ts';
      2 import {
      3   publicPublicationOwner,
      4   readPublicListingIntent,
      5   type PublicPublicationRepository
      6 } from '../persistence/public-publications.ts';
      7 import { publicRecordSnapshot } from '../persistence/records.ts';
      8 import {
      9   identitySessionSnapshot,
     10   subscribeIdentityInvalidation,
     11   type IdentitySession
     12 } from '../runtime/identity-session.ts';
     13 import {
     14   listingSigningSnapshot,
     15   subscribeListingSigning,
     16   type ListingSigning
     17 } from './sign-listing.ts';
     18 import { inspectLocalTemplate } from '../nostr/local-template.ts';
     19 import { projectFoodParts } from '../contracts/food-availability-v1/read.ts';
     20 import type { PublicTargetReceipt } from '../contracts/local-records.ts';
     21 import type { StatusCopy } from '../presentation/status-copy.ts';
     22 
     23 declare const viewBrand: unique symbol;
     24 export type ListingOperationView = Readonly<{ [viewBrand]: true }>;
     25 export type ListingOperationSnapshot = Readonly<{
     26   owner: string;
     27   command: string;
     28   revision: number;
     29   eventId: string;
     30   purpose: 'listing' | 'withdrawal';
     31   artifact: 'unsigned' | 'signed';
     32   state:
     33     | 'prepared'
     34     | 'signing'
     35     | 'partial'
     36     | 'accepted'
     37     | 'readback'
     38     | 'unknown'
     39     | 'needs-action';
     40   acceptanceCount: number;
     41   readbackCount: number;
     42   needsAction: boolean;
     43   localSource: 'retained-prototype' | 'read-only';
     44   summary: StatusCopy;
     45   targets: readonly Readonly<{
     46     origin: string;
     47     eventId: string;
     48     accepted: boolean;
     49     readback: 'confirmed' | 'not-observed';
     50     latestOutcome: PublicTargetReceipt['status'] | 'unattempted';
     51     receipts: readonly PublicTargetReceipt[];
     52   }>[];
     53 }>;
     54 type View = Readonly<{
     55   wire: string;
     56   current(): boolean;
     57   retire(): void;
     58   subscribe(listener: () => void): () => void;
     59 }>;
     60 const views = new WeakMap<ListingOperationView, View>();
     61 const active = new WeakMap<
     62   PublicPublicationRepository,
     63   Map<string, Readonly<{ stamp: symbol; retire(): void }>>
     64 >();
     65 
     66 // This is account-local presentation only. Reading a retained operation grants
     67 // no sign, send, edit, current-head or relay qualification capability.
     68 export async function readListingOperationView(
     69   repository: PublicPublicationRepository,
     70   identity: IdentitySession,
     71   command: unknown,
     72   signing?: ListingSigning
     73 ): Promise<
     74   | Readonly<{ status: 'found'; view: ListingOperationView }>
     75   | Readonly<{ status: 'unavailable' }>
     76 > {
     77   const owner = publicPublicationOwner(repository),
     78     id = canonicalLocalId(command);
     79   const identityOwner = () => {
     80     const snapshot = identitySessionSnapshot(identity);
     81     return 'publicKey' in snapshot ? snapshot.publicKey : undefined;
     82   };
     83   if (!owner || !id || identityOwner() !== owner)
     84     return { status: 'unavailable' };
     85   const cache =
     86     active.get(repository) ??
     87     new Map<string, Readonly<{ stamp: symbol; retire(): void }>>();
     88   active.set(repository, cache);
     89   cache.get(id)?.retire();
     90   const stamp = Symbol(),
     91     listeners = new Map<symbol, () => void>();
     92   let alive = true,
     93     unsubscribe = () => {},
     94     unsubscribeSigning = () => {},
     95     observesSigning = false;
     96   function retire() {
     97     if (!alive) return;
     98     alive = false;
     99     unsubscribe();
    100     unsubscribeSigning();
    101     if (cache.get(id!)?.stamp === stamp) cache.delete(id!);
    102     for (const listener of listeners.values()) {
    103       try {
    104         listener();
    105       } catch {
    106         /* Presentation callbacks cannot retain original custody. */
    107       }
    108     }
    109     listeners.clear();
    110   }
    111   function current() {
    112     const live =
    113       observesSigning && signing ? listingSigningSnapshot(signing) : undefined;
    114     const originalSigningCurrent =
    115       !observesSigning ||
    116       !!(
    117         live &&
    118         live.signing &&
    119         !live.stopped &&
    120         live.owner === owner &&
    121         live.command === id
    122       );
    123     return (
    124       originalSigningCurrent &&
    125       alive &&
    126       cache.get(id!)?.stamp === stamp &&
    127       publicPublicationOwner(repository) === owner &&
    128       identityOwner() === owner
    129     );
    130   }
    131   cache.set(id, { stamp, retire });
    132   unsubscribe = subscribeIdentityInvalidation(identity, retire);
    133   try {
    134     const read = await readPublicListingIntent(repository, id);
    135     const row =
    136       read.status === 'found' && publicRecordSnapshot(read.record, owner, id);
    137     if (
    138       !current() ||
    139       !row ||
    140       row.family !== 'public_operation' ||
    141       !(
    142         row.capture.kind === 30402 ||
    143         (row.capture.kind === 5 && row.source.type === 'public_head')
    144       ) ||
    145       row.capture.targets.length === 0 ||
    146       (!row.artifact && (row.revision > 1 || row.receipts.length !== 0)) ||
    147       (row.artifact && row.revision < 2)
    148     ) {
    149       retire();
    150       return { status: 'unavailable' };
    151     }
    152     const template = inspectLocalTemplate(
    153       row.capture.wire,
    154       owner,
    155       row.capture.kind
    156     );
    157     if (
    158       !template ||
    159       (template.kind === 30402 &&
    160         projectFoodParts(template).outcome !== 'focused')
    161     ) {
    162       retire();
    163       return { status: 'unavailable' };
    164     }
    165     const targets = row.capture.targets.map((origin) => {
    166       const receipts = row.receipts.filter(
    167         (receipt) =>
    168           receipt.origin === origin && receipt.eventId === row.capture.hash
    169       );
    170       return {
    171         origin,
    172         eventId: row.capture.hash,
    173         accepted: receipts.some((receipt) => receipt.status === 'accepted'),
    174         readback: receipts.some((receipt) => receipt.readbackWire !== null)
    175           ? ('confirmed' as const)
    176           : ('not-observed' as const),
    177         latestOutcome: receipts.at(-1)?.status ?? ('unattempted' as const),
    178         receipts
    179       };
    180     });
    181     const acceptanceCount = targets.filter((target) => target.accepted).length,
    182       readbackCount = targets.filter(
    183         (target) => target.readback === 'confirmed'
    184       ).length;
    185     const needsAction = targets.some((target) =>
    186       ['refused', 'timed_out', 'unknown', 'stopped'].includes(
    187         target.latestOutcome
    188       )
    189     );
    190     const live = signing && listingSigningSnapshot(signing);
    191     const genuinelySigning =
    192       live &&
    193       live.owner === owner &&
    194       live.command === id &&
    195       live.hash === row.capture.hash &&
    196       live.signing &&
    197       !live.stopped;
    198     const state: ListingOperationSnapshot['state'] = !row.artifact
    199       ? row.revision === 0
    200         ? 'prepared'
    201         : genuinelySigning
    202           ? 'signing'
    203           : 'unknown'
    204       : readbackCount === targets.length
    205         ? 'readback'
    206         : acceptanceCount === targets.length
    207           ? 'accepted'
    208           : acceptanceCount > 0 || readbackCount > 0
    209             ? 'partial'
    210             : targets.some(
    211                   (target) =>
    212                     target.latestOutcome === 'refused' ||
    213                     target.latestOutcome === 'stopped'
    214                 )
    215               ? 'needs-action'
    216               : row.receipts.length > 0
    217                 ? 'unknown'
    218                 : 'prepared';
    219     observesSigning = state === 'signing';
    220     if (observesSigning && signing)
    221       unsubscribeSigning = subscribeListingSigning(signing, retire);
    222     const listingText =
    223       state === 'signing'
    224         ? 'Waiting for your extension to sign the retained listing.'
    225         : state === 'unknown'
    226           ? 'The outcome is unknown. Keep the original listing operation for reconciliation.'
    227           : state === 'needs-action'
    228             ? 'Needs action. Keep the original listing operation and its recorded target outcomes.'
    229             : state === 'partial'
    230               ? 'Publication evidence is partial. Check the individual target outcomes.'
    231               : state === 'readback'
    232                 ? 'Exact listing read-back is recorded for each frozen target.'
    233                 : state === 'accepted'
    234                   ? 'Each frozen target accepted this listing event. Exact read-back is recorded separately.'
    235                   : row.artifact
    236                     ? 'Signed listing saved in this browser. No relay acceptance is recorded.'
    237                     : 'Saved in this browser. The retained listing has not been signed.';
    238     const text =
    239       row.capture.kind === 5
    240         ? listingText
    241             .replaceAll('listing event', 'removal request')
    242             .replaceAll('listing', 'removal request') +
    243           ' This request cannot erase all other copies.'
    244         : listingText;
    245     const snapshot: ListingOperationSnapshot = {
    246       owner,
    247       command: id,
    248       revision: row.revision,
    249       eventId: row.capture.hash,
    250       purpose: row.capture.kind === 5 ? 'withdrawal' : 'listing',
    251       artifact: row.artifact ? 'signed' : 'unsigned',
    252       state,
    253       acceptanceCount,
    254       readbackCount,
    255       needsAction,
    256       localSource:
    257         row.artifact && row.source.type === 'draft'
    258           ? 'retained-prototype'
    259           : 'read-only',
    260       summary: {
    261         tone:
    262           needsAction || state === 'unknown' || state === 'partial'
    263             ? 'warning'
    264             : 'info',
    265         text
    266       },
    267       targets
    268     };
    269     if (!current()) {
    270       retire();
    271       return { status: 'unavailable' };
    272     }
    273     const view = Object.freeze({}) as ListingOperationView;
    274     views.set(view, {
    275       wire: JSON.stringify(snapshot),
    276       current,
    277       retire,
    278       subscribe(listener) {
    279         if (!current()) return () => {};
    280         const key = Symbol();
    281         listeners.set(key, listener);
    282         return () => {
    283           listeners.delete(key);
    284         };
    285       }
    286     });
    287     return { status: 'found', view };
    288   } catch {
    289     retire();
    290     return { status: 'unavailable' };
    291   }
    292 }
    293 export function listingOperationSnapshot(
    294   token: ListingOperationView
    295 ): ListingOperationSnapshot | undefined {
    296   const value = views.get(token);
    297   if (!value) return;
    298   if (!value.current()) {
    299     value.retire();
    300     return;
    301   }
    302   return JSON.parse(value.wire) as ListingOperationSnapshot;
    303 }
    304 export function closeListingOperationView(token: ListingOperationView): void {
    305   views.get(token)?.retire();
    306 }
    307 export function subscribeListingOperationView(
    308   token: ListingOperationView,
    309   listener: () => void
    310 ): () => void {
    311   const value = views.get(token);
    312   if (!value?.current()) return () => {};
    313   return value.subscribe(listener);
    314 }