|
| 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 <subscription-name-or-id> |
| 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)); |