@rivetkit/effect 0.0.0-06-09-refactor-rivetkit-split-workflow-context-into-workflowcontext-workflowstepcontext.e0c9540 → 0.0.0-bisect-sync-sqlite-1.910d1c7

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 (74) hide show
  1. package/dist/Action.d.ts +1 -1
  2. package/dist/Action.js +1 -1
  3. package/dist/Actor.d.ts +28 -4
  4. package/dist/Actor.d.ts.map +1 -1
  5. package/dist/Actor.js +3 -2
  6. package/dist/Actor.js.map +1 -1
  7. package/dist/Client.d.ts.map +1 -1
  8. package/dist/Client.js +6 -4
  9. package/dist/Client.js.map +1 -1
  10. package/dist/Registry.d.ts +70 -8
  11. package/dist/Registry.d.ts.map +1 -1
  12. package/dist/Registry.js +93 -41
  13. package/dist/Registry.js.map +1 -1
  14. package/dist/RivetError.d.ts +61 -3
  15. package/dist/RivetError.d.ts.map +1 -1
  16. package/dist/RivetError.js +171 -25
  17. package/dist/RivetError.js.map +1 -1
  18. package/dist/RivetLogger.d.ts +41 -0
  19. package/dist/RivetLogger.d.ts.map +1 -0
  20. package/dist/RivetLogger.js +41 -0
  21. package/dist/RivetLogger.js.map +1 -0
  22. package/dist/State.d.ts +92 -56
  23. package/dist/State.d.ts.map +1 -1
  24. package/dist/State.js +51 -57
  25. package/dist/State.js.map +1 -1
  26. package/dist/internal/ActionDispatcher.d.ts +3 -3
  27. package/dist/internal/ActionDispatcher.d.ts.map +1 -1
  28. package/dist/internal/ActionDispatcher.js +23 -1
  29. package/dist/internal/ActionDispatcher.js.map +1 -1
  30. package/dist/internal/ActorInstanceManager.d.ts +7 -0
  31. package/dist/internal/ActorInstanceManager.d.ts.map +1 -1
  32. package/dist/internal/ActorInstanceManager.js +44 -4
  33. package/dist/internal/ActorInstanceManager.js.map +1 -1
  34. package/dist/internal/ActorStateAdapter.d.ts +1 -1
  35. package/dist/internal/ActorStateAdapter.d.ts.map +1 -1
  36. package/dist/internal/ActorStateAdapter.js +2 -7
  37. package/dist/internal/ActorStateAdapter.js.map +1 -1
  38. package/dist/internal/StateOptions.d.ts +1 -0
  39. package/dist/internal/StateOptions.d.ts.map +1 -1
  40. package/dist/internal/logging.d.ts +6 -7
  41. package/dist/internal/logging.d.ts.map +1 -1
  42. package/dist/internal/logging.js +78 -102
  43. package/dist/internal/logging.js.map +1 -1
  44. package/dist/mod.d.ts +2 -1
  45. package/dist/mod.d.ts.map +1 -1
  46. package/dist/mod.js +2 -1
  47. package/dist/mod.js.map +1 -1
  48. package/package.json +14 -7
  49. package/src/Action.ts +1 -1
  50. package/src/Actor.ts +57 -4
  51. package/src/Client.ts +6 -4
  52. package/src/Registry.ts +132 -71
  53. package/src/RivetError.ts +184 -25
  54. package/src/RivetLogger.ts +60 -0
  55. package/src/State.ts +293 -97
  56. package/src/internal/ActionDispatcher.ts +37 -9
  57. package/src/internal/ActorInstanceManager.ts +85 -37
  58. package/src/internal/ActorStateAdapter.ts +5 -11
  59. package/src/internal/StateOptions.ts +4 -0
  60. package/src/internal/logging.ts +103 -143
  61. package/src/mod.ts +2 -1
  62. package/dist/Logger.d.ts +0 -29
  63. package/dist/Logger.d.ts.map +0 -1
  64. package/dist/Logger.js +0 -31
  65. package/dist/Logger.js.map +0 -1
  66. package/src/Actor.test-d.ts +0 -603
  67. package/src/Actor.test.ts +0 -206
  68. package/src/Client.test.ts +0 -210
  69. package/src/Logger.ts +0 -43
  70. package/src/Registry.test-d.ts +0 -126
  71. package/src/Registry.test.ts +0 -411
  72. package/src/RivetError.test.ts +0 -188
  73. package/src/State.test.ts +0 -181
  74. package/src/internal/logging.test.ts +0 -288
package/src/State.ts CHANGED
@@ -26,6 +26,7 @@ import {
26
26
  Predicate,
27
27
  PubSub,
28
28
  Semaphore,
29
+ Scope,
29
30
  Stream,
30
31
  type Types,
31
32
  } from "effect";
@@ -33,6 +34,15 @@ import { dual } from "effect/Function";
33
34
 
34
35
  const TypeId = "~@rivetkit/effect/State";
35
36
 
37
+ /**
38
+ * Internal access to `State`'s backing store and publish machinery.
39
+ *
40
+ * @internal
41
+ */
42
+ export const RuntimeTypeId: unique symbol = Symbol.for(
43
+ "~@rivetkit/effect/State/Runtime",
44
+ ) as never;
45
+
36
46
  /**
37
47
  * A view over a persisted state cell with a subscribable change stream.
38
48
  *
@@ -45,17 +55,97 @@ export interface State<A, E = never, R = never>
45
55
  extends Variance<A, E, R>,
46
56
  Pipeable.Pipeable,
47
57
  Inspectable.Inspectable {
58
+ /**
59
+ * Retrieves the persisted value.
60
+ */
61
+ readonly get: Effect.Effect<A, E, R>;
62
+ /**
63
+ * Retrieves the persisted value and sets a new value atomically.
64
+ */
65
+ readonly getAndSet: (value: A) => Effect.Effect<A, E, R>;
66
+ /**
67
+ * Retrieves the current value and updates it atomically with the result of
68
+ * applying a function.
69
+ */
70
+ readonly getAndUpdate: (f: (a: A) => A) => Effect.Effect<A, E, R>;
71
+ /**
72
+ * Retrieves the current value and updates it atomically with the result of
73
+ * applying an effectful function.
74
+ */
75
+ readonly getAndUpdateEffect: <E2, R2>(
76
+ f: (a: A) => Effect.Effect<A, E2, R2>,
77
+ ) => Effect.Effect<A, E | E2, R | R2>;
78
+ /**
79
+ * Modifies atomically with a function that computes a return value and
80
+ * a new value.
81
+ */
82
+ readonly modify: <B>(
83
+ f: (a: A) => readonly [B, A],
84
+ ) => Effect.Effect<B, E, R>;
85
+ /**
86
+ * Modifies atomically with an effectful function that computes a return value
87
+ * and a new value.
88
+ */
89
+ readonly modifyEffect: <B, E2, R2>(
90
+ f: (a: A) => Effect.Effect<readonly [B, A], E2, R2>,
91
+ ) => Effect.Effect<B, E | E2, R | R2>;
92
+ /**
93
+ * Writes the persisted value.
94
+ */
95
+ readonly set: (value: A) => Effect.Effect<void, E, R>;
96
+ /**
97
+ * Sets the persisted value and returns the new value.
98
+ */
99
+ readonly setAndGet: (value: A) => Effect.Effect<A, E, R>;
100
+ /**
101
+ * Updates the persisted value with the result of applying a function.
102
+ */
103
+ readonly update: (f: (a: A) => A) => Effect.Effect<void, E, R>;
104
+ /**
105
+ * Updates the persisted value with the result of applying an effectful function.
106
+ */
107
+ readonly updateEffect: <E2, R2>(
108
+ f: (a: A) => Effect.Effect<A, E2, R2>,
109
+ ) => Effect.Effect<void, E | E2, R | R2>;
110
+ /**
111
+ * Updates the persisted value with the result of applying an effectful function
112
+ * and returns the new value.
113
+ */
114
+ readonly updateAndGet: (f: (a: A) => A) => Effect.Effect<A, E, R>;
115
+ /**
116
+ * Updates the persisted value with the result of applying an effectful function
117
+ * and returns the new value.
118
+ */
119
+ readonly updateAndGetEffect: <E2, R2>(
120
+ f: (a: A) => Effect.Effect<A, E2, R2>,
121
+ ) => Effect.Effect<A, E | E2, R | R2>;
122
+ /**
123
+ * Creates a stream that emits the current persisted value and all subsequent
124
+ * changes.
125
+ */
126
+ readonly changes: Stream.Stream<A>;
127
+ /**
128
+ * Internal access to `State`'s backing store and publish machinery.
129
+ *
130
+ * @internal
131
+ */
132
+ readonly [RuntimeTypeId]: StateRuntime<A, E, R>;
133
+ }
134
+
135
+ /**
136
+ * Runtime-only hooks for wiring actor state persistence and change
137
+ * notifications.
138
+ *
139
+ * @internal
140
+ */
141
+ export interface StateRuntime<A, E = never, R = never> {
142
+ readonly publish: (value: A) => Effect.Effect<boolean>;
143
+ readonly publishEffect: <E2, R2>(
144
+ effect: Effect.Effect<A, E2, R2>,
145
+ ) => Effect.Effect<boolean, E2, R2>;
48
146
  readonly read: () => Effect.Effect<A, E, R>;
49
147
  readonly write: (value: A) => Effect.Effect<void, E, R>;
50
148
  readonly pubsub: PubSub.PubSub<A>;
51
- /**
52
- * Serializes writes (`set`, `update`, `modify`) so the read/apply/
53
- * write triple is atomic. The runtime may also use this semaphore
54
- * to serialize its own decode-and-publish work from
55
- * `onStateChange`, keeping the change stream's order consistent
56
- * with the write order.
57
- */
58
- readonly semaphore: Semaphore.Semaphore;
59
149
  }
60
150
 
61
151
  export const isState = (u: unknown): u is State<unknown, unknown> =>
@@ -86,47 +176,192 @@ const Proto = {
86
176
  * The current value (per `read()`) is published to the pubsub on
87
177
  * construction so any subscription obtained later replays it.
88
178
  *
89
- * The PubSub is not explicitly shut down — it's reclaimed by GC when
90
- * the `State` and any subscribers become unreachable.
179
+ * The backing PubSub is scoped and shuts down when the current
180
+ * `Scope` closes.
91
181
  */
92
182
  export const make = Effect.fnUntraced(function* <A, E, R>(
93
183
  read: () => Effect.Effect<A, E, R>,
94
184
  write: (value: A) => Effect.Effect<void, E, R>,
95
- ): Effect.fn.Return<State<A, E, R>, E, R> {
185
+ ): Effect.fn.Return<State<A, E, R>, E, R | Scope.Scope> {
96
186
  const pubsub = yield* PubSub.unbounded<A>({ replay: 1 });
187
+ yield* Effect.addFinalizer(() => PubSub.shutdown(pubsub));
97
188
  const initial = yield* read();
98
- PubSub.publishUnsafe(pubsub, initial);
189
+ yield* PubSub.publish(pubsub, initial);
99
190
  const self = Object.create(Proto);
100
- self.read = read;
101
- self.write = write;
102
- self.pubsub = pubsub;
103
- self.semaphore = Semaphore.makeUnsafe(1);
191
+ const semaphore = yield* Semaphore.make(1);
192
+ self[RuntimeTypeId] = {
193
+ read,
194
+ write,
195
+ pubsub,
196
+ publish: (value: A) => PubSub.publish(pubsub, value),
197
+ publishEffect: <E2, R2>(effect: Effect.Effect<A, E2, R2>) =>
198
+ Semaphore.withPermit(
199
+ semaphore,
200
+ Effect.flatMap(effect, (value) =>
201
+ PubSub.publish(pubsub, value),
202
+ ),
203
+ ),
204
+ };
205
+ self.get = Effect.suspend(() => self[RuntimeTypeId].read());
206
+ self.set = (value: A) => Semaphore.withPermit(semaphore, write(value));
207
+ self.getAndSet = (value: A) =>
208
+ Semaphore.withPermit(
209
+ semaphore,
210
+ Effect.flatMap(read(), (previous) =>
211
+ Effect.as(write(value), previous),
212
+ ),
213
+ );
214
+ self.setAndGet = (value: A) =>
215
+ Semaphore.withPermit(semaphore, Effect.as(write(value), value));
216
+ self.update = (f: (a: A) => A) =>
217
+ Semaphore.withPermit(
218
+ semaphore,
219
+ Effect.flatMap(read(), (a) => write(f(a))),
220
+ );
221
+ self.updateEffect = <E2, R2>(f: (a: A) => Effect.Effect<A, E2, R2>) =>
222
+ Semaphore.withPermit(
223
+ semaphore,
224
+ Effect.flatMap(read(), (a) => Effect.flatMap(f(a), write)),
225
+ );
226
+ self.getAndUpdate = (f: (a: A) => A) =>
227
+ Semaphore.withPermit(
228
+ semaphore,
229
+ Effect.flatMap(read(), (previous) =>
230
+ Effect.as(write(f(previous)), previous),
231
+ ),
232
+ );
233
+ self.getAndUpdateEffect = <E2, R2>(f: (a: A) => Effect.Effect<A, E2, R2>) =>
234
+ Semaphore.withPermit(
235
+ semaphore,
236
+ Effect.flatMap(read(), (previous) =>
237
+ Effect.flatMap(f(previous), (next) =>
238
+ Effect.as(write(next), previous),
239
+ ),
240
+ ),
241
+ );
242
+ self.updateAndGet = (f: (a: A) => A) =>
243
+ Semaphore.withPermit(
244
+ semaphore,
245
+ Effect.flatMap(read(), (a) => {
246
+ const next = f(a);
247
+ return Effect.as(write(next), next);
248
+ }),
249
+ );
250
+ self.updateAndGetEffect = <E2, R2>(f: (a: A) => Effect.Effect<A, E2, R2>) =>
251
+ Semaphore.withPermit(
252
+ semaphore,
253
+ Effect.flatMap(read(), (a) =>
254
+ Effect.flatMap(f(a), (next) => Effect.as(write(next), next)),
255
+ ),
256
+ );
257
+ self.modify = <B>(f: (a: A) => readonly [B, A]) =>
258
+ Semaphore.withPermit(
259
+ semaphore,
260
+ Effect.flatMap(read(), (a) => {
261
+ const [b, next] = f(a);
262
+ return Effect.as(write(next), b);
263
+ }),
264
+ );
265
+ self.modifyEffect = <B, E2, R2>(
266
+ f: (a: A) => Effect.Effect<readonly [B, A], E2, R2>,
267
+ ) =>
268
+ Semaphore.withPermit(
269
+ semaphore,
270
+ Effect.flatMap(read(), (a) =>
271
+ Effect.flatMap(f(a), ([b, next]) => Effect.as(write(next), b)),
272
+ ),
273
+ );
274
+ self.changes = Stream.fromPubSub(pubsub);
104
275
  return self;
105
276
  });
106
277
 
107
- /**
108
- * Reads the current value.
109
- */
110
278
  export const get = <A, E, R>(self: State<A, E, R>): Effect.Effect<A, E, R> =>
111
- self.read();
279
+ self.get;
280
+
281
+ export const getAndSet: {
282
+ <A>(value: A): <E, R>(self: State<A, E, R>) => Effect.Effect<A, E, R>;
283
+ <A, E, R>(self: State<A, E, R>, value: A): Effect.Effect<A, E, R>;
284
+ } = dual(
285
+ 2,
286
+ <A, E, R>(self: State<A, E, R>, value: A): Effect.Effect<A, E, R> =>
287
+ self.getAndSet(value),
288
+ );
289
+
290
+ export const getAndUpdate: {
291
+ <A>(f: (a: A) => A): <E, R>(self: State<A, E, R>) => Effect.Effect<A, E, R>;
292
+ <A, E, R>(self: State<A, E, R>, f: (a: A) => A): Effect.Effect<A, E, R>;
293
+ } = dual(
294
+ 2,
295
+ <A, E, R>(self: State<A, E, R>, f: (a: A) => A): Effect.Effect<A, E, R> =>
296
+ self.getAndUpdate(f),
297
+ );
298
+
299
+ export const getAndUpdateEffect: {
300
+ <A, E2, R2>(
301
+ f: (a: A) => Effect.Effect<A, E2, R2>,
302
+ ): <E, R>(self: State<A, E, R>) => Effect.Effect<A, E | E2, R | R2>;
303
+ <A, E, R, E2, R2>(
304
+ self: State<A, E, R>,
305
+ f: (a: A) => Effect.Effect<A, E2, R2>,
306
+ ): Effect.Effect<A, E | E2, R | R2>;
307
+ } = dual(
308
+ 2,
309
+ <A, E, R, E2, R2>(
310
+ self: State<A, E, R>,
311
+ f: (a: A) => Effect.Effect<A, E2, R2>,
312
+ ): Effect.Effect<A, E | E2, R | R2> => self.getAndUpdateEffect(f),
313
+ );
314
+
315
+ export const modify: {
316
+ <A, B>(
317
+ f: (a: A) => readonly [B, A],
318
+ ): <E, R>(self: State<A, E, R>) => Effect.Effect<B, E, R>;
319
+ <A, E, R, B>(
320
+ self: State<A, E, R>,
321
+ f: (a: A) => readonly [B, A],
322
+ ): Effect.Effect<B, E, R>;
323
+ } = dual(
324
+ 2,
325
+ <A, E, R, B>(
326
+ self: State<A, E, R>,
327
+ f: (a: A) => readonly [B, A],
328
+ ): Effect.Effect<B, E, R> => self.modify(f),
329
+ );
330
+
331
+ export const modifyEffect: {
332
+ <A, B, E2, R2>(
333
+ f: (a: A) => Effect.Effect<readonly [B, A], E2, R2>,
334
+ ): <E, R>(self: State<A, E, R>) => Effect.Effect<B, E | E2, R | R2>;
335
+ <A, E, R, B, E2, R2>(
336
+ self: State<A, E, R>,
337
+ f: (a: A) => Effect.Effect<readonly [B, A], E2, R2>,
338
+ ): Effect.Effect<B, E | E2, R | R2>;
339
+ } = dual(
340
+ 2,
341
+ <A, E, R, B, E2, R2>(
342
+ self: State<A, E, R>,
343
+ f: (a: A) => Effect.Effect<readonly [B, A], E2, R2>,
344
+ ): Effect.Effect<B, E | E2, R | R2> => self.modifyEffect(f),
345
+ );
112
346
 
113
- /**
114
- * Replaces the value. Serialized with `update` / `modify` so writes
115
- * happen in invocation order.
116
- */
117
347
  export const set: {
118
348
  <A>(value: A): <E, R>(self: State<A, E, R>) => Effect.Effect<void, E, R>;
119
349
  <A, E, R>(self: State<A, E, R>, value: A): Effect.Effect<void, E, R>;
120
350
  } = dual(
121
351
  2,
122
352
  <A, E, R>(self: State<A, E, R>, value: A): Effect.Effect<void, E, R> =>
123
- Semaphore.withPermit(self.semaphore, self.write(value)),
353
+ self.set(value),
354
+ );
355
+
356
+ export const setAndGet: {
357
+ <A>(value: A): <E, R>(self: State<A, E, R>) => Effect.Effect<A, E, R>;
358
+ <A, E, R>(self: State<A, E, R>, value: A): Effect.Effect<A, E, R>;
359
+ } = dual(
360
+ 2,
361
+ <A, E, R>(self: State<A, E, R>, value: A): Effect.Effect<A, E, R> =>
362
+ self.setAndGet(value),
124
363
  );
125
364
 
126
- /**
127
- * Updates the value by applying `f` to the current value. The
128
- * read/apply/write triple is atomic across fibers.
129
- */
130
365
  export const update: {
131
366
  <A>(
132
367
  f: (a: A) => A,
@@ -137,88 +372,49 @@ export const update: {
137
372
  <A, E, R>(
138
373
  self: State<A, E, R>,
139
374
  f: (a: A) => A,
140
- ): Effect.Effect<void, E, R> =>
141
- Semaphore.withPermit(
142
- self.semaphore,
143
- Effect.flatMap(self.read(), (a) => self.write(f(a))),
144
- ),
375
+ ): Effect.Effect<void, E, R> => self.update(f),
376
+ );
377
+
378
+ export const updateEffect: {
379
+ <A, E2, R2>(
380
+ f: (a: A) => Effect.Effect<A, E2, R2>,
381
+ ): <E, R>(self: State<A, E, R>) => Effect.Effect<void, E | E2, R | R2>;
382
+ <A, E, R, E2, R2>(
383
+ self: State<A, E, R>,
384
+ f: (a: A) => Effect.Effect<A, E2, R2>,
385
+ ): Effect.Effect<void, E | E2, R | R2>;
386
+ } = dual(
387
+ 2,
388
+ <A, E, R, E2, R2>(
389
+ self: State<A, E, R>,
390
+ f: (a: A) => Effect.Effect<A, E2, R2>,
391
+ ): Effect.Effect<void, E | E2, R | R2> => self.updateEffect(f),
145
392
  );
146
393
 
147
- /**
148
- * Updates the value by applying `f` and returns the new value. The
149
- * read/apply/write triple is atomic across fibers.
150
- */
151
394
  export const updateAndGet: {
152
395
  <A>(f: (a: A) => A): <E, R>(self: State<A, E, R>) => Effect.Effect<A, E, R>;
153
396
  <A, E, R>(self: State<A, E, R>, f: (a: A) => A): Effect.Effect<A, E, R>;
154
397
  } = dual(
155
398
  2,
156
399
  <A, E, R>(self: State<A, E, R>, f: (a: A) => A): Effect.Effect<A, E, R> =>
157
- Semaphore.withPermit(
158
- self.semaphore,
159
- Effect.flatMap(self.read(), (a) => {
160
- const next = f(a);
161
- return Effect.as(self.write(next), next);
162
- }),
163
- ),
400
+ self.updateAndGet(f),
164
401
  );
165
402
 
166
- /**
167
- * Atomically replaces the value with the second element of `f(prev)`
168
- * and returns the first. The read/apply/write triple is atomic across
169
- * fibers.
170
- */
171
- export const modify: {
172
- <A, B>(
173
- f: (a: A) => readonly [B, A],
174
- ): <E, R>(self: State<A, E, R>) => Effect.Effect<B, E, R>;
175
- <A, E, R, B>(
403
+ export const updateAndGetEffect: {
404
+ <A, E2, R2>(
405
+ f: (a: A) => Effect.Effect<A, E2, R2>,
406
+ ): <E, R>(self: State<A, E, R>) => Effect.Effect<A, E | E2, R | R2>;
407
+ <A, E, R, E2, R2>(
176
408
  self: State<A, E, R>,
177
- f: (a: A) => readonly [B, A],
178
- ): Effect.Effect<B, E, R>;
409
+ f: (a: A) => Effect.Effect<A, E2, R2>,
410
+ ): Effect.Effect<A, E | E2, R | R2>;
179
411
  } = dual(
180
412
  2,
181
- <A, E, R, B>(
413
+ <A, E, R, E2, R2>(
182
414
  self: State<A, E, R>,
183
- f: (a: A) => readonly [B, A],
184
- ): Effect.Effect<B, E, R> =>
185
- Semaphore.withPermit(
186
- self.semaphore,
187
- Effect.flatMap(self.read(), (a) => {
188
- const [b, next] = f(a);
189
- return Effect.as(self.write(next), b);
190
- }),
191
- ),
415
+ f: (a: A) => Effect.Effect<A, E2, R2>,
416
+ ): Effect.Effect<A, E | E2, R | R2> => self.updateAndGetEffect(f),
192
417
  );
193
418
 
194
- /**
195
- * Stream of every value published to this `State`. New subscribers
196
- * immediately see the most recent value (replay = 1), then every
197
- * subsequent publish.
198
- */
199
419
  export const changes = <A, E, R>(self: State<A, E, R>): Stream.Stream<A> =>
200
- Stream.fromPubSub(self.pubsub);
201
-
202
- /**
203
- * Publish a value to the change stream as an `Effect`. Does not
204
- * modify the underlying store.
205
- */
206
- export const publish: {
207
- <A>(value: A): <E, R>(self: State<A, E, R>) => Effect.Effect<boolean>;
208
- <A, E, R>(self: State<A, E, R>, value: A): Effect.Effect<boolean>;
209
- } = dual(
210
- 2,
211
- <A, E, R>(self: State<A, E, R>, value: A): Effect.Effect<boolean> =>
212
- PubSub.publish(self.pubsub, value),
213
- );
214
-
215
- /**
216
- * Synchronous variant of {@link publish}. Returns `true` when the
217
- * publish succeeded, `false` if the pubsub is shut down. The runtime
218
- * uses this from rivetkit's `onStateChange` callback to feed the
219
- * change stream.
220
- */
221
- export const publishUnsafe = <A, E, R>(
222
- self: State<A, E, R>,
223
- value: A,
224
- ): boolean => PubSub.publishUnsafe(self.pubsub, value);
420
+ self.changes;
@@ -6,16 +6,17 @@ import {
6
6
  Option,
7
7
  Record,
8
8
  Schema,
9
+ type Scope,
9
10
  Tracer,
10
11
  } from "effect";
11
12
  import * as Rivetkit from "rivetkit";
12
13
  import type * as Action from "../Action.ts";
13
14
  import type {
15
+ ActionConnection,
14
16
  ActionHandlersFrom,
15
17
  ActionRequest,
16
18
  Actor,
17
19
  } from "../Actor.ts";
18
- import type * as Client from "../Client.ts";
19
20
  import * as ActionErrorEnvelope from "./ActionErrorEnvelope.ts";
20
21
  import { makeActorLogAnnotations } from "./logging.ts";
21
22
  import { readTraceMeta, rpcSystem } from "./tracing.ts";
@@ -27,6 +28,7 @@ export type Instance<ActionHandlers> = {
27
28
  effect: Effect.Effect<A, E, any>,
28
29
  options?: Effect.RunOptions,
29
30
  ) => Fiber.Fiber<A, E>;
31
+ readonly connectionScope: (connectionId: string) => Scope.Scope;
30
32
  };
31
33
 
32
34
  export const make = <
@@ -58,9 +60,14 @@ export const make = <
58
60
  action._tag,
59
61
  async (
60
62
  c: Rivetkit.ActionContextOf<ActorDefinition>,
61
- payload: Action.Payload<typeof action>,
62
- meta?: Client.ActionMeta, // TODO: Find better type
63
+ ...args: unknown[]
63
64
  ) => {
65
+ // Scheduler metadata is appended after stored arguments. Only strip
66
+ // the trusted invocation object, never a caller-supplied lookalike.
67
+ if (c.scheduledFire && args.at(-1) === c.scheduledFire) {
68
+ args.pop();
69
+ }
70
+ const [payload, meta] = args;
64
71
  // Always wrap in a server-side span so the handler has a
65
72
  // live `currentSpan` even when the caller didn't ship trace
66
73
  // context (e.g., a non-Effect-SDK client). When trace context
@@ -96,12 +103,13 @@ export const make = <
96
103
  const decodedPayload = yield* decodePayload(
97
104
  payloadForDecode,
98
105
  ).pipe(
99
- Effect.mapError(() =>
100
- new Rivetkit.RivetError(
101
- "request",
102
- "invalid",
103
- `Invalid payload for action ${actor.name}/${action._tag}`,
104
- ),
106
+ Effect.mapError(
107
+ () =>
108
+ new Rivetkit.RivetError(
109
+ "request",
110
+ "invalid",
111
+ `Invalid payload for action ${actor.name}/${action._tag}`,
112
+ ),
105
113
  ),
106
114
  );
107
115
  // The payload was decoded with this action's schema,
@@ -111,6 +119,7 @@ export const make = <
111
119
  _tag: action._tag,
112
120
  action,
113
121
  payload: decodedPayload,
122
+ connection: makeActionConnection(c, instance),
114
123
  } as ActionRequest<typeof action>;
115
124
 
116
125
  const resultExit = yield* Effect.exit(
@@ -186,6 +195,25 @@ export const make = <
186
195
  ];
187
196
  });
188
197
 
198
+ const makeActionConnection = (
199
+ c: { readonly conn?: { readonly id: string } },
200
+ instance: Pick<Instance<unknown>, "connectionScope">,
201
+ ): Option.Option<ActionConnection> => {
202
+ // Scheduled actions run without a connection, although the RivetKit
203
+ // context type declares `conn` as always present.
204
+ if (!c.conn) return Option.none();
205
+
206
+ const { id } = c.conn;
207
+ return Option.some({
208
+ id,
209
+ // Most handlers never read this, and the first read checks the
210
+ // connection list, which costs O(connections).
211
+ get scope() {
212
+ return instance.connectionScope(id);
213
+ },
214
+ });
215
+ };
216
+
189
217
  const makeActorAbortedError = () =>
190
218
  new Rivetkit.RivetError("actor", "aborted", "Actor aborted", {
191
219
  public: true,
@@ -35,6 +35,47 @@ export type Instance<
35
35
  ) => Fiber.Fiber<A, E>;
36
36
  readonly scope: Scope.Closeable;
37
37
  readonly state?: ActorStateAdapter.ActorState<StateDefinition>;
38
+ readonly connectionScope: (connectionId: string) => Scope.Scope;
39
+ readonly closeConnectionScope: (
40
+ connectionId: string,
41
+ ) => Effect.Effect<void>;
42
+ };
43
+
44
+ /**
45
+ * Tracks one scope per connection, created when a handler first reads it.
46
+ * Each scope is a child of the wake scope, so sleep and destroy also close it.
47
+ */
48
+ const makeConnectionScopes = (
49
+ wakeScope: Scope.Scope,
50
+ isConnected: (connectionId: string) => boolean,
51
+ ) => {
52
+ const scopes = new Map<string, Scope.Closeable>();
53
+
54
+ return {
55
+ connectionScope: (connectionId: string): Scope.Scope => {
56
+ const existing = scopes.get(connectionId);
57
+ if (existing) return existing;
58
+
59
+ const scope = Scope.forkUnsafe(wakeScope);
60
+ // Core removes a connection before it reports the disconnect. So a
61
+ // connection that is still present will get a later close, and one
62
+ // that is gone gets a closed scope, which runs finalizers immediately.
63
+ if (isConnected(connectionId)) {
64
+ scopes.set(connectionId, scope);
65
+ } else {
66
+ Scope.closeUnsafe(scope, Exit.void);
67
+ }
68
+ return scope;
69
+ },
70
+ closeConnectionScope: (connectionId: string) =>
71
+ Effect.suspend(() => {
72
+ const scope = scopes.get(connectionId);
73
+ if (!scope) return Effect.void;
74
+
75
+ scopes.delete(connectionId);
76
+ return Scope.close(scope, Exit.void);
77
+ }),
78
+ };
38
79
  };
39
80
 
40
81
  export const make = Effect.fnUntraced(function* <
@@ -71,49 +112,46 @@ export const make = Effect.fnUntraced(function* <
71
112
  const services = yield* Effect.context<any>();
72
113
  const runPromise = Effect.runPromiseWith(services);
73
114
 
74
- const makeInstance = Effect.fnUntraced(function* (
75
- c: WakeContext<StateDefinition, Database>,
76
- ): Effect.fn.Return<Instance<ActionHandlers, StateDefinition>, never, any> {
77
- const scope = yield* Scope.make();
78
- return yield* Effect.gen(function* () {
79
- const state = stateAdapter
80
- ? yield* stateAdapter.makeStateView(c)
81
- : undefined;
82
- const context = makeContext(c, scope);
83
- const actionHandlers = yield* wakeHandler(
84
- makeWakeOptions(c, state),
85
- ).pipe(Effect.provide(context));
86
- const runFork = yield* FiberSet.makeRuntime<
87
- any,
88
- unknown,
89
- unknown
90
- >().pipe(Effect.provide(Context.merge(services, context)));
115
+ const makeInstance = Effect.fnUntraced(function* (
116
+ c: WakeContext<StateDefinition, Database>,
117
+ ): Effect.fn.Return<Instance<ActionHandlers, StateDefinition>, never, any> {
118
+ const scope = yield* Scope.make();
119
+ return yield* Effect.gen(function* () {
120
+ const state = stateAdapter
121
+ ? yield* stateAdapter
122
+ .makeStateView(c)
123
+ .pipe(Effect.provideService(Scope.Scope, scope))
124
+ : undefined;
125
+ const context = makeContext(c, scope);
126
+ const actionHandlers = yield* wakeHandler(
127
+ makeWakeOptions(c, state),
128
+ ).pipe(Effect.provide(context));
129
+ const runFork = yield* FiberSet.makeRuntime<
130
+ any,
131
+ unknown,
132
+ unknown
133
+ >().pipe(Effect.provide(Context.merge(services, context)));
91
134
 
92
- return {
93
- actionHandlers,
94
- runFork,
95
- scope,
96
- state,
97
- };
98
- }).pipe(
99
- Effect.onError((cause) =>
100
- Scope.close(scope, Exit.failCause(cause)),
135
+ return {
136
+ actionHandlers,
137
+ runFork,
138
+ scope,
139
+ state,
140
+ ...makeConnectionScopes(scope, (connectionId) =>
141
+ c.conns.has(connectionId),
101
142
  ),
102
- );
103
- });
143
+ };
144
+ }).pipe(
145
+ Effect.onError((cause) =>
146
+ Scope.close(scope, Exit.failCause(cause)),
147
+ ),
148
+ );
149
+ });
104
150
 
105
151
  return {
106
152
  get: (actorId: string) => instances.get(actorId),
107
153
  onWake: async (c: WakeContext<StateDefinition, Database>) => {
108
- await runPromise(
109
- makeInstance(c).pipe(
110
- Effect.tap((instance) =>
111
- Effect.sync(() => {
112
- instances.set(c.actorId, instance);
113
- }),
114
- ),
115
- ),
116
- );
154
+ instances.set(c.actorId, await runPromise(makeInstance(c)));
117
155
  },
118
156
  onStateChange: stateAdapter
119
157
  ? (
@@ -127,6 +165,16 @@ export const make = Effect.fnUntraced(function* <
127
165
  stateAdapter.publishChange(instance, newState);
128
166
  }
129
167
  : undefined,
168
+ onDisconnect: async (
169
+ c: { readonly actorId: string },
170
+ conn: { readonly id: string },
171
+ ) => {
172
+ const instance = instances.get(c.actorId);
173
+ // The disconnect can arrive after teardown closed the wake scope.
174
+ if (!instance) return;
175
+
176
+ await runPromise(instance.closeConnectionScope(conn.id));
177
+ },
130
178
  onTeardown: async (c: { readonly actorId: string }) => {
131
179
  return runPromise(
132
180
  Effect.gen(function* () {