private-send-reservations.ts (8795B)
1 import { canonicalPublicKey } from '../contracts/public-key.ts'; 2 import { exactLocalFields } from '../contracts/local-records.ts'; 3 import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts'; 4 import { canonicalLocalId } from '../private-handles.ts'; 5 import { safeUnsignedInteger } from '../nostr/envelope-bounds.ts'; 6 import { LOCAL_PERSISTENCE_BUDGETS } from '../config/budgets.ts'; 7 import { 8 browserDatabaseState, 9 browserDatabaseTransaction, 10 type BrowserDatabase 11 } from './database.ts'; 12 import { 13 inspectPrivateSendReservation, 14 decodePrivateRecord, 15 privateRecordSnapshot, 16 type PrivateSendReservation 17 } from './private-records.ts'; 18 export { 19 inspectPrivateSendReservation, 20 type PrivateSendReservation 21 } from './private-records.ts'; 22 declare const repositoryBrand: unique symbol; 23 export type PrivateSendReservationRepository = Readonly<{ 24 [repositoryBrand]: true; 25 }>; 26 export type ReservationFailure = 27 | 'invalid' 28 | 'invalid_scope' 29 | 'unavailable' 30 | 'aborted' 31 | 'unknown_completion' 32 | 'corrupt_record' 33 | 'capacity' 34 | 'conflict' 35 | 'clock_conflict' 36 | 'stopped'; 37 export type ReservationResult = 38 | Readonly<{ 39 ok: true; 40 state: 'created' | 'existing'; 41 value: PrivateSendReservation; 42 }> 43 | Readonly<{ 44 ok: false; 45 reason: ReservationFailure; 46 disposition: 'not_attempted' | 'not_created' | 'may_exist'; 47 }>; 48 type Scope = { database: BrowserDatabase; owner: string }; 49 const repositories = new WeakMap<PrivateSendReservationRepository, Scope>(); 50 const failed = ( 51 reason: ReservationFailure, 52 disposition: 'not_attempted' | 'not_created' | 'may_exist' = 'not_attempted' 53 ): ReservationResult => ({ 54 ok: false, 55 reason, 56 disposition 57 }); 58 export function createPrivateSendReservationRepository( 59 database: BrowserDatabase, 60 expectedOwner: unknown 61 ): PrivateSendReservationRepository | undefined { 62 const owner = canonicalPublicKey(expectedOwner); 63 try { 64 if (!owner || browserDatabaseState(database).state !== 'ready') 65 return undefined; 66 const token = Object.freeze({}) as PrivateSendReservationRepository; 67 repositories.set(token, { database, owner }); 68 return token; 69 } catch { 70 return undefined; 71 } 72 } 73 export function privateSendReservationOwner( 74 repository: PrivateSendReservationRepository 75 ) { 76 return repositories.get(repository)?.owner; 77 } 78 // Atomic local metadata CAS, not identity, signing, encryption, relay delivery 79 // or global uniqueness proof. Completion, never request success, grants credit. 80 export function reservePrivateSendReservation( 81 repository: PrivateSendReservationRepository, 82 rawReservation: unknown, 83 observedSeconds: unknown, 84 current: () => boolean 85 ): Promise<ReservationResult> { 86 const scope = repositories.get(repository); 87 if ( 88 !scope || 89 typeof rawReservation !== 'string' || 90 typeof current !== 'function' 91 ) 92 return Promise.resolve(failed('invalid')); 93 let candidateId: unknown; 94 try { 95 if (!boundedUtf8(rawReservation, 4096)) 96 return Promise.resolve(failed('invalid')); 97 const input: unknown = JSON.parse(rawReservation); 98 if (typeof input !== 'object' || input === null || Array.isArray(input)) 99 return Promise.resolve(failed('invalid')); 100 candidateId = (input as Record<string, unknown>).id; 101 } catch { 102 return Promise.resolve(failed('invalid')); 103 } 104 const candidate = inspectPrivateSendReservation( 105 rawReservation, 106 scope.owner, 107 candidateId 108 ), 109 seconds = safeUnsignedInteger(observedSeconds); 110 if (!candidate || seconds === undefined) 111 return Promise.resolve(failed('invalid')); 112 const wire = JSON.stringify(candidate), 113 next = { owner: scope.owner, id: candidate.id, wire }; 114 let transaction: IDBTransaction; 115 try { 116 transaction = browserDatabaseTransaction( 117 scope.database, 118 ['private_sends'], 119 'readwrite' 120 ); 121 } catch { 122 return Promise.resolve(failed('unavailable')); 123 } 124 return new Promise((resolve) => { 125 let outcome: ReservationResult | undefined; 126 let existing: PrivateSendReservation | undefined; 127 let candidateAbsent = false; 128 let count = 0, 129 bytes = 0, 130 collision = false; 131 function refuse(reason: ReservationFailure) { 132 outcome = failed(reason, 'may_exist'); 133 try { 134 transaction.abort(); 135 } catch { 136 outcome = failed('unknown_completion', 'may_exist'); 137 } 138 } 139 transaction.addEventListener('complete', () => 140 resolve(outcome ?? failed('unknown_completion', 'may_exist')) 141 ); 142 transaction.addEventListener('abort', () => { 143 const reason = outcome && !outcome.ok ? outcome.reason : 'aborted'; 144 resolve(failed(reason, candidateAbsent ? 'not_created' : 'may_exist')); 145 }); 146 try { 147 const store = transaction.objectStore('private_sends'); 148 // Same transaction and owner lock: absence plus actual abort proves no 149 // original row survived. Request success alone never credits a write. 150 const candidateRequest = store.get([scope.owner, candidate.id]); 151 candidateRequest.addEventListener('success', () => { 152 candidateAbsent = candidateRequest.result === undefined; 153 }); 154 const request = store 155 .index('by_owner') 156 .openCursor(IDBKeyRange.only(scope.owner)); 157 request.addEventListener('success', () => { 158 try { 159 if (!current()) { 160 refuse('stopped'); 161 return; 162 } 163 const cursor = request.result; 164 if (cursor) { 165 const key = cursor.primaryKey, 166 id = 167 Array.isArray(key) && key.length === 2 && key[0] === scope.owner 168 ? canonicalLocalId(key[1]) 169 : undefined; 170 const row: unknown = cursor.value; 171 if ( 172 !id || 173 !exactLocalFields(row, ['owner', 'id', 'wire']) || 174 row.owner !== scope.owner || 175 row.id !== id || 176 typeof row.wire !== 'string' 177 ) { 178 refuse('corrupt_record'); 179 return; 180 } 181 const decoded = decodePrivateRecord(row.wire, scope.owner, id), 182 value = 183 decoded.ok && 184 privateRecordSnapshot(decoded.value, scope.owner, id); 185 if (!value || value.family === 'received_envelope') { 186 refuse('corrupt_record'); 187 return; 188 } 189 count += 1; 190 if ( 191 value.id === candidate.id && 192 value.family === 'private_access_probe' 193 ) { 194 refuse('conflict'); 195 return; 196 } 197 if ( 198 value.id === candidate.id && 199 value.family !== 'private_access_probe' 200 ) 201 existing = { 202 schema: 1, 203 family: 'private_send_reservation', 204 owner: value.owner, 205 id: value.id, 206 revision: 0, 207 peer: value.peer, 208 rumorHash: value.rumorHash, 209 createdAt: value.createdAt 210 }; 211 if ( 212 value.family !== 'private_access_probe' && 213 value.rumorHash === candidate.rumorHash 214 ) 215 collision = true; 216 bytes += new TextEncoder().encode(JSON.stringify(row)).length; 217 if ( 218 count > LOCAL_PERSISTENCE_BUDGETS.unfinishedPrivateSends || 219 bytes > LOCAL_PERSISTENCE_BUDGETS.privateSendBytes 220 ) { 221 refuse('capacity'); 222 return; 223 } 224 cursor.continue(); 225 return; 226 } 227 if (existing) { 228 if (JSON.stringify(existing) !== wire) { 229 refuse('conflict'); 230 return; 231 } 232 outcome = { ok: true, state: 'existing', value: existing }; 233 return; 234 } 235 if (candidate.createdAt > seconds || collision) { 236 refuse('clock_conflict'); 237 return; 238 } 239 if ( 240 count >= LOCAL_PERSISTENCE_BUDGETS.unfinishedPrivateSends || 241 bytes + new TextEncoder().encode(JSON.stringify(next)).length > 242 LOCAL_PERSISTENCE_BUDGETS.privateSendBytes 243 ) { 244 refuse('capacity'); 245 return; 246 } 247 if (!current()) { 248 refuse('stopped'); 249 return; 250 } 251 // The owner cursor proved this key absent in the same readwrite 252 // transaction; put cannot replace another concurrent reservation. 253 store.put(next); 254 outcome = { ok: true, state: 'created', value: candidate }; 255 } catch { 256 refuse('aborted'); 257 } 258 }); 259 } catch { 260 refuse('aborted'); 261 } 262 }); 263 }