@platformatic/telemetry 0.33.0

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/.taprc ADDED
@@ -0,0 +1 @@
1
+ jobs: 1
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,13 @@
1
+ Copyright 2022 Platformatic
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
package/index.js ADDED
@@ -0,0 +1,9 @@
1
+ 'use strict'
2
+
3
+ const telemetry = require('./lib/telemetry')
4
+ const schema = require('./lib/schema')
5
+
6
+ module.exports = {
7
+ telemetry,
8
+ schema
9
+ }
@@ -0,0 +1,22 @@
1
+ 'use strict'
2
+
3
+ const fastifyTextMapGetter = {
4
+ get (request, key) {
5
+ return request.headers[key]
6
+ },
7
+ /* istanbul ignore next */
8
+ keys (request) {
9
+ return Object.keys(request.headers)
10
+ }
11
+ }
12
+
13
+ const fastifyTextMapSetter = {
14
+ set (reply, key, value) {
15
+ reply.headers({ [key]: value })
16
+ }
17
+ }
18
+
19
+ module.exports = {
20
+ fastifyTextMapGetter,
21
+ fastifyTextMapSetter
22
+ }
@@ -0,0 +1,39 @@
1
+ 'use strict'
2
+
3
+ // This implements the SpanProcessor interface:
4
+ // https://github.com/open-telemetry/opentelemetry-js/blob/main/packages/opentelemetry-sdk-trace-base/src/SpanProcessor.ts
5
+ class MultiSpanProcessor {
6
+ constructor (_spanProcessors = []) {
7
+ this._spanProcessors = _spanProcessors
8
+ }
9
+
10
+ async forceFlush () {
11
+ const promises = []
12
+ for (const spanProcessor of this._spanProcessors) {
13
+ promises.push(spanProcessor.forceFlush())
14
+ }
15
+ return Promise.all(promises)
16
+ }
17
+
18
+ onStart (span, context) {
19
+ for (const spanProcessor of this._spanProcessors) {
20
+ spanProcessor.onStart(span, context)
21
+ }
22
+ }
23
+
24
+ onEnd (span) {
25
+ for (const spanProcessor of this._spanProcessors) {
26
+ spanProcessor.onEnd(span)
27
+ }
28
+ }
29
+
30
+ async shutdown () {
31
+ const promises = []
32
+ for (const spanProcessor of this._spanProcessors) {
33
+ promises.push(spanProcessor.shutdown())
34
+ }
35
+ return Promise.all(promises)
36
+ }
37
+ }
38
+
39
+ module.exports = { MultiSpanProcessor }
@@ -0,0 +1,41 @@
1
+ 'use strict'
2
+
3
+ const { createContextKey } = require('@opentelemetry/api')
4
+
5
+ // Unfortunately, these kesy are not exported by the OpenTelemetry API :()
6
+ // And we HAVE to use these keys because are used by the propagators
7
+ const SPAN_KEY = createContextKey('OpenTelemetry Context Key SPAN')
8
+
9
+ // This is basicaklly the same as https://github.com/open-telemetry/opentelemetry-js/blob/main/api/src/context/context.ts#L85
10
+ // (so just a wrapper around a Map)
11
+ // Note that mutating the context is not allowed by the OpenTelemetry spec.
12
+ class PlatformaticContext {
13
+ _currentContext
14
+
15
+ constructor (parentContext) {
16
+ this._currentContext = parentContext ? new Map(parentContext) : new Map()
17
+
18
+ this.getValue = (key) => this._currentContext.get(key)
19
+
20
+ // Must create and return a new context
21
+ this.setValue = (key, value) => {
22
+ const context = new PlatformaticContext(this._currentContext)
23
+ context._currentContext.set(key, value)
24
+ return context
25
+ }
26
+
27
+ // Must return a new context
28
+ /* istanbul ignore next */
29
+ this.deleteValue = (key) => {
30
+ const context = new PlatformaticContext(this._currentContext)
31
+ context._currentContext.delete(key)
32
+ return context
33
+ }
34
+
35
+ this.setSpan = (span) => {
36
+ return this.setValue(SPAN_KEY, span)
37
+ }
38
+ }
39
+ }
40
+
41
+ module.exports = { PlatformaticContext }
@@ -0,0 +1,64 @@
1
+ 'use strict'
2
+
3
+ const { Resource } = require('@opentelemetry/resources')
4
+ const { AlwaysOnSampler, merge, CompositePropagator, W3CTraceContextPropagator } = require('@opentelemetry/core')
5
+ const { Tracer } = require('@opentelemetry/sdk-trace-base')
6
+ const { MultiSpanProcessor } = require('./multispan-processor')
7
+
8
+ class PlatformaticTracerProvider {
9
+ activeSpanProcessor = null
10
+ _registeredSpanProcessors = []
11
+ // This MUST be called `resource`, see: https://github.com/open-telemetry/opentelemetry-js/blob/main/packages/opentelemetry-sdk-trace-base/src/Tracer.ts#L57
12
+ resource = null
13
+ _config = null
14
+
15
+ constructor (config = {}) {
16
+ const mergedConfig = merge(
17
+ {},
18
+ {
19
+ sampler: new AlwaysOnSampler()
20
+ },
21
+ config
22
+ )
23
+ this.resource = mergedConfig.resource ?? Resource.empty()
24
+ this._config = Object.assign({}, mergedConfig, {
25
+ resource: this.resource
26
+ })
27
+ }
28
+
29
+ // This is the only mandatory API: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/api.md#get-a-tracer
30
+ getTracer (name, version, options) {
31
+ return new Tracer({ name, version }, this._config, this)
32
+ }
33
+
34
+ addSpanProcessor (spanProcessor) {
35
+ this._registeredSpanProcessors.push(spanProcessor)
36
+ this.activeSpanProcessor = new MultiSpanProcessor(
37
+ this._registeredSpanProcessors
38
+ )
39
+ }
40
+
41
+ getActiveSpanProcessor () {
42
+ return this.activeSpanProcessor
43
+ }
44
+
45
+ getPropagator () {
46
+ return new CompositePropagator({
47
+ propagators: [
48
+ new W3CTraceContextPropagator() // see: https://www.w3.org/TR/trace-context/
49
+ ]
50
+ })
51
+ }
52
+
53
+ forceFlush () {
54
+ // Let's do a fire-and-forget of forceFlush on all the processor for the time being.
55
+ // TODO: manage errors
56
+ this._registeredSpanProcessors.forEach(spanProcessor => spanProcessor.forceFlush())
57
+ }
58
+
59
+ shutdown () {
60
+ return this.activeSpanProcessor.shutdown()
61
+ }
62
+ }
63
+
64
+ module.exports = { PlatformaticTracerProvider }
package/lib/schema.js ADDED
@@ -0,0 +1,45 @@
1
+ 'use strict'
2
+
3
+ const TelemetrySchema = {
4
+ $id: '/OpenTelemetry',
5
+ type: 'object',
6
+ properties: {
7
+ serviceName: {
8
+ type: 'string',
9
+ description: 'The name of the service. Defaults to the folder name if not specified.'
10
+ },
11
+ version: {
12
+ type: 'string',
13
+ description: 'The version of the service (optional)'
14
+ },
15
+ exporter: {
16
+ type: 'object',
17
+ properties: {
18
+ type: {
19
+ type: 'string',
20
+ enum: ['console', 'otlp', 'zipkin', 'memory'],
21
+ default: 'console'
22
+ },
23
+ options: {
24
+ type: 'object',
25
+ description: 'Options for the exporter. These are passed directly to the exporter.',
26
+ properties: {
27
+ url: {
28
+ type: 'string',
29
+ description: 'The URL to send the traces to. Not used for console or memory exporters.'
30
+ },
31
+ headers: {
32
+ type: 'object',
33
+ description: 'Headers to send to the exporter. Not used for console or memory exporters.'
34
+ }
35
+ }
36
+ },
37
+ additionalProperties: false
38
+ }
39
+ }
40
+ },
41
+ required: ['serviceName'],
42
+ additionalProperties: false
43
+ }
44
+
45
+ module.exports = TelemetrySchema
@@ -0,0 +1,231 @@
1
+ 'use strict'
2
+
3
+ const fp = require('fastify-plugin')
4
+ const { SpanStatusCode } = require('@opentelemetry/api')
5
+ const { ConsoleSpanExporter, BatchSpanProcessor, SimpleSpanProcessor, InMemorySpanExporter } = require('@opentelemetry/sdk-trace-base')
6
+ const { SemanticResourceAttributes } = require('@opentelemetry/semantic-conventions')
7
+ const { Resource } = require('@opentelemetry/resources')
8
+ const { PlatformaticTracerProvider } = require('./platformatic-trace-provider')
9
+ const { PlatformaticContext } = require('./platformatic-context')
10
+ const { fastifyTextMapGetter, fastifyTextMapSetter } = require('./fastify-text-map')
11
+
12
+ // Platformatic telemetry plugin.
13
+ // Supported Exporters:
14
+ // - console
15
+ // - otlp: (which also supports jaeger, see: https://opentelemetry.io/docs/instrumentation/js/exporters/#otlp-endpoint)
16
+ // - zipkin (https://github.com/open-telemetry/opentelemetry-js/blob/main/packages/opentelemetry-exporter-zipkin/README.md)
17
+ // - memory: for testing
18
+
19
+ // This has been partially copied and modified from @autotelic/opentelemetry: https://github.com/autotelic/fastify-opentelemetry/blob/main/index.js
20
+ // , according with [MIT license](https://github.com/autotelic/fastify-opentelemetry/blob/main/LICENSE.md):
21
+ // MIT License
22
+ // Copyright (c) 2020 autotelic
23
+ // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
24
+ // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
25
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26
+
27
+ const { name: moduleName, version: moduleVersion } = require('../package.json')
28
+
29
+ function formatSpanName (request) {
30
+ const { method, routerPath } = request
31
+ /* istanbul ignore next */
32
+ return routerPath ? `${method} ${routerPath}` : method
33
+ }
34
+
35
+ const defaultFormatSpanAttributes = {
36
+ request (request) {
37
+ return {
38
+ 'req.method': request.raw.method,
39
+ 'req.url': request.raw.url
40
+ }
41
+ },
42
+ reply (reply) {
43
+ return {
44
+ 'reply.statusCode': reply.statusCode
45
+ }
46
+ },
47
+ error (error) {
48
+ return {
49
+ 'error.name': error.name,
50
+ 'error.message': error.message,
51
+ 'error.stack': error.stack
52
+ }
53
+ }
54
+ }
55
+
56
+ const setupProvider = (app, opts) => {
57
+ const { serviceName, version } = opts
58
+ let exporter = opts.exporter
59
+ if (!exporter) {
60
+ app.log.warn('No exporter configured, defaulting to console.')
61
+ exporter = { type: 'console' }
62
+ }
63
+ app.log.info(`Setting up telemetry for service: ${serviceName} version: ${version} and exporter of type ${exporter.type}`)
64
+ const provider = new PlatformaticTracerProvider({
65
+ resource: new Resource({
66
+ [SemanticResourceAttributes.SERVICE_NAME]: serviceName,
67
+ [SemanticResourceAttributes.SERVICE_VERSION]: version
68
+ })
69
+ })
70
+
71
+ // Exporter config:
72
+ // https://open-telemetry.github.io/opentelemetry-js/interfaces/_opentelemetry_exporter_zipkin.ExporterConfig.html
73
+ const exporterOptions = { ...exporter.options, serviceName }
74
+
75
+ let exporterObj
76
+ if (exporter.type === 'console') {
77
+ exporterObj = new ConsoleSpanExporter(exporterOptions)
78
+ } else if (exporter.type === 'otlp') {
79
+ // We require here because this require (and only the require!) creates some issue with c8 on some mjs tests on other modules. Since we need an assignemet here, we don't use a switch.
80
+ const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-proto')
81
+ exporterObj = new OTLPTraceExporter(exporterOptions)
82
+ } else if (exporter.type === 'zipkin') {
83
+ const { ZipkinExporter } = require('@opentelemetry/exporter-zipkin')
84
+ exporterObj = new ZipkinExporter(exporterOptions)
85
+ } else if (exporter.type === 'memory') {
86
+ exporterObj = new InMemorySpanExporter()
87
+ } else {
88
+ app.log.warn(`Unknown exporter type: ${exporter.type}, defaulting to console.`)
89
+ exporterObj = new ConsoleSpanExporter(exporterOptions)
90
+ }
91
+
92
+ // We use a SimpleSpanProcessor for the console/memory exporters and a BatchSpanProcessor for the others.
93
+ const spanProcessor = ['memory', 'console'].includes(exporter.type) ? new SimpleSpanProcessor(exporterObj) : new BatchSpanProcessor(exporterObj)
94
+ provider.addSpanProcessor(spanProcessor)
95
+ const tracer = provider.getTracer(moduleName, moduleVersion)
96
+ const propagator = provider.getPropagator()
97
+ return { tracer, exporter: exporterObj, propagator, provider }
98
+ }
99
+
100
+ async function setupTelemetry (app, opts) {
101
+ // const { serviceName, version } = opts
102
+ const openTelemetryAPIs = setupProvider(app, opts)
103
+ const { tracer, propagator, provider } = openTelemetryAPIs
104
+
105
+ const formatSpanAttributes = {
106
+ ...defaultFormatSpanAttributes,
107
+ ...(opts.formatSpanAttributes || {})
108
+ }
109
+
110
+ // expose the span as a request decorator
111
+ app.decorateRequest('span')
112
+
113
+ const startSpan = async (request) => {
114
+ // We populate the context with the incoming request headers
115
+ let context = propagator.extract(new PlatformaticContext(), request, fastifyTextMapGetter)
116
+
117
+ const span = tracer.startSpan(
118
+ formatSpanName(request),
119
+ {},
120
+ context
121
+ )
122
+ // Next 2 lines are needed by W3CTraceContextPropagator
123
+ context = context.setSpan(span)
124
+ span.setAttributes(formatSpanAttributes.request(request))
125
+ span.context = context
126
+ request.span = span
127
+ }
128
+
129
+ const setErrorInSpan = async (request, reply, error) => {
130
+ const span = request.span
131
+ span.setAttributes(formatSpanAttributes.error(error))
132
+ }
133
+
134
+ const injectPropagationHeadersInReply = async (request, reply) => {
135
+ const context = request.span.context
136
+ propagator.inject(context, reply, fastifyTextMapSetter)
137
+ }
138
+
139
+ const endSpan = async (request, reply) => {
140
+ const span = request.span
141
+ const spanStatus = { code: SpanStatusCode.OK }
142
+ if (reply.statusCode >= 400) {
143
+ spanStatus.code = SpanStatusCode.ERROR
144
+ }
145
+ span.setAttributes(formatSpanAttributes.reply(reply))
146
+ span.setStatus(spanStatus)
147
+ span.end()
148
+ }
149
+
150
+ app.addHook('onRequest', startSpan)
151
+ app.addHook('onSend', injectPropagationHeadersInReply)
152
+ app.addHook('onResponse', endSpan)
153
+ app.addHook('onError', setErrorInSpan)
154
+ app.addHook('onClose', async function () {
155
+ await provider.shutdown()
156
+ })
157
+
158
+ //* Client APIs
159
+ const getSpanPropagationHeaders = (span) => {
160
+ const context = span.context
161
+ const headers = {}
162
+ propagator.inject(context, headers, {
163
+ set (carrier, key, value) {
164
+ headers[key] = value
165
+ }
166
+ })
167
+ return headers
168
+ }
169
+
170
+ // If a context is passed, is used. Otherwise is a new one is created.
171
+ // Note that in this case we don't set the span in request, as this is a client call.
172
+ // So the client caller is responible of:
173
+ // - setting the propagatorHeaders in the client request
174
+ // - closing the span
175
+ const startSpanClient = (url, method, ctx) => {
176
+ let context = ctx || new PlatformaticContext()
177
+ /* istanbul ignore next */
178
+ method = method || ''
179
+ const span = tracer.startSpan(`${method} ${url}`, {}, context)
180
+ /* istanbul ignore next */
181
+ const attributes = url ? { 'server.url': url } : {}
182
+ span.setAttributes(attributes)
183
+
184
+ // Next 2 lines are needed by W3CTraceContextPropagator
185
+ context = context.setSpan(span)
186
+ span.context = context
187
+
188
+ const telemetryHeaders = getSpanPropagationHeaders(span)
189
+ return { span, telemetryHeaders }
190
+ }
191
+
192
+ const endSpanClient = (span, response) => {
193
+ /* istanbul ignore next */
194
+ if (!span) {
195
+ return
196
+ }
197
+ if (response) {
198
+ const spanStatus = { code: SpanStatusCode.OK }
199
+ if (response.statusCode >= 400) {
200
+ spanStatus.code = SpanStatusCode.ERROR
201
+ }
202
+ span.setAttributes({
203
+ 'response.statusCode': response.statusCode
204
+ })
205
+ span.setStatus(spanStatus)
206
+ } else {
207
+ span.setStatus({
208
+ code: SpanStatusCode.ERROR,
209
+ message: 'No response received'
210
+ })
211
+ }
212
+ span.end()
213
+ }
214
+
215
+ const setErrorInSpanClient = (span, error) => {
216
+ /* istanbul ignore next */
217
+ if (!span) {
218
+ return
219
+ }
220
+ span.setAttributes(formatSpanAttributes.error(error))
221
+ }
222
+
223
+ app.decorate('openTelemetry', {
224
+ ...openTelemetryAPIs,
225
+ startSpanClient,
226
+ endSpanClient,
227
+ setErrorInSpanClient
228
+ })
229
+ }
230
+
231
+ module.exports = fp(setupTelemetry)
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@platformatic/telemetry",
3
+ "version": "0.33.0",
4
+ "description": "OpenTelemetry integration for Platformatic",
5
+ "main": "index.js",
6
+ "author": "Marco Piraccini <marco.piraccini@gmail.com>",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/platformatic/platformatic.git"
10
+ },
11
+ "license": "Apache-2.0",
12
+ "devDependencies": {
13
+ "fastify": "^4.18.0",
14
+ "snazzy": "^9.0.0",
15
+ "standard": "^17.1.0",
16
+ "tap": "^16.3.6"
17
+ },
18
+ "dependencies": {
19
+ "@opentelemetry/api": "^1.4.1",
20
+ "@opentelemetry/core": "^1.15.0",
21
+ "@opentelemetry/exporter-trace-otlp-proto": "^0.41.0",
22
+ "@opentelemetry/exporter-zipkin": "^1.15.0",
23
+ "@opentelemetry/resources": "^1.15.0",
24
+ "@opentelemetry/sdk-trace-base": "^1.15.0",
25
+ "@opentelemetry/semantic-conventions": "^1.15.0",
26
+ "fastify-plugin": "^4.5.0"
27
+ },
28
+ "scripts": {
29
+ "test": "npm run lint | snazzy && tap test/*test.js",
30
+ "lint": "standard | snazzy"
31
+ }
32
+ }
@@ -0,0 +1,226 @@
1
+ 'use strict'
2
+
3
+ const { test } = require('tap')
4
+ const fastify = require('fastify')
5
+ const { SpanStatusCode } = require('@opentelemetry/api')
6
+ const telemetryPlugin = require('../lib/telemetry')
7
+ const { PlatformaticContext } = require('../lib/platformatic-context')
8
+ const { fastifyTextMapGetter } = require('../lib/fastify-text-map')
9
+
10
+ async function setupApp (pluginOpts, routeHandler, teardown) {
11
+ const app = fastify()
12
+ await app.register(telemetryPlugin, pluginOpts)
13
+ app.get('/test', routeHandler)
14
+ app.ready()
15
+ teardown(async () => {
16
+ await app.close()
17
+ const { exporter } = app.openTelemetry
18
+ if (exporter.constructor.name === 'InMemorySpanExporter') {
19
+ exporter.reset()
20
+ }
21
+ })
22
+ return app
23
+ }
24
+
25
+ test('should add the propagation headers correctly, new propagation started', async ({ equal, same, teardown }) => {
26
+ const handler = async (request, reply) => {
27
+ return { foo: 'bar' }
28
+ }
29
+
30
+ const app = await setupApp({
31
+ serviceName: 'test-service',
32
+ version: '1.0.0',
33
+ exporter: {
34
+ type: 'memory'
35
+ }
36
+ }, handler, teardown)
37
+
38
+ const { startSpanClient } = app.openTelemetry
39
+
40
+ const url = 'http://localhost:3000/test'
41
+ const { span, telemetryHeaders } = startSpanClient(url, 'GET')
42
+
43
+ const spanId = span._spanContext.spanId
44
+ const traceId = span._spanContext.traceId
45
+ same(telemetryHeaders, {
46
+ traceparent: `00-${traceId}-${spanId}-01`
47
+ })
48
+ })
49
+
50
+ test('should add the propagation headers correctly, with propagation already started', async ({ equal, same, teardown }) => {
51
+ const traceId = '5e994e8fb53b27c91dcd2fec22771d15'
52
+ const spanId = '166f3ab30f21800b'
53
+ const traceparent = `00-${traceId}-${spanId}-01`
54
+
55
+ const handler = async (request, reply) => {
56
+ return { foo: 'bar' }
57
+ }
58
+
59
+ const app = await setupApp({
60
+ serviceName: 'test-service',
61
+ version: '1.0.0',
62
+ exporter: {
63
+ type: 'memory'
64
+ }
65
+ }, handler, teardown)
66
+
67
+ const { startSpanClient } = app.openTelemetry
68
+
69
+ const url = 'http://localhost:3000/test'
70
+ const incomingHeaders = {
71
+ host: 'test',
72
+ traceparent
73
+ }
74
+ const { propagator } = app.openTelemetry
75
+ const context = propagator.extract(new PlatformaticContext(), { headers: incomingHeaders }, fastifyTextMapGetter)
76
+
77
+ const { span, telemetryHeaders } = startSpanClient(url, 'GET', context)
78
+
79
+ const spanId2 = span._spanContext.spanId
80
+ const traceId2 = span._spanContext.traceId
81
+
82
+ // We preserved the tracedId
83
+ same(traceId, traceId2)
84
+ same(telemetryHeaders, {
85
+ traceparent: `00-${traceId}-${spanId2}-01`
86
+ })
87
+ })
88
+
89
+ test('should trace a client request', async ({ equal, same, teardown }) => {
90
+ let receivedHeaders = null
91
+ const handler = async (request, reply) => {
92
+ receivedHeaders = request.headers
93
+ return { foo: 'bar' }
94
+ }
95
+
96
+ const app = await setupApp({
97
+ serviceName: 'test-service',
98
+ version: '1.0.0',
99
+ exporter: {
100
+ type: 'memory'
101
+ }
102
+ }, handler, teardown)
103
+
104
+ const { startSpanClient, endSpanClient } = app.openTelemetry
105
+
106
+ const url = 'http://localhost:3000/test'
107
+
108
+ const { propagator } = app.openTelemetry
109
+ const context = propagator.extract(new PlatformaticContext(), { headers: {} }, fastifyTextMapGetter)
110
+
111
+ const { span, telemetryHeaders } = startSpanClient(url, 'GET', context)
112
+ const args = {
113
+ method: 'GET',
114
+ url: '/test',
115
+ headers: {
116
+ ...telemetryHeaders
117
+ }
118
+ }
119
+
120
+ const response = await app.inject(args)
121
+ endSpanClient(span, response)
122
+
123
+ const { exporter } = app.openTelemetry
124
+ const finishedSpans = exporter.getFinishedSpans()
125
+ equal(finishedSpans.length, 2)
126
+ // We have two one for the client and one for the server
127
+ const spanServer = finishedSpans[0]
128
+ equal(spanServer.name, 'GET /test')
129
+ equal(spanServer.status.code, SpanStatusCode.OK)
130
+ equal(spanServer.attributes['req.method'], 'GET')
131
+ equal(spanServer.attributes['req.url'], '/test')
132
+ equal(spanServer.attributes['reply.statusCode'], 200)
133
+
134
+ const spanClient = finishedSpans[1]
135
+ equal(spanClient.name, 'GET http://localhost:3000/test')
136
+ equal(spanClient.status.code, SpanStatusCode.OK)
137
+ equal(spanClient.attributes['server.url'], 'http://localhost:3000/test')
138
+ equal(spanClient.attributes['response.statusCode'], 200)
139
+
140
+ // The traceparent header is added to the request and propagated to the server
141
+ equal(receivedHeaders.traceparent, telemetryHeaders.traceparent)
142
+ })
143
+
144
+ test('should trace a client request failing', async ({ equal, same, teardown }) => {
145
+ const handler = async (request, reply) => {
146
+ return { foo: 'bar' }
147
+ }
148
+
149
+ const app = await setupApp({
150
+ serviceName: 'test-service',
151
+ version: '1.0.0',
152
+ exporter: {
153
+ type: 'memory'
154
+ }
155
+ }, handler, teardown)
156
+
157
+ const { startSpanClient, endSpanClient } = app.openTelemetry
158
+
159
+ const { propagator } = app.openTelemetry
160
+ const context = propagator.extract(new PlatformaticContext(), { headers: {} }, fastifyTextMapGetter)
161
+
162
+ const url = 'http://localhost:3000/test'
163
+ const { span, telemetryHeaders } = startSpanClient(url, 'GET', context)
164
+ const args = {
165
+ method: 'GET',
166
+ url: '/wrong',
167
+ headers: telemetryHeaders
168
+ }
169
+ const response = await app.inject(args)
170
+ endSpanClient(span, response)
171
+
172
+ const { exporter } = app.openTelemetry
173
+ const finishedSpans = exporter.getFinishedSpans()
174
+ equal(finishedSpans.length, 2)
175
+ // We have two one for the client and one for the server
176
+ const spanServer = finishedSpans[0]
177
+ equal(spanServer.name, 'GET')
178
+ equal(spanServer.status.code, SpanStatusCode.ERROR)
179
+ equal(spanServer.attributes['req.method'], 'GET')
180
+ equal(spanServer.attributes['req.url'], '/wrong')
181
+ equal(spanServer.attributes['reply.statusCode'], 404)
182
+
183
+ const spanClient = finishedSpans[1]
184
+ equal(spanClient.name, 'GET http://localhost:3000/test')
185
+ equal(spanClient.status.code, SpanStatusCode.ERROR)
186
+ equal(spanClient.attributes['server.url'], 'http://localhost:3000/test')
187
+ equal(spanClient.attributes['response.statusCode'], 404)
188
+ })
189
+
190
+ test('should trace a client request failing (no HTTP error)', async ({ equal, same, teardown }) => {
191
+ const handler = async (request, reply) => {
192
+ return { foo: 'bar' }
193
+ }
194
+
195
+ const app = await setupApp({
196
+ serviceName: 'test-service',
197
+ version: '1.0.0',
198
+ exporter: {
199
+ type: 'memory'
200
+ }
201
+ }, handler, teardown)
202
+
203
+ const { startSpanClient, endSpanClient, setErrorInSpanClient } = app.openTelemetry
204
+
205
+ const url = 'http://localhost:3000/test'
206
+ const { span } = startSpanClient(url, 'GET')
207
+ try {
208
+ throw new Error('KABOOM!!!')
209
+ } catch (err) {
210
+ setErrorInSpanClient(span, err)
211
+ } finally {
212
+ endSpanClient(span)
213
+ }
214
+
215
+ const { exporter } = app.openTelemetry
216
+ const finishedSpans = exporter.getFinishedSpans()
217
+ equal(finishedSpans.length, 1)
218
+
219
+ const spanClient = finishedSpans[0]
220
+ equal(spanClient.name, 'GET http://localhost:3000/test')
221
+ equal(spanClient.status.code, SpanStatusCode.ERROR)
222
+ equal(spanClient.attributes['server.url'], 'http://localhost:3000/test')
223
+ equal(spanClient.attributes['error.name'], 'Error')
224
+ equal(spanClient.attributes['error.message'], 'KABOOM!!!')
225
+ equal(spanClient.attributes['error.stack'].includes('Error: KABOOM!!!'), true)
226
+ })
@@ -0,0 +1,81 @@
1
+ 'use strict'
2
+
3
+ const { test } = require('tap')
4
+ const { MultiSpanProcessor } = require('../lib/multispan-processor')
5
+
6
+ test('should add multiple processors', async ({ equal, same, teardown }) => {
7
+ const mockSpanProcessor = {
8
+ onStart: () => {},
9
+ onEnd: () => {},
10
+ shutdown: async () => {},
11
+ forceFlush: async () => {}
12
+ }
13
+ const processor = new MultiSpanProcessor()
14
+ equal(processor._spanProcessors.length, 0)
15
+
16
+ {
17
+ const processor = new MultiSpanProcessor([mockSpanProcessor, mockSpanProcessor])
18
+ equal(processor._spanProcessors.length, 2)
19
+ }
20
+ })
21
+
22
+ test('should call onStart on every processor', async ({ equal, same, teardown }) => {
23
+ let called1 = false
24
+ let called2 = false
25
+ const mockSpanProcessor1 = {
26
+ onStart: () => { called1 = true }
27
+ }
28
+ const mockSpanProcessor2 = {
29
+ called: false,
30
+ onStart: () => { called2 = true }
31
+ }
32
+ const processor = new MultiSpanProcessor([mockSpanProcessor1, mockSpanProcessor2])
33
+ processor.onStart()
34
+ equal(called1, true)
35
+ equal(called2, true)
36
+ })
37
+
38
+ test('should call onEnd on every processor', async ({ equal, same, teardown }) => {
39
+ let called1 = false
40
+ let called2 = false
41
+ const mockSpanProcessor1 = {
42
+ onEnd: () => { called1 = true }
43
+ }
44
+ const mockSpanProcessor2 = {
45
+ onEnd: () => { called2 = true }
46
+ }
47
+ const processor = new MultiSpanProcessor([mockSpanProcessor1, mockSpanProcessor2])
48
+ processor.onEnd()
49
+ equal(called1, true)
50
+ equal(called2, true)
51
+ })
52
+
53
+ test('should call shutdown on every processor', async ({ equal, same, teardown }) => {
54
+ let called1 = false
55
+ let called2 = false
56
+ const mockSpanProcessor1 = {
57
+ shutdown: async () => { called1 = true }
58
+ }
59
+ const mockSpanProcessor2 = {
60
+ shutdown: async () => { called2 = true }
61
+ }
62
+ const processor = new MultiSpanProcessor([mockSpanProcessor1, mockSpanProcessor2])
63
+ await processor.shutdown()
64
+ equal(called1, true)
65
+ equal(called2, true)
66
+ })
67
+
68
+ test('should call forceFlush on every processor', async ({ equal, same, teardown }) => {
69
+ let called1 = false
70
+ let called2 = false
71
+ const mockSpanProcessor1 = {
72
+ forceFlush: async () => { called1 = true }
73
+ }
74
+ const mockSpanProcessor2 = {
75
+ forceFlush: async () => { called2 = true }
76
+ }
77
+ const processor = new MultiSpanProcessor([mockSpanProcessor1, mockSpanProcessor2])
78
+ await processor.forceFlush()
79
+ equal(called1, true)
80
+ equal(called2, true)
81
+ })
@@ -0,0 +1,46 @@
1
+ 'use strict'
2
+
3
+ const { test } = require('tap')
4
+ const { PlatformaticTracerProvider } = require('../lib/platformatic-trace-provider')
5
+
6
+ test('should propagate forceFlush to all registered processors ', async ({ equal, same, teardown }) => {
7
+ let called1 = false
8
+ let called2 = false
9
+ const mockSpanProcessor1 = {
10
+ forceFlush: async () => { called1 = true }
11
+ }
12
+ const mockSpanProcessor2 = {
13
+ forceFlush: async () => { called2 = true }
14
+ }
15
+ const provider = new PlatformaticTracerProvider()
16
+ equal(provider._registeredSpanProcessors.length, 0)
17
+
18
+ provider.addSpanProcessor(mockSpanProcessor1)
19
+ provider.addSpanProcessor(mockSpanProcessor2)
20
+
21
+ equal(provider._registeredSpanProcessors.length, 2)
22
+ await provider.forceFlush()
23
+ equal(called1, true)
24
+ equal(called2, true)
25
+ })
26
+
27
+ test('should propagate shutdown to the active span processor, which should propagate to all the processors ', async ({ equal, same, teardown }) => {
28
+ let called1 = false
29
+ let called2 = false
30
+ const mockSpanProcessor1 = {
31
+ shutdown: async () => { called1 = true }
32
+ }
33
+ const mockSpanProcessor2 = {
34
+ shutdown: async () => { called2 = true }
35
+ }
36
+ const provider = new PlatformaticTracerProvider()
37
+ equal(provider._registeredSpanProcessors.length, 0)
38
+
39
+ provider.addSpanProcessor(mockSpanProcessor1)
40
+ provider.addSpanProcessor(mockSpanProcessor2)
41
+
42
+ equal(provider._registeredSpanProcessors.length, 2)
43
+ await provider.shutdown()
44
+ equal(called1, true)
45
+ equal(called2, true)
46
+ })
@@ -0,0 +1,208 @@
1
+ 'use strict'
2
+
3
+ const { test } = require('tap')
4
+ const fastify = require('fastify')
5
+ const { SpanStatusCode } = require('@opentelemetry/api')
6
+ const telemetryPlugin = require('../lib/telemetry')
7
+
8
+ async function setupApp (pluginOpts, routeHandler, teardown) {
9
+ const app = fastify()
10
+ await app.register(telemetryPlugin, pluginOpts)
11
+ app.get('/test', routeHandler)
12
+ app.ready()
13
+ teardown(async () => {
14
+ await app.close()
15
+ const { exporter } = app.openTelemetry
16
+ if (exporter.constructor.name === 'InMemorySpanExporter') {
17
+ exporter.reset()
18
+ }
19
+ })
20
+ return app
21
+ }
22
+
23
+ const injectArgs = {
24
+ method: 'GET',
25
+ url: '/test',
26
+ headers: {
27
+ host: 'test'
28
+ }
29
+ }
30
+
31
+ test('should trace a request not failing', async ({ equal, same, teardown }) => {
32
+ const handler = async (request, reply) => {
33
+ return { foo: 'bar' }
34
+ }
35
+
36
+ const app = await setupApp({
37
+ serviceName: 'test-service',
38
+ version: '1.0.0',
39
+ exporter: {
40
+ type: 'memory'
41
+ }
42
+ }, handler, teardown)
43
+
44
+ await app.inject(injectArgs)
45
+ const { exporter } = app.openTelemetry
46
+ const finishedSpans = exporter.getFinishedSpans()
47
+ equal(finishedSpans.length, 1)
48
+ const span = finishedSpans[0]
49
+ equal(span.name, 'GET /test')
50
+ equal(span.status.code, SpanStatusCode.OK)
51
+ equal(span.attributes['req.method'], 'GET')
52
+ equal(span.attributes['req.url'], '/test')
53
+ equal(span.attributes['reply.statusCode'], 200)
54
+ const resource = span.resource
55
+ same(resource.attributes['service.name'], 'test-service')
56
+ same(resource.attributes['service.version'], '1.0.0')
57
+ })
58
+
59
+ test('request should add attribute to a span', async ({ equal, same, teardown }) => {
60
+ const handler = async (request, reply) => {
61
+ request.span.setAttribute('foo', 'bar')
62
+ return { foo: 'bar' }
63
+ }
64
+
65
+ const app = await setupApp({
66
+ serviceName: 'test-service',
67
+ version: '1.0.0',
68
+ exporter: {
69
+ type: 'memory'
70
+ }
71
+ }, handler, teardown)
72
+
73
+ await app.inject(injectArgs)
74
+ const { exporter } = app.openTelemetry
75
+ const finishedSpans = exporter.getFinishedSpans()
76
+ equal(finishedSpans.length, 1)
77
+ const span = finishedSpans[0]
78
+ equal(span.name, 'GET /test')
79
+ equal(span.status.code, SpanStatusCode.OK)
80
+ equal(span.attributes['req.method'], 'GET')
81
+ equal(span.attributes['req.url'], '/test')
82
+ equal(span.attributes['reply.statusCode'], 200)
83
+ // This is the attribute we added
84
+ equal(span.attributes.foo, 'bar')
85
+ const resource = span.resource
86
+ same(resource.attributes['service.name'], 'test-service')
87
+ same(resource.attributes['service.version'], '1.0.0')
88
+ })
89
+
90
+ test('should be able to set the W3C trace context', async ({ equal, same, teardown, ok }) => {
91
+ const handler = async (request, reply) => {
92
+ const context = request.openTelemetry().span.context
93
+ const newContext = context.setValue('foo', 'bar')
94
+ request.openTelemetry().span.context = newContext
95
+ return { foo: 'bar' }
96
+ }
97
+
98
+ const app = await setupApp({
99
+ serviceName: 'test-service',
100
+ version: '1.0.0',
101
+ exporter: {
102
+ type: 'memory'
103
+ }
104
+ }, handler, teardown)
105
+
106
+ const response = await app.inject(injectArgs)
107
+ // see: https://www.w3.org/TR/trace-context/#design-overview
108
+ ok(response.headers.traceparent)
109
+ })
110
+
111
+ test('should trace a request that fails', async ({ equal, same, teardown }) => {
112
+ const handler = async (request, reply) => {
113
+ throw new Error('booooom!!!')
114
+ }
115
+ const app = await setupApp({
116
+ serviceName: 'test-service',
117
+ version: '1.0.0',
118
+ exporter: {
119
+ type: 'memory'
120
+ }
121
+ }, handler, teardown)
122
+
123
+ await app.inject(injectArgs)
124
+ const { exporter } = app.openTelemetry
125
+ const finishedSpans = exporter.getFinishedSpans()
126
+ equal(finishedSpans.length, 1)
127
+ const span = finishedSpans[0]
128
+ equal(span.name, 'GET /test')
129
+ equal(span.status.code, SpanStatusCode.ERROR)
130
+ equal(span.attributes['req.method'], 'GET')
131
+ equal(span.attributes['req.url'], '/test')
132
+ equal(span.attributes['reply.statusCode'], 500)
133
+ equal(span.attributes['error.message'], 'booooom!!!')
134
+ const resource = span.resource
135
+ same(resource.attributes['service.name'], 'test-service')
136
+ same(resource.attributes['service.version'], '1.0.0')
137
+ })
138
+
139
+ test('if no exporter is configured, should default to console', async ({ equal, same, teardown }) => {
140
+ const handler = async (request, reply) => {
141
+ return {}
142
+ }
143
+ const app = await setupApp({
144
+ serviceName: 'test-service',
145
+ version: '1.0.0'
146
+ }, handler, teardown)
147
+
148
+ await app.inject(injectArgs)
149
+ const { exporter } = app.openTelemetry
150
+ same(exporter.constructor.name, 'ConsoleSpanExporter')
151
+ })
152
+
153
+ test('should configure OTLP correctly', async ({ equal, same, teardown }) => {
154
+ const handler = async (request, reply) => {
155
+ return {}
156
+ }
157
+ const app = await setupApp({
158
+ serviceName: 'test-service',
159
+ version: '1.0.0',
160
+ exporter: {
161
+ type: 'otlp',
162
+ options: {
163
+ url: 'http://localhost:4317'
164
+ }
165
+ }
166
+ }, handler, teardown)
167
+
168
+ const { exporter } = app.openTelemetry
169
+ same(exporter.constructor.name, 'OTLPTraceExporter')
170
+ same(exporter.url, 'http://localhost:4317')
171
+ })
172
+
173
+ test('should configure Zipkin correctly', async ({ equal, same, teardown }) => {
174
+ const handler = async (request, reply) => {
175
+ return {}
176
+ }
177
+ const app = await setupApp({
178
+ serviceName: 'test-service',
179
+ version: '1.0.0',
180
+ exporter: {
181
+ type: 'zipkin',
182
+ options: {
183
+ url: 'http://localhost:9876'
184
+ }
185
+ }
186
+ }, handler, teardown)
187
+
188
+ const { exporter } = app.openTelemetry
189
+ same(exporter.constructor.name, 'ZipkinExporter')
190
+ same(exporter._urlStr, 'http://localhost:9876')
191
+ })
192
+
193
+ test('wrong exporter is configured, should default to console', async ({ equal, same, teardown }) => {
194
+ const handler = async (request, reply) => {
195
+ return {}
196
+ }
197
+ const app = await setupApp({
198
+ serviceName: 'test-service',
199
+ version: '1.0.0',
200
+ exporter: {
201
+ type: 'wrong-exporter'
202
+ }
203
+ }, handler, teardown)
204
+
205
+ await app.inject(injectArgs)
206
+ const { exporter } = app.openTelemetry
207
+ same(exporter.constructor.name, 'ConsoleSpanExporter')
208
+ })