@netgreener/runtime 0.1.8 → 0.1.9

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 (100) hide show
  1. package/TUTORIAL.md +120 -29
  2. package/dist/aggregator.d.ts +12 -2
  3. package/dist/aggregator.js +135 -8
  4. package/dist/analyze/buildResourceFindings.d.ts +4 -0
  5. package/dist/analyze/buildResourceFindings.js +17 -0
  6. package/dist/analyze/cli.d.ts +1 -0
  7. package/dist/analyze/cli.js +22 -1
  8. package/dist/analyze/declaredExternalApis.d.ts +31 -0
  9. package/dist/analyze/declaredExternalApis.js +174 -0
  10. package/dist/analyze/index.d.ts +1 -0
  11. package/dist/analyze/index.js +1 -0
  12. package/dist/auto.d.ts +7 -0
  13. package/dist/auto.js +8 -0
  14. package/dist/bullmq.d.ts +2 -2
  15. package/dist/bullmq.js +28 -58
  16. package/dist/carbonLedger.d.ts +28 -0
  17. package/dist/carbonLedger.js +52 -0
  18. package/dist/cgroupV2.d.ts +44 -0
  19. package/dist/cgroupV2.js +174 -0
  20. package/dist/cli/helpText.d.ts +3 -3
  21. package/dist/cli/helpText.js +42 -35
  22. package/dist/cli/netgreener.d.ts +7 -7
  23. package/dist/cli/netgreener.js +23 -16
  24. package/dist/cli/runCli.d.ts +20 -0
  25. package/dist/cli/runCli.js +249 -0
  26. package/dist/cli/runPreload.d.ts +5 -0
  27. package/dist/cli/runPreload.js +43 -0
  28. package/dist/collectorMetadata.d.ts +1 -1
  29. package/dist/collectorMetadata.js +2 -0
  30. package/dist/config.d.ts +2 -0
  31. package/dist/config.js +6 -2
  32. package/dist/exporter.d.ts +7 -2
  33. package/dist/exporter.js +12 -6
  34. package/dist/express.js +17 -6
  35. package/dist/externalApiMeter.d.ts +43 -1
  36. package/dist/externalApiMeter.js +267 -5
  37. package/dist/fastify.js +17 -6
  38. package/dist/index.d.ts +10 -2
  39. package/dist/index.js +9 -1
  40. package/dist/init.d.ts +30 -0
  41. package/dist/init.js +31 -0
  42. package/dist/lifecycle.d.ts +45 -0
  43. package/dist/lifecycle.js +112 -0
  44. package/dist/managedCollectorLauncher.d.ts +37 -0
  45. package/dist/managedCollectorLauncher.js +162 -0
  46. package/dist/n4/deploymentMatrix.d.ts +9 -5
  47. package/dist/n4/deploymentMatrix.js +13 -9
  48. package/dist/n4/missingnessInventory.js +3 -3
  49. package/dist/next.d.ts +61 -0
  50. package/dist/next.js +195 -0
  51. package/dist/occupancyTracker.d.ts +27 -0
  52. package/dist/occupancyTracker.js +87 -0
  53. package/dist/optimize/apply.d.ts +38 -0
  54. package/dist/optimize/apply.js +173 -0
  55. package/dist/optimize/cli.d.ts +26 -0
  56. package/dist/optimize/cli.js +323 -0
  57. package/dist/optimize/index.d.ts +6 -0
  58. package/dist/optimize/index.js +5 -0
  59. package/dist/optimize/llmApply.d.ts +22 -0
  60. package/dist/optimize/llmApply.js +80 -0
  61. package/dist/optimize/llmSession.d.ts +88 -0
  62. package/dist/optimize/llmSession.js +135 -0
  63. package/dist/optimize/provider.d.ts +17 -0
  64. package/dist/optimize/provider.js +119 -0
  65. package/dist/optimize/safePatches.d.ts +18 -0
  66. package/dist/optimize/safePatches.js +247 -0
  67. package/dist/optimize/types.d.ts +79 -0
  68. package/dist/optimize/types.js +6 -0
  69. package/dist/optimize/verification.d.ts +16 -0
  70. package/dist/optimize/verification.js +165 -0
  71. package/dist/processResources.d.ts +5 -0
  72. package/dist/processResources.js +28 -4
  73. package/dist/processRuntime.js +7 -28
  74. package/dist/processTree.d.ts +47 -0
  75. package/dist/processTree.js +148 -0
  76. package/dist/runContextEnrichment.d.ts +11 -0
  77. package/dist/runContextEnrichment.js +92 -0
  78. package/dist/runtime.d.ts +29 -1
  79. package/dist/runtime.js +94 -16
  80. package/dist/sdk/client.d.ts +152 -0
  81. package/dist/sdk/client.js +396 -0
  82. package/dist/sdk/gitUrl.d.ts +6 -0
  83. package/dist/sdk/gitUrl.js +87 -0
  84. package/dist/sdk/index.d.ts +5 -0
  85. package/dist/sdk/index.js +5 -0
  86. package/dist/serverlessHints.d.ts +9 -6
  87. package/dist/serverlessHints.js +10 -7
  88. package/dist/taskMeter.d.ts +14 -0
  89. package/dist/taskMeter.js +53 -0
  90. package/dist/types.d.ts +35 -0
  91. package/examples/aca-container-gate/Dockerfile +20 -0
  92. package/examples/aca-container-gate/azure-container-app.yaml +27 -0
  93. package/examples/aca-container-gate/gate.env +7 -0
  94. package/examples/aca-container-gate/server.mjs +117 -0
  95. package/examples/express-local-live-smoke.mjs +127 -0
  96. package/examples/extractRunId.mjs +11 -0
  97. package/examples/next-pilot-dry-run.mjs +32 -0
  98. package/examples/serverless-thin-gate.mjs +89 -0
  99. package/fixtures/run-smoke/hello.mjs +4 -0
  100. package/package.json +23 -2
@@ -4,13 +4,34 @@
4
4
  * Mirrors Python ASGI middleware: ``time.process_time()`` + ``psutil`` RSS.
5
5
  * Uses Node ``process.cpuUsage`` / ``process.memoryUsage().rss`` only —
6
6
  * never invents cgroup or process-tree values.
7
+ *
8
+ * RSS OS reads are rate-limited (still measured, never fabricated). Peak RSS
9
+ * aggregation stays honest: a cached sample is a real prior ``memoryUsage().rss``.
7
10
  */
8
11
  export const CPU_SOURCE_PROCESS = 'node_process_cpu_usage';
9
12
  export const MEMORY_SOURCE_PROCESS = 'node_process_memory_rss';
13
+ /** Min gap between ``memoryUsage()`` RSS reads (ms). Override via env for tests. */
14
+ const RSS_MIN_INTERVAL_MS = Number(process.env.NETGREENER_RSS_SAMPLE_INTERVAL_MS || 50);
15
+ let lastRssKb = 0;
16
+ let lastRssAtMs = 0;
10
17
  /** Start a CPU interval (call at request/task entry). */
11
18
  export function beginProcessResourceSample() {
12
19
  return { cpuStart: process.cpuUsage() };
13
20
  }
21
+ function readRssKb(force = false) {
22
+ const now = performance.now();
23
+ if (!force &&
24
+ lastRssAtMs > 0 &&
25
+ now - lastRssAtMs < RSS_MIN_INTERVAL_MS &&
26
+ lastRssKb > 0) {
27
+ return lastRssKb;
28
+ }
29
+ const rssKb = Math.round(process.memoryUsage().rss / 1024);
30
+ const safe = Number.isFinite(rssKb) && rssKb >= 0 ? rssKb : 0;
31
+ lastRssKb = safe;
32
+ lastRssAtMs = now;
33
+ return safe;
34
+ }
14
35
  /**
15
36
  * End a CPU interval and read current RSS.
16
37
  * ``cpuUsage(previous)`` returns user+system microseconds since ``previous``.
@@ -18,14 +39,17 @@ export function beginProcessResourceSample() {
18
39
  export function endProcessResourceSample(mark) {
19
40
  const delta = process.cpuUsage(mark.cpuStart);
20
41
  const cpuTimeMs = (delta.user + delta.system) / 1000;
21
- const rssKb = Math.round(process.memoryUsage().rss / 1024);
22
42
  return {
23
43
  cpuTimeMs: Number.isFinite(cpuTimeMs) && cpuTimeMs >= 0 ? cpuTimeMs : 0,
24
- rssKb: Number.isFinite(rssKb) && rssKb >= 0 ? rssKb : 0,
44
+ rssKb: readRssKb(false),
25
45
  };
26
46
  }
27
47
  /** Point-in-time RSS (KiB) when no interval mark is available. */
28
48
  export function currentRssKb() {
29
- const rssKb = Math.round(process.memoryUsage().rss / 1024);
30
- return Number.isFinite(rssKb) && rssKb >= 0 ? rssKb : 0;
49
+ return readRssKb(true);
50
+ }
51
+ /** Test helper — clear RSS cache. */
52
+ export function _resetRssSampleCacheForTests() {
53
+ lastRssKb = 0;
54
+ lastRssAtMs = 0;
31
55
  }
@@ -6,7 +6,7 @@
6
6
  import { getRuntime, } from './runtime.js';
7
7
  import { normalizeTenantId, runWithTenantContext, setTenantContext, } from './tenantContext.js';
8
8
  import { runWithRequestAttribution } from './requestContext.js';
9
- import { beginProcessResourceSample, endProcessResourceSample, } from './processResources.js';
9
+ import { recordMeteredTask } from './taskMeter.js';
10
10
  let signalsInstalled = false;
11
11
  /**
12
12
  * Enable NetGreener runtime for a long-lived Node process (cron worker, script).
@@ -19,7 +19,7 @@ export function startProcessRuntime(opts = {}) {
19
19
  ...opts,
20
20
  });
21
21
  runtime.start();
22
- if (!signalsInstalled) {
22
+ if (!signalsInstalled && runtime.lifecycle === 'persistent') {
23
23
  signalsInstalled = true;
24
24
  const shutdown = () => {
25
25
  void runtime.shutdown();
@@ -45,32 +45,11 @@ export async function runWithProcessTenant(tenantId, fn, opts) {
45
45
  ...(opts?.label ? { tenantLabel: opts.label.slice(0, 128) } : {}),
46
46
  };
47
47
  const serviceUnit = opts?.serviceUnit || 'task:process';
48
- const started = performance.now();
49
- const resourceMark = beginProcessResourceSample();
50
- let error = false;
51
- const run = async () => {
52
- try {
53
- return await fn();
54
- }
55
- catch (err) {
56
- error = true;
57
- throw err;
58
- }
59
- finally {
60
- if (runtime.enabled) {
61
- const resources = endProcessResourceSample(resourceMark);
62
- runtime.recordTask({
63
- serviceUnit,
64
- durationMs: performance.now() - started,
65
- error,
66
- tenantId: normalized,
67
- cpuTimeMs: resources.cpuTimeMs,
68
- peakRssKb: resources.rssKb,
69
- });
70
- }
71
- }
72
- };
73
- return runWithTenantContext(ctx, () => runWithRequestAttribution({ serviceUnit }, () => run()));
48
+ return runWithTenantContext(ctx, () => runWithRequestAttribution({ serviceUnit }, () => recordMeteredTask(runtime, {
49
+ serviceUnit,
50
+ tenantId: normalized,
51
+ fn,
52
+ })));
74
53
  }
75
54
  /**
76
55
  * Convenience: set tenant for the rest of the current async chain (enterWith).
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Process-tree CPU/RSS sampling (Linux /proc first; Windows honest unavailable).
3
+ *
4
+ * Aggregates self + descendant PIDs. Never invents cgroup values.
5
+ * Injectable ``readProc`` supports unit tests without a real /proc.
6
+ */
7
+ export declare const CPU_SOURCE_PROCESS_TREE = "process_tree_proc";
8
+ export declare const MEMORY_SOURCE_PROCESS_TREE = "process_tree_rss";
9
+ export type ProcessTreeSample = {
10
+ /** Aggregate user+system CPU milliseconds since boot for the tree. */
11
+ cpuTimeMs: number;
12
+ /** Sum of RSS (KiB) across observed PIDs. */
13
+ rssKb: number;
14
+ /** Root + descendants successfully sampled. */
15
+ pidCount: number;
16
+ provenanceCpu: typeof CPU_SOURCE_PROCESS_TREE;
17
+ provenanceMemory: typeof MEMORY_SOURCE_PROCESS_TREE;
18
+ };
19
+ export type ProcessTreeAvailability = {
20
+ available: boolean;
21
+ reason: string | null;
22
+ platform: string;
23
+ };
24
+ export type ProcessTreeOptions = {
25
+ rootPid?: number;
26
+ procRoot?: string;
27
+ platform?: NodeJS.Platform;
28
+ /** Override /proc reads for tests. */
29
+ readText?: (path: string) => string | null;
30
+ listPids?: () => number[];
31
+ };
32
+ /** Parse ``/proc/<pid>/stat`` utime+stime (fields 14–15, 1/100s ticks). */
33
+ export declare function parseProcStatCpuTicks(statText: string): number | null;
34
+ /** Parse ``/proc/<pid>/stat`` ppid (field after state). */
35
+ export declare function parseProcStatPpid(statText: string): number | null;
36
+ /** Parse ``/proc/<pid>/status`` VmRSS in KiB. */
37
+ export declare function parseProcStatusRssKb(statusText: string): number | null;
38
+ export declare function processTreeAvailability(opts?: ProcessTreeOptions): ProcessTreeAvailability;
39
+ /**
40
+ * Collect descendant PIDs of ``rootPid`` (including root) via ppid links.
41
+ */
42
+ export declare function collectDescendantPids(rootPid: number, opts?: ProcessTreeOptions): number[];
43
+ /**
44
+ * Snapshot aggregate CPU ticks (ms) + RSS for the process tree.
45
+ * CPU uses 100 Hz ticks → ms = ticks * 10.
46
+ */
47
+ export declare function sampleProcessTree(opts?: ProcessTreeOptions): ProcessTreeSample | null;
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Process-tree CPU/RSS sampling (Linux /proc first; Windows honest unavailable).
3
+ *
4
+ * Aggregates self + descendant PIDs. Never invents cgroup values.
5
+ * Injectable ``readProc`` supports unit tests without a real /proc.
6
+ */
7
+ import { readFileSync, readdirSync, existsSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+ import { platform } from 'node:os';
10
+ export const CPU_SOURCE_PROCESS_TREE = 'process_tree_proc';
11
+ export const MEMORY_SOURCE_PROCESS_TREE = 'process_tree_rss';
12
+ function defaultReadText(path) {
13
+ try {
14
+ return readFileSync(path, 'utf8');
15
+ }
16
+ catch {
17
+ return null;
18
+ }
19
+ }
20
+ function defaultListPids(procRoot) {
21
+ try {
22
+ return readdirSync(procRoot)
23
+ .map((name) => Number(name))
24
+ .filter((n) => Number.isFinite(n) && n > 0);
25
+ }
26
+ catch {
27
+ return [];
28
+ }
29
+ }
30
+ /** Parse ``/proc/<pid>/stat`` utime+stime (fields 14–15, 1/100s ticks). */
31
+ export function parseProcStatCpuTicks(statText) {
32
+ const closeParen = statText.lastIndexOf(')');
33
+ if (closeParen < 0)
34
+ return null;
35
+ const rest = statText.slice(closeParen + 2).trim().split(/\s+/);
36
+ // After ``)``: state(0) ppid(1) … utime(11) stime(12) — 0-based in rest.
37
+ const utime = Number(rest[11]);
38
+ const stime = Number(rest[12]);
39
+ if (!Number.isFinite(utime) || !Number.isFinite(stime))
40
+ return null;
41
+ return utime + stime;
42
+ }
43
+ /** Parse ``/proc/<pid>/stat`` ppid (field after state). */
44
+ export function parseProcStatPpid(statText) {
45
+ const closeParen = statText.lastIndexOf(')');
46
+ if (closeParen < 0)
47
+ return null;
48
+ const rest = statText.slice(closeParen + 2).trim().split(/\s+/);
49
+ const ppid = Number(rest[1]);
50
+ return Number.isFinite(ppid) ? ppid : null;
51
+ }
52
+ /** Parse ``/proc/<pid>/status`` VmRSS in KiB. */
53
+ export function parseProcStatusRssKb(statusText) {
54
+ for (const line of statusText.split(/\r?\n/)) {
55
+ if (!line.startsWith('VmRSS:'))
56
+ continue;
57
+ const n = Number(line.replace(/^VmRSS:\s*/, '').split(/\s+/)[0]);
58
+ return Number.isFinite(n) ? Math.max(0, n) : null;
59
+ }
60
+ return null;
61
+ }
62
+ export function processTreeAvailability(opts = {}) {
63
+ const plat = opts.platform ?? platform();
64
+ if (plat !== 'linux') {
65
+ return {
66
+ available: false,
67
+ reason: 'process_tree_linux_proc_only',
68
+ platform: plat,
69
+ };
70
+ }
71
+ const procRoot = opts.procRoot ?? '/proc';
72
+ if (!existsSync(procRoot) && !opts.listPids) {
73
+ return { available: false, reason: 'proc_unavailable', platform: plat };
74
+ }
75
+ return { available: true, reason: null, platform: plat };
76
+ }
77
+ /**
78
+ * Collect descendant PIDs of ``rootPid`` (including root) via ppid links.
79
+ */
80
+ export function collectDescendantPids(rootPid, opts = {}) {
81
+ const procRoot = opts.procRoot ?? '/proc';
82
+ const readText = opts.readText ?? defaultReadText;
83
+ const allPids = opts.listPids ? opts.listPids() : defaultListPids(procRoot);
84
+ const children = new Map();
85
+ for (const pid of allPids) {
86
+ const stat = readText(join(procRoot, String(pid), 'stat'));
87
+ if (!stat)
88
+ continue;
89
+ const ppid = parseProcStatPpid(stat);
90
+ if (ppid == null)
91
+ continue;
92
+ const list = children.get(ppid) ?? [];
93
+ list.push(pid);
94
+ children.set(ppid, list);
95
+ }
96
+ const out = [];
97
+ const stack = [rootPid];
98
+ const seen = new Set();
99
+ while (stack.length) {
100
+ const pid = stack.pop();
101
+ if (seen.has(pid))
102
+ continue;
103
+ seen.add(pid);
104
+ out.push(pid);
105
+ for (const child of children.get(pid) ?? [])
106
+ stack.push(child);
107
+ }
108
+ return out;
109
+ }
110
+ /**
111
+ * Snapshot aggregate CPU ticks (ms) + RSS for the process tree.
112
+ * CPU uses 100 Hz ticks → ms = ticks * 10.
113
+ */
114
+ export function sampleProcessTree(opts = {}) {
115
+ const avail = processTreeAvailability(opts);
116
+ if (!avail.available)
117
+ return null;
118
+ const rootPid = opts.rootPid ?? process.pid;
119
+ const procRoot = opts.procRoot ?? '/proc';
120
+ const readText = opts.readText ?? defaultReadText;
121
+ const pids = collectDescendantPids(rootPid, opts);
122
+ let ticks = 0;
123
+ let rssKb = 0;
124
+ let pidCount = 0;
125
+ for (const pid of pids) {
126
+ const stat = readText(join(procRoot, String(pid), 'stat'));
127
+ const status = readText(join(procRoot, String(pid), 'status'));
128
+ if (!stat)
129
+ continue;
130
+ const t = parseProcStatCpuTicks(stat);
131
+ if (t == null)
132
+ continue;
133
+ ticks += t;
134
+ const rss = status ? parseProcStatusRssKb(status) : null;
135
+ if (rss != null)
136
+ rssKb += rss;
137
+ pidCount += 1;
138
+ }
139
+ if (pidCount === 0)
140
+ return null;
141
+ return {
142
+ cpuTimeMs: ticks * 10,
143
+ rssKb,
144
+ pidCount,
145
+ provenanceCpu: CPU_SOURCE_PROCESS_TREE,
146
+ provenanceMemory: MEMORY_SOURCE_PROCESS_TREE,
147
+ };
148
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Enrich run_context for anomaly / optimize evidence (additive).
3
+ *
4
+ * Twin intent of Python ``attach_release_identity`` + CI flags used by
5
+ * ``anomaly_feature_projection._is_ci``. Does not change EXPORT_MODE or upload path.
6
+ */
7
+ /**
8
+ * Attach release identity + CI flags onto an existing run_context object.
9
+ * Never overwrites an already-set ``release_tag`` / ``git_sha`` / ``deploy_id``.
10
+ */
11
+ export declare function enrichRunContextForAnomaly(ctx: Record<string, unknown>, env?: NodeJS.ProcessEnv): Record<string, unknown>;
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Enrich run_context for anomaly / optimize evidence (additive).
3
+ *
4
+ * Twin intent of Python ``attach_release_identity`` + CI flags used by
5
+ * ``anomaly_feature_projection._is_ci``. Does not change EXPORT_MODE or upload path.
6
+ */
7
+ function firstEnv(env, names) {
8
+ for (const name of names) {
9
+ const v = (env[name] || '').trim();
10
+ if (v)
11
+ return v;
12
+ }
13
+ return null;
14
+ }
15
+ function detectCi(env) {
16
+ return Boolean(firstEnv(env, [
17
+ 'CI',
18
+ 'GITHUB_ACTIONS',
19
+ 'GITLAB_CI',
20
+ 'BUILD_BUILDID',
21
+ 'TF_BUILD',
22
+ 'CIRCLECI',
23
+ 'TRAVIS',
24
+ ]));
25
+ }
26
+ function resolveCiProvider(env) {
27
+ if (firstEnv(env, ['GITHUB_ACTIONS']))
28
+ return 'github_actions';
29
+ if (firstEnv(env, ['GITLAB_CI']))
30
+ return 'gitlab_ci';
31
+ if (firstEnv(env, ['TF_BUILD', 'BUILD_BUILDID']))
32
+ return 'azure_devops';
33
+ if (firstEnv(env, ['CIRCLECI']))
34
+ return 'circleci';
35
+ if (firstEnv(env, ['TRAVIS']))
36
+ return 'travis';
37
+ if (firstEnv(env, ['CI']))
38
+ return 'ci';
39
+ return null;
40
+ }
41
+ function resolveReleaseTagFallback(env) {
42
+ return firstEnv(env, [
43
+ 'NETGREENER_RELEASE_TAG',
44
+ 'RELEASE_TAG',
45
+ 'IMAGE_TAG',
46
+ 'DOCKER_IMAGE_TAG',
47
+ 'DOCKER_TAG',
48
+ 'CONTAINER_IMAGE_TAG',
49
+ 'APP_VERSION',
50
+ 'CI_COMMIT_TAG',
51
+ 'BUILD_BUILDNUMBER',
52
+ ]);
53
+ }
54
+ /**
55
+ * Attach release identity + CI flags onto an existing run_context object.
56
+ * Never overwrites an already-set ``release_tag`` / ``git_sha`` / ``deploy_id``.
57
+ */
58
+ export function enrichRunContextForAnomaly(ctx, env = process.env) {
59
+ if (!(typeof ctx.release_tag === 'string' && ctx.release_tag.trim())) {
60
+ const tag = resolveReleaseTagFallback(env);
61
+ if (tag)
62
+ ctx.release_tag = tag.slice(0, 255);
63
+ }
64
+ if (!(typeof ctx.git_sha === 'string' && ctx.git_sha.trim())) {
65
+ const sha = firstEnv(env, [
66
+ 'NETGREENER_GIT_SHA',
67
+ 'GIT_SHA',
68
+ 'GITHUB_SHA',
69
+ 'BUILD_SOURCEVERSION',
70
+ ]);
71
+ if (sha)
72
+ ctx.git_sha = sha.slice(0, 64);
73
+ }
74
+ if (!(typeof ctx.deploy_id === 'string' && ctx.deploy_id.trim())) {
75
+ const deployId = firstEnv(env, [
76
+ 'NETGREENER_DEPLOY_ID',
77
+ 'DEPLOY_ID',
78
+ 'BUILD_BUILDID',
79
+ ]);
80
+ if (deployId)
81
+ ctx.deploy_id = deployId.slice(0, 255);
82
+ }
83
+ if (detectCi(env)) {
84
+ ctx.is_ci = true;
85
+ ctx.ci = true;
86
+ ctx.continuous_integration = true;
87
+ const provider = resolveCiProvider(env);
88
+ if (provider)
89
+ ctx.ci_provider = provider;
90
+ }
91
+ return ctx;
92
+ }
package/dist/runtime.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { type RuntimeConfig } from './config.js';
2
2
  import { type RunSessionCreatePayload, type UploadResult } from './uploader.js';
3
3
  import { type ObservationExporter } from './exporter.js';
4
- export type FlushKind = 'periodic' | 'shutdown' | 'manual';
4
+ import { type ResolvedRuntimeLifecycle, type RuntimeModePreference } from './lifecycle.js';
5
+ export type FlushKind = 'periodic' | 'shutdown' | 'manual' | 'invoke_end';
5
6
  export type NetGreenerRuntimeOptions = {
6
7
  config?: RuntimeConfig;
7
8
  collector?: string;
@@ -10,12 +11,19 @@ export type NetGreenerRuntimeOptions = {
10
11
  /** MP2: defaults to direct upload exporter (unchanged pipeline). */
11
12
  exporter?: ObservationExporter;
12
13
  onFlush?: (result: UploadResult, payload: RunSessionCreatePayload) => void;
14
+ /**
15
+ * Lifecycle preference (auto | persistent | ephemeral).
16
+ * Default auto — serverless signals → ephemeral flush policy.
17
+ */
18
+ runtimeMode?: RuntimeModePreference;
13
19
  };
14
20
  /**
15
21
  * Process-wide runtime controller: record samples, periodic flush, shutdown flush.
22
+ * Ephemeral lifecycle skips the periodic timer and flushes at invoke/request idle.
16
23
  */
17
24
  export declare class NetGreenerRuntime {
18
25
  readonly config: RuntimeConfig;
26
+ readonly lifecycleInfo: ResolvedRuntimeLifecycle;
19
27
  private readonly aggregator;
20
28
  private readonly collector;
21
29
  private readonly framework;
@@ -26,12 +34,32 @@ export declare class NetGreenerRuntime {
26
34
  private flushing;
27
35
  private started;
28
36
  private outboundInstalled;
37
+ /** In-flight HTTP/task units — gates ephemeral idle flush. */
38
+ private inFlight;
39
+ private invokeFlushScheduled;
40
+ /**
41
+ * Sticky window id until a successful export — preserves idempotency across
42
+ * retry of the same in-memory snapshot (serverless / network retry).
43
+ */
44
+ private stickyWindowId;
29
45
  constructor(opts?: NetGreenerRuntimeOptions);
46
+ get lifecycle(): ResolvedRuntimeLifecycle['lifecycle'];
30
47
  get enabled(): boolean;
31
48
  private ensureOutboundMeter;
32
49
  /** Prefer unwrapped fetch so telemetry uploads are never metered. */
33
50
  private uploadFetch;
34
51
  start(): void;
52
+ /** Mark start of an inbound request/task (ephemeral idle-flush accounting). */
53
+ beginRequest(): void;
54
+ /**
55
+ * Mark end of an inbound request/task. In ephemeral mode, schedules a flush
56
+ * when no requests remain in flight (safe under concurrency).
57
+ */
58
+ endRequest(): void;
59
+ /** Explicit serverless invoke-end flush (Lambda finally / platform adapter). */
60
+ flushForInvokeEnd(): Promise<UploadResult | null>;
61
+ /** Test helper: in-flight request counter. */
62
+ _inFlightForTests(): number;
35
63
  stop(): void;
36
64
  recordHttp(sample: {
37
65
  method: string;