@plitzi/sdk-actions 0.39.9 → 0.39.11

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,5 +1,25 @@
1
1
  # @plitzi/sdk-actions
2
2
 
3
+ ## 0.39.11
4
+
5
+ ### Patch Changes
6
+
7
+ - d0b5be6: Released with every `@plitzi` package at this version. What changed in each, and what to do when you upgrade, is in
8
+ `@plitzi/cli`'s `CHANGELOG.md`: one copy of the notes, not one per package.
9
+ - Updated dependencies [d0b5be6]
10
+ - @plitzi/sdk-kernel@0.39.11
11
+ - @plitzi/sdk-shared@0.39.11
12
+
13
+ ## 0.39.10
14
+
15
+ ### Patch Changes
16
+
17
+ - 97d3b64: Released with every `@plitzi` package at this version. What changed in each, and what to do when you upgrade, is in
18
+ `@plitzi/cli`'s `CHANGELOG.md`: one copy of the notes, not one per package.
19
+ - Updated dependencies [97d3b64]
20
+ - @plitzi/sdk-kernel@0.39.10
21
+ - @plitzi/sdk-shared@0.39.10
22
+
3
23
  ## 0.39.9
4
24
 
5
25
  ### Patch Changes
@@ -1,4 +1,4 @@
1
- import { i as buildFunctions } from "./module-CAk06qne.mjs";
1
+ import { i as buildFunctions } from "./module-BejdMWyt.mjs";
2
2
  import { isRecord } from "@plitzi/sdk-shared/helpers";
3
3
  import { readFunctionsSource } from "@plitzi/sdk-shared/actions";
4
4
  import { readFile, readdir } from "node:fs/promises";
@@ -1,4 +1,4 @@
1
- import { a as emptyState, c as queueRules, p as SET_ASIDE_WORDS, r as applyRule, s as queueOver } from "./queueRules-B3AGQGPs.mjs";
1
+ import { a as emptyState, o as queueOver, p as SET_ASIDE_WORDS, r as applyRule, s as queueRules } from "./queueRules-DCW5x5as.mjs";
2
2
  import { a as triggerParams, i as findTriggerNode, n as RunLimitReached, r as limitOf, t as ActionRunError } from "./errors-bCBfIe7c.mjs";
3
3
  import { i as KV_METHODS, n as MAX_GRANT_SECONDS, o as createMemoryKv, t as DEFAULT_GRANT_SECONDS } from "./grants-BsD-WlLE.mjs";
4
4
  import { cappedResponse, fetchOutbound, isBlockedHost } from "@plitzi/sdk-kernel/outbound";
@@ -422,6 +422,7 @@ var JOB_QUEUE_METHODS = {
422
422
  advanceSchedule: true,
423
423
  putSchedules: true,
424
424
  listJobs: true,
425
+ listJobGroups: true,
425
426
  listAcross: true,
426
427
  summarize: true,
427
428
  countDue: true,
@@ -977,6 +978,13 @@ var claimsWithin = (queue, waiting, turn) => {
977
978
  return taken;
978
979
  };
979
980
  };
981
+ // src/engine/jobs/tally.ts
982
+ /** How many of `values` each one is: the work a process holds, counted by the environment each piece is for. */
983
+ var tally = (values) => {
984
+ const counted = {};
985
+ for (const value of values) counted[value] = (counted[value] ?? 0) + 1;
986
+ return counted;
987
+ };
980
988
  // src/engine/jobs/worker.ts
981
989
  /**
982
990
  * What a job is reckoned to hold until this worker has measured its own (what it holds over what it held idle, by the
@@ -991,6 +999,7 @@ var createJobWorker = ({ queue, lookups, module, functionJobs, workers = 4, poll
991
999
  const claimFailures = createFailureStreak("Actions", "job claim");
992
1000
  const heartbeatFailures = createFailureStreak("Actions", "job heartbeat");
993
1001
  const { baseMs = 3e4, maxMs = 9e5 } = backoff;
1002
+ /** The jobs held: what stops each, and the environment it is of — what the process's stats count its jobs by. */
994
1003
  const active = /* @__PURE__ */ new Map();
995
1004
  /** Of `active`, the jobs of a space's functions: what a stop asks to save and hand back, rather than waits for. */
996
1005
  const slicing = /* @__PURE__ */ new Set();
@@ -1069,7 +1078,10 @@ var createJobWorker = ({ queue, lookups, module, functionJobs, workers = 4, poll
1069
1078
  */
1070
1079
  const executeSlice = async (job, jobs) => {
1071
1080
  const controller = new AbortController();
1072
- active.set(job.id, controller);
1081
+ active.set(job.id, {
1082
+ controller,
1083
+ environment: job.environment
1084
+ });
1073
1085
  slicing.add(job.id);
1074
1086
  try {
1075
1087
  await jobs.announce(job.spaceId, job.id);
@@ -1206,6 +1218,7 @@ var createJobWorker = ({ queue, lookups, module, functionJobs, workers = 4, poll
1206
1218
  const ttlMs = (await module.limitsFor(job.spaceId, entry.document)).timeoutMs;
1207
1219
  const begin = call?.idempotencyKey ? {
1208
1220
  spaceId: job.spaceId,
1221
+ environment: job.environment,
1209
1222
  actionId,
1210
1223
  callerId: call.callerId,
1211
1224
  input: job.input,
@@ -1214,6 +1227,7 @@ var createJobWorker = ({ queue, lookups, module, functionJobs, workers = 4, poll
1214
1227
  ...spareJobs.has(job.id) ? { spare: true } : {}
1215
1228
  } : {
1216
1229
  spaceId: job.spaceId,
1230
+ environment: job.environment,
1217
1231
  actionId,
1218
1232
  callerId: call?.callerId ?? trigger,
1219
1233
  input: job.input,
@@ -1264,7 +1278,10 @@ var createJobWorker = ({ queue, lookups, module, functionJobs, workers = 4, poll
1264
1278
  await fail(job, void 0, `could not start: ${refusal}`);
1265
1279
  return;
1266
1280
  }
1267
- active.set(job.id, run.controller);
1281
+ active.set(job.id, {
1282
+ controller: run.controller,
1283
+ environment: job.environment
1284
+ });
1268
1285
  try {
1269
1286
  const result = await module.runAction({
1270
1287
  entry,
@@ -1460,7 +1477,7 @@ var createJobWorker = ({ queue, lookups, module, functionJobs, workers = 4, poll
1460
1477
  jobIds: held,
1461
1478
  workerId,
1462
1479
  leaseMs
1463
- })) active.get(jobId)?.abort(stop);
1480
+ })) active.get(jobId)?.controller.abort(stop);
1464
1481
  };
1465
1482
  /** The jobs this replica marked as held near its memory: each is said once, while it holds it. */
1466
1483
  const markedNear = /* @__PURE__ */ new Set();
@@ -1503,6 +1520,7 @@ var createJobWorker = ({ queue, lookups, module, functionJobs, workers = 4, poll
1503
1520
  beat,
1504
1521
  watchMemory,
1505
1522
  inFlight: () => active.size,
1523
+ inFlightByEnvironment: () => tally([...active.values()].map((held) => held.environment)),
1506
1524
  start: () => {
1507
1525
  if (timer || workers <= 0) return;
1508
1526
  timer = setInterval(() => void guarded(), pollMs);
@@ -1523,7 +1541,7 @@ var createJobWorker = ({ queue, lookups, module, functionJobs, workers = 4, poll
1523
1541
  stopListening = void 0;
1524
1542
  await pass;
1525
1543
  if (inFlight.size > 0) serverLog.info("Actions", `waiting for ${inFlight.size} running job(s) to finish before stopping`);
1526
- for (const jobId of slicing) active.get(jobId)?.abort("shutdown");
1544
+ for (const jobId of slicing) active.get(jobId)?.controller.abort("shutdown");
1527
1545
  /**
1528
1546
  * Drained rather than abandoned: a deploy finishes the jobs it started instead of leaving them to be retried.
1529
1547
  *
@@ -1774,6 +1792,7 @@ var createRunGuards = (config = {}, store, idempotency = {}) => {
1774
1792
  runKey,
1775
1793
  kind,
1776
1794
  spaceId: params.spaceId,
1795
+ ...params.environment ? { environment: params.environment } : {},
1777
1796
  actionId: params.actionId,
1778
1797
  callerId: params.callerId,
1779
1798
  controller: new AbortController(),
@@ -1882,14 +1901,24 @@ var createRunGuards = (config = {}, store, idempotency = {}) => {
1882
1901
  }
1883
1902
  };
1884
1903
  const join = (params) => byKey.get(deriveRunKey(params))?.answered;
1904
+ /** The runs of a kind in flight, by the environment each said it is for. */
1905
+ const byEnvironment = (kind) => {
1906
+ const held = {};
1907
+ byKey.forEach((run) => {
1908
+ if (run.kind === kind && run.environment) held[run.environment] = (held[run.environment] ?? 0) + 1;
1909
+ });
1910
+ return held;
1911
+ };
1885
1912
  const slots = () => ({
1886
1913
  calls: {
1887
1914
  used: count((run) => run.kind === "call"),
1888
- of: perProcess
1915
+ of: perProcess,
1916
+ environments: byEnvironment("call")
1889
1917
  },
1890
1918
  renders: {
1891
1919
  used: count((run) => run.kind === "render"),
1892
- of: renderPerProcess
1920
+ of: renderPerProcess,
1921
+ environments: byEnvironment("render")
1893
1922
  }
1894
1923
  });
1895
1924
  const room = () => {
@@ -1,4 +1,4 @@
1
- import { l as scheduleKey } from "./queueRules-B3AGQGPs.mjs";
1
+ import { c as scheduleKey } from "./queueRules-DCW5x5as.mjs";
2
2
  import { isRecord } from "@plitzi/sdk-shared/helpers";
3
3
  // src/engine/jobs/queueDocument.ts
4
4
  var documentOf = ({ jobs, schedules }) => ({
@@ -53,6 +53,37 @@ var flowOf = (jobs, from, to) => {
53
53
  };
54
54
  });
55
55
  };
56
+ // src/engine/jobs/jobGroups.ts
57
+ /**
58
+ * Jobs, the most recently touched first, as `JobQueue.listJobGroups` answers them: a group per space, work and status,
59
+ * in the order their latest jobs come — what the in-process stores' rules (`queueRules`) page.
60
+ */
61
+ var groupJobs = (newestFirst) => {
62
+ const groups = /* @__PURE__ */ new Map();
63
+ for (const job of newestFirst) {
64
+ const key = [
65
+ job.spaceId,
66
+ job.target.kind,
67
+ job.target.name,
68
+ job.status
69
+ ].join("\0");
70
+ const group = groups.get(key);
71
+ if (group) {
72
+ group.count += 1;
73
+ group.firstDueAt = Math.min(group.firstDueAt, job.dueAt);
74
+ group.lastDueAt = Math.max(group.lastDueAt, job.dueAt);
75
+ continue;
76
+ }
77
+ const { state: _state, ...latest } = job;
78
+ groups.set(key, {
79
+ latest,
80
+ count: 1,
81
+ firstDueAt: job.dueAt,
82
+ lastDueAt: job.dueAt
83
+ });
84
+ }
85
+ return [...groups.values()];
86
+ };
56
87
  // src/engine/jobs/memoryNeeds.ts
57
88
  /**
58
89
  * What a job needs once the worker running it died, in the words every store writes: the in-process ones through
@@ -130,6 +161,8 @@ var queueRules = ({ jobs, schedules }, { retainFinished, clock, onUnansweredChan
130
161
  const job = jobs.get(jobId);
131
162
  return job && spaceIds.includes(job.spaceId) ? job : void 0;
132
163
  };
164
+ /** What `listJobs` and `listJobGroups` read: the jobs a query names, the most recently touched first. */
165
+ const listed = ({ spaceIds, name, status, kind }) => [...jobs.values()].filter((job) => spaceIds.includes(job.spaceId) && (name === void 0 || job.target.name === name) && (status === void 0 || job.status === status) && (kind === void 0 || job.target.kind === kind)).sort((a, b) => b.updatedAt - a.updatedAt);
133
166
  /** Numbered by the history itself, not by `attempts`: an operator who repeats a finished job starts its attempt
134
167
  * count again, and the record of what has already been tried must not start again with it. */
135
168
  const appendAttempt = (job, attempt) => {
@@ -285,14 +318,23 @@ var queueRules = ({ jobs, schedules }, { retainFinished, clock, onUnansweredChan
285
318
  });
286
319
  }
287
320
  },
288
- listJobs: ({ spaceIds, name, status, kind, limit, offset }) => {
289
- const matching = [...jobs.values()].filter((job) => spaceIds.includes(job.spaceId) && (name === void 0 || job.target.name === name) && (status === void 0 || job.status === status) && (kind === void 0 || job.target.kind === kind)).sort((a, b) => b.updatedAt - a.updatedAt);
321
+ listJobs: (query) => {
322
+ const matching = listed(query);
290
323
  return {
291
- jobs: matching.slice(offset, offset + limit).map((job) => ({ ...job })),
324
+ jobs: matching.slice(query.offset, query.offset + query.limit).map((job) => ({ ...job })),
292
325
  total: matching.length
293
326
  };
294
327
  },
295
- listAcross: ({ statuses, limit, order }) => [...jobs.values()].filter((job) => statuses.includes(job.status)).sort((a, b) => order === "due" ? a.runAt - b.runAt : b.updatedAt - a.updatedAt).slice(0, limit).map((job) => ({ ...job })),
328
+ listJobGroups: (query) => {
329
+ const matching = listed(query);
330
+ const groups = groupJobs(matching);
331
+ return {
332
+ groups: groups.slice(query.offset, query.offset + query.limit),
333
+ total: groups.length,
334
+ jobs: matching.length
335
+ };
336
+ },
337
+ listAcross: ({ statuses, limit, order, environment }) => [...jobs.values()].filter((job) => statuses.includes(job.status) && (environment === void 0 || job.environment === environment)).sort((a, b) => order === "due" ? a.runAt - b.runAt : b.updatedAt - a.updatedAt).slice(0, limit).map((job) => ({ ...job })),
296
338
  summarize: ({ spaces = 10 } = {}) => summarizeJobs([...jobs.values()], spaces),
297
339
  countDue: ({ spaces, memoryMb } = {}) => {
298
340
  const at = now();
@@ -396,6 +438,28 @@ var waitingKindOf = (kind, trigger) => {
396
438
  }
397
439
  };
398
440
  /** Every status at zero: what a summary counts up from, so a status nothing is in still says 0. */
441
+ /**
442
+ * The jobs counted by status and environment — a store's own grouping, one row a pair — as `summarize` answers them:
443
+ * every status, and the same for each environment, the one with the most jobs first.
444
+ */
445
+ var statusCounts = (counted) => {
446
+ const byStatus = noJobsByStatus();
447
+ const byEnvironment = /* @__PURE__ */ new Map();
448
+ for (const { status, environment, n } of counted) {
449
+ byStatus[status] += n;
450
+ const kept = byEnvironment.get(environment) ?? noJobsByStatus();
451
+ kept[status] += n;
452
+ byEnvironment.set(environment, kept);
453
+ }
454
+ const total = (counts) => Object.values(counts).reduce((sum, n) => sum + n, 0);
455
+ return {
456
+ byStatus,
457
+ environments: [...byEnvironment].map(([environment, counts]) => ({
458
+ environment,
459
+ byStatus: counts
460
+ })).sort((a, b) => total(b.byStatus) - total(a.byStatus) || a.environment.localeCompare(b.environment))
461
+ };
462
+ };
399
463
  var noJobsByStatus = () => ({
400
464
  pending: 0,
401
465
  running: 0,
@@ -418,7 +482,7 @@ var NEEDING_STATUSES = ["pending", "paused"];
418
482
  * ones count the same in their own query.
419
483
  */
420
484
  var summarizeJobs = (all, spaces) => {
421
- const byStatus = noJobsByStatus();
485
+ const pairs = /* @__PURE__ */ new Map();
422
486
  const waiting = {
423
487
  calls: 0,
424
488
  schedules: 0,
@@ -433,7 +497,14 @@ var summarizeJobs = (all, spaces) => {
433
497
  paused: 0
434
498
  };
435
499
  all.forEach((job) => {
436
- byStatus[job.status] += 1;
500
+ const pair = `${job.status}\u0000${job.environment}`;
501
+ const counted = pairs.get(pair) ?? {
502
+ status: job.status,
503
+ environment: job.environment,
504
+ n: 0
505
+ };
506
+ counted.n += 1;
507
+ pairs.set(pair, counted);
437
508
  if (job.needsMemoryMb !== void 0 && NEEDING_STATUSES.includes(job.status)) {
438
509
  if (job.status === "paused") needingMemory.paused += 1;
439
510
  else {
@@ -463,7 +534,7 @@ var summarizeJobs = (all, spaces) => {
463
534
  bySpace.set(job.spaceId, space);
464
535
  });
465
536
  return {
466
- byStatus,
537
+ ...statusCounts(pairs.values()),
467
538
  waiting,
468
539
  ...oldestDueAt === void 0 ? {} : { oldestDueAt },
469
540
  needingMemory,
@@ -491,6 +562,7 @@ var queueOver = (access) => ({
491
562
  advanceSchedule: (...args) => access("advanceSchedule", args),
492
563
  putSchedules: (...args) => access("putSchedules", args),
493
564
  listJobs: (...args) => access("listJobs", args),
565
+ listJobGroups: (...args) => access("listJobGroups", args),
494
566
  listAcross: (...args) => access("listAcross", args),
495
567
  summarize: (...args) => access("summarize", args),
496
568
  countDue: (...args) => access("countDue", args),
@@ -504,4 +576,4 @@ var queueOver = (access) => ({
504
576
  cancelPending: (...args) => access("cancelPending", args),
505
577
  cancelWaiting: (...args) => access("cancelWaiting", args)
506
578
  });
507
- export { flowOf as _, emptyState as a, queueRules as c, LOST_ERROR as d, LOST_MEMORY_WORDS as f, outgrewWorker as g, needsAfterLoss as h, changedBy as i, scheduleKey as l, lostError as m, WAITING_STATUSES as n, noJobsByStatus as o, SET_ASIDE_WORDS as p, applyRule as r, queueOver as s, NEEDING_STATUSES as t, waitingKindOf as u };
579
+ export { flowOf as _, emptyState as a, scheduleKey as c, LOST_ERROR as d, LOST_MEMORY_WORDS as f, outgrewWorker as g, needsAfterLoss as h, changedBy as i, statusCounts as l, lostError as m, WAITING_STATUSES as n, queueOver as o, SET_ASIDE_WORDS as p, applyRule as r, queueRules as s, NEEDING_STATUSES as t, waitingKindOf as u };
@@ -173,6 +173,7 @@ var createActionResolver = (lookups, module) => {
173
173
  */
174
174
  const run = await module.guards.begin({
175
175
  spaceId,
176
+ environment,
176
177
  actionId: entry.id,
177
178
  callerId,
178
179
  input,
@@ -1,4 +1,4 @@
1
- import { I as fetchConnectorRecords } from "./module-CAk06qne.mjs";
1
+ import { I as fetchConnectorRecords } from "./module-BejdMWyt.mjs";
2
2
  import { getSourceName } from "@plitzi/sdk-shared/dataSource/helpers";
3
3
  // src/connectors/projection.ts
4
4
  /**
@@ -0,0 +1,7 @@
1
+ import { JobGroup } from '../../types';
2
+ import { Job } from '@plitzi/sdk-shared';
3
+ /**
4
+ * Jobs, the most recently touched first, as `JobQueue.listJobGroups` answers them: a group per space, work and status,
5
+ * in the order their latest jobs come — what the in-process stores' rules (`queueRules`) page.
6
+ */
7
+ export declare const groupJobs: (newestFirst: readonly Job[]) => JobGroup[];
@@ -41,6 +41,15 @@ export declare const queueRules: ({ jobs, schedules }: QueueState, { retainFinis
41
41
  /** Which of {@link WaitingJobs} a job is, by its target's kind and trigger — as a store's own query reads them. */
42
42
  export declare const waitingKindOf: (kind: string, trigger: string | null | undefined) => keyof WaitingJobs;
43
43
  /** Every status at zero: what a summary counts up from, so a status nothing is in still says 0. */
44
+ /**
45
+ * The jobs counted by status and environment — a store's own grouping, one row a pair — as `summarize` answers them:
46
+ * every status, and the same for each environment, the one with the most jobs first.
47
+ */
48
+ export declare const statusCounts: (counted: Iterable<{
49
+ status: JobStatus;
50
+ environment: string;
51
+ n: number;
52
+ }>) => Pick<JobQueueSummary, "byStatus" | "environments">;
44
53
  export declare const noJobsByStatus: () => Record<JobStatus, number>;
45
54
  /**
46
55
  * The status a job waits for the queue in. One set aside (`paused`) waits for a person and is said apart
@@ -0,0 +1,2 @@
1
+ /** How many of `values` each one is: the work a process holds, counted by the environment each piece is for. */
2
+ export declare const tally: (values: Iterable<string>) => Record<string, number>;
@@ -95,5 +95,7 @@ export type JobWorker = {
95
95
  */
96
96
  stop: () => Promise<void>;
97
97
  inFlight: () => number;
98
+ /** The jobs it holds, by the environment each is of. */
99
+ inFlightByEnvironment: () => Record<string, number>;
98
100
  };
99
101
  export declare const createJobWorker: ({ queue, lookups, module, functionJobs, workers, pollMs, wake, spaces, memory, helps, memoryWatchMs, readMemory, readLoad, leaseMs, backoff, workerId, onError: customOnError }: JobWorkerOptions) => JobWorker;
@@ -18,6 +18,8 @@ export type ActiveRun = {
18
18
  runKey: string;
19
19
  kind: RunKind;
20
20
  spaceId: number;
21
+ /** Which of the space's environments it runs for, when whoever began it said: what its slot is counted by. */
22
+ environment?: string;
21
23
  actionId: string;
22
24
  callerId: string;
23
25
  controller: AbortController;
@@ -81,6 +83,8 @@ export type RunGuardsConfig = {
81
83
  };
82
84
  export type BeginRunParams = {
83
85
  spaceId: number;
86
+ /** Which of the space's environments the run is for: counted apart in the process's stats, never part of its key. */
87
+ environment?: string;
84
88
  actionId: string;
85
89
  callerId: string;
86
90
  input: Record<string, unknown>;
@@ -128,16 +132,11 @@ export type RunGuards = {
128
132
  cancel: (runId: string, callerId: string) => Promise<boolean>;
129
133
  active: () => number;
130
134
  /** Runs in flight against what this process takes at once, by kind: what its stats report as its slots. */
131
- slots: () => {
132
- calls: {
133
- used: number;
134
- of: number;
135
- };
136
- renders: {
137
- used: number;
138
- of: number;
139
- };
140
- };
135
+ slots: () => Record<'calls' | 'renders', {
136
+ used: number;
137
+ of: number;
138
+ environments: Record<string, number>;
139
+ }>;
141
140
  /**
142
141
  * The room this process has for more calls: how many more it takes, the spaces already at their share, and how many it
143
142
  * may take past a share while no other space's work waits (`spare`) — what a job worker claims by, so it never takes a
@@ -1,5 +1,5 @@
1
- import { c as oauthCallbackUrlOn, d as DEFAULT_FUNCTION_LIMITS, i as buildFunctions, l as readManifest, n as functionsInHand, o as DEFAULT_FUNCTION_JOB_LIMITS, r as FunctionsBuildError, t as createActionsModule, u as DEFAULT_FUNCTION_CEILINGS } from "../chunks/module-CAk06qne.mjs";
2
- import { i as readFunctionsDir, n as loadFunctions, r as loadFunctionsSource } from "../chunks/load-CKHHu7UP.mjs";
1
+ import { c as oauthCallbackUrlOn, d as DEFAULT_FUNCTION_LIMITS, i as buildFunctions, l as readManifest, n as functionsInHand, o as DEFAULT_FUNCTION_JOB_LIMITS, r as FunctionsBuildError, t as createActionsModule, u as DEFAULT_FUNCTION_CEILINGS } from "../chunks/module-BejdMWyt.mjs";
2
+ import { i as readFunctionsDir, n as loadFunctions, r as loadFunctionsSource } from "../chunks/load-Dhjk46sd.mjs";
3
3
  import { t as credentialsFromEnv } from "../chunks/credentials-DwxZeAvH.mjs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { FUNCTIONS_PROTOCOL, FunctionFailure, failedAnswerOf, readResponseMessage } from "@plitzi/sdk-shared/functions";
package/dist/index.d.ts CHANGED
@@ -4,6 +4,7 @@ export { KEPT_CALL_MS, KEPT_CALLS_PER_SPACE } from './engine/jobs/calls';
4
4
  export { createFileJobQueue } from './engine/jobs/fileQueue';
5
5
  export { createActionJobs } from './engine/jobs/jobs';
6
6
  export { createMemoryJobQueue } from './engine/jobs/memoryQueue';
7
+ export { statusCounts } from './engine/jobs/queueRules';
7
8
  export { createScheduler } from './engine/jobs/scheduler';
8
9
  export { DEFAULT_MAX_ATTEMPTS, scheduleFor, scheduleJobId, schedulesFor } from './engine/jobs/schedules';
9
10
  export { createJobWorker } from './engine/jobs/worker';
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import { A as schedulesFor, C as fleetJobQueue, D as DEFAULT_MAX_ATTEMPTS, E as createScheduler, I as fetchConnectorRecords, L as rebaseMedia, M as KEPT_CALLS_PER_SPACE, N as KEPT_CALL_MS, O as scheduleFor, R as writeConnectorRecord, T as createJobWorker, _ as DEFAULT_LIMITS, a as createTaskRegistry, b as MAX_LIST_ENTRIES, f as taskName, g as spaceKvPatterns, j as createMemoryJobQueue, k as scheduleJobId, m as createSigning, p as MIN_SIGNING_SECRET_LENGTH, s as jobViewOf, t as createActionsModule, v as createKvStore, w as fleetKv, x as createActionJobs, y as MAX_LIST_BYTES } from "./chunks/module-CAk06qne.mjs";
2
- import { n as describeTask, r as createConnectorResolver, t as describeCatalog } from "./chunks/taskCatalog-Cq7B1kUM.mjs";
3
- import { n as stateOf, t as documentOf } from "./chunks/queueDocument-B3y8qr0i.mjs";
4
- import { a as emptyState, c as queueRules, i as changedBy, r as applyRule, s as queueOver } from "./chunks/queueRules-B3AGQGPs.mjs";
1
+ import { A as schedulesFor, C as fleetJobQueue, D as DEFAULT_MAX_ATTEMPTS, E as createScheduler, I as fetchConnectorRecords, L as rebaseMedia, M as KEPT_CALLS_PER_SPACE, N as KEPT_CALL_MS, O as scheduleFor, R as writeConnectorRecord, T as createJobWorker, _ as DEFAULT_LIMITS, a as createTaskRegistry, b as MAX_LIST_ENTRIES, f as taskName, g as spaceKvPatterns, j as createMemoryJobQueue, k as scheduleJobId, m as createSigning, p as MIN_SIGNING_SECRET_LENGTH, s as jobViewOf, t as createActionsModule, v as createKvStore, w as fleetKv, x as createActionJobs, y as MAX_LIST_BYTES } from "./chunks/module-BejdMWyt.mjs";
2
+ import { n as describeTask, r as createConnectorResolver, t as describeCatalog } from "./chunks/taskCatalog-Crx-1ixP.mjs";
3
+ import { n as stateOf, t as documentOf } from "./chunks/queueDocument-wwfFHQvw.mjs";
4
+ import { a as emptyState, i as changedBy, l as statusCounts, o as queueOver, r as applyRule, s as queueRules } from "./chunks/queueRules-DCW5x5as.mjs";
5
5
  import { a as triggerParams, t as ActionRunError } from "./chunks/errors-bCBfIe7c.mjs";
6
6
  import { a as createMapKv, o as createMemoryKv } from "./chunks/grants-BsD-WlLE.mjs";
7
7
  import { createActionRealtime, n as publishJobView, r as createRealtimeHub, t as createRealtimeRetained } from "./realtime/index.mjs";
@@ -549,4 +549,4 @@ var createJobControl = ({ queue, realtime }) => {
549
549
  }
550
550
  };
551
551
  };
552
- export { ActionRunError, DEFAULT_LIMITS, DEFAULT_MAX_ATTEMPTS, FileInUseError, KEPT_CALLS_PER_SPACE, KEPT_CALL_MS, MAX_LIST_BYTES, MAX_LIST_ENTRIES, MIN_SIGNING_SECRET_LENGTH, checkAction, createActionJobs, createActionRealtime, createActionsModule, createConnectorResolver, createFileJobQueue, createFileKv, createJobControl, createJobWorker, createKvStore, createMemoryJobQueue, createMemoryKv, createRedisKv, createRejectLogger, createRunLogger, createScheduler, createSigning, createTaskRegistry, credentialsFromEnv, describeCatalog, describeTask, fetchConnectorRecords, fleetJobQueue, fleetKv, rebaseMedia, scheduleFor, scheduleJobId, schedulesFor, spaceKvPatterns, taskName, writeConnectorRecord };
552
+ export { ActionRunError, DEFAULT_LIMITS, DEFAULT_MAX_ATTEMPTS, FileInUseError, KEPT_CALLS_PER_SPACE, KEPT_CALL_MS, MAX_LIST_BYTES, MAX_LIST_ENTRIES, MIN_SIGNING_SECRET_LENGTH, checkAction, createActionJobs, createActionRealtime, createActionsModule, createConnectorResolver, createFileJobQueue, createFileKv, createJobControl, createJobWorker, createKvStore, createMemoryJobQueue, createMemoryKv, createRedisKv, createRejectLogger, createRunLogger, createScheduler, createSigning, createTaskRegistry, credentialsFromEnv, describeCatalog, describeTask, fetchConnectorRecords, fleetJobQueue, fleetKv, rebaseMedia, scheduleFor, scheduleJobId, schedulesFor, spaceKvPatterns, statusCounts, taskName, writeConnectorRecord };
@@ -1,4 +1,4 @@
1
- import { _ as flowOf, d as LOST_ERROR, f as LOST_MEMORY_WORDS, n as WAITING_STATUSES, o as noJobsByStatus, p as SET_ASIDE_WORDS, t as NEEDING_STATUSES, u as waitingKindOf } from "../chunks/queueRules-B3AGQGPs.mjs";
1
+ import { _ as flowOf, d as LOST_ERROR, f as LOST_MEMORY_WORDS, l as statusCounts, n as WAITING_STATUSES, p as SET_ASIDE_WORDS, t as NEEDING_STATUSES, u as waitingKindOf } from "../chunks/queueRules-DCW5x5as.mjs";
2
2
  import { t as createStoreClock } from "../chunks/storeClock-Btm7EaVm.mjs";
3
3
  import { TERMINAL_JOB_STATUSES } from "@plitzi/sdk-shared/actions";
4
4
  // src/mongo/claimable.ts
@@ -56,6 +56,63 @@ var dropWaiting = async (jobs, { spaceIds, status, kind, name }, at, expiresAt)
56
56
  functionJobs: watched.map((job) => job._id)
57
57
  };
58
58
  };
59
+ // src/mongo/jobLists.ts
60
+ /** The jobs a list names (`listJobs`, `listJobGroups`). */
61
+ var listFilter = ({ spaceIds, name, status, kind }) => ({
62
+ spaceId: { $in: spaceIds },
63
+ ...name ? { "target.name": name } : {},
64
+ ...status ? { status } : {},
65
+ ...kind ? { "target.kind": kind } : {}
66
+ });
67
+ /**
68
+ * `JobQueue.listJobGroups` over the jobs' collection, in one pass — the page and the count alike: a group per space,
69
+ * work and status, the one of the most recently touched job first. What a job of the functions saved is left out before
70
+ * the grouping: up to megabytes per job, and no row shows it.
71
+ */
72
+ var listJobGroupsOf = async (jobs, query) => {
73
+ const [found] = await jobs.aggregate([
74
+ { $match: listFilter(query) },
75
+ { $project: { state: 0 } },
76
+ { $sort: {
77
+ updatedAt: -1,
78
+ _id: -1
79
+ } },
80
+ { $group: {
81
+ _id: {
82
+ spaceId: "$spaceId",
83
+ kind: "$target.kind",
84
+ name: "$target.name",
85
+ status: "$status"
86
+ },
87
+ latest: { $first: "$$ROOT" },
88
+ count: { $sum: 1 },
89
+ firstDueAt: { $min: "$dueAt" },
90
+ lastDueAt: { $max: "$dueAt" }
91
+ } },
92
+ { $sort: {
93
+ "latest.updatedAt": -1,
94
+ "latest._id": -1
95
+ } },
96
+ { $facet: {
97
+ page: [
98
+ { $skip: query.offset },
99
+ { $limit: Math.max(1, query.limit) },
100
+ { $project: { _id: 0 } }
101
+ ],
102
+ total: [{ $group: {
103
+ _id: null,
104
+ groups: { $sum: 1 },
105
+ jobs: { $sum: "$count" }
106
+ } }]
107
+ } }
108
+ ]).toArray();
109
+ const total = found.total.at(0);
110
+ return {
111
+ groups: found.page.slice(0, query.limit),
112
+ total: total?.groups ?? 0,
113
+ jobs: total?.jobs ?? 0
114
+ };
115
+ };
59
116
  // src/mongo/jobQueue.ts
60
117
  /** Mongo's code for a unique index that refused a second document with the same key. */
61
118
  var DUPLICATE_KEY$1 = 11e3;
@@ -420,26 +477,35 @@ var createMongoJobQueue = ({ db, collections: names = {}, retentionDays = 90 })
420
477
  actionId: { $nin: incoming.map((schedule) => schedule.actionId) }
421
478
  });
422
479
  },
423
- listJobs: async ({ spaceIds, name, status, kind, limit, offset }) => {
480
+ listJobs: async (query) => {
424
481
  const { jobs } = await collections();
425
- const filter = {
426
- spaceId: { $in: spaceIds },
427
- ...name ? { "target.name": name } : {},
428
- ...status ? { status } : {},
429
- ...kind ? { "target.kind": kind } : {}
430
- };
482
+ const filter = listFilter(query);
431
483
  const [found, total] = await Promise.all([jobs.find(filter).sort({
432
484
  updatedAt: -1,
433
485
  _id: -1
434
- }).skip(offset).limit(limit).toArray(), jobs.countDocuments(filter)]);
486
+ }).skip(query.offset).limit(query.limit).toArray(), jobs.countDocuments(filter)]);
435
487
  return {
436
488
  jobs: found.map(toJob),
437
489
  total
438
490
  };
439
491
  },
440
- listAcross: async ({ statuses, limit, order }) => {
492
+ listJobGroups: async (query) => {
441
493
  const { jobs } = await collections();
442
- return (await jobs.find({ status: { $in: statuses } }).sort(order === "due" ? {
494
+ const { groups, ...counted } = await listJobGroupsOf(jobs, query);
495
+ return {
496
+ ...counted,
497
+ groups: groups.map(({ latest, ...group }) => ({
498
+ ...group,
499
+ latest: toJob(latest)
500
+ }))
501
+ };
502
+ },
503
+ listAcross: async ({ statuses, limit, order, environment }) => {
504
+ const { jobs } = await collections();
505
+ return (await jobs.find({
506
+ status: { $in: statuses },
507
+ ...environment === void 0 ? {} : { environment }
508
+ }).sort(order === "due" ? {
443
509
  runAt: 1,
444
510
  _id: 1
445
511
  } : {
@@ -452,7 +518,10 @@ var createMongoJobQueue = ({ db, collections: names = {}, retentionDays = 90 })
452
518
  const waitingNow = { status: { $in: [...WAITING_STATUSES] } };
453
519
  const [found] = await jobs.aggregate([{ $facet: {
454
520
  byStatus: [{ $group: {
455
- _id: "$status",
521
+ _id: {
522
+ status: "$status",
523
+ environment: "$environment"
524
+ },
456
525
  n: { $sum: 1 }
457
526
  } }],
458
527
  needingMemory: [{ $match: {
@@ -492,10 +561,6 @@ var createMongoJobQueue = ({ db, collections: names = {}, retentionDays = 90 })
492
561
  { $limit: Math.max(1, spaces) }
493
562
  ]
494
563
  } }]).toArray();
495
- const byStatus = noJobsByStatus();
496
- found.byStatus.forEach((each) => {
497
- byStatus[each._id] = each.n;
498
- });
499
564
  const waiting = {
500
565
  calls: 0,
501
566
  schedules: 0,
@@ -510,7 +575,10 @@ var createMongoJobQueue = ({ db, collections: names = {}, retentionDays = 90 })
510
575
  });
511
576
  const waitingForMemory = found.needingMemory.find((each) => each._id === "pending");
512
577
  return {
513
- byStatus,
578
+ ...statusCounts(found.byStatus.map((each) => ({
579
+ ...each._id,
580
+ n: each.n
581
+ }))),
514
582
  waiting,
515
583
  ...oldestDueAt === void 0 ? {} : { oldestDueAt },
516
584
  needingMemory: {
@@ -0,0 +1,19 @@
1
+ import { JobDocument } from './jobQueue';
2
+ import { JobGroup, JobQuery } from '../types';
3
+ import { Collection, Filter } from 'mongodb';
4
+ /** The jobs a list names (`listJobs`, `listJobGroups`). */
5
+ export declare const listFilter: ({ spaceIds, name, status, kind }: JobQuery) => Filter<JobDocument>;
6
+ /** A group as the collection answers it: its latest job still a document. */
7
+ export type JobGroupDocument = Omit<JobGroup, 'latest'> & {
8
+ latest: JobDocument;
9
+ };
10
+ /**
11
+ * `JobQueue.listJobGroups` over the jobs' collection, in one pass — the page and the count alike: a group per space,
12
+ * work and status, the one of the most recently touched job first. What a job of the functions saved is left out before
13
+ * the grouping: up to megabytes per job, and no row shows it.
14
+ */
15
+ export declare const listJobGroupsOf: (jobs: Collection<JobDocument>, query: JobQuery) => Promise<{
16
+ groups: JobGroupDocument[];
17
+ total: number;
18
+ jobs: number;
19
+ }>;
@@ -1,8 +1,43 @@
1
- import { _ as flowOf, d as LOST_ERROR, g as outgrewWorker, h as needsAfterLoss, m as lostError, o as noJobsByStatus, p as SET_ASIDE_WORDS, u as waitingKindOf } from "../chunks/queueRules-B3AGQGPs.mjs";
1
+ import { _ as flowOf, d as LOST_ERROR, g as outgrewWorker, h as needsAfterLoss, l as statusCounts, m as lostError, p as SET_ASIDE_WORDS, u as waitingKindOf } from "../chunks/queueRules-DCW5x5as.mjs";
2
2
  import { t as createStoreClock } from "../chunks/storeClock-Btm7EaVm.mjs";
3
3
  import { TERMINAL_JOB_STATUSES } from "@plitzi/sdk-shared/actions";
4
4
  import { execute, selectOne, selectRows } from "@plitzi/sdk-kernel/mysql";
5
- // src/mysql/rows.ts
5
+ /**
6
+ * A job's row as a list reads it: every column but what a job of the functions saved (`state`, up to megabytes, and no
7
+ * list shows it) — read as NULL, so `toJob` reads it as none.
8
+ */
9
+ var LISTED_JOB_COLUMNS = [...Object.keys({
10
+ id: true,
11
+ space_id: true,
12
+ target_kind: true,
13
+ target_name: true,
14
+ target: true,
15
+ environment: true,
16
+ input: true,
17
+ due_at: true,
18
+ max_attempts: true,
19
+ missed: true,
20
+ job_key: true,
21
+ status: true,
22
+ run_at: true,
23
+ attempts: true,
24
+ lease_until: true,
25
+ worker_id: true,
26
+ run_id: true,
27
+ cancel_requested: true,
28
+ created_at: true,
29
+ updated_at: true,
30
+ error: true,
31
+ history: true,
32
+ state: true,
33
+ progress: true,
34
+ result: true,
35
+ pause_requested: true,
36
+ active_ms: true,
37
+ holder_memory_mb: true,
38
+ needs_memory_mb: true,
39
+ near_memory_limit: true
40
+ }).filter((column) => column !== "state"), "NULL AS state"].join(", ");
6
41
  /**
7
42
  * A row as the contract shapes it.
8
43
  *
@@ -79,6 +114,57 @@ var claimable = (at, spaces, memoryMb, takes) => {
79
114
  ]
80
115
  };
81
116
  };
117
+ // src/mysql/jobLists.ts
118
+ /** Digits an epoch-ms `updated_at` is padded to, so its text sorts as the number does. */
119
+ var LATEST_PAD = 20;
120
+ /** The jobs a list names (`listJobs`, `listJobGroups`): the clause and its parameters. */
121
+ var listWhere = ({ spaceIds, name, status, kind }) => ({
122
+ sql: [
123
+ "space_id IN (?)",
124
+ ...name ? ["target_name = ?"] : [],
125
+ ...status ? ["status = ?"] : [],
126
+ ...kind ? ["target_kind = ?"] : []
127
+ ].join(" AND "),
128
+ params: [
129
+ spaceIds,
130
+ ...name ? [name] : [],
131
+ ...status ? [status] : [],
132
+ ...kind ? [kind] : []
133
+ ]
134
+ });
135
+ /**
136
+ * `JobQueue.listJobGroups` over the jobs table: a group per space, work and status, the one of the most recently
137
+ * touched job first. Each group's latest job — by `updated_at`, then `id`, as `listJobs` orders them — is read off one
138
+ * MAX of the two written as one string: MySQL 5.7 has no window functions. A query naming no space is answered empty
139
+ * by the caller (`IN ()` is not SQL).
140
+ */
141
+ var listJobGroupsOf = async (conn, table, query) => {
142
+ const where = listWhere(query);
143
+ const grouped = `FROM ${table} WHERE ${where.sql} GROUP BY space_id, target_kind, target_name, status`;
144
+ const [found, count] = await Promise.all([selectRows(conn, `SELECT MAX(CONCAT(LPAD(updated_at, ${String(LATEST_PAD)}, '0'), id)) AS latest, COUNT(*) AS n,
145
+ MIN(due_at) AS first_due, MAX(due_at) AS last_due
146
+ ${grouped} ORDER BY latest DESC LIMIT ? OFFSET ?`, [
147
+ ...where.params,
148
+ query.limit,
149
+ query.offset
150
+ ]), selectOne(conn, `SELECT COUNT(*) AS total, SUM(n) AS jobs FROM (SELECT COUNT(*) AS n ${grouped}) AS g`, where.params)]);
151
+ const ids = found.map((group) => group.latest.slice(LATEST_PAD));
152
+ const rows = ids.length > 0 ? await selectRows(conn, `SELECT ${LISTED_JOB_COLUMNS} FROM ${table} WHERE id IN (?)`, [ids]) : [];
153
+ const latest = new Map(rows.map((row) => [row.id, toJob(row)]));
154
+ return {
155
+ groups: found.flatMap((group, at) => {
156
+ const job = latest.get(ids[at] ?? "");
157
+ return job ? [{
158
+ latest: job,
159
+ count: Number(group.n),
160
+ firstDueAt: Number(group.first_due),
161
+ lastDueAt: Number(group.last_due)
162
+ }] : [];
163
+ }),
164
+ total: Number(count?.total ?? 0),
165
+ jobs: Number(count?.jobs ?? 0)
166
+ };
167
+ };
82
168
  // src/mysql/schema.ts
83
169
  var PREFIX = /^[A-Za-z0-9_]*$/;
84
170
  /**
@@ -200,7 +286,7 @@ var NEEDING = "status IN ('pending', 'paused')";
200
286
  */
201
287
  var summarizeJobsTable = async (conn, table, spaces) => {
202
288
  const [statuses, kinds, bySpace, needing] = await Promise.all([
203
- selectRows(conn, `SELECT status, COUNT(*) AS n FROM ${table} GROUP BY status`, []),
289
+ selectRows(conn, `SELECT status, environment, COUNT(*) AS n FROM ${table} GROUP BY status, environment`, []),
204
290
  selectRows(conn, `SELECT target_kind AS kind, ${TRIGGER} AS trig, COUNT(*) AS n, MIN(due_at) AS oldest
205
291
  FROM ${table} WHERE ${WAITING} GROUP BY target_kind, trig`, []),
206
292
  selectRows(conn, `SELECT j.space_id, COUNT(*) AS waiting, SUM(JSON_UNQUOTE(JSON_EXTRACT(j.target, '$.trigger')) = 'call') AS calls,
@@ -214,10 +300,6 @@ var summarizeJobsTable = async (conn, table, spaces) => {
214
300
  ]);
215
301
  const waitingForMemory = needing.find((row) => row.status === "pending");
216
302
  const pausedForMemory = needing.find((row) => row.status === "paused");
217
- const byStatus = noJobsByStatus();
218
- statuses.forEach((row) => {
219
- byStatus[row.status] = Number(row.n);
220
- });
221
303
  const waiting = {
222
304
  calls: 0,
223
305
  schedules: 0,
@@ -231,7 +313,10 @@ var summarizeJobsTable = async (conn, table, spaces) => {
231
313
  oldestDueAt = oldestDueAt === void 0 ? Number(row.oldest) : Math.min(oldestDueAt, Number(row.oldest));
232
314
  });
233
315
  return {
234
- byStatus,
316
+ ...statusCounts(statuses.map((row) => ({
317
+ ...row,
318
+ n: Number(row.n)
319
+ }))),
235
320
  waiting,
236
321
  ...oldestDueAt === void 0 ? {} : { oldestDueAt },
237
322
  needingMemory: {
@@ -557,43 +642,42 @@ var createMysqlJobQueue = ({ pool, tablePrefix = "", createTables = true, retent
557
642
  await execute(connection, kept.length > 0 ? `DELETE FROM ${t.schedules} WHERE space_id = ? AND action_id NOT IN (?)` : `DELETE FROM ${t.schedules} WHERE space_id = ?`, kept.length > 0 ? [spaceId, kept] : [spaceId]);
558
643
  });
559
644
  },
560
- listJobs: async ({ spaceIds, name, status, kind, limit, offset }) => {
561
- if (!inSpaces(spaceIds)) return {
645
+ listJobs: async (query) => {
646
+ if (!inSpaces(query.spaceIds)) return {
562
647
  jobs: [],
563
648
  total: 0
564
649
  };
565
650
  const conn = await db();
566
- const where = [
567
- "space_id IN (?)",
568
- ...name ? ["target_name = ?"] : [],
569
- ...status ? ["status = ?"] : [],
570
- ...kind ? ["target_kind = ?"] : []
571
- ].join(" AND ");
572
- const params = [
573
- spaceIds,
574
- ...name ? [name] : [],
575
- ...status ? [status] : [],
576
- ...kind ? [kind] : []
577
- ];
578
- const [rows, count] = await Promise.all([selectRows(conn, `SELECT * FROM ${t.jobs} WHERE ${where} ORDER BY updated_at DESC, id DESC LIMIT ? OFFSET ?`, [
579
- ...params,
580
- limit,
581
- offset
582
- ]), selectOne(conn, `SELECT COUNT(*) AS total FROM ${t.jobs} WHERE ${where}`, params)]);
651
+ const where = listWhere(query);
652
+ const [rows, count] = await Promise.all([selectRows(conn, `SELECT * FROM ${t.jobs} WHERE ${where.sql} ORDER BY updated_at DESC, id DESC LIMIT ? OFFSET ?`, [
653
+ ...where.params,
654
+ query.limit,
655
+ query.offset
656
+ ]), selectOne(conn, `SELECT COUNT(*) AS total FROM ${t.jobs} WHERE ${where.sql}`, where.params)]);
583
657
  return {
584
658
  jobs: rows.map(toJob),
585
659
  total: Number(count?.total ?? 0)
586
660
  };
587
661
  },
662
+ listJobGroups: async (query) => inSpaces(query.spaceIds) ? listJobGroupsOf(await db(), t.jobs, query) : {
663
+ groups: [],
664
+ total: 0,
665
+ jobs: 0
666
+ },
588
667
  countDue: async ({ spaces, memoryMb } = {}) => {
589
668
  const conn = await db();
590
669
  const where = claimable(await clock.now(), spaces, memoryMb);
591
670
  const row = await selectOne(conn, `SELECT COUNT(*) AS n FROM ${t.jobs} WHERE ${where.sql}`, where.params);
592
671
  return Number(row?.n ?? 0);
593
672
  },
594
- listAcross: async ({ statuses, limit, order }) => {
673
+ listAcross: async ({ statuses, limit, order, environment }) => {
595
674
  if (statuses.length === 0) return [];
596
- return (await selectRows(await db(), `SELECT * FROM ${t.jobs} WHERE status IN (?) ORDER BY ${order === "due" ? "run_at ASC" : "updated_at DESC"}, id LIMIT ?`, [statuses, limit])).map(toJob);
675
+ return (await selectRows(await db(), `SELECT * FROM ${t.jobs} WHERE status IN (?)${environment === void 0 ? "" : " AND environment = ?"}
676
+ ORDER BY ${order === "due" ? "run_at ASC" : "updated_at DESC"}, id LIMIT ?`, [
677
+ statuses,
678
+ ...environment === void 0 ? [] : [environment],
679
+ limit
680
+ ])).map(toJob);
597
681
  },
598
682
  summarize: async ({ spaces = 10 } = {}) => summarizeJobsTable(await db(), t.jobs, spaces),
599
683
  flow: async ({ from, to }) => {
@@ -0,0 +1,18 @@
1
+ import { JobGroup, JobQuery } from '../types';
2
+ import { Pool } from 'mysql2/promise';
3
+ /** The jobs a list names (`listJobs`, `listJobGroups`): the clause and its parameters. */
4
+ export declare const listWhere: ({ spaceIds, name, status, kind }: JobQuery) => {
5
+ sql: string;
6
+ params: unknown[];
7
+ };
8
+ /**
9
+ * `JobQueue.listJobGroups` over the jobs table: a group per space, work and status, the one of the most recently
10
+ * touched job first. Each group's latest job — by `updated_at`, then `id`, as `listJobs` orders them — is read off one
11
+ * MAX of the two written as one string: MySQL 5.7 has no window functions. A query naming no space is answered empty
12
+ * by the caller (`IN ()` is not SQL).
13
+ */
14
+ export declare const listJobGroupsOf: (conn: Pool, table: string, query: JobQuery) => Promise<{
15
+ groups: JobGroup[];
16
+ total: number;
17
+ jobs: number;
18
+ }>;
@@ -34,6 +34,11 @@ export type JobRow = {
34
34
  needs_memory_mb: Numeric | null;
35
35
  near_memory_limit: Numeric;
36
36
  };
37
+ /**
38
+ * A job's row as a list reads it: every column but what a job of the functions saved (`state`, up to megabytes, and no
39
+ * list shows it) — read as NULL, so `toJob` reads it as none.
40
+ */
41
+ export declare const LISTED_JOB_COLUMNS: string;
37
42
  export type ScheduleRow = {
38
43
  space_id: Numeric;
39
44
  action_id: string;
@@ -1 +1 @@
1
- export { n as RENDER_PATH, r as RENDER_PROTOCOL, a as createActionResolver, t as createRemoteRenderResolver } from "../chunks/remote-Cm3IDERi.mjs";
1
+ export { n as RENDER_PATH, r as RENDER_PROTOCOL, a as createActionResolver, t as createRemoteRenderResolver } from "../chunks/remote-DZSzOO01.mjs";
@@ -1,5 +1,5 @@
1
- import { n as stateOf, t as documentOf } from "../chunks/queueDocument-B3y8qr0i.mjs";
2
- import { a as emptyState, c as queueRules, i as changedBy, r as applyRule, s as queueOver } from "../chunks/queueRules-B3AGQGPs.mjs";
1
+ import { n as stateOf, t as documentOf } from "../chunks/queueDocument-wwfFHQvw.mjs";
2
+ import { a as emptyState, i as changedBy, o as queueOver, r as applyRule, s as queueRules } from "../chunks/queueRules-DCW5x5as.mjs";
3
3
  import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  import { DatabaseSync } from "node:sqlite";
@@ -1,2 +1,2 @@
1
1
  export type { ActionLookupsConfig, ConnectorLookupsConfig, EngineConfig, EngineOptions, EngineServerConfig, SSRActionConfig, ActionJobsConfig } from './config';
2
- export type { ActionSchedule, ActionScheduleInput, JobClaimMemory, JobQuery, JobQueue, JobFlowMinute, JobQueueSummary, JobSettlement, JobsDropped, JobsNeedingMemory, JobsToDrop, JobSpaces, JobStop, JobTake, JobWake, JobWrite, WaitingJobs } from './jobs';
2
+ export type { ActionSchedule, ActionScheduleInput, JobClaimMemory, JobQuery, JobQueue, JobFlowMinute, JobGroup, JobQueueSummary, JobSettlement, JobsDropped, JobsNeedingMemory, JobsToDrop, JobSpaces, JobStop, JobTake, JobWake, JobWrite, WaitingJobs } from './jobs';
@@ -100,6 +100,14 @@ export type WaitingJobs = {
100
100
  /** A queue at a glance — see `JobQueue.summarize`. */
101
101
  export type JobQueueSummary = {
102
102
  byStatus: Record<JobStatus, number>;
103
+ /**
104
+ * The same count for each environment of the spaces that has any job — `production`, `main`… — the most jobs first:
105
+ * what a view narrowed to one environment reads. They add up to `byStatus`.
106
+ */
107
+ environments: {
108
+ environment: string;
109
+ byStatus: Record<JobStatus, number>;
110
+ }[];
103
111
  waiting: WaitingJobs;
104
112
  /** When the job waiting longest was due, epoch ms by the queue's clock; absent with nothing waiting. */
105
113
  oldestDueAt?: number;
@@ -138,6 +146,20 @@ export type JobQuery = {
138
146
  limit: number;
139
147
  offset: number;
140
148
  };
149
+ /**
150
+ * Jobs that say the same thing — one space's runs of one work (`target.kind` and `target.name`) in one status: what
151
+ * `JobQueue.listJobGroups` answers as one row, and exactly what `cancelWaiting` drops at once when narrowed to them.
152
+ */
153
+ export type JobGroup = {
154
+ /** The most recently touched of them, as `listJobs` reads it, without what a job of the functions saved (`state`). */
155
+ latest: Omit<Job, 'state'>;
156
+ /** How many jobs the group holds, `latest` among them. */
157
+ count: number;
158
+ /** The earliest `dueAt` among them. */
159
+ firstDueAt: number;
160
+ /** The latest `dueAt` among them. */
161
+ lastDueAt: number;
162
+ };
141
163
  /**
142
164
  * Which jobs an operator drops at once (`JobQueue.cancelWaiting`): everything of these spaces that has not started —
143
165
  * waiting to run or set aside — narrowed like a list of them is.
@@ -273,6 +295,17 @@ export type JobQueue = {
273
295
  jobs: Job[];
274
296
  total: number;
275
297
  }>;
298
+ /**
299
+ * The jobs `listJobs` would list, a {@link JobGroup} per space, work and status — the group of the most recently
300
+ * touched job first — paged by groups, `total` counting them and `jobs` the jobs they hold, every page's. What a queue
301
+ * reads as a list a person scans: a schedule whose every fire was set aside is one row saying how many, not a page of
302
+ * the same line, every page alike.
303
+ */
304
+ listJobGroups: (query: JobQuery) => Promise<{
305
+ groups: JobGroup[];
306
+ total: number;
307
+ jobs: number;
308
+ }>;
276
309
  /**
277
310
  * Jobs of EVERY space in these statuses — an operator's view, never a space's own (`listJobs` is): the longest due first
278
311
  * (`due`), or the latest written first (`latest`). What a monitoring screen lists of what waits, runs and just ended.
@@ -281,6 +314,8 @@ export type JobQueue = {
281
314
  statuses: JobStatus[];
282
315
  limit: number;
283
316
  order: 'due' | 'latest';
317
+ /** One environment's jobs alone (`production`, `main`…); every environment's without it. */
318
+ environment?: Environment;
284
319
  }) => Promise<Job[]>;
285
320
  /**
286
321
  * The whole queue at a glance, every space: what an operator reads to tell a queue that drains from one that fills —
@@ -1,9 +1,9 @@
1
1
  import { handleRealtimePublish, handleRealtimeSocket, handleRealtimeSubscribe, realtimeModuleFor } from "../realtime/index.mjs";
2
- import { a as createActionResolver, i as readRenderAsk, n as RENDER_PATH, t as createRemoteRenderResolver } from "../chunks/remote-Cm3IDERi.mjs";
3
- import { F as readKeptCall, P as keepCall, R as writeConnectorRecord, S as ACTIONS_FLEET_STORES, h as precheckRun, t as createActionsModule } from "../chunks/module-CAk06qne.mjs";
2
+ import { a as createActionResolver, i as readRenderAsk, n as RENDER_PATH, t as createRemoteRenderResolver } from "../chunks/remote-DZSzOO01.mjs";
3
+ import { F as readKeptCall, P as keepCall, R as writeConnectorRecord, S as ACTIONS_FLEET_STORES, h as precheckRun, t as createActionsModule } from "../chunks/module-BejdMWyt.mjs";
4
4
  import { a as triggerParams, i as findTriggerNode, t as ActionRunError } from "../chunks/errors-bCBfIe7c.mjs";
5
- import { r as createConnectorResolver, t as describeCatalog } from "../chunks/taskCatalog-Cq7B1kUM.mjs";
6
- import { t as isFunctionsDefinition } from "../chunks/load-CKHHu7UP.mjs";
5
+ import { r as createConnectorResolver, t as describeCatalog } from "../chunks/taskCatalog-Crx-1ixP.mjs";
6
+ import { t as isFunctionsDefinition } from "../chunks/load-Dhjk46sd.mjs";
7
7
  import { privateOriginsOf } from "@plitzi/sdk-kernel/outbound";
8
8
  import { isConnectorManifestDraft, validateConnectorManifest } from "@plitzi/sdk-shared/connectors";
9
9
  import { createHmac, timingSafeEqual } from "node:crypto";
@@ -63,7 +63,7 @@ var wantsStream = (accept) => {
63
63
  * belong to the deployment.
64
64
  */
65
65
  var reportReject = async (config, record) => {
66
- if (config.stats) statsRecorderFor(config.stats, config.health?.version).refuse(record.reason);
66
+ if (config.stats) statsRecorderFor(config.stats, config.health?.version).refuse(record.reason, record.environment);
67
67
  try {
68
68
  await config.action?.onReject?.(record);
69
69
  } catch (error) {
@@ -180,6 +180,7 @@ var handleActionCall = async (deps) => {
180
180
  const input = body.input ?? {};
181
181
  const begin = {
182
182
  spaceId,
183
+ environment,
183
184
  actionId: entry.id,
184
185
  callerId,
185
186
  input,
@@ -605,6 +606,7 @@ var handleActionWebhook = async (deps) => {
605
606
  const limits = await module.limitsFor(spaceId, entry.document);
606
607
  const begin = {
607
608
  spaceId,
609
+ environment,
608
610
  actionId: entry.id,
609
611
  callerId,
610
612
  input,
@@ -933,7 +935,8 @@ var recordedRun = (stats, onRun) => async (record) => {
933
935
  kind: "action",
934
936
  name: record.actionId,
935
937
  trigger: record.trigger,
936
- runId: record.runId
938
+ runId: record.runId,
939
+ environment: record.environment
937
940
  });
938
941
  await onRun?.(record);
939
942
  };
@@ -977,11 +980,14 @@ var actionsModuleFor = (config) => {
977
980
  });
978
981
  if (stats) {
979
982
  const sizes = module.guards.slots();
980
- stats.slot("calls", sizes.calls.of, () => module.guards.slots().calls.used);
981
- stats.slot("renders", sizes.renders.of, () => module.guards.slots().renders.used);
983
+ stats.slot("calls", sizes.calls.of, () => module.guards.slots().calls.used, { environments: () => module.guards.slots().calls.environments });
984
+ stats.slot("renders", sizes.renders.of, () => module.guards.slots().renders.used, { environments: () => module.guards.slots().renders.environments });
982
985
  const jobs = module.jobs;
983
986
  const jobWorkers = config.action?.jobs === false ? 0 : config.action?.jobs?.workers ?? 4;
984
- if (jobs && jobWorkers > 0) stats.slot("jobs", jobWorkers, () => jobs.worker.inFlight(), { queues: true });
987
+ if (jobs && jobWorkers > 0) stats.slot("jobs", jobWorkers, () => jobs.worker.inFlight(), {
988
+ queues: true,
989
+ environments: () => jobs.worker.inFlightByEnvironment()
990
+ });
985
991
  }
986
992
  modules.set(config, module);
987
993
  return module;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plitzi/sdk-actions",
3
- "version": "0.39.9",
3
+ "version": "0.39.11",
4
4
  "license": "AGPL-3.0",
5
5
  "description": "The actions engine: server actions, a space's functions and runtimes as the platform holds them, the connectors, realtime, jobs, and the stock queues and stores. What a worker runs; what a page server is handed.",
6
6
  "files": [
@@ -37,8 +37,8 @@
37
37
  "build:prod": "vite build"
38
38
  },
39
39
  "dependencies": {
40
- "@plitzi/sdk-kernel": "0.39.9",
41
- "@plitzi/sdk-shared": "0.39.9",
40
+ "@plitzi/sdk-kernel": "0.39.11",
41
+ "@plitzi/sdk-shared": "0.39.11",
42
42
  "nodemailer": "^10.6.0",
43
43
  "ws": "^8.23.0"
44
44
  },
@@ -59,7 +59,7 @@
59
59
  }
60
60
  },
61
61
  "devDependencies": {
62
- "@plitzi/sdk-runtime": "0.39.9",
62
+ "@plitzi/sdk-runtime": "0.39.11",
63
63
  "@types/node": "^26.6.6",
64
64
  "@types/nodemailer": "^8.0.2",
65
65
  "@types/ws": "^8.18.2",