@yieldkit/jobs 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +307 -2
- package/dist/_virtual/_rolldown/runtime.js +12 -0
- package/dist/activity.d.ts +81 -0
- package/dist/activity.js +151 -0
- package/dist/calendar.d.ts +33 -0
- package/dist/calendar.js +205 -0
- package/dist/cluster.d.ts +54 -0
- package/dist/cluster.js +115 -0
- package/dist/cron.d.ts +21 -0
- package/dist/cron.js +80 -0
- package/dist/dispatch.d.ts +97 -0
- package/dist/dispatch.js +140 -0
- package/dist/errors.d.ts +194 -0
- package/dist/errors.js +132 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.js +22 -0
- package/dist/job.d.ts +306 -0
- package/dist/job.js +45 -0
- package/dist/ledger-memory.d.ts +64 -0
- package/dist/ledger-memory.js +246 -0
- package/dist/ledger-retry.js +21 -0
- package/dist/ledger-sql-deadline.js +39 -0
- package/dist/ledger-sql.d.ts +5 -0
- package/dist/ledger-sql.js +332 -0
- package/dist/ledger-types.d.ts +340 -0
- package/dist/ledger-types.js +71 -0
- package/dist/ledger.d.ts +51 -0
- package/dist/ledger.js +66 -0
- package/dist/logging.d.ts +83 -0
- package/dist/logging.js +117 -0
- package/dist/maintenance.d.ts +6 -0
- package/dist/maintenance.js +115 -0
- package/dist/metrics.d.ts +14 -0
- package/dist/metrics.js +35 -0
- package/dist/migrations.d.ts +21 -0
- package/dist/migrations.js +194 -0
- package/dist/omit-undefined.js +10 -0
- package/dist/params.d.ts +58 -0
- package/dist/params.js +97 -0
- package/dist/policy.d.ts +225 -0
- package/dist/policy.js +247 -0
- package/dist/probe.js +67 -0
- package/dist/requests-memory.d.ts +36 -0
- package/dist/requests-memory.js +142 -0
- package/dist/requests.d.ts +195 -0
- package/dist/requests.js +242 -0
- package/dist/run-key.d.ts +25 -0
- package/dist/run-key.js +85 -0
- package/dist/run-support.js +212 -0
- package/dist/run.d.ts +163 -0
- package/dist/run.js +258 -0
- package/dist/scheduler.d.ts +56 -0
- package/dist/scheduler.js +227 -0
- package/dist/settle-hook.d.ts +3 -0
- package/dist/settle-hook.js +33 -0
- package/dist/storage-options.d.ts +25 -0
- package/dist/storage-options.js +60 -0
- package/dist/storage.d.ts +53 -0
- package/dist/storage.js +75 -0
- package/dist/testing/index.d.ts +4 -0
- package/dist/testing/index.js +4 -0
- package/dist/time-zone.js +83 -0
- package/dist/workflow-activities.js +227 -0
- package/dist/workflow-retry.js +80 -0
- package/dist/workflow-schema.d.ts +207 -0
- package/dist/workflow-schema.js +360 -0
- package/dist/workflow-settle.js +234 -0
- package/dist/workflow.d.ts +17 -0
- package/dist/workflow.js +202 -0
- package/docs/deployment.md +167 -0
- package/docs/jobs.md +200 -0
- package/docs/logs-and-metrics.md +129 -0
- package/docs/migrations.md +66 -0
- package/docs/policy.md +75 -0
- package/docs/scheduling.md +149 -0
- package/docs/storage.md +138 -0
- package/docs/testing.md +144 -0
- package/docs/workers-and-clients.md +100 -0
- package/package.json +82 -3
package/dist/logging.js
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { Cause, Clock, Effect, Exit, Schema } from "effect";
|
|
2
|
+
import { SecureRandom } from "effect/crypto";
|
|
3
|
+
import { compactLogFields, extractErrorFields, logErrorCause, logWithFields, withLogContext } from "@yieldkit/logger";
|
|
4
|
+
// src/logging.ts
|
|
5
|
+
/**
|
|
6
|
+
* Allocates a new random UUIDv4 run id from `SecureRandom`. Callers that already have one should
|
|
7
|
+
* pass it instead.
|
|
8
|
+
*/
|
|
9
|
+
const generateJobRunId = SecureRandom.SecureRandom.use((random) => random.uuidV4());
|
|
10
|
+
/**
|
|
11
|
+
* Drops omitted context fields so they are not written as `undefined`.
|
|
12
|
+
*/
|
|
13
|
+
const buildJobAnnotations = (context, jobRunId) => compactLogFields({
|
|
14
|
+
...compactLogFields(context.fields ?? {}),
|
|
15
|
+
job: context.job,
|
|
16
|
+
jobRunId,
|
|
17
|
+
trigger: context.trigger,
|
|
18
|
+
attempt: context.attempt
|
|
19
|
+
});
|
|
20
|
+
/**
|
|
21
|
+
* Annotates logs inside `effect` with the job name, run id, trigger, attempt and `fields`. Does not
|
|
22
|
+
* emit start or completion events. Requires `SecureRandom` to generate a run id when `jobRunId` is
|
|
23
|
+
* omitted.
|
|
24
|
+
*/
|
|
25
|
+
const withJobContext = (context) => (effect) => Effect.gen(function* () {
|
|
26
|
+
const jobRunId = context.jobRunId ?? (yield* generateJobRunId);
|
|
27
|
+
return yield* effect.pipe(Effect.annotateLogs(buildJobAnnotations(context, jobRunId)));
|
|
28
|
+
});
|
|
29
|
+
/**
|
|
30
|
+
* Names one step inside a job. Adds a `stage` annotation, a log span, and a trace span.
|
|
31
|
+
*/
|
|
32
|
+
const withJobStage = (stage, fields) => (effect) => effect.pipe(withLogContext({ stage }), withLogContext(fields ?? {}), Effect.withLogSpan(`stage.${stage}`), Effect.withSpan(`job.stage.${stage}`, { attributes: { stage } }));
|
|
33
|
+
/**
|
|
34
|
+
* Structural shape matching `JobStageError` for typed log extraction without a circular import from
|
|
35
|
+
* `activity.ts`.
|
|
36
|
+
*/
|
|
37
|
+
const JobStageErrorShape = Schema.TaggedStruct("JobStageError", {
|
|
38
|
+
/**
|
|
39
|
+
* Name of the durable stage that failed.
|
|
40
|
+
*/
|
|
41
|
+
stage: Schema.String,
|
|
42
|
+
/**
|
|
43
|
+
* Redacted human-readable failure message.
|
|
44
|
+
*/
|
|
45
|
+
message: Schema.String,
|
|
46
|
+
/**
|
|
47
|
+
* Original `_tag` of the underlying error, or `null`.
|
|
48
|
+
*/
|
|
49
|
+
errorTag: Schema.NullOr(Schema.String),
|
|
50
|
+
/**
|
|
51
|
+
* Whether the failure originated as a defect.
|
|
52
|
+
*/
|
|
53
|
+
isDefect: Schema.Boolean
|
|
54
|
+
});
|
|
55
|
+
/**
|
|
56
|
+
* Failure annotations shared by a typed error and a defect. Omitted summary fields are dropped.
|
|
57
|
+
*/
|
|
58
|
+
const buildFailureFields = (cause, durationMs) => {
|
|
59
|
+
const failReason = cause.reasons.find(Cause.isFailReason);
|
|
60
|
+
if (failReason !== void 0 && Schema.is(JobStageErrorShape)(failReason.error)) return compactLogFields({
|
|
61
|
+
status: "failed",
|
|
62
|
+
durationMs,
|
|
63
|
+
isDefect: failReason.error.isDefect,
|
|
64
|
+
errorTag: failReason.error.errorTag ?? "JobStageError",
|
|
65
|
+
errorMessage: failReason.error.message,
|
|
66
|
+
stage: failReason.error.stage
|
|
67
|
+
});
|
|
68
|
+
const reason = failReason ?? cause.reasons.find(Cause.isDieReason);
|
|
69
|
+
const isDefect = reason !== void 0 && Cause.isDieReason(reason);
|
|
70
|
+
const error = isDefect ? reason.defect : failReason?.error;
|
|
71
|
+
return compactLogFields({
|
|
72
|
+
status: "failed",
|
|
73
|
+
durationMs,
|
|
74
|
+
isDefect,
|
|
75
|
+
...reason === void 0 ? {} : extractErrorFields(error)
|
|
76
|
+
});
|
|
77
|
+
};
|
|
78
|
+
/**
|
|
79
|
+
* Logs `job.started`, then `job.completed`, `job.skipped`, `job.interrupted`, or `job.failed`.
|
|
80
|
+
* Duration comes from the Effect clock. A missing `jobRunId` is generated from `SecureRandom`,
|
|
81
|
+
* which the returned effect therefore requires.
|
|
82
|
+
*/
|
|
83
|
+
const withJobLogging = (options) => (effect) => Effect.gen(function* () {
|
|
84
|
+
const jobRunId = options.jobRunId ?? (yield* generateJobRunId);
|
|
85
|
+
const annotations = buildJobAnnotations(options, jobRunId);
|
|
86
|
+
const startedMs = yield* Clock.currentTimeMillis;
|
|
87
|
+
const startLevel = options.startLevel ?? "Debug";
|
|
88
|
+
const completeLevel = options.completeLevel ?? "Info";
|
|
89
|
+
const skipLevel = options.skipLevel ?? "Info";
|
|
90
|
+
const spanName = options.spanName ?? `job.${options.job}`;
|
|
91
|
+
const logSpanName = options.logSpanName ?? "job.run";
|
|
92
|
+
return yield* Effect.gen(function* () {
|
|
93
|
+
yield* logWithFields(startLevel, "job.started", { status: "started" });
|
|
94
|
+
return yield* effect.pipe(Effect.onExit((exit) => Effect.gen(function* () {
|
|
95
|
+
const durationMs = Math.max(0, (yield* Clock.currentTimeMillis) - startedMs);
|
|
96
|
+
if (Exit.isSuccess(exit)) {
|
|
97
|
+
const summary = options.summarizeResult?.(exit.value);
|
|
98
|
+
const skipped = options.isSkipped?.(exit.value) ?? false;
|
|
99
|
+
yield* logWithFields(skipped ? skipLevel : completeLevel, skipped ? "job.skipped" : "job.completed", {
|
|
100
|
+
...summary,
|
|
101
|
+
status: skipped ? "skipped" : "completed",
|
|
102
|
+
durationMs
|
|
103
|
+
});
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
if (Cause.hasInterruptsOnly(exit.cause)) {
|
|
107
|
+
yield* logWithFields("Warn", "job.interrupted", {
|
|
108
|
+
status: "interrupted",
|
|
109
|
+
durationMs
|
|
110
|
+
});
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
yield* logErrorCause("job.failed", exit.cause, buildFailureFields(exit.cause, durationMs));
|
|
114
|
+
})));
|
|
115
|
+
}).pipe(Effect.annotateLogs(annotations), Effect.withLogSpan(logSpanName), Effect.withSpan(spanName, { attributes: annotations }));
|
|
116
|
+
});
|
|
117
|
+
export { generateJobRunId, withJobContext, withJobLogging, withJobStage };
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { MAINTENANCE_SHARD_GROUP } from "./cluster.js";
|
|
2
|
+
import { JobRuns } from "./ledger.js";
|
|
3
|
+
import { JobRequests } from "./requests.js";
|
|
4
|
+
import { Clock, Duration, Effect } from "effect";
|
|
5
|
+
import { describeError, logInfo, logWarning } from "@yieldkit/logger";
|
|
6
|
+
import { MessageStorage, Singleton } from "effect/cluster";
|
|
7
|
+
// src/maintenance.ts
|
|
8
|
+
/**
|
|
9
|
+
* Entity type used by `ClusterWorkflowEngine` for durable clock wakeups.
|
|
10
|
+
*/
|
|
11
|
+
const DURABLE_CLOCK_ENTITY_TYPE = "Workflow/-/DurableClock";
|
|
12
|
+
/**
|
|
13
|
+
* Name of the cluster-wide maintenance Singleton.
|
|
14
|
+
*/
|
|
15
|
+
const MAINTENANCE_SINGLETON_NAME = "@yieldkit/jobs/maintenance";
|
|
16
|
+
/**
|
|
17
|
+
* Deletes processed cluster messages for `entityType` older than `retention` in bounded batches.
|
|
18
|
+
*/
|
|
19
|
+
const pruneEntityMessages = Effect.fnUntraced(function* (storage, entityType, retention, batchSize) {
|
|
20
|
+
const completedBefore = (yield* Clock.currentTimeMillis) - Duration.toMillis(retention);
|
|
21
|
+
let totalDeleted = 0;
|
|
22
|
+
for (;;) {
|
|
23
|
+
const deleted = yield* storage.deleteProcessed({
|
|
24
|
+
entityType,
|
|
25
|
+
completedBefore,
|
|
26
|
+
limit: batchSize
|
|
27
|
+
}).pipe(Effect.catch((error) => logWarning("worker.maintenance.cluster_prune_failed", {
|
|
28
|
+
entityType,
|
|
29
|
+
errorMessage: describeError(error)
|
|
30
|
+
}).pipe(Effect.as(0))));
|
|
31
|
+
totalDeleted += deleted;
|
|
32
|
+
if (deleted < batchSize) return totalDeleted;
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
/**
|
|
36
|
+
* Deletes finished request rows older than `retention` in batches of `batchSize`. A failed batch is
|
|
37
|
+
* logged and ends the sweep.
|
|
38
|
+
*/
|
|
39
|
+
const pruneRequests = Effect.fnUntraced(function* (requests, retention, batchSize) {
|
|
40
|
+
let totalDeleted = 0;
|
|
41
|
+
for (;;) {
|
|
42
|
+
const deleted = yield* requests.prune(retention, batchSize).pipe(Effect.catch((error) => logWarning("worker.maintenance.requests_prune_failed", { errorMessage: describeError(error) }).pipe(Effect.as(0))));
|
|
43
|
+
totalDeleted += deleted;
|
|
44
|
+
if (deleted < batchSize) return totalDeleted;
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
/**
|
|
48
|
+
* Lists the workflow and cron entity types of `jobNames`, in job order, all kept for `retention`.
|
|
49
|
+
*/
|
|
50
|
+
const entityPruneTargets = (jobNames, retention) => jobNames.flatMap((name) => [{
|
|
51
|
+
entityType: `Workflow/${name}`,
|
|
52
|
+
retention
|
|
53
|
+
}, {
|
|
54
|
+
entityType: `ClusterCron/${name}`,
|
|
55
|
+
retention
|
|
56
|
+
}]);
|
|
57
|
+
/**
|
|
58
|
+
* Names of the jobs in `jobs` whose cadence is one of `tags`.
|
|
59
|
+
*/
|
|
60
|
+
const jobNamesWith = (jobs, tags) => jobs.flatMap((job) => tags.includes(job.cadence._tag) ? [job.name] : []);
|
|
61
|
+
/**
|
|
62
|
+
* Lists every processed-message prune target of `jobs` under `policy`: `Every` and `Cron` workflows
|
|
63
|
+
* and crons after `retention.everyCluster`, `Daily` ones after `retention.dailyCluster`, `OnDemand`
|
|
64
|
+
* workflows after `retention.onDemand`, and durable clocks after the shorter of
|
|
65
|
+
* `retention.everyCluster` and `retention.onDemand`, because a processed clock that outlives its
|
|
66
|
+
* pruned `OnDemand` workflow would swallow the same wake-up of a later run of that key. `Once`
|
|
67
|
+
* workflows are never pruned, so a completed `Once` job stays deduplicated.
|
|
68
|
+
*/
|
|
69
|
+
const clusterPruneTargetsFor = (jobs, policy) => [
|
|
70
|
+
...entityPruneTargets(jobNamesWith(jobs, ["Every", "Cron"]), policy.retention.everyCluster),
|
|
71
|
+
...entityPruneTargets(jobNamesWith(jobs, ["Daily"]), policy.retention.dailyCluster),
|
|
72
|
+
...jobNamesWith(jobs, ["OnDemand"]).map((name) => ({
|
|
73
|
+
entityType: `Workflow/${name}`,
|
|
74
|
+
retention: policy.retention.onDemand
|
|
75
|
+
})),
|
|
76
|
+
{
|
|
77
|
+
entityType: DURABLE_CLOCK_ENTITY_TYPE,
|
|
78
|
+
retention: Duration.min(policy.retention.everyCluster, policy.retention.onDemand)
|
|
79
|
+
}
|
|
80
|
+
];
|
|
81
|
+
/**
|
|
82
|
+
* Cluster-wide maintenance `Singleton`. When it starts and then every `policy.maintenance.interval`
|
|
83
|
+
* it prunes `Every` and `Cron` ledger rows older than `retention.everyRuns`, `OnDemand` rows older
|
|
84
|
+
* than `retention.onDemand`, finished request rows older than `retention.requests`, and processed
|
|
85
|
+
* Cluster messages (see `clusterPruneTargetsFor`). `jobs` is every job of the deployment, so the
|
|
86
|
+
* one worker holding the singleton prunes for all of them.
|
|
87
|
+
*/
|
|
88
|
+
const makeMaintenanceLayer = (jobs) => {
|
|
89
|
+
const everyJobNames = jobNamesWith(jobs, ["Every", "Cron"]);
|
|
90
|
+
const onDemandJobNames = jobNamesWith(jobs, ["OnDemand"]);
|
|
91
|
+
return Singleton.make(MAINTENANCE_SINGLETON_NAME, Effect.gen(function* () {
|
|
92
|
+
const runs = yield* JobRuns;
|
|
93
|
+
const requests = yield* JobRequests;
|
|
94
|
+
const storage = yield* MessageStorage.MessageStorage;
|
|
95
|
+
const { policy } = runs;
|
|
96
|
+
const clusterPruneTargets = clusterPruneTargetsFor(jobs, policy);
|
|
97
|
+
return yield* Effect.forever(Effect.gen(function* () {
|
|
98
|
+
if (everyJobNames.length > 0) yield* runs.prune(everyJobNames, policy.retention.everyRuns).pipe(Effect.tap((deleted) => deleted > 0 ? logInfo("worker.supervisor.pruned", {
|
|
99
|
+
deleted,
|
|
100
|
+
jobs: everyJobNames
|
|
101
|
+
}) : Effect.void), Effect.catch((error) => logWarning("worker.supervisor.prune_failed", { errorMessage: describeError(error) })));
|
|
102
|
+
if (onDemandJobNames.length > 0) yield* runs.prune(onDemandJobNames, policy.retention.onDemand).pipe(Effect.tap((deleted) => deleted > 0 ? logInfo("worker.supervisor.pruned", {
|
|
103
|
+
deleted,
|
|
104
|
+
jobs: onDemandJobNames
|
|
105
|
+
}) : Effect.void), Effect.catch((error) => logWarning("worker.supervisor.prune_failed", { errorMessage: describeError(error) })));
|
|
106
|
+
const requestsDeleted = yield* pruneRequests(requests, policy.retention.requests, policy.maintenance.batchSize);
|
|
107
|
+
if (requestsDeleted > 0) yield* logInfo("worker.maintenance.requests_pruned", { deleted: requestsDeleted });
|
|
108
|
+
let clusterDeleted = 0;
|
|
109
|
+
for (const target of clusterPruneTargets) clusterDeleted += yield* pruneEntityMessages(storage, target.entityType, target.retention, policy.maintenance.batchSize);
|
|
110
|
+
if (clusterDeleted > 0) yield* logInfo("worker.maintenance.cluster_pruned", { deleted: clusterDeleted });
|
|
111
|
+
yield* Effect.sleep(policy.maintenance.interval);
|
|
112
|
+
}));
|
|
113
|
+
}), { shardGroup: MAINTENANCE_SHARD_GROUP });
|
|
114
|
+
};
|
|
115
|
+
export { clusterPruneTargetsFor, makeMaintenanceLayer };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import "./job.js";
|
|
2
|
+
import { Effect, Metric } from "effect";
|
|
3
|
+
/**
|
|
4
|
+
* Counter of finished job runs tagged by `job`, `status`, and `trigger`.
|
|
5
|
+
*/
|
|
6
|
+
export declare const jobRunsTotal: Metric.Counter<number>;
|
|
7
|
+
/**
|
|
8
|
+
* Histogram of job run durations in milliseconds tagged by `job`.
|
|
9
|
+
*/
|
|
10
|
+
export declare const jobDurationMs: Metric.Histogram<number>;
|
|
11
|
+
/**
|
|
12
|
+
* Counter of runs that lost their `(job, run_key)` lease claim before settling.
|
|
13
|
+
*/
|
|
14
|
+
export declare const jobLeaseLostTotal: Metric.Counter<number>;
|
package/dist/metrics.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { Effect, Metric } from "effect";
|
|
2
|
+
import { durationHistogram } from "@yieldkit/logger";
|
|
3
|
+
// src/metrics.ts
|
|
4
|
+
/**
|
|
5
|
+
* Counter of finished job runs tagged by `job`, `status`, and `trigger`.
|
|
6
|
+
*/
|
|
7
|
+
const jobRunsTotal = Metric.counter("job_runs_total", {
|
|
8
|
+
description: "Finished job runs by job, status and trigger",
|
|
9
|
+
incremental: true
|
|
10
|
+
});
|
|
11
|
+
/**
|
|
12
|
+
* Histogram of job run durations in milliseconds tagged by `job`.
|
|
13
|
+
*/
|
|
14
|
+
const jobDurationMs = durationHistogram("job_duration_ms", "Job run duration in milliseconds by job");
|
|
15
|
+
/**
|
|
16
|
+
* Counter of runs that lost their `(job, run_key)` lease claim before settling.
|
|
17
|
+
*/
|
|
18
|
+
const jobLeaseLostTotal = Metric.counter("job_lease_lost_total", {
|
|
19
|
+
description: "Job runs that lost their run claim before settling",
|
|
20
|
+
incremental: true
|
|
21
|
+
});
|
|
22
|
+
/**
|
|
23
|
+
* Records `job_runs_total`, `job_duration_ms` and, when `leaseLost` is `true`,
|
|
24
|
+
* `job_lease_lost_total`.
|
|
25
|
+
*/
|
|
26
|
+
const recordJobRunMetrics = (params) => {
|
|
27
|
+
const updates = [Metric.update(Metric.withAttributes(jobRunsTotal, {
|
|
28
|
+
job: params.job,
|
|
29
|
+
status: params.status,
|
|
30
|
+
trigger: params.trigger
|
|
31
|
+
}), 1), Metric.update(Metric.withAttributes(jobDurationMs, { job: params.job }), Math.max(0, params.elapsedMs))];
|
|
32
|
+
if (params.leaseLost) updates.push(Metric.update(Metric.withAttributes(jobLeaseLostTotal, { job: params.job }), 1));
|
|
33
|
+
return Effect.all(updates, { discard: true });
|
|
34
|
+
};
|
|
35
|
+
export { jobDurationMs, jobLeaseLostTotal, jobRunsTotal, recordJobRunMetrics };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { JobsStorageOptions } from "./storage-options.js";
|
|
2
|
+
import { MigrationError, PgConfigError } from "@yieldkit/pg";
|
|
3
|
+
import { Effect, Layer, Schema } from "effect";
|
|
4
|
+
import { Migrator, SqlClient, SqlError } from "effect/sql";
|
|
5
|
+
/**
|
|
6
|
+
* Migration loader for the library's tables, like Effect Cluster's `SqlMessageStorage.migrations`,
|
|
7
|
+
* for callers who run `Migrator` themselves. Record its history in `<prefix>_migrations` (in
|
|
8
|
+
* `schema` when one is set), the table `layerStorage` checks. Invalid storage options fail the
|
|
9
|
+
* loader with Effect's `Migrator.MigrationError`.
|
|
10
|
+
*/
|
|
11
|
+
export declare const migrations: (options?: JobsStorageOptions) => Migrator.Loader;
|
|
12
|
+
/**
|
|
13
|
+
* Runs the library's migrations on the provided `SqlClient`, like Effect Cluster's
|
|
14
|
+
* `SqlMessageStorage.layerMigrations`: use an owner connection in a deploy step, then
|
|
15
|
+
* `layerStorage` with a DML-only runtime connection. Creates the library's tables only, never
|
|
16
|
+
* Cluster's. Without `schema`, the tables go to the first existing schema of the connection's
|
|
17
|
+
* `search_path`. The schema must exist. Unlike Effect's, failures are typed: `MigrationError`, or
|
|
18
|
+
* `PgConfigError` for invalid options. Logs `jobs.migrate.completed` with the number of applied
|
|
19
|
+
* steps.
|
|
20
|
+
*/
|
|
21
|
+
export declare const layerMigrations: (options?: JobsStorageOptions) => Layer.Layer<never, MigrationError | PgConfigError, SqlClient.SqlClient>;
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { recordedMigrationId, tableExists } from "./probe.js";
|
|
2
|
+
import { resolveStorage } from "./storage-options.js";
|
|
3
|
+
import { MigrationError } from "@yieldkit/pg";
|
|
4
|
+
import { Data, Effect, Layer, Predicate, Schema } from "effect";
|
|
5
|
+
import { Migrator, SqlClient } from "effect/sql";
|
|
6
|
+
import { describeError, logInfo } from "@yieldkit/logger";
|
|
7
|
+
// src/migrations.ts
|
|
8
|
+
/**
|
|
9
|
+
* A migration precondition does not hold: a missing schema, a missing grant, or an adopted table
|
|
10
|
+
* the library cannot use as it is.
|
|
11
|
+
*/
|
|
12
|
+
var MigrationStepError = class extends Data.TaggedError("MigrationStepError") {};
|
|
13
|
+
/**
|
|
14
|
+
* Succeeds when `holds`, otherwise fails with `MigrationStepError` carrying `message`.
|
|
15
|
+
*/
|
|
16
|
+
const requireThat = (holds, message) => holds ? Effect.void : Effect.fail(new MigrationStepError({ message }));
|
|
17
|
+
/**
|
|
18
|
+
* Row read by the trigger CHECK guard at the end of step 0001.
|
|
19
|
+
*/
|
|
20
|
+
const ConstraintRow = Schema.Struct({
|
|
21
|
+
/**
|
|
22
|
+
* `pg_get_constraintdef` of the constraint.
|
|
23
|
+
*/
|
|
24
|
+
definition: Schema.String });
|
|
25
|
+
/**
|
|
26
|
+
* Trigger values the run ledger stores, each of which an adopted trigger CHECK must mention.
|
|
27
|
+
*/
|
|
28
|
+
const REQUIRED_TRIGGER_VALUES = [
|
|
29
|
+
"'schedule'",
|
|
30
|
+
"'manual'",
|
|
31
|
+
"'api'"
|
|
32
|
+
];
|
|
33
|
+
/**
|
|
34
|
+
* Fails step 0001 when the run ledger already has a trigger CHECK whose definition does not mention
|
|
35
|
+
* all of `'schedule'`, `'manual'` and `'api'`, which a table created by an earlier,
|
|
36
|
+
* application-owned migration may have. Without this guard the readiness check would pass and the
|
|
37
|
+
* first run with a missing trigger would hit a constraint violation. It reads the definition's text
|
|
38
|
+
* only, so a CHECK that names all three values but still rejects one is not caught.
|
|
39
|
+
*/
|
|
40
|
+
const assertTriggerCheckAllowsManual = Effect.fnUntraced(function* (sql, storage) {
|
|
41
|
+
const rows = yield* sql`
|
|
42
|
+
SELECT pg_get_constraintdef(c.oid) AS definition
|
|
43
|
+
FROM pg_constraint c
|
|
44
|
+
WHERE c.conrelid = to_regclass(${storage.runsTable})
|
|
45
|
+
AND c.conname = ${storage.runsTriggerCheck}
|
|
46
|
+
`;
|
|
47
|
+
const existing = (yield* Schema.decodeUnknownEffect(Schema.Array(ConstraintRow))(rows))[0];
|
|
48
|
+
yield* requireThat(existing === void 0 || REQUIRED_TRIGGER_VALUES.every((value) => existing.definition.includes(value)), `${storage.runsTable} has a trigger CHECK (${storage.runsTriggerCheck}) that does not allow 'schedule', 'manual' and 'api'. Replace it with CHECK (trigger IN ('schedule', 'manual', 'api')) before migrating; see "Adopting existing tables" in docs/migrations.md.`);
|
|
49
|
+
});
|
|
50
|
+
/**
|
|
51
|
+
* Step 0001: the run ledger, its index and the request table. Every statement is idempotent, so it
|
|
52
|
+
* also adopts tables that exist without a history row; `CREATE TABLE IF NOT EXISTS` leaves an
|
|
53
|
+
* existing table's columns and constraints as they are.
|
|
54
|
+
*/
|
|
55
|
+
const createTables = (storage) => Effect.gen(function* () {
|
|
56
|
+
const sql = (yield* SqlClient.SqlClient).withoutTransforms();
|
|
57
|
+
yield* sql`
|
|
58
|
+
CREATE TABLE IF NOT EXISTS ${sql(storage.runsTable)} (
|
|
59
|
+
job TEXT NOT NULL,
|
|
60
|
+
run_key TEXT NOT NULL,
|
|
61
|
+
status TEXT NOT NULL
|
|
62
|
+
CONSTRAINT ${sql(storage.runsStatusCheck)}
|
|
63
|
+
CHECK (status IN ('running', 'completed', 'failed')),
|
|
64
|
+
claim_token UUID NOT NULL,
|
|
65
|
+
lease_expires_at TIMESTAMPTZ NOT NULL,
|
|
66
|
+
attempt INTEGER NOT NULL DEFAULT 1,
|
|
67
|
+
failures INTEGER NOT NULL DEFAULT 0,
|
|
68
|
+
next_attempt_at TIMESTAMPTZ,
|
|
69
|
+
trigger TEXT NOT NULL
|
|
70
|
+
CONSTRAINT ${sql(storage.runsTriggerCheck)}
|
|
71
|
+
CHECK (trigger IN ('schedule', 'manual', 'api')),
|
|
72
|
+
params JSONB NOT NULL DEFAULT '{}'::jsonb,
|
|
73
|
+
stats JSONB,
|
|
74
|
+
error_message TEXT,
|
|
75
|
+
started_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
76
|
+
finished_at TIMESTAMPTZ,
|
|
77
|
+
execution_id TEXT,
|
|
78
|
+
PRIMARY KEY (job, run_key)
|
|
79
|
+
)
|
|
80
|
+
`;
|
|
81
|
+
yield* sql`ALTER TABLE ${sql(storage.runsTable)} ADD COLUMN IF NOT EXISTS execution_id TEXT`;
|
|
82
|
+
yield* sql`
|
|
83
|
+
CREATE INDEX IF NOT EXISTS ${sql(storage.runsRecentIndex)}
|
|
84
|
+
ON ${sql(storage.runsTable)} (job, started_at DESC)
|
|
85
|
+
`;
|
|
86
|
+
yield* sql`
|
|
87
|
+
CREATE TABLE IF NOT EXISTS ${sql(storage.requestsTable)} (
|
|
88
|
+
id UUID PRIMARY KEY,
|
|
89
|
+
job TEXT NOT NULL,
|
|
90
|
+
params JSONB NOT NULL DEFAULT '{}'::jsonb,
|
|
91
|
+
force BOOLEAN NOT NULL DEFAULT FALSE,
|
|
92
|
+
requested_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
93
|
+
picked_at TIMESTAMPTZ,
|
|
94
|
+
finished_at TIMESTAMPTZ,
|
|
95
|
+
run_key TEXT,
|
|
96
|
+
outcome JSONB,
|
|
97
|
+
execution_id TEXT
|
|
98
|
+
)
|
|
99
|
+
`;
|
|
100
|
+
yield* sql`ALTER TABLE ${sql(storage.requestsTable)} ADD COLUMN IF NOT EXISTS execution_id TEXT`;
|
|
101
|
+
yield* assertTriggerCheckAllowsManual(sql, storage);
|
|
102
|
+
});
|
|
103
|
+
/**
|
|
104
|
+
* The library's migration loader for resolved names. New steps are appended with higher ids and
|
|
105
|
+
* must stay idempotent. `Migrator` runs every pending step in one transaction, so a step that
|
|
106
|
+
* rewrites a large table belongs in its own deploy step instead.
|
|
107
|
+
*/
|
|
108
|
+
const jobsMigrationLoader = (storage) => Migrator.fromRecord({ "0001_create_tables": createTables(storage) });
|
|
109
|
+
/**
|
|
110
|
+
* Migration loader for the library's tables, like Effect Cluster's `SqlMessageStorage.migrations`,
|
|
111
|
+
* for callers who run `Migrator` themselves. Record its history in `<prefix>_migrations` (in
|
|
112
|
+
* `schema` when one is set), the table `layerStorage` checks. Invalid storage options fail the
|
|
113
|
+
* loader with Effect's `Migrator.MigrationError`.
|
|
114
|
+
*/
|
|
115
|
+
const migrations = (options) => resolveStorage(options).pipe(Effect.mapError((error) => new Migrator.MigrationError({
|
|
116
|
+
kind: "BadState",
|
|
117
|
+
message: error.message
|
|
118
|
+
})), Effect.flatMap(jobsMigrationLoader));
|
|
119
|
+
/**
|
|
120
|
+
* Text of a failure from Effect's `Migrator`, with the failing step's cause appended.
|
|
121
|
+
*/
|
|
122
|
+
const describeMigratorFailure = (error) => {
|
|
123
|
+
if (Predicate.isTagged(error, "MigrationError") && Predicate.hasProperty(error, "cause") && error.cause !== void 0) return `${describeError(error)}: ${describeError(error.cause)}`;
|
|
124
|
+
return describeError(error);
|
|
125
|
+
};
|
|
126
|
+
/**
|
|
127
|
+
* Row of the target schema check.
|
|
128
|
+
*/
|
|
129
|
+
const SchemaRow = Schema.Struct({
|
|
130
|
+
/**
|
|
131
|
+
* The configured schema, or the first one of `search_path` that exists.
|
|
132
|
+
*/
|
|
133
|
+
schema: Schema.NullOr(Schema.String),
|
|
134
|
+
/**
|
|
135
|
+
* Whether that schema exists.
|
|
136
|
+
*/
|
|
137
|
+
present: Schema.Boolean,
|
|
138
|
+
/**
|
|
139
|
+
* Whether the current role may create tables in it.
|
|
140
|
+
*/
|
|
141
|
+
canCreate: Schema.Boolean
|
|
142
|
+
});
|
|
143
|
+
/**
|
|
144
|
+
* Checks, before any DDL, that the target schema exists and the role may create tables in it, and
|
|
145
|
+
* that the history is not shared with another component: a history with rows while the run ledger
|
|
146
|
+
* is missing means Cluster storage, or something else, records its steps there too, and the
|
|
147
|
+
* library's steps would be skipped as already applied.
|
|
148
|
+
*/
|
|
149
|
+
const preflight = Effect.fnUntraced(function* (storage) {
|
|
150
|
+
const sql = (yield* SqlClient.SqlClient).withoutTransforms();
|
|
151
|
+
const rows = yield* sql`
|
|
152
|
+
SELECT s.name AS schema,
|
|
153
|
+
(s.name IS NOT NULL AND EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = s.name)) AS present,
|
|
154
|
+
(s.name IS NOT NULL
|
|
155
|
+
AND EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = s.name)
|
|
156
|
+
AND has_schema_privilege(current_user, s.name, 'CREATE')) AS "canCreate"
|
|
157
|
+
FROM (SELECT ${storage.schema === void 0 ? sql`current_schema()` : sql`${storage.schema}::text`} AS name) s
|
|
158
|
+
`;
|
|
159
|
+
const row = (yield* Schema.decodeUnknownEffect(Schema.Array(SchemaRow))(rows))[0];
|
|
160
|
+
yield* requireThat(row?.present === true, storage.schema === void 0 ? "No schema of the connection's search_path exists. Create one, or set `schema`." : `Schema "${storage.schema}" does not exist. Create it before running the migrations.`);
|
|
161
|
+
yield* requireThat(row?.canCreate === true, `The migration role cannot create tables in schema "${row?.schema ?? ""}". GRANT CREATE ON SCHEMA ${row?.schema ?? ""} to it, or migrate as the schema owner.`);
|
|
162
|
+
const recorded = yield* recordedMigrationId(sql, storage.migrationsTable);
|
|
163
|
+
yield* requireThat(recorded === 0 || (yield* tableExists(sql, storage.runsTable)), `${storage.migrationsTable} has steps recorded but ${storage.runsTable} does not exist. Another component, such as Cluster storage with the same prefix, uses that history; give the library its own prefix.`);
|
|
164
|
+
});
|
|
165
|
+
/**
|
|
166
|
+
* Runs the library's loader into `<prefix>_migrations` and returns the applied steps as
|
|
167
|
+
* `<history>:<id>_<name>`. `Migrator` locks the history table, so concurrent runs apply each step
|
|
168
|
+
* once.
|
|
169
|
+
*/
|
|
170
|
+
const runJobsMigrations = (storage) => preflight(storage).pipe(Effect.andThen(Migrator.make({})({
|
|
171
|
+
loader: jobsMigrationLoader(storage),
|
|
172
|
+
table: storage.migrationsTable
|
|
173
|
+
})), Effect.map((applied) => applied.map(([id, name]) => `${storage.migrationsTable}:${String(id).padStart(4, "0")}_${name}`)));
|
|
174
|
+
/**
|
|
175
|
+
* Runs the library's migrations on the provided `SqlClient`, like Effect Cluster's
|
|
176
|
+
* `SqlMessageStorage.layerMigrations`: use an owner connection in a deploy step, then
|
|
177
|
+
* `layerStorage` with a DML-only runtime connection. Creates the library's tables only, never
|
|
178
|
+
* Cluster's. Without `schema`, the tables go to the first existing schema of the connection's
|
|
179
|
+
* `search_path`. The schema must exist. Unlike Effect's, failures are typed: `MigrationError`, or
|
|
180
|
+
* `PgConfigError` for invalid options. Logs `jobs.migrate.completed` with the number of applied
|
|
181
|
+
* steps.
|
|
182
|
+
*/
|
|
183
|
+
const layerMigrations = (options) => Layer.effectDiscard(Effect.gen(function* () {
|
|
184
|
+
const storage = yield* resolveStorage(options);
|
|
185
|
+
const applied = yield* runJobsMigrations(storage).pipe(Effect.mapError((error) => new MigrationError({
|
|
186
|
+
message: describeMigratorFailure(error),
|
|
187
|
+
direction: "up"
|
|
188
|
+
})));
|
|
189
|
+
yield* logInfo("jobs.migrate.completed", {
|
|
190
|
+
history: storage.migrationsTable,
|
|
191
|
+
applied: applied.length
|
|
192
|
+
});
|
|
193
|
+
}));
|
|
194
|
+
export { MigrationStepError, describeMigratorFailure, jobsMigrationLoader, layerMigrations, migrations, requireThat, runJobsMigrations };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// src/omit-undefined.ts
|
|
2
|
+
/**
|
|
3
|
+
* Implementation signature: copies the own entries whose value is not `undefined`.
|
|
4
|
+
*/
|
|
5
|
+
function omitUndefined(value) {
|
|
6
|
+
const result = {};
|
|
7
|
+
for (const key in value) if (Object.hasOwn(value, key) && value[key] !== void 0) result[key] = value[key];
|
|
8
|
+
return result;
|
|
9
|
+
}
|
|
10
|
+
export { omitUndefined };
|
package/dist/params.d.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { AnyJobDefinition, JobApiParamsPolicy } from "./job.js";
|
|
2
|
+
import { WorkflowParamOverrides } from "./workflow-schema.js";
|
|
3
|
+
import { InvalidJobParams } from "./errors.js";
|
|
4
|
+
import { Effect, Schema } from "effect";
|
|
5
|
+
/**
|
|
6
|
+
* Decoded runtime job parameters paired with their JSON-safe encoded representation for storage in
|
|
7
|
+
* `job_runs.params`.
|
|
8
|
+
*/
|
|
9
|
+
export type DecodedJobParams<Params, ParamsEncoded> = {
|
|
10
|
+
/**
|
|
11
|
+
* Validated runtime parameters passed to `JobDefinition.run`.
|
|
12
|
+
*/
|
|
13
|
+
readonly params: Params;
|
|
14
|
+
/**
|
|
15
|
+
* Encoded JSON-safe representation stored on the `job_runs` row.
|
|
16
|
+
*/
|
|
17
|
+
readonly encoded: ParamsEncoded;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Merges `spec.defaults` with `overrides` (overrides win per key), validates through `spec.schema`,
|
|
21
|
+
* and encodes the validated parameters back into `ParamsEncoded` for ledger storage. Maps schema
|
|
22
|
+
* issues into `InvalidJobParams`.
|
|
23
|
+
*/
|
|
24
|
+
export declare const decodeParams: <Params, ParamsEncoded>(job: string, spec: {
|
|
25
|
+
/**
|
|
26
|
+
* Parameter codec used for both decoding input overrides and encoding for persistence.
|
|
27
|
+
*/
|
|
28
|
+
readonly schema: Schema.Codec<Params, ParamsEncoded>;
|
|
29
|
+
/**
|
|
30
|
+
* Encoded default parameter values applied underneath `overrides`.
|
|
31
|
+
*/
|
|
32
|
+
readonly defaults: Partial<ParamsEncoded>;
|
|
33
|
+
}, overrides?: WorkflowParamOverrides) => Effect.Effect<DecodedJobParams<Params, ParamsEncoded>, InvalidJobParams>;
|
|
34
|
+
/**
|
|
35
|
+
* Validates and encodes parameter overrides for any `JobDefinition` (including unions drawn from
|
|
36
|
+
* `ALL_JOBS`) without executing the job, using its rank-2 `JOB_CONTINUATION` when present.
|
|
37
|
+
*/
|
|
38
|
+
export declare const decodeJobParams: (definition: AnyJobDefinition, overrides?: WorkflowParamOverrides) => Effect.Effect<DecodedJobParams<unknown, unknown>, InvalidJobParams>;
|
|
39
|
+
/**
|
|
40
|
+
* Lists the keys of `overrides` that `definition.params.apiParams` does not allow an API caller to
|
|
41
|
+
* set, in their original order. Every key counts, whatever its value. Returns an empty array when
|
|
42
|
+
* `overrides` is missing or sets only allowed keys.
|
|
43
|
+
*/
|
|
44
|
+
export declare const findDisallowedApiParams: (definition: JobApiParamsPolicy, overrides: WorkflowParamOverrides | undefined) => ReadonlyArray<string>;
|
|
45
|
+
/**
|
|
46
|
+
* Returns a copy of `params` holding only the keys `definition.params.apiParams` allows an API
|
|
47
|
+
* caller to set, so every other param comes from the worker. Entries whose value is not JSON are
|
|
48
|
+
* dropped too, since overrides travel through the JSON workflow payload. Returns an empty record
|
|
49
|
+
* when `params` is not an object.
|
|
50
|
+
*/
|
|
51
|
+
export declare const pickApiParams: (definition: JobApiParamsPolicy, params: unknown) => Schema.JsonObject;
|
|
52
|
+
/**
|
|
53
|
+
* Parses repeated `--set key=value` CLI flags into an override record, later flags overriding
|
|
54
|
+
* earlier ones for the same key. Each value is decoded via `Schema.fromJsonString(Schema.Json)`,
|
|
55
|
+
* falling back to the raw string when JSON decoding fails. Fails with `InvalidJobParams` (job
|
|
56
|
+
* `--set`) on the first entry lacking `=` or using an empty key.
|
|
57
|
+
*/
|
|
58
|
+
export declare const parseSetFlags: (flags: ReadonlyArray<string>) => Effect.Effect<Schema.JsonObject, InvalidJobParams>;
|