cited-product.ts (8644B)
1 import { includedProductVersion } from '../nostr/enquiry-references.ts'; 2 import { PUBLIC_QUERY_BUDGETS } from '../config/budgets.ts'; 3 import { decodeProductReference } from '../nostr/references.ts'; 4 import { 5 inboxMessageSnapshot, 6 inboxReplyOwnership, 7 inboxThreadSnapshot, 8 subscribeInboxView, 9 type InboxReplyOwnership, 10 type InboxView 11 } from './inbox-view.ts'; 12 import { 13 createPublicView, 14 beginPublicViewRun, 15 disposePublicView, 16 publicViewRunCurrent, 17 publicViewOwnsRun, 18 publicViewProjectionAvailable, 19 subscribePublicView, 20 type PublicView, 21 type PublicRuntime 22 } from '../runtime/public-runtime.ts'; 23 import { 24 publicRequestScopeSnapshot, 25 type PublicRequest 26 } from '../nostr/request-scope.ts'; 27 import { 28 createPublicHeadCandidate, 29 publicHeadSnapshot, 30 selectPublicHead, 31 type PublicHead 32 } from '../catalog/heads.ts'; 33 import { 34 createPublicViewHeadResolver, 35 headResolutionSnapshot, 36 resolveHeads, 37 closeHeadResolver 38 } from '../catalog/resolve-head.ts'; 39 import { subscribePrivateSessionClose } from '../runtime/private-session.ts'; 40 import { subscribeIdentityInvalidation } from '../runtime/identity-session.ts'; 41 import type { FoodProjection } from '../contracts/food-availability-v1/read.ts'; 42 43 declare const citedBrand: unique symbol; 44 export type CitedProduct = Readonly<{ [citedBrand]: true }>; 45 type Snapshot = Readonly<{ 46 outcome: 'checking' | 'unresolved' | 'active' | 'sold' | 'withdrawn'; 47 food?: FoodProjection; 48 lastKnownFood?: FoodProjection; 49 includedVersion: 'none' | 'unverified' | 'matched' | 'different'; 50 }>; 51 const owners = new WeakMap< 52 CitedProduct, 53 { snapshot(): Snapshot | undefined; close(): void } 54 >(); 55 56 export function conversationOptionsSnapshot( 57 view: InboxView, 58 id: string 59 ): Readonly<{ peer: string }> | undefined { 60 const thread = inboxThreadSnapshot(view, id); 61 for (const row of thread.messages) { 62 const original = inboxReplyOwnership(view, id, row.data.rumorId); 63 if (original?.current()) return { peer: original.peer }; 64 } 65 return undefined; 66 } 67 export function requestConversationOption( 68 view: InboxView, 69 id: string, 70 action: 'block' | 'report', 71 invoke: (peer: string) => void, 72 review: unknown 73 ): boolean { 74 if ( 75 review !== 'reviewed_conversation_option' || 76 (action !== 'block' && action !== 'report') 77 ) 78 return false; 79 const actual = conversationOptionsSnapshot(view, id); 80 if (!actual) return false; 81 invoke(actual.peer); 82 return true; 83 } 84 85 // Neither a copied row nor a body pointer is authority. Resolve the selector 86 // against the current original private room before allocating an anonymous view. 87 export function captureCitedProduct( 88 inbox: InboxView, 89 id: string, 90 rumor: string, 91 value: unknown, 92 runtime: PublicRuntime, 93 review: unknown 94 ): CitedProduct | undefined { 95 if (typeof window === 'undefined' || review !== 'reviewed_product_citation') 96 return undefined; 97 const original = inboxReplyOwnership(inbox, id, rumor), 98 message = inboxMessageSnapshot(inbox, id, rumor), 99 decoded = decodeProductReference(value); 100 if ( 101 !original?.current() || 102 !message || 103 !decoded || 104 !message.citations.some((row) => row.naddr === decoded.naddr) || 105 ![original.owner, original.peer].includes(decoded.pubkey) 106 ) 107 return undefined; 108 const reference = decoded; 109 const privateIds = inboxThreadSnapshot(inbox, id).messages.flatMap((row) => [ 110 row.data.rumorId, 111 ...(row.data.replyTo ? [row.data.replyTo] : []) 112 ]); 113 if (privateIds.includes(reference.identifier)) return undefined; 114 let versions = Array.from<string>([]); 115 for (const match of message.data.content.matchAll( 116 /\b(nevent1[023456789acdefghjklmnpqrstuvwxyz]+)\b/gi 117 )) { 118 const version = includedProductVersion(match[1], reference.pubkey); 119 if (version && !privateIds.includes(version) && !versions.includes(version)) 120 versions = versions.concat(version); 121 } 122 const exactId = versions.length === 1 ? versions[0] : undefined; 123 let view: PublicView; 124 try { 125 view = createPublicView(runtime); 126 } catch { 127 return undefined; 128 } 129 const run = beginPublicViewRun(view), 130 resolver = createPublicViewHeadResolver(view, run, { 131 nowSeconds: () => Math.floor(Date.now() / 1000) 132 }); 133 let closed = false, 134 failed = false, 135 head: PublicHead | undefined, 136 exact: string | undefined; 137 let privateScope: InboxReplyOwnership | undefined = original; 138 const requests = new Map<PublicRequest, true>(); 139 let offPrivate = () => {}, 140 offInbox = () => {}, 141 offIdentity = () => {}; 142 function close() { 143 if (closed) return; 144 closed = true; 145 privateScope = undefined; 146 offPrivate(); 147 offInbox(); 148 offIdentity(); 149 try { 150 closeHeadResolver(resolver); 151 } finally { 152 disposePublicView(view); 153 } 154 } 155 const owned = () => 156 !closed && 157 !!privateScope?.current() && 158 !!inboxMessageSnapshot(inbox, id, rumor) && 159 publicViewProjectionAvailable(view) && 160 publicViewOwnsRun(view, run); 161 const current = () => owned() && publicViewRunCurrent(view, run); 162 const token = Object.freeze({}) as CitedProduct; 163 owners.set(token, { 164 close, 165 snapshot() { 166 if (!owned()) { 167 close(); 168 return undefined; 169 } 170 const row = headResolutionSnapshot(resolver)[0], 171 scopes = Array.from(requests.keys(), publicRequestScopeSnapshot); 172 const pending = 173 current() && 174 [ 175 ...scopes, 176 ...(row?.headSources ? [row.headSources] : []), 177 ...(row?.deletionSources ? [row.deletionSources] : []) 178 ].some((scope) => scope.state === 'active'); 179 const suppressed = row?.deletion.outcome === 'suppressed'; 180 // A retained signed head is not a completed coordinate/withdrawal read. 181 // Original source coverage must remain honest after ordinary run expiry. 182 const complete = 183 row?.coverage === 'bounded-eose' && 184 !row.lastKnown && 185 scopes.length > 0 && 186 scopes.every( 187 (scope) => 188 scope.state === 'eose' && scope.result.coverage === 'bounded-eose' 189 ); 190 const food = 191 !suppressed && !pending && !failed && complete 192 ? row?.state.food 193 : undefined; 194 return { 195 outcome: suppressed 196 ? 'withdrawn' 197 : pending 198 ? 'checking' 199 : food 200 ? food.status 201 : 'unresolved', 202 food, 203 lastKnownFood: 204 !suppressed && !pending && !food ? row?.state.food : undefined, 205 includedVersion: !exactId 206 ? 'none' 207 : !exact || !food 208 ? 'unverified' 209 : exact === row?.state.head.id 210 ? 'matched' 211 : 'different' 212 }; 213 } 214 }); 215 offPrivate = subscribePrivateSessionClose(original.session, close); 216 offIdentity = subscribeIdentityInvalidation(original.identity, close); 217 offInbox = subscribeInboxView(inbox, () => { 218 if (!owned()) close(); 219 }); 220 function admit( 221 proof: Parameters<typeof createPublicHeadCandidate>[0], 222 exactOnly: boolean 223 ) { 224 if (!current()) return; 225 const candidate = createPublicHeadCandidate(proof); 226 if (!candidate) return; 227 const data = publicHeadSnapshot(candidate); 228 if ( 229 data.kind !== 30402 || 230 data.pubkey !== reference.pubkey || 231 data.identifier !== reference.identifier 232 ) 233 return; 234 if (exactOnly) { 235 if (data.id === exactId) exact = data.id; 236 return; 237 } 238 head = selectPublicHead(head, candidate).head; 239 try { 240 resolveHeads(resolver, [head]); 241 } catch { 242 failed = true; 243 } 244 } 245 try { 246 const request = subscribePublicView( 247 view, 248 run, 249 'head', 250 [ 251 { 252 kinds: [30402], 253 authors: [reference.pubkey], 254 '#d': [reference.identifier], 255 limit: PUBLIC_QUERY_BUDGETS.requestedPerRelay 256 } 257 ], 258 (proof) => admit(proof, false) 259 ); 260 requests.set(request, true); 261 if (exactId && current()) 262 requests.set( 263 subscribePublicView( 264 view, 265 run, 266 'head', 267 [ 268 { 269 kinds: [30402], 270 authors: [reference.pubkey], 271 ids: [exactId], 272 limit: PUBLIC_QUERY_BUDGETS.requestedPerRelay 273 } 274 ], 275 (proof) => admit(proof, true) 276 ), 277 true 278 ); 279 } catch { 280 failed = true; 281 } 282 return token; 283 } 284 export function citedProductSnapshot( 285 token: CitedProduct 286 ): Snapshot | undefined { 287 return owners.get(token)?.snapshot(); 288 } 289 export function closeCitedProduct(token: CitedProduct): void { 290 owners.get(token)?.close(); 291 }