@plitzi/sdk-actions 0.39.9 → 0.39.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,5 +1,15 @@
1
1
  # @plitzi/sdk-actions
2
2
 
3
+ ## 0.39.10
4
+
5
+ ### Patch Changes
6
+
7
+ - 97d3b64: 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 [97d3b64]
10
+ - @plitzi/sdk-kernel@0.39.10
11
+ - @plitzi/sdk-shared@0.39.10
12
+
3
13
  ## 0.39.9
4
14
 
5
15
  ### Patch Changes
@@ -1,4 +1,4 @@
1
- import { i as buildFunctions } from "./module-CAk06qne.mjs";
1
+ import { i as buildFunctions } from "./module-BP0LBhlj.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-C6jJo_yv.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";
@@ -977,6 +977,13 @@ var claimsWithin = (queue, waiting, turn) => {
977
977
  return taken;
978
978
  };
979
979
  };
980
+ // src/engine/jobs/tally.ts
981
+ /** How many of `values` each one is: the work a process holds, counted by the environment each piece is for. */
982
+ var tally = (values) => {
983
+ const counted = {};
984
+ for (const value of values) counted[value] = (counted[value] ?? 0) + 1;
985
+ return counted;
986
+ };
980
987
  // src/engine/jobs/worker.ts
981
988
  /**
982
989
  * 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 +998,7 @@ var createJobWorker = ({ queue, lookups, module, functionJobs, workers = 4, poll
991
998
  const claimFailures = createFailureStreak("Actions", "job claim");
992
999
  const heartbeatFailures = createFailureStreak("Actions", "job heartbeat");
993
1000
  const { baseMs = 3e4, maxMs = 9e5 } = backoff;
1001
+ /** The jobs held: what stops each, and the environment it is of — what the process's stats count its jobs by. */
994
1002
  const active = /* @__PURE__ */ new Map();
995
1003
  /** Of `active`, the jobs of a space's functions: what a stop asks to save and hand back, rather than waits for. */
996
1004
  const slicing = /* @__PURE__ */ new Set();
@@ -1069,7 +1077,10 @@ var createJobWorker = ({ queue, lookups, module, functionJobs, workers = 4, poll
1069
1077
  */
1070
1078
  const executeSlice = async (job, jobs) => {
1071
1079
  const controller = new AbortController();
1072
- active.set(job.id, controller);
1080
+ active.set(job.id, {
1081
+ controller,
1082
+ environment: job.environment
1083
+ });
1073
1084
  slicing.add(job.id);
1074
1085
  try {
1075
1086
  await jobs.announce(job.spaceId, job.id);
@@ -1206,6 +1217,7 @@ var createJobWorker = ({ queue, lookups, module, functionJobs, workers = 4, poll
1206
1217
  const ttlMs = (await module.limitsFor(job.spaceId, entry.document)).timeoutMs;
1207
1218
  const begin = call?.idempotencyKey ? {
1208
1219
  spaceId: job.spaceId,
1220
+ environment: job.environment,
1209
1221
  actionId,
1210
1222
  callerId: call.callerId,
1211
1223
  input: job.input,
@@ -1214,6 +1226,7 @@ var createJobWorker = ({ queue, lookups, module, functionJobs, workers = 4, poll
1214
1226
  ...spareJobs.has(job.id) ? { spare: true } : {}
1215
1227
  } : {
1216
1228
  spaceId: job.spaceId,
1229
+ environment: job.environment,
1217
1230
  actionId,
1218
1231
  callerId: call?.callerId ?? trigger,
1219
1232
  input: job.input,
@@ -1264,7 +1277,10 @@ var createJobWorker = ({ queue, lookups, module, functionJobs, workers = 4, poll
1264
1277
  await fail(job, void 0, `could not start: ${refusal}`);
1265
1278
  return;
1266
1279
  }
1267
- active.set(job.id, run.controller);
1280
+ active.set(job.id, {
1281
+ controller: run.controller,
1282
+ environment: job.environment
1283
+ });
1268
1284
  try {
1269
1285
  const result = await module.runAction({
1270
1286
  entry,
@@ -1460,7 +1476,7 @@ var createJobWorker = ({ queue, lookups, module, functionJobs, workers = 4, poll
1460
1476
  jobIds: held,
1461
1477
  workerId,
1462
1478
  leaseMs
1463
- })) active.get(jobId)?.abort(stop);
1479
+ })) active.get(jobId)?.controller.abort(stop);
1464
1480
  };
1465
1481
  /** The jobs this replica marked as held near its memory: each is said once, while it holds it. */
1466
1482
  const markedNear = /* @__PURE__ */ new Set();
@@ -1503,6 +1519,7 @@ var createJobWorker = ({ queue, lookups, module, functionJobs, workers = 4, poll
1503
1519
  beat,
1504
1520
  watchMemory,
1505
1521
  inFlight: () => active.size,
1522
+ inFlightByEnvironment: () => tally([...active.values()].map((held) => held.environment)),
1506
1523
  start: () => {
1507
1524
  if (timer || workers <= 0) return;
1508
1525
  timer = setInterval(() => void guarded(), pollMs);
@@ -1523,7 +1540,7 @@ var createJobWorker = ({ queue, lookups, module, functionJobs, workers = 4, poll
1523
1540
  stopListening = void 0;
1524
1541
  await pass;
1525
1542
  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");
1543
+ for (const jobId of slicing) active.get(jobId)?.controller.abort("shutdown");
1527
1544
  /**
1528
1545
  * Drained rather than abandoned: a deploy finishes the jobs it started instead of leaving them to be retried.
1529
1546
  *
@@ -1774,6 +1791,7 @@ var createRunGuards = (config = {}, store, idempotency = {}) => {
1774
1791
  runKey,
1775
1792
  kind,
1776
1793
  spaceId: params.spaceId,
1794
+ ...params.environment ? { environment: params.environment } : {},
1777
1795
  actionId: params.actionId,
1778
1796
  callerId: params.callerId,
1779
1797
  controller: new AbortController(),
@@ -1882,14 +1900,24 @@ var createRunGuards = (config = {}, store, idempotency = {}) => {
1882
1900
  }
1883
1901
  };
1884
1902
  const join = (params) => byKey.get(deriveRunKey(params))?.answered;
1903
+ /** The runs of a kind in flight, by the environment each said it is for. */
1904
+ const byEnvironment = (kind) => {
1905
+ const held = {};
1906
+ byKey.forEach((run) => {
1907
+ if (run.kind === kind && run.environment) held[run.environment] = (held[run.environment] ?? 0) + 1;
1908
+ });
1909
+ return held;
1910
+ };
1885
1911
  const slots = () => ({
1886
1912
  calls: {
1887
1913
  used: count((run) => run.kind === "call"),
1888
- of: perProcess
1914
+ of: perProcess,
1915
+ environments: byEnvironment("call")
1889
1916
  },
1890
1917
  renders: {
1891
1918
  used: count((run) => run.kind === "render"),
1892
- of: renderPerProcess
1919
+ of: renderPerProcess,
1920
+ environments: byEnvironment("render")
1893
1921
  }
1894
1922
  });
1895
1923
  const room = () => {
@@ -1,4 +1,4 @@
1
- import { l as scheduleKey } from "./queueRules-B3AGQGPs.mjs";
1
+ import { c as scheduleKey } from "./queueRules-C6jJo_yv.mjs";
2
2
  import { isRecord } from "@plitzi/sdk-shared/helpers";
3
3
  // src/engine/jobs/queueDocument.ts
4
4
  var documentOf = ({ jobs, schedules }) => ({
@@ -292,7 +292,7 @@ var queueRules = ({ jobs, schedules }, { retainFinished, clock, onUnansweredChan
292
292
  total: matching.length
293
293
  };
294
294
  },
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 })),
295
+ 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
296
  summarize: ({ spaces = 10 } = {}) => summarizeJobs([...jobs.values()], spaces),
297
297
  countDue: ({ spaces, memoryMb } = {}) => {
298
298
  const at = now();
@@ -396,6 +396,28 @@ var waitingKindOf = (kind, trigger) => {
396
396
  }
397
397
  };
398
398
  /** Every status at zero: what a summary counts up from, so a status nothing is in still says 0. */
399
+ /**
400
+ * The jobs counted by status and environment — a store's own grouping, one row a pair — as `summarize` answers them:
401
+ * every status, and the same for each environment, the one with the most jobs first.
402
+ */
403
+ var statusCounts = (counted) => {
404
+ const byStatus = noJobsByStatus();
405
+ const byEnvironment = /* @__PURE__ */ new Map();
406
+ for (const { status, environment, n } of counted) {
407
+ byStatus[status] += n;
408
+ const kept = byEnvironment.get(environment) ?? noJobsByStatus();
409
+ kept[status] += n;
410
+ byEnvironment.set(environment, kept);
411
+ }
412
+ const total = (counts) => Object.values(counts).reduce((sum, n) => sum + n, 0);
413
+ return {
414
+ byStatus,
415
+ environments: [...byEnvironment].map(([environment, counts]) => ({
416
+ environment,
417
+ byStatus: counts
418
+ })).sort((a, b) => total(b.byStatus) - total(a.byStatus) || a.environment.localeCompare(b.environment))
419
+ };
420
+ };
399
421
  var noJobsByStatus = () => ({
400
422
  pending: 0,
401
423
  running: 0,
@@ -418,7 +440,7 @@ var NEEDING_STATUSES = ["pending", "paused"];
418
440
  * ones count the same in their own query.
419
441
  */
420
442
  var summarizeJobs = (all, spaces) => {
421
- const byStatus = noJobsByStatus();
443
+ const pairs = /* @__PURE__ */ new Map();
422
444
  const waiting = {
423
445
  calls: 0,
424
446
  schedules: 0,
@@ -433,7 +455,14 @@ var summarizeJobs = (all, spaces) => {
433
455
  paused: 0
434
456
  };
435
457
  all.forEach((job) => {
436
- byStatus[job.status] += 1;
458
+ const pair = `${job.status}\u0000${job.environment}`;
459
+ const counted = pairs.get(pair) ?? {
460
+ status: job.status,
461
+ environment: job.environment,
462
+ n: 0
463
+ };
464
+ counted.n += 1;
465
+ pairs.set(pair, counted);
437
466
  if (job.needsMemoryMb !== void 0 && NEEDING_STATUSES.includes(job.status)) {
438
467
  if (job.status === "paused") needingMemory.paused += 1;
439
468
  else {
@@ -463,7 +492,7 @@ var summarizeJobs = (all, spaces) => {
463
492
  bySpace.set(job.spaceId, space);
464
493
  });
465
494
  return {
466
- byStatus,
495
+ ...statusCounts(pairs.values()),
467
496
  waiting,
468
497
  ...oldestDueAt === void 0 ? {} : { oldestDueAt },
469
498
  needingMemory,
@@ -504,4 +533,4 @@ var queueOver = (access) => ({
504
533
  cancelPending: (...args) => access("cancelPending", args),
505
534
  cancelWaiting: (...args) => access("cancelWaiting", args)
506
535
  });
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 };
536
+ 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-BP0LBhlj.mjs";
2
2
  import { getSourceName } from "@plitzi/sdk-shared/dataSource/helpers";
3
3
  // src/connectors/projection.ts
4
4
  /**
@@ -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-BP0LBhlj.mjs";
2
+ import { i as readFunctionsDir, n as loadFunctions, r as loadFunctionsSource } from "../chunks/load-qeEXWO8c.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-BP0LBhlj.mjs";
2
+ import { n as describeTask, r as createConnectorResolver, t as describeCatalog } from "./chunks/taskCatalog-Dp8XjA8_.mjs";
3
+ import { n as stateOf, t as documentOf } from "./chunks/queueDocument-veQsE-_i.mjs";
4
+ import { a as emptyState, i as changedBy, l as statusCounts, o as queueOver, r as applyRule, s as queueRules } from "./chunks/queueRules-C6jJo_yv.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-C6jJo_yv.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
@@ -437,9 +437,12 @@ var createMongoJobQueue = ({ db, collections: names = {}, retentionDays = 90 })
437
437
  total
438
438
  };
439
439
  },
440
- listAcross: async ({ statuses, limit, order }) => {
440
+ listAcross: async ({ statuses, limit, order, environment }) => {
441
441
  const { jobs } = await collections();
442
- return (await jobs.find({ status: { $in: statuses } }).sort(order === "due" ? {
442
+ return (await jobs.find({
443
+ status: { $in: statuses },
444
+ ...environment === void 0 ? {} : { environment }
445
+ }).sort(order === "due" ? {
443
446
  runAt: 1,
444
447
  _id: 1
445
448
  } : {
@@ -452,7 +455,10 @@ var createMongoJobQueue = ({ db, collections: names = {}, retentionDays = 90 })
452
455
  const waitingNow = { status: { $in: [...WAITING_STATUSES] } };
453
456
  const [found] = await jobs.aggregate([{ $facet: {
454
457
  byStatus: [{ $group: {
455
- _id: "$status",
458
+ _id: {
459
+ status: "$status",
460
+ environment: "$environment"
461
+ },
456
462
  n: { $sum: 1 }
457
463
  } }],
458
464
  needingMemory: [{ $match: {
@@ -492,10 +498,6 @@ var createMongoJobQueue = ({ db, collections: names = {}, retentionDays = 90 })
492
498
  { $limit: Math.max(1, spaces) }
493
499
  ]
494
500
  } }]).toArray();
495
- const byStatus = noJobsByStatus();
496
- found.byStatus.forEach((each) => {
497
- byStatus[each._id] = each.n;
498
- });
499
501
  const waiting = {
500
502
  calls: 0,
501
503
  schedules: 0,
@@ -510,7 +512,10 @@ var createMongoJobQueue = ({ db, collections: names = {}, retentionDays = 90 })
510
512
  });
511
513
  const waitingForMemory = found.needingMemory.find((each) => each._id === "pending");
512
514
  return {
513
- byStatus,
515
+ ...statusCounts(found.byStatus.map((each) => ({
516
+ ...each._id,
517
+ n: each.n
518
+ }))),
514
519
  waiting,
515
520
  ...oldestDueAt === void 0 ? {} : { oldestDueAt },
516
521
  needingMemory: {
@@ -1,4 +1,4 @@
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-C6jJo_yv.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";
@@ -200,7 +200,7 @@ var NEEDING = "status IN ('pending', 'paused')";
200
200
  */
201
201
  var summarizeJobsTable = async (conn, table, spaces) => {
202
202
  const [statuses, kinds, bySpace, needing] = await Promise.all([
203
- selectRows(conn, `SELECT status, COUNT(*) AS n FROM ${table} GROUP BY status`, []),
203
+ selectRows(conn, `SELECT status, environment, COUNT(*) AS n FROM ${table} GROUP BY status, environment`, []),
204
204
  selectRows(conn, `SELECT target_kind AS kind, ${TRIGGER} AS trig, COUNT(*) AS n, MIN(due_at) AS oldest
205
205
  FROM ${table} WHERE ${WAITING} GROUP BY target_kind, trig`, []),
206
206
  selectRows(conn, `SELECT j.space_id, COUNT(*) AS waiting, SUM(JSON_UNQUOTE(JSON_EXTRACT(j.target, '$.trigger')) = 'call') AS calls,
@@ -214,10 +214,6 @@ var summarizeJobsTable = async (conn, table, spaces) => {
214
214
  ]);
215
215
  const waitingForMemory = needing.find((row) => row.status === "pending");
216
216
  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
217
  const waiting = {
222
218
  calls: 0,
223
219
  schedules: 0,
@@ -231,7 +227,10 @@ var summarizeJobsTable = async (conn, table, spaces) => {
231
227
  oldestDueAt = oldestDueAt === void 0 ? Number(row.oldest) : Math.min(oldestDueAt, Number(row.oldest));
232
228
  });
233
229
  return {
234
- byStatus,
230
+ ...statusCounts(statuses.map((row) => ({
231
+ ...row,
232
+ n: Number(row.n)
233
+ }))),
235
234
  waiting,
236
235
  ...oldestDueAt === void 0 ? {} : { oldestDueAt },
237
236
  needingMemory: {
@@ -591,9 +590,14 @@ var createMysqlJobQueue = ({ pool, tablePrefix = "", createTables = true, retent
591
590
  const row = await selectOne(conn, `SELECT COUNT(*) AS n FROM ${t.jobs} WHERE ${where.sql}`, where.params);
592
591
  return Number(row?.n ?? 0);
593
592
  },
594
- listAcross: async ({ statuses, limit, order }) => {
593
+ listAcross: async ({ statuses, limit, order, environment }) => {
595
594
  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);
595
+ return (await selectRows(await db(), `SELECT * FROM ${t.jobs} WHERE status IN (?)${environment === void 0 ? "" : " AND environment = ?"}
596
+ ORDER BY ${order === "due" ? "run_at ASC" : "updated_at DESC"}, id LIMIT ?`, [
597
+ statuses,
598
+ ...environment === void 0 ? [] : [environment],
599
+ limit
600
+ ])).map(toJob);
597
601
  },
598
602
  summarize: async ({ spaces = 10 } = {}) => summarizeJobsTable(await db(), t.jobs, spaces),
599
603
  flow: async ({ from, to }) => {
@@ -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-veQsE-_i.mjs";
2
+ import { a as emptyState, i as changedBy, o as queueOver, r as applyRule, s as queueRules } from "../chunks/queueRules-C6jJo_yv.mjs";
3
3
  import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  import { DatabaseSync } from "node:sqlite";
@@ -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;
@@ -281,6 +289,8 @@ export type JobQueue = {
281
289
  statuses: JobStatus[];
282
290
  limit: number;
283
291
  order: 'due' | 'latest';
292
+ /** One environment's jobs alone (`production`, `main`…); every environment's without it. */
293
+ environment?: Environment;
284
294
  }) => Promise<Job[]>;
285
295
  /**
286
296
  * 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-BP0LBhlj.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-Dp8XjA8_.mjs";
6
+ import { t as isFunctionsDefinition } from "../chunks/load-qeEXWO8c.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.10",
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.10",
41
+ "@plitzi/sdk-shared": "0.39.10",
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.10",
63
63
  "@types/node": "^26.6.6",
64
64
  "@types/nodemailer": "^8.0.2",
65
65
  "@types/ws": "^8.18.2",