Skip to content

Commit 4b5c90d

Browse files
feywindgcf-owl-bot[bot]release-please[bot]alevenberg
authored
feat: add support for OTel context propagation and harmonized spans (#1833)
* feat: use the propagation inject framework for OpenTelemetry publishes * feat: add propagation extraction to subscriber for OpenTelemetry * feat: work in progress on adding sub-spans * add more spans * wrap subscriber on() handlers to get better receive process spans * update otel core version for tests * fix: change some span names for doc updates * fix: move emitter wrapper out one level, to catch user functions properly * fix: don't send anything besides what's actually needed during publish * fix: close the publish span at RPC time, not up front * fix: delay caching of the trace provider so the user has a chance to make one * build: bring OTel versions back to compatible with Node 12 * fix: clean up a few more namespace pollution issues in OTel support * tests: manually end the publish span for tests * build: update package names for recent version updates * chore: get versions of OTel that work together and with Node 12 * chore: linter nit * chore: another linter nit * chore: OTel sample formatting * chore: some internal renaming to reflect the function rather than name of telemetry tracing * fix: more work towards the Promise-first publish flow * tests: remove unnecessary init line * fix: add tracing support for updating the topic name in publisher spans * fix: use the most up to date name for topic, subscription, and iam * fix: update telemetry spans before publishing, in case the topic name wasn't ready * chore: calm linter qualms * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * fix: update drain() not to promisify * tests: update unit tests for recent promise changes to publish() * feat: add modAck spans during leasing * docs: add more code comment docs * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * tests: unit test fixes, also include deadline and initial parameters for modAck * fix: make sure the subscriber span ends, update sample * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * tests: update unit test for latest changes * chore: pull promise-based publish out of OTel change * tests: update otel sample test * wip: end all telemetry spans when clear() is called * wip: add more unit tests * fix: include batch size with each published message span * chore: fix lint * fix: separate out the getter and setter classes * chore: rename span related objects in subscriber * chore: rename SpanMaker * docs: improved comments and lint fixes * docs: more class/comment updating * fix: missing spans caused by renames; also do more renames * tests: more renaming issues * tests: add otel test for FlowControlledPublisher * tests: add lease manager tests for otel * tests: add SubscriberSpans unit tests * fix: simplify logic for HTTP/1.1 REST fallback option (#1809) * fix: simplify logic for HTTP/1.1 REST fallback option For the `fallback` parameter, all values considered as `true` in Boolean context will enable HTTP/1.1 REST fallback, since the other fallback transport, proto over HTTP, is removed from `google-gax` v4. PiperOrigin-RevId: 559812260 Source-Link: googleapis/googleapis@6a6fd29 Source-Link: googleapis/googleapis-gen@56c1665 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNTZjMTY2NTdlN2E1OTEyMmIxZGE5NDc3MWE5ZWY0MDk4OWMyODJjMCJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --------- Co-authored-by: Owl Bot * build: update Node.js version and base Debian version (#1793) * build: update Node.js version and base Debian version * test: update Python and Node versions in container test YAMLs Source-Link: googleapis/synthtool@f54a720 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-nodejs:latest@sha256:aeccbef8061fc122542e8f381c4e7b66b32e23dda522e94c68346585dc408f0d Co-authored-by: Owl Bot Co-authored-by: Megan Potter <[email protected]> * docs: fix node release schedule link (#1794) Co-authored-by: Jeffrey Rennie Source-Link: googleapis/synthtool@1a24315 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-nodejs:latest@sha256:e08f9a3757808cdaf7a377e962308c65c4d7eff12db206d4fae702dd50d43430 Co-authored-by: Owl Bot Co-authored-by: Megan Potter <[email protected]> * chore: update release-please post-processing for nodejs apiary (#1805) * chore: update release-please post-processing for nodejs apiary Source-Link: googleapis/synthtool@59fe44f Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-nodejs:latest@sha256:606f3d9d99a1c7cdfa7158cbb1a75bfeef490655e246a2052f9ee741740d736c Co-authored-by: Owl Bot * fix: Make retry policy back off more aggressively for RPCs that retry RESOURCE_EXHAUSTD (#1806) * fix: Make retry policy back off more aggressively for RPCs that retry RESOURCE_EXHAUSTD PiperOrigin-RevId: 557935020 Source-Link: googleapis/googleapis@38e1f31 Source-Link: googleapis/googleapis-gen@5bbe39d Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNWJiZTM5ZDM3MjE4YTQyMGIyMzY4YzM3NTQxZGU1ODg3ZGI3ZDZhZiJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --------- Co-authored-by: Owl Bot * fix: set grpc keepalive time|outs by default (#1814) * fix: always fill the topic and sub names when creating from a PubSub object (#1816) * chore(legacy-v3): release 3.7.4 (#1820) Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com> * docs: update copyrights to make header-check happy * chore: remove left-in console.trace * feat: update opentelemetry packages to latest * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * samples: mostly whitespace, but updated OTel sample * feat: updates for the new design doc: batching, events, separate RPC span * tests: fix / update tests for batch changes * feat: change ack/nack/modack to be events * fix: fixes for previous commits * fix: move span closing to subscriber, upon (n)ack * docs: update custom gcp attributes * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * docs: update subscriber comments * tests: add unit tests for shutdown events * fix: missed commits from previous * fix: update span attributes for ordering key Co-authored-by: Anna Levenberg * fix: update gcp.pubsub to gcp_pubsub * feat: add back in receive response spans * docs: fix inadequate comments for deadline * feat: add ack/nack/modack events in processing * fix: publisher -> publish scheduler Co-authored-by: Anna Levenberg * chore: fix intermediate samples build exclusion * feat: update otel span names and attributes to latest spec * chore: remove extraneous import * feat: add publish start/end events * docs: comment updates about modack spans * tests: add a bunch of unit tests for new otel stuff * fix: subId might be undefined * fix: revert incorrect attribute change * docs: clarify some comments * tests: update the test for the last commit * fix: change processing span to use ack/nack instead of callback time * docs: fix copyright ranges on renamed/updated files * chore: OTel changed how semantic attribute names are specified * tests: update otel sample tests for latest changes * samples: update JS otel sample from TS * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * samples: update otel tracing sample with the correct tags and some other cleanup * samples: split otel samples into listen/publish * tests: fix resource name for otel * build: remove defunct typing * feat: add support for globally enabling (and disabling) otel tracing * feat: add bidi links between RPC and message spans, and filter by isSampled * feat: track code.function * docs: update comment based on CR * tests: publishSpan might be undefined if tracing isn't enabled * chore: small merge issue * fix: update spans for ack/modack to match newest spec * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * samples: add the otel enable flag to new otel samples * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * docs: last minute review, mostly adding private/internal doc tags --------- Co-authored-by: Owl Bot Co-authored-by: gcf-owl-bot[bot] <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com> Co-authored-by: Anna Levenberg
1 parent b8b625d commit 4b5c90d

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+2708
-557
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
/.nyc_output
66
/docs/
77
/out/
8-
/build/
8+
**/build/
99
system-test/secrets.js
1010
system-test/*key.json
1111
*.lock

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,15 +163,16 @@ Samples are in the [`samples/`](https://github.com/googleapis/nodejs-pubsub/tree
163163
| Listen with exactly-once delivery | [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/listenForMessagesWithExactlyOnceDelivery.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/listenForMessagesWithExactlyOnceDelivery.js,samples/README.md) |
164164
| Listen For Protobuf Messages | [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/listenForProtobufMessages.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/listenForProtobufMessages.js,samples/README.md) |
165165
| Listen For Messages With Custom Attributes | [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/listenWithCustomAttributes.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/listenWithCustomAttributes.js,samples/README.md) |
166+
| Subscribe with OpenTelemetry Tracing | [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/listenWithOpenTelemetryTracing.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/listenWithOpenTelemetryTracing.js,samples/README.md) |
166167
| Modify Push Configuration | [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/modifyPushConfig.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/modifyPushConfig.js,samples/README.md) |
167-
| OpenTelemetry Tracing | [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/openTelemetryTracing.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/openTelemetryTracing.js,samples/README.md) |
168168
| Publish Avro Records to a Topic | [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/publishAvroRecords.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/publishAvroRecords.js,samples/README.md) |
169169
| Publish Batched Messages | [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/publishBatchedMessages.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/publishBatchedMessages.js,samples/README.md) |
170170
| Publish Message | [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/publishMessage.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/publishMessage.js,samples/README.md) |
171171
| Publish Message With Custom Attributes | [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/publishMessageWithCustomAttributes.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/publishMessageWithCustomAttributes.js,samples/README.md) |
172172
| Publish Ordered Message | [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/publishOrderedMessage.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/publishOrderedMessage.js,samples/README.md) |
173173
| Publish Protobuf Messages to a Topic | [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/publishProtobufMessages.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/publishProtobufMessages.js,samples/README.md) |
174174
| Publish with flow control | [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/publishWithFlowControl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/publishWithFlowControl.js,samples/README.md) |
175+
| Publish with OpenTelemetry Tracing | [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/publishWithOpenTelemetryTracing.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/publishWithOpenTelemetryTracing.js,samples/README.md) |
175176
| Publish With Retry Settings | [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/publishWithRetrySettings.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/publishWithRetrySettings.js,samples/README.md) |
176177
| Quickstart | [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/quickstart.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/quickstart.js,samples/README.md) |
177178
| Remove Dead Letter Policy | [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/removeDeadLetterPolicy.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/removeDeadLetterPolicy.js,samples/README.md) |

package.json

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,8 @@
5151
"@google-cloud/precise-date": "^4.0.0",
5252
"@google-cloud/projectify": "^4.0.0",
5353
"@google-cloud/promisify": "^4.0.0",
54-
"@opentelemetry/api": "~1.8.0",
55-
"@opentelemetry/semantic-conventions": "~1.21.0",
54+
"@opentelemetry/api": "~1.9.0",
55+
"@opentelemetry/semantic-conventions": "~1.25.1",
5656
"arrify": "^2.0.0",
5757
"extend": "^3.0.2",
5858
"google-auth-library": "^9.3.0",
@@ -64,7 +64,8 @@
6464
},
6565
"devDependencies": {
6666
"@grpc/proto-loader": "^0.7.0",
67-
"@opentelemetry/tracing": "^0.24.0",
67+
"@opentelemetry/core": "^1.17.0",
68+
"@opentelemetry/sdk-trace-base": "^1.17.0",
6869
"@types/duplexify": "^3.6.4",
6970
"@types/extend": "^3.0.0",
7071
"@types/lodash.snakecase": "^4.1.6",

protos/protos.json

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

samples/README.md

Lines changed: 31 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -60,15 +60,16 @@ guides.
6060
* [Listen with exactly-once delivery](#listen-with-exactly-once-delivery)
6161
* [Listen For Protobuf Messages](#listen-for-protobuf-messages)
6262
* [Listen For Messages With Custom Attributes](#listen-for-messages-with-custom-attributes)
63+
* [Subscribe with OpenTelemetry Tracing](#subscribe-with-opentelemetry-tracing)
6364
* [Modify Push Configuration](#modify-push-configuration)
64-
* [OpenTelemetry Tracing](#opentelemetry-tracing)
6565
* [Publish Avro Records to a Topic](#publish-avro-records-to-a-topic)
6666
* [Publish Batched Messages](#publish-batched-messages)
6767
* [Publish Message](#publish-message)
6868
* [Publish Message With Custom Attributes](#publish-message-with-custom-attributes)
6969
* [Publish Ordered Message](#publish-ordered-message)
7070
* [Publish Protobuf Messages to a Topic](#publish-protobuf-messages-to-a-topic)
7171
* [Publish with flow control](#publish-with-flow-control)
72+
* [Publish with OpenTelemetry Tracing](#publish-with-opentelemetry-tracing)
7273
* [Publish With Retry Settings](#publish-with-retry-settings)
7374
* [Quickstart](#quickstart)
7475
* [Remove Dead Letter Policy](#remove-dead-letter-policy)
@@ -862,37 +863,37 @@ __Usage:__
862863

863864

864865

865-
### Modify Push Configuration
866+
### Subscribe with OpenTelemetry Tracing
866867

867-
Modifies the configuration of an existing push subscription.
868+
Demonstrates how to enable OpenTelemetry tracing in a subscriber.
868869

869-
View the [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/modifyPushConfig.js).
870+
View the [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/listenWithOpenTelemetryTracing.js).
870871

871-
[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/modifyPushConfig.js,samples/README.md)
872+
[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/listenWithOpenTelemetryTracing.js,samples/README.md)
872873

873874
__Usage:__
874875

875876

876-
`node modifyPushConfig.js `
877+
`node listenWithOpenTelemetryTracing.js `
877878

878879

879880
-----
880881

881882

882883

883884

884-
### OpenTelemetry Tracing
885+
### Modify Push Configuration
885886

886-
Demonstrates how to enable OpenTelemetry tracing in a publisher or subscriber.
887+
Modifies the configuration of an existing push subscription.
887888

888-
View the [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/openTelemetryTracing.js).
889+
View the [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/modifyPushConfig.js).
889890

890-
[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/openTelemetryTracing.js,samples/README.md)
891+
[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/modifyPushConfig.js,samples/README.md)
891892

892893
__Usage:__
893894

894895

895-
`node openTelemetryTracing.js `
896+
`node modifyPushConfig.js `
896897

897898

898899
-----
@@ -1033,6 +1034,25 @@ __Usage:__
10331034

10341035

10351036

1037+
### Publish with OpenTelemetry Tracing
1038+
1039+
Demonstrates how to enable OpenTelemetry tracing in a publisher.
1040+
1041+
View the [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/publishWithOpenTelemetryTracing.js).
1042+
1043+
[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/publishWithOpenTelemetryTracing.js,samples/README.md)
1044+
1045+
__Usage:__
1046+
1047+
1048+
`node openTelemetryTracing.js `
1049+
1050+
1051+
-----
1052+
1053+
1054+
1055+
10361056
### Publish With Retry Settings
10371057

10381058
Publishes a message to a topic with retry settings.
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
// Copyright 2020-2024 Google LLC
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.
14+
15+
// This is a generated sample, using the typeless sample bot. Please
16+
// look for the source TypeScript sample (.ts) for modifications.
17+
'use strict';
18+
19+
/**
20+
* This sample demonstrates how to add OpenTelemetry tracing to the
21+
* Google Cloud Pub/Sub API.
22+
*
23+
* For more information, see the README.md under /pubsub and the documentation
24+
* at https://cloud.google.com/pubsub/docs.
25+
*/
26+
27+
// sample-metadata:
28+
// title: Subscribe with OpenTelemetry Tracing
29+
// description: Demonstrates how to enable OpenTelemetry tracing in a subscriber.
30+
// usage: node listenWithOpenTelemetryTracing.js
31+
32+
const OTEL_TIMEOUT = 2;
33+
const SUBSCRIBER_TIMEOUT = 10;
34+
35+
// [START pubsub_subscribe_otel_tracing]
36+
/**
37+
* TODO(developer): Uncomment these variables before running the sample.
38+
*/
39+
// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_OR_ID';
40+
41+
// Imports the Google Cloud client library
42+
const {PubSub} = require('@google-cloud/pubsub');
43+
44+
// Imports the OpenTelemetry API
45+
const {NodeTracerProvider} = require('@opentelemetry/sdk-trace-node');
46+
const {diag, DiagConsoleLogger, DiagLogLevel} = require('@opentelemetry/api');
47+
const {SimpleSpanProcessor} = require('@opentelemetry/sdk-trace-base');
48+
49+
// To output to the console for testing, use the ConsoleSpanExporter.
50+
// import {ConsoleSpanExporter} from '@opentelemetry/sdk-trace-base';
51+
52+
// To output to Cloud Trace, import the OpenTelemetry bridge library.
53+
const {
54+
TraceExporter,
55+
} = require('@google-cloud/opentelemetry-cloud-trace-exporter');
56+
57+
const {Resource} = require('@opentelemetry/resources');
58+
const {
59+
SEMRESATTRS_SERVICE_NAME,
60+
} = require('@opentelemetry/semantic-conventions');
61+
62+
// Enable the diagnostic logger for OpenTelemetry
63+
diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.DEBUG);
64+
65+
// Log spans out to the console, for testing.
66+
// const exporter = new ConsoleSpanExporter();
67+
68+
// Log spans out to Cloud Trace, for production.
69+
const exporter = new TraceExporter();
70+
71+
// Build a tracer provider and a span processor to do
72+
// something with the spans we're generating.
73+
const provider = new NodeTracerProvider({
74+
resource: new Resource({
75+
[SEMRESATTRS_SERVICE_NAME]: 'otel subscriber example',
76+
}),
77+
});
78+
const processor = new SimpleSpanProcessor(exporter);
79+
provider.addSpanProcessor(processor);
80+
provider.register();
81+
82+
// Creates a client; cache this for further use.
83+
const pubSubClient = new PubSub({enableOpenTelemetryTracing: true});
84+
85+
async function subscriptionListen(subscriptionNameOrId) {
86+
const subscriber = pubSubClient.subscription(subscriptionNameOrId);
87+
88+
// Message handler for subscriber
89+
const messageHandler = async message => {
90+
console.log(`Message ${message.id} received.`);
91+
message.ack();
92+
};
93+
94+
// Error handler for subscriber
95+
const errorHandler = async error => {
96+
console.log('Received error:', error);
97+
};
98+
99+
// Listens for new messages from the topic
100+
subscriber.on('message', messageHandler);
101+
subscriber.on('error', errorHandler);
102+
103+
// Ensures that all spans got flushed by the exporter. This function
104+
// is in service to making sure that any buffered Pub/Sub messages
105+
// and/or OpenTelemetry spans are properly flushed to the server
106+
// side. In normal usage, you'd only need to do something like this
107+
// on process shutdown.
108+
async function shutdown() {
109+
await subscriber.close();
110+
await processor.forceFlush();
111+
await new Promise(r => setTimeout(r, OTEL_TIMEOUT * 1000));
112+
}
113+
114+
// Wait a bit for the subscription to receive messages, then shut down
115+
// gracefully. This is for the sample only; normally you would not need
116+
// this delay.
117+
await new Promise(r =>
118+
setTimeout(async () => {
119+
subscriber.removeAllListeners();
120+
await shutdown();
121+
r();
122+
}, SUBSCRIBER_TIMEOUT * 1000)
123+
);
124+
}
125+
// [END pubsub_subscribe_otel_tracing]
126+
127+
function main(subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID') {
128+
subscriptionListen(subscriptionNameOrId).catch(err => {
129+
console.error(err.message);
130+
process.exitCode = 1;
131+
});
132+
}
133+
134+
main(...process.argv.slice(2));

0 commit comments

Comments
 (0)