@pikku/schedule 0.12.8 → 0.12.10

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 CHANGED
@@ -1,3 +1,56 @@
1
+ ## 0.12.10
2
+
3
+ ### Patch Changes
4
+
5
+ - de9af6a: RPCs for Pikku Studio's migrated screens. Runtime state that must be visible on a deployed app lives in `@pikku/addon-admin`; local-copy tools stay in `@pikku/addon-console`.
6
+
7
+ `@pikku/addon-admin`:
8
+
9
+ - `admin:getSchedulerHistory` returns each scheduled task's last run, next run and recent runs, from a new `SchedulerService.getTaskRuns()` (empty by default). `InMemorySchedulerService` records the last 50 runs per cron task with status, duration and error. Scope `admin:schedules:read`.
10
+ - `admin:getQueueHistory({ queueNames?, limit? })` returns live counts and recent jobs per queue, from a new optional `QueueService.inspect(queueName, { limit })`, implemented by `InMemoryQueueService` and `BullQueueService` and forwarded by `SignedQueueService`. Scope `admin:queues:read`.
11
+ - `admin:listIncomingWebhookReceipts` / `admin:getIncomingWebhookReceipt` expose received webhooks, backed by a new `IncomingWebhookService.getReceipt(receiptId)` (null by default; implemented by `KyselyIncomingWebhookService`). Scope `admin:webhooks:read`.
12
+
13
+ `@pikku/addon-console`:
14
+
15
+ - `console:variableGet` / `console:variableSet` read and write a project variable, gated on `pikku:console:variables:read` / `:write`.
16
+ - `console:runScenarios({ names?, environment? })` starts `pikku scenario run` as a detached child process and returns `{ runId }` to follow through `listScenarioRuns` / `getScenarioRun`, gated on the new `pikku:console:scenarios:run` scope. `pikku scenario run` takes `--run-id <id>` to record under a caller-chosen id.
17
+
18
+ - Updated dependencies [de9af6a]
19
+ - @pikku/core@0.12.143
20
+
21
+ ## 0.12.9
22
+
23
+ ### Patch Changes
24
+
25
+ - 15c4968: The default runtime path no longer needs `node:*`, `Buffer` or an unguarded `process`, so it loads on edge runtimes (Web APIs only).
26
+
27
+ **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.
28
+
29
+ **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.
30
+
31
+ `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`.
32
+
33
+ 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`.
34
+
35
+ 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.
36
+
37
+ `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.
38
+
39
+ `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.
40
+
41
+ `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.
42
+
43
+ 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`.
44
+
45
+ `@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.
46
+
47
+ - Updated dependencies [6f11bb5]
48
+ - Updated dependencies [0c67e33]
49
+ - Updated dependencies [15c4968]
50
+ - Updated dependencies [d75a23d]
51
+ - Updated dependencies [9b12c8a]
52
+ - @pikku/core@0.12.138
53
+
1
54
  ## 0.12.8
2
55
 
3
56
  ### Patch Changes
@@ -1,5 +1,6 @@
1
1
  import type { CoreUserSession } from '@pikku/core/types';
2
2
  import type { ScheduledTaskInfo, ScheduledTaskSummary } from '@pikku/core/services';
3
+ import type { ScheduledTaskRuns } from '@pikku/core/scheduler';
3
4
  import { SchedulerService } from '@pikku/core/services';
4
5
  /**
5
6
  * In-memory SchedulerService implementation.
@@ -8,6 +9,7 @@ import { SchedulerService } from '@pikku/core/services';
8
9
  export declare class InMemorySchedulerService extends SchedulerService {
9
10
  private cronJobs;
10
11
  private delayedTasks;
12
+ private taskRuns;
11
13
  private idCounter;
12
14
  init(): Promise<void>;
13
15
  /**
@@ -17,6 +19,7 @@ export declare class InMemorySchedulerService extends SchedulerService {
17
19
  unschedule(taskId: string): Promise<boolean>;
18
20
  getTask(taskId: string): Promise<ScheduledTaskInfo | null>;
19
21
  getAllTasks(): Promise<ScheduledTaskSummary[]>;
22
+ getTaskRuns(): Promise<Record<string, ScheduledTaskRuns>>;
20
23
  close(): Promise<void>;
21
24
  /**
22
25
  * Start recurring scheduled tasks.
@@ -27,4 +30,5 @@ export declare class InMemorySchedulerService extends SchedulerService {
27
30
  */
28
31
  stop(): Promise<void>;
29
32
  private startCronJob;
33
+ private recordRun;
30
34
  }
@@ -5,6 +5,7 @@ import { pikkuState, getSingletonServices } from '@pikku/core/state';
5
5
  import { runScheduledTask } from '@pikku/core/scheduler';
6
6
  import { getScheduledTasks } from '@pikku/core/scheduler';
7
7
  import { rpcService } from '@pikku/core/rpc';
8
+ const RUN_HISTORY_LIMIT = 50;
8
9
  const getLogger = () => {
9
10
  return pikkuState(null, 'package', 'singletonServices').logger;
10
11
  };
@@ -15,6 +16,7 @@ const getLogger = () => {
15
16
  export class InMemorySchedulerService extends SchedulerService {
16
17
  cronJobs = new Map();
17
18
  delayedTasks = new Map();
19
+ taskRuns = new Map();
18
20
  idCounter = 0;
19
21
  async init() { }
20
22
  /**
@@ -24,7 +26,7 @@ export class InMemorySchedulerService extends SchedulerService {
24
26
  const delayMs = typeof delay === 'string' ? parseDurationString(delay) : delay;
25
27
  const taskId = `inmem-${++this.idCounter}-${Date.now()}`;
26
28
  const scheduledFor = new Date(Date.now() + delayMs);
27
- const timer = setTimeout(async () => {
29
+ const run = async () => {
28
30
  this.delayedTasks.delete(taskId);
29
31
  try {
30
32
  // An RPC, not a cron task. `runScheduledTask` looks the name up in the
@@ -48,6 +50,10 @@ export class InMemorySchedulerService extends SchedulerService {
48
50
  catch (err) {
49
51
  getLogger().error(`Failed to execute delayed RPC '${rpcName}': ${err}`);
50
52
  }
53
+ };
54
+ // `run` catches and logs every error itself, so nothing can reject
55
+ const timer = setTimeout(() => {
56
+ void run();
51
57
  }, delayMs);
52
58
  this.delayedTasks.set(taskId, {
53
59
  taskId,
@@ -88,6 +94,18 @@ export class InMemorySchedulerService extends SchedulerService {
88
94
  scheduledFor: t.scheduledFor,
89
95
  }));
90
96
  }
97
+ async getTaskRuns() {
98
+ const runs = {};
99
+ for (const [name, job] of this.cronJobs) {
100
+ const history = this.taskRuns.get(name) ?? [];
101
+ runs[name] = {
102
+ nextRun: job.isActive ? job.nextDate().toJSDate() : null,
103
+ lastRun: history[0] ?? null,
104
+ history: [...history],
105
+ };
106
+ }
107
+ return runs;
108
+ }
91
109
  async close() {
92
110
  await this.stop();
93
111
  // Clear delayed tasks
@@ -110,16 +128,38 @@ export class InMemorySchedulerService extends SchedulerService {
110
128
  */
111
129
  async stop() {
112
130
  for (const [, job] of this.cronJobs) {
113
- job.stop();
131
+ await job.stop();
114
132
  }
115
133
  this.cronJobs.clear();
116
134
  }
117
135
  startCronJob(name, schedule) {
118
136
  const job = new CronJob(schedule, async () => {
119
- getLogger().info(`Running scheduled task: ${name}`);
120
- await runScheduledTask({ name });
121
- getLogger().debug(`Completed scheduled task: ${name}`);
137
+ const startedAt = new Date();
138
+ try {
139
+ getLogger().info(`Running scheduled task: ${name}`);
140
+ await runScheduledTask({ name });
141
+ getLogger().debug(`Completed scheduled task: ${name}`);
142
+ this.recordRun(name, startedAt, 'completed', null);
143
+ }
144
+ catch (err) {
145
+ const skipped = err instanceof Error && err.name === 'ScheduledTaskSkippedError';
146
+ this.recordRun(name, startedAt, skipped ? 'skipped' : 'failed', err instanceof Error ? err.message : String(err));
147
+ if (!skipped) {
148
+ getLogger().error(`Scheduled task '${name}' failed: ${err}`);
149
+ }
150
+ }
122
151
  }, null, true);
123
152
  this.cronJobs.set(name, job);
124
153
  }
154
+ recordRun(name, startedAt, status, error) {
155
+ const history = this.taskRuns.get(name) ?? [];
156
+ history.unshift({
157
+ startedAt,
158
+ status,
159
+ durationMs: Date.now() - startedAt.getTime(),
160
+ error,
161
+ });
162
+ history.length = Math.min(history.length, RUN_HISTORY_LIMIT);
163
+ this.taskRuns.set(name, history);
164
+ }
125
165
  }
@@ -0,0 +1,13 @@
1
+ ---
2
+ type: overview
3
+ title: Knowledge
4
+ description: Questions raised by the schedule package's in-memory scheduler
5
+ ---
6
+
7
+ # Knowledge
8
+
9
+ Questions about how the schedule package runs delayed work, where the code does not say what is intended.
10
+
11
+ <!-- pikku:knowledge-index -->
12
+ - [questions](questions/index.md) — something asked and not yet answered
13
+ <!-- /pikku:knowledge-index -->
@@ -0,0 +1,13 @@
1
+ ---
2
+ type: overview
3
+ title: Questions
4
+ description: Things asked of the schedule package and not yet answered
5
+ ---
6
+
7
+ # Questions
8
+
9
+ Something asked and not yet answered. The choice stays, the doubt gets recorded.
10
+
11
+ <!-- pikku:knowledge-index -->
12
+ - [Should a delayed RPC run as the session it was scheduled with?](should-a-delayed-rpc-run-as-the-session-it-was-scheduled-with.md) — The in-memory scheduler stores the session with the task and returns it from getTask, but the timer runs the RPC without it
13
+ <!-- /pikku:knowledge-index -->
@@ -0,0 +1,22 @@
1
+ ---
2
+ type: question
3
+ title: Should a delayed RPC run as the session it was scheduled with?
4
+ description: The in-memory scheduler stores the session with the task and returns it from getTask, but the timer runs the RPC without it
5
+ tags: [schedule, sessions, rpc]
6
+ ---
7
+
8
+ # Should a delayed RPC run as the session it was scheduled with?
9
+
10
+ `scheduleRPC` in `packages/schedule/src/in-memory-scheduler-service.ts` takes an optional `session`
11
+ (line 45). It stores it on the task (lines 85-92), and `getTask` returns it (line 115).
12
+
13
+ The timer callback `run` (line 52) calls `rpcService.getContextRPCService(services, {}, false)` (lines 69-74)
14
+ and then `rpc.invoke(rpcName, data)` (line 75). The `session` is not passed to either call and is not in
15
+ scope inside `run`.
16
+
17
+ The comment at lines 67-68 says the BullMQ and pg-boss schedulers "enqueue `{ rpcName, data, session }`
18
+ and invoke the RPC with it". This file does not do that for the session.
19
+
20
+ Question: should the in-memory scheduler run the RPC as the captured session, as the comment says the other
21
+ schedulers do, or is a delayed RPC meant to run with no user? The code does not settle it, and no note in
22
+ this package records the choice.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pikku/schedule",
3
- "version": "0.12.8",
3
+ "version": "0.12.10",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/pikkujs/pikku.git",
@@ -24,7 +24,7 @@
24
24
  "prepublishOnly": "bun run build"
25
25
  },
26
26
  "peerDependencies": {
27
- "@pikku/core": "^0.12.108"
27
+ "@pikku/core": "^0.12.143"
28
28
  },
29
29
  "devDependencies": {
30
30
  "@types/node": "^24.13.3"