@prairielearn/opentelemetry 2.1.9 → 2.1.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/dist/init.js +4 -5
- package/dist/init.js.map +1 -1
- package/dist/metrics.d.ts +1 -1
- package/dist/metrics.js.map +1 -1
- package/dist/metrics.test.js +2 -2
- package/dist/metrics.test.js.map +1 -1
- package/dist/tracing.test.js +1 -1
- package/dist/tracing.test.js.map +1 -1
- package/package.json +24 -24
- package/src/init.ts +14 -15
- package/src/metrics.test.ts +3 -3
- package/src/metrics.ts +5 -5
- package/src/tracing.test.ts +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# @prairielearn/opentelemetry
|
|
2
2
|
|
|
3
|
+
## 2.1.11
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 984dc62: Upgrade all JavaScript dependencies
|
|
8
|
+
|
|
9
|
+
## 2.1.10
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- 49bb3fa: Upgrade all JavaScript dependencies
|
|
14
|
+
- 16c6dd4: Upgrade all `@opentelemetry` dependencies
|
|
15
|
+
|
|
3
16
|
## 2.1.9
|
|
4
17
|
|
|
5
18
|
### Patch Changes
|
package/dist/init.js
CHANGED
|
@@ -7,15 +7,15 @@ import { OTLPTraceExporter as OTLPTraceExporterHttp } from '@opentelemetry/expor
|
|
|
7
7
|
import { AwsInstrumentation } from '@opentelemetry/instrumentation-aws-sdk';
|
|
8
8
|
import { ConnectInstrumentation } from '@opentelemetry/instrumentation-connect';
|
|
9
9
|
import { DnsInstrumentation } from '@opentelemetry/instrumentation-dns';
|
|
10
|
-
import {
|
|
10
|
+
import { ExpressInstrumentation, ExpressLayerType } from '@opentelemetry/instrumentation-express';
|
|
11
11
|
import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
|
|
12
12
|
import { IORedisInstrumentation } from '@opentelemetry/instrumentation-ioredis';
|
|
13
13
|
import { PgInstrumentation } from '@opentelemetry/instrumentation-pg';
|
|
14
14
|
import { RedisInstrumentation } from '@opentelemetry/instrumentation-redis';
|
|
15
15
|
import { awsEc2Detector } from '@opentelemetry/resource-detector-aws';
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
16
|
+
import { Resource, detectResourcesSync, envDetector, processDetector, } from '@opentelemetry/resources';
|
|
17
|
+
import { AggregationTemporality, ConsoleMetricExporter, MeterProvider, PeriodicExportingMetricReader, } from '@opentelemetry/sdk-metrics';
|
|
18
|
+
import { AlwaysOffSampler, AlwaysOnSampler, BatchSpanProcessor, ConsoleSpanExporter, ParentBasedSampler, SimpleSpanProcessor, TraceIdRatioBasedSampler, } from '@opentelemetry/sdk-trace-base';
|
|
19
19
|
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
|
|
20
20
|
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';
|
|
21
21
|
/**
|
|
@@ -124,7 +124,6 @@ function getTraceExporter(config) {
|
|
|
124
124
|
credentials: credentials.createSsl(),
|
|
125
125
|
metadata: getHoneycombMetadata(config),
|
|
126
126
|
});
|
|
127
|
-
break;
|
|
128
127
|
case 'jaeger':
|
|
129
128
|
return new OTLPTraceExporterHttp();
|
|
130
129
|
default:
|
package/dist/init.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.js","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAuB,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAAE,kBAAkB,EAAE,MAAM,2CAA2C,CAAC;AAC/E,OAAO,EAAE,iBAAiB,EAAE,MAAM,yCAA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,CAAC;oBAChC,QAAQ,EAAE,cAAc;oBACxB,oBAAoB,EAAE,MAAM,CAAC,uCAAuC,IAAI,MAAM;iBAC/E,CAAC;aACH;SACF,CAAC,CAAC;QACH,OAAO,CAAC,sBAAsB,CAAC,aAAa,CAAC,CAAC;IAChD,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,QAAQ;IAC5B,IAAI,cAAc,EAAE,CAAC;QACnB,MAAM,cAAc,CAAC,QAAQ,EAAE,CAAC;QAChC,cAAc,GAAG,IAAI,CAAC;IACxB,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,uBAAuB;IACrC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;AAC/C,CAAC","sourcesContent":["import { Metadata, credentials } from '@grpc/grpc-js';\nimport { type ContextManager, metrics } from '@opentelemetry/api';\nimport { hrTimeToMilliseconds } from '@opentelemetry/core';\nimport { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-grpc';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc';\nimport { OTLPTraceExporter as OTLPTraceExporterHttp } from '@opentelemetry/exporter-trace-otlp-http';\nimport { AwsInstrumentation } from '@opentelemetry/instrumentation-aws-sdk';\nimport { ConnectInstrumentation } from '@opentelemetry/instrumentation-connect';\nimport { DnsInstrumentation } from '@opentelemetry/instrumentation-dns';\nimport { ExpressLayerType, ExpressInstrumentation } from '@opentelemetry/instrumentation-express';\nimport { HttpInstrumentation } from '@opentelemetry/instrumentation-http';\nimport { IORedisInstrumentation } from '@opentelemetry/instrumentation-ioredis';\nimport { PgInstrumentation } from '@opentelemetry/instrumentation-pg';\nimport { RedisInstrumentation } from '@opentelemetry/instrumentation-redis';\nimport { awsEc2Detector } from '@opentelemetry/resource-detector-aws';\nimport {\n detectResourcesSync,\n processDetector,\n envDetector,\n Resource,\n} from '@opentelemetry/resources';\nimport {\n PeriodicExportingMetricReader,\n MeterProvider,\n type PushMetricExporter,\n ConsoleMetricExporter,\n AggregationTemporality,\n} from '@opentelemetry/sdk-metrics';\nimport {\n type SpanExporter,\n type ReadableSpan,\n type SpanProcessor,\n SimpleSpanProcessor,\n BatchSpanProcessor,\n ParentBasedSampler,\n TraceIdRatioBasedSampler,\n AlwaysOnSampler,\n AlwaysOffSampler,\n type Sampler,\n ConsoleSpanExporter,\n} from '@opentelemetry/sdk-trace-base';\nimport { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';\nimport { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';\n\n/**\n * Extends `BatchSpanProcessor` to give it the ability to filter out spans\n * before they're queued up to send. This enhances our sampling process so\n * that we can filter spans _after_ they've been emitted.\n */\nclass FilterBatchSpanProcessor extends BatchSpanProcessor {\n private filter: (span: ReadableSpan) => boolean;\n\n constructor(exporter: SpanExporter, filter: (span: ReadableSpan) => boolean) {\n super(exporter);\n this.filter = filter;\n }\n\n /**\n * This is invoked after a span is \"finalized\". `super.onEnd` will queue up\n * the span to be exported, but if we don't call that, we can just drop the\n * span and the parent will be none the wiser!\n */\n onEnd(span: ReadableSpan) {\n if (!this.filter(span)) return;\n\n super.onEnd(span);\n }\n}\n\n/**\n * This will be used with our {@link FilterBatchSpanProcessor} to filter out\n * events that we're not interested in. This helps reduce our event volume\n * but still gives us fine-grained control over which events we keep.\n */\nfunction filter(span: ReadableSpan) {\n if (span.name === 'pg-pool.connect') {\n // Looking at historical data, this generally happens in under a millisecond,\n // precisely because we maintain a pool of long-lived connections. The only\n // time obtaining a client should take longer than that is if we're\n // establishing a connection for the first time, which should happen only at\n // bootup, or if a connection errors out. Those are the cases we're\n // interested in, so we'll filter accordingly.\n return hrTimeToMilliseconds(span.duration) > 1;\n }\n\n // Always return true so that we default to including a span.\n return true;\n}\n\n// When adding new instrumentation here, add the corresponding packages to\n// `commonjs-preloads.ts` so that we can ensure that they're loaded via CJS\n// before anything tries to load them via CJS. This is necessary because the\n// instrumentations can't hook into the ESM loader.\nconst instrumentations = [\n new AwsInstrumentation(),\n new ConnectInstrumentation(),\n new DnsInstrumentation(),\n new ExpressInstrumentation({\n // We use a lot of middleware; it makes the traces way too noisy. If we\n // want telemetry on a particular middleware, we should instrument it\n // manually.\n ignoreLayersType: [ExpressLayerType.MIDDLEWARE],\n ignoreLayers: [\n // These don't provide useful information to us.\n 'router - /',\n 'request handler - /*',\n ],\n }),\n new HttpInstrumentation({\n ignoreIncomingRequestHook(req) {\n return [\n // socket.io requests are generally just long-polling; they don't add\n // useful information for us.\n /\\/socket.io\\//,\n // We get several of these per second; they just chew through our event quota.\n // They don't really do anything interesting anyways.\n /\\/pl\\/webhooks\\/ping/,\n ].some((re) => re.test(req.url ?? '/'));\n },\n }),\n new IORedisInstrumentation(),\n new PgInstrumentation(),\n new RedisInstrumentation(),\n];\n\n// Enable all instrumentations now, even though we haven't configured our\n// span processors or trace exporters yet. We'll set those up later.\ninstrumentations.forEach((i) => {\n i.enable();\n});\n\nlet tracerProvider: NodeTracerProvider | null;\n\ninterface OpenTelemetryConfigEnabled {\n openTelemetryEnabled: boolean;\n openTelemetryExporter?: 'console' | 'honeycomb' | 'jaeger' | SpanExporter | null;\n openTelemetryMetricExporter?: 'console' | 'honeycomb' | PushMetricExporter | null;\n openTelemetryMetricExportIntervalMillis?: number;\n openTelemetrySamplerType: 'always-on' | 'always-off' | 'trace-id-ratio';\n openTelemetrySampleRate?: number;\n openTelemetrySpanProcessor?: 'batch' | 'simple' | SpanProcessor;\n contextManager?: ContextManager;\n honeycombApiKey?: string | null;\n honeycombDataset?: string | null;\n serviceName?: string;\n}\n\n// When we know for sure that OpenTelemetry is disabled, we won't require\n// any other attributes to be set.\ninterface OpenTelemetryConfigDisabled extends Partial<OpenTelemetryConfigEnabled> {\n openTelemetryEnabled: false;\n}\n\nexport type OpenTelemetryConfig = OpenTelemetryConfigEnabled | OpenTelemetryConfigDisabled;\n\nfunction getHoneycombMetadata(config: OpenTelemetryConfig, datasetSuffix = ''): Metadata {\n if (!config.honeycombApiKey) throw new Error('Missing Honeycomb API key');\n if (!config.honeycombDataset) throw new Error('Missing Honeycomb dataset');\n\n const metadata = new Metadata();\n\n metadata.set('x-honeycomb-team', config.honeycombApiKey);\n metadata.set('x-honeycomb-dataset', config.honeycombDataset + datasetSuffix);\n\n return metadata;\n}\n\nfunction getTraceExporter(config: OpenTelemetryConfig): SpanExporter | null {\n if (!config.openTelemetryExporter) return null;\n\n if (typeof config.openTelemetryExporter === 'object') {\n return config.openTelemetryExporter;\n }\n\n switch (config.openTelemetryExporter) {\n case 'console':\n return new ConsoleSpanExporter();\n case 'honeycomb':\n return new OTLPTraceExporter({\n url: 'grpc://api.honeycomb.io:443/',\n credentials: credentials.createSsl(),\n metadata: getHoneycombMetadata(config),\n });\n break;\n case 'jaeger':\n return new OTLPTraceExporterHttp();\n default:\n throw new Error(`Unknown OpenTelemetry exporter: ${config.openTelemetryExporter}`);\n }\n}\n\nfunction getMetricExporter(config: OpenTelemetryConfig): PushMetricExporter | null {\n if (!config.openTelemetryMetricExporter) return null;\n\n if (typeof config.openTelemetryMetricExporter === 'object') {\n return config.openTelemetryMetricExporter;\n }\n\n switch (config.openTelemetryMetricExporter) {\n case 'console':\n return new ConsoleMetricExporter();\n case 'honeycomb':\n return new OTLPMetricExporter({\n url: 'grpc://api.honeycomb.io:443/',\n credentials: credentials.createSsl(),\n // Honeycomb recommends using a separate dataset for metrics, so we'll\n // adopt the convention of appending '-metrics' to the dataset name.\n metadata: getHoneycombMetadata(config, '-metrics'),\n // Delta temporality means that sums, histograms, etc. will reset each\n // time data is collected. This more closely matches how we want to\n // observe our metrics than the default cumulative temporality.\n temporalityPreference: AggregationTemporality.DELTA,\n });\n default:\n throw new Error(\n `Unknown OpenTelemetry metric exporter: ${config.openTelemetryMetricExporter}`,\n );\n }\n}\n\nfunction getSpanProcessor(config: OpenTelemetryConfig): SpanProcessor | null {\n if (typeof config.openTelemetrySpanProcessor === 'object') {\n return config.openTelemetrySpanProcessor;\n }\n\n const traceExporter = getTraceExporter(config);\n if (!traceExporter) return null;\n\n switch (config.openTelemetrySpanProcessor ?? 'batch') {\n case 'batch': {\n return new FilterBatchSpanProcessor(traceExporter, filter);\n }\n case 'simple': {\n return new SimpleSpanProcessor(traceExporter);\n }\n default: {\n throw new Error(`Unknown OpenTelemetry span processor: ${config.openTelemetrySpanProcessor}`);\n }\n }\n}\n\n/**\n * Should be called once we've loaded our config; this will allow us to set up\n * the correct metadata for the Honeycomb exporter. We don't actually have that\n * information available until we've loaded our config.\n */\nexport async function init(config: OpenTelemetryConfig) {\n if (!config.openTelemetryEnabled) {\n // If not enabled, do nothing. We used to disable the instrumentations, but\n // per maintainers, that can actually be problematic. See the comments on\n // https://github.com/open-telemetry/opentelemetry-js-contrib/issues/970\n // The Express instrumentation also logs a benign error, which can be\n // confusing to users. There's a fix in progress if we want to switch back\n // to disabling instrumentations in the future:\n // https://github.com/open-telemetry/opentelemetry-js-contrib/pull/972\n return;\n }\n\n const metricExporter = getMetricExporter(config);\n const spanProcessor = getSpanProcessor(config);\n\n let sampler: Sampler;\n switch (config.openTelemetrySamplerType ?? 'always-on') {\n case 'always-on': {\n sampler = new AlwaysOnSampler();\n break;\n }\n case 'always-off': {\n sampler = new AlwaysOffSampler();\n break;\n }\n case 'trace-id-ratio': {\n sampler = new ParentBasedSampler({\n root: new TraceIdRatioBasedSampler(config.openTelemetrySampleRate),\n });\n break;\n }\n default:\n throw new Error(`Unknown OpenTelemetry sampler type: ${config.openTelemetrySamplerType}`);\n }\n\n // Much of this functionality is copied from `@opentelemetry/sdk-node`, but\n // we can't use the SDK directly because of the fact that we load our config\n // asynchronously. We need to initialize our instrumentations first; only\n // then can we actually start requiring all of our code that loads our config\n // and ultimately tells us how to configure OpenTelemetry.\n\n let resource = detectResourcesSync({\n // The AWS resource detector always tries to reach out to the EC2 metadata\n // service endpoint. When running locally, or otherwise in a non-AWS environment,\n // this will typically fail immediately wih `EHOSTDOWN`, but will sometimes wait\n // 5 seconds before failing with a network timeout error. This causes problems\n // when running tests, as 5 seconds is longer than Mocha lets tests and hooks run\n // for by default. This causes nondeterministic test failures when the EC2 metadata\n // request fails with a network timeout.\n //\n // To work around this, the AWS resource detector is only enabled when running in\n // a production environment. In general this is reasonable, as we only care about\n // AWS resource detection in production-like environments.\n detectors: [\n process.env.NODE_ENV === 'production' ? awsEc2Detector : null,\n processDetector,\n envDetector,\n ].filter((d) => !!d),\n });\n\n if (config.serviceName) {\n resource = resource.merge(\n new Resource({ [SemanticResourceAttributes.SERVICE_NAME]: config.serviceName }),\n );\n }\n\n // Set up tracing instrumentation.\n const nodeTracerProvider = new NodeTracerProvider({\n sampler,\n resource,\n });\n if (spanProcessor) {\n nodeTracerProvider.addSpanProcessor(spanProcessor);\n }\n nodeTracerProvider.register({\n contextManager: config.contextManager,\n });\n instrumentations.forEach((i) => i.setTracerProvider(nodeTracerProvider));\n\n // Save the provider so we can shut it down later.\n tracerProvider = nodeTracerProvider;\n\n // Set up metrics instrumentation if it's enabled.\n if (metricExporter) {\n const meterProvider = new MeterProvider({\n resource,\n readers: [\n new PeriodicExportingMetricReader({\n exporter: metricExporter,\n exportIntervalMillis: config.openTelemetryMetricExportIntervalMillis ?? 30_000,\n }),\n ],\n });\n metrics.setGlobalMeterProvider(meterProvider);\n }\n}\n\n/**\n * Gracefully shuts down the OpenTelemetry instrumentation. Should be called\n * when a `SIGTERM` signal is handled.\n */\nexport async function shutdown(): Promise<void> {\n if (tracerProvider) {\n await tracerProvider.shutdown();\n tracerProvider = null;\n }\n}\n\n/**\n * Disables all OpenTelemetry instrumentations. This is useful for tests that\n * need to access the unwrapped modules.\n */\nexport function disableInstrumentations() {\n instrumentations.forEach((i) => i.disable());\n}\n"]}
|
|
1
|
+
{"version":3,"file":"init.js","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,eAAe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C,CAAC,CAAC;IAEzE,kDAAkD;IAClD,cAAc,GAAG,kBAAkB,CAAC;IAEpC,kDAAkD;IAClD,IAAI,cAAc,EAAE,CAAC;QACnB,MAAM,aAAa,GAAG,IAAI,aAAa,CAAC;YACtC,QAAQ;YACR,OAAO,EAAE;gBACP,IAAI,6BAA6B,CAAC;oBAChC,QAAQ,EAAE,cAAc;oBACxB,oBAAoB,EAAE,MAAM,CAAC,uCAAuC,IAAI,MAAM;iBAC/E,CAAC;aACH;SACF,CAAC,CAAC;QACH,OAAO,CAAC,sBAAsB,CAAC,aAAa,CAAC,CAAC;IAChD,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,QAAQ;IAC5B,IAAI,cAAc,EAAE,CAAC;QACnB,MAAM,cAAc,CAAC,QAAQ,EAAE,CAAC;QAChC,cAAc,GAAG,IAAI,CAAC;IACxB,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,uBAAuB;IACrC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;AAC/C,CAAC","sourcesContent":["import { Metadata, credentials } from '@grpc/grpc-js';\nimport { type ContextManager, metrics } from '@opentelemetry/api';\nimport { hrTimeToMilliseconds } from '@opentelemetry/core';\nimport { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-grpc';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc';\nimport { OTLPTraceExporter as OTLPTraceExporterHttp } from '@opentelemetry/exporter-trace-otlp-http';\nimport { AwsInstrumentation } from '@opentelemetry/instrumentation-aws-sdk';\nimport { ConnectInstrumentation } from '@opentelemetry/instrumentation-connect';\nimport { DnsInstrumentation } from '@opentelemetry/instrumentation-dns';\nimport { ExpressInstrumentation, ExpressLayerType } from '@opentelemetry/instrumentation-express';\nimport { HttpInstrumentation } from '@opentelemetry/instrumentation-http';\nimport { IORedisInstrumentation } from '@opentelemetry/instrumentation-ioredis';\nimport { PgInstrumentation } from '@opentelemetry/instrumentation-pg';\nimport { RedisInstrumentation } from '@opentelemetry/instrumentation-redis';\nimport { awsEc2Detector } from '@opentelemetry/resource-detector-aws';\nimport {\n Resource,\n detectResourcesSync,\n envDetector,\n processDetector,\n} from '@opentelemetry/resources';\nimport {\n AggregationTemporality,\n ConsoleMetricExporter,\n MeterProvider,\n PeriodicExportingMetricReader,\n type PushMetricExporter,\n} from '@opentelemetry/sdk-metrics';\nimport {\n AlwaysOffSampler,\n AlwaysOnSampler,\n BatchSpanProcessor,\n ConsoleSpanExporter,\n ParentBasedSampler,\n type ReadableSpan,\n type Sampler,\n SimpleSpanProcessor,\n type SpanExporter,\n type SpanProcessor,\n TraceIdRatioBasedSampler,\n} from '@opentelemetry/sdk-trace-base';\nimport { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';\nimport { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';\n\n/**\n * Extends `BatchSpanProcessor` to give it the ability to filter out spans\n * before they're queued up to send. This enhances our sampling process so\n * that we can filter spans _after_ they've been emitted.\n */\nclass FilterBatchSpanProcessor extends BatchSpanProcessor {\n private filter: (span: ReadableSpan) => boolean;\n\n constructor(exporter: SpanExporter, filter: (span: ReadableSpan) => boolean) {\n super(exporter);\n this.filter = filter;\n }\n\n /**\n * This is invoked after a span is \"finalized\". `super.onEnd` will queue up\n * the span to be exported, but if we don't call that, we can just drop the\n * span and the parent will be none the wiser!\n */\n onEnd(span: ReadableSpan) {\n if (!this.filter(span)) return;\n\n super.onEnd(span);\n }\n}\n\n/**\n * This will be used with our {@link FilterBatchSpanProcessor} to filter out\n * events that we're not interested in. This helps reduce our event volume\n * but still gives us fine-grained control over which events we keep.\n */\nfunction filter(span: ReadableSpan) {\n if (span.name === 'pg-pool.connect') {\n // Looking at historical data, this generally happens in under a millisecond,\n // precisely because we maintain a pool of long-lived connections. The only\n // time obtaining a client should take longer than that is if we're\n // establishing a connection for the first time, which should happen only at\n // bootup, or if a connection errors out. Those are the cases we're\n // interested in, so we'll filter accordingly.\n return hrTimeToMilliseconds(span.duration) > 1;\n }\n\n // Always return true so that we default to including a span.\n return true;\n}\n\n// When adding new instrumentation here, add the corresponding packages to\n// `commonjs-preloads.ts` so that we can ensure that they're loaded via CJS\n// before anything tries to load them via CJS. This is necessary because the\n// instrumentations can't hook into the ESM loader.\nconst instrumentations = [\n new AwsInstrumentation(),\n new ConnectInstrumentation(),\n new DnsInstrumentation(),\n new ExpressInstrumentation({\n // We use a lot of middleware; it makes the traces way too noisy. If we\n // want telemetry on a particular middleware, we should instrument it\n // manually.\n ignoreLayersType: [ExpressLayerType.MIDDLEWARE],\n ignoreLayers: [\n // These don't provide useful information to us.\n 'router - /',\n 'request handler - /*',\n ],\n }),\n new HttpInstrumentation({\n ignoreIncomingRequestHook(req) {\n return [\n // socket.io requests are generally just long-polling; they don't add\n // useful information for us.\n /\\/socket.io\\//,\n // We get several of these per second; they just chew through our event quota.\n // They don't really do anything interesting anyways.\n /\\/pl\\/webhooks\\/ping/,\n ].some((re) => re.test(req.url ?? '/'));\n },\n }),\n new IORedisInstrumentation(),\n new PgInstrumentation(),\n new RedisInstrumentation(),\n];\n\n// Enable all instrumentations now, even though we haven't configured our\n// span processors or trace exporters yet. We'll set those up later.\ninstrumentations.forEach((i) => {\n i.enable();\n});\n\nlet tracerProvider: NodeTracerProvider | null;\n\ninterface OpenTelemetryConfigEnabled {\n openTelemetryEnabled: boolean;\n openTelemetryExporter?: 'console' | 'honeycomb' | 'jaeger' | SpanExporter | null;\n openTelemetryMetricExporter?: 'console' | 'honeycomb' | PushMetricExporter | null;\n openTelemetryMetricExportIntervalMillis?: number;\n openTelemetrySamplerType: 'always-on' | 'always-off' | 'trace-id-ratio';\n openTelemetrySampleRate?: number;\n openTelemetrySpanProcessor?: 'batch' | 'simple' | SpanProcessor;\n contextManager?: ContextManager;\n honeycombApiKey?: string | null;\n honeycombDataset?: string | null;\n serviceName?: string;\n}\n\n// When we know for sure that OpenTelemetry is disabled, we won't require\n// any other attributes to be set.\ninterface OpenTelemetryConfigDisabled extends Partial<OpenTelemetryConfigEnabled> {\n openTelemetryEnabled: false;\n}\n\nexport type OpenTelemetryConfig = OpenTelemetryConfigEnabled | OpenTelemetryConfigDisabled;\n\nfunction getHoneycombMetadata(config: OpenTelemetryConfig, datasetSuffix = ''): Metadata {\n if (!config.honeycombApiKey) throw new Error('Missing Honeycomb API key');\n if (!config.honeycombDataset) throw new Error('Missing Honeycomb dataset');\n\n const metadata = new Metadata();\n\n metadata.set('x-honeycomb-team', config.honeycombApiKey);\n metadata.set('x-honeycomb-dataset', config.honeycombDataset + datasetSuffix);\n\n return metadata;\n}\n\nfunction getTraceExporter(config: OpenTelemetryConfig): SpanExporter | null {\n if (!config.openTelemetryExporter) return null;\n\n if (typeof config.openTelemetryExporter === 'object') {\n return config.openTelemetryExporter;\n }\n\n switch (config.openTelemetryExporter) {\n case 'console':\n return new ConsoleSpanExporter();\n case 'honeycomb':\n return new OTLPTraceExporter({\n url: 'grpc://api.honeycomb.io:443/',\n credentials: credentials.createSsl(),\n metadata: getHoneycombMetadata(config),\n });\n case 'jaeger':\n return new OTLPTraceExporterHttp();\n default:\n throw new Error(`Unknown OpenTelemetry exporter: ${config.openTelemetryExporter}`);\n }\n}\n\nfunction getMetricExporter(config: OpenTelemetryConfig): PushMetricExporter | null {\n if (!config.openTelemetryMetricExporter) return null;\n\n if (typeof config.openTelemetryMetricExporter === 'object') {\n return config.openTelemetryMetricExporter;\n }\n\n switch (config.openTelemetryMetricExporter) {\n case 'console':\n return new ConsoleMetricExporter();\n case 'honeycomb':\n return new OTLPMetricExporter({\n url: 'grpc://api.honeycomb.io:443/',\n credentials: credentials.createSsl(),\n // Honeycomb recommends using a separate dataset for metrics, so we'll\n // adopt the convention of appending '-metrics' to the dataset name.\n metadata: getHoneycombMetadata(config, '-metrics'),\n // Delta temporality means that sums, histograms, etc. will reset each\n // time data is collected. This more closely matches how we want to\n // observe our metrics than the default cumulative temporality.\n temporalityPreference: AggregationTemporality.DELTA,\n });\n default:\n throw new Error(\n `Unknown OpenTelemetry metric exporter: ${config.openTelemetryMetricExporter}`,\n );\n }\n}\n\nfunction getSpanProcessor(config: OpenTelemetryConfig): SpanProcessor | null {\n if (typeof config.openTelemetrySpanProcessor === 'object') {\n return config.openTelemetrySpanProcessor;\n }\n\n const traceExporter = getTraceExporter(config);\n if (!traceExporter) return null;\n\n switch (config.openTelemetrySpanProcessor ?? 'batch') {\n case 'batch': {\n return new FilterBatchSpanProcessor(traceExporter, filter);\n }\n case 'simple': {\n return new SimpleSpanProcessor(traceExporter);\n }\n default: {\n throw new Error(`Unknown OpenTelemetry span processor: ${config.openTelemetrySpanProcessor}`);\n }\n }\n}\n\n/**\n * Should be called once we've loaded our config; this will allow us to set up\n * the correct metadata for the Honeycomb exporter. We don't actually have that\n * information available until we've loaded our config.\n */\nexport async function init(config: OpenTelemetryConfig) {\n if (!config.openTelemetryEnabled) {\n // If not enabled, do nothing. We used to disable the instrumentations, but\n // per maintainers, that can actually be problematic. See the comments on\n // https://github.com/open-telemetry/opentelemetry-js-contrib/issues/970\n // The Express instrumentation also logs a benign error, which can be\n // confusing to users. There's a fix in progress if we want to switch back\n // to disabling instrumentations in the future:\n // https://github.com/open-telemetry/opentelemetry-js-contrib/pull/972\n return;\n }\n\n const metricExporter = getMetricExporter(config);\n const spanProcessor = getSpanProcessor(config);\n\n let sampler: Sampler;\n switch (config.openTelemetrySamplerType ?? 'always-on') {\n case 'always-on': {\n sampler = new AlwaysOnSampler();\n break;\n }\n case 'always-off': {\n sampler = new AlwaysOffSampler();\n break;\n }\n case 'trace-id-ratio': {\n sampler = new ParentBasedSampler({\n root: new TraceIdRatioBasedSampler(config.openTelemetrySampleRate),\n });\n break;\n }\n default:\n throw new Error(`Unknown OpenTelemetry sampler type: ${config.openTelemetrySamplerType}`);\n }\n\n // Much of this functionality is copied from `@opentelemetry/sdk-node`, but\n // we can't use the SDK directly because of the fact that we load our config\n // asynchronously. We need to initialize our instrumentations first; only\n // then can we actually start requiring all of our code that loads our config\n // and ultimately tells us how to configure OpenTelemetry.\n\n let resource = detectResourcesSync({\n // The AWS resource detector always tries to reach out to the EC2 metadata\n // service endpoint. When running locally, or otherwise in a non-AWS environment,\n // this will typically fail immediately wih `EHOSTDOWN`, but will sometimes wait\n // 5 seconds before failing with a network timeout error. This causes problems\n // when running tests, as 5 seconds is longer than Mocha lets tests and hooks run\n // for by default. This causes nondeterministic test failures when the EC2 metadata\n // request fails with a network timeout.\n //\n // To work around this, the AWS resource detector is only enabled when running in\n // a production environment. In general this is reasonable, as we only care about\n // AWS resource detection in production-like environments.\n detectors: [\n process.env.NODE_ENV === 'production' ? awsEc2Detector : null,\n processDetector,\n envDetector,\n ].filter((d) => !!d),\n });\n\n if (config.serviceName) {\n resource = resource.merge(\n new Resource({ [SemanticResourceAttributes.SERVICE_NAME]: config.serviceName }),\n );\n }\n\n // Set up tracing instrumentation.\n const nodeTracerProvider = new NodeTracerProvider({\n sampler,\n resource,\n });\n if (spanProcessor) {\n nodeTracerProvider.addSpanProcessor(spanProcessor);\n }\n nodeTracerProvider.register({\n contextManager: config.contextManager,\n });\n instrumentations.forEach((i) => i.setTracerProvider(nodeTracerProvider));\n\n // Save the provider so we can shut it down later.\n tracerProvider = nodeTracerProvider;\n\n // Set up metrics instrumentation if it's enabled.\n if (metricExporter) {\n const meterProvider = new MeterProvider({\n resource,\n readers: [\n new PeriodicExportingMetricReader({\n exporter: metricExporter,\n exportIntervalMillis: config.openTelemetryMetricExportIntervalMillis ?? 30_000,\n }),\n ],\n });\n metrics.setGlobalMeterProvider(meterProvider);\n }\n}\n\n/**\n * Gracefully shuts down the OpenTelemetry instrumentation. Should be called\n * when a `SIGTERM` signal is handled.\n */\nexport async function shutdown(): Promise<void> {\n if (tracerProvider) {\n await tracerProvider.shutdown();\n tracerProvider = null;\n }\n}\n\n/**\n * Disables all OpenTelemetry instrumentations. This is useful for tests that\n * need to access the unwrapped modules.\n */\nexport function disableInstrumentations() {\n instrumentations.forEach((i) => i.disable());\n}\n"]}
|
package/dist/metrics.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type
|
|
1
|
+
import { type Counter, type Histogram, type Meter, type MetricOptions, type ObservableCounter, type ObservableGauge, type ObservableUpDownCounter, type UpDownCounter } from '@opentelemetry/api';
|
|
2
2
|
export declare function getHistogram(meter: Meter, name: string, options?: MetricOptions): Histogram;
|
|
3
3
|
export declare function getCounter(meter: Meter, name: string, options?: MetricOptions): Counter<import("@opentelemetry/api").Attributes>;
|
|
4
4
|
export declare function getUpDownCounter(meter: Meter, name: string, options?: MetricOptions): UpDownCounter<import("@opentelemetry/api").Attributes>;
|
package/dist/metrics.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"metrics.js","sourceRoot":"","sources":["../src/metrics.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"metrics.js","sourceRoot":"","sources":["../src/metrics.ts"],"names":[],"mappings":"AAAA,OAAO,EASL,SAAS,GACV,MAAM,oBAAoB,CAAC;AAE5B,MAAM,cAAc,GAAG,IAAI,OAAO,EAAiC,CAAC;AACpE,MAAM,YAAY,GAAG,IAAI,OAAO,EAA+B,CAAC;AAChE,MAAM,kBAAkB,GAAG,IAAI,OAAO,EAAqC,CAAC;AAC5E,MAAM,sBAAsB,GAAG,IAAI,OAAO,EAAyC,CAAC;AACpF,MAAM,4BAA4B,GAAG,IAAI,OAAO,EAA+C,CAAC;AAChG,MAAM,oBAAoB,GAAG,IAAI,OAAO,EAAuC,CAAC;AAEhF,SAAS,eAAe,CACtB,KAAqC,EACrC,KAAY,EACZ,IAAY,EACZ,MAAe;IAEf,IAAI,UAAU,GAAG,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAClC,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,UAAU,GAAG,IAAI,GAAG,EAAE,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AAC,gBAAgB,EAAE,EAAE;QACxC,gBAAgB,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAE9B,GAAG,GAAG,CAAC,CAAC;IACV,CAAC,CAAC,CAAC;IAEH,QAAQ,CAAC,WAAW,CAAC,CAAC,gBAAgB,EAAE,EAAE;QACxC,gBAAgB,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAE9B,GAAG,GAAG,CAAC,CAAC;IACV,CAAC,CAAC,CAAC;IAEH,YAAY,CAAC,WAAW,CAAC,CAAC,gBAAgB,EAAE,EAAE;QAC5C,MAAM,GAAG,GAAG,GAAG,GAAG,KAAK,CAAC;QACxB,gBAAgB,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAE9B,GAAG,GAAG,CAAC,CAAC;QACR,KAAK,GAAG,CAAC,CAAC;IACZ,CAAC,CAAC,CAAC;IAEH,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,YAAY,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,aAAa,CAAC,UAAU,CAAC,EAAE,CAAC;AACrF,CAAC","sourcesContent":["import {\n type Counter,\n type Histogram,\n type Meter,\n type MetricOptions,\n type ObservableCounter,\n type ObservableGauge,\n type ObservableUpDownCounter,\n type UpDownCounter,\n ValueType,\n} from '@opentelemetry/api';\n\nconst histogramCache = new WeakMap<Meter, Map<string, Histogram>>();\nconst counterCache = new WeakMap<Meter, Map<string, Counter>>();\nconst upDownCounterCache = new WeakMap<Meter, Map<string, UpDownCounter>>();\nconst observableCounterCache = new WeakMap<Meter, Map<string, ObservableCounter>>();\nconst observableUpDownCounterCache = new WeakMap<Meter, Map<string, ObservableUpDownCounter>>();\nconst observableGaugeCache = new WeakMap<Meter, Map<string, ObservableGauge>>();\n\nfunction getCachedMetric<T>(\n cache: WeakMap<Meter, Map<string, T>>,\n meter: Meter,\n name: string,\n create: () => T,\n): T {\n let meterCache = cache.get(meter);\n if (!meterCache) {\n meterCache = new Map();\n cache.set(meter, meterCache);\n }\n\n let metric = meterCache.get(name);\n if (!metric) {\n metric = create();\n meterCache.set(name, metric);\n }\n\n return metric;\n}\n\nexport function getHistogram(meter: Meter, name: string, options?: MetricOptions): Histogram {\n return getCachedMetric(histogramCache, meter, name, () => meter.createHistogram(name, options));\n}\n\nexport function getCounter(meter: Meter, name: string, options?: MetricOptions) {\n return getCachedMetric(counterCache, meter, name, () => meter.createCounter(name, options));\n}\n\nexport function getUpDownCounter(meter: Meter, name: string, options?: MetricOptions) {\n return getCachedMetric(upDownCounterCache, meter, name, () =>\n meter.createUpDownCounter(name, options),\n );\n}\n\nexport function getObservableCounter(meter: Meter, name: string, options?: MetricOptions) {\n return getCachedMetric(observableCounterCache, meter, name, () =>\n meter.createObservableCounter(name, options),\n );\n}\n\nexport function getObservableUpDownCounter(meter: Meter, name: string, options?: MetricOptions) {\n return getCachedMetric(observableUpDownCounterCache, meter, name, () =>\n meter.createObservableUpDownCounter(name, options),\n );\n}\n\nexport function getObservableGauge(meter: Meter, name: string, options?: MetricOptions) {\n return getCachedMetric(observableGaugeCache, meter, name, () =>\n meter.createObservableGauge(name, options),\n );\n}\n\nexport async function instrumentedWithMetrics<T>(\n meter: Meter,\n name: string,\n fn: () => Promise<T> | T,\n done?: (duration: number) => void,\n): Promise<T> {\n const error = getCounter(meter, `${name}.error`, { valueType: ValueType.INT });\n const histogram = getHistogram(meter, `${name}.duration`, {\n unit: 'milliseconds',\n valueType: ValueType.DOUBLE,\n });\n\n const start = performance.now();\n try {\n return await fn();\n } catch (e) {\n error.add(1);\n throw e;\n } finally {\n const duration = performance.now() - start;\n histogram.record(duration);\n done?.(duration);\n }\n}\n\nexport interface CreateObservableValueGaugesOptions extends MetricOptions {\n interval: number;\n}\n\n/**\n * Creates a set of gauges that track the min, max, and average of a value over\n * time. The value is observed on a regular interval.\n *\n * The provided {@link name} is used as the base name for the three gauges. The\n * names of the individual gauges are:\n *\n * - `${name}.min`\n * - `${name}.max`\n * - `${name}.avg`\n */\nexport function createObservableValueGauges(\n meter: Meter,\n name: string,\n options: CreateObservableValueGaugesOptions,\n observe: () => number,\n) {\n const { interval, ...metricOptions } = options;\n\n let min = 0;\n let max = 0;\n let sum = 0;\n let count = 0;\n\n // Observe the value on a regular interval. Black-hole any errors.\n const intervalId = setInterval(() => {\n Promise.resolve(observe())\n .then((value) => {\n min = count === 0 ? value : Math.min(min, value);\n max = Math.max(max, value);\n sum += value;\n count += 1;\n })\n .catch(() => {});\n }, interval);\n\n // Don't let this keep the process alive.\n intervalId.unref();\n\n const minGauge = getObservableGauge(meter, `${name}.min`, metricOptions);\n const maxGauge = getObservableGauge(meter, `${name}.max`, metricOptions);\n const averageGauge = getObservableGauge(meter, `${name}.avg`, {\n ...metricOptions,\n // Average is always a double, even if the observed value is an int.\n valueType: ValueType.DOUBLE,\n });\n\n minGauge.addCallback((observableResult) => {\n observableResult.observe(min);\n\n min = 0;\n });\n\n maxGauge.addCallback((observableResult) => {\n observableResult.observe(max);\n\n max = 0;\n });\n\n averageGauge.addCallback((observableResult) => {\n const avg = sum / count;\n observableResult.observe(avg);\n\n sum = 0;\n count = 0;\n });\n\n return { minGauge, maxGauge, averageGauge, stop: () => clearInterval(intervalId) };\n}\n"]}
|
package/dist/metrics.test.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {} from '@opentelemetry/api';
|
|
2
|
-
import {
|
|
3
|
-
import { use as chaiUse
|
|
2
|
+
import { AggregationTemporality, InMemoryMetricExporter, MeterProvider, PeriodicExportingMetricReader, } from '@opentelemetry/sdk-metrics';
|
|
3
|
+
import { assert, use as chaiUse } from 'chai';
|
|
4
4
|
import chaiAsPromised from 'chai-as-promised';
|
|
5
5
|
import { instrumentedWithMetrics } from './metrics.js';
|
|
6
6
|
chaiUse(chaiAsPromised);
|
package/dist/metrics.test.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"metrics.test.js","sourceRoot":"","sources":["../src/metrics.test.ts"],"names":[],"mappings":"AAAA,OAAO,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AC;QAEF,MAAM,oBAAoB,CAAC,QAAQ,CAAC,CAAC;QACrC,MAAM,eAAe,GAAG,QAAQ,CAAC,UAAU,EAAE,CAAC;QAC9C,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,eAAe,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;QAE9D,uEAAuE;QACvE,yBAAyB;QACzB,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;QAC5B,MAAM,CAAC,aAAa,EAAE,eAAe,CAAC,GAAG,OAAO,CAAC;QAEjD,MAAM,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;QACjB,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QAEjC,MAAM,CAAC,EAAE,CAAC,aAAa,CAAC,CAAC;QACzB,MAAM,CAAC,KAAK,CAAC,aAAa,CAAC,UAAU,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;QAC1D,MAAM,CAAC,KAAK,CAAC,aAAa,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;QAEnD,MAAM,CAAC,EAAE,CAAC,eAAe,CAAC,CAAC;QAC3B,MAAM,CAAC,KAAK,CAAC,eAAe,CAAC,UAAU,CAAC,IAAI,EAAE,eAAe,CAAC,CAAC;QAC/D,MAAM,CAAC,KAAK,CAAE,eAAe,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,KAAmB,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;IAC5E,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { type Meter } from '@opentelemetry/api';\nimport {\n AggregationTemporality,\n type Histogram,\n InMemoryMetricExporter,\n MeterProvider,\n PeriodicExportingMetricReader,\n} from '@opentelemetry/sdk-metrics';\nimport { assert, use as chaiUse } from 'chai';\nimport chaiAsPromised from 'chai-as-promised';\n\nimport { instrumentedWithMetrics } from './metrics.js';\n\nchaiUse(chaiAsPromised);\n\nasync function waitForMetricsExport(exporter: InMemoryMetricExporter) {\n while (exporter.getMetrics().length === 0) {\n await new Promise((resolve) => setTimeout(resolve, 50));\n }\n}\n\ndescribe('instrumentedWithMetrics', () => {\n let exporter: InMemoryMetricExporter;\n let metricReader: PeriodicExportingMetricReader;\n let meter: Meter;\n\n beforeEach(async () => {\n const meterProvider = new MeterProvider();\n meter = meterProvider.getMeter('test');\n exporter = new InMemoryMetricExporter(AggregationTemporality.DELTA);\n metricReader = new PeriodicExportingMetricReader({\n exporter,\n exportIntervalMillis: 50,\n });\n meterProvider.addMetricReader(metricReader);\n });\n\n afterEach(async () => {\n await exporter.shutdown();\n await metricReader.shutdown();\n });\n\n it('records a histogram for the function duration', async () => {\n await instrumentedWithMetrics(meter, 'test', async () => {});\n\n await waitForMetricsExport(exporter);\n const exportedMetrics = exporter.getMetrics();\n const { scope, metrics } = exportedMetrics[0].scopeMetrics[0];\n\n // We won't see an exported metric for the error counter because the\n // Metrics SDK no longer exports metrics with no data points.\n // https://github.com/open-telemetry/opentelemetry-js/pull/4135\n assert.lengthOf(metrics, 1);\n const [histogramMetric] = metrics;\n\n assert.equal(scope.name, 'test');\n\n assert.ok(histogramMetric);\n assert.equal(histogramMetric.descriptor.name, 'test.duration');\n assert.equal((histogramMetric.dataPoints[0].value as Histogram).count, 1);\n });\n\n it('records an error count', async () => {\n await assert.isRejected(\n instrumentedWithMetrics(meter, 'test', async () => {\n throw new Error('error for test');\n }),\n 'error for test',\n );\n\n await waitForMetricsExport(exporter);\n const exportedMetrics = exporter.getMetrics();\n const { metrics, scope } = exportedMetrics[0].scopeMetrics[0];\n\n // An error was reported above, so there will be both the error counter\n // and histogram metrics.\n assert.lengthOf(metrics, 2);\n const [counterMetric, histogramMetric] = metrics;\n\n assert.ok(scope);\n assert.equal(scope.name, 'test');\n\n assert.ok(counterMetric);\n assert.equal(counterMetric.descriptor.name, 'test.error');\n assert.equal(counterMetric.dataPoints[0].value, 1);\n\n assert.ok(histogramMetric);\n assert.equal(histogramMetric.descriptor.name, 'test.duration');\n assert.equal((histogramMetric.dataPoints[0].value as Histogram).count, 1);\n });\n});\n"]}
|
package/dist/tracing.test.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks';
|
|
2
2
|
import { tracing } from '@opentelemetry/sdk-node';
|
|
3
3
|
import { assert } from 'chai';
|
|
4
|
-
import { context, init, instrumented, trace
|
|
4
|
+
import { SpanStatusCode, context, init, instrumented, trace } from './index.js';
|
|
5
5
|
describe('instrumented', () => {
|
|
6
6
|
let contextManager;
|
|
7
7
|
const exporter = new tracing.InMemorySpanExporter();
|
package/dist/tracing.test.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tracing.test.js","sourceRoot":"","sources":["../src/tracing.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAC9E,OAAO,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAC;AAClD,OAAO,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AAE9B,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"tracing.test.js","sourceRoot":"","sources":["../src/tracing.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAC9E,OAAO,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAC;AAClD,OAAO,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AAE9B,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAEhF,QAAQ,CAAC,cAAc,EAAE,GAAG,EAAE;IAC5B,IAAI,cAAwC,CAAC;IAC7C,MAAM,QAAQ,GAAG,IAA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2BAA2B,EAAE,KAAK,IAAI,EAAE;QACzC,MAAM,MAAM,GAAG,KAAK,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;QAC1C,MAAM,UAAU,GAAG,MAAM,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC;QAClD,MAAM,aAAa,GAAG,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,UAAU,CAAC,CAAC;QAElE,MAAM,YAAY,CAAC,MAAM,EAAE,KAAK,IAAI,EAAE;YACpC,MAAM,YAAY,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;YACtC,MAAM,CAAC,cAAc,CAAC,YAAY,EAAE,aAAa,CAAC,CAAC;QACrD,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks';\nimport { tracing } from '@opentelemetry/sdk-node';\nimport { assert } from 'chai';\n\nimport { SpanStatusCode, context, init, instrumented, trace } from './index.js';\n\ndescribe('instrumented', () => {\n let contextManager: AsyncHooksContextManager;\n const exporter = new tracing.InMemorySpanExporter();\n const spanProcessor = new tracing.SimpleSpanProcessor(exporter);\n\n before(async () => {\n await init({\n openTelemetryEnabled: true,\n openTelemetryExporter: exporter,\n openTelemetrySamplerType: 'always-on',\n openTelemetrySpanProcessor: spanProcessor,\n });\n });\n\n beforeEach(async () => {\n contextManager = new AsyncHooksContextManager();\n context.setGlobalContextManager(contextManager.enable());\n });\n\n afterEach(async () => {\n await spanProcessor.forceFlush();\n exporter.reset();\n context.disable();\n });\n\n it('returns the value from the function', async () => {\n const res = await instrumented('test', () => 'foo');\n assert.equal(res, 'foo');\n });\n\n it('records a span on success', async () => {\n await instrumented('test-success', () => 'foo');\n\n await spanProcessor.forceFlush();\n const spans = exporter.getFinishedSpans();\n assert.lengthOf(spans, 1);\n assert.equal(spans[0].name, 'test-success');\n assert.equal(spans[0].status.code, SpanStatusCode.OK);\n });\n\n it('records a span on failure', async () => {\n let maybeError: Error | null = null;\n\n try {\n await instrumented('test-failure', () => {\n throw new Error('foo');\n });\n } catch (err: any) {\n maybeError = err;\n }\n\n // Ensure the error was propagated back to the caller.\n assert.equal(maybeError?.message, 'foo');\n\n // Ensure the correct span was recorded.\n await spanProcessor.forceFlush();\n const spans = exporter.getFinishedSpans();\n assert.lengthOf(spans, 1);\n assert.equal(spans[0].name, 'test-failure');\n assert.equal(spans[0].status.code, SpanStatusCode.ERROR);\n assert.equal(spans[0].status.message, 'foo');\n assert.equal(spans[0].events[0].name, 'exception');\n });\n\n it('sets up context correctly', async () => {\n const tracer = trace.getTracer('default');\n const parentSpan = tracer.startSpan('parentSpan');\n const parentContext = trace.setSpan(context.active(), parentSpan);\n\n await instrumented('test', async () => {\n const childContext = context.active();\n assert.notStrictEqual(childContext, parentContext);\n });\n });\n});\n"]}
|
package/package.json
CHANGED
|
@@ -1,54 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prairielearn/opentelemetry",
|
|
3
|
-
"version": "2.1.
|
|
3
|
+
"version": "2.1.11",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"main": "dist/index.js",
|
|
6
5
|
"repository": {
|
|
7
6
|
"type": "git",
|
|
8
7
|
"url": "https://github.com/PrairieLearn/PrairieLearn.git",
|
|
9
8
|
"directory": "packages/opentelemetry"
|
|
10
9
|
},
|
|
10
|
+
"main": "dist/index.js",
|
|
11
11
|
"scripts": {
|
|
12
12
|
"build": "tsc",
|
|
13
13
|
"dev": "tsc --watch --preserveWatchOutput",
|
|
14
14
|
"test": "c8 mocha src/**/*.test.ts"
|
|
15
15
|
},
|
|
16
16
|
"dependencies": {
|
|
17
|
-
"@grpc/grpc-js": "^1.
|
|
17
|
+
"@grpc/grpc-js": "^1.13.2",
|
|
18
18
|
"@opentelemetry/api": "^1.9.0",
|
|
19
19
|
"@opentelemetry/core": "^1.30.1",
|
|
20
|
-
"@opentelemetry/exporter-metrics-otlp-grpc": "^0.57.
|
|
21
|
-
"@opentelemetry/exporter-trace-otlp-grpc": "^0.57.
|
|
22
|
-
"@opentelemetry/exporter-trace-otlp-http": "^0.57.
|
|
23
|
-
"@opentelemetry/instrumentation": "^0.57.
|
|
24
|
-
"@opentelemetry/instrumentation-aws-sdk": "^0.49.
|
|
25
|
-
"@opentelemetry/instrumentation-connect": "^0.43.
|
|
26
|
-
"@opentelemetry/instrumentation-dns": "^0.43.
|
|
27
|
-
"@opentelemetry/instrumentation-express": "^0.47.
|
|
28
|
-
"@opentelemetry/instrumentation-http": "^0.57.
|
|
29
|
-
"@opentelemetry/instrumentation-ioredis": "^0.47.
|
|
30
|
-
"@opentelemetry/instrumentation-pg": "^0.
|
|
31
|
-
"@opentelemetry/instrumentation-redis": "^0.46.
|
|
32
|
-
"@opentelemetry/resource-detector-aws": "^1.
|
|
20
|
+
"@opentelemetry/exporter-metrics-otlp-grpc": "^0.57.2",
|
|
21
|
+
"@opentelemetry/exporter-trace-otlp-grpc": "^0.57.2",
|
|
22
|
+
"@opentelemetry/exporter-trace-otlp-http": "^0.57.2",
|
|
23
|
+
"@opentelemetry/instrumentation": "^0.57.2",
|
|
24
|
+
"@opentelemetry/instrumentation-aws-sdk": "^0.49.1",
|
|
25
|
+
"@opentelemetry/instrumentation-connect": "^0.43.1",
|
|
26
|
+
"@opentelemetry/instrumentation-dns": "^0.43.1",
|
|
27
|
+
"@opentelemetry/instrumentation-express": "^0.47.1",
|
|
28
|
+
"@opentelemetry/instrumentation-http": "^0.57.2",
|
|
29
|
+
"@opentelemetry/instrumentation-ioredis": "^0.47.1",
|
|
30
|
+
"@opentelemetry/instrumentation-pg": "^0.51.1",
|
|
31
|
+
"@opentelemetry/instrumentation-redis": "^0.46.1",
|
|
32
|
+
"@opentelemetry/resource-detector-aws": "^1.12.0",
|
|
33
33
|
"@opentelemetry/resources": "^1.30.1",
|
|
34
34
|
"@opentelemetry/sdk-metrics": "^1.30.1",
|
|
35
|
-
"@opentelemetry/sdk-node": "^0.57.
|
|
35
|
+
"@opentelemetry/sdk-node": "^0.57.2",
|
|
36
36
|
"@opentelemetry/sdk-trace-base": "^1.30.1",
|
|
37
37
|
"@opentelemetry/sdk-trace-node": "^1.30.1",
|
|
38
|
-
"@opentelemetry/semantic-conventions": "^1.
|
|
38
|
+
"@opentelemetry/semantic-conventions": "^1.30.0"
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|
|
41
41
|
"@opentelemetry/context-async-hooks": "^1.30.1",
|
|
42
42
|
"@prairielearn/tsconfig": "^0.0.0",
|
|
43
|
-
"@types/chai": "^5.
|
|
43
|
+
"@types/chai": "^5.2.1",
|
|
44
44
|
"@types/mocha": "^10.0.10",
|
|
45
|
-
"@types/node": "^20.17.
|
|
45
|
+
"@types/node": "^20.17.28",
|
|
46
46
|
"c8": "^10.1.3",
|
|
47
|
-
"chai": "^5.
|
|
47
|
+
"chai": "^5.2.0",
|
|
48
48
|
"chai-as-promised": "^8.0.1",
|
|
49
|
-
"mocha": "^
|
|
50
|
-
"tsx": "^4.19.
|
|
51
|
-
"typescript": "^5.
|
|
49
|
+
"mocha": "^11.1.0",
|
|
50
|
+
"tsx": "^4.19.3",
|
|
51
|
+
"typescript": "^5.8.2"
|
|
52
52
|
},
|
|
53
53
|
"c8": {
|
|
54
54
|
"reporter": [
|
package/src/init.ts
CHANGED
|
@@ -7,37 +7,37 @@ import { OTLPTraceExporter as OTLPTraceExporterHttp } from '@opentelemetry/expor
|
|
|
7
7
|
import { AwsInstrumentation } from '@opentelemetry/instrumentation-aws-sdk';
|
|
8
8
|
import { ConnectInstrumentation } from '@opentelemetry/instrumentation-connect';
|
|
9
9
|
import { DnsInstrumentation } from '@opentelemetry/instrumentation-dns';
|
|
10
|
-
import {
|
|
10
|
+
import { ExpressInstrumentation, ExpressLayerType } from '@opentelemetry/instrumentation-express';
|
|
11
11
|
import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
|
|
12
12
|
import { IORedisInstrumentation } from '@opentelemetry/instrumentation-ioredis';
|
|
13
13
|
import { PgInstrumentation } from '@opentelemetry/instrumentation-pg';
|
|
14
14
|
import { RedisInstrumentation } from '@opentelemetry/instrumentation-redis';
|
|
15
15
|
import { awsEc2Detector } from '@opentelemetry/resource-detector-aws';
|
|
16
16
|
import {
|
|
17
|
+
Resource,
|
|
17
18
|
detectResourcesSync,
|
|
18
|
-
processDetector,
|
|
19
19
|
envDetector,
|
|
20
|
-
|
|
20
|
+
processDetector,
|
|
21
21
|
} from '@opentelemetry/resources';
|
|
22
22
|
import {
|
|
23
|
-
|
|
23
|
+
AggregationTemporality,
|
|
24
|
+
ConsoleMetricExporter,
|
|
24
25
|
MeterProvider,
|
|
26
|
+
PeriodicExportingMetricReader,
|
|
25
27
|
type PushMetricExporter,
|
|
26
|
-
ConsoleMetricExporter,
|
|
27
|
-
AggregationTemporality,
|
|
28
28
|
} from '@opentelemetry/sdk-metrics';
|
|
29
29
|
import {
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
type SpanProcessor,
|
|
33
|
-
SimpleSpanProcessor,
|
|
30
|
+
AlwaysOffSampler,
|
|
31
|
+
AlwaysOnSampler,
|
|
34
32
|
BatchSpanProcessor,
|
|
33
|
+
ConsoleSpanExporter,
|
|
35
34
|
ParentBasedSampler,
|
|
36
|
-
|
|
37
|
-
AlwaysOnSampler,
|
|
38
|
-
AlwaysOffSampler,
|
|
35
|
+
type ReadableSpan,
|
|
39
36
|
type Sampler,
|
|
40
|
-
|
|
37
|
+
SimpleSpanProcessor,
|
|
38
|
+
type SpanExporter,
|
|
39
|
+
type SpanProcessor,
|
|
40
|
+
TraceIdRatioBasedSampler,
|
|
41
41
|
} from '@opentelemetry/sdk-trace-base';
|
|
42
42
|
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
|
|
43
43
|
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';
|
|
@@ -181,7 +181,6 @@ function getTraceExporter(config: OpenTelemetryConfig): SpanExporter | null {
|
|
|
181
181
|
credentials: credentials.createSsl(),
|
|
182
182
|
metadata: getHoneycombMetadata(config),
|
|
183
183
|
});
|
|
184
|
-
break;
|
|
185
184
|
case 'jaeger':
|
|
186
185
|
return new OTLPTraceExporterHttp();
|
|
187
186
|
default:
|
package/src/metrics.test.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { type Meter } from '@opentelemetry/api';
|
|
2
2
|
import {
|
|
3
|
-
InMemoryMetricExporter,
|
|
4
3
|
AggregationTemporality,
|
|
4
|
+
type Histogram,
|
|
5
|
+
InMemoryMetricExporter,
|
|
5
6
|
MeterProvider,
|
|
6
7
|
PeriodicExportingMetricReader,
|
|
7
|
-
type Histogram,
|
|
8
8
|
} from '@opentelemetry/sdk-metrics';
|
|
9
|
-
import { use as chaiUse
|
|
9
|
+
import { assert, use as chaiUse } from 'chai';
|
|
10
10
|
import chaiAsPromised from 'chai-as-promised';
|
|
11
11
|
|
|
12
12
|
import { instrumentedWithMetrics } from './metrics.js';
|
package/src/metrics.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import {
|
|
2
|
+
type Counter,
|
|
3
|
+
type Histogram,
|
|
2
4
|
type Meter,
|
|
3
|
-
ValueType,
|
|
4
5
|
type MetricOptions,
|
|
5
|
-
type Histogram,
|
|
6
|
-
type Counter,
|
|
7
|
-
type UpDownCounter,
|
|
8
6
|
type ObservableCounter,
|
|
9
|
-
type ObservableUpDownCounter,
|
|
10
7
|
type ObservableGauge,
|
|
8
|
+
type ObservableUpDownCounter,
|
|
9
|
+
type UpDownCounter,
|
|
10
|
+
ValueType,
|
|
11
11
|
} from '@opentelemetry/api';
|
|
12
12
|
|
|
13
13
|
const histogramCache = new WeakMap<Meter, Map<string, Histogram>>();
|
package/src/tracing.test.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks';
|
|
|
2
2
|
import { tracing } from '@opentelemetry/sdk-node';
|
|
3
3
|
import { assert } from 'chai';
|
|
4
4
|
|
|
5
|
-
import { context, init, instrumented, trace
|
|
5
|
+
import { SpanStatusCode, context, init, instrumented, trace } from './index.js';
|
|
6
6
|
|
|
7
7
|
describe('instrumented', () => {
|
|
8
8
|
let contextManager: AsyncHooksContextManager;
|