From 6949362c1b541fea21ce57f1765180732229f6dc Mon Sep 17 00:00:00 2001 From: Pete Karl II Date: Sat, 7 Sep 2024 10:00:36 -0400 Subject: [PATCH] add dist to this tmp build --- dist/cjs/buffer.d.ts | 2 + dist/cjs/buffer.d.ts.map | 1 + dist/cjs/buffer.js | 7 + dist/cjs/buffer.js.map | 1 + dist/cjs/config.d.ts | 5 + dist/cjs/config.d.ts.map | 1 + dist/cjs/config.js | 14 ++ dist/cjs/config.js.map | 1 + dist/cjs/context.d.ts | 59 +++++ dist/cjs/context.d.ts.map | 1 + dist/cjs/context.js | 215 ++++++++++++++++ dist/cjs/context.js.map | 1 + dist/cjs/exporter.d.ts | 17 ++ dist/cjs/exporter.d.ts.map | 1 + dist/cjs/exporter.js | 74 ++++++ dist/cjs/exporter.js.map | 1 + dist/cjs/index.d.ts | 10 + dist/cjs/index.d.ts.map | 1 + dist/cjs/index.js | 27 ++ dist/cjs/index.js.map | 1 + .../cjs/instrumentation/analytics-engine.d.ts | 2 + .../instrumentation/analytics-engine.d.ts.map | 1 + dist/cjs/instrumentation/analytics-engine.js | 67 +++++ .../instrumentation/analytics-engine.js.map | 1 + dist/cjs/instrumentation/cache.d.ts | 2 + dist/cjs/instrumentation/cache.d.ts.map | 1 + dist/cjs/instrumentation/cache.js | 91 +++++++ dist/cjs/instrumentation/cache.js.map | 1 + dist/cjs/instrumentation/common.d.ts | 21 ++ dist/cjs/instrumentation/common.d.ts.map | 1 + dist/cjs/instrumentation/common.js | 89 +++++++ dist/cjs/instrumentation/common.js.map | 1 + dist/cjs/instrumentation/do-storage.d.ts | 2 + dist/cjs/instrumentation/do-storage.d.ts.map | 1 + dist/cjs/instrumentation/do-storage.js | 204 +++++++++++++++ dist/cjs/instrumentation/do-storage.js.map | 1 + dist/cjs/instrumentation/do.d.ts | 13 + dist/cjs/instrumentation/do.d.ts.map | 1 + dist/cjs/instrumentation/do.js | 229 +++++++++++++++++ dist/cjs/instrumentation/do.js.map | 1 + dist/cjs/instrumentation/env.d.ts | 4 + dist/cjs/instrumentation/env.d.ts.map | 1 + dist/cjs/instrumentation/env.js | 66 +++++ dist/cjs/instrumentation/env.js.map | 1 + dist/cjs/instrumentation/fetch.d.ts | 30 +++ dist/cjs/instrumentation/fetch.d.ts.map | 1 + dist/cjs/instrumentation/fetch.js | 220 ++++++++++++++++ dist/cjs/instrumentation/fetch.js.map | 1 + dist/cjs/instrumentation/kv.d.ts | 2 + dist/cjs/instrumentation/kv.d.ts.map | 1 + dist/cjs/instrumentation/kv.js | 129 ++++++++++ dist/cjs/instrumentation/kv.js.map | 1 + dist/cjs/instrumentation/queue.d.ts | 8 + dist/cjs/instrumentation/queue.d.ts.map | 1 + dist/cjs/instrumentation/queue.js | 238 ++++++++++++++++++ dist/cjs/instrumentation/queue.js.map | 1 + dist/cjs/instrumentation/scheduled.d.ts | 7 + dist/cjs/instrumentation/scheduled.d.ts.map | 1 + dist/cjs/instrumentation/scheduled.js | 78 ++++++ dist/cjs/instrumentation/scheduled.js.map | 1 + dist/cjs/instrumentation/service.d.ts | 2 + dist/cjs/instrumentation/service.d.ts.map | 1 + dist/cjs/instrumentation/service.js | 23 ++ dist/cjs/instrumentation/service.js.map | 1 + dist/cjs/instrumentation/version.d.ts | 2 + dist/cjs/instrumentation/version.d.ts.map | 1 + dist/cjs/instrumentation/version.js | 20 ++ dist/cjs/instrumentation/version.js.map | 1 + dist/cjs/multiexporter.d.ts | 15 ++ dist/cjs/multiexporter.d.ts.map | 1 + dist/cjs/multiexporter.js | 60 +++++ dist/cjs/multiexporter.js.map | 1 + dist/cjs/package-info.d.ts | 3 + dist/cjs/package-info.d.ts.map | 1 + dist/cjs/package-info.js | 7 + dist/cjs/package-info.js.map | 1 + dist/cjs/provider.d.ts | 19 ++ dist/cjs/provider.d.ts.map | 1 + dist/cjs/provider.js | 33 +++ dist/cjs/provider.js.map | 1 + dist/cjs/sampling.d.ts | 11 + dist/cjs/sampling.d.ts.map | 1 + dist/cjs/sampling.js | 21 ++ dist/cjs/sampling.js.map | 1 + dist/cjs/sdk.d.ts | 12 + dist/cjs/sdk.d.ts.map | 1 + dist/cjs/sdk.js | 169 +++++++++++++ dist/cjs/sdk.js.map | 1 + dist/cjs/span.d.ts | 55 ++++ dist/cjs/span.d.ts.map | 1 + dist/cjs/span.js | 146 +++++++++++ dist/cjs/span.js.map | 1 + dist/cjs/spanprocessor.d.ts | 16 ++ dist/cjs/spanprocessor.d.ts.map | 1 + dist/cjs/spanprocessor.js | 149 +++++++++++ dist/cjs/spanprocessor.js.map | 1 + dist/cjs/tracer.d.ts | 17 ++ dist/cjs/tracer.d.ts.map | 1 + dist/cjs/tracer.js | 79 ++++++ dist/cjs/tracer.js.map | 1 + dist/cjs/types.d.ts | 61 +++++ dist/cjs/types.d.ts.map | 1 + dist/cjs/types.js | 7 + dist/cjs/types.js.map | 1 + .../vendor/ts-checked-fsm/StateMachine.d.ts | 104 ++++++++ .../ts-checked-fsm/StateMachine.d.ts.map | 1 + .../cjs/vendor/ts-checked-fsm/StateMachine.js | 78 ++++++ .../vendor/ts-checked-fsm/StateMachine.js.map | 1 + dist/cjs/wrap.d.ts | 11 + dist/cjs/wrap.d.ts.map | 1 + dist/cjs/wrap.js | 65 +++++ dist/cjs/wrap.js.map | 1 + dist/esm/buffer.d.ts | 2 + dist/esm/buffer.d.ts.map | 1 + dist/esm/buffer.js | 5 + dist/esm/buffer.js.map | 1 + dist/esm/config.d.ts | 5 + dist/esm/config.d.ts.map | 1 + dist/esm/config.js | 10 + dist/esm/config.js.map | 1 + dist/esm/context.d.ts | 59 +++++ dist/esm/context.d.ts.map | 1 + dist/esm/context.js | 208 +++++++++++++++ dist/esm/context.js.map | 1 + dist/esm/exporter.d.ts | 17 ++ dist/esm/exporter.d.ts.map | 1 + dist/esm/exporter.js | 61 +++++ dist/esm/exporter.js.map | 1 + dist/esm/index.d.ts | 10 + dist/esm/index.d.ts.map | 1 + dist/esm/index.js | 9 + dist/esm/index.js.map | 1 + .../esm/instrumentation/analytics-engine.d.ts | 2 + .../instrumentation/analytics-engine.d.ts.map | 1 + dist/esm/instrumentation/analytics-engine.js | 55 ++++ .../instrumentation/analytics-engine.js.map | 1 + dist/esm/instrumentation/cache.d.ts | 2 + dist/esm/instrumentation/cache.d.ts.map | 1 + dist/esm/instrumentation/cache.js | 75 ++++++ dist/esm/instrumentation/cache.js.map | 1 + dist/esm/instrumentation/common.d.ts | 21 ++ dist/esm/instrumentation/common.d.ts.map | 1 + dist/esm/instrumentation/common.js | 66 +++++ dist/esm/instrumentation/common.js.map | 1 + dist/esm/instrumentation/do-storage.d.ts | 2 + dist/esm/instrumentation/do-storage.d.ts.map | 1 + dist/esm/instrumentation/do-storage.js | 195 ++++++++++++++ dist/esm/instrumentation/do-storage.js.map | 1 + dist/esm/instrumentation/do.d.ts | 13 + dist/esm/instrumentation/do.d.ts.map | 1 + dist/esm/instrumentation/do.js | 209 +++++++++++++++ dist/esm/instrumentation/do.js.map | 1 + dist/esm/instrumentation/env.d.ts | 4 + dist/esm/instrumentation/env.d.ts.map | 1 + dist/esm/instrumentation/env.js | 62 +++++ dist/esm/instrumentation/env.js.map | 1 + dist/esm/instrumentation/fetch.d.ts | 30 +++ dist/esm/instrumentation/fetch.d.ts.map | 1 + dist/esm/instrumentation/fetch.js | 196 +++++++++++++++ dist/esm/instrumentation/fetch.js.map | 1 + dist/esm/instrumentation/kv.d.ts | 2 + dist/esm/instrumentation/kv.d.ts.map | 1 + dist/esm/instrumentation/kv.js | 117 +++++++++ dist/esm/instrumentation/kv.js.map | 1 + dist/esm/instrumentation/queue.d.ts | 8 + dist/esm/instrumentation/queue.d.ts.map | 1 + dist/esm/instrumentation/queue.js | 222 ++++++++++++++++ dist/esm/instrumentation/queue.js.map | 1 + dist/esm/instrumentation/scheduled.d.ts | 7 + dist/esm/instrumentation/scheduled.d.ts.map | 1 + dist/esm/instrumentation/scheduled.js | 63 +++++ dist/esm/instrumentation/scheduled.js.map | 1 + dist/esm/instrumentation/service.d.ts | 2 + dist/esm/instrumentation/service.d.ts.map | 1 + dist/esm/instrumentation/service.js | 20 ++ dist/esm/instrumentation/service.js.map | 1 + dist/esm/instrumentation/version.d.ts | 2 + dist/esm/instrumentation/version.d.ts.map | 1 + dist/esm/instrumentation/version.js | 17 ++ dist/esm/instrumentation/version.js.map | 1 + dist/esm/multiexporter.d.ts | 15 ++ dist/esm/multiexporter.d.ts.map | 1 + dist/esm/multiexporter.js | 44 ++++ dist/esm/multiexporter.js.map | 1 + dist/esm/package-info.d.ts | 3 + dist/esm/package-info.d.ts.map | 1 + dist/esm/package-info.js | 4 + dist/esm/package-info.js.map | 1 + dist/esm/provider.d.ts | 19 ++ dist/esm/provider.d.ts.map | 1 + dist/esm/provider.js | 31 +++ dist/esm/provider.js.map | 1 + dist/esm/sampling.d.ts | 11 + dist/esm/sampling.d.ts.map | 1 + dist/esm/sampling.js | 15 ++ dist/esm/sampling.js.map | 1 + dist/esm/sdk.d.ts | 12 + dist/esm/sdk.d.ts.map | 1 + dist/esm/sdk.js | 159 ++++++++++++ dist/esm/sdk.js.map | 1 + dist/esm/span.d.ts | 55 ++++ dist/esm/span.d.ts.map | 1 + dist/esm/span.js | 151 +++++++++++ dist/esm/span.js.map | 1 + dist/esm/spanprocessor.d.ts | 16 ++ dist/esm/spanprocessor.d.ts.map | 1 + dist/esm/spanprocessor.js | 139 ++++++++++ dist/esm/spanprocessor.js.map | 1 + dist/esm/tracer.d.ts | 17 ++ dist/esm/tracer.d.ts.map | 1 + dist/esm/tracer.js | 76 ++++++ dist/esm/tracer.js.map | 1 + dist/esm/types.d.ts | 61 +++++ dist/esm/types.d.ts.map | 1 + dist/esm/types.js | 4 + dist/esm/types.js.map | 1 + .../vendor/ts-checked-fsm/StateMachine.d.ts | 104 ++++++++ .../ts-checked-fsm/StateMachine.d.ts.map | 1 + .../esm/vendor/ts-checked-fsm/StateMachine.js | 83 ++++++ .../vendor/ts-checked-fsm/StateMachine.js.map | 1 + dist/esm/wrap.d.ts | 11 + dist/esm/wrap.d.ts.map | 1 + dist/esm/wrap.js | 58 +++++ dist/esm/wrap.js.map | 1 + 224 files changed, 6095 insertions(+) create mode 100644 dist/cjs/buffer.d.ts create mode 100644 dist/cjs/buffer.d.ts.map create mode 100644 dist/cjs/buffer.js create mode 100644 dist/cjs/buffer.js.map create mode 100644 dist/cjs/config.d.ts create mode 100644 dist/cjs/config.d.ts.map create mode 100644 dist/cjs/config.js create mode 100644 dist/cjs/config.js.map create mode 100644 dist/cjs/context.d.ts create mode 100644 dist/cjs/context.d.ts.map create mode 100644 dist/cjs/context.js create mode 100644 dist/cjs/context.js.map create mode 100644 dist/cjs/exporter.d.ts create mode 100644 dist/cjs/exporter.d.ts.map create mode 100644 dist/cjs/exporter.js create mode 100644 dist/cjs/exporter.js.map create mode 100644 dist/cjs/index.d.ts create mode 100644 dist/cjs/index.d.ts.map create mode 100644 dist/cjs/index.js create mode 100644 dist/cjs/index.js.map create mode 100644 dist/cjs/instrumentation/analytics-engine.d.ts create mode 100644 dist/cjs/instrumentation/analytics-engine.d.ts.map create mode 100644 dist/cjs/instrumentation/analytics-engine.js create mode 100644 dist/cjs/instrumentation/analytics-engine.js.map create mode 100644 dist/cjs/instrumentation/cache.d.ts create mode 100644 dist/cjs/instrumentation/cache.d.ts.map create mode 100644 dist/cjs/instrumentation/cache.js create mode 100644 dist/cjs/instrumentation/cache.js.map create mode 100644 dist/cjs/instrumentation/common.d.ts create mode 100644 dist/cjs/instrumentation/common.d.ts.map create mode 100644 dist/cjs/instrumentation/common.js create mode 100644 dist/cjs/instrumentation/common.js.map create mode 100644 dist/cjs/instrumentation/do-storage.d.ts create mode 100644 dist/cjs/instrumentation/do-storage.d.ts.map create mode 100644 dist/cjs/instrumentation/do-storage.js create mode 100644 dist/cjs/instrumentation/do-storage.js.map create mode 100644 dist/cjs/instrumentation/do.d.ts create mode 100644 dist/cjs/instrumentation/do.d.ts.map create mode 100644 dist/cjs/instrumentation/do.js create mode 100644 dist/cjs/instrumentation/do.js.map create mode 100644 dist/cjs/instrumentation/env.d.ts create mode 100644 dist/cjs/instrumentation/env.d.ts.map create mode 100644 dist/cjs/instrumentation/env.js create mode 100644 dist/cjs/instrumentation/env.js.map create mode 100644 dist/cjs/instrumentation/fetch.d.ts create mode 100644 dist/cjs/instrumentation/fetch.d.ts.map create mode 100644 dist/cjs/instrumentation/fetch.js create mode 100644 dist/cjs/instrumentation/fetch.js.map create mode 100644 dist/cjs/instrumentation/kv.d.ts create mode 100644 dist/cjs/instrumentation/kv.d.ts.map create mode 100644 dist/cjs/instrumentation/kv.js create mode 100644 dist/cjs/instrumentation/kv.js.map create mode 100644 dist/cjs/instrumentation/queue.d.ts create mode 100644 dist/cjs/instrumentation/queue.d.ts.map create mode 100644 dist/cjs/instrumentation/queue.js create mode 100644 dist/cjs/instrumentation/queue.js.map create mode 100644 dist/cjs/instrumentation/scheduled.d.ts create mode 100644 dist/cjs/instrumentation/scheduled.d.ts.map create mode 100644 dist/cjs/instrumentation/scheduled.js create mode 100644 dist/cjs/instrumentation/scheduled.js.map create mode 100644 dist/cjs/instrumentation/service.d.ts create mode 100644 dist/cjs/instrumentation/service.d.ts.map create mode 100644 dist/cjs/instrumentation/service.js create mode 100644 dist/cjs/instrumentation/service.js.map create mode 100644 dist/cjs/instrumentation/version.d.ts create mode 100644 dist/cjs/instrumentation/version.d.ts.map create mode 100644 dist/cjs/instrumentation/version.js create mode 100644 dist/cjs/instrumentation/version.js.map create mode 100644 dist/cjs/multiexporter.d.ts create mode 100644 dist/cjs/multiexporter.d.ts.map create mode 100644 dist/cjs/multiexporter.js create mode 100644 dist/cjs/multiexporter.js.map create mode 100644 dist/cjs/package-info.d.ts create mode 100644 dist/cjs/package-info.d.ts.map create mode 100644 dist/cjs/package-info.js create mode 100644 dist/cjs/package-info.js.map create mode 100644 dist/cjs/provider.d.ts create mode 100644 dist/cjs/provider.d.ts.map create mode 100644 dist/cjs/provider.js create mode 100644 dist/cjs/provider.js.map create mode 100644 dist/cjs/sampling.d.ts create mode 100644 dist/cjs/sampling.d.ts.map create mode 100644 dist/cjs/sampling.js create mode 100644 dist/cjs/sampling.js.map create mode 100644 dist/cjs/sdk.d.ts create mode 100644 dist/cjs/sdk.d.ts.map create mode 100644 dist/cjs/sdk.js create mode 100644 dist/cjs/sdk.js.map create mode 100644 dist/cjs/span.d.ts create mode 100644 dist/cjs/span.d.ts.map create mode 100644 dist/cjs/span.js create mode 100644 dist/cjs/span.js.map create mode 100644 dist/cjs/spanprocessor.d.ts create mode 100644 dist/cjs/spanprocessor.d.ts.map create mode 100644 dist/cjs/spanprocessor.js create mode 100644 dist/cjs/spanprocessor.js.map create mode 100644 dist/cjs/tracer.d.ts create mode 100644 dist/cjs/tracer.d.ts.map create mode 100644 dist/cjs/tracer.js create mode 100644 dist/cjs/tracer.js.map create mode 100644 dist/cjs/types.d.ts create mode 100644 dist/cjs/types.d.ts.map create mode 100644 dist/cjs/types.js create mode 100644 dist/cjs/types.js.map create mode 100644 dist/cjs/vendor/ts-checked-fsm/StateMachine.d.ts create mode 100644 dist/cjs/vendor/ts-checked-fsm/StateMachine.d.ts.map create mode 100644 dist/cjs/vendor/ts-checked-fsm/StateMachine.js create mode 100644 dist/cjs/vendor/ts-checked-fsm/StateMachine.js.map create mode 100644 dist/cjs/wrap.d.ts create mode 100644 dist/cjs/wrap.d.ts.map create mode 100644 dist/cjs/wrap.js create mode 100644 dist/cjs/wrap.js.map create mode 100644 dist/esm/buffer.d.ts create mode 100644 dist/esm/buffer.d.ts.map create mode 100644 dist/esm/buffer.js create mode 100644 dist/esm/buffer.js.map create mode 100644 dist/esm/config.d.ts create mode 100644 dist/esm/config.d.ts.map create mode 100644 dist/esm/config.js create mode 100644 dist/esm/config.js.map create mode 100644 dist/esm/context.d.ts create mode 100644 dist/esm/context.d.ts.map create mode 100644 dist/esm/context.js create mode 100644 dist/esm/context.js.map create mode 100644 dist/esm/exporter.d.ts create mode 100644 dist/esm/exporter.d.ts.map create mode 100644 dist/esm/exporter.js create mode 100644 dist/esm/exporter.js.map create mode 100644 dist/esm/index.d.ts create mode 100644 dist/esm/index.d.ts.map create mode 100644 dist/esm/index.js create mode 100644 dist/esm/index.js.map create mode 100644 dist/esm/instrumentation/analytics-engine.d.ts create mode 100644 dist/esm/instrumentation/analytics-engine.d.ts.map create mode 100644 dist/esm/instrumentation/analytics-engine.js create mode 100644 dist/esm/instrumentation/analytics-engine.js.map create mode 100644 dist/esm/instrumentation/cache.d.ts create mode 100644 dist/esm/instrumentation/cache.d.ts.map create mode 100644 dist/esm/instrumentation/cache.js create mode 100644 dist/esm/instrumentation/cache.js.map create mode 100644 dist/esm/instrumentation/common.d.ts create mode 100644 dist/esm/instrumentation/common.d.ts.map create mode 100644 dist/esm/instrumentation/common.js create mode 100644 dist/esm/instrumentation/common.js.map create mode 100644 dist/esm/instrumentation/do-storage.d.ts create mode 100644 dist/esm/instrumentation/do-storage.d.ts.map create mode 100644 dist/esm/instrumentation/do-storage.js create mode 100644 dist/esm/instrumentation/do-storage.js.map create mode 100644 dist/esm/instrumentation/do.d.ts create mode 100644 dist/esm/instrumentation/do.d.ts.map create mode 100644 dist/esm/instrumentation/do.js create mode 100644 dist/esm/instrumentation/do.js.map create mode 100644 dist/esm/instrumentation/env.d.ts create mode 100644 dist/esm/instrumentation/env.d.ts.map create mode 100644 dist/esm/instrumentation/env.js create mode 100644 dist/esm/instrumentation/env.js.map create mode 100644 dist/esm/instrumentation/fetch.d.ts create mode 100644 dist/esm/instrumentation/fetch.d.ts.map create mode 100644 dist/esm/instrumentation/fetch.js create mode 100644 dist/esm/instrumentation/fetch.js.map create mode 100644 dist/esm/instrumentation/kv.d.ts create mode 100644 dist/esm/instrumentation/kv.d.ts.map create mode 100644 dist/esm/instrumentation/kv.js create mode 100644 dist/esm/instrumentation/kv.js.map create mode 100644 dist/esm/instrumentation/queue.d.ts create mode 100644 dist/esm/instrumentation/queue.d.ts.map create mode 100644 dist/esm/instrumentation/queue.js create mode 100644 dist/esm/instrumentation/queue.js.map create mode 100644 dist/esm/instrumentation/scheduled.d.ts create mode 100644 dist/esm/instrumentation/scheduled.d.ts.map create mode 100644 dist/esm/instrumentation/scheduled.js create mode 100644 dist/esm/instrumentation/scheduled.js.map create mode 100644 dist/esm/instrumentation/service.d.ts create mode 100644 dist/esm/instrumentation/service.d.ts.map create mode 100644 dist/esm/instrumentation/service.js create mode 100644 dist/esm/instrumentation/service.js.map create mode 100644 dist/esm/instrumentation/version.d.ts create mode 100644 dist/esm/instrumentation/version.d.ts.map create mode 100644 dist/esm/instrumentation/version.js create mode 100644 dist/esm/instrumentation/version.js.map create mode 100644 dist/esm/multiexporter.d.ts create mode 100644 dist/esm/multiexporter.d.ts.map create mode 100644 dist/esm/multiexporter.js create mode 100644 dist/esm/multiexporter.js.map create mode 100644 dist/esm/package-info.d.ts create mode 100644 dist/esm/package-info.d.ts.map create mode 100644 dist/esm/package-info.js create mode 100644 dist/esm/package-info.js.map create mode 100644 dist/esm/provider.d.ts create mode 100644 dist/esm/provider.d.ts.map create mode 100644 dist/esm/provider.js create mode 100644 dist/esm/provider.js.map create mode 100644 dist/esm/sampling.d.ts create mode 100644 dist/esm/sampling.d.ts.map create mode 100644 dist/esm/sampling.js create mode 100644 dist/esm/sampling.js.map create mode 100644 dist/esm/sdk.d.ts create mode 100644 dist/esm/sdk.d.ts.map create mode 100644 dist/esm/sdk.js create mode 100644 dist/esm/sdk.js.map create mode 100644 dist/esm/span.d.ts create mode 100644 dist/esm/span.d.ts.map create mode 100644 dist/esm/span.js create mode 100644 dist/esm/span.js.map create mode 100644 dist/esm/spanprocessor.d.ts create mode 100644 dist/esm/spanprocessor.d.ts.map create mode 100644 dist/esm/spanprocessor.js create mode 100644 dist/esm/spanprocessor.js.map create mode 100644 dist/esm/tracer.d.ts create mode 100644 dist/esm/tracer.d.ts.map create mode 100644 dist/esm/tracer.js create mode 100644 dist/esm/tracer.js.map create mode 100644 dist/esm/types.d.ts create mode 100644 dist/esm/types.d.ts.map create mode 100644 dist/esm/types.js create mode 100644 dist/esm/types.js.map create mode 100644 dist/esm/vendor/ts-checked-fsm/StateMachine.d.ts create mode 100644 dist/esm/vendor/ts-checked-fsm/StateMachine.d.ts.map create mode 100644 dist/esm/vendor/ts-checked-fsm/StateMachine.js create mode 100644 dist/esm/vendor/ts-checked-fsm/StateMachine.js.map create mode 100644 dist/esm/wrap.d.ts create mode 100644 dist/esm/wrap.d.ts.map create mode 100644 dist/esm/wrap.js create mode 100644 dist/esm/wrap.js.map diff --git a/dist/cjs/buffer.d.ts b/dist/cjs/buffer.d.ts new file mode 100644 index 0000000..791fb5b --- /dev/null +++ b/dist/cjs/buffer.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=buffer.d.ts.map \ No newline at end of file diff --git a/dist/cjs/buffer.d.ts.map b/dist/cjs/buffer.d.ts.map new file mode 100644 index 0000000..e8e3934 --- /dev/null +++ b/dist/cjs/buffer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"buffer.d.ts","sourceRoot":"","sources":["../../src/buffer.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/buffer.js b/dist/cjs/buffer.js new file mode 100644 index 0000000..496eb77 --- /dev/null +++ b/dist/cjs/buffer.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//@ts-ignore +const node_buffer_1 = require("node:buffer"); +//@ts-ignore +globalThis.Buffer = node_buffer_1.Buffer; +//# sourceMappingURL=buffer.js.map \ No newline at end of file diff --git a/dist/cjs/buffer.js.map b/dist/cjs/buffer.js.map new file mode 100644 index 0000000..0ec2f0b --- /dev/null +++ b/dist/cjs/buffer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"buffer.js","sourceRoot":"","sources":["../../src/buffer.ts"],"names":[],"mappings":";;AAAA,YAAY;AACZ,6CAAoC;AACpC,YAAY;AACZ,UAAU,CAAC,MAAM,GAAG,oBAAM,CAAA"} \ No newline at end of file diff --git a/dist/cjs/config.d.ts b/dist/cjs/config.d.ts new file mode 100644 index 0000000..f53b0a9 --- /dev/null +++ b/dist/cjs/config.d.ts @@ -0,0 +1,5 @@ +import { ResolvedTraceConfig, Trigger } from './types.js'; +export type Initialiser = (env: Record, trigger: Trigger) => ResolvedTraceConfig; +export declare function setConfig(config: ResolvedTraceConfig, ctx?: import("@opentelemetry/api").Context): import("@opentelemetry/api").Context; +export declare function getActiveConfig(): ResolvedTraceConfig | undefined; +//# sourceMappingURL=config.d.ts.map \ No newline at end of file diff --git a/dist/cjs/config.d.ts.map b/dist/cjs/config.d.ts.map new file mode 100644 index 0000000..5aca950 --- /dev/null +++ b/dist/cjs/config.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAIzD,MAAM,MAAM,WAAW,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,EAAE,OAAO,KAAK,mBAAmB,CAAA;AAEjG,wBAAgB,SAAS,CAAC,MAAM,EAAE,mBAAmB,EAAE,GAAG,uCAAmB,wCAE5E;AAED,wBAAgB,eAAe,IAAI,mBAAmB,GAAG,SAAS,CAGjE"} \ No newline at end of file diff --git a/dist/cjs/config.js b/dist/cjs/config.js new file mode 100644 index 0000000..49d3b88 --- /dev/null +++ b/dist/cjs/config.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.setConfig = setConfig; +exports.getActiveConfig = getActiveConfig; +const api_1 = require("@opentelemetry/api"); +const configSymbol = Symbol('Otel Workers Tracing Configuration'); +function setConfig(config, ctx = api_1.context.active()) { + return ctx.setValue(configSymbol, config); +} +function getActiveConfig() { + const config = api_1.context.active().getValue(configSymbol); + return config || undefined; +} +//# sourceMappingURL=config.js.map \ No newline at end of file diff --git a/dist/cjs/config.js.map b/dist/cjs/config.js.map new file mode 100644 index 0000000..0b9bab5 --- /dev/null +++ b/dist/cjs/config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":";;AAOA,8BAEC;AAED,0CAGC;AAdD,4CAA4C;AAG5C,MAAM,YAAY,GAAG,MAAM,CAAC,oCAAoC,CAAC,CAAA;AAIjE,SAAgB,SAAS,CAAC,MAA2B,EAAE,GAAG,GAAG,aAAO,CAAC,MAAM,EAAE;IAC5E,OAAO,GAAG,CAAC,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC,CAAA;AAC1C,CAAC;AAED,SAAgB,eAAe;IAC9B,MAAM,MAAM,GAAG,aAAO,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,YAAY,CAAwB,CAAA;IAC7E,OAAO,MAAM,IAAI,SAAS,CAAA;AAC3B,CAAC"} \ No newline at end of file diff --git a/dist/cjs/context.d.ts b/dist/cjs/context.d.ts new file mode 100644 index 0000000..997e893 --- /dev/null +++ b/dist/cjs/context.d.ts @@ -0,0 +1,59 @@ +import { ContextManager, Context } from '@opentelemetry/api'; +declare abstract class AbstractAsyncHooksContextManager implements ContextManager { + abstract active(): Context; + abstract with ReturnType>(context: Context, fn: F, thisArg?: ThisParameterType, ...args: A): ReturnType; + abstract enable(): this; + abstract disable(): this; + /** + * Binds a the certain context or the active one to the target function and then returns the target + * @param context A context (span) to be bind to target + * @param target a function or event emitter. When target or one of its callbacks is called, + * the provided context will be used as the active context for the duration of the call. + */ + bind(context: Context, target: T): T; + private _bindFunction; + /** + * By default, EventEmitter call their callback with their context, which we do + * not want, instead we will bind a specific context to all callbacks that + * go through it. + * @param context the context we want to bind + * @param ee EventEmitter an instance of EventEmitter to patch + */ + private _bindEventEmitter; + /** + * Patch methods that remove a given listener so that we match the "patched" + * version of that listener (the one that propagate context). + * @param ee EventEmitter instance + * @param original reference to the patched method + */ + private _patchRemoveListener; + /** + * Patch methods that remove all listeners so we remove our + * internal references for a given event. + * @param ee EventEmitter instance + * @param original reference to the patched method + */ + private _patchRemoveAllListeners; + /** + * Patch methods on an event emitter instance that can add listeners so we + * can force them to propagate a given context. + * @param ee EventEmitter instance + * @param original reference to the patched method + * @param [context] context to propagate when calling listeners + */ + private _patchAddListener; + private _createPatchMap; + private _getPatchMap; + private readonly _kOtListeners; + private _wrapped; +} +export declare class AsyncLocalStorageContextManager extends AbstractAsyncHooksContextManager { + private _asyncLocalStorage; + constructor(); + active(): Context; + with ReturnType>(context: Context, fn: F, thisArg?: ThisParameterType, ...args: A): ReturnType; + enable(): this; + disable(): this; +} +export {}; +//# sourceMappingURL=context.d.ts.map \ No newline at end of file diff --git a/dist/cjs/context.d.ts.map b/dist/cjs/context.d.ts.map new file mode 100644 index 0000000..1dacda5 --- /dev/null +++ b/dist/cjs/context.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../src/context.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,cAAc,EAAE,OAAO,EAAgB,MAAM,oBAAoB,CAAA;AAyB1E,uBAAe,gCAAiC,YAAW,cAAc;IACxE,QAAQ,CAAC,MAAM,IAAI,OAAO;IAE1B,QAAQ,CAAC,IAAI,CAAC,CAAC,SAAS,OAAO,EAAE,EAAE,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,CAAC,KAAK,UAAU,CAAC,CAAC,CAAC,EACzE,OAAO,EAAE,OAAO,EAChB,EAAE,EAAE,CAAC,EACL,OAAO,CAAC,EAAE,iBAAiB,CAAC,CAAC,CAAC,EAC9B,GAAG,IAAI,EAAE,CAAC,GACR,UAAU,CAAC,CAAC,CAAC;IAEhB,QAAQ,CAAC,MAAM,IAAI,IAAI;IAEvB,QAAQ,CAAC,OAAO,IAAI,IAAI;IAExB;;;;;OAKG;IACH,IAAI,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,GAAG,CAAC;IAWvC,OAAO,CAAC,aAAa;IAmBrB;;;;;;OAMG;IACH,OAAO,CAAC,iBAAiB;IAwBzB;;;;;OAKG;IACH,OAAO,CAAC,oBAAoB;IAY5B;;;;;OAKG;IACH,OAAO,CAAC,wBAAwB;IAehC;;;;;;OAMG;IACH,OAAO,CAAC,iBAAiB;IAuCzB,OAAO,CAAC,eAAe;IAMvB,OAAO,CAAC,YAAY;IAIpB,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAwB;IACtD,OAAO,CAAC,QAAQ,CAAQ;CACxB;AAED,qBAAa,+BAAgC,SAAQ,gCAAgC;IACpF,OAAO,CAAC,kBAAkB,CAA4B;;IAOtD,MAAM,IAAI,OAAO;IAIjB,IAAI,CAAC,CAAC,SAAS,OAAO,EAAE,EAAE,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,CAAC,KAAK,UAAU,CAAC,CAAC,CAAC,EAChE,OAAO,EAAE,OAAO,EAChB,EAAE,EAAE,CAAC,EACL,OAAO,CAAC,EAAE,iBAAiB,CAAC,CAAC,CAAC,EAC9B,GAAG,IAAI,EAAE,CAAC,GACR,UAAU,CAAC,CAAC,CAAC;IAKhB,MAAM,IAAI,IAAI;IAId,OAAO,IAAI,IAAI;CAIf"} \ No newline at end of file diff --git a/dist/cjs/context.js b/dist/cjs/context.js new file mode 100644 index 0000000..be2633a --- /dev/null +++ b/dist/cjs/context.js @@ -0,0 +1,215 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AsyncLocalStorageContextManager = void 0; +const api_1 = require("@opentelemetry/api"); +//@ts-ignore +const node_async_hooks_1 = require("node:async_hooks"); +//@ts-ignore +const node_events_1 = require("node:events"); +const ADD_LISTENER_METHODS = [ + 'addListener', + 'on', + 'once', + 'prependListener', + 'prependOnceListener', +]; +class AbstractAsyncHooksContextManager { + constructor() { + this._kOtListeners = Symbol('OtListeners'); + this._wrapped = false; + } + /** + * Binds a the certain context or the active one to the target function and then returns the target + * @param context A context (span) to be bind to target + * @param target a function or event emitter. When target or one of its callbacks is called, + * the provided context will be used as the active context for the duration of the call. + */ + bind(context, target) { + if (target instanceof node_events_1.EventEmitter) { + return this._bindEventEmitter(context, target); + } + if (typeof target === 'function') { + return this._bindFunction(context, target); + } + return target; + } + _bindFunction(context, target) { + const manager = this; + const contextWrapper = function (...args) { + return manager.with(context, () => target.apply(this, args)); + }; + Object.defineProperty(contextWrapper, 'length', { + enumerable: false, + configurable: true, + writable: false, + value: target.length, + }); + /** + * It isn't possible to tell Typescript that contextWrapper is the same as T + * so we forced to cast as any here. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return contextWrapper; + } + /** + * By default, EventEmitter call their callback with their context, which we do + * not want, instead we will bind a specific context to all callbacks that + * go through it. + * @param context the context we want to bind + * @param ee EventEmitter an instance of EventEmitter to patch + */ + _bindEventEmitter(context, ee) { + const map = this._getPatchMap(ee); + if (map !== undefined) + return ee; + this._createPatchMap(ee); + // patch methods that add a listener to propagate context + ADD_LISTENER_METHODS.forEach((methodName) => { + if (ee[methodName] === undefined) + return; + ee[methodName] = this._patchAddListener(ee, ee[methodName], context); + }); + // patch methods that remove a listener + if (typeof ee.removeListener === 'function') { + ee.removeListener = this._patchRemoveListener(ee, ee.removeListener); + } + if (typeof ee.off === 'function') { + ee.off = this._patchRemoveListener(ee, ee.off); + } + // patch method that remove all listeners + if (typeof ee.removeAllListeners === 'function') { + ee.removeAllListeners = this._patchRemoveAllListeners(ee, ee.removeAllListeners); + } + return ee; + } + /** + * Patch methods that remove a given listener so that we match the "patched" + * version of that listener (the one that propagate context). + * @param ee EventEmitter instance + * @param original reference to the patched method + */ + _patchRemoveListener(ee, original) { + const contextManager = this; + return function (event, listener) { + var _a; + const events = (_a = contextManager._getPatchMap(ee)) === null || _a === void 0 ? void 0 : _a[event]; + if (events === undefined) { + return original.call(this, event, listener); + } + const patchedListener = events.get(listener); + return original.call(this, event, patchedListener || listener); + }; + } + /** + * Patch methods that remove all listeners so we remove our + * internal references for a given event. + * @param ee EventEmitter instance + * @param original reference to the patched method + */ + _patchRemoveAllListeners(ee, original) { + const contextManager = this; + return function (event) { + const map = contextManager._getPatchMap(ee); + if (map !== undefined) { + if (arguments.length === 0) { + contextManager._createPatchMap(ee); + } + else if (map[event] !== undefined) { + delete map[event]; + } + } + return original.apply(this, arguments); + }; + } + /** + * Patch methods on an event emitter instance that can add listeners so we + * can force them to propagate a given context. + * @param ee EventEmitter instance + * @param original reference to the patched method + * @param [context] context to propagate when calling listeners + */ + _patchAddListener(ee, original, context) { + const contextManager = this; + return function (event, listener) { + /** + * This check is required to prevent double-wrapping the listener. + * The implementation for ee.once wraps the listener and calls ee.on. + * Without this check, we would wrap that wrapped listener. + * This causes an issue because ee.removeListener depends on the onceWrapper + * to properly remove the listener. If we wrap their wrapper, we break + * that detection. + */ + if (contextManager._wrapped) { + return original.call(this, event, listener); + } + let map = contextManager._getPatchMap(ee); + if (map === undefined) { + map = contextManager._createPatchMap(ee); + } + let listeners = map[event]; + if (listeners === undefined) { + listeners = new WeakMap(); + map[event] = listeners; + } + const patchedListener = contextManager.bind(context, listener); + // store a weak reference of the user listener to ours + listeners.set(listener, patchedListener); + /** + * See comment at the start of this function for the explanation of this property. + */ + contextManager._wrapped = true; + try { + return original.call(this, event, patchedListener); + } + finally { + contextManager._wrapped = false; + } + }; + } + _createPatchMap(ee) { + const map = Object.create(null); + ee[this._kOtListeners] = map; + return map; + } + _getPatchMap(ee) { + return ee[this._kOtListeners]; + } +} +class AsyncLocalStorageContextManager extends AbstractAsyncHooksContextManager { + constructor() { + super(); + this._asyncLocalStorage = new node_async_hooks_1.AsyncLocalStorage(); + } + active() { + var _a; + return (_a = this._asyncLocalStorage.getStore()) !== null && _a !== void 0 ? _a : api_1.ROOT_CONTEXT; + } + with(context, fn, thisArg, ...args) { + const cb = thisArg == null ? fn : fn.bind(thisArg); + return this._asyncLocalStorage.run(context, cb, ...args); + } + enable() { + return this; + } + disable() { + this._asyncLocalStorage.disable(); + return this; + } +} +exports.AsyncLocalStorageContextManager = AsyncLocalStorageContextManager; +//# sourceMappingURL=context.js.map \ No newline at end of file diff --git a/dist/cjs/context.js.map b/dist/cjs/context.js.map new file mode 100644 index 0000000..3859bcc --- /dev/null +++ b/dist/cjs/context.js.map @@ -0,0 +1 @@ +{"version":3,"file":"context.js","sourceRoot":"","sources":["../../src/context.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4CAA0E;AAC1E,YAAY;AACZ,uDAAoD;AACpD,YAAY;AACZ,6CAA0C;AAa1C,MAAM,oBAAoB,GAAG;IAC5B,aAAsB;IACtB,IAAa;IACb,MAAe;IACf,iBAA0B;IAC1B,qBAA8B;CAC9B,CAAA;AAED,MAAe,gCAAgC;IAA/C;QAgLkB,kBAAa,GAAG,MAAM,CAAC,aAAa,CAAC,CAAA;QAC9C,aAAQ,GAAG,KAAK,CAAA;IACzB,CAAC;IApKA;;;;;OAKG;IACH,IAAI,CAAI,OAAgB,EAAE,MAAS;QAClC,IAAI,MAAM,YAAY,0BAAY,EAAE,CAAC;YACpC,OAAO,IAAI,CAAC,iBAAiB,CAAC,OAAO,EAAE,MAAM,CAAC,CAAA;QAC/C,CAAC;QAED,IAAI,OAAO,MAAM,KAAK,UAAU,EAAE,CAAC;YAClC,OAAO,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,MAAM,CAAC,CAAA;QAC3C,CAAC;QACD,OAAO,MAAM,CAAA;IACd,CAAC;IAEO,aAAa,CAAqB,OAAgB,EAAE,MAAS;QACpE,MAAM,OAAO,GAAG,IAAI,CAAA;QACpB,MAAM,cAAc,GAAG,U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AAC;QACF,CAAC,CAAA;IACF,CAAC;IAEO,eAAe,CAAC,EAAgB;QACvC,MAAM,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAE9B;QAAC,EAAU,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,GAAG,CAAA;QACtC,OAAO,GAAG,CAAA;IACX,CAAC;IACO,YAAY,CAAC,EAAgB;QACpC,OAAQ,EAAY,CAAC,IAAI,CAAC,aAAa,CAAC,CAAA;IACzC,CAAC;CAID;AAED,MAAa,+BAAgC,SAAQ,gCAAgC;IAGpF;QACC,KAAK,EAAE,CAAA;QACP,IAAI,CAAC,kBAAkB,GAAG,IAAI,oCAAiB,EAAE,CAAA;IAClD,CAAC;IAED,MAAM;;QACL,OAAO,MAAA,IAAI,CAAC,kBAAkB,CAAC,QAAQ,EAAE,mCAAI,kBAAY,CAAA;IAC1D,CAAC;IAED,IAAI,CACH,OAAgB,EAChB,EAAK,EACL,OAA8B,EAC9B,GAAG,IAAO;QAEV,MAAM,EAAE,GAAG,OAAO,IAAI,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAClD,OAAO,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,OAAO,EAAE,EAAW,EAAE,GAAG,IAAI,CAAC,CAAA;IAClE,CAAC;IAED,MAAM;QACL,OAAO,IAAI,CAAA;IACZ,CAAC;IAED,OAAO;QACN,IAAI,CAAC,kBAAkB,CAAC,OAAO,EAAE,CAAA;QACjC,OAAO,IAAI,CAAA;IACZ,CAAC;CACD;AA9BD,0EA8BC"} \ No newline at end of file diff --git a/dist/cjs/exporter.d.ts b/dist/cjs/exporter.d.ts new file mode 100644 index 0000000..5842fc5 --- /dev/null +++ b/dist/cjs/exporter.d.ts @@ -0,0 +1,17 @@ +import { OTLPExporterError } from '@opentelemetry/otlp-exporter-base'; +import { ExportResult } from '@opentelemetry/core'; +import { SpanExporter } from '@opentelemetry/sdk-trace-base'; +export interface OTLPExporterConfig { + url: string; + headers?: Record; +} +export declare class OTLPExporter implements SpanExporter { + private headers; + private url; + constructor(config: OTLPExporterConfig); + export(items: any[], resultCallback: (result: ExportResult) => void): void; + private _export; + send(items: any[], onSuccess: () => void, onError: (error: OTLPExporterError) => void): void; + shutdown(): Promise; +} +//# sourceMappingURL=exporter.d.ts.map \ No newline at end of file diff --git a/dist/cjs/exporter.d.ts.map b/dist/cjs/exporter.d.ts.map new file mode 100644 index 0000000..df6f7af --- /dev/null +++ b/dist/cjs/exporter.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"exporter.d.ts","sourceRoot":"","sources":["../../src/exporter.ts"],"names":[],"mappings":"AACA,OAAO,EAAsB,iBAAiB,EAAE,MAAM,mCAAmC,CAAA;AACzF,OAAO,EAAE,YAAY,EAAoB,MAAM,qBAAqB,CAAA;AACpE,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAA;AAG5D,MAAM,WAAW,kBAAkB;IAClC,GAAG,EAAE,MAAM,CAAA;IACX,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAChC;AAOD,qBAAa,YAAa,YAAW,YAAY;IAChD,OAAO,CAAC,OAAO,CAAwB;IACvC,OAAO,CAAC,GAAG,CAAQ;gBACP,MAAM,EAAE,kBAAkB;IAKtC,MAAM,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,cAAc,EAAE,CAAC,MAAM,EAAE,YAAY,KAAK,IAAI,GAAG,IAAI;IAU1E,OAAO,CAAC,OAAO;IAUf,IAAI,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,SAAS,EAAE,MAAM,IAAI,EAAE,OAAO,EAAE,CAAC,KAAK,EAAE,iBAAiB,KAAK,IAAI,GAAG,IAAI;IAyBtF,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;CAC/B"} \ No newline at end of file diff --git a/dist/cjs/exporter.js b/dist/cjs/exporter.js new file mode 100644 index 0000000..163455c --- /dev/null +++ b/dist/cjs/exporter.js @@ -0,0 +1,74 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OTLPExporter = void 0; +const otlp_transformer_1 = require("@opentelemetry/otlp-transformer"); +const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base"); +const core_1 = require("@opentelemetry/core"); +const wrap_js_1 = require("./wrap.js"); +const defaultHeaders = { + accept: 'application/json', + 'content-type': 'application/json', +}; +class OTLPExporter { + constructor(config) { + this.url = config.url; + this.headers = Object.assign({}, defaultHeaders, config.headers); + } + export(items, resultCallback) { + this._export(items) + .then(() => { + resultCallback({ code: core_1.ExportResultCode.SUCCESS }); + }) + .catch((error) => { + resultCallback({ code: core_1.ExportResultCode.FAILED, error }); + }); + } + _export(items) { + return new Promise((resolve, reject) => { + try { + this.send(items, resolve, reject); + } + catch (e) { + reject(e); + } + }); + } + send(items, onSuccess, onError) { + const exportMessage = (0, otlp_transformer_1.createExportTraceServiceRequest)(items, { + useHex: true, + useLongBits: false, + }); + const body = JSON.stringify(exportMessage); + const params = { + method: 'POST', + headers: this.headers, + body, + }; + (0, wrap_js_1.unwrap)(fetch)(this.url, params) + .then((response) => { + if (response.ok) { + onSuccess(); + } + else { + onError(new otlp_exporter_base_1.OTLPExporterError(`Exporter received a statusCode: ${response.status}`)); + } + }) + .catch((error) => { + onError(new otlp_exporter_base_1.OTLPExporterError(`Exception during export: ${error.toString()}`, error.code, error.stack)); + }); + } + shutdown() { + return __awaiter(this, void 0, void 0, function* () { }); + } +} +exports.OTLPExporter = OTLPExporter; +//# sourceMappingURL=exporter.js.map \ No newline at end of file diff --git a/dist/cjs/exporter.js.map b/dist/cjs/exporter.js.map new file mode 100644 index 0000000..4c72201 --- /dev/null +++ b/dist/cjs/exporter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"exporter.js","sourceRoot":"","sources":["../../src/exporter.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,sEAAiF;AACjF,0EAAyF;AACzF,8CAAoE;AAEpE,uCAAkC;AAOlC,MAAM,cAAc,GAA2B;IAC9C,MAAM,EAAE,kBAAkB;IAC1B,cAAc,EAAE,kBAAkB;CAClC,CAAA;AAED,MAAa,YAAY;IAGxB,YAAY,MAA0B;QACrC,IAAI,CAAC,GAAG,GAAG,MAAM,CAAC,GAAG,CAAA;QACrB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,cAAc,EAAE,MAAM,CAAC,OAAO,CAAC,CAAA;IACjE,CAAC;IAED,MAAM,CAAC,KAAY,EAAE,cAA8C;QAClE,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC;aACjB,IAAI,CAAC,GAAG,EAAE;YACV,cAAc,CAAC,EAAE,IAAI,EAAE,uBAAgB,CAAC,OAAO,EAAE,CAAC,CAAA;QACnD,CAAC,CAAC;aACD,KAAK,CAAC,CAAC,KAAyB,EAAE,EAAE;YACpC,cAAc,CAAC,EAAE,IAAI,EAAE,uBAAgB,CAAC,MAAM,EAAE,KAAK,EAAE,CAAC,CAAA;QACzD,CAAC,CAAC,CAAA;IACJ,CAAC;IAEO,OAAO,CAAC,KAAY;QAC3B,OAAO,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YAC5C,IAAI,CAAC;gBACJ,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,CAAC,CAAA;YAClC,CAAC;YAAC,OAAO,CAAC,EAAE,CAAC;gBACZ,MAAM,CAAC,CAAC,CAAC,CAAA;YACV,CAAC;QACF,CAAC,CAAC,CAAA;IACH,CAAC;IAED,IAAI,CAAC,KAAY,EAAE,SAAqB,EAAE,OAA2C;QACpF,MAAM,aAAa,GAAG,IAAA,kDAA+B,EAAC,KAAK,EAAE;YAC5D,MAAM,EAAE,IAAI;YACZ,WAAW,EAAE,KAAK;SAClB,CAAC,CAAA;QACF,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,CAAA;QAC1C,MAAM,MAAM,GAAgB;YAC3B,MAAM,EAAE,MAAM;YACd,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,IAAI;SACJ,CAAA;QAED,IAAA,gBAAM,EAAC,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,MAAM,CAAC;aAC7B,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE;YAClB,IAAI,QAAQ,CAAC,EAAE,EAAE,CAAC;gBACjB,SAAS,EAAE,CAAA;YACZ,CAAC;iBAAM,CAAC;gBACP,OAAO,CAAC,IAAI,sCAAiB,CAAC,mCAAmC,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC,CAAA;YACrF,CAAC;QACF,CAAC,CAAC;aACD,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;YAChB,OAAO,CAAC,IAAI,sCAAiB,CAAC,4BAA4B,KAAK,CAAC,QAAQ,EAAE,EAAE,EAAE,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC,CAAA;QACxG,CAAC,CAAC,CAAA;IACJ,CAAC;IAEK,QAAQ;8DAAmB,CAAC;KAAA;CAClC;AAtDD,oCAsDC"} \ No newline at end of file diff --git a/dist/cjs/index.d.ts b/dist/cjs/index.d.ts new file mode 100644 index 0000000..56637cc --- /dev/null +++ b/dist/cjs/index.d.ts @@ -0,0 +1,10 @@ +export * from './buffer.js'; +export * from './sampling.js'; +export * from './sdk.js'; +export * from './span.js'; +export * from './exporter.js'; +export * from './multiexporter.js'; +export * from './spanprocessor.js'; +export { withNextSpan } from './tracer.js'; +export type * from './types.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/cjs/index.d.ts.map b/dist/cjs/index.d.ts.map new file mode 100644 index 0000000..9510ad3 --- /dev/null +++ b/dist/cjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAA;AAC3B,cAAc,eAAe,CAAA;AAC7B,cAAc,UAAU,CAAA;AACxB,cAAc,WAAW,CAAA;AACzB,cAAc,eAAe,CAAA;AAC7B,cAAc,oBAAoB,CAAA;AAClC,cAAc,oBAAoB,CAAA;AAClC,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAC1C,mBAAmB,YAAY,CAAA"} \ No newline at end of file diff --git a/dist/cjs/index.js b/dist/cjs/index.js new file mode 100644 index 0000000..2c20c11 --- /dev/null +++ b/dist/cjs/index.js @@ -0,0 +1,27 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.withNextSpan = void 0; +__exportStar(require("./buffer.js"), exports); +__exportStar(require("./sampling.js"), exports); +__exportStar(require("./sdk.js"), exports); +__exportStar(require("./span.js"), exports); +__exportStar(require("./exporter.js"), exports); +__exportStar(require("./multiexporter.js"), exports); +__exportStar(require("./spanprocessor.js"), exports); +var tracer_js_1 = require("./tracer.js"); +Object.defineProperty(exports, "withNextSpan", { enumerable: true, get: function () { return tracer_js_1.withNextSpan; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/cjs/index.js.map b/dist/cjs/index.js.map new file mode 100644 index 0000000..41da903 --- /dev/null +++ b/dist/cjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,8CAA2B;AAC3B,gDAA6B;AAC7B,2CAAwB;AACxB,4CAAyB;AACzB,gDAA6B;AAC7B,qDAAkC;AAClC,qDAAkC;AAClC,yCAA0C;AAAjC,yGAAA,YAAY,OAAA"} \ No newline at end of file diff --git a/dist/cjs/instrumentation/analytics-engine.d.ts b/dist/cjs/instrumentation/analytics-engine.d.ts new file mode 100644 index 0000000..99ca8f7 --- /dev/null +++ b/dist/cjs/instrumentation/analytics-engine.d.ts @@ -0,0 +1,2 @@ +export declare function instrumentAnalyticsEngineDataset(dataset: AnalyticsEngineDataset, name: string): AnalyticsEngineDataset; +//# sourceMappingURL=analytics-engine.d.ts.map \ No newline at end of file diff --git a/dist/cjs/instrumentation/analytics-engine.d.ts.map b/dist/cjs/instrumentation/analytics-engine.d.ts.map new file mode 100644 index 0000000..edb40e4 --- /dev/null +++ b/dist/cjs/instrumentation/analytics-engine.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"analytics-engine.d.ts","sourceRoot":"","sources":["../../../src/instrumentation/analytics-engine.ts"],"names":[],"mappings":"AAkDA,wBAAgB,gCAAgC,CAC/C,OAAO,EAAE,sBAAsB,EAC/B,IAAI,EAAE,MAAM,GACV,sBAAsB,CASxB"} \ No newline at end of file diff --git a/dist/cjs/instrumentation/analytics-engine.js b/dist/cjs/instrumentation/analytics-engine.js new file mode 100644 index 0000000..ae61fd6 --- /dev/null +++ b/dist/cjs/instrumentation/analytics-engine.js @@ -0,0 +1,67 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.instrumentAnalyticsEngineDataset = instrumentAnalyticsEngineDataset; +const api_1 = require("@opentelemetry/api"); +const semantic_conventions_1 = require("@opentelemetry/semantic-conventions"); +const wrap_js_1 = require("../wrap.js"); +const dbSystem = 'Cloudflare Analytics Engine'; +const AEAttributes = { + writeDataPoint(argArray) { + const attrs = {}; + const opts = argArray[0]; + if (typeof opts === 'object') { + attrs['db.cf.ae.indexes'] = opts.indexes.length; + attrs['db.cf.ae.index'] = opts.indexes[0].toString(); + attrs['db.cf.ae.doubles'] = opts.doubles.length; + attrs['db.cf.ae.blobs'] = opts.blobs.length; + } + return attrs; + }, +}; +function instrumentAEFn(fn, name, operation) { + const tracer = api_1.trace.getTracer('AnalyticsEngine'); + const fnHandler = { + apply: (target, thisArg, argArray) => { + const attributes = { + binding_type: 'AnalyticsEngine', + [semantic_conventions_1.SemanticAttributes.DB_NAME]: name, + [semantic_conventions_1.SemanticAttributes.DB_SYSTEM]: dbSystem, + [semantic_conventions_1.SemanticAttributes.DB_OPERATION]: operation, + }; + const options = { + kind: api_1.SpanKind.CLIENT, + attributes, + }; + return tracer.startActiveSpan(`Analytics Engine ${name} ${operation}`, options, (span) => __awaiter(this, void 0, void 0, function* () { + const result = yield Reflect.apply(target, thisArg, argArray); + const extraAttrsFn = AEAttributes[operation]; + const extraAttrs = extraAttrsFn ? extraAttrsFn(argArray, result) : {}; + span.setAttributes(extraAttrs); + span.setAttribute(semantic_conventions_1.SemanticAttributes.DB_STATEMENT, `${operation} ${argArray[0]}`); + span.end(); + return result; + })); + }, + }; + return (0, wrap_js_1.wrap)(fn, fnHandler); +} +function instrumentAnalyticsEngineDataset(dataset, name) { + const datasetHandler = { + get: (target, prop, receiver) => { + const operation = String(prop); + const fn = Reflect.get(target, prop, receiver); + return instrumentAEFn(fn, name, operation); + }, + }; + return (0, wrap_js_1.wrap)(dataset, datasetHandler); +} +//# sourceMappingURL=analytics-engine.js.map \ No newline at end of file diff --git a/dist/cjs/instrumentation/analytics-engine.js.map b/dist/cjs/instrumentation/analytics-engine.js.map new file mode 100644 index 0000000..e9723a5 --- /dev/null +++ b/dist/cjs/instrumentation/analytics-engine.js.map @@ -0,0 +1 @@ +{"version":3,"file":"analytics-engine.js","sourceRoot":"","sources":["../../../src/instrumentation/analytics-engine.ts"],"names":[],"mappings":";;;;;;;;;;;AAkDA,4EAYC;AA9DD,4CAA6E;AAC7E,8EAAwE;AACxE,wCAAiC;AAIjC,MAAM,QAAQ,GAAG,6BAA6B,CAAA;AAE9C,MAAM,YAAY,GAA8C;IAC/D,cAAc,CAAC,QAAQ;QACtB,MAAM,KAAK,GAAe,EAAE,CAAA;QAC5B,MAAM,IAAI,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAA;QACxB,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC9B,KAAK,CAAC,kBAAkB,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAA;YAC/C,KAAK,CAAC,gBAAgB,CAAC,GAAI,IAAI,CAAC,OAAO,CAAC,CAAC,CAA0B,CAAC,QAAQ,EAAE,CAAA;YAC9E,KAAK,CAAC,kBAAkB,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAA;YAC/C,KAAK,CAAC,gBAAgB,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAA;QAC5C,CAAC;QACD,OAAO,KAAK,CAAA;IACb,CAAC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EAAE,EAAE,SAAS,CAAC,CAAA;AAC3B,CAAC;AAED,SAAgB,gCAAgC,CAC/C,OAA+B,EAC/B,IAAY;IAEZ,MAAM,cAAc,GAAyC;QAC5D,GAAG,EAAE,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE;YAC/B,MAAM,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,CAAA;YAC9B,MAAM,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAA;YAC9C,OAAO,cAAc,CAAC,EAAE,EAAE,IAAI,EAAE,SAAS,CAAC,CAAA;QAC3C,CAAC;KACD,CAAA;IACD,OAAO,IAAA,cAAI,EAAC,OAAO,EAAE,cAAc,CAAC,CAAA;AACrC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/instrumentation/cache.d.ts b/dist/cjs/instrumentation/cache.d.ts new file mode 100644 index 0000000..b75bf3c --- /dev/null +++ b/dist/cjs/instrumentation/cache.d.ts @@ -0,0 +1,2 @@ +export declare function instrumentGlobalCache(): void; +//# sourceMappingURL=cache.d.ts.map \ No newline at end of file diff --git a/dist/cjs/instrumentation/cache.d.ts.map b/dist/cjs/instrumentation/cache.d.ts.map new file mode 100644 index 0000000..db3f9ce --- /dev/null +++ b/dist/cjs/instrumentation/cache.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"cache.d.ts","sourceRoot":"","sources":["../../../src/instrumentation/cache.ts"],"names":[],"mappings":"AA6EA,wBAAgB,qBAAqB,SAEpC"} \ No newline at end of file diff --git a/dist/cjs/instrumentation/cache.js b/dist/cjs/instrumentation/cache.js new file mode 100644 index 0000000..8686dc6 --- /dev/null +++ b/dist/cjs/instrumentation/cache.js @@ -0,0 +1,91 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.instrumentGlobalCache = instrumentGlobalCache; +const api_1 = require("@opentelemetry/api"); +const wrap_js_1 = require("../wrap.js"); +const tracer = api_1.trace.getTracer('cache instrumentation'); +function sanitiseURL(url) { + const u = new URL(url); + return `${u.protocol}//${u.host}${u.pathname}${u.search}`; +} +function instrumentFunction(fn, cacheName, op) { + const handler = { + apply(target, thisArg, argArray) { + return __awaiter(this, void 0, void 0, function* () { + const attributes = { + 'cache.name': cacheName, + 'http.url': argArray[0].url ? sanitiseURL(argArray[0].url) : undefined, + 'cache.operation': op, + }; + const options = { kind: api_1.SpanKind.CLIENT, attributes }; + return tracer.startActiveSpan(`Cache ${cacheName} ${op}`, options, (span) => __awaiter(this, void 0, void 0, function* () { + const result = yield Reflect.apply(target, thisArg, argArray); + if (op === 'match') { + span.setAttribute('cache.hit', !!result); + } + span.end(); + return result; + })); + }); + }, + }; + return (0, wrap_js_1.wrap)(fn, handler); +} +function instrumentCache(cache, cacheName) { + const handler = { + get(target, prop) { + if (prop === 'delete' || prop === 'match' || prop === 'put') { + const fn = Reflect.get(target, prop).bind(target); + return instrumentFunction(fn, cacheName, prop); + } + else { + return Reflect.get(target, prop); + } + }, + }; + return (0, wrap_js_1.wrap)(cache, handler); +} +function instrumentOpen(openFn) { + const handler = { + apply(target, thisArg, argArray) { + return __awaiter(this, void 0, void 0, function* () { + const cacheName = argArray[0]; + const cache = yield Reflect.apply(target, thisArg, argArray); + return instrumentCache(cache, cacheName); + }); + }, + }; + return (0, wrap_js_1.wrap)(openFn, handler); +} +function _instrumentGlobalCache() { + const handler = { + get(target, prop) { + if (prop === 'default') { + const cache = target.default; + return instrumentCache(cache, 'default'); + } + else if (prop === 'open') { + const openFn = Reflect.get(target, prop).bind(target); + return instrumentOpen(openFn); + } + else { + return Reflect.get(target, prop); + } + }, + }; + //@ts-ignore + globalThis.caches = (0, wrap_js_1.wrap)(caches, handler); +} +function instrumentGlobalCache() { + return _instrumentGlobalCache(); +} +//# sourceMappingURL=cache.js.map \ No newline at end of file diff --git a/dist/cjs/instrumentation/cache.js.map b/dist/cjs/instrumentation/cache.js.map new file mode 100644 index 0000000..a709515 --- /dev/null +++ b/dist/cjs/instrumentation/cache.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cache.js","sourceRoot":"","sources":["../../../src/instrumentation/cache.ts"],"names":[],"mappings":";;;;;;;;;;;AA6EA,sDAEC;AA/ED,4CAAiE;AACjE,wCAAiC;AAIjC,MAAM,MAAM,GAAG,WAAK,CAAC,SAAS,CAAC,uBAAuB,CAAC,CAAA;AAEvD,SAAS,WAAW,CAAC,GAAW;IAC/B,MAAM,CAAC,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAA;IACtB,OAAO,GAAG,CAAC,CAAC,QAAQ,KAAK,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,MAAM,EAAE,CAAA;AAC1D,CAAC;AAED,SAAS,kBAAkB,CAAqB,EAAK,EAAE,SAAiB,EAAE,EAAU;IACnF,MAAM,OAAO,GAA4B;QAClC,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ;;gBACpC,MAAM,UAAU,GAAG;oBAClB,YAAY,EAAE,SAAS;oBACvB,UAAU,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS;oBACtE,iBAAiB,EAAE,EAAE;iBACrB,CAAA;gBACD,MAAM,OAAO,GAAgB,EAAE,IAAI,EAAE,cAAQ,CAAC,MAAM,EAAE,UAAU,EAAE,CAAA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G,QAAQ,CAAC,CAAC,CAAC,CAAA;gBAC7B,MAAM,KAAK,GAAG,MAAM,OAAO,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAA;gBAC5D,OAAO,eAAe,CAAC,KAAK,EAAE,SAAS,CAAC,CAAA;YACzC,CAAC;SAAA;KACD,CAAA;IACD,OAAO,IAAA,cAAI,EAAC,MAAM,EAAE,OAAO,CAAC,CAAA;AAC7B,CAAC;AAED,SAAS,sBAAsB;IAC9B,MAAM,OAAO,GAAgC;QAC5C,GAAG,CAAC,MAAM,EAAE,IAAI;YACf,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;gBACxB,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,CAAA;gBAC5B,OAAO,eAAe,CAAC,KAAK,EAAE,SAAS,CAAC,CAAA;YACzC,CAAC;iBAAM,IAAI,IAAI,KAAK,MAAM,EAAE,CAAC;gBAC5B,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;gBACrD,OAAO,cAAc,CAAC,MAAM,CAAC,CAAA;YAC9B,CAAC;iBAAM,CAAC;gBACP,OAAO,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;YACjC,CAAC;QACF,CAAC;KACD,CAAA;IACD,YAAY;IACZ,UAAU,CAAC,MAAM,GAAG,IAAA,cAAI,EAAC,MAAM,EAAE,OAAO,CAAC,CAAA;AAC1C,CAAC;AAED,SAAgB,qBAAqB;IACpC,OAAO,sBAAsB,EAAE,CAAA;AAChC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/instrumentation/common.d.ts b/dist/cjs/instrumentation/common.d.ts new file mode 100644 index 0000000..3c59dd1 --- /dev/null +++ b/dist/cjs/instrumentation/common.d.ts @@ -0,0 +1,21 @@ +type ContextAndTracker = { + ctx: ExecutionContext; + tracker: PromiseTracker; +}; +export declare class PromiseTracker { + _outstandingPromises: Promise[]; + get outstandingPromiseCount(): number; + track(promise: Promise): void; + wait(): Promise; +} +export declare function proxyExecutionContext(context: ExecutionContext): ContextAndTracker; +export declare function exportSpans(tracker?: PromiseTracker): Promise; +/** Overloads extracts up to 4 overloads for the given function. */ +export type Overloads = T extends { + (...args: infer P1): infer R1; + (...args: infer P2): infer R2; + (...args: infer P3): infer R3; + (...args: infer P4): infer R4; +} ? ((...args: P1) => R1) | ((...args: P2) => R2) | ((...args: P3) => R3) | ((...args: P4) => R4) : never; +export {}; +//# sourceMappingURL=common.d.ts.map \ No newline at end of file diff --git a/dist/cjs/instrumentation/common.d.ts.map b/dist/cjs/instrumentation/common.d.ts.map new file mode 100644 index 0000000..8d4837c --- /dev/null +++ b/dist/cjs/instrumentation/common.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../../../src/instrumentation/common.ts"],"names":[],"mappings":"AAIA,KAAK,iBAAiB,GAAG;IAAE,GAAG,EAAE,gBAAgB,CAAC;IAAC,OAAO,EAAE,cAAc,CAAA;CAAE,CAAA;AAG3E,qBAAa,cAAc;IAC1B,oBAAoB,EAAE,OAAO,CAAC,OAAO,CAAC,EAAE,CAAK;IAE7C,IAAI,uBAAuB,WAE1B;IAED,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,IAAI;IAIhC,IAAI;CAGV;AAYD,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,gBAAgB,GAAG,iBAAiB,CAalF;AAED,wBAAsB,WAAW,CAAC,OAAO,CAAC,EAAE,cAAc,iBAczD;AAaD,mEAAmE;AACnE,MAAM,MAAM,SAAS,CAAC,CAAC,IAAI,CAAC,SAAS;IACpC,CAAC,GAAG,IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAAA;IAC7B,CAAC,GAAG,IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAAA;IAC7B,CAAC,GAAG,IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAAA;IAC7B,CAAC,GAAG,IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAAA;CAC7B,GACE,CAAC,CAAC,GAAG,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,GAC7F,KAAK,CAAA"} \ No newline at end of file diff --git a/dist/cjs/instrumentation/common.js b/dist/cjs/instrumentation/common.js new file mode 100644 index 0000000..c8a9b82 --- /dev/null +++ b/dist/cjs/instrumentation/common.js @@ -0,0 +1,89 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PromiseTracker = void 0; +exports.proxyExecutionContext = proxyExecutionContext; +exports.exportSpans = exportSpans; +const api_1 = require("@opentelemetry/api"); +const tracer_js_1 = require("../tracer.js"); +const wrap_js_1 = require("../wrap.js"); +class PromiseTracker { + constructor() { + this._outstandingPromises = []; + } + get outstandingPromiseCount() { + return this._outstandingPromises.length; + } + track(promise) { + this._outstandingPromises.push(promise); + } + wait() { + return __awaiter(this, void 0, void 0, function* () { + yield allSettledMutable(this._outstandingPromises); + }); + } +} +exports.PromiseTracker = PromiseTracker; +function createWaitUntil(fn, context, tracker) { + const handler = { + apply(target, _thisArg, argArray) { + tracker.track(argArray[0]); + return Reflect.apply(target, context, argArray); + }, + }; + return (0, wrap_js_1.wrap)(fn, handler); +} +function proxyExecutionContext(context) { + const tracker = new PromiseTracker(); + const ctx = new Proxy(context, { + get(target, prop) { + if (prop === 'waitUntil') { + const fn = Reflect.get(target, prop); + return createWaitUntil(fn, context, tracker); + } + else { + return (0, wrap_js_1.passthroughGet)(target, prop); + } + }, + }); + return { ctx, tracker }; +} +function exportSpans(tracker) { + return __awaiter(this, void 0, void 0, function* () { + const tracer = api_1.trace.getTracer('export'); + if (tracer instanceof tracer_js_1.WorkerTracer) { + yield scheduler.wait(1); + if (tracker) { + yield tracker.wait(); + } + const promises = tracer.spanProcessors.map((spanProcessor) => __awaiter(this, void 0, void 0, function* () { + yield spanProcessor.forceFlush(); + })); + yield Promise.allSettled(promises); + } + else { + console.error('The global tracer is not of type WorkerTracer and can not export spans'); + } + }); +} +/** Like `Promise.allSettled`, but handles modifications to the promises array */ +function allSettledMutable(promises) { + return __awaiter(this, void 0, void 0, function* () { + let values; + // when the length of the array changes, there has been a nested call to waitUntil + // and we should await the promises again + do { + values = yield Promise.allSettled(promises); + } while (values.length !== promises.length); + return values; + }); +} +//# sourceMappingURL=common.js.map \ No newline at end of file diff --git a/dist/cjs/instrumentation/common.js.map b/dist/cjs/instrumentation/common.js.map new file mode 100644 index 0000000..469d00d --- /dev/null +++ b/dist/cjs/instrumentation/common.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common.js","sourceRoot":"","sources":["../../../src/instrumentation/common.ts"],"names":[],"mappings":";;;;;;;;;;;;AAiCA,sDAaC;AAED,kCAcC;AA9DD,4CAA0C;AAC1C,4CAA2C;AAC3C,wCAAiD;AAKjD,MAAa,cAAc;IAA3B;QACC,yBAAoB,GAAuB,EAAE,CAAA;IAa9C,CAAC;IAXA,IAAI,uBAAuB;QAC1B,OAAO,IAAI,CAAC,oBAAoB,CAAC,MAAM,CAAA;IACxC,CAAC;IAED,KAAK,CAAC,OAAyB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Y,wBAAY,EAAE,CAAC;YACpC,MAAM,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;YACvB,IAAI,OAAO,EAAE,CAAC;gBACb,MAAM,OAAO,CAAC,IAAI,EAAE,CAAA;YACrB,CAAC;YACD,MAAM,QAAQ,GAAG,MAAM,CAAC,cAAc,CAAC,GAAG,CAAC,CAAO,aAAa,EAAE,EAAE;gBAClE,MAAM,aAAa,CAAC,UAAU,EAAE,CAAA;YACjC,CAAC,CAAA,CAAC,CAAA;YACF,MAAM,OAAO,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAA;QACnC,CAAC;aAAM,CAAC;YACP,OAAO,CAAC,KAAK,CAAC,wEAAwE,CAAC,CAAA;QACxF,CAAC;IACF,CAAC;CAAA;AAED,iFAAiF;AACjF,SAAe,iBAAiB,CAAC,QAA4B;;QAC5D,IAAI,MAAuC,CAAA;QAC3C,kFAAkF;QAClF,yCAAyC;QACzC,GAAG,CAAC;YACH,MAAM,GAAG,MAAM,OAAO,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAA;QAC5C,CAAC,QAAQ,MAAM,CAAC,MAAM,KAAK,QAAQ,CAAC,MAAM,EAAC;QAC3C,OAAO,MAAM,CAAA;IACd,CAAC;CAAA"} \ No newline at end of file diff --git a/dist/cjs/instrumentation/do-storage.d.ts b/dist/cjs/instrumentation/do-storage.d.ts new file mode 100644 index 0000000..2d9a8f3 --- /dev/null +++ b/dist/cjs/instrumentation/do-storage.d.ts @@ -0,0 +1,2 @@ +export declare function instrumentStorage(storage: DurableObjectStorage): DurableObjectStorage; +//# sourceMappingURL=do-storage.d.ts.map \ No newline at end of file diff --git a/dist/cjs/instrumentation/do-storage.d.ts.map b/dist/cjs/instrumentation/do-storage.d.ts.map new file mode 100644 index 0000000..4df17b8 --- /dev/null +++ b/dist/cjs/instrumentation/do-storage.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"do-storage.d.ts","sourceRoot":"","sources":["../../../src/instrumentation/do-storage.ts"],"names":[],"mappings":"AAgMA,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,oBAAoB,GAAG,oBAAoB,CASrF"} \ No newline at end of file diff --git a/dist/cjs/instrumentation/do-storage.js b/dist/cjs/instrumentation/do-storage.js new file mode 100644 index 0000000..e5a8dfb --- /dev/null +++ b/dist/cjs/instrumentation/do-storage.js @@ -0,0 +1,204 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.instrumentStorage = instrumentStorage; +const api_1 = require("@opentelemetry/api"); +const semantic_conventions_1 = require("@opentelemetry/semantic-conventions"); +const wrap_js_1 = require("../wrap.js"); +const dbSystem = 'Cloudflare DO'; +function isDurableObjectCommonOptions(options) { + return (typeof options === 'object' && + ('allowConcurrency' in options || 'allowUnconfirmed' in options || 'noCache' in options)); +} +/** Applies attributes for common Durable Objects options: + * `allowConcurrency`, `allowUnconfirmed`, and `noCache` + */ +function applyOptionsAttributes(attrs, options) { + if ('allowConcurrency' in options) { + attrs['db.cf.do.allow_concurrency'] = options.allowConcurrency; + } + if ('allowUnconfirmed' in options) { + attrs['db.cf.do.allow_unconfirmed'] = options.allowUnconfirmed; + } + if ('noCache' in options) { + attrs['db.cf.do.no_cache'] = options.noCache; + } +} +const StorageAttributes = { + delete(argArray, result) { + const args = argArray; + let attrs = {}; + if (Array.isArray(args[0])) { + const keys = args[0]; + attrs = { + // todo: Maybe set db.cf.do.keys to the whole array here? + 'db.cf.do.key': keys[0], + 'db.cf.do.number_of_keys': keys.length, + 'db.cf.do.keys_deleted': result, + }; + } + else { + attrs = { + 'db.cf.do.key': args[0], + 'db.cf.do.success': result, + }; + } + if (args[1]) { + applyOptionsAttributes(attrs, args[1]); + } + return attrs; + }, + deleteAll(argArray) { + const args = argArray; + let attrs = {}; + if (args[0]) { + applyOptionsAttributes(attrs, args[0]); + } + return attrs; + }, + get(argArray) { + const args = argArray; + let attrs = {}; + if (Array.isArray(args[0])) { + const keys = args[0]; + attrs = { + // todo: Maybe set db.cf.do.keys to the whole array here? + 'db.cf.do.key': keys[0], + 'db.cf.do.number_of_keys': keys.length, + }; + } + else { + attrs = { + 'db.cf.do.key': args[0], + }; + } + if (args[1]) { + applyOptionsAttributes(attrs, args[1]); + } + return attrs; + }, + list(argArray, result) { + const args = argArray; + const attrs = { + 'db.cf.do.number_of_results': result.size, + }; + if (args[0]) { + const options = args[0]; + applyOptionsAttributes(attrs, options); + if ('start' in options) { + attrs['db.cf.do.start'] = options.start; + } + if ('startAfter' in options) { + attrs['db.cf.do.start_after'] = options.startAfter; + } + if ('end' in options) { + attrs['db.cf.do.end'] = options.end; + } + if ('prefix' in options) { + attrs['db.cf.do.prefix'] = options.prefix; + } + if ('reverse' in options) { + attrs['db.cf.do.reverse'] = options.reverse; + } + if ('limit' in options) { + attrs['db.cf.do.limit'] = options.limit; + } + } + return attrs; + }, + put(argArray) { + const args = argArray; + const attrs = {}; + if (typeof args[0] === 'string') { + attrs['db.cf.do.key'] = args[0]; + if (args[2]) { + applyOptionsAttributes(attrs, args[2]); + } + } + else { + const keys = Object.keys(args[0]); + // todo: Maybe set db.cf.do.keys to the whole array here? + attrs['db.cf.do.key'] = keys[0]; + attrs['db.cf.do.number_of_keys'] = keys.length; + if (isDurableObjectCommonOptions(args[1])) { + applyOptionsAttributes(attrs, args[1]); + } + } + return attrs; + }, + getAlarm(argArray) { + const args = argArray; + const attrs = {}; + if (args[0]) { + applyOptionsAttributes(attrs, args[0]); + } + return attrs; + }, + setAlarm(argArray) { + const args = argArray; + const attrs = {}; + if (args[0] instanceof Date) { + attrs['db.cf.do.alarm_time'] = args[0].getTime(); + } + else { + attrs['db.cf.do.alarm_time'] = args[0]; + } + if (args[1]) { + applyOptionsAttributes(attrs, args[1]); + } + return attrs; + }, + deleteAlarm(argArray) { + const args = argArray; + const attrs = {}; + if (args[0]) { + applyOptionsAttributes(attrs, args[0]); + } + return attrs; + }, +}; +function instrumentStorageFn(fn, operation) { + const tracer = api_1.trace.getTracer('do_storage'); + const fnHandler = { + apply: (target, thisArg, argArray) => { + const attributes = { + [semantic_conventions_1.SemanticAttributes.DB_SYSTEM]: dbSystem, + [semantic_conventions_1.SemanticAttributes.DB_OPERATION]: operation, + [semantic_conventions_1.SemanticAttributes.DB_STATEMENT]: `${operation} ${argArray[0]}`, + }; + const options = { + kind: api_1.SpanKind.CLIENT, + attributes: Object.assign(Object.assign({}, attributes), { operation }), + }; + return tracer.startActiveSpan(`Durable Object Storage ${operation}`, options, (span) => __awaiter(this, void 0, void 0, function* () { + const result = yield Reflect.apply(target, thisArg, argArray); + const extraAttrsFn = StorageAttributes[operation]; + const extraAttrs = extraAttrsFn ? extraAttrsFn(argArray, result) : {}; + span.setAttributes(extraAttrs); + span.setAttribute('db.cf.do.has_result', !!result); + span.end(); + return result; + })); + }, + }; + return (0, wrap_js_1.wrap)(fn, fnHandler); +} +function instrumentStorage(storage) { + const storageHandler = { + get: (target, prop, receiver) => { + const operation = String(prop); + const fn = Reflect.get(target, prop, receiver); + return instrumentStorageFn(fn, operation); + }, + }; + return (0, wrap_js_1.wrap)(storage, storageHandler); +} +//# sourceMappingURL=do-storage.js.map \ No newline at end of file diff --git a/dist/cjs/instrumentation/do-storage.js.map b/dist/cjs/instrumentation/do-storage.js.map new file mode 100644 index 0000000..c5bee73 --- /dev/null +++ b/dist/cjs/instrumentation/do-storage.js.map @@ -0,0 +1 @@ +{"version":3,"file":"do-storage.js","sourceRoot":"","sources":["../../../src/instrumentation/do-storage.ts"],"names":[],"mappings":";;;;;;;;;;;AA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ACrE,IAAI,CAAC,aAAa,CAAC,UAAU,CAAC,CAAA;gBAC9B,IAAI,CAAC,YAAY,CAAC,qBAAqB,EAAE,CAAC,CAAC,MAAM,CAAC,CAAA;gBAClD,IAAI,CAAC,GAAG,EAAE,CAAA;gBACV,OAAO,MAAM,CAAA;YACd,CAAC,CAAA,CAAC,CAAA;QACH,CAAC;KACD,CAAA;IACD,OAAO,IAAA,cAAI,EAAC,EAAE,EAAE,SAAS,CAAC,CAAA;AAC3B,CAAC;AAED,SAAgB,iBAAiB,CAAC,OAA6B;IAC9D,MAAM,cAAc,GAAuC;QAC1D,GAAG,EAAE,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE;YAC/B,MAAM,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,CAAA;YAC9B,MAAM,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAA;YAC9C,OAAO,mBAAmB,CAAC,EAAE,EAAE,SAAS,CAAC,CAAA;QAC1C,CAAC;KACD,CAAA;IACD,OAAO,IAAA,cAAI,EAAC,OAAO,EAAE,cAAc,CAAC,CAAA;AACrC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/instrumentation/do.d.ts b/dist/cjs/instrumentation/do.d.ts new file mode 100644 index 0000000..261ea52 --- /dev/null +++ b/dist/cjs/instrumentation/do.d.ts @@ -0,0 +1,13 @@ +import { Initialiser } from '../config.js'; +type FetchFn = DurableObject['fetch']; +type AlarmFn = DurableObject['alarm']; +export declare function instrumentDOBinding(ns: DurableObjectNamespace, nsName: string): DurableObjectNamespace; +export declare function instrumentState(state: DurableObjectState): DurableObjectState; +export type DOClass = { + new (state: DurableObjectState, env: any): DurableObject; +}; +export declare function executeDOFetch(fetchFn: FetchFn, request: Request, id: DurableObjectId): Promise; +export declare function executeDOAlarm(alarmFn: NonNullable, id: DurableObjectId): Promise; +export declare function instrumentDOClass(doClass: DOClass, initialiser: Initialiser): DOClass; +export {}; +//# sourceMappingURL=do.d.ts.map \ No newline at end of file diff --git a/dist/cjs/instrumentation/do.d.ts.map b/dist/cjs/instrumentation/do.d.ts.map new file mode 100644 index 0000000..108dc6c --- /dev/null +++ b/dist/cjs/instrumentation/do.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"do.d.ts","sourceRoot":"","sources":["../../../src/instrumentation/do.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,WAAW,EAAa,MAAM,cAAc,CAAA;AAKrD,KAAK,OAAO,GAAG,aAAa,CAAC,OAAO,CAAC,CAAA;AACrC,KAAK,OAAO,GAAG,aAAa,CAAC,OAAO,CAAC,CAAA;AAiCrC,wBAAgB,mBAAmB,CAAC,EAAE,EAAE,sBAAsB,EAAE,MAAM,EAAE,MAAM,qCAY7E;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,kBAAkB,sBAcxD;AAGD,MAAM,MAAM,OAAO,GAAG;IAAE,KAAK,KAAK,EAAE,kBAAkB,EAAE,GAAG,EAAE,GAAG,GAAG,aAAa,CAAA;CAAE,CAAA;AAClF,wBAAgB,cAAc,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,eAAe,GAAG,OAAO,CAAC,QAAQ,CAAC,CAmCzG;AAED,wBAAgB,cAAc,CAAC,OAAO,EAAE,WAAW,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAqBhG;AA8DD,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,WAAW,GAAG,OAAO,CAoBrF"} \ No newline at end of file diff --git a/dist/cjs/instrumentation/do.js b/dist/cjs/instrumentation/do.js new file mode 100644 index 0000000..ff020ad --- /dev/null +++ b/dist/cjs/instrumentation/do.js @@ -0,0 +1,229 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.instrumentDOBinding = instrumentDOBinding; +exports.instrumentState = instrumentState; +exports.executeDOFetch = executeDOFetch; +exports.executeDOAlarm = executeDOAlarm; +exports.instrumentDOClass = instrumentDOClass; +const api_1 = require("@opentelemetry/api"); +const semantic_conventions_1 = require("@opentelemetry/semantic-conventions"); +const wrap_js_1 = require("../wrap.js"); +const fetch_js_1 = require("./fetch.js"); +const env_js_1 = require("./env.js"); +const config_js_1 = require("../config.js"); +const common_js_1 = require("./common.js"); +const do_storage_js_1 = require("./do-storage.js"); +function instrumentBindingStub(stub, nsName) { + const stubHandler = { + get(target, prop) { + if (prop === 'fetch') { + const fetcher = Reflect.get(target, prop); + const attrs = { + name: `Durable Object ${nsName}`, + 'do.namespace': nsName, + 'do.id': target.id.toString(), + 'do.id.name': target.id.name, + }; + return (0, fetch_js_1.instrumentClientFetch)(fetcher, () => ({ includeTraceContext: true }), attrs); + } + else { + return (0, wrap_js_1.passthroughGet)(target, prop); + } + }, + }; + return (0, wrap_js_1.wrap)(stub, stubHandler); +} +function instrumentBindingGet(getFn, nsName) { + const getHandler = { + apply(target, thisArg, argArray) { + const stub = Reflect.apply(target, thisArg, argArray); + return instrumentBindingStub(stub, nsName); + }, + }; + return (0, wrap_js_1.wrap)(getFn, getHandler); +} +function instrumentDOBinding(ns, nsName) { + const nsHandler = { + get(target, prop) { + if (prop === 'get') { + const fn = Reflect.get(ns, prop); + return instrumentBindingGet(fn, nsName); + } + else { + return (0, wrap_js_1.passthroughGet)(target, prop); + } + }, + }; + return (0, wrap_js_1.wrap)(ns, nsHandler); +} +function instrumentState(state) { + const stateHandler = { + get(target, prop, receiver) { + const result = Reflect.get(target, prop, (0, wrap_js_1.unwrap)(receiver)); + if (prop === 'storage') { + return (0, do_storage_js_1.instrumentStorage)(result); + } + else if (typeof result === 'function') { + return result.bind(target); + } + else { + return result; + } + }, + }; + return (0, wrap_js_1.wrap)(state, stateHandler); +} +let cold_start = true; +function executeDOFetch(fetchFn, request, id) { + const spanContext = (0, fetch_js_1.getParentContextFromHeaders)(request.headers); + const tracer = api_1.trace.getTracer('DO fetchHandler'); + const attributes = { + [semantic_conventions_1.SemanticAttributes.FAAS_TRIGGER]: 'http', + [semantic_conventions_1.SemanticAttributes.FAAS_COLDSTART]: cold_start, + }; + cold_start = false; + Object.assign(attributes, (0, fetch_js_1.gatherRequestAttributes)(request)); + Object.assign(attributes, (0, fetch_js_1.gatherIncomingCfAttributes)(request)); + const options = { + attributes, + kind: api_1.SpanKind.SERVER, + }; + const name = id.name || ''; + const promise = tracer.startActiveSpan(`Durable Object Fetch ${name}`, options, spanContext, (span) => __awaiter(this, void 0, void 0, function* () { + try { + const response = yield fetchFn(request); + if (response.ok) { + span.setStatus({ code: api_1.SpanStatusCode.OK }); + } + span.setAttributes((0, fetch_js_1.gatherResponseAttributes)(response)); + span.end(); + return response; + } + catch (error) { + span.recordException(error); + span.setStatus({ code: api_1.SpanStatusCode.ERROR }); + span.end(); + throw error; + } + })); + return promise; +} +function executeDOAlarm(alarmFn, id) { + const tracer = api_1.trace.getTracer('DO alarmHandler'); + const name = id.name || ''; + const promise = tracer.startActiveSpan(`Durable Object Alarm ${name}`, (span) => __awaiter(this, void 0, void 0, function* () { + span.setAttribute(semantic_conventions_1.SemanticAttributes.FAAS_COLDSTART, cold_start); + cold_start = false; + span.setAttribute('do.id', id.toString()); + if (id.name) + span.setAttribute('do.name', id.name); + try { + yield alarmFn(); + span.end(); + } + catch (error) { + span.recordException(error); + span.setStatus({ code: api_1.SpanStatusCode.ERROR }); + span.end(); + throw error; + } + })); + return promise; +} +function instrumentFetchFn(fetchFn, initialiser, env, id) { + const fetchHandler = { + apply(target, thisArg, argArray) { + return __awaiter(this, void 0, void 0, function* () { + const request = argArray[0]; + const config = initialiser(env, request); + const context = (0, config_js_1.setConfig)(config); + try { + const bound = target.bind((0, wrap_js_1.unwrap)(thisArg)); + return yield api_1.context.with(context, executeDOFetch, undefined, bound, request, id); + } + catch (error) { + throw error; + } + finally { + (0, common_js_1.exportSpans)(); + } + }); + }, + }; + return (0, wrap_js_1.wrap)(fetchFn, fetchHandler); +} +function instrumentAlarmFn(alarmFn, initialiser, env, id) { + if (!alarmFn) + return undefined; + const alarmHandler = { + apply(target, thisArg) { + return __awaiter(this, void 0, void 0, function* () { + const config = initialiser(env, 'do-alarm'); + const context = (0, config_js_1.setConfig)(config); + try { + const bound = target.bind((0, wrap_js_1.unwrap)(thisArg)); + return yield api_1.context.with(context, executeDOAlarm, undefined, bound, id); + } + catch (error) { + throw error; + } + finally { + (0, common_js_1.exportSpans)(); + } + }); + }, + }; + return (0, wrap_js_1.wrap)(alarmFn, alarmHandler); +} +function instrumentDurableObject(doObj, initialiser, env, state) { + const objHandler = { + get(target, prop) { + if (prop === 'fetch') { + const fetchFn = Reflect.get(target, prop); + return instrumentFetchFn(fetchFn, initialiser, env, state.id); + } + else if (prop === 'alarm') { + const alarmFn = Reflect.get(target, prop); + return instrumentAlarmFn(alarmFn, initialiser, env, state.id); + } + else { + const result = Reflect.get(target, prop); + if (typeof result === 'function') { + result.bind(doObj); + } + return result; + } + }, + }; + return (0, wrap_js_1.wrap)(doObj, objHandler); +} +function instrumentDOClass(doClass, initialiser) { + const classHandler = { + construct(target, [orig_state, orig_env]) { + const trigger = { + id: orig_state.id.toString(), + name: orig_state.id.name, + }; + const constructorConfig = initialiser(orig_env, trigger); + const context = (0, config_js_1.setConfig)(constructorConfig); + const state = instrumentState(orig_state); + const env = (0, env_js_1.instrumentEnv)(orig_env); + const createDO = () => { + return new target(state, env); + }; + const doObj = api_1.context.with(context, createDO); + return instrumentDurableObject(doObj, initialiser, env, state); + }, + }; + return (0, wrap_js_1.wrap)(doClass, classHandler); +} +//# sourceMappingURL=do.js.map \ No newline at end of file diff --git a/dist/cjs/instrumentation/do.js.map b/dist/cjs/instrumentation/do.js.map new file mode 100644 index 0000000..04aed2d --- /dev/null +++ b/dist/cjs/instrumentation/do.js.map @@ -0,0 +1 @@ +{"version":3,"file":"do.js","sourceRoot":"","sources":["../../../src/instrumentation/do.ts"],"names":[],"mappings":";;;;;;;;;;;AAkDA,kDAYC;AAED,0CAcC;AAID,wCAmCC;AAED,wCAqBC;AA8DD,8CAoBC;AA9ND,4CAAoH;AACpH,8EAAwE;AACxE,wCAAyD;AACzD,yCAMmB;AACnB,qCAAwC;AACxC,4CAAqD;AACrD,2CAAyC;AACzC,mDAAmD;AAOnD,SAAS,qBAAqB,CAAC,IAAuB,EAAE,MAAc;IACrE,MAAM,WAAW,GAA8B;QAC9C,GAAG,CAAC,MAAM,EAAE,IAAI;YACf,IAAI,IAAI,KAAK,OAAO,EAAE,CAAC;gBACtB,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;gBACzC,MAAM,KAAK,GAAG;oBACb,IAAI,EAAE,kBAAkB,MAAM,EAAE;oBAChC,cAAc,EAAE,MAAM;oBACtB,OAAO,EAAE,MAAM,CAAC,EAAE,CAAC,QAAQ,EAAE;oBAC7B,YAAY,EAAE,MAAM,CAAC,EAAE,CAAC,IAAI;iBAC5B,CAAA;gBACD,OAAO,IAAA,gCAAqB,EAAC,OAAO,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,mBAAmB,EAAE,IAAI,EAAE,CAAC,EAAE,KAAK,CAAC,CAAA;YACpF,CAAC;iBAAM,CAAC;gBACP,OAAO,IAAA,wBAAc,EAAC,MAAM,EAAE,IAAI,CAAC,CAAA;YACpC,CAAC;QACF,CAAC;KACD,CAAA;IACD,OAAO,IAAA,cAAI,EAAC,IAAI,EAAE,WAAW,C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ts b/dist/cjs/instrumentation/env.d.ts new file mode 100644 index 0000000..2b996f3 --- /dev/null +++ b/dist/cjs/instrumentation/env.d.ts @@ -0,0 +1,4 @@ +export declare const isVersionMetadata: (item?: unknown) => item is WorkerVersionMetadata; +declare const instrumentEnv: (env: Record) => Record; +export { instrumentEnv }; +//# sourceMappingURL=env.d.ts.map \ No newline at end of file diff --git a/dist/cjs/instrumentation/env.d.ts.map b/dist/cjs/instrumentation/env.d.ts.map new file mode 100644 index 0000000..7f7981b --- /dev/null +++ b/dist/cjs/instrumentation/env.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"env.d.ts","sourceRoot":"","sources":["../../../src/instrumentation/env.ts"],"names":[],"mappings":"AAwBA,eAAO,MAAM,iBAAiB,UAAW,OAAO,KAAG,IAAI,IAAI,qBAM1D,CAAA;AAMD,QAAA,MAAM,aAAa,QAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CA0B3E,CAAA;AAED,OAAO,EAAE,aAAa,EAAE,CAAA"} \ No newline at end of file diff --git a/dist/cjs/instrumentation/env.js b/dist/cjs/instrumentation/env.js new file mode 100644 index 0000000..edbdcc3 --- /dev/null +++ b/dist/cjs/instrumentation/env.js @@ -0,0 +1,66 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.instrumentEnv = exports.isVersionMetadata = void 0; +const wrap_js_1 = require("../wrap.js"); +const do_js_1 = require("./do.js"); +const kv_js_1 = require("./kv.js"); +const queue_js_1 = require("./queue.js"); +const service_js_1 = require("./service.js"); +const analytics_engine_js_1 = require("./analytics-engine.js"); +const isJSRPC = (item) => { + // @ts-expect-error The point of RPC types is to block non-existent properties, but that's the goal here + return !!(item === null || item === void 0 ? void 0 : item['__some_property_that_will_never_exist' + Math.random()]); +}; +const isKVNamespace = (item) => { + return !isJSRPC(item) && !!(item === null || item === void 0 ? void 0 : item.getWithMetadata); +}; +const isQueue = (item) => { + return !isJSRPC(item) && !!(item === null || item === void 0 ? void 0 : item.sendBatch); +}; +const isDurableObject = (item) => { + return !isJSRPC(item) && !!(item === null || item === void 0 ? void 0 : item.idFromName); +}; +const isVersionMetadata = (item) => { + return (!isJSRPC(item) && + typeof (item === null || item === void 0 ? void 0 : item.id) === 'string' && + typeof (item === null || item === void 0 ? void 0 : item.tag) === 'string'); +}; +exports.isVersionMetadata = isVersionMetadata; +const isAnalyticsEngineDataset = (item) => { + return !isJSRPC(item) && !!(item === null || item === void 0 ? void 0 : item.writeDataPoint); +}; +const instrumentEnv = (env) => { + const envHandler = { + get: (target, prop, receiver) => { + const item = Reflect.get(target, prop, receiver); + if (!(0, wrap_js_1.isProxyable)(item)) { + return item; + } + if (isJSRPC(item)) { + return (0, service_js_1.instrumentServiceBinding)(item, String(prop)); + } + else if (isKVNamespace(item)) { + return (0, kv_js_1.instrumentKV)(item, String(prop)); + } + else if (isQueue(item)) { + return (0, queue_js_1.instrumentQueueSender)(item, String(prop)); + } + else if (isDurableObject(item)) { + return (0, do_js_1.instrumentDOBinding)(item, String(prop)); + } + else if ((0, exports.isVersionMetadata)(item)) { + // we do not need to log accesses to the metadata + return item; + } + else if (isAnalyticsEngineDataset(item)) { + return (0, analytics_engine_js_1.instrumentAnalyticsEngineDataset)(item, String(prop)); + } + else { + return item; + } + }, + }; + return (0, wrap_js_1.wrap)(env, envHandler); +}; +exports.instrumentEnv = instrumentEnv; +//# sourceMappingURL=env.js.map \ No newline at end of file diff --git a/dist/cjs/instrumentation/env.js.map b/dist/cjs/instrumentation/env.js.map new file mode 100644 index 0000000..681a3a3 --- /dev/null +++ b/dist/cjs/instrumentation/env.js.map @@ -0,0 +1 @@ +{"version":3,"file":"env.js","sourceRoot":"","sources":["../../../src/instrumentation/env.ts"],"names":[],"mappings":";;;AAAA,wCAA8C;AAC9C,mCAA6C;AAC7C,mCAAsC;AACtC,yCAAkD;AAClD,6CAAuD;AACvD,+DAAwE;AAExE,MAAM,OAAO,GAAG,CAAC,IA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AAO,IAAI,CAAA;YACZ,CAAC;QACF,CAAC;KACD,CAAA;IACD,OAAO,IAAA,cAAI,EAAC,GAAG,EAAE,UAAU,CAAC,CAAA;AAC7B,CAAC,CAAA;AAEQ,sCAAa"} \ No newline at end of file diff --git a/dist/cjs/instrumentation/fetch.d.ts b/dist/cjs/instrumentation/fetch.d.ts new file mode 100644 index 0000000..081bd67 --- /dev/null +++ b/dist/cjs/instrumentation/fetch.d.ts @@ -0,0 +1,30 @@ +import { Attributes, Context } from '@opentelemetry/api'; +import { Initialiser } from '../config.js'; +import { ResolvedTraceConfig } from '../types.js'; +export type IncludeTraceContextFn = (request: Request) => boolean; +export interface FetcherConfig { + includeTraceContext?: boolean | IncludeTraceContextFn; +} +export type AcceptTraceContextFn = (request: Request) => boolean; +export interface FetchHandlerConfig { + /** + * Whether to enable context propagation for incoming requests to `fetch`. + * This enables or disables distributed tracing from W3C Trace Context headers. + * @default true + */ + acceptTraceContext?: boolean | AcceptTraceContextFn; +} +type FetchHandler = ExportedHandlerFetchHandler; +type FetchHandlerArgs = Parameters; +export declare function gatherRequestAttributes(request: Request): Attributes; +export declare function gatherResponseAttributes(response: Response): Attributes; +export declare function gatherIncomingCfAttributes(request: Request): Attributes; +export declare function getParentContextFromHeaders(headers: Headers): Context; +export declare function waitUntilTrace(fn: () => Promise): Promise; +export declare function executeFetchHandler(fetchFn: FetchHandler, [request, env, ctx]: FetchHandlerArgs): Promise; +export declare function createFetchHandler(fetchFn: FetchHandler, initialiser: Initialiser): FetchHandler; +type getFetchConfig = (config: ResolvedTraceConfig) => FetcherConfig; +export declare function instrumentClientFetch(fetchFn: Fetcher['fetch'], configFn: getFetchConfig, attrs?: Attributes): Fetcher['fetch']; +export declare function instrumentGlobalFetch(): void; +export {}; +//# sourceMappingURL=fetch.d.ts.map \ No newline at end of file diff --git a/dist/cjs/instrumentation/fetch.d.ts.map b/dist/cjs/instrumentation/fetch.d.ts.map new file mode 100644 index 0000000..be4050b --- /dev/null +++ b/dist/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AED,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,WAAW,gBAoBjF;AAED,KAAK,cAAc,GAAG,CAAC,MAAM,EAAE,mBAAmB,KAAK,aAAa,CAAA;AACpE,wBAAgB,qBAAqB,CACpC,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,EACzB,QAAQ,EAAE,cAAc,EACxB,KAAK,CAAC,EAAE,UAAU,GAChB,OAAO,CAAC,OAAO,CAAC,CAyClB;AAED,wBAAgB,qBAAqB,IAAI,IAAI,CAG5C"} \ No newline at end of file diff --git a/dist/cjs/instrumentation/fetch.js b/dist/cjs/instrumentation/fetch.js new file mode 100644 index 0000000..88a5181 --- /dev/null +++ b/dist/cjs/instrumentation/fetch.js @@ -0,0 +1,220 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.gatherRequestAttributes = gatherRequestAttributes; +exports.gatherResponseAttributes = gatherResponseAttributes; +exports.gatherIncomingCfAttributes = gatherIncomingCfAttributes; +exports.getParentContextFromHeaders = getParentContextFromHeaders; +exports.waitUntilTrace = waitUntilTrace; +exports.executeFetchHandler = executeFetchHandler; +exports.createFetchHandler = createFetchHandler; +exports.instrumentClientFetch = instrumentClientFetch; +exports.instrumentGlobalFetch = instrumentGlobalFetch; +const api_1 = require("@opentelemetry/api"); +const config_js_1 = require("../config.js"); +const wrap_js_1 = require("../wrap.js"); +const env_js_1 = require("./env.js"); +const common_js_1 = require("./common.js"); +const version_js_1 = require("./version.js"); +const netKeysFromCF = new Set(['colo', 'country', 'request_priority', 'tls_cipher', 'tls_version', 'asn', 'tcp_rtt']); +const camelToSnakeCase = (s) => { + return s.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`); +}; +const gatherOutgoingCfAttributes = (cf) => { + const attrs = {}; + Object.keys(cf).forEach((key) => { + const value = cf[key]; + const destKey = camelToSnakeCase(key); + if (!netKeysFromCF.has(destKey)) { + if (typeof value === 'string' || typeof value === 'number') { + attrs[`cf.${destKey}`] = value; + } + else { + attrs[`cf.${destKey}`] = JSON.stringify(value); + } + } + }); + return attrs; +}; +function gatherRequestAttributes(request) { + var _a, _b; + const attrs = {}; + const headers = request.headers; + attrs['http.request.method'] = request.method.toUpperCase(); + attrs['network.protocol.name'] = 'http'; + attrs['network.protocol.version'] = (_a = request.cf) === null || _a === void 0 ? void 0 : _a.httpProtocol; + attrs['http.request.body.size'] = headers.get('content-length'); + attrs['user_agent.original'] = headers.get('user-agent'); + attrs['http.mime_type'] = headers.get('content-type'); + attrs['http.accepts'] = (_b = request.cf) === null || _b === void 0 ? void 0 : _b.clientAcceptEncoding; + const u = new URL(request.url); + attrs['url.full'] = `${u.protocol}//${u.host}${u.pathname}${u.search}`; + attrs['server.address'] = u.host; + attrs['url.scheme'] = u.protocol; + attrs['url.path'] = u.pathname; + attrs['url.query'] = u.search; + return attrs; +} +function gatherResponseAttributes(response) { + const attrs = {}; + attrs['http.response.status_code'] = response.status; + if (response.headers.get('content-length') == null) { + attrs['http.response.body.size'] = response.headers.get('content-length'); + } + attrs['http.mime_type'] = response.headers.get('content-type'); + return attrs; +} +function gatherIncomingCfAttributes(request) { + var _a, _b, _c, _d, _e, _f, _g; + const attrs = {}; + attrs['net.colo'] = (_a = request.cf) === null || _a === void 0 ? void 0 : _a.colo; + attrs['net.country'] = (_b = request.cf) === null || _b === void 0 ? void 0 : _b.country; + attrs['net.request_priority'] = (_c = request.cf) === null || _c === void 0 ? void 0 : _c.requestPriority; + attrs['net.tls_cipher'] = (_d = request.cf) === null || _d === void 0 ? void 0 : _d.tlsCipher; + attrs['net.tls_version'] = (_e = request.cf) === null || _e === void 0 ? void 0 : _e.tlsVersion; + attrs['net.asn'] = (_f = request.cf) === null || _f === void 0 ? void 0 : _f.asn; + attrs['net.tcp_rtt'] = (_g = request.cf) === null || _g === void 0 ? void 0 : _g.clientTcpRtt; + return attrs; +} +function getParentContextFromHeaders(headers) { + return api_1.propagation.extract(api_1.context.active(), headers, { + get(headers, key) { + return headers.get(key) || undefined; + }, + keys(headers) { + return [...headers.keys()]; + }, + }); +} +function getParentContextFromRequest(request) { + var _a; + const workerConfig = (0, config_js_1.getActiveConfig)(); + if (workerConfig === undefined) { + return api_1.context.active(); + } + const acceptTraceContext = typeof workerConfig.handlers.fetch.acceptTraceContext === 'function' + ? workerConfig.handlers.fetch.acceptTraceContext(request) + : ((_a = workerConfig.handlers.fetch.acceptTraceContext) !== null && _a !== void 0 ? _a : true); + return acceptTraceContext ? getParentContextFromHeaders(request.headers) : api_1.context.active(); +} +function waitUntilTrace(fn) { + const tracer = api_1.trace.getTracer('waitUntil'); + return tracer.startActiveSpan('waitUntil', (span) => __awaiter(this, void 0, void 0, function* () { + yield fn(); + span.end(); + })); +} +let cold_start = true; +function executeFetchHandler(fetchFn, [request, env, ctx]) { + var _a; + const spanContext = getParentContextFromRequest(request); + const tracer = api_1.trace.getTracer('fetchHandler'); + const attributes = { + ['faas.trigger']: 'http', + ['faas.coldstart']: cold_start, + ['faas.invocation_id']: (_a = request.headers.get('cf-ray')) !== null && _a !== void 0 ? _a : undefined, + }; + cold_start = false; + Object.assign(attributes, gatherRequestAttributes(request)); + Object.assign(attributes, gatherIncomingCfAttributes(request)); + Object.assign(attributes, (0, version_js_1.versionAttributes)(env)); + const options = { + attributes, + kind: api_1.SpanKind.SERVER, + }; + const method = request.method.toUpperCase(); + const promise = tracer.startActiveSpan(`fetchHandler ${method}`, options, spanContext, (span) => __awaiter(this, void 0, void 0, function* () { + const readable = span; + try { + const response = yield fetchFn(request, env, ctx); + span.setAttributes(gatherResponseAttributes(response)); + return response; + } + catch (error) { + span.recordException(error); + span.setStatus({ code: api_1.SpanStatusCode.ERROR }); + throw error; + } + finally { + if (readable.attributes['http.route']) { + span.updateName(`fetchHandler ${method} ${readable.attributes['http.route']}`); + } + span.end(); + } + })); + return promise; +} +function createFetchHandler(fetchFn, initialiser) { + const fetchHandler = { + apply: (target, _thisArg, argArray) => __awaiter(this, void 0, void 0, function* () { + const [request, orig_env, orig_ctx] = argArray; + const config = initialiser(orig_env, request); + const env = (0, env_js_1.instrumentEnv)(orig_env); + const { ctx, tracker } = (0, common_js_1.proxyExecutionContext)(orig_ctx); + const context = (0, config_js_1.setConfig)(config); + try { + const args = [request, env, ctx]; + return yield api_1.context.with(context, executeFetchHandler, undefined, target, args); + } + catch (error) { + throw error; + } + finally { + orig_ctx.waitUntil((0, common_js_1.exportSpans)(tracker)); + } + }), + }; + return (0, wrap_js_1.wrap)(fetchFn, fetchHandler); +} +function instrumentClientFetch(fetchFn, configFn, attrs) { + const handler = { + apply: (target, thisArg, argArray) => { + const request = new Request(argArray[0], argArray[1]); + if (!request.url.startsWith('http')) { + return Reflect.apply(target, thisArg, argArray); + } + const workerConfig = (0, config_js_1.getActiveConfig)(); + if (!workerConfig) { + return Reflect.apply(target, thisArg, [request]); + } + const config = configFn(workerConfig); + const tracer = api_1.trace.getTracer('fetcher'); + const options = { kind: api_1.SpanKind.CLIENT, attributes: attrs }; + const host = new URL(request.url).host; + const method = request.method.toUpperCase(); + const spanName = typeof (attrs === null || attrs === void 0 ? void 0 : attrs['name']) === 'string' ? attrs === null || attrs === void 0 ? void 0 : attrs['name'] : `fetch ${method} ${host}`; + const promise = tracer.startActiveSpan(spanName, options, (span) => __awaiter(this, void 0, void 0, function* () { + const includeTraceContext = typeof config.includeTraceContext === 'function' + ? config.includeTraceContext(request) + : config.includeTraceContext; + if (includeTraceContext !== null && includeTraceContext !== void 0 ? includeTraceContext : true) { + api_1.propagation.inject(api_1.context.active(), request.headers, { + set: (h, k, v) => h.set(k, typeof v === 'string' ? v : String(v)), + }); + } + span.setAttributes(gatherRequestAttributes(request)); + if (request.cf) + span.setAttributes(gatherOutgoingCfAttributes(request.cf)); + const response = yield Reflect.apply(target, thisArg, [request]); + span.setAttributes(gatherResponseAttributes(response)); + span.end(); + return response; + })); + return promise; + }, + }; + return (0, wrap_js_1.wrap)(fetchFn, handler, true); +} +function instrumentGlobalFetch() { + //@ts-ignore For some reason the node types are imported and complain. + globalThis.fetch = instrumentClientFetch(globalThis.fetch, (config) => config.fetch); +} +//# sourceMappingURL=fetch.js.map \ No newline at end of file diff --git a/dist/cjs/instrumentation/fetch.js.map b/dist/cjs/instrumentation/fetch.js.map new file mode 100644 index 0000000..c88de40 --- /dev/null +++ b/dist/cjs/instrumentation/fetch.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../../src/instrumentation/fetch.ts"],"names":[],"mappings":";;;;;;;;;;;AA2DA,0DAmBC;AAED,4DAQC;AAED,gEAUC;AAED,kEASC;AAgBD,wCAMC;AAGD,kDAsCC;AAED,gDAoBC;AAGD,sDA6CC;AAED,sDAGC;AAzPD,4CAU2B;AAC3B,4CAAsE;AACtE,wCAAiC;AACjC,qCAAwC;AACxC,2CAAgE;AAGhE,6CAAgD;AAoBhD,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,SAAS,EAAE,kBAAkB,EAAE,YAAY,EAAE,aAAa,EAAE,KAAK,EAAE,SAAS,CAAC,CAAC,CAAA;AAErH,MAAM,gBAAgB,GAAG,CAAC,CAAS,EAAU,EAAE;IAC9C,OAAO,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,IAAI,MAAM,CAAC,WAAW,EAAE,EAAE,CAAC,CAAA;AACnE,CAAC,CAAA;AAED,MAAM,0BAA0B,GAAG,CAAC,EAA2B,EAAc,EAAE;IAC9E,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CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;qBACjE,CAAC,CAAA;gBACH,CAAC;gBACD,IAAI,CAAC,aAAa,CAAC,uBAAuB,CAAC,OAAO,CAAC,CAAC,CAAA;gBACpD,IAAI,OAAO,CAAC,EAAE;oBAAE,IAAI,CAAC,aAAa,CAAC,0BAA0B,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAA;gBAC1E,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC,OAAO,CAAC,CAAC,CAAA;gBAChE,IAAI,CAAC,aAAa,CAAC,wBAAwB,CAAC,QAAQ,CAAC,CAAC,CAAA;gBACtD,IAAI,CAAC,GAAG,EAAE,CAAA;gBACV,OAAO,QAAQ,CAAA;YAChB,CAAC,CAAA,CAAC,CAAA;YACF,OAAO,OAAO,CAAA;QACf,CAAC;KACD,CAAA;IACD,OAAO,IAAA,cAAI,EAAC,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,CAAA;AACpC,CAAC;AAED,SAAgB,qBAAqB;IACpC,sEAAsE;IACtE,UAAU,CAAC,KAAK,GAAG,qBAAqB,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;AACrF,CAAC"} \ No newline at end of file diff --git a/dist/cjs/instrumentation/kv.d.ts b/dist/cjs/instrumentation/kv.d.ts new file mode 100644 index 0000000..b1c5b66 --- /dev/null +++ b/dist/cjs/instrumentation/kv.d.ts @@ -0,0 +1,2 @@ +export declare function instrumentKV(kv: KVNamespace, name: string): KVNamespace; +//# sourceMappingURL=kv.d.ts.map \ No newline at end of file diff --git a/dist/cjs/instrumentation/kv.d.ts.map b/dist/cjs/instrumentation/kv.d.ts.map new file mode 100644 index 0000000..8497c7c --- /dev/null +++ b/dist/cjs/instrumentation/kv.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"kv.d.ts","sourceRoot":"","sources":["../../../src/instrumentation/kv.ts"],"names":[],"mappings":"AA6GA,wBAAgB,YAAY,CAAC,EAAE,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,GAAG,WAAW,CASvE"} \ No newline at end of file diff --git a/dist/cjs/instrumentation/kv.js b/dist/cjs/instrumentation/kv.js new file mode 100644 index 0000000..3c7f0f8 --- /dev/null +++ b/dist/cjs/instrumentation/kv.js @@ -0,0 +1,129 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.instrumentKV = instrumentKV; +const api_1 = require("@opentelemetry/api"); +const semantic_conventions_1 = require("@opentelemetry/semantic-conventions"); +const wrap_js_1 = require("../wrap.js"); +const dbSystem = 'Cloudflare KV'; +const KVAttributes = { + delete(_argArray) { + return {}; + }, + get(argArray) { + const attrs = {}; + const opts = argArray[1]; + if (typeof opts === 'string') { + attrs['db.cf.kv.type'] = opts; + } + else if (typeof opts === 'object') { + attrs['db.cf.kv.type'] = opts.type; + attrs['db.cf.kv.cache_ttl'] = opts.cacheTtl; + } + return attrs; + }, + getWithMetadata(argArray, result) { + const attrs = {}; + const opts = argArray[1]; + if (typeof opts === 'string') { + attrs['db.cf.kv.type'] = opts; + } + else if (typeof opts === 'object') { + attrs['db.cf.kv.type'] = opts.type; + attrs['db.cf.kv.cache_ttl'] = opts.cacheTtl; + } + attrs['db.cf.kv.metadata'] = true; + const { cacheStatus } = result; + if (typeof cacheStatus === 'string') { + attrs['db.cf.kv.cache_status'] = cacheStatus; + } + return attrs; + }, + list(argArray, result) { + const attrs = {}; + const opts = argArray[0] || {}; + const { cursor, limit } = opts; + attrs['db.cf.kv.list_request_cursor'] = cursor || undefined; + attrs['db.cf.kv.list_limit'] = limit || undefined; + const { list_complete, cacheStatus } = result; + attrs['db.cf.kv.list_complete'] = list_complete || undefined; + if (!list_complete) { + attrs['db.cf.kv.list_response_cursor'] = cursor || undefined; + } + if (typeof cacheStatus === 'string') { + attrs['db.cf.kv.cache_status'] = cacheStatus; + } + return attrs; + }, + put(argArray) { + const attrs = {}; + if (argArray.length > 2 && argArray[2]) { + const { expiration, expirationTtl, metadata } = argArray[2]; + attrs['db.cf.kv.expiration'] = expiration; + attrs['db.cf.kv.expiration_ttl'] = expirationTtl; + attrs['db.cf.kv.metadata'] = !!metadata; + } + return attrs; + }, +}; +function instrumentKVFn(fn, name, operation) { + const tracer = api_1.trace.getTracer('KV'); + const fnHandler = { + apply: (target, thisArg, argArray) => { + const attributes = { + binding_type: 'KV', + [semantic_conventions_1.SemanticAttributes.DB_NAME]: name, + [semantic_conventions_1.SemanticAttributes.DB_SYSTEM]: dbSystem, + [semantic_conventions_1.SemanticAttributes.DB_OPERATION]: operation, + }; + const options = { + kind: api_1.SpanKind.CLIENT, + attributes, + }; + return tracer.startActiveSpan(`KV ${name} ${operation}`, options, (span) => __awaiter(this, void 0, void 0, function* () { + const result = yield Reflect.apply(target, thisArg, argArray); + const extraAttrsFn = KVAttributes[operation]; + const extraAttrs = extraAttrsFn ? extraAttrsFn(argArray, result) : {}; + span.setAttributes(extraAttrs); + if (operation === 'list') { + const opts = argArray[0] || {}; + const { prefix } = opts; + span.setAttribute(semantic_conventions_1.SemanticAttributes.DB_STATEMENT, `${operation} ${prefix || undefined}`); + } + else { + span.setAttribute(semantic_conventions_1.SemanticAttributes.DB_STATEMENT, `${operation} ${argArray[0]}`); + span.setAttribute('db.cf.kv.key', argArray[0]); + } + if (operation === 'getWithMetadata') { + const hasResults = !!result && !!result.value; + span.setAttribute('db.cf.kv.has_result', hasResults); + } + else { + span.setAttribute('db.cf.kv.has_result', !!result); + } + span.end(); + return result; + })); + }, + }; + return (0, wrap_js_1.wrap)(fn, fnHandler); +} +function instrumentKV(kv, name) { + const kvHandler = { + get: (target, prop, receiver) => { + const operation = String(prop); + const fn = Reflect.get(target, prop, receiver); + return instrumentKVFn(fn, name, operation); + }, + }; + return (0, wrap_js_1.wrap)(kv, kvHandler); +} +//# sourceMappingURL=kv.js.map \ No newline at end of file diff --git a/dist/cjs/instrumentation/kv.js.map b/dist/cjs/instrumentation/kv.js.map new file mode 100644 index 0000000..33b8f95 --- /dev/null +++ b/dist/cjs/instrumentation/kv.js.map @@ -0,0 +1 @@ +{"version":3,"file":"kv.js","sourceRoot":"","sources":["../../../src/instrumentation/kv.ts"],"names":[],"mappings":";;;;;;;;;;;AA6GA,oCASC;AAtHD,4CAA6E;AAC7E,8EAAwE;AACxE,wCAAiC;AAIjC,MAAM,QAAQ,GAAG,eAAe,CAAA;AAEhC,MAAM,YAAY,GAA8C;IAC/D,MAAM,CAAC,SAAS;QACf,OAAO,EAAE,CAAA;IACV,CAAC;IACD,GAAG,CAAC,QAAQ;QACX,MAAM,KAAK,GAAe,EAAE,CAAA;QAC5B,MAAM,IAAI,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAA;QACxB,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC9B,KAAK,CAAC,eAAe,CAAC,GAAG,IAAI,CAAA;QAC9B,CAAC;aAAM,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;YACrC,KAAK,CAAC,eAAe,CAAC,GAAG,IAAI,CAAC,IAAI,CAAA;YAClC,KAAK,CAAC,oBAAoB,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAA;QAC5C,CAAC;QACD,OAAO,K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AAM,CAAA;YACd,CAAC,CAAA,CAAC,CAAA;QACH,CAAC;KACD,CAAA;IACD,OAAO,IAAA,cAAI,EAAC,EAAE,EAAE,SAAS,CAAC,CAAA;AAC3B,CAAC;AAED,SAAgB,YAAY,CAAC,EAAe,EAAE,IAAY;IACzD,MAAM,SAAS,GAA8B;QAC5C,GAAG,EAAE,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE;YAC/B,MAAM,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,CAAA;YAC9B,MAAM,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAA;YAC9C,OAAO,cAAc,CAAC,EAAE,EAAE,IAAI,EAAE,SAAS,CAAC,CAAA;QAC3C,CAAC;KACD,CAAA;IACD,OAAO,IAAA,cAAI,EAAC,EAAE,EAAE,SAAS,CAAC,CAAA;AAC3B,CAAC"} \ No newline at end of file diff --git a/dist/cjs/instrumentation/queue.d.ts b/dist/cjs/instrumentation/queue.d.ts new file mode 100644 index 0000000..306299e --- /dev/null +++ b/dist/cjs/instrumentation/queue.d.ts @@ -0,0 +1,8 @@ +import { Initialiser } from '../config.js'; +type QueueHandler = ExportedHandlerQueueHandler; +export type QueueHandlerArgs = Parameters; +export declare function executeQueueHandler(queueFn: QueueHandler, [batch, env, ctx]: QueueHandlerArgs): Promise; +export declare function createQueueHandler(queueFn: QueueHandler, initialiser: Initialiser): QueueHandler; +export declare function instrumentQueueSender(queue: Queue, name: string): Queue; +export {}; +//# sourceMappingURL=queue.d.ts.map \ No newline at end of file diff --git a/dist/cjs/instrumentation/queue.d.ts.map b/dist/cjs/instrumentation/queue.d.ts.map new file mode 100644 index 0000000..314f338 --- /dev/null +++ b/dist/cjs/instrumentation/queue.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"queue.d.ts","sourceRoot":"","sources":["../../../src/instrumentation/queue.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAa,MAAM,cAAc,CAAA;AAMrD,KAAK,YAAY,GAAG,2BAA2B,CAAC,OAAO,EAAE,OAAO,CAAC,CAAA;AACjE,MAAM,MAAM,gBAAgB,GAAG,UAAU,CAAC,YAAY,CAAC,CAAA;AA4HvD,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,YAAY,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,CAAC,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CA+B7G;AAED,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,WAAW,gBAqBjF;AA8BD,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,MAAM,kBAexE"} \ No newline at end of file diff --git a/dist/cjs/instrumentation/queue.js b/dist/cjs/instrumentation/queue.js new file mode 100644 index 0000000..74946a9 --- /dev/null +++ b/dist/cjs/instrumentation/queue.js @@ -0,0 +1,238 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.executeQueueHandler = executeQueueHandler; +exports.createQueueHandler = createQueueHandler; +exports.instrumentQueueSender = instrumentQueueSender; +const api_1 = require("@opentelemetry/api"); +const semantic_conventions_1 = require("@opentelemetry/semantic-conventions"); +const config_js_1 = require("../config.js"); +const common_js_1 = require("./common.js"); +const env_js_1 = require("./env.js"); +const wrap_js_1 = require("../wrap.js"); +const version_js_1 = require("./version.js"); +const traceIdSymbol = Symbol('traceId'); +class MessageStatusCount { + constructor(total) { + this.succeeded = 0; + this.failed = 0; + this.total = total; + } + ack() { + this.succeeded = this.succeeded + 1; + } + ackRemaining() { + this.succeeded = this.total - this.failed; + } + retry() { + this.failed = this.failed + 1; + } + retryRemaining() { + this.failed = this.total - this.succeeded; + } + toAttributes() { + return { + 'queue.messages_count': this.total, + 'queue.messages_success': this.succeeded, + 'queue.messages_failed': this.failed, + 'queue.batch_success': this.succeeded === this.total, + }; + } +} +const addEvent = (name, msg) => { + var _a; + const attrs = {}; + if (msg) { + attrs['queue.message_id'] = msg.id; + attrs['queue.message_timestamp'] = msg.timestamp.toISOString(); + } + (_a = api_1.trace.getActiveSpan()) === null || _a === void 0 ? void 0 : _a.addEvent(name, attrs); +}; +const proxyQueueMessage = (msg, count) => { + const msgHandler = { + get: (target, prop) => { + if (prop === 'ack') { + const ackFn = Reflect.get(target, prop); + return new Proxy(ackFn, { + apply: (fnTarget) => { + addEvent('messageAck', msg); + count.ack(); + //TODO: handle errors + Reflect.apply(fnTarget, msg, []); + }, + }); + } + else if (prop === 'retry') { + const retryFn = Reflect.get(target, prop); + return new Proxy(retryFn, { + apply: (fnTarget) => { + addEvent('messageRetry', msg); + count.retry(); + //TODO: handle errors + const result = Reflect.apply(fnTarget, msg, []); + return result; + }, + }); + } + else { + return Reflect.get(target, prop, msg); + } + }, + }; + return (0, wrap_js_1.wrap)(msg, msgHandler); +}; +const proxyMessageBatch = (batch, count) => { + const batchHandler = { + get: (target, prop) => { + if (prop === 'messages') { + const messages = Reflect.get(target, prop); + const messagesHandler = { + get: (target, prop) => { + if (typeof prop === 'string' && !isNaN(parseInt(prop))) { + const message = Reflect.get(target, prop); + return proxyQueueMessage(message, count); + } + else { + return Reflect.get(target, prop); + } + }, + }; + return (0, wrap_js_1.wrap)(messages, messagesHandler); + } + else if (prop === 'ackAll') { + const ackFn = Reflect.get(target, prop); + return new Proxy(ackFn, { + apply: (fnTarget) => { + addEvent('ackAll'); + count.ackRemaining(); + //TODO: handle errors + Reflect.apply(fnTarget, batch, []); + }, + }); + } + else if (prop === 'retryAll') { + const retryFn = Reflect.get(target, prop); + return new Proxy(retryFn, { + apply: (fnTarget) => { + addEvent('retryAll'); + count.retryRemaining(); + //TODO: handle errors + Reflect.apply(fnTarget, batch, []); + }, + }); + } + return Reflect.get(target, prop); + }, + }; + return (0, wrap_js_1.wrap)(batch, batchHandler); +}; +function executeQueueHandler(queueFn, [batch, env, ctx]) { + const count = new MessageStatusCount(batch.messages.length); + batch = proxyMessageBatch(batch, count); + const tracer = api_1.trace.getTracer('queueHandler'); + const options = { + attributes: { + [semantic_conventions_1.SemanticAttributes.FAAS_TRIGGER]: 'pubsub', + 'queue.name': batch.queue, + }, + kind: api_1.SpanKind.CONSUMER, + }; + Object.assign(options.attributes, (0, version_js_1.versionAttributes)(env)); + const promise = tracer.startActiveSpan(`queueHandler ${batch.queue}`, options, (span) => __awaiter(this, void 0, void 0, function* () { + const traceId = span.spanContext().traceId; + api_1.context.active().setValue(traceIdSymbol, traceId); + try { + const result = yield queueFn(batch, env, ctx); + span.setAttribute('queue.implicitly_acked', count.total - count.succeeded - count.failed); + count.ackRemaining(); + span.setAttributes(count.toAttributes()); + span.end(); + return result; + } + catch (error) { + span.recordException(error); + span.setAttribute('queue.implicitly_retried', count.total - count.succeeded - count.failed); + count.retryRemaining(); + span.end(); + throw error; + } + })); + return promise; +} +function createQueueHandler(queueFn, initialiser) { + const queueHandler = { + apply(target, _thisArg, argArray) { + return __awaiter(this, void 0, void 0, function* () { + const [batch, orig_env, orig_ctx] = argArray; + const config = initialiser(orig_env, batch); + const env = (0, env_js_1.instrumentEnv)(orig_env); + const { ctx, tracker } = (0, common_js_1.proxyExecutionContext)(orig_ctx); + const context = (0, config_js_1.setConfig)(config); + try { + const args = [batch, env, ctx]; + return yield api_1.context.with(context, executeQueueHandler, undefined, target, args); + } + catch (error) { + throw error; + } + finally { + orig_ctx.waitUntil((0, common_js_1.exportSpans)(tracker)); + } + }); + }, + }; + return (0, wrap_js_1.wrap)(queueFn, queueHandler); +} +function instrumentQueueSend(fn, name) { + const tracer = api_1.trace.getTracer('queueSender'); + const handler = { + apply: (target, thisArg, argArray) => { + return tracer.startActiveSpan(`Queues ${name} send`, (span) => __awaiter(this, void 0, void 0, function* () { + span.setAttribute('queue.operation', 'send'); + yield Reflect.apply(target, (0, wrap_js_1.unwrap)(thisArg), argArray); + span.end(); + })); + }, + }; + return (0, wrap_js_1.wrap)(fn, handler); +} +function instrumentQueueSendBatch(fn, name) { + const tracer = api_1.trace.getTracer('queueSender'); + const handler = { + apply: (target, thisArg, argArray) => { + return tracer.startActiveSpan(`Queues ${name} sendBatch`, (span) => __awaiter(this, void 0, void 0, function* () { + span.setAttribute('queue.operation', 'sendBatch'); + yield Reflect.apply(target, (0, wrap_js_1.unwrap)(thisArg), argArray); + span.end(); + })); + }, + }; + return (0, wrap_js_1.wrap)(fn, handler); +} +function instrumentQueueSender(queue, name) { + const queueHandler = { + get: (target, prop) => { + if (prop === 'send') { + const sendFn = Reflect.get(target, prop); + return instrumentQueueSend(sendFn, name); + } + else if (prop === 'sendBatch') { + const sendFn = Reflect.get(target, prop); + return instrumentQueueSendBatch(sendFn, name); + } + else { + return Reflect.get(target, prop); + } + }, + }; + return (0, wrap_js_1.wrap)(queue, queueHandler); +} +//# sourceMappingURL=queue.js.map \ No newline at end of file diff --git a/dist/cjs/instrumentation/queue.js.map b/dist/cjs/instrumentation/queue.js.map new file mode 100644 index 0000000..0b6e995 --- /dev/null +++ b/dist/cjs/instrumentation/queue.js.map @@ -0,0 +1 @@ +{"version":3,"file":"queue.js","sourceRoot":"","sources":["../../../src/instrumentation/queue.ts"],"names":[],"mappings":";;;;;;;;;;;AAqIA,kDA+BC;AAED,gDAqBC;AA8BD,sDAeC;AAxOD,4CAAgH;AAChH,8EAAwE;AACxE,4CAAqD;AACrD,2CAAgE;AAChE,qCAAwC;AACxC,wCAAyC;AACzC,6CAAgD;AAKhD,MAAM,aAAa,GAAG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AAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;YACjC,CAAC;QACF,CAAC;KACD,CAAA;IACD,OAAO,IAAA,cAAI,EAAC,KAAK,EAAE,YAAY,CAAC,CAAA;AACjC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/instrumentation/scheduled.d.ts b/dist/cjs/instrumentation/scheduled.d.ts new file mode 100644 index 0000000..f8282c5 --- /dev/null +++ b/dist/cjs/instrumentation/scheduled.d.ts @@ -0,0 +1,7 @@ +import { Initialiser } from '../config.js'; +type ScheduledHandler = ExportedHandlerScheduledHandler; +export type ScheduledHandlerArgs = Parameters; +export declare function executeScheduledHandler(scheduledFn: ScheduledHandler, [controller, env, ctx]: ScheduledHandlerArgs): Promise; +export declare function createScheduledHandler(scheduledFn: ScheduledHandler, initialiser: Initialiser): ScheduledHandler; +export {}; +//# sourceMappingURL=scheduled.d.ts.map \ No newline at end of file diff --git a/dist/cjs/instrumentation/scheduled.d.ts.map b/dist/cjs/instrumentation/scheduled.d.ts.map new file mode 100644 index 0000000..60244e4 --- /dev/null +++ b/dist/cjs/instrumentation/scheduled.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"scheduled.d.ts","sourceRoot":"","sources":["../../../src/instrumentation/scheduled.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAa,MAAM,cAAc,CAAA;AAMrD,KAAK,gBAAgB,GAAG,+BAA+B,CAAC,OAAO,CAAC,CAAA;AAChE,MAAM,MAAM,oBAAoB,GAAG,UAAU,CAAC,gBAAgB,CAAC,CAAA;AAK/D,wBAAgB,uBAAuB,CACtC,WAAW,EAAE,gBAAgB,EAC7B,CAAC,UAAU,EAAE,GAAG,EAAE,GAAG,CAAC,EAAE,oBAAoB,GAC1C,OAAO,CAAC,IAAI,CAAC,CA6Bf;AAED,wBAAgB,sBAAsB,CAAC,WAAW,EAAE,gBAAgB,EAAE,WAAW,EAAE,WAAW,oBAqB7F"} \ No newline at end of file diff --git a/dist/cjs/instrumentation/scheduled.js b/dist/cjs/instrumentation/scheduled.js new file mode 100644 index 0000000..9a476cb --- /dev/null +++ b/dist/cjs/instrumentation/scheduled.js @@ -0,0 +1,78 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.executeScheduledHandler = executeScheduledHandler; +exports.createScheduledHandler = createScheduledHandler; +const api_1 = require("@opentelemetry/api"); +const semantic_conventions_1 = require("@opentelemetry/semantic-conventions"); +const config_js_1 = require("../config.js"); +const common_js_1 = require("./common.js"); +const env_js_1 = require("./env.js"); +const wrap_js_1 = require("../wrap.js"); +const version_js_1 = require("./version.js"); +const traceIdSymbol = Symbol('traceId'); +let cold_start = true; +function executeScheduledHandler(scheduledFn, [controller, env, ctx]) { + const tracer = api_1.trace.getTracer('scheduledHandler'); + const attributes = { + [semantic_conventions_1.SemanticAttributes.FAAS_TRIGGER]: 'timer', + [semantic_conventions_1.SemanticAttributes.FAAS_COLDSTART]: cold_start, + [semantic_conventions_1.SemanticAttributes.FAAS_CRON]: controller.cron, + [semantic_conventions_1.SemanticAttributes.FAAS_TIME]: new Date(controller.scheduledTime).toISOString(), + }; + cold_start = false; + Object.assign(attributes, (0, version_js_1.versionAttributes)(env)); + const options = { + attributes, + kind: api_1.SpanKind.SERVER, + }; + const promise = tracer.startActiveSpan(`scheduledHandler ${controller.cron}`, options, (span) => __awaiter(this, void 0, void 0, function* () { + const traceId = span.spanContext().traceId; + api_1.context.active().setValue(traceIdSymbol, traceId); + try { + yield scheduledFn(controller, env, ctx); + } + catch (error) { + span.recordException(error); + span.setStatus({ code: api_1.SpanStatusCode.ERROR }); + throw error; + } + finally { + span.end(); + } + })); + return promise; +} +function createScheduledHandler(scheduledFn, initialiser) { + const scheduledHandler = { + apply(target, _thisArg, argArray) { + return __awaiter(this, void 0, void 0, function* () { + const [controller, orig_env, orig_ctx] = argArray; + const config = initialiser(orig_env, controller); + const env = (0, env_js_1.instrumentEnv)(orig_env); + const { ctx, tracker } = (0, common_js_1.proxyExecutionContext)(orig_ctx); + const context = (0, config_js_1.setConfig)(config); + try { + const args = [controller, env, ctx]; + return yield api_1.context.with(context, executeScheduledHandler, undefined, target, args); + } + catch (error) { + throw error; + } + finally { + orig_ctx.waitUntil((0, common_js_1.exportSpans)(tracker)); + } + }); + }, + }; + return (0, wrap_js_1.wrap)(scheduledFn, scheduledHandler); +} +//# sourceMappingURL=scheduled.js.map \ No newline at end of file diff --git a/dist/cjs/instrumentation/scheduled.js.map b/dist/cjs/instrumentation/scheduled.js.map new file mode 100644 index 0000000..0442ce0 --- /dev/null +++ b/dist/cjs/instrumentation/scheduled.js.map @@ -0,0 +1 @@ +{"version":3,"file":"scheduled.js","sourceRoot":"","sources":["../../../src/instrumentation/scheduled.ts"],"names":[],"mappings":";;;;;;;;;;;AAcA,0DAgCC;AAED,wDAqBC;AArED,4CAAoH;AACpH,8EAAwE;AACxE,4CAAqD;AACrD,2CAAgE;AAChE,qCAAwC;AACxC,wCAAiC;AACjC,6CAAgD;AAKhD,MAAM,aAAa,GAAG,MAAM,CAAC,SAAS,CAAC,CAAA;AAEvC,IAAI,UAAU,GAAG,IAAI,CAAA;AACrB,SAAgB,uBAAuB,CACtC,WAA6B,EAC7B,CAAC,UAAU,EAAE,GAAG,EAAE,GAAG,CAAuB;IAE5C,MAAM,MAAM,GAAG,WAAK,CAAC,SAAS,CAAC,kBAAkB,CAAC,CAAA;IAClD,MAAM,UAAU,GAAG;QAClB,CAAC,yCAAkB,CAAC,YAAY,CAAC,EAAE,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AE,QAAQ,EAAE,QAAsC;;gBACnE,MAAM,CAAC,UAAU,EAAE,QAAQ,EAAE,QAAQ,CAAC,GAAG,QAAQ,CAAA;gBACjD,MAAM,MAAM,GAAG,WAAW,CAAC,QAAmC,EAAE,UAAU,CAAC,CAAA;gBAC3E,MAAM,GAAG,GAAG,IAAA,sBAAa,EAAC,QAAmC,CAAC,CAAA;gBAC9D,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,IAAA,iCAAqB,EAAC,QAAQ,CAAC,CAAA;gBACxD,MAAM,OAAO,GAAG,IAAA,qBAAS,EAAC,MAAM,CAAC,CAAA;gBAEjC,IAAI,CAAC;oBACJ,MAAM,IAAI,GAAyB,CAAC,UAAU,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;oBAEzD,OAAO,MAAM,aAAW,CAAC,IAAI,CAAC,OAAO,EAAE,uBAAuB,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,CAAC,CAAA;gBACzF,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBAChB,MAAM,KAAK,CAAA;gBACZ,CAAC;wBAAS,CAAC;oBACV,QAAQ,CAAC,SAAS,CAAC,IAAA,uBAAW,EAAC,OAAO,CAAC,CAAC,CAAA;gBACzC,CAAC;YACF,CAAC;SAAA;KACD,CAAA;IACD,OAAO,IAAA,cAAI,EAAC,WAAW,EAAE,gBAAgB,CAAC,CAAA;AAC3C,CAAC"} \ No newline at end of file diff --git a/dist/cjs/instrumentation/service.d.ts b/dist/cjs/instrumentation/service.d.ts new file mode 100644 index 0000000..d171b64 --- /dev/null +++ b/dist/cjs/instrumentation/service.d.ts @@ -0,0 +1,2 @@ +export declare function instrumentServiceBinding(fetcher: Fetcher, envName: string): Fetcher; +//# sourceMappingURL=service.d.ts.map \ No newline at end of file diff --git a/dist/cjs/instrumentation/service.d.ts.map b/dist/cjs/instrumentation/service.d.ts.map new file mode 100644 index 0000000..7ed8650 --- /dev/null +++ b/dist/cjs/instrumentation/service.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../../src/instrumentation/service.ts"],"names":[],"mappings":"AAGA,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAenF"} \ No newline at end of file diff --git a/dist/cjs/instrumentation/service.js b/dist/cjs/instrumentation/service.js new file mode 100644 index 0000000..17f6972 --- /dev/null +++ b/dist/cjs/instrumentation/service.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.instrumentServiceBinding = instrumentServiceBinding; +const wrap_js_1 = require("../wrap.js"); +const fetch_js_1 = require("./fetch.js"); +function instrumentServiceBinding(fetcher, envName) { + const fetcherHandler = { + get(target, prop) { + if (prop === 'fetch') { + const fetcher = Reflect.get(target, prop); + const attrs = { + name: `Service Binding ${envName}`, + }; + return (0, fetch_js_1.instrumentClientFetch)(fetcher, () => ({ includeTraceContext: true }), attrs); + } + else { + return (0, wrap_js_1.passthroughGet)(target, prop); + } + }, + }; + return (0, wrap_js_1.wrap)(fetcher, fetcherHandler); +} +//# sourceMappingURL=service.js.map \ No newline at end of file diff --git a/dist/cjs/instrumentation/service.js.map b/dist/cjs/instrumentation/service.js.map new file mode 100644 index 0000000..f7d45e4 --- /dev/null +++ b/dist/cjs/instrumentation/service.js.map @@ -0,0 +1 @@ +{"version":3,"file":"service.js","sourceRoot":"","sources":["../../../src/instrumentation/service.ts"],"names":[],"mappings":";;AAGA,4DAeC;AAlBD,wCAAiD;AACjD,yCAAkD;AAElD,SAAgB,wBAAwB,CAAC,OAAgB,EAAE,OAAe;IACzE,MAAM,cAAc,GAA0B;QAC7C,GAAG,CAAC,MAAM,EAAE,IAAI;YACf,IAAI,IAAI,KAAK,OAAO,EAAE,CAAC;gBACtB,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;gBACzC,MAAM,KAAK,GAAG;oBACb,IAAI,EAAE,mBAAmB,OAAO,EAAE;iBAClC,CAAA;gBACD,OAAO,IAAA,gCAAqB,EAAC,OAAO,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,mBAAmB,EAAE,IAAI,EAAE,CAAC,EAAE,KAAK,CAAC,CAAA;YACpF,CAAC;iBAAM,CAAC;gBACP,OAAO,IAAA,wBAAc,EAAC,MAAM,EAAE,IAAI,CAAC,CAAA;YACpC,CAAC;QACF,CAAC;KACD,CAAA;IACD,OAAO,IAAA,cAAI,EAAC,OAAO,EAAE,cAAc,CAAC,CAAA;AACrC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/instrumentation/version.d.ts b/dist/cjs/instrumentation/version.d.ts new file mode 100644 index 0000000..e32c3f8 --- /dev/null +++ b/dist/cjs/instrumentation/version.d.ts @@ -0,0 +1,2 @@ +export declare function versionAttributes(env: unknown): Record; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/dist/cjs/instrumentation/version.d.ts.map b/dist/cjs/instrumentation/version.d.ts.map new file mode 100644 index 0000000..bac2e52 --- /dev/null +++ b/dist/cjs/instrumentation/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../../src/instrumentation/version.ts"],"names":[],"mappings":"AAEA,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAgBlF"} \ No newline at end of file diff --git a/dist/cjs/instrumentation/version.js b/dist/cjs/instrumentation/version.js new file mode 100644 index 0000000..f391167 --- /dev/null +++ b/dist/cjs/instrumentation/version.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.versionAttributes = versionAttributes; +const env_js_1 = require("./env.js"); +function versionAttributes(env) { + const attributes = {}; + if (typeof env === 'object' && env !== null) { + for (const [binding, data] of Object.entries(env)) { + if ((0, env_js_1.isVersionMetadata)(data)) { + attributes['cf.workers_version_metadata.binding'] = binding; + attributes['cf.workers_version_metadata.id'] = data.id; + attributes['cf.workers_version_metadata.tag'] = data.tag; + // Version metadata bindings are identical, so we can stop after the first one found + break; + } + } + } + return attributes; +} +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/dist/cjs/instrumentation/version.js.map b/dist/cjs/instrumentation/version.js.map new file mode 100644 index 0000000..0fa2ac3 --- /dev/null +++ b/dist/cjs/instrumentation/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/instrumentation/version.ts"],"names":[],"mappings":";;AAEA,8CAgBC;AAlBD,qCAA4C;AAE5C,SAAgB,iBAAiB,CAAC,GAAY;IAC7C,MAAM,UAAU,GAAG,EAAwC,CAAA;IAE3D,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,IAAI,EAAE,CAAC;QAC7C,KAAK,MAAM,CAAC,OAAO,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;YACnD,IAAI,IAAA,0BAAiB,EAAC,IAAI,CAAC,EAAE,CAAC;gBAC7B,UAAU,CAAC,qCAAqC,CAAC,GAAG,OAAO,CAAA;gBAC3D,UAAU,CAAC,gCAAgC,CAAC,GAAG,IAAI,CAAC,EAAE,CAAA;gBACtD,UAAU,CAAC,iCAAiC,CAAC,GAAG,IAAI,CAAC,GAAG,CAAA;gBACxD,oFAAoF;gBACpF,MAAK;YACN,CAAC;QACF,CAAC;IACF,CAAC;IAED,OAAO,UAAU,CAAA;AAClB,CAAC"} \ No newline at end of file diff --git a/dist/cjs/multiexporter.d.ts b/dist/cjs/multiexporter.d.ts new file mode 100644 index 0000000..457df78 --- /dev/null +++ b/dist/cjs/multiexporter.d.ts @@ -0,0 +1,15 @@ +import { SpanExporter } from '@opentelemetry/sdk-trace-base'; +import { ExportResult } from '@opentelemetry/core'; +export declare class MultiSpanExporter implements SpanExporter { + private exporters; + constructor(exporters: Array); + export(items: any[], resultCallback: (result: ExportResult) => void): void; + shutdown(): Promise; +} +export declare class MultiSpanExporterAsync implements SpanExporter { + private exporters; + constructor(exporters: Array); + export(items: any[], resultCallback: (result: ExportResult) => void): void; + shutdown(): Promise; +} +//# sourceMappingURL=multiexporter.d.ts.map \ No newline at end of file diff --git a/dist/cjs/multiexporter.d.ts.map b/dist/cjs/multiexporter.d.ts.map new file mode 100644 index 0000000..d2b4c8e --- /dev/null +++ b/dist/cjs/multiexporter.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"multiexporter.d.ts","sourceRoot":"","sources":["../../src/multiexporter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAA;AAC5D,OAAO,EAAE,YAAY,EAAoB,MAAM,qBAAqB,CAAA;AAIpE,qBAAa,iBAAkB,YAAW,YAAY;IACrD,OAAO,CAAC,SAAS,CAAqB;gBAC1B,SAAS,EAAE,KAAK,CAAC,YAAY,CAAC;IAI1C,MAAM,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,cAAc,EAAE,CAAC,MAAM,EAAE,YAAY,KAAK,IAAI,GAAG,IAAI;IAMpE,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;CAK/B;AAID,qBAAa,sBAAuB,YAAW,YAAY;IAC1D,OAAO,CAAC,SAAS,CAAqB;gBAC1B,SAAS,EAAE,KAAK,CAAC,YAAY,CAAC;IAI1C,MAAM,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,cAAc,EAAE,CAAC,MAAM,EAAE,YAAY,KAAK,IAAI,GAAG,IAAI;IAmBpE,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;CAG/B"} \ No newline at end of file diff --git a/dist/cjs/multiexporter.js b/dist/cjs/multiexporter.js new file mode 100644 index 0000000..5512544 --- /dev/null +++ b/dist/cjs/multiexporter.js @@ -0,0 +1,60 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MultiSpanExporterAsync = exports.MultiSpanExporter = void 0; +const core_1 = require("@opentelemetry/core"); +// First implementation, completely synchronous, more tested. +class MultiSpanExporter { + constructor(exporters) { + this.exporters = exporters; + } + export(items, resultCallback) { + for (const exporter of this.exporters) { + exporter.export(items, resultCallback); + } + } + shutdown() { + return __awaiter(this, void 0, void 0, function* () { + for (const exporter of this.exporters) { + yield exporter.shutdown(); + } + }); + } +} +exports.MultiSpanExporter = MultiSpanExporter; +// async +class MultiSpanExporterAsync { + constructor(exporters) { + this.exporters = exporters; + } + export(items, resultCallback) { + const promises = this.exporters.map((exporter) => new Promise((resolve) => { + exporter.export(items, resolve); + })); + Promise.all(promises).then((results) => { + const failed = results.filter((result) => result.code === core_1.ExportResultCode.FAILED); + if (failed.length > 0) { + // not ideal, but just return the first error + resultCallback({ code: core_1.ExportResultCode.FAILED, error: failed[0].error }); + } + else { + resultCallback({ code: core_1.ExportResultCode.SUCCESS }); + } + }); + } + shutdown() { + return __awaiter(this, void 0, void 0, function* () { + yield Promise.all(this.exporters.map((exporter) => exporter.shutdown())); + }); + } +} +exports.MultiSpanExporterAsync = MultiSpanExporterAsync; +//# sourceMappingURL=multiexporter.js.map \ No newline at end of file diff --git a/dist/cjs/multiexporter.js.map b/dist/cjs/multiexporter.js.map new file mode 100644 index 0000000..e24eb5d --- /dev/null +++ b/dist/cjs/multiexporter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"multiexporter.js","sourceRoot":"","sources":["../../src/multiexporter.ts"],"names":[],"mappings":";;;;;;;;;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,CAAE,CAAC,KAAK,EAAE,CAAC,CAAA;YAC3E,CAAC;iBAAM,CAAC;gBACP,cAAc,CAAC,EAAE,IAAI,EAAE,uBAAgB,CAAC,OAAO,EAAE,CAAC,CAAA;YACnD,CAAC;QACF,CAAC,CAAC,CAAA;IACH,CAAC;IAEK,QAAQ;;YACb,MAAM,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAA;QACzE,CAAC;KAAA;CACD;AA5BD,wDA4BC"} \ No newline at end of file diff --git a/dist/cjs/package-info.d.ts b/dist/cjs/package-info.d.ts new file mode 100644 index 0000000..e8231f3 --- /dev/null +++ b/dist/cjs/package-info.d.ts @@ -0,0 +1,3 @@ +export declare const name = "@microlabs/otel-cf-workers"; +export declare const version = "1.0.0-rc.46"; +//# sourceMappingURL=package-info.d.ts.map \ No newline at end of file diff --git a/dist/cjs/package-info.d.ts.map b/dist/cjs/package-info.d.ts.map new file mode 100644 index 0000000..cc612dd --- /dev/null +++ b/dist/cjs/package-info.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"package-info.d.ts","sourceRoot":"","sources":["../../src/package-info.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,IAAI,+BAA+B,CAAC;AACjD,eAAO,MAAM,OAAO,gBAAgB,CAAC"} \ No newline at end of file diff --git a/dist/cjs/package-info.js b/dist/cjs/package-info.js new file mode 100644 index 0000000..aea6464 --- /dev/null +++ b/dist/cjs/package-info.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.version = exports.name = void 0; +// This file is auto-generated by package-info.js +exports.name = '@microlabs/otel-cf-workers'; +exports.version = '1.0.0-rc.46'; +//# sourceMappingURL=package-info.js.map \ No newline at end of file diff --git a/dist/cjs/package-info.js.map b/dist/cjs/package-info.js.map new file mode 100644 index 0000000..cd7830a --- /dev/null +++ b/dist/cjs/package-info.js.map @@ -0,0 +1 @@ +{"version":3,"file":"package-info.js","sourceRoot":"","sources":["../../src/package-info.ts"],"names":[],"mappings":";;;AACA,iDAAiD;AACpC,QAAA,IAAI,GAAG,4BAA4B,CAAC;AACpC,QAAA,OAAO,GAAG,aAAa,CAAC"} \ No newline at end of file diff --git a/dist/cjs/provider.d.ts b/dist/cjs/provider.d.ts new file mode 100644 index 0000000..8f47e9c --- /dev/null +++ b/dist/cjs/provider.d.ts @@ -0,0 +1,19 @@ +import { Tracer, TracerOptions, TracerProvider } from '@opentelemetry/api'; +import { SpanProcessor } from '@opentelemetry/sdk-trace-base'; +import { Resource } from '@opentelemetry/resources'; +/** + * Register this TracerProvider for use with the OpenTelemetry API. + * Undefined values may be replaced with defaults, and + * null values will be skipped. + * + * @param config Configuration object for SDK registration + */ +export declare class WorkerTracerProvider implements TracerProvider { + private spanProcessors; + private resource; + private tracers; + constructor(spanProcessors: SpanProcessor[], resource: Resource); + getTracer(name: string, version?: string, options?: TracerOptions): Tracer; + register(): void; +} +//# sourceMappingURL=provider.d.ts.map \ No newline at end of file diff --git a/dist/cjs/provider.d.ts.map b/dist/cjs/provider.d.ts.map new file mode 100644 index 0000000..331b0ab --- /dev/null +++ b/dist/cjs/provider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../src/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,MAAM,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;AAE1F,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAA;AAC7D,OAAO,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAA;AAKnD;;;;;;GAMG;AACH,qBAAa,oBAAqB,YAAW,cAAc;IAC1D,OAAO,CAAC,cAAc,CAAiB;IACvC,OAAO,CAAC,QAAQ,CAAU;IAC1B,OAAO,CAAC,OAAO,CAA6B;gBAEhC,cAAc,EAAE,aAAa,EAAE,EAAE,QAAQ,EAAE,QAAQ;IAK/D,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,aAAa,GAAG,MAAM;IAQ1E,QAAQ,IAAI,IAAI;CAIhB"} \ No newline at end of file diff --git a/dist/cjs/provider.js b/dist/cjs/provider.js new file mode 100644 index 0000000..b1a882c --- /dev/null +++ b/dist/cjs/provider.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WorkerTracerProvider = void 0; +const api_1 = require("@opentelemetry/api"); +const context_js_1 = require("./context.js"); +const tracer_js_1 = require("./tracer.js"); +/** + * Register this TracerProvider for use with the OpenTelemetry API. + * Undefined values may be replaced with defaults, and + * null values will be skipped. + * + * @param config Configuration object for SDK registration + */ +class WorkerTracerProvider { + constructor(spanProcessors, resource) { + this.tracers = {}; + this.spanProcessors = spanProcessors; + this.resource = resource; + } + getTracer(name, version, options) { + const key = `${name}@${version || ''}:${(options === null || options === void 0 ? void 0 : options.schemaUrl) || ''}`; + if (!this.tracers[key]) { + this.tracers[key] = new tracer_js_1.WorkerTracer(this.spanProcessors, this.resource); + } + return this.tracers[key]; + } + register() { + api_1.trace.setGlobalTracerProvider(this); + api_1.context.setGlobalContextManager(new context_js_1.AsyncLocalStorageContextManager()); + } +} +exports.WorkerTracerProvider = WorkerTracerProvider; +//# sourceMappingURL=provider.js.map \ No newline at end of file diff --git a/dist/cjs/provider.js.map b/dist/cjs/provider.js.map new file mode 100644 index 0000000..e1df8b7 --- /dev/null +++ b/dist/cjs/provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../src/provider.ts"],"names":[],"mappings":";;;AAAA,4CAA0F;AAK1F,6CAA8D;AAC9D,2CAA0C;AAE1C;;;;;;GAMG;AACH,MAAa,oBAAoB;IAKhC,YAAY,cAA+B,EAAE,QAAkB;QAFvD,YAAO,GAA2B,EAAE,CAAA;QAG3C,IAAI,CAAC,cAAc,GAAG,cAAc,CAAA;QACpC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;IACzB,CAAC;IAED,SAAS,CAAC,IAAY,EAAE,OAAgB,EAAE,OAAuB;QAChE,MAAM,GAAG,GAAG,GAAG,IAAI,IAAI,OAAO,IAAI,EAAE,IAAI,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,SAAS,KAAI,EAAE,EAAE,CAAA;QAClE,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;YACxB,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,IAAI,wBAAY,CAAC,IAAI,CAAC,cAAc,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAA;QACzE,CAAC;QACD,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAE,CAAA;IAC1B,CAAC;IAED,QAAQ;QACP,WAAK,CAAC,uBAAuB,CAAC,IAAI,CAAC,CAAA;QACnC,aAAO,CAAC,uBAAuB,CAAC,IAAI,4CAA+B,EAAE,CAAC,CAAA;IACvE,CAAC;CACD;AAtBD,oDAsBC"} \ No newline at end of file diff --git a/dist/cjs/sampling.d.ts b/dist/cjs/sampling.d.ts new file mode 100644 index 0000000..65673a0 --- /dev/null +++ b/dist/cjs/sampling.d.ts @@ -0,0 +1,11 @@ +import { ReadableSpan } from '@opentelemetry/sdk-trace-base'; +export interface LocalTrace { + readonly traceId: string; + readonly localRootSpan: ReadableSpan; + readonly spans: ReadableSpan[]; +} +export type TailSampleFn = (traceInfo: LocalTrace) => boolean; +export declare function multiTailSampler(samplers: TailSampleFn[]): TailSampleFn; +export declare const isHeadSampled: TailSampleFn; +export declare const isRootErrorSpan: TailSampleFn; +//# sourceMappingURL=sampling.d.ts.map \ No newline at end of file diff --git a/dist/cjs/sampling.d.ts.map b/dist/cjs/sampling.d.ts.map new file mode 100644 index 0000000..920997d --- /dev/null +++ b/dist/cjs/sampling.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sampling.d.ts","sourceRoot":"","sources":["../../src/sampling.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAA;AAE5D,MAAM,WAAW,UAAU;IAC1B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,aAAa,EAAE,YAAY,CAAA;IACpC,QAAQ,CAAC,KAAK,EAAE,YAAY,EAAE,CAAA;CAC9B;AAED,MAAM,MAAM,YAAY,GAAG,CAAC,SAAS,EAAE,UAAU,KAAK,OAAO,CAAA;AAE7D,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,YAAY,EAAE,GAAG,YAAY,CAIvE;AAED,eAAO,MAAM,aAAa,EAAE,YAG3B,CAAA;AAED,eAAO,MAAM,eAAe,EAAE,YAG7B,CAAA"} \ No newline at end of file diff --git a/dist/cjs/sampling.js b/dist/cjs/sampling.js new file mode 100644 index 0000000..9cccfc0 --- /dev/null +++ b/dist/cjs/sampling.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isRootErrorSpan = exports.isHeadSampled = void 0; +exports.multiTailSampler = multiTailSampler; +const api_1 = require("@opentelemetry/api"); +function multiTailSampler(samplers) { + return (traceInfo) => { + return samplers.reduce((result, sampler) => result || sampler(traceInfo), false); + }; +} +const isHeadSampled = (traceInfo) => { + const localRootSpan = traceInfo.localRootSpan; + return (localRootSpan.spanContext().traceFlags & api_1.TraceFlags.SAMPLED) === api_1.TraceFlags.SAMPLED; +}; +exports.isHeadSampled = isHeadSampled; +const isRootErrorSpan = (traceInfo) => { + const localRootSpan = traceInfo.localRootSpan; + return localRootSpan.status.code === api_1.SpanStatusCode.ERROR; +}; +exports.isRootErrorSpan = isRootErrorSpan; +//# sourceMappingURL=sampling.js.map \ No newline at end of file diff --git a/dist/cjs/sampling.js.map b/dist/cjs/sampling.js.map new file mode 100644 index 0000000..c5486ee --- /dev/null +++ b/dist/cjs/sampling.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sampling.js","sourceRoot":"","sources":["../../src/sampling.ts"],"names":[],"mappings":";;;AAWA,4CAIC;AAfD,4CAA+D;AAW/D,SAAgB,gBAAgB,CAAC,QAAwB;IACxD,OAAO,CAAC,SAAS,EAAE,EAAE;QACpB,OAAO,QAAQ,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,CAAC,MAAM,IAAI,OAAO,CAAC,SAAS,CAAC,EAAE,KAAK,CAAC,CAAA;IACjF,CAAC,CAAA;AACF,CAAC;AAEM,MAAM,aAAa,GAAiB,CAAC,SAAS,EAAE,EAAE;IACxD,MAAM,aAAa,GAAG,SAAS,CAAC,aAAwC,CAAA;IACxE,OAAO,CAAC,aAAa,CAAC,WAAW,EAAE,CAAC,UAAU,GAAG,gBAAU,CAAC,OAAO,CAAC,KAAK,gBAAU,CAAC,OAAO,CAAA;AAC5F,CAAC,CAAA;AAHY,QAAA,aAAa,iBAGzB;AAEM,MAAM,eAAe,GAAiB,CAAC,SAAS,EAAE,EAAE;IAC1D,MAAM,aAAa,GAAG,SAAS,CAAC,aAAwC,CAAA;IACxE,OAAO,aAAa,CAAC,MAAM,CAAC,IAAI,KAAK,oBAAc,CAAC,KAAK,CAAA;AAC1D,CAAC,CAAA;AAHY,QAAA,eAAe,mBAG3B"} \ No newline at end of file diff --git a/dist/cjs/sdk.d.ts b/dist/cjs/sdk.d.ts new file mode 100644 index 0000000..e40be39 --- /dev/null +++ b/dist/cjs/sdk.d.ts @@ -0,0 +1,12 @@ +import { Trigger, TraceConfig } from './types.js'; +import { DOClass } from './instrumentation/do.js'; +export type ResolveConfigFn = (env: Env, trigger: Trigger) => TraceConfig; +export type ConfigurationOption = TraceConfig | ResolveConfigFn; +export declare function isRequest(trigger: Trigger): trigger is Request; +export declare function isMessageBatch(trigger: Trigger): trigger is MessageBatch; +export declare function isAlarm(trigger: Trigger): trigger is 'do-alarm'; +export declare function instrument(handler: ExportedHandler, config: ConfigurationOption): ExportedHandler; +export declare function instrumentDO(doClass: DOClass, config: ConfigurationOption): DOClass; +export { waitUntilTrace } from './instrumentation/fetch.js'; +export declare const __unwrappedFetch: typeof fetch; +//# sourceMappingURL=sdk.d.ts.map \ No newline at end of file diff --git a/dist/cjs/sdk.d.ts.map b/dist/cjs/sdk.d.ts.map new file mode 100644 index 0000000..46ffd9d --- /dev/null +++ b/dist/cjs/sdk.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../src/sdk.ts"],"names":[],"mappings":"AAiBA,OAAO,EACN,OAAO,EACP,WAAW,EAKX,MAAM,YAAY,CAAA;AAKnB,OAAO,EAAE,OAAO,EAAqB,MAAM,yBAAyB,CAAA;AAQpE,MAAM,MAAM,eAAe,CAAC,GAAG,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,EAAE,OAAO,KAAK,WAAW,CAAA;AACpF,MAAM,MAAM,mBAAmB,GAAG,WAAW,GAAG,eAAe,CAAA;AAE/D,wBAAgB,SAAS,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,OAAO,CAE9D;AAED,wBAAgB,cAAc,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,YAAY,CAExE;AAED,wBAAgB,OAAO,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,UAAU,CAE/D;AAwHD,wBAAgB,UAAU,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EACjC,OAAO,EAAE,eAAe,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EACjC,MAAM,EAAE,mBAAmB,GACzB,eAAe,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAkB1B;AAED,wBAAgB,YAAY,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,mBAAmB,WAIzE;AAED,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAA;AAE3D,eAAO,MAAM,gBAAgB,cAAgB,CAAA"} \ No newline at end of file diff --git a/dist/cjs/sdk.js b/dist/cjs/sdk.js new file mode 100644 index 0000000..2862561 --- /dev/null +++ b/dist/cjs/sdk.js @@ -0,0 +1,169 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.__unwrappedFetch = exports.waitUntilTrace = void 0; +exports.isRequest = isRequest; +exports.isMessageBatch = isMessageBatch; +exports.isAlarm = isAlarm; +exports.instrument = instrument; +exports.instrumentDO = instrumentDO; +const api_1 = require("@opentelemetry/api"); +const core_1 = require("@opentelemetry/core"); +const resources_1 = require("@opentelemetry/resources"); +const sdk_trace_base_1 = require("@opentelemetry/sdk-trace-base"); +const exporter_js_1 = require("./exporter.js"); +const provider_js_1 = require("./provider.js"); +const sampling_js_1 = require("./sampling.js"); +const spanprocessor_js_1 = require("./spanprocessor.js"); +const types_js_1 = require("./types.js"); +const wrap_js_1 = require("./wrap.js"); +const fetch_js_1 = require("./instrumentation/fetch.js"); +const cache_js_1 = require("./instrumentation/cache.js"); +const queue_js_1 = require("./instrumentation/queue.js"); +const do_js_1 = require("./instrumentation/do.js"); +const scheduled_js_1 = require("./instrumentation/scheduled.js"); +const package_info_1 = require("./package-info"); +function isRequest(trigger) { + return trigger instanceof Request; +} +function isMessageBatch(trigger) { + return !!trigger.ackAll; +} +function isAlarm(trigger) { + return trigger === 'do-alarm'; +} +const createResource = (config) => { + const workerResourceAttrs = { + 'cloud.provider': 'cloudflare', + 'cloud.platform': 'cloudflare.workers', + 'cloud.region': 'earth', + 'faas.max_memory': 134217728, + 'telemetry.sdk.language': 'js', + 'telemetry.sdk.name': package_info_1.name, + 'telemetry.sdk.version': package_info_1.version, + }; + const serviceResource = new resources_1.Resource({ + 'service.name': config.service.name, + 'service.namespace': config.service.namespace, + 'service.version': config.service.version, + }); + const resource = new resources_1.Resource(workerResourceAttrs); + return resource.merge(serviceResource); +}; +function isSpanExporter(exporterConfig) { + return !!exporterConfig.export; +} +let initialised = false; +function init(config) { + if (!initialised) { + if (config.instrumentation.instrumentGlobalCache) { + (0, cache_js_1.instrumentGlobalCache)(); + } + if (config.instrumentation.instrumentGlobalFetch) { + (0, fetch_js_1.instrumentGlobalFetch)(); + } + api_1.propagation.setGlobalPropagator(config.propagator); + const resource = createResource(config); + const provider = new provider_js_1.WorkerTracerProvider(config.spanProcessors, resource); + provider.register(); + initialised = true; + } +} +function isSampler(sampler) { + return !!sampler.shouldSample; +} +function createSampler(conf) { + const ratioSampler = new sdk_trace_base_1.TraceIdRatioBasedSampler(conf.ratio); + if (typeof conf.acceptRemote === 'boolean' && !conf.acceptRemote) { + return new sdk_trace_base_1.ParentBasedSampler({ + root: ratioSampler, + remoteParentSampled: ratioSampler, + remoteParentNotSampled: ratioSampler, + }); + } + else { + return new sdk_trace_base_1.ParentBasedSampler({ root: ratioSampler }); + } +} +function parseConfig(supplied) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; + if ((0, types_js_1.isSpanProcessorConfig)(supplied)) { + const headSampleConf = (_a = supplied.sampling) === null || _a === void 0 ? void 0 : _a.headSampler; + const headSampler = headSampleConf + ? isSampler(headSampleConf) + ? headSampleConf + : createSampler(headSampleConf) + : new sdk_trace_base_1.AlwaysOnSampler(); + const spanProcessors = Array.isArray(supplied.spanProcessors) ? supplied.spanProcessors : [supplied.spanProcessors]; + if (spanProcessors.length === 0) { + console.log('Warning! You must either specify an exporter or your own SpanProcessor(s)/Exporter combination in the open-telemetry configuration.'); + } + return { + fetch: { + includeTraceContext: (_c = (_b = supplied.fetch) === null || _b === void 0 ? void 0 : _b.includeTraceContext) !== null && _c !== void 0 ? _c : true, + }, + handlers: { + fetch: { + acceptTraceContext: (_f = (_e = (_d = supplied.handlers) === null || _d === void 0 ? void 0 : _d.fetch) === null || _e === void 0 ? void 0 : _e.acceptTraceContext) !== null && _f !== void 0 ? _f : true, + }, + }, + postProcessor: supplied.postProcessor || ((spans) => spans), + sampling: { + headSampler, + tailSampler: ((_g = supplied.sampling) === null || _g === void 0 ? void 0 : _g.tailSampler) || (0, sampling_js_1.multiTailSampler)([sampling_js_1.isHeadSampled, sampling_js_1.isRootErrorSpan]), + }, + service: supplied.service, + spanProcessors, + propagator: supplied.propagator || new core_1.W3CTraceContextPropagator(), + instrumentation: { + instrumentGlobalCache: (_j = (_h = supplied.instrumentation) === null || _h === void 0 ? void 0 : _h.instrumentGlobalCache) !== null && _j !== void 0 ? _j : true, + instrumentGlobalFetch: (_l = (_k = supplied.instrumentation) === null || _k === void 0 ? void 0 : _k.instrumentGlobalFetch) !== null && _l !== void 0 ? _l : true, + }, + }; + } + else { + const exporter = isSpanExporter(supplied.exporter) ? supplied.exporter : new exporter_js_1.OTLPExporter(supplied.exporter); + const spanProcessors = [new spanprocessor_js_1.BatchTraceSpanProcessor(exporter)]; + const newConfig = Object.assign(supplied, { exporter: undefined, spanProcessors }); + return parseConfig(newConfig); + } +} +function createInitialiser(config) { + if (typeof config === 'function') { + return (env, trigger) => { + const conf = parseConfig(config(env, trigger)); + init(conf); + return conf; + }; + } + else { + return () => { + const conf = parseConfig(config); + init(conf); + return conf; + }; + } +} +function instrument(handler, config) { + const initialiser = createInitialiser(config); + if (handler.fetch) { + const fetcher = (0, wrap_js_1.unwrap)(handler.fetch); + handler.fetch = (0, fetch_js_1.createFetchHandler)(fetcher, initialiser); + } + if (handler.scheduled) { + const scheduler = (0, wrap_js_1.unwrap)(handler.scheduled); + handler.scheduled = (0, scheduled_js_1.createScheduledHandler)(scheduler, initialiser); + } + if (handler.queue) { + const queuer = (0, wrap_js_1.unwrap)(handler.queue); + handler.queue = (0, queue_js_1.createQueueHandler)(queuer, initialiser); + } + return handler; +} +function instrumentDO(doClass, config) { + const initialiser = createInitialiser(config); + return (0, do_js_1.instrumentDOClass)(doClass, initialiser); +} +var fetch_js_2 = require("./instrumentation/fetch.js"); +Object.defineProperty(exports, "waitUntilTrace", { enumerable: true, get: function () { return fetch_js_2.waitUntilTrace; } }); +exports.__unwrappedFetch = (0, wrap_js_1.unwrap)(fetch); +//# sourceMappingURL=sdk.js.map \ No newline at end of file diff --git a/dist/cjs/sdk.js.map b/dist/cjs/sdk.js.map new file mode 100644 index 0000000..fb28bca --- /dev/null +++ b/dist/cjs/sdk.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/sdk.ts"],"names":[],"mappings":";;;AAwCA,8BAEC;AAED,wCAEC;AAED,0BAEC;AAwHD,gCAqBC;AAED,oCAIC;AArMD,4CAAgD;AAChD,8CAA+D;AAC/D,wDAAmD;AACnD,kEAOsC;AAGtC,+CAA4C;AAC5C,+CAAoD;AACpD,+CAAgF;AAChF,yDAA4D;AAC5D,yCAOmB;AACnB,uCAAkC;AAClC,yDAAsF;AACtF,yDAAkE;AAClE,yDAA+D;AAC/D,mDAAoE;AACpE,iEAAuE;AACvE,iDAA8C;AAS9C,SAAgB,SAAS,CAAC,OAAgB;IACzC,OAAO,OAAO,YAAY,OAAO,CAAA;AAClC,CAAC;AAED,SAAgB,cAAc,CAAC,OAAgB;IAC9C,OAAO,CAAC,CAAE,OAAwB,CAAC,MAAM,CAAA;AAC1C,CAAC;AAED,SAAgB,OAAO,CAAC,OAAgB;IACvC,OAAO,OAAO,KAAK,UAAU,CAAA;AAC9B,CAAC;AAED,MAAM,cAAc,GAAG,CAAC,MAA2B,EAAY,EAAE;IAChE,MAAM,mBAAmB,GAAG;QAC3B,gBAAgB,EAAE,YAAY;QAC9B,gBAAgB,EAAE,oBAAoB;QACtC,cAAc,EAAE,OAAO;QACvB,iBAAiB,EAAE,SAAS;QAC5B,wBAAwB,EAAE,IAAI;QAC9B,oBAAoB,EAAE,mBAAI;QAC1B,uBAAuB,EAAE,sBAAO;KAChC,CAAA;IACD,MAAM,eAAe,GAAG,IAAI,oBAAQ,CAAC;QACpC,cAAc,EAAE,MAAM,CAAC,OAAO,CAAC,IAAI;QACnC,mBAAmB,EAAE,MAAM,CAAC,OAAO,CAAC,SAAS;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ist/cjs/span.d.ts new file mode 100644 index 0000000..7b1aca8 --- /dev/null +++ b/dist/cjs/span.d.ts @@ -0,0 +1,55 @@ +import { SpanContext, Link, SpanKind, TimeInput, Exception, Attributes, HrTime, Span, SpanStatus, AttributeValue } from '@opentelemetry/api'; +import { InstrumentationLibrary } from '@opentelemetry/core'; +import { IResource } from '@opentelemetry/resources'; +import { ReadableSpan, TimedEvent } from '@opentelemetry/sdk-trace-base'; +type OnSpanEnd = (span: Span) => void; +interface SpanInit { + attributes: unknown; + name: string; + onEnd: OnSpanEnd; + resource: IResource; + spanContext: SpanContext; + links?: Link[]; + parentSpanId?: string; + spanKind?: SpanKind; + startTime?: TimeInput; +} +export declare class SpanImpl implements Span, ReadableSpan { + name: string; + private readonly _spanContext; + private readonly onEnd; + readonly parentSpanId?: string; + readonly kind: SpanKind; + readonly attributes: Attributes; + status: SpanStatus; + endTime: HrTime; + private _duration; + readonly startTime: HrTime; + readonly events: TimedEvent[]; + readonly links: Link[]; + readonly resource: IResource; + instrumentationLibrary: InstrumentationLibrary; + private _ended; + private _droppedAttributesCount; + private _droppedEventsCount; + private _droppedLinksCount; + constructor(init: SpanInit); + addLink(link: Link): this; + addLinks(links: Link[]): this; + spanContext(): SpanContext; + setAttribute(key: string, value?: AttributeValue): this; + setAttributes(attributes: Attributes): this; + addEvent(name: string, attributesOrStartTime?: Attributes | TimeInput, startTime?: TimeInput): this; + setStatus(status: SpanStatus): this; + updateName(name: string): this; + end(endTime?: TimeInput): void; + isRecording(): boolean; + recordException(exception: Exception, time?: TimeInput): void; + get duration(): HrTime; + get ended(): boolean; + get droppedAttributesCount(): number; + get droppedEventsCount(): number; + get droppedLinksCount(): number; +} +export {}; +//# sourceMappingURL=span.d.ts.map \ No newline at end of file diff --git a/dist/cjs/span.d.ts.map b/dist/cjs/span.d.ts.map new file mode 100644 index 0000000..9adad2f --- /dev/null +++ b/dist/cjs/span.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"span.d.ts","sourceRoot":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0,0 +1,146 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SpanImpl = void 0; +const api_1 = require("@opentelemetry/api"); +const core_1 = require("@opentelemetry/core"); +const semantic_conventions_1 = require("@opentelemetry/semantic-conventions"); +function transformExceptionAttributes(exception) { + const attributes = {}; + if (typeof exception === 'string') { + attributes[semantic_conventions_1.SemanticAttributes.EXCEPTION_MESSAGE] = exception; + } + else { + if (exception.code) { + attributes[semantic_conventions_1.SemanticAttributes.EXCEPTION_TYPE] = exception.code.toString(); + } + else if (exception.name) { + attributes[semantic_conventions_1.SemanticAttributes.EXCEPTION_TYPE] = exception.name; + } + if (exception.message) { + attributes[semantic_conventions_1.SemanticAttributes.EXCEPTION_MESSAGE] = exception.message; + } + if (exception.stack) { + attributes[semantic_conventions_1.SemanticAttributes.EXCEPTION_STACKTRACE] = exception.stack; + } + } + return attributes; +} +function millisToHr(millis) { + return [Math.trunc(millis / 1000), (millis % 1000) * 1e6]; +} +function getHrTime(input) { + const now = Date.now(); + if (!input) { + return millisToHr(now); + } + else if (input instanceof Date) { + return millisToHr(input.getTime()); + } + else if (typeof input === 'number') { + //TODO: do something with performance.now something + return millisToHr(input); + } + else if (Array.isArray(input)) { + return input; + } + const v = input; + throw new Error(`unreachable value: ${JSON.stringify(v)}`); +} +class SpanImpl { + constructor(init) { + this.status = { + code: api_1.SpanStatusCode.UNSET, + }; + this.endTime = [0, 0]; + this._duration = [0, 0]; + this.events = []; + this.instrumentationLibrary = { name: '@microlabs/otel-cf-workers' }; + this._ended = false; + this._droppedAttributesCount = 0; + this._droppedEventsCount = 0; + this._droppedLinksCount = 0; + this.name = init.name; + this._spanContext = init.spanContext; + this.parentSpanId = init.parentSpanId; + this.kind = init.spanKind || api_1.SpanKind.INTERNAL; + this.attributes = (0, core_1.sanitizeAttributes)(init.attributes); + this.startTime = getHrTime(init.startTime); + this.links = init.links || []; + this.resource = init.resource; + this.onEnd = init.onEnd; + } + addLink(link) { + this.links.push(link); + return this; + } + addLinks(links) { + this.links.push(...links); + return this; + } + spanContext() { + return this._spanContext; + } + setAttribute(key, value) { + if ((0, core_1.isAttributeKey)(key) && (0, core_1.isAttributeValue)(value)) { + this.attributes[key] = value; + } + return this; + } + setAttributes(attributes) { + for (const [key, value] of Object.entries(attributes)) { + this.setAttribute(key, value); + } + return this; + } + addEvent(name, attributesOrStartTime, startTime) { + if ((0, core_1.isTimeInput)(attributesOrStartTime)) { + startTime = attributesOrStartTime; + attributesOrStartTime = undefined; + } + const attributes = (0, core_1.sanitizeAttributes)(attributesOrStartTime); + const time = getHrTime(startTime); + this.events.push({ name, attributes, time }); + return this; + } + setStatus(status) { + this.status = status; + return this; + } + updateName(name) { + this.name = name; + return this; + } + end(endTime) { + if (this._ended) { + return; + } + this._ended = true; + this.endTime = getHrTime(endTime); + this._duration = (0, core_1.hrTimeDuration)(this.startTime, this.endTime); + this.onEnd(this); + } + isRecording() { + return !this._ended; + } + recordException(exception, time) { + const attributes = transformExceptionAttributes(exception); + this.addEvent('exception', attributes, time); + } + get duration() { + return this._duration; + } + get ended() { + return this._ended; + } + get droppedAttributesCount() { + return this._droppedAttributesCount; + } + get droppedEventsCount() { + return this._droppedEventsCount; + } + get droppedLinksCount() { + return this._droppedLinksCount; + } +} +exports.SpanImpl = SpanImpl; +//# sourceMappingURL=span.js.map \ No newline at end of file diff --git a/dist/cjs/span.js.map b/dist/cjs/span.js.map new file mode 100644 index 0000000..348447a --- /dev/null +++ b/dist/cjs/span.js.map @@ -0,0 +1 @@ +{"version":3,"file":"span.js","sourceRoot":"","sources":["../../src/span.ts"],"names":[],"mappings":";;;AAAA,4CAY2B;AAC3B,8CAO4B;AAG5B,8EAAwE;AAgBxE,SAAS,4BAA4B,CAAC,SAAoB;IACzD,MAAM,UAAU,GAAe,EAAE,CAAA;IACjC,IAAI,OAAO,SAAS,KAAK,QAAQ,EAAE,CAAC;QACnC,UAAU,CAAC,yCAAkB,CAAC,iBAAiB,CAAC,GAAG,SAAS,CAAA;I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ev/null +++ b/dist/cjs/spanprocessor.d.ts @@ -0,0 +1,16 @@ +import { Context, Span } from '@opentelemetry/api'; +import { ReadableSpan, SpanExporter, SpanProcessor } from '@opentelemetry/sdk-trace-base'; +export declare class BatchTraceSpanProcessor implements SpanProcessor { + private exporter; + private traceLookup; + private localRootSpanLookup; + private inprogressExports; + constructor(exporter: SpanExporter); + private action; + private export; + onStart(span: Span, parentContext: Context): void; + onEnd(span: ReadableSpan): void; + forceFlush(): Promise; + shutdown(): Promise; +} +//# sourceMappingURL=spanprocessor.d.ts.map \ No newline at end of file diff --git a/dist/cjs/spanprocessor.d.ts.map b/dist/cjs/spanprocessor.d.ts.map new file mode 100644 index 0000000..b3e224a --- /dev/null +++ b/dist/cjs/spanprocessor.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"spanprocessor.d.ts","sourceRoot":"","sources":["../../src/spanprocessor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAS,MAAM,oBAAoB,CAAA;AACzD,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAA;AAiHzF,qBAAa,uBAAwB,YAAW,aAAa;IAKhD,OAAO,CAAC,QAAQ;IAJ5B,OAAO,CAAC,WAAW,CAAwC;IAC3D,OAAO,CAAC,mBAAmB,CAAiC;IAC5D,OAAO,CAAC,iBAAiB,CAAgD;gBAErD,QAAQ,EAAE,YAAY;IAE1C,OAAO,CAAC,MAAM;IAWd,OAAO,CAAC,MAAM;IAoBd,OAAO,CAAC,IAAI,EAAE,IAAI,EAAE,aAAa,EAAE,OAAO,GAAG,IAAI;IAUjD,KAAK,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI;IAczB,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAI3B,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;CAC/B"} \ No newline at end of file diff --git a/dist/cjs/spanprocessor.js b/dist/cjs/spanprocessor.js new file mode 100644 index 0000000..f60ac52 --- /dev/null +++ b/dist/cjs/spanprocessor.js @@ -0,0 +1,149 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BatchTraceSpanProcessor = void 0; +const api_1 = require("@opentelemetry/api"); +const core_1 = require("@opentelemetry/core"); +const StateMachine_js_1 = require("./vendor/ts-checked-fsm/StateMachine.js"); +const config_js_1 = require("./config.js"); +function newTrace(currentState, { span }) { + const spanId = span.spanContext().spanId; + return Object.assign(Object.assign({}, currentState), { stateName: 'in_progress', traceId: span.spanContext().traceId, localRootSpan: span, completedSpans: [], inProgressSpanIds: new Set([spanId]) }); +} +function newSpan(currentState, { span }) { + const spanId = span.spanContext().spanId; + currentState.inProgressSpanIds.add(spanId); + return Object.assign({}, currentState); +} +function endSpan(currentState, { span }) { + currentState.completedSpans.push(span); + currentState.inProgressSpanIds.delete(span.spanContext().spanId); + if (currentState.inProgressSpanIds.size === 0) { + return { + stateName: 'trace_complete', + traceId: currentState.traceId, + localRootSpan: currentState.localRootSpan, + completedSpans: currentState.completedSpans, + }; + } + else { + return Object.assign({}, currentState); + } +} +function startExport(currentState, { args }) { + const { exporter, tailSampler, postProcessor } = args; + const { traceId, localRootSpan, completedSpans: spans } = currentState; + const shouldExport = tailSampler({ traceId, localRootSpan, spans }); + if (shouldExport) { + const exportSpans = postProcessor(spans); + const promise = new Promise((resolve) => { + exporter.export(exportSpans, resolve); + }); + return { stateName: 'exporting', promise }; + } + else { + return { stateName: 'done' }; + } +} +const { nextState } = (0, StateMachine_js_1.stateMachine)() + .state('not_started') + .state('in_progress') + .state('trace_complete') + .state('exporting') + .state('done') + .transition('not_started', 'in_progress') + .transition('in_progress', 'in_progress') + .transition('in_progress', 'trace_complete') + .transition('trace_complete', 'exporting') + .transition('trace_complete', 'done') + .transition('exporting', 'done') + .action('startSpan') + .action('endSpan') + .action('startExport') + .action('exportDone') + .actionHandler('not_started', 'startSpan', newTrace) + .actionHandler('in_progress', 'startSpan', newSpan) + .actionHandler('in_progress', 'endSpan', endSpan) + .actionHandler('trace_complete', 'startExport', startExport) + .actionHandler('exporting', 'exportDone', (_c, _a) => { + return { stateName: 'done' }; +}) + .done(); +class BatchTraceSpanProcessor { + constructor(exporter) { + this.exporter = exporter; + this.traceLookup = new Map(); + this.localRootSpanLookup = new Map(); + this.inprogressExports = new Map(); + } + action(localRootSpanId, action) { + const state = this.traceLookup.get(localRootSpanId) || { stateName: 'not_started' }; + const newState = nextState(state, action); + if (newState.stateName === 'done') { + this.traceLookup.delete(localRootSpanId); + } + else { + this.traceLookup.set(localRootSpanId, newState); + } + return newState; + } + export(localRootSpanId) { + const config = (0, config_js_1.getActiveConfig)(); + if (!config) + throw new Error('Config is undefined. This is a bug in the instrumentation logic'); + const { sampling, postProcessor } = config; + const exportArgs = { exporter: this.exporter, tailSampler: sampling.tailSampler, postProcessor }; + const newState = this.action(localRootSpanId, { actionName: 'startExport', args: exportArgs }); + if (newState.stateName === 'exporting') { + const promise = newState.promise; + this.inprogressExports.set(localRootSpanId, promise); + promise.then((result) => { + if (result.code === core_1.ExportResultCode.FAILED) { + console.log('Error sending spans to exporter:', result.error); + } + this.action(localRootSpanId, { actionName: 'exportDone' }); + this.inprogressExports.delete(localRootSpanId); + }); + } + } + onStart(span, parentContext) { + var _b, _d; + const spanId = span.spanContext().spanId; + const parentSpanId = (_d = (_b = api_1.trace.getSpan(parentContext)) === null || _b === void 0 ? void 0 : _b.spanContext()) === null || _d === void 0 ? void 0 : _d.spanId; + const parentRootSpanId = parentSpanId ? this.localRootSpanLookup.get(parentSpanId) : undefined; + const localRootSpanId = parentRootSpanId || spanId; + this.localRootSpanLookup.set(spanId, localRootSpanId); + this.action(localRootSpanId, { actionName: 'startSpan', span }); + } + onEnd(span) { + const spanId = span.spanContext().spanId; + const localRootSpanId = this.localRootSpanLookup.get(spanId); + if (localRootSpanId) { + const state = this.action(localRootSpanId, { actionName: 'endSpan', span }); + if (state.stateName === 'trace_complete') { + state.completedSpans.forEach((span) => { + this.localRootSpanLookup.delete(span.spanContext().spanId); + }); + this.export(localRootSpanId); + } + } + } + forceFlush() { + return __awaiter(this, void 0, void 0, function* () { + yield Promise.allSettled(this.inprogressExports.values()); + }); + } + shutdown() { + return __awaiter(this, void 0, void 0, function* () { }); + } +} +exports.BatchTraceSpanProcessor = BatchTraceSpanProcessor; +//# sourceMappingURL=spanprocessor.js.map \ No newline at end of file diff --git a/dist/cjs/spanprocessor.js.map b/dist/cjs/spanprocessor.js.map new file mode 100644 index 0000000..55a74c5 --- /dev/null +++ b/dist/cjs/spanprocessor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"spanprocessor.js","sourceRoot":"","sources":["../../src/spanprocessor.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,4CAAyD;AAEzD,8CAAoE;AACpE,6EAAqF;AAErF,2CAA6C;AA8B7C,SAAS,QAAQ,CAAC,YAA0B,EAAE,EAAE,IAAI,EAAmB;IACtE,MAAM,MAAM,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC,MAAM,CAAA;IACxC,OAAO,gCACH,YAAY,KACf,SAAS,EAAE,aAAa,EACxB,OAAO,EAAE,IAAI,CAAC,WAAW,EAAE,CAAC,OAAO,EACnC,aAAa,EAAE,IAA+B,EAC9C,cAAc,EAAE,EAAoB,EACpC,iBAAiB,EAAE,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,GAC3B,CAAA;AACX,CAAC;AAED,SAAS,OAAO,CAAC,YAAkC,EAAE,EAAE,IAAI,EAAmB;IA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,IAAI,CAAC,MAAM,CAAC,eAAe,EAAE,EAAE,UAAU,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAA;YAC3E,IAAI,KAAK,CAAC,SAAS,KAAK,gBAAgB,EAAE,CAAC;gBAC1C,KAAK,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;oBACrC,IAAI,CAAC,mBAAmB,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,MAAM,CAAC,CAAA;gBAC3D,CAAC,CAAC,CAAA;gBACF,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,CAAA;YAC7B,CAAC;QACF,CAAC;IACF,CAAC;IAEK,UAAU;;YACf,MAAM,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,iBAAiB,CAAC,MAAM,EAAE,CAAC,CAAA;QAC1D,CAAC;KAAA;IAEK,QAAQ;8DAAmB,CAAC;KAAA;CAClC;AAnED,0DAmEC"} \ No newline at end of file diff --git a/dist/cjs/tracer.d.ts b/dist/cjs/tracer.d.ts new file mode 100644 index 0000000..e7537d6 --- /dev/null +++ b/dist/cjs/tracer.d.ts @@ -0,0 +1,17 @@ +import { Attributes, Tracer, Span, SpanOptions, Context } from '@opentelemetry/api'; +import { Resource } from '@opentelemetry/resources'; +import { SpanProcessor } from '@opentelemetry/sdk-trace-base'; +export declare class WorkerTracer implements Tracer { + private readonly _spanProcessors; + private readonly resource; + private readonly idGenerator; + constructor(spanProcessors: SpanProcessor[], resource: Resource); + get spanProcessors(): SpanProcessor[]; + addToResource(extra: Resource): void; + startSpan(name: string, options?: SpanOptions, context?: Context): Span; + startActiveSpan ReturnType>(name: string, fn: F): ReturnType; + startActiveSpan ReturnType>(name: string, options: SpanOptions, fn: F): ReturnType; + startActiveSpan ReturnType>(name: string, options: SpanOptions, context: Context, fn: F): ReturnType; +} +export declare function withNextSpan(attrs: Attributes): void; +//# sourceMappingURL=tracer.d.ts.map \ No newline at end of file diff --git a/dist/cjs/tracer.d.ts.map b/dist/cjs/tracer.d.ts.map new file mode 100644 index 0000000..5980d7c --- /dev/null +++ b/dist/cjs/tracer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tracer.d.ts","sourceRoot":"","sources":["../../src/tracer.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,UAAU,EACV,MAAM,EAEN,IAAI,EAEJ,WAAW,EACX,OAAO,EAGP,MAAM,oBAAoB,CAAA;AAE3B,OAAO,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAA;AACnD,OAAO,EAAE,aAAa,EAAqD,MAAM,+BAA+B,CAAA;AAOhH,qBAAa,YAAa,YAAW,MAAM;IAC1C,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAiB;IACjD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAU;IACnC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAA6C;gBAC7D,cAAc,EAAE,aAAa,EAAE,EAAE,QAAQ,EAAE,QAAQ;IAK/D,IAAI,cAAc,oBAEjB;IAED,aAAa,CAAC,KAAK,EAAE,QAAQ;IAI7B,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,WAAgB,EAAE,OAAO,UAAuB,GAAG,IAAI;IAiDxF,eAAe,CAAC,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,KAAK,UAAU,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC;IAC5F,eAAe,CAAC,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,KAAK,UAAU,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,EAAE,EAAE,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC;IAClH,eAAe,CAAC,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,KAAK,UAAU,CAAC,CAAC,CAAC,EACtD,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,WAAW,EACpB,OAAO,EAAE,OAAO,EAChB,EAAE,EAAE,CAAC,GACH,UAAU,CAAC,CAAC,CAAC;CAWhB;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,UAAU,QAE7C"} \ No newline at end of file diff --git a/dist/cjs/tracer.js b/dist/cjs/tracer.js new file mode 100644 index 0000000..69c8f4b --- /dev/null +++ b/dist/cjs/tracer.js @@ -0,0 +1,79 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WorkerTracer = void 0; +exports.withNextSpan = withNextSpan; +const api_1 = require("@opentelemetry/api"); +const core_1 = require("@opentelemetry/core"); +const sdk_trace_base_1 = require("@opentelemetry/sdk-trace-base"); +const span_js_1 = require("./span.js"); +const config_js_1 = require("./config.js"); +let withNextSpanAttributes; +class WorkerTracer { + constructor(spanProcessors, resource) { + this.idGenerator = new sdk_trace_base_1.RandomIdGenerator(); + this._spanProcessors = spanProcessors; + this.resource = resource; + } + get spanProcessors() { + return this._spanProcessors; + } + addToResource(extra) { + this.resource.merge(extra); + } + startSpan(name, options = {}, context = api_1.context.active()) { + if (options.root) { + context = api_1.trace.deleteSpan(context); + } + const parentSpan = api_1.trace.getSpan(context); + const parentSpanContext = parentSpan === null || parentSpan === void 0 ? void 0 : parentSpan.spanContext(); + const hasParentContext = parentSpanContext && api_1.trace.isSpanContextValid(parentSpanContext); + const traceId = hasParentContext ? parentSpanContext.traceId : this.idGenerator.generateTraceId(); + const spanKind = options.kind || api_1.SpanKind.INTERNAL; + const sanitisedAttrs = (0, core_1.sanitizeAttributes)(options.attributes); + const config = (0, config_js_1.getActiveConfig)(); + if (!config) + throw new Error('Config is undefined. This is a bug in the instrumentation logic'); + const sampler = config.sampling.headSampler; + const samplingDecision = sampler.shouldSample(context, traceId, name, spanKind, sanitisedAttrs, []); + const { decision, traceState, attributes: attrs } = samplingDecision; + const attributes = Object.assign({}, sanitisedAttrs, attrs, withNextSpanAttributes); + withNextSpanAttributes = {}; + const spanId = this.idGenerator.generateSpanId(); + const parentSpanId = hasParentContext ? parentSpanContext.spanId : undefined; + const traceFlags = decision === sdk_trace_base_1.SamplingDecision.RECORD_AND_SAMPLED ? api_1.TraceFlags.SAMPLED : api_1.TraceFlags.NONE; + const spanContext = { traceId, spanId, traceFlags, traceState }; + const span = new span_js_1.SpanImpl({ + attributes, + name, + onEnd: (span) => { + this.spanProcessors.forEach((sp) => { + sp.onEnd(span); + }); + }, + resource: this.resource, + spanContext, + parentSpanId, + spanKind, + startTime: options.startTime, + }); + this.spanProcessors.forEach((sp) => { + //Do not get me started on the idosyncracies of the Otel JS libraries. + //@ts-ignore + sp.onStart(span, context); + }); + return span; + } + startActiveSpan(name, ...args) { + const options = args.length > 1 ? args[0] : undefined; + const parentContext = args.length > 2 ? args[1] : api_1.context.active(); + const fn = args[args.length - 1]; + const span = this.startSpan(name, options, parentContext); + const contextWithSpanSet = api_1.trace.setSpan(parentContext, span); + return api_1.context.with(contextWithSpanSet, fn, undefined, span); + } +} +exports.WorkerTracer = WorkerTracer; +function withNextSpan(attrs) { + withNextSpanAttributes = Object.assign({}, withNextSpanAttributes, attrs); +} +//# sourceMappingURL=tracer.js.map \ No newline at end of file diff --git a/dist/cjs/tracer.js.map b/dist/cjs/tracer.js.map new file mode 100644 index 0000000..d00e71c --- /dev/null +++ b/dist/cjs/tracer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tracer.js","sourceRoot":"","sources":["../../src/tracer.ts"],"names":[],"mappings":";;;AA0GA,oCAEC;AA5GD,4CAU2B;AAC3B,8CAAwD;AAExD,kEAAgH;AAEhH,uCAAoC;AACpC,2CAA6C;AAE7C,IAAI,sBAAkC,CAAA;AAEtC,MAAa,YAAY;IAIxB,YAAY,cAA+B,EAAE,QAAkB;QAD9C,gBAAW,GAAsB,IAAI,kCAAiB,EAAE,CAAA;QAExE,IAAI,CAAC,eAAe,GAAG,cAAc,CAAA;QACrC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;IACzB,CAAC;I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Ae;QACxF,MAAM,OAAO,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAE,IAAI,CAAC,CAAC,CAAiB,CAAC,CAAC,CAAC,SAAS,CAAA;QACtE,MAAM,aAAa,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAE,IAAI,CAAC,CAAC,CAAa,CAAC,CAAC,CAAC,aAAW,CAAC,MAAM,EAAE,CAAA;QACnF,MAAM,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAM,CAAA;QAErC,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO,EAAE,aAAa,CAAC,CAAA;QACzD,MAAM,kBAAkB,GAAG,WAAK,CAAC,OAAO,CAAC,aAAa,EAAE,IAAI,CAAC,CAAA;QAE7D,OAAO,aAAW,CAAC,IAAI,CAAC,kBAAkB,EAAE,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,CAAA;IACjE,CAAC;CACD;AApFD,oCAoFC;AAED,SAAgB,YAAY,CAAC,KAAiB;IAC7C,sBAAsB,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,sBAAsB,EAAE,KAAK,CAAC,CAAA;AAC1E,CAAC"} \ No newline at end of file diff --git a/dist/cjs/types.d.ts b/dist/cjs/types.d.ts new file mode 100644 index 0000000..86fb8e4 --- /dev/null +++ b/dist/cjs/types.d.ts @@ -0,0 +1,61 @@ +import { TextMapPropagator } from '@opentelemetry/api'; +import { ReadableSpan, Sampler, SpanExporter, SpanProcessor } from '@opentelemetry/sdk-trace-base'; +import { OTLPExporterConfig } from './exporter.js'; +import { FetchHandlerConfig, FetcherConfig } from './instrumentation/fetch.js'; +import { TailSampleFn } from './sampling.js'; +export type PostProcessorFn = (spans: ReadableSpan[]) => ReadableSpan[]; +export type ExporterConfig = OTLPExporterConfig | SpanExporter; +export interface HandlerConfig { + fetch?: FetchHandlerConfig; +} +export interface ServiceConfig { + name: string; + namespace?: string; + version?: string; +} +export interface ParentRatioSamplingConfig { + acceptRemote?: boolean; + ratio: number; +} +type HeadSamplerConf = Sampler | ParentRatioSamplingConfig; +export interface SamplingConfig { + headSampler?: HS; + tailSampler?: TailSampleFn; +} +export interface InstrumentationOptions { + instrumentGlobalFetch?: boolean; + instrumentGlobalCache?: boolean; +} +interface TraceConfigBase { + service: ServiceConfig; + handlers?: HandlerConfig; + fetch?: FetcherConfig; + postProcessor?: PostProcessorFn; + sampling?: SamplingConfig; + propagator?: TextMapPropagator; + instrumentation?: InstrumentationOptions; +} +interface TraceConfigExporter extends TraceConfigBase { + exporter: ExporterConfig; +} +interface TraceConfigSpanProcessors extends TraceConfigBase { + spanProcessors: SpanProcessor | SpanProcessor[]; +} +export type TraceConfig = TraceConfigExporter | TraceConfigSpanProcessors; +export declare function isSpanProcessorConfig(config: TraceConfig): config is TraceConfigSpanProcessors; +export interface ResolvedTraceConfig extends TraceConfigBase { + handlers: Required; + fetch: Required; + postProcessor: PostProcessorFn; + sampling: Required>; + spanProcessors: SpanProcessor[]; + propagator: TextMapPropagator; + instrumentation: InstrumentationOptions; +} +export interface DOConstructorTrigger { + id: string; + name?: string; +} +export type Trigger = Request | MessageBatch | ScheduledController | DOConstructorTrigger | 'do-alarm'; +export {}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/dist/cjs/types.d.ts.map b/dist/cjs/types.d.ts.map new file mode 100644 index 0000000..2557200 --- /dev/null +++ b/dist/cjs/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAA;AACtD,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAA;AAClG,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAA;AAClD,OAAO,EAAE,kBAAkB,EA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aAAa,GAAG,aAAa,EAAE,CAAA;CAC/C;AAED,MAAM,MAAM,WAAW,GAAG,mBAAmB,GAAG,yBAAyB,CAAA;AAEzE,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,WAAW,GAAG,MAAM,IAAI,yBAAyB,CAE9F;AAED,MAAM,WAAW,mBAAoB,SAAQ,eAAe;IAC3D,QAAQ,EAAE,QAAQ,CAAC,aAAa,CAAC,CAAA;IACjC,KAAK,EAAE,QAAQ,CAAC,aAAa,CAAC,CAAA;IAC9B,aAAa,EAAE,eAAe,CAAA;IAC9B,QAAQ,EAAE,QAAQ,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,CAAA;IAC3C,cAAc,EAAE,aAAa,EAAE,CAAA;IAC/B,UAAU,EAAE,iBAAiB,CAAA;IAC7B,eAAe,EAAE,sBAAsB,CAAA;CACvC;AAED,MAAM,WAAW,oBAAoB;IACpC,EAAE,EAAE,MAAM,CAAA;IACV,IAAI,CAAC,EAAE,MAAM,CAAA;CACb;AAED,MAAM,MAAM,OAAO,GAAG,OAAO,GAAG,YAAY,GAAG,mBAAmB,GAAG,oBAAoB,GAAG,UAAU,CAAA"} \ No newline at end of file diff --git a/dist/cjs/types.js b/dist/cjs/types.js new file mode 100644 index 0000000..f13e1f4 --- /dev/null +++ b/dist/cjs/types.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isSpanProcessorConfig = isSpanProcessorConfig; +function isSpanProcessorConfig(config) { + return !!config.spanProcessors; +} +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/dist/cjs/types.js.map b/dist/cjs/types.js.map new file mode 100644 index 0000000..3694a4d --- /dev/null +++ b/dist/cjs/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";;AAwDA,sDAEC;AAFD,SAAgB,qBAAqB,CAAC,MAAmB;IACxD,OAAO,CAAC,CAAE,MAAoC,CAAC,cAAc,CAAA;AAC9D,CAAC"} \ No newline at end of file diff --git a/dist/cjs/vendor/ts-checked-fsm/StateMachine.d.ts b/dist/cjs/vendor/ts-checked-fsm/StateMachine.d.ts new file mode 100644 index 0000000..db591ea --- /dev/null +++ b/dist/cjs/vendor/ts-checked-fsm/StateMachine.d.ts @@ -0,0 +1,104 @@ +/** + * State labels can be strings + */ +type StateType = IndexType; +/** + * Action labels can be strings + */ +export type ActionNameType = IndexType; +/** + * Represents a state and data and its corresponding data. + */ +export type State = Readonly & { + readonly stateName: S; +}; +/** + * Give Actions to nextState() to (maybe) trigger a transition. + */ +export type Action = Readonly & { + readonly actionName: Name; +}; +/** + * Represents a compiler error message. Error brands prevent really clever users from naming their states as one of the error messages + * and subverting error checking. Yet, the compiler still displays the string at the end of the failed cast indicating what the + * issue is rather than something puzzling like could not assign to never. + */ +type ErrorBrand = { + [k in T]: void; +}; +type IndexType = string | number; +type AssertStateInMap = S extends MapKeys ? S : ErrorBrand<`'${S}' is not a state`>; +type AssertNewState = S extends MapKeys ? ErrorBrand<`'${S}' has already been declared`> : S; +type AssertNewTransition = N extends MapLookup ? ErrorBrand<`There already exists a transition from '${S}' to '${N}'`> : N; +type AssertActionNotDefined = AN extends ActionNames ? ErrorBrand<`Action '${AN}' already declared`> : AN; +type AssertActionIsDefined = AN extends ActionNames ? AN : ErrorBrand<`'${AN}' is not an action`>; +type AssertAllNonTerminalStatesHandled = MapKeys extends HandledStates ? void : ErrorBrand<`No handlers declared for ${Exclude, HandledStates>}`>; +type AddToTypeMap = M | [K, V]; +type MapLookup = Map extends [K, infer V] ? V : never; +type MapKeys = Map extends [infer K, infer _] ? (K extends IndexType ? K : never) : never; +type MapValues = Map extends [infer _, infer V] ? V : never; +/** + * A builder from calling stateMachine(). + */ +export type StateMachineBuilder = { + /** + * Add a state to this state machine. + */ + readonly state: StateFunc; +}; +type StateMachineFunc = () => StateMachineBuilder; +/** + * A builder from calling .state() + */ +export type StateBuilder = { + /** + * Add a state to this state machine. + */ + readonly state: StateFunc; + readonly transition: TransitionFunc; +}; +/** + * The signature for calling the state function in the builder. + */ +type StateFunc = (state: AssertNewState) => StateBuilder>>; +/** + * The builder returned by .transition() + */ +export type TransitionBuilder = { + /** + * Add a transition to this state machine. + */ + readonly transition: TransitionFunc; + readonly action: ActionFunc; +}; +/** + * The signature of .transition() + */ +export type TransitionFunc = (curState: AssertStateInMap, nextState: N extends MapKeys ? AssertNewTransition : ErrorBrand<`${S} is not a declared state`>) => TransitionBuilder>; +export type ActionBuilder = { + readonly action: ActionFunc; + readonly actionHandler: ActionHandlerFunc; +}; +export type ActionFunc = (actionName: AssertActionNotDefined>) => ActionBuilder>>; +/** + * The builder returned by .actionHandler() + */ +export type ActionHandlersBuilder = { + readonly actionHandler: ActionHandlerFunc; + readonly done: DoneFunc; +}; +/** + * The Signature of .actionHandler(). + */ +export type ActionHandlerFunc = >(state: AssertStateInMap, action: AssertActionIsDefined>, handler: ActionHandlerCallback) => ActionHandlersBuilder; +type ActionHandlerCallback, Actions> = (state: MapLookup, action: MapLookup) => NS extends State ? N extends MapKeys ? CS extends MapKeys ? N extends MapLookup ? State : ErrorBrand<`No transition declared between ${CS} and ${N}`> : ErrorBrand<`State ${CS} is terminal and has no transitions`> : ErrorBrand<`${N} is not a state`> : ErrorBrand<'The returned value is not a state'>; +type DoneFunc = (_: AssertAllNonTerminalStatesHandled) => StateMachine; +/** + * A state machine + */ +export type StateMachine = { + nextState: (curState: MapValues, action: MapValues) => MapValues; +}; +export declare const stateMachine: StateMachineFunc; +export {}; +//# sourceMappingURL=StateMachine.d.ts.map \ No newline at end of file diff --git a/dist/cjs/vendor/ts-checked-fsm/StateMachine.d.ts.map b/dist/cjs/vendor/ts-checked-fsm/StateMachine.d.ts.map new file mode 100644 index 0000000..a53ce47 --- /dev/null +++ b/dist/cjs/vendor/ts-checked-fsm/StateMachine.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"StateMachine.d.ts","sourceRoot":"","sources":["../../../../src/vendor/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,MAAM,YAAY,EAAE,gBAM1B,CAAA"} \ No newline at end of file diff --git a/dist/cjs/vendor/ts-checked-fsm/StateMachine.js b/dist/cjs/vendor/ts-checked-fsm/StateMachine.js new file mode 100644 index 0000000..35af6e8 --- /dev/null +++ b/dist/cjs/vendor/ts-checked-fsm/StateMachine.js @@ -0,0 +1,78 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.stateMachine = void 0; +const stateMachine = () => { + const stateFunc = state(); + return { + state: stateFunc, + }; +}; +exports.stateMachine = stateMachine; +const state = () => { + return (_s) => { + const transitionFunc = transition(); + const stateFunc = state(); + const builder = { + state: stateFunc, + transition: transitionFunc, + }; + return builder; + }; +}; +const transition = () => { + return (_curState, _next) => { + const transitionFunction = transition(); + const actionFunc = action(); + return { + transition: transitionFunction, + action: actionFunc, + }; + }; +}; +const action = () => { + return (_actionName) => { + const actionFunc = action(); + const actionHandlerFunc = actionHandler({ handlers: {} }); + return { + action: actionFunc, + actionHandler: actionHandlerFunc, + }; + }; +}; +const actionHandler = (definition) => { + return (state, action, handler) => { + const untypedState = state; + const untypedAction = action; + const newDefinition = Object.assign(Object.assign({}, definition), { handlers: Object.assign(Object.assign({}, definition.handlers), { [untypedState]: Object.assign(Object.assign({}, (definition.handlers[untypedState] ? definition.handlers[untypedState] : {})), { [untypedAction]: handler }) }) }); + const doneFunc = done(newDefinition); + const actionHandlerFunc = actionHandler(newDefinition); + return { + actionHandler: actionHandlerFunc, + done: doneFunc, + }; + }; +}; +const done = (definition) => { + const doneFunc = (_) => { + const nextStateFunction = (curState, action) => { + const curStateAsState = curState; + const actionAsAction = action; + // If no handler declared for state, state doesn't change. + if (definition.handlers[curStateAsState.stateName] == null) { + return curState; + } + // If no handler declared for action in given state, state doesn't change. + const handler = definition.handlers[curStateAsState.stateName]; + if (handler === undefined) { + return curState; + } + const nextAction = handler[actionAsAction.actionName]; + return nextAction != null ? nextAction(curState, action) : curState; + }; + return { + nextState: nextStateFunction, + }; + }; + return doneFunc; +}; +//# sourceMappingURL=StateMachine.js.map \ No newline at end of file diff --git a/dist/cjs/vendor/ts-checked-fsm/StateMachine.js.map b/dist/cjs/vendor/ts-checked-fsm/StateMachine.js.map new file mode 100644 index 0000000..49b0133 --- /dev/null +++ b/dist/cjs/vendor/ts-checked-fsm/StateMachine.js.map @@ -0,0 +1 @@ +{"version":3,"file":"StateMachine.js","sourceRoot":"","sources":["../../../../src/vendor/ts-checked-fsm/StateMachine.ts"],"names":[],"mappings":";;;AAuNO,MAAM,YAAY,GAAqB,GAAwB,EAAE;IACvE,MAAM,SAAS,GAAG,KAAK,EAAS,CAAA;IAEhC,OAAO;QACN,KAAK,EAAE,SAAS;KAChB,CAAA;AACF,CAAC,CAAA;AANY,QAAA,YAAY,gBAMxB;AAED,MAAM,KAAK,GAAG,GAAkC,EAAE;IACjD,OAAO,CAA8B,EAA+B,EAAE,EAAE;QAGvE,MAAM,cAAc,GAAG,UAAU,EAAsB,CAAA;QACvD,MAAM,SAAS,GAAG,KAAK,EAAe,CAAA;QAEtC,MAAM,OAAO,GAAG;YACf,KAAK,EAAE,SAAS;YAChB,UAAU,EAAE,cAAc;SAC1B,CAAA;QAED,OAAO,OAAO,CAAA;IACf,CAAC,CAAA;AACF,CAAC,CAAA;AAED,MAAM,UAAU,GAAG,GAAiE,EAAE;IACrF,OAAO,CACN,SAAwC,EACxC,KAE6C,EAC5C,EAAE;QAGH,MAAM,kBAAkB,GAAG,UAAU,EAA4B,CAAA;QACjE,MAAM,UAAU,GAAG,MAAM,EAAmC,CAAA;QAE5D,OAAO;YACN,UAAU,EAAE,kBAAkB;YAC9B,MAAM,EAAE,UAAU;SAClB,CAAA;IACF,CAAC,CAAA;AACF,CAAC,CAAA;AAED,MAAM,MAAM,GAAG,GAAmF,EAAE;IACnG,OAAO,CAAqC,WAA2D,EAAE,EAAE;QAG1G,MAAM,UAAU,GAAQ,MAAM,EAAuC,CAAA;QACrE,MAAM,iBAAiB,GAAG,aAAa,CAA6C,EAAE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AC1E,MAAM,OAAO,GAAG,UAAU,CAAC,QAAQ,CAAC,eAAe,CAAC,SAAS,CAAC,CAAA;YAC9D,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;gBAC3B,OAAO,QAAQ,CAAA;YAChB,CAAC;YACD,MAAM,UAAU,GAAG,OAAO,CAAC,cAAc,CAAC,UAAU,CAAC,CAAA;YAErD,OAAO,UAAU,IAAI,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAA;QACpE,CAAC,CAAA;QAED,OAAO;YACN,SAAS,EAAE,iBAAiB;SAC5B,CAAA;IACF,CAAC,CAAA;IAED,OAAO,QAAQ,CAAA;AAChB,CAAC,CAAA"} \ No newline at end of file diff --git a/dist/cjs/wrap.d.ts b/dist/cjs/wrap.d.ts new file mode 100644 index 0000000..a318610 --- /dev/null +++ b/dist/cjs/wrap.d.ts @@ -0,0 +1,11 @@ +declare const unwrapSymbol: unique symbol; +type Wrapped = { + [unwrapSymbol]: T; +} & T; +export declare function isWrapped(item: T): item is Wrapped; +export declare function isProxyable(item: any): boolean; +export declare function wrap(item: T, handler: ProxyHandler, autoPassthrough?: boolean): T; +export declare function unwrap(item: T): T; +export declare function passthroughGet(target: any, prop: string | symbol, thisArg?: any): any; +export {}; +//# sourceMappingURL=wrap.d.ts.map \ No newline at end of file diff --git a/dist/cjs/wrap.d.ts.map b/dist/cjs/wrap.d.ts.map new file mode 100644 index 0000000..0ee44b1 --- /dev/null +++ b/dist/cjs/wrap.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"wrap.d.ts","sourceRoot":"","sources":["../../src/wrap.ts"],"names":[],"mappings":"AAAA,QAAA,MAAM,YAAY,eAAmB,CAAA;AAErC,KAAK,OAAO,CAAC,CAAC,IAAI;IAAE,CAAC,YAAY,CAAC,EAAE,CAAC,CAAA;CAAE,GAAG,CAAC,CAAA;AAE3C,wBAAgB,SAAS,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,GAAG,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,CAExD;AAED,wBAAgB,WAAW,CAAC,IAAI,EAAE,GAAG,WAEpC;AAED,wBAAgB,IAAI,CAAC,CAAC,SAAS,MAAM,EAAE,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,EAAE,eAAe,GAAE,OAAc,GAAG,CAAC,CAwB5G;AAED,wBAAgB,MAAM,CAAC,CAAC,SAAS,MAAM,EAAE,IAAI,EAAE,CAAC,GAAG,CAAC,CAMnD;AAED,wBAAgB,cAAc,CAAC,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,OAY/E"} \ No newline at end of file diff --git a/dist/cjs/wrap.js b/dist/cjs/wrap.js new file mode 100644 index 0000000..98b3ec5 --- /dev/null +++ b/dist/cjs/wrap.js @@ -0,0 +1,65 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isWrapped = isWrapped; +exports.isProxyable = isProxyable; +exports.wrap = wrap; +exports.unwrap = unwrap; +exports.passthroughGet = passthroughGet; +const unwrapSymbol = Symbol('unwrap'); +function isWrapped(item) { + return item && !!item[unwrapSymbol]; +} +function isProxyable(item) { + return (item !== null && typeof item === 'object') || typeof item === 'function'; +} +function wrap(item, handler, autoPassthrough = true) { + if (isWrapped(item) || !isProxyable(item)) { + return item; + } + const proxyHandler = Object.assign({}, handler); + proxyHandler.get = (target, prop, receiver) => { + if (prop === unwrapSymbol) { + return item; + } + else { + if (handler.get) { + return handler.get(target, prop, receiver); + } + else if (prop === 'bind') { + return () => receiver; + } + else if (autoPassthrough) { + return passthroughGet(target, prop); + } + } + }; + proxyHandler.apply = (target, thisArg, argArray) => { + if (handler.apply) { + return handler.apply(unwrap(target), unwrap(thisArg), argArray); + } + }; + return new Proxy(item, proxyHandler); +} +function unwrap(item) { + if (item && isWrapped(item)) { + return item[unwrapSymbol]; + } + else { + return item; + } +} +function passthroughGet(target, prop, thisArg) { + const unwrappedTarget = unwrap(target); + const value = Reflect.get(unwrappedTarget, prop); + if (typeof value === 'function') { + if (value.constructor.name === 'RpcProperty') { + return (...args) => unwrappedTarget[prop](...args); + } + thisArg = thisArg || unwrappedTarget; + return value.bind(thisArg); + } + else { + return value; + } +} +//# sourceMappingURL=wrap.js.map \ No newline at end of file diff --git a/dist/cjs/wrap.js.map b/dist/cjs/wrap.js.map new file mode 100644 index 0000000..2c1af1f --- /dev/null +++ b/dist/cjs/wrap.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wrap.js","sourceRoot":"","sources":["../../src/wrap.ts"],"names":[],"mappings":";;AAIA,8BAEC;AAED,kCAEC;AAED,oBAwBC;AAED,wBAMC;AAED,wCAYC;AA1DD,MAAM,YAAY,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAA;AAIrC,SAAgB,SAAS,CAAI,IAAO;IACnC,OAAO,IAAI,IAAI,CAAC,CAAE,IAAmB,CAAC,YAAY,CAAC,CAAA;AACpD,CAAC;AAED,SAAgB,WAAW,CAAC,IAAS;IACpC,OAAO,CAAC,IAAI,KAAK,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,CAAC,IAAI,OAAO,IAAI,KAAK,UAAU,CAAA;AACjF,CAAC;AAED,SAAgB,IAAI,CAAmB,IAAO,EAAE,OAAwB,EAAE,kBAA2B,IAAI;IACxG,IAAI,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC;QAC3C,OAAO,IAAI,CAAA;IACZ,CAAC;IACD,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,OAAO,CAAC,CAAA;IAC/C,YAAY,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE;QAC7C,IAAI,IAAI,KAAK,YAAY,EAAE,CAAC;YAC3B,OAAO,IAAI,CAAA;QAC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AC9C,OAAO,CAAC,GAAG,IAAe,EAAE,EAAE,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,CAAA;QAC9D,CAAC;QACD,OAAO,GAAG,OAAO,IAAI,eAAe,CAAA;QACpC,OAAO,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;IAC3B,CAAC;SAAM,CAAC;QACP,OAAO,KAAK,CAAA;IACb,CAAC;AACF,CAAC"} \ No newline at end of file diff --git a/dist/esm/buffer.d.ts b/dist/esm/buffer.d.ts new file mode 100644 index 0000000..791fb5b --- /dev/null +++ b/dist/esm/buffer.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=buffer.d.ts.map \ No newline at end of file diff --git a/dist/esm/buffer.d.ts.map b/dist/esm/buffer.d.ts.map new file mode 100644 index 0000000..e8e3934 --- /dev/null +++ b/dist/esm/buffer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"buffer.d.ts","sourceRoot":"","sources":["../../src/buffer.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/buffer.js b/dist/esm/buffer.js new file mode 100644 index 0000000..cd3e214 --- /dev/null +++ b/dist/esm/buffer.js @@ -0,0 +1,5 @@ +//@ts-ignore +import { Buffer } from 'node:buffer'; +//@ts-ignore +globalThis.Buffer = Buffer; +//# sourceMappingURL=buffer.js.map \ No newline at end of file diff --git a/dist/esm/buffer.js.map b/dist/esm/buffer.js.map new file mode 100644 index 0000000..b481391 --- /dev/null +++ b/dist/esm/buffer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"buffer.js","sourceRoot":"","sources":["../../src/buffer.ts"],"names":[],"mappings":"AAAA,YAAY;AACZ,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,YAAY;AACZ,UAAU,CAAC,MAAM,GAAG,MAAM,CAAA"} \ No newline at end of file diff --git a/dist/esm/config.d.ts b/dist/esm/config.d.ts new file mode 100644 index 0000000..f53b0a9 --- /dev/null +++ b/dist/esm/config.d.ts @@ -0,0 +1,5 @@ +import { ResolvedTraceConfig, Trigger } from './types.js'; +export type Initialiser = (env: Record, trigger: Trigger) => ResolvedTraceConfig; +export declare function setConfig(config: ResolvedTraceConfig, ctx?: import("@opentelemetry/api").Context): import("@opentelemetry/api").Context; +export declare function getActiveConfig(): ResolvedTraceConfig | undefined; +//# sourceMappingURL=config.d.ts.map \ No newline at end of file diff --git a/dist/esm/config.d.ts.map b/dist/esm/config.d.ts.map new file mode 100644 index 0000000..5aca950 --- /dev/null +++ b/dist/esm/config.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAIzD,MAAM,MAAM,WAAW,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,EAAE,OAAO,KAAK,mBAAmB,CAAA;AAEjG,wBAAgB,SAAS,CAAC,MAAM,EAAE,mBAAmB,EAAE,GAAG,uCAAmB,wCAE5E;AAED,wBAAgB,eAAe,IAAI,mBAAmB,GAAG,SAAS,CAGjE"} \ No newline at end of file diff --git a/dist/esm/config.js b/dist/esm/config.js new file mode 100644 index 0000000..5311cfb --- /dev/null +++ b/dist/esm/config.js @@ -0,0 +1,10 @@ +import { context } from '@opentelemetry/api'; +const configSymbol = Symbol('Otel Workers Tracing Configuration'); +export function setConfig(config, ctx = context.active()) { + return ctx.setValue(configSymbol, config); +} +export function getActiveConfig() { + const config = context.active().getValue(configSymbol); + return config || undefined; +} +//# sourceMappingURL=config.js.map \ No newline at end of file diff --git a/dist/esm/config.js.map b/dist/esm/config.js.map new file mode 100644 index 0000000..cb7c21d --- /dev/null +++ b/dist/esm/config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAA;AAG5C,MAAM,YAAY,GAAG,MAAM,CAAC,oCAAoC,CAAC,CAAA;AAIjE,MAAM,UAAU,SAAS,CAAC,MAA2B,EAAE,GAAG,GAAG,OAAO,CAAC,MAAM,EAAE;IAC5E,OAAO,GAAG,CAAC,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC,CAAA;AAC1C,CAAC;AAED,MAAM,UAAU,eAAe;IAC9B,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,YAAY,CAAwB,CAAA;IAC7E,OAAO,MAAM,IAAI,SAAS,CAAA;AAC3B,CAAC"} \ No newline at end of file diff --git a/dist/esm/context.d.ts b/dist/esm/context.d.ts new file mode 100644 index 0000000..997e893 --- /dev/null +++ b/dist/esm/context.d.ts @@ -0,0 +1,59 @@ +import { ContextManager, Context } from '@opentelemetry/api'; +declare abstract class AbstractAsyncHooksContextManager implements ContextManager { + abstract active(): Context; + abstract with ReturnType>(context: Context, fn: F, thisArg?: ThisParameterType, ...args: A): ReturnType; + abstract enable(): this; + abstract disable(): this; + /** + * Binds a the certain context or the active one to the target function and then returns the target + * @param context A context (span) to be bind to target + * @param target a function or event emitter. When target or one of its callbacks is called, + * the provided context will be used as the active context for the duration of the call. + */ + bind(context: Context, target: T): T; + private _bindFunction; + /** + * By default, EventEmitter call their callback with their context, which we do + * not want, instead we will bind a specific context to all callbacks that + * go through it. + * @param context the context we want to bind + * @param ee EventEmitter an instance of EventEmitter to patch + */ + private _bindEventEmitter; + /** + * Patch methods that remove a given listener so that we match the "patched" + * version of that listener (the one that propagate context). + * @param ee EventEmitter instance + * @param original reference to the patched method + */ + private _patchRemoveListener; + /** + * Patch methods that remove all listeners so we remove our + * internal references for a given event. + * @param ee EventEmitter instance + * @param original reference to the patched method + */ + private _patchRemoveAllListeners; + /** + * Patch methods on an event emitter instance that can add listeners so we + * can force them to propagate a given context. + * @param ee EventEmitter instance + * @param original reference to the patched method + * @param [context] context to propagate when calling listeners + */ + private _patchAddListener; + private _createPatchMap; + private _getPatchMap; + private readonly _kOtListeners; + private _wrapped; +} +export declare class AsyncLocalStorageContextManager extends AbstractAsyncHooksContextManager { + private _asyncLocalStorage; + constructor(); + active(): Context; + with ReturnType>(context: Context, fn: F, thisArg?: ThisParameterType, ...args: A): ReturnType; + enable(): this; + disable(): this; +} +export {}; +//# sourceMappingURL=context.d.ts.map \ No newline at end of file diff --git a/dist/esm/context.d.ts.map b/dist/esm/context.d.ts.map new file mode 100644 index 0000000..1dacda5 --- /dev/null +++ b/dist/esm/context.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../src/context.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,cAAc,EAAE,OAAO,EAAgB,MAAM,oBAAoB,CAAA;AAyB1E,uBAAe,gCAAiC,YAAW,cAAc;IACxE,QAAQ,CAAC,MAAM,IAAI,OAAO;IAE1B,QAAQ,CAAC,IAAI,CAAC,CAAC,SAAS,OAAO,EAAE,EAAE,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,CAAC,KAAK,UAAU,CAAC,CAAC,CAAC,EACzE,OAAO,EAAE,OAAO,EAChB,EAAE,EAAE,CAAC,EACL,OAAO,CAAC,EAAE,iBAAiB,CAAC,CAAC,CAAC,EAC9B,GAAG,IAAI,EAAE,CAAC,GACR,UAAU,CAAC,CAAC,CAAC;IAEhB,QAAQ,CAAC,MAAM,IAAI,IAAI;IAEvB,QAAQ,CAAC,OAAO,IAAI,IAAI;IAExB;;;;;OAKG;IACH,IAAI,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,GAAG,CAAC;IAWvC,OAAO,CAAC,aAAa;IAmBrB;;;;;;OAMG;IACH,OAAO,CAAC,iBAAiB;IAwBzB;;;;;OAKG;IACH,OAAO,CAAC,oBAAoB;IAY5B;;;;;OAKG;IACH,OAAO,CAAC,wBAAwB;IAehC;;;;;;OAMG;IACH,OAAO,CAAC,iBAAiB;IAuCzB,OAAO,CAAC,eAAe;IAMvB,OAAO,CAAC,YAAY;IAIpB,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAwB;IACtD,OAAO,CAAC,QAAQ,CAAQ;CACxB;AAED,qBAAa,+BAAgC,SAAQ,gCAAgC;IACpF,OAAO,CAAC,kBAAkB,CAA4B;;IAOtD,MAAM,IAAI,OAAO;IAIjB,IAAI,CAAC,CAAC,SAAS,OAAO,EAAE,EAAE,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,CAAC,KAAK,UAAU,CAAC,CAAC,CAAC,EAChE,OAAO,EAAE,OAAO,EAChB,EAAE,EAAE,CAAC,EACL,OAAO,CAAC,EAAE,iBAAiB,CAAC,CAAC,CAAC,EAC9B,GAAG,IAAI,EAAE,CAAC,GACR,UAAU,CAAC,CAAC,CAAC;IAKhB,MAAM,IAAI,IAAI;IAId,OAAO,IAAI,IAAI;CAIf"} \ No newline at end of file diff --git a/dist/esm/context.js b/dist/esm/context.js new file mode 100644 index 0000000..2d36bc7 --- /dev/null +++ b/dist/esm/context.js @@ -0,0 +1,208 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ROOT_CONTEXT } from '@opentelemetry/api'; +//@ts-ignore +import { AsyncLocalStorage } from 'node:async_hooks'; +//@ts-ignore +import { EventEmitter } from 'node:events'; +const ADD_LISTENER_METHODS = [ + 'addListener', + 'on', + 'once', + 'prependListener', + 'prependOnceListener', +]; +class AbstractAsyncHooksContextManager { + /** + * Binds a the certain context or the active one to the target function and then returns the target + * @param context A context (span) to be bind to target + * @param target a function or event emitter. When target or one of its callbacks is called, + * the provided context will be used as the active context for the duration of the call. + */ + bind(context, target) { + if (target instanceof EventEmitter) { + return this._bindEventEmitter(context, target); + } + if (typeof target === 'function') { + return this._bindFunction(context, target); + } + return target; + } + _bindFunction(context, target) { + const manager = this; + const contextWrapper = function (...args) { + return manager.with(context, () => target.apply(this, args)); + }; + Object.defineProperty(contextWrapper, 'length', { + enumerable: false, + configurable: true, + writable: false, + value: target.length, + }); + /** + * It isn't possible to tell Typescript that contextWrapper is the same as T + * so we forced to cast as any here. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return contextWrapper; + } + /** + * By default, EventEmitter call their callback with their context, which we do + * not want, instead we will bind a specific context to all callbacks that + * go through it. + * @param context the context we want to bind + * @param ee EventEmitter an instance of EventEmitter to patch + */ + _bindEventEmitter(context, ee) { + const map = this._getPatchMap(ee); + if (map !== undefined) + return ee; + this._createPatchMap(ee); + // patch methods that add a listener to propagate context + ADD_LISTENER_METHODS.forEach((methodName) => { + if (ee[methodName] === undefined) + return; + ee[methodName] = this._patchAddListener(ee, ee[methodName], context); + }); + // patch methods that remove a listener + if (typeof ee.removeListener === 'function') { + ee.removeListener = this._patchRemoveListener(ee, ee.removeListener); + } + if (typeof ee.off === 'function') { + ee.off = this._patchRemoveListener(ee, ee.off); + } + // patch method that remove all listeners + if (typeof ee.removeAllListeners === 'function') { + ee.removeAllListeners = this._patchRemoveAllListeners(ee, ee.removeAllListeners); + } + return ee; + } + /** + * Patch methods that remove a given listener so that we match the "patched" + * version of that listener (the one that propagate context). + * @param ee EventEmitter instance + * @param original reference to the patched method + */ + _patchRemoveListener(ee, original) { + const contextManager = this; + return function (event, listener) { + const events = contextManager._getPatchMap(ee)?.[event]; + if (events === undefined) { + return original.call(this, event, listener); + } + const patchedListener = events.get(listener); + return original.call(this, event, patchedListener || listener); + }; + } + /** + * Patch methods that remove all listeners so we remove our + * internal references for a given event. + * @param ee EventEmitter instance + * @param original reference to the patched method + */ + _patchRemoveAllListeners(ee, original) { + const contextManager = this; + return function (event) { + const map = contextManager._getPatchMap(ee); + if (map !== undefined) { + if (arguments.length === 0) { + contextManager._createPatchMap(ee); + } + else if (map[event] !== undefined) { + delete map[event]; + } + } + return original.apply(this, arguments); + }; + } + /** + * Patch methods on an event emitter instance that can add listeners so we + * can force them to propagate a given context. + * @param ee EventEmitter instance + * @param original reference to the patched method + * @param [context] context to propagate when calling listeners + */ + _patchAddListener(ee, original, context) { + const contextManager = this; + return function (event, listener) { + /** + * This check is required to prevent double-wrapping the listener. + * The implementation for ee.once wraps the listener and calls ee.on. + * Without this check, we would wrap that wrapped listener. + * This causes an issue because ee.removeListener depends on the onceWrapper + * to properly remove the listener. If we wrap their wrapper, we break + * that detection. + */ + if (contextManager._wrapped) { + return original.call(this, event, listener); + } + let map = contextManager._getPatchMap(ee); + if (map === undefined) { + map = contextManager._createPatchMap(ee); + } + let listeners = map[event]; + if (listeners === undefined) { + listeners = new WeakMap(); + map[event] = listeners; + } + const patchedListener = contextManager.bind(context, listener); + // store a weak reference of the user listener to ours + listeners.set(listener, patchedListener); + /** + * See comment at the start of this function for the explanation of this property. + */ + contextManager._wrapped = true; + try { + return original.call(this, event, patchedListener); + } + finally { + contextManager._wrapped = false; + } + }; + } + _createPatchMap(ee) { + const map = Object.create(null); + ee[this._kOtListeners] = map; + return map; + } + _getPatchMap(ee) { + return ee[this._kOtListeners]; + } + _kOtListeners = Symbol('OtListeners'); + _wrapped = false; +} +export class AsyncLocalStorageContextManager extends AbstractAsyncHooksContextManager { + _asyncLocalStorage; + constructor() { + super(); + this._asyncLocalStorage = new AsyncLocalStorage(); + } + active() { + return this._asyncLocalStorage.getStore() ?? ROOT_CONTEXT; + } + with(context, fn, thisArg, ...args) { + const cb = thisArg == null ? fn : fn.bind(thisArg); + return this._asyncLocalStorage.run(context, cb, ...args); + } + enable() { + return this; + } + disable() { + this._asyncLocalStorage.disable(); + return this; + } +} +//# sourceMappingURL=context.js.map \ No newline at end of file diff --git a/dist/esm/context.js.map b/dist/esm/context.js.map new file mode 100644 index 0000000..900b6c0 --- /dev/null +++ b/dist/esm/context.js.map @@ -0,0 +1 @@ +{"version":3,"file":"context.js","sourceRoot":"","sources":["../../src/context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAA2B,YAAY,EAAE,MAAM,oBAAoB,CAAA;AAC1E,YAAY;AACZ,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAA;AACpD,YAAY;AACZ,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAa1C,MAAM,oBAAoB,GAAG;IAC5B,aAAsB;IACtB,IAAa;IACb,MAAe;IACf,iBAA0B;IAC1B,qBAA8B;CAC9B,CAAA;AAED,MAAe,gCAAgC;IAc9C;;;;;OAKG;IACH,IAAI,CAAI,OAAgB,EAAE,MAAS;QAClC,IAAI,MAAM,YAAY,YAAY,EAAE,CAAC;YACpC,OAAO,IAAI,CAAC,iBAAiB,CAAC,OAAO,EAAE,MAAM,CAAC,CAAA;QAC/C,CAAC;QAED,IAAI,OAAO,MAAM,KAAK,UAAU,EAAE,CAAC;YAClC,OAAO,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,MAAM,CAAC,CAAA;QAC3C,CAAC;QACD,OAAO,MAAM,CAAA;IACd,CAAC;IAEO,aAAa,CAAqB,OAAgB,EAAE,MAAS;QACpE,MAAM,OAAO,GAAG,IAAI,CAAA;QACpB,MAAM,cAAc,GAAG,UAAuB,GAAG,IAAe;YAC/D,OAAO,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAA;QAC7D,CAAC,CAAA;QACD,MAAM,CAAC,cAAc,CAAC,cAAc,EAAE,QAAQ,EAAE;YAC/C,UAAU,EAAE,KAAK;YACjB,YAAY,EAAE,IAAI;YAClB,QAAQ,EAAE,KAAK;YACf,KAAK,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AAC;IAEgB,aAAa,GAAG,MAAM,CAAC,aAAa,CAAC,CAAA;IAC9C,QAAQ,GAAG,KAAK,CAAA;CACxB;AAED,MAAM,OAAO,+BAAgC,SAAQ,gCAAgC;IAC5E,kBAAkB,CAA4B;IAEtD;QACC,KAAK,EAAE,CAAA;QACP,IAAI,CAAC,kBAAkB,GAAG,IAAI,iBAAiB,EAAE,CAAA;IAClD,CAAC;IAED,MAAM;QACL,OAAO,IAAI,CAAC,kBAAkB,CAAC,QAAQ,EAAE,IAAI,YAAY,CAAA;IAC1D,CAAC;IAED,IAAI,CACH,OAAgB,EAChB,EAAK,EACL,OAA8B,EAC9B,GAAG,IAAO;QAEV,MAAM,EAAE,GAAG,OAAO,IAAI,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAClD,OAAO,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,OAAO,EAAE,EAAW,EAAE,GAAG,IAAI,CAAC,CAAA;IAClE,CAAC;IAED,MAAM;QACL,OAAO,IAAI,CAAA;IACZ,CAAC;IAED,OAAO;QACN,IAAI,CAAC,kBAAkB,CAAC,OAAO,EAAE,CAAA;QACjC,OAAO,IAAI,CAAA;IACZ,CAAC;CACD"} \ No newline at end of file diff --git a/dist/esm/exporter.d.ts b/dist/esm/exporter.d.ts new file mode 100644 index 0000000..5842fc5 --- /dev/null +++ b/dist/esm/exporter.d.ts @@ -0,0 +1,17 @@ +import { OTLPExporterError } from '@opentelemetry/otlp-exporter-base'; +import { ExportResult } from '@opentelemetry/core'; +import { SpanExporter } from '@opentelemetry/sdk-trace-base'; +export interface OTLPExporterConfig { + url: string; + headers?: Record; +} +export declare class OTLPExporter implements SpanExporter { + private headers; + private url; + constructor(config: OTLPExporterConfig); + export(items: any[], resultCallback: (result: ExportResult) => void): void; + private _export; + send(items: any[], onSuccess: () => void, onError: (error: OTLPExporterError) => void): void; + shutdown(): Promise; +} +//# sourceMappingURL=exporter.d.ts.map \ No newline at end of file diff --git a/dist/esm/exporter.d.ts.map b/dist/esm/exporter.d.ts.map new file mode 100644 index 0000000..df6f7af --- /dev/null +++ b/dist/esm/exporter.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"exporter.d.ts","sourceRoot":"","sources":["../../src/exporter.ts"],"names":[],"mappings":"AACA,OAAO,EAAsB,iBAAiB,EAAE,MAAM,mCAAmC,CAAA;AACzF,OAAO,EAAE,YAAY,EAAoB,MAAM,qBAAqB,CAAA;AACpE,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAA;AAG5D,MAAM,WAAW,kBAAkB;IAClC,GAAG,EAAE,MAAM,CAAA;IACX,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAChC;AAOD,qBAAa,YAAa,YAAW,YAAY;IAChD,OAAO,CAAC,OAAO,CAAwB;IACvC,OAAO,CAAC,GAAG,CAAQ;gBACP,MAAM,EAAE,kBAAkB;IAKtC,MAAM,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,cAAc,EAAE,CAAC,MAAM,EAAE,YAAY,KAAK,IAAI,GAAG,IAAI;IAU1E,OAAO,CAAC,OAAO;IAUf,IAAI,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,SAAS,EAAE,MAAM,IAAI,EAAE,OAAO,EAAE,CAAC,KAAK,EAAE,iBAAiB,KAAK,IAAI,GAAG,IAAI;IAyBtF,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;CAC/B"} \ No newline at end of file diff --git a/dist/esm/exporter.js b/dist/esm/exporter.js new file mode 100644 index 0000000..074a9a0 --- /dev/null +++ b/dist/esm/exporter.js @@ -0,0 +1,61 @@ +import { createExportTraceServiceRequest } from '@opentelemetry/otlp-transformer'; +import { OTLPExporterError } from '@opentelemetry/otlp-exporter-base'; +import { ExportResultCode } from '@opentelemetry/core'; +import { unwrap } from './wrap.js'; +const defaultHeaders = { + accept: 'application/json', + 'content-type': 'application/json', +}; +export class OTLPExporter { + headers; + url; + constructor(config) { + this.url = config.url; + this.headers = Object.assign({}, defaultHeaders, config.headers); + } + export(items, resultCallback) { + this._export(items) + .then(() => { + resultCallback({ code: ExportResultCode.SUCCESS }); + }) + .catch((error) => { + resultCallback({ code: ExportResultCode.FAILED, error }); + }); + } + _export(items) { + return new Promise((resolve, reject) => { + try { + this.send(items, resolve, reject); + } + catch (e) { + reject(e); + } + }); + } + send(items, onSuccess, onError) { + const exportMessage = createExportTraceServiceRequest(items, { + useHex: true, + useLongBits: false, + }); + const body = JSON.stringify(exportMessage); + const params = { + method: 'POST', + headers: this.headers, + body, + }; + unwrap(fetch)(this.url, params) + .then((response) => { + if (response.ok) { + onSuccess(); + } + else { + onError(new OTLPExporterError(`Exporter received a statusCode: ${response.status}`)); + } + }) + .catch((error) => { + onError(new OTLPExporterError(`Exception during export: ${error.toString()}`, error.code, error.stack)); + }); + } + async shutdown() { } +} +//# sourceMappingURL=exporter.js.map \ No newline at end of file diff --git a/dist/esm/exporter.js.map b/dist/esm/exporter.js.map new file mode 100644 index 0000000..f9123bb --- /dev/null +++ b/dist/esm/exporter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"exporter.js","sourceRoot":"","sources":["../../src/exporter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,+BAA+B,EAAE,MAAM,iCAAiC,CAAA;AACjF,OAAO,EAAsB,iBAAiB,EAAE,MAAM,mCAAmC,CAAA;AACzF,OAAO,EAAgB,gBAAgB,EAAE,MAAM,qBAAqB,CAAA;AAEpE,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAA;AAOlC,MAAM,cAAc,GAA2B;IAC9C,MAAM,EAAE,kBAAkB;IAC1B,cAAc,EAAE,kBAAkB;CAClC,CAAA;AAED,MAAM,OAAO,YAAY;IAChB,OAAO,CAAwB;IAC/B,GAAG,CAAQ;IACnB,YAAY,MAA0B;QACrC,IAAI,CAAC,GAAG,GAAG,MAAM,CAAC,GAAG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,CAAC,QAAQ,EAAE,EAAE;YAClB,IAAI,QAAQ,CAAC,EAAE,EAAE,CAAC;gBACjB,SAAS,EAAE,CAAA;YACZ,CAAC;iBAAM,CAAC;gBACP,OAAO,CAAC,IAAI,iBAAiB,CAAC,mCAAmC,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC,CAAA;YACrF,CAAC;QACF,CAAC,CAAC;aACD,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;YAChB,OAAO,CAAC,IAAI,iBAAiB,CAAC,4BAA4B,KAAK,CAAC,QAAQ,EAAE,EAAE,EAAE,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC,CAAA;QACxG,CAAC,CAAC,CAAA;IACJ,CAAC;IAED,KAAK,CAAC,QAAQ,KAAmB,CAAC;CAClC"} \ No newline at end of file diff --git a/dist/esm/index.d.ts b/dist/esm/index.d.ts new file mode 100644 index 0000000..56637cc --- /dev/null +++ b/dist/esm/index.d.ts @@ -0,0 +1,10 @@ +export * from './buffer.js'; +export * from './sampling.js'; +export * from './sdk.js'; +export * from './span.js'; +export * from './exporter.js'; +export * from './multiexporter.js'; +export * from './spanprocessor.js'; +export { withNextSpan } from './tracer.js'; +export type * from './types.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/esm/index.d.ts.map b/dist/esm/index.d.ts.map new file mode 100644 index 0000000..9510ad3 --- /dev/null +++ b/dist/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAA;AAC3B,cAAc,eAAe,CAAA;AAC7B,cAAc,UAAU,CAAA;AACxB,cAAc,WAAW,CAAA;AACzB,cAAc,eAAe,CAAA;AAC7B,cAAc,oBAAoB,CAAA;AAClC,cAAc,oBAAoB,CAAA;AAClC,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAC1C,mBAAmB,YAAY,CAAA"} \ No newline at end of file diff --git a/dist/esm/index.js b/dist/esm/index.js new file mode 100644 index 0000000..2537a3b --- /dev/null +++ b/dist/esm/index.js @@ -0,0 +1,9 @@ +export * from './buffer.js'; +export * from './sampling.js'; +export * from './sdk.js'; +export * from './span.js'; +export * from './exporter.js'; +export * from './multiexporter.js'; +export * from './spanprocessor.js'; +export { withNextSpan } from './tracer.js'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/esm/index.js.map b/dist/esm/index.js.map new file mode 100644 index 0000000..61b08c3 --- /dev/null +++ b/dist/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAA;AAC3B,cAAc,eAAe,CAAA;AAC7B,cAAc,UAAU,CAAA;AACxB,cAAc,WAAW,CAAA;AACzB,cAAc,eAAe,CAAA;AAC7B,cAAc,oBAAoB,CAAA;AAClC,cAAc,oBAAoB,CAAA;AAClC,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA"} \ No newline at end of file diff --git a/dist/esm/instrumentation/analytics-engine.d.ts b/dist/esm/instrumentation/analytics-engine.d.ts new file mode 100644 index 0000000..99ca8f7 --- /dev/null +++ b/dist/esm/instrumentation/analytics-engine.d.ts @@ -0,0 +1,2 @@ +export declare function instrumentAnalyticsEngineDataset(dataset: AnalyticsEngineDataset, name: string): AnalyticsEngineDataset; +//# sourceMappingURL=analytics-engine.d.ts.map \ No newline at end of file diff --git a/dist/esm/instrumentation/analytics-engine.d.ts.map b/dist/esm/instrumentation/analytics-engine.d.ts.map new file mode 100644 index 0000000..edb40e4 --- /dev/null +++ b/dist/esm/instrumentation/analytics-engine.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"analytics-engine.d.ts","sourceRoot":"","sources":["../../../src/instrumentation/analytics-engine.ts"],"names":[],"mappings":"AAkDA,wBAAgB,gCAAgC,CAC/C,OAAO,EAAE,sBAAsB,EAC/B,IAAI,EAAE,MAAM,GACV,sBAAsB,CASxB"} \ No newline at end of file diff --git a/dist/esm/instrumentation/analytics-engine.js b/dist/esm/instrumentation/analytics-engine.js new file mode 100644 index 0000000..ac065cc --- /dev/null +++ b/dist/esm/instrumentation/analytics-engine.js @@ -0,0 +1,55 @@ +import { SpanKind, trace } from '@opentelemetry/api'; +import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; +import { wrap } from '../wrap.js'; +const dbSystem = 'Cloudflare Analytics Engine'; +const AEAttributes = { + writeDataPoint(argArray) { + const attrs = {}; + const opts = argArray[0]; + if (typeof opts === 'object') { + attrs['db.cf.ae.indexes'] = opts.indexes.length; + attrs['db.cf.ae.index'] = opts.indexes[0].toString(); + attrs['db.cf.ae.doubles'] = opts.doubles.length; + attrs['db.cf.ae.blobs'] = opts.blobs.length; + } + return attrs; + }, +}; +function instrumentAEFn(fn, name, operation) { + const tracer = trace.getTracer('AnalyticsEngine'); + const fnHandler = { + apply: (target, thisArg, argArray) => { + const attributes = { + binding_type: 'AnalyticsEngine', + [SemanticAttributes.DB_NAME]: name, + [SemanticAttributes.DB_SYSTEM]: dbSystem, + [SemanticAttributes.DB_OPERATION]: operation, + }; + const options = { + kind: SpanKind.CLIENT, + attributes, + }; + return tracer.startActiveSpan(`Analytics Engine ${name} ${operation}`, options, async (span) => { + const result = await Reflect.apply(target, thisArg, argArray); + const extraAttrsFn = AEAttributes[operation]; + const extraAttrs = extraAttrsFn ? extraAttrsFn(argArray, result) : {}; + span.setAttributes(extraAttrs); + span.setAttribute(SemanticAttributes.DB_STATEMENT, `${operation} ${argArray[0]}`); + span.end(); + return result; + }); + }, + }; + return wrap(fn, fnHandler); +} +export function instrumentAnalyticsEngineDataset(dataset, name) { + const datasetHandler = { + get: (target, prop, receiver) => { + const operation = String(prop); + const fn = Reflect.get(target, prop, receiver); + return instrumentAEFn(fn, name, operation); + }, + }; + return wrap(dataset, datasetHandler); +} +//# sourceMappingURL=analytics-engine.js.map \ No newline at end of file diff --git a/dist/esm/instrumentation/analytics-engine.js.map b/dist/esm/instrumentation/analytics-engine.js.map new file mode 100644 index 0000000..7ea9a86 --- /dev/null +++ b/dist/esm/instrumentation/analytics-engine.js.map @@ -0,0 +1 @@ +{"version":3,"file":"analytics-engine.js","sourceRoot":"","sources":["../../../src/instrumentation/analytics-engine.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,QAAQ,EAAe,KAAK,EAAE,MAAM,oBAAoB,CAAA;AAC7E,OAAO,EAAE,kBAAkB,EAAE,MAAM,qCAAqC,CAAA;AACxE,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;AAIjC,MAAM,QAAQ,GAAG,6BAA6B,CAAA;AAE9C,MAAM,YAAY,GAA8C;IAC/D,cAAc,CAAC,QAAQ;QACtB,MAAM,KAAK,GAAe,EAAE,CAAA;QAC5B,MAAM,IAAI,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAA;QACxB,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC9B,KAAK,CAAC,kBAAkB,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAA;YAC/C,KAAK,CAAC,gBAAgB,CAAC,GAAI,IAAI,CAAC,OAAO,CAAC,CAAC,CAA0B,CAAC,QAAQ,EAAE,CAAA;YAC9E,KAAK,CAAC,kBAAkB,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAA;YAC/C,KAAK,CAAC,gBAAgB,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAA;QAC5C,CAAC;QACD,OAAO,KAAK,CAAA;IACb,CAAC;CACD,CAAA;AAED,SAAS,cAAc,CAAC,EAAY,EAAE,IAAY,EAAE,SAAiB;IACpE,MAAM,MAAM,GAAG,KAAK,CAAC,SAAS,CAAC,iBAAiB,CAAC,CAAA;IACjD,MAAM,SAAS,GAAsB;QACpC,KAAK,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE;YACpC,MAAM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A;YAC9B,MAAM,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAA;YAC9C,OAAO,cAAc,CAAC,EAAE,EAAE,IAAI,EAAE,SAAS,CAAC,CAAA;QAC3C,CAAC;KACD,CAAA;IACD,OAAO,IAAI,CAAC,OAAO,EAAE,cAAc,CAAC,CAAA;AACrC,CAAC"} \ No newline at end of file diff --git a/dist/esm/instrumentation/cache.d.ts b/dist/esm/instrumentation/cache.d.ts new file mode 100644 index 0000000..b75bf3c --- /dev/null +++ b/dist/esm/instrumentation/cache.d.ts @@ -0,0 +1,2 @@ +export declare function instrumentGlobalCache(): void; +//# sourceMappingURL=cache.d.ts.map \ No newline at end of file diff --git a/dist/esm/instrumentation/cache.d.ts.map b/dist/esm/instrumentation/cache.d.ts.map new file mode 100644 index 0000000..db3f9ce --- /dev/null +++ b/dist/esm/instrumentation/cache.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"cache.d.ts","sourceRoot":"","sources":["../../../src/instrumentation/cache.ts"],"names":[],"mappings":"AA6EA,wBAAgB,qBAAqB,SAEpC"} \ No newline at end of file diff --git a/dist/esm/instrumentation/cache.js b/dist/esm/instrumentation/cache.js new file mode 100644 index 0000000..248993d --- /dev/null +++ b/dist/esm/instrumentation/cache.js @@ -0,0 +1,75 @@ +import { SpanKind, trace } from '@opentelemetry/api'; +import { wrap } from '../wrap.js'; +const tracer = trace.getTracer('cache instrumentation'); +function sanitiseURL(url) { + const u = new URL(url); + return `${u.protocol}//${u.host}${u.pathname}${u.search}`; +} +function instrumentFunction(fn, cacheName, op) { + const handler = { + async apply(target, thisArg, argArray) { + const attributes = { + 'cache.name': cacheName, + 'http.url': argArray[0].url ? sanitiseURL(argArray[0].url) : undefined, + 'cache.operation': op, + }; + const options = { kind: SpanKind.CLIENT, attributes }; + return tracer.startActiveSpan(`Cache ${cacheName} ${op}`, options, async (span) => { + const result = await Reflect.apply(target, thisArg, argArray); + if (op === 'match') { + span.setAttribute('cache.hit', !!result); + } + span.end(); + return result; + }); + }, + }; + return wrap(fn, handler); +} +function instrumentCache(cache, cacheName) { + const handler = { + get(target, prop) { + if (prop === 'delete' || prop === 'match' || prop === 'put') { + const fn = Reflect.get(target, prop).bind(target); + return instrumentFunction(fn, cacheName, prop); + } + else { + return Reflect.get(target, prop); + } + }, + }; + return wrap(cache, handler); +} +function instrumentOpen(openFn) { + const handler = { + async apply(target, thisArg, argArray) { + const cacheName = argArray[0]; + const cache = await Reflect.apply(target, thisArg, argArray); + return instrumentCache(cache, cacheName); + }, + }; + return wrap(openFn, handler); +} +function _instrumentGlobalCache() { + const handler = { + get(target, prop) { + if (prop === 'default') { + const cache = target.default; + return instrumentCache(cache, 'default'); + } + else if (prop === 'open') { + const openFn = Reflect.get(target, prop).bind(target); + return instrumentOpen(openFn); + } + else { + return Reflect.get(target, prop); + } + }, + }; + //@ts-ignore + globalThis.caches = wrap(caches, handler); +} +export function instrumentGlobalCache() { + return _instrumentGlobalCache(); +} +//# sourceMappingURL=cache.js.map \ No newline at end of file diff --git a/dist/esm/instrumentation/cache.js.map b/dist/esm/instrumentation/cache.js.map new file mode 100644 index 0000000..bff7caf --- /dev/null +++ b/dist/esm/instrumentation/cache.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cache.js","sourceRoot":"","sources":["../../../src/instrumentation/cache.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAe,KAAK,EAAE,MAAM,oBAAoB,CAAA;AACjE,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;AAIjC,MAAM,MAAM,GAAG,KAAK,CAAC,SAAS,CAAC,uBAAuB,CAAC,CAAA;AAEvD,SAAS,WAAW,CAAC,GAAW;IAC/B,MAAM,CAAC,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAA;IACtB,OAAO,GAAG,CAAC,CAAC,QAAQ,KAAK,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,QAAQ,GAAG,C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;iBAAM,CAAC;gBACP,OAAO,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;YACjC,CAAC;QACF,CAAC;KACD,CAAA;IACD,YAAY;IACZ,UAAU,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;AAC1C,CAAC;AAED,MAAM,UAAU,qBAAqB;IACpC,OAAO,sBAAsB,EAAE,CAAA;AAChC,CAAC"} \ No newline at end of file diff --git a/dist/esm/instrumentation/common.d.ts b/dist/esm/instrumentation/common.d.ts new file mode 100644 index 0000000..3c59dd1 --- /dev/null +++ b/dist/esm/instrumentation/common.d.ts @@ -0,0 +1,21 @@ +type ContextAndTracker = { + ctx: ExecutionContext; + tracker: PromiseTracker; +}; +export declare class PromiseTracker { + _outstandingPromises: Promise[]; + get outstandingPromiseCount(): number; + track(promise: Promise): void; + wait(): Promise; +} +export declare function proxyExecutionContext(context: ExecutionContext): ContextAndTracker; +export declare function exportSpans(tracker?: PromiseTracker): Promise; +/** Overloads extracts up to 4 overloads for the given function. */ +export type Overloads = T extends { + (...args: infer P1): infer R1; + (...args: infer P2): infer R2; + (...args: infer P3): infer R3; + (...args: infer P4): infer R4; +} ? ((...args: P1) => R1) | ((...args: P2) => R2) | ((...args: P3) => R3) | ((...args: P4) => R4) : never; +export {}; +//# sourceMappingURL=common.d.ts.map \ No newline at end of file diff --git a/dist/esm/instrumentation/common.d.ts.map b/dist/esm/instrumentation/common.d.ts.map new file mode 100644 index 0000000..8d4837c --- /dev/null +++ b/dist/esm/instrumentation/common.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../../../src/instrumentation/common.ts"],"names":[],"mappings":"AAIA,KAAK,iBAAiB,GAAG;IAAE,GAAG,EAAE,gBAAgB,CAAC;IAAC,OAAO,EAAE,cAAc,CAAA;CAAE,CAAA;AAG3E,qBAAa,cAAc;IAC1B,oBAAoB,EAAE,OAAO,CAAC,OAAO,CAAC,EAAE,CAAK;IAE7C,IAAI,uBAAuB,WAE1B;IAED,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,IAAI;IAIhC,IAAI;CAGV;AAYD,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,gBAAgB,GAAG,iBAAiB,CAalF;AAED,wBAAsB,WAAW,CAAC,OAAO,CAAC,EAAE,cAAc,iBAczD;AAaD,mEAAmE;AACnE,MAAM,MAAM,SAAS,CAAC,CAAC,IAAI,CAAC,SAAS;IACpC,CAAC,GAAG,IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAAA;IAC7B,CAAC,GAAG,IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAAA;IAC7B,CAAC,GAAG,IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAAA;IAC7B,CAAC,GAAG,IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAAA;CAC7B,GACE,CAAC,CAAC,GAAG,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,GAC7F,KAAK,CAAA"} \ No newline at end of file diff --git a/dist/esm/instrumentation/common.js b/dist/esm/instrumentation/common.js new file mode 100644 index 0000000..6ddf68e --- /dev/null +++ b/dist/esm/instrumentation/common.js @@ -0,0 +1,66 @@ +import { trace } from '@opentelemetry/api'; +import { WorkerTracer } from '../tracer.js'; +import { passthroughGet, wrap } from '../wrap.js'; +export class PromiseTracker { + _outstandingPromises = []; + get outstandingPromiseCount() { + return this._outstandingPromises.length; + } + track(promise) { + this._outstandingPromises.push(promise); + } + async wait() { + await allSettledMutable(this._outstandingPromises); + } +} +function createWaitUntil(fn, context, tracker) { + const handler = { + apply(target, _thisArg, argArray) { + tracker.track(argArray[0]); + return Reflect.apply(target, context, argArray); + }, + }; + return wrap(fn, handler); +} +export function proxyExecutionContext(context) { + const tracker = new PromiseTracker(); + const ctx = new Proxy(context, { + get(target, prop) { + if (prop === 'waitUntil') { + const fn = Reflect.get(target, prop); + return createWaitUntil(fn, context, tracker); + } + else { + return passthroughGet(target, prop); + } + }, + }); + return { ctx, tracker }; +} +export async function exportSpans(tracker) { + const tracer = trace.getTracer('export'); + if (tracer instanceof WorkerTracer) { + await scheduler.wait(1); + if (tracker) { + await tracker.wait(); + } + const promises = tracer.spanProcessors.map(async (spanProcessor) => { + await spanProcessor.forceFlush(); + }); + await Promise.allSettled(promises); + } + else { + console.error('The global tracer is not of type WorkerTracer and can not export spans'); + } +} +/** Like `Promise.allSettled`, but handles modifications to the promises array */ +async function allSettledMutable(promises) { + let values; + // when the length of the array changes, there has been a nested call to waitUntil + // and we should await the promises again + do { + values = await Promise.allSettled(promises); + } while (values.length !== promises.length); + return values; +} +//# sourceMappingURL=common.js.map \ No newline at end of file diff --git a/dist/esm/instrumentation/common.js.map b/dist/esm/instrumentation/common.js.map new file mode 100644 index 0000000..b96296b --- /dev/null +++ b/dist/esm/instrumentation/common.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common.js","sourceRoot":"","sources":["../../../src/instrumentation/common.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAA;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAA;AAC3C,OAAO,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;AAKjD,MAAM,OAAO,cAAc;IAC1B,oBAAoB,GAAuB,EAAE,CAAA;IAE7C,IAAI,uBAAuB;QAC1B,OAAO,IAAI,CAAC,oBAAoB,CAAC,MAAM,CAAA;IACxC,CAAC;IAED,KAAK,CAAC,OAAyB;QAC9B,IAAI,CAAC,oBAAoB,CAAC,IAAI,CAAC,OAAO,CAAC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C,CAAC,CAAA;QACvB,IAAI,OAAO,EAAE,CAAC;YACb,MAAM,OAAO,CAAC,IAAI,EAAE,CAAA;QACrB,CAAC;QACD,MAAM,QAAQ,GAAG,MAAM,CAAC,cAAc,CAAC,GAAG,CAAC,KAAK,EAAE,aAAa,EAAE,EAAE;YAClE,MAAM,aAAa,CAAC,UAAU,EAAE,CAAA;QACjC,CAAC,CAAC,CAAA;QACF,MAAM,OAAO,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAA;IACnC,CAAC;SAAM,CAAC;QACP,OAAO,CAAC,KAAK,CAAC,wEAAwE,CAAC,CAAA;IACxF,CAAC;AACF,CAAC;AAED,iFAAiF;AACjF,KAAK,UAAU,iBAAiB,CAAC,QAA4B;IAC5D,IAAI,MAAuC,CAAA;IAC3C,kFAAkF;IAClF,yCAAyC;IACzC,GAAG,CAAC;QACH,MAAM,GAAG,MAAM,OAAO,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAA;IAC5C,CAAC,QAAQ,MAAM,CAAC,MAAM,KAAK,QAAQ,CAAC,MAAM,EAAC;IAC3C,OAAO,MAAM,CAAA;AACd,CAAC"} \ No newline at end of file diff --git a/dist/esm/instrumentation/do-storage.d.ts b/dist/esm/instrumentation/do-storage.d.ts new file mode 100644 index 0000000..2d9a8f3 --- /dev/null +++ b/dist/esm/instrumentation/do-storage.d.ts @@ -0,0 +1,2 @@ +export declare function instrumentStorage(storage: DurableObjectStorage): DurableObjectStorage; +//# sourceMappingURL=do-storage.d.ts.map \ No newline at end of file diff --git a/dist/esm/instrumentation/do-storage.d.ts.map b/dist/esm/instrumentation/do-storage.d.ts.map new file mode 100644 index 0000000..4df17b8 --- /dev/null +++ b/dist/esm/instrumentation/do-storage.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"do-storage.d.ts","sourceRoot":"","sources":["../../../src/instrumentation/do-storage.ts"],"names":[],"mappings":"AAgMA,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,oBAAoB,GAAG,oBAAoB,CASrF"} \ No newline at end of file diff --git a/dist/esm/instrumentation/do-storage.js b/dist/esm/instrumentation/do-storage.js new file mode 100644 index 0000000..77ded62 --- /dev/null +++ b/dist/esm/instrumentation/do-storage.js @@ -0,0 +1,195 @@ +import { SpanKind, trace } from '@opentelemetry/api'; +import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; +import { wrap } from '../wrap.js'; +const dbSystem = 'Cloudflare DO'; +function isDurableObjectCommonOptions(options) { + return (typeof options === 'object' && + ('allowConcurrency' in options || 'allowUnconfirmed' in options || 'noCache' in options)); +} +/** Applies attributes for common Durable Objects options: + * `allowConcurrency`, `allowUnconfirmed`, and `noCache` + */ +function applyOptionsAttributes(attrs, options) { + if ('allowConcurrency' in options) { + attrs['db.cf.do.allow_concurrency'] = options.allowConcurrency; + } + if ('allowUnconfirmed' in options) { + attrs['db.cf.do.allow_unconfirmed'] = options.allowUnconfirmed; + } + if ('noCache' in options) { + attrs['db.cf.do.no_cache'] = options.noCache; + } +} +const StorageAttributes = { + delete(argArray, result) { + const args = argArray; + let attrs = {}; + if (Array.isArray(args[0])) { + const keys = args[0]; + attrs = { + // todo: Maybe set db.cf.do.keys to the whole array here? + 'db.cf.do.key': keys[0], + 'db.cf.do.number_of_keys': keys.length, + 'db.cf.do.keys_deleted': result, + }; + } + else { + attrs = { + 'db.cf.do.key': args[0], + 'db.cf.do.success': result, + }; + } + if (args[1]) { + applyOptionsAttributes(attrs, args[1]); + } + return attrs; + }, + deleteAll(argArray) { + const args = argArray; + let attrs = {}; + if (args[0]) { + applyOptionsAttributes(attrs, args[0]); + } + return attrs; + }, + get(argArray) { + const args = argArray; + let attrs = {}; + if (Array.isArray(args[0])) { + const keys = args[0]; + attrs = { + // todo: Maybe set db.cf.do.keys to the whole array here? + 'db.cf.do.key': keys[0], + 'db.cf.do.number_of_keys': keys.length, + }; + } + else { + attrs = { + 'db.cf.do.key': args[0], + }; + } + if (args[1]) { + applyOptionsAttributes(attrs, args[1]); + } + return attrs; + }, + list(argArray, result) { + const args = argArray; + const attrs = { + 'db.cf.do.number_of_results': result.size, + }; + if (args[0]) { + const options = args[0]; + applyOptionsAttributes(attrs, options); + if ('start' in options) { + attrs['db.cf.do.start'] = options.start; + } + if ('startAfter' in options) { + attrs['db.cf.do.start_after'] = options.startAfter; + } + if ('end' in options) { + attrs['db.cf.do.end'] = options.end; + } + if ('prefix' in options) { + attrs['db.cf.do.prefix'] = options.prefix; + } + if ('reverse' in options) { + attrs['db.cf.do.reverse'] = options.reverse; + } + if ('limit' in options) { + attrs['db.cf.do.limit'] = options.limit; + } + } + return attrs; + }, + put(argArray) { + const args = argArray; + const attrs = {}; + if (typeof args[0] === 'string') { + attrs['db.cf.do.key'] = args[0]; + if (args[2]) { + applyOptionsAttributes(attrs, args[2]); + } + } + else { + const keys = Object.keys(args[0]); + // todo: Maybe set db.cf.do.keys to the whole array here? + attrs['db.cf.do.key'] = keys[0]; + attrs['db.cf.do.number_of_keys'] = keys.length; + if (isDurableObjectCommonOptions(args[1])) { + applyOptionsAttributes(attrs, args[1]); + } + } + return attrs; + }, + getAlarm(argArray) { + const args = argArray; + const attrs = {}; + if (args[0]) { + applyOptionsAttributes(attrs, args[0]); + } + return attrs; + }, + setAlarm(argArray) { + const args = argArray; + const attrs = {}; + if (args[0] instanceof Date) { + attrs['db.cf.do.alarm_time'] = args[0].getTime(); + } + else { + attrs['db.cf.do.alarm_time'] = args[0]; + } + if (args[1]) { + applyOptionsAttributes(attrs, args[1]); + } + return attrs; + }, + deleteAlarm(argArray) { + const args = argArray; + const attrs = {}; + if (args[0]) { + applyOptionsAttributes(attrs, args[0]); + } + return attrs; + }, +}; +function instrumentStorageFn(fn, operation) { + const tracer = trace.getTracer('do_storage'); + const fnHandler = { + apply: (target, thisArg, argArray) => { + const attributes = { + [SemanticAttributes.DB_SYSTEM]: dbSystem, + [SemanticAttributes.DB_OPERATION]: operation, + [SemanticAttributes.DB_STATEMENT]: `${operation} ${argArray[0]}`, + }; + const options = { + kind: SpanKind.CLIENT, + attributes: { + ...attributes, + operation, + }, + }; + return tracer.startActiveSpan(`Durable Object Storage ${operation}`, options, async (span) => { + const result = await Reflect.apply(target, thisArg, argArray); + const extraAttrsFn = StorageAttributes[operation]; + const extraAttrs = extraAttrsFn ? extraAttrsFn(argArray, result) : {}; + span.setAttributes(extraAttrs); + span.setAttribute('db.cf.do.has_result', !!result); + span.end(); + return result; + }); + }, + }; + return wrap(fn, fnHandler); +} +export function instrumentStorage(storage) { + const storageHandler = { + get: (target, prop, receiver) => { + const operation = String(prop); + const fn = Reflect.get(target, prop, receiver); + return instrumentStorageFn(fn, operation); + }, + }; + return wrap(storage, storageHandler); +} +//# sourceMappingURL=do-storage.js.map \ No newline at end of file diff --git a/dist/esm/instrumentation/do-storage.js.map b/dist/esm/instrumentation/do-storage.js.map new file mode 100644 index 0000000..b862832 --- /dev/null +++ b/dist/esm/instrumentation/do-storage.js.map @@ -0,0 +1 @@ +{"version":3,"file":"do-storage.js","sourceRoot":"","sources":["../../../src/instrumentation/do-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,QAAQ,EAAe,KAAK,EAAE,MAAM,oBAAoB,CAAA;AAC7E,OAAO,EAAE,kBAAkB,EAAE,MAAM,qCAAqC,CAAA;AACxE,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;AAKjC,MAAM,QAAQ,GAAG,eAAe,CAAA;AAGhC,SAAS,4BAA4B,CAAC,OAAY;IACjD,OAAO,CACN,OAAO,OAAO,KAAK,QAAQ;QAC3B,CAAC,kBAAkB,IAAI,OAAO,IAAI,kBAAkB,IAAI,OAAO,IAAI,SAAS,IAAI,OAAO,CAAC,CACxF,CAAA;AACF,CAAC;AAED;;GAEG;AACH,SAAS,sBAAsB,CAAC,KAAiB,EAAE,OAAmC;IACrF,IAAI,kBAAkB,IAAI,OAAO,EAAE,CAAC;QACnC,KAAK,CAAC,4BAA4B,CAAC,GAAG,OAAO,CAAC,gBAAgB,CAAA;IAC/D,CAAC;I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AS,GAAG,MAAM,CAAC,IAAI,CAAC,CAAA;YAC9B,MAAM,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAA;YAC9C,OAAO,mBAAmB,CAAC,EAAE,EAAE,SAAS,CAAC,CAAA;QAC1C,CAAC;KACD,CAAA;IACD,OAAO,IAAI,CAAC,OAAO,EAAE,cAAc,CAAC,CAAA;AACrC,CAAC"} \ No newline at end of file diff --git a/dist/esm/instrumentation/do.d.ts b/dist/esm/instrumentation/do.d.ts new file mode 100644 index 0000000..261ea52 --- /dev/null +++ b/dist/esm/instrumentation/do.d.ts @@ -0,0 +1,13 @@ +import { Initialiser } from '../config.js'; +type FetchFn = DurableObject['fetch']; +type AlarmFn = DurableObject['alarm']; +export declare function instrumentDOBinding(ns: DurableObjectNamespace, nsName: string): DurableObjectNamespace; +export declare function instrumentState(state: DurableObjectState): DurableObjectState; +export type DOClass = { + new (state: DurableObjectState, env: any): DurableObject; +}; +export declare function executeDOFetch(fetchFn: FetchFn, request: Request, id: DurableObjectId): Promise; +export declare function executeDOAlarm(alarmFn: NonNullable, id: DurableObjectId): Promise; +export declare function instrumentDOClass(doClass: DOClass, initialiser: Initialiser): DOClass; +export {}; +//# sourceMappingURL=do.d.ts.map \ No newline at end of file diff --git a/dist/esm/instrumentation/do.d.ts.map b/dist/esm/instrumentation/do.d.ts.map new file mode 100644 index 0000000..108dc6c --- /dev/null +++ b/dist/esm/instrumentation/do.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"do.d.ts","sourceRoot":"","sources":["../../../src/instrumentation/do.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,WAAW,EAAa,MAAM,cAAc,CAAA;AAKrD,KAAK,OAAO,GAAG,aAAa,CAAC,OAAO,CAAC,CAAA;AACrC,KAAK,OAAO,GAAG,aAAa,CAAC,OAAO,CAAC,CAAA;AAiCrC,wBAAgB,mBAAmB,CAAC,EAAE,EAAE,sBAAsB,EAAE,MAAM,EAAE,MAAM,qCAY7E;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,kBAAkB,sBAcxD;AAGD,MAAM,MAAM,OAAO,GAAG;IAAE,KAAK,KAAK,EAAE,kBAAkB,EAAE,GAAG,EAAE,GAAG,GAAG,aAAa,CAAA;CAAE,CAAA;AAClF,wBAAgB,cAAc,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,eAAe,GAAG,OAAO,CAAC,QAAQ,CAAC,CAmCzG;AAED,wBAAgB,cAAc,CAAC,OAAO,EAAE,WAAW,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAqBhG;AA8DD,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,WAAW,GAAG,OAAO,CAoBrF"} \ No newline at end of file diff --git a/dist/esm/instrumentation/do.js b/dist/esm/instrumentation/do.js new file mode 100644 index 0000000..417a860 --- /dev/null +++ b/dist/esm/instrumentation/do.js @@ -0,0 +1,209 @@ +import { context as api_context, trace, SpanKind, SpanStatusCode } from '@opentelemetry/api'; +import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; +import { passthroughGet, unwrap, wrap } from '../wrap.js'; +import { getParentContextFromHeaders, gatherIncomingCfAttributes, gatherRequestAttributes, gatherResponseAttributes, instrumentClientFetch, } from './fetch.js'; +import { instrumentEnv } from './env.js'; +import { setConfig } from '../config.js'; +import { exportSpans } from './common.js'; +import { instrumentStorage } from './do-storage.js'; +function instrumentBindingStub(stub, nsName) { + const stubHandler = { + get(target, prop) { + if (prop === 'fetch') { + const fetcher = Reflect.get(target, prop); + const attrs = { + name: `Durable Object ${nsName}`, + 'do.namespace': nsName, + 'do.id': target.id.toString(), + 'do.id.name': target.id.name, + }; + return instrumentClientFetch(fetcher, () => ({ includeTraceContext: true }), attrs); + } + else { + return passthroughGet(target, prop); + } + }, + }; + return wrap(stub, stubHandler); +} +function instrumentBindingGet(getFn, nsName) { + const getHandler = { + apply(target, thisArg, argArray) { + const stub = Reflect.apply(target, thisArg, argArray); + return instrumentBindingStub(stub, nsName); + }, + }; + return wrap(getFn, getHandler); +} +export function instrumentDOBinding(ns, nsName) { + const nsHandler = { + get(target, prop) { + if (prop === 'get') { + const fn = Reflect.get(ns, prop); + return instrumentBindingGet(fn, nsName); + } + else { + return passthroughGet(target, prop); + } + }, + }; + return wrap(ns, nsHandler); +} +export function instrumentState(state) { + const stateHandler = { + get(target, prop, receiver) { + const result = Reflect.get(target, prop, unwrap(receiver)); + if (prop === 'storage') { + return instrumentStorage(result); + } + else if (typeof result === 'function') { + return result.bind(target); + } + else { + return result; + } + }, + }; + return wrap(state, stateHandler); +} +let cold_start = true; +export function executeDOFetch(fetchFn, request, id) { + const spanContext = getParentContextFromHeaders(request.headers); + const tracer = trace.getTracer('DO fetchHandler'); + const attributes = { + [SemanticAttributes.FAAS_TRIGGER]: 'http', + [SemanticAttributes.FAAS_COLDSTART]: cold_start, + }; + cold_start = false; + Object.assign(attributes, gatherRequestAttributes(request)); + Object.assign(attributes, gatherIncomingCfAttributes(request)); + const options = { + attributes, + kind: SpanKind.SERVER, + }; + const name = id.name || ''; + const promise = tracer.startActiveSpan(`Durable Object Fetch ${name}`, options, spanContext, async (span) => { + try { + const response = await fetchFn(request); + if (response.ok) { + span.setStatus({ code: SpanStatusCode.OK }); + } + span.setAttributes(gatherResponseAttributes(response)); + span.end(); + return response; + } + catch (error) { + span.recordException(error); + span.setStatus({ code: SpanStatusCode.ERROR }); + span.end(); + throw error; + } + }); + return promise; +} +export function executeDOAlarm(alarmFn, id) { + const tracer = trace.getTracer('DO alarmHandler'); + const name = id.name || ''; + const promise = tracer.startActiveSpan(`Durable Object Alarm ${name}`, async (span) => { + span.setAttribute(SemanticAttributes.FAAS_COLDSTART, cold_start); + cold_start = false; + span.setAttribute('do.id', id.toString()); + if (id.name) + span.setAttribute('do.name', id.name); + try { + await alarmFn(); + span.end(); + } + catch (error) { + span.recordException(error); + span.setStatus({ code: SpanStatusCode.ERROR }); + span.end(); + throw error; + } + }); + return promise; +} +function instrumentFetchFn(fetchFn, initialiser, env, id) { + const fetchHandler = { + async apply(target, thisArg, argArray) { + const request = argArray[0]; + const config = initialiser(env, request); + const context = setConfig(config); + try { + const bound = target.bind(unwrap(thisArg)); + return await api_context.with(context, executeDOFetch, undefined, bound, request, id); + } + catch (error) { + throw error; + } + finally { + exportSpans(); + } + }, + }; + return wrap(fetchFn, fetchHandler); +} +function instrumentAlarmFn(alarmFn, initialiser, env, id) { + if (!alarmFn) + return undefined; + const alarmHandler = { + async apply(target, thisArg) { + const config = initialiser(env, 'do-alarm'); + const context = setConfig(config); + try { + const bound = target.bind(unwrap(thisArg)); + return await api_context.with(context, executeDOAlarm, undefined, bound, id); + } + catch (error) { + throw error; + } + finally { + exportSpans(); + } + }, + }; + return wrap(alarmFn, alarmHandler); +} +function instrumentDurableObject(doObj, initialiser, env, state) { + const objHandler = { + get(target, prop) { + if (prop === 'fetch') { + const fetchFn = Reflect.get(target, prop); + return instrumentFetchFn(fetchFn, initialiser, env, state.id); + } + else if (prop === 'alarm') { + const alarmFn = Reflect.get(target, prop); + return instrumentAlarmFn(alarmFn, initialiser, env, state.id); + } + else { + const result = Reflect.get(target, prop); + if (typeof result === 'function') { + result.bind(doObj); + } + return result; + } + }, + }; + return wrap(doObj, objHandler); +} +export function instrumentDOClass(doClass, initialiser) { + const classHandler = { + construct(target, [orig_state, orig_env]) { + const trigger = { + id: orig_state.id.toString(), + name: orig_state.id.name, + }; + const constructorConfig = initialiser(orig_env, trigger); + const context = setConfig(constructorConfig); + const state = instrumentState(orig_state); + const env = instrumentEnv(orig_env); + const createDO = () => { + return new target(state, env); + }; + const doObj = api_context.with(context, createDO); + return instrumentDurableObject(doObj, initialiser, env, state); + }, + }; + return wrap(doClass, classHandler); +} +//# sourceMappingURL=do.js.map \ No newline at end of file diff --git a/dist/esm/instrumentation/do.js.map b/dist/esm/instrumentation/do.js.map new file mode 100644 index 0000000..1c0ce1d --- /dev/null +++ b/dist/esm/instrumentation/do.js.map @@ -0,0 +1 @@ +{"version":3,"file":"do.js","sourceRoot":"","sources":["../../../src/instrumentation/do.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,KAAK,EAAe,QAAQ,EAAa,cAAc,EAAE,MAAM,oBAAoB,CAAA;AACpH,OAAO,EAAE,kBAAkB,EAAE,MAAM,qCAAqC,CAAA;AACxE,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;AACzD,OAAO,EACN,2BAA2B,EAC3B,0BAA0B,EAC1B,uBAAuB,EACvB,wBAAwB,EACxB,qBAAqB,GACrB,MAAM,YAAY,CAAA;AACnB,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AACxC,OAAO,EAAe,SAAS,EAAE,MAAM,cAAc,CAAA;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAA;AAOnD,SAAS,qBAAqB,CAAC,IAAuB,EAAE,MAAc;IACrE,MAAM,WAAW,GAA8B;QAC9C,GAAG,CAAC,MAAM,EAAE,IAAI;YACf,IAAI,IAAI,KAAK,OAAO,EAAE,CAAC;gBACtB,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;gBACzC,MAAM,KAAK,GAAG;oBACb,IAAI,EAAE,kBAAkB,MAAM,EAAE;oBAChC,cAAc,EAAE,MAAM;oBACtB,OAAO,EAAE,MAAM,CAAC,EAAE,CAAC,QAAQ,EAAE;oBAC7B,YAAY,EAAE,MAAM,CAAC,EAAE,CAAC,IAAI;iBAC5B,CAAA;gBACD,OAAO,qBAAqB,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,mBAAmB,EAAE,IAAI,EAAE,CA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AACnC,CAAC"} \ No newline at end of file diff --git a/dist/esm/instrumentation/env.d.ts b/dist/esm/instrumentation/env.d.ts new file mode 100644 index 0000000..2b996f3 --- /dev/null +++ b/dist/esm/instrumentation/env.d.ts @@ -0,0 +1,4 @@ +export declare const isVersionMetadata: (item?: unknown) => item is WorkerVersionMetadata; +declare const instrumentEnv: (env: Record) => Record; +export { instrumentEnv }; +//# sourceMappingURL=env.d.ts.map \ No newline at end of file diff --git a/dist/esm/instrumentation/env.d.ts.map b/dist/esm/instrumentation/env.d.ts.map new file mode 100644 index 0000000..7f7981b --- /dev/null +++ b/dist/esm/instrumentation/env.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"env.d.ts","sourceRoot":"","sources":["../../../src/instrumentation/env.ts"],"names":[],"mappings":"AAwBA,eAAO,MAAM,iBAAiB,UAAW,OAAO,KAAG,IAAI,IAAI,qBAM1D,CAAA;AAMD,QAAA,MAAM,aAAa,QAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CA0B3E,CAAA;AAED,OAAO,EAAE,aAAa,EAAE,CAAA"} \ No newline at end of file diff --git a/dist/esm/instrumentation/env.js b/dist/esm/instrumentation/env.js new file mode 100644 index 0000000..e7bff0a --- /dev/null +++ b/dist/esm/instrumentation/env.js @@ -0,0 +1,62 @@ +import { isProxyable, wrap } from '../wrap.js'; +import { instrumentDOBinding } from './do.js'; +import { instrumentKV } from './kv.js'; +import { instrumentQueueSender } from './queue.js'; +import { instrumentServiceBinding } from './service.js'; +import { instrumentAnalyticsEngineDataset } from './analytics-engine.js'; +const isJSRPC = (item) => { + // @ts-expect-error The point of RPC types is to block non-existent properties, but that's the goal here + return !!item?.['__some_property_that_will_never_exist' + Math.random()]; +}; +const isKVNamespace = (item) => { + return !isJSRPC(item) && !!item?.getWithMetadata; +}; +const isQueue = (item) => { + return !isJSRPC(item) && !!item?.sendBatch; +}; +const isDurableObject = (item) => { + return !isJSRPC(item) && !!item?.idFromName; +}; +export const isVersionMetadata = (item) => { + return (!isJSRPC(item) && + typeof item?.id === 'string' && + typeof item?.tag === 'string'); +}; +const isAnalyticsEngineDataset = (item) => { + return !isJSRPC(item) && !!item?.writeDataPoint; +}; +const instrumentEnv = (env) => { + const envHandler = { + get: (target, prop, receiver) => { + const item = Reflect.get(target, prop, receiver); + if (!isProxyable(item)) { + return item; + } + if (isJSRPC(item)) { + return instrumentServiceBinding(item, String(prop)); + } + else if (isKVNamespace(item)) { + return instrumentKV(item, String(prop)); + } + else if (isQueue(item)) { + return instrumentQueueSender(item, String(prop)); + } + else if (isDurableObject(item)) { + return instrumentDOBinding(item, String(prop)); + } + else if (isVersionMetadata(item)) { + // we do not need to log accesses to the metadata + return item; + } + else if (isAnalyticsEngineDataset(item)) { + return instrumentAnalyticsEngineDataset(item, String(prop)); + } + else { + return item; + } + }, + }; + return wrap(env, envHandler); +}; +export { instrumentEnv }; +//# sourceMappingURL=env.js.map \ No newline at end of file diff --git a/dist/esm/instrumentation/env.js.map b/dist/esm/instrumentation/env.js.map new file mode 100644 index 0000000..8451674 --- /dev/null +++ b/dist/esm/instrumentation/env.js.map @@ -0,0 +1 @@ +{"version":3,"file":"env.js","sourceRoot":"","sources":["../../../src/instrumentation/env.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;AAC9C,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAA;AAC7C,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AACtC,OAAO,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAA;AAClD,OAAO,EAAE,wBAAwB,EAAE,MAAM,cAAc,CAAA;AACvD,OAAO,EAAE,gCAAgC,EAAE,MAAM,uBAAuB,CAAA;AAExE,MAAM,OAAO,GAAG,CAAC,IAAc,EAAmB,EAAE;IACnD,wGAAwG;IACxG,OAAO,CAAC,CAAE,IAAgB,EAAE,CAAC,uCAAuC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YACD,IAAI,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;gBACnB,OAAO,wBAAwB,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAA;YACpD,CAAC;iBAAM,IAAI,aAAa,CAAC,IAAI,CAAC,EAAE,CAAC;gBAChC,OAAO,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAA;YACxC,CAAC;iBAAM,IAAI,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;gBAC1B,OAAO,qBAAqB,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAA;YACjD,CAAC;iBAAM,IAAI,eAAe,CAAC,IAAI,CAAC,EAAE,CAAC;gBAClC,OAAO,mBAAmB,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAA;YAC/C,CAAC;iBAAM,IAAI,iBAAiB,CAAC,IAAI,CAAC,EAAE,CAAC;gBACpC,iDAAiD;gBACjD,OAAO,IAAI,CAAA;YACZ,CAAC;iBAAM,IAAI,wBAAwB,CAAC,IAAI,CAAC,EAAE,CAAC;gBAC3C,OAAO,gCAAgC,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAA;YAC5D,CAAC;iBAAM,CAAC;gBACP,OAAO,IAAI,CAAA;YACZ,CAAC;QACF,CAAC;KACD,CAAA;IACD,OAAO,IAAI,CAAC,GAAG,EAAE,UAAU,CAAC,CAAA;AAC7B,CAAC,CAAA;AAED,OAAO,EAAE,aAAa,EAAE,CAAA"} \ No newline at end of file diff --git a/dist/esm/instrumentation/fetch.d.ts b/dist/esm/instrumentation/fetch.d.ts new file mode 100644 index 0000000..081bd67 --- /dev/null +++ b/dist/esm/instrumentation/fetch.d.ts @@ -0,0 +1,30 @@ +import { Attributes, Context } from '@opentelemetry/api'; +import { Initialiser } from '../config.js'; +import { ResolvedTraceConfig } from '../types.js'; +export type IncludeTraceContextFn = (request: Request) => boolean; +export interface FetcherConfig { + includeTraceContext?: boolean | IncludeTraceContextFn; +} +export type AcceptTraceContextFn = (request: Request) => boolean; +export interface FetchHandlerConfig { + /** + * Whether to enable context propagation for incoming requests to `fetch`. + * This enables or disables distributed tracing from W3C Trace Context headers. + * @default true + */ + acceptTraceContext?: boolean | AcceptTraceContextFn; +} +type FetchHandler = ExportedHandlerFetchHandler; +type FetchHandlerArgs = Parameters; +export declare function gatherRequestAttributes(request: Request): Attributes; +export declare function gatherResponseAttributes(response: Response): Attributes; +export declare function gatherIncomingCfAttributes(request: Request): Attributes; +export declare function getParentContextFromHeaders(headers: Headers): Context; +export declare function waitUntilTrace(fn: () => Promise): Promise; +export declare function executeFetchHandler(fetchFn: FetchHandler, [request, env, ctx]: FetchHandlerArgs): Promise; +export declare function createFetchHandler(fetchFn: FetchHandler, initialiser: Initialiser): FetchHandler; +type getFetchConfig = (config: ResolvedTraceConfig) => FetcherConfig; +export declare function instrumentClientFetch(fetchFn: Fetcher['fetch'], configFn: getFetchConfig, attrs?: Attributes): Fetcher['fetch']; +export declare function instrumentGlobalFetch(): void; +export {}; +//# sourceMappingURL=fetch.d.ts.map \ No newline at end of file diff --git a/dist/esm/instrumentation/fetch.d.ts.map b/dist/esm/instrumentation/fetch.d.ts.map new file mode 100644 index 0000000..be4050b --- /dev/null +++ b/dist/esm/instrumentation/fetch.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../../src/instrumentation/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAMN,UAAU,EAEV,OAAO,EAEP,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EAAE,WAAW,EAA8B,MAAM,cAAc,CAAA;AAItE,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAA;AAIjD,MAAM,MAAM,qBAAqB,GAAG,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAA;AACjE,MAAM,WAAW,aAAa;IAC7B,mBAAmB,CAAC,EAAE,OAA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 100644 index 0000000..5784074 --- /dev/null +++ b/dist/esm/instrumentation/fetch.js @@ -0,0 +1,196 @@ +import { trace, SpanKind, propagation, context as api_context, SpanStatusCode, } from '@opentelemetry/api'; +import { getActiveConfig, setConfig } from '../config.js'; +import { wrap } from '../wrap.js'; +import { instrumentEnv } from './env.js'; +import { exportSpans, proxyExecutionContext } from './common.js'; +import { versionAttributes } from './version.js'; +const netKeysFromCF = new Set(['colo', 'country', 'request_priority', 'tls_cipher', 'tls_version', 'asn', 'tcp_rtt']); +const camelToSnakeCase = (s) => { + return s.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`); +}; +const gatherOutgoingCfAttributes = (cf) => { + const attrs = {}; + Object.keys(cf).forEach((key) => { + const value = cf[key]; + const destKey = camelToSnakeCase(key); + if (!netKeysFromCF.has(destKey)) { + if (typeof value === 'string' || typeof value === 'number') { + attrs[`cf.${destKey}`] = value; + } + else { + attrs[`cf.${destKey}`] = JSON.stringify(value); + } + } + }); + return attrs; +}; +export function gatherRequestAttributes(request) { + const attrs = {}; + const headers = request.headers; + attrs['http.request.method'] = request.method.toUpperCase(); + attrs['network.protocol.name'] = 'http'; + attrs['network.protocol.version'] = request.cf?.httpProtocol; + attrs['http.request.body.size'] = headers.get('content-length'); + attrs['user_agent.original'] = headers.get('user-agent'); + attrs['http.mime_type'] = headers.get('content-type'); + attrs['http.accepts'] = request.cf?.clientAcceptEncoding; + const u = new URL(request.url); + attrs['url.full'] = `${u.protocol}//${u.host}${u.pathname}${u.search}`; + attrs['server.address'] = u.host; + attrs['url.scheme'] = u.protocol; + attrs['url.path'] = u.pathname; + attrs['url.query'] = u.search; + return attrs; +} +export function gatherResponseAttributes(response) { + const attrs = {}; + attrs['http.response.status_code'] = response.status; + if (response.headers.get('content-length') == null) { + attrs['http.response.body.size'] = response.headers.get('content-length'); + } + attrs['http.mime_type'] = response.headers.get('content-type'); + return attrs; +} +export function gatherIncomingCfAttributes(request) { + const attrs = {}; + attrs['net.colo'] = request.cf?.colo; + attrs['net.country'] = request.cf?.country; + attrs['net.request_priority'] = request.cf?.requestPriority; + attrs['net.tls_cipher'] = request.cf?.tlsCipher; + attrs['net.tls_version'] = request.cf?.tlsVersion; + attrs['net.asn'] = request.cf?.asn; + attrs['net.tcp_rtt'] = request.cf?.clientTcpRtt; + return attrs; +} +export function getParentContextFromHeaders(headers) { + return propagation.extract(api_context.active(), headers, { + get(headers, key) { + return headers.get(key) || undefined; + }, + keys(headers) { + return [...headers.keys()]; + }, + }); +} +function getParentContextFromRequest(request) { + const workerConfig = getActiveConfig(); + if (workerConfig === undefined) { + return api_context.active(); + } + const acceptTraceContext = typeof workerConfig.handlers.fetch.acceptTraceContext === 'function' + ? workerConfig.handlers.fetch.acceptTraceContext(request) + : (workerConfig.handlers.fetch.acceptTraceContext ?? true); + return acceptTraceContext ? getParentContextFromHeaders(request.headers) : api_context.active(); +} +export function waitUntilTrace(fn) { + const tracer = trace.getTracer('waitUntil'); + return tracer.startActiveSpan('waitUntil', async (span) => { + await fn(); + span.end(); + }); +} +let cold_start = true; +export function executeFetchHandler(fetchFn, [request, env, ctx]) { + const spanContext = getParentContextFromRequest(request); + const tracer = trace.getTracer('fetchHandler'); + const attributes = { + ['faas.trigger']: 'http', + ['faas.coldstart']: cold_start, + ['faas.invocation_id']: request.headers.get('cf-ray') ?? undefined, + }; + cold_start = false; + Object.assign(attributes, gatherRequestAttributes(request)); + Object.assign(attributes, gatherIncomingCfAttributes(request)); + Object.assign(attributes, versionAttributes(env)); + const options = { + attributes, + kind: SpanKind.SERVER, + }; + const method = request.method.toUpperCase(); + const promise = tracer.startActiveSpan(`fetchHandler ${method}`, options, spanContext, async (span) => { + const readable = span; + try { + const response = await fetchFn(request, env, ctx); + span.setAttributes(gatherResponseAttributes(response)); + return response; + } + catch (error) { + span.recordException(error); + span.setStatus({ code: SpanStatusCode.ERROR }); + throw error; + } + finally { + if (readable.attributes['http.route']) { + span.updateName(`fetchHandler ${method} ${readable.attributes['http.route']}`); + } + span.end(); + } + }); + return promise; +} +export function createFetchHandler(fetchFn, initialiser) { + const fetchHandler = { + apply: async (target, _thisArg, argArray) => { + const [request, orig_env, orig_ctx] = argArray; + const config = initialiser(orig_env, request); + const env = instrumentEnv(orig_env); + const { ctx, tracker } = proxyExecutionContext(orig_ctx); + const context = setConfig(config); + try { + const args = [request, env, ctx]; + return await api_context.with(context, executeFetchHandler, undefined, target, args); + } + catch (error) { + throw error; + } + finally { + orig_ctx.waitUntil(exportSpans(tracker)); + } + }, + }; + return wrap(fetchFn, fetchHandler); +} +export function instrumentClientFetch(fetchFn, configFn, attrs) { + const handler = { + apply: (target, thisArg, argArray) => { + const request = new Request(argArray[0], argArray[1]); + if (!request.url.startsWith('http')) { + return Reflect.apply(target, thisArg, argArray); + } + const workerConfig = getActiveConfig(); + if (!workerConfig) { + return Reflect.apply(target, thisArg, [request]); + } + const config = configFn(workerConfig); + const tracer = trace.getTracer('fetcher'); + const options = { kind: SpanKind.CLIENT, attributes: attrs }; + const host = new URL(request.url).host; + const method = request.method.toUpperCase(); + const spanName = typeof attrs?.['name'] === 'string' ? attrs?.['name'] : `fetch ${method} ${host}`; + const promise = tracer.startActiveSpan(spanName, options, async (span) => { + const includeTraceContext = typeof config.includeTraceContext === 'function' + ? config.includeTraceContext(request) + : config.includeTraceContext; + if (includeTraceContext ?? true) { + propagation.inject(api_context.active(), request.headers, { + set: (h, k, v) => h.set(k, typeof v === 'string' ? v : String(v)), + }); + } + span.setAttributes(gatherRequestAttributes(request)); + if (request.cf) + span.setAttributes(gatherOutgoingCfAttributes(request.cf)); + const response = await Reflect.apply(target, thisArg, [request]); + span.setAttributes(gatherResponseAttributes(response)); + span.end(); + return response; + }); + return promise; + }, + }; + return wrap(fetchFn, handler, true); +} +export function instrumentGlobalFetch() { + //@ts-ignore For some reason the node types are imported and complain. + globalThis.fetch = instrumentClientFetch(globalThis.fetch, (config) => config.fetch); +} +//# sourceMappingURL=fetch.js.map \ No newline at end of file diff --git a/dist/esm/instrumentation/fetch.js.map b/dist/esm/instrumentation/fetch.js.map new file mode 100644 index 0000000..65f190a --- /dev/null +++ b/dist/esm/instrumentation/fetch.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../../src/instrumentation/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,EAEL,QAAQ,EACR,WAAW,EACX,OAAO,IAAI,WAAW,EAItB,cAAc,GACd,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EAAe,eAAe,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA;AACtE,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;AACjC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AACxC,OAAO,EAAE,WAAW,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAA;AAGhE,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAA;AAoBhD,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,SAAS,EAAE,kBAAkB,EAAE,YAAY,EAAE,aAAa,EAAE,KAAK,EAAE,SAAS,CAAC,CAAC,CAAA;AAErH,MAAM,gBAAgB,GAAG,CAAC,CAAS,EAAU,EAAE;IAC9C,OAAO,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,IAAI,MAAM,CAAC,WAAW,EAAE,EAAE,CAAC,CAAA;AACnE,CAAC,CAAA;AAED,MAAM,0BAA0B,GAAG,CAAC,EAA2B,EAAc,EAAE;IAC9E,MAAM,KAAK,GAAoC,EAAE,CAAA;IACjD,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;QAC/B,MAAM,KAAK,GAAG,EAAE,CAAC,GAAG,CAAC,CAAA;QACrB,MAAM,OAAO,GAAG,gBAAgB,CAAC,GAAG,CAAC,CAAA;QACrC,IAAI,CAAC,aAAa,CAAC,GAAG,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AO,EAAE,CAAC,OAAO,CAAC,CAAC,CAAA;gBAChE,IAAI,CAAC,aAAa,CAAC,wBAAwB,CAAC,QAAQ,CAAC,CAAC,CAAA;gBACtD,IAAI,CAAC,GAAG,EAAE,CAAA;gBACV,OAAO,QAAQ,CAAA;YAChB,CAAC,CAAC,CAAA;YACF,OAAO,OAAO,CAAA;QACf,CAAC;KACD,CAAA;IACD,OAAO,IAAI,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,CAAA;AACpC,CAAC;AAED,MAAM,UAAU,qBAAqB;IACpC,sEAAsE;IACtE,UAAU,CAAC,KAAK,GAAG,qBAAqB,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;AACrF,CAAC"} \ No newline at end of file diff --git a/dist/esm/instrumentation/kv.d.ts b/dist/esm/instrumentation/kv.d.ts new file mode 100644 index 0000000..b1c5b66 --- /dev/null +++ b/dist/esm/instrumentation/kv.d.ts @@ -0,0 +1,2 @@ +export declare function instrumentKV(kv: KVNamespace, name: string): KVNamespace; +//# sourceMappingURL=kv.d.ts.map \ No newline at end of file diff --git a/dist/esm/instrumentation/kv.d.ts.map b/dist/esm/instrumentation/kv.d.ts.map new file mode 100644 index 0000000..8497c7c --- /dev/null +++ b/dist/esm/instrumentation/kv.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"kv.d.ts","sourceRoot":"","sources":["../../../src/instrumentation/kv.ts"],"names":[],"mappings":"AA6GA,wBAAgB,YAAY,CAAC,EAAE,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,GAAG,WAAW,CASvE"} \ No newline at end of file diff --git a/dist/esm/instrumentation/kv.js b/dist/esm/instrumentation/kv.js new file mode 100644 index 0000000..64a6cc1 --- /dev/null +++ b/dist/esm/instrumentation/kv.js @@ -0,0 +1,117 @@ +import { SpanKind, trace } from '@opentelemetry/api'; +import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; +import { wrap } from '../wrap.js'; +const dbSystem = 'Cloudflare KV'; +const KVAttributes = { + delete(_argArray) { + return {}; + }, + get(argArray) { + const attrs = {}; + const opts = argArray[1]; + if (typeof opts === 'string') { + attrs['db.cf.kv.type'] = opts; + } + else if (typeof opts === 'object') { + attrs['db.cf.kv.type'] = opts.type; + attrs['db.cf.kv.cache_ttl'] = opts.cacheTtl; + } + return attrs; + }, + getWithMetadata(argArray, result) { + const attrs = {}; + const opts = argArray[1]; + if (typeof opts === 'string') { + attrs['db.cf.kv.type'] = opts; + } + else if (typeof opts === 'object') { + attrs['db.cf.kv.type'] = opts.type; + attrs['db.cf.kv.cache_ttl'] = opts.cacheTtl; + } + attrs['db.cf.kv.metadata'] = true; + const { cacheStatus } = result; + if (typeof cacheStatus === 'string') { + attrs['db.cf.kv.cache_status'] = cacheStatus; + } + return attrs; + }, + list(argArray, result) { + const attrs = {}; + const opts = argArray[0] || {}; + const { cursor, limit } = opts; + attrs['db.cf.kv.list_request_cursor'] = cursor || undefined; + attrs['db.cf.kv.list_limit'] = limit || undefined; + const { list_complete, cacheStatus } = result; + attrs['db.cf.kv.list_complete'] = list_complete || undefined; + if (!list_complete) { + attrs['db.cf.kv.list_response_cursor'] = cursor || undefined; + } + if (typeof cacheStatus === 'string') { + attrs['db.cf.kv.cache_status'] = cacheStatus; + } + return attrs; + }, + put(argArray) { + const attrs = {}; + if (argArray.length > 2 && argArray[2]) { + const { expiration, expirationTtl, metadata } = argArray[2]; + attrs['db.cf.kv.expiration'] = expiration; + attrs['db.cf.kv.expiration_ttl'] = expirationTtl; + attrs['db.cf.kv.metadata'] = !!metadata; + } + return attrs; + }, +}; +function instrumentKVFn(fn, name, operation) { + const tracer = trace.getTracer('KV'); + const fnHandler = { + apply: (target, thisArg, argArray) => { + const attributes = { + binding_type: 'KV', + [SemanticAttributes.DB_NAME]: name, + [SemanticAttributes.DB_SYSTEM]: dbSystem, + [SemanticAttributes.DB_OPERATION]: operation, + }; + const options = { + kind: SpanKind.CLIENT, + attributes, + }; + return tracer.startActiveSpan(`KV ${name} ${operation}`, options, async (span) => { + const result = await Reflect.apply(target, thisArg, argArray); + const extraAttrsFn = KVAttributes[operation]; + const extraAttrs = extraAttrsFn ? extraAttrsFn(argArray, result) : {}; + span.setAttributes(extraAttrs); + if (operation === 'list') { + const opts = argArray[0] || {}; + const { prefix } = opts; + span.setAttribute(SemanticAttributes.DB_STATEMENT, `${operation} ${prefix || undefined}`); + } + else { + span.setAttribute(SemanticAttributes.DB_STATEMENT, `${operation} ${argArray[0]}`); + span.setAttribute('db.cf.kv.key', argArray[0]); + } + if (operation === 'getWithMetadata') { + const hasResults = !!result && !!result.value; + span.setAttribute('db.cf.kv.has_result', hasResults); + } + else { + span.setAttribute('db.cf.kv.has_result', !!result); + } + span.end(); + return result; + }); + }, + }; + return wrap(fn, fnHandler); +} +export function instrumentKV(kv, name) { + const kvHandler = { + get: (target, prop, receiver) => { + const operation = String(prop); + const fn = Reflect.get(target, prop, receiver); + return instrumentKVFn(fn, name, operation); + }, + }; + return wrap(kv, kvHandler); +} +//# sourceMappingURL=kv.js.map \ No newline at end of file diff --git a/dist/esm/instrumentation/kv.js.map b/dist/esm/instrumentation/kv.js.map new file mode 100644 index 0000000..e79c7cc --- /dev/null +++ b/dist/esm/instrumentation/kv.js.map @@ -0,0 +1 @@ +{"version":3,"file":"kv.js","sourceRoot":"","sources":["../../../src/instrumentation/kv.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,QAAQ,EAAe,KAAK,EAAE,MAAM,oBAAoB,CAAA;AAC7E,OAAO,EAAE,kBAAkB,EAAE,MAAM,qCAAqC,CAAA;AACxE,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;AAIjC,MAAM,QAAQ,GAAG,eAAe,CAAA;AAEhC,MAAM,YAAY,GAA8C;IAC/D,MAAM,CAAC,SAAS;QACf,OAAO,EAAE,CAAA;IACV,CAAC;IACD,GAAG,CAAC,QAAQ;QACX,MAAM,KAAK,GAAe,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CAAC,CAAA;gBAC/C,CAAC;gBACD,IAAI,SAAS,KAAK,iBAAiB,EAAE,CAAC;oBACrC,MAAM,UAAU,GAAG,CAAC,CAAC,MAAM,IAAI,CAAC,CAAE,MAA4D,CAAC,KAAK,CAAA;oBACpG,IAAI,CAAC,YAAY,CAAC,qBAAqB,EAAE,UAAU,CAAC,CAAA;gBACrD,CAAC;qBAAM,CAAC;oBACP,IAAI,CAAC,YAAY,CAAC,qBAAqB,EAAE,CAAC,CAAC,MAAM,CAAC,CAAA;gBACnD,CAAC;gBACD,IAAI,CAAC,GAAG,EAAE,CAAA;gBACV,OAAO,MAAM,CAAA;YACd,CAAC,CAAC,CAAA;QACH,CAAC;KACD,CAAA;IACD,OAAO,IAAI,CAAC,EAAE,EAAE,SAAS,CAAC,CAAA;AAC3B,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,EAAe,EAAE,IAAY;IACzD,MAAM,SAAS,GAA8B;QAC5C,GAAG,EAAE,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE;YAC/B,MAAM,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,CAAA;YAC9B,MAAM,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAA;YAC9C,OAAO,cAAc,CAAC,EAAE,EAAE,IAAI,EAAE,SAAS,CAAC,CAAA;QAC3C,CAAC;KACD,CAAA;IACD,OAAO,IAAI,CAAC,EAAE,EAAE,SAAS,CAAC,CAAA;AAC3B,CAAC"} \ No newline at end of file diff --git a/dist/esm/instrumentation/queue.d.ts b/dist/esm/instrumentation/queue.d.ts new file mode 100644 index 0000000..306299e --- /dev/null +++ b/dist/esm/instrumentation/queue.d.ts @@ -0,0 +1,8 @@ +import { Initialiser } from '../config.js'; +type QueueHandler = ExportedHandlerQueueHandler; +export type QueueHandlerArgs = Parameters; +export declare function executeQueueHandler(queueFn: QueueHandler, [batch, env, ctx]: QueueHandlerArgs): Promise; +export declare function createQueueHandler(queueFn: QueueHandler, initialiser: Initialiser): QueueHandler; +export declare function instrumentQueueSender(queue: Queue, name: string): Queue; +export {}; +//# sourceMappingURL=queue.d.ts.map \ No newline at end of file diff --git a/dist/esm/instrumentation/queue.d.ts.map b/dist/esm/instrumentation/queue.d.ts.map new file mode 100644 index 0000000..314f338 --- /dev/null +++ b/dist/esm/instrumentation/queue.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"queue.d.ts","sourceRoot":"","sources":["../../../src/instrumentation/queue.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAa,MAAM,cAAc,CAAA;AAMrD,KAAK,YAAY,GAAG,2BAA2B,CAAC,OAAO,EAAE,OAAO,CAAC,CAAA;AACjE,MAAM,MAAM,gBAAgB,GAAG,UAAU,CAAC,YAAY,CAAC,CAAA;AA4HvD,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,YAAY,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,CAAC,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CA+B7G;AAED,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,WAAW,gBAqBjF;AA8BD,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,MAAM,kBAexE"} \ No newline at end of file diff --git a/dist/esm/instrumentation/queue.js b/dist/esm/instrumentation/queue.js new file mode 100644 index 0000000..c390f86 --- /dev/null +++ b/dist/esm/instrumentation/queue.js @@ -0,0 +1,222 @@ +import { trace, SpanKind, context as api_context } from '@opentelemetry/api'; +import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; +import { setConfig } from '../config.js'; +import { exportSpans, proxyExecutionContext } from './common.js'; +import { instrumentEnv } from './env.js'; +import { unwrap, wrap } from '../wrap.js'; +import { versionAttributes } from './version.js'; +const traceIdSymbol = Symbol('traceId'); +class MessageStatusCount { + succeeded = 0; + failed = 0; + total; + constructor(total) { + this.total = total; + } + ack() { + this.succeeded = this.succeeded + 1; + } + ackRemaining() { + this.succeeded = this.total - this.failed; + } + retry() { + this.failed = this.failed + 1; + } + retryRemaining() { + this.failed = this.total - this.succeeded; + } + toAttributes() { + return { + 'queue.messages_count': this.total, + 'queue.messages_success': this.succeeded, + 'queue.messages_failed': this.failed, + 'queue.batch_success': this.succeeded === this.total, + }; + } +} +const addEvent = (name, msg) => { + const attrs = {}; + if (msg) { + attrs['queue.message_id'] = msg.id; + attrs['queue.message_timestamp'] = msg.timestamp.toISOString(); + } + trace.getActiveSpan()?.addEvent(name, attrs); +}; +const proxyQueueMessage = (msg, count) => { + const msgHandler = { + get: (target, prop) => { + if (prop === 'ack') { + const ackFn = Reflect.get(target, prop); + return new Proxy(ackFn, { + apply: (fnTarget) => { + addEvent('messageAck', msg); + count.ack(); + //TODO: handle errors + Reflect.apply(fnTarget, msg, []); + }, + }); + } + else if (prop === 'retry') { + const retryFn = Reflect.get(target, prop); + return new Proxy(retryFn, { + apply: (fnTarget) => { + addEvent('messageRetry', msg); + count.retry(); + //TODO: handle errors + const result = Reflect.apply(fnTarget, msg, []); + return result; + }, + }); + } + else { + return Reflect.get(target, prop, msg); + } + }, + }; + return wrap(msg, msgHandler); +}; +const proxyMessageBatch = (batch, count) => { + const batchHandler = { + get: (target, prop) => { + if (prop === 'messages') { + const messages = Reflect.get(target, prop); + const messagesHandler = { + get: (target, prop) => { + if (typeof prop === 'string' && !isNaN(parseInt(prop))) { + const message = Reflect.get(target, prop); + return proxyQueueMessage(message, count); + } + else { + return Reflect.get(target, prop); + } + }, + }; + return wrap(messages, messagesHandler); + } + else if (prop === 'ackAll') { + const ackFn = Reflect.get(target, prop); + return new Proxy(ackFn, { + apply: (fnTarget) => { + addEvent('ackAll'); + count.ackRemaining(); + //TODO: handle errors + Reflect.apply(fnTarget, batch, []); + }, + }); + } + else if (prop === 'retryAll') { + const retryFn = Reflect.get(target, prop); + return new Proxy(retryFn, { + apply: (fnTarget) => { + addEvent('retryAll'); + count.retryRemaining(); + //TODO: handle errors + Reflect.apply(fnTarget, batch, []); + }, + }); + } + return Reflect.get(target, prop); + }, + }; + return wrap(batch, batchHandler); +}; +export function executeQueueHandler(queueFn, [batch, env, ctx]) { + const count = new MessageStatusCount(batch.messages.length); + batch = proxyMessageBatch(batch, count); + const tracer = trace.getTracer('queueHandler'); + const options = { + attributes: { + [SemanticAttributes.FAAS_TRIGGER]: 'pubsub', + 'queue.name': batch.queue, + }, + kind: SpanKind.CONSUMER, + }; + Object.assign(options.attributes, versionAttributes(env)); + const promise = tracer.startActiveSpan(`queueHandler ${batch.queue}`, options, async (span) => { + const traceId = span.spanContext().traceId; + api_context.active().setValue(traceIdSymbol, traceId); + try { + const result = await queueFn(batch, env, ctx); + span.setAttribute('queue.implicitly_acked', count.total - count.succeeded - count.failed); + count.ackRemaining(); + span.setAttributes(count.toAttributes()); + span.end(); + return result; + } + catch (error) { + span.recordException(error); + span.setAttribute('queue.implicitly_retried', count.total - count.succeeded - count.failed); + count.retryRemaining(); + span.end(); + throw error; + } + }); + return promise; +} +export function createQueueHandler(queueFn, initialiser) { + const queueHandler = { + async apply(target, _thisArg, argArray) { + const [batch, orig_env, orig_ctx] = argArray; + const config = initialiser(orig_env, batch); + const env = instrumentEnv(orig_env); + const { ctx, tracker } = proxyExecutionContext(orig_ctx); + const context = setConfig(config); + try { + const args = [batch, env, ctx]; + return await api_context.with(context, executeQueueHandler, undefined, target, args); + } + catch (error) { + throw error; + } + finally { + orig_ctx.waitUntil(exportSpans(tracker)); + } + }, + }; + return wrap(queueFn, queueHandler); +} +function instrumentQueueSend(fn, name) { + const tracer = trace.getTracer('queueSender'); + const handler = { + apply: (target, thisArg, argArray) => { + return tracer.startActiveSpan(`Queues ${name} send`, async (span) => { + span.setAttribute('queue.operation', 'send'); + await Reflect.apply(target, unwrap(thisArg), argArray); + span.end(); + }); + }, + }; + return wrap(fn, handler); +} +function instrumentQueueSendBatch(fn, name) { + const tracer = trace.getTracer('queueSender'); + const handler = { + apply: (target, thisArg, argArray) => { + return tracer.startActiveSpan(`Queues ${name} sendBatch`, async (span) => { + span.setAttribute('queue.operation', 'sendBatch'); + await Reflect.apply(target, unwrap(thisArg), argArray); + span.end(); + }); + }, + }; + return wrap(fn, handler); +} +export function instrumentQueueSender(queue, name) { + const queueHandler = { + get: (target, prop) => { + if (prop === 'send') { + const sendFn = Reflect.get(target, prop); + return instrumentQueueSend(sendFn, name); + } + else if (prop === 'sendBatch') { + const sendFn = Reflect.get(target, prop); + return instrumentQueueSendBatch(sendFn, name); + } + else { + return Reflect.get(target, prop); + } + }, + }; + return wrap(queue, queueHandler); +} +//# sourceMappingURL=queue.js.map \ No newline at end of file diff --git a/dist/esm/instrumentation/queue.js.map b/dist/esm/instrumentation/queue.js.map new file mode 100644 index 0000000..27c3d37 --- /dev/null +++ b/dist/esm/instrumentation/queue.js.map @@ -0,0 +1 @@ +{"version":3,"file":"queue.js","sourceRoot":"","sources":["../../../src/instrumentation/queue.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAe,QAAQ,EAAyB,OAAO,IAAI,WAAW,EAAE,MAAM,oBAAoB,CAAA;AAChH,OAAO,EAAE,kBAAkB,EAAE,MAAM,qCAAqC,CAAA;AACxE,OAAO,EAAe,SAAS,EAAE,MAAM,cAAc,CAAA;AACrD,OAAO,EAAE,WAAW,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAA;AAChE,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AACxC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAA;AAKhD,MAAM,aAAa,GAAG,MAAM,CAAC,SAAS,CAAC,CAAA;AAEvC,MAAM,kBAAkB;IACvB,SAAS,GAAG,CAAC,CAAA;IACb,MAAM,GAAG,CAAC,CAAA;IACD,KAAK,CAAQ;IACtB,YAAY,KA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duled.d.ts new file mode 100644 index 0000000..f8282c5 --- /dev/null +++ b/dist/esm/instrumentation/scheduled.d.ts @@ -0,0 +1,7 @@ +import { Initialiser } from '../config.js'; +type ScheduledHandler = ExportedHandlerScheduledHandler; +export type ScheduledHandlerArgs = Parameters; +export declare function executeScheduledHandler(scheduledFn: ScheduledHandler, [controller, env, ctx]: ScheduledHandlerArgs): Promise; +export declare function createScheduledHandler(scheduledFn: ScheduledHandler, initialiser: Initialiser): ScheduledHandler; +export {}; +//# sourceMappingURL=scheduled.d.ts.map \ No newline at end of file diff --git a/dist/esm/instrumentation/scheduled.d.ts.map b/dist/esm/instrumentation/scheduled.d.ts.map new file mode 100644 index 0000000..60244e4 --- /dev/null +++ b/dist/esm/instrumentation/scheduled.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"scheduled.d.ts","sourceRoot":"","sources":["../../../src/instrumentation/scheduled.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAa,MAAM,cAAc,CAAA;AAMrD,KAAK,gBAAgB,GAAG,+BAA+B,CAAC,OAAO,CAAC,CAAA;AAChE,MAAM,MAAM,oBAAoB,GAAG,UAAU,CAAC,gBAAgB,CAAC,CAAA;AAK/D,wBAAgB,uBAAuB,CACtC,WAAW,EAAE,gBAAgB,EAC7B,CAAC,UAAU,EAAE,GAAG,EAAE,GAAG,CAAC,EAAE,oBAAoB,GAC1C,OAAO,CAAC,IAAI,CAAC,CA6Bf;AAED,wBAAgB,sBAAsB,CAAC,WAAW,EAAE,gBAAgB,EAAE,WAAW,EAAE,WAAW,oBAqB7F"} \ No newline at end of file diff --git a/dist/esm/instrumentation/scheduled.js b/dist/esm/instrumentation/scheduled.js new file mode 100644 index 0000000..2ed4829 --- /dev/null +++ b/dist/esm/instrumentation/scheduled.js @@ -0,0 +1,63 @@ +import { trace, SpanKind, context as api_context, SpanStatusCode } from '@opentelemetry/api'; +import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; +import { setConfig } from '../config.js'; +import { exportSpans, proxyExecutionContext } from './common.js'; +import { instrumentEnv } from './env.js'; +import { wrap } from '../wrap.js'; +import { versionAttributes } from './version.js'; +const traceIdSymbol = Symbol('traceId'); +let cold_start = true; +export function executeScheduledHandler(scheduledFn, [controller, env, ctx]) { + const tracer = trace.getTracer('scheduledHandler'); + const attributes = { + [SemanticAttributes.FAAS_TRIGGER]: 'timer', + [SemanticAttributes.FAAS_COLDSTART]: cold_start, + [SemanticAttributes.FAAS_CRON]: controller.cron, + [SemanticAttributes.FAAS_TIME]: new Date(controller.scheduledTime).toISOString(), + }; + cold_start = false; + Object.assign(attributes, versionAttributes(env)); + const options = { + attributes, + kind: SpanKind.SERVER, + }; + const promise = tracer.startActiveSpan(`scheduledHandler ${controller.cron}`, options, async (span) => { + const traceId = span.spanContext().traceId; + api_context.active().setValue(traceIdSymbol, traceId); + try { + await scheduledFn(controller, env, ctx); + } + catch (error) { + span.recordException(error); + span.setStatus({ code: SpanStatusCode.ERROR }); + throw error; + } + finally { + span.end(); + } + }); + return promise; +} +export function createScheduledHandler(scheduledFn, initialiser) { + const scheduledHandler = { + async apply(target, _thisArg, argArray) { + const [controller, orig_env, orig_ctx] = argArray; + const config = initialiser(orig_env, controller); + const env = instrumentEnv(orig_env); + const { ctx, tracker } = proxyExecutionContext(orig_ctx); + const context = setConfig(config); + try { + const args = [controller, env, ctx]; + return await api_context.with(context, executeScheduledHandler, undefined, target, args); + } + catch (error) { + throw error; + } + finally { + orig_ctx.waitUntil(exportSpans(tracker)); + } + }, + }; + return wrap(scheduledFn, scheduledHandler); +} +//# sourceMappingURL=scheduled.js.map \ No newline at end of file diff --git a/dist/esm/instrumentation/scheduled.js.map b/dist/esm/instrumentation/scheduled.js.map new file mode 100644 index 0000000..88b15ef --- /dev/null +++ b/dist/esm/instrumentation/scheduled.js.map @@ -0,0 +1 @@ +{"version":3,"file":"scheduled.js","sourceRoot":"","sources":["../../../src/instrumentation/scheduled.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,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E,uBAAuB,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,CAAC,CAAA;YACzF,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBAChB,MAAM,KAAK,CAAA;YACZ,CAAC;oBAAS,CAAC;gBACV,QAAQ,CAAC,SAAS,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,CAAA;YACzC,CAAC;QACF,CAAC;KACD,CAAA;IACD,OAAO,IAAI,CAAC,WAAW,EAAE,gBAAgB,CAAC,CAAA;AAC3C,CAAC"} \ No newline at end of file diff --git a/dist/esm/instrumentation/service.d.ts b/dist/esm/instrumentation/service.d.ts new file mode 100644 index 0000000..d171b64 --- /dev/null +++ b/dist/esm/instrumentation/service.d.ts @@ -0,0 +1,2 @@ +export declare function instrumentServiceBinding(fetcher: Fetcher, envName: string): Fetcher; +//# sourceMappingURL=service.d.ts.map \ No newline at end of file diff --git a/dist/esm/instrumentation/service.d.ts.map b/dist/esm/instrumentation/service.d.ts.map new file mode 100644 index 0000000..7ed8650 --- /dev/null +++ b/dist/esm/instrumentation/service.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../../src/instrumentation/service.ts"],"names":[],"mappings":"AAGA,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAenF"} \ No newline at end of file diff --git a/dist/esm/instrumentation/service.js b/dist/esm/instrumentation/service.js new file mode 100644 index 0000000..ea824fd --- /dev/null +++ b/dist/esm/instrumentation/service.js @@ -0,0 +1,20 @@ +import { passthroughGet, wrap } from '../wrap.js'; +import { instrumentClientFetch } from './fetch.js'; +export function instrumentServiceBinding(fetcher, envName) { + const fetcherHandler = { + get(target, prop) { + if (prop === 'fetch') { + const fetcher = Reflect.get(target, prop); + const attrs = { + name: `Service Binding ${envName}`, + }; + return instrumentClientFetch(fetcher, () => ({ includeTraceContext: true }), attrs); + } + else { + return passthroughGet(target, prop); + } + }, + }; + return wrap(fetcher, fetcherHandler); +} +//# sourceMappingURL=service.js.map \ No newline at end of file diff --git a/dist/esm/instrumentation/service.js.map b/dist/esm/instrumentation/service.js.map new file mode 100644 index 0000000..7799a61 --- /dev/null +++ b/dist/esm/instrumentation/service.js.map @@ -0,0 +1 @@ +{"version":3,"file":"service.js","sourceRoot":"","sources":["../../../src/instrumentation/service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;AACjD,OAAO,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAA;AAElD,MAAM,UAAU,wBAAwB,CAAC,OAAgB,EAAE,OAAe;IACzE,MAAM,cAAc,GAA0B;QAC7C,GAAG,CAAC,MAAM,EAAE,IAAI;YACf,IAAI,IAAI,KAAK,OAAO,EAAE,CAAC;gBACtB,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;gBACzC,MAAM,KAAK,GAAG;oBACb,IAAI,EAAE,mBAAmB,OAAO,EAAE;iBAClC,CAAA;gBACD,OAAO,qBAAqB,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,mBAAmB,EAAE,IAAI,EAAE,CAAC,EAAE,KAAK,CAAC,CAAA;YACpF,CAAC;iBAAM,CAAC;gBACP,OAAO,cAAc,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;YACpC,CAAC;QACF,CAAC;KACD,CAAA;IACD,OAAO,IAAI,CAAC,OAAO,EAAE,cAAc,CAAC,CAAA;AACrC,CAAC"} \ No newline at end of file diff --git a/dist/esm/instrumentation/version.d.ts b/dist/esm/instrumentation/version.d.ts new file mode 100644 index 0000000..e32c3f8 --- /dev/null +++ b/dist/esm/instrumentation/version.d.ts @@ -0,0 +1,2 @@ +export declare function versionAttributes(env: unknown): Record; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/dist/esm/instrumentation/version.d.ts.map b/dist/esm/instrumentation/version.d.ts.map new file mode 100644 index 0000000..bac2e52 --- /dev/null +++ b/dist/esm/instrumentation/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../../src/instrumentation/version.ts"],"names":[],"mappings":"AAEA,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAgBlF"} \ No newline at end of file diff --git a/dist/esm/instrumentation/version.js b/dist/esm/instrumentation/version.js new file mode 100644 index 0000000..dd87544 --- /dev/null +++ b/dist/esm/instrumentation/version.js @@ -0,0 +1,17 @@ +import { isVersionMetadata } from './env.js'; +export function versionAttributes(env) { + const attributes = {}; + if (typeof env === 'object' && env !== null) { + for (const [binding, data] of Object.entries(env)) { + if (isVersionMetadata(data)) { + attributes['cf.workers_version_metadata.binding'] = binding; + attributes['cf.workers_version_metadata.id'] = data.id; + attributes['cf.workers_version_metadata.tag'] = data.tag; + // Version metadata bindings are identical, so we can stop after the first one found + break; + } + } + } + return attributes; +} +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/dist/esm/instrumentation/version.js.map b/dist/esm/instrumentation/version.js.map new file mode 100644 index 0000000..cb125ff --- /dev/null +++ b/dist/esm/instrumentation/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/instrumentation/version.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAA;AAE5C,MAAM,UAAU,iBAAiB,CAAC,GAAY;IAC7C,MAAM,UAAU,GAAG,EAAwC,CAAA;IAE3D,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,IAAI,EAAE,CAAC;QAC7C,KAAK,MAAM,CAAC,OAAO,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;YACnD,IAAI,iBAAiB,CAAC,IAAI,CAAC,EAAE,CAAC;gBAC7B,UAAU,CAAC,qCAAqC,CAAC,GAAG,OAAO,CAAA;gBAC3D,UAAU,CAAC,gCAAgC,CAAC,GAAG,IAAI,CAAC,EAAE,CAAA;gBACtD,UAAU,CAAC,iCAAiC,CAAC,GAAG,IAAI,CAAC,GAAG,CAAA;gBACxD,oFAAoF;gBACpF,MAAK;YACN,CAAC;QACF,CAAC;IACF,CAAC;IAED,OAAO,UAAU,CAAA;AAClB,CAAC"} \ No newline at end of file diff --git a/dist/esm/multiexporter.d.ts b/dist/esm/multiexporter.d.ts new file mode 100644 index 0000000..457df78 --- /dev/null +++ b/dist/esm/multiexporter.d.ts @@ -0,0 +1,15 @@ +import { SpanExporter } from '@opentelemetry/sdk-trace-base'; +import { ExportResult } from '@opentelemetry/core'; +export declare class MultiSpanExporter implements SpanExporter { + private exporters; + constructor(exporters: Array); + export(items: any[], resultCallback: (result: ExportResult) => void): void; + shutdown(): Promise; +} +export declare class MultiSpanExporterAsync implements SpanExporter { + private exporters; + constructor(exporters: Array); + export(items: any[], resultCallback: (result: ExportResult) => void): void; + shutdown(): Promise; +} +//# sourceMappingURL=multiexporter.d.ts.map \ No newline at end of file diff --git a/dist/esm/multiexporter.d.ts.map b/dist/esm/multiexporter.d.ts.map new file mode 100644 index 0000000..d2b4c8e --- /dev/null +++ b/dist/esm/multiexporter.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"multiexporter.d.ts","sourceRoot":"","sources":["../../src/multiexporter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAA;AAC5D,OAAO,EAAE,YAAY,EAAoB,MAAM,qBAAqB,CAAA;AAIpE,qBAAa,iBAAkB,YAAW,YAAY;IACrD,OAAO,CAAC,SAAS,CAAqB;gBAC1B,SAAS,EAAE,KAAK,CAAC,YAAY,CAAC;IAI1C,MAAM,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,cAAc,EAAE,CAAC,MAAM,EAAE,YAAY,KAAK,IAAI,GAAG,IAAI;IAMpE,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;CAK/B;AAID,qBAAa,sBAAuB,YAAW,YAAY;IAC1D,OAAO,CAAC,SAAS,CAAqB;gBAC1B,SAAS,EAAE,KAAK,CAAC,YAAY,CAAC;IAI1C,MAAM,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,cAAc,EAAE,CAAC,MAAM,EAAE,YAAY,KAAK,IAAI,GAAG,IAAI;IAmBpE,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;CAG/B"} \ No newline at end of file diff --git a/dist/esm/multiexporter.js b/dist/esm/multiexporter.js new file mode 100644 index 0000000..8d8ddaf --- /dev/null +++ b/dist/esm/multiexporter.js @@ -0,0 +1,44 @@ +import { ExportResultCode } from '@opentelemetry/core'; +// First implementation, completely synchronous, more tested. +export class MultiSpanExporter { + exporters; + constructor(exporters) { + this.exporters = exporters; + } + export(items, resultCallback) { + for (const exporter of this.exporters) { + exporter.export(items, resultCallback); + } + } + async shutdown() { + for (const exporter of this.exporters) { + await exporter.shutdown(); + } + } +} +// async +export class MultiSpanExporterAsync { + exporters; + constructor(exporters) { + this.exporters = exporters; + } + export(items, resultCallback) { + const promises = this.exporters.map((exporter) => new Promise((resolve) => { + exporter.export(items, resolve); + })); + Promise.all(promises).then((results) => { + const failed = results.filter((result) => result.code === ExportResultCode.FAILED); + if (failed.length > 0) { + // not ideal, but just return the first error + resultCallback({ code: ExportResultCode.FAILED, error: failed[0].error }); + } + else { + resultCallback({ code: ExportResultCode.SUCCESS }); + } + }); + } + async shutdown() { + await Promise.all(this.exporters.map((exporter) => exporter.shutdown())); + } +} +//# sourceMappingURL=multiexporter.js.map \ No newline at end of file diff --git a/dist/esm/multiexporter.js.map b/dist/esm/multiexporter.js.map new file mode 100644 index 0000000..29e4103 --- /dev/null +++ b/dist/esm/multiexporter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"multiexporter.js","sourceRoot":"","sources":["../../src/multiexporter.ts"],"names":[],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,CAAC,EAAE,IAAI,EAAE,gBAAgB,CAAC,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAE,CAAC,KAAK,EAAE,CAAC,CAAA;YAC3E,CAAC;iBAAM,CAAC;gBACP,cAAc,CAAC,EAAE,IAAI,EAAE,gBAAgB,CAAC,OAAO,EAAE,CAAC,CAAA;YACnD,CAAC;QACF,CAAC,CAAC,CAAA;IACH,CAAC;IAED,KAAK,CAAC,QAAQ;QACb,MAAM,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAA;IACzE,CAAC;CACD"} \ No newline at end of file diff --git a/dist/esm/package-info.d.ts b/dist/esm/package-info.d.ts new file mode 100644 index 0000000..e8231f3 --- /dev/null +++ b/dist/esm/package-info.d.ts @@ -0,0 +1,3 @@ +export declare const name = "@microlabs/otel-cf-workers"; +export declare const version = "1.0.0-rc.46"; +//# sourceMappingURL=package-info.d.ts.map \ No newline at end of file diff --git a/dist/esm/package-info.d.ts.map b/dist/esm/package-info.d.ts.map new file mode 100644 index 0000000..cc612dd --- /dev/null +++ b/dist/esm/package-info.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"package-info.d.ts","sourceRoot":"","sources":["../../src/package-info.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,IAAI,+BAA+B,CAAC;AACjD,eAAO,MAAM,OAAO,gBAAgB,CAAC"} \ No newline at end of file diff --git a/dist/esm/package-info.js b/dist/esm/package-info.js new file mode 100644 index 0000000..7e11982 --- /dev/null +++ b/dist/esm/package-info.js @@ -0,0 +1,4 @@ +// This file is auto-generated by package-info.js +export const name = '@microlabs/otel-cf-workers'; +export const version = '1.0.0-rc.46'; +//# sourceMappingURL=package-info.js.map \ No newline at end of file diff --git a/dist/esm/package-info.js.map b/dist/esm/package-info.js.map new file mode 100644 index 0000000..0290ba9 --- /dev/null +++ b/dist/esm/package-info.js.map @@ -0,0 +1 @@ +{"version":3,"file":"package-info.js","sourceRoot":"","sources":["../../src/package-info.ts"],"names":[],"mappings":"AACA,iDAAiD;AACjD,MAAM,CAAC,MAAM,IAAI,GAAG,4BAA4B,CAAC;AACjD,MAAM,CAAC,MAAM,OAAO,GAAG,aAAa,CAAC"} \ No newline at end of file diff --git a/dist/esm/provider.d.ts b/dist/esm/provider.d.ts new file mode 100644 index 0000000..8f47e9c --- /dev/null +++ b/dist/esm/provider.d.ts @@ -0,0 +1,19 @@ +import { Tracer, TracerOptions, TracerProvider } from '@opentelemetry/api'; +import { SpanProcessor } from '@opentelemetry/sdk-trace-base'; +import { Resource } from '@opentelemetry/resources'; +/** + * Register this TracerProvider for use with the OpenTelemetry API. + * Undefined values may be replaced with defaults, and + * null values will be skipped. + * + * @param config Configuration object for SDK registration + */ +export declare class WorkerTracerProvider implements TracerProvider { + private spanProcessors; + private resource; + private tracers; + constructor(spanProcessors: SpanProcessor[], resource: Resource); + getTracer(name: string, version?: string, options?: TracerOptions): Tracer; + register(): void; +} +//# sourceMappingURL=provider.d.ts.map \ No newline at end of file diff --git a/dist/esm/provider.d.ts.map b/dist/esm/provider.d.ts.map new file mode 100644 index 0000000..331b0ab --- /dev/null +++ b/dist/esm/provider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../src/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,MAAM,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;AAE1F,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAA;AAC7D,OAAO,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAA;AAKnD;;;;;;GAMG;AACH,qBAAa,oBAAqB,YAAW,cAAc;IAC1D,OAAO,CAAC,cAAc,CAAiB;IACvC,OAAO,CAAC,QAAQ,CAAU;IAC1B,OAAO,CAAC,OAAO,CAA6B;gBAEhC,cAAc,EAAE,aAAa,EAAE,EAAE,QAAQ,EAAE,QAAQ;IAK/D,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,aAAa,GAAG,MAAM;IAQ1E,QAAQ,IAAI,IAAI;CAIhB"} \ No newline at end of file diff --git a/dist/esm/provider.js b/dist/esm/provider.js new file mode 100644 index 0000000..a229ce4 --- /dev/null +++ b/dist/esm/provider.js @@ -0,0 +1,31 @@ +import { context, trace } from '@opentelemetry/api'; +import { AsyncLocalStorageContextManager } from './context.js'; +import { WorkerTracer } from './tracer.js'; +/** + * Register this TracerProvider for use with the OpenTelemetry API. + * Undefined values may be replaced with defaults, and + * null values will be skipped. + * + * @param config Configuration object for SDK registration + */ +export class WorkerTracerProvider { + spanProcessors; + resource; + tracers = {}; + constructor(spanProcessors, resource) { + this.spanProcessors = spanProcessors; + this.resource = resource; + } + getTracer(name, version, options) { + const key = `${name}@${version || ''}:${options?.schemaUrl || ''}`; + if (!this.tracers[key]) { + this.tracers[key] = new WorkerTracer(this.spanProcessors, this.resource); + } + return this.tracers[key]; + } + register() { + trace.setGlobalTracerProvider(this); + context.setGlobalContextManager(new AsyncLocalStorageContextManager()); + } +} +//# sourceMappingURL=provider.js.map \ No newline at end of file diff --git a/dist/esm/provider.js.map b/dist/esm/provider.js.map new file mode 100644 index 0000000..1e99360 --- /dev/null +++ b/dist/esm/provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../src/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,KAAK,EAAyC,MAAM,oBAAoB,CAAA;AAK1F,OAAO,EAAE,+BAA+B,EAAE,MAAM,cAAc,CAAA;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAE1C;;;;;;GAMG;AACH,MAAM,OAAO,oBAAoB;IACxB,cAAc,CAAiB;IAC/B,QAAQ,CAAU;IAClB,OAAO,GAA2B,EAAE,CAAA;IAE5C,YAAY,cAA+B,EAAE,QAAkB;QAC9D,IAAI,CAAC,cAAc,GAAG,cAAc,CAAA;QACpC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;IACzB,CAAC;IAED,SAAS,CAAC,IAAY,EAAE,OAAgB,EAAE,OAAuB;QAChE,MAAM,GAAG,GAAG,GAAG,IAAI,IAAI,OAAO,IAAI,EAAE,IAAI,OAAO,EAAE,SAAS,IAAI,EAAE,EAAE,CAAA;QAClE,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;YACxB,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,IAAI,YAAY,CAAC,IAAI,CAAC,cAAc,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAA;QACzE,CAAC;QACD,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAE,CAAA;IAC1B,CAAC;IAED,QAAQ;QACP,KAAK,CAAC,uBAAuB,CAAC,IAAI,CAAC,CAAA;QACnC,OAAO,CAAC,uBAAuB,CAAC,IAAI,+BAA+B,EAAE,CAAC,CAAA;IACvE,CAAC;CACD"} \ No newline at end of file diff --git a/dist/esm/sampling.d.ts b/dist/esm/sampling.d.ts new file mode 100644 index 0000000..65673a0 --- /dev/null +++ b/dist/esm/sampling.d.ts @@ -0,0 +1,11 @@ +import { ReadableSpan } from '@opentelemetry/sdk-trace-base'; +export interface LocalTrace { + readonly traceId: string; + readonly localRootSpan: ReadableSpan; + readonly spans: ReadableSpan[]; +} +export type TailSampleFn = (traceInfo: LocalTrace) => boolean; +export declare function multiTailSampler(samplers: TailSampleFn[]): TailSampleFn; +export declare const isHeadSampled: TailSampleFn; +export declare const isRootErrorSpan: TailSampleFn; +//# sourceMappingURL=sampling.d.ts.map \ No newline at end of file diff --git a/dist/esm/sampling.d.ts.map b/dist/esm/sampling.d.ts.map new file mode 100644 index 0000000..920997d --- /dev/null +++ b/dist/esm/sampling.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sampling.d.ts","sourceRoot":"","sources":["../../src/sampling.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAA;AAE5D,MAAM,WAAW,UAAU;IAC1B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,aAAa,EAAE,YAAY,CAAA;IACpC,QAAQ,CAAC,KAAK,EAAE,YAAY,EAAE,CAAA;CAC9B;AAED,MAAM,MAAM,YAAY,GAAG,CAAC,SAAS,EAAE,UAAU,KAAK,OAAO,CAAA;AAE7D,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,YAAY,EAAE,GAAG,YAAY,CAIvE;AAED,eAAO,MAAM,aAAa,EAAE,YAG3B,CAAA;AAED,eAAO,MAAM,eAAe,EAAE,YAG7B,CAAA"} \ No newline at end of file diff --git a/dist/esm/sampling.js b/dist/esm/sampling.js new file mode 100644 index 0000000..af8695a --- /dev/null +++ b/dist/esm/sampling.js @@ -0,0 +1,15 @@ +import { TraceFlags, SpanStatusCode } from '@opentelemetry/api'; +export function multiTailSampler(samplers) { + return (traceInfo) => { + return samplers.reduce((result, sampler) => result || sampler(traceInfo), false); + }; +} +export const isHeadSampled = (traceInfo) => { + const localRootSpan = traceInfo.localRootSpan; + return (localRootSpan.spanContext().traceFlags & TraceFlags.SAMPLED) === TraceFlags.SAMPLED; +}; +export const isRootErrorSpan = (traceInfo) => { + const localRootSpan = traceInfo.localRootSpan; + return localRootSpan.status.code === SpanStatusCode.ERROR; +}; +//# sourceMappingURL=sampling.js.map \ No newline at end of file diff --git a/dist/esm/sampling.js.map b/dist/esm/sampling.js.map new file mode 100644 index 0000000..2c49016 --- /dev/null +++ b/dist/esm/sampling.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sampling.js","sourceRoot":"","sources":["../../src/sampling.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;AAW/D,MAAM,UAAU,gBAAgB,CAAC,QAAwB;IACxD,OAAO,CAAC,SAAS,EAAE,EAAE;QACpB,OAAO,QAAQ,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,CAAC,MAAM,IAAI,OAAO,CAAC,SAAS,CAAC,EAAE,KAAK,CAAC,CAAA;IACjF,CAAC,CAAA;AACF,CAAC;AAED,MAAM,CAAC,MAAM,aAAa,GAAiB,CAAC,SAAS,EAAE,EAAE;IACxD,MAAM,aAAa,GAAG,SAAS,CAAC,aAAwC,CAAA;IACxE,OAAO,CAAC,aAAa,CAAC,WAAW,EAAE,CAAC,UAAU,GAAG,UAAU,CAAC,OAAO,CAAC,KAAK,UAAU,CAAC,OAAO,CAAA;AAC5F,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,eAAe,GAAiB,CAAC,SAAS,EAAE,EAAE;IAC1D,MAAM,aAAa,GAAG,SAAS,CAAC,aAAwC,CAAA;IACxE,OAAO,aAAa,CAAC,MAAM,CAAC,IAAI,KAAK,cAAc,CAAC,KAAK,CAAA;AAC1D,CAAC,CAAA"} \ No newline at end of file diff --git a/dist/esm/sdk.d.ts b/dist/esm/sdk.d.ts new file mode 100644 index 0000000..e40be39 --- /dev/null +++ b/dist/esm/sdk.d.ts @@ -0,0 +1,12 @@ +import { Trigger, TraceConfig } from './types.js'; +import { DOClass } from './instrumentation/do.js'; +export type ResolveConfigFn = (env: Env, trigger: Trigger) => TraceConfig; +export type ConfigurationOption = TraceConfig | ResolveConfigFn; +export declare function isRequest(trigger: Trigger): trigger is Request; +export declare function isMessageBatch(trigger: Trigger): trigger is MessageBatch; +export declare function isAlarm(trigger: Trigger): trigger is 'do-alarm'; +export declare function instrument(handler: ExportedHandler, config: ConfigurationOption): ExportedHandler; +export declare function instrumentDO(doClass: DOClass, config: ConfigurationOption): DOClass; +export { waitUntilTrace } from './instrumentation/fetch.js'; +export declare const __unwrappedFetch: typeof fetch; +//# sourceMappingURL=sdk.d.ts.map \ No newline at end of file diff --git a/dist/esm/sdk.d.ts.map b/dist/esm/sdk.d.ts.map new file mode 100644 index 0000000..46ffd9d --- /dev/null +++ b/dist/esm/sdk.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../src/sdk.ts"],"names":[],"mappings":"AAiBA,OAAO,EACN,OAAO,EACP,WAAW,EAKX,MAAM,YAAY,CAAA;AAKnB,OAAO,EAAE,OAAO,EAAqB,MAAM,yBAAyB,CAAA;AAQpE,MAAM,MAAM,eAAe,CAAC,GAAG,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,EAAE,OAAO,KAAK,WAAW,CAAA;AACpF,MAAM,MAAM,mBAAmB,GAAG,WAAW,GAAG,eAAe,CAAA;AAE/D,wBAAgB,SAAS,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,OAAO,CAE9D;AAED,wBAAgB,cAAc,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,YAAY,CAExE;AAED,wBAAgB,OAAO,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,UAAU,CAE/D;AAwHD,wBAAgB,UAAU,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EACjC,OAAO,EAAE,eAAe,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EACjC,MAAM,EAAE,mBAAmB,GACzB,eAAe,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAkB1B;AAED,wBAAgB,YAAY,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,mBAAmB,WAIzE;AAED,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAA;AAE3D,eAAO,MAAM,gBAAgB,cAAgB,CAAA"} \ No newline at end of file diff --git a/dist/esm/sdk.js b/dist/esm/sdk.js new file mode 100644 index 0000000..509af3b --- /dev/null +++ b/dist/esm/sdk.js @@ -0,0 +1,159 @@ +import { propagation } from '@opentelemetry/api'; +import { W3CTraceContextPropagator } from '@opentelemetry/core'; +import { Resource } from '@opentelemetry/resources'; +import { AlwaysOnSampler, ParentBasedSampler, TraceIdRatioBasedSampler, } from '@opentelemetry/sdk-trace-base'; +import { OTLPExporter } from './exporter.js'; +import { WorkerTracerProvider } from './provider.js'; +import { isHeadSampled, isRootErrorSpan, multiTailSampler } from './sampling.js'; +import { BatchTraceSpanProcessor } from './spanprocessor.js'; +import { isSpanProcessorConfig, } from './types.js'; +import { unwrap } from './wrap.js'; +import { createFetchHandler, instrumentGlobalFetch } from './instrumentation/fetch.js'; +import { instrumentGlobalCache } from './instrumentation/cache.js'; +import { createQueueHandler } from './instrumentation/queue.js'; +import { instrumentDOClass } from './instrumentation/do.js'; +import { createScheduledHandler } from './instrumentation/scheduled.js'; +import { name, version } from './package-info'; +export function isRequest(trigger) { + return trigger instanceof Request; +} +export function isMessageBatch(trigger) { + return !!trigger.ackAll; +} +export function isAlarm(trigger) { + return trigger === 'do-alarm'; +} +const createResource = (config) => { + const workerResourceAttrs = { + 'cloud.provider': 'cloudflare', + 'cloud.platform': 'cloudflare.workers', + 'cloud.region': 'earth', + 'faas.max_memory': 134217728, + 'telemetry.sdk.language': 'js', + 'telemetry.sdk.name': name, + 'telemetry.sdk.version': version, + }; + const serviceResource = new Resource({ + 'service.name': config.service.name, + 'service.namespace': config.service.namespace, + 'service.version': config.service.version, + }); + const resource = new Resource(workerResourceAttrs); + return resource.merge(serviceResource); +}; +function isSpanExporter(exporterConfig) { + return !!exporterConfig.export; +} +let initialised = false; +function init(config) { + if (!initialised) { + if (config.instrumentation.instrumentGlobalCache) { + instrumentGlobalCache(); + } + if (config.instrumentation.instrumentGlobalFetch) { + instrumentGlobalFetch(); + } + propagation.setGlobalPropagator(config.propagator); + const resource = createResource(config); + const provider = new WorkerTracerProvider(config.spanProcessors, resource); + provider.register(); + initialised = true; + } +} +function isSampler(sampler) { + return !!sampler.shouldSample; +} +function createSampler(conf) { + const ratioSampler = new TraceIdRatioBasedSampler(conf.ratio); + if (typeof conf.acceptRemote === 'boolean' && !conf.acceptRemote) { + return new ParentBasedSampler({ + root: ratioSampler, + remoteParentSampled: ratioSampler, + remoteParentNotSampled: ratioSampler, + }); + } + else { + return new ParentBasedSampler({ root: ratioSampler }); + } +} +function parseConfig(supplied) { + if (isSpanProcessorConfig(supplied)) { + const headSampleConf = supplied.sampling?.headSampler; + const headSampler = headSampleConf + ? isSampler(headSampleConf) + ? headSampleConf + : createSampler(headSampleConf) + : new AlwaysOnSampler(); + const spanProcessors = Array.isArray(supplied.spanProcessors) ? supplied.spanProcessors : [supplied.spanProcessors]; + if (spanProcessors.length === 0) { + console.log('Warning! You must either specify an exporter or your own SpanProcessor(s)/Exporter combination in the open-telemetry configuration.'); + } + return { + fetch: { + includeTraceContext: supplied.fetch?.includeTraceContext ?? true, + }, + handlers: { + fetch: { + acceptTraceContext: supplied.handlers?.fetch?.acceptTraceContext ?? true, + }, + }, + postProcessor: supplied.postProcessor || ((spans) => spans), + sampling: { + headSampler, + tailSampler: supplied.sampling?.tailSampler || multiTailSampler([isHeadSampled, isRootErrorSpan]), + }, + service: supplied.service, + spanProcessors, + propagator: supplied.propagator || new W3CTraceContextPropagator(), + instrumentation: { + instrumentGlobalCache: supplied.instrumentation?.instrumentGlobalCache ?? true, + instrumentGlobalFetch: supplied.instrumentation?.instrumentGlobalFetch ?? true, + }, + }; + } + else { + const exporter = isSpanExporter(supplied.exporter) ? supplied.exporter : new OTLPExporter(supplied.exporter); + const spanProcessors = [new BatchTraceSpanProcessor(exporter)]; + const newConfig = Object.assign(supplied, { exporter: undefined, spanProcessors }); + return parseConfig(newConfig); + } +} +function createInitialiser(config) { + if (typeof config === 'function') { + return (env, trigger) => { + const conf = parseConfig(config(env, trigger)); + init(conf); + return conf; + }; + } + else { + return () => { + const conf = parseConfig(config); + init(conf); + return conf; + }; + } +} +export function instrument(handler, config) { + const initialiser = createInitialiser(config); + if (handler.fetch) { + const fetcher = unwrap(handler.fetch); + handler.fetch = createFetchHandler(fetcher, initialiser); + } + if (handler.scheduled) { + const scheduler = unwrap(handler.scheduled); + handler.scheduled = createScheduledHandler(scheduler, initialiser); + } + if (handler.queue) { + const queuer = unwrap(handler.queue); + handler.queue = createQueueHandler(queuer, initialiser); + } + return handler; +} +export function instrumentDO(doClass, config) { + const initialiser = createInitialiser(config); + return instrumentDOClass(doClass, initialiser); +} +export { waitUntilTrace } from './instrumentation/fetch.js'; +export const __unwrappedFetch = unwrap(fetch); +//# sourceMappingURL=sdk.js.map \ No newline at end of file diff --git a/dist/esm/sdk.js.map b/dist/esm/sdk.js.map new file mode 100644 index 0000000..4257181 --- /dev/null +++ b/dist/esm/sdk.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAA;AAChD,OAAO,EAAE,yBAAyB,EAAE,MAAM,qBAAqB,CAAA;AAC/D,OAAO,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAA;AACnD,OAAO,EACN,eAAe,EACf,kBAAkB,EAIlB,wBAAwB,GACxB,MAAM,+BAA+B,CAAA;AAGtC,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAA;AAC5C,OAAO,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAA;AACpD,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAA;AAChF,OAAO,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAA;AAC5D,OAAO,EAMN,qBAAqB,GACrB,MAAM,YAAY,CAAA;AACnB,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAA;AAClC,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAA;AACtF,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAA;AAClE,OAAO,EAAE,kBAAkB,EAAE,MAAM,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SAAS,EAAE,CAAC;QACvB,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,SAAS,CAAqB,CAAA;QAC/D,OAAO,CAAC,SAAS,GAAG,sBAAsB,CAAC,SAAS,EAAE,WAAW,CAAC,CAAA;IACnE,CAAC;IAED,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;QACnB,MAAM,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,KAAK,CAAiB,CAAA;QACpD,OAAO,CAAC,KAAK,GAAG,kBAAkB,CAAC,MAAM,EAAE,WAAW,CAAC,CAAA;IACxD,CAAC;IACD,OAAO,OAAO,CAAA;AACf,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,OAAgB,EAAE,MAA2B;IACzE,MAAM,WAAW,GAAG,iBAAiB,CAAC,MAAM,CAAC,CAAA;IAE7C,OAAO,iBAAiB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAA;AAC/C,CAAC;AAED,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAA;AAE3D,MAAM,CAAC,MAAM,gBAAgB,GAAG,MAAM,CAAC,KAAK,CAAC,CAAA"} \ No newline at end of file diff --git a/dist/esm/span.d.ts b/dist/esm/span.d.ts new file mode 100644 index 0000000..7b1aca8 --- /dev/null +++ b/dist/esm/span.d.ts @@ -0,0 +1,55 @@ +import { SpanContext, Link, SpanKind, TimeInput, Exception, Attributes, HrTime, Span, SpanStatus, AttributeValue } from '@opentelemetry/api'; +import { InstrumentationLibrary } from '@opentelemetry/core'; +import { IResource } from '@opentelemetry/resources'; +import { ReadableSpan, TimedEvent } from '@opentelemetry/sdk-trace-base'; +type OnSpanEnd = (span: Span) => void; +interface SpanInit { + attributes: unknown; + name: string; + onEnd: OnSpanEnd; + resource: IResource; + spanContext: SpanContext; + links?: Link[]; + parentSpanId?: string; + spanKind?: SpanKind; + startTime?: TimeInput; +} +export declare class SpanImpl implements Span, ReadableSpan { + name: string; + private readonly _spanContext; + private readonly onEnd; + readonly parentSpanId?: string; + readonly kind: SpanKind; + readonly attributes: Attributes; + status: SpanStatus; + endTime: HrTime; + private _duration; + readonly startTime: HrTime; + readonly events: TimedEvent[]; + readonly links: Link[]; + readonly resource: IResource; + instrumentationLibrary: InstrumentationLibrary; + private _ended; + private _droppedAttributesCount; + private _droppedEventsCount; + private _droppedLinksCount; + constructor(init: SpanInit); + addLink(link: Link): this; + addLinks(links: Link[]): this; + spanContext(): SpanContext; + setAttribute(key: string, value?: AttributeValue): this; + setAttributes(attributes: Attributes): this; + addEvent(name: string, attributesOrStartTime?: Attributes | TimeInput, startTime?: TimeInput): this; + setStatus(status: SpanStatus): this; + updateName(name: string): this; + end(endTime?: TimeInput): void; + isRecording(): boolean; + recordException(exception: Exception, time?: TimeInput): void; + get duration(): HrTime; + get ended(): boolean; + get droppedAttributesCount(): number; + get droppedEventsCount(): number; + get droppedLinksCount(): number; +} +export {}; +//# sourceMappingURL=span.d.ts.map \ No newline at end of file diff --git a/dist/esm/span.d.ts.map b/dist/esm/span.d.ts.map new file mode 100644 index 0000000..9adad2f --- /dev/null +++ b/dist/esm/span.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"span.d.ts","sourceRoot":"","sources":["../../src/span.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,WAAW,EACX,IAAI,EACJ,QAAQ,EACR,SAAS,EACT,SAAS,EACT,UAAU,EACV,MAAM,EACN,IAAI,EACJ,UAAU,EAEV,cAAc,EACd,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EAEN,sBAAsB,EAKtB,MAAM,qBAAqB,CAAA;AAC5B,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAA;AACpD,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAA;AAGxE,KAAK,SAAS,GAAG,CAAC,IAAI,EAAE,IAAI,KAAK,IAAI,CAAA;AAErC,UAAU,QAAQ;IACjB,UAAU,EAAE,OAAO,CAAA;IACnB,IAAI,EAAE,MAAM,CAAA;IACZ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;IAOvD,aAAa,CAAC,UAAU,EAAE,UAAU,GAAG,IAAI;IAO3C,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,qBAAqB,CAAC,EAAE,UAAU,GAAG,SAAS,EAAE,SAAS,CAAC,EAAE,SAAS,GAAG,IAAI;IAYnG,SAAS,CAAC,MAAM,EAAE,UAAU,GAAG,IAAI;IAKnC,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAK9B,GAAG,CAAC,OAAO,CAAC,EAAE,SAAS,GAAG,IAAI;IAU9B,WAAW,IAAI,OAAO;IAItB,eAAe,CAAC,SAAS,EAAE,SAAS,EAAE,IAAI,CAAC,EAAE,SAAS,GAAG,IAAI;IAK7D,IAAI,QAAQ,IAAI,MAAM,CAErB;IAED,IAAI,KAAK,IAAI,OAAO,CAEnB;IAED,IAAI,sBAAsB,IAAI,MAAM,CAEnC;IAED,IAAI,kBAAkB,IAAI,MAAM,CAE/B;IAED,IAAI,iBAAiB,IAAI,MAAM,CAE9B;CACD"} \ No newline at end of file diff --git a/dist/esm/span.js b/dist/esm/span.js new file mode 100644 index 0000000..2426f6d --- /dev/null +++ b/dist/esm/span.js @@ -0,0 +1,151 @@ +import { SpanKind, SpanStatusCode, } from '@opentelemetry/api'; +import { hrTimeDuration, isAttributeKey, isAttributeValue, isTimeInput, sanitizeAttributes, } from '@opentelemetry/core'; +import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; +function transformExceptionAttributes(exception) { + const attributes = {}; + if (typeof exception === 'string') { + attributes[SemanticAttributes.EXCEPTION_MESSAGE] = exception; + } + else { + if (exception.code) { + attributes[SemanticAttributes.EXCEPTION_TYPE] = exception.code.toString(); + } + else if (exception.name) { + attributes[SemanticAttributes.EXCEPTION_TYPE] = exception.name; + } + if (exception.message) { + attributes[SemanticAttributes.EXCEPTION_MESSAGE] = exception.message; + } + if (exception.stack) { + attributes[SemanticAttributes.EXCEPTION_STACKTRACE] = exception.stack; + } + } + return attributes; +} +function millisToHr(millis) { + return [Math.trunc(millis / 1000), (millis % 1000) * 1e6]; +} +function getHrTime(input) { + const now = Date.now(); + if (!input) { + return millisToHr(now); + } + else if (input instanceof Date) { + return millisToHr(input.getTime()); + } + else if (typeof input === 'number') { + //TODO: do something with performance.now something + return millisToHr(input); + } + else if (Array.isArray(input)) { + return input; + } + const v = input; + throw new Error(`unreachable value: ${JSON.stringify(v)}`); +} +export class SpanImpl { + name; + _spanContext; + onEnd; + parentSpanId; + kind; + attributes; + status = { + code: SpanStatusCode.UNSET, + }; + endTime = [0, 0]; + _duration = [0, 0]; + startTime; + events = []; + links; + resource; + instrumentationLibrary = { name: '@microlabs/otel-cf-workers' }; + _ended = false; + _droppedAttributesCount = 0; + _droppedEventsCount = 0; + _droppedLinksCount = 0; + constructor(init) { + this.name = init.name; + this._spanContext = init.spanContext; + this.parentSpanId = init.parentSpanId; + this.kind = init.spanKind || SpanKind.INTERNAL; + this.attributes = sanitizeAttributes(init.attributes); + this.startTime = getHrTime(init.startTime); + this.links = init.links || []; + this.resource = init.resource; + this.onEnd = init.onEnd; + } + addLink(link) { + this.links.push(link); + return this; + } + addLinks(links) { + this.links.push(...links); + return this; + } + spanContext() { + return this._spanContext; + } + setAttribute(key, value) { + if (isAttributeKey(key) && isAttributeValue(value)) { + this.attributes[key] = value; + } + return this; + } + setAttributes(attributes) { + for (const [key, value] of Object.entries(attributes)) { + this.setAttribute(key, value); + } + return this; + } + addEvent(name, attributesOrStartTime, startTime) { + if (isTimeInput(attributesOrStartTime)) { + startTime = attributesOrStartTime; + attributesOrStartTime = undefined; + } + const attributes = sanitizeAttributes(attributesOrStartTime); + const time = getHrTime(startTime); + this.events.push({ name, attributes, time }); + return this; + } + setStatus(status) { + this.status = status; + return this; + } + updateName(name) { + this.name = name; + return this; + } + end(endTime) { + if (this._ended) { + return; + } + this._ended = true; + this.endTime = getHrTime(endTime); + this._duration = hrTimeDuration(this.startTime, this.endTime); + this.onEnd(this); + } + isRecording() { + return !this._ended; + } + recordException(exception, time) { + const attributes = transformExceptionAttributes(exception); + this.addEvent('exception', attributes, time); + } + get duration() { + return this._duration; + } + get ended() { + return this._ended; + } + get droppedAttributesCount() { + return this._droppedAttributesCount; + } + get droppedEventsCount() { + return this._droppedEventsCount; + } + get droppedLinksCount() { + return this._droppedLinksCount; + } +} +//# sourceMappingURL=span.js.map \ No newline at end of file diff --git a/dist/esm/span.js.map b/dist/esm/span.js.map new file mode 100644 index 0000000..362a13b --- /dev/null +++ b/dist/esm/span.js.map @@ -0,0 +1 @@ +{"version":3,"file":"span.js","sourceRoot":"","sources":["../../src/span.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,QAAQ,EAOR,cAAc,GAEd,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EACN,cAAc,EAEd,cAAc,EACd,gBAAgB,EAChB,WAAW,EACX,kBAAkB,GAClB,MAAM,qBAAqB,CAAA;AAG5B,OAAO,EAAE,kBAAkB,EAAE,MAAM,qCAAqC,CAAA;AAgBxE,SAAS,4BAA4B,CAAC,SAAoB;IACzD,MAAM,UAAU,GAAe,EAAE,CAAA;IACjC,IAAI,OAAO,SAAS,KAAK,QAAQ,EAAE,CAAC;QACnC,UAAU,CAAC,kBAAkB,CAAC,iBAAiB,CAAC,GAAG,SAAS,CAAA;IAC7D,CAAC;SAAM,CAAC;QACP,IAAI,SAAS,CAAC,IAAI,EAAE,CAAC;YACpB,UAAU,CAAC,kBAAkB,CAAC,cAAc,CAAC,GAAG,SAAS,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAA;QAC1E,CAAC;aAAM,IAAI,SAAS,CAAC,IAAI,EAAE,CAAC;YAC3B,UAAU,CAAC,kBAAkB,CAAC,cAAc,CAAC,GAAG,SAAS,CAAC,IAAI,CAAA;QAC/D,CAAC;QACD,IAAI,SAAS,CAAC,OAAO,EAAE,CAAC;YACvB,UAAU,CAAC,kBAAkB,CAAC,iBAAiB,CAAC,GAAG,SAAS,CAAC,OAAO,CAAA;QACrE,CAAC;QACD,IAAI,S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IAAI,CAAC,OAAO,GAAG,SAAS,CAAC,OAAO,CAAC,CAAA;QACjC,IAAI,CAAC,SAAS,GAAG,cAAc,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,CAAA;QAC7D,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;IACjB,CAAC;IAED,WAAW;QACV,OAAO,CAAC,IAAI,CAAC,MAAM,CAAA;IACpB,CAAC;IAED,eAAe,CAAC,SAAoB,EAAE,IAAgB;QACrD,MAAM,UAAU,GAAG,4BAA4B,CAAC,SAAS,CAAC,CAAA;QAC1D,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE,UAAU,EAAE,IAAI,CAAC,CAAA;IAC7C,CAAC;IAED,IAAI,QAAQ;QACX,OAAO,IAAI,CAAC,SAAS,CAAA;IACtB,CAAC;IAED,IAAI,KAAK;QACR,OAAO,IAAI,CAAC,MAAM,CAAA;IACnB,CAAC;IAED,IAAI,sBAAsB;QACzB,OAAO,IAAI,CAAC,uBAAuB,CAAA;IACpC,CAAC;IAED,IAAI,kBAAkB;QACrB,OAAO,IAAI,CAAC,mBAAmB,CAAA;IAChC,CAAC;IAED,IAAI,iBAAiB;QACpB,OAAO,IAAI,CAAC,kBAAkB,CAAA;IAC/B,CAAC;CACD"} \ No newline at end of file diff --git a/dist/esm/spanprocessor.d.ts b/dist/esm/spanprocessor.d.ts new file mode 100644 index 0000000..ba1d7dd --- /dev/null +++ b/dist/esm/spanprocessor.d.ts @@ -0,0 +1,16 @@ +import { Context, Span } from '@opentelemetry/api'; +import { ReadableSpan, SpanExporter, SpanProcessor } from '@opentelemetry/sdk-trace-base'; +export declare class BatchTraceSpanProcessor implements SpanProcessor { + private exporter; + private traceLookup; + private localRootSpanLookup; + private inprogressExports; + constructor(exporter: SpanExporter); + private action; + private export; + onStart(span: Span, parentContext: Context): void; + onEnd(span: ReadableSpan): void; + forceFlush(): Promise; + shutdown(): Promise; +} +//# sourceMappingURL=spanprocessor.d.ts.map \ No newline at end of file diff --git a/dist/esm/spanprocessor.d.ts.map b/dist/esm/spanprocessor.d.ts.map new file mode 100644 index 0000000..b3e224a --- /dev/null +++ b/dist/esm/spanprocessor.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"spanprocessor.d.ts","sourceRoot":"","sources":["../../src/spanprocessor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAS,MAAM,oBAAoB,CAAA;AACzD,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAA;AAiHzF,qBAAa,uBAAwB,YAAW,aAAa;IAKhD,OAAO,CAAC,QAAQ;IAJ5B,OAAO,CAAC,WAAW,CAAwC;IAC3D,OAAO,CAAC,mBAAmB,CAAiC;IAC5D,OAAO,CAAC,iBAAiB,CAAgD;gBAErD,QAAQ,EAAE,YAAY;IAE1C,OAAO,CAAC,MAAM;IAWd,OAAO,CAAC,MAAM;IAoBd,OAAO,CAAC,IAAI,EAAE,IAAI,EAAE,aAAa,EAAE,OAAO,GAAG,IAAI;IAUjD,KAAK,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI;IAczB,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAI3B,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;CAC/B"} \ No newline at end of file diff --git a/dist/esm/spanprocessor.js b/dist/esm/spanprocessor.js new file mode 100644 index 0000000..ec9d9fc --- /dev/null +++ b/dist/esm/spanprocessor.js @@ -0,0 +1,139 @@ +import { trace } from '@opentelemetry/api'; +import { ExportResultCode } from '@opentelemetry/core'; +import { stateMachine } from './vendor/ts-checked-fsm/StateMachine.js'; +import { getActiveConfig } from './config.js'; +function newTrace(currentState, { span }) { + const spanId = span.spanContext().spanId; + return { + ...currentState, + stateName: 'in_progress', + traceId: span.spanContext().traceId, + localRootSpan: span, + completedSpans: [], + inProgressSpanIds: new Set([spanId]), + }; +} +function newSpan(currentState, { span }) { + const spanId = span.spanContext().spanId; + currentState.inProgressSpanIds.add(spanId); + return { ...currentState }; +} +function endSpan(currentState, { span }) { + currentState.completedSpans.push(span); + currentState.inProgressSpanIds.delete(span.spanContext().spanId); + if (currentState.inProgressSpanIds.size === 0) { + return { + stateName: 'trace_complete', + traceId: currentState.traceId, + localRootSpan: currentState.localRootSpan, + completedSpans: currentState.completedSpans, + }; + } + else { + return { ...currentState }; + } +} +function startExport(currentState, { args }) { + const { exporter, tailSampler, postProcessor } = args; + const { traceId, localRootSpan, completedSpans: spans } = currentState; + const shouldExport = tailSampler({ traceId, localRootSpan, spans }); + if (shouldExport) { + const exportSpans = postProcessor(spans); + const promise = new Promise((resolve) => { + exporter.export(exportSpans, resolve); + }); + return { stateName: 'exporting', promise }; + } + else { + return { stateName: 'done' }; + } +} +const { nextState } = stateMachine() + .state('not_started') + .state('in_progress') + .state('trace_complete') + .state('exporting') + .state('done') + .transition('not_started', 'in_progress') + .transition('in_progress', 'in_progress') + .transition('in_progress', 'trace_complete') + .transition('trace_complete', 'exporting') + .transition('trace_complete', 'done') + .transition('exporting', 'done') + .action('startSpan') + .action('endSpan') + .action('startExport') + .action('exportDone') + .actionHandler('not_started', 'startSpan', newTrace) + .actionHandler('in_progress', 'startSpan', newSpan) + .actionHandler('in_progress', 'endSpan', endSpan) + .actionHandler('trace_complete', 'startExport', startExport) + .actionHandler('exporting', 'exportDone', (_c, _a) => { + return { stateName: 'done' }; +}) + .done(); +export class BatchTraceSpanProcessor { + exporter; + traceLookup = new Map(); + localRootSpanLookup = new Map(); + inprogressExports = new Map(); + constructor(exporter) { + this.exporter = exporter; + } + action(localRootSpanId, action) { + const state = this.traceLookup.get(localRootSpanId) || { stateName: 'not_started' }; + const newState = nextState(state, action); + if (newState.stateName === 'done') { + this.traceLookup.delete(localRootSpanId); + } + else { + this.traceLookup.set(localRootSpanId, newState); + } + return newState; + } + export(localRootSpanId) { + const config = getActiveConfig(); + if (!config) + throw new Error('Config is undefined. This is a bug in the instrumentation logic'); + const { sampling, postProcessor } = config; + const exportArgs = { exporter: this.exporter, tailSampler: sampling.tailSampler, postProcessor }; + const newState = this.action(localRootSpanId, { actionName: 'startExport', args: exportArgs }); + if (newState.stateName === 'exporting') { + const promise = newState.promise; + this.inprogressExports.set(localRootSpanId, promise); + promise.then((result) => { + if (result.code === ExportResultCode.FAILED) { + console.log('Error sending spans to exporter:', result.error); + } + this.action(localRootSpanId, { actionName: 'exportDone' }); + this.inprogressExports.delete(localRootSpanId); + }); + } + } + onStart(span, parentContext) { + const spanId = span.spanContext().spanId; + const parentSpanId = trace.getSpan(parentContext)?.spanContext()?.spanId; + const parentRootSpanId = parentSpanId ? this.localRootSpanLookup.get(parentSpanId) : undefined; + const localRootSpanId = parentRootSpanId || spanId; + this.localRootSpanLookup.set(spanId, localRootSpanId); + this.action(localRootSpanId, { actionName: 'startSpan', span }); + } + onEnd(span) { + const spanId = span.spanContext().spanId; + const localRootSpanId = this.localRootSpanLookup.get(spanId); + if (localRootSpanId) { + const state = this.action(localRootSpanId, { actionName: 'endSpan', span }); + if (state.stateName === 'trace_complete') { + state.completedSpans.forEach((span) => { + this.localRootSpanLookup.delete(span.spanContext().spanId); + }); + this.export(localRootSpanId); + } + } + } + async forceFlush() { + await Promise.allSettled(this.inprogressExports.values()); + } + async shutdown() { } +} +//# sourceMappingURL=spanprocessor.js.map \ No newline at end of file diff --git a/dist/esm/spanprocessor.js.map b/dist/esm/spanprocessor.js.map new file mode 100644 index 0000000..ccb1059 --- /dev/null +++ b/dist/esm/spanprocessor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"spanprocessor.js","sourceRoot":"","sources":["../../src/spanprocessor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,KAAK,EAAE,MAAM,oBAAoB,CAAA;AAEzD,OAAO,EAAgB,gBAAgB,EAAE,MAAM,qBAAqB,CAAA;AACpE,OAAO,EAAiB,YAAY,EAAE,MAAM,yCAAyC,CAAA;AAErF,OAAO,EAAE,eAAe,EAAE,MAAM,aA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AAM,eAAe,GAAG,gBAAgB,IAAI,MAAM,CAAA;QAClD,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,MAAM,EAAE,eAAe,CAAC,CAAA;QAErD,IAAI,CAAC,MAAM,CAAC,eAAe,EAAE,EAAE,UAAU,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC,CAAA;IAChE,CAAC;IAED,KAAK,CAAC,IAAkB;QACvB,MAAM,MAAM,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC,MAAM,CAAA;QACxC,MAAM,eAAe,GAAG,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;QAC5D,IAAI,eAAe,EAAE,CAAC;YACrB,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,eAAe,EAAE,EAAE,UAAU,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAA;YAC3E,IAAI,KAAK,CAAC,SAAS,KAAK,gBAAgB,EAAE,CAAC;gBAC1C,KAAK,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;oBACrC,IAAI,CAAC,mBAAmB,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,MAAM,CAAC,CAAA;gBAC3D,CAAC,CAAC,CAAA;gBACF,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,CAAA;YAC7B,CAAC;QACF,CAAC;IACF,CAAC;IAED,KAAK,CAAC,UAAU;QACf,MAAM,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,iBAAiB,CAAC,MAAM,EAAE,CAAC,CAAA;IAC1D,CAAC;IAED,KAAK,CAAC,QAAQ,KAAmB,CAAC;CAClC"} \ No newline at end of file diff --git a/dist/esm/tracer.d.ts b/dist/esm/tracer.d.ts new file mode 100644 index 0000000..e7537d6 --- /dev/null +++ b/dist/esm/tracer.d.ts @@ -0,0 +1,17 @@ +import { Attributes, Tracer, Span, SpanOptions, Context } from '@opentelemetry/api'; +import { Resource } from '@opentelemetry/resources'; +import { SpanProcessor } from '@opentelemetry/sdk-trace-base'; +export declare class WorkerTracer implements Tracer { + private readonly _spanProcessors; + private readonly resource; + private readonly idGenerator; + constructor(spanProcessors: SpanProcessor[], resource: Resource); + get spanProcessors(): SpanProcessor[]; + addToResource(extra: Resource): void; + startSpan(name: string, options?: SpanOptions, context?: Context): Span; + startActiveSpan ReturnType>(name: string, fn: F): ReturnType; + startActiveSpan ReturnType>(name: string, options: SpanOptions, fn: F): ReturnType; + startActiveSpan ReturnType>(name: string, options: SpanOptions, context: Context, fn: F): ReturnType; +} +export declare function withNextSpan(attrs: Attributes): void; +//# sourceMappingURL=tracer.d.ts.map \ No newline at end of file diff --git a/dist/esm/tracer.d.ts.map b/dist/esm/tracer.d.ts.map new file mode 100644 index 0000000..5980d7c --- /dev/null +++ b/dist/esm/tracer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tracer.d.ts","sourceRoot":"","sources":["../../src/tracer.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,UAAU,EACV,MAAM,EAEN,IAAI,EAEJ,WAAW,EACX,OAAO,EAGP,MAAM,oBAAoB,CAAA;AAE3B,OAAO,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAA;AACnD,OAAO,EAAE,aAAa,EAAqD,MAAM,+BAA+B,CAAA;AAOhH,qBAAa,YAAa,YAAW,MAAM;IAC1C,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAiB;IACjD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAU;IACnC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAA6C;gBAC7D,cAAc,EAAE,aAAa,EAAE,EAAE,QAAQ,EAAE,QAAQ;IAK/D,IAAI,cAAc,oBAEjB;IAED,aAAa,CAAC,KAAK,EAAE,QAAQ;IAI7B,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,WAAgB,EAAE,OAAO,UAAuB,GAAG,IAAI;IAiDxF,eAAe,CAAC,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,KAAK,UAAU,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC;IAC5F,eAAe,CAAC,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,KAAK,UAAU,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,EAAE,EAAE,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC;IAClH,eAAe,CAAC,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,KAAK,UAAU,CAAC,CAAC,CAAC,EACtD,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,WAAW,EACpB,OAAO,EAAE,OAAO,EAChB,EAAE,EAAE,CAAC,GACH,UAAU,CAAC,CAAC,CAAC;CAWhB;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,UAAU,QAE7C"} \ No newline at end of file diff --git a/dist/esm/tracer.js b/dist/esm/tracer.js new file mode 100644 index 0000000..1087464 --- /dev/null +++ b/dist/esm/tracer.js @@ -0,0 +1,76 @@ +import { TraceFlags, SpanKind, context as api_context, trace, } from '@opentelemetry/api'; +import { sanitizeAttributes } from '@opentelemetry/core'; +import { RandomIdGenerator, SamplingDecision } from '@opentelemetry/sdk-trace-base'; +import { SpanImpl } from './span.js'; +import { getActiveConfig } from './config.js'; +let withNextSpanAttributes; +export class WorkerTracer { + _spanProcessors; + resource; + idGenerator = new RandomIdGenerator(); + constructor(spanProcessors, resource) { + this._spanProcessors = spanProcessors; + this.resource = resource; + } + get spanProcessors() { + return this._spanProcessors; + } + addToResource(extra) { + this.resource.merge(extra); + } + startSpan(name, options = {}, context = api_context.active()) { + if (options.root) { + context = trace.deleteSpan(context); + } + const parentSpan = trace.getSpan(context); + const parentSpanContext = parentSpan?.spanContext(); + const hasParentContext = parentSpanContext && trace.isSpanContextValid(parentSpanContext); + const traceId = hasParentContext ? parentSpanContext.traceId : this.idGenerator.generateTraceId(); + const spanKind = options.kind || SpanKind.INTERNAL; + const sanitisedAttrs = sanitizeAttributes(options.attributes); + const config = getActiveConfig(); + if (!config) + throw new Error('Config is undefined. This is a bug in the instrumentation logic'); + const sampler = config.sampling.headSampler; + const samplingDecision = sampler.shouldSample(context, traceId, name, spanKind, sanitisedAttrs, []); + const { decision, traceState, attributes: attrs } = samplingDecision; + const attributes = Object.assign({}, sanitisedAttrs, attrs, withNextSpanAttributes); + withNextSpanAttributes = {}; + const spanId = this.idGenerator.generateSpanId(); + const parentSpanId = hasParentContext ? parentSpanContext.spanId : undefined; + const traceFlags = decision === SamplingDecision.RECORD_AND_SAMPLED ? TraceFlags.SAMPLED : TraceFlags.NONE; + const spanContext = { traceId, spanId, traceFlags, traceState }; + const span = new SpanImpl({ + attributes, + name, + onEnd: (span) => { + this.spanProcessors.forEach((sp) => { + sp.onEnd(span); + }); + }, + resource: this.resource, + spanContext, + parentSpanId, + spanKind, + startTime: options.startTime, + }); + this.spanProcessors.forEach((sp) => { + //Do not get me started on the idosyncracies of the Otel JS libraries. + //@ts-ignore + sp.onStart(span, context); + }); + return span; + } + startActiveSpan(name, ...args) { + const options = args.length > 1 ? args[0] : undefined; + const parentContext = args.length > 2 ? args[1] : api_context.active(); + const fn = args[args.length - 1]; + const span = this.startSpan(name, options, parentContext); + const contextWithSpanSet = trace.setSpan(parentContext, span); + return api_context.with(contextWithSpanSet, fn, undefined, span); + } +} +export function withNextSpan(attrs) { + withNextSpanAttributes = Object.assign({}, withNextSpanAttributes, attrs); +} +//# sourceMappingURL=tracer.js.map \ No newline at end of file diff --git a/dist/esm/tracer.js.map b/dist/esm/tracer.js.map new file mode 100644 index 0000000..a8caac0 --- /dev/null +++ b/dist/esm/tracer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tracer.js","sourceRoot":"","sources":["../../src/tracer.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,UAAU,EAEV,QAAQ,EAGR,OAAO,IAAI,WAAW,EACtB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CAAC,CAAA;AAC1E,CAAC"} \ No newline at end of file diff --git a/dist/esm/types.d.ts b/dist/esm/types.d.ts new file mode 100644 index 0000000..86fb8e4 --- /dev/null +++ b/dist/esm/types.d.ts @@ -0,0 +1,61 @@ +import { TextMapPropagator } from '@opentelemetry/api'; +import { ReadableSpan, Sampler, SpanExporter, SpanProcessor } from '@opentelemetry/sdk-trace-base'; +import { OTLPExporterConfig } from './exporter.js'; +import { FetchHandlerConfig, FetcherConfig } from './instrumentation/fetch.js'; +import { TailSampleFn } from './sampling.js'; +export type PostProcessorFn = (spans: ReadableSpan[]) => ReadableSpan[]; +export type ExporterConfig = OTLPExporterConfig | SpanExporter; +export interface HandlerConfig { + fetch?: FetchHandlerConfig; +} +export interface ServiceConfig { + name: string; + namespace?: string; + version?: string; +} +export interface ParentRatioSamplingConfig { + acceptRemote?: boolean; + ratio: number; +} +type HeadSamplerConf = Sampler | ParentRatioSamplingConfig; +export interface SamplingConfig { + headSampler?: HS; + tailSampler?: TailSampleFn; +} +export interface InstrumentationOptions { + instrumentGlobalFetch?: boolean; + instrumentGlobalCache?: boolean; +} +interface TraceConfigBase { + service: ServiceConfig; + handlers?: HandlerConfig; + fetch?: FetcherConfig; + postProcessor?: PostProcessorFn; + sampling?: SamplingConfig; + propagator?: TextMapPropagator; + instrumentation?: InstrumentationOptions; +} +interface TraceConfigExporter extends TraceConfigBase { + exporter: ExporterConfig; +} +interface TraceConfigSpanProcessors extends TraceConfigBase { + spanProcessors: SpanProcessor | SpanProcessor[]; +} +export type TraceConfig = TraceConfigExporter | TraceConfigSpanProcessors; +export declare function isSpanProcessorConfig(config: TraceConfig): config is TraceConfigSpanProcessors; +export interface ResolvedTraceConfig extends TraceConfigBase { + handlers: Required; + fetch: Required; + postProcessor: PostProcessorFn; + sampling: Required>; + spanProcessors: SpanProcessor[]; + propagator: TextMapPropagator; + instrumentation: InstrumentationOptions; +} +export interface DOConstructorTrigger { + id: string; + name?: string; +} +export type Trigger = Request | MessageBatch | ScheduledController | DOConstructorTrigger | 'do-alarm'; +export {}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/dist/esm/types.d.ts.map b/dist/esm/types.d.ts.map new file mode 100644 index 0000000..2557200 --- /dev/null +++ b/dist/esm/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAA;AACtD,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAA;AAClG,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAA;AAClD,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAA;AAC9E,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAA;AAE5C,MAAM,MAAM,eAAe,GAAG,CAAC,KAAK,EAAE,YAAY,EAAE,KAAK,YAAY,EAAE,CAAA;AAEvE,MAAM,MAAM,cAAc,GAAG,kBAAkB,GAAG,YAAY,CAAA;AAE9D,MAAM,WAAW,aAAa;IAC7B,KAAK,CAAC,EAAE,kBAAkB,CAAA;CAC1B;AAED,MAAM,WAAW,aAAa;IAC7B,IAAI,EAAE,MAAM,CAAA;IACZ,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,OAAO,CAAC,EAAE,MAAM,CAAA;CAChB;AAED,MAAM,WAAW,yBAAyB;IACzC,YAAY,CAAC,EAAE,OAAO,CAAA;IACtB,KAAK,EAAE,MAAM,CAAA;CACb;AAED,KAAK,eAAe,GAAG,OAAO,GAAG,yBAAyB,CAAA;AAC1D,MAAM,WAAW,cAAc,CAAC,EAAE,SAAS,eAAe,GAAG,eAAe;IAC3E,WAAW,CAAC,EAAE,EAAE,CAAA;IAChB,WAAW,CAAC,EAAE,YAAY,CAAA;CAC1B;AAED,MAAM,WAAW,sBAAsB;IACtC,qBAAqB,CAAC,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100644 index 0000000..d94e021 --- /dev/null +++ b/dist/esm/types.js @@ -0,0 +1,4 @@ +export function isSpanProcessorConfig(config) { + return !!config.spanProcessors; +} +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/dist/esm/types.js.map b/dist/esm/types.js.map new file mode 100644 index 0000000..95e8a43 --- /dev/null +++ b/dist/esm/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAwDA,MAAM,UAAU,qBAAqB,CAAC,MAAmB;IACxD,OAAO,CAAC,CAAE,MAAoC,CAAC,cAAc,CAAA;AAC9D,CAAC"} \ No newline at end of file diff --git a/dist/esm/vendor/ts-checked-fsm/StateMachine.d.ts b/dist/esm/vendor/ts-checked-fsm/StateMachine.d.ts new file mode 100644 index 0000000..db591ea --- /dev/null +++ b/dist/esm/vendor/ts-checked-fsm/StateMachine.d.ts @@ -0,0 +1,104 @@ +/** + * State labels can be strings + */ +type StateType = IndexType; +/** + * Action labels can be strings + */ +export type ActionNameType = IndexType; +/** + * Represents a state and data and its corresponding data. + */ +export type State = Readonly & { + readonly stateName: S; +}; +/** + * Give Actions to nextState() to (maybe) trigger a transition. + */ +export type Action = Readonly & { + readonly actionName: Name; +}; +/** + * Represents a compiler error message. Error brands prevent really clever users from naming their states as one of the error messages + * and subverting error checking. Yet, the compiler still displays the string at the end of the failed cast indicating what the + * issue is rather than something puzzling like could not assign to never. + */ +type ErrorBrand = { + [k in T]: void; +}; +type IndexType = string | number; +type AssertStateInMap = S extends MapKeys ? S : ErrorBrand<`'${S}' is not a state`>; +type AssertNewState = S extends MapKeys ? ErrorBrand<`'${S}' has already been declared`> : S; +type AssertNewTransition = N extends MapLookup ? ErrorBrand<`There already exists a transition from '${S}' to '${N}'`> : N; +type AssertActionNotDefined = AN extends ActionNames ? ErrorBrand<`Action '${AN}' already declared`> : AN; +type AssertActionIsDefined = AN extends ActionNames ? AN : ErrorBrand<`'${AN}' is not an action`>; +type AssertAllNonTerminalStatesHandled = MapKeys extends HandledStates ? void : ErrorBrand<`No handlers declared for ${Exclude, HandledStates>}`>; +type AddToTypeMap = M | [K, V]; +type MapLookup = Map extends [K, infer V] ? V : never; +type MapKeys = Map extends [infer K, infer _] ? (K extends IndexType ? K : never) : never; +type MapValues = Map extends [infer _, infer V] ? V : never; +/** + * A builder from calling stateMachine(). + */ +export type StateMachineBuilder = { + /** + * Add a state to this state machine. + */ + readonly state: StateFunc; +}; +type StateMachineFunc = () => StateMachineBuilder; +/** + * A builder from calling .state() + */ +export type StateBuilder = { + /** + * Add a state to this state machine. + */ + readonly state: StateFunc; + readonly transition: TransitionFunc; +}; +/** + * The signature for calling the state function in the builder. + */ +type StateFunc = (state: AssertNewState) => StateBuilder>>; +/** + * The builder returned by .transition() + */ +export type TransitionBuilder = { + /** + * Add a transition to this state machine. + */ + readonly transition: TransitionFunc; + readonly action: ActionFunc; +}; +/** + * The signature of .transition() + */ +export type TransitionFunc = (curState: AssertStateInMap, nextState: N extends MapKeys ? AssertNewTransition : ErrorBrand<`${S} is not a declared state`>) => TransitionBuilder>; +export type ActionBuilder = { + readonly action: ActionFunc; + readonly actionHandler: ActionHandlerFunc; +}; +export type ActionFunc = (actionName: AssertActionNotDefined>) => ActionBuilder>>; +/** + * The builder returned by .actionHandler() + */ +export type ActionHandlersBuilder = { + readonly actionHandler: ActionHandlerFunc; + readonly done: DoneFunc; +}; +/** + * The Signature of .actionHandler(). + */ +export type ActionHandlerFunc = >(state: AssertStateInMap, action: AssertActionIsDefined>, handler: ActionHandlerCallback) => ActionHandlersBuilder; +type ActionHandlerCallback, Actions> = (state: MapLookup, action: MapLookup) => NS extends State ? N extends MapKeys ? CS extends MapKeys ? N extends MapLookup ? State : ErrorBrand<`No transition declared between ${CS} and ${N}`> : ErrorBrand<`State ${CS} is terminal and has no transitions`> : ErrorBrand<`${N} is not a state`> : ErrorBrand<'The returned value is not a state'>; +type DoneFunc = (_: AssertAllNonTerminalStatesHandled) => StateMachine; +/** + * A state machine + */ +export type StateMachine = { + nextState: (curState: MapValues, action: MapValues) => MapValues; +}; +export declare const stateMachine: StateMachineFunc; +export {}; +//# sourceMappingURL=StateMachine.d.ts.map \ No newline at end of file diff --git a/dist/esm/vendor/ts-checked-fsm/StateMachine.d.ts.map b/dist/esm/vendor/ts-checked-fsm/StateMachine.d.ts.map new file mode 100644 index 0000000..a53ce47 --- /dev/null +++ b/dist/esm/vendor/ts-checked-fsm/StateMachine.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"StateMachine.d.ts","sourceRoot":"","sources":["../../../../src/vendor/ts-checked-fsm/StateMachine.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,KAAK,SAAS,GAAG,SAAS,CAAA;AAE1B;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG,SAAS,CAAA;AAEtC;;GAEG;AACH,MAAM,MAAM,KAAK,CAAC,CAAC,SAAS,SAAS,EAAE,CAAC,GAAG,EAAE,IAAI,QAAQ,CAAC,CAAC,CAAC,GAAG;IAC9D,QAAQ,CAAC,SAAS,EAAE,CAAC,CAAA;CACrB,CAAA;AAED;;GAEG;AACH,MAAM,MAAM,MAAM,CAAC,IAAI,SAAS,cAAc,EAAE,OAAO,IAAI,QAAQ,CAAC,OAAO,CAAC,GAAG;IAC9E,QAAQ,CAAC,UAAU,EAAE,IAAI,CAAA;CACzB,CAAA;AAMD;;;;GAIG;AACH,KAAK,UAAU,CAAC,CAAC,SAAS,SAAS,IAAI;KAAG,CAAC,IAAI,CAAC,GAAG,IAAI;CAAE,CAAA;AAEzD,KAAK,SAAS,GAAG,MAAM,GAAG,MAAM,CAAA;AAGhC,KAAK,gBAAgB,CAAC,QAAQ,EAAE,CAAC,SAAS,SAAS,IAClD,CAAC,SAAS,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,UAAU,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAA;AACtE,KAAK,cAAc,CAAC,CAAC,SAAS,SAAS,EAAE,MAAM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AE,WAAW,EAAE,aAAa,IAAI,CAChE,CAAC,EAAE,iCAAiC,CAAC,WAAW,EAAE,aAAa,CAAC,KAC5D,YAAY,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAA;AAEtC;;GAEG;AACH,MAAM,MAAM,YAAY,CAAC,QAAQ,EAAE,SAAS,IAAI;IAC/C,SAAS,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,SAAS,CAAC,SAAS,CAAC,KAAK,SAAS,CAAC,QAAQ,CAAC,CAAA;CAC/F,CAAA;AAED,eAAO,MAAM,YAAY,EAAE,gBAM1B,CAAA"} \ No newline at end of file diff --git a/dist/esm/vendor/ts-checked-fsm/StateMachine.js b/dist/esm/vendor/ts-checked-fsm/StateMachine.js new file mode 100644 index 0000000..57bcebe --- /dev/null +++ b/dist/esm/vendor/ts-checked-fsm/StateMachine.js @@ -0,0 +1,83 @@ +export const stateMachine = () => { + const stateFunc = state(); + return { + state: stateFunc, + }; +}; +const state = () => { + return (_s) => { + const transitionFunc = transition(); + const stateFunc = state(); + const builder = { + state: stateFunc, + transition: transitionFunc, + }; + return builder; + }; +}; +const transition = () => { + return (_curState, _next) => { + const transitionFunction = transition(); + const actionFunc = action(); + return { + transition: transitionFunction, + action: actionFunc, + }; + }; +}; +const action = () => { + return (_actionName) => { + const actionFunc = action(); + const actionHandlerFunc = actionHandler({ handlers: {} }); + return { + action: actionFunc, + actionHandler: actionHandlerFunc, + }; + }; +}; +const actionHandler = (definition) => { + return (state, action, handler) => { + const untypedState = state; + const untypedAction = action; + const newDefinition = { + ...definition, + handlers: { + ...definition.handlers, + [untypedState]: { + ...(definition.handlers[untypedState] ? definition.handlers[untypedState] : {}), + [untypedAction]: handler, + }, + }, + }; + const doneFunc = done(newDefinition); + const actionHandlerFunc = actionHandler(newDefinition); + return { + actionHandler: actionHandlerFunc, + done: doneFunc, + }; + }; +}; +const done = (definition) => { + const doneFunc = (_) => { + const nextStateFunction = (curState, action) => { + const curStateAsState = curState; + const actionAsAction = action; + // If no handler declared for state, state doesn't change. + if (definition.handlers[curStateAsState.stateName] == null) { + return curState; + } + // If no handler declared for action in given state, state doesn't change. + const handler = definition.handlers[curStateAsState.stateName]; + if (handler === undefined) { + return curState; + } + const nextAction = handler[actionAsAction.actionName]; + return nextAction != null ? nextAction(curState, action) : curState; + }; + return { + nextState: nextStateFunction, + }; + }; + return doneFunc; +}; +//# sourceMappingURL=StateMachine.js.map \ No newline at end of file diff --git a/dist/esm/vendor/ts-checked-fsm/StateMachine.js.map b/dist/esm/vendor/ts-checked-fsm/StateMachine.js.map new file mode 100644 index 0000000..e43dec9 --- /dev/null +++ b/dist/esm/vendor/ts-checked-fsm/StateMachine.js.map @@ -0,0 +1 @@ +{"version":3,"file":"StateMachine.js","sourceRoot":"","sources":["../../../../src/vendor/ts-checked-fsm/StateMachine.ts"],"names":[],"mappings":"AAuNA,MAAM,CAAC,MAAM,YAAY,GAAqB,GAAwB,EAAE;IACvE,MAAM,SAAS,GAAG,KAAK,EAAS,CAAA;IAEhC,OAAO;QACN,KAAK,EAAE,SAAS;KAChB,CAAA;AACF,CAAC,CAAA;AAED,MAAM,KAAK,GAAG,GAAkC,EAAE;IACjD,OAAO,CAA8B,EAA+B,EAAE,EAAE;QAGvE,MAAM,cAAc,GAAG,UAAU,EAAsB,CAAA;QACvD,MAAM,SAAS,GAAG,KAAK,EAAe,CAAA;QAEtC,MAAM,OAAO,GAAG;YACf,KAAK,EAAE,SAAS;YAChB,UAAU,EAAE,cAAc;SAC1B,CAAA;QAED,OAAO,OAAO,CAAA;IACf,CAAC,CAAA;AACF,CAAC,CAAA;AAED,MAAM,UAAU,GAAG,GAAiE,EAAE;IACrF,OAAO,CACN,SAAwC,EACxC,KAE6C,EAC5C,EAAE;QAGH,MAAM,kBAAkB,GAAG,UAAU,EAA4B,CAAA;QACjE,MAAM,UAAU,GAAG,MAAM,EAAmC,CAAA;QAE5D,OAAO;YACN,UAAU,EAAE,kB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AAM,iBAAiB,GAAG,CAAC,QAA6B,EAAE,MAA4B,EAAuB,EAAE;YAC9G,MAAM,eAAe,GAAG,QAAwC,CAAA;YAChE,MAAM,cAAc,GAAG,MAAuC,CAAA;YAE9D,0DAA0D;YAC1D,IAAI,UAAU,CAAC,QAAQ,CAAC,eAAe,CAAC,SAAS,CAAC,IAAI,IAAI,EAAE,CAAC;gBAC5D,OAAO,QAAQ,CAAA;YAChB,CAAC;YAED,0EAA0E;YAC1E,MAAM,OAAO,GAAG,UAAU,CAAC,QAAQ,CAAC,eAAe,CAAC,SAAS,CAAC,CAAA;YAC9D,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;gBAC3B,OAAO,QAAQ,CAAA;YAChB,CAAC;YACD,MAAM,UAAU,GAAG,OAAO,CAAC,cAAc,CAAC,UAAU,CAAC,CAAA;YAErD,OAAO,UAAU,IAAI,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAA;QACpE,CAAC,CAAA;QAED,OAAO;YACN,SAAS,EAAE,iBAAiB;SAC5B,CAAA;IACF,CAAC,CAAA;IAED,OAAO,QAAQ,CAAA;AAChB,CAAC,CAAA"} \ No newline at end of file diff --git a/dist/esm/wrap.d.ts b/dist/esm/wrap.d.ts new file mode 100644 index 0000000..a318610 --- /dev/null +++ b/dist/esm/wrap.d.ts @@ -0,0 +1,11 @@ +declare const unwrapSymbol: unique symbol; +type Wrapped = { + [unwrapSymbol]: T; +} & T; +export declare function isWrapped(item: T): item is Wrapped; +export declare function isProxyable(item: any): boolean; +export declare function wrap(item: T, handler: ProxyHandler, autoPassthrough?: boolean): T; +export declare function unwrap(item: T): T; +export declare function passthroughGet(target: any, prop: string | symbol, thisArg?: any): any; +export {}; +//# sourceMappingURL=wrap.d.ts.map \ No newline at end of file diff --git a/dist/esm/wrap.d.ts.map b/dist/esm/wrap.d.ts.map new file mode 100644 index 0000000..0ee44b1 --- /dev/null +++ b/dist/esm/wrap.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"wrap.d.ts","sourceRoot":"","sources":["../../src/wrap.ts"],"names":[],"mappings":"AAAA,QAAA,MAAM,YAAY,eAAmB,CAAA;AAErC,KAAK,OAAO,CAAC,CAAC,IAAI;IAAE,CAAC,YAAY,CAAC,EAAE,CAAC,CAAA;CAAE,GAAG,CAAC,CAAA;AAE3C,wBAAgB,SAAS,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,GAAG,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,CAExD;AAED,wBAAgB,WAAW,CAAC,IAAI,EAAE,GAAG,WAEpC;AAED,wBAAgB,IAAI,CAAC,CAAC,SAAS,MAAM,EAAE,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,EAAE,eAAe,GAAE,OAAc,GAAG,CAAC,CAwB5G;AAED,wBAAgB,MAAM,CAAC,CAAC,SAAS,MAAM,EAAE,IAAI,EAAE,CAAC,GAAG,CAAC,CAMnD;AAED,wBAAgB,cAAc,CAAC,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,OAY/E"} \ No newline at end of file diff --git a/dist/esm/wrap.js b/dist/esm/wrap.js new file mode 100644 index 0000000..e9a41d7 --- /dev/null +++ b/dist/esm/wrap.js @@ -0,0 +1,58 @@ +const unwrapSymbol = Symbol('unwrap'); +export function isWrapped(item) { + return item && !!item[unwrapSymbol]; +} +export function isProxyable(item) { + return (item !== null && typeof item === 'object') || typeof item === 'function'; +} +export function wrap(item, handler, autoPassthrough = true) { + if (isWrapped(item) || !isProxyable(item)) { + return item; + } + const proxyHandler = Object.assign({}, handler); + proxyHandler.get = (target, prop, receiver) => { + if (prop === unwrapSymbol) { + return item; + } + else { + if (handler.get) { + return handler.get(target, prop, receiver); + } + else if (prop === 'bind') { + return () => receiver; + } + else if (autoPassthrough) { + return passthroughGet(target, prop); + } + } + }; + proxyHandler.apply = (target, thisArg, argArray) => { + if (handler.apply) { + return handler.apply(unwrap(target), unwrap(thisArg), argArray); + } + }; + return new Proxy(item, proxyHandler); +} +export function unwrap(item) { + if (item && isWrapped(item)) { + return item[unwrapSymbol]; + } + else { + return item; + } +} +export function passthroughGet(target, prop, thisArg) { + const unwrappedTarget = unwrap(target); + const value = Reflect.get(unwrappedTarget, prop); + if (typeof value === 'function') { + if (value.constructor.name === 'RpcProperty') { + return (...args) => unwrappedTarget[prop](...args); + } + thisArg = thisArg || unwrappedTarget; + return value.bind(thisArg); + } + else { + return value; + } +} +//# sourceMappingURL=wrap.js.map \ No newline at end of file diff --git a/dist/esm/wrap.js.map b/dist/esm/wrap.js.map new file mode 100644 index 0000000..017c2cf --- /dev/null +++ b/dist/esm/wrap.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wrap.js","sourceRoot":"","sources":["../../src/wrap.ts"],"names":[],"mappings":"AAAA,MAAM,YAAY,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAA;AAIrC,MAAM,UAAU,SAAS,CAAI,IAAO;IACnC,OAAO,IAAI,IAAI,CAAC,CAAE,IAAmB,CAAC,YAAY,CAAC,CAAA;AACpD,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,IAAS;IACpC,OAAO,CAAC,IAAI,KAAK,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,CAAC,IAAI,OAAO,IAAI,KAAK,UAAU,CAAA;AACjF,CAAC;AAED,MAAM,UAAU,IAAI,CAAmB,IAAO,EAAE,OAAwB,EAAE,kBAA2B,IAAI;IACxG,IAAI,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC;QAC3C,OAAO,IAAI,CAAA;IACZ,CAAC;IACD,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,OAAO,CAAC,CAAA;IAC/C,YAAY,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,I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