@pikku/schedule 0.12.7 → 0.12.9
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/CHANGELOG.md +61 -0
- package/dist/in-memory-scheduler-service.js +14 -5
- package/package.json +10 -6
- package/run-tests.sh +21 -6
- package/src/in-memory-scheduler-service.test.ts +0 -94
- package/src/in-memory-scheduler-service.ts +0 -166
- package/src/index.ts +0 -6
- package/tsconfig.json +0 -18
- package/tsconfig.tsbuildinfo +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,64 @@
|
|
|
1
|
+
## 0.12.9
|
|
2
|
+
|
|
3
|
+
### Patch Changes
|
|
4
|
+
|
|
5
|
+
- 15c4968: The default runtime path no longer needs `node:*`, `Buffer` or an unguarded `process`, so it loads on edge runtimes (Web APIs only).
|
|
6
|
+
|
|
7
|
+
**Breaking:** `FileScenarioRunStore`, `scenarioArtifactContentType` and `scenarioRunSummary` leave the `@pikku/core/services` barrel because they use `node:fs`. Import them from `@pikku/core/services/file-scenario-run-store`. Pre-0.13 breaking changes still ship as a patch.
|
|
8
|
+
|
|
9
|
+
**Breaking:** the HMAC helpers in `@pikku/core/hmac` run on Web Crypto, which is async. `hmacSha256Hex`, `hmacDigest`, `verifyHmacSignature` and `verifyPublicKeySignature` now return a Promise; `timingSafeStringEqual` stays synchronous. `WebhookService.sign` and `WebhookService.verify` return a Promise, and so does `verifySlackSignature` in `@pikku/gateway-slack`: `await` them. A function-style `verify` on a webhook source may return a Promise as well. `verifyPublicKeySignature` accepts RSA and EC (P-256, P-384, P-521) PEM keys; Ed25519 and RSA-PSS keys verify as false.
|
|
10
|
+
|
|
11
|
+
`isProduction()` (and the `PIKKU_MODEL_ALIASES` and `PIKKU_ENV` reads) now ask the registered singleton services' `variables` service first, then `process.env` when `process` exists. With neither, `isProduction()` is true, so an edge deployment never exposes error details by accident. `LocalVariablesService` resolves its `process.env` default when constructed and falls back to an empty store without `process`.
|
|
12
|
+
|
|
13
|
+
Workflow invocation ids use a built-in SHA-1 and stay byte-identical. `@pikku/kysely` and the Cloudflare hibernation server use `globalThis.crypto.randomUUID()` and no `Buffer`; `@pikku/kysely` is marked `sideEffects: false`. `@pikku/ai-deepinfra` reads `DEEPINFRA_API_KEY` only when `process` exists and decodes base64 audio without `Buffer`.
|
|
14
|
+
|
|
15
|
+
Runtime tiers. A package declares where it can run in `package.json`: `"pikku": { "runtime": "edge" | "serverless" | "server" }`, with optional per-subpath overrides (`"exports": { "./dev": "server" }`). `server` is the default. `@pikku/core` and the default services are `edge` (core's Node-only subpaths are `server`), `@pikku/better-auth`, `@pikku/addon-admin` and `@pikku/cloudflare` are `serverless` (better-auth statically imports `node:crypto` scrypt), and `@pikku/addon-console` is `server` and must never land in a deployed unit.
|
|
16
|
+
|
|
17
|
+
`pikku deploy` now verifies each deployed unit before bundling it. The unit is bundled with esbuild (neutral platform, `workerd`/`worker`/`browser` conditions) under its tier's profile, ahead of the adapter's aliases and stubs so they cannot hide anything, and the build fails when the bundle holds a package declared above the unit's tier or a Node built-in the runtime does not provide. The error names the unit, package, import chain and the fix. A built-in the provider stubs is a warning. On an edge unit, a bundled `InMemory*` class also fails the build. The unit's tier is its `runtime`, else the project's own `pikku.runtime`, else the provider default (`serverless` on Cloudflare). Packages that declare nothing are judged by their imports only.
|
|
18
|
+
|
|
19
|
+
`ProviderAdapter.getRuntimeProfile(tier?)` returns the compat date, compat flags, the built-ins the runtime provides (keyed by compat date), the stubbed ones and the externals. The Cloudflare adapter derives `wrangler.toml`, the upload metadata and the bundle externals from it; `node:os` and `node:fs` are not provided before compat date 2025-09-15. The default is `nodejs_compat_v2` with compat date 2024-12-18, which is what `wrangler.toml` and Fabric's live workers already use, so Fabric deploys see no runtime change. Only the direct-API upload in `@pikku/deploy-cloudflare` (`createWorker`, used by its own `deploy()`) moves: it sent `nodejs_compat` with 2024-01-01 before. A newer date or flag is opt-in through the adapter option `new CloudflareProviderAdapter({ compatDate })` or `getCloudflareRuntimeProfile(tier, compatDate)`. From 2025-08-15 `node:http` and `node:https` exist, and from 2025-09-15 `node:os`, `node:fs` (stubbed by the build regardless) and `node:perf_hooks`; the verifier's allowed built-ins follow the effective date. A newer date changes the runtime of every worker deployed with it.
|
|
20
|
+
|
|
21
|
+
`declareScopes(['pikku:console'])` (from `@pikku/core/scope`) declares scopes by id without wiring anything. `wireAddon({ scopes })` only requires a scope of an addon's functions; the tree arrives with the addon's metadata, so a role granting `pikku:console` used to fail PKU124 unless the addon was wired, and a wired `@pikku/addon-console` lands in every unit carrying the `/rpc` catch-all. An app that grants the scope without the console now calls `declareScopes` and no longer needs the scaffold or the addon. When the addon is wired its tree and descriptions win and the bare id adds nothing.
|
|
22
|
+
|
|
23
|
+
More packages declare a tier after bundling each with the edge profile. `edge`: `@pikku/addon-graph`, `@pikku/pino`, `@pikku/jose`, `@pikku/ai-vercel`, `@pikku/ai-voice`. `serverless`: `@pikku/kysely-postgres` (postgres.js needs `node:buffer`, `stream`, `events`), `@pikku/backblaze` (`copyFile` reads a local file, which the build stubs), `@pikku/gateway-slack` (`@slack/web-api` imports `node:os` and `zlib`). `server`: `@pikku/schedule` (`cron` imports `child_process`), `@pikku/aws-services` (the AWS SDK's Node handler needs `node:http2`), `@pikku/browser` (puppeteer), and `@pikku/modelcontextprotocol` except its `./fetch` subpath, which is `edge`.
|
|
24
|
+
|
|
25
|
+
`@pikku/addon-graph` no longer needs `node:crypto` or `Buffer`: the Crypto function hashes and HMACs on Web Crypto (MD5 is built in, since Web Crypto has none) and encodes with `TextEncoder`/`atob`/`btoa`, with output unchanged.
|
|
26
|
+
|
|
27
|
+
- Updated dependencies [6f11bb5]
|
|
28
|
+
- Updated dependencies [0c67e33]
|
|
29
|
+
- Updated dependencies [15c4968]
|
|
30
|
+
- Updated dependencies [d75a23d]
|
|
31
|
+
- Updated dependencies [9b12c8a]
|
|
32
|
+
- @pikku/core@0.12.138
|
|
33
|
+
|
|
34
|
+
## 0.12.8
|
|
35
|
+
|
|
36
|
+
### Patch Changes
|
|
37
|
+
|
|
38
|
+
- 4c7a1b5: Run the monorepo's own scripts through bun instead of yarn. What moves is the
|
|
39
|
+
package manager each package's `prepublishOnly` and build scripts invoke, plus
|
|
40
|
+
the two manifest fixes bun needs to resolve the tree: `uWebSockets.js` is
|
|
41
|
+
declared with an explicit `github:` specifier, and `@pikku/uws-handler` marks
|
|
42
|
+
its `uWebSockets.js` peer optional so a bun install of a consumer that brings
|
|
43
|
+
its own uWS app does not try to fetch it from the registry.
|
|
44
|
+
|
|
45
|
+
Three published behaviours change, all of them cases where an isolated
|
|
46
|
+
`node_modules` or bun as the runtime had been papered over by yarn's hoisting:
|
|
47
|
+
|
|
48
|
+
- `@pikku/migrator-sql` turns foreign keys on when it opens a sqlite database
|
|
49
|
+
through bun. `node:sqlite` enforces them by default and `bun:sqlite` does not,
|
|
50
|
+
which silently turned every `ON DELETE CASCADE` into a no-op under
|
|
51
|
+
`bunx --bun pikku`.
|
|
52
|
+
- `@pikku/cli` resolves a deploy provider against the project being deployed
|
|
53
|
+
rather than against wherever the CLI itself is installed, which is what its
|
|
54
|
+
own "is not installed" error asks the user to arrange.
|
|
55
|
+
- `@pikku/cli` treats a specifier a runtime hands straight back — bun does this
|
|
56
|
+
for the modules it implements itself — as not resolved from the project, so
|
|
57
|
+
it falls back rather than loading the runtime's own copy.
|
|
58
|
+
|
|
59
|
+
- Updated dependencies [4c7a1b5]
|
|
60
|
+
- @pikku/core@0.12.108
|
|
61
|
+
|
|
1
62
|
## 0.12.7
|
|
2
63
|
|
|
3
64
|
### Patch Changes
|
|
@@ -24,7 +24,7 @@ export class InMemorySchedulerService extends SchedulerService {
|
|
|
24
24
|
const delayMs = typeof delay === 'string' ? parseDurationString(delay) : delay;
|
|
25
25
|
const taskId = `inmem-${++this.idCounter}-${Date.now()}`;
|
|
26
26
|
const scheduledFor = new Date(Date.now() + delayMs);
|
|
27
|
-
const
|
|
27
|
+
const run = async () => {
|
|
28
28
|
this.delayedTasks.delete(taskId);
|
|
29
29
|
try {
|
|
30
30
|
// An RPC, not a cron task. `runScheduledTask` looks the name up in the
|
|
@@ -48,6 +48,10 @@ export class InMemorySchedulerService extends SchedulerService {
|
|
|
48
48
|
catch (err) {
|
|
49
49
|
getLogger().error(`Failed to execute delayed RPC '${rpcName}': ${err}`);
|
|
50
50
|
}
|
|
51
|
+
};
|
|
52
|
+
// `run` catches and logs every error itself, so nothing can reject
|
|
53
|
+
const timer = setTimeout(() => {
|
|
54
|
+
void run();
|
|
51
55
|
}, delayMs);
|
|
52
56
|
this.delayedTasks.set(taskId, {
|
|
53
57
|
taskId,
|
|
@@ -110,15 +114,20 @@ export class InMemorySchedulerService extends SchedulerService {
|
|
|
110
114
|
*/
|
|
111
115
|
async stop() {
|
|
112
116
|
for (const [, job] of this.cronJobs) {
|
|
113
|
-
job.stop();
|
|
117
|
+
await job.stop();
|
|
114
118
|
}
|
|
115
119
|
this.cronJobs.clear();
|
|
116
120
|
}
|
|
117
121
|
startCronJob(name, schedule) {
|
|
118
122
|
const job = new CronJob(schedule, async () => {
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
123
|
+
try {
|
|
124
|
+
getLogger().info(`Running scheduled task: ${name}`);
|
|
125
|
+
await runScheduledTask({ name });
|
|
126
|
+
getLogger().debug(`Completed scheduled task: ${name}`);
|
|
127
|
+
}
|
|
128
|
+
catch (err) {
|
|
129
|
+
getLogger().error(`Scheduled task '${name}' failed: ${err}`);
|
|
130
|
+
}
|
|
122
131
|
}, null, true);
|
|
123
132
|
this.cronJobs.set(name, job);
|
|
124
133
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pikku/schedule",
|
|
3
|
-
"version": "0.12.
|
|
3
|
+
"version": "0.12.9",
|
|
4
|
+
"repository": {
|
|
5
|
+
"type": "git",
|
|
6
|
+
"url": "git+https://github.com/pikkujs/pikku.git",
|
|
7
|
+
"directory": "packages/schedule"
|
|
8
|
+
},
|
|
4
9
|
"description": "In-memory scheduler service for Pikku cron wirings",
|
|
5
10
|
"author": "yasser.fadl@gmail.com",
|
|
6
11
|
"license": "MIT",
|
|
@@ -16,14 +21,13 @@
|
|
|
16
21
|
"test": "bash run-tests.sh",
|
|
17
22
|
"test:watch": "bash run-tests.sh --watch",
|
|
18
23
|
"test:coverage": "bash run-tests.sh --coverage",
|
|
19
|
-
"prepublishOnly": "
|
|
24
|
+
"prepublishOnly": "bun run build"
|
|
20
25
|
},
|
|
21
26
|
"peerDependencies": {
|
|
22
|
-
"@pikku/core": "^0.12.
|
|
27
|
+
"@pikku/core": "^0.12.138"
|
|
23
28
|
},
|
|
24
29
|
"devDependencies": {
|
|
25
|
-
"@types/node": "^24.13.3"
|
|
26
|
-
"typescript": "^6.0.3"
|
|
30
|
+
"@types/node": "^24.13.3"
|
|
27
31
|
},
|
|
28
32
|
"engines": {
|
|
29
33
|
"node": ">=24"
|
|
@@ -39,4 +43,4 @@
|
|
|
39
43
|
"default": "./dist/index.js"
|
|
40
44
|
}
|
|
41
45
|
}
|
|
42
|
-
}
|
|
46
|
+
}
|
package/run-tests.sh
CHANGED
|
@@ -34,20 +34,35 @@ files=($(find src -type f -name "*.test.ts"))
|
|
|
34
34
|
# Check if any files matched the pattern
|
|
35
35
|
if [ ${#files[@]} -eq 0 ]; then
|
|
36
36
|
echo "No test files found matching pattern: $pattern"
|
|
37
|
+
if [ "${STRICT_TEST_DISCOVERY}" = "1" ]; then
|
|
38
|
+
exit 1
|
|
39
|
+
fi
|
|
37
40
|
exit 0
|
|
38
41
|
fi
|
|
39
42
|
|
|
40
|
-
# Construct the
|
|
41
|
-
|
|
43
|
+
# Construct the bun command
|
|
44
|
+
#
|
|
45
|
+
# --parallel gives every test file its own worker process, which is what node's
|
|
46
|
+
# `--test` did. Several suites keep module-level caches (a TypeScript program, a
|
|
47
|
+
# temp fixture directory) that a shared process would leak between files.
|
|
48
|
+
#
|
|
49
|
+
# --timeout because bun caps a test at 5s by default where node had no cap, and
|
|
50
|
+
# the suites that build real TypeScript programs run well past that.
|
|
51
|
+
bun_cmd=(bun test --parallel --timeout 120000)
|
|
42
52
|
|
|
43
53
|
# Append options based on flags
|
|
44
54
|
if [ "$watch_mode" = true ]; then
|
|
45
|
-
|
|
55
|
+
# --watch reruns in one process; parallel workers have nothing to watch.
|
|
56
|
+
bun_cmd=(bun test --watch --timeout 120000)
|
|
46
57
|
fi
|
|
47
58
|
|
|
48
59
|
if [ "$coverage_mode" = true ]; then
|
|
49
|
-
|
|
60
|
+
# --coverage-dir=. keeps lcov.info at the package root: CI merges every
|
|
61
|
+
# package's report by prefixing its SF paths with the file's own directory,
|
|
62
|
+
# so a nested coverage/ directory would re-root them one level too deep.
|
|
63
|
+
bun_cmd+=(--coverage --coverage-reporter=lcov --coverage-reporter=text --coverage-dir=.)
|
|
64
|
+
export PIKKU_TEST_COVERAGE=1
|
|
50
65
|
fi
|
|
51
66
|
|
|
52
|
-
# Execute the
|
|
53
|
-
"${
|
|
67
|
+
# Execute the bun command with the expanded list of files
|
|
68
|
+
"${bun_cmd[@]}" "${files[@]}"
|
|
@@ -1,94 +0,0 @@
|
|
|
1
|
-
import { describe, test } from 'node:test'
|
|
2
|
-
import assert from 'node:assert/strict'
|
|
3
|
-
import { pikkuState } from '@pikku/core/state'
|
|
4
|
-
import { addFunction } from '@pikku/core/function'
|
|
5
|
-
|
|
6
|
-
import { InMemorySchedulerService } from './in-memory-scheduler-service.js'
|
|
7
|
-
|
|
8
|
-
const waitFor = async (predicate: () => boolean, withinMs = 2000) => {
|
|
9
|
-
const deadline = Date.now() + withinMs
|
|
10
|
-
while (Date.now() < deadline) {
|
|
11
|
-
if (predicate()) return true
|
|
12
|
-
await new Promise((resolve) => setTimeout(resolve, 10))
|
|
13
|
-
}
|
|
14
|
-
return false
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
describe('InMemorySchedulerService scheduleRPC', () => {
|
|
18
|
-
test('schedules and executes delayed RPC', async () => {
|
|
19
|
-
const logger = {
|
|
20
|
-
info: () => {},
|
|
21
|
-
warn: () => {},
|
|
22
|
-
debug: () => {},
|
|
23
|
-
error: () => {},
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
pikkuState(null, 'package', 'singletonServices', {
|
|
27
|
-
logger,
|
|
28
|
-
} as any)
|
|
29
|
-
|
|
30
|
-
const scheduler = new InMemorySchedulerService()
|
|
31
|
-
try {
|
|
32
|
-
const taskId = await scheduler.scheduleRPC(50, 'testRpc', { ok: true }, {
|
|
33
|
-
userId: 'user-1',
|
|
34
|
-
} as any)
|
|
35
|
-
assert.ok(taskId)
|
|
36
|
-
|
|
37
|
-
const task = await scheduler.getTask(taskId)
|
|
38
|
-
assert.ok(task)
|
|
39
|
-
assert.equal(task.rpcName, 'testRpc')
|
|
40
|
-
} finally {
|
|
41
|
-
await scheduler.close()
|
|
42
|
-
}
|
|
43
|
-
})
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* The delay actually has to invoke the RPC, with its data.
|
|
47
|
-
*
|
|
48
|
-
* The test above only proved the task was registered, which is why the
|
|
49
|
-
* scheduler could dispatch through `runScheduledTask` — a lookup against the
|
|
50
|
-
* *cron task* registry that no scheduled RPC is ever in — and still pass.
|
|
51
|
-
* Every internally scheduled RPC failed with ScheduledTaskNotFoundError,
|
|
52
|
-
* `pikkuWorkflowSleeper` among them, so an async workflow never woke from
|
|
53
|
-
* `workflow.sleep`.
|
|
54
|
-
*/
|
|
55
|
-
test('invokes the named RPC with its data once the delay elapses', async () => {
|
|
56
|
-
const errors: string[] = []
|
|
57
|
-
const logger = {
|
|
58
|
-
info: () => {},
|
|
59
|
-
warn: () => {},
|
|
60
|
-
debug: () => {},
|
|
61
|
-
error: (message: string) => errors.push(message),
|
|
62
|
-
}
|
|
63
|
-
pikkuState(null, 'package', 'singletonServices', { logger } as any)
|
|
64
|
-
|
|
65
|
-
const calls: unknown[] = []
|
|
66
|
-
addFunction(
|
|
67
|
-
'delayedTestRpc',
|
|
68
|
-
{
|
|
69
|
-
func: async (_services: any, data: unknown) => calls.push(data),
|
|
70
|
-
} as any,
|
|
71
|
-
null
|
|
72
|
-
)
|
|
73
|
-
pikkuState(null, 'function', 'meta')['delayedTestRpc'] = {
|
|
74
|
-
name: 'delayedTestRpc',
|
|
75
|
-
sessionless: true,
|
|
76
|
-
permissions: [],
|
|
77
|
-
} as any
|
|
78
|
-
|
|
79
|
-
const scheduler = new InMemorySchedulerService()
|
|
80
|
-
try {
|
|
81
|
-
await scheduler.scheduleRPC(20, 'delayedTestRpc', {
|
|
82
|
-
runId: 'run-1',
|
|
83
|
-
stepId: 'step-1',
|
|
84
|
-
})
|
|
85
|
-
assert.ok(
|
|
86
|
-
await waitFor(() => calls.length > 0),
|
|
87
|
-
`RPC was never invoked; scheduler errors: ${JSON.stringify(errors)}`
|
|
88
|
-
)
|
|
89
|
-
assert.deepEqual(calls[0], { runId: 'run-1', stepId: 'step-1' })
|
|
90
|
-
} finally {
|
|
91
|
-
await scheduler.close()
|
|
92
|
-
}
|
|
93
|
-
})
|
|
94
|
-
})
|
|
@@ -1,166 +0,0 @@
|
|
|
1
|
-
import { CronJob } from 'cron'
|
|
2
|
-
import type { CoreUserSession } from '@pikku/core/types'
|
|
3
|
-
import type {
|
|
4
|
-
ScheduledTaskInfo,
|
|
5
|
-
ScheduledTaskSummary,
|
|
6
|
-
} from '@pikku/core/services'
|
|
7
|
-
import { SchedulerService } from '@pikku/core/services'
|
|
8
|
-
import { parseDurationString } from '@pikku/core/utils'
|
|
9
|
-
import { pikkuState, getSingletonServices } from '@pikku/core/state'
|
|
10
|
-
import { runScheduledTask } from '@pikku/core/scheduler'
|
|
11
|
-
import { getScheduledTasks } from '@pikku/core/scheduler'
|
|
12
|
-
import { rpcService } from '@pikku/core/rpc'
|
|
13
|
-
|
|
14
|
-
interface DelayedTask {
|
|
15
|
-
taskId: string
|
|
16
|
-
rpcName: string
|
|
17
|
-
data?: any
|
|
18
|
-
session?: CoreUserSession
|
|
19
|
-
scheduledFor: Date
|
|
20
|
-
timer: ReturnType<typeof setTimeout>
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
const getLogger = () => {
|
|
24
|
-
return pikkuState(null, 'package', 'singletonServices')!.logger
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* In-memory SchedulerService implementation.
|
|
29
|
-
* Uses CronJob for recurring tasks and setTimeout for delayed RPCs.
|
|
30
|
-
*/
|
|
31
|
-
export class InMemorySchedulerService extends SchedulerService {
|
|
32
|
-
private cronJobs = new Map<string, CronJob>()
|
|
33
|
-
private delayedTasks = new Map<string, DelayedTask>()
|
|
34
|
-
private idCounter = 0
|
|
35
|
-
|
|
36
|
-
async init(): Promise<void> {}
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* Schedule a one-off delayed RPC call via setTimeout
|
|
40
|
-
*/
|
|
41
|
-
async scheduleRPC(
|
|
42
|
-
delay: number | string,
|
|
43
|
-
rpcName: string,
|
|
44
|
-
data?: any,
|
|
45
|
-
session?: CoreUserSession
|
|
46
|
-
): Promise<string> {
|
|
47
|
-
const delayMs =
|
|
48
|
-
typeof delay === 'string' ? parseDurationString(delay) : delay
|
|
49
|
-
const taskId = `inmem-${++this.idCounter}-${Date.now()}`
|
|
50
|
-
const scheduledFor = new Date(Date.now() + delayMs)
|
|
51
|
-
|
|
52
|
-
const timer = setTimeout(async () => {
|
|
53
|
-
this.delayedTasks.delete(taskId)
|
|
54
|
-
try {
|
|
55
|
-
// An RPC, not a cron task. `runScheduledTask` looks the name up in the
|
|
56
|
-
// scheduler's task registry, which only ever holds wired cron tasks —
|
|
57
|
-
// so every internally-scheduled RPC died here as
|
|
58
|
-
// ScheduledTaskNotFoundError. The one that matters most is
|
|
59
|
-
// `pikkuWorkflowSleeper`: it is registered by the workflow service as a
|
|
60
|
-
// function, and it is what wakes a run from `workflow.sleep`. With the
|
|
61
|
-
// wake-up lost to a swallowed log line, an async workflow run stopped
|
|
62
|
-
// at its first sleep and stayed `running` forever.
|
|
63
|
-
//
|
|
64
|
-
// `data` has to be forwarded for the same reason. The sleeper is called
|
|
65
|
-
// with `{ runId, stepId }` and cannot identify the sleeping step
|
|
66
|
-
// without it — it was captured in `delayedTasks` but never passed on.
|
|
67
|
-
// This matches what the BullMQ and pg-boss schedulers already do:
|
|
68
|
-
// enqueue `{ rpcName, data, session }` and invoke the RPC with it.
|
|
69
|
-
const services = getSingletonServices()
|
|
70
|
-
const rpc = rpcService.getContextRPCService(
|
|
71
|
-
services as any,
|
|
72
|
-
{},
|
|
73
|
-
false
|
|
74
|
-
) as { invoke: (name: string, data: unknown) => Promise<unknown> }
|
|
75
|
-
await rpc.invoke(rpcName, data)
|
|
76
|
-
} catch (err: unknown) {
|
|
77
|
-
getLogger().error(`Failed to execute delayed RPC '${rpcName}': ${err}`)
|
|
78
|
-
}
|
|
79
|
-
}, delayMs)
|
|
80
|
-
|
|
81
|
-
this.delayedTasks.set(taskId, {
|
|
82
|
-
taskId,
|
|
83
|
-
rpcName,
|
|
84
|
-
data,
|
|
85
|
-
session,
|
|
86
|
-
scheduledFor,
|
|
87
|
-
timer,
|
|
88
|
-
})
|
|
89
|
-
|
|
90
|
-
return taskId
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
async unschedule(taskId: string): Promise<boolean> {
|
|
94
|
-
const task = this.delayedTasks.get(taskId)
|
|
95
|
-
if (task) {
|
|
96
|
-
clearTimeout(task.timer)
|
|
97
|
-
this.delayedTasks.delete(taskId)
|
|
98
|
-
return true
|
|
99
|
-
}
|
|
100
|
-
return false
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
async getTask(taskId: string): Promise<ScheduledTaskInfo | null> {
|
|
104
|
-
const task = this.delayedTasks.get(taskId)
|
|
105
|
-
if (!task) return null
|
|
106
|
-
return {
|
|
107
|
-
taskId: task.taskId,
|
|
108
|
-
rpcName: task.rpcName,
|
|
109
|
-
scheduledFor: task.scheduledFor,
|
|
110
|
-
data: task.data,
|
|
111
|
-
session: task.session,
|
|
112
|
-
status: 'scheduled',
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
async getAllTasks(): Promise<ScheduledTaskSummary[]> {
|
|
117
|
-
return Array.from(this.delayedTasks.values()).map((t) => ({
|
|
118
|
-
taskId: t.taskId,
|
|
119
|
-
rpcName: t.rpcName,
|
|
120
|
-
scheduledFor: t.scheduledFor,
|
|
121
|
-
}))
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
async close(): Promise<void> {
|
|
125
|
-
await this.stop()
|
|
126
|
-
// Clear delayed tasks
|
|
127
|
-
for (const [, task] of this.delayedTasks) {
|
|
128
|
-
clearTimeout(task.timer)
|
|
129
|
-
}
|
|
130
|
-
this.delayedTasks.clear()
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
/**
|
|
134
|
-
* Start recurring scheduled tasks.
|
|
135
|
-
*/
|
|
136
|
-
async start(): Promise<void> {
|
|
137
|
-
const scheduledTasks = getScheduledTasks()
|
|
138
|
-
for (const [, task] of scheduledTasks) {
|
|
139
|
-
this.startCronJob(task.name, task.schedule)
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
/**
|
|
144
|
-
* Stop all recurring CronJobs.
|
|
145
|
-
*/
|
|
146
|
-
async stop(): Promise<void> {
|
|
147
|
-
for (const [, job] of this.cronJobs) {
|
|
148
|
-
job.stop()
|
|
149
|
-
}
|
|
150
|
-
this.cronJobs.clear()
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
private startCronJob(name: string, schedule: string) {
|
|
154
|
-
const job = new CronJob(
|
|
155
|
-
schedule,
|
|
156
|
-
async () => {
|
|
157
|
-
getLogger().info(`Running scheduled task: ${name}`)
|
|
158
|
-
await runScheduledTask({ name })
|
|
159
|
-
getLogger().debug(`Completed scheduled task: ${name}`)
|
|
160
|
-
},
|
|
161
|
-
null,
|
|
162
|
-
true
|
|
163
|
-
)
|
|
164
|
-
this.cronJobs.set(name, job)
|
|
165
|
-
}
|
|
166
|
-
}
|
package/src/index.ts
DELETED
package/tsconfig.json
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"extends": "../tsconfig.json",
|
|
3
|
-
"compilerOptions": {
|
|
4
|
-
"rootDir": "./src",
|
|
5
|
-
"module": "Node18",
|
|
6
|
-
"outDir": "dist",
|
|
7
|
-
"target": "esnext",
|
|
8
|
-
"declaration": true,
|
|
9
|
-
"resolveJsonModule": true
|
|
10
|
-
},
|
|
11
|
-
"include": ["bin/**/*.ts", "src/**/*.ts"],
|
|
12
|
-
"exclude": ["**/*.test.ts", "node_modules", "bin/dist"],
|
|
13
|
-
"references": [
|
|
14
|
-
{
|
|
15
|
-
"path": "../core/tsconfig.json"
|
|
16
|
-
}
|
|
17
|
-
]
|
|
18
|
-
}
|
package/tsconfig.tsbuildinfo
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"root":["./src/in-memory-scheduler-service.ts","./src/index.ts"],"version":"6.0.3"}
|