envio 3.5.1 → 3.6.1-subgraph

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/evm.schema.json +7 -0
  2. package/fuel.schema.json +7 -0
  3. package/index.d.ts +33 -10
  4. package/package.json +6 -6
  5. package/src/ChainState.res +22 -4
  6. package/src/ChainState.res.mjs +20 -3
  7. package/src/ChainState.resi +3 -0
  8. package/src/Config.res +72 -2
  9. package/src/Config.res.mjs +57 -15
  10. package/src/Core.res +15 -0
  11. package/src/Core.res.mjs +11 -0
  12. package/src/EffectState.res +2 -2
  13. package/src/EffectState.res.mjs +2 -2
  14. package/src/EntityTables.res +32 -0
  15. package/src/EntityTables.res.mjs +44 -0
  16. package/src/Envio.res +7 -7
  17. package/src/Envio.res.mjs +5 -6
  18. package/src/EventProcessing.res +6 -6
  19. package/src/EventProcessing.res.mjs +8 -6
  20. package/src/HandlerLoader.res +20 -8
  21. package/src/HandlerLoader.res.mjs +11 -2
  22. package/src/Hasura.res +37 -3
  23. package/src/Hasura.res.mjs +23 -5
  24. package/src/InMemoryStore.res +48 -8
  25. package/src/InMemoryStore.res.mjs +37 -7
  26. package/src/IndexerState.res +30 -24
  27. package/src/IndexerState.res.mjs +20 -35
  28. package/src/IndexerState.resi +8 -6
  29. package/src/Internal.res +29 -11
  30. package/src/Internal.res.mjs +27 -10
  31. package/src/LoadLayer.res +39 -8
  32. package/src/LoadLayer.res.mjs +36 -9
  33. package/src/LoadLayer.resi +2 -0
  34. package/src/Metrics.res +5 -5
  35. package/src/Metrics.res.mjs +5 -1
  36. package/src/Persistence.res +12 -1
  37. package/src/PgStorage.res +183 -37
  38. package/src/PgStorage.res.mjs +149 -34
  39. package/src/PruneStaleHistory.res +1 -0
  40. package/src/PruneStaleHistory.res.mjs +2 -1
  41. package/src/Sink.res +3 -3
  42. package/src/Sink.res.mjs +2 -2
  43. package/src/TestIndexer.res +128 -17
  44. package/src/TestIndexer.res.mjs +75 -9
  45. package/src/UserContext.res +375 -53
  46. package/src/UserContext.res.mjs +281 -39
  47. package/src/Writing.res +8 -16
  48. package/src/Writing.res.mjs +10 -10
  49. package/src/bindings/ClickHouse.res +40 -4
  50. package/src/bindings/ClickHouse.res.mjs +37 -5
  51. package/src/db/EntityHistory.res +64 -21
  52. package/src/db/EntityHistory.res.mjs +43 -22
  53. package/src/db/InternalTable.res.mjs +31 -31
  54. package/src/db/Table.res +24 -1
  55. package/src/db/Table.res.mjs +26 -4
  56. package/src/sources/SourceManager.res +6 -12
  57. package/src/sources/SourceManager.res.mjs +8 -5
  58. package/src/subgraph/blocks.ts +176 -0
  59. package/src/subgraph/calls.ts +213 -0
  60. package/src/subgraph/conformance.ts +99 -0
  61. package/src/subgraph/division.ts +100 -0
  62. package/src/subgraph/errors.ts +90 -0
  63. package/src/subgraph/graph-ts-types/VERSION +2 -0
  64. package/src/subgraph/graph-ts-types/chain/arweave.d.ts +70 -0
  65. package/src/subgraph/graph-ts-types/chain/cosmos.d.ts +327 -0
  66. package/src/subgraph/graph-ts-types/chain/ethereum.d.ts +233 -0
  67. package/src/subgraph/graph-ts-types/chain/near.d.ts +253 -0
  68. package/src/subgraph/graph-ts-types/chain/starknet.d.ts +32 -0
  69. package/src/subgraph/graph-ts-types/common/collections.d.ts +136 -0
  70. package/src/subgraph/graph-ts-types/common/conversion.d.ts +11 -0
  71. package/src/subgraph/graph-ts-types/common/datasource.d.ts +30 -0
  72. package/src/subgraph/graph-ts-types/common/eager-offset.d.ts +0 -0
  73. package/src/subgraph/graph-ts-types/common/json.d.ts +17 -0
  74. package/src/subgraph/graph-ts-types/common/numbers.d.ts +120 -0
  75. package/src/subgraph/graph-ts-types/common/value.d.ts +120 -0
  76. package/src/subgraph/graph-ts-types/common/yaml.d.ts +90 -0
  77. package/src/subgraph/graph-ts-types/global/global.d.ts +194 -0
  78. package/src/subgraph/graph-ts-types/helper-functions.d.ts +22 -0
  79. package/src/subgraph/graph-ts-types/index.d.ts +102 -0
  80. package/src/subgraph/graph-ts.ts +1695 -0
  81. package/src/subgraph/hosts.ts +148 -0
  82. package/src/subgraph/runtime.ts +827 -0
  83. package/src/subgraph/scope.ts +63 -0
  84. package/svm.schema.json +7 -0
@@ -1,3 +1,37 @@
1
+ // Thrown by a sync op that can't be served from memory. Owned by envio so the
2
+ // subgraph runtime's replay loop can tell it apart from a real handler error.
3
+ // User code never swallows it: AssemblyScript has no try/catch, and the traps
4
+ // keep re-throwing it while the context stays aborted.
5
+ exception Suspend
6
+
7
+ let isSuspend = exn =>
8
+ switch exn {
9
+ | Suspend => true
10
+ | _ => false
11
+ }
12
+
13
+ type contextStatus =
14
+ | Active
15
+ // Set by a suspended sync op. Every trap access and every op closure
16
+ // re-throws the stored error, so even a caught suspend stops the handler
17
+ // at its next context interaction.
18
+ | Aborted(exn)
19
+ | Resolved
20
+
21
+ // Held by reference so the entity sub-proxies, which copy the rest of the
22
+ // params by value, observe the same lifecycle as the handler context.
23
+ type syncState = {
24
+ mutable status: contextStatus,
25
+ // Ops scheduled by this round's suspended reads, awaited before the replay.
26
+ mutable pending: option<array<promise<unit>>>,
27
+ // Effect outputs already resolved for this handler invocation. Replay rounds
28
+ // and the preload -> execute transition reuse them even when the in-memory
29
+ // effect table drops the entry (`cache: false`).
30
+ mutable memo: option<dict<Internal.effectOutput>>,
31
+ }
32
+
33
+ let makeSyncState = () => {status: Active, pending: None, memo: None}
34
+
1
35
  type contextParams = {
2
36
  item: Internal.item,
3
37
  checkpointId: Internal.checkpointId,
@@ -7,7 +41,45 @@ type contextParams = {
7
41
  isPreload: bool,
8
42
  chains: Internal.chains,
9
43
  config: Config.t,
10
- mutable isResolved: bool,
44
+ sync: syncState,
45
+ }
46
+
47
+ let getPending = (sync: syncState) =>
48
+ switch sync.pending {
49
+ | Some(pending) => pending
50
+ | None =>
51
+ let pending = []
52
+ sync.pending = Some(pending)
53
+ pending
54
+ }
55
+
56
+ let getMemo = (sync: syncState) =>
57
+ switch sync.memo {
58
+ | Some(memo) => memo
59
+ | None =>
60
+ let memo = Dict.make()
61
+ sync.memo = Some(memo)
62
+ memo
63
+ }
64
+
65
+ let checkStatusOrThrow = (params: contextParams, ~access: string) =>
66
+ switch params.sync.status {
67
+ | Active => ()
68
+ | Aborted(exn) => throw(exn)
69
+ | Resolved =>
70
+ Utils.Error.make(
71
+ `Impossible to access ${access} after the handler is resolved. Make sure you didn't miss an await in the handler.`,
72
+ )->ErrorHandling.mkLogAndRaise(
73
+ ~logger=Ecosystem.getItemLogger(params.item, ~ecosystem=params.config.ecosystem),
74
+ )
75
+ }
76
+
77
+ // Fires the async op behind a sync miss, records it for the replay loop and
78
+ // aborts the context.
79
+ let scheduleAndSuspend = (params: contextParams, promise: promise<'a>): 'b => {
80
+ params.sync->getPending->Array.push(promise->Utils.Promise.ignoreValue)
81
+ params.sync.status = Aborted(Suspend)
82
+ throw(Suspend)
11
83
  }
12
84
 
13
85
  // We don't want to expose the params to the user
@@ -58,55 +130,117 @@ external makeEffectContext: (
58
130
  ~callEffect: (Internal.effect, Internal.effectInput) => promise<Internal.effectOutput>,
59
131
  ) => Internal.effectContext = "EffectContext"
60
132
 
61
- let initEffect = (params: contextParams) => {
62
- let handlerChainId = params.item->Internal.getItemChainId
133
+ // Builds the scope and args a call to `effect` resolves against. Split out of
134
+ // `initEffect` so the sync caller derives the same cache key and scope without
135
+ // duplicating the nested-caller rules.
136
+ let rec prepareEffectCall = (
137
+ params: contextParams,
138
+ ~effect: Internal.effect,
139
+ ~input: Internal.effectInput,
140
+ ~caller: option<Internal.effect>,
141
+ ) => {
142
+ // An effect that didn't state a scope follows the config: cross-chain by
143
+ // default, per-chain under `disable_default_cross_chain`.
144
+ let isCrossChain = (effect: Internal.effect) =>
145
+ effect.crossChain->Option.getOr(params.config.defaultCrossChain)
63
146
  // A chain-scoped effect always resolves against the chain of the handler that
64
147
  // triggered the call, even several effects deep, so the chain id is captured
65
148
  // once from the item and reused for the whole nested-call tree.
66
- let rec makeCaller = (~caller: option<Internal.effect>) => {
67
- (effect: Internal.effect, input: Internal.effectInput) => {
68
- let scope = effect.crossChain ? Internal.CrossChain : Internal.Chain(handlerChainId)
69
-
70
- switch caller {
71
- | Some(callerEffect) if callerEffect.crossChain && !effect.crossChain =>
72
- // A cross-chain effect isn't tied to a single chain, so it has no chain
73
- // to resolve a chain-scoped child against. Reject before any cache work.
74
- JsError.throwWithMessage(
75
- `The cross-chain effect "${callerEffect.name}" cannot call the chain-scoped effect "${effect.name}", because a cross-chain effect isn't tied to a single chain. Make "${effect.name}" cross-chain (\`crossChain: true\`), or make "${callerEffect.name}" chain-scoped (\`crossChain: false\`).`,
76
- )
77
- | _ => ()
78
- }
149
+ let scope = effect->isCrossChain
150
+ ? Internal.CrossChain
151
+ : Internal.Chain(params.item->Internal.getItemChainId)
79
152
 
80
- let effectContext = makeEffectContext(
81
- params,
82
- ~chainId=switch scope {
83
- | Internal.Chain(chainId) => Some(chainId)
84
- | Internal.CrossChain => None
85
- },
86
- ~effectName=effect.name,
87
- ~defaultShouldCache=effect.defaultShouldCache,
88
- ~callEffect=makeCaller(~caller=Some(effect)),
89
- )
90
- let effectArgs: Internal.effectArgs = {
91
- input,
92
- context: effectContext,
93
- cacheKey: input->S.reverseConvertOrThrow(effect.input)->Utils.Hash.makeOrThrow,
94
- checkpointId: params.checkpointId,
153
+ switch caller {
154
+ | Some(callerEffect) if callerEffect->isCrossChain && !(effect->isCrossChain) =>
155
+ // A cross-chain effect isn't tied to a single chain, so it has no chain
156
+ // to resolve a chain-scoped child against. Reject before any cache work.
157
+ JsError.throwWithMessage(
158
+ `The cross-chain effect "${callerEffect.name}" cannot call the chain-scoped effect "${effect.name}", because a cross-chain effect isn't tied to a single chain. Make "${effect.name}" cross-chain (\`crossChain: true\`), or make "${callerEffect.name}" chain-scoped (\`crossChain: false\`).`,
159
+ )
160
+ | _ => ()
161
+ }
162
+
163
+ let effectContext = makeEffectContext(
164
+ params,
165
+ ~chainId=switch scope {
166
+ | Internal.Chain(chainId) => Some(chainId)
167
+ | Internal.CrossChain => None
168
+ },
169
+ ~effectName=effect.name,
170
+ ~defaultShouldCache=effect.defaultShouldCache,
171
+ // Nested calls made by the effect handler itself stay async: only the
172
+ // handler that started the sync run needs a sync answer.
173
+ ~callEffect=(nested, nestedInput) =>
174
+ params->callEffectAsync(~effect=nested, ~input=nestedInput, ~caller=Some(effect)),
175
+ )
176
+ let effectArgs: Internal.effectArgs = {
177
+ input,
178
+ context: effectContext,
179
+ cacheKey: input->S.reverseConvertOrThrow(effect.input)->Utils.Hash.makeOrThrow,
180
+ checkpointId: params.checkpointId,
181
+ }
182
+ (scope, effectArgs)
183
+ }
184
+
185
+ and callEffectAsync = (params: contextParams, ~effect, ~input, ~caller) => {
186
+ let (scope, effectArgs) = params->prepareEffectCall(~effect, ~input, ~caller)
187
+ LoadLayer.loadEffect(
188
+ ~loadManager=params.loadManager,
189
+ ~persistence=params.persistence,
190
+ ~effect,
191
+ ~effectArgs,
192
+ ~scope,
193
+ ~indexerState=params.indexerState,
194
+ ~shouldGroup=params.isPreload,
195
+ ~item=params.item,
196
+ ~ecosystem=params.config.ecosystem,
197
+ )
198
+ }
199
+
200
+ let initEffect = (params: contextParams) => {
201
+ (effect: Internal.effect, input: Internal.effectInput) => {
202
+ params->checkStatusOrThrow(~access="context.effect")
203
+ params->callEffectAsync(~effect, ~input, ~caller=None)
204
+ }
205
+ }
206
+
207
+ let effectMemoKey = (~effect: Internal.effect, ~scope: Internal.chainScope, ~cacheKey) =>
208
+ switch scope {
209
+ | CrossChain => `${effect.name}.${cacheKey}`
210
+ | Chain(chainId) => `${effect.name}.${chainId->ChainId.toString}.${cacheKey}`
211
+ }
212
+
213
+ let initEffectSync = (params: contextParams) => {
214
+ (effect: Internal.effect, input: Internal.effectInput) => {
215
+ params->checkStatusOrThrow(~access="context.effectSync")
216
+ let (scope, effectArgs) = params->prepareEffectCall(~effect, ~input, ~caller=None)
217
+ let memo = params.sync->getMemo
218
+ let memoKey = effectMemoKey(~effect, ~scope, ~cacheKey=effectArgs.cacheKey)
219
+ switch memo->Utils.Dict.dangerouslyGetNonOption(memoKey) {
220
+ | Some(output) => output
221
+ | None =>
222
+ let inMemTable = params.indexerState->InMemoryStore.getEffectInMemTable(~effect, ~scope)
223
+ if inMemTable->InMemoryStore.hasEffectOutput(effectArgs.cacheKey) {
224
+ let output = inMemTable->InMemoryStore.getEffectOutputUnsafe(effectArgs.cacheKey)
225
+ memo->Dict.set(memoKey, output)
226
+ output
227
+ } else {
228
+ params->scheduleAndSuspend(
229
+ LoadLayer.loadEffect(
230
+ ~loadManager=params.loadManager,
231
+ ~persistence=params.persistence,
232
+ ~effect,
233
+ ~effectArgs,
234
+ ~scope,
235
+ ~indexerState=params.indexerState,
236
+ ~shouldGroup=params.isPreload,
237
+ ~item=params.item,
238
+ ~ecosystem=params.config.ecosystem,
239
+ ),
240
+ )
95
241
  }
96
- LoadLayer.loadEffect(
97
- ~loadManager=params.loadManager,
98
- ~persistence=params.persistence,
99
- ~effect,
100
- ~effectArgs,
101
- ~scope,
102
- ~indexerState=params.indexerState,
103
- ~shouldGroup=params.isPreload,
104
- ~item=params.item,
105
- ~ecosystem=params.config.ecosystem,
106
- )
107
242
  }
108
243
  }
109
- makeCaller(~caller=None)
110
244
  }
111
245
 
112
246
  type entityContextParams = {
@@ -114,6 +248,13 @@ type entityContextParams = {
114
248
  entityConfig: Internal.entityConfig,
115
249
  }
116
250
 
251
+ // The handler context is always chain-scoped, so a per-chain entity resolves to
252
+ // the chain the handler runs on and a cross-chain one to the shared partition.
253
+ let entityScope = (params: entityContextParams) =>
254
+ params.entityConfig->InMemoryStore.entityScope(
255
+ ~chainId=params.item->Internal.getItemChainId,
256
+ )
257
+
117
258
  let getWhereHandler = (params: entityContextParams, filter: dict<dict<unknown>>) => {
118
259
  let entityConfig = params.entityConfig
119
260
 
@@ -123,6 +264,7 @@ let getWhereHandler = (params: entityContextParams, filter: dict<dict<unknown>>)
123
264
  ~loadManager=params.loadManager,
124
265
  ~persistence=params.persistence,
125
266
  ~entityConfig,
267
+ ~scope=params->entityScope,
126
268
  ~indexerState=params.indexerState,
127
269
  ~shouldGroup=params.isPreload,
128
270
  ~item=params.item,
@@ -154,17 +296,113 @@ let throwClickHouseReadOnly = (entityConfig: Internal.entityConfig, op: string)
154
296
  `context.${entityConfig.name}.${op}() is unavailable: ClickHouse storage is currently write-only. Follow Envio releases to be notified when ClickHouse supports both reads and writes from handlers.`,
155
297
  )
156
298
 
299
+ // A sync read against the in-memory entity table: a hit is returned as-is
300
+ // (including a recorded absence), a miss schedules the async load and suspends.
301
+ let getSyncHandler = (params: entityContextParams, entityId: string) => {
302
+ let inMemTable =
303
+ params.indexerState->InMemoryStore.getInMemTable(
304
+ ~entityConfig=params.entityConfig,
305
+ ~scope=params->entityScope,
306
+ )
307
+ if inMemTable.latestEntityChangeById->Dict.has(entityId) {
308
+ (inMemTable->InMemoryTable.Entity.getUnsafe)(entityId)
309
+ } else {
310
+ (params :> contextParams)->scheduleAndSuspend(
311
+ LoadLayer.loadById(
312
+ ~loadManager=params.loadManager,
313
+ ~persistence=params.persistence,
314
+ ~entityConfig=params.entityConfig,
315
+ ~scope=params->entityScope,
316
+ ~indexerState=params.indexerState,
317
+ ~shouldGroup=params.isPreload,
318
+ ~item=params.item,
319
+ ~ecosystem=params.config.ecosystem,
320
+ ~entityId,
321
+ ),
322
+ )
323
+ }
324
+ }
325
+
326
+ let getWhereSyncHandler = (params: entityContextParams, filter: dict<dict<unknown>>) => {
327
+ let entityConfig = params.entityConfig
328
+ let inMemTable =
329
+ params.indexerState->InMemoryStore.getInMemTable(~entityConfig, ~scope=params->entityScope)
330
+ let hasIndex = inMemTable->InMemoryTable.Entity.hasIndex
331
+ let getOnIndex = inMemTable->InMemoryTable.Entity.getUnsafeOnIndex
332
+
333
+ let filters =
334
+ filter->EntityFilter.parseGetWhereOrThrow(
335
+ ~entityName=entityConfig.name,
336
+ ~table=entityConfig.table,
337
+ )
338
+
339
+ let missing = []
340
+ let entities = []
341
+ filters->Array.forEach(filter => {
342
+ let filterKey = filter->EntityFilter.toString
343
+ if hasIndex(filterKey) {
344
+ entities->Array.pushMany(getOnIndex(filterKey))
345
+ } else {
346
+ missing->Array.push(
347
+ LoadLayer.loadByFilter(
348
+ ~loadManager=params.loadManager,
349
+ ~persistence=params.persistence,
350
+ ~entityConfig,
351
+ ~scope=params->entityScope,
352
+ ~indexerState=params.indexerState,
353
+ ~shouldGroup=params.isPreload,
354
+ ~item=params.item,
355
+ ~ecosystem=params.config.ecosystem,
356
+ ~filter,
357
+ )->Utils.Promise.ignoreValue,
358
+ )
359
+ }
360
+ })
361
+
362
+ if missing->Utils.Array.notEmpty {
363
+ let pending = params.sync->getPending
364
+ missing->Array.forEach(promise => pending->Array.push(promise))
365
+ params.sync.status = Aborted(Suspend)
366
+ throw(Suspend)
367
+ }
368
+ entities
369
+ }
370
+
371
+ // Never suspends: the in-memory table spans the whole batch, so a change only
372
+ // counts as "in this block" when it was written at this handler's checkpoint.
373
+ let getInBlockSyncHandler = (params: entityContextParams, entityId: string) => {
374
+ let inMemTable =
375
+ params.indexerState->InMemoryStore.getInMemTable(
376
+ ~entityConfig=params.entityConfig,
377
+ ~scope=params->entityScope,
378
+ )
379
+ switch inMemTable.latestEntityChangeById->Utils.Dict.dangerouslyGetNonOption(entityId) {
380
+ | Some(change) if change->Change.getCheckpointId == params.checkpointId =>
381
+ change->InMemoryTable.Entity.mapChangeToEntity
382
+ | _ => None
383
+ }
384
+ }
385
+
157
386
  let entityTraps: Utils.Proxy.traps<entityContextParams> = {
158
387
  get: (~target as params, ~prop: unknown) => {
159
388
  let prop = prop->(Utils.magic: unknown => string)
160
389
 
390
+ (params :> contextParams)->checkStatusOrThrow(
391
+ ~access=`context.${params.entityConfig.name}.${prop}`,
392
+ )
393
+
161
394
  let isClickHouseOnly = !params.entityConfig.storage.postgres
162
395
 
163
396
  let set = params.isPreload
164
397
  ? noopSet
165
398
  : (entity: Internal.entity) => {
399
+ // The check lives inside the closure too: a handler that grabbed
400
+ // `context.X.set` before a suspend must not keep writing.
401
+ (params :> contextParams)->checkStatusOrThrow(
402
+ ~access=`context.${params.entityConfig.name}.set`,
403
+ )
166
404
  params.indexerState
167
- ->InMemoryStore.getInMemTable(~entityConfig=params.entityConfig)
405
+ ->InMemoryStore.getInMemTable(~entityConfig=params.entityConfig, ~scope=params->entityScope)
168
406
  ->InMemoryTable.Entity.set(
169
407
  ~committedCheckpointId=params.indexerState->IndexerState.committedCheckpointId,
170
408
  Set({
@@ -176,6 +414,18 @@ let entityTraps: Utils.Proxy.traps<entityContextParams> = {
176
414
  }
177
415
 
178
416
  switch prop {
417
+ | "getSync" =>
418
+ (entityId => params->getSyncHandler(entityId))->(
419
+ Utils.magic: (string => option<Internal.entity>) => unknown
420
+ )
421
+ | "getWhereSync" =>
422
+ (
423
+ filter => params->getWhereSyncHandler(filter->(Utils.magic: unknown => dict<dict<unknown>>))
424
+ )->(Utils.magic: (unknown => array<Internal.entity>) => unknown)
425
+ | "getInBlockSync" =>
426
+ (entityId => params->getInBlockSyncHandler(entityId))->(
427
+ Utils.magic: (string => option<Internal.entity>) => unknown
428
+ )
179
429
  | "get" =>
180
430
  if isClickHouseOnly {
181
431
  ((_entityId: string) => throwClickHouseReadOnly(params.entityConfig, "get"))->(
@@ -188,6 +438,7 @@ let entityTraps: Utils.Proxy.traps<entityContextParams> = {
188
438
  ~loadManager=params.loadManager,
189
439
  ~persistence=params.persistence,
190
440
  ~entityConfig=params.entityConfig,
441
+ ~scope=params->entityScope,
191
442
  ~indexerState=params.indexerState,
192
443
  ~shouldGroup=params.isPreload,
193
444
  ~item=params.item,
@@ -220,6 +471,7 @@ let entityTraps: Utils.Proxy.traps<entityContextParams> = {
220
471
  ~loadManager=params.loadManager,
221
472
  ~persistence=params.persistence,
222
473
  ~entityConfig=params.entityConfig,
474
+ ~scope=params->entityScope,
223
475
  ~indexerState=params.indexerState,
224
476
  ~shouldGroup=params.isPreload,
225
477
  ~item=params.item,
@@ -250,6 +502,7 @@ let entityTraps: Utils.Proxy.traps<entityContextParams> = {
250
502
  ~loadManager=params.loadManager,
251
503
  ~persistence=params.persistence,
252
504
  ~entityConfig=params.entityConfig,
505
+ ~scope=params->entityScope,
253
506
  ~indexerState=params.indexerState,
254
507
  ~shouldGroup=params.isPreload,
255
508
  ~item=params.item,
@@ -272,8 +525,11 @@ let entityTraps: Utils.Proxy.traps<entityContextParams> = {
272
525
  noopDeleteUnsafe
273
526
  } else {
274
527
  entityId => {
528
+ (params :> contextParams)->checkStatusOrThrow(
529
+ ~access=`context.${params.entityConfig.name}.deleteUnsafe`,
530
+ )
275
531
  params.indexerState
276
- ->InMemoryStore.getInMemTable(~entityConfig=params.entityConfig)
532
+ ->InMemoryStore.getInMemTable(~entityConfig=params.entityConfig, ~scope=params->entityScope)
277
533
  ->InMemoryTable.Entity.set(
278
534
  ~committedCheckpointId=params.indexerState->IndexerState.committedCheckpointId,
279
535
  Delete({
@@ -289,17 +545,83 @@ let entityTraps: Utils.Proxy.traps<entityContextParams> = {
289
545
  },
290
546
  }
291
547
 
548
+ // Deterministic mappings always make progress, so the cap only exists to turn
549
+ // a non-deterministic one into a clear error instead of a hang.
550
+ let maxSyncRounds = 10000
551
+
552
+ // Runs a synchronous body, replaying it from the top each time it suspends on
553
+ // a read that wasn't in memory yet.
554
+ let rec runSyncRound = async (params: contextParams, fn: unit => unit, ~round) => {
555
+ if round > maxSyncRounds {
556
+ JsError.throwWithMessage(
557
+ `The handler suspended on a synchronous read too many times: gave up after ${maxSyncRounds->Int.toString} rounds. This usually means the code isn't deterministic across reruns.`,
558
+ )
559
+ }
560
+ params.sync.status = Active
561
+ params.sync.pending = None
562
+
563
+ let suspended = switch fn() {
564
+ | () => false
565
+ | exception exn =>
566
+ if exn->isSuspend {
567
+ true
568
+ } else {
569
+ // The body threw its own error after scheduling a read. Those ops are
570
+ // nobody's result now, and an unhandled rejection would replace the
571
+ // error the handler actually raised.
572
+ switch params.sync.pending {
573
+ | None => ()
574
+ | Some(pending) => {
575
+ params.sync.pending = None
576
+ pending->Array.forEach(promise => promise->Utils.Promise.silentCatch->ignore)
577
+ }
578
+ }
579
+ throw(exn)
580
+ }
581
+ }
582
+
583
+ switch params.sync.pending {
584
+ | None => ()
585
+ | Some(pending) =>
586
+ params.sync.pending = None
587
+ if suspended {
588
+ let errors = []
589
+ let _ =
590
+ await pending
591
+ ->Array.map(promise =>
592
+ promise->Promise.catch(exn => {
593
+ errors->Array.push(exn)
594
+ Promise.resolve()
595
+ })
596
+ )
597
+ ->Promise.all
598
+ switch errors->Array.get(0) {
599
+ | Some(exn) => throw(exn)
600
+ | None => ()
601
+ }
602
+ await params->runSyncRound(fn, ~round=round + 1)
603
+ } else {
604
+ // The body swallowed the suspend and returned anyway. The scheduled ops
605
+ // are nobody's result now, but they must not surface as unhandled
606
+ // rejections.
607
+ pending->Array.forEach(promise => promise->Utils.Promise.silentCatch->ignore)
608
+ }
609
+ }
610
+ }
611
+
292
612
  let handlerTraps: Utils.Proxy.traps<contextParams> = {
293
613
  get: (~target as params, ~prop: unknown) => {
294
614
  let prop = prop->(Utils.magic: unknown => string)
295
- if params.isResolved {
296
- Utils.Error.make(
297
- `Impossible to access context.${prop} after the handler is resolved. Make sure you didn't miss an await in the handler.`,
298
- )->ErrorHandling.mkLogAndRaise(
299
- ~logger=Ecosystem.getItemLogger(params.item, ~ecosystem=params.config.ecosystem),
300
- )
301
- }
615
+ params->checkStatusOrThrow(~access=`context.${prop}`)
302
616
  switch prop {
617
+ | "effectSync" =>
618
+ initEffectSync((params :> contextParams))->(
619
+ Utils.magic: ((Internal.effect, Internal.effectInput) => Internal.effectOutput) => unknown
620
+ )
621
+ | "runSync" =>
622
+ (fn => params->runSyncRound(fn, ~round=1))->(
623
+ Utils.magic: ((unit => unit) => promise<unit>) => unknown
624
+ )
303
625
  | "log" =>
304
626
  (
305
627
  params.isPreload
@@ -331,7 +653,7 @@ let handlerTraps: Utils.Proxy.traps<contextParams> = {
331
653
  persistence: params.persistence,
332
654
  checkpointId: params.checkpointId,
333
655
  chains: params.chains,
334
- isResolved: params.isResolved,
656
+ sync: params.sync,
335
657
  config: params.config,
336
658
  entityConfig,
337
659
  }