@diia-inhouse/workflow 1.17.7 → 2.5.0

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.
Files changed (144) hide show
  1. package/dist/activities/index.d.ts +1 -0
  2. package/dist/activities/index.js +2 -18
  3. package/dist/activities/proxy.d.ts +34 -0
  4. package/dist/activities/proxy.js +16 -24
  5. package/dist/activity.d.ts +2 -0
  6. package/dist/activity.js +2 -15
  7. package/dist/cli/checkWorkflowDeterminism.js +249 -275
  8. package/dist/cli/determinism/errorClassifier.js +56 -60
  9. package/dist/cli/determinism/historyFiles.js +68 -97
  10. package/dist/cli/determinism/index.js +7 -19
  11. package/dist/cli/determinism/replayExecutor.js +114 -133
  12. package/dist/cli/determinism/replayOptions.js +13 -22
  13. package/dist/cli/determinism/report.js +55 -45
  14. package/dist/cli/determinism/reportPrinter.js +101 -138
  15. package/dist/cli/index.d.ts +1 -0
  16. package/dist/cli/index.js +79 -119
  17. package/dist/cli/syncTemporalSchedules.js +74 -91
  18. package/dist/cli/updateTemporalSchedule.js +43 -53
  19. package/dist/client.d.ts +3 -0
  20. package/dist/client.js +3 -19
  21. package/dist/common.d.ts +2 -0
  22. package/dist/common.js +2 -13
  23. package/dist/encryption/crypto.d.ts +7 -0
  24. package/dist/encryption/crypto.js +20 -22
  25. package/dist/encryption/dataConverter.d.ts +7 -0
  26. package/dist/encryption/dataConverter.js +15 -22
  27. package/dist/encryption/encryptionCodec.d.ts +31 -0
  28. package/dist/encryption/encryptionCodec.js +108 -124
  29. package/dist/encryption/index.d.ts +3 -0
  30. package/dist/encryption/index.js +4 -20
  31. package/dist/index.d.ts +7 -0
  32. package/dist/index.js +6 -42
  33. package/dist/instrumentation.js +6 -10
  34. package/dist/interceptors/asyncLocalStorageBridge.js +29 -66
  35. package/dist/interceptors/traceLogAttributes.d.ts +6 -0
  36. package/dist/interceptors/traceLogAttributes.js +16 -54
  37. package/dist/interceptors.d.ts +6 -0
  38. package/dist/interceptors.js +6 -8
  39. package/dist/interfaces/config.d.ts +58 -0
  40. package/dist/interfaces/index.d.ts +1 -0
  41. package/dist/interfaces/services/schedulesExporter.d.ts +96 -0
  42. package/dist/interfaces/services/worker.d.ts +60 -0
  43. package/dist/operations.d.ts +9 -0
  44. package/dist/operations.js +11 -75
  45. package/dist/services/client.d.ts +24 -0
  46. package/dist/services/client.js +89 -96
  47. package/dist/services/schedulesExporter.d.ts +101 -0
  48. package/dist/services/schedulesExporter.js +456 -0
  49. package/dist/services/worker/identity.d.ts +4 -0
  50. package/dist/services/worker/identity.js +6 -9
  51. package/dist/services/worker.d.ts +124 -0
  52. package/dist/services/worker.js +324 -304
  53. package/dist/services/workerHealth.d.ts +15 -0
  54. package/dist/services/workerHealth.js +26 -35
  55. package/dist/testing.d.ts +42 -0
  56. package/dist/testing.js +43 -54
  57. package/dist/worker.d.ts +9 -0
  58. package/dist/worker.js +7 -25
  59. package/package.json +40 -38
  60. package/dist/activities/index.js.map +0 -1
  61. package/dist/activities/proxy.js.map +0 -1
  62. package/dist/activity.js.map +0 -1
  63. package/dist/cli/checkWorkflowDeterminism.js.map +0 -1
  64. package/dist/cli/determinism/errorClassifier.js.map +0 -1
  65. package/dist/cli/determinism/historyFiles.js.map +0 -1
  66. package/dist/cli/determinism/index.js.map +0 -1
  67. package/dist/cli/determinism/replayExecutor.js.map +0 -1
  68. package/dist/cli/determinism/replayOptions.js.map +0 -1
  69. package/dist/cli/determinism/report.js.map +0 -1
  70. package/dist/cli/determinism/reportPrinter.js.map +0 -1
  71. package/dist/cli/determinism/types.js +0 -3
  72. package/dist/cli/determinism/types.js.map +0 -1
  73. package/dist/cli/index.js.map +0 -1
  74. package/dist/cli/syncTemporalSchedules.js.map +0 -1
  75. package/dist/cli/updateTemporalSchedule.js.map +0 -1
  76. package/dist/client.js.map +0 -1
  77. package/dist/common.js.map +0 -1
  78. package/dist/encryption/crypto.js.map +0 -1
  79. package/dist/encryption/dataConverter.js.map +0 -1
  80. package/dist/encryption/encryptionCodec.js.map +0 -1
  81. package/dist/encryption/index.js.map +0 -1
  82. package/dist/index.js.map +0 -1
  83. package/dist/instrumentation.js.map +0 -1
  84. package/dist/interceptors/asyncLocalStorageBridge.js.map +0 -1
  85. package/dist/interceptors/index.js +0 -8
  86. package/dist/interceptors/index.js.map +0 -1
  87. package/dist/interceptors/traceLogAttributes.js.map +0 -1
  88. package/dist/interceptors.js.map +0 -1
  89. package/dist/interfaces/config.js +0 -3
  90. package/dist/interfaces/config.js.map +0 -1
  91. package/dist/interfaces/index.js +0 -18
  92. package/dist/interfaces/index.js.map +0 -1
  93. package/dist/interfaces/services/worker.js +0 -3
  94. package/dist/interfaces/services/worker.js.map +0 -1
  95. package/dist/operations.js.map +0 -1
  96. package/dist/services/client.js.map +0 -1
  97. package/dist/services/index.js +0 -19
  98. package/dist/services/index.js.map +0 -1
  99. package/dist/services/worker/identity.js.map +0 -1
  100. package/dist/services/worker/index.js +0 -18
  101. package/dist/services/worker/index.js.map +0 -1
  102. package/dist/services/worker.js.map +0 -1
  103. package/dist/services/workerHealth.js.map +0 -1
  104. package/dist/testing.js.map +0 -1
  105. package/dist/types/activities/index.d.ts +0 -1
  106. package/dist/types/activities/proxy.d.ts +0 -35
  107. package/dist/types/activity.d.ts +0 -1
  108. package/dist/types/cli/checkWorkflowDeterminism.d.ts +0 -19
  109. package/dist/types/cli/determinism/errorClassifier.d.ts +0 -15
  110. package/dist/types/cli/determinism/historyFiles.d.ts +0 -18
  111. package/dist/types/cli/determinism/index.d.ts +0 -10
  112. package/dist/types/cli/determinism/replayExecutor.d.ts +0 -9
  113. package/dist/types/cli/determinism/replayOptions.d.ts +0 -7
  114. package/dist/types/cli/determinism/report.d.ts +0 -16
  115. package/dist/types/cli/determinism/reportPrinter.d.ts +0 -5
  116. package/dist/types/cli/determinism/types.d.ts +0 -44
  117. package/dist/types/cli/index.d.ts +0 -2
  118. package/dist/types/cli/syncTemporalSchedules.d.ts +0 -12
  119. package/dist/types/cli/updateTemporalSchedule.d.ts +0 -9
  120. package/dist/types/client.d.ts +0 -2
  121. package/dist/types/common.d.ts +0 -1
  122. package/dist/types/encryption/crypto.d.ts +0 -3
  123. package/dist/types/encryption/dataConverter.d.ts +0 -3
  124. package/dist/types/encryption/encryptionCodec.d.ts +0 -27
  125. package/dist/types/encryption/index.d.ts +0 -3
  126. package/dist/types/index.d.ts +0 -3
  127. package/dist/types/instrumentation.d.ts +0 -2
  128. package/dist/types/interceptors/asyncLocalStorageBridge.d.ts +0 -21
  129. package/dist/types/interceptors/index.d.ts +0 -2
  130. package/dist/types/interceptors/traceLogAttributes.d.ts +0 -2
  131. package/dist/types/interceptors.d.ts +0 -2
  132. package/dist/types/interfaces/config.d.ts +0 -38
  133. package/dist/types/interfaces/index.d.ts +0 -1
  134. package/dist/types/interfaces/services/worker.d.ts +0 -37
  135. package/dist/types/operations.d.ts +0 -5
  136. package/dist/types/services/client.d.ts +0 -20
  137. package/dist/types/services/index.d.ts +0 -2
  138. package/dist/types/services/worker/identity.d.ts +0 -1
  139. package/dist/types/services/worker/index.d.ts +0 -1
  140. package/dist/types/services/worker.d.ts +0 -113
  141. package/dist/types/services/workerHealth.d.ts +0 -11
  142. package/dist/types/testing.d.ts +0 -42
  143. package/dist/types/worker.d.ts +0 -3
  144. package/dist/worker.js.map +0 -1
@@ -0,0 +1,96 @@
1
+ import { Logger } from "@diia-inhouse/types";
2
+ import { Client } from "@temporalio/client";
3
+
4
+ //#region src/interfaces/services/schedulesExporter.d.ts
5
+ interface SchedulesExporterConfig {
6
+ /**
7
+ * Polling interval for `client.schedule.list()` and `describe()`. Default 30s.
8
+ */
9
+ pollIntervalMs?: number;
10
+ /**
11
+ * Polling interval for the visibility query that powers `diia_workflows_running`.
12
+ * Default 10s. Ignored when `pollVisibility` is `false`.
13
+ */
14
+ visibilityPollIntervalMs?: number;
15
+ /**
16
+ * If `false`, skip the visibility query (`workflow.list({ status=Running })`). Use this
17
+ * when the Temporal cluster does not have advanced visibility (Elasticsearch) enabled.
18
+ * Default `true`.
19
+ */
20
+ pollVisibility?: boolean;
21
+ /**
22
+ * How many upcoming fire times to expose per schedule as `slot=0..N-1` gauges.
23
+ * Default 5.
24
+ */
25
+ nextActionSlots?: number;
26
+ /**
27
+ * Maximum number of recent action events kept in memory for the `getRecentActions()`
28
+ * snapshot. Default 200.
29
+ */
30
+ recentActionsHistorySize?: number;
31
+ /**
32
+ * If `false`, skip the completed-executions query that powers `diia_workflow_duration_seconds`.
33
+ * Default `true`. Disable when you have no advanced visibility, or when duration
34
+ * tracking is handled elsewhere (e.g. via the SDK's `workflow_endtoend_latency` metric).
35
+ */
36
+ pollCompletions?: boolean;
37
+ /**
38
+ * Polling interval for the completed-executions query. Default 60s.
39
+ */
40
+ completionsPollIntervalMs?: number;
41
+ /**
42
+ * How far back the FIRST completions poll looks (subsequent polls use a sliding window
43
+ * based on the previous poll time). Set this to roughly the histogram retention you want
44
+ * after a fresh restart. Default 1h.
45
+ */
46
+ completionsLookbackMs?: number;
47
+ /**
48
+ * Maximum number of recently-observed completed run IDs kept in memory for de-duplication
49
+ * across overlapping polls. LRU-trimmed. Default 2000.
50
+ */
51
+ completionsSeenCapacity?: number;
52
+ }
53
+ interface SchedulesExporterDeps {
54
+ /**
55
+ * Temporal client used to call `schedule.list`, `schedule.getHandle().describe`, and
56
+ * `workflow.list`. Typed as `Pick<Client, 'schedule' | 'workflow'>` so this interface
57
+ * stays decoupled from the `TemporalClient` wrapper class (avoids a cycle through
58
+ * `interfaces/config.ts`); the wrapper's `schedule`/`workflow` getters satisfy this shape.
59
+ */
60
+ client: Pick<Client, "schedule" | "workflow">;
61
+ /**
62
+ * The worker's task queue. Schedules whose `action.taskQueue` does not match are
63
+ * ignored — this guarantees each service emits metrics only for the schedules it owns.
64
+ */
65
+ taskQueue: string;
66
+ logger?: Logger;
67
+ }
68
+ /**
69
+ * Single upcoming schedule fire returned by `SchedulesExporter.getCalendarEvents()`.
70
+ * Each schedule contributes up to `nextActionSlots` events, ordered by `slot` ascending
71
+ * (slot 0 is the next fire).
72
+ */
73
+ interface ScheduleCalendarEvent {
74
+ scheduleId: string;
75
+ workflowType: string;
76
+ taskQueue: string;
77
+ cadence: string;
78
+ slot: number;
79
+ fireAt: string;
80
+ fireAtMs: number;
81
+ paused: number;
82
+ lastSucceeded: number | null;
83
+ }
84
+ /**
85
+ * Single recent schedule action returned by `SchedulesExporter.getRecentActions()`.
86
+ */
87
+ interface ScheduleRecentAction {
88
+ scheduleId: string;
89
+ workflowType: string;
90
+ taskQueue: string;
91
+ firedAt: string;
92
+ firedAtMs: number;
93
+ succeeded: number;
94
+ }
95
+ //#endregion
96
+ export { ScheduleCalendarEvent, ScheduleRecentAction, SchedulesExporterConfig, SchedulesExporterDeps };
@@ -0,0 +1,60 @@
1
+ import { WorkerOptions, WorkerStatus } from "@temporalio/worker";
2
+
3
+ //#region src/interfaces/services/worker.d.ts
4
+ /**
5
+ * Structural type for the OpenTelemetry tracer provider that pkg-workflow accepts.
6
+ *
7
+ * pkg-workflow only needs the `service.name` resource attribute. By matching that
8
+ * shape structurally (instead of importing `NodeTracerProvider` from a pinned
9
+ * `@opentelemetry/sdk-trace-node` major), we accept providers from both OTel 1.x
10
+ * (where `resource` is a public field) and OTel 2.x (where it is private and the
11
+ * value is read defensively at runtime).
12
+ *
13
+ * `getTracer` is required because it is the only public member shared by both
14
+ * OTel majors — without it TypeScript's weak-type check rejects 2.x providers
15
+ * (whose other state is private).
16
+ */
17
+ interface NodeTracerProviderLike {
18
+ getTracer(name: string, version?: string, options?: {
19
+ schemaUrl?: string;
20
+ }): unknown;
21
+ resource?: {
22
+ attributes?: Record<string, unknown>;
23
+ };
24
+ }
25
+ type WorkerStatusProvider = () => WorkerStatus;
26
+ type ActivityClass = new (...args: any[]) => any;
27
+ interface WorkerBootstrapOptions extends Omit<WorkerOptions, "taskQueue" | "activities" | "workflowsPath"> {
28
+ /**
29
+ * Path to the workflows module. Accepts either an absolute filesystem path
30
+ * or a `file://` URL (e.g. from `import.meta.resolve('./worker/workflows/index.js')`).
31
+ */
32
+ workflowsPath: string;
33
+ activities: Record<string, ActivityClass>;
34
+ nodeTracerProvider?: NodeTracerProviderLike;
35
+ shutdownSignals?: NodeJS.Signals[];
36
+ /**
37
+ * When provided together with `deps`, `bootstrapWorker` manages the full application
38
+ * lifecycle: setConfig → apply worker overrides → setDeps → initialize → start → run worker.
39
+ */
40
+ configFactory?: (...args: any[]) => Promise<any>;
41
+ /**
42
+ * Dependency factory passed to `app.setDeps()`. Required when `configFactory` is provided.
43
+ */
44
+ deps?: (...args: any[]) => Promise<any>;
45
+ }
46
+ interface Container {
47
+ build(constructor: new (...args: unknown[]) => unknown): unknown;
48
+ resolve<T = unknown>(key: string): T;
49
+ }
50
+ interface App {
51
+ container?: Container;
52
+ getConfig?(): unknown;
53
+ setConfig?(factory: (...args: any[]) => Promise<any>): Promise<any>;
54
+ setDeps?(factory: (...args: any[]) => Promise<any>): Promise<any>;
55
+ initialize?(...args: any[]): Promise<{
56
+ start(): Promise<any>;
57
+ }>;
58
+ }
59
+ //#endregion
60
+ export { ActivityClass, App, NodeTracerProviderLike, WorkerBootstrapOptions, WorkerStatusProvider };
@@ -0,0 +1,9 @@
1
+ import { buildActivitiesProxy } from "./activities/proxy.js";
2
+ import { workflowInterceptors } from "./interceptors.js";
3
+ import { ActivityFailure as ActivityFailure$1 } from "@temporalio/common";
4
+ import { ActivityFailure, ApplicationFailure, CancellationScope, CancellationScopeOptions, CancelledFailure, ChildWorkflowFailure, ChildWorkflowHandle, ChildWorkflowOptions, CommonWorkflowOptions, ContinueAsNew, ContinueAsNewOptions, DeterminismViolationError, ServerFailure, TemporalFailure, TerminatedFailure, TimeoutFailure, Trigger, WorkflowError, WorkflowInfo, WorkflowInterceptorsFactory, addDefaultWorkflowOptions, allHandlersFinished, condition, continueAsNew, currentUpdateInfo, defineQuery, defineSignal, defineUpdate, deprecatePatch, executeChild, extractWorkflowType, getExternalWorkflowHandle, inWorkflowContext, isCancellation, log, makeContinueAsNewFunc, patched, proxyActivities, proxyLocalActivities, proxySinks, scheduleActivity, scheduleLocalActivity, setDefaultSignalHandler, setHandler, sleep, startChild, upsertMemo, upsertSearchAttributes, uuid4, workflowInfo, workflowMetadataQuery } from "@temporalio/workflow";
5
+
6
+ //#region src/operations.d.ts
7
+ declare function isNonRetryableFailure(err: unknown): err is ActivityFailure$1;
8
+ //#endregion
9
+ export { ActivityFailure, ApplicationFailure, CancellationScope, type CancellationScopeOptions, CancelledFailure, ChildWorkflowFailure, type ChildWorkflowHandle, type ChildWorkflowOptions, type CommonWorkflowOptions, ContinueAsNew, type ContinueAsNewOptions, DeterminismViolationError, ServerFailure, TemporalFailure, TerminatedFailure, TimeoutFailure, Trigger, WorkflowError, type WorkflowInfo, type WorkflowInterceptorsFactory, addDefaultWorkflowOptions, allHandlersFinished, buildActivitiesProxy, condition, continueAsNew, currentUpdateInfo, defineQuery, defineSignal, defineUpdate, deprecatePatch, executeChild, extractWorkflowType, getExternalWorkflowHandle, inWorkflowContext, isCancellation, isNonRetryableFailure, log, makeContinueAsNewFunc, patched, proxyActivities, proxyLocalActivities, proxySinks, scheduleActivity, scheduleLocalActivity, setDefaultSignalHandler, setHandler, sleep, startChild, upsertMemo, upsertSearchAttributes, uuid4, workflowInfo, workflowInterceptors, workflowMetadataQuery };
@@ -1,77 +1,13 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.buildActivitiesProxy = exports.TemporalFailure = exports.TerminatedFailure = exports.CancelledFailure = exports.ActivityFailure = exports.TimeoutFailure = exports.ServerFailure = exports.ChildWorkflowFailure = exports.ApplicationFailure = exports.WorkflowError = exports.DeterminismViolationError = exports.getExternalWorkflowHandle = exports.Trigger = exports.CancellationScope = exports.inWorkflowContext = exports.proxySinks = exports.proxyLocalActivities = exports.proxyActivities = exports.scheduleLocalActivity = exports.scheduleActivity = exports.isCancellation = exports.uuid4 = exports.addDefaultWorkflowOptions = exports.deprecatePatch = exports.patched = exports.upsertSearchAttributes = exports.upsertMemo = exports.extractWorkflowType = exports.startChild = exports.executeChild = exports.defineUpdate = exports.defineSignal = exports.defineQuery = exports.setHandler = exports.sleep = exports.workflowMetadataQuery = exports.currentUpdateInfo = exports.workflowInfo = exports.log = exports.setDefaultSignalHandler = exports.ContinueAsNew = exports.makeContinueAsNewFunc = exports.continueAsNew = exports.condition = exports.allHandlersFinished = void 0;
18
- exports.isNonRetryableFailure = isNonRetryableFailure;
19
- const common_1 = require("@temporalio/common");
20
- var workflow_1 = require("@temporalio/workflow");
21
- Object.defineProperty(exports, "allHandlersFinished", { enumerable: true, get: function () { return workflow_1.allHandlersFinished; } });
22
- Object.defineProperty(exports, "condition", { enumerable: true, get: function () { return workflow_1.condition; } });
23
- Object.defineProperty(exports, "continueAsNew", { enumerable: true, get: function () { return workflow_1.continueAsNew; } });
24
- Object.defineProperty(exports, "makeContinueAsNewFunc", { enumerable: true, get: function () { return workflow_1.makeContinueAsNewFunc; } });
25
- Object.defineProperty(exports, "ContinueAsNew", { enumerable: true, get: function () { return workflow_1.ContinueAsNew; } });
26
- Object.defineProperty(exports, "setDefaultSignalHandler", { enumerable: true, get: function () { return workflow_1.setDefaultSignalHandler; } });
27
- Object.defineProperty(exports, "log", { enumerable: true, get: function () { return workflow_1.log; } });
28
- Object.defineProperty(exports, "workflowInfo", { enumerable: true, get: function () { return workflow_1.workflowInfo; } });
29
- Object.defineProperty(exports, "currentUpdateInfo", { enumerable: true, get: function () { return workflow_1.currentUpdateInfo; } });
30
- Object.defineProperty(exports, "workflowMetadataQuery", { enumerable: true, get: function () { return workflow_1.workflowMetadataQuery; } });
31
- Object.defineProperty(exports, "sleep", { enumerable: true, get: function () { return workflow_1.sleep; } });
32
- Object.defineProperty(exports, "setHandler", { enumerable: true, get: function () { return workflow_1.setHandler; } });
33
- Object.defineProperty(exports, "defineQuery", { enumerable: true, get: function () { return workflow_1.defineQuery; } });
34
- Object.defineProperty(exports, "defineSignal", { enumerable: true, get: function () { return workflow_1.defineSignal; } });
35
- Object.defineProperty(exports, "defineUpdate", { enumerable: true, get: function () { return workflow_1.defineUpdate; } });
36
- Object.defineProperty(exports, "executeChild", { enumerable: true, get: function () { return workflow_1.executeChild; } });
37
- Object.defineProperty(exports, "startChild", { enumerable: true, get: function () { return workflow_1.startChild; } });
38
- Object.defineProperty(exports, "extractWorkflowType", { enumerable: true, get: function () { return workflow_1.extractWorkflowType; } });
39
- Object.defineProperty(exports, "upsertMemo", { enumerable: true, get: function () { return workflow_1.upsertMemo; } });
40
- Object.defineProperty(exports, "upsertSearchAttributes", { enumerable: true, get: function () { return workflow_1.upsertSearchAttributes; } });
41
- Object.defineProperty(exports, "patched", { enumerable: true, get: function () { return workflow_1.patched; } });
42
- Object.defineProperty(exports, "deprecatePatch", { enumerable: true, get: function () { return workflow_1.deprecatePatch; } });
43
- Object.defineProperty(exports, "addDefaultWorkflowOptions", { enumerable: true, get: function () { return workflow_1.addDefaultWorkflowOptions; } });
44
- Object.defineProperty(exports, "uuid4", { enumerable: true, get: function () { return workflow_1.uuid4; } });
45
- Object.defineProperty(exports, "isCancellation", { enumerable: true, get: function () { return workflow_1.isCancellation; } });
46
- Object.defineProperty(exports, "scheduleActivity", { enumerable: true, get: function () { return workflow_1.scheduleActivity; } });
47
- Object.defineProperty(exports, "scheduleLocalActivity", { enumerable: true, get: function () { return workflow_1.scheduleLocalActivity; } });
48
- Object.defineProperty(exports, "proxyActivities", { enumerable: true, get: function () { return workflow_1.proxyActivities; } });
49
- Object.defineProperty(exports, "proxyLocalActivities", { enumerable: true, get: function () { return workflow_1.proxyLocalActivities; } });
50
- Object.defineProperty(exports, "proxySinks", { enumerable: true, get: function () { return workflow_1.proxySinks; } });
51
- Object.defineProperty(exports, "inWorkflowContext", { enumerable: true, get: function () { return workflow_1.inWorkflowContext; } });
52
- Object.defineProperty(exports, "CancellationScope", { enumerable: true, get: function () { return workflow_1.CancellationScope; } });
53
- Object.defineProperty(exports, "Trigger", { enumerable: true, get: function () { return workflow_1.Trigger; } });
54
- Object.defineProperty(exports, "getExternalWorkflowHandle", { enumerable: true, get: function () { return workflow_1.getExternalWorkflowHandle; } });
55
- Object.defineProperty(exports, "DeterminismViolationError", { enumerable: true, get: function () { return workflow_1.DeterminismViolationError; } });
56
- Object.defineProperty(exports, "WorkflowError", { enumerable: true, get: function () { return workflow_1.WorkflowError; } });
57
- Object.defineProperty(exports, "ApplicationFailure", { enumerable: true, get: function () { return workflow_1.ApplicationFailure; } });
58
- Object.defineProperty(exports, "ChildWorkflowFailure", { enumerable: true, get: function () { return workflow_1.ChildWorkflowFailure; } });
59
- Object.defineProperty(exports, "ServerFailure", { enumerable: true, get: function () { return workflow_1.ServerFailure; } });
60
- Object.defineProperty(exports, "TimeoutFailure", { enumerable: true, get: function () { return workflow_1.TimeoutFailure; } });
61
- Object.defineProperty(exports, "ActivityFailure", { enumerable: true, get: function () { return workflow_1.ActivityFailure; } });
62
- Object.defineProperty(exports, "CancelledFailure", { enumerable: true, get: function () { return workflow_1.CancelledFailure; } });
63
- Object.defineProperty(exports, "TerminatedFailure", { enumerable: true, get: function () { return workflow_1.TerminatedFailure; } });
64
- Object.defineProperty(exports, "TemporalFailure", { enumerable: true, get: function () { return workflow_1.TemporalFailure; } });
65
- var activities_1 = require("./activities");
66
- Object.defineProperty(exports, "buildActivitiesProxy", { enumerable: true, get: function () { return activities_1.buildActivitiesProxy; } });
67
- __exportStar(require("./interceptors"), exports);
1
+ import { buildActivitiesProxy } from "./activities/proxy.js";
2
+ import "./activities/index.js";
3
+ import { workflowInterceptors } from "./interceptors.js";
4
+ import { ActivityFailure as ActivityFailure$1, ApplicationFailure as ApplicationFailure$1, RetryState } from "@temporalio/common";
5
+ import { ActivityFailure, ApplicationFailure, CancellationScope, CancelledFailure, ChildWorkflowFailure, ContinueAsNew, DeterminismViolationError, ServerFailure, TemporalFailure, TerminatedFailure, TimeoutFailure, Trigger, WorkflowError, addDefaultWorkflowOptions, allHandlersFinished, condition, continueAsNew, currentUpdateInfo, defineQuery, defineSignal, defineUpdate, deprecatePatch, executeChild, extractWorkflowType, getExternalWorkflowHandle, inWorkflowContext, isCancellation, log, makeContinueAsNewFunc, patched, proxyActivities, proxyLocalActivities, proxySinks, scheduleActivity, scheduleLocalActivity, setDefaultSignalHandler, setHandler, sleep, startChild, upsertMemo, upsertSearchAttributes, uuid4, workflowInfo, workflowMetadataQuery } from "@temporalio/workflow";
6
+ //#region src/operations.ts
68
7
  function isNonRetryableFailure(err) {
69
- if (!(err instanceof common_1.ActivityFailure)) {
70
- return false;
71
- }
72
- if (err.retryState === common_1.RetryState.RETRY_POLICY_NOT_SET || err.retryState === common_1.RetryState.MAXIMUM_ATTEMPTS_REACHED) {
73
- return true;
74
- }
75
- return err.cause instanceof common_1.ApplicationFailure && Boolean(err.cause.nonRetryable);
8
+ if (!(err instanceof ActivityFailure$1)) return false;
9
+ if (err.retryState === RetryState.RETRY_POLICY_NOT_SET || err.retryState === RetryState.MAXIMUM_ATTEMPTS_REACHED) return true;
10
+ return err.cause instanceof ApplicationFailure$1 && Boolean(err.cause.nonRetryable);
76
11
  }
77
- //# sourceMappingURL=operations.js.map
12
+ //#endregion
13
+ export { ActivityFailure, ApplicationFailure, CancellationScope, CancelledFailure, ChildWorkflowFailure, ContinueAsNew, DeterminismViolationError, ServerFailure, TemporalFailure, TerminatedFailure, TimeoutFailure, Trigger, WorkflowError, addDefaultWorkflowOptions, allHandlersFinished, buildActivitiesProxy, condition, continueAsNew, currentUpdateInfo, defineQuery, defineSignal, defineUpdate, deprecatePatch, executeChild, extractWorkflowType, getExternalWorkflowHandle, inWorkflowContext, isCancellation, isNonRetryableFailure, log, makeContinueAsNewFunc, patched, proxyActivities, proxyLocalActivities, proxySinks, scheduleActivity, scheduleLocalActivity, setDefaultSignalHandler, setHandler, sleep, startChild, upsertMemo, upsertSearchAttributes, uuid4, workflowInfo, workflowInterceptors, workflowMetadataQuery };
@@ -0,0 +1,24 @@
1
+ import { TemporalConfig } from "../interfaces/config.js";
2
+ import { EnvService } from "@diia-inhouse/env";
3
+ import { Logger, OnInit } from "@diia-inhouse/types";
4
+ import { Client, ScheduleOptions, ScheduleUpdateOptions } from "@temporalio/client";
5
+
6
+ //#region src/services/client.d.ts
7
+ declare class TemporalClient implements OnInit {
8
+ private readonly config;
9
+ private readonly envService;
10
+ private readonly logger;
11
+ nativeClient!: Client;
12
+ private readonly defaultTimezone;
13
+ constructor(config: TemporalConfig, envService: EnvService, logger: Logger);
14
+ get connection(): Client["connection"];
15
+ get workflow(): Client["workflow"];
16
+ get workflowService(): Client["workflowService"];
17
+ get schedule(): Client["schedule"];
18
+ get taskQueue(): Client["taskQueue"];
19
+ onInit(): Promise<void>;
20
+ syncSchedules(schedules: Record<string, ((config: TemporalConfig) => ScheduleOptions) | ScheduleOptions>): Promise<void>;
21
+ updateSchedule(scheduleId: string, updateData: ScheduleUpdateOptions): Promise<void>;
22
+ }
23
+ //#endregion
24
+ export { TemporalClient };
@@ -1,96 +1,89 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TemporalClient = void 0;
4
- const client_1 = require("@temporalio/client");
5
- const client_2 = require("@temporalio/interceptors-opentelemetry/lib/client");
6
- const lodash_1 = require("lodash");
7
- const env_1 = require("@diia-inhouse/env");
8
- const dataConverter_1 = require("../encryption/dataConverter");
9
- class TemporalClient {
10
- config;
11
- envService;
12
- logger;
13
- nativeClient;
14
- defaultTimezone = 'Europe/Kyiv';
15
- constructor(config, envService, logger) {
16
- this.config = config;
17
- this.envService = envService;
18
- this.logger = logger;
19
- }
20
- get connection() {
21
- return this.nativeClient.connection;
22
- }
23
- get workflow() {
24
- return this.nativeClient.workflow;
25
- }
26
- get workflowService() {
27
- return this.nativeClient.workflowService;
28
- }
29
- get schedule() {
30
- return this.nativeClient.schedule;
31
- }
32
- get taskQueue() {
33
- return this.nativeClient.taskQueue;
34
- }
35
- async onInit() {
36
- const { address, tls, connectTimeout, encryptionEnabled, encryptionKeyId, encryptionKeyRefreshInterval, ...clientConfig } = this.config;
37
- const connection = await client_1.Connection.connect({ address, tls, connectTimeout }).catch((err) => {
38
- this.logger.error('Failed to connect to Temporal', { err });
39
- throw new Error('Failed to connect to Temporal', { cause: err });
40
- });
41
- const dataConverter = encryptionEnabled
42
- ? await (0, dataConverter_1.getDataConverter)(encryptionKeyId, this.envService, encryptionKeyRefreshInterval)
43
- : undefined;
44
- const interceptors = env_1.EnvService.getVar('TRACING_ENABLED', 'boolean', false)
45
- ? { workflow: [new client_2.OpenTelemetryWorkflowClientInterceptor()] }
46
- : undefined;
47
- this.nativeClient = new client_1.Client({ ...clientConfig, connection, dataConverter, interceptors });
48
- }
49
- async syncSchedules(schedules) {
50
- const applicationSchedules = Object.entries(schedules).map(([, schedule]) => typeof schedule === 'function' ? schedule(this.config) : schedule);
51
- const temporalSchedules = [];
52
- for await (const schedule of this.schedule.list()) {
53
- if (schedule.memo?.TaskQueue === this.config.taskQueue) {
54
- temporalSchedules.push(schedule);
55
- }
56
- }
57
- const schedulesToCreate = applicationSchedules.filter((scheduleOptions) => !temporalSchedules.some((schedule) => schedule.scheduleId === scheduleOptions.scheduleId));
58
- for (const scheduleOptions of schedulesToCreate) {
59
- scheduleOptions.memo = {
60
- ...scheduleOptions.memo,
61
- TaskQueue: scheduleOptions.action.taskQueue,
62
- };
63
- if (!scheduleOptions.spec.timezone) {
64
- scheduleOptions.spec.timezone = this.defaultTimezone;
65
- }
66
- await this.schedule.create(scheduleOptions);
67
- }
68
- if (schedulesToCreate.length > 0) {
69
- this.logger.info(`Schedules created (${schedulesToCreate.length}): ${schedulesToCreate.map((schedule) => schedule.scheduleId).join(', ')}`);
70
- }
71
- const schedulesToDelete = temporalSchedules.filter((schedule) => !applicationSchedules.some((scheduleOptions) => scheduleOptions.scheduleId === schedule.scheduleId));
72
- for (const schedule of schedulesToDelete) {
73
- const handle = this.schedule.getHandle(schedule.scheduleId);
74
- await handle.delete();
75
- }
76
- if (schedulesToDelete.length > 0) {
77
- this.logger.info(`Schedules deleted (${schedulesToDelete.length}): ${schedulesToDelete.map((schedule) => schedule.scheduleId).join(', ')}`);
78
- }
79
- }
80
- async updateSchedule(scheduleId, updateData) {
81
- try {
82
- const scheduleHandle = this.schedule.getHandle(scheduleId);
83
- this.logger.info('Schedule update details:', { scheduleId, updateData });
84
- await scheduleHandle.update((previous) => {
85
- return (0, lodash_1.merge)(previous, updateData);
86
- });
87
- this.logger.info('Successfully updated temporal schedule', { scheduleId });
88
- }
89
- catch (err) {
90
- this.logger.error('Failed to update temporal schedule', { err });
91
- throw err;
92
- }
93
- }
94
- }
95
- exports.TemporalClient = TemporalClient;
96
- //# sourceMappingURL=client.js.map
1
+ import { getDataConverter } from "../encryption/dataConverter.js";
2
+ import { EnvService } from "@diia-inhouse/env";
3
+ import { Client, Connection } from "@temporalio/client";
4
+ import { OpenTelemetryWorkflowClientInterceptor } from "@temporalio/interceptors-opentelemetry/lib/client/index.js";
5
+ import lodash from "lodash";
6
+ //#region src/services/client.ts
7
+ const { merge } = lodash;
8
+ var TemporalClient = class {
9
+ config;
10
+ envService;
11
+ logger;
12
+ nativeClient;
13
+ defaultTimezone = "Europe/Kyiv";
14
+ constructor(config, envService, logger) {
15
+ this.config = config;
16
+ this.envService = envService;
17
+ this.logger = logger;
18
+ }
19
+ get connection() {
20
+ return this.nativeClient.connection;
21
+ }
22
+ get workflow() {
23
+ return this.nativeClient.workflow;
24
+ }
25
+ get workflowService() {
26
+ return this.nativeClient.workflowService;
27
+ }
28
+ get schedule() {
29
+ return this.nativeClient.schedule;
30
+ }
31
+ get taskQueue() {
32
+ return this.nativeClient.taskQueue;
33
+ }
34
+ async onInit() {
35
+ const { address, tls, connectTimeout, encryptionEnabled, encryptionKeyId, encryptionKeyRefreshInterval, ...clientConfig } = this.config;
36
+ const connection = await Connection.connect({
37
+ address,
38
+ tls,
39
+ connectTimeout
40
+ }).catch((err) => {
41
+ this.logger.error("Failed to connect to Temporal", { err });
42
+ throw new Error("Failed to connect to Temporal", { cause: err });
43
+ });
44
+ const dataConverter = encryptionEnabled ? await getDataConverter(encryptionKeyId, this.envService, encryptionKeyRefreshInterval) : void 0;
45
+ const interceptors = EnvService.getVar("TRACING_ENABLED", "boolean", false) ? { workflow: [new OpenTelemetryWorkflowClientInterceptor()] } : void 0;
46
+ this.nativeClient = new Client({
47
+ ...clientConfig,
48
+ connection,
49
+ dataConverter,
50
+ interceptors
51
+ });
52
+ }
53
+ async syncSchedules(schedules) {
54
+ const applicationSchedules = Object.entries(schedules).map(([, schedule]) => typeof schedule === "function" ? schedule(this.config) : schedule);
55
+ const temporalSchedules = [];
56
+ for await (const schedule of this.schedule.list()) if (schedule.memo?.TaskQueue === this.config.taskQueue) temporalSchedules.push(schedule);
57
+ const schedulesToCreate = applicationSchedules.filter((scheduleOptions) => !temporalSchedules.some((schedule) => schedule.scheduleId === scheduleOptions.scheduleId));
58
+ for (const scheduleOptions of schedulesToCreate) {
59
+ scheduleOptions.memo = {
60
+ ...scheduleOptions.memo,
61
+ TaskQueue: scheduleOptions.action.taskQueue
62
+ };
63
+ if (!scheduleOptions.spec.timezone) scheduleOptions.spec.timezone = this.defaultTimezone;
64
+ await this.schedule.create(scheduleOptions);
65
+ }
66
+ if (schedulesToCreate.length > 0) this.logger.info(`Schedules created (${schedulesToCreate.length}): ${schedulesToCreate.map((schedule) => schedule.scheduleId).join(", ")}`);
67
+ const schedulesToDelete = temporalSchedules.filter((schedule) => !applicationSchedules.some((scheduleOptions) => scheduleOptions.scheduleId === schedule.scheduleId));
68
+ for (const schedule of schedulesToDelete) await this.schedule.getHandle(schedule.scheduleId).delete();
69
+ if (schedulesToDelete.length > 0) this.logger.info(`Schedules deleted (${schedulesToDelete.length}): ${schedulesToDelete.map((schedule) => schedule.scheduleId).join(", ")}`);
70
+ }
71
+ async updateSchedule(scheduleId, updateData) {
72
+ try {
73
+ const scheduleHandle = this.schedule.getHandle(scheduleId);
74
+ this.logger.info("Schedule update details:", {
75
+ scheduleId,
76
+ updateData
77
+ });
78
+ await scheduleHandle.update((previous) => {
79
+ return merge(previous, updateData);
80
+ });
81
+ this.logger.info("Successfully updated temporal schedule", { scheduleId });
82
+ } catch (err) {
83
+ this.logger.error("Failed to update temporal schedule", { err });
84
+ throw err;
85
+ }
86
+ }
87
+ };
88
+ //#endregion
89
+ export { TemporalClient };
@@ -0,0 +1,101 @@
1
+ import { ScheduleCalendarEvent, ScheduleRecentAction, SchedulesExporterConfig, SchedulesExporterDeps } from "../interfaces/services/schedulesExporter.js";
2
+ import { OnDestroy, OnInit } from "@diia-inhouse/types";
3
+
4
+ //#region src/services/schedulesExporter.d.ts
5
+ /**
6
+ * Periodically polls the Temporal Schedule and Visibility APIs, exposing per-schedule and
7
+ * per-workflow-type business metrics that the SDK does not provide out of the box:
8
+ *
9
+ * - `diia_schedule_paused` (0/1)
10
+ * - `diia_schedule_last_action_age_seconds`
11
+ * - `diia_schedule_last_action_succeeded` (0/1)
12
+ * - `diia_schedule_next_action_at_seconds{slot}` — Unix seconds of upcoming fire
13
+ * - `diia_schedule_next_action_eta_seconds{slot}` — seconds from now until upcoming fire
14
+
15
+ * - `diia_schedule_cadence_seconds` — approximate gap between fires (slot1 − slot0, falls back to spec)
16
+ * - `diia_schedule_fires_total{result="ok"|"failed"}` — counter of observed schedule fires; pair
17
+ * with cadence to compute expected/day and detect missed runs
18
+ * - `diia_workflows_running` — count of executions in `Running` state for this task queue
19
+ * - `diia_workflows_oldest_running_age_seconds` — age of the oldest running workflow
20
+ *
21
+ * The `service` label is supplied by the `diia-metrics` default labels at scrape time, so it
22
+ * is intentionally absent from the metric labelNames.
23
+ *
24
+ * Schedules with `action.taskQueue` other than `deps.taskQueue` are ignored, so a service
25
+ * only emits metrics for schedules it actually owns. This avoids fan-out when many services
26
+ * share a Temporal namespace.
27
+ *
28
+ * The exporter does NOT run its own HTTP server. Metrics flow through the existing
29
+ * `diia-metrics` `/metrics` endpoint. If a service needs to expose the calendar event list
30
+ * or recent action feed as JSON (e.g. for a Grafana Infinity datasource), it should call
31
+ * {@link SchedulesExporter.getCalendarEvents} and {@link SchedulesExporter.getRecentActions}
32
+ * from a route on its existing HTTP framework.
33
+ */
34
+ declare class SchedulesExporter implements OnInit, OnDestroy {
35
+ private readonly deps;
36
+ private readonly pollIntervalMs;
37
+ private readonly visibilityPollIntervalMs;
38
+ private readonly pollVisibility;
39
+ private readonly nextActionSlots;
40
+ private readonly historySize;
41
+ private readonly logger;
42
+ private readonly calendarEvents;
43
+ private readonly recentActionsLog;
44
+ private readonly paused;
45
+ private readonly lastActionAge;
46
+ private readonly lastActionSucceeded;
47
+ private readonly nextActionAt;
48
+ private readonly nextActionEta;
49
+ private readonly cadence;
50
+ private readonly running;
51
+ private readonly oldestRunningAge;
52
+ private readonly firesTotal;
53
+ private readonly workflowDuration;
54
+ private readonly seenCompletedRunIds;
55
+ private readonly seenCompletedRunIdSet;
56
+ private readonly seenActionKeys;
57
+ private readonly seenActionKeySet;
58
+ private static readonly ACTIONS_SEEN_CAPACITY;
59
+ private readonly lastSeenScheduleLabels;
60
+ private readonly pollCompletions;
61
+ private readonly completionsPollIntervalMs;
62
+ private readonly completionsLookbackMs;
63
+ private readonly completionsSeenCapacity;
64
+ private completionsLastPollMs;
65
+ private scheduleTimer;
66
+ private visibilityTimer;
67
+ private completionsTimer;
68
+ private schedulesPolling;
69
+ private runningPolling;
70
+ private completionsPolling;
71
+ private activeSchedulesPoll;
72
+ private activeRunningPoll;
73
+ private activeCompletionsPoll;
74
+ private stopped;
75
+ constructor(deps: SchedulesExporterDeps, config?: SchedulesExporterConfig);
76
+ onInit(): Promise<void>;
77
+ onDestroy(): Promise<void>;
78
+ private armSchedulesTimer;
79
+ private armVisibilityTimer;
80
+ private armCompletionsTimer;
81
+ private runSchedulesPoll;
82
+ private runRunningPoll;
83
+ private runCompletionsPoll;
84
+ /**
85
+ * Snapshot of the next-N upcoming fires across all tracked schedules.
86
+ * Each schedule contributes up to `nextActionSlots` events, ordered by `slot`.
87
+ * Mount on a service HTTP route to feed the Grafana Business Calendar panel via the
88
+ * Infinity datasource — the data shape is already calendar-event-shaped.
89
+ */
90
+ getCalendarEvents(): readonly ScheduleCalendarEvent[];
91
+ /**
92
+ * Snapshot of the most recent schedule actions across all tracked schedules,
93
+ * ordered newest first. Capped at `recentActionsHistorySize` entries.
94
+ */
95
+ getRecentActions(limit?: number): readonly ScheduleRecentAction[];
96
+ private pollSchedules;
97
+ private pollRunning;
98
+ private pollCompleted;
99
+ }
100
+ //#endregion
101
+ export { SchedulesExporter };