@happyvertical/smrt-jobs 0.60.13 → 0.60.15
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/AGENTS.md +13 -6
- package/README.md +68 -0
- package/dist/chunks/{runner-CH-xLt22.js → runner-DucZ0Lvj.js} +306 -22
- package/dist/chunks/runner-DucZ0Lvj.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +306 -153
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +244 -12
- package/dist/runner.d.ts +6 -0
- package/dist/runner.d.ts.map +1 -1
- package/dist/runner.js +1 -1
- package/dist/schedule-admission.d.ts +44 -0
- package/dist/schedule-admission.d.ts.map +1 -0
- package/dist/schedule-runner.d.ts +30 -15
- package/dist/schedule-runner.d.ts.map +1 -1
- package/dist/smrt-job-dedupe-slot.d.ts +19 -0
- package/dist/smrt-job-dedupe-slot.d.ts.map +1 -0
- package/dist/smrt-job.d.ts +31 -6
- package/dist/smrt-job.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +73 -7
- package/dist/smrt-knowledge.okf.md +8 -2
- package/package.json +7 -7
- package/dist/chunks/runner-CH-xLt22.js.map +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -43,8 +43,10 @@ export { type CreateMcpTaskInput, createMcpTaskResult, getMcpTaskMarker, MCP_TAS
|
|
|
43
43
|
export { type BackgroundCapable, type BgOptions, withBackgroundJobs, } from './object-extension.js';
|
|
44
44
|
export { DEFAULT_JOB_RETENTION, DEFAULT_RETENTION_SWEEP_INTERVAL_MS, JOB_EVENTS_RETENTION_TASK, JOBS_RETENTION_TASK, type JobRetentionOptions, type RetentionSweeper, type RetentionSweeperOptions, registerJobRetentionTasks, startRetentionSweeper, unregisterJobRetentionTasks, } from './retention.js';
|
|
45
45
|
export { createTaskRunner, getActiveJobExecutionContext, isRunnerExecutionContext, JobCancelledError, JobTimeoutError, TaskRunner, type TaskRunnerConfig, type TaskRunnerEvents, } from './runner.js';
|
|
46
|
+
export { getScheduleAdmissionPayload, getScheduleAdmissionPolicy, type ScheduleAdmissionPayload, type ScheduleAdmissionPolicy, verifyScheduleAdmission, } from './schedule-admission.js';
|
|
46
47
|
export { createScheduleRunner, getNextCronDate, SCHEDULED_JOB_QUEUE, type ScheduleInfo, ScheduleRunner, type ScheduleRunnerConfig, type ScheduleRunnerEvents, validateCronExpression, } from './schedule-runner.js';
|
|
47
48
|
export { type ClaimReadyOptions, type JobStatus, type ListReadyOptions, SmrtJob, SmrtJobCollection, type SmrtJobData, type TimeoutBehavior, } from './smrt-job.js';
|
|
49
|
+
export { SmrtJobDedupeSlot } from './smrt-job-dedupe-slot.js';
|
|
48
50
|
export { type JobEventCursor, type ListJobEventsOptions, type ListTerminalOutcomesOptions, SmrtJobEvent, SmrtJobEventCollection, type SmrtJobEventData, type SmrtJobEventLevel, type SmrtJobEventType, type SmrtJobTerminalOutcome, type SmrtJobTerminalOutcomePage, type SmrtJobTerminalStatus, } from './smrt-job-event.js';
|
|
49
51
|
export { type RegisterWorkerInput, SmrtWorker, SmrtWorkerCollection, } from './smrt-worker.js';
|
|
50
52
|
export { createWorkerKey, isWorkerAlive, registerLiveWorker, unregisterLiveWorker, } from './worker-liveness.js';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAKH,OAAO,wBAAwB,CAAC;AAYhC,OAAO,EACL,6BAA6B,EAC7B,KAAK,uBAAuB,EAC5B,kBAAkB,EAClB,YAAY,EACZ,sBAAsB,EACtB,4BAA4B,EAC5B,0BAA0B,EAC1B,eAAe,EACf,sBAAsB,EACtB,yBAAyB,GAC1B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,iCAAiC,EACjC,KAAK,0BAA0B,EAC/B,KAAK,uBAAuB,GAC7B,MAAM,gCAAgC,CAAC;AAExC,OAAO,EACL,yBAAyB,EACzB,kBAAkB,GACnB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACL,KAAK,qBAAqB,EAC1B,KAAK,wBAAwB,EAC7B,KAAK,yBAAyB,EAC9B,aAAa,EACb,uBAAuB,EACvB,KAAK,mBAAmB,EACxB,KAAK,gBAAgB,EACrB,KAAK,yBAAyB,EAC9B,KAAK,wBAAwB,EAC7B,yBAAyB,EACzB,KAAK,sBAAsB,EAC3B,sBAAsB,EACtB,KAAK,6BAA6B,EAClC,KAAK,cAAc,GACpB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EACL,UAAU,EACV,KAAK,QAAQ,EACb,UAAU,EACV,gBAAgB,GACjB,MAAM,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"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"}
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { A as SmrtJob, B as
|
|
1
|
+
import { A as SmrtJob, B as backgroundEligible, C as DEFAULT_JOB_RETENTION, D as registerJobRetentionTasks, E as JOB_EVENTS_RETENTION_TASK, F as SmrtJobDedupeSlot, H as getBackgroundEligibleMethods, I as DEFAULT_TENANT_JOB_CAP, L as MAX_JOB_RETRIES, M as countScheduleJobs, N as SmrtJobEvent, O as startRetentionSweeper, P as SmrtJobEventCollection, R as TenantJobCapExceededError, S as redactErrorMessage, T as JOBS_RETENTION_TASK, U as isBackgroundEligibleMethod, V as clampRetries, W as markBackgroundEligible, _ as requestMcpTaskContinuation, a as getActiveJobExecutionContext, b as JobContextLogger, c as SmrtWorker, d as McpTaskCancelledError, f as McpTaskNotFoundError, g as getMcpTaskMarker, h as createMcpTaskResult, i as createTaskRunner, j as SmrtJobCollection, k as unregisterJobRetentionTasks, l as SmrtWorkerCollection, m as McpTaskSuspendedError, n as JobTimeoutError, o as isRunnerExecutionContext, p as McpTaskStore, r as TaskRunner, s as DEFAULT_TASK_HEARTBEAT_INTERVAL_MS, t as JobCancelledError, u as MCP_TASKS_EXTENSION, v as requestMcpTaskInput, w as DEFAULT_RETENTION_SWEEP_INTERVAL_MS, x as redactErrorForPersistence, y as taskFromJob, z as assertWithinTenantCreationCap } from "./chunks/runner-DucZ0Lvj.js";
|
|
2
2
|
import { c as unregisterLiveWorker, i as registerLiveWorker, n as isWorkerAlive, t as createWorkerKey } from "./chunks/worker-liveness-C1Gjnhax.js";
|
|
3
3
|
import { ObjectRegistry, SmrtCollection, SmrtObject, detectEngine, field, smrt } from "@happyvertical/smrt-core";
|
|
4
4
|
import { createLogger } from "@happyvertical/logger";
|
|
5
|
-
import { TenantScoped, requireTenant, tenantId, withTenant } from "@happyvertical/smrt-tenancy";
|
|
6
5
|
import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
|
|
6
|
+
import { TenantScoped, requireTenant, tenantId, withTenant } from "@happyvertical/smrt-tenancy";
|
|
7
7
|
import { exponential } from "@happyvertical/jobs";
|
|
8
8
|
import { createId } from "@happyvertical/utils";
|
|
9
9
|
import { EventEmitter } from "node:events";
|
|
@@ -874,22 +874,102 @@ function withBackgroundJobs(BaseClass) {
|
|
|
874
874
|
return BaseClass;
|
|
875
875
|
}
|
|
876
876
|
//#endregion
|
|
877
|
+
//#region src/schedule-admission.ts
|
|
878
|
+
function getScheduleAdmissionPolicy(args) {
|
|
879
|
+
if (typeof args === "string") args = JSON.parse(args);
|
|
880
|
+
if (!record(args)) throw new TypeError("Schedule method_args must be a JSON object");
|
|
881
|
+
if (!Object.hasOwn(args, "_scheduleAdmissionPolicy")) return null;
|
|
882
|
+
const value = args._scheduleAdmissionPolicy;
|
|
883
|
+
if (!record(value) || Object.keys(value).sort().join(",") !== "keyId,queue,requireIntegrity,version" || value.version !== 1 || value.requireIntegrity !== true || typeof value.queue !== "string" || !value.queue.trim() || typeof value.keyId !== "string" || !value.keyId.trim() || value.keyId.length > 256) throw new TypeError("Unsupported or malformed schedule admission policy");
|
|
884
|
+
return {
|
|
885
|
+
version: 1,
|
|
886
|
+
requireIntegrity: true,
|
|
887
|
+
queue: value.queue,
|
|
888
|
+
keyId: value.keyId
|
|
889
|
+
};
|
|
890
|
+
}
|
|
891
|
+
function record(value) {
|
|
892
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
893
|
+
const prototype = Object.getPrototypeOf(value);
|
|
894
|
+
return prototype === Object.prototype || prototype === null;
|
|
895
|
+
}
|
|
896
|
+
function identity(value, name) {
|
|
897
|
+
if (typeof value !== "string" || !value.trim()) throw new TypeError(`Schedule admission requires ${name}`);
|
|
898
|
+
return value;
|
|
899
|
+
}
|
|
900
|
+
function getScheduleAdmissionPayload(job, keyId) {
|
|
901
|
+
if (!job || typeof job !== "object") throw new TypeError("Schedule admission requires a job");
|
|
902
|
+
const row = job;
|
|
903
|
+
if (!record(row.args)) throw new TypeError("Schedule admission requires JSON object arguments");
|
|
904
|
+
const scheduledFor = identity(row.args._scheduledFor, "scheduledFor");
|
|
905
|
+
const epoch = Date.parse(scheduledFor);
|
|
906
|
+
if (!Number.isFinite(epoch) || new Date(epoch).toISOString() !== scheduledFor) throw new TypeError("Schedule admission requires canonical UTC scheduledFor");
|
|
907
|
+
const signatureKey = identity(keyId, "keyId");
|
|
908
|
+
if (signatureKey.length > 256) throw new TypeError("Invalid admission keyId");
|
|
909
|
+
const policy = getScheduleAdmissionPolicy(row.args);
|
|
910
|
+
if (policy && (policy.queue !== row.queue || policy.keyId !== signatureKey)) throw new TypeError("Schedule admission does not match its durable policy");
|
|
911
|
+
const { _scheduleAdmission: _, ...argumentsWithoutSignature } = row.args;
|
|
912
|
+
const args = JSON.parse(JSON.stringify(argumentsWithoutSignature));
|
|
913
|
+
return {
|
|
914
|
+
purpose: "smrt.schedule-admission",
|
|
915
|
+
version: 1,
|
|
916
|
+
keyId: signatureKey,
|
|
917
|
+
jobId: identity(row.id, "jobId"),
|
|
918
|
+
tenantId: row.tenantId === null ? null : identity(row.tenantId, "tenantId"),
|
|
919
|
+
scheduleId: identity(row.args._scheduleId, "scheduleId"),
|
|
920
|
+
scheduledFor,
|
|
921
|
+
queue: identity(row.queue, "queue"),
|
|
922
|
+
objectType: identity(row.objectType, "objectType"),
|
|
923
|
+
objectId: row.objectId === null ? null : identity(row.objectId, "objectId"),
|
|
924
|
+
method: identity(row.method, "method"),
|
|
925
|
+
args
|
|
926
|
+
};
|
|
927
|
+
}
|
|
928
|
+
function verifyScheduleAdmission(job, signer) {
|
|
929
|
+
try {
|
|
930
|
+
if (!job || typeof job !== "object") return false;
|
|
931
|
+
const args = job.args;
|
|
932
|
+
if (!record(args)) return false;
|
|
933
|
+
const integrity = args._scheduleAdmission;
|
|
934
|
+
if (!record(integrity) || Object.keys(integrity).length !== 3 || ![
|
|
935
|
+
"version",
|
|
936
|
+
"keyId",
|
|
937
|
+
"signature"
|
|
938
|
+
].every((key) => Object.hasOwn(integrity, key)) || integrity.version !== 1 || typeof integrity.keyId !== "string" || !integrity.keyId.trim() || integrity.keyId.length > 256 || typeof integrity.signature !== "string" || !integrity.signature.trim()) return false;
|
|
939
|
+
return signer.verify(getScheduleAdmissionPayload(job, integrity.keyId), integrity) === true;
|
|
940
|
+
} catch {
|
|
941
|
+
return false;
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
//#endregion
|
|
877
945
|
//#region src/schedule-runner.ts
|
|
946
|
+
var ScheduleAdmissionBlockedError = class extends Error {};
|
|
878
947
|
var SCHEDULED_JOB_QUEUE = "agents";
|
|
879
948
|
var DEFAULT_CONFIG = {
|
|
880
949
|
id: "",
|
|
881
950
|
pollInterval: 6e4,
|
|
882
951
|
batchSize: 50,
|
|
952
|
+
occurrenceSigner: null,
|
|
953
|
+
queue: SCHEDULED_JOB_QUEUE,
|
|
883
954
|
staleJobThresholdMs: 9e4,
|
|
884
955
|
taskHeartbeatInterval: DEFAULT_TASK_HEARTBEAT_INTERVAL_MS
|
|
885
956
|
};
|
|
886
957
|
var ScheduleRunner = class extends EventEmitter {
|
|
958
|
+
/** Public contracts hosts may require before admitting enabled schedules. */
|
|
959
|
+
static capabilities = Object.freeze({
|
|
960
|
+
atomicOccurrences: true,
|
|
961
|
+
scopedAdmission: true,
|
|
962
|
+
drain: true,
|
|
963
|
+
occurrenceIntegrity: true,
|
|
964
|
+
requiredOccurrenceIntegrity: true
|
|
965
|
+
});
|
|
887
966
|
id;
|
|
888
967
|
config;
|
|
889
968
|
jobCollection = null;
|
|
890
|
-
workerCollection = null;
|
|
891
969
|
running = false;
|
|
892
970
|
pollTimer = null;
|
|
971
|
+
pollInFlight = null;
|
|
972
|
+
stopping = null;
|
|
893
973
|
db = null;
|
|
894
974
|
logger = createLogger(true);
|
|
895
975
|
constructor(config = {}) {
|
|
@@ -900,6 +980,35 @@ var ScheduleRunner = class extends EventEmitter {
|
|
|
900
980
|
id: config.id || `schedule_${createId().slice(0, 8)}`
|
|
901
981
|
};
|
|
902
982
|
this.id = this.config.id;
|
|
983
|
+
const signer = this.config.occurrenceSigner;
|
|
984
|
+
if (signer != null && (typeof signer.keyId !== "string" || !signer.keyId.trim() || signer.keyId.length > 256 || typeof signer.sign !== "function" || typeof signer.verify !== "function")) throw new TypeError("occurrenceSigner must be a trusted host signer with a current keyId");
|
|
985
|
+
if (!Number.isInteger(this.config.batchSize) || this.config.batchSize <= 0) throw new TypeError("batchSize must be a positive integer");
|
|
986
|
+
if (!Number.isFinite(this.config.pollInterval) || this.config.pollInterval <= 0 || this.config.pollInterval > 2147483647) throw new TypeError("pollInterval must be a finite positive Node timer interval");
|
|
987
|
+
if (typeof this.config.queue !== "string" || !this.config.queue.trim()) throw new TypeError("queue must be nonblank");
|
|
988
|
+
for (const values of [this.config.agentTypes, this.config.tenantIds]) if (values !== void 0 && (!Array.isArray(values) || values.some((value) => value !== null && (typeof value !== "string" || !value.trim())))) throw new TypeError("ScheduleRunner scopes must contain nonblank identities");
|
|
989
|
+
if (this.config.agentTypes?.some((value) => value == null)) throw new TypeError("agentTypes cannot contain null");
|
|
990
|
+
if (this.config.agentTypes) this.config.agentTypes = [...this.config.agentTypes];
|
|
991
|
+
if (this.config.tenantIds) this.config.tenantIds = [...this.config.tenantIds];
|
|
992
|
+
}
|
|
993
|
+
scheduleScope() {
|
|
994
|
+
const terms = [];
|
|
995
|
+
const params = [];
|
|
996
|
+
if (this.config.agentTypes !== void 0) {
|
|
997
|
+
terms.push(this.config.agentTypes.length ? `agent_type IN (${this.config.agentTypes.map(() => "?").join(", ")})` : "1 = 0");
|
|
998
|
+
params.push(...this.config.agentTypes);
|
|
999
|
+
}
|
|
1000
|
+
if (this.config.tenantIds !== void 0) {
|
|
1001
|
+
const tenants = this.config.tenantIds.filter((id) => id !== null);
|
|
1002
|
+
const parts = [];
|
|
1003
|
+
if (tenants.length) parts.push(`tenant_id IN (${tenants.map(() => "?").join(", ")})`);
|
|
1004
|
+
if (this.config.tenantIds.includes(null)) parts.push("tenant_id IS NULL");
|
|
1005
|
+
terms.push(parts.length ? `(${parts.join(" OR ")})` : "1 = 0");
|
|
1006
|
+
params.push(...tenants);
|
|
1007
|
+
}
|
|
1008
|
+
return {
|
|
1009
|
+
sql: terms.length ? ` AND ${terms.join(" AND ")}` : "",
|
|
1010
|
+
params
|
|
1011
|
+
};
|
|
903
1012
|
}
|
|
904
1013
|
/**
|
|
905
1014
|
* Initialize the runner with database connection
|
|
@@ -907,14 +1016,15 @@ var ScheduleRunner = class extends EventEmitter {
|
|
|
907
1016
|
async initialize(db) {
|
|
908
1017
|
this.db = db;
|
|
909
1018
|
this.jobCollection = await SmrtJobCollection.create({ db });
|
|
910
|
-
this.workerCollection = await SmrtWorkerCollection.create({ db });
|
|
911
1019
|
}
|
|
912
1020
|
/**
|
|
913
1021
|
* Start processing schedules
|
|
914
1022
|
*/
|
|
915
1023
|
async start() {
|
|
1024
|
+
if (this.stopping) await this.stopping;
|
|
916
1025
|
if (this.running) return;
|
|
917
1026
|
if (!this.db) throw new Error("ScheduleRunner not initialized. Call initialize() first.");
|
|
1027
|
+
if (!this.db.transaction) throw new Error("ScheduleRunner requires transaction support");
|
|
918
1028
|
this.running = true;
|
|
919
1029
|
this.startPolling();
|
|
920
1030
|
this.emit("runner:started");
|
|
@@ -924,14 +1034,23 @@ var ScheduleRunner = class extends EventEmitter {
|
|
|
924
1034
|
* Stop processing schedules
|
|
925
1035
|
*/
|
|
926
1036
|
async stop() {
|
|
927
|
-
if (
|
|
1037
|
+
if (this.stopping) return this.stopping;
|
|
1038
|
+
if (!this.running && !this.pollInFlight) return;
|
|
928
1039
|
this.running = false;
|
|
929
1040
|
if (this.pollTimer) {
|
|
930
1041
|
clearTimeout(this.pollTimer);
|
|
931
1042
|
this.pollTimer = null;
|
|
932
1043
|
}
|
|
933
|
-
this.
|
|
934
|
-
|
|
1044
|
+
this.stopping = (async () => {
|
|
1045
|
+
await this.pollInFlight;
|
|
1046
|
+
this.emit("runner:stopped");
|
|
1047
|
+
this.logger.info("ScheduleRunner stopped", { id: this.id });
|
|
1048
|
+
})();
|
|
1049
|
+
try {
|
|
1050
|
+
await this.stopping;
|
|
1051
|
+
} finally {
|
|
1052
|
+
this.stopping = null;
|
|
1053
|
+
}
|
|
935
1054
|
}
|
|
936
1055
|
/**
|
|
937
1056
|
* Check if runner is running
|
|
@@ -947,27 +1066,28 @@ var ScheduleRunner = class extends EventEmitter {
|
|
|
947
1066
|
*/
|
|
948
1067
|
async handleJobCompletion(scheduleId, success, errorMessage) {
|
|
949
1068
|
if (!this.db) return;
|
|
1069
|
+
const scope = this.scheduleScope();
|
|
950
1070
|
const safeErrorMessage = redactErrorMessage(errorMessage ?? "Unknown error");
|
|
951
1071
|
try {
|
|
952
1072
|
if (success) {
|
|
953
|
-
await this.db.query(`UPDATE _smrt_agent_schedules
|
|
1073
|
+
if ((await this.db.query(`UPDATE _smrt_agent_schedules
|
|
954
1074
|
SET running_count = CASE WHEN COALESCE(running_count, 0) > 0 THEN running_count - 1 ELSE 0 END,
|
|
955
1075
|
last_run = ?,
|
|
956
1076
|
last_status = 'success',
|
|
957
1077
|
last_error = NULL,
|
|
958
1078
|
run_count = COALESCE(run_count, 0) + 1,
|
|
959
1079
|
success_count = COALESCE(success_count, 0) + 1
|
|
960
|
-
WHERE id =
|
|
1080
|
+
WHERE id = ?${scope.sql} RETURNING id`, (/* @__PURE__ */ new Date()).toISOString(), scheduleId, ...scope.params)).rows.length !== 1) return;
|
|
961
1081
|
this.emit("schedule:completed", scheduleId);
|
|
962
1082
|
} else {
|
|
963
|
-
await this.db.query(`UPDATE _smrt_agent_schedules
|
|
1083
|
+
if ((await this.db.query(`UPDATE _smrt_agent_schedules
|
|
964
1084
|
SET running_count = CASE WHEN COALESCE(running_count, 0) > 0 THEN running_count - 1 ELSE 0 END,
|
|
965
1085
|
last_run = ?,
|
|
966
1086
|
last_status = 'failed',
|
|
967
1087
|
last_error = ?,
|
|
968
1088
|
run_count = COALESCE(run_count, 0) + 1,
|
|
969
1089
|
failure_count = COALESCE(failure_count, 0) + 1
|
|
970
|
-
WHERE id =
|
|
1090
|
+
WHERE id = ?${scope.sql} RETURNING id`, (/* @__PURE__ */ new Date()).toISOString(), safeErrorMessage, scheduleId, ...scope.params)).rows.length !== 1) return;
|
|
971
1091
|
this.emit("schedule:failed", scheduleId, safeErrorMessage);
|
|
972
1092
|
}
|
|
973
1093
|
} catch (err) {
|
|
@@ -984,10 +1104,13 @@ var ScheduleRunner = class extends EventEmitter {
|
|
|
984
1104
|
const poll = async () => {
|
|
985
1105
|
if (!this.running) return;
|
|
986
1106
|
try {
|
|
987
|
-
|
|
1107
|
+
this.pollInFlight = this.poll();
|
|
1108
|
+
await this.pollInFlight;
|
|
988
1109
|
} catch (error) {
|
|
989
1110
|
this.emit("runner:error", error);
|
|
990
1111
|
this.logger.error("ScheduleRunner poll error", { error });
|
|
1112
|
+
} finally {
|
|
1113
|
+
this.pollInFlight = null;
|
|
991
1114
|
}
|
|
992
1115
|
if (this.running) this.pollTimer = setTimeout(poll, this.config.pollInterval);
|
|
993
1116
|
};
|
|
@@ -998,110 +1121,123 @@ var ScheduleRunner = class extends EventEmitter {
|
|
|
998
1121
|
*/
|
|
999
1122
|
async poll() {
|
|
1000
1123
|
if (!this.db || !this.jobCollection) return;
|
|
1124
|
+
const managedPoll = this.running;
|
|
1001
1125
|
await this.recoverStaleScheduleState();
|
|
1002
1126
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1003
|
-
const
|
|
1127
|
+
const scope = this.scheduleScope();
|
|
1128
|
+
const result = await this.db.query(`SELECT *, CAST(id AS VARCHAR) AS schedule_id_text, CAST(tenant_id AS VARCHAR) AS schedule_tenant_text, CAST(next_run AS VARCHAR) AS occurrence_time FROM _smrt_agent_schedules
|
|
1004
1129
|
WHERE enabled = true
|
|
1005
1130
|
AND status = 'active'
|
|
1006
|
-
AND next_run <=
|
|
1131
|
+
AND next_run <= ?${scope.sql}
|
|
1007
1132
|
AND COALESCE(running_count, 0) < COALESCE(max_concurrent, 1)
|
|
1008
1133
|
ORDER BY next_run ASC
|
|
1009
|
-
LIMIT ?`, now, this.config.batchSize);
|
|
1010
|
-
for (const row of result.rows)
|
|
1134
|
+
LIMIT ?`, now, ...scope.params, this.config.batchSize);
|
|
1135
|
+
for (const row of result.rows) {
|
|
1136
|
+
if (managedPoll && !this.running) break;
|
|
1137
|
+
await this.triggerSchedule(portableScheduleRow(row), managedPoll);
|
|
1138
|
+
}
|
|
1011
1139
|
}
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
*
|
|
1019
|
-
* Staleness keys on worker *liveness* (issue #1474), not per-job heartbeat
|
|
1020
|
-
* freshness: a job whose `worker_id` is live in this process or holds a fresh
|
|
1021
|
-
* lease in `_smrt_workers` is healthy even if its handler is holding the loop
|
|
1022
|
-
* synchronously. ScheduleRunner has no in-process active-job set, so this is
|
|
1023
|
-
* its entire correctness mechanism.
|
|
1024
|
-
*/
|
|
1025
|
-
async recoverStaleScheduleState() {
|
|
1026
|
-
if (!this.db || !this.workerCollection) return;
|
|
1027
|
-
const schedules = (await this.db.query(`SELECT id, running_count
|
|
1028
|
-
FROM _smrt_agent_schedules
|
|
1029
|
-
WHERE COALESCE(running_count, 0) > 0`)).rows;
|
|
1030
|
-
if (schedules.length === 0) return;
|
|
1031
|
-
const workersReady = await this.workerCollection.tableReady();
|
|
1032
|
-
const freshLeaseKeys = workersReady ? await this.workerCollection.freshLeaseWorkerKeys() : /* @__PURE__ */ new Set();
|
|
1033
|
-
const jobRows = (await this.db.query(`SELECT id, args, worker_id
|
|
1034
|
-
FROM _smrt_jobs
|
|
1035
|
-
WHERE status = 'running'`)).rows;
|
|
1036
|
-
const stateBySchedule = /* @__PURE__ */ new Map();
|
|
1037
|
-
for (const schedule of schedules) stateBySchedule.set(schedule.id, {
|
|
1038
|
-
live: 0,
|
|
1039
|
-
staleJobIds: []
|
|
1040
|
-
});
|
|
1041
|
-
for (const row of jobRows) {
|
|
1042
|
-
const scheduleId = this.getScheduleIdFromJobArgs(row.args);
|
|
1043
|
-
if (!scheduleId) continue;
|
|
1044
|
-
const state = stateBySchedule.get(scheduleId);
|
|
1045
|
-
if (!state) continue;
|
|
1046
|
-
if (!(workersReady ? isWorkerAlive(row.worker_id, freshLeaseKeys) : true)) state.staleJobIds.push(row.id);
|
|
1047
|
-
else state.live += 1;
|
|
1140
|
+
assertAdmissionHost(schedule) {
|
|
1141
|
+
let policy;
|
|
1142
|
+
try {
|
|
1143
|
+
policy = getScheduleAdmissionPolicy(schedule.method_args || {});
|
|
1144
|
+
} catch {
|
|
1145
|
+
throw new ScheduleAdmissionBlockedError("INVALID_ADMISSION_POLICY");
|
|
1048
1146
|
}
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1147
|
+
if (!policy) return;
|
|
1148
|
+
if (!this.config.occurrenceSigner) throw new ScheduleAdmissionBlockedError("MISSING_OCCURRENCE_SIGNER");
|
|
1149
|
+
if (this.config.occurrenceSigner.keyId !== policy.keyId) throw new ScheduleAdmissionBlockedError("WRONG_OCCURRENCE_KEY");
|
|
1150
|
+
if (this.config.queue !== policy.queue) throw new ScheduleAdmissionBlockedError("WRONG_OCCURRENCE_QUEUE");
|
|
1151
|
+
}
|
|
1152
|
+
reportBlocked(schedule, error) {
|
|
1153
|
+
const diagnostic = {
|
|
1154
|
+
scheduleId: String(schedule.id),
|
|
1155
|
+
reason: error.message
|
|
1156
|
+
};
|
|
1157
|
+
this.emit("schedule:blocked", diagnostic);
|
|
1158
|
+
this.logger.warn("Schedule admission blocked by durable policy", diagnostic);
|
|
1159
|
+
}
|
|
1160
|
+
/** Pending retries occupy slots too; TaskRunner alone owns worker recovery. */
|
|
1161
|
+
async countScheduleJobs(db, schedule) {
|
|
1162
|
+
return countScheduleJobs(db, String(schedule.id), schedule.tenant_id == null ? null : String(schedule.tenant_id), {
|
|
1163
|
+
objectType: String(schedule.agent_type),
|
|
1164
|
+
objectId: schedule.agent_id == null ? null : String(schedule.agent_id),
|
|
1165
|
+
method: String(schedule.method || "run")
|
|
1052
1166
|
});
|
|
1053
|
-
const recoveredJobIds = /* @__PURE__ */ new Set();
|
|
1054
|
-
if (staleJobIds.length > 0) {
|
|
1055
|
-
const placeholders = staleJobIds.map(() => "?").join(", ");
|
|
1056
|
-
const result = await this.db.query(`UPDATE _smrt_jobs
|
|
1057
|
-
SET status = 'failed',
|
|
1058
|
-
completed_at = ?,
|
|
1059
|
-
last_error = ?,
|
|
1060
|
-
worker_id = NULL,
|
|
1061
|
-
worker_heartbeat = NULL
|
|
1062
|
-
WHERE status = 'running'
|
|
1063
|
-
AND id IN (${placeholders})
|
|
1064
|
-
RETURNING id`, now, "Recovered orphaned scheduled job: its owning worker is no longer alive (no fresh liveness lease in _smrt_workers and not running in this process).", ...staleJobIds);
|
|
1065
|
-
for (const row of result.rows) if (typeof row.id === "string") recoveredJobIds.add(row.id);
|
|
1066
|
-
}
|
|
1067
|
-
for (const schedule of schedules) {
|
|
1068
|
-
const state = stateBySchedule.get(schedule.id);
|
|
1069
|
-
if (!state) continue;
|
|
1070
|
-
const desiredRunningCount = state.live;
|
|
1071
|
-
const recoveredCount = state.staleJobIds.filter((id) => recoveredJobIds.has(id)).length;
|
|
1072
|
-
if (Number(schedule.running_count) === desiredRunningCount && recoveredCount === 0) continue;
|
|
1073
|
-
if (recoveredCount > 0) {
|
|
1074
|
-
await this.db.query(`UPDATE _smrt_agent_schedules
|
|
1075
|
-
SET running_count = ?,
|
|
1076
|
-
last_run = ?,
|
|
1077
|
-
last_status = 'failed',
|
|
1078
|
-
last_error = ?,
|
|
1079
|
-
run_count = COALESCE(run_count, 0) + ?,
|
|
1080
|
-
failure_count = COALESCE(failure_count, 0) + ?
|
|
1081
|
-
WHERE id = ?`, desiredRunningCount, now, `Recovered ${recoveredCount} orphaned scheduled job(s) from dead worker(s)`, recoveredCount, recoveredCount, schedule.id);
|
|
1082
|
-
this.emit("schedule:failed", schedule.id, `Recovered ${recoveredCount} orphaned scheduled job(s)`);
|
|
1083
|
-
} else await this.db.query(`UPDATE _smrt_agent_schedules
|
|
1084
|
-
SET running_count = ?
|
|
1085
|
-
WHERE id = ?`, desiredRunningCount, schedule.id);
|
|
1086
|
-
}
|
|
1087
1167
|
}
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
if (
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1168
|
+
/** Reconcile cached slots without changing TaskRunner-owned job lifecycle. */
|
|
1169
|
+
async recoverStaleScheduleState() {
|
|
1170
|
+
const db = this.db;
|
|
1171
|
+
if (!db?.transaction) return;
|
|
1172
|
+
const scope = this.scheduleScope();
|
|
1173
|
+
const schedules = await db.query(`SELECT *, CAST(id AS VARCHAR) AS schedule_id_text, CAST(tenant_id AS VARCHAR) AS schedule_tenant_text FROM _smrt_agent_schedules WHERE 1 = 1${scope.sql}`, ...scope.params);
|
|
1174
|
+
for (const row of schedules.rows) {
|
|
1175
|
+
const candidate = portableScheduleRow(row);
|
|
1176
|
+
try {
|
|
1177
|
+
this.assertAdmissionHost(candidate);
|
|
1178
|
+
await db.transaction(async (tx) => {
|
|
1179
|
+
const locked = await tx.query(`UPDATE _smrt_agent_schedules SET running_count = running_count WHERE id = ?${scope.sql} RETURNING *, CAST(id AS VARCHAR) AS schedule_id_text, CAST(tenant_id AS VARCHAR) AS schedule_tenant_text, CAST(next_run AS VARCHAR) AS occurrence_time`, candidate.id, ...scope.params);
|
|
1180
|
+
if (locked.rows.length !== 1) return;
|
|
1181
|
+
const schedule = portableScheduleRow(locked.rows[0]);
|
|
1182
|
+
this.assertAdmissionHost(schedule);
|
|
1183
|
+
const occupied = await this.countScheduleJobs(tx, schedule);
|
|
1184
|
+
await tx.query("UPDATE _smrt_agent_schedules SET running_count = ? WHERE id = ?", occupied, candidate.id);
|
|
1185
|
+
});
|
|
1186
|
+
} catch (error) {
|
|
1187
|
+
if (!(error instanceof ScheduleAdmissionBlockedError)) throw error;
|
|
1188
|
+
this.reportBlocked(candidate, error);
|
|
1189
|
+
}
|
|
1095
1190
|
}
|
|
1096
|
-
if (!parsedArgs || typeof parsedArgs !== "object" || Array.isArray(parsedArgs)) return null;
|
|
1097
|
-
const scheduleId = parsedArgs._scheduleId;
|
|
1098
|
-
return typeof scheduleId === "string" && scheduleId.length > 0 ? scheduleId : null;
|
|
1099
1191
|
}
|
|
1100
1192
|
/**
|
|
1101
1193
|
* Trigger a schedule by creating a job
|
|
1102
1194
|
*/
|
|
1103
|
-
async triggerSchedule(
|
|
1195
|
+
async triggerSchedule(candidate, managedPoll = false) {
|
|
1104
1196
|
if (!this.db || !this.jobCollection) return;
|
|
1197
|
+
candidate = portableScheduleRow(candidate);
|
|
1198
|
+
const db = this.db;
|
|
1199
|
+
let admission;
|
|
1200
|
+
try {
|
|
1201
|
+
this.assertAdmissionHost(candidate);
|
|
1202
|
+
if (!db.transaction) throw new Error("ScheduleRunner requires transaction support");
|
|
1203
|
+
admission = await db.transaction(async (tx) => {
|
|
1204
|
+
if (managedPoll && !this.running) return;
|
|
1205
|
+
const expected = candidate.occurrence_time ?? candidate.next_run;
|
|
1206
|
+
const scope = this.scheduleScope();
|
|
1207
|
+
const claimed = await tx.query(`UPDATE _smrt_agent_schedules SET running_count = running_count
|
|
1208
|
+
WHERE id = ? AND enabled = TRUE AND status = 'active'
|
|
1209
|
+
AND next_run <= ?${expected == null ? "" : " AND next_run = ?"}${scope.sql}
|
|
1210
|
+
RETURNING *, CAST(id AS VARCHAR) AS schedule_id_text, CAST(tenant_id AS VARCHAR) AS schedule_tenant_text, CAST(next_run AS VARCHAR) AS occurrence_time`, candidate.id, (/* @__PURE__ */ new Date()).toISOString(), ...expected == null ? [] : [expected], ...scope.params);
|
|
1211
|
+
if (claimed.rows.length !== 1 || managedPoll && !this.running) return;
|
|
1212
|
+
const schedule = portableScheduleRow(claimed.rows[0]);
|
|
1213
|
+
this.assertAdmissionHost(schedule);
|
|
1214
|
+
const occupied = await this.countScheduleJobs(tx, schedule);
|
|
1215
|
+
await tx.query("UPDATE _smrt_agent_schedules SET running_count = ? WHERE id = ?", occupied, schedule.id);
|
|
1216
|
+
if (occupied >= Number(schedule.max_concurrent ?? 1)) return;
|
|
1217
|
+
const jobs = await SmrtJobCollection.create({ db: tx });
|
|
1218
|
+
return this.triggerLockedSchedule(schedule, tx, jobs, occupied);
|
|
1219
|
+
});
|
|
1220
|
+
} catch (error) {
|
|
1221
|
+
if (error instanceof ScheduleAdmissionBlockedError) {
|
|
1222
|
+
this.reportBlocked(candidate, error);
|
|
1223
|
+
return;
|
|
1224
|
+
}
|
|
1225
|
+
await db.query("UPDATE _smrt_agent_schedules SET last_error = ? WHERE id = ?", redactErrorForPersistence(error), candidate.id);
|
|
1226
|
+
this.emit("schedule:error", {
|
|
1227
|
+
id: String(candidate.id),
|
|
1228
|
+
agentType: String(candidate.agent_type),
|
|
1229
|
+
agentId: candidate.agent_id,
|
|
1230
|
+
cron: String(candidate.cron)
|
|
1231
|
+
}, error);
|
|
1232
|
+
return;
|
|
1233
|
+
}
|
|
1234
|
+
if (admission?.error) this.emit("schedule:error", admission.schedule, admission.error);
|
|
1235
|
+
else if (admission) {
|
|
1236
|
+
this.emit("schedule:triggered", admission.schedule);
|
|
1237
|
+
this.logger.info("Schedule triggered", { scheduleId: admission.schedule.id });
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
async triggerLockedSchedule(schedule, db, jobs, occupied) {
|
|
1105
1241
|
const rawAgentType = schedule.agent_type;
|
|
1106
1242
|
const canonicalAgentType = ObjectRegistry.getClass(rawAgentType)?.qualifiedName || rawAgentType;
|
|
1107
1243
|
const scheduleInfo = {
|
|
@@ -1110,67 +1246,84 @@ var ScheduleRunner = class extends EventEmitter {
|
|
|
1110
1246
|
agentId: schedule.agent_id,
|
|
1111
1247
|
cron: schedule.cron
|
|
1112
1248
|
};
|
|
1249
|
+
let methodArgs = {};
|
|
1250
|
+
if (schedule.method_args) methodArgs = typeof schedule.method_args === "string" ? JSON.parse(schedule.method_args) : schedule.method_args;
|
|
1251
|
+
if (!methodArgs || typeof methodArgs !== "object" || Array.isArray(methodArgs)) throw new TypeError("Schedule method_args must be a JSON object");
|
|
1252
|
+
for (const key of [
|
|
1253
|
+
"_scheduleId",
|
|
1254
|
+
"_scheduledFor",
|
|
1255
|
+
"_agentConfig",
|
|
1256
|
+
"_scheduleAdmission"
|
|
1257
|
+
]) if (Object.hasOwn(methodArgs, key)) throw new TypeError(`Schedule method_args cannot set reserved ${key}`);
|
|
1258
|
+
let agentConfig = {};
|
|
1259
|
+
if (schedule.agent_config) agentConfig = typeof schedule.agent_config === "string" ? JSON.parse(schedule.agent_config) : schedule.agent_config;
|
|
1260
|
+
const timezone = typeof schedule.timezone === "string" && schedule.timezone.trim() ? schedule.timezone.trim() : "UTC";
|
|
1113
1261
|
try {
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
const timezone = typeof schedule.timezone === "string" && schedule.timezone.trim() ? schedule.timezone.trim() : "UTC";
|
|
1119
|
-
try {
|
|
1120
|
-
validateCronExpression(schedule.cron);
|
|
1121
|
-
validateCronTimezone(timezone);
|
|
1122
|
-
} catch (error) {
|
|
1123
|
-
await this.db.query(`UPDATE _smrt_agent_schedules
|
|
1262
|
+
validateCronExpression(schedule.cron);
|
|
1263
|
+
validateCronTimezone(timezone);
|
|
1264
|
+
} catch (error) {
|
|
1265
|
+
await db.query(`UPDATE _smrt_agent_schedules
|
|
1124
1266
|
SET status = 'error', last_error = ?
|
|
1125
1267
|
WHERE id = ?`, redactErrorForPersistence(error), schedule.id);
|
|
1126
|
-
|
|
1127
|
-
this.logger.error("Schedule has an invalid cron or time zone", {
|
|
1128
|
-
scheduleId: schedule.id,
|
|
1129
|
-
error
|
|
1130
|
-
});
|
|
1131
|
-
return;
|
|
1132
|
-
}
|
|
1133
|
-
const nextRun = getNextCronDate(schedule.cron, timezone);
|
|
1134
|
-
const args = {
|
|
1135
|
-
...methodArgs,
|
|
1136
|
-
_scheduleId: schedule.id
|
|
1137
|
-
};
|
|
1138
|
-
if (Object.keys(agentConfig).length > 0) args._agentConfig = agentConfig;
|
|
1139
|
-
const job = await this.jobCollection.enqueueJob({
|
|
1140
|
-
tenantId: typeof schedule.tenant_id === "string" && schedule.tenant_id.length > 0 ? schedule.tenant_id : null,
|
|
1141
|
-
queue: SCHEDULED_JOB_QUEUE,
|
|
1142
|
-
objectType: canonicalAgentType,
|
|
1143
|
-
objectId: schedule.agent_id,
|
|
1144
|
-
method: schedule.method || "run",
|
|
1145
|
-
args,
|
|
1146
|
-
priority: 75,
|
|
1147
|
-
maxAttempts: 3,
|
|
1148
|
-
timeout: schedule.timeout || 36e5
|
|
1149
|
-
});
|
|
1150
|
-
await this.db.query(`UPDATE _smrt_agent_schedules
|
|
1151
|
-
SET agent_type = ?,
|
|
1152
|
-
running_count = running_count + 1,
|
|
1153
|
-
next_run = ?
|
|
1154
|
-
WHERE id = ?`, canonicalAgentType, nextRun.toISOString(), schedule.id);
|
|
1155
|
-
this.emit("schedule:triggered", scheduleInfo);
|
|
1156
|
-
this.logger.info("Schedule triggered", {
|
|
1157
|
-
scheduleId: schedule.id,
|
|
1158
|
-
agentType: canonicalAgentType,
|
|
1159
|
-
jobId: job.id,
|
|
1160
|
-
nextRun: nextRun.toISOString()
|
|
1161
|
-
});
|
|
1162
|
-
} catch (error) {
|
|
1163
|
-
await this.db.query(`UPDATE _smrt_agent_schedules
|
|
1164
|
-
SET last_error = ?
|
|
1165
|
-
WHERE id = ?`, redactErrorForPersistence(error), schedule.id);
|
|
1166
|
-
this.emit("schedule:error", scheduleInfo, error);
|
|
1167
|
-
this.logger.error("Schedule trigger failed", {
|
|
1268
|
+
this.logger.error("Schedule has an invalid cron or time zone", {
|
|
1168
1269
|
scheduleId: schedule.id,
|
|
1169
1270
|
error
|
|
1170
1271
|
});
|
|
1272
|
+
return {
|
|
1273
|
+
schedule: scheduleInfo,
|
|
1274
|
+
error
|
|
1275
|
+
};
|
|
1171
1276
|
}
|
|
1277
|
+
const nextRun = getNextCronDate(schedule.cron, timezone);
|
|
1278
|
+
const args = {
|
|
1279
|
+
...methodArgs,
|
|
1280
|
+
_scheduleId: String(schedule.id),
|
|
1281
|
+
_scheduledFor: scheduleOccurrenceInstant(schedule)
|
|
1282
|
+
};
|
|
1283
|
+
if (Object.keys(agentConfig).length > 0) args._agentConfig = agentConfig;
|
|
1284
|
+
const job = await jobs.enqueueJob({
|
|
1285
|
+
tenantId: typeof schedule.tenant_id === "string" && schedule.tenant_id.length > 0 ? schedule.tenant_id : null,
|
|
1286
|
+
queue: this.config.queue,
|
|
1287
|
+
objectType: canonicalAgentType,
|
|
1288
|
+
objectId: schedule.agent_id,
|
|
1289
|
+
method: schedule.method || "run",
|
|
1290
|
+
args,
|
|
1291
|
+
priority: 75,
|
|
1292
|
+
maxAttempts: 3,
|
|
1293
|
+
timeout: schedule.timeout || 36e5
|
|
1294
|
+
});
|
|
1295
|
+
if (this.config.occurrenceSigner) {
|
|
1296
|
+
const signer = this.config.occurrenceSigner;
|
|
1297
|
+
const integrity = signer.sign(getScheduleAdmissionPayload(job, signer.keyId));
|
|
1298
|
+
job.args = {
|
|
1299
|
+
...job.args,
|
|
1300
|
+
_scheduleAdmission: integrity
|
|
1301
|
+
};
|
|
1302
|
+
if (!verifyScheduleAdmission(job, signer)) throw new Error("Occurrence signer returned invalid schedule admission integrity");
|
|
1303
|
+
await job.save();
|
|
1304
|
+
}
|
|
1305
|
+
await db.query(`UPDATE _smrt_agent_schedules
|
|
1306
|
+
SET agent_type = ?,
|
|
1307
|
+
running_count = ?,
|
|
1308
|
+
next_run = ?
|
|
1309
|
+
WHERE id = ?`, canonicalAgentType, occupied + 1, nextRun.toISOString(), schedule.id);
|
|
1310
|
+
return { schedule: scheduleInfo };
|
|
1172
1311
|
}
|
|
1173
1312
|
};
|
|
1313
|
+
function portableScheduleRow(row) {
|
|
1314
|
+
return {
|
|
1315
|
+
...row,
|
|
1316
|
+
id: row.schedule_id_text ?? row.id,
|
|
1317
|
+
tenant_id: Object.hasOwn(row, "schedule_tenant_text") ? row.schedule_tenant_text : row.tenant_id
|
|
1318
|
+
};
|
|
1319
|
+
}
|
|
1320
|
+
function scheduleOccurrenceInstant(schedule) {
|
|
1321
|
+
const raw = schedule.occurrence_time ?? schedule.next_run;
|
|
1322
|
+
if (raw instanceof Date) return raw.toISOString();
|
|
1323
|
+
let text = String(raw).trim();
|
|
1324
|
+
if (/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?$/.test(text)) text = `${text.replace(" ", "T")}Z`;
|
|
1325
|
+
return new Date(text).toISOString();
|
|
1326
|
+
}
|
|
1174
1327
|
var CRON_FIELD_RANGES = [
|
|
1175
1328
|
{
|
|
1176
1329
|
name: "minute",
|
|
@@ -1374,6 +1527,6 @@ function createScheduleRunner(config) {
|
|
|
1374
1527
|
//#region src/index.ts
|
|
1375
1528
|
registerJobRetentionTasks();
|
|
1376
1529
|
//#endregion
|
|
1377
|
-
export { DEFAULT_JOB_RETENTION, DEFAULT_RETENTION_SWEEP_INTERVAL_MS, DEFAULT_TENANT_JOB_CAP, ForgeDelivery, ForgeDeliveryCollection, ForgeProjectionCheckpoint, ForgeProjectionRuntime, JOBS_RETENTION_TASK, JOB_EVENTS_RETENTION_TASK, JobBuilder, JobCancelledError, JobContextLogger, JobHandle, JobTimeoutError, MAX_JOB_RETRIES, MCP_TASKS_EXTENSION, McpTaskCancelledError, McpTaskNotFoundError, McpTaskStore, McpTaskSuspendedError, SCHEDULED_JOB_QUEUE, ScheduleRunner, SmrtJob, SmrtJobCollection, SmrtJobEvent, SmrtJobEventCollection, SmrtWorker, SmrtWorkerCollection, TaskRunner, TenantJobCapExceededError, assertWithinTenantCreationCap, backgroundEligible, clampRetries, createHmacDurableJobPayloadSigner, createMcpTaskResult, createScheduleRunner, createTaskRunner, createWorkerKey, getActiveJobExecutionContext, getBackgroundEligibleMethods, getMcpTaskMarker, getNextCronDate, isBackgroundEligibleMethod, isRunnerExecutionContext, isWorkerAlive, markBackgroundEligible, parseDelay, priorityToNumber, redactErrorForPersistence, redactErrorMessage, registerJobRetentionTasks, registerLiveWorker, requestMcpTaskContinuation, requestMcpTaskInput, startRetentionSweeper, taskFromJob, unregisterJobRetentionTasks, unregisterLiveWorker, validateCronExpression, withBackgroundJobs };
|
|
1530
|
+
export { DEFAULT_JOB_RETENTION, DEFAULT_RETENTION_SWEEP_INTERVAL_MS, DEFAULT_TENANT_JOB_CAP, ForgeDelivery, ForgeDeliveryCollection, ForgeProjectionCheckpoint, ForgeProjectionRuntime, JOBS_RETENTION_TASK, JOB_EVENTS_RETENTION_TASK, JobBuilder, JobCancelledError, JobContextLogger, JobHandle, JobTimeoutError, MAX_JOB_RETRIES, MCP_TASKS_EXTENSION, McpTaskCancelledError, McpTaskNotFoundError, McpTaskStore, McpTaskSuspendedError, SCHEDULED_JOB_QUEUE, ScheduleRunner, SmrtJob, SmrtJobCollection, SmrtJobDedupeSlot, SmrtJobEvent, SmrtJobEventCollection, SmrtWorker, SmrtWorkerCollection, TaskRunner, TenantJobCapExceededError, assertWithinTenantCreationCap, backgroundEligible, clampRetries, createHmacDurableJobPayloadSigner, createMcpTaskResult, createScheduleRunner, createTaskRunner, createWorkerKey, getActiveJobExecutionContext, getBackgroundEligibleMethods, getMcpTaskMarker, getNextCronDate, getScheduleAdmissionPayload, getScheduleAdmissionPolicy, isBackgroundEligibleMethod, isRunnerExecutionContext, isWorkerAlive, markBackgroundEligible, parseDelay, priorityToNumber, redactErrorForPersistence, redactErrorMessage, registerJobRetentionTasks, registerLiveWorker, requestMcpTaskContinuation, requestMcpTaskInput, startRetentionSweeper, taskFromJob, unregisterJobRetentionTasks, unregisterLiveWorker, validateCronExpression, verifyScheduleAdmission, withBackgroundJobs };
|
|
1378
1531
|
|
|
1379
1532
|
//# sourceMappingURL=index.js.map
|