@durable-effect/jobs 0.0.1-next.1
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.
- package/LICENSE +21 -0
- package/README.md +490 -0
- package/dist/client/client.d.ts +34 -0
- package/dist/client/client.d.ts.map +1 -0
- package/dist/client/client.js +427 -0
- package/dist/client/client.js.map +1 -0
- package/dist/client/index.d.ts +4 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +4 -0
- package/dist/client/index.js.map +1 -0
- package/dist/client/response.d.ts +99 -0
- package/dist/client/response.d.ts.map +1 -0
- package/dist/client/response.js +92 -0
- package/dist/client/response.js.map +1 -0
- package/dist/client/types.d.ts +242 -0
- package/dist/client/types.d.ts.map +1 -0
- package/dist/client/types.js +3 -0
- package/dist/client/types.js.map +1 -0
- package/dist/definitions/continuous.d.ts +110 -0
- package/dist/definitions/continuous.d.ts.map +1 -0
- package/dist/definitions/continuous.js +79 -0
- package/dist/definitions/continuous.js.map +1 -0
- package/dist/definitions/debounce.d.ts +67 -0
- package/dist/definitions/debounce.d.ts.map +1 -0
- package/dist/definitions/debounce.js +28 -0
- package/dist/definitions/debounce.js.map +1 -0
- package/dist/definitions/index.d.ts +4 -0
- package/dist/definitions/index.d.ts.map +1 -0
- package/dist/definitions/index.js +5 -0
- package/dist/definitions/index.js.map +1 -0
- package/dist/definitions/task.d.ts +234 -0
- package/dist/definitions/task.d.ts.map +1 -0
- package/dist/definitions/task.js +106 -0
- package/dist/definitions/task.js.map +1 -0
- package/dist/engine/engine.d.ts +60 -0
- package/dist/engine/engine.d.ts.map +1 -0
- package/dist/engine/engine.js +89 -0
- package/dist/engine/engine.js.map +1 -0
- package/dist/engine/index.d.ts +3 -0
- package/dist/engine/index.d.ts.map +1 -0
- package/dist/engine/index.js +3 -0
- package/dist/engine/index.js.map +1 -0
- package/dist/engine/types.d.ts +53 -0
- package/dist/engine/types.d.ts.map +1 -0
- package/dist/engine/types.js +3 -0
- package/dist/engine/types.js.map +1 -0
- package/dist/errors.d.ts +119 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +80 -0
- package/dist/errors.js.map +1 -0
- package/dist/factory.d.ts +97 -0
- package/dist/factory.d.ts.map +1 -0
- package/dist/factory.js +94 -0
- package/dist/factory.js.map +1 -0
- package/dist/handlers/continuous/context.d.ts +25 -0
- package/dist/handlers/continuous/context.d.ts.map +1 -0
- package/dist/handlers/continuous/context.js +38 -0
- package/dist/handlers/continuous/context.js.map +1 -0
- package/dist/handlers/continuous/executor.d.ts +10 -0
- package/dist/handlers/continuous/executor.d.ts.map +1 -0
- package/dist/handlers/continuous/executor.js +83 -0
- package/dist/handlers/continuous/executor.js.map +1 -0
- package/dist/handlers/continuous/handler.d.ts +14 -0
- package/dist/handlers/continuous/handler.d.ts.map +1 -0
- package/dist/handlers/continuous/handler.js +283 -0
- package/dist/handlers/continuous/handler.js.map +1 -0
- package/dist/handlers/continuous/index.d.ts +4 -0
- package/dist/handlers/continuous/index.d.ts.map +1 -0
- package/dist/handlers/continuous/index.js +4 -0
- package/dist/handlers/continuous/index.js.map +1 -0
- package/dist/handlers/continuous/types.d.ts +36 -0
- package/dist/handlers/continuous/types.d.ts.map +1 -0
- package/dist/handlers/continuous/types.js +3 -0
- package/dist/handlers/continuous/types.js.map +1 -0
- package/dist/handlers/debounce/handler.d.ts +14 -0
- package/dist/handlers/debounce/handler.d.ts.map +1 -0
- package/dist/handlers/debounce/handler.js +261 -0
- package/dist/handlers/debounce/handler.js.map +1 -0
- package/dist/handlers/debounce/index.d.ts +3 -0
- package/dist/handlers/debounce/index.d.ts.map +1 -0
- package/dist/handlers/debounce/index.js +3 -0
- package/dist/handlers/debounce/index.js.map +1 -0
- package/dist/handlers/debounce/types.d.ts +10 -0
- package/dist/handlers/debounce/types.d.ts.map +1 -0
- package/dist/handlers/debounce/types.js +3 -0
- package/dist/handlers/debounce/types.js.map +1 -0
- package/dist/handlers/index.d.ts +14 -0
- package/dist/handlers/index.d.ts.map +1 -0
- package/dist/handlers/index.js +25 -0
- package/dist/handlers/index.js.map +1 -0
- package/dist/handlers/task/context.d.ts +35 -0
- package/dist/handlers/task/context.d.ts.map +1 -0
- package/dist/handlers/task/context.js +156 -0
- package/dist/handlers/task/context.js.map +1 -0
- package/dist/handlers/task/handler.d.ts +13 -0
- package/dist/handlers/task/handler.d.ts.map +1 -0
- package/dist/handlers/task/handler.js +280 -0
- package/dist/handlers/task/handler.js.map +1 -0
- package/dist/handlers/task/index.d.ts +3 -0
- package/dist/handlers/task/index.d.ts.map +1 -0
- package/dist/handlers/task/index.js +2 -0
- package/dist/handlers/task/index.js.map +1 -0
- package/dist/handlers/task/types.d.ts +10 -0
- package/dist/handlers/task/types.d.ts.map +1 -0
- package/dist/handlers/task/types.js +3 -0
- package/dist/handlers/task/types.js.map +1 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +79 -0
- package/dist/index.js.map +1 -0
- package/dist/registry/index.d.ts +5 -0
- package/dist/registry/index.d.ts.map +1 -0
- package/dist/registry/index.js +4 -0
- package/dist/registry/index.js.map +1 -0
- package/dist/registry/registry.d.ts +74 -0
- package/dist/registry/registry.d.ts.map +1 -0
- package/dist/registry/registry.js +159 -0
- package/dist/registry/registry.js.map +1 -0
- package/dist/registry/typed.d.ts +146 -0
- package/dist/registry/typed.d.ts.map +1 -0
- package/dist/registry/typed.js +29 -0
- package/dist/registry/typed.js.map +1 -0
- package/dist/registry/types.d.ts +497 -0
- package/dist/registry/types.d.ts.map +1 -0
- package/dist/registry/types.js +3 -0
- package/dist/registry/types.js.map +1 -0
- package/dist/retry/errors.d.ts +31 -0
- package/dist/retry/errors.d.ts.map +1 -0
- package/dist/retry/errors.js +22 -0
- package/dist/retry/errors.js.map +1 -0
- package/dist/retry/executor.d.ts +53 -0
- package/dist/retry/executor.d.ts.map +1 -0
- package/dist/retry/executor.js +112 -0
- package/dist/retry/executor.js.map +1 -0
- package/dist/retry/index.d.ts +4 -0
- package/dist/retry/index.d.ts.map +1 -0
- package/dist/retry/index.js +4 -0
- package/dist/retry/index.js.map +1 -0
- package/dist/retry/types.d.ts +29 -0
- package/dist/retry/types.d.ts.map +1 -0
- package/dist/retry/types.js +3 -0
- package/dist/retry/types.js.map +1 -0
- package/dist/runtime/dispatcher.d.ts +39 -0
- package/dist/runtime/dispatcher.d.ts.map +1 -0
- package/dist/runtime/dispatcher.js +76 -0
- package/dist/runtime/dispatcher.js.map +1 -0
- package/dist/runtime/index.d.ts +4 -0
- package/dist/runtime/index.d.ts.map +1 -0
- package/dist/runtime/index.js +6 -0
- package/dist/runtime/index.js.map +1 -0
- package/dist/runtime/runtime.d.ts +88 -0
- package/dist/runtime/runtime.d.ts.map +1 -0
- package/dist/runtime/runtime.js +116 -0
- package/dist/runtime/runtime.js.map +1 -0
- package/dist/runtime/types.d.ts +182 -0
- package/dist/runtime/types.d.ts.map +1 -0
- package/dist/runtime/types.js +3 -0
- package/dist/runtime/types.js.map +1 -0
- package/dist/services/alarm.d.ts +37 -0
- package/dist/services/alarm.d.ts.map +1 -0
- package/dist/services/alarm.js +39 -0
- package/dist/services/alarm.js.map +1 -0
- package/dist/services/cleanup.d.ts +27 -0
- package/dist/services/cleanup.d.ts.map +1 -0
- package/dist/services/cleanup.js +25 -0
- package/dist/services/cleanup.js.map +1 -0
- package/dist/services/entity-state.d.ts +49 -0
- package/dist/services/entity-state.d.ts.map +1 -0
- package/dist/services/entity-state.js +72 -0
- package/dist/services/entity-state.js.map +1 -0
- package/dist/services/execution.d.ts +70 -0
- package/dist/services/execution.d.ts.map +1 -0
- package/dist/services/execution.js +159 -0
- package/dist/services/execution.js.map +1 -0
- package/dist/services/execution_test.d.ts +13 -0
- package/dist/services/execution_test.d.ts.map +1 -0
- package/dist/services/execution_test.js +11 -0
- package/dist/services/execution_test.js.map +1 -0
- package/dist/services/idempotency.d.ts +36 -0
- package/dist/services/idempotency.d.ts.map +1 -0
- package/dist/services/idempotency.js +48 -0
- package/dist/services/idempotency.js.map +1 -0
- package/dist/services/index.d.ts +19 -0
- package/dist/services/index.d.ts.map +1 -0
- package/dist/services/index.js +33 -0
- package/dist/services/index.js.map +1 -0
- package/dist/services/metadata.d.ts +64 -0
- package/dist/services/metadata.d.ts.map +1 -0
- package/dist/services/metadata.js +56 -0
- package/dist/services/metadata.js.map +1 -0
- package/dist/services/registry.d.ts +19 -0
- package/dist/services/registry.d.ts.map +1 -0
- package/dist/services/registry.js +17 -0
- package/dist/services/registry.js.map +1 -0
- package/dist/storage-keys.d.ts +38 -0
- package/dist/storage-keys.d.ts.map +1 -0
- package/dist/storage-keys.js +47 -0
- package/dist/storage-keys.js.map +1 -0
- package/package.json +35 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 backpine
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
# @durable-effect/jobs
|
|
2
|
+
|
|
3
|
+
Durable jobs for Cloudflare Workers built on Effect. This package provides high-level abstractions for common durable patterns:
|
|
4
|
+
|
|
5
|
+
- **Continuous** - Execute functions on a schedule (this guide)
|
|
6
|
+
- **Debounce** - Accumulate events and flush on schedule/threshold (coming soon)
|
|
7
|
+
- **WorkerPool** - Process events one at a time with retries (coming soon)
|
|
8
|
+
|
|
9
|
+
## Installation
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install @durable-effect/jobs effect
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Continuous Primitive
|
|
16
|
+
|
|
17
|
+
The Continuous primitive executes a function on a recurring schedule. Perfect for:
|
|
18
|
+
|
|
19
|
+
- Token refresh
|
|
20
|
+
- Periodic data sync
|
|
21
|
+
- Health checks
|
|
22
|
+
- Report generation
|
|
23
|
+
- Cache warming
|
|
24
|
+
|
|
25
|
+
### Quick Start
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import { Effect, Schema } from "effect";
|
|
29
|
+
import { Continuous, createDurableJobs } from "@durable-effect/jobs";
|
|
30
|
+
|
|
31
|
+
// 1. Define your primitive (name comes from the object key in step 2)
|
|
32
|
+
const tokenRefresher = Continuous.make({
|
|
33
|
+
// Schema for persistent state
|
|
34
|
+
stateSchema: Schema.Struct({
|
|
35
|
+
accessToken: Schema.String,
|
|
36
|
+
refreshToken: Schema.String,
|
|
37
|
+
expiresAt: Schema.Number,
|
|
38
|
+
}),
|
|
39
|
+
|
|
40
|
+
// Execute every 30 minutes
|
|
41
|
+
schedule: Continuous.every("30 minutes"),
|
|
42
|
+
|
|
43
|
+
// The function to run
|
|
44
|
+
execute: (ctx) =>
|
|
45
|
+
Effect.gen(function* () {
|
|
46
|
+
console.log(`Refreshing token (run #${ctx.runCount})`);
|
|
47
|
+
|
|
48
|
+
// Access current state
|
|
49
|
+
const { refreshToken } = ctx.state;
|
|
50
|
+
|
|
51
|
+
// Call your refresh API
|
|
52
|
+
const newTokens = yield* refreshTokens(refreshToken);
|
|
53
|
+
|
|
54
|
+
// Update state (persisted automatically)
|
|
55
|
+
ctx.setState({
|
|
56
|
+
accessToken: newTokens.access_token,
|
|
57
|
+
refreshToken: newTokens.refresh_token,
|
|
58
|
+
expiresAt: Date.now() + newTokens.expires_in * 1000,
|
|
59
|
+
});
|
|
60
|
+
}),
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
// 2. Create the Durable Object and Client - keys become primitive names
|
|
64
|
+
const { Jobs, JobsClient } = createDurableJobs({
|
|
65
|
+
tokenRefresher,
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
// 3. Export the Durable Object class
|
|
69
|
+
export { Jobs };
|
|
70
|
+
|
|
71
|
+
// 4. Use in your worker
|
|
72
|
+
export default {
|
|
73
|
+
async fetch(request: Request, env: Env): Promise<Response> {
|
|
74
|
+
const client = JobsClient.fromBinding(env.PRIMITIVES);
|
|
75
|
+
|
|
76
|
+
// Start a token refresher for a user (name matches the key from step 2)
|
|
77
|
+
await client.continuous("tokenRefresher").start({
|
|
78
|
+
id: "user-123",
|
|
79
|
+
input: {
|
|
80
|
+
accessToken: "",
|
|
81
|
+
refreshToken: "rt_initial_token",
|
|
82
|
+
expiresAt: 0,
|
|
83
|
+
},
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
return new Response("Token refresher started!");
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### wrangler.toml Configuration
|
|
92
|
+
|
|
93
|
+
```toml
|
|
94
|
+
[[durable_objects.bindings]]
|
|
95
|
+
name = "PRIMITIVES"
|
|
96
|
+
class_name = "Jobs"
|
|
97
|
+
|
|
98
|
+
[[migrations]]
|
|
99
|
+
tag = "v1"
|
|
100
|
+
new_classes = ["Jobs"]
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## API Reference
|
|
104
|
+
|
|
105
|
+
### `Continuous.make(config)`
|
|
106
|
+
|
|
107
|
+
Creates a continuous primitive definition. The name is assigned when you register
|
|
108
|
+
the primitive via `createDurableJobs()` - the object key becomes the name.
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
const myPrimitive = Continuous.make({
|
|
112
|
+
stateSchema: Schema.Struct({ ... }),
|
|
113
|
+
schedule: Continuous.every("1 hour"),
|
|
114
|
+
execute: (ctx) => Effect.succeed(undefined),
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
// Name "myPrimitive" comes from the key
|
|
118
|
+
const { Jobs, JobsClient } = createDurableJobs({
|
|
119
|
+
myPrimitive,
|
|
120
|
+
});
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
#### Parameters
|
|
124
|
+
|
|
125
|
+
| Parameter | Type | Description |
|
|
126
|
+
|-----------|------|-------------|
|
|
127
|
+
| `config.stateSchema` | `Schema.Schema<S>` | Effect Schema for validating and serializing state |
|
|
128
|
+
| `config.schedule` | `ContinuousSchedule` | When to execute (see Schedules below) |
|
|
129
|
+
| `config.startImmediately` | `boolean` | Execute immediately on start (default: `true`) |
|
|
130
|
+
| `config.execute` | `(ctx) => Effect<void, E, R>` | Function to execute on schedule |
|
|
131
|
+
| `config.onError` | `(error, ctx) => Effect<void>` | Optional error handler |
|
|
132
|
+
|
|
133
|
+
### Schedules
|
|
134
|
+
|
|
135
|
+
#### `Continuous.every(interval)`
|
|
136
|
+
|
|
137
|
+
Execute at a fixed interval.
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
Continuous.every("30 minutes")
|
|
141
|
+
Continuous.every("1 hour")
|
|
142
|
+
Continuous.every("24 hours")
|
|
143
|
+
Continuous.every(Duration.minutes(30))
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
#### `Continuous.cron(expression)` (coming soon)
|
|
147
|
+
|
|
148
|
+
Execute based on a cron expression.
|
|
149
|
+
|
|
150
|
+
```ts
|
|
151
|
+
// Every day at midnight
|
|
152
|
+
Continuous.cron("0 0 * * *")
|
|
153
|
+
|
|
154
|
+
// Every Monday at 9am
|
|
155
|
+
Continuous.cron("0 9 * * 1")
|
|
156
|
+
|
|
157
|
+
// Every hour
|
|
158
|
+
Continuous.cron("0 * * * *")
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
### ContinuousContext
|
|
162
|
+
|
|
163
|
+
The context object passed to your `execute` function:
|
|
164
|
+
|
|
165
|
+
```ts
|
|
166
|
+
interface ContinuousContext<S> {
|
|
167
|
+
// Current state (read-only reference)
|
|
168
|
+
readonly state: S;
|
|
169
|
+
|
|
170
|
+
// Replace the entire state
|
|
171
|
+
readonly setState: (state: S) => void;
|
|
172
|
+
|
|
173
|
+
// Update state via function
|
|
174
|
+
readonly updateState: (fn: (current: S) => S) => void;
|
|
175
|
+
|
|
176
|
+
// Unique instance identifier
|
|
177
|
+
readonly instanceId: string;
|
|
178
|
+
|
|
179
|
+
// Number of times execute has been called
|
|
180
|
+
readonly runCount: number;
|
|
181
|
+
|
|
182
|
+
// Name of this primitive
|
|
183
|
+
readonly primitiveName: string;
|
|
184
|
+
}
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
### Client Methods
|
|
188
|
+
|
|
189
|
+
#### `client.continuous(name).start({ id, input })`
|
|
190
|
+
|
|
191
|
+
Start a continuous primitive instance.
|
|
192
|
+
|
|
193
|
+
```ts
|
|
194
|
+
const result = await client.continuous("tokenRefresher").start({
|
|
195
|
+
id: "user-123", // Unique instance ID
|
|
196
|
+
input: { ... }, // Initial state (must match stateSchema)
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
// Result:
|
|
200
|
+
// { _type: "continuous.start", instanceId: string, created: boolean, status: string }
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
If the instance already exists, returns `{ created: false }` with current status.
|
|
204
|
+
|
|
205
|
+
#### `client.continuous(name).stop(id, options?)`
|
|
206
|
+
|
|
207
|
+
Stop a running instance.
|
|
208
|
+
|
|
209
|
+
```ts
|
|
210
|
+
const result = await client.continuous("tokenRefresher").stop("user-123", {
|
|
211
|
+
reason: "User logged out", // Optional reason
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
// Result:
|
|
215
|
+
// { _type: "continuous.stop", stopped: boolean, reason: string }
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
#### `client.continuous(name).trigger(id)`
|
|
219
|
+
|
|
220
|
+
Manually trigger immediate execution (bypasses schedule).
|
|
221
|
+
|
|
222
|
+
```ts
|
|
223
|
+
const result = await client.continuous("tokenRefresher").trigger("user-123");
|
|
224
|
+
|
|
225
|
+
// Result:
|
|
226
|
+
// { _type: "continuous.trigger", triggered: boolean }
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
#### `client.continuous(name).status(id)`
|
|
230
|
+
|
|
231
|
+
Get current status of an instance.
|
|
232
|
+
|
|
233
|
+
```ts
|
|
234
|
+
const result = await client.continuous("tokenRefresher").status("user-123");
|
|
235
|
+
|
|
236
|
+
// Result:
|
|
237
|
+
// { _type: "continuous.status", status: string, runCount: number, nextRunAt?: number }
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
#### `client.continuous(name).getState(id)`
|
|
241
|
+
|
|
242
|
+
Get current state of an instance.
|
|
243
|
+
|
|
244
|
+
```ts
|
|
245
|
+
const result = await client.continuous("tokenRefresher").getState("user-123");
|
|
246
|
+
|
|
247
|
+
// Result:
|
|
248
|
+
// { _type: "continuous.getState", state: S | null }
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
## Error Handling
|
|
252
|
+
|
|
253
|
+
### Using `onError`
|
|
254
|
+
|
|
255
|
+
Handle errors gracefully without failing the execution:
|
|
256
|
+
|
|
257
|
+
```ts
|
|
258
|
+
const resilientPrimitive = Continuous.make({
|
|
259
|
+
stateSchema: Schema.Struct({
|
|
260
|
+
data: Schema.String,
|
|
261
|
+
errorCount: Schema.Number,
|
|
262
|
+
lastError: Schema.NullOr(Schema.String),
|
|
263
|
+
}),
|
|
264
|
+
schedule: Continuous.every("5 minutes"),
|
|
265
|
+
|
|
266
|
+
execute: (ctx) =>
|
|
267
|
+
Effect.gen(function* () {
|
|
268
|
+
// This might fail
|
|
269
|
+
const data = yield* fetchExternalData();
|
|
270
|
+
ctx.updateState((s) => ({
|
|
271
|
+
...s,
|
|
272
|
+
data,
|
|
273
|
+
errorCount: 0,
|
|
274
|
+
lastError: null,
|
|
275
|
+
}));
|
|
276
|
+
}),
|
|
277
|
+
|
|
278
|
+
onError: (error, ctx) =>
|
|
279
|
+
Effect.sync(() => {
|
|
280
|
+
console.error(`Execution failed: ${error}`);
|
|
281
|
+
ctx.updateState((s) => ({
|
|
282
|
+
...s,
|
|
283
|
+
errorCount: s.errorCount + 1,
|
|
284
|
+
lastError: String(error),
|
|
285
|
+
}));
|
|
286
|
+
}),
|
|
287
|
+
});
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
### Typed Errors
|
|
291
|
+
|
|
292
|
+
Define typed errors for better error handling:
|
|
293
|
+
|
|
294
|
+
```ts
|
|
295
|
+
class RefreshError extends Data.TaggedError("RefreshError")<{
|
|
296
|
+
readonly reason: string;
|
|
297
|
+
}> {}
|
|
298
|
+
|
|
299
|
+
const typedPrimitive = Continuous.make({
|
|
300
|
+
stateSchema: Schema.Struct({ token: Schema.String }),
|
|
301
|
+
schedule: Continuous.every("1 hour"),
|
|
302
|
+
|
|
303
|
+
execute: (ctx) =>
|
|
304
|
+
Effect.gen(function* () {
|
|
305
|
+
const result = yield* refreshToken(ctx.state.token);
|
|
306
|
+
if (!result.ok) {
|
|
307
|
+
return yield* Effect.fail(new RefreshError({ reason: result.error }));
|
|
308
|
+
}
|
|
309
|
+
ctx.setState({ token: result.token });
|
|
310
|
+
}),
|
|
311
|
+
|
|
312
|
+
onError: (error, ctx) =>
|
|
313
|
+
Effect.sync(() => {
|
|
314
|
+
// error is typed as RefreshError
|
|
315
|
+
console.error(`Refresh failed: ${error.reason}`);
|
|
316
|
+
}),
|
|
317
|
+
});
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
## Testing
|
|
321
|
+
|
|
322
|
+
Use the test runtime for unit testing:
|
|
323
|
+
|
|
324
|
+
```ts
|
|
325
|
+
import { describe, it, expect } from "vitest";
|
|
326
|
+
import { Effect, Schema } from "effect";
|
|
327
|
+
import { createTestRuntime, NoopTrackerLayer } from "@durable-effect/core";
|
|
328
|
+
import { createJobsRuntimeFromLayer } from "@durable-effect/jobs";
|
|
329
|
+
|
|
330
|
+
describe("tokenRefresher", () => {
|
|
331
|
+
it("refreshes token on schedule", async () => {
|
|
332
|
+
// Create test runtime with time control
|
|
333
|
+
const { layer, time, handles } = createTestRuntime("test-instance", 1000000);
|
|
334
|
+
|
|
335
|
+
// Create registry (manually add name for test registry)
|
|
336
|
+
const registry = {
|
|
337
|
+
continuous: new Map([["tokenRefresher", { ...tokenRefresher, name: "tokenRefresher" }]]),
|
|
338
|
+
debounce: new Map(),
|
|
339
|
+
workerPool: new Map(),
|
|
340
|
+
};
|
|
341
|
+
|
|
342
|
+
// Create runtime from test layer
|
|
343
|
+
const runtime = createJobsRuntimeFromLayer(layer, registry);
|
|
344
|
+
|
|
345
|
+
// Start the primitive
|
|
346
|
+
await runtime.handle({
|
|
347
|
+
type: "continuous",
|
|
348
|
+
action: "start",
|
|
349
|
+
name: "tokenRefresher",
|
|
350
|
+
id: "test-user",
|
|
351
|
+
input: { accessToken: "", refreshToken: "rt_test", expiresAt: 0 },
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
// Advance time past schedule
|
|
355
|
+
time.advance(30 * 60 * 1000); // 30 minutes
|
|
356
|
+
|
|
357
|
+
// Trigger alarm
|
|
358
|
+
await runtime.handleAlarm();
|
|
359
|
+
|
|
360
|
+
// Verify state was updated
|
|
361
|
+
const result = await runtime.handle({
|
|
362
|
+
type: "continuous",
|
|
363
|
+
action: "getState",
|
|
364
|
+
name: "tokenRefresher",
|
|
365
|
+
id: "test-user",
|
|
366
|
+
});
|
|
367
|
+
|
|
368
|
+
expect(result.state.accessToken).toBeDefined();
|
|
369
|
+
});
|
|
370
|
+
});
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
## Examples
|
|
374
|
+
|
|
375
|
+
### Daily Report Generator
|
|
376
|
+
|
|
377
|
+
```ts
|
|
378
|
+
const dailyReport = Continuous.make({
|
|
379
|
+
stateSchema: Schema.Struct({
|
|
380
|
+
lastReportDate: Schema.NullOr(Schema.String),
|
|
381
|
+
totalReports: Schema.Number,
|
|
382
|
+
}),
|
|
383
|
+
schedule: Continuous.every("24 hours"),
|
|
384
|
+
startImmediately: false, // Wait for first schedule
|
|
385
|
+
|
|
386
|
+
execute: (ctx) =>
|
|
387
|
+
Effect.gen(function* () {
|
|
388
|
+
const report = yield* generateReport();
|
|
389
|
+
yield* sendReport(report);
|
|
390
|
+
|
|
391
|
+
ctx.updateState((s) => ({
|
|
392
|
+
lastReportDate: new Date().toISOString(),
|
|
393
|
+
totalReports: s.totalReports + 1,
|
|
394
|
+
}));
|
|
395
|
+
}),
|
|
396
|
+
});
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
### Health Check Monitor
|
|
400
|
+
|
|
401
|
+
```ts
|
|
402
|
+
const healthCheck = Continuous.make({
|
|
403
|
+
stateSchema: Schema.Struct({
|
|
404
|
+
status: Schema.Literal("healthy", "degraded", "down"),
|
|
405
|
+
lastCheck: Schema.Number,
|
|
406
|
+
consecutiveFailures: Schema.Number,
|
|
407
|
+
}),
|
|
408
|
+
schedule: Continuous.every("1 minute"),
|
|
409
|
+
|
|
410
|
+
execute: (ctx) =>
|
|
411
|
+
Effect.gen(function* () {
|
|
412
|
+
const isHealthy = yield* checkHealth();
|
|
413
|
+
|
|
414
|
+
ctx.updateState((s) => ({
|
|
415
|
+
status: isHealthy ? "healthy" : s.consecutiveFailures >= 3 ? "down" : "degraded",
|
|
416
|
+
lastCheck: Date.now(),
|
|
417
|
+
consecutiveFailures: isHealthy ? 0 : s.consecutiveFailures + 1,
|
|
418
|
+
}));
|
|
419
|
+
|
|
420
|
+
if (!isHealthy && ctx.state.consecutiveFailures >= 3) {
|
|
421
|
+
yield* sendAlert("Service is down!");
|
|
422
|
+
}
|
|
423
|
+
}),
|
|
424
|
+
});
|
|
425
|
+
```
|
|
426
|
+
|
|
427
|
+
### Cache Warmer
|
|
428
|
+
|
|
429
|
+
```ts
|
|
430
|
+
const cacheWarmer = Continuous.make({
|
|
431
|
+
stateSchema: Schema.Struct({
|
|
432
|
+
lastWarmTime: Schema.Number,
|
|
433
|
+
itemsWarmed: Schema.Number,
|
|
434
|
+
}),
|
|
435
|
+
schedule: Continuous.every("15 minutes"),
|
|
436
|
+
|
|
437
|
+
execute: (ctx) =>
|
|
438
|
+
Effect.gen(function* () {
|
|
439
|
+
const items = yield* getPopularItems();
|
|
440
|
+
|
|
441
|
+
for (const item of items) {
|
|
442
|
+
yield* warmCache(item);
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
ctx.setState({
|
|
446
|
+
lastWarmTime: Date.now(),
|
|
447
|
+
itemsWarmed: items.length,
|
|
448
|
+
});
|
|
449
|
+
}),
|
|
450
|
+
});
|
|
451
|
+
```
|
|
452
|
+
|
|
453
|
+
## Architecture
|
|
454
|
+
|
|
455
|
+
The Continuous primitive is built on a thin Durable Object shell that delegates to a swappable runtime:
|
|
456
|
+
|
|
457
|
+
```
|
|
458
|
+
┌─────────────────────────────────────────────────────────────┐
|
|
459
|
+
│ Worker Code │
|
|
460
|
+
│ client.continuous("name").start({ id, input }) │
|
|
461
|
+
└─────────────────────────────────────────────────────────────┘
|
|
462
|
+
│
|
|
463
|
+
▼
|
|
464
|
+
┌─────────────────────────────────────────────────────────────┐
|
|
465
|
+
│ Durable Object (Thin Shell) │
|
|
466
|
+
│ │
|
|
467
|
+
│ • Receives RPC calls │
|
|
468
|
+
│ • Delegates to JobsRuntime │
|
|
469
|
+
│ • Handles alarms │
|
|
470
|
+
└─────────────────────────────────────────────────────────────┘
|
|
471
|
+
│
|
|
472
|
+
▼
|
|
473
|
+
┌─────────────────────────────────────────────────────────────┐
|
|
474
|
+
│ Jobs Runtime │
|
|
475
|
+
│ │
|
|
476
|
+
│ • Routes requests to handlers │
|
|
477
|
+
│ • Manages state via StorageAdapter │
|
|
478
|
+
│ • Schedules alarms via SchedulerAdapter │
|
|
479
|
+
│ • Executes user functions │
|
|
480
|
+
└─────────────────────────────────────────────────────────────┘
|
|
481
|
+
```
|
|
482
|
+
|
|
483
|
+
Each instance has its own:
|
|
484
|
+
- **Storage** - Isolated key-value storage for state
|
|
485
|
+
- **Alarm** - Single alarm for scheduling next execution
|
|
486
|
+
- **Instance ID** - Format: `continuous:{name}:{userProvidedId}`
|
|
487
|
+
|
|
488
|
+
## License
|
|
489
|
+
|
|
490
|
+
MIT
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { AnyUnregisteredDefinition } from "../registry/types";
|
|
2
|
+
import type { TypedJobRegistry } from "../registry/typed";
|
|
3
|
+
import type { JobsClient } from "./types";
|
|
4
|
+
/**
|
|
5
|
+
* Create a jobs client from a Durable Object binding.
|
|
6
|
+
*
|
|
7
|
+
* The client provides typed access to all registered jobs and
|
|
8
|
+
* handles instance ID resolution and routing.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* const client = createJobsClient(env.JOBS, registry);
|
|
13
|
+
*
|
|
14
|
+
* // Access continuous job
|
|
15
|
+
* await client.continuous("tokenRefresher").start({
|
|
16
|
+
* id: "user-123",
|
|
17
|
+
* input: { refreshToken: "rt_abc" },
|
|
18
|
+
* });
|
|
19
|
+
*
|
|
20
|
+
* // Access debounce job
|
|
21
|
+
* await client.debounce("webhookDebounce").add({
|
|
22
|
+
* id: "contact-456",
|
|
23
|
+
* event: { type: "contact.updated", data: {...} },
|
|
24
|
+
* });
|
|
25
|
+
*
|
|
26
|
+
* // Access workerPool job (auto-routes to instance)
|
|
27
|
+
* await client.workerPool("emailWorkerPool").enqueue({
|
|
28
|
+
* id: "email-789",
|
|
29
|
+
* event: { to: "user@example.com", template: "welcome" },
|
|
30
|
+
* });
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
export declare function createJobsClient<T extends Record<string, AnyUnregisteredDefinition>>(binding: DurableObjectNamespace, registry: TypedJobRegistry<T>): JobsClient<TypedJobRegistry<T>>;
|
|
34
|
+
//# sourceMappingURL=client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/client/client.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AACnE,OAAO,KAAK,EAAE,gBAAgB,EAAsB,MAAM,mBAAmB,CAAC;AAE9E,OAAO,KAAK,EACV,UAAU,EAOX,MAAM,SAAS,CAAC;AAyDjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,yBAAyB,CAAC,EAClF,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,EAAE,gBAAgB,CAAC,CAAC,CAAC,GAC5B,UAAU,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,CA2fjC"}
|