@netgreener/runtime 0.1.11 → 0.1.12
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/dist/aggregator.d.ts +1 -0
- package/dist/aggregator.js +3 -0
- package/dist/cli/helpText.js +1 -0
- package/dist/cli/netgreener.js +8 -0
- package/dist/cli/runtimeCli.d.ts +2 -0
- package/dist/cli/runtimeCli.js +35 -0
- package/dist/config.js +3 -1
- package/dist/exporter.js +9 -0
- package/dist/externalApiMeter.js +6 -3
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/mcpToolMeter.js +6 -1
- package/dist/processResources.js +5 -2
- package/dist/runtime.js +22 -2
- package/dist/runtimeControls.d.ts +5 -0
- package/dist/runtimeControls.js +69 -0
- package/dist/runtimeHealth.d.ts +15 -0
- package/dist/runtimeHealth.js +46 -0
- package/dist/tenantContext.d.ts +1 -0
- package/dist/tenantContext.js +1 -1
- package/dist/uploader.js +45 -1
- package/package.json +1 -1
package/dist/aggregator.d.ts
CHANGED
package/dist/aggregator.js
CHANGED
|
@@ -23,6 +23,9 @@ export class ServiceRuntimeAggregator {
|
|
|
23
23
|
this.byTenant.clear();
|
|
24
24
|
this.windowStartedAt = Date.now();
|
|
25
25
|
}
|
|
26
|
+
excludePausedTime(milliseconds) {
|
|
27
|
+
this.windowStartedAt += Math.max(0, milliseconds);
|
|
28
|
+
}
|
|
26
29
|
windowStartedMs() {
|
|
27
30
|
return this.windowStartedAt;
|
|
28
31
|
}
|
package/dist/cli/helpText.js
CHANGED
|
@@ -10,6 +10,7 @@ Usage:
|
|
|
10
10
|
netgreener help [command]
|
|
11
11
|
|
|
12
12
|
Commands:
|
|
13
|
+
runtime status [--json] Check local runtime configuration (no network)
|
|
13
14
|
analyze <projectDir> Local resource Analyze (manifest + findings)
|
|
14
15
|
run <script> [projectDir] Execute script with process metering (+ optional upload)
|
|
15
16
|
optimize <projectDir> Local proposals; --llm for api_server optimize session
|
package/dist/cli/netgreener.js
CHANGED
|
@@ -14,6 +14,7 @@ import { runAnalyzeCli } from '../analyze/cli.js';
|
|
|
14
14
|
import { formatOptimizeHelp, runOptimizeCli } from '../optimize/cli.js';
|
|
15
15
|
import { CLI_VERSION, formatAnalyzeHelp, formatRootHelp, } from './helpText.js';
|
|
16
16
|
import { formatRunHelp, runRunCli } from './runCli.js';
|
|
17
|
+
import { formatRuntimeHelp, runRuntimeCli } from './runtimeCli.js';
|
|
17
18
|
function printHelpFor(topic) {
|
|
18
19
|
const key = (topic || '').trim().toLowerCase();
|
|
19
20
|
if (!key || key === 'help') {
|
|
@@ -28,6 +29,10 @@ function printHelpFor(topic) {
|
|
|
28
29
|
process.stdout.write(formatRunHelp());
|
|
29
30
|
return 0;
|
|
30
31
|
}
|
|
32
|
+
if (key === 'runtime') {
|
|
33
|
+
process.stdout.write(formatRuntimeHelp());
|
|
34
|
+
return 0;
|
|
35
|
+
}
|
|
31
36
|
if (key === 'optimize') {
|
|
32
37
|
process.stdout.write(formatOptimizeHelp());
|
|
33
38
|
return 0;
|
|
@@ -56,6 +61,9 @@ export function runNetgreenerCli(argv) {
|
|
|
56
61
|
if (cmd === 'run') {
|
|
57
62
|
return runRunCli(rest);
|
|
58
63
|
}
|
|
64
|
+
if (cmd === 'runtime') {
|
|
65
|
+
return runRuntimeCli(rest);
|
|
66
|
+
}
|
|
59
67
|
if (cmd === 'optimize') {
|
|
60
68
|
return runOptimizeCli(rest);
|
|
61
69
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { inspectRuntimeSetup } from '../runtimeHealth.js';
|
|
2
|
+
export function formatRuntimeHelp() {
|
|
3
|
+
return `Usage: netgreener runtime status [--json]
|
|
4
|
+
|
|
5
|
+
Check local runtime configuration without contacting the API.
|
|
6
|
+
Use NETGREENER_TOKEN and NETGREENER_PROJECT_ID; NETGREENER_SERVICE_RUNTIME=0 disables monitoring.
|
|
7
|
+
This does not verify running hooks, tenant binding, provider coverage, authentication, or uploads.
|
|
8
|
+
|
|
9
|
+
Options:
|
|
10
|
+
--json Print a credential-free JSON report
|
|
11
|
+
-h, --help Show this help
|
|
12
|
+
`;
|
|
13
|
+
}
|
|
14
|
+
export function runRuntimeCli(argv) {
|
|
15
|
+
if (!argv.length || argv.includes('--help') || argv.includes('-h')) {
|
|
16
|
+
process.stdout.write(formatRuntimeHelp());
|
|
17
|
+
return 0;
|
|
18
|
+
}
|
|
19
|
+
if (argv[0] !== 'status' || argv.slice(1).some(arg => arg !== '--json')) {
|
|
20
|
+
process.stderr.write(formatRuntimeHelp());
|
|
21
|
+
return 2;
|
|
22
|
+
}
|
|
23
|
+
const report = inspectRuntimeSetup();
|
|
24
|
+
if (argv.includes('--json')) {
|
|
25
|
+
process.stdout.write(`${JSON.stringify(report)}\n`);
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
process.stdout.write('NetGreener runtime status (local configuration only)\n');
|
|
29
|
+
for (const check of report.checks) {
|
|
30
|
+
process.stdout.write(` ${check.name}: ${check.status} — ${check.detail}\n`);
|
|
31
|
+
}
|
|
32
|
+
process.stdout.write(report.ready ? 'Local configuration is ready; live verification is still required.\n' : 'Runtime upload is not ready.\n');
|
|
33
|
+
}
|
|
34
|
+
return report.ready ? 0 : 1;
|
|
35
|
+
}
|
package/dist/config.js
CHANGED
|
@@ -39,10 +39,12 @@ function isPositiveSafeInteger(value) {
|
|
|
39
39
|
* API URL: NETGREENER_API_URL (default https://core-api.netgreener.com)
|
|
40
40
|
*/
|
|
41
41
|
export function loadRuntimeConfig(env = process.env) {
|
|
42
|
-
const enabled = envTruthy(env, 'NETGREENER_SERVICE_RUNTIME');
|
|
43
42
|
const apiUrl = (env.NETGREENER_API_URL || 'https://core-api.netgreener.com').replace(/\/+$/, '');
|
|
44
43
|
const token = (env.NETGREENER_TOKEN || '').trim();
|
|
45
44
|
const projectId = envPositiveSafeInteger(env, 'NETGREENER_PROJECT_ID', 0);
|
|
45
|
+
const enabled = (env.NETGREENER_SERVICE_RUNTIME || '').trim()
|
|
46
|
+
? envTruthy(env, 'NETGREENER_SERVICE_RUNTIME')
|
|
47
|
+
: Boolean(token && projectId > 0 && /^[0-9]+$/.test((env.NETGREENER_PROJECT_ID || '').trim()));
|
|
46
48
|
const organizationIdRaw = envPositiveSafeInteger(env, 'NETGREENER_ORG_ID', 0);
|
|
47
49
|
const organizationSlug = (env.NETGREENER_ORG_SLUG || '').trim().toLowerCase() || null;
|
|
48
50
|
const flushMinutes = envNumberInRange(env, 'NETGREENER_RUNTIME_FLUSH_MINUTES', DEFAULT_RUNTIME_FLUSH_MINUTES, MIN_RUNTIME_FLUSH_MINUTES, MAX_RUNTIME_FLUSH_MINUTES);
|
package/dist/exporter.js
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* ``NETGREENER_MP2_SHADOW_COMPARE=1`` logs canonical payload digests only
|
|
9
9
|
* (no dual-POST, no default flip). Matches Python bridge digest semantics.
|
|
10
10
|
*/
|
|
11
|
+
import { meteringAllowed, startRuntimeControls } from './runtimeControls.js';
|
|
11
12
|
import { createHash } from 'node:crypto';
|
|
12
13
|
import { sendCollectorEvent, newCollectorEventId, CollectorIpcError, } from './collectorIpc.js';
|
|
13
14
|
import { uploadRunSession, } from './uploader.js';
|
|
@@ -142,6 +143,10 @@ export class ThinRunSessionExporter {
|
|
|
142
143
|
export class CollectorRunSessionExporter {
|
|
143
144
|
mode = 'collector';
|
|
144
145
|
async exportRunSessionWindow(config, payload, _fetchImpl) {
|
|
146
|
+
startRuntimeControls(config, _fetchImpl ?? fetch);
|
|
147
|
+
if (!config.dryRun && !meteringAllowed(config)) {
|
|
148
|
+
return { ok: false, status: 423, error: 'Metering is paused by your organization administrator', mode: 'collector', durabilityGrade: 'durable_sibling_spool' };
|
|
149
|
+
}
|
|
145
150
|
const endpoint = (process.env.NETGREENER_COLLECTOR_ENDPOINT || '').trim();
|
|
146
151
|
if (!endpoint) {
|
|
147
152
|
return {
|
|
@@ -218,6 +223,10 @@ export class CollectorRunSessionExporter {
|
|
|
218
223
|
}
|
|
219
224
|
}
|
|
220
225
|
async exportObservationBatch(config, batch, options) {
|
|
226
|
+
startRuntimeControls(config, fetch);
|
|
227
|
+
if (!config.dryRun && !meteringAllowed(config)) {
|
|
228
|
+
return { ok: false, status: 423, error: 'Metering is paused by your organization administrator', mode: 'collector', durabilityGrade: 'durable_sibling_spool' };
|
|
229
|
+
}
|
|
221
230
|
const endpoint = (process.env.NETGREENER_COLLECTOR_ENDPOINT || '').trim();
|
|
222
231
|
if (!endpoint) {
|
|
223
232
|
return {
|
package/dist/externalApiMeter.js
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
* Uploads restore unwrapped ``fetch``. Axios→fetch adapter paths skip the
|
|
12
12
|
* fetch meter via ALS so the same call is not double-counted.
|
|
13
13
|
*/
|
|
14
|
+
import { meteringAllowed } from './runtimeControls.js';
|
|
14
15
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
15
16
|
import { activeMcpToolCallId, recordHttpInToolContext } from './mcpToolMeter.js';
|
|
16
17
|
import { createRequire } from 'node:module';
|
|
@@ -1048,6 +1049,8 @@ function trackStreamMeter(meter) {
|
|
|
1048
1049
|
pendingUsageParses.push(meter.whenFinished());
|
|
1049
1050
|
}
|
|
1050
1051
|
function recordMeteredCall(opts) {
|
|
1052
|
+
if (!meteringAllowed())
|
|
1053
|
+
return;
|
|
1051
1054
|
try {
|
|
1052
1055
|
globalAgg.record({
|
|
1053
1056
|
host: opts.host,
|
|
@@ -1135,7 +1138,7 @@ function installFetchWrap() {
|
|
|
1135
1138
|
const base = originalFetch;
|
|
1136
1139
|
const wrapped = async (input, init) => {
|
|
1137
1140
|
// Axios (or another outer wrap) already owns this call.
|
|
1138
|
-
if (outboundMeterOwnerAls.getStore()) {
|
|
1141
|
+
if (!meteringAllowed() || outboundMeterOwnerAls.getStore()) {
|
|
1139
1142
|
return base(input, init);
|
|
1140
1143
|
}
|
|
1141
1144
|
const url = typeof input === 'string'
|
|
@@ -1236,7 +1239,7 @@ function installAxiosWrap() {
|
|
|
1236
1239
|
return;
|
|
1237
1240
|
const originalRequest = proto.request;
|
|
1238
1241
|
const wrappedRequest = function netgreenerAxiosRequest(...args) {
|
|
1239
|
-
if (outboundMeterOwnerAls.getStore()) {
|
|
1242
|
+
if (!meteringAllowed() || outboundMeterOwnerAls.getStore()) {
|
|
1240
1243
|
return originalRequest.apply(this, args);
|
|
1241
1244
|
}
|
|
1242
1245
|
const configOrUrl = args[0];
|
|
@@ -1351,7 +1354,7 @@ function installUndiciWrap() {
|
|
|
1351
1354
|
const wrapUndiciRequest = (original) => {
|
|
1352
1355
|
const wrapped = function netgreenerUndiciRequest(...args) {
|
|
1353
1356
|
// Outer fetch/axios already recorded — undici is the transport only.
|
|
1354
|
-
if (outboundMeterOwnerAls.getStore()) {
|
|
1357
|
+
if (!meteringAllowed() || outboundMeterOwnerAls.getStore()) {
|
|
1355
1358
|
return original.apply(this, args);
|
|
1356
1359
|
}
|
|
1357
1360
|
// Dispatcher.prototype.request(opts) vs undici.request(url, opts)
|
package/dist/index.d.ts
CHANGED
|
@@ -17,7 +17,7 @@ export { CgroupV2Reader, resolveCgroupV2Path, snapshotDelta, type CgroupV2Snapsh
|
|
|
17
17
|
export { sampleProcessTree, processTreeAvailability, collectDescendantPids, CPU_SOURCE_PROCESS_TREE, MEMORY_SOURCE_PROCESS_TREE, type ProcessTreeSample, } from './processTree.js';
|
|
18
18
|
export { startManagedCollector, normalizedCollectorMode, childEnvForManagedCollector, reserveTcpEndpoint, type ManagedCollectorHandle, type CollectorMode, } from './managedCollectorLauncher.js';
|
|
19
19
|
export { OccupancyTracker, getOccupancyTracker, type OccupancyWindowSnapshot, } from './occupancyTracker.js';
|
|
20
|
-
export { buildRuntimeHealthV0, mergeHealthIntoMetadata, markHooksActive, type RuntimeHealthV0, type RuntimeHealthStatus, } from './runtimeHealth.js';
|
|
20
|
+
export { buildRuntimeHealthV0, inspectRuntimeSetup, mergeHealthIntoMetadata, markHooksActive, type RuntimeHealthV0, type RuntimeHealthStatus, type RuntimeSetupCheck, } from './runtimeHealth.js';
|
|
21
21
|
export { newRuntimeWindowId } from './windowId.js';
|
|
22
22
|
export { uploadRunSession, type RunSessionCreatePayload, type UploadResult, } from './uploader.js';
|
|
23
23
|
export { resolveObservationExporter, exportModeFromEnv, DirectRunSessionExporter, ThinRunSessionExporter, CollectorRunSessionExporter, type ExportMode, type ExportResult, type ObservationExporter, type ObservationBatchDocument, } from './exporter.js';
|
package/dist/index.js
CHANGED
|
@@ -16,7 +16,7 @@ export { CgroupV2Reader, resolveCgroupV2Path, snapshotDelta, } from './cgroupV2.
|
|
|
16
16
|
export { sampleProcessTree, processTreeAvailability, collectDescendantPids, CPU_SOURCE_PROCESS_TREE, MEMORY_SOURCE_PROCESS_TREE, } from './processTree.js';
|
|
17
17
|
export { startManagedCollector, normalizedCollectorMode, childEnvForManagedCollector, reserveTcpEndpoint, } from './managedCollectorLauncher.js';
|
|
18
18
|
export { OccupancyTracker, getOccupancyTracker, } from './occupancyTracker.js';
|
|
19
|
-
export { buildRuntimeHealthV0, mergeHealthIntoMetadata, markHooksActive, } from './runtimeHealth.js';
|
|
19
|
+
export { buildRuntimeHealthV0, inspectRuntimeSetup, mergeHealthIntoMetadata, markHooksActive, } from './runtimeHealth.js';
|
|
20
20
|
export { newRuntimeWindowId } from './windowId.js';
|
|
21
21
|
export { uploadRunSession, } from './uploader.js';
|
|
22
22
|
export { resolveObservationExporter, exportModeFromEnv, DirectRunSessionExporter, ThinRunSessionExporter, CollectorRunSessionExporter, } from './exporter.js';
|
package/dist/mcpToolMeter.js
CHANGED
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
*
|
|
13
13
|
* Raw tool arguments, results, and HTTP bodies are not stored.
|
|
14
14
|
*/
|
|
15
|
+
import { meteringAllowed } from './runtimeControls.js';
|
|
15
16
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
16
17
|
import { randomUUID } from 'node:crypto';
|
|
17
18
|
import { connect } from 'node:net';
|
|
@@ -171,6 +172,8 @@ export class McpToolLedger {
|
|
|
171
172
|
return this.calls.length > 0;
|
|
172
173
|
}
|
|
173
174
|
beginToolCall(server, tool) {
|
|
175
|
+
if (!meteringAllowed())
|
|
176
|
+
return { callId: randomUUID(), server, tool, attempt: 1, action: 'allow', reason: null };
|
|
174
177
|
const serverName = clean(server, 'unknown');
|
|
175
178
|
const toolName = clean(tool, 'unknown');
|
|
176
179
|
const scope = 'process';
|
|
@@ -203,6 +206,8 @@ export class McpToolLedger {
|
|
|
203
206
|
};
|
|
204
207
|
}
|
|
205
208
|
finishToolCall(decision, opts) {
|
|
209
|
+
if (!meteringAllowed())
|
|
210
|
+
return;
|
|
206
211
|
const blocked = decision.action === 'block';
|
|
207
212
|
const row = {
|
|
208
213
|
server: decision.server,
|
|
@@ -370,7 +375,7 @@ export function finishToolCall(decision, opts) {
|
|
|
370
375
|
ledger.finishToolCall(decision, opts);
|
|
371
376
|
}
|
|
372
377
|
export function recordHttpInToolContext(row) {
|
|
373
|
-
if (!row.toolCallId)
|
|
378
|
+
if (!meteringAllowed() || !row.toolCallId)
|
|
374
379
|
return;
|
|
375
380
|
ledger.recordHttpLink({
|
|
376
381
|
toolCallId: row.toolCallId,
|
package/dist/processResources.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { meteringAllowed } from './runtimeControls.js';
|
|
1
2
|
/**
|
|
2
3
|
* Process-level CPU / RSS sampling for Node Runtime (CAP-R4 / N5).
|
|
3
4
|
*
|
|
@@ -16,7 +17,7 @@ let lastRssKb = 0;
|
|
|
16
17
|
let lastRssAtMs = 0;
|
|
17
18
|
/** Start a CPU interval (call at request/task entry). */
|
|
18
19
|
export function beginProcessResourceSample() {
|
|
19
|
-
return { cpuStart: process.cpuUsage() };
|
|
20
|
+
return { cpuStart: meteringAllowed() ? process.cpuUsage() : { user: 0, system: 0 } };
|
|
20
21
|
}
|
|
21
22
|
function readRssKb(force = false) {
|
|
22
23
|
const now = performance.now();
|
|
@@ -37,6 +38,8 @@ function readRssKb(force = false) {
|
|
|
37
38
|
* ``cpuUsage(previous)`` returns user+system microseconds since ``previous``.
|
|
38
39
|
*/
|
|
39
40
|
export function endProcessResourceSample(mark) {
|
|
41
|
+
if (!meteringAllowed())
|
|
42
|
+
return { cpuTimeMs: 0, rssKb: 0 };
|
|
40
43
|
const delta = process.cpuUsage(mark.cpuStart);
|
|
41
44
|
const cpuTimeMs = (delta.user + delta.system) / 1000;
|
|
42
45
|
return {
|
|
@@ -46,7 +49,7 @@ export function endProcessResourceSample(mark) {
|
|
|
46
49
|
}
|
|
47
50
|
/** Point-in-time RSS (KiB) when no interval mark is available. */
|
|
48
51
|
export function currentRssKb() {
|
|
49
|
-
return readRssKb(true);
|
|
52
|
+
return meteringAllowed() ? readRssKb(true) : 0;
|
|
50
53
|
}
|
|
51
54
|
/** Test helper — clear RSS cache. */
|
|
52
55
|
export function _resetRssSampleCacheForTests() {
|
package/dist/runtime.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { meteringAllowed, startRuntimeControls } from './runtimeControls.js';
|
|
1
2
|
import { hostname } from 'node:os';
|
|
2
3
|
import { ServiceRuntimeAggregator } from './aggregator.js';
|
|
3
4
|
import { carbonFactorDict } from './carbonLedger.js';
|
|
@@ -72,7 +73,7 @@ export class NetGreenerRuntime {
|
|
|
72
73
|
return this.lifecycleInfo.lifecycle;
|
|
73
74
|
}
|
|
74
75
|
get enabled() {
|
|
75
|
-
return configReady(this.config).ok;
|
|
76
|
+
return configReady(this.config).ok && meteringAllowed(this.config);
|
|
76
77
|
}
|
|
77
78
|
ensureOutboundMeter() {
|
|
78
79
|
if (this.outboundInstalled || !this.enabled)
|
|
@@ -106,8 +107,27 @@ export class NetGreenerRuntime {
|
|
|
106
107
|
if (this.started)
|
|
107
108
|
return;
|
|
108
109
|
this.started = true;
|
|
109
|
-
if (!this.
|
|
110
|
+
if (!configReady(this.config).ok)
|
|
110
111
|
return;
|
|
112
|
+
let pauseCpu = null;
|
|
113
|
+
let pauseAt = 0;
|
|
114
|
+
if (!meteringAllowed(this.config)) {
|
|
115
|
+
pauseAt = Date.now();
|
|
116
|
+
pauseCpu = process.cpuUsage();
|
|
117
|
+
}
|
|
118
|
+
startRuntimeControls(this.config, this.uploadFetch(), (enabled) => {
|
|
119
|
+
if (!enabled) {
|
|
120
|
+
pauseAt = Date.now();
|
|
121
|
+
pauseCpu = process.cpuUsage();
|
|
122
|
+
}
|
|
123
|
+
else if (pauseCpu) {
|
|
124
|
+
const delta = process.cpuUsage(pauseCpu);
|
|
125
|
+
this.cpuWindowMark.cpuStart.user += delta.user;
|
|
126
|
+
this.cpuWindowMark.cpuStart.system += delta.system;
|
|
127
|
+
this.aggregator.excludePausedTime(Date.now() - pauseAt);
|
|
128
|
+
pauseCpu = null;
|
|
129
|
+
}
|
|
130
|
+
});
|
|
111
131
|
markHooksActive({
|
|
112
132
|
processKind: this.framework,
|
|
113
133
|
exportMode: this.exporter.mode,
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { RuntimeConfig } from './config.js';
|
|
2
|
+
export declare function meteringAllowed(config?: RuntimeConfig): boolean;
|
|
3
|
+
export declare function applyRuntimeControls(config: RuntimeConfig, enabled: boolean, orgId?: number): void;
|
|
4
|
+
export declare function refreshRuntimeControls(config: RuntimeConfig, fetchImpl: typeof fetch): Promise<void>;
|
|
5
|
+
export declare function startRuntimeControls(config: RuntimeConfig, fetchImpl: typeof fetch, onChange?: (enabled: boolean) => void): void;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/** Company policy cache shared by JavaScript/TypeScript hooks and exporters. */
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { jwtPayloadUnverified } from './tenantContext.js';
|
|
4
|
+
const states = new Map();
|
|
5
|
+
let activeKey;
|
|
6
|
+
function accountKey(config) {
|
|
7
|
+
return createHash('sha256').update(JSON.stringify([config.apiUrl, config.organizationId, config.token])).digest('hex');
|
|
8
|
+
}
|
|
9
|
+
function stateFor(config) {
|
|
10
|
+
const key = accountKey(config);
|
|
11
|
+
let state = states.get(key);
|
|
12
|
+
if (!state) {
|
|
13
|
+
const claim = jwtPayloadUnverified(`Bearer ${config.token}`)?.org_id;
|
|
14
|
+
const id = config.organizationId ?? Number(claim);
|
|
15
|
+
state = { enabled: true, orgId: Number.isSafeInteger(id) && Number(id) > 0 ? Number(id) : null, refreshing: false, listeners: new Set() };
|
|
16
|
+
states.set(key, state);
|
|
17
|
+
}
|
|
18
|
+
return state;
|
|
19
|
+
}
|
|
20
|
+
export function meteringAllowed(config) {
|
|
21
|
+
return (config ? stateFor(config) : activeKey ? states.get(activeKey) : undefined)?.enabled ?? true;
|
|
22
|
+
}
|
|
23
|
+
export function applyRuntimeControls(config, enabled, orgId) {
|
|
24
|
+
const state = stateFor(config);
|
|
25
|
+
if (orgId != null && Number.isSafeInteger(orgId) && orgId > 0)
|
|
26
|
+
state.orgId = orgId;
|
|
27
|
+
activeKey = accountKey(config);
|
|
28
|
+
if (state.enabled === enabled)
|
|
29
|
+
return;
|
|
30
|
+
state.enabled = enabled;
|
|
31
|
+
for (const listener of state.listeners)
|
|
32
|
+
listener(enabled);
|
|
33
|
+
}
|
|
34
|
+
export async function refreshRuntimeControls(config, fetchImpl) {
|
|
35
|
+
const state = stateFor(config);
|
|
36
|
+
if (config.dryRun || state.orgId == null || state.refreshing)
|
|
37
|
+
return;
|
|
38
|
+
state.refreshing = true;
|
|
39
|
+
try {
|
|
40
|
+
const response = await fetchImpl(`${config.apiUrl}/api/v1/organizations/${state.orgId}/runtime-controls`, {
|
|
41
|
+
headers: { Authorization: `Bearer ${config.token}`, 'X-Organization-ID': String(state.orgId) },
|
|
42
|
+
signal: AbortSignal.timeout(5000),
|
|
43
|
+
});
|
|
44
|
+
if (!response.ok)
|
|
45
|
+
return;
|
|
46
|
+
const data = await response.json();
|
|
47
|
+
if (data.org_id === state.orgId && typeof data.metering_enabled === 'boolean') {
|
|
48
|
+
applyRuntimeControls(config, data.metering_enabled);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
// Retain the last known policy, including a known pause, during outages.
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
state.refreshing = false;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
export function startRuntimeControls(config, fetchImpl, onChange) {
|
|
59
|
+
if (config.dryRun || !config.enabled)
|
|
60
|
+
return;
|
|
61
|
+
activeKey = accountKey(config);
|
|
62
|
+
const state = stateFor(config);
|
|
63
|
+
if (onChange)
|
|
64
|
+
state.listeners.add(onChange);
|
|
65
|
+
if (state.timer)
|
|
66
|
+
return;
|
|
67
|
+
state.timer = setInterval(() => { void refreshRuntimeControls(config, fetchImpl); }, 30_000);
|
|
68
|
+
state.timer.unref?.();
|
|
69
|
+
}
|
package/dist/runtimeHealth.d.ts
CHANGED
|
@@ -4,6 +4,21 @@
|
|
|
4
4
|
* Additive ``runtime_health_v0`` twin of Python ``netgreener.runtime_health``.
|
|
5
5
|
* Does not change upload defaults or invent collector spool metrics.
|
|
6
6
|
*/
|
|
7
|
+
export type RuntimeSetupCheck = {
|
|
8
|
+
name: string;
|
|
9
|
+
status: 'pass' | 'fail' | 'not_verified';
|
|
10
|
+
detail: string;
|
|
11
|
+
};
|
|
12
|
+
export declare function inspectRuntimeSetup(env?: NodeJS.ProcessEnv): {
|
|
13
|
+
schema: "netgreener_runtime_status_v1";
|
|
14
|
+
scope: "local_configuration";
|
|
15
|
+
ready: boolean;
|
|
16
|
+
enabled: boolean;
|
|
17
|
+
dry_run: boolean;
|
|
18
|
+
lifecycle: import("./lifecycle.js").RuntimeLifecycle;
|
|
19
|
+
export_mode: import("./exporter.js").ExportMode;
|
|
20
|
+
checks: RuntimeSetupCheck[];
|
|
21
|
+
};
|
|
7
22
|
export type RuntimeHealthStatus = 'ok' | 'degraded' | 'conflict' | 'unknown';
|
|
8
23
|
export type RuntimeHealthV0 = {
|
|
9
24
|
schema_version: 1;
|
package/dist/runtimeHealth.js
CHANGED
|
@@ -4,6 +4,52 @@
|
|
|
4
4
|
* Additive ``runtime_health_v0`` twin of Python ``netgreener.runtime_health``.
|
|
5
5
|
* Does not change upload defaults or invent collector spool metrics.
|
|
6
6
|
*/
|
|
7
|
+
import { configReady, loadRuntimeConfig } from './config.js';
|
|
8
|
+
import { exportModeFromEnv } from './exporter.js';
|
|
9
|
+
import { resolveLifecycle } from './lifecycle.js';
|
|
10
|
+
import { normalizeCollectorEndpoint } from './collectorIpc.js';
|
|
11
|
+
export function inspectRuntimeSetup(env = process.env) {
|
|
12
|
+
const config = loadRuntimeConfig(env);
|
|
13
|
+
const lifecycle = resolveLifecycle({ env }).lifecycle;
|
|
14
|
+
const exportMode = exportModeFromEnv(env, { lifecycle });
|
|
15
|
+
let validApiUrl = false;
|
|
16
|
+
try {
|
|
17
|
+
const url = new URL(config.apiUrl);
|
|
18
|
+
validApiUrl = ['https:', 'http:'].includes(url.protocol) && Boolean(url.hostname);
|
|
19
|
+
}
|
|
20
|
+
catch { }
|
|
21
|
+
let validDelivery = exportMode !== 'collector';
|
|
22
|
+
if (exportMode === 'collector') {
|
|
23
|
+
try {
|
|
24
|
+
const endpoint = new URL(normalizeCollectorEndpoint(env.NETGREENER_COLLECTOR_ENDPOINT || ''));
|
|
25
|
+
validDelivery = endpoint.protocol === 'tcp:'
|
|
26
|
+
? Boolean(endpoint.hostname && Number(endpoint.port) > 0 && Number(endpoint.port) <= 65535)
|
|
27
|
+
: endpoint.protocol === 'unix:' && process.platform !== 'win32' && endpoint.pathname.startsWith('/');
|
|
28
|
+
}
|
|
29
|
+
catch { }
|
|
30
|
+
}
|
|
31
|
+
const checks = [
|
|
32
|
+
{ name: 'runtime_enabled', status: config.enabled ? 'pass' : 'fail', detail: 'Set the token and project ID to enable automatically; NETGREENER_SERVICE_RUNTIME=0 disables it.' },
|
|
33
|
+
{ name: 'credentials', status: config.token ? 'pass' : 'fail', detail: 'NETGREENER_TOKEN is checked for presence only; authentication is not verified.' },
|
|
34
|
+
{ name: 'project', status: config.projectId > 0 ? 'pass' : 'fail', detail: 'NETGREENER_PROJECT_ID must be a positive safe integer; project access is not verified.' },
|
|
35
|
+
{ name: 'api_url', status: validApiUrl ? 'pass' : 'fail', detail: 'NETGREENER_API_URL must be an HTTP(S) URL; the endpoint is not contacted.' },
|
|
36
|
+
{ name: 'delivery', status: validDelivery ? 'pass' : 'fail', detail: 'Collector mode requires a valid TCP host/port or supported Unix socket endpoint; availability is not verified.' },
|
|
37
|
+
...['hooks', 'tenant_attribution', 'provider_instrumentation', 'upload'].map(name => ({
|
|
38
|
+
name, status: 'not_verified',
|
|
39
|
+
detail: 'Verify inside the running application with authenticated traffic and persisted telemetry.',
|
|
40
|
+
})),
|
|
41
|
+
];
|
|
42
|
+
return {
|
|
43
|
+
schema: 'netgreener_runtime_status_v1',
|
|
44
|
+
scope: 'local_configuration',
|
|
45
|
+
ready: configReady(config).ok && checks.every(check => check.status !== 'fail'),
|
|
46
|
+
enabled: config.enabled,
|
|
47
|
+
dry_run: config.dryRun,
|
|
48
|
+
lifecycle,
|
|
49
|
+
export_mode: exportMode,
|
|
50
|
+
checks,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
7
53
|
const state = {
|
|
8
54
|
hooksActive: false,
|
|
9
55
|
processKind: 'process',
|
package/dist/tenantContext.d.ts
CHANGED
|
@@ -38,6 +38,7 @@ export declare function tenantConfigFromRuntime(config: {
|
|
|
38
38
|
tenantTaskKwarg: string;
|
|
39
39
|
tenantLabelClaim: string | null;
|
|
40
40
|
}): TenantConfig;
|
|
41
|
+
export declare function jwtPayloadUnverified(authorization: string | null): Record<string, unknown> | null;
|
|
41
42
|
export declare function resolveTenantFromHttpRequest(req: {
|
|
42
43
|
headers?: Record<string, unknown>;
|
|
43
44
|
path?: string;
|
package/dist/tenantContext.js
CHANGED
package/dist/uploader.js
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
|
+
import { applyRuntimeControls, meteringAllowed, startRuntimeControls } from './runtimeControls.js';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
1
3
|
import { validateRuntimeSessionMetadata } from './contract/validate.js';
|
|
4
|
+
// A 402 pauses all windows for this account, including new exporter instances.
|
|
5
|
+
// Collector delivery uses the Python durable queue and its persisted billing pause.
|
|
6
|
+
const billingPauses = new Map();
|
|
2
7
|
export async function uploadRunSession(config, payload, fetchImpl = fetch) {
|
|
3
8
|
const validation = validateRuntimeSessionMetadata(payload.session_metadata);
|
|
4
9
|
if (!validation.ok) {
|
|
@@ -10,6 +15,10 @@ export async function uploadRunSession(config, payload, fetchImpl = fetch) {
|
|
|
10
15
|
if (config.dryRun) {
|
|
11
16
|
return { ok: true, status: 0, body: payload, dryRun: true };
|
|
12
17
|
}
|
|
18
|
+
startRuntimeControls(config, fetchImpl);
|
|
19
|
+
if (!meteringAllowed(config)) {
|
|
20
|
+
return { ok: false, status: 423, error: 'Metering is paused by your organization administrator' };
|
|
21
|
+
}
|
|
13
22
|
const url = `${config.apiUrl}/api/v1/runsessions/`;
|
|
14
23
|
const headers = {
|
|
15
24
|
Authorization: `Bearer ${config.token}`,
|
|
@@ -19,7 +28,27 @@ export async function uploadRunSession(config, payload, fetchImpl = fetch) {
|
|
|
19
28
|
if (config.organizationId != null) {
|
|
20
29
|
headers['X-Organization-ID'] = String(config.organizationId);
|
|
21
30
|
}
|
|
31
|
+
const account = createHash('sha256').update(JSON.stringify([config.apiUrl, config.organizationId, config.token])).digest('hex');
|
|
32
|
+
const pause = billingPauses.get(account);
|
|
33
|
+
const pausedResult = () => ({
|
|
34
|
+
ok: false, status: 402, body: pause?.body,
|
|
35
|
+
error: 'Runtime uploads paused: insufficient organization credits. Add credits in the dashboard at /billing/credits.',
|
|
36
|
+
});
|
|
22
37
|
try {
|
|
38
|
+
if (pause) {
|
|
39
|
+
if (Date.now() < pause.checkAfter)
|
|
40
|
+
return pausedResult();
|
|
41
|
+
pause.checkAfter = Date.now() + 300_000;
|
|
42
|
+
if (pause.orgId != null) {
|
|
43
|
+
const balance = await fetchImpl(`${config.apiUrl}/api/v1/billing/organizations/${pause.orgId}/credits`, { headers });
|
|
44
|
+
if (!balance.ok)
|
|
45
|
+
return pausedResult();
|
|
46
|
+
const data = await balance.json();
|
|
47
|
+
if (typeof data.balance_credits !== 'number' || data.balance_credits < pause.required)
|
|
48
|
+
return pausedResult();
|
|
49
|
+
}
|
|
50
|
+
billingPauses.delete(account);
|
|
51
|
+
}
|
|
23
52
|
const res = await fetchImpl(url, {
|
|
24
53
|
method: 'POST',
|
|
25
54
|
headers,
|
|
@@ -34,10 +63,25 @@ export async function uploadRunSession(config, payload, fetchImpl = fetch) {
|
|
|
34
63
|
/* keep text */
|
|
35
64
|
}
|
|
36
65
|
if (!res.ok) {
|
|
66
|
+
if (res.status === 423) {
|
|
67
|
+
const envelope = body;
|
|
68
|
+
applyRuntimeControls(config, false, (envelope?.detail ?? envelope?.error)?.org_id);
|
|
69
|
+
}
|
|
70
|
+
if (res.status === 402) {
|
|
71
|
+
const envelope = body;
|
|
72
|
+
const detail = envelope?.detail ?? envelope?.error;
|
|
73
|
+
const orgId = detail?.org_id ?? config.organizationId;
|
|
74
|
+
billingPauses.set(account, {
|
|
75
|
+
checkAfter: Date.now() + 300_000,
|
|
76
|
+
required: Math.max(1, Number(detail?.required_credits) || 1), orgId, body,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
37
79
|
return {
|
|
38
80
|
ok: false,
|
|
39
81
|
status: res.status,
|
|
40
|
-
error:
|
|
82
|
+
error: res.status === 402
|
|
83
|
+
? 'Runtime uploads paused: insufficient organization credits. Add credits in the dashboard at /billing/credits.'
|
|
84
|
+
: `upload failed HTTP ${res.status}`,
|
|
41
85
|
body,
|
|
42
86
|
};
|
|
43
87
|
}
|
package/package.json
CHANGED