app

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

inbox-probe-cleanup.ts (13683B)


      1 import type { RelayPolicy } from '../config/relays.ts';
      2 import type { InboxOperatorQualification } from '../config/inbox-operators.ts';
      3 import {
      4   inboxAccessConstructionBinding,
      5   subscribeInboxAccessControllerClose,
      6   type InboxAccessController
      7 } from '../messaging/inbox-access-controller.ts';
      8 import {
      9   acquireInboxProbeCleanupLease,
     10   inboxProbeCleanupReady,
     11   inboxProbeCleanupLeaseCurrent,
     12   releaseInboxProbeCleanupLease,
     13   retireInboxProbeCleanupLease,
     14   inboxProbeQualifiedRemovalBinding
     15 } from '../nostr/private-publisher.ts';
     16 import {
     17   privateSessionOwnership,
     18   recheckPrivateSession,
     19   subscribePrivateSessionClose,
     20   withIdlePrivateLocalStorage,
     21   type PrivateSession
     22 } from '../runtime/private-session.ts';
     23 import {
     24   captureInboxProbeCleanupSelection,
     25   inboxProbeCleanupSelectionBinding,
     26   type InboxProbeCleanupSelection,
     27   type InboxProbeNonceAcknowledgement
     28 } from './inbox-probes.ts';
     29 import { privateRecordWire } from './private-records.ts';
     30 import {
     31   observePrivateRecord,
     32   removePrivateInboxProbe,
     33   type PrivateStorageRepository,
     34   type PrivateStorageFailure,
     35   type PrivateProbeRemovalProof
     36 } from './private-storage.ts';
     37 
     38 declare const cleanupBrand: unique symbol;
     39 export type InboxProbeCleanup = Readonly<{ [cleanupBrand]: true }>;
     40 declare const nativeCleanupBrand: unique symbol;
     41 export type InboxProbeNativeCleanup = Readonly<{ [nativeCleanupBrand]: true }>;
     42 declare const removalAcknowledgementBrand: unique symbol;
     43 export type InboxProbeRemovalAcknowledgement = Readonly<{
     44   [removalAcknowledgementBrand]: true;
     45 }>;
     46 export type InboxProbeCleanupResult = Readonly<{
     47   status: 'removed' | 'invalid' | 'busy' | 'stopped' | PrivateStorageFailure;
     48   removed?: 1;
     49   acknowledgement?: InboxProbeRemovalAcknowledgement;
     50 }>;
     51 type NativeAdmission = Readonly<{
     52   repository: PrivateStorageRepository;
     53   session: PrivateSession;
     54   selection: InboxProbeCleanupSelection;
     55   owner: string;
     56   id: string;
     57   wire: string;
     58   signal: AbortSignal;
     59   current(): boolean;
     60   take(): boolean;
     61 }>;
     62 const nativeAdmissions = new WeakMap<
     63   InboxProbeNativeCleanup,
     64   NativeAdmission
     65 >();
     66 const actions = new WeakMap<
     67   InboxProbeCleanup,
     68   Readonly<{
     69     run(review: unknown): Promise<InboxProbeCleanupResult>;
     70     stop(): void;
     71   }>
     72 >();
     73 const removals = new WeakMap<
     74   InboxProbeRemovalAcknowledgement,
     75   Readonly<{
     76     repository: PrivateStorageRepository;
     77     session: PrivateSession;
     78     policy: RelayPolicy;
     79     access: InboxAccessController;
     80     operator: InboxOperatorQualification;
     81     nativeProof: PrivateProbeRemovalProof;
     82     owner: string;
     83     command: string;
     84     eventId: string;
     85     preferenceId: string;
     86     readTargets: readonly string[];
     87     archiveTargets: readonly string[];
     88     operatorWire: string;
     89     current(): boolean;
     90   }>
     91 >();
     92 
     93 // Only this module issues these tickets, while its actual owner WebLock and SDK
     94 // job are both held. No public capture returns a native ticket or raw validator.
     95 export function inboxProbeCleanupAdmission(
     96   ticket: InboxProbeNativeCleanup,
     97   repository: PrivateStorageRepository,
     98   session: PrivateSession
     99 ) {
    100   const saved = nativeAdmissions.get(ticket);
    101   return saved?.repository === repository &&
    102     saved.session === session &&
    103     saved.current()
    104     ? saved
    105     : undefined;
    106 }
    107 
    108 export async function captureInboxProbeCleanup(
    109   repository: PrivateStorageRepository,
    110   session: PrivateSession,
    111   policy: RelayPolicy,
    112   nonce: InboxProbeNonceAcknowledgement,
    113   observations: unknown,
    114   review: unknown
    115 ): Promise<InboxProbeCleanup | undefined> {
    116   const selection = captureInboxProbeCleanupSelection(
    117       repository,
    118       session,
    119       policy,
    120       nonce,
    121       observations,
    122       review
    123     ),
    124     selected =
    125       selection &&
    126       inboxProbeCleanupSelectionBinding(selection, repository, session, policy);
    127   if (!selection || !selected) return undefined;
    128   try {
    129     const scope = inboxAccessConstructionBinding(
    130         selected.access,
    131         session,
    132         policy
    133       ),
    134       ownership = privateSessionOwnership(session);
    135     if (!scope || !ownership?.current()) return undefined;
    136     const observed = await observePrivateRecord(
    137       repository,
    138       'private_sends',
    139       selected.record.id
    140     );
    141     if (
    142       !observed.ok ||
    143       observed.value.wire !== selected.wire ||
    144       !selected.current() ||
    145       !scope.current() ||
    146       !ownership.current()
    147     )
    148       return undefined;
    149     const token = Object.freeze({}) as InboxProbeCleanup,
    150       cancellation = new AbortController();
    151     let stopped = false,
    152       used = false;
    153     const listeners = new Map<symbol, () => void>();
    154     function forget() {
    155       for (const [id, off] of listeners) {
    156         off();
    157         listeners.delete(id);
    158       }
    159     }
    160     function stop() {
    161       stopped = true;
    162       cancellation.abort();
    163       forget();
    164     }
    165     function current() {
    166       return (
    167         !stopped &&
    168         !cancellation.signal.aborted &&
    169         selected!.current() &&
    170         scope!.current() &&
    171         ownership!.current()
    172       );
    173     }
    174     actions.set(token, {
    175       stop,
    176       async run(consent) {
    177         if (consent !== 'reviewed_delete_local_inbox_probe' || used)
    178           return { status: 'invalid' };
    179         if (!current()) return { status: 'stopped' };
    180         used = true;
    181         let attempted = false;
    182         try {
    183           if (!navigator.locks?.request) return { status: 'unavailable' };
    184           return await navigator.locks.request(
    185             'harvestcircle:owner:' + selected.record.owner,
    186             { mode: 'exclusive', ifAvailable: true },
    187             async (lock): Promise<InboxProbeCleanupResult> => {
    188               if (!lock) return { status: 'busy' };
    189               if (!current()) return { status: 'stopped' };
    190               if (
    191                 !inboxProbeCleanupReady(repository, session, policy, selection)
    192               )
    193                 return { status: current() ? 'busy' : 'stopped' };
    194               // No provider request is made while a foreign owner lock is held.
    195               // The actual fresh key wait finishes before the short SDK/IDB job.
    196               if (!(await recheckPrivateSession(session)))
    197                 return { status: current() ? 'busy' : 'stopped' };
    198               if (!current()) return { status: 'stopped' };
    199               const job =
    200                 await withIdlePrivateLocalStorage<InboxProbeCleanupResult>(
    201                   session,
    202                   async () => {
    203                     if (!current()) return { status: 'stopped' };
    204                     if (!selected.begin()) return { status: 'busy' };
    205                     const lease = acquireInboxProbeCleanupLease(
    206                       repository,
    207                       session,
    208                       policy,
    209                       selection
    210                     );
    211                     let ticket: InboxProbeNativeCleanup | undefined,
    212                       active = false,
    213                       taken = false;
    214                     try {
    215                       if (!lease)
    216                         return { status: current() ? 'busy' : 'stopped' };
    217                       const read = await observePrivateRecord(
    218                         repository,
    219                         'private_sends',
    220                         selected.record.id
    221                       );
    222                       if (!read.ok) {
    223                         if (current()) releaseInboxProbeCleanupLease(lease);
    224                         return { status: read.reason };
    225                       }
    226                       if (
    227                         read.value.wire !== selected.wire ||
    228                         privateRecordWire(
    229                           read.value.handle,
    230                           selected.record.owner,
    231                           selected.record.id
    232                         ) !== selected.wire
    233                       ) {
    234                         if (current()) releaseInboxProbeCleanupLease(lease);
    235                         return { status: 'conflict' };
    236                       }
    237                       if (!current() || !inboxProbeCleanupLeaseCurrent(lease))
    238                         return { status: 'stopped' };
    239                       active = true;
    240                       ticket = Object.freeze({}) as InboxProbeNativeCleanup;
    241                       nativeAdmissions.set(ticket, {
    242                         repository,
    243                         session,
    244                         selection,
    245                         owner: selected.record.owner,
    246                         id: selected.record.id,
    247                         wire: selected.wire,
    248                         signal: cancellation.signal,
    249                         current: () =>
    250                           active &&
    251                           current() &&
    252                           inboxProbeCleanupLeaseCurrent(lease),
    253                         take() {
    254                           if (taken) return false;
    255                           taken = true;
    256                           return true;
    257                         }
    258                       });
    259                       attempted = true;
    260                       const removed = await removePrivateInboxProbe(
    261                         repository,
    262                         session,
    263                         ticket
    264                       );
    265                       if (!removed.ok) {
    266                         if (removed.disposition === 'not_removed' && current())
    267                           releaseInboxProbeCleanupLease(lease);
    268                         return { status: removed.reason };
    269                       }
    270                       if (!current() || !inboxProbeCleanupLeaseCurrent(lease))
    271                         return { status: 'unknown_completion' };
    272                       if (!retireInboxProbeCleanupLease(lease, removed.value))
    273                         return { status: 'unknown_completion' };
    274                       // Old nonce/ACKs are now deliberately gone. The removal fact
    275                       // follows the separately captured real controller/session.
    276                       if (stopped || !scope.current() || !ownership.current())
    277                         return { status: 'unknown_completion' };
    278                       const acknowledgement = Object.freeze(
    279                         {}
    280                       ) as InboxProbeRemovalAcknowledgement;
    281                       removals.set(acknowledgement, {
    282                         repository,
    283                         session,
    284                         policy,
    285                         access: selected.access,
    286                         operator: selected.operator,
    287                         nativeProof: removed.value,
    288                         owner: selected.record.owner,
    289                         command: selected.record.id,
    290                         eventId: selected.record.self!.eventId,
    291                         preferenceId: selected.record.binding.preferenceId,
    292                         readTargets:
    293                           selected.record.binding.readTargets.slice(),
    294                         archiveTargets:
    295                           selected.record.binding.archiveTargets.slice(),
    296                         operatorWire: selected.record.binding.operatorWire,
    297                         current: () => scope.current() && ownership.current()
    298                       });
    299                       return { status: 'removed', removed: 1, acknowledgement };
    300                     } finally {
    301                       active = false;
    302                       if (ticket) nativeAdmissions.delete(ticket);
    303                       selected.finish();
    304                     }
    305                   }
    306                 );
    307               return job.ok
    308                 ? job.value
    309                 : {
    310                     status: attempted
    311                       ? 'unknown_completion'
    312                       : current()
    313                         ? 'busy'
    314                         : 'stopped'
    315                   };
    316             }
    317           );
    318         } catch {
    319           return {
    320             status: attempted
    321               ? 'unknown_completion'
    322               : current()
    323                 ? 'unavailable'
    324                 : 'stopped'
    325           };
    326         } finally {
    327           forget();
    328         }
    329       }
    330     });
    331     const offSession = subscribePrivateSessionClose(session, stop);
    332     listeners.set(Symbol(), offSession);
    333     const offAccess = subscribeInboxAccessControllerClose(
    334       selected.access,
    335       stop
    336     );
    337     listeners.set(Symbol(), offAccess);
    338     if (!current()) {
    339       stop();
    340       return undefined;
    341     }
    342     return token;
    343   } catch {
    344     return undefined;
    345   }
    346 }
    347 
    348 export function deleteReviewedInboxProbe(
    349   token: InboxProbeCleanup,
    350   review: unknown
    351 ): Promise<InboxProbeCleanupResult> {
    352   return (
    353     actions.get(token)?.run(review) ?? Promise.resolve({ status: 'invalid' })
    354   );
    355 }
    356 export function stopInboxProbeCleanup(token: InboxProbeCleanup): void {
    357   actions.get(token)?.stop();
    358 }
    359 export function inboxProbeRemovalAcknowledgementBinding(
    360   acknowledgement: InboxProbeRemovalAcknowledgement,
    361   repository: PrivateStorageRepository,
    362   session: PrivateSession,
    363   policy: RelayPolicy
    364 ) {
    365   const saved = removals.get(acknowledgement);
    366   return saved?.repository === repository &&
    367     saved.session === session &&
    368     saved.policy === policy &&
    369     saved.current()
    370     ? {
    371         owner: saved.owner,
    372         access: saved.access,
    373         operator: saved.operator,
    374         qualification: inboxProbeQualifiedRemovalBinding(
    375           saved.nativeProof,
    376           repository,
    377           session,
    378           policy
    379         ),
    380         command: saved.command,
    381         eventId: saved.eventId,
    382         preferenceId: saved.preferenceId,
    383         readTargets: saved.readTargets.slice(),
    384         archiveTargets: saved.archiveTargets.slice(),
    385         operatorWire: saved.operatorWire,
    386         current: saved.current
    387       }
    388     : undefined;
    389 }