@hivekit/integration-sdk-node 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hivekit
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,227 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # Hivekit Integration SDK for Node.js
2
+
3
+ Report job executions, progress and logs to Hivekit's Integration Registry.
4
+ The SDK requires Node.js 22 or newer and has no external dependencies.
5
+
6
+ ## Install
7
+
8
+ ```sh
9
+ npm install @hivekit/integration-sdk-node
10
+ ```
11
+
12
+ Use the SDK from an ES module or CommonJS:
13
+
14
+ ```js
15
+ import { IntegrationClient } from '@hivekit/integration-sdk-node';
16
+ // Or: const { IntegrationClient } = require('@hivekit/integration-sdk-node');
17
+ ```
18
+
19
+ ## Use a previously registered job
20
+
21
+ Registration and execution can happen in separate processes. A runtime can look
22
+ up a job by its stable key without registering or changing its manifest.
23
+
24
+ ```js
25
+ const client = new IntegrationClient({
26
+ url: 'http://localhost:8090/v2/',
27
+ token: process.env.HIVEKIT_TOKEN,
28
+ });
29
+
30
+ try {
31
+ const job = await client.getJob('fleet-import');
32
+ const execution = await job.startExecution([
33
+ { key: 'fetch-data', name: 'Fetch fleet data', weight: 0.4 },
34
+ { key: 'publish', name: 'Publish updates', weight: 0.6 },
35
+ ]);
36
+
37
+ const fetchStep = execution.startStep('fetch-data');
38
+ const records = await fetchFleetData(execution.config);
39
+ fetchStep.progress(0.5);
40
+ fetchStep.info('Fetched fleet data', { count: records.length });
41
+ await fetchStep.complete();
42
+
43
+ const publishStep = execution.startStep('publish');
44
+ await publishUpdates(records);
45
+ await publishStep.complete();
46
+
47
+ await execution.complete();
48
+ } finally {
49
+ await client.close();
50
+ }
51
+ ```
52
+
53
+ `fetchFleetData` and `publishUpdates` above are your own integration functions.
54
+ For Lambda handlers, construct the client inside the handler and await `close()`
55
+ in `finally` before returning. The SDK keeps reports in memory and writes no files.
56
+
57
+ ## Jobs
58
+
59
+ ```js
60
+ const job = await client.registerJob('fleet-import', {
61
+ name: 'Fleet Import',
62
+ kind: 'scheduled', // scheduled, continuous, manual
63
+ expectedIntervalSeconds: 900,
64
+ executionTimeoutSeconds: 300,
65
+ configuration: {
66
+ endpoint: { type: 'string', required: true },
67
+ apiKey: { type: 'string', required: true, secret: true },
68
+ enabled: { type: 'boolean', default: true },
69
+ },
70
+ });
71
+
72
+ const existing = await client.getJob('fleet-import');
73
+ const jobs = await client.listJobs({ limit: 100, afterKey: 'fleet-import' });
74
+ ```
75
+
76
+ `registerJob(key, manifest)` creates or updates a manifest and supplies its `key`.
77
+ Manifest fields follow the server API, including the original configuration field
78
+ map or the supported JSON Schema object. Configuration values are managed through
79
+ the server API separately. Step definitions belong to `startExecution`, never the
80
+ manifest.
81
+
82
+ Jobs expose `id`, `key`, `manifest`, `manifestRevision`, `configRevision`, and
83
+ `monitoringEnabled`. `getJob` always queries the server and rejects with status
84
+ 404 when absent. `listJobs` returns a page of job handles; filters are `key`,
85
+ `afterKey`, and `limit` (1–1000, default 100).
86
+
87
+ ### Deregister a job
88
+
89
+ On a server that exposes `DELETE service/integration/job/{jobId}`, a token with
90
+ `RD` permission for the job can look it up and deregister it:
91
+
92
+ ```js
93
+ await client.deregisterJob('fleet-import');
94
+ ```
95
+
96
+ Deregistration permanently deletes the job, its configuration, and its
97
+ executions, steps and logs. The server retains audit entries.
98
+
99
+ ## Executions and steps
100
+
101
+ ```js
102
+ const execution = await job.startExecution([
103
+ { key: 'fetch-data', weight: 0.7 },
104
+ { key: 'publish', weight: 0.3 },
105
+ ], { metadata: { source: 'fleet-api' } });
106
+
107
+ const step = execution.startStep('fetch-data'); // Synchronous handle
108
+ step.progress(0.5); // Synchronously queued
109
+ step.debug('Starting request');
110
+ step.info('Received records', { count: 42 });
111
+ step.warn('Using cached data');
112
+ step.error('A recoverable error', { code: 'RETRY' });
113
+
114
+ await step.complete();
115
+ // Or: await step.fail('Upstream unavailable', { status: 503 });
116
+ // Or: await step.skip('Nothing to process');
117
+
118
+ await execution.startStep('publish').skip('No updates required');
119
+ await execution.complete();
120
+ // On failure: await execution.fail(errorOrReason, optionalDetails);
121
+ ```
122
+
123
+ - `startExecution(steps = [], { metadata } = {})` declares up to 1000 unique steps.
124
+ Each definition has a `key`, optional `name` (defaults to the key), and optional
125
+ `weight` (defaults to 1). Positive weights up to 1 are relative; they needn't sum
126
+ to 1. The server stores weights with six decimal places.
127
+ - `execution.config` is its resolved, frozen configuration snapshot. Secret values
128
+ are available here. Later customer edits affect subsequent executions.
129
+ - Each invocation starts a new execution. Network retries reuse an internally
130
+ generated request identity. There is no public request-key option or automatic
131
+ rerun of integration code.
132
+ - Progress is a fraction from 0 to 1. Lower, delayed values are ignored. The SDK
133
+ converts progress to the server's 0–100 representation.
134
+ - `startStep(key)` requires a declared key and queues its running state. Repeated
135
+ starts of the same running step return the same handle.
136
+ - Completing or skipping a step sets progress to 1. Failing preserves the last
137
+ progress. A failed step leaves the execution open for other steps or cleanup.
138
+ - A step exposes `key`, `name`, `weight`, `status`, and `progressValue`.
139
+ - `execution.complete()` requires all steps to be complete or skipped; it works
140
+ with an empty step list too. `execution.fail(reason, details)` can end a run with
141
+ unfinished steps. Both flush pending reports before reporting the outcome.
142
+ - `step.fail` and `execution.fail` also emit an error log. Reasons may be strings
143
+ or `Error` objects; details must be JSON serializable (`Error` details include
144
+ name, message, and stack).
145
+ - `execution.debug/info/warn/error` create execution-wide logs. The same methods
146
+ on steps automatically associate logs with the step.
147
+
148
+ Automatic heartbeats start with each execution. The SDK selects an interval from
149
+ the manifest's `heartbeatTimeoutSeconds`, capped at ten seconds. Heartbeats stop
150
+ on execution completion or client close. Background timers are unreferenced so
151
+ they do not keep a process alive by themselves.
152
+
153
+ ## Logging, batching, and shutdown
154
+
155
+ Every valid log call immediately calls Node's console: `debug`/`info` write to
156
+ stdout, `warn`/`error` to stderr, including the job, step, message and supplied
157
+ details. The same log is timestamped, snapshotted, and queued for HTTP delivery.
158
+ There are no severity filters and no disk spool or process-wide exit handlers.
159
+ Configuration and tokens are never automatically logged.
160
+
161
+ Pending reports flush every second, with log batches capped at 100 entries and
162
+ 1 MiB. Step updates are ordered with logs; consecutive unsent running-progress
163
+ updates are coalesced. Later caller mutations cannot change queued log details.
164
+
165
+ Use `await execution.flush()` or `await client.flush()` for an explicit delivery
166
+ barrier. Await `step.complete()`/`fail()`/`skip()`, `execution.complete()`/`fail()`,
167
+ and `client.close()` to observe reporting errors. Background failures go to
168
+ `onError`, or stderr by default. Rejected batches stay in memory for a later flush;
169
+ an unsuccessful `close()` can be retried. A recovered log batch may be delivered
170
+ twice after an ambiguous connection failure, since the server cannot deduplicate
171
+ log batches.
172
+
173
+ `close()` waits for in-flight job operations, stops timers and flushes reports. It
174
+ does not mark running executions complete or failed. A closed client cannot be
175
+ reused; create another for the next Lambda invocation.
176
+
177
+ The queue is limited to 10,000 reports and 8 MiB to bound memory use. At capacity,
178
+ new reports throw instead of being silently dropped; log calls still make their
179
+ console copy first. Await `flush()` to release capacity. Individual messages must
180
+ be non-empty strings up to 16,384 UTF-8 bytes, and log entries must fit within a
181
+ 1 MiB request. JSON numbers must be finite; unsafe JavaScript integers are rejected.
182
+
183
+ Console output provides a separate copy for the host's log capture. Fatal process
184
+ termination can lose pending HTTP batches; stdout/stderr capture follows the host
185
+ platform's behavior. Awaiting `close()` is required for ordinary invocation exit.
186
+
187
+ ## Connection options and errors
188
+
189
+ ```js
190
+ const client = new IntegrationClient({
191
+ url: 'https://example.com/custom/v2/', // REST prefix, with or without trailing slash
192
+ token: async () => obtainCurrentToken(),
193
+ flushIntervalMs: 1000, // Optional
194
+ requestTimeoutMs: 10000, // Optional, per HTTP attempt
195
+ onError(error) {
196
+ console.error('Integration reporting failed', error);
197
+ },
198
+ });
199
+ ```
200
+
201
+ Tokens may be strings or asynchronous providers. Requests always use bearer
202
+ headers and JSON content type, including GET. HTTP API errors reject with
203
+ `IntegrationApiError` (`status`, `message`); connection failures and timeouts use
204
+ `IntegrationTransportError` (`message`, `cause`).
205
+
206
+ Reads, execution starts, step reports, heartbeats and completion use bounded
207
+ transport retries. Manifest registration and deletion are not automatically
208
+ retried. Server authorization is unchanged: `C` registers, `R` looks up/lists,
209
+ `P` reports executions, and `D` deletes. An execution-only runtime using
210
+ `getJob(key)` typically needs `RP`; an operator looking up and deleting needs `RD`.
211
+
212
+ ## Tests
213
+
214
+ ```sh
215
+ npm test
216
+ ```
217
+
218
+ Tests use Node's built-in test runner and localhost HTTP servers; no installation
219
+ or external dependencies are required. They cover background batching, console
220
+ copies before a forced process crash, retries, concurrent flushes, state
221
+ transitions, queue limits, heartbeat shutdown, and CommonJS/ES module imports.
222
+
223
+ An additional test uses a running Hivekit server when both
224
+ `HIVEKIT_INTEGRATION_TEST_URL` and `HIVEKIT_INTEGRATION_TEST_TOKEN` are set. It
225
+ creates and deletes only its randomly named job. The test server needs PostgreSQL,
226
+ integration encryption keys, the deletion endpoint, and credentials with
227
+ `CRUPD` permissions (or deployment administrator access).
package/index.js ADDED
@@ -0,0 +1,6 @@
1
+ 'use strict';
2
+
3
+ const { IntegrationClient } = require('./lib/client');
4
+ const { IntegrationApiError, IntegrationTransportError } = require('./lib/errors');
5
+
6
+ module.exports = { IntegrationClient, IntegrationApiError, IntegrationTransportError };
package/index.mjs ADDED
@@ -0,0 +1,3 @@
1
+ import sdk from './index.js';
2
+
3
+ export const { IntegrationClient, IntegrationApiError, IntegrationTransportError } = sdk;
package/lib/client.js ADDED
@@ -0,0 +1,219 @@
1
+ 'use strict';
2
+
3
+ const { randomUUID } = require('node:crypto');
4
+ const { IntegrationApiError, IntegrationTransportError } = require('./errors');
5
+ const { nonempty, object, snapshot, stepDefinitions } = require('./values');
6
+ const { Execution } = require('./execution');
7
+
8
+ function tokenValue(value) {
9
+ nonempty(value, 'token');
10
+ if (/[^\x21-\x7e]/.test(value)) throw new TypeError('token must be a raw ASCII bearer token without whitespace');
11
+ return value;
12
+ }
13
+
14
+ class IntegrationClient {
15
+ #baseUrl;
16
+ #token;
17
+ #timeout;
18
+ #onError;
19
+ #jobs = new Map();
20
+ #executions = new Set();
21
+ #operations = new Set();
22
+ #closing;
23
+ #closed = false;
24
+
25
+ constructor({ url, token, flushIntervalMs = 1000, requestTimeoutMs = 10000, onError } = {}) {
26
+ const base = new URL(nonempty(url, 'url'));
27
+ if (!['http:', 'https:'].includes(base.protocol) || base.username || base.password || base.search || base.hash) {
28
+ throw new TypeError('url must be an HTTP(S) REST base URL without credentials, query or fragment');
29
+ }
30
+ if (typeof token !== 'function') tokenValue(token);
31
+ for (const [name, value] of Object.entries({ flushIntervalMs, requestTimeoutMs })) {
32
+ if (!Number.isSafeInteger(value) || value < 1 || value > 2147483647) throw new RangeError(`${name} must be a positive timer duration in milliseconds`);
33
+ }
34
+ if (onError !== undefined && typeof onError !== 'function') throw new TypeError('onError must be a function');
35
+ this.#baseUrl = `${base.href.replace(/\/+$/, '')}/service/integration/`;
36
+ this.#token = token;
37
+ this.#timeout = requestTimeoutMs;
38
+ this.#onError = onError;
39
+ this.flushIntervalMs = flushIntervalMs;
40
+ }
41
+
42
+ registerJob(key, manifest) {
43
+ return this._operation(async () => {
44
+ nonempty(key, 'key');
45
+ object(manifest, 'manifest');
46
+ if (manifest.key !== undefined && manifest.key !== key) throw new TypeError('manifest.key must match the job key');
47
+ if (Object.hasOwn(manifest, 'steps')) throw new TypeError('Pass step definitions to job.startExecution(), not the manifest');
48
+ const record = await this._request('POST', 'job/', { manifest: snapshot({ ...manifest, key }) });
49
+ const job = new Job(this, record);
50
+ this.#jobs.set(key, job);
51
+ return job;
52
+ });
53
+ }
54
+
55
+ getJob(key) {
56
+ return this._operation(() => this.#findJob(nonempty(key, 'key')));
57
+ }
58
+
59
+ async #findJob(key) {
60
+ const records = await this._request('GET', 'job/', undefined, { key, limit: 1 }, true);
61
+ const record = records.find(record => record.key === key);
62
+ if (!record) throw new IntegrationApiError(`Integration job not found: ${key}`, 404);
63
+ const job = new Job(this, record);
64
+ this.#jobs.set(key, job);
65
+ return job;
66
+ }
67
+
68
+ listJobs(filter = {}) {
69
+ return this._operation(async () => {
70
+ object(filter, 'filter');
71
+ for (const key of Object.keys(filter)) {
72
+ if (!['key', 'afterKey', 'limit'].includes(key)) throw new TypeError(`Unknown job filter: ${key}`);
73
+ }
74
+ if (filter.limit !== undefined && (!Number.isInteger(filter.limit) || filter.limit < 1 || filter.limit > 1000)) throw new RangeError('limit must be between 1 and 1000');
75
+ for (const key of ['key', 'afterKey']) if (filter[key] !== undefined) nonempty(filter[key], key);
76
+ const records = await this._request('GET', 'job/', undefined, filter, true);
77
+ return records.map(record => {
78
+ const job = new Job(this, record);
79
+ this.#jobs.set(job.key, job);
80
+ return job;
81
+ });
82
+ });
83
+ }
84
+
85
+ deregisterJob(key) {
86
+ return this._operation(async () => {
87
+ nonempty(key, 'key');
88
+ const job = this.#jobs.get(key) || await this.#findJob(key);
89
+ await this._request('DELETE', `job/${encodeURIComponent(job.id)}`);
90
+ this.#jobs.delete(key);
91
+ });
92
+ }
93
+
94
+ async flush() {
95
+ const results = await Promise.allSettled([...this.#executions].map(execution => execution.flush()));
96
+ const errors = results.filter(result => result.status === 'rejected').map(result => result.reason);
97
+ if (errors.length === 1) throw errors[0];
98
+ if (errors.length) throw new AggregateError(errors, 'Failed to flush integration reports');
99
+ }
100
+
101
+ close() {
102
+ if (this.#closed) return Promise.resolve();
103
+ if (this.#closing) return this.#closing;
104
+ this.#closing = (async () => {
105
+ // Include executions whose start requests were already in flight.
106
+ await Promise.allSettled([...this.#operations]);
107
+ for (const execution of this.#executions) execution._stopTimers();
108
+ await this.flush();
109
+ this.#closed = true;
110
+ this.#executions.clear();
111
+ })().finally(() => { this.#closing = undefined; });
112
+ return this.#closing;
113
+ }
114
+
115
+ _assertOpen() {
116
+ if (this.#closed || this.#closing) throw new Error('Integration client is closing or closed');
117
+ }
118
+
119
+ _operation(fn) {
120
+ let promise;
121
+ try {
122
+ this._assertOpen();
123
+ promise = Promise.resolve(fn());
124
+ } catch (error) {
125
+ return Promise.reject(error);
126
+ }
127
+ this.#operations.add(promise);
128
+ promise.then(() => this.#operations.delete(promise), () => this.#operations.delete(promise));
129
+ return promise;
130
+ }
131
+
132
+ _attach(execution) { this.#executions.add(execution); }
133
+ _detach(execution) { this.#executions.delete(execution); }
134
+
135
+ _reportError(error) {
136
+ if (this.#onError) {
137
+ try {
138
+ Promise.resolve(this.#onError(error)).catch(handlerError => {
139
+ console.error('[Hivekit SDK] onError handler failed:', handlerError);
140
+ });
141
+ return;
142
+ } catch (handlerError) {
143
+ console.error('[Hivekit SDK] onError handler failed:', handlerError);
144
+ }
145
+ }
146
+ console.error('[Hivekit SDK] Background reporting failed:', error);
147
+ }
148
+
149
+ async _request(method, path, body, query, retry = false) {
150
+ const url = new URL(path, this.#baseUrl);
151
+ for (const [key, value] of Object.entries(query || {})) {
152
+ if (value !== undefined) url.searchParams.set(key, String(value));
153
+ }
154
+ const serialized = body === undefined ? undefined : JSON.stringify(body);
155
+ for (let attempt = 0; ; attempt++) {
156
+ const token = tokenValue(typeof this.#token === 'function' ? await this.#token() : this.#token);
157
+ const controller = new AbortController();
158
+ const timeout = setTimeout(() => controller.abort(), this.#timeout);
159
+ timeout.unref();
160
+ let error;
161
+ try {
162
+ const response = await fetch(url, {
163
+ method, body: serialized, signal: controller.signal, redirect: 'error',
164
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', Accept: 'application/json' }
165
+ });
166
+ const raw = await response.text();
167
+ let payload;
168
+ try { payload = JSON.parse(raw); } catch {
169
+ throw new IntegrationApiError('Integration server returned an invalid JSON response', response.status);
170
+ }
171
+ if (!payload || typeof payload !== 'object') throw new IntegrationApiError('Integration server returned an unexpected response', response.status);
172
+ if (!response.ok || payload.result === 'error') {
173
+ throw new IntegrationApiError(typeof payload.message === 'string' ? payload.message : 'Integration request rejected', response.status);
174
+ }
175
+ if (payload.result === 'success') return payload.data;
176
+ if (payload.res === 'suc') return;
177
+ throw new IntegrationApiError('Integration server returned an unexpected response', response.status);
178
+ } catch (cause) {
179
+ error = cause instanceof IntegrationApiError ? cause : new IntegrationTransportError(
180
+ controller.signal.aborted ? 'Integration request timed out' : 'Integration request failed', cause);
181
+ } finally {
182
+ clearTimeout(timeout);
183
+ }
184
+ if (!retry || attempt >= 2 || (error instanceof IntegrationApiError && ![408, 429, 502, 503, 504].includes(error.status))) throw error;
185
+ await new Promise(resolve => setTimeout(resolve, 100 * (2 ** attempt)));
186
+ }
187
+ }
188
+ }
189
+
190
+ class Job {
191
+ #client;
192
+
193
+ constructor(client, record) {
194
+ this.#client = client;
195
+ this.id = record.id;
196
+ this.key = record.key;
197
+ this.manifest = Object.freeze(snapshot(record.manifest));
198
+ this.manifestRevision = record.manifestRevision;
199
+ this.configRevision = record.configRevision;
200
+ this.monitoringEnabled = record.monitoringEnabled;
201
+ }
202
+
203
+ startExecution(steps = [], options = {}) {
204
+ return this.#client._operation(async () => {
205
+ const definitions = stepDefinitions(steps);
206
+ object(options, 'execution options');
207
+ for (const key of Object.keys(options)) if (key !== 'metadata') throw new TypeError(`Unknown execution option: ${key}`);
208
+ // Generated once per invocation and reused only for transport retries.
209
+ const body = { idempotencyKey: randomUUID(), steps: definitions };
210
+ if (options.metadata !== undefined) body.metadata = snapshot(options.metadata);
211
+ const result = await this.#client._request('POST', `job/${encodeURIComponent(this.id)}/execution/`, body, undefined, true);
212
+ const execution = new Execution(this.#client, this, result, definitions);
213
+ this.#client._attach(execution);
214
+ return execution;
215
+ });
216
+ }
217
+ }
218
+
219
+ module.exports = { IntegrationClient };
package/lib/errors.js ADDED
@@ -0,0 +1,18 @@
1
+ 'use strict';
2
+
3
+ class IntegrationApiError extends Error {
4
+ constructor(message, status) {
5
+ super(message);
6
+ this.name = 'IntegrationApiError';
7
+ this.status = status;
8
+ }
9
+ }
10
+
11
+ class IntegrationTransportError extends Error {
12
+ constructor(message, cause) {
13
+ super(message, { cause });
14
+ this.name = 'IntegrationTransportError';
15
+ }
16
+ }
17
+
18
+ module.exports = { IntegrationApiError, IntegrationTransportError };
@@ -0,0 +1,293 @@
1
+ 'use strict';
2
+
3
+ const { nonempty, reasonText, snapshot } = require('./values');
4
+
5
+ const MAX_QUEUE_ENTRIES = 10000;
6
+ const MAX_QUEUE_BYTES = 8 * 1024 * 1024;
7
+ const MAX_BATCH_BYTES = 1024 * 1024;
8
+ const LOG_BATCH_SIZE = 100;
9
+
10
+ class Execution {
11
+ #client;
12
+ #job;
13
+ #status;
14
+ #steps = new Map();
15
+ #queue = [];
16
+ #queueBytes = 0;
17
+ #sendingCount = 0;
18
+ #flushing;
19
+ #finishing;
20
+ #finishStatus;
21
+ #flushTimer;
22
+ #heartbeatTimer;
23
+ #heartbeat;
24
+ #lastError;
25
+
26
+ constructor(client, job, result, definitions) {
27
+ this.#client = client;
28
+ this.#job = job;
29
+ this.id = result.execution.id;
30
+ this.#status = result.execution.status;
31
+ this.config = Object.freeze(snapshot(result.configuration));
32
+ this.manifestRevision = result.execution.manifestRevision;
33
+ this.configRevision = result.execution.configRevision;
34
+ for (const definition of definitions) this.#steps.set(definition.key, new Step(this, definition));
35
+ this.#startFlushTimer();
36
+ this.#startHeartbeats();
37
+ }
38
+
39
+ get status() { return this.#status; }
40
+
41
+ startStep(key) {
42
+ this._assertRunning();
43
+ const step = this.#steps.get(nonempty(key, 'step key'));
44
+ if (!step) throw new Error(`Step was not declared in startExecution(): ${key}`);
45
+ return step._start();
46
+ }
47
+
48
+ debug(message, details) { this._log('debug', message, details); }
49
+ info(message, details) { this._log('info', message, details); }
50
+ warn(message, details) { this._log('warn', message, details); }
51
+ error(message, details) { this._log('error', message, details); }
52
+
53
+ _assertRunning() {
54
+ this.#client._assertOpen();
55
+ if (this.#status !== 'running' || this.#finishing) throw new Error('Execution is completing or already complete');
56
+ }
57
+
58
+ _log(level, message, details, stepKey) {
59
+ nonempty(message, 'log message');
60
+ if (Buffer.byteLength(message) > 16384) throw new RangeError('Log messages must be at most 16384 UTF-8 bytes');
61
+ const occurredAt = new Date().toISOString();
62
+ const prefix = `[${this.#job.key}]${stepKey === undefined ? '' : `[${stepKey}]`} ${message}`;
63
+ // Mirror synchronously at the call site, before any batching or network
64
+ // work. The host's stdout/stderr capture remains available after a crash.
65
+ if (details === undefined) console[level](prefix);
66
+ else console[level](prefix, details);
67
+
68
+ this.#client._assertOpen();
69
+ if (this.#finishing) throw new Error('Execution is completing');
70
+ const entry = { level, message, occurredAt };
71
+ if (stepKey !== undefined) entry.stepKey = stepKey;
72
+ if (details !== undefined) entry.details = snapshot(details);
73
+ const bytes = Buffer.byteLength(JSON.stringify(entry));
74
+ if (bytes > MAX_BATCH_BYTES - 32) throw new RangeError('A log entry must fit within a 1 MiB request');
75
+ this.#append({ type: 'log', body: entry, bytes });
76
+ if (this.#queue.length >= LOG_BATCH_SIZE) this.#flushInBackground();
77
+ }
78
+
79
+ _updateStep(key, body) {
80
+ this._assertRunning();
81
+ const bytes = Buffer.byteLength(JSON.stringify(body));
82
+ const last = this.#queue.at(-1);
83
+ // Coalesce only unsent running updates. Mutating an in-flight entry
84
+ // would lose progress when that earlier request is acknowledged.
85
+ if (last && this.#queue.length > this.#sendingCount && last.type === 'step' && last.key === key && last.body.status === 'running' && body.status === 'running') {
86
+ if (this.#queueBytes + bytes - last.bytes > MAX_QUEUE_BYTES) throw new RangeError('Integration reporting queue is full; await execution.flush() before adding more reports');
87
+ this.#queueBytes += bytes - last.bytes;
88
+ last.body = body;
89
+ last.bytes = bytes;
90
+ return;
91
+ }
92
+ this.#append({ type: 'step', key, body, bytes });
93
+ }
94
+
95
+ #append(entry) {
96
+ if (this.#queue.length >= MAX_QUEUE_ENTRIES || this.#queueBytes + entry.bytes > MAX_QUEUE_BYTES) {
97
+ throw new RangeError('Integration reporting queue is full; await execution.flush() before adding more reports');
98
+ }
99
+ this.#queue.push(entry);
100
+ this.#queueBytes += entry.bytes;
101
+ this.#client._attach(this);
102
+ this.#startFlushTimer();
103
+ }
104
+
105
+ async flush() {
106
+ // Every caller observes the same ordered drain. Failed reports remain
107
+ // queued, so a later explicit flush/close can recover a temporary outage.
108
+ while (this.#queue.length || this.#flushing) {
109
+ if (!this.#flushing) {
110
+ this.#flushing = this.#drain().finally(() => { this.#flushing = undefined; });
111
+ }
112
+ await this.#flushing;
113
+ }
114
+ if (this.#heartbeat) await this.#heartbeat;
115
+ if (this.#status !== 'running') {
116
+ this._stopTimers();
117
+ this.#client._detach(this);
118
+ }
119
+ }
120
+
121
+ async #drain() {
122
+ while (this.#queue.length) {
123
+ const first = this.#queue[0];
124
+ let count = 1;
125
+ let method = 'PUT';
126
+ let path = `execution/${encodeURIComponent(this.id)}/step/${encodeURIComponent(first.key)}`;
127
+ let body = first.body;
128
+ if (first.type === 'log') {
129
+ let bytes = first.bytes + 32;
130
+ while (count < this.#queue.length && count < LOG_BATCH_SIZE && this.#queue[count].type === 'log' && bytes + this.#queue[count].bytes + 1 <= MAX_BATCH_BYTES) {
131
+ bytes += this.#queue[count].bytes + 1;
132
+ count++;
133
+ }
134
+ method = 'POST';
135
+ path = `execution/${encodeURIComponent(this.id)}/log/`;
136
+ body = { logs: this.#queue.slice(0, count).map(entry => entry.body) };
137
+ }
138
+ this.#sendingCount = count;
139
+ try {
140
+ await this.#client._request(method, path, body, undefined, first.type === 'step');
141
+ for (const entry of this.#queue.splice(0, count)) this.#queueBytes -= entry.bytes;
142
+ this.#lastError = undefined;
143
+ } finally {
144
+ this.#sendingCount = 0;
145
+ }
146
+ }
147
+ }
148
+
149
+ #backgroundError(error) {
150
+ if (this.#lastError !== error.message) this.#client._reportError(error);
151
+ this.#lastError = error.message;
152
+ }
153
+
154
+ #flushInBackground() {
155
+ this.flush().catch(error => this.#backgroundError(error));
156
+ }
157
+
158
+ #startFlushTimer() {
159
+ if (this.#flushTimer) return;
160
+ this.#flushTimer = setInterval(() => this.#flushInBackground(), this.#client.flushIntervalMs);
161
+ this.#flushTimer.unref();
162
+ }
163
+
164
+ #startHeartbeats() {
165
+ if (this.#heartbeatTimer || this.#status !== 'running') return;
166
+ const seconds = this.#job.manifest.heartbeatTimeoutSeconds;
167
+ const interval = Number.isFinite(seconds) && seconds > 0 ? Math.max(250, Math.min(10000, Math.floor(seconds * 1000 / 3))) : 10000;
168
+ this.#heartbeatTimer = setInterval(() => {
169
+ if (this.#heartbeat) return;
170
+ this.#heartbeat = this.#client._request('POST', `execution/${encodeURIComponent(this.id)}/heartbeat`, {}, undefined, true)
171
+ .catch(error => this.#backgroundError(error))
172
+ .finally(() => { this.#heartbeat = undefined; });
173
+ }, interval);
174
+ this.#heartbeatTimer.unref();
175
+ }
176
+
177
+ _stopTimers() {
178
+ clearInterval(this.#flushTimer);
179
+ clearInterval(this.#heartbeatTimer);
180
+ this.#flushTimer = this.#heartbeatTimer = undefined;
181
+ }
182
+
183
+ complete() {
184
+ return this.#client._operation(() => this.#finish('succeeded'));
185
+ }
186
+
187
+ fail(reason, details) {
188
+ return this.#client._operation(() => this.#finish('failed', reasonText(reason), details === undefined && reason instanceof Error ? reason : details));
189
+ }
190
+
191
+ #finish(status, reason, details) {
192
+ if (this.#status !== 'running') {
193
+ if (this.#status !== status) return Promise.reject(new Error('Execution already completed with a different status'));
194
+ return this.flush();
195
+ }
196
+ if (this.#finishing) {
197
+ if (this.#finishStatus !== status) return Promise.reject(new Error('Execution is completing with a different status'));
198
+ return this.#finishing;
199
+ }
200
+ if (status === 'succeeded' && [...this.#steps.values()].some(step => !['succeeded', 'skipped'].includes(step.status))) {
201
+ return Promise.reject(new Error('Every step must be complete or skipped before completing the execution'));
202
+ }
203
+ if (status === 'failed') this.error(reason, details);
204
+ this.#finishStatus = status;
205
+ clearInterval(this.#heartbeatTimer);
206
+ this.#heartbeatTimer = undefined;
207
+ this.#finishing = (async () => {
208
+ await this.flush();
209
+ const body = { status };
210
+ if (reason !== undefined) body.errorSummary = reason;
211
+ await this.#client._request('POST', `execution/${encodeURIComponent(this.id)}/complete`, body, undefined, true);
212
+ this.#status = status;
213
+ this._stopTimers();
214
+ this.#client._detach(this);
215
+ })().finally(() => {
216
+ this.#finishing = undefined;
217
+ if (this.#status === 'running') this.#startHeartbeats();
218
+ });
219
+ return this.#finishing;
220
+ }
221
+ }
222
+
223
+ class Step {
224
+ #execution;
225
+ #status = 'pending';
226
+ #progress = 0;
227
+
228
+ constructor(execution, { key, name, weight }) {
229
+ this.#execution = execution;
230
+ this.key = key;
231
+ this.name = name;
232
+ this.weight = weight;
233
+ }
234
+
235
+ get status() { return this.#status; }
236
+ get progressValue() { return this.#progress; }
237
+
238
+ _start() {
239
+ if (this.#status === 'running') return this;
240
+ if (this.#status !== 'pending') throw new Error(`Step already completed: ${this.key}`);
241
+ this.#execution._updateStep(this.key, { status: 'running', progress: 0 });
242
+ this.#status = 'running';
243
+ return this;
244
+ }
245
+
246
+ progress(value) {
247
+ this.#execution._assertRunning();
248
+ if (this.#status !== 'running') throw new Error('Step is not running');
249
+ if (!Number.isFinite(value) || value < 0 || value > 1) throw new RangeError('Progress must be a fraction between 0 and 1');
250
+ const progress = Math.round(value * 100 * 1e6) / 1e6;
251
+ if (progress <= this.#progress * 100) return;
252
+ this.#execution._updateStep(this.key, { status: 'running', progress });
253
+ this.#progress = progress / 100;
254
+ }
255
+
256
+ debug(message, details) { this.#execution._log('debug', message, details, this.key); }
257
+ info(message, details) { this.#execution._log('info', message, details, this.key); }
258
+ warn(message, details) { this.#execution._log('warn', message, details, this.key); }
259
+ error(message, details) { this.#execution._log('error', message, details, this.key); }
260
+
261
+ async complete() {
262
+ this.#finish('succeeded');
263
+ await this.#execution.flush();
264
+ }
265
+
266
+ async fail(reason, details) {
267
+ this.#execution._assertRunning();
268
+ const message = reasonText(reason);
269
+ if (this.#status !== 'failed') {
270
+ this.#finish('failed');
271
+ this.error(message, details === undefined && reason instanceof Error ? reason : details);
272
+ }
273
+ await this.#execution.flush();
274
+ }
275
+
276
+ async skip(reason) {
277
+ this.#finish('skipped');
278
+ if (reason !== undefined) this.info(nonempty(reason, 'reason'));
279
+ await this.#execution.flush();
280
+ }
281
+
282
+ #finish(status) {
283
+ this.#execution._assertRunning();
284
+ if (this.#status === status) return;
285
+ if (this.#status !== 'running') throw new Error('Step already completed with a different status');
286
+ const progress = status === 'failed' ? this.#progress : 1;
287
+ this.#execution._updateStep(this.key, { status, progress: progress * 100 });
288
+ this.#progress = progress;
289
+ this.#status = status;
290
+ }
291
+ }
292
+
293
+ module.exports = { Execution };
package/lib/values.js ADDED
@@ -0,0 +1,53 @@
1
+ 'use strict';
2
+
3
+ function nonempty(value, name) {
4
+ if (typeof value !== 'string' || !value.trim()) {
5
+ throw new TypeError(`${name} must be a non-empty string`);
6
+ }
7
+ return value;
8
+ }
9
+
10
+ function object(value, name) {
11
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
12
+ throw new TypeError(`${name} must be an object`);
13
+ }
14
+ }
15
+
16
+ // Snapshot queued data now: later caller mutations must not change reports or
17
+ // the body of a retried execution start. Also avoid silently rounding integers.
18
+ function snapshot(value) {
19
+ return JSON.parse(JSON.stringify(value, (key, entry) => {
20
+ if (typeof entry === 'number' && (!Number.isFinite(entry) || (Number.isInteger(entry) && !Number.isSafeInteger(entry)))) {
21
+ throw new RangeError('JSON numbers must be finite and integers must be within the JavaScript safe range');
22
+ }
23
+ if (entry instanceof Error) {
24
+ return { name: entry.name, message: entry.message, stack: entry.stack };
25
+ }
26
+ return entry;
27
+ }));
28
+ }
29
+
30
+ function reasonText(reason) {
31
+ return nonempty(reason instanceof Error ? reason.message : reason, 'reason');
32
+ }
33
+
34
+ function stepDefinitions(steps) {
35
+ if (!Array.isArray(steps) || steps.length > 1000) {
36
+ throw new TypeError('steps must be an array of at most 1000 step definitions');
37
+ }
38
+ const keys = new Set();
39
+ return steps.map(step => {
40
+ object(step, 'step');
41
+ const key = nonempty(step.key, 'step.key');
42
+ if (keys.has(key)) throw new TypeError(`Duplicate step key: ${key}`);
43
+ keys.add(key);
44
+ const name = step.name === undefined ? key : nonempty(step.name, 'step.name');
45
+ const weight = step.weight === undefined ? 1 : step.weight;
46
+ if (!Number.isFinite(weight) || weight <= 0 || weight > 1 || Number(weight.toFixed(6)) === 0) {
47
+ throw new RangeError('Step weights must be positive fractions up to 1, representable with six decimal places');
48
+ }
49
+ return { key, name, weight: Number(weight.toFixed(6)) };
50
+ });
51
+ }
52
+
53
+ module.exports = { nonempty, object, snapshot, reasonText, stepDefinitions };
package/package.json CHANGED
@@ -1,6 +1,25 @@
1
- {
2
- "name": "@hivekit/integration-sdk-node",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@hivekit/integration-sdk-node",
3
+ "version": "0.1.0",
4
+ "description": "Plain JavaScript SDK for reporting Hivekit integration jobs, executions, steps and logs",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/hivekit/integration-sdk-node.git"
8
+ },
9
+ "keywords": ["hivekit", "integration", "sdk", "job-monitoring"],
10
+ "main": "index.js",
11
+ "exports": {
12
+ ".": {
13
+ "import": "./index.mjs",
14
+ "require": "./index.js"
15
+ }
16
+ },
17
+ "files": ["index.js", "index.mjs", "lib", "README.md", "LICENSE"],
18
+ "engines": { "node": ">=22" },
19
+ "scripts": { "test": "node --test" },
20
+ "publishConfig": {
21
+ "access": "public",
22
+ "registry": "https://registry.npmjs.org/"
23
+ },
24
+ "license": "MIT"
25
+ }