app

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

deliver-listing.ts (7074B)


      1 import { PUBLIC_PUBLICATION_BUDGETS } from '../config/budgets.ts';
      2 import type { RelayPolicy } from '../config/relays.ts';
      3 import type { ListingPublication } from './sign-listing.ts';
      4 import {
      5   listingRetryOwnership,
      6   type ListingRetry,
      7   type ListingRetrySource
      8 } from './retry-listing.ts';
      9 import {
     10   authorizeListingAttempt,
     11   listingDeliveryOwnership,
     12   readOwnedListingDelivery,
     13   readRetainedListingDelivery,
     14   withListingDeliveryOwnership,
     15   type ListingDeliveryLease
     16 } from '../nostr/listing-publisher.ts';
     17 import {
     18   publishPublicListingAttempt,
     19   readPublicListingExactAttempt,
     20   type PublicPool
     21 } from '../nostr/public-pool.ts';
     22 import { publicRecordSnapshot } from '../persistence/records.ts';
     23 import { commitPublicListingReceipt } from '../persistence/public-receipts.ts';
     24 export type ListingDeliveryResult = Readonly<{
     25   status:
     26     | 'completed'
     27     | 'needs_action'
     28     | 'storage_failed'
     29     | 'invalid'
     30     | 'unavailable'
     31     | 'busy'
     32     | 'stopped';
     33 }>;
     34 const pending = new WeakMap<
     35   ListingRetrySource,
     36   Promise<ListingDeliveryResult>
     37 >();
     38 async function deliver(
     39   lease: ListingDeliveryLease,
     40   pool: PublicPool,
     41   policy: RelayPolicy,
     42   signal?: AbortSignal
     43 ): Promise<ListingDeliveryResult> {
     44   const custody = listingDeliveryOwnership(lease),
     45     initial = await readOwnedListingDelivery(lease);
     46   if (!custody || !initial)
     47     return {
     48       status:
     49         signal?.aborted || (custody && !custody.current())
     50           ? 'stopped'
     51           : 'storage_failed'
     52     };
     53   const row = publicRecordSnapshot(initial, custody.owner, custody.command);
     54   if (row?.family !== 'public_operation' || !row.artifact)
     55     return { status: 'invalid' };
     56   const eventId = row.artifact.eventId;
     57   const actionId = crypto.randomUUID(),
     58     controller = new AbortController(),
     59     started = performance.now();
     60   const stop = () => controller.abort();
     61   signal?.addEventListener('abort', stop, { once: true });
     62   if (signal?.aborted) stop();
     63   const remaining = () =>
     64     PUBLIC_PUBLICATION_BUDGETS.networkActionMilliseconds -
     65     (performance.now() - started);
     66   async function retain(
     67     origin: string,
     68     attempt: number,
     69     status: string,
     70     readbackWire: string | null
     71   ) {
     72     const current = await readRetainedListingDelivery(lease);
     73     if (!current || !custody) return false;
     74     const result = await commitPublicListingReceipt(
     75       custody.repository,
     76       current,
     77       custody.command,
     78       JSON.stringify({
     79         actionId,
     80         origin,
     81         role: 'publication',
     82         attempt,
     83         eventId,
     84         status,
     85         observedAtMilliseconds: Date.now(),
     86         readbackWire
     87       })
     88     );
     89     return result.status === 'saved';
     90   }
     91   try {
     92     for (const origin of row.capture.targets) {
     93       if (
     94         row.receipts.some(
     95           (fact) =>
     96             fact.origin === origin &&
     97             fact.eventId === eventId &&
     98             fact.readbackWire !== null
     99         )
    100       )
    101         continue;
    102       const accepted = row.receipts.some(
    103         (fact) =>
    104           fact.origin === origin &&
    105           fact.eventId === row.artifact!.eventId &&
    106           fact.status === 'accepted'
    107       );
    108       let done = accepted;
    109       for (
    110         let attempt = 1;
    111         attempt <= PUBLIC_PUBLICATION_BUDGETS.attemptsPerTargetAction;
    112         attempt++
    113       ) {
    114         if (!custody.current() || controller.signal.aborted)
    115           return { status: 'stopped' };
    116         if (remaining() <= 0) return { status: 'needs_action' };
    117         let status: 'accepted' | 'timed_out' = 'accepted';
    118         if (!accepted) {
    119           const permission = await authorizeListingAttempt(
    120             lease,
    121             origin,
    122             'publish'
    123           );
    124           if (!permission) return { status: 'stopped' };
    125           if (remaining() <= 0) return { status: 'needs_action' };
    126           const result = await publishPublicListingAttempt(
    127             pool,
    128             permission,
    129             policy,
    130             origin,
    131             controller.signal,
    132             remaining()
    133           );
    134           if (!(await retain(origin, attempt, result.status, null)))
    135             return { status: 'storage_failed' };
    136           if (result.status !== 'accepted' && result.status !== 'timed_out')
    137             return {
    138               status: result.status === 'stopped' ? 'stopped' : 'needs_action'
    139             };
    140           status = result.status;
    141           done = result.status === 'accepted';
    142         }
    143         const permission = await authorizeListingAttempt(
    144           lease,
    145           origin,
    146           'readback'
    147         );
    148         if (!permission) return { status: 'stopped' };
    149         if (remaining() <= 0) return { status: 'needs_action' };
    150         const readback = await readPublicListingExactAttempt(
    151           pool,
    152           permission,
    153           policy,
    154           origin,
    155           controller.signal,
    156           remaining()
    157         );
    158         if (readback.status === 'found') {
    159           if (!(await retain(origin, attempt, status, readback.wire)))
    160             return { status: 'storage_failed' };
    161           done = true;
    162         }
    163         if (readback.status === 'stopped') return { status: 'stopped' };
    164         if (done) break;
    165       }
    166       if (!done) return { status: 'needs_action' };
    167     }
    168     return { status: 'completed' };
    169   } finally {
    170     controller.abort();
    171     signal?.removeEventListener('abort', stop);
    172   }
    173 }
    174 // The public control is opaque: no caller-supplied AbortSignal, raw event,
    175 // repository or destination can substitute for the original retry custody.
    176 export function deliverControlledListing(
    177   control: ListingRetry
    178 ): Promise<ListingDeliveryResult> {
    179   const original = listingRetryOwnership(control);
    180   if (!original) return Promise.resolve({ status: 'invalid' });
    181   if (!original.current()) return Promise.resolve({ status: 'stopped' });
    182   if (pending.has(original.source)) return Promise.resolve({ status: 'busy' });
    183   const job = withListingDeliveryOwnership(
    184     original.source,
    185     original.policy,
    186     original.consent,
    187     (lease) => deliver(lease, original.pool, original.policy, original.signal),
    188     control
    189   )
    190     .then((result) =>
    191       result.status === 'completed' ? result.value : { status: result.status }
    192     )
    193     .finally(() => {
    194       if (pending.get(original.source) === job) pending.delete(original.source);
    195     });
    196   pending.set(original.source, job);
    197   return job;
    198 }
    199 export function deliverListing(
    200   publication: ListingPublication,
    201   pool: PublicPool,
    202   policy: RelayPolicy,
    203   consent: unknown
    204 ): Promise<ListingDeliveryResult> {
    205   if (consent !== 'publish_stored_listing')
    206     return Promise.resolve({ status: 'invalid' });
    207   const active = pending.get(publication);
    208   if (active) return active;
    209   const job = withListingDeliveryOwnership(
    210     publication,
    211     policy,
    212     consent,
    213     (lease) => deliver(lease, pool, policy)
    214   )
    215     .then((result) =>
    216       result.status === 'completed' ? result.value : { status: result.status }
    217     )
    218     .finally(() => {
    219       if (pending.get(publication) === job) pending.delete(publication);
    220     });
    221   pending.set(publication, job);
    222   return job;
    223 }