app

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

private-receipts.ts (5801B)


      1 import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts';
      2 import { exactLocalFields } from '../contracts/local-records.ts';
      3 import { LOCAL_PERSISTENCE_BUDGETS } from '../config/budgets.ts';
      4 import {
      5   decodePrivateRecord,
      6   privateRecordSnapshot,
      7   privateRecordWire,
      8   type PrivateRecordHandle,
      9   type PrivateTargetReceipt
     10 } from './private-records.ts';
     11 import {
     12   commitPrivateRecord,
     13   loadPrivateRecord,
     14   type PrivateStorageRepository,
     15   type PrivateStorageFailure
     16 } from './private-storage.ts';
     17 declare const transitionBrand: unique symbol;
     18 export type PrivateReceiptTransition = Readonly<{ [transitionBrand]: true }>;
     19 type Transition = Readonly<{
     20   owner: string;
     21   id: string;
     22   base: PrivateRecordHandle;
     23   next: PrivateRecordHandle;
     24   baseWire: string;
     25   nextWire: string;
     26 }>;
     27 const transitions = new WeakMap<PrivateReceiptTransition, Transition>();
     28 type Result =
     29   | Readonly<{ ok: true; value: PrivateReceiptTransition }>
     30   | Readonly<{
     31       ok: false;
     32       reason: 'invalid_record' | 'conflict' | 'revision_exhausted';
     33     }>;
     34 function sameFact(a: PrivateTargetReceipt, b: PrivateTargetReceipt) {
     35   return (
     36     a.actionId === b.actionId &&
     37     a.origin === b.origin &&
     38     a.role === b.role &&
     39     a.attempt === b.attempt &&
     40     a.eventId === b.eventId &&
     41     a.status === b.status
     42   );
     43 }
     44 // Primitive canonical JSON only. Strict complete private codec binds the named
     45 // role/destination to the persisted outer ID and verifies exact readback bytes.
     46 // This is observed local bookkeeping, not network provenance/effect authority.
     47 export function preparePrivateReceiptTransition(
     48   record: PrivateRecordHandle,
     49   owner: unknown,
     50   id: unknown,
     51   receiptWire: unknown
     52 ): Result {
     53   const row = privateRecordSnapshot(record, owner, id),
     54     baseWire = privateRecordWire(record, owner, id);
     55   if (
     56     !row ||
     57     row.family !== 'private_send_operation' ||
     58     !row.peerArtifact ||
     59     !row.deliveryPlan ||
     60     !baseWire ||
     61     typeof receiptWire !== 'string' ||
     62     !boundedUtf8(receiptWire, LOCAL_PERSISTENCE_BUDGETS.privateSendBytes)
     63   )
     64     return { ok: false, reason: 'invalid_record' };
     65   try {
     66     const fact: unknown = JSON.parse(receiptWire);
     67     if (
     68       JSON.stringify(fact) !== receiptWire ||
     69       !exactLocalFields(fact, [
     70         'actionId',
     71         'origin',
     72         'role',
     73         'attempt',
     74         'eventId',
     75         'status',
     76         'observedAtMilliseconds',
     77         'readbackWire'
     78       ])
     79     )
     80       return { ok: false, reason: 'invalid_record' };
     81     const checked = decodePrivateRecord(
     82       JSON.stringify({ ...row, receipts: [fact] }),
     83       row.owner,
     84       row.id
     85     );
     86     if (!checked.ok) return { ok: false, reason: 'invalid_record' };
     87     const admitted = privateRecordSnapshot(checked.value, row.owner, row.id);
     88     if (
     89       !admitted ||
     90       admitted.family !== 'private_send_operation' ||
     91       !admitted.receipts
     92     )
     93       return { ok: false, reason: 'invalid_record' };
     94     const nextFact = admitted.receipts[0],
     95       existing = row.receipts?.find((r) => sameFact(r, nextFact));
     96     let next = record,
     97       nextWire = baseWire;
     98     if (existing) {
     99       if (existing.readbackWire !== nextFact.readbackWire)
    100         return { ok: false, reason: 'conflict' };
    101     } else {
    102       if (row.revision === Number.MAX_SAFE_INTEGER)
    103         return { ok: false, reason: 'revision_exhausted' };
    104       const decoded = decodePrivateRecord(
    105         JSON.stringify({
    106           ...row,
    107           revision: row.revision + 1,
    108           receipts: [...(row.receipts ?? []), nextFact]
    109         }),
    110         row.owner,
    111         row.id
    112       );
    113       if (!decoded.ok) return { ok: false, reason: 'invalid_record' };
    114       next = decoded.value;
    115       const wire = privateRecordWire(next, row.owner, row.id);
    116       if (!wire) return { ok: false, reason: 'invalid_record' };
    117       nextWire = wire;
    118     }
    119     const token = Object.freeze({}) as PrivateReceiptTransition;
    120     transitions.set(token, {
    121       owner: row.owner,
    122       id: row.id,
    123       base: record,
    124       next,
    125       baseWire,
    126       nextWire
    127     });
    128     return { ok: true, value: token };
    129   } catch {
    130     return { ok: false, reason: 'invalid_record' };
    131   }
    132 }
    133 export function privateReceiptTransitionSnapshot(
    134   token: PrivateReceiptTransition,
    135   owner: unknown,
    136   id: unknown
    137 ) {
    138   const saved = transitions.get(token);
    139   return saved && saved.owner === owner && saved.id === id
    140     ? { ...saved }
    141     : undefined;
    142 }
    143 export type PrivateReceiptCommitResult =
    144   | Readonly<{ status: 'saved' | 'existing'; record: PrivateRecordHandle }>
    145   | Readonly<{ status: PrivateStorageFailure | 'invalid' }>;
    146 // No SDK work in IDB. Request success is insufficient: actual exact full-wire
    147 // readback must acknowledge the CAS append. Unknown commits stay uncertain.
    148 export async function commitPrivateReceiptTransition(
    149   repository: PrivateStorageRepository,
    150   token: PrivateReceiptTransition
    151 ): Promise<PrivateReceiptCommitResult> {
    152   const saved = transitions.get(token);
    153   if (!saved) return { status: 'invalid' };
    154   try {
    155     let status: 'saved' | 'existing' = 'existing';
    156     if (saved.baseWire !== saved.nextWire) {
    157       const committed = await commitPrivateRecord(
    158         repository,
    159         saved.next,
    160         saved.base
    161       );
    162       if (!committed.ok) return { status: committed.reason };
    163       status = committed.value.state === 'existing' ? 'existing' : 'saved';
    164     }
    165     const readback = await loadPrivateRecord(
    166       repository,
    167       'private_sends',
    168       saved.id
    169     );
    170     if (!readback.ok) return { status: 'unknown_completion' };
    171     if (
    172       privateRecordWire(readback.value, saved.owner, saved.id) !==
    173       saved.nextWire
    174     )
    175       return { status: 'conflict' };
    176     return { status, record: readback.value };
    177   } catch {
    178     return { status: 'unknown_completion' };
    179   }
    180 }