@rasputin-ai/node 0.12.1 → 0.13.1

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 (50) hide show
  1. package/dist/auto-instrumentation/bun-plugin.d.ts.map +1 -1
  2. package/dist/auto-instrumentation/instrument-compiled-esm.d.ts.map +1 -1
  3. package/dist/auto-instrumentation/instrumentation-manifest-registry.d.ts +2 -1
  4. package/dist/auto-instrumentation/instrumentation-manifest-registry.d.ts.map +1 -1
  5. package/dist/auto-instrumentation/node-hooks.d.ts.map +1 -1
  6. package/dist/auto-instrumentation/transform-disk-cache.d.ts.map +1 -1
  7. package/dist/execution-recorder/bind-adaptive-recorder.d.ts +4 -2
  8. package/dist/execution-recorder/bind-adaptive-recorder.d.ts.map +1 -1
  9. package/dist/execution-recorder/execution-recorder-hooks.d.ts +3 -0
  10. package/dist/execution-recorder/execution-recorder-hooks.d.ts.map +1 -1
  11. package/dist/execution-recorder/execution-recorder-types.d.ts +1 -2
  12. package/dist/execution-recorder/execution-recorder-types.d.ts.map +1 -1
  13. package/dist/execution-recorder/execution-recorder.d.ts.map +1 -1
  14. package/dist/execution-recorder/execution-recording-sync.d.ts +2 -2
  15. package/dist/execution-recorder/execution-recording-sync.d.ts.map +1 -1
  16. package/dist/execution-recorder/function-plan.d.ts +3 -1
  17. package/dist/execution-recorder/function-plan.d.ts.map +1 -1
  18. package/dist/function-metrics/bind-function-metrics.d.ts +19 -0
  19. package/dist/function-metrics/bind-function-metrics.d.ts.map +1 -0
  20. package/dist/function-metrics/create-metrics-only-runtime.d.ts +4 -0
  21. package/dist/function-metrics/create-metrics-only-runtime.d.ts.map +1 -0
  22. package/dist/function-metrics/encode-function-metrics-upload.d.ts +14 -0
  23. package/dist/function-metrics/encode-function-metrics-upload.d.ts.map +1 -0
  24. package/dist/function-metrics/function-metric-declaration-registry.d.ts +9 -0
  25. package/dist/function-metrics/function-metric-declaration-registry.d.ts.map +1 -0
  26. package/dist/function-metrics/function-metrics-batches.d.ts +35 -0
  27. package/dist/function-metrics/function-metrics-batches.d.ts.map +1 -0
  28. package/dist/function-metrics/function-metrics-collector.d.ts +45 -0
  29. package/dist/function-metrics/function-metrics-collector.d.ts.map +1 -0
  30. package/dist/function-metrics/function-metrics-exporter.d.ts +23 -0
  31. package/dist/function-metrics/function-metrics-exporter.d.ts.map +1 -0
  32. package/dist/function-metrics/install-function-metric-declaration-sink.d.ts +2 -0
  33. package/dist/function-metrics/install-function-metric-declaration-sink.d.ts.map +1 -0
  34. package/dist/function-metrics/intern-prepared-metrics.d.ts +4 -0
  35. package/dist/function-metrics/intern-prepared-metrics.d.ts.map +1 -0
  36. package/dist/function-metrics/send-function-metrics-batch.d.ts +25 -0
  37. package/dist/function-metrics/send-function-metrics-batch.d.ts.map +1 -0
  38. package/dist/function-metrics/settle-function-metrics.d.ts +5 -0
  39. package/dist/function-metrics/settle-function-metrics.d.ts.map +1 -0
  40. package/dist/index.js +1624 -147
  41. package/dist/instrument/build.js +458 -162
  42. package/dist/instrument/bun.js +454 -132
  43. package/dist/instrument/node.js +452 -132
  44. package/dist/internal.d.ts +2 -0
  45. package/dist/internal.d.ts.map +1 -1
  46. package/dist/internal.js +1600 -139
  47. package/dist/rasputin-init.d.ts +17 -4
  48. package/dist/rasputin-init.d.ts.map +1 -1
  49. package/dist/sdk-meta.d.ts +1 -1
  50. package/package.json +2 -2
package/dist/internal.js CHANGED
@@ -312,9 +312,12 @@ var snapshotInstrumentationManifest = (options = {}) => {
312
312
  if (registry.snapshotCache && registry.snapshotCache.generation === registry.generation && registry.snapshotCache.optionsKey === optionsKey) {
313
313
  return registry.snapshotCache.manifest;
314
314
  }
315
- const functions = [];
316
- const callSites = [];
317
- const destructures = [];
315
+ const functions = new Map(
316
+ registry.prebuilt?.functions.map((fn) => [fn.functionId, fn])
317
+ );
318
+ const callSites = new Map(
319
+ registry.prebuilt?.callSites.map((site) => [site.id, site])
320
+ );
318
321
  const remember = (manifest) => {
319
322
  registry.snapshotCache = {
320
323
  generation: registry.generation,
@@ -327,83 +330,95 @@ var snapshotInstrumentationManifest = (options = {}) => {
327
330
  for (const fn of delta.functions) {
328
331
  const definition = definitionFromEncodedPlan(fn.plan);
329
332
  if (!definition.source) continue;
330
- functions.push({
333
+ if (!fn.metricsDeclaration) {
334
+ throw new Error(`Missing function metrics declaration: ${fn.functionId}`);
335
+ }
336
+ functions.set(definition.functionId, {
337
+ ...functions.get(definition.functionId),
331
338
  functionId: definition.functionId,
332
- source: definition.source,
339
+ source: {
340
+ packageRelativePath: definition.source.packageRelativePath,
341
+ ...definition.source.packageName ? { packageName: definition.source.packageName } : {},
342
+ ...definition.source.repositoryPath ? { repositoryPath: definition.source.repositoryPath } : {}
343
+ },
333
344
  name: fn.name,
334
345
  startLine: fn.startLine,
335
346
  startColumn: fn.startColumn,
336
347
  endLine: fn.endLine,
337
348
  endColumn: fn.endColumn,
338
- params: fn.params,
349
+ metricsDeclaration: fn.metricsDeclaration,
339
350
  ...fn.instrumented === false ? { instrumented: false, skipReason: fn.skipReason } : {}
340
351
  });
341
352
  }
342
353
  for (const site of delta.callSites) {
343
354
  const source = sourceAt(site.filePath, site.line, site.column);
344
355
  if (!source) continue;
345
- callSites.push({
346
- id: stableId(
347
- "cs",
348
- site.callerFunctionId,
349
- source.packageName ?? "",
350
- source.packageRelativePath,
351
- site.line,
352
- site.column
353
- ),
356
+ const id = stableId(
357
+ "cs",
358
+ site.callerFunctionId,
359
+ source.packageName ?? "",
360
+ source.packageRelativePath,
361
+ site.line,
362
+ site.column
363
+ );
364
+ callSites.set(id, {
365
+ id,
354
366
  callerFunctionId: site.callerFunctionId,
355
367
  calleeName: site.calleeName,
356
368
  calleeText: site.calleeText,
357
- source,
358
369
  line: site.line,
359
370
  column: site.column,
360
371
  endLine: site.endLine,
361
372
  endColumn: site.endColumn,
362
- resultBinding: site.resultBinding,
363
- argIdentifiers: site.argIdentifiers
364
- });
365
- }
366
- for (const destructure of delta.destructures) {
367
- const source = sourceAt(destructure.filePath, destructure.line, destructure.column);
368
- if (!source) continue;
369
- destructures.push({
370
- callerFunctionId: destructure.callerFunctionId,
371
- sourceParam: destructure.sourceParam,
372
- source,
373
- line: destructure.line,
374
- column: destructure.column,
375
- binding: destructure.binding
373
+ resultBinding: site.resultBinding
376
374
  });
377
375
  }
378
376
  }
379
377
  if (registry.prebuilt && registry.files.size === 0) {
380
- const prebuilt = registry.prebuilt;
381
- if (!options.sourceRoot && !options.sourceRoots) return remember(prebuilt);
378
+ if (!options.sourceRoot && !options.sourceRoots) return remember(registry.prebuilt);
382
379
  return remember({
383
- ...prebuilt,
380
+ ...registry.prebuilt,
384
381
  sourceRoots: {
385
382
  ...options.sourceRoot ? { default: options.sourceRoot } : {},
386
383
  packages: { ...options.sourceRoots ?? {} }
387
384
  }
388
385
  });
389
386
  }
390
- if (functions.length === 0 && callSites.length === 0 && destructures.length === 0) {
387
+ if (functions.size === 0 && callSites.size === 0) {
391
388
  return remember(void 0);
392
389
  }
393
- const packages = { ...options.sourceRoots ?? {} };
390
+ const packages = { ...registry.prebuilt?.sourceRoots?.packages, ...options.sourceRoots };
391
+ const sourceRoot = options.sourceRoot ?? registry.prebuilt?.sourceRoots?.default;
394
392
  return remember({
395
393
  schema_version: INSTRUMENTATION_MANIFEST_SCHEMA_VERSION,
396
- ...options.sourceRoot || Object.keys(packages).length > 0 ? {
394
+ ...sourceRoot || Object.keys(packages).length > 0 ? {
397
395
  sourceRoots: {
398
- ...options.sourceRoot ? { default: options.sourceRoot } : {},
396
+ ...sourceRoot ? { default: sourceRoot } : {},
399
397
  packages
400
398
  }
401
399
  } : {},
402
- functions,
403
- callSites,
404
- destructures
400
+ functions: [...functions.values()],
401
+ callSites: [...callSites.values()]
405
402
  });
406
403
  };
404
+ var collectParamsByFunctionId = () => {
405
+ const registry = getRegistry();
406
+ if (registry.paramsCache?.generation === registry.generation) return registry.paramsCache.params;
407
+ const params = /* @__PURE__ */ new Map();
408
+ for (const delta of registry.files.values()) {
409
+ for (const fn of delta.functions) {
410
+ if (!fn.params || fn.params.length === 0) continue;
411
+ const definition = definitionFromEncodedPlan(fn.plan);
412
+ params.set(definition.functionId, fn.params);
413
+ }
414
+ }
415
+ registry.paramsCache = { generation: registry.generation, params };
416
+ return params;
417
+ };
418
+ var paramsForRuntimeFunction = (functionId) => {
419
+ const params = collectParamsByFunctionId().get(functionId);
420
+ return params && params.length > 0 ? params : void 0;
421
+ };
407
422
  var markInstrumentationManifestUploaded = (generation) => {
408
423
  const registry = getRegistry();
409
424
  if (registry.generation === generation) registry.uploadedGeneration = generation;
@@ -633,13 +648,318 @@ var scheduleInstrumentationManifestUpload = (options) => {
633
648
  };
634
649
 
635
650
  // src/execution-recorder/execution-recorder.ts
636
- import { AsyncLocalStorage } from "node:async_hooks";
651
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
637
652
  import {
653
+ functionMetricsTraceDeclaration as functionMetricsTraceDeclaration3,
638
654
  rasputinOmitted,
639
655
  rasputinTagKind,
656
+ runtimeFunctionId as runtimeFunctionId3
657
+ } from "@rasputin-ai/core";
658
+
659
+ // src/function-metrics/create-metrics-only-runtime.ts
660
+ import { AsyncLocalStorage } from "node:async_hooks";
661
+ import {
662
+ functionMetricsTraceDeclaration as functionMetricsTraceDeclaration2,
640
663
  runtimeFunctionId as runtimeFunctionId2
641
664
  } from "@rasputin-ai/core";
642
665
 
666
+ // src/execution-recorder/error-observation.ts
667
+ var bindings = /* @__PURE__ */ new WeakMap();
668
+ var mintErrorObservation = (binding) => {
669
+ const observation = Object.freeze(/* @__PURE__ */ Object.create(null));
670
+ bindings.set(observation, binding);
671
+ return observation;
672
+ };
673
+ var bindingForObservation = (value) => {
674
+ if (typeof value !== "object" || value === null) return void 0;
675
+ return bindings.get(value);
676
+ };
677
+ var inertErrorObservation = () => {
678
+ return Object.freeze(/* @__PURE__ */ Object.create(null));
679
+ };
680
+
681
+ // src/execution-recorder/execution-identity.ts
682
+ var MAX_EXECUTION_TYPE_KEY_LENGTH = 256;
683
+ var NAMED_KINDS = /* @__PURE__ */ new Set(["job", "scheduled", "custom", "serverless"]);
684
+ var trimmed = (value) => typeof value === "string" ? value.trim() : "";
685
+ var boundedKey = (key) => {
686
+ return key.length > 0 && key.length <= MAX_EXECUTION_TYPE_KEY_LENGTH ? key : void 0;
687
+ };
688
+ var executionTypeKey = (metadata) => {
689
+ if (metadata.kind === "http") {
690
+ const method = trimmed(metadata.request?.method).toUpperCase();
691
+ const route = trimmed(metadata.request?.route);
692
+ if (!method || !route) return void 0;
693
+ if (route.includes("?") || route.includes("://")) return void 0;
694
+ return boundedKey(`http:${method}:${route}`);
695
+ }
696
+ if (!NAMED_KINDS.has(metadata.kind)) return void 0;
697
+ const name = trimmed(metadata.name);
698
+ if (!name) return void 0;
699
+ return boundedKey(`${metadata.kind}:${name}`);
700
+ };
701
+ var isHttpClientErrorStatus = (status) => {
702
+ return typeof status === "number" && Number.isFinite(status) && status >= 400 && status < 500;
703
+ };
704
+
705
+ // src/execution-recorder/function-plan.ts
706
+ var EVENT_PAIR_BASE_ESTIMATED_BYTES = 512;
707
+ var estimatedCallBytesFor = (functionId) => EVENT_PAIR_BASE_ESTIMATED_BYTES + Buffer.byteLength(functionId, "utf8") * 2;
708
+
709
+ // src/function-metrics/function-metric-declaration-registry.ts
710
+ var REGISTRY_SYMBOL = Symbol.for("rasputin.functionMetrics.declarations.v1");
711
+ var getRegistry2 = () => {
712
+ const existing = Reflect.get(globalThis, REGISTRY_SYMBOL);
713
+ if (typeof existing === "object" && existing !== null) {
714
+ const byRuntimeId = Reflect.get(existing, "byRuntimeId");
715
+ if (byRuntimeId instanceof Map) return { byRuntimeId };
716
+ }
717
+ const registry = {
718
+ byRuntimeId: /* @__PURE__ */ new Map()
719
+ };
720
+ Reflect.set(globalThis, REGISTRY_SYMBOL, registry);
721
+ return registry;
722
+ };
723
+ var registerFunctionMetricDeclarations = (declarations) => {
724
+ const { byRuntimeId } = getRegistry2();
725
+ for (const declaration of declarations) {
726
+ if (byRuntimeId.has(declaration.runtime_id)) continue;
727
+ byRuntimeId.set(declaration.runtime_id, declaration);
728
+ }
729
+ };
730
+ var functionMetricDeclarationFor = (runtimeId) => getRegistry2().byRuntimeId.get(runtimeId);
731
+
732
+ // src/function-metrics/intern-prepared-metrics.ts
733
+ import { functionMetricsTraceDeclaration } from "@rasputin-ai/core";
734
+ var internPreparedMetrics = (collector, plan) => {
735
+ if (plan.excluded) return void 0;
736
+ if (plan.metricsHandle !== void 0) return plan.metricsHandle;
737
+ const declaration = plan.metricsDeclaration ?? functionMetricDeclarationFor(plan.functionId) ?? functionMetricsTraceDeclaration({
738
+ runtimeId: plan.functionId
739
+ });
740
+ plan.metricsDeclaration = declaration;
741
+ const handle = collector.internDeclaration(declaration);
742
+ if (handle !== void 0) plan.metricsHandle = handle;
743
+ return handle;
744
+ };
745
+
746
+ // src/function-metrics/settle-function-metrics.ts
747
+ var finishMetricsCall = (collector, functionHandle, executionHandle, startedNs, failed, endedNs) => {
748
+ try {
749
+ collector.finishCall(functionHandle, executionHandle, startedNs, failed, endedNs);
750
+ } catch {
751
+ }
752
+ };
753
+ var thenOf = (value) => {
754
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
755
+ return void 0;
756
+ }
757
+ if (!("then" in value)) return void 0;
758
+ const then = value.then;
759
+ if (typeof then !== "function") return void 0;
760
+ return (onFulfilled, onRejected) => {
761
+ Reflect.apply(then, value, [onFulfilled, onRejected]);
762
+ };
763
+ };
764
+ var startMetricsCall = (collector, functionHandle, executionHandle, startedNs) => {
765
+ if (!collector || functionHandle === void 0) return void 0;
766
+ try {
767
+ return collector.startCall(functionHandle, executionHandle, startedNs);
768
+ } catch {
769
+ return void 0;
770
+ }
771
+ };
772
+ var completeMetricsResult = (collector, functionHandle, executionHandle, startedNs, value) => {
773
+ const then = thenOf(value);
774
+ if (!then) {
775
+ finishMetricsCall(collector, functionHandle, executionHandle, startedNs, false);
776
+ return;
777
+ }
778
+ try {
779
+ then(
780
+ () => finishMetricsCall(collector, functionHandle, executionHandle, startedNs, false),
781
+ () => finishMetricsCall(collector, functionHandle, executionHandle, startedNs, true)
782
+ );
783
+ } catch {
784
+ finishMetricsCall(collector, functionHandle, executionHandle, startedNs, true);
785
+ }
786
+ };
787
+
788
+ // src/function-metrics/create-metrics-only-runtime.ts
789
+ var emptyStats = () => ({
790
+ functionCallsObserved: 0,
791
+ functionCallsCaptured: 0,
792
+ functionCallsExcluded: 0,
793
+ serializedValues: 0,
794
+ serializedValueNodes: 0,
795
+ serializedValueBytes: 0,
796
+ errorSnapshots: 0,
797
+ successfulExecutionsDiscarded: 0,
798
+ truncatedEvents: 0,
799
+ repeatedCallsSuppressed: 0,
800
+ activeExecutions: 0,
801
+ peakActiveExecutions: 0,
802
+ activeEstimatedBytes: 0,
803
+ peakActiveEstimatedBytes: 0,
804
+ memoryPressureExecutions: 0,
805
+ memoryPressureDegradations: 0,
806
+ valuesDroppedByMemoryBudget: 0,
807
+ eventsDroppedByMemoryBudget: 0,
808
+ partialErrorSnapshots: 0,
809
+ measuredExecutions: 0,
810
+ totalInlineWallTimeMs: 0,
811
+ maxInlineWallTimeMs: 0,
812
+ journalPoolHits: 0,
813
+ journalPoolMisses: 0,
814
+ journalPoolSize: 0,
815
+ journalAllocatedCapacity: 0,
816
+ attributionDegradations: 0,
817
+ adaptiveLightExecutions: 0,
818
+ adaptiveFullExecutions: 0,
819
+ adaptiveActivations: 0,
820
+ adaptiveNotifyFailures: 0,
821
+ adaptiveRefreshFailures: 0,
822
+ lastAdaptiveFailureKind: null
823
+ });
824
+ var mergeMetadata = (store, metadata) => {
825
+ if (metadata.kind) store.execution.kind = metadata.kind;
826
+ if (metadata.name !== void 0) store.execution.name = metadata.name;
827
+ if (metadata.request) {
828
+ store.execution.request = { ...store.execution.request, ...metadata.request };
829
+ }
830
+ };
831
+ var definitionOf = (input) => {
832
+ if (typeof input === "string")
833
+ return { name: input, functionId: runtimeFunctionId2({ name: input }) };
834
+ return input;
835
+ };
836
+ var bindExecutionHandle = (collector, store) => {
837
+ store.executionHandle = collector.internExecutionKey(executionTypeKey(store.execution));
838
+ };
839
+ var runWithMetrics = (collector, plan, executionHandle, callback) => {
840
+ const functionHandle = internPreparedMetrics(collector, plan);
841
+ const startedNs = startMetricsCall(collector, functionHandle, executionHandle);
842
+ try {
843
+ const result = callback();
844
+ if (startedNs !== void 0 && functionHandle !== void 0 && executionHandle !== void 0) {
845
+ completeMetricsResult(collector, functionHandle, executionHandle, startedNs, result);
846
+ }
847
+ return result;
848
+ } catch (error) {
849
+ if (startedNs !== void 0 && functionHandle !== void 0 && executionHandle !== void 0) {
850
+ finishMetricsCall(collector, functionHandle, executionHandle, startedNs, true);
851
+ }
852
+ throw error;
853
+ }
854
+ };
855
+ var metricsHandle = (collector, plan, executionHandle) => {
856
+ const functionHandle = internPreparedMetrics(collector, plan);
857
+ const startedNs = startMetricsCall(collector, functionHandle, executionHandle);
858
+ if (startedNs === void 0 || functionHandle === void 0 || executionHandle === void 0) {
859
+ return passthroughHandle();
860
+ }
861
+ let failed = false;
862
+ let settled = false;
863
+ return {
864
+ leave: (value) => value,
865
+ fail: () => {
866
+ failed = true;
867
+ },
868
+ end: () => {
869
+ if (settled) return;
870
+ settled = true;
871
+ finishMetricsCall(collector, functionHandle, executionHandle, startedNs, failed);
872
+ },
873
+ run: function __rasputinHandleRun__4(callback) {
874
+ return runExactlyOnce((invoke) => invoke(), callback);
875
+ },
876
+ suspend: (value) => value,
877
+ resume: (value) => value
878
+ };
879
+ };
880
+ var createMetricsOnlyRuntime = (collector) => {
881
+ const storage = new AsyncLocalStorage();
882
+ const preparedModules = /* @__PURE__ */ new WeakMap();
883
+ let nextRuntimePlanId = 1;
884
+ const currentHandle = () => storage.getStore()?.executionHandle;
885
+ const planFor = (definition) => ({
886
+ runtimePlanId: nextRuntimePlanId++,
887
+ definition,
888
+ functionId: definition.functionId,
889
+ excluded: false,
890
+ estimatedCallBytes: estimatedCallBytesFor(definition.functionId),
891
+ omitCallValues: false,
892
+ metricsDeclaration: functionMetricDeclarationFor(definition.functionId) ?? functionMetricsTraceDeclaration2({
893
+ runtimeId: definition.functionId
894
+ })
895
+ });
896
+ const prepareEncoded = (plans) => {
897
+ const cached = preparedModules.get(plans);
898
+ if (cached) return cached;
899
+ const prepared = plans.map((encoded) => {
900
+ const definition = definitionFromEncodedPlan(encoded);
901
+ return {
902
+ ...planFor(definition),
903
+ omitCallValues: encodedPlanOmitsCallValues(encoded),
904
+ metricsDeclaration: functionMetricDeclarationFor(definition.functionId)
905
+ };
906
+ });
907
+ preparedModules.set(plans, prepared);
908
+ return prepared;
909
+ };
910
+ const runPrepared = (plan, _args, callback) => runWithMetrics(collector, plan, currentHandle(), callback);
911
+ function trace(input, fn) {
912
+ const definition = typeof input === "string" ? definitionOf(input) : { ...input, functionId: runtimeFunctionId2(input) };
913
+ const plan = planFor(definition);
914
+ return function __rasputinHandleRun__4(...args) {
915
+ if (new.target) {
916
+ throw new TypeError("execution.trace() wraps function calls, not constructors");
917
+ }
918
+ return runPrepared(plan, args, () => fn.apply(this, args));
919
+ };
920
+ }
921
+ return {
922
+ createScope: (metadata) => {
923
+ const store = {
924
+ execution: {
925
+ ...metadata,
926
+ ...metadata.request ? { request: { ...metadata.request } } : {}
927
+ },
928
+ executionHandle: void 0
929
+ };
930
+ bindExecutionHandle(collector, store);
931
+ return {
932
+ run: (callback) => storage.run(store, callback),
933
+ getErrorState: () => void 0,
934
+ observeError: () => inertErrorObservation(),
935
+ finish: (next) => {
936
+ if (next) {
937
+ mergeMetadata(store, next);
938
+ bindExecutionHandle(collector, store);
939
+ }
940
+ },
941
+ mergeMetadata: (next) => {
942
+ mergeMetadata(store, next);
943
+ bindExecutionHandle(collector, store);
944
+ }
945
+ };
946
+ },
947
+ getErrorState: () => void 0,
948
+ runFunction: (definition, args, callback) => runPrepared(planFor(definitionOf(definition)), args, callback),
949
+ runFunctionPlans: (plans, planIndex, args, callback) => {
950
+ const plan = prepareEncoded(plans)[planIndex];
951
+ return plan ? runPrepared(plan, args, callback) : callback();
952
+ },
953
+ prepareFunctionPlans: (plans) => prepareEncoded(plans),
954
+ runPreparedFunction: runPrepared,
955
+ enterPreparedFunction: (plan) => metricsHandle(collector, plan, currentHandle()),
956
+ trace,
957
+ getStats: () => emptyStats(),
958
+ close: () => {
959
+ }
960
+ };
961
+ };
962
+
643
963
  // src/execution-recorder/adaptive-recording-options.ts
644
964
  var DEFAULT_FULL_CAPTURE_DURATION_MS = 24 * 60 * 60 * 1e3;
645
965
  var MIN_FULL_CAPTURE_DURATION_MS = 1e3;
@@ -716,45 +1036,6 @@ var createDynamicDurationSampleBuckets = (options) => {
716
1036
  };
717
1037
  };
718
1038
 
719
- // src/execution-recorder/error-observation.ts
720
- var bindings = /* @__PURE__ */ new WeakMap();
721
- var mintErrorObservation = (binding) => {
722
- const observation = Object.freeze(/* @__PURE__ */ Object.create(null));
723
- bindings.set(observation, binding);
724
- return observation;
725
- };
726
- var bindingForObservation = (value) => {
727
- if (typeof value !== "object" || value === null) return void 0;
728
- return bindings.get(value);
729
- };
730
- var inertErrorObservation = () => {
731
- return Object.freeze(/* @__PURE__ */ Object.create(null));
732
- };
733
-
734
- // src/execution-recorder/execution-identity.ts
735
- var MAX_EXECUTION_TYPE_KEY_LENGTH = 256;
736
- var NAMED_KINDS = /* @__PURE__ */ new Set(["job", "scheduled", "custom", "serverless"]);
737
- var trimmed = (value) => typeof value === "string" ? value.trim() : "";
738
- var boundedKey = (key) => {
739
- return key.length > 0 && key.length <= MAX_EXECUTION_TYPE_KEY_LENGTH ? key : void 0;
740
- };
741
- var executionTypeKey = (metadata) => {
742
- if (metadata.kind === "http") {
743
- const method = trimmed(metadata.request?.method).toUpperCase();
744
- const route = trimmed(metadata.request?.route);
745
- if (!method || !route) return void 0;
746
- if (route.includes("?") || route.includes("://")) return void 0;
747
- return boundedKey(`http:${method}:${route}`);
748
- }
749
- if (!NAMED_KINDS.has(metadata.kind)) return void 0;
750
- const name = trimmed(metadata.name);
751
- if (!name) return void 0;
752
- return boundedKey(`${metadata.kind}:${name}`);
753
- };
754
- var isHttpClientErrorStatus = (status) => {
755
- return typeof status === "number" && Number.isFinite(status) && status >= 400 && status < 500;
756
- };
757
-
758
1039
  // src/execution-recorder/execution-journal.ts
759
1040
  var KIND_ENTER = 1;
760
1041
  var KIND_EXIT = 2;
@@ -1154,10 +1435,6 @@ var ExecutionJournalPool = class {
1154
1435
  }
1155
1436
  };
1156
1437
 
1157
- // src/execution-recorder/function-plan.ts
1158
- var EVENT_PAIR_BASE_ESTIMATED_BYTES = 512;
1159
- var estimatedCallBytesFor = (functionId) => EVENT_PAIR_BASE_ESTIMATED_BYTES + Buffer.byteLength(functionId, "utf8") * 2;
1160
-
1161
1438
  // src/execution-recorder/publish-runtime-state.ts
1162
1439
  var measured = (value) => typeof value === "number";
1163
1440
  var eventsAreFullyTimed = (events) => {
@@ -2656,7 +2933,7 @@ var manualFunctionDefinition = (value) => {
2656
2933
  ...located?.[4] ? { column: Number(located[4]) } : {}
2657
2934
  } : void 0;
2658
2935
  const definition = { name, ...source ? { source } : {} };
2659
- return { ...definition, functionId: runtimeFunctionId2(definition) };
2936
+ return { ...definition, functionId: runtimeFunctionId3(definition) };
2660
2937
  };
2661
2938
  var normalizeFunctionDefinition = (value) => typeof value === "string" ? manualFunctionDefinition(value) : value;
2662
2939
  var elapsedMs2 = (startedAtNs, endedAtNs = process.hrtime.bigint()) => Number(endedAtNs - startedAtNs) / 1e6;
@@ -2697,7 +2974,7 @@ var observeRecordedCallback = function __rasputinHandleRun__3(recording, recorde
2697
2974
  recordExitWork(phaseTimingEnabled ? process.hrtime.bigint() : recorderStartedAtNs);
2698
2975
  return result;
2699
2976
  };
2700
- var emptyStats = {
2977
+ var emptyStats2 = {
2701
2978
  functionCallsObserved: 0,
2702
2979
  functionCallsCaptured: 0,
2703
2980
  functionCallsExcluded: 0,
@@ -2758,7 +3035,7 @@ var noOpExecution = {
2758
3035
  resume: (value) => value
2759
3036
  }),
2760
3037
  trace: (_functionId, fn) => fn,
2761
- getStats: () => ({ ...emptyStats }),
3038
+ getStats: () => ({ ...emptyStats2 }),
2762
3039
  close: () => {
2763
3040
  }
2764
3041
  };
@@ -2792,7 +3069,16 @@ var newSuppression = (group, parentCallId, startedAtNs, endedAtNs, timed) => {
2792
3069
  var EMPTY_POLICY_SNAPSHOT = /* @__PURE__ */ new Map();
2793
3070
  var EMPTY_SESSION_SNAPSHOT = /* @__PURE__ */ new Map();
2794
3071
  var createExecutionRecorder = (options, hooks = {}) => {
2795
- if (!options?.enabled) return noOpExecution;
3072
+ if (!options?.enabled) {
3073
+ return hooks.functionMetrics ? createMetricsOnlyRuntime(hooks.functionMetrics) : noOpExecution;
3074
+ }
3075
+ const functionMetrics = hooks.functionMetrics;
3076
+ const bindMetricsExecution = (recording) => {
3077
+ if (!functionMetrics) return;
3078
+ recording.metricsExecutionHandle = functionMetrics.internExecutionKey(
3079
+ executionTypeKey(recording.execution)
3080
+ );
3081
+ };
2796
3082
  warnIfMissingAsyncContextFrame();
2797
3083
  const adaptiveEnabled = options.adaptive?.enabled === true;
2798
3084
  const fullCaptureDurationMs = sanitizeFullCaptureDurationMs(
@@ -2814,7 +3100,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
2814
3100
  if (!key) return false;
2815
3101
  return keyIsActive(snapshot, key, atMs);
2816
3102
  };
2817
- const storage = new AsyncLocalStorage();
3103
+ const storage = new AsyncLocalStorage2();
2818
3104
  const currentStore = () => {
2819
3105
  try {
2820
3106
  return storage.getStore();
@@ -3065,7 +3351,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
3065
3351
  functionId: definition.functionId,
3066
3352
  excluded: excludesSource(definition),
3067
3353
  estimatedCallBytes: estimatedCallBytesFor(definition.functionId),
3068
- omitCallValues: false
3354
+ omitCallValues: false,
3355
+ metricsDeclaration: functionMetricDeclarationFor(definition.functionId)
3069
3356
  });
3070
3357
  internedPlans.set(definition.functionId, plan);
3071
3358
  return plan;
@@ -3075,13 +3362,16 @@ var createExecutionRecorder = (options, hooks = {}) => {
3075
3362
  if (cached) return cached;
3076
3363
  const prepared = plans.map((encoded) => {
3077
3364
  const definition = definitionFromEncodedPlan(encoded);
3365
+ const params = paramsForRuntimeFunction(definition.functionId);
3366
+ const withParams = params && params.length > 0 ? { ...definition, params } : definition;
3078
3367
  return storePlan({
3079
3368
  runtimePlanId: nextRuntimePlanId++,
3080
- definition,
3081
- functionId: definition.functionId,
3082
- excluded: excludesSource(definition),
3083
- estimatedCallBytes: estimatedCallBytesFor(definition.functionId),
3084
- omitCallValues: encodedPlanOmitsCallValues(encoded)
3369
+ definition: withParams,
3370
+ functionId: withParams.functionId,
3371
+ excluded: excludesSource(withParams),
3372
+ estimatedCallBytes: estimatedCallBytesFor(withParams.functionId),
3373
+ omitCallValues: encodedPlanOmitsCallValues(encoded),
3374
+ metricsDeclaration: functionMetricDeclarationFor(withParams.functionId)
3085
3375
  });
3086
3376
  });
3087
3377
  preparedModules.set(plans, prepared);
@@ -3600,7 +3890,10 @@ var createExecutionRecorder = (options, hooks = {}) => {
3600
3890
  }
3601
3891
  const recorderStartedAtNs = process.hrtime.bigint();
3602
3892
  recording.finished = true;
3603
- if (metadata) mergeExecutionMetadata(recording.execution, metadata);
3893
+ if (metadata) {
3894
+ mergeExecutionMetadata(recording.execution, metadata);
3895
+ bindMetricsExecution(recording);
3896
+ }
3604
3897
  stats.activeExecutions = Math.max(0, stats.activeExecutions - 1);
3605
3898
  if (recording.runFailed && !recording.hasError) {
3606
3899
  retainFailure(recording);
@@ -3669,6 +3962,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
3669
3962
  sessionCaptureSnapshot
3670
3963
  };
3671
3964
  if (identityComplete) tryAdmitLiveSession(recording);
3965
+ bindMetricsExecution(recording);
3672
3966
  stats.activeExecutions++;
3673
3967
  stats.peakActiveExecutions = Math.max(stats.peakActiveExecutions, stats.activeExecutions);
3674
3968
  liveRecordings.push(recording);
@@ -3720,6 +4014,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
3720
4014
  try {
3721
4015
  mergeExecutionMetadata(recording.execution, nextMetadata);
3722
4016
  completeIdentityFromSnapshot(recording);
4017
+ bindMetricsExecution(recording);
3723
4018
  } catch {
3724
4019
  }
3725
4020
  }
@@ -3736,9 +4031,22 @@ var createExecutionRecorder = (options, hooks = {}) => {
3736
4031
  }
3737
4032
  };
3738
4033
  const runPreparedFunctionFromStore = function __rasputinHandleRun__4(store, plan, args, callback, omitValues) {
4034
+ const functionHandle = functionMetrics && !plan.excluded ? internPreparedMetrics(functionMetrics, plan) : void 0;
4035
+ const executionHandle = store?.recording.metricsExecutionHandle;
4036
+ const startedNs = startMetricsCall(functionMetrics, functionHandle, executionHandle);
4037
+ const settle = (value, failed) => {
4038
+ if (!functionMetrics || startedNs === void 0 || functionHandle === void 0 || executionHandle === void 0) {
4039
+ return;
4040
+ }
4041
+ if (failed) {
4042
+ finishMetricsCall(functionMetrics, functionHandle, executionHandle, startedNs, true);
4043
+ return;
4044
+ }
4045
+ completeMetricsResult(functionMetrics, functionHandle, executionHandle, startedNs, value);
4046
+ };
3739
4047
  let startedCallback = false;
3740
4048
  try {
3741
- return runPreparedFunctionFromStoreInner(
4049
+ const result = runPreparedFunctionFromStoreInner(
3742
4050
  store,
3743
4051
  plan,
3744
4052
  args,
@@ -3748,9 +4056,16 @@ var createExecutionRecorder = (options, hooks = {}) => {
3748
4056
  },
3749
4057
  omitValues
3750
4058
  );
4059
+ settle(result, false);
4060
+ return result;
3751
4061
  } catch (error) {
3752
- if (startedCallback) throw error;
3753
- return callback();
4062
+ if (startedCallback) {
4063
+ settle(error, true);
4064
+ throw error;
4065
+ }
4066
+ const result = callback();
4067
+ settle(result, false);
4068
+ return result;
3754
4069
  }
3755
4070
  };
3756
4071
  const runPreparedFunctionFromStoreInner = function __rasputinHandleRun__4(store, plan, args, callback, omitValues) {
@@ -3955,6 +4270,11 @@ var createExecutionRecorder = (options, hooks = {}) => {
3955
4270
  this.group = group;
3956
4271
  this.captureDroppedThrow = captureDroppedThrow;
3957
4272
  this.callerClaimed = false;
4273
+ this.metricsOpen = false;
4274
+ this.metricsFailed = false;
4275
+ this.metricsFunctionHandle = 0;
4276
+ this.metricsExecutionHandle = 0;
4277
+ this.metricsStartedNs = 0n;
3958
4278
  }
3959
4279
  claimCaller() {
3960
4280
  if (this.callerClaimed || !durationSamplingEnabled || !this.plan) return;
@@ -3989,6 +4309,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
3989
4309
  try {
3990
4310
  if (this.status === "failed") return;
3991
4311
  this.status = "failed";
4312
+ this.metricsFailed = true;
3992
4313
  if (this.mode === "captured") writeCapturedThrow(this, error);
3993
4314
  else if (this.mode === "suppressed" && this.plan) {
3994
4315
  captureCompletedThrow(
@@ -4017,18 +4338,38 @@ var createExecutionRecorder = (options, hooks = {}) => {
4017
4338
  }
4018
4339
  }
4019
4340
  end() {
4341
+ let endedAtNs;
4342
+ if (this.metricsOpen && functionMetrics) {
4343
+ this.metricsOpen = false;
4344
+ try {
4345
+ endedAtNs = readCallClock();
4346
+ finishMetricsCall(
4347
+ functionMetrics,
4348
+ this.metricsFunctionHandle,
4349
+ this.metricsExecutionHandle,
4350
+ this.metricsStartedNs,
4351
+ this.metricsFailed,
4352
+ endedAtNs
4353
+ );
4354
+ } catch {
4355
+ }
4356
+ }
4020
4357
  if (this.mode === "expired") return;
4021
4358
  try {
4022
4359
  if (this.status !== "failed") {
4023
4360
  if (this.mode === "captured") {
4024
- writeCapturedExit(this, this.status === "left" ? this.pendingReturn : void 0);
4361
+ writeCapturedExit(
4362
+ this,
4363
+ this.status === "left" ? this.pendingReturn : void 0,
4364
+ endedAtNs
4365
+ );
4025
4366
  } else if (this.mode === "suppressed" && this.group) {
4026
4367
  recordSuppressedCall(
4027
4368
  this.recording,
4028
4369
  this.group,
4029
4370
  this.parentCallId,
4030
4371
  this.startedAtNs,
4031
- this.timed ? readCallClock() : 0n,
4372
+ this.timed ? endedAtNs ?? readCallClock() : 0n,
4032
4373
  this.timed
4033
4374
  );
4034
4375
  } else if (this.mode === "dropped") {
@@ -4101,9 +4442,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
4101
4442
  const expectStore = (frame, expected) => {
4102
4443
  if (currentStore() !== expected && frame.plan) degradeAttribution(frame.recording, frame.plan);
4103
4444
  };
4104
- const writeCapturedExit = (frame, value) => {
4445
+ const writeCapturedExit = (frame, value, completedAtNs) => {
4105
4446
  if (!frame.recording.journal) return;
4106
- const endedAtNs = frame.timed ? readCallClock() : void 0;
4447
+ const endedAtNs = frame.timed ? completedAtNs ?? readCallClock() : void 0;
4107
4448
  const returnValue = exitPayload(frame.recording, frame.omitCallValues, value);
4108
4449
  if (endedAtNs !== void 0) {
4109
4450
  frame.recording.journal.finishCall(
@@ -4138,6 +4479,24 @@ var createExecutionRecorder = (options, hooks = {}) => {
4138
4479
  stats.functionCallsCaptured++;
4139
4480
  capturedError.commit();
4140
4481
  };
4482
+ const armCallFrameMetrics = (frame, plan) => {
4483
+ if (!functionMetrics || plan.excluded) return;
4484
+ const functionHandle = internPreparedMetrics(functionMetrics, plan);
4485
+ const reuseStart = frame.timed && frame.startedAtNs !== 0n ? frame.startedAtNs : void 0;
4486
+ const startedNs = startMetricsCall(
4487
+ functionMetrics,
4488
+ functionHandle,
4489
+ frame.recording.metricsExecutionHandle,
4490
+ reuseStart
4491
+ );
4492
+ if (startedNs === void 0 || functionHandle === void 0) return;
4493
+ const executionHandle = frame.recording.metricsExecutionHandle;
4494
+ if (executionHandle === void 0) return;
4495
+ frame.metricsOpen = true;
4496
+ frame.metricsFunctionHandle = functionHandle;
4497
+ frame.metricsExecutionHandle = executionHandle;
4498
+ frame.metricsStartedNs = startedNs;
4499
+ };
4141
4500
  const activateUncaptured = (mode, recording, parentStore, plan, args, omitCallValues, parentCallId, startedAtNs, timed, group, captureDroppedThrow) => {
4142
4501
  const frame = new CallFrame(
4143
4502
  mode,
@@ -4156,6 +4515,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4156
4515
  );
4157
4516
  frame.claimCaller();
4158
4517
  enterStore(frame, parentStore);
4518
+ armCallFrameMetrics(frame, plan);
4159
4519
  return frame;
4160
4520
  };
4161
4521
  const enterPreparedFunctionFromStore = (store, plan, args, omitValues) => {
@@ -4167,7 +4527,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4167
4527
  if (store.recording.finished) {
4168
4528
  if (!store.recording.budgetExpired && !store.recording.evicted) return noopHandle2;
4169
4529
  const expiredStore = { recording: store.recording };
4170
- return new CallFrame(
4530
+ const expired = new CallFrame(
4171
4531
  "expired",
4172
4532
  store.recording,
4173
4533
  expiredStore,
@@ -4182,6 +4542,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4182
4542
  void 0,
4183
4543
  false
4184
4544
  );
4545
+ armCallFrameMetrics(expired, plan);
4546
+ return expired;
4185
4547
  }
4186
4548
  stats.functionCallsObserved++;
4187
4549
  const recording = store.recording;
@@ -4206,6 +4568,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4206
4568
  false
4207
4569
  );
4208
4570
  enterStore(frame, excludedStore);
4571
+ armCallFrameMetrics(frame, plan);
4209
4572
  return frame;
4210
4573
  }
4211
4574
  recording.inFlightCalls++;
@@ -4319,6 +4682,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4319
4682
  false
4320
4683
  );
4321
4684
  enterStore(captured, callStore);
4685
+ armCallFrameMetrics(captured, plan);
4322
4686
  return captured;
4323
4687
  };
4324
4688
  const runPreparedFunction = (plan, args, callback, omitValues) => {
@@ -4359,8 +4723,11 @@ var createExecutionRecorder = (options, hooks = {}) => {
4359
4723
  };
4360
4724
  const prepareFunctionPlans = (plans) => preparedPlansFor(plans);
4361
4725
  function trace(input, fn) {
4362
- const definition = typeof input === "string" ? manualFunctionDefinition(input) : { ...input, functionId: runtimeFunctionId2(input) };
4726
+ const definition = typeof input === "string" ? manualFunctionDefinition(input) : { ...input, functionId: runtimeFunctionId3(input) };
4363
4727
  const plan = preparePlan(definition);
4728
+ plan.metricsDeclaration ??= functionMetricsTraceDeclaration3({
4729
+ runtimeId: definition.functionId
4730
+ });
4364
4731
  return function __rasputinHandleRun__4(...args) {
4365
4732
  if (new.target) {
4366
4733
  throw new TypeError("execution.trace() wraps function calls, not constructors");
@@ -4653,10 +5020,9 @@ var abortFrom = (parent, child) => {
4653
5020
  return () => parent.removeEventListener("abort", onAbort);
4654
5021
  };
4655
5022
  var createExecutionRecordingCoordinator = (options) => {
4656
- const environment = trimmed2(options.environment);
5023
+ const environment = options.environment;
4657
5024
  const nowMs = () => options.nowMs?.() ?? Date.now();
4658
5025
  const fetchFn = options.fetch ?? defaultIngestFetch();
4659
- const networkEnabled = environment.length > 0;
4660
5026
  const instanceId = crypto.randomUUID();
4661
5027
  const startedAt = /* @__PURE__ */ new Date();
4662
5028
  const redactKeys = copyRedactKeys(options.recorderOptions?.redactKeys);
@@ -4909,8 +5275,7 @@ var createExecutionRecordingCoordinator = (options) => {
4909
5275
  }
4910
5276
  };
4911
5277
  const kickNotify = () => {
4912
- if (!networkEnabled || closed || closing || pending.size === 0 || options.mode !== "adaptive")
4913
- return;
5278
+ if (closed || closing || pending.size === 0 || options.mode !== "adaptive") return;
4914
5279
  void drainNotifies(notifySignal());
4915
5280
  };
4916
5281
  const rememberCatalog = (key, atMs) => {
@@ -4989,7 +5354,7 @@ var createExecutionRecordingCoordinator = (options) => {
4989
5354
  return entries;
4990
5355
  };
4991
5356
  const syncOnce = async (signal) => {
4992
- if (!networkEnabled || closed) return;
5357
+ if (closed) return;
4993
5358
  const types2 = catalogTypes();
4994
5359
  try {
4995
5360
  const { response, body: payload } = await postJson(
@@ -5142,7 +5507,7 @@ var createExecutionRecordingCoordinator = (options) => {
5142
5507
  }
5143
5508
  };
5144
5509
  const kickRecordings = () => {
5145
- if (!networkEnabled || closed || closing || recordings.length === 0) return;
5510
+ if (closed || closing || recordings.length === 0) return;
5146
5511
  if (recordingPump) return;
5147
5512
  const running = drainRecordings(recordingSignal());
5148
5513
  recordingPump = running;
@@ -5160,7 +5525,7 @@ var createExecutionRecordingCoordinator = (options) => {
5160
5525
  if (existing !== void 0 && existing > atMs) return;
5161
5526
  cache.set(key, window.expiresAtMs);
5162
5527
  trimCache();
5163
- if (!networkEnabled || window.expiresAtMs <= atMs) return;
5528
+ if (window.expiresAtMs <= atMs) return;
5164
5529
  if (pending.size >= MAX_PENDING_NOTIFIES && !pending.has(key)) {
5165
5530
  for (const oldest of pending.keys()) {
5166
5531
  if (oldest !== sendingKey) {
@@ -5205,22 +5570,20 @@ var createExecutionRecordingCoordinator = (options) => {
5205
5570
  recordings.push(payload);
5206
5571
  kickRecordings();
5207
5572
  };
5208
- if (networkEnabled) {
5209
- const interval = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
5210
- const jitterMax = Math.max(0, options.pollJitterMs ?? MAX_POLL_JITTER_MS);
5211
- const delay = interval + Math.floor(Math.random() * jitterMax);
5212
- pollStartTimer = setTimeout(() => {
5213
- pollStartTimer = void 0;
5573
+ const interval = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
5574
+ const jitterMax = Math.max(0, options.pollJitterMs ?? MAX_POLL_JITTER_MS);
5575
+ const delay = interval + Math.floor(Math.random() * jitterMax);
5576
+ pollStartTimer = setTimeout(() => {
5577
+ pollStartTimer = void 0;
5578
+ if (closed || closing) return;
5579
+ void runSyncOnce(pollSignal());
5580
+ pollTimer = setInterval(() => {
5214
5581
  if (closed || closing) return;
5215
5582
  void runSyncOnce(pollSignal());
5216
- pollTimer = setInterval(() => {
5217
- if (closed || closing) return;
5218
- void runSyncOnce(pollSignal());
5219
- }, interval);
5220
- pollTimer.unref?.();
5221
- }, delay);
5222
- pollStartTimer.unref?.();
5223
- }
5583
+ }, interval);
5584
+ pollTimer.unref?.();
5585
+ }, delay);
5586
+ pollStartTimer.unref?.();
5224
5587
  const stopTimers = () => {
5225
5588
  if (pollStartTimer) {
5226
5589
  clearTimeout(pollStartTimer);
@@ -5244,7 +5607,7 @@ var createExecutionRecordingCoordinator = (options) => {
5244
5607
  lastAdaptiveFailureKind: lastFailureKind
5245
5608
  }),
5246
5609
  flush: async (timeoutMs = 2e3) => {
5247
- if (!networkEnabled || closed || closing) return;
5610
+ if (closed || closing) return;
5248
5611
  const flushAbort = new AbortController();
5249
5612
  const onAbort = () => interruptWork();
5250
5613
  flushAbort.signal.addEventListener("abort", onAbort, { once: true });
@@ -5269,7 +5632,7 @@ var createExecutionRecordingCoordinator = (options) => {
5269
5632
  interruptWork();
5270
5633
  }, 2e3);
5271
5634
  try {
5272
- if (networkEnabled) await runSyncOnce(deadline.signal);
5635
+ await runSyncOnce(deadline.signal);
5273
5636
  if (!deadline.signal.aborted) await drainNotifies(deadline.signal);
5274
5637
  await joinUntil(recordingPump, deadline.signal);
5275
5638
  if (!deadline.signal.aborted) await drainRecordings(deadline.signal);
@@ -5292,10 +5655,11 @@ var bindAdaptiveRecorder = (input) => {
5292
5655
  dsn: input.dsn,
5293
5656
  projectApiKey: input.projectApiKey,
5294
5657
  apiUrl: input.apiUrl,
5295
- release: input.release
5658
+ release: input.release,
5659
+ environment: input.environment
5296
5660
  });
5297
5661
  const coordinator = input.recorderEnabled && activation.enabled && options?.sessions !== false ? createExecutionRecordingCoordinator({
5298
- environment: input.environment ?? "",
5662
+ environment: activation.environment,
5299
5663
  ingestToken: activation.ingestToken,
5300
5664
  activateUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingActivateUrl,
5301
5665
  syncUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingSyncUrl,
@@ -5308,21 +5672,1116 @@ var bindAdaptiveRecorder = (input) => {
5308
5672
  mode: adaptiveEnabled ? "adaptive" : "full",
5309
5673
  fetch: input.fetch
5310
5674
  }) : void 0;
5675
+ const recorderHooks = {};
5676
+ if (coordinator) {
5677
+ recorderHooks.policySnapshot = coordinator.peek;
5678
+ recorderHooks.onQualifyingFailure = adaptiveEnabled ? coordinator.activate : void 0;
5679
+ recorderHooks.getStats = coordinator.getStats;
5680
+ recorderHooks.sessionCaptureSnapshot = coordinator.peekSessions;
5681
+ recorderHooks.consumeSession = coordinator.consumeSession;
5682
+ recorderHooks.observeExecutionType = coordinator.observeType;
5683
+ recorderHooks.onSessionRecording = coordinator.enqueueRecording;
5684
+ }
5685
+ if (input.functionMetrics) recorderHooks.functionMetrics = input.functionMetrics;
5311
5686
  const runtime = createExecutionRecorder(
5312
5687
  { ...options, enabled: input.recorderEnabled },
5313
- coordinator ? {
5314
- policySnapshot: coordinator.peek,
5315
- onQualifyingFailure: adaptiveEnabled ? coordinator.activate : void 0,
5316
- getStats: coordinator.getStats,
5317
- sessionCaptureSnapshot: coordinator.peekSessions,
5318
- consumeSession: coordinator.consumeSession,
5319
- observeExecutionType: coordinator.observeType,
5320
- onSessionRecording: coordinator.enqueueRecording
5321
- } : void 0
5688
+ recorderHooks
5322
5689
  );
5323
5690
  return { runtime, policy: coordinator };
5324
5691
  };
5325
5692
 
5693
+ // src/function-metrics/bind-function-metrics.ts
5694
+ import { randomUUID as randomUUID2 } from "node:crypto";
5695
+ import {
5696
+ defaultIngestFetch as defaultIngestFetch2,
5697
+ resolveEndpointUrls as resolveEndpointUrls3
5698
+ } from "@rasputin-ai/core";
5699
+
5700
+ // src/function-metrics/function-metrics-collector.ts
5701
+ import {
5702
+ durationHistogramBucket,
5703
+ FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT,
5704
+ FUNCTION_METRICS_MAX_ACTIVE_SERIES,
5705
+ FUNCTION_METRICS_MAX_BUFFERED_MS,
5706
+ FUNCTION_METRICS_MAX_EXECUTION_TYPES,
5707
+ FUNCTION_METRICS_MAX_FUNCTIONS,
5708
+ FUNCTION_METRICS_MAX_MINUTE_ROWS,
5709
+ FUNCTION_METRICS_MAX_STATE_BYTES,
5710
+ FUNCTION_METRICS_MINUTE_MS,
5711
+ functionIdentityKey,
5712
+ isCanonicalFunctionMetricsExecutionKey
5713
+ } from "@rasputin-ai/core";
5714
+
5715
+ // src/function-metrics/function-metrics-batches.ts
5716
+ import { randomUUID } from "node:crypto";
5717
+ import {
5718
+ FUNCTION_METRICS_MEASUREMENT_FORMAT,
5719
+ FUNCTION_METRICS_SCHEMA_VERSION
5720
+ } from "@rasputin-ai/core";
5721
+ var emptyCoverage = (buckets) => ({
5722
+ covered_bucket_starts: buckets,
5723
+ skipped_unresolved_execution_type: 0,
5724
+ dropped_active_series: 0,
5725
+ dropped_byte_budget: 0,
5726
+ dropped_queue_budget: 0,
5727
+ dropped_late_completion: 0,
5728
+ dropped_unexportable: 0
5729
+ });
5730
+ var bucketStart = (minute) => new Date(minute * 6e4).toISOString();
5731
+ var sparseHistogram = (histogram) => {
5732
+ const cells = [];
5733
+ for (let index = 0; index < histogram.length; index += 1) {
5734
+ const count = histogram[index] ?? 0;
5735
+ if (count > 0) cells.push([index, count]);
5736
+ }
5737
+ return cells;
5738
+ };
5739
+ var toMinute = (row, functionIndex, executionTypeIndex) => ({
5740
+ function_index: functionIndex,
5741
+ execution_type_index: executionTypeIndex,
5742
+ bucket_start: bucketStart(row.minute),
5743
+ started_calls: row.series.started,
5744
+ completed_calls: row.series.completed,
5745
+ failed_calls: row.series.failed,
5746
+ duration_sample_count: row.series.sampleCount,
5747
+ duration_sample_sum_us: row.series.sampleSumUs,
5748
+ duration_sample_min_us: row.series.sampleMinUs,
5749
+ duration_sample_max_us: row.series.sampleMaxUs,
5750
+ duration_histogram: sparseHistogram(row.series.histogram),
5751
+ invalid_timing_count: row.series.invalidTiming
5752
+ });
5753
+ var rowsFromQueue = (queued) => {
5754
+ const rows = [];
5755
+ for (const queuedMinute of queued) {
5756
+ for (const [functionHandle, byExecution] of queuedMinute.series) {
5757
+ for (const [executionHandle, series] of byExecution) {
5758
+ rows.push({
5759
+ minute: queuedMinute.minute,
5760
+ functionHandle,
5761
+ executionHandle,
5762
+ series
5763
+ });
5764
+ }
5765
+ }
5766
+ }
5767
+ rows.sort((left, right) => {
5768
+ if (left.minute !== right.minute) return left.minute - right.minute;
5769
+ if (left.functionHandle !== right.functionHandle) {
5770
+ return left.functionHandle - right.functionHandle;
5771
+ }
5772
+ return left.executionHandle - right.executionHandle;
5773
+ });
5774
+ return rows;
5775
+ };
5776
+ var chunkRows = (rows, maxFunctions, maxExecutionTypes, maxMinuteRows) => {
5777
+ const chunks = [];
5778
+ let current = [];
5779
+ let functions = /* @__PURE__ */ new Set();
5780
+ let executionTypes = /* @__PURE__ */ new Set();
5781
+ const flush = () => {
5782
+ if (current.length === 0) return;
5783
+ chunks.push(current);
5784
+ current = [];
5785
+ functions = /* @__PURE__ */ new Set();
5786
+ executionTypes = /* @__PURE__ */ new Set();
5787
+ };
5788
+ for (const row of rows) {
5789
+ const nextFunctions = functions.has(row.functionHandle) ? functions.size : functions.size + 1;
5790
+ const nextTypes = executionTypes.has(row.executionHandle) ? executionTypes.size : executionTypes.size + 1;
5791
+ const rowWouldOverflow = current.length >= maxMinuteRows || nextFunctions > maxFunctions || nextTypes > maxExecutionTypes;
5792
+ if (rowWouldOverflow) flush();
5793
+ current.push(row);
5794
+ functions.add(row.functionHandle);
5795
+ executionTypes.add(row.executionHandle);
5796
+ }
5797
+ flush();
5798
+ return chunks;
5799
+ };
5800
+ var batchForChunk = (draft, rows, coverage) => {
5801
+ const functionIndexes = /* @__PURE__ */ new Map();
5802
+ const executionIndexes = /* @__PURE__ */ new Map();
5803
+ const functions = [];
5804
+ const executionTypes = [];
5805
+ const minutes = [];
5806
+ for (const row of rows) {
5807
+ let functionIndex = functionIndexes.get(row.functionHandle);
5808
+ if (functionIndex === void 0) {
5809
+ const declaration = draft.functions[row.functionHandle];
5810
+ if (!declaration) continue;
5811
+ functionIndex = functions.length;
5812
+ functionIndexes.set(row.functionHandle, functionIndex);
5813
+ functions.push(declaration);
5814
+ }
5815
+ let executionTypeIndex = executionIndexes.get(row.executionHandle);
5816
+ if (executionTypeIndex === void 0) {
5817
+ const executionKey = draft.executionKeys[row.executionHandle];
5818
+ if (!executionKey) continue;
5819
+ executionTypeIndex = executionTypes.length;
5820
+ executionIndexes.set(row.executionHandle, executionTypeIndex);
5821
+ executionTypes.push({ execution_key: executionKey });
5822
+ }
5823
+ minutes.push(toMinute(row, functionIndex, executionTypeIndex));
5824
+ }
5825
+ const covered = [...new Set(minutes.map((minute) => minute.bucket_start))].sort();
5826
+ return {
5827
+ schema_version: FUNCTION_METRICS_SCHEMA_VERSION,
5828
+ measurement_format: FUNCTION_METRICS_MEASUREMENT_FORMAT,
5829
+ producer_id: draft.producerId,
5830
+ batch_id: draft.batchId(),
5831
+ environment: draft.environment,
5832
+ release: draft.release,
5833
+ functions,
5834
+ execution_types: executionTypes,
5835
+ minutes,
5836
+ coverage: { ...coverage, covered_bucket_starts: covered }
5837
+ };
5838
+ };
5839
+ var functionMetricsBatchesFromQueue = (draft) => {
5840
+ const rows = rowsFromQueue(draft.queued);
5841
+ if (rows.length === 0) {
5842
+ const hasLoss = Object.entries(draft.coverage).some(([key, value]) => {
5843
+ return key !== "covered_bucket_starts" && typeof value === "number" && value > 0;
5844
+ });
5845
+ if (!hasLoss) return [];
5846
+ return [
5847
+ {
5848
+ schema_version: FUNCTION_METRICS_SCHEMA_VERSION,
5849
+ measurement_format: FUNCTION_METRICS_MEASUREMENT_FORMAT,
5850
+ producer_id: draft.producerId,
5851
+ batch_id: draft.batchId(),
5852
+ environment: draft.environment,
5853
+ release: draft.release,
5854
+ functions: [],
5855
+ execution_types: [],
5856
+ minutes: [],
5857
+ coverage: draft.coverage
5858
+ }
5859
+ ];
5860
+ }
5861
+ const chunks = chunkRows(rows, draft.maxFunctions, draft.maxExecutionTypes, draft.maxMinuteRows);
5862
+ return chunks.map(
5863
+ (chunk, index) => batchForChunk(draft, chunk, index === 0 ? draft.coverage : emptyCoverage([]))
5864
+ );
5865
+ };
5866
+ var newFunctionMetricsBatchId = () => randomUUID();
5867
+
5868
+ // src/function-metrics/function-metrics-collector.ts
5869
+ var SERIES_BYTES = 256;
5870
+ var HISTOGRAM_BYTES = FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT * 4;
5871
+ var DECLARATION_BYTES = 1024;
5872
+ var MAX_ELAPSED_NS = BigInt(Number.MAX_SAFE_INTEGER);
5873
+ var defaultLimits = () => ({
5874
+ maxActiveSeries: FUNCTION_METRICS_MAX_ACTIVE_SERIES,
5875
+ maxStateBytes: FUNCTION_METRICS_MAX_STATE_BYTES,
5876
+ maxQueuedMinutes: FUNCTION_METRICS_MAX_BUFFERED_MS / FUNCTION_METRICS_MINUTE_MS,
5877
+ maxFunctions: FUNCTION_METRICS_MAX_FUNCTIONS,
5878
+ maxExecutionTypes: FUNCTION_METRICS_MAX_EXECUTION_TYPES,
5879
+ maxMinuteRows: FUNCTION_METRICS_MAX_MINUTE_ROWS
5880
+ });
5881
+ var defaultClock = () => ({
5882
+ monotonicNs: () => process.hrtime.bigint(),
5883
+ wallTimeMs: () => Date.now()
5884
+ });
5885
+ var emptyCoverage2 = () => ({
5886
+ covered_bucket_starts: [],
5887
+ skipped_unresolved_execution_type: 0,
5888
+ dropped_active_series: 0,
5889
+ dropped_byte_budget: 0,
5890
+ dropped_queue_budget: 0,
5891
+ dropped_late_completion: 0,
5892
+ dropped_unexportable: 0
5893
+ });
5894
+ var note = (coverage, counter, amount = 1) => {
5895
+ const next = coverage[counter] + amount;
5896
+ coverage[counter] = Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
5897
+ };
5898
+ var countSeries = (table) => {
5899
+ let count = 0;
5900
+ for (const byExecution of table.values()) count += byExecution.size;
5901
+ return count;
5902
+ };
5903
+ var tableBytes = (table) => {
5904
+ let bytes = 0;
5905
+ for (const byExecution of table.values()) {
5906
+ for (const series of byExecution.values()) bytes += series.bytes;
5907
+ }
5908
+ return bytes;
5909
+ };
5910
+ var discardedMarks = (table) => {
5911
+ let marks = 0;
5912
+ for (const byExecution of table.values()) {
5913
+ for (const series of byExecution.values()) {
5914
+ const next = marks + series.started + series.completed;
5915
+ marks = Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
5916
+ }
5917
+ }
5918
+ return marks;
5919
+ };
5920
+ var seriesHasMarks = (series) => series.started > 0 || series.completed > 0 || series.failed > 0 || series.sampleCount > 0 || series.invalidTiming > 0;
5921
+ var copySeries = (series) => ({
5922
+ ...series,
5923
+ histogram: series.histogram.slice()
5924
+ });
5925
+ var resetSeries = (series) => {
5926
+ series.started = 0;
5927
+ series.completed = 0;
5928
+ series.failed = 0;
5929
+ series.sampleCount = 0;
5930
+ series.sampleSumUs = 0;
5931
+ series.sampleMinUs = null;
5932
+ series.sampleMaxUs = null;
5933
+ series.invalidTiming = 0;
5934
+ series.histogram.fill(0);
5935
+ };
5936
+ var snapshotAndReset = (table) => {
5937
+ const snapshot = /* @__PURE__ */ new Map();
5938
+ for (const [functionHandle, byExecution] of table) {
5939
+ const copied = /* @__PURE__ */ new Map();
5940
+ for (const [executionHandle, series] of byExecution) {
5941
+ if (seriesHasMarks(series)) copied.set(executionHandle, copySeries(series));
5942
+ resetSeries(series);
5943
+ }
5944
+ if (copied.size > 0) snapshot.set(functionHandle, copied);
5945
+ }
5946
+ return snapshot;
5947
+ };
5948
+ var declarationAccepted = (declaration) => {
5949
+ if (declaration.identity_kind !== declaration.descriptor.identity_kind) return false;
5950
+ if (declaration.logical_key !== functionIdentityKey(declaration.descriptor)) return false;
5951
+ if (declaration.descriptor.identity_kind === "release_scoped") {
5952
+ return declaration.descriptor.declaration_id === declaration.runtime_id;
5953
+ }
5954
+ return true;
5955
+ };
5956
+ var createFunctionMetricsCollector = (options) => {
5957
+ const limits = { ...defaultLimits(), ...options.limits };
5958
+ const clock = options.clock ?? defaultClock();
5959
+ const batchId = options.batchId ?? newFunctionMetricsBatchId;
5960
+ const coverage = emptyCoverage2();
5961
+ const functions = [];
5962
+ const functionHandleByRuntimeId = /* @__PURE__ */ new Map();
5963
+ const executionKeys = [];
5964
+ const executionHandleByKey = /* @__PURE__ */ new Map();
5965
+ const active = /* @__PURE__ */ new Map();
5966
+ const queue = [];
5967
+ let lastClosedMinute = Number.NEGATIVE_INFINITY;
5968
+ let lastSeenMinute = Number.NEGATIVE_INFINITY;
5969
+ let stateBytes = 0;
5970
+ let activeSeries = 0;
5971
+ let sealed = false;
5972
+ const reserve = (bytes) => {
5973
+ if (stateBytes > limits.maxStateBytes - bytes) {
5974
+ note(coverage, "dropped_byte_budget");
5975
+ return false;
5976
+ }
5977
+ stateBytes += bytes;
5978
+ return true;
5979
+ };
5980
+ const internDeclaration = (declaration) => {
5981
+ if (!declaration) {
5982
+ note(coverage, "dropped_unexportable");
5983
+ return void 0;
5984
+ }
5985
+ const existing = functionHandleByRuntimeId.get(declaration.runtime_id);
5986
+ if (existing !== void 0) return existing;
5987
+ if (!declarationAccepted(declaration)) {
5988
+ note(coverage, "dropped_unexportable");
5989
+ return void 0;
5990
+ }
5991
+ if (functions.length >= limits.maxFunctions) {
5992
+ note(coverage, "dropped_unexportable");
5993
+ return void 0;
5994
+ }
5995
+ if (!reserve(DECLARATION_BYTES + declaration.runtime_id.length)) return void 0;
5996
+ const handle = functions.length;
5997
+ functions.push(declaration);
5998
+ functionHandleByRuntimeId.set(declaration.runtime_id, handle);
5999
+ return handle;
6000
+ };
6001
+ const internExecutionKey = (key) => {
6002
+ if (!key || !isCanonicalFunctionMetricsExecutionKey(key)) return void 0;
6003
+ const existing = executionHandleByKey.get(key);
6004
+ if (existing !== void 0) return existing;
6005
+ if (executionKeys.length >= limits.maxExecutionTypes) {
6006
+ note(coverage, "dropped_unexportable");
6007
+ return void 0;
6008
+ }
6009
+ if (!reserve(key.length)) return void 0;
6010
+ const handle = executionKeys.length;
6011
+ executionKeys.push(key);
6012
+ executionHandleByKey.set(key, handle);
6013
+ return handle;
6014
+ };
6015
+ const ensureSeries = (minute, functionHandle, executionHandle) => {
6016
+ let byFunction = active.get(minute);
6017
+ if (!byFunction) {
6018
+ byFunction = /* @__PURE__ */ new Map();
6019
+ active.set(minute, byFunction);
6020
+ }
6021
+ let byExecution = byFunction.get(functionHandle);
6022
+ if (!byExecution) {
6023
+ byExecution = /* @__PURE__ */ new Map();
6024
+ byFunction.set(functionHandle, byExecution);
6025
+ }
6026
+ const existing = byExecution.get(executionHandle);
6027
+ if (existing) return existing;
6028
+ if (activeSeries >= limits.maxActiveSeries) {
6029
+ note(coverage, "dropped_active_series");
6030
+ return void 0;
6031
+ }
6032
+ if (!reserve(SERIES_BYTES + HISTOGRAM_BYTES)) return void 0;
6033
+ const series = {
6034
+ started: 0,
6035
+ completed: 0,
6036
+ failed: 0,
6037
+ sampleCount: 0,
6038
+ sampleSumUs: 0,
6039
+ sampleMinUs: null,
6040
+ sampleMaxUs: null,
6041
+ invalidTiming: 0,
6042
+ histogram: new Uint32Array(FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT),
6043
+ bytes: SERIES_BYTES + HISTOGRAM_BYTES
6044
+ };
6045
+ byExecution.set(executionHandle, series);
6046
+ activeSeries += 1;
6047
+ return series;
6048
+ };
6049
+ const appendQueue = (entry) => {
6050
+ if (discardedMarks(entry.series) === 0) {
6051
+ stateBytes -= entry.bytes;
6052
+ if (stateBytes < 0) stateBytes = 0;
6053
+ return;
6054
+ }
6055
+ queue.push(entry);
6056
+ queue.sort((left, right) => left.minute - right.minute);
6057
+ while (queue.length > limits.maxQueuedMinutes) {
6058
+ const dropped = queue.shift();
6059
+ if (!dropped) break;
6060
+ stateBytes -= dropped.bytes;
6061
+ if (stateBytes < 0) stateBytes = 0;
6062
+ note(coverage, "dropped_queue_budget", discardedMarks(dropped.series));
6063
+ }
6064
+ };
6065
+ const closeMinute = (minute, table) => {
6066
+ active.delete(minute);
6067
+ activeSeries -= countSeries(table);
6068
+ if (minute > lastClosedMinute) lastClosedMinute = minute;
6069
+ appendQueue({ minute, series: table, bytes: tableBytes(table) });
6070
+ };
6071
+ const rotate = (currentMinute) => {
6072
+ for (const minute of [...active.keys()]) {
6073
+ if (minute >= currentMinute) continue;
6074
+ const table = active.get(minute);
6075
+ if (table) closeMinute(minute, table);
6076
+ }
6077
+ const closedThrough = currentMinute - 1;
6078
+ if (closedThrough > lastClosedMinute) lastClosedMinute = closedThrough;
6079
+ };
6080
+ const rotateIfNeeded = (minute) => {
6081
+ if (minute === lastSeenMinute) return;
6082
+ lastSeenMinute = minute;
6083
+ rotate(minute);
6084
+ };
6085
+ const snapshotActive = () => {
6086
+ for (const [minute, table] of active) {
6087
+ appendQueue({ minute, series: snapshotAndReset(table), bytes: 0 });
6088
+ }
6089
+ };
6090
+ const moveAllActive = () => {
6091
+ for (const minute of [...active.keys()]) {
6092
+ const table = active.get(minute);
6093
+ if (table) closeMinute(minute, table);
6094
+ }
6095
+ };
6096
+ const rememberSample = (series, durationUs, bucket) => {
6097
+ const sampleCount = series.sampleCount + 1;
6098
+ const sampleSumUs = series.sampleSumUs + durationUs;
6099
+ const previous = series.histogram[bucket];
6100
+ if (previous === void 0) return false;
6101
+ const cell = previous + 1;
6102
+ const sumFits = Number.isFinite(sampleSumUs) && sampleSumUs >= 0 && sampleSumUs <= Number.MAX_SAFE_INTEGER;
6103
+ if (!Number.isSafeInteger(sampleCount) || !Number.isSafeInteger(cell) || !sumFits) return false;
6104
+ series.histogram[bucket] = cell;
6105
+ series.sampleCount = sampleCount;
6106
+ series.sampleSumUs = sampleSumUs;
6107
+ series.sampleMinUs = series.sampleMinUs === null ? durationUs : Math.min(series.sampleMinUs, durationUs);
6108
+ series.sampleMaxUs = series.sampleMaxUs === null ? durationUs : Math.max(series.sampleMaxUs, durationUs);
6109
+ return true;
6110
+ };
6111
+ const rememberCompletion = (series, startedNs, failed, endedNs) => {
6112
+ const completed = series.completed + 1;
6113
+ const failures = series.failed + (failed ? 1 : 0);
6114
+ if (!Number.isSafeInteger(completed) || !Number.isSafeInteger(failures)) return false;
6115
+ const elapsed = endedNs - startedNs;
6116
+ const durationUs = Number(elapsed) / 1e3;
6117
+ const placed = durationHistogramBucket(durationUs);
6118
+ const elapsedFits = elapsed >= 0n && elapsed <= MAX_ELAPSED_NS;
6119
+ const sampled = elapsedFits && placed !== void 0 && rememberSample(series, durationUs, placed);
6120
+ if (!sampled) {
6121
+ const invalidTiming = series.invalidTiming + 1;
6122
+ if (!Number.isSafeInteger(invalidTiming)) return false;
6123
+ series.invalidTiming = invalidTiming;
6124
+ }
6125
+ series.completed = completed;
6126
+ series.failed = failures;
6127
+ return true;
6128
+ };
6129
+ const startCall = (functionHandle, executionHandle, startedNs) => {
6130
+ if (sealed) {
6131
+ note(coverage, "dropped_unexportable");
6132
+ return void 0;
6133
+ }
6134
+ if (executionHandle === void 0) {
6135
+ note(coverage, "skipped_unresolved_execution_type");
6136
+ return void 0;
6137
+ }
6138
+ const minute = Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS);
6139
+ rotateIfNeeded(minute);
6140
+ if (minute <= lastClosedMinute) {
6141
+ note(coverage, "dropped_late_completion");
6142
+ return void 0;
6143
+ }
6144
+ const series = ensureSeries(minute, functionHandle, executionHandle);
6145
+ if (!series) return void 0;
6146
+ const started = series.started + 1;
6147
+ if (!Number.isSafeInteger(started)) {
6148
+ note(coverage, "dropped_unexportable");
6149
+ return void 0;
6150
+ }
6151
+ series.started = started;
6152
+ return startedNs ?? clock.monotonicNs();
6153
+ };
6154
+ const finishCall = (functionHandle, executionHandle, startedNs, failed, endedNs) => {
6155
+ if (sealed) {
6156
+ note(coverage, "dropped_late_completion");
6157
+ return;
6158
+ }
6159
+ const minute = Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS);
6160
+ rotateIfNeeded(minute);
6161
+ if (minute <= lastClosedMinute && !active.has(minute)) {
6162
+ note(coverage, "dropped_late_completion");
6163
+ return;
6164
+ }
6165
+ const series = ensureSeries(minute, functionHandle, executionHandle);
6166
+ if (!series) return;
6167
+ const remembered = rememberCompletion(
6168
+ series,
6169
+ startedNs,
6170
+ failed,
6171
+ endedNs ?? clock.monotonicNs()
6172
+ );
6173
+ if (!remembered) note(coverage, "dropped_unexportable");
6174
+ };
6175
+ const beginCall = (input) => {
6176
+ const functionHandle = internDeclaration(input.declaration);
6177
+ if (functionHandle === void 0) return void 0;
6178
+ if (!input.executionKey || !isCanonicalFunctionMetricsExecutionKey(input.executionKey)) {
6179
+ startCall(functionHandle, void 0);
6180
+ return void 0;
6181
+ }
6182
+ const executionHandle = internExecutionKey(input.executionKey);
6183
+ if (executionHandle === void 0) return void 0;
6184
+ const startedNs = startCall(functionHandle, executionHandle);
6185
+ if (startedNs === void 0) return void 0;
6186
+ return { settled: false, functionHandle, executionHandle, startedNs };
6187
+ };
6188
+ const completeCall = (call, failed) => {
6189
+ if (!call || call.settled) return;
6190
+ call.settled = true;
6191
+ finishCall(call.functionHandle, call.executionHandle, call.startedNs, failed);
6192
+ };
6193
+ const drain = (drainOptions) => {
6194
+ if (!sealed) {
6195
+ rotateIfNeeded(Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS));
6196
+ if (drainOptions?.flushAll) snapshotActive();
6197
+ }
6198
+ const batches = functionMetricsBatchesFromQueue({
6199
+ environment: options.environment,
6200
+ release: options.release,
6201
+ producerId: options.producerId,
6202
+ batchId,
6203
+ maxFunctions: limits.maxFunctions,
6204
+ maxExecutionTypes: limits.maxExecutionTypes,
6205
+ maxMinuteRows: limits.maxMinuteRows,
6206
+ functions,
6207
+ executionKeys,
6208
+ queued: queue,
6209
+ coverage: { ...coverage, covered_bucket_starts: [] }
6210
+ });
6211
+ if (batches.length === 0) return [];
6212
+ for (const queued of queue) stateBytes -= queued.bytes;
6213
+ if (stateBytes < 0) stateBytes = 0;
6214
+ queue.length = 0;
6215
+ coverage.skipped_unresolved_execution_type = 0;
6216
+ coverage.dropped_active_series = 0;
6217
+ coverage.dropped_byte_budget = 0;
6218
+ coverage.dropped_queue_budget = 0;
6219
+ coverage.dropped_late_completion = 0;
6220
+ coverage.dropped_unexportable = 0;
6221
+ return batches;
6222
+ };
6223
+ return {
6224
+ internDeclaration,
6225
+ internExecutionKey,
6226
+ startCall,
6227
+ finishCall,
6228
+ beginCall,
6229
+ completeCall,
6230
+ drain,
6231
+ seal: () => {
6232
+ if (sealed) return;
6233
+ sealed = true;
6234
+ moveAllActive();
6235
+ }
6236
+ };
6237
+ };
6238
+
6239
+ // src/function-metrics/encode-function-metrics-upload.ts
6240
+ import {
6241
+ encodeFunctionMetricsBatch,
6242
+ encodeJsonRequestBodyAsync as encodeJsonRequestBodyAsync2,
6243
+ FUNCTION_METRICS_BUCKET_LATENESS_MS,
6244
+ FUNCTION_METRICS_MAX_DECODED_BYTES,
6245
+ FUNCTION_METRICS_MINUTE_MS as FUNCTION_METRICS_MINUTE_MS2,
6246
+ parseFunctionMetricsBucketStart
6247
+ } from "@rasputin-ai/core";
6248
+ var minuteMarks = (minute) => {
6249
+ const next = minute.started_calls + minute.completed_calls;
6250
+ return Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
6251
+ };
6252
+ var expiresAtMsFor = (batch, nowMs) => {
6253
+ let oldest;
6254
+ for (const start of batch.coverage.covered_bucket_starts) {
6255
+ const bucket = parseFunctionMetricsBucketStart(start);
6256
+ if (bucket === void 0) continue;
6257
+ if (oldest === void 0 || bucket < oldest) oldest = bucket;
6258
+ }
6259
+ if (oldest === void 0) return nowMs + FUNCTION_METRICS_BUCKET_LATENESS_MS;
6260
+ return oldest + FUNCTION_METRICS_MINUTE_MS2 + FUNCTION_METRICS_BUCKET_LATENESS_MS;
6261
+ };
6262
+ var zeroLossCoverage = (coverage) => ({
6263
+ ...coverage,
6264
+ skipped_unresolved_execution_type: 0,
6265
+ dropped_active_series: 0,
6266
+ dropped_byte_budget: 0,
6267
+ dropped_queue_budget: 0,
6268
+ dropped_late_completion: 0,
6269
+ dropped_unexportable: 0
6270
+ });
6271
+ var projectMinutes = (source, minutes, coverage, batchId) => {
6272
+ const functionIndexes = /* @__PURE__ */ new Map();
6273
+ const typeIndexes = /* @__PURE__ */ new Map();
6274
+ const functions = [];
6275
+ const executionTypes = [];
6276
+ const remapped = [];
6277
+ for (const minute of minutes) {
6278
+ let functionIndex = functionIndexes.get(minute.function_index);
6279
+ if (functionIndex === void 0) {
6280
+ const declaration = source.functions[minute.function_index];
6281
+ if (!declaration) continue;
6282
+ functionIndex = functions.length;
6283
+ functionIndexes.set(minute.function_index, functionIndex);
6284
+ functions.push(declaration);
6285
+ }
6286
+ let executionTypeIndex = typeIndexes.get(minute.execution_type_index);
6287
+ if (executionTypeIndex === void 0) {
6288
+ const entry = source.execution_types[minute.execution_type_index];
6289
+ if (!entry) continue;
6290
+ executionTypeIndex = executionTypes.length;
6291
+ typeIndexes.set(minute.execution_type_index, executionTypeIndex);
6292
+ executionTypes.push(entry);
6293
+ }
6294
+ remapped.push({
6295
+ ...minute,
6296
+ function_index: functionIndex,
6297
+ execution_type_index: executionTypeIndex
6298
+ });
6299
+ }
6300
+ const covered = [...new Set(remapped.map((minute) => minute.bucket_start))].sort();
6301
+ return {
6302
+ ...source,
6303
+ batch_id: batchId,
6304
+ functions,
6305
+ execution_types: executionTypes,
6306
+ minutes: remapped,
6307
+ coverage: { ...coverage, covered_bucket_starts: covered }
6308
+ };
6309
+ };
6310
+ var withLoss = (batch, loss) => ({
6311
+ ...batch,
6312
+ coverage: {
6313
+ ...batch.coverage,
6314
+ dropped_unexportable: batch.coverage.dropped_unexportable + loss.dropped_unexportable,
6315
+ dropped_queue_budget: batch.coverage.dropped_queue_budget + loss.dropped_queue_budget
6316
+ }
6317
+ });
6318
+ var encodeOne = async (batch, nowMs, signal) => {
6319
+ const decodedBytes = encodeFunctionMetricsBatch(batch);
6320
+ if (decodedBytes.byteLength > FUNCTION_METRICS_MAX_DECODED_BYTES) return void 0;
6321
+ const encoded = await encodeJsonRequestBodyAsync2(decodedBytes, void 0, signal);
6322
+ return {
6323
+ decodedBytes,
6324
+ body: encoded.body,
6325
+ gzip: encoded.gzip,
6326
+ batchId: batch.batch_id,
6327
+ expiresAtMs: expiresAtMsFor(batch, nowMs)
6328
+ };
6329
+ };
6330
+ var encodeFitting = async (batch, nowMs, signal) => {
6331
+ const encoded = await encodeOne(batch, nowMs, signal);
6332
+ if (encoded) return { uploads: [encoded], droppedUnexportable: 0 };
6333
+ if (batch.minutes.length <= 1) {
6334
+ return {
6335
+ uploads: [],
6336
+ droppedUnexportable: batch.minutes.reduce((sum, minute) => sum + minuteMarks(minute), 0)
6337
+ };
6338
+ }
6339
+ const mid = Math.ceil(batch.minutes.length / 2);
6340
+ const first = projectMinutes(batch, batch.minutes.slice(0, mid), batch.coverage, batch.batch_id);
6341
+ const rest = projectMinutes(
6342
+ batch,
6343
+ batch.minutes.slice(mid),
6344
+ zeroLossCoverage(batch.coverage),
6345
+ newFunctionMetricsBatchId()
6346
+ );
6347
+ const left = await encodeFitting(first, nowMs, signal);
6348
+ const right = await encodeFitting(rest, nowMs, signal);
6349
+ return {
6350
+ uploads: [...left.uploads, ...right.uploads],
6351
+ droppedUnexportable: left.droppedUnexportable + right.droppedUnexportable
6352
+ };
6353
+ };
6354
+ var encodeFunctionMetricsUploads = async (batches, input) => {
6355
+ const uploads = [];
6356
+ let extra = {
6357
+ dropped_unexportable: 0,
6358
+ dropped_queue_budget: input.queueDrops ?? 0
6359
+ };
6360
+ for (const batch of batches) {
6361
+ const fitted = await encodeFitting(withLoss(batch, extra), input.nowMs, input.signal);
6362
+ extra = { dropped_unexportable: fitted.droppedUnexportable, dropped_queue_budget: 0 };
6363
+ uploads.push(...fitted.uploads);
6364
+ }
6365
+ return uploads;
6366
+ };
6367
+
6368
+ // src/function-metrics/send-function-metrics-batch.ts
6369
+ var REQUEST_TIMEOUT_MS2 = 2e4;
6370
+ var abortError = () => Object.assign(new Error("aborted"), { name: "AbortError" });
6371
+ var retryAfterMs = (response) => {
6372
+ const header = response.headers.get("retry-after");
6373
+ if (!header) return null;
6374
+ const seconds = Number(header);
6375
+ if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
6376
+ const date = Date.parse(header);
6377
+ return Number.isFinite(date) ? Math.max(0, date - Date.now()) : null;
6378
+ };
6379
+ var backoffMs2 = (attempt, random) => {
6380
+ const base = Math.min(3e4, 500 * 2 ** attempt);
6381
+ return Math.floor(base * (0.5 + random()));
6382
+ };
6383
+ var fetchUntilAborted = (fetchFn, url, init) => new Promise((resolve, reject) => {
6384
+ const onAbort = () => reject(abortError());
6385
+ init.signal.addEventListener("abort", onAbort, { once: true });
6386
+ if (init.signal.aborted) {
6387
+ init.signal.removeEventListener("abort", onAbort);
6388
+ reject(abortError());
6389
+ return;
6390
+ }
6391
+ void fetchFn(url, init).then(
6392
+ (value) => {
6393
+ init.signal.removeEventListener("abort", onAbort);
6394
+ resolve(value);
6395
+ },
6396
+ (error) => {
6397
+ init.signal.removeEventListener("abort", onAbort);
6398
+ reject(error);
6399
+ }
6400
+ );
6401
+ });
6402
+ var sendFunctionMetricsBatch = async (input) => {
6403
+ if (input.signal.aborted) return { outcome: "aborted" };
6404
+ const nowMs = input.nowMs ?? Date.now;
6405
+ if (input.upload.expiresAtMs <= nowMs())
6406
+ return { outcome: "terminal", status: null, halt: false };
6407
+ const request = new AbortController();
6408
+ const timer = setTimeout(() => request.abort(), REQUEST_TIMEOUT_MS2);
6409
+ timer.unref?.();
6410
+ const onParentAbort = () => request.abort();
6411
+ input.signal.addEventListener("abort", onParentAbort, { once: true });
6412
+ if (input.signal.aborted) request.abort();
6413
+ const headers = {
6414
+ Authorization: `Bearer ${input.ingestToken}`,
6415
+ "Content-Type": "application/json",
6416
+ Accept: "application/json"
6417
+ };
6418
+ if (input.upload.gzip) headers["Content-Encoding"] = "gzip";
6419
+ try {
6420
+ const response = await fetchUntilAborted(input.fetch, input.url, {
6421
+ method: "POST",
6422
+ headers,
6423
+ body: input.upload.body,
6424
+ signal: request.signal
6425
+ });
6426
+ if (response.ok) return { outcome: "ok" };
6427
+ if (response.status === 429) {
6428
+ return {
6429
+ outcome: "retry",
6430
+ waitMs: retryAfterMs(response) ?? backoffMs2(input.attempt, input.random ?? Math.random)
6431
+ };
6432
+ }
6433
+ if (response.status === 401 || response.status === 403 || response.status === 404) {
6434
+ return { outcome: "terminal", status: response.status, halt: true };
6435
+ }
6436
+ if (response.status >= 400 && response.status < 500) {
6437
+ return { outcome: "terminal", status: response.status, halt: false };
6438
+ }
6439
+ return {
6440
+ outcome: "retry",
6441
+ waitMs: backoffMs2(input.attempt, input.random ?? Math.random)
6442
+ };
6443
+ } catch {
6444
+ if (input.signal.aborted) return { outcome: "aborted" };
6445
+ return { outcome: "retry", waitMs: backoffMs2(input.attempt, input.random ?? Math.random) };
6446
+ } finally {
6447
+ clearTimeout(timer);
6448
+ input.signal.removeEventListener("abort", onParentAbort);
6449
+ }
6450
+ };
6451
+
6452
+ // src/function-metrics/function-metrics-exporter.ts
6453
+ var MAX_QUEUE_ITEMS = 32;
6454
+ var MAX_QUEUE_BYTES = 4 * 1024 * 1024;
6455
+ var DEFAULT_SCHEDULE_MS = 6e4;
6456
+ var FLUSH_MS = 1e4;
6457
+ var SHUTDOWN_FLUSH_MS = 2e3;
6458
+ var MAX_ATTEMPTS = 8;
6459
+ var sleep = (ms, signal) => new Promise((resolve) => {
6460
+ if (ms <= 0 || signal.aborted) {
6461
+ resolve();
6462
+ return;
6463
+ }
6464
+ const timer = setTimeout(finish, ms);
6465
+ timer.unref?.();
6466
+ const onAbort = () => {
6467
+ clearTimeout(timer);
6468
+ finish();
6469
+ };
6470
+ function finish() {
6471
+ signal.removeEventListener("abort", onAbort);
6472
+ resolve();
6473
+ }
6474
+ signal.addEventListener("abort", onAbort);
6475
+ if (signal.aborted) onAbort();
6476
+ });
6477
+ var createFunctionMetricsExporter = (input) => {
6478
+ const nowMs = input.nowMs ?? Date.now;
6479
+ const random = input.random ?? Math.random;
6480
+ const scheduleMs = input.scheduleMs ?? DEFAULT_SCHEDULE_MS;
6481
+ const queue = [];
6482
+ let queueBytes = 0;
6483
+ let queueDrops = 0;
6484
+ let timer;
6485
+ let closed = false;
6486
+ let halted = false;
6487
+ let stopped = false;
6488
+ let workAbort;
6489
+ let work;
6490
+ let sent = 0;
6491
+ let dropped = 0;
6492
+ let warnedHalt = null;
6493
+ const dropOldest = () => {
6494
+ const oldest = queue.shift();
6495
+ if (!oldest) return;
6496
+ queueBytes -= oldest.upload.decodedBytes.byteLength;
6497
+ if (queueBytes < 0) queueBytes = 0;
6498
+ queueDrops += 1;
6499
+ dropped += 1;
6500
+ };
6501
+ const enqueue = (upload) => {
6502
+ queue.push({ upload, attempt: 0 });
6503
+ queueBytes += upload.decodedBytes.byteLength;
6504
+ while (queue.length > MAX_QUEUE_ITEMS || queueBytes > MAX_QUEUE_BYTES) dropOldest();
6505
+ };
6506
+ const drainAndEnqueue = async (flushAll2) => {
6507
+ if (halted || stopped) return;
6508
+ const batches = input.collector.drain({ flushAll: flushAll2 });
6509
+ if (batches.length === 0) return;
6510
+ const encoded = await encodeFunctionMetricsUploads(batches, {
6511
+ nowMs: nowMs(),
6512
+ queueDrops
6513
+ });
6514
+ if (encoded.length === 0 || halted || stopped) return;
6515
+ queueDrops = 0;
6516
+ for (const upload of encoded) enqueue(upload);
6517
+ };
6518
+ const warnHalt = (status) => {
6519
+ if (warnedHalt === status) return;
6520
+ warnedHalt = status;
6521
+ if (status === 401 || status === 403) {
6522
+ console.warn("[rasputin] function metrics export stopped: authentication failed");
6523
+ return;
6524
+ }
6525
+ if (status === 404) {
6526
+ console.warn("[rasputin] function metrics export stopped: ingest route is unavailable");
6527
+ }
6528
+ };
6529
+ const pump = async (signal) => {
6530
+ while (queue.length > 0 && !halted && !stopped && !signal.aborted) {
6531
+ const item = queue[0];
6532
+ if (!item) return;
6533
+ if (item.upload.expiresAtMs <= nowMs()) {
6534
+ queue.shift();
6535
+ queueBytes -= item.upload.decodedBytes.byteLength;
6536
+ dropped += 1;
6537
+ continue;
6538
+ }
6539
+ if (item.attempt >= MAX_ATTEMPTS) {
6540
+ queue.shift();
6541
+ queueBytes -= item.upload.decodedBytes.byteLength;
6542
+ dropped += 1;
6543
+ continue;
6544
+ }
6545
+ const result = await sendFunctionMetricsBatch({
6546
+ url: input.url,
6547
+ ingestToken: input.ingestToken,
6548
+ upload: item.upload,
6549
+ fetch: input.fetch,
6550
+ signal,
6551
+ attempt: item.attempt,
6552
+ random,
6553
+ nowMs
6554
+ });
6555
+ if (result.outcome === "aborted") return;
6556
+ if (result.outcome === "ok") {
6557
+ queue.shift();
6558
+ queueBytes -= item.upload.decodedBytes.byteLength;
6559
+ sent += 1;
6560
+ continue;
6561
+ }
6562
+ if (result.outcome === "terminal") {
6563
+ queue.shift();
6564
+ queueBytes -= item.upload.decodedBytes.byteLength;
6565
+ dropped += 1;
6566
+ if (result.halt) {
6567
+ halted = true;
6568
+ warnHalt(result.status);
6569
+ }
6570
+ continue;
6571
+ }
6572
+ item.attempt += 1;
6573
+ await sleep(result.waitMs, signal);
6574
+ }
6575
+ };
6576
+ const abortCurrent = () => {
6577
+ workAbort?.abort();
6578
+ };
6579
+ const raceUntilAborted = async (running, signal) => {
6580
+ if (signal.aborted) return;
6581
+ await new Promise((resolve) => {
6582
+ let settled = false;
6583
+ const finish = () => {
6584
+ if (settled) return;
6585
+ settled = true;
6586
+ signal.removeEventListener("abort", finish);
6587
+ resolve();
6588
+ };
6589
+ signal.addEventListener("abort", finish);
6590
+ if (signal.aborted) {
6591
+ finish();
6592
+ return;
6593
+ }
6594
+ void running.then(finish, finish);
6595
+ });
6596
+ };
6597
+ const runWork = async (signal, task) => {
6598
+ const onAbort = () => abortCurrent();
6599
+ signal.addEventListener("abort", onAbort);
6600
+ if (signal.aborted) abortCurrent();
6601
+ try {
6602
+ while (work) {
6603
+ const previous = work;
6604
+ await raceUntilAborted(previous, signal);
6605
+ if (signal.aborted || halted) return;
6606
+ if (work === previous) return;
6607
+ }
6608
+ if (halted) return;
6609
+ const inner = new AbortController();
6610
+ workAbort = inner;
6611
+ if (signal.aborted) {
6612
+ workAbort = void 0;
6613
+ return;
6614
+ }
6615
+ const running = task(inner.signal).finally(() => {
6616
+ if (workAbort === inner) workAbort = void 0;
6617
+ if (work === running) work = void 0;
6618
+ });
6619
+ work = running;
6620
+ await raceUntilAborted(running, signal);
6621
+ } finally {
6622
+ signal.removeEventListener("abort", onAbort);
6623
+ }
6624
+ };
6625
+ const tick = async () => {
6626
+ if (closed || halted) return;
6627
+ try {
6628
+ await runWork(new AbortController().signal, async (signal) => {
6629
+ if (closed || halted) return;
6630
+ await drainAndEnqueue(false);
6631
+ await pump(signal);
6632
+ });
6633
+ } catch {
6634
+ }
6635
+ if (!closed && !halted) arm();
6636
+ };
6637
+ const arm = () => {
6638
+ if (closed || halted) return;
6639
+ const delay = Math.max(1e3, Math.floor(scheduleMs * (0.85 + random() * 0.3)));
6640
+ timer = setTimeout(() => {
6641
+ void tick();
6642
+ }, delay);
6643
+ timer.unref?.();
6644
+ };
6645
+ arm();
6646
+ const flush = async (timeoutMs) => {
6647
+ if (closed || halted) return;
6648
+ const abort = new AbortController();
6649
+ const budget = timeoutMs ?? FLUSH_MS;
6650
+ const timeout = setTimeout(() => abort.abort(), Math.max(0, budget));
6651
+ try {
6652
+ await runWork(abort.signal, async (signal) => {
6653
+ if (closed || halted) return;
6654
+ await drainAndEnqueue(true);
6655
+ await pump(signal);
6656
+ });
6657
+ } catch {
6658
+ } finally {
6659
+ clearTimeout(timeout);
6660
+ }
6661
+ };
6662
+ return {
6663
+ flush,
6664
+ close: async () => {
6665
+ if (closed) return;
6666
+ closed = true;
6667
+ if (timer) clearTimeout(timer);
6668
+ timer = void 0;
6669
+ const abort = new AbortController();
6670
+ const timeout = setTimeout(() => abort.abort(), SHUTDOWN_FLUSH_MS);
6671
+ abortCurrent();
6672
+ try {
6673
+ await runWork(abort.signal, async (signal) => {
6674
+ input.collector.seal();
6675
+ await drainAndEnqueue(false);
6676
+ await pump(signal);
6677
+ });
6678
+ } catch {
6679
+ } finally {
6680
+ clearTimeout(timeout);
6681
+ stopped = true;
6682
+ input.collector.seal();
6683
+ queue.length = 0;
6684
+ queueBytes = 0;
6685
+ }
6686
+ },
6687
+ getStats: () => ({ sent, dropped, halted })
6688
+ };
6689
+ };
6690
+
6691
+ // src/function-metrics/install-function-metric-declaration-sink.ts
6692
+ var REGISTER = "__rasputinRegisterFunctionMetricDeclarations";
6693
+ var PENDING = "__rasputinPendingFunctionMetricDeclarations";
6694
+ var installFunctionMetricDeclarationSink = () => {
6695
+ Reflect.set(globalThis, REGISTER, registerFunctionMetricDeclarations);
6696
+ const pending = Reflect.get(globalThis, PENDING);
6697
+ if (!Array.isArray(pending) || pending.length === 0) return;
6698
+ registerFunctionMetricDeclarations(pending);
6699
+ pending.length = 0;
6700
+ };
6701
+
6702
+ // src/function-metrics/bind-function-metrics.ts
6703
+ var SLOT = Symbol.for("rasputin.functionMetrics.runtime.v1");
6704
+ var releasedHandles = /* @__PURE__ */ new WeakSet();
6705
+ var isRuntime = (value) => {
6706
+ if (typeof value !== "object" || value === null) return false;
6707
+ return "collector" in value && "exporter" in value && "refs" in value && "identity" in value && "warnedMismatch" in value;
6708
+ };
6709
+ var bindingIdentity = (input) => `${input.ingestToken}
6710
+ ${input.url}
6711
+ ${input.environment}
6712
+ ${input.release}`;
6713
+ var warnIncompatible = (runtime) => {
6714
+ if (runtime.warnedMismatch) return;
6715
+ runtime.warnedMismatch = true;
6716
+ console.warn(
6717
+ "[rasputin] function metrics already running with a different configuration; this client will not collect function metrics"
6718
+ );
6719
+ };
6720
+ var createBindings = (input) => {
6721
+ installFunctionMetricDeclarationSink();
6722
+ const collector = createFunctionMetricsCollector({
6723
+ environment: input.environment,
6724
+ producerId: randomUUID2(),
6725
+ release: input.release
6726
+ });
6727
+ return {
6728
+ collector,
6729
+ exporter: createFunctionMetricsExporter({
6730
+ collector,
6731
+ url: input.url,
6732
+ ingestToken: input.ingestToken,
6733
+ fetch: input.fetch ?? defaultIngestFetch2()
6734
+ })
6735
+ };
6736
+ };
6737
+ var bindFunctionMetrics = (input) => {
6738
+ if (!input.clientEnabled) return void 0;
6739
+ if (input.options?.enabled === false) return void 0;
6740
+ const release = input.release.trim().toLowerCase();
6741
+ if (!/^[0-9a-f]{7,40}$/.test(release)) return void 0;
6742
+ const url = resolveEndpointUrls3(input.apiUrl).functionMetricsUrl;
6743
+ const key = bindingIdentity({
6744
+ ingestToken: input.ingestToken,
6745
+ url,
6746
+ environment: input.environment,
6747
+ release
6748
+ });
6749
+ const existing = Reflect.get(globalThis, SLOT);
6750
+ if (isRuntime(existing)) {
6751
+ if (existing.identity !== key) {
6752
+ warnIncompatible(existing);
6753
+ return void 0;
6754
+ }
6755
+ existing.refs += 1;
6756
+ return { collector: existing.collector, exporter: existing.exporter };
6757
+ }
6758
+ const bindings2 = createBindings({
6759
+ release,
6760
+ ingestToken: input.ingestToken,
6761
+ url,
6762
+ environment: input.environment,
6763
+ fetch: input.fetch
6764
+ });
6765
+ Reflect.set(globalThis, SLOT, {
6766
+ ...bindings2,
6767
+ refs: 1,
6768
+ identity: key,
6769
+ warnedMismatch: false
6770
+ });
6771
+ return bindings2;
6772
+ };
6773
+ var releaseFunctionMetricsBindings = async (bindings2) => {
6774
+ if (!bindings2 || releasedHandles.has(bindings2)) return;
6775
+ releasedHandles.add(bindings2);
6776
+ const existing = Reflect.get(globalThis, SLOT);
6777
+ if (isRuntime(existing) && existing.exporter === bindings2.exporter) {
6778
+ existing.refs -= 1;
6779
+ if (existing.refs > 0) return;
6780
+ Reflect.deleteProperty(globalThis, SLOT);
6781
+ }
6782
+ await bindings2.exporter.close();
6783
+ };
6784
+
5326
6785
  // src/install-global-handlers.ts
5327
6786
  var RASPUTIN_PROCESS_LISTENER = Symbol.for("rasputin.process.listener.v1");
5328
6787
  var unhandledRejectionMode = () => {
@@ -5460,9 +6919,11 @@ var installGlobalHandlers = (client, options = {}) => {
5460
6919
  };
5461
6920
  export {
5462
6921
  bindAdaptiveRecorder,
6922
+ bindFunctionMetrics,
5463
6923
  createExecutionRecorder,
5464
6924
  inertErrorObservation,
5465
6925
  installAutomaticExecutionRuntime,
5466
6926
  installGlobalHandlers,
6927
+ releaseFunctionMetricsBindings,
5467
6928
  scheduleInstrumentationManifestUpload
5468
6929
  };