@colony2/jobdb 0.0.1 → 0.0.7

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 ADDED
@@ -0,0 +1,184 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright
13
+ owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities
16
+ that control, are controlled by, or are under common control with that entity.
17
+ For the purposes of this definition, "control" means (i) the power, direct or
18
+ indirect, to cause the direction or management of such entity, whether by
19
+ contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
20
+ outstanding shares, or (iii) beneficial ownership of such entity.
21
+
22
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
23
+ permissions granted by this License.
24
+
25
+ "Source" form shall mean the preferred form for making modifications, including
26
+ but not limited to software source code, documentation source, and configuration
27
+ files.
28
+
29
+ "Object" form shall mean any form resulting from mechanical transformation or
30
+ translation of a Source form, including but not limited to compiled object code,
31
+ generated documentation, and conversions to other media types.
32
+
33
+ "Work" shall mean the work of authorship, whether in Source or Object form,
34
+ made available under the License, as indicated by a copyright notice that is
35
+ included in or attached to the work (an example is provided in the Appendix
36
+ below).
37
+
38
+ "Derivative Works" shall mean any work, whether in Source or Object form, that
39
+ is based on (or derived from) the Work and for which the editorial revisions,
40
+ annotations, elaborations, or other modifications represent, as a whole, an
41
+ original work of authorship. For the purposes of this License, Derivative Works
42
+ shall not include works that remain separable from, or merely link (or bind by
43
+ name) to the interfaces of, the Work and Derivative Works thereof.
44
+
45
+ "Contribution" shall mean any work of authorship, including the original
46
+ version of the Work and any modifications or additions to that Work or
47
+ Derivative Works thereof, that is intentionally submitted to Licensor for
48
+ inclusion in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes of this
50
+ definition, "submitted" means any form of electronic, verbal, or written
51
+ communication sent to the Licensor or its representatives, including but not
52
+ limited to communication on electronic mailing lists, source code control
53
+ systems, and issue tracking systems that are managed by, or on behalf of, the
54
+ Licensor for the purpose of discussing and improving the Work, but excluding
55
+ communication that is conspicuously marked or otherwise designated in writing by
56
+ the copyright owner as "Not a Contribution."
57
+
58
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
59
+ of whom a Contribution has been received by Licensor and subsequently
60
+ incorporated within the Work.
61
+
62
+ 2. Grant of Copyright License. Subject to the terms and conditions of this
63
+ License, each Contributor hereby grants to You a perpetual, worldwide,
64
+ non-exclusive, no-charge, royalty-free, irrevocable copyright license to
65
+ reproduce, prepare Derivative Works of, publicly display, publicly perform,
66
+ sublicense, and distribute the Work and such Derivative Works in Source or
67
+ Object form.
68
+
69
+ 3. Grant of Patent License. Subject to the terms and conditions of this License,
70
+ each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
71
+ no-charge, royalty-free, irrevocable (except as stated in this section) patent
72
+ license to make, have made, use, offer to sell, sell, import, and otherwise
73
+ transfer the Work, where such license applies only to those patent claims
74
+ licensable by such Contributor that are necessarily infringed by their
75
+ Contribution(s) alone or by combination of their Contribution(s) with the Work to
76
+ which such Contribution(s) was submitted. If You institute patent litigation
77
+ against any entity (including a cross-claim or counterclaim in a lawsuit)
78
+ alleging that the Work or a Contribution incorporated within the Work
79
+ constitutes direct or contributory patent infringement, then any patent licenses
80
+ granted to You under this License for that Work shall terminate as of the date
81
+ such litigation is filed.
82
+
83
+ 4. Redistribution. You may reproduce and distribute copies of the Work or
84
+ Derivative Works thereof in any medium, with or without modifications, and in
85
+ Source or Object form, provided that You meet the following conditions:
86
+
87
+ (a) You must give any other recipients of the Work or Derivative Works a copy of
88
+ this License; and
89
+
90
+ (b) You must cause any modified files to carry prominent notices stating that
91
+ You changed the files; and
92
+
93
+ (c) You must retain, in the Source form of any Derivative Works that You
94
+ distribute, all copyright, patent, trademark, and attribution notices from the
95
+ Source form of the Work, excluding those notices that do not pertain to any part
96
+ of the Derivative Works; and
97
+
98
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then
99
+ any Derivative Works that You distribute must include a readable copy of the
100
+ attribution notices contained within such NOTICE file, excluding those notices
101
+ that do not pertain to any part of the Derivative Works, in at least one of the
102
+ following places: within a NOTICE text file distributed as part of the
103
+ Derivative Works; within the Source form or documentation, if provided along
104
+ with the Derivative Works; or, within a display generated by the Derivative
105
+ Works, if and wherever such third-party notices normally appear. The contents of
106
+ the NOTICE file are for informational purposes only and do not modify the
107
+ License. You may add Your own attribution notices within Derivative Works that
108
+ You distribute, alongside or as an addendum to the NOTICE text from the Work,
109
+ provided that such additional attribution notices cannot be construed as
110
+ modifying the License.
111
+
112
+ You may add Your own copyright statement to Your modifications and may provide
113
+ additional or different license terms and conditions for use, reproduction, or
114
+ distribution of Your modifications, or for any such Derivative Works as a whole,
115
+ provided Your use, reproduction, and distribution of the Work otherwise complies
116
+ with the conditions stated in this License.
117
+
118
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any
119
+ Contribution intentionally submitted for inclusion in the Work by You to the
120
+ Licensor shall be under the terms and conditions of this License, without any
121
+ additional terms or conditions. Notwithstanding the above, nothing herein shall
122
+ supersede or modify the terms of any separate license agreement you may have
123
+ executed with Licensor regarding such Contributions.
124
+
125
+ 6. Trademarks. This License does not grant permission to use the trade names,
126
+ trademarks, service marks, or product names of the Licensor, except as required
127
+ for reasonable and customary use in describing the origin of the Work and
128
+ reproducing the content of the NOTICE file.
129
+
130
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
131
+ writing, Licensor provides the Work (and each Contributor provides its
132
+ Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
133
+ KIND, either express or implied, including, without limitation, any warranties or
134
+ conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
135
+ PARTICULAR PURPOSE. You are solely responsible for determining the
136
+ appropriateness of using or redistributing the Work and assume any risks
137
+ associated with Your exercise of permissions under this License.
138
+
139
+ 8. Limitation of Liability. In no event and under no legal theory, whether in
140
+ tort (including negligence), contract, or otherwise, unless required by
141
+ applicable law (such as deliberate and grossly negligent acts) or agreed to in
142
+ writing, shall any Contributor be liable to You for damages, including any
143
+ direct, indirect, special, incidental, or consequential damages of any character
144
+ arising as a result of this License or out of the use or inability to use the
145
+ Work (including but not limited to damages for loss of goodwill, work stoppage,
146
+ computer failure or malfunction, or any and all other commercial damages or
147
+ losses), even if such Contributor has been advised of the possibility of such
148
+ damages.
149
+
150
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or
151
+ Derivative Works thereof, You may choose to offer, and charge a fee for,
152
+ acceptance of support, warranty, indemnity, or other liability obligations
153
+ and/or rights consistent with this License. However, in accepting such
154
+ obligations, You may act only on Your own behalf and on Your sole
155
+ responsibility, not on behalf of any other Contributor, and only if You agree to
156
+ indemnify, defend, and hold each Contributor harmless for any liability incurred
157
+ by, or claims asserted against, such Contributor by reason of your accepting any
158
+ such warranty or additional liability.
159
+
160
+ END OF TERMS AND CONDITIONS
161
+
162
+ APPENDIX: How to apply the Apache License to your work.
163
+
164
+ To apply the Apache License to your work, attach the following boilerplate
165
+ notice, with the fields enclosed by brackets "[]" replaced with your own
166
+ identifying information. (Don't include the brackets!) The text should be
167
+ enclosed in the appropriate comment syntax for the file format. We also
168
+ recommend that a file or class name and description of purpose be included on
169
+ the same "printed page" as the copyright notice for easier identification within
170
+ third-party archives.
171
+
172
+ Copyright [yyyy] [name of copyright owner]
173
+
174
+ Licensed under the Apache License, Version 2.0 (the "License");
175
+ you may not use this file except in compliance with the License.
176
+ You may obtain a copy of the License at
177
+
178
+ http://www.apache.org/licenses/LICENSE-2.0
179
+
180
+ Unless required by applicable law or agreed to in writing, software
181
+ distributed under the License is distributed on an "AS IS" BASIS,
182
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
183
+ See the License for the specific language governing permissions and
184
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,721 @@
1
+ # jobdb
2
+
3
+ A durable workflow library for Go that provides reliable, long-running workflow orchestration with built-in retry logic, timeout handling, and persistent state management.
4
+
5
+ ## What is jobdb?
6
+
7
+ jobdb is a workflow orchestration library that helps you build reliable, distributed workflows. It handles the complexity of managing workflow state, retries, timeouts, and task coordination so you can focus on your business logic.
8
+
9
+ **Key Features:**
10
+ - **Durable Workflows**: Workflow state persists across failures and restarts
11
+ - **Task Orchestration**: Break workflows into reusable task units
12
+ - **Automatic Retries**: Configurable retry policies with exponential backoff
13
+ - **Timeout Management**: Set invocation and total timeout limits
14
+ - **Async Child Workflows**: Spawn and await child workflows
15
+ - **Artifact Support**: Handle large files and binary data efficiently
16
+ - **Multi-Tenant**: Built-in tenant isolation
17
+ - **Job Querying**: List and filter jobs with flexible criteria
18
+ - **Schedules**: First-class recurring jobs with pause/resume/archive support
19
+ - **Embedded SQLite Runtime**: Durable local execution without external services
20
+ - **Remote Runtime Protocol**: REST runtime adapter with tokenized lease operations
21
+
22
+ ## Installation
23
+
24
+ ```bash
25
+ go get github.com/colony-2/jobdb
26
+ ```
27
+
28
+ ## Local Runtime CLI
29
+
30
+ The repo includes a Cobra-based local runtime server at `cmd/jobdb`.
31
+
32
+ Run the default SQLite-backed embedded runtime:
33
+
34
+ ```bash
35
+ go run ./cmd/jobdb --listen 127.0.0.1:9047 --db jobdb.db
36
+ ```
37
+
38
+ The SQLite runtime stores jobs, chapters, artifacts, leases, and schedules in a
39
+ local SQLite database plus a blob directory.
40
+
41
+ Run the in-memory toy runtime explicitly:
42
+
43
+ ```bash
44
+ go run ./cmd/jobdb toy --listen 127.0.0.1:9047
45
+ ```
46
+
47
+ For Go module migration details, including moving embedded direct-runtime users
48
+ to SQLite, see
49
+ [`docs/MIGRATION-SQLITE-EMBEDDED-RUNTIME.md`](docs/MIGRATION-SQLITE-EMBEDDED-RUNTIME.md).
50
+
51
+ ## Quick Start
52
+
53
+ Here's a simple workflow that processes data through multiple tasks:
54
+
55
+ ```go
56
+ package main
57
+
58
+ import (
59
+ "context"
60
+ "log"
61
+
62
+ "github.com/colony-2/jobdb/pkg/jobdb"
63
+ toyruntime "github.com/colony-2/jobdb/pkg/jobdb/runtime/toy"
64
+ )
65
+
66
+ // Define a job worker (orchestrates tasks)
67
+ type DataProcessingJob struct{}
68
+
69
+ func (j DataProcessingJob) Name() string { return "data_processing" }
70
+
71
+ func (j DataProcessingJob) Run(ctx jobdb.JobContext, input jobdb.JobData) (jobdb.JobData, error) {
72
+ // Execute tasks in sequence
73
+ result, err := ctx.DoTask(jobdb.DefaultRunPolicy(), "validate", input)
74
+ if err != nil {
75
+ return nil, err
76
+ }
77
+
78
+ result, err = ctx.DoTask(jobdb.DefaultRunPolicy(), "transform", result)
79
+ if err != nil {
80
+ return nil, err
81
+ }
82
+
83
+ return result, nil
84
+ }
85
+
86
+ // Define task workers
87
+ type ValidateTask struct{}
88
+
89
+ func (t ValidateTask) Name() string { return "validate" }
90
+
91
+ func (t ValidateTask) Run(ctx jobdb.TaskContext, input jobdb.TaskData) (jobdb.TaskData, error) {
92
+ // Your validation logic here
93
+ return input, nil
94
+ }
95
+
96
+ type TransformTask struct{}
97
+
98
+ func (t TransformTask) Name() string { return "transform" }
99
+
100
+ func (t TransformTask) Run(ctx jobdb.TaskContext, input jobdb.TaskData) (jobdb.TaskData, error) {
101
+ // Your transformation logic here
102
+ return input, nil
103
+ }
104
+
105
+ func main() {
106
+ ctx := context.Background()
107
+ runtime := toyruntime.New()
108
+
109
+ // Build the engine
110
+ engine, err := jobdb.NewEngineBuilder().
111
+ WithRuntime(runtime).
112
+ WithWorkerTenantId("my-tenant").
113
+ PlusWorkers(DataProcessingJob{}, ValidateTask{}, TransformTask{}).
114
+ BuildEngine()
115
+ if err != nil {
116
+ log.Fatal(err)
117
+ }
118
+
119
+ // Start the engine worker loop
120
+ go engine.Run(ctx)
121
+
122
+ // Start a job
123
+ input := jobdb.NewTaskDataOrPanic(map[string]interface{}{"value": 42})
124
+ jobKey, err := engine.SubmitJob(ctx, jobdb.SubmitJob{
125
+ TenantId: "my-tenant",
126
+ JobType: "data_processing",
127
+ Data: input,
128
+ })
129
+ if err != nil {
130
+ log.Fatal(err)
131
+ }
132
+
133
+ log.Printf("Started job: %s", jobKey)
134
+ }
135
+ ```
136
+
137
+ ## Core Concepts
138
+
139
+ ### Jobs vs Tasks
140
+
141
+ - **Jobs** are the top-level workflows that orchestrate tasks. A job worker defines the workflow logic.
142
+ - **Tasks** are individual units of work within a job. Task workers implement specific operations.
143
+
144
+ Jobs use `JobContext` to execute tasks, wait, and spawn child workflows. Tasks receive `TaskContext` for execution context.
145
+
146
+ ### JobWorker Interface
147
+
148
+ ```go
149
+ type JobWorker interface {
150
+ Name() string
151
+ Run(JobContext, JobData) (JobData, error)
152
+ }
153
+ ```
154
+
155
+ Your job worker orchestrates the workflow:
156
+
157
+ ```go
158
+ func (j MyJob) Run(ctx jobdb.JobContext, input jobdb.JobData) (jobdb.JobData, error) {
159
+ // Execute tasks
160
+ result, err := ctx.DoTask(policy, "task-name", taskInput)
161
+ if err != nil {
162
+ return nil, err
163
+ }
164
+
165
+ // Wait/sleep
166
+ if err := ctx.AwaitDuration(jobdb.Duration(5 * time.Minute)); err != nil {
167
+ return nil, err
168
+ }
169
+
170
+ // Wait for another job in the same tenant
171
+ if err := ctx.AwaitJobs(childJobID); err != nil {
172
+ return nil, err
173
+ }
174
+
175
+ return result, nil
176
+ }
177
+ ```
178
+
179
+ ### TaskWorker Interface
180
+
181
+ ```go
182
+ type TaskWorker interface {
183
+ Name() string
184
+ Run(TaskContext, TaskData) (TaskData, error)
185
+ }
186
+ ```
187
+
188
+ Your task worker implements a specific operation:
189
+
190
+ ```go
191
+ func (t MyTask) Run(ctx jobdb.TaskContext, input jobdb.TaskData) (jobdb.TaskData, error) {
192
+ // Access job context
193
+ ctx.Logger.Info("processing task", "job", ctx.JobKey, "step", ctx.Step)
194
+
195
+ // Wait if needed
196
+ ctx.AwaitDuration(jobdb.Duration(30 * time.Second))
197
+
198
+ // Return result
199
+ return jobdb.NewTaskData(result)
200
+ }
201
+ ```
202
+
203
+ ## Working with Data
204
+
205
+ ### Creating TaskData
206
+
207
+ ```go
208
+ // From a struct or map
209
+ data, err := jobdb.NewTaskData(map[string]interface{}{
210
+ "userId": 123,
211
+ "action": "process",
212
+ })
213
+
214
+ // Panic version for tests/simple cases
215
+ data := jobdb.NewTaskDataOrPanic(myStruct)
216
+
217
+ // With artifacts
218
+ data, err := jobdb.NewTaskData(payload, artifact1, artifact2)
219
+ ```
220
+
221
+ ### Reading TaskData
222
+
223
+ ```go
224
+ func (t MyTask) Run(ctx jobdb.TaskContext, input jobdb.TaskData) (jobdb.TaskData, error) {
225
+ // Get raw JSON data
226
+ rawData, err := input.GetData()
227
+ if err != nil {
228
+ return nil, err
229
+ }
230
+
231
+ // Unmarshal into your struct
232
+ var payload MyPayload
233
+ if err := json.Unmarshal(rawData, &payload); err != nil {
234
+ return nil, err
235
+ }
236
+
237
+ // Access artifacts
238
+ artifacts, err := input.GetArtifacts()
239
+ if err != nil {
240
+ return nil, err
241
+ }
242
+
243
+ return jobdb.NewTaskData(result)
244
+ }
245
+ ```
246
+
247
+ ## Working with Artifacts
248
+
249
+ Artifacts represent file-like data that flows through workflows. They support lazy loading and automatic cleanup.
250
+
251
+ ### Creating Artifacts
252
+
253
+ ```go
254
+ // From bytes (in-memory)
255
+ artifact := jobdb.NewArtifactFromBytes("config.json", jsonBytes)
256
+
257
+ // From a reader
258
+ artifact := jobdb.NewArtifactFromReader("output.txt", reader, size)
259
+
260
+ // From a file (auto-cleanup enabled)
261
+ artifact, err := jobdb.NewArtifactFromFile("build.tar.gz", "/tmp/build.tar.gz")
262
+
263
+ // From a file (no cleanup)
264
+ artifact, err := jobdb.NewArtifactFromFileNoCleanup("data.csv", "/data/input.csv")
265
+
266
+ // Custom artifact with full control
267
+ artifact := jobdb.NewArtifact("custom.dat",
268
+ func() (io.ReadCloser, int64, error) {
269
+ // Your opener logic
270
+ f, _ := os.Open(path)
271
+ info, _ := f.Stat()
272
+ return f, info.Size(), nil
273
+ },
274
+ func() error {
275
+ // Your cleanup logic
276
+ return os.Remove(path)
277
+ },
278
+ )
279
+ ```
280
+
281
+ ### Using Artifacts
282
+
283
+ ```go
284
+ // Get artifact metadata
285
+ name := artifact.Name() // "output.tar.gz"
286
+ size := artifact.Size() // size in bytes
287
+
288
+ // Stream artifact contents
289
+ rc, err := artifact.Open()
290
+ if err != nil {
291
+ return err
292
+ }
293
+ defer rc.Close()
294
+ // ... read from rc
295
+
296
+ // Write to a file
297
+ err = artifact.SaveToFile(ctx, "/output/file.tar.gz")
298
+
299
+ // Get full contents (use carefully for large files)
300
+ data, err := artifact.Bytes(ctx)
301
+
302
+ // Compute SHA256 hash
303
+ hash, err := artifact.Sha256(ctx)
304
+ ```
305
+
306
+ ### Artifacts in Tasks
307
+
308
+ ```go
309
+ func (t ProcessFileTask) Run(ctx jobdb.TaskContext, input jobdb.TaskData) (jobdb.TaskData, error) {
310
+ artifacts, err := input.GetArtifacts()
311
+ if err != nil {
312
+ return nil, err
313
+ }
314
+
315
+ // Process the first artifact
316
+ if len(artifacts) > 0 {
317
+ inputFile := artifacts[0]
318
+
319
+ // Save to local file for processing
320
+ tmpPath := "/tmp/input.dat"
321
+ if err := inputFile.SaveToFile(context.Background(), tmpPath); err != nil {
322
+ return nil, err
323
+ }
324
+
325
+ // Process the file...
326
+ processFile(tmpPath)
327
+
328
+ // Create output artifact
329
+ outputArtifact, err := jobdb.NewArtifactFromFile("output.dat", "/tmp/output.dat")
330
+ if err != nil {
331
+ return nil, err
332
+ }
333
+
334
+ return jobdb.NewTaskData(result, outputArtifact)
335
+ }
336
+
337
+ return input, nil
338
+ }
339
+ ```
340
+
341
+ ## Retry and Timeout Policies
342
+
343
+ ### RunPolicy Configuration
344
+
345
+ ```go
346
+ policy := jobdb.RunPolicy{
347
+ Retry: jobdb.RetryPolicy{
348
+ InitialInterval: jobdb.Duration(100 * time.Millisecond),
349
+ BackoffCoefficient: 2.0,
350
+ MaximumInterval: jobdb.Duration(30 * time.Second),
351
+ MaximumAttempts: 5,
352
+ NonRetryableErrorTypes: []string{"ValidationError"},
353
+ },
354
+ InvocationTimeout: jobdb.AsDuration(30 * time.Second), // Per attempt
355
+ TotalTimeout: jobdb.AsDuration(10 * time.Minute), // Overall
356
+ }
357
+
358
+ result, err := ctx.DoTask(policy, "my-task", input)
359
+ ```
360
+
361
+ ### Default Policy
362
+
363
+ ```go
364
+ // Use the default policy
365
+ result, err := ctx.DoTask(jobdb.DefaultRunPolicy(), "my-task", input)
366
+
367
+ // Default values:
368
+ // - InvocationTimeout: 30 seconds
369
+ // - TotalTimeout: 30 minutes
370
+ // - InitialInterval: 100ms
371
+ // - BackoffCoefficient: 2.0
372
+ // - MaximumInterval: 30 seconds
373
+ // - MaximumAttempts: 3
374
+ ```
375
+
376
+ ## Error Handling
377
+
378
+ ### Application Errors
379
+
380
+ Regular errors returned from your workers are treated as application errors and will trigger retries according to the retry policy:
381
+
382
+ ```go
383
+ func (t MyTask) Run(ctx jobdb.TaskContext, input jobdb.TaskData) (jobdb.TaskData, error) {
384
+ if err := validateInput(input); err != nil {
385
+ return nil, fmt.Errorf("validation failed: %w", err)
386
+ }
387
+ return result, nil
388
+ }
389
+ ```
390
+
391
+ ### System Errors
392
+
393
+ System errors represent infrastructure failures:
394
+
395
+ ```go
396
+ if err := connectToDatabase(); err != nil {
397
+ return nil, jobdb.NewSystemError(jobdb.SystemErrorPayload{
398
+ Message: "database connection failed",
399
+ Component: "database",
400
+ Code: "connection_error",
401
+ Retryable: true,
402
+ })
403
+ }
404
+ ```
405
+
406
+ ### Non-Retryable Errors
407
+
408
+ Mark errors as non-retryable to stop retry attempts immediately:
409
+
410
+ ```go
411
+ type ValidationError struct {
412
+ error
413
+ }
414
+
415
+ func (e ValidationError) NonRetryable() bool {
416
+ return true
417
+ }
418
+
419
+ // Usage
420
+ if !isValid(input) {
421
+ return nil, ValidationError{errors.New("invalid input")}
422
+ }
423
+ ```
424
+
425
+ ### Checking Error Types
426
+
427
+ ```go
428
+ if jobdb.IsAppError(err) {
429
+ // Handle application error
430
+ }
431
+
432
+ if jobdb.IsSystemError(err) {
433
+ // Handle system error
434
+ }
435
+ ```
436
+
437
+ ## Advanced Features
438
+
439
+ ### Awaiting Jobs
440
+
441
+ Wait for previously submitted jobs before continuing:
442
+
443
+ ```go
444
+ func (j ParentJob) Run(ctx jobdb.JobContext, input jobdb.JobData) (jobdb.JobData, error) {
445
+ if err := ctx.AwaitJobs(childJobID); err != nil {
446
+ return nil, err
447
+ }
448
+
449
+ return input, nil
450
+ }
451
+ ```
452
+
453
+ ### Job Restart
454
+
455
+ Restart a failed job from a specific step:
456
+
457
+ ```go
458
+ newJobKey, err := engine.SubmitRestartJob(ctx, jobdb.SubmitRestartJob{
459
+ PriorJobKey: failedJobKey,
460
+ LastStepToKeep: 5, // Replay from step 6 onwards
461
+ ExtraTaskInput: newInput,
462
+ ExtraTaskOutput: newOutput,
463
+ })
464
+ ```
465
+
466
+ ### Job Cancellation
467
+
468
+ ```go
469
+ err := engine.CancelJob(ctx, jobdb.CancelJob{
470
+ JobKey: jobKey,
471
+ Reason: "user requested cancellation",
472
+ })
473
+ ```
474
+
475
+ ### Checking Job Status
476
+
477
+ ```go
478
+ status, err := engine.CheckJobStatus(ctx, jobKey)
479
+
480
+ switch status {
481
+ case jobdb.JobStatusCompleted:
482
+ // Job finished successfully
483
+ case jobdb.JobStatusActive:
484
+ // Job is running
485
+ case jobdb.JobStatusCancelled:
486
+ // Job was cancelled
487
+ case jobdb.JobStatusReady:
488
+ // Job is ready to run
489
+ }
490
+ ```
491
+
492
+ ### Getting Job Results
493
+
494
+ ```go
495
+ result, err := engine.GetJobResult(ctx, jobKey)
496
+ if err == jobdb.ErrJobNotComplete {
497
+ // Job hasn't completed yet
498
+ return
499
+ }
500
+
501
+ // Use result
502
+ data, _ := result.GetData()
503
+ ```
504
+
505
+ ### Listing Jobs
506
+
507
+ ```go
508
+ resp, err := engine.ListJobs(ctx, jobdb.ListJobsRequest{
509
+ TenantIds: []string{"my-tenant"},
510
+ Statuses: []jobdb.JobStatus{jobdb.JobStatusActive, jobdb.JobStatusCompleted},
511
+ JobTypes: []string{"data-processing"},
512
+ PageSize: 50,
513
+ PageToken: "", // empty for first page
514
+ })
515
+
516
+ for _, job := range resp.Jobs {
517
+ log.Printf("Job %s: %s", job.JobKey, job.Status)
518
+ }
519
+
520
+ // Get next page
521
+ if resp.NextPageToken != "" {
522
+ nextResp, err := engine.ListJobs(ctx, jobdb.ListJobsRequest{
523
+ PageToken: resp.NextPageToken,
524
+ // ... other filters
525
+ })
526
+ }
527
+ ```
528
+
529
+ ### Schedules
530
+
531
+ Schedules are runtime-owned recurring job definitions. A schedule target is the
532
+ same shape as a job start: job type, input `TaskData`, run policy, and app
533
+ metadata. The runtime stores the target, including an artifact snapshot, and
534
+ materializes each occurrence as a normal app job.
535
+
536
+ ```go
537
+ start := time.Now().UTC()
538
+
539
+ info, err := engine.UpsertSchedule(ctx, jobdb.UpsertScheduleRequest{
540
+ TenantId: "my-tenant",
541
+ ScheduleId: "daily-cleanup",
542
+ Trigger: jobdb.ScheduleTrigger{
543
+ Kind: jobdb.ScheduleTriggerInterval,
544
+ Interval: 24 * time.Hour,
545
+ StartAt: &start,
546
+ },
547
+ Target: jobdb.ScheduleTarget{
548
+ JobType: "data-processing",
549
+ Data: jobdb.JobData(jobdb.NewTaskDataOrPanic(map[string]any{"bucket": "reports"})),
550
+ Metadata: json.RawMessage(`{"owner":"analytics"}`),
551
+ },
552
+ OverlapPolicy: jobdb.ScheduleOverlapSerial,
553
+ })
554
+ if err != nil {
555
+ return err
556
+ }
557
+
558
+ log.Printf("next scheduled job: %s", info.NextJobKey)
559
+ ```
560
+
561
+ The schedule API includes `GetSchedule`, `ListSchedules`, `PauseSchedule`,
562
+ `ResumeSchedule`, `ArchiveSchedule`, `TriggerSchedule`, and
563
+ `ListScheduleRuns`. With serial overlap policy, the runtime submits the next
564
+ occurrence before app execution starts, but makes it wait for the previous
565
+ occurrence to complete before it can be leased.
566
+
567
+ ### External Task Completion
568
+
569
+ For tasks that require external input (e.g., human approval), you can complete them externally:
570
+
571
+ ```go
572
+ // Find tasks waiting for capability
573
+ handles, err := engine.FindTasksWaitingForCapability(ctx,
574
+ "approval-job", // job type
575
+ "human-approval", // task type
576
+ []string{"tenant-1"}, // tenants (nil for all)
577
+ )
578
+
579
+ for _, handle := range handles {
580
+ // Get task input
581
+ input, err := handle.Data()
582
+
583
+ // ... process externally ...
584
+
585
+ // Complete the task
586
+ output := jobdb.NewTaskDataOrPanic(approvalResult)
587
+ err = handle.Finish(ctx, output)
588
+ }
589
+ ```
590
+
591
+ ## Engine Configuration
592
+
593
+ ### Builder Options
594
+
595
+ ```go
596
+ runtime := toyruntime.New()
597
+
598
+ engine, err := jobdb.NewEngineBuilder().
599
+ WithRuntime(runtime). // Required
600
+ WithWorkerTenantId("tenant-1"). // Required when running workers
601
+ WithMaxActive(10). // Concurrent task limit
602
+ WithLogger(logger). // Custom logger
603
+ WithAwaitRecycleThreshold(5 * time.Minute). // Await recycle threshold
604
+ PlusWorkers(job1, task1, task2). // Register workers
605
+ PlusWorkers(job2, task3). // Add more workers
606
+ BuildEngine()
607
+ ```
608
+
609
+ ### Registering Workers
610
+
611
+ #### At Engine Build Time
612
+
613
+ Workers can be registered during engine construction:
614
+
615
+ ```go
616
+ builder := jobdb.NewEngineBuilder().
617
+ WithRuntime(runtime).
618
+ WithWorkerTenantId("tenant-1")
619
+
620
+ // Register a job with its tasks
621
+ builder.PlusWorkers(
622
+ MyJobWorker{},
623
+ Task1{},
624
+ Task2{},
625
+ )
626
+
627
+ // Register another job
628
+ builder.PlusWorkers(
629
+ AnotherJobWorker{},
630
+ Task3{},
631
+ )
632
+
633
+ engine, err := builder.BuildEngine()
634
+ ```
635
+
636
+ #### After Engine Start (Dynamic Registration)
637
+
638
+ Workers can also be registered after the engine has started:
639
+
640
+ ```go
641
+ // Engine was built with WithWorkerTenantId("my-tenant") and is already running.
642
+ go engine.Run(ctx)
643
+
644
+ // Create a workset
645
+ workset, err := jobdb.AsWorkSet(
646
+ NewJobWorker{},
647
+ NewTask1{},
648
+ NewTask2{},
649
+ )
650
+ if err != nil {
651
+ log.Fatal(err)
652
+ }
653
+
654
+ // Register dynamically
655
+ err = engine.RegisterWorkers(workset)
656
+ if err != nil {
657
+ log.Fatal(err)
658
+ }
659
+
660
+ // The engine can now process jobs of type NewJobWorker.Name()
661
+ ```
662
+
663
+ This is useful for:
664
+ - Plugin systems where workers are loaded dynamically
665
+ - Multi-tenant systems where different tenants have different workflows
666
+ - Hot-reloading worker implementations without restarting the engine
667
+
668
+ ### Running the Engine
669
+
670
+ ```go
671
+ ctx := context.Background()
672
+
673
+ // Run the engine worker loop (blocks)
674
+ engine.Run(ctx)
675
+
676
+ // Or run in background
677
+ go engine.Run(ctx)
678
+
679
+ // Cancel when done
680
+ ctx, cancel := context.WithCancel(context.Background())
681
+ defer cancel()
682
+
683
+ go engine.Run(ctx)
684
+ // ... do work ...
685
+ cancel() // Gracefully stop the engine
686
+ ```
687
+
688
+ Engines with registered workers must be built with `WithWorkerTenantId`.
689
+ The worker loop polls only that tenant; run a separate engine for another
690
+ tenant.
691
+
692
+ ## Best Practices
693
+
694
+ 1. **Keep Tasks Idempotent**: Tasks may be retried, so ensure they can safely run multiple times
695
+ 2. **Use Appropriate Timeouts**: Set realistic invocation and total timeouts based on expected task duration
696
+ 3. **Handle Large Data with Artifacts**: Use artifacts for files and binary data instead of embedding in TaskData
697
+ 4. **Log Generously**: Use `ctx.Logger` to log progress and debug issues
698
+ 5. **Design for Failure**: Workflows should gracefully handle task failures and retries
699
+ 6. **Clean Up Resources**: Implement proper cleanup in artifact handlers
700
+ 7. **Use Singleton Keys**: For jobs that should only run once (e.g., daily reports)
701
+ 8. **Monitor Job Status**: Use ListJobs and CheckJobStatus to monitor workflow health
702
+
703
+ ## Architecture Notes
704
+
705
+ jobdb can run against several runtime backends:
706
+
707
+ - **SQLite runtime**: Stores workflow state, leases, schedules, Strata row data,
708
+ and blobfs artifacts locally. This is the default embedded runtime and the
709
+ default `jobdb` mode.
710
+ - **Postgres/Strata direct runtime**: Stores workflow state and coordinates
711
+ distributed execution through pgwf, with workflow data and artifacts in
712
+ Strata.
713
+ - **Remote runtime**: Uses the same `WorkflowRuntime` API over REST. The server
714
+ owns lease tokens and schedule preflight; clients and workers stay generic.
715
+
716
+ Multiple engine instances can run concurrently when the selected runtime backend
717
+ supports shared coordination.
718
+
719
+ ## License
720
+
721
+ See LICENSE file for details.
package/install.js ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+
3
+ // This file was generated by GoReleaser. DO NOT EDIT.
4
+
5
+ import { install } from "./lib.js";
6
+ install();
package/lib.js ADDED
@@ -0,0 +1,259 @@
1
+ // This file was generated by GoReleaser. DO NOT EDIT.
2
+ import fs from "fs";
3
+ import crypto from "crypto";
4
+ import http from "http";
5
+ import https from "https";
6
+ import path from "path";
7
+ import JSZip from "jszip";
8
+ import { x as tarExtract } from "tar";
9
+ import { ProxyAgent } from "proxy-agent";
10
+ import { spawnSync } from "child_process";
11
+ import { fileURLToPath } from "url";
12
+
13
+ const { archives, name, version } = JSON.parse(
14
+ fs.readFileSync(new URL("./package.json", import.meta.url), "utf8"),
15
+ );
16
+
17
+ const agent = new ProxyAgent();
18
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
19
+
20
+ const getArchive = () => {
21
+ let target = `${process.platform}-${process.arch}`;
22
+ const archive = archives[target];
23
+ if (!archive) {
24
+ throw new Error(`No archive available for ${target}`);
25
+ }
26
+ return archive;
27
+ };
28
+
29
+ const binDir = path.join(__dirname, "bin");
30
+
31
+ async function extractTar(tarPath, binaries, dir, wrappedIn) {
32
+ try {
33
+ const filesToExtract = wrappedIn
34
+ ? binaries.map((bin) =>
35
+ path.join(wrappedIn, bin).replace(/\\/g, "/"),
36
+ )
37
+ : binaries;
38
+
39
+ await tarExtract({
40
+ file: tarPath,
41
+ cwd: dir,
42
+ filter: (path) => filesToExtract.includes(path),
43
+ });
44
+
45
+ // If wrapped, move files from wrapped directory to bin directory
46
+ if (wrappedIn) {
47
+ const wrappedDir = path.join(dir, wrappedIn);
48
+ for (const binary of binaries) {
49
+ const srcPath = path.join(wrappedDir, binary);
50
+ const destPath = path.join(dir, binary);
51
+ if (fs.existsSync(srcPath)) {
52
+ fs.renameSync(srcPath, destPath);
53
+ }
54
+ }
55
+ // Clean up empty wrapped directory
56
+ try {
57
+ fs.rmSync(wrappedDir, { recursive: true, force: true });
58
+ } catch (err) {
59
+ // Ignore cleanup errors
60
+ }
61
+ }
62
+
63
+ console.log(`Successfully extracted ${binaries} to "${dir}"`);
64
+ } catch (err) {
65
+ throw new Error(`Extraction failed: ${err.message}`);
66
+ }
67
+ }
68
+
69
+ async function extractZip(zipPath, binaries, dir, wrappedIn) {
70
+ try {
71
+ const zipData = fs.readFileSync(zipPath);
72
+ const zip = await JSZip.loadAsync(zipData);
73
+
74
+ for (const binary of binaries) {
75
+ const binaryPath = wrappedIn
76
+ ? path.join(wrappedIn, binary).replace(/\\/g, "/")
77
+ : binary;
78
+
79
+ if (!zip.files[binaryPath]) {
80
+ throw new Error(
81
+ `Error: ${binaryPath} does not exist in ${zipPath}`,
82
+ );
83
+ }
84
+
85
+ const content = await zip.files[binaryPath].async("nodebuffer");
86
+ if (!fs.existsSync(dir)) {
87
+ fs.mkdirSync(dir, { recursive: true });
88
+ }
89
+ const file = path.join(dir, binary);
90
+ fs.writeFileSync(file, content);
91
+ fs.chmodSync(file, "755");
92
+ console.log(`Successfully extracted "${binary}" to "${dir}"`);
93
+ }
94
+ } catch (err) {
95
+ throw new Error(`Extraction failed: ${err.message}`);
96
+ }
97
+ }
98
+
99
+ const run = async (bin) => {
100
+ await install();
101
+ if (process.platform === "win32") {
102
+ bin += ".exe";
103
+ }
104
+ const [, , ...args] = process.argv;
105
+ let result = spawnSync(path.join(binDir, bin), args, {
106
+ cwd: process.cwd(),
107
+ stdio: "inherit",
108
+ });
109
+ if (result.error) {
110
+ console.error(result.error);
111
+ }
112
+ return result.status;
113
+ };
114
+
115
+ const install = async () => {
116
+ try {
117
+ let archive = getArchive();
118
+ if (await exists(archive)) {
119
+ return;
120
+ }
121
+ let tmp = fs.mkdtempSync("archive-");
122
+ let archivePath = path.join(tmp, archive.name);
123
+ await download(archive.url, archivePath);
124
+ verify(archivePath, archive.checksum);
125
+
126
+ if (!fs.existsSync(binDir)) {
127
+ fs.mkdirSync(binDir);
128
+ }
129
+ switch (archive.format) {
130
+ case "binary":
131
+ const bin = path.join(binDir, archive.bins[0]);
132
+ fs.copyFileSync(archivePath, bin);
133
+ fs.chmodSync(bin, 0o755);
134
+ break;
135
+ case "zip":
136
+ await extractZip(
137
+ archivePath,
138
+ archive.bins,
139
+ binDir,
140
+ archive.wrappedIn,
141
+ );
142
+ break;
143
+ case "tar":
144
+ case "tar.gz":
145
+ case "tgz":
146
+ await extractTar(
147
+ archivePath,
148
+ archive.bins,
149
+ binDir,
150
+ archive.wrappedIn,
151
+ );
152
+ break;
153
+ case "tar.zst":
154
+ case "tzst":
155
+ case "tar.xz":
156
+ case "txz":
157
+ default:
158
+ throw new Error(`unsupported format: ${archive.format}`);
159
+ }
160
+ console.log(`Installed ${name} ${version} to ${binDir}`);
161
+ } catch (err) {
162
+ throw new Error(`Installation failed: ${err.message}`);
163
+ }
164
+ };
165
+
166
+ const verify = (filename, checksum) => {
167
+ if (checksum.algorithm == "" || checksum.digest == "") {
168
+ console.warn("Warning: No checksum provided for verification");
169
+ return;
170
+ }
171
+ let digest = crypto
172
+ .createHash(checksum.algorithm)
173
+ .update(fs.readFileSync(filename))
174
+ .digest("hex");
175
+ if (digest != checksum.digest) {
176
+ throw new Error(
177
+ `${filename}: ${checksum.algorithm} does not match, expected ${checksum.digest}, got ${digest}`,
178
+ );
179
+ }
180
+ };
181
+
182
+ const download = async (url, filename, maxRedirects = 10) => {
183
+ try {
184
+ console.log(`Downloading ${url} to ${filename}...`);
185
+ const dir = path.dirname(filename);
186
+ if (!fs.existsSync(dir)) {
187
+ fs.mkdirSync(dir, { recursive: true });
188
+ }
189
+
190
+ return new Promise((resolve, reject) => {
191
+ const parsedUrl = new URL(url);
192
+ const mod = parsedUrl.protocol === "https:" ? https : http;
193
+
194
+ const request = mod.get(url, { agent }, (response) => {
195
+ if (
196
+ response.statusCode >= 300 &&
197
+ response.statusCode < 400 &&
198
+ response.headers.location
199
+ ) {
200
+ if (maxRedirects <= 0) {
201
+ reject(new Error("Too many redirects"));
202
+ return;
203
+ }
204
+ download(response.headers.location, filename, maxRedirects - 1)
205
+ .then(resolve)
206
+ .catch(reject);
207
+ return;
208
+ }
209
+
210
+ if (response.statusCode !== 200) {
211
+ reject(
212
+ new Error(
213
+ `HTTP ${response.statusCode}: ${response.statusMessage}`,
214
+ ),
215
+ );
216
+ return;
217
+ }
218
+
219
+ const writer = fs.createWriteStream(filename);
220
+ response.pipe(writer);
221
+
222
+ writer.on("finish", () => {
223
+ console.log(`Download complete: ${filename}`);
224
+ resolve(dir);
225
+ });
226
+
227
+ writer.on("error", (err) => {
228
+ console.error(`Error writing file: ${err.message}`);
229
+ reject(err);
230
+ });
231
+ });
232
+
233
+ request.on("error", (err) => {
234
+ reject(new Error(`Request failed: ${err.message}`));
235
+ });
236
+
237
+ request.setTimeout(300000, () => {
238
+ request.destroy();
239
+ reject(new Error("Request timed out"));
240
+ });
241
+ });
242
+ } catch (err) {
243
+ throw new Error(`Download failed: ${err.message}`);
244
+ }
245
+ };
246
+
247
+ function exists(archive) {
248
+ if (!fs.existsSync(binDir)) {
249
+ return false;
250
+ }
251
+ return archive.bins.every((bin) => fs.existsSync(path.join(binDir, bin)));
252
+ }
253
+
254
+ export {
255
+ install,
256
+ run,
257
+ getArchive,
258
+ download,
259
+ };
package/package.json CHANGED
@@ -1,13 +1,92 @@
1
1
  {
2
2
  "name": "@colony2/jobdb",
3
- "version": "0.0.1",
4
- "description": "",
5
- "main": "index.js",
3
+ "type": "module",
4
+ "version": "0.0.7",
5
+ "description": "jobdb job system",
6
6
  "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1"
7
+ "postinstall": "node install.js",
8
+ "run": "node run-jobdb.js"
8
9
  },
9
- "keywords": [],
10
- "author": "",
11
- "license": "ISC",
12
- "type": "commonjs"
13
- }
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/colony-2/jobdb.git"
13
+ },
14
+ "author": {
15
+ "email": "noreply@colony2.com",
16
+ "name": "Colony 2"
17
+ },
18
+ "license": "Apache-2.0",
19
+ "bugs": {
20
+ "url": "https://github.com/colony-2/jobdb/issues"
21
+ },
22
+ "homepage": "https://github.com/colony-2/jobdb",
23
+ "bin": {
24
+ "jobdb": "run-jobdb.js"
25
+ },
26
+ "dependencies": {
27
+ "jszip": "3.10.1",
28
+ "proxy-agent": "8.0.1",
29
+ "tar": "7.5.15"
30
+ },
31
+ "archives": {
32
+ "darwin-arm64": {
33
+ "name": "jobdb_0.0.7_Darwin_arm64.tar.gz",
34
+ "url": "https://github.com/colony-2/jobdb/releases/download/v0.0.7/jobdb_0.0.7_Darwin_arm64.tar.gz",
35
+ "bins": [
36
+ "jobdb"
37
+ ],
38
+ "format": "tar.gz",
39
+ "checksum": {
40
+ "algorithm": "sha256",
41
+ "digest": "462f01b3754e85129d7564cf5e7dddc03e68539e535aff01de60db26277c78e2"
42
+ }
43
+ },
44
+ "darwin-x64": {
45
+ "name": "jobdb_0.0.7_Darwin_x86_64.tar.gz",
46
+ "url": "https://github.com/colony-2/jobdb/releases/download/v0.0.7/jobdb_0.0.7_Darwin_x86_64.tar.gz",
47
+ "bins": [
48
+ "jobdb"
49
+ ],
50
+ "format": "tar.gz",
51
+ "checksum": {
52
+ "algorithm": "sha256",
53
+ "digest": "0982242b1a0aa33553c966e823c81bfd6161558d7500def7e5ba624cf93ce8c9"
54
+ }
55
+ },
56
+ "linux-arm64": {
57
+ "name": "jobdb_0.0.7_Linux_arm64.tar.gz",
58
+ "url": "https://github.com/colony-2/jobdb/releases/download/v0.0.7/jobdb_0.0.7_Linux_arm64.tar.gz",
59
+ "bins": [
60
+ "jobdb"
61
+ ],
62
+ "format": "tar.gz",
63
+ "checksum": {
64
+ "algorithm": "sha256",
65
+ "digest": "d4086e3fd83f8e3eb9227a70fbd14954950600a16918042626c68a1e976a0545"
66
+ }
67
+ },
68
+ "linux-x64": {
69
+ "name": "jobdb_0.0.7_Linux_x86_64.tar.gz",
70
+ "url": "https://github.com/colony-2/jobdb/releases/download/v0.0.7/jobdb_0.0.7_Linux_x86_64.tar.gz",
71
+ "bins": [
72
+ "jobdb"
73
+ ],
74
+ "format": "tar.gz",
75
+ "checksum": {
76
+ "algorithm": "sha256",
77
+ "digest": "d6eb564436f0a654f8355569db66588d60e21fcedd790601b437ca0712475495"
78
+ }
79
+ }
80
+ },
81
+ "keywords": [
82
+ "sandbox",
83
+ "docker",
84
+ "ai",
85
+ "agent",
86
+ "cli",
87
+ "security"
88
+ ],
89
+ "engines": {
90
+ "node": "\u003e=14.0.0"
91
+ }
92
+ }
package/run-jobdb.js ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+
3
+ // This file was generated by GoReleaser. DO NOT EDIT.
4
+
5
+ import { run } from "./lib.js";
6
+ run("jobdb").then((code) => process.exit(code));