-
Notifications
You must be signed in to change notification settings - Fork 22
/
events.js
341 lines (310 loc) · 9.21 KB
/
events.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import { Storefront, Aggregator } from '@web3-storage/filecoin-client'
import * as AggregatorCaps from '@web3-storage/capabilities/filecoin/aggregator'
import { Assert } from '@web3-storage/content-claims/capability'
import { computePieceCid } from './piece.js'
// eslint-disable-next-line no-unused-vars
import * as API from '../types.js'
import {
RecordNotFoundErrorName,
BlobNotFound,
StoreOperationFailed,
UnexpectedPiece,
UnexpectedState,
} from '../errors.js'
/**
* @typedef {import('./api.js').PieceRecord} PieceRecord
* @typedef {import('./api.js').PieceRecordKey} PieceRecordKey
* @typedef {import('./api.js').PieceStore} PieceStore
*/
/** Max items per page of query. */
const MAX_PAGE_SIZE = 20
/**
* On filecoin submit queue messages, validate piece for given content and store it in store.
*
* @param {import('./api.js').FilecoinSubmitMessageContext} context
* @param {import('./api.js').FilecoinSubmitMessage} message
*/
export const handleFilecoinSubmitMessage = async (context, message) => {
// dedupe concurrent writes
const hasRes = await context.pieceStore.has({ piece: message.piece })
if (hasRes.error) {
return { error: new StoreOperationFailed(hasRes.error.message) }
}
if (hasRes.ok) {
return {
ok: {},
}
}
// read and compute piece for content
// TODO: needs to be hooked with location claims
const contentStreamRes = await context.contentStore.stream(message.content)
if (contentStreamRes.error) {
return { error: new BlobNotFound(contentStreamRes.error.message) }
}
const computedPieceCid = await computePieceCid(contentStreamRes.ok)
if (computedPieceCid.error) {
return computedPieceCid
}
// check provided piece equals the one computed
if (!message.piece.equals(computedPieceCid.ok.piece.link)) {
return {
error: new UnexpectedPiece(
`provided piece ${message.piece.toString()} is not the same as computed ${
computedPieceCid.ok.piece
}`
),
}
}
const putRes = await context.pieceStore.put({
piece: message.piece,
content: message.content,
group: message.group,
status: 'submitted',
insertedAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
})
if (putRes.error) {
return { error: new StoreOperationFailed(putRes.error.message) }
}
return { ok: {} }
}
/**
* On piece offer queue message, offer piece for aggregation.
*
* @param {import('./api.js').PieceOfferMessageContext} context
* @param {import('./api.js').PieceOfferMessage} message
*/
export const handlePieceOfferMessage = async (context, message) => {
const pieceOfferInv = await Aggregator.pieceOffer(
context.aggregatorService.invocationConfig,
message.piece,
message.group,
{ connection: context.aggregatorService.connection }
)
if (pieceOfferInv.out.error) {
return {
error: pieceOfferInv.out.error,
}
}
return { ok: {} }
}
/**
* On piece inserted into store, invoke submit to queue piece to be offered for aggregate.
*
* @param {import('./api.js').StorefrontClientContext} context
* @param {PieceRecord} record
*/
export const handlePieceInsert = async (context, record) => {
const filecoinSubmitInv = await Storefront.filecoinSubmit(
context.storefrontService.invocationConfig,
record.content,
record.piece,
{ connection: context.storefrontService.connection }
)
if (filecoinSubmitInv.out.error) {
return {
error: filecoinSubmitInv.out.error,
}
}
return { ok: {} }
}
/**
* On piece inserted into store, invoke equivalency claim to enable reads.
*
* @param {import('./api.js').ClaimsClientContext} context
* @param {PieceRecord} record
*/
export const handlePieceInsertToEquivalencyClaim = async (context, record) => {
const claimResult = await Assert.equals
.invoke({
issuer: context.claimsService.invocationConfig.issuer,
audience: context.claimsService.invocationConfig.audience,
with: context.claimsService.invocationConfig.with,
nb: {
content: record.content,
equals: record.piece,
},
expiration: Infinity,
proofs: context.claimsService.invocationConfig.proofs,
})
.execute(context.claimsService.connection)
if (claimResult.out.error) {
return {
error: claimResult.out.error,
}
}
return {
ok: {},
}
}
/**
* @param {import('./api.js').StorefrontClientContext} context
* @param {PieceRecord} record
*/
export const handlePieceStatusUpdate = async (context, record) => {
// Validate expected status
if (record.status === 'submitted') {
return {
error: new UnexpectedState(
`record status for ${record.piece} is "${record.status}"`
),
}
}
const filecoinAcceptInv = await Storefront.filecoinAccept(
context.storefrontService.invocationConfig,
record.content,
record.piece,
{ connection: context.storefrontService.connection }
)
if (filecoinAcceptInv.out.error) {
return {
error: filecoinAcceptInv.out.error,
}
}
return { ok: {} }
}
/**
* @param {import('./api.js').CronContext} context
*/
export const handleCronTick = async (context) => {
let totalPiecesCount = 0
let updatedPiecesCount = 0
/** @type {string|undefined} */
let cursor
do {
const submittedPieces = await context.pieceStore.query(
{
status: 'submitted',
},
{ cursor, size: MAX_PAGE_SIZE }
)
if (submittedPieces.error) {
return {
error: submittedPieces.error,
}
}
totalPiecesCount += submittedPieces.ok.results.length
// Update approved pieces from the ones resolved
const updatedResponses = await Promise.all(
submittedPieces.ok.results.map((pieceRecord) =>
updatePiecesWithDeal({
id: context.id,
aggregatorId: context.aggregatorId,
pieceRecord,
pieceStore: context.pieceStore,
taskStore: context.taskStore,
receiptStore: context.receiptStore,
})
)
)
// Fail if one or more update operations did not succeed.
// The successful ones are still valid, but we should keep track of errors for monitoring/alerting.
const updateErrorResponse = updatedResponses.find((r) => r.error)
if (updateErrorResponse) {
return {
error: updateErrorResponse.error,
}
}
updatedPiecesCount += updatedResponses.filter((r) => r.ok?.updated).length
cursor = submittedPieces.ok.cursor
} while (cursor)
// Return successful update operation
// Include in response the ones that were Updated, and the ones still pending response.
return {
ok: {
updatedCount: updatedPiecesCount,
pendingCount: totalPiecesCount - updatedPiecesCount,
},
}
}
/**
* Read receipt chain to determine if an aggregate was accepted for the piece.
* Update its status if there is an accepted aggregate.
*
* @param {object} context
* @param {import('@ucanto/interface').Signer} context.id
* @param {import('@ucanto/interface').Principal} context.aggregatorId
* @param {PieceRecord} context.pieceRecord
* @param {PieceStore} context.pieceStore
* @param {API.Store<import('@ucanto/interface').UnknownLink, API.UcantoInterface.Invocation>} context.taskStore
* @param {API.Store<import('@ucanto/interface').UnknownLink, API.UcantoInterface.Receipt>} context.receiptStore
*/
async function updatePiecesWithDeal({
id,
aggregatorId,
pieceRecord,
pieceStore,
taskStore,
receiptStore,
}) {
let aggregateAcceptReceipt
let task = /** @type {API.UcantoInterface.Link} */ (
(
await AggregatorCaps.pieceOffer
.invoke({
issuer: id,
audience: aggregatorId,
with: id.did(),
nb: {
piece: pieceRecord.piece,
group: pieceRecord.group,
},
expiration: Infinity,
})
.delegate()
).cid
)
// eslint-disable-next-line no-constant-condition
while (true) {
const [taskRes, receiptRes] = await Promise.all([
taskStore.get(task),
receiptStore.get(task),
])
// Should fail if errored and not with StoreNotFound Error
if (
(taskRes.error && taskRes.error.name !== RecordNotFoundErrorName) ||
(receiptRes.error && receiptRes.error.name !== RecordNotFoundErrorName)
) {
return {
error: taskRes.error || receiptRes.error,
}
}
// Might not be available still, as piece is in progress to get into a deal
if (taskRes.error || receiptRes.error) {
// Store not found
break
}
// Save very last receipt - aggregate/accept
const ability = taskRes.ok.capabilities[0]?.can
if (ability === 'aggregate/accept') {
aggregateAcceptReceipt = receiptRes.ok
}
if (!receiptRes.ok.fx.join) break
task = receiptRes.ok.fx.join.link()
}
// If there is a receipt, status can be updated
if (aggregateAcceptReceipt) {
const updateRes = await pieceStore.update(
{
piece: pieceRecord.piece,
},
{
// eslint-disable-next-line no-extra-boolean-cast
status: !!aggregateAcceptReceipt.out.ok ? 'accepted' : 'invalid',
updatedAt: new Date().toISOString(),
}
)
if (updateRes.ok) {
return {
ok: {
updated: true,
},
}
}
}
return {
ok: {
updated: false,
},
}
}