@yieldkit/jobs 0.2.0 → 0.3.0
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/README.md +17 -0
- package/dist/errors.d.ts +16 -0
- package/dist/errors.js +9 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -2
- package/dist/ledger-memory-history.js +82 -0
- package/dist/ledger-memory.js +8 -14
- package/dist/ledger-page.js +114 -0
- package/dist/ledger-sql-history.js +104 -0
- package/dist/ledger-sql.js +2 -35
- package/dist/ledger-types.d.ts +35 -0
- package/dist/ledger.d.ts +14 -2
- package/dist/ledger.js +4 -1
- package/dist/migrations.js +14 -1
- package/dist/storage-options.js +1 -0
- package/docs/logs-and-metrics.md +1 -0
- package/docs/storage.md +21 -13
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -245,6 +245,23 @@ export const backfill = runJob(syncOrders, { trigger: 'manual', params: { limit:
|
|
|
245
245
|
);
|
|
246
246
|
```
|
|
247
247
|
|
|
248
|
+
### Look up a run and page through history
|
|
249
|
+
|
|
250
|
+
```ts
|
|
251
|
+
import { JobRuns } from '@yieldkit/jobs';
|
|
252
|
+
import { Effect } from 'effect';
|
|
253
|
+
|
|
254
|
+
export const history = Effect.gen(function* () {
|
|
255
|
+
const runs = yield* JobRuns;
|
|
256
|
+
const job = 'sync-orders';
|
|
257
|
+
const run = yield* runs.get({ job, runKey: '2026-11-25T10:00Z' });
|
|
258
|
+
const page = yield* runs.page({ job, limit: 20 });
|
|
259
|
+
return { run, page };
|
|
260
|
+
});
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
`get` returns `Option.none()` for a missing key. Pass `page.nextCursor` as `cursor` with the same job filter to load more history. A `null` cursor marks the last page. See [storage and the run ledger](docs/storage.md#jobruns).
|
|
264
|
+
|
|
248
265
|
### Record something in the same transaction as the settle
|
|
249
266
|
|
|
250
267
|
<!-- prettier-ignore -->
|
package/dist/errors.d.ts
CHANGED
|
@@ -191,4 +191,20 @@ declare const JobsNotMigratedError_base: Schema.Class<JobsNotMigratedError, Sche
|
|
|
191
191
|
* is accepted.
|
|
192
192
|
*/
|
|
193
193
|
export declare class JobsNotMigratedError extends JobsNotMigratedError_base {}
|
|
194
|
+
declare const InvalidRunCursor_base: Schema.Class<InvalidRunCursor, Schema.TaggedStruct<"InvalidRunCursor", {
|
|
195
|
+
/**
|
|
196
|
+
* Description of the invalid cursor.
|
|
197
|
+
*/
|
|
198
|
+
readonly message: Schema.String;
|
|
199
|
+
}>, import("effect/Cause").YieldableError & {
|
|
200
|
+
/**
|
|
201
|
+
* Nominal marker: only values built by this class's constructor satisfy the type, never a
|
|
202
|
+
* structurally similar object.
|
|
203
|
+
*/
|
|
204
|
+
readonly brand: unique symbol;
|
|
205
|
+
}>;
|
|
206
|
+
/**
|
|
207
|
+
* Raised by `JobRuns.page` when the continuation cursor is malformed.
|
|
208
|
+
*/
|
|
209
|
+
export declare class InvalidRunCursor extends InvalidRunCursor_base {}
|
|
194
210
|
export {};
|
package/dist/errors.js
CHANGED
|
@@ -129,4 +129,12 @@ var JobsNotMigratedError = class extends Schema.TaggedError()("JobsNotMigratedEr
|
|
|
129
129
|
*/
|
|
130
130
|
message: Schema.String
|
|
131
131
|
}) {};
|
|
132
|
-
|
|
132
|
+
/**
|
|
133
|
+
* Raised by `JobRuns.page` when the continuation cursor is malformed.
|
|
134
|
+
*/
|
|
135
|
+
var InvalidRunCursor = class extends Schema.TaggedError()("InvalidRunCursor", {
|
|
136
|
+
/**
|
|
137
|
+
* Description of the invalid cursor.
|
|
138
|
+
*/
|
|
139
|
+
message: Schema.String }) {};
|
|
140
|
+
export { ClusterConfigError, DryRunUnsupported, InvalidDispatch, InvalidJobParams, InvalidRunCursor, InvalidRunKey, JobsNotMigratedError, JobsStorageComponent, RUN_CLAIM_LOST_MESSAGE, RUN_CLAIM_LOST_TAG, RunClaimLost, UnknownJobError };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { JobStorageLayerOptions, storage_d_exports } from "./storage.js";
|
|
2
2
|
import { AnyJobDefinition, DailyCadence, DailyWindow, JobApiParamsPolicy, JobCadence, JobContext, JobDefinition, JobServices, JobTrigger, TimeOfDay, defineJob, isApiRequestable, isManualOnceJob } from "./job.js";
|
|
3
|
-
import { ClusterConfigError, DryRunUnsupported, InvalidDispatch, InvalidJobParams, InvalidRunKey, JobsNotMigratedError, JobsStorageComponent, RUN_CLAIM_LOST_MESSAGE, RUN_CLAIM_LOST_TAG, RunClaimLost, UnknownJobError } from "./errors.js";
|
|
3
|
+
import { ClusterConfigError, DryRunUnsupported, InvalidDispatch, InvalidJobParams, InvalidRunCursor, InvalidRunKey, JobsNotMigratedError, JobsStorageComponent, RUN_CLAIM_LOST_MESSAGE, RUN_CLAIM_LOST_TAG, RunClaimLost, UnknownJobError } from "./errors.js";
|
|
4
4
|
import { DecodedJobParams, decodeJobParams, decodeParams, findDisallowedApiParams, parseSetFlags, pickApiParams } from "./params.js";
|
|
5
5
|
import { ClockCadence, ONCE_RUN_KEY, runKeyFor } from "./run-key.js";
|
|
6
6
|
import { MAX_RUN_KEY_LENGTH } from "./calendar.js";
|
|
7
7
|
import { DEFAULT_CRON_CATCH_UP, DEFAULT_DAILY_CHECK_EVERY, DEFAULT_SHARDS_PER_GROUP, JobsPolicy, JobsPolicyOverrides, LeasePolicy, MaintenancePolicy, NextAttemptInput, RetentionPolicy, RetryPolicy, defaultJobsPolicy, heartbeatIntervalFor, nextAttemptAt, onDemandRetryDelay, onceRetryDelay, resolveJobsPolicy } from "./policy.js";
|
|
8
8
|
import { DEFAULT_PREFIX, JobsStorageOptions } from "./storage-options.js";
|
|
9
9
|
import { JobRuns } from "./ledger.js";
|
|
10
|
-
import { ClaimRequest, JobFailureReason, JobRunRecord, JobRunStatus, JobSettleHook, JobSettled, OwnedRun, RecentRunsQuery, RunClaim, RunResult } from "./ledger-types.js";
|
|
10
|
+
import { ClaimRequest, JobFailureReason, JobRunKey, JobRunRecord, JobRunStatus, JobRunsPage, JobRunsPageQuery, JobSettleHook, JobSettled, OwnedRun, RecentRunsQuery, RunClaim, RunResult } from "./ledger-types.js";
|
|
11
11
|
import { JobOutcomeSchema, JobWorkflow, JobWorkflowPayload, MAX_CRASH_ATTEMPTS_TAG, OperatorJobParams, WorkerJobParams, WorkflowJobOutcome, WorkflowParamOverrides, makeJobWorkflow, maxCrashAttemptsMessage } from "./workflow-schema.js";
|
|
12
12
|
import { CreateJobRequest, DispatchFailedJobRequest, FinishJobRequest, JobRequestRecord, JobRequestStatus, JobRequests, UpsertStartedJobRequest } from "./requests.js";
|
|
13
13
|
import { DurableStageOptions, JobStageError, durableStage, toJobStageError } from "./activity.js";
|
|
@@ -19,4 +19,4 @@ import { makeAnyJobWorkflowLayer, makeJobWorkflowLayer } from "./workflow.js";
|
|
|
19
19
|
import { cronForCadence } from "./cron.js";
|
|
20
20
|
import { SchedulerOptions, makeSchedulerLayer, selectWorkerJobs } from "./scheduler.js";
|
|
21
21
|
import { ClusterServices, DEFAULT_SHARD_GROUP, MAINTENANCE_SHARD_GROUP, assignedShardGroupsFor, availableShardGroupsFor, checkShardingConfig, checkWorkerAssignment } from "./cluster.js";
|
|
22
|
-
export { type AnyJobDefinition, type ClaimRequest, type ClockCadence, ClusterConfigError, type ClusterServices, type CreateJobRequest, DEFAULT_CRON_CATCH_UP, DEFAULT_DAILY_CHECK_EVERY, DEFAULT_PREFIX, DEFAULT_SHARDS_PER_GROUP, DEFAULT_SHARD_GROUP, type DailyCadence, type DailyWindow, type DecodedJobParams, type DispatchApiJobWorkflowOptions, type DispatchFailedJobRequest, type DispatchJobOptions, type DispatchedApiJobWorkflow, type DispatchedJob, DryRunUnsupported, type DurableStageOptions, type FinishJobRequest, InvalidDispatch, InvalidJobParams, InvalidRunKey, type JobApiParamsPolicy, type JobCadence, type JobContext, type JobDefinition, type JobFailureReason, type JobLogContext, type JobLoggingOptions, type JobOutcome, JobOutcomeSchema, JobRequestRecord, type JobRequestStatus, JobRequests, JobRunRecord, JobRunStatus, JobRuns, type JobServices, type JobSettleHook, type JobSettled, JobStageError, storage_d_exports as JobStorage, type JobStorageLayerOptions, JobTrigger, type JobWorkflow, JobWorkflowPayload, JobsNotMigratedError, type JobsPolicy, type JobsPolicyOverrides, JobsStorageComponent, type JobsStorageOptions, type LeasePolicy, MAINTENANCE_SHARD_GROUP, MAX_CRASH_ATTEMPTS_TAG, MAX_RUN_KEY_LENGTH, type MaintenancePolicy, type NextAttemptInput, ONCE_RUN_KEY, type OperatorJobParams, type OwnedRun, RUN_CLAIM_LOST_MESSAGE, RUN_CLAIM_LOST_TAG, type RecentRunsQuery, type RetentionPolicy, type RetryPolicy, type RunClaim, RunClaimLost, type RunJobOptions, type RunResult, type SchedulerOptions, type SkipReason, type TimeOfDay, UnknownJobError, type UpsertStartedJobRequest, WorkerJobParams, type WorkflowJobOutcome, type WorkflowParamOverrides, assignedShardGroupsFor, availableShardGroupsFor, checkShardingConfig, checkWorkerAssignment, cronForCadence, decodeJobParams, decodeParams, defaultJobsPolicy, defineJob, dispatchApiJobWorkflow, dispatchJob, durableStage, findDisallowedApiParams, generateJobRunId, heartbeatIntervalFor, isApiRequestable, isManualOnceJob, jobDurationMs, jobLeaseLostTotal, jobRunsTotal, makeAnyJobWorkflowLayer, makeJobWorkflow, makeJobWorkflowLayer, makeSchedulerLayer, maxCrashAttemptsMessage, nextAttemptAt, onDemandRetryDelay, onceRetryDelay, parseSetFlags, pickApiParams, resolveJobsPolicy, runAnyJob, runJob, runKeyFor, selectWorkerJobs, toJobStageError, withJobContext, withJobLogging, withJobStage };
|
|
22
|
+
export { type AnyJobDefinition, type ClaimRequest, type ClockCadence, ClusterConfigError, type ClusterServices, type CreateJobRequest, DEFAULT_CRON_CATCH_UP, DEFAULT_DAILY_CHECK_EVERY, DEFAULT_PREFIX, DEFAULT_SHARDS_PER_GROUP, DEFAULT_SHARD_GROUP, type DailyCadence, type DailyWindow, type DecodedJobParams, type DispatchApiJobWorkflowOptions, type DispatchFailedJobRequest, type DispatchJobOptions, type DispatchedApiJobWorkflow, type DispatchedJob, DryRunUnsupported, type DurableStageOptions, type FinishJobRequest, InvalidDispatch, InvalidJobParams, InvalidRunCursor, InvalidRunKey, type JobApiParamsPolicy, type JobCadence, type JobContext, type JobDefinition, type JobFailureReason, type JobLogContext, type JobLoggingOptions, type JobOutcome, JobOutcomeSchema, JobRequestRecord, type JobRequestStatus, JobRequests, type JobRunKey, JobRunRecord, JobRunStatus, JobRuns, type JobRunsPage, type JobRunsPageQuery, type JobServices, type JobSettleHook, type JobSettled, JobStageError, storage_d_exports as JobStorage, type JobStorageLayerOptions, JobTrigger, type JobWorkflow, JobWorkflowPayload, JobsNotMigratedError, type JobsPolicy, type JobsPolicyOverrides, JobsStorageComponent, type JobsStorageOptions, type LeasePolicy, MAINTENANCE_SHARD_GROUP, MAX_CRASH_ATTEMPTS_TAG, MAX_RUN_KEY_LENGTH, type MaintenancePolicy, type NextAttemptInput, ONCE_RUN_KEY, type OperatorJobParams, type OwnedRun, RUN_CLAIM_LOST_MESSAGE, RUN_CLAIM_LOST_TAG, type RecentRunsQuery, type RetentionPolicy, type RetryPolicy, type RunClaim, RunClaimLost, type RunJobOptions, type RunResult, type SchedulerOptions, type SkipReason, type TimeOfDay, UnknownJobError, type UpsertStartedJobRequest, WorkerJobParams, type WorkflowJobOutcome, type WorkflowParamOverrides, assignedShardGroupsFor, availableShardGroupsFor, checkShardingConfig, checkWorkerAssignment, cronForCadence, decodeJobParams, decodeParams, defaultJobsPolicy, defineJob, dispatchApiJobWorkflow, dispatchJob, durableStage, findDisallowedApiParams, generateJobRunId, heartbeatIntervalFor, isApiRequestable, isManualOnceJob, jobDurationMs, jobLeaseLostTotal, jobRunsTotal, makeAnyJobWorkflowLayer, makeJobWorkflow, makeJobWorkflowLayer, makeSchedulerLayer, maxCrashAttemptsMessage, nextAttemptAt, onDemandRetryDelay, onceRetryDelay, parseSetFlags, pickApiParams, resolveJobsPolicy, runAnyJob, runJob, runKeyFor, selectWorkerJobs, toJobStageError, withJobContext, withJobLogging, withJobStage };
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { storage_exports } from "./storage.js";
|
|
2
2
|
import { JobTrigger, defineJob, isApiRequestable, isManualOnceJob } from "./job.js";
|
|
3
|
-
import { ClusterConfigError, DryRunUnsupported, InvalidDispatch, InvalidJobParams, InvalidRunKey, JobsNotMigratedError, JobsStorageComponent, RUN_CLAIM_LOST_MESSAGE, RUN_CLAIM_LOST_TAG, RunClaimLost, UnknownJobError } from "./errors.js";
|
|
3
|
+
import { ClusterConfigError, DryRunUnsupported, InvalidDispatch, InvalidJobParams, InvalidRunCursor, InvalidRunKey, JobsNotMigratedError, JobsStorageComponent, RUN_CLAIM_LOST_MESSAGE, RUN_CLAIM_LOST_TAG, RunClaimLost, UnknownJobError } from "./errors.js";
|
|
4
4
|
import { decodeJobParams, decodeParams, findDisallowedApiParams, parseSetFlags, pickApiParams } from "./params.js";
|
|
5
5
|
import { ONCE_RUN_KEY, runKeyFor } from "./run-key.js";
|
|
6
6
|
import { MAX_RUN_KEY_LENGTH } from "./calendar.js";
|
|
@@ -19,4 +19,4 @@ import { dispatchApiJobWorkflow, dispatchJob } from "./dispatch.js";
|
|
|
19
19
|
import { cronForCadence } from "./cron.js";
|
|
20
20
|
import { makeSchedulerLayer, selectWorkerJobs } from "./scheduler.js";
|
|
21
21
|
import { DEFAULT_SHARD_GROUP, MAINTENANCE_SHARD_GROUP, assignedShardGroupsFor, availableShardGroupsFor, checkShardingConfig, checkWorkerAssignment } from "./cluster.js";
|
|
22
|
-
export { ClusterConfigError, DEFAULT_CRON_CATCH_UP, DEFAULT_DAILY_CHECK_EVERY, DEFAULT_PREFIX, DEFAULT_SHARDS_PER_GROUP, DEFAULT_SHARD_GROUP, DryRunUnsupported, InvalidDispatch, InvalidJobParams, InvalidRunKey, JobOutcomeSchema, JobRequestRecord, JobRequests, JobRunRecord, JobRunStatus, JobRuns, JobStageError, storage_exports as JobStorage, JobTrigger, JobWorkflowPayload, JobsNotMigratedError, JobsStorageComponent, MAINTENANCE_SHARD_GROUP, MAX_CRASH_ATTEMPTS_TAG, MAX_RUN_KEY_LENGTH, ONCE_RUN_KEY, RUN_CLAIM_LOST_MESSAGE, RUN_CLAIM_LOST_TAG, RunClaimLost, UnknownJobError, WorkerJobParams, assignedShardGroupsFor, availableShardGroupsFor, checkShardingConfig, checkWorkerAssignment, cronForCadence, decodeJobParams, decodeParams, defaultJobsPolicy, defineJob, dispatchApiJobWorkflow, dispatchJob, durableStage, findDisallowedApiParams, generateJobRunId, heartbeatIntervalFor, isApiRequestable, isManualOnceJob, jobDurationMs, jobLeaseLostTotal, jobRunsTotal, makeAnyJobWorkflowLayer, makeJobWorkflow, makeJobWorkflowLayer, makeSchedulerLayer, maxCrashAttemptsMessage, nextAttemptAt, onDemandRetryDelay, onceRetryDelay, parseSetFlags, pickApiParams, resolveJobsPolicy, runAnyJob, runJob, runKeyFor, selectWorkerJobs, toJobStageError, withJobContext, withJobLogging, withJobStage };
|
|
22
|
+
export { ClusterConfigError, DEFAULT_CRON_CATCH_UP, DEFAULT_DAILY_CHECK_EVERY, DEFAULT_PREFIX, DEFAULT_SHARDS_PER_GROUP, DEFAULT_SHARD_GROUP, DryRunUnsupported, InvalidDispatch, InvalidJobParams, InvalidRunCursor, InvalidRunKey, JobOutcomeSchema, JobRequestRecord, JobRequests, JobRunRecord, JobRunStatus, JobRuns, JobStageError, storage_exports as JobStorage, JobTrigger, JobWorkflowPayload, JobsNotMigratedError, JobsStorageComponent, MAINTENANCE_SHARD_GROUP, MAX_CRASH_ATTEMPTS_TAG, MAX_RUN_KEY_LENGTH, ONCE_RUN_KEY, RUN_CLAIM_LOST_MESSAGE, RUN_CLAIM_LOST_TAG, RunClaimLost, UnknownJobError, WorkerJobParams, assignedShardGroupsFor, availableShardGroupsFor, checkShardingConfig, checkWorkerAssignment, cronForCadence, decodeJobParams, decodeParams, defaultJobsPolicy, defineJob, dispatchApiJobWorkflow, dispatchJob, durableStage, findDisallowedApiParams, generateJobRunId, heartbeatIntervalFor, isApiRequestable, isManualOnceJob, jobDurationMs, jobLeaseLostTotal, jobRunsTotal, makeAnyJobWorkflowLayer, makeJobWorkflow, makeJobWorkflowLayer, makeSchedulerLayer, maxCrashAttemptsMessage, nextAttemptAt, onDemandRetryDelay, onceRetryDelay, parseSetFlags, pickApiParams, resolveJobsPolicy, runAnyJob, runJob, runKeyFor, selectWorkerJobs, toJobStageError, withJobContext, withJobLogging, withJobStage };
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { decodeRunPageCursor, makeRunsPage, pageLimit, runTimestampMicros } from "./ledger-page.js";
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
// src/ledger-memory-history.ts
|
|
4
|
+
/**
|
|
5
|
+
* Formats the collision-free composite `Map` key for `(job, runKey)`.
|
|
6
|
+
*/
|
|
7
|
+
const rowKey = (job, runKey) => JSON.stringify([job, runKey]);
|
|
8
|
+
/**
|
|
9
|
+
* Copies a nullable `Date` so callers cannot mutate ledger timestamps.
|
|
10
|
+
*/
|
|
11
|
+
const cloneDate = (value) => value === null ? null : new Date(value.getTime());
|
|
12
|
+
/**
|
|
13
|
+
* Returns a detached copy of a stored `JobRunRecord`.
|
|
14
|
+
*/
|
|
15
|
+
const cloneRunRecord = (record) => ({
|
|
16
|
+
...record,
|
|
17
|
+
nextAttemptAt: cloneDate(record.nextAttemptAt),
|
|
18
|
+
params: structuredClone(record.params),
|
|
19
|
+
stats: structuredClone(record.stats),
|
|
20
|
+
startedAt: new Date(record.startedAt.getTime()),
|
|
21
|
+
finishedAt: cloneDate(record.finishedAt)
|
|
22
|
+
});
|
|
23
|
+
/**
|
|
24
|
+
* Encodes text as UTF-8 for the bytewise comparison used by the SQL ledger.
|
|
25
|
+
*/
|
|
26
|
+
const utf8 = new TextEncoder();
|
|
27
|
+
/**
|
|
28
|
+
* Compares text in descending UTF-8 byte order, matching PostgreSQL's C collation.
|
|
29
|
+
*/
|
|
30
|
+
const compareTextDescending = (left, right) => {
|
|
31
|
+
if (left === right) return 0;
|
|
32
|
+
const leftBytes = utf8.encode(left);
|
|
33
|
+
const rightBytes = utf8.encode(right);
|
|
34
|
+
for (const [index, leftByte] of leftBytes.entries()) {
|
|
35
|
+
const rightByte = rightBytes[index];
|
|
36
|
+
if (rightByte === void 0) return -1;
|
|
37
|
+
if (leftByte !== rightByte) return rightByte - leftByte;
|
|
38
|
+
}
|
|
39
|
+
return rightBytes.length - leftBytes.length;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Compares cursor positions in history order, newest first.
|
|
43
|
+
*/
|
|
44
|
+
const compareRunPositions = (left, right) => {
|
|
45
|
+
if (left.startedAtMicros !== right.startedAtMicros) return left.startedAtMicros > right.startedAtMicros ? -1 : 1;
|
|
46
|
+
return compareTextDescending(left.runKey, right.runKey) || compareTextDescending(left.job, right.job);
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* Projects matching rows into their history sort position.
|
|
50
|
+
*/
|
|
51
|
+
const matchingRuns = (store, job) => store.values().filter(({ record }) => job === void 0 || record.job === job).map(({ record }) => ({
|
|
52
|
+
run: record,
|
|
53
|
+
startedAtMicros: runTimestampMicros(record.startedAt),
|
|
54
|
+
job: record.job,
|
|
55
|
+
runKey: record.runKey
|
|
56
|
+
}));
|
|
57
|
+
/**
|
|
58
|
+
* Returns the newest rows in the SQL ledger's keyset order.
|
|
59
|
+
*/
|
|
60
|
+
const recentMemory = (store, query) => Effect.sync(() => {
|
|
61
|
+
const limit = pageLimit(query.limit);
|
|
62
|
+
if (limit === 0) return [];
|
|
63
|
+
return matchingRuns(store, query.job).toArray().toSorted(compareRunPositions).slice(0, limit).map(({ run }) => cloneRunRecord(run));
|
|
64
|
+
});
|
|
65
|
+
/**
|
|
66
|
+
* Returns rows strictly after the optional cursor using the SQL ledger's keyset order.
|
|
67
|
+
*/
|
|
68
|
+
const pageMemory = Effect.fnUntraced(function* (store, query) {
|
|
69
|
+
const after = yield* decodeRunPageCursor(query.cursor);
|
|
70
|
+
const limit = pageLimit(query.limit);
|
|
71
|
+
if (limit === 0) return {
|
|
72
|
+
runs: [],
|
|
73
|
+
nextCursor: null
|
|
74
|
+
};
|
|
75
|
+
const eligible = matchingRuns(store, query.job).filter((row) => after === void 0 || compareRunPositions(row, after) > 0).toArray();
|
|
76
|
+
const page = makeRunsPage(eligible.toSorted(compareRunPositions), limit);
|
|
77
|
+
return {
|
|
78
|
+
...page,
|
|
79
|
+
runs: page.runs.map(cloneRunRecord)
|
|
80
|
+
};
|
|
81
|
+
});
|
|
82
|
+
export { cloneRunRecord, pageMemory, recentMemory, rowKey };
|
package/dist/ledger-memory.js
CHANGED
|
@@ -1,15 +1,12 @@
|
|
|
1
|
+
import { cloneRunRecord, pageMemory, recentMemory, rowKey } from "./ledger-memory-history.js";
|
|
1
2
|
import { failedNextAttemptAt } from "./ledger-retry.js";
|
|
2
3
|
import { JobRuns } from "./ledger.js";
|
|
3
4
|
import { decideClaim, resolveJobsPolicy } from "./policy.js";
|
|
4
5
|
import { bindSettleHook } from "./settle-hook.js";
|
|
5
|
-
import { Clock, DateTime, Duration, Effect, Layer } from "effect";
|
|
6
|
+
import { Clock, DateTime, Duration, Effect, Layer, Option } from "effect";
|
|
6
7
|
import { SecureRandom } from "effect/crypto";
|
|
7
8
|
// src/ledger-memory.ts
|
|
8
9
|
/**
|
|
9
|
-
* Formats the composite `Map` key for `(job, runKey)`.
|
|
10
|
-
*/
|
|
11
|
-
const rowKey = (job, runKey) => `${job}\0${runKey}`;
|
|
12
|
-
/**
|
|
13
10
|
* Returns the row of `run` while it is still `running` under `run.token`, or `undefined` once it
|
|
14
11
|
* settled, vanished, or another claim rotated the token.
|
|
15
12
|
*/
|
|
@@ -210,15 +207,12 @@ const makeJobRunsMemory = (options) => Effect.gen(function* () {
|
|
|
210
207
|
retry: policy.retry
|
|
211
208
|
}, run, result).pipe(Effect.flatMap((event) => event === void 0 && isSettledByClaim(store, run, result) ? Effect.succeed(true) : runMemoryHook(hook, event))),
|
|
212
209
|
isCompleted: (job, runKey) => Effect.sync(() => store.get(rowKey(job, runKey))?.record.status === "completed"),
|
|
213
|
-
|
|
214
|
-
const
|
|
215
|
-
|
|
216
|
-
return [...store.values()].flatMap(({ record }) => query.job === void 0 || record.job === query.job ? [record] : []).toSorted((left, right) => {
|
|
217
|
-
const timeDiff = right.startedAt.getTime() - left.startedAt.getTime();
|
|
218
|
-
if (timeDiff !== 0) return timeDiff;
|
|
219
|
-
return right.runKey.localeCompare(left.runKey);
|
|
220
|
-
}).slice(0, limit);
|
|
210
|
+
get: ({ job, runKey }) => Effect.sync(() => {
|
|
211
|
+
const existing = store.get(rowKey(job, runKey));
|
|
212
|
+
return existing === void 0 ? Option.none() : Option.some(cloneRunRecord(existing.record));
|
|
221
213
|
}),
|
|
214
|
+
recent: (query) => recentMemory(store, query),
|
|
215
|
+
page: (query) => pageMemory(store, query),
|
|
222
216
|
prune: (jobs, olderThan) => Effect.gen(function* () {
|
|
223
217
|
if (jobs.length === 0) return 0;
|
|
224
218
|
const cutoffMs = (yield* Clock.currentTimeMillis) - Math.max(0, Duration.toMillis(Duration.fromInputUnsafe(olderThan)));
|
|
@@ -240,7 +234,7 @@ const makeJobRunsMemory = (options) => Effect.gen(function* () {
|
|
|
240
234
|
return makeService(random, bindSettleHook(options?.onSettle, context));
|
|
241
235
|
})).pipe(Layer.provideMerge(SecureRandom.layerWebCrypto)),
|
|
242
236
|
settles: () => [...settleLog],
|
|
243
|
-
rows: () => [...store.values()].map((entry) => entry.record)
|
|
237
|
+
rows: () => [...store.values()].map((entry) => cloneRunRecord(entry.record))
|
|
244
238
|
};
|
|
245
239
|
});
|
|
246
240
|
export { makeJobRunsMemory };
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { InvalidRunCursor } from "./errors.js";
|
|
2
|
+
import { Effect, Schema, SchemaIssue, SchemaTransformation } from "effect";
|
|
3
|
+
// src/ledger-page.ts
|
|
4
|
+
/**
|
|
5
|
+
* Start of PostgreSQL's timestamp epoch, in Unix milliseconds for JavaScript dates.
|
|
6
|
+
*/
|
|
7
|
+
const POSTGRES_EPOCH_MS = Date.UTC(2e3, 0, 1);
|
|
8
|
+
/**
|
|
9
|
+
* PostgreSQL stores timestamps in microseconds; JavaScript clocks have millisecond precision.
|
|
10
|
+
*/
|
|
11
|
+
const MICROS_PER_MILLISECOND = 1000n;
|
|
12
|
+
/**
|
|
13
|
+
* Microseconds per 24-hour UTC day, used to reconstruct a PostgreSQL timestamp exactly.
|
|
14
|
+
*/
|
|
15
|
+
const MICROS_PER_DAY = 86400000000n;
|
|
16
|
+
/**
|
|
17
|
+
* PostgreSQL's first finite timestamp, in microseconds since its epoch.
|
|
18
|
+
*/
|
|
19
|
+
const MIN_TIMESTAMP_MICROS = -211813488000000000n;
|
|
20
|
+
/**
|
|
21
|
+
* PostgreSQL's last finite timestamp, in microseconds since its epoch.
|
|
22
|
+
*
|
|
23
|
+
* @see https://doxygen.postgresql.org/datatype_2timestamp_8h_source.html
|
|
24
|
+
*/
|
|
25
|
+
const MAX_TIMESTAMP_MICROS = 9223371331199999999n;
|
|
26
|
+
/**
|
|
27
|
+
* Unpadded URL-safe base64 alphabet used by cursor tokens.
|
|
28
|
+
*/
|
|
29
|
+
const BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/u;
|
|
30
|
+
/**
|
|
31
|
+
* Strict UTF-8 decoder rejecting invalid byte sequences instead of replacing them with U+FFFD.
|
|
32
|
+
*/
|
|
33
|
+
const utf8Decoder = new TextDecoder("utf-8", { fatal: true });
|
|
34
|
+
/**
|
|
35
|
+
* UTF-8 encoder paired with `utf8Decoder` for cursor round-trips.
|
|
36
|
+
*/
|
|
37
|
+
const utf8Encoder = new TextEncoder();
|
|
38
|
+
/**
|
|
39
|
+
* Whether `value` is valid Unicode text that PostgreSQL stores without zero-byte errors or
|
|
40
|
+
* replacement characters.
|
|
41
|
+
*/
|
|
42
|
+
const isPostgresText = (value) => value.isWellFormed() && !value.includes("\0");
|
|
43
|
+
/**
|
|
44
|
+
* Unicode text that can be sent losslessly as a PostgreSQL key.
|
|
45
|
+
*/
|
|
46
|
+
const CursorKey = Schema.String.check(Schema.makeFilter(isPostgresText, { description: "a well-formed key without zero bytes" }));
|
|
47
|
+
/**
|
|
48
|
+
* Base64url payload decoded strictly as UTF-8 text.
|
|
49
|
+
*/
|
|
50
|
+
const StrictUtf8FromBase64Url = Schema.Uint8ArrayFromBase64Url.pipe(Schema.decodeTo(Schema.String, SchemaTransformation.transformEffect({
|
|
51
|
+
decode: (bytes, options) => Effect.try({
|
|
52
|
+
try: () => utf8Decoder.decode(bytes),
|
|
53
|
+
catch: () => new SchemaIssue.InvalidValue({ message: "Invalid UTF-8" }, bytes, options)
|
|
54
|
+
}),
|
|
55
|
+
encode: (text) => Effect.succeed(utf8Encoder.encode(text))
|
|
56
|
+
})));
|
|
57
|
+
/**
|
|
58
|
+
* Finite PostgreSQL timestamp in microseconds since 2000-01-01 UTC, encoded as decimal text.
|
|
59
|
+
*/
|
|
60
|
+
const RunTimestampMicros = Schema.BigIntFromString.check(Schema.isGreaterThanOrEqualToBigInt(MIN_TIMESTAMP_MICROS), Schema.isLessThanOrEqualToBigInt(MAX_TIMESTAMP_MICROS));
|
|
61
|
+
/**
|
|
62
|
+
* Base64url JSON carrying all columns in the history sort order.
|
|
63
|
+
*/
|
|
64
|
+
const RunPageCursor = Schema.String.check(Schema.isPattern(BASE64URL_PATTERN)).pipe(Schema.decodeTo(StrictUtf8FromBase64Url), Schema.decodeTo(Schema.fromJsonString(Schema.Struct({
|
|
65
|
+
/**
|
|
66
|
+
* Full precision of the boundary row's start time.
|
|
67
|
+
*/
|
|
68
|
+
startedAtMicros: RunTimestampMicros,
|
|
69
|
+
/**
|
|
70
|
+
* Run key of the boundary row.
|
|
71
|
+
*/
|
|
72
|
+
runKey: CursorKey,
|
|
73
|
+
/**
|
|
74
|
+
* Job name of the boundary row.
|
|
75
|
+
*/
|
|
76
|
+
job: CursorKey
|
|
77
|
+
}))));
|
|
78
|
+
/**
|
|
79
|
+
* Decodes a continuation token, or starts at the newest run when the token is absent.
|
|
80
|
+
*/
|
|
81
|
+
const decodeRunPageCursor = (cursor) => {
|
|
82
|
+
if (cursor === void 0) return Effect.undefined;
|
|
83
|
+
return Schema.decodeEffect(RunPageCursor)(cursor).pipe(Effect.mapError(() => new InvalidRunCursor({ message: "Invalid run history cursor" })));
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* Truncates finite limits to whole rows and reserves room for one lookahead row. Negative and
|
|
87
|
+
* non-finite limits return zero.
|
|
88
|
+
*/
|
|
89
|
+
const pageLimit = (limit) => Number.isFinite(limit) ? Math.min(Number.MAX_SAFE_INTEGER - 1, Math.max(0, Math.trunc(limit))) : 0;
|
|
90
|
+
/**
|
|
91
|
+
* Returns at most `limit` records, encoding the last returned row when a lookahead row exists.
|
|
92
|
+
*/
|
|
93
|
+
const makeRunsPage = (rows, limit) => {
|
|
94
|
+
const runs = rows.slice(0, limit).map(({ run }) => run);
|
|
95
|
+
const last = rows[limit - 1];
|
|
96
|
+
if (rows.length <= limit || last === void 0) return {
|
|
97
|
+
runs,
|
|
98
|
+
nextCursor: null
|
|
99
|
+
};
|
|
100
|
+
const { job, runKey } = last.run;
|
|
101
|
+
return {
|
|
102
|
+
runs,
|
|
103
|
+
nextCursor: Schema.encodeSync(RunPageCursor)({
|
|
104
|
+
job,
|
|
105
|
+
runKey,
|
|
106
|
+
startedAtMicros: last.startedAtMicros
|
|
107
|
+
})
|
|
108
|
+
};
|
|
109
|
+
};
|
|
110
|
+
/**
|
|
111
|
+
* Converts the memory clock's millisecond timestamp into the shared paging representation.
|
|
112
|
+
*/
|
|
113
|
+
const runTimestampMicros = (startedAt) => (BigInt(startedAt.getTime()) - BigInt(POSTGRES_EPOCH_MS)) * MICROS_PER_MILLISECOND;
|
|
114
|
+
export { MICROS_PER_DAY, RunTimestampMicros, decodeRunPageCursor, isPostgresText, makeRunsPage, pageLimit, runTimestampMicros };
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { MICROS_PER_DAY, RunTimestampMicros, decodeRunPageCursor, isPostgresText, makeRunsPage, pageLimit } from "./ledger-page.js";
|
|
2
|
+
import { JobRunRecord } from "./ledger-types.js";
|
|
3
|
+
import { Effect, Option, Schema } from "effect";
|
|
4
|
+
// src/ledger-sql-history.ts
|
|
5
|
+
/**
|
|
6
|
+
* Public record projection shared by the ledger's history queries.
|
|
7
|
+
*/
|
|
8
|
+
const runRecordColumns = (sql) => sql`
|
|
9
|
+
job,
|
|
10
|
+
run_key AS "runKey",
|
|
11
|
+
execution_id AS "executionId",
|
|
12
|
+
status,
|
|
13
|
+
attempt,
|
|
14
|
+
failures,
|
|
15
|
+
next_attempt_at AS "nextAttemptAt",
|
|
16
|
+
trigger,
|
|
17
|
+
params,
|
|
18
|
+
stats,
|
|
19
|
+
error_message AS "errorMessage",
|
|
20
|
+
started_at AS "startedAt",
|
|
21
|
+
finished_at AS "finishedAt"
|
|
22
|
+
`;
|
|
23
|
+
/**
|
|
24
|
+
* Decodes public run rows. A disagreement between a stored row and the schema is a defect.
|
|
25
|
+
*/
|
|
26
|
+
const decodeRunRecords = (rows) => Schema.decodeUnknownEffect(Schema.Array(JobRunRecord))(rows).pipe(Effect.orDie);
|
|
27
|
+
/**
|
|
28
|
+
* Finds the run under the composite primary key, or returns `None` if it is absent.
|
|
29
|
+
*/
|
|
30
|
+
const getRunSql = ({ sql, runsTable }, key) => {
|
|
31
|
+
if (!isPostgresText(key.job) || !isPostgresText(key.runKey)) return Effect.succeedNone;
|
|
32
|
+
return sql`
|
|
33
|
+
SELECT ${runRecordColumns(sql)}
|
|
34
|
+
FROM ${sql(runsTable)}
|
|
35
|
+
WHERE job = ${key.job} AND run_key = ${key.runKey}
|
|
36
|
+
`.pipe(Effect.flatMap(decodeRunRecords), Effect.map((rows) => Option.fromUndefinedOr(rows[0])));
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Queries recent run ledger rows ordered newest first, optionally filtered to one job. A row that
|
|
40
|
+
* fails to decode as `JobRunRecord` dies: it means the table and the schema disagree, a bug rather
|
|
41
|
+
* than a failure the caller can handle.
|
|
42
|
+
*/
|
|
43
|
+
const queryRecentRunsSql = ({ sql, runsTable }, query) => {
|
|
44
|
+
const limit = pageLimit(query.limit);
|
|
45
|
+
if (limit === 0 || query.job !== void 0 && !isPostgresText(query.job)) return Effect.succeed([]);
|
|
46
|
+
const jobFilter = query.job === void 0 ? sql`` : sql`WHERE job = ${query.job}`;
|
|
47
|
+
return sql`
|
|
48
|
+
SELECT ${runRecordColumns(sql)}
|
|
49
|
+
FROM ${sql(runsTable)}
|
|
50
|
+
${jobFilter}
|
|
51
|
+
ORDER BY started_at DESC, run_key COLLATE "C" DESC, job COLLATE "C" DESC
|
|
52
|
+
LIMIT ${limit}
|
|
53
|
+
`.pipe(Effect.flatMap(decodeRunRecords));
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* History row with the precise start time that the JavaScript Date column cannot represent.
|
|
57
|
+
*/
|
|
58
|
+
const PagedRunRow = Schema.Struct({
|
|
59
|
+
...JobRunRecord.fields,
|
|
60
|
+
/**
|
|
61
|
+
* Exact start time in microseconds since the PostgreSQL epoch.
|
|
62
|
+
*/
|
|
63
|
+
startedAtMicros: RunTimestampMicros
|
|
64
|
+
});
|
|
65
|
+
/**
|
|
66
|
+
* Restricts the query to rows after the cursor. Splitting into days and sub-day microseconds keeps
|
|
67
|
+
* interval arithmetic exact and leaves the indexed `started_at` column bare.
|
|
68
|
+
*/
|
|
69
|
+
const pageBoundarySql = (sql, after) => {
|
|
70
|
+
if (after === void 0) return sql`TRUE`;
|
|
71
|
+
return sql`
|
|
72
|
+
(started_at, run_key COLLATE "C", job COLLATE "C") <
|
|
73
|
+
((DATE '2000-01-01' + ${Number(after.startedAtMicros / MICROS_PER_DAY)}::int + ${Number(after.startedAtMicros % MICROS_PER_DAY)}::double precision * INTERVAL '1 microsecond')
|
|
74
|
+
AT TIME ZONE 'UTC', ${after.runKey}::text, ${after.job}::text)
|
|
75
|
+
`;
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* Reads one keyset page and projects a lossless boundary timestamp for its continuation.
|
|
79
|
+
*/
|
|
80
|
+
const pageRunsSql = Effect.fnUntraced(function* ({ sql, runsTable }, query) {
|
|
81
|
+
const after = yield* decodeRunPageCursor(query.cursor);
|
|
82
|
+
const limit = pageLimit(query.limit);
|
|
83
|
+
if (limit === 0 || query.job !== void 0 && !isPostgresText(query.job)) return {
|
|
84
|
+
runs: [],
|
|
85
|
+
nextCursor: null
|
|
86
|
+
};
|
|
87
|
+
const jobFilter = query.job === void 0 ? sql`TRUE` : sql`job = ${query.job}`;
|
|
88
|
+
const rows = yield* sql`
|
|
89
|
+
SELECT ${runRecordColumns(sql)},
|
|
90
|
+
trunc((EXTRACT(EPOCH FROM started_at) -
|
|
91
|
+
EXTRACT(EPOCH FROM TIMESTAMPTZ '2000-01-01 00:00:00+00')) * 1000000)::text
|
|
92
|
+
AS "startedAtMicros"
|
|
93
|
+
FROM ${sql(runsTable)}
|
|
94
|
+
WHERE ${jobFilter} AND ${pageBoundarySql(sql, after)}
|
|
95
|
+
ORDER BY started_at DESC, run_key COLLATE "C" DESC, job COLLATE "C" DESC
|
|
96
|
+
LIMIT ${limit + 1}
|
|
97
|
+
`;
|
|
98
|
+
const decoded = yield* Schema.decodeUnknownEffect(Schema.Array(PagedRunRow))(rows).pipe(Effect.orDie);
|
|
99
|
+
return makeRunsPage(decoded.map(({ startedAtMicros, ...run }) => ({
|
|
100
|
+
run,
|
|
101
|
+
startedAtMicros
|
|
102
|
+
})), limit);
|
|
103
|
+
});
|
|
104
|
+
export { getRunSql, pageRunsSql, queryRecentRunsSql };
|
package/dist/ledger-sql.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { failedNextAttemptAt } from "./ledger-retry.js";
|
|
2
2
|
import { refusePastDeadlineSql } from "./ledger-sql-deadline.js";
|
|
3
|
-
import {
|
|
3
|
+
import { JobRunStatus } from "./ledger-types.js";
|
|
4
4
|
import { decideClaim } from "./policy.js";
|
|
5
5
|
import { runSettleHook } from "./settle-hook.js";
|
|
6
6
|
import { Effect, Schema } from "effect";
|
|
@@ -296,37 +296,4 @@ const isRunCompletedSql = ({ sql, runsTable }, job, runKey) => sql`
|
|
|
296
296
|
AND run_key = ${runKey}
|
|
297
297
|
AND status = 'completed'
|
|
298
298
|
`.pipe(Effect.map((rows) => rows.length > 0));
|
|
299
|
-
|
|
300
|
-
* Queries recent run ledger rows ordered newest first, optionally filtered to one job. A row that
|
|
301
|
-
* fails to decode as `JobRunRecord` dies: it means the table and the schema disagree, a bug rather
|
|
302
|
-
* than a failure the caller can handle.
|
|
303
|
-
*/
|
|
304
|
-
const queryRecentRunsSql = ({ sql, runsTable }, query) => {
|
|
305
|
-
const limit = Math.max(0, Math.trunc(query.limit));
|
|
306
|
-
if (limit === 0) return Effect.succeed([]);
|
|
307
|
-
const jobFilter = query.job === void 0 ? sql`` : sql`WHERE job = ${query.job}`;
|
|
308
|
-
return Effect.gen(function* () {
|
|
309
|
-
const rows = yield* sql`
|
|
310
|
-
SELECT
|
|
311
|
-
job,
|
|
312
|
-
run_key AS "runKey",
|
|
313
|
-
execution_id AS "executionId",
|
|
314
|
-
status,
|
|
315
|
-
attempt,
|
|
316
|
-
failures,
|
|
317
|
-
next_attempt_at AS "nextAttemptAt",
|
|
318
|
-
trigger,
|
|
319
|
-
params,
|
|
320
|
-
stats,
|
|
321
|
-
error_message AS "errorMessage",
|
|
322
|
-
started_at AS "startedAt",
|
|
323
|
-
finished_at AS "finishedAt"
|
|
324
|
-
FROM ${sql(runsTable)}
|
|
325
|
-
${jobFilter}
|
|
326
|
-
ORDER BY started_at DESC, run_key DESC
|
|
327
|
-
LIMIT ${limit}
|
|
328
|
-
`;
|
|
329
|
-
return yield* Schema.decodeUnknownEffect(Schema.Array(JobRunRecord))(rows).pipe(Effect.orDie);
|
|
330
|
-
});
|
|
331
|
-
};
|
|
332
|
-
export { claimRunSql, heartbeatRunSql, isRunCompletedSql, queryRecentRunsSql, serializeJsonb, settleRunSql };
|
|
299
|
+
export { claimRunSql, heartbeatRunSql, isRunCompletedSql, serializeJsonb, settleRunSql };
|
package/dist/ledger-types.d.ts
CHANGED
|
@@ -325,6 +325,19 @@ export declare const JobRunRecord: Schema.Struct<{
|
|
|
325
325
|
* Decoded run ledger row.
|
|
326
326
|
*/
|
|
327
327
|
export type JobRunRecord = typeof JobRunRecord.Type;
|
|
328
|
+
/**
|
|
329
|
+
* Identifies a run ledger row by its composite key.
|
|
330
|
+
*/
|
|
331
|
+
export type JobRunKey = {
|
|
332
|
+
/**
|
|
333
|
+
* Job name (the ledger's `job` column).
|
|
334
|
+
*/
|
|
335
|
+
readonly job: string;
|
|
336
|
+
/**
|
|
337
|
+
* Ledger run key (the `run_key` column).
|
|
338
|
+
*/
|
|
339
|
+
readonly runKey: string;
|
|
340
|
+
};
|
|
328
341
|
/**
|
|
329
342
|
* Query filter for `JobRuns.recent`.
|
|
330
343
|
*/
|
|
@@ -337,4 +350,26 @@ export type RecentRunsQuery = {
|
|
|
337
350
|
* Maximum number of rows returned, ordered newest first.
|
|
338
351
|
*/
|
|
339
352
|
readonly limit: number;
|
|
353
|
+
};
|
|
354
|
+
/**
|
|
355
|
+
* Query filter for `JobRuns.page`.
|
|
356
|
+
*/
|
|
357
|
+
export type JobRunsPageQuery = RecentRunsQuery & {
|
|
358
|
+
/**
|
|
359
|
+
* Opaque cursor returned by a previous `JobRuns.page` call; omit for the first page.
|
|
360
|
+
*/
|
|
361
|
+
readonly cursor?: string | undefined;
|
|
362
|
+
};
|
|
363
|
+
/**
|
|
364
|
+
* A page of run history and its continuation cursor.
|
|
365
|
+
*/
|
|
366
|
+
export type JobRunsPage = {
|
|
367
|
+
/**
|
|
368
|
+
* Run records ordered newest first.
|
|
369
|
+
*/
|
|
370
|
+
readonly runs: ReadonlyArray<JobRunRecord>;
|
|
371
|
+
/**
|
|
372
|
+
* Pass to the next `JobRuns.page` call with the same job filter, or `null` at the end.
|
|
373
|
+
*/
|
|
374
|
+
readonly nextCursor: string | null;
|
|
340
375
|
};
|
package/dist/ledger.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { InvalidRunCursor } from "./errors.js";
|
|
1
2
|
import "./ledger-sql.js";
|
|
2
|
-
import { ClaimRequest, JobRunRecord, OwnedRun, RecentRunsQuery, RunClaim, RunResult } from "./ledger-types.js";
|
|
3
|
+
import { ClaimRequest, JobRunKey, JobRunRecord, JobRunsPage, JobRunsPageQuery, OwnedRun, RecentRunsQuery, RunClaim, RunResult } from "./ledger-types.js";
|
|
3
4
|
import { JobsPolicy } from "./policy.js";
|
|
4
|
-
import { Context, Duration, Effect } from "effect";
|
|
5
|
+
import { Context, Duration, Effect, Option } from "effect";
|
|
5
6
|
import { SqlError } from "effect/sql";
|
|
6
7
|
declare const JobRuns_base: Context.ServiceClass<JobRuns, "@yieldkit/jobs/JobRuns", {
|
|
7
8
|
/**
|
|
@@ -19,6 +20,11 @@ declare const JobRuns_base: Context.ServiceClass<JobRuns, "@yieldkit/jobs/JobRun
|
|
|
19
20
|
* token returns `true` again without applying it or calling the hook twice.
|
|
20
21
|
*/
|
|
21
22
|
readonly settle: (run: OwnedRun, result: RunResult) => Effect.Effect<boolean, SqlError.SqlError>;
|
|
23
|
+
/**
|
|
24
|
+
* Returns the row for `(job, runKey)`, or `None` when it is absent. As with `recent`, a row
|
|
25
|
+
* that fails to decode as `JobRunRecord` is a defect.
|
|
26
|
+
*/
|
|
27
|
+
readonly get: (key: JobRunKey) => Effect.Effect<Option.Option<JobRunRecord>, SqlError.SqlError>;
|
|
22
28
|
/**
|
|
23
29
|
* Returns `true` when `(job, runKey)` is stored with `status = 'completed'`.
|
|
24
30
|
*/
|
|
@@ -28,6 +34,12 @@ declare const JobRuns_base: Context.ServiceClass<JobRuns, "@yieldkit/jobs/JobRun
|
|
|
28
34
|
* is a defect, not a typed failure.
|
|
29
35
|
*/
|
|
30
36
|
readonly recent: (query: RecentRunsQuery) => Effect.Effect<ReadonlyArray<JobRunRecord>, SqlError.SqlError>;
|
|
37
|
+
/**
|
|
38
|
+
* Pages through run history by descending start time, run key and job. Ties use bytewise text
|
|
39
|
+
* ordering. Pass the returned cursor with the same job filter to continue. A malformed cursor
|
|
40
|
+
* fails with `InvalidRunCursor`; an undecodable ledger row is a defect.
|
|
41
|
+
*/
|
|
42
|
+
readonly page: (query: JobRunsPageQuery) => Effect.Effect<JobRunsPage, SqlError.SqlError | InvalidRunCursor>;
|
|
31
43
|
/**
|
|
32
44
|
* Deletes rows of `jobs` that started more than `olderThan` ago, whatever their status, in
|
|
33
45
|
* batches of `policy.maintenance.batchSize`. Returns the deleted row count.
|
package/dist/ledger.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { getRunSql, pageRunsSql, queryRecentRunsSql } from "./ledger-sql-history.js";
|
|
2
|
+
import { claimRunSql, heartbeatRunSql, isRunCompletedSql, settleRunSql } from "./ledger-sql.js";
|
|
2
3
|
import { Context, Duration, Effect, Schema } from "effect";
|
|
3
4
|
// src/ledger.ts
|
|
4
5
|
/**
|
|
@@ -57,7 +58,9 @@ const makeSqlJobRuns = (context, policy, newToken) => {
|
|
|
57
58
|
heartbeat: (run) => heartbeatRunSql(context, run, leaseMs),
|
|
58
59
|
settle: (run, result) => settleRunSql(context, run, result),
|
|
59
60
|
isCompleted: (job, runKey) => isRunCompletedSql(context, job, runKey),
|
|
61
|
+
get: (key) => getRunSql(context, key),
|
|
60
62
|
recent: (query) => queryRecentRunsSql(context, query),
|
|
63
|
+
page: (query) => pageRunsSql(context, query),
|
|
61
64
|
prune: (jobs, olderThan) => pruneRunsSql(context, jobs, olderThan, policy.maintenance.batchSize),
|
|
62
65
|
leaseDuration: policy.lease.duration,
|
|
63
66
|
policy
|
package/dist/migrations.js
CHANGED
|
@@ -101,11 +101,24 @@ const createTables = (storage) => Effect.gen(function* () {
|
|
|
101
101
|
yield* assertTriggerCheckAllowsManual(sql, storage);
|
|
102
102
|
});
|
|
103
103
|
/**
|
|
104
|
+
* Step 0002: index for keyset-paginated run history across all jobs.
|
|
105
|
+
*/
|
|
106
|
+
const addRunsHistoryIndex = (storage) => Effect.gen(function* () {
|
|
107
|
+
const sql = (yield* SqlClient.SqlClient).withoutTransforms();
|
|
108
|
+
yield* sql`
|
|
109
|
+
CREATE INDEX IF NOT EXISTS ${sql(storage.runsHistoryIndex)}
|
|
110
|
+
ON ${sql(storage.runsTable)} (started_at DESC, run_key COLLATE "C" DESC, job COLLATE "C" DESC)
|
|
111
|
+
`;
|
|
112
|
+
});
|
|
113
|
+
/**
|
|
104
114
|
* The library's migration loader for resolved names. New steps are appended with higher ids and
|
|
105
115
|
* must stay idempotent. `Migrator` runs every pending step in one transaction, so a step that
|
|
106
116
|
* rewrites a large table belongs in its own deploy step instead.
|
|
107
117
|
*/
|
|
108
|
-
const jobsMigrationLoader = (storage) => Migrator.fromRecord({
|
|
118
|
+
const jobsMigrationLoader = (storage) => Migrator.fromRecord({
|
|
119
|
+
"0001_create_tables": createTables(storage),
|
|
120
|
+
"0002_add_runs_history_index": addRunsHistoryIndex(storage)
|
|
121
|
+
});
|
|
109
122
|
/**
|
|
110
123
|
* Migration loader for the library's tables, like Effect Cluster's `SqlMessageStorage.migrations`,
|
|
111
124
|
* for callers who run `Migrator` themselves. Record its history in `<prefix>_migrations` (in
|
package/dist/storage-options.js
CHANGED
|
@@ -53,6 +53,7 @@ const resolveStorage = Effect.fnUntraced(function* (options) {
|
|
|
53
53
|
migrationsTable: qualify(schema, `${prefix}_migrations`),
|
|
54
54
|
migrationsTableName: `${prefix}_migrations`,
|
|
55
55
|
runsRecentIndex: `idx_${prefix}_runs_recent`,
|
|
56
|
+
runsHistoryIndex: `idx_${prefix}_runs_history`,
|
|
56
57
|
runsStatusCheck: `${prefix}_runs_status_check`,
|
|
57
58
|
runsTriggerCheck: `${prefix}_runs_trigger_check`
|
|
58
59
|
};
|
package/docs/logs-and-metrics.md
CHANGED
|
@@ -106,6 +106,7 @@ Scope them per service with your exporter's resource attributes.
|
|
|
106
106
|
| `JobsNotMigratedError` | Runtime layers started against missing or older tables; `component`, `table`, `found`, `expected` |
|
|
107
107
|
| `JobStageError` | A failed durable stage, stored in Cluster's replies with a redacted message |
|
|
108
108
|
| `RunClaimLost` | A run whose heartbeat found another owner; it ends as a `failed` outcome |
|
|
109
|
+
| `InvalidRunCursor` | `JobRuns.page` received a malformed continuation cursor |
|
|
109
110
|
| `MigrationError`, `PgConfigError` | `JobStorage.layerMigrations` and invalid storage options (from `@yieldkit/pg`) |
|
|
110
111
|
|
|
111
112
|
They are tagged errors, so `Effect.catchTag` picks one out:
|
package/docs/storage.md
CHANGED
|
@@ -94,21 +94,29 @@ export const StorageLive = JobStorage.layerStorage({ onSettle: recordHealth });
|
|
|
94
94
|
import { JobRuns } from '@yieldkit/jobs';
|
|
95
95
|
import { Effect } from 'effect';
|
|
96
96
|
|
|
97
|
-
export const
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
97
|
+
export const runHistory = (cursor?: string) =>
|
|
98
|
+
Effect.gen(function* () {
|
|
99
|
+
const runs = yield* JobRuns;
|
|
100
|
+
const job = 'sync-orders';
|
|
101
|
+
const run = yield* runs.get({ job, runKey: '2026-11-25T10:00Z' });
|
|
102
|
+
const page = yield* runs.page({ job, limit: 20, cursor });
|
|
103
|
+
return { run, page };
|
|
104
|
+
});
|
|
101
105
|
```
|
|
102
106
|
|
|
103
|
-
| Member
|
|
104
|
-
|
|
|
105
|
-
| `claim(request)`
|
|
106
|
-
| `heartbeat(run)`
|
|
107
|
-
| `settle(run, result)`
|
|
108
|
-
| `isCompleted(job, runKey)`
|
|
109
|
-
| `
|
|
110
|
-
| `
|
|
111
|
-
| `
|
|
107
|
+
| Member | Does |
|
|
108
|
+
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
109
|
+
| `claim(request)` | Takes `(job, runKey)` and returns `Acquired` with a fence token, or why not: `Busy`, `Completed`, `AlreadySettled`, `RetryLater`, `Exhausted` |
|
|
110
|
+
| `heartbeat(run)` | Extends the lease; `false` when another attempt owns the key |
|
|
111
|
+
| `settle(run, result)` | Fenced update plus the hook; `false` when the claim was lost |
|
|
112
|
+
| `isCompleted(job, runKey)` | Whether the key is completed |
|
|
113
|
+
| `get({ job, runKey })` | `Option<JobRunRecord>` for the key |
|
|
114
|
+
| `recent({ job?, limit })` | Newest rows first, as `JobRunRecord` |
|
|
115
|
+
| `page({ job?, limit, cursor? })` | Newest rows first with an opaque continuation cursor |
|
|
116
|
+
| `prune(jobs, olderThan)` | Deletes rows of `jobs` that started before the cutoff, `maintenance.batchSize` rows per statement |
|
|
117
|
+
| `leaseDuration`, `policy` | The lease and the resolved [policy](policy.md) |
|
|
118
|
+
|
|
119
|
+
`page` and `recent` order rows by start time, then run key, then job, all descending, comparing text bytewise (`COLLATE "C"` on a UTF-8 database) for ties. Pass the returned `nextCursor` with the same job filter to continue. An empty page or the last page returns `nextCursor: null`. A malformed cursor fails with `InvalidRunCursor`. `page` reads live ledger state, so a run reclaimed while walking can move ahead of an existing cursor; run the walk inside a single `REPEATABLE READ` transaction when you need a point-in-time snapshot. An undecodable ledger row is a defect in all three read methods.
|
|
112
120
|
|
|
113
121
|
A claim with the same workflow `executionId` resumes its own `running` row after a crash, with a fresh token. Heartbeats and settles match the token, so a stale process never overwrites a newer owner.
|
|
114
122
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yieldkit/jobs",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Durable scheduled and on-demand jobs for Effect on PostgreSQL, on the Effect Cluster you bring: cron schedules, a fenced run ledger, retries and explicit migrations.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cron",
|