effect-ownership.ts (11709B)
1 import { canonicalPublicKey } from '../contracts/public-key.ts'; 2 import { canonicalLocalId } from '../private-handles.ts'; 3 import { 4 publicRecordSnapshot, 5 publicRecordWire, 6 type PublicRecordHandle 7 } from '../persistence/records.ts'; 8 import { 9 claimPublicOperation, 10 loadPreferenceOperation, 11 publicQuotaOwner, 12 type PublicQuotaRepository, 13 type PublicQuotaFailure 14 } from '../persistence/quota.ts'; 15 16 declare const leaseBrand: unique symbol; 17 export type PublicEffectLease = Readonly<{ [leaseBrand]: true }>; 18 export type PublicEffectCapture = Readonly<{ 19 owner: string; 20 session: symbol; 21 current(): boolean; 22 }>; 23 export type PublicEffectResult<T> = 24 | Readonly<{ status: 'completed'; value: T }> 25 | Readonly<{ status: 'unknown' | 'retained'; record: PublicRecordHandle }> 26 | Readonly<{ 27 status: 28 'invalid' | 'unavailable' | 'busy' | 'stopped' | PublicQuotaFailure; 29 }>; 30 type Authority = Readonly<{ 31 owner: string; 32 id: string; 33 recordWire: string; 34 session: symbol; 35 }>; 36 type State = 'active' | 'unknown' | 'stopped' | 'closed'; 37 type JobResult<T> = 38 | Readonly<{ status: 'settled'; value: T; current: boolean }> 39 | Readonly<{ status: 'invalid' | 'busy' | 'stopped' | 'unknown' }>; 40 type Controller = { 41 current(authority: Authority): boolean; 42 call<T>(authority: Authority, work: () => Promise<T>): Promise<JobResult<T>>; 43 mark(): boolean; 44 stop(): void; 45 snapshot(): Readonly<{ 46 state: State; 47 pending: boolean; 48 owner: string; 49 id: string; 50 hash: string; 51 revision: number; 52 }>; 53 }; 54 const leases = new WeakMap<PublicEffectLease, Controller>(); 55 56 // Lazy browser-only origin/author ownership. It coordinates this client, never 57 // independent Nostr clients. Only transaction completion acknowledges a plan. 58 export async function runCapturedPublicEffect<T>( 59 repository: PublicQuotaRepository, 60 handle: PublicRecordHandle, 61 expectedId: unknown, 62 input: PublicEffectCapture, 63 review: unknown, 64 work: (lease: PublicEffectLease, stored: PublicRecordHandle) => Promise<T> 65 ): Promise<PublicEffectResult<T>> { 66 try { 67 const owner = canonicalPublicKey(input?.owner), 68 id = canonicalLocalId(expectedId); 69 const session = input?.session, 70 fresh = input?.current; 71 const row = 72 owner && id ? publicRecordSnapshot(handle, owner, id) : undefined; 73 const recordWire = 74 owner && id ? publicRecordWire(handle, owner, id) : undefined; 75 if ( 76 (review !== 'reviewed_captured_operation' && 77 review !== 'reviewed_prepared_listing_operation' && 78 review !== 'reviewed_prepared_withdrawal_operation' && 79 review !== 'reviewed_prepared_preference_operation' && 80 review !== 'reviewed_stored_preference_retry') || 81 !owner || 82 !id || 83 !row || 84 !recordWire || 85 row.family === 'public_draft' || 86 row.revision !== 0 || 87 row.artifact !== null || 88 typeof session !== 'symbol' || 89 typeof fresh !== 'function' || 90 typeof work !== 'function' 91 ) 92 return { status: 'invalid' }; 93 const listingMode = review === 'reviewed_prepared_listing_operation'; 94 const withdrawalMode = review === 'reviewed_prepared_withdrawal_operation'; 95 const preferenceMode = 96 review !== 'reviewed_captured_operation' && 97 !listingMode && 98 !withdrawalMode; 99 const storedRetry = review === 'reviewed_stored_preference_retry'; 100 if ( 101 listingMode && 102 (row.family !== 'public_operation' || 103 row.capture.kind !== 30402 || 104 row.source.type !== 'draft') 105 ) 106 return { status: 'invalid' }; 107 if ( 108 withdrawalMode && 109 (row.family !== 'public_operation' || 110 row.capture.kind !== 5 || 111 row.source.type !== 'public_head') 112 ) 113 return { status: 'invalid' }; 114 if ( 115 preferenceMode && 116 (row.family !== 'preference_operation' || row.capture.kind !== 10050) 117 ) 118 return { status: 'invalid' }; 119 if (typeof window === 'undefined' || !navigator.locks?.request) 120 return { status: 'unavailable' }; 121 if (publicQuotaOwner(repository) !== owner) 122 return { status: 'invalid_scope' }; 123 return await navigator.locks.request( 124 'harvestcircle:owner:' + owner, 125 { mode: 'exclusive', ifAvailable: true }, 126 async (lock): Promise<PublicEffectResult<T>> => { 127 if (!lock) return { status: 'busy' }; 128 if (!fresh()) return { status: 'stopped' }; 129 async function claimOriginal() { 130 if (!storedRetry) 131 return await claimPublicOperation(repository, id, handle); 132 const loaded = await loadPreferenceOperation(repository, id); 133 if (!loaded.ok) return loaded; 134 const stored = publicRecordSnapshot(loaded.value, owner, id); 135 if ( 136 stored?.family !== 'preference_operation' || 137 row?.family !== 'preference_operation' || 138 JSON.stringify(stored.capture) !== JSON.stringify(row.capture) || 139 JSON.stringify(stored.source) !== JSON.stringify(row.source) || 140 stored.consent !== row.consent 141 ) 142 return { ok: false as const, reason: 'conflict' as const }; 143 return { 144 ok: true as const, 145 value: { state: 'existing' as const, record: loaded.value } 146 }; 147 } 148 const claimed = await claimOriginal(); 149 if (!claimed.ok) 150 return claimed.reason === 'unknown_completion' 151 ? { status: 'unknown', record: handle } 152 : { status: claimed.reason }; 153 const original = claimed.value.record; 154 if (storedRetry && claimed.value.state !== 'existing') 155 return { status: 'unknown', record: original }; 156 if (claimed.value.state === 'existing') { 157 const stored = publicRecordSnapshot(original, owner, id); 158 const prepared = 159 !storedRetry && 160 ((preferenceMode && stored?.family === 'preference_operation') || 161 (listingMode && 162 stored?.family === 'public_operation' && 163 stored.capture.kind === 30402 && 164 stored.source.type === 'draft') || 165 (withdrawalMode && 166 stored?.family === 'public_operation' && 167 stored.capture.kind === 5 && 168 stored.source.type === 'public_head')) && 169 stored.revision === 0 && 170 stored.artifact === null; 171 const retry = 172 storedRetry && 173 stored?.family === 'preference_operation' && 174 stored.revision >= 2 && 175 stored.artifact !== null; 176 if (!prepared && !retry) 177 return { 178 status: 179 stored && 180 stored.family !== 'public_draft' && 181 stored.artifact !== null 182 ? 'retained' 183 : 'unknown', 184 record: original 185 }; 186 } 187 let phase: State = 'active', 188 closed = false, 189 accepting = true, 190 started = false; 191 let settlement: Promise<void> | null = null; 192 function outstanding(): Promise<void> | null { 193 return settlement; 194 } 195 function stop() { 196 if (!closed) phase = started ? 'unknown' : 'stopped'; 197 } 198 function current() { 199 if (closed || phase !== 'active') return false; 200 let valid = false; 201 try { 202 valid = publicQuotaOwner(repository) === owner && fresh() === true; 203 } catch { 204 /* finite stale result */ 205 } 206 if (!valid) stop(); 207 return valid && !closed && phase === 'active'; 208 } 209 function matches(authority: Authority) { 210 return ( 211 authority.owner === owner && 212 authority.id === id && 213 authority.recordWire === recordWire && 214 authority.session === session 215 ); 216 } 217 const lease = Object.freeze({}) as PublicEffectLease; 218 async function call<V>( 219 authority: Authority, 220 invoke: () => Promise<V> 221 ): Promise<JobResult<V>> { 222 if ( 223 storedRetry || 224 !matches(authority) || 225 typeof invoke !== 'function' 226 ) 227 return { status: 'invalid' }; 228 if (!accepting || !current()) 229 return { status: phase === 'unknown' ? 'unknown' : 'stopped' }; 230 if (outstanding()) return { status: 'busy' }; 231 if (started) return { status: 'stopped' }; 232 // Reserve the whole SDK job before invoking even its synchronous prefix. 233 // Callback return cannot release a forgotten/unsettled permission wait. 234 let release = () => {}; 235 const held = new Promise<void>((resolve) => { 236 release = resolve; 237 }); 238 settlement = held; 239 try { 240 const value = await invoke(); 241 return { status: 'settled', value, current: current() }; 242 } catch { 243 stop(); 244 return { status: phase === 'unknown' ? 'unknown' : 'stopped' }; 245 } finally { 246 settlement = null; 247 release(); 248 } 249 } 250 leases.set(lease, { 251 current: (authority) => matches(authority) && current(), 252 call, 253 stop, 254 mark() { 255 if (storedRetry || started || !outstanding() || !current()) 256 return false; 257 started = true; 258 return true; 259 }, 260 snapshot: () => ({ 261 state: phase, 262 pending: outstanding() !== null, 263 owner, 264 id, 265 hash: row.capture.hash, 266 revision: row.revision 267 }) 268 }); 269 try { 270 if (!current()) return { status: 'stopped' }; 271 let value: T; 272 try { 273 value = await work(lease, original); 274 } catch { 275 stop(); 276 return { 277 status: 'unknown', 278 record: original 279 }; 280 } 281 accepting = false; 282 const waiting = outstanding(); 283 if (waiting) { 284 // An orphaned job may settle, but cannot acquire more SDK effects 285 // or expose an artifact after the operation callback has returned. 286 phase = 'unknown'; 287 await waiting; 288 } 289 if (!current()) 290 return phase === 'unknown' 291 ? { status: 'unknown', record: original } 292 : { status: 'stopped' }; 293 return { status: 'completed', value }; 294 } finally { 295 accepting = false; 296 const waiting = outstanding(); 297 if (waiting) await waiting; 298 closed = true; 299 if (phase === 'active') phase = 'closed'; 300 } 301 } 302 ); 303 } catch { 304 return { status: 'unavailable' }; 305 } 306 } 307 // These internal mechanical ports expose neither a signer nor a raw template. 308 // The adapter supplies its actual private session and genuine approval wire. 309 export function publicEffectLeaseCurrent( 310 lease: PublicEffectLease, 311 authority: Authority 312 ): boolean { 313 return leases.get(lease)?.current(authority) ?? false; 314 } 315 export function callOwnedExtension<T>( 316 lease: PublicEffectLease, 317 authority: Authority, 318 work: () => Promise<T> 319 ): Promise<JobResult<T>> { 320 return ( 321 leases.get(lease)?.call(authority, work) ?? 322 Promise.resolve({ status: 'invalid' }) 323 ); 324 } 325 export function markOwnedSignaturePending(lease: PublicEffectLease): boolean { 326 return leases.get(lease)?.mark() ?? false; 327 } 328 export function stopPublicEffect(lease: PublicEffectLease): void { 329 leases.get(lease)?.stop(); 330 } 331 export function publicEffectSnapshot(lease: PublicEffectLease) { 332 return leases.get(lease)?.snapshot(); 333 }