Cloud Pub/Sub Client Library for Node.js

repository·main·Indexed 20 days ago

https://github.com/googleapis/nodejs-pubsub

A stable Node.js client library for interacting with Google Cloud Pub/Sub, a fully-managed real-time messaging service. It enables developers to send and receive messages between independent applications using topics and subscriptions. The library supports advanced features including Avro and Proto schemas, dead-letter policies, exactly-once delivery, message ordering, and ingestion from external sources like AWS MSK, Azure Event Hubs, and Confluent Cloud.

Tokens
19.9K
Snippets
69
Records
75
Agent score
68%

What's inside @google-cloud/pubsub

  1. Understand the library versioning and stability

    main

    This library follows Semantic Versioning (SemVer) and is classified as stable.

    As a stable library, the code surface is guaranteed not to change in backwards-incompatible ways unless absolutely necessary (such as for critical security issues) or following an extensive deprecation period. Issues and requests for stable libraries are addressed with the highest priority.

  2. Quickstart: Install and use the Google Cloud Pub/Sub client library

    main

    To get started with Cloud Pub/Sub in Node.js, follow these steps to set up your environment, install the library, and run a basic publish/subscribe flow.

    1. Prerequisites

    • Select or create a Google Cloud Platform project.
    • Enable billing for your project.
    • Enable the Google Cloud Pub/Sub API.
    • Set up authentication to allow your local workstation to access the API.

    2. Installation

    Install the client library using npm:

    npm install @google-cloud/pubsub

    3. Basic Usage Example

    The following example demonstrates how to instantiate a client, create a topic, create a subscription, listen for messages, and publish a message.

    // Imports the Google Cloud client library
    const {PubSub} = require('@google-cloud/pubsub');
    
    async function quickstart(
      projectId = 'your-project-id', // Your Google Cloud Platform project ID
      topicNameOrId = 'my-topic', // Name for the new topic to create
      subscriptionName = 'my-sub', // Name for the new subscription to create
    ) {
      // Instantiates a client
      const pubsub = new PubSub({projectId});
    
      // Creates a new topic
      const [topic] = await pubsub.createTopic(topicNameOrId);
      console.log(`Topic ${topic.name} created.`);
    
      // Creates a subscription on that new topic
      const [subscription] = await topic.createSubscription(subscriptionName);
    
      // Receive callbacks for new messages on the subscription
      subscription.on('message', message => {
        console.log('Received message:', message.data.toString());
        process.exit(0);
      });
    
      // Receive callbacks for errors on the subscription
      subscription.on('error', error => {
        console.error('Received error:', error);
        process.exit(1);
      });
    
      // Send a message to the topic
      await topic.publishMessage({data: Buffer.from('Test message!')});
    }
  3. Quickstart with Pub/Sub Client Library

    main

    A basic introduction to using the Google Cloud Pub/Sub client library. This sample covers the fundamental workflow of interacting with a project, topic, and subscription.

    node quickstart.js <project-id> <topic-name-or-id> <subscription-name-or-id>
  4. Set up the Pub/Sub Node.js samples environment

    main

    To run the provided code samples, you must first ensure you have followed the standard client library setup instructions. Once the client library is configured, navigate to the samples directory and install the necessary dependencies using npm install.

    cd samples
    npm install
    cd ..
  5. Manage Avro and Proto schemas

    main

    Pub/Sub allows you to define schemas for your messages using Avro or Protocol Buffers (Proto). You can create new schemas or commit new revisions to existing ones.

    # Avro
    node createAvroSchema.js <schema-name> <avsc-filename>
    node commitAvroSchema.js <schema-name> <avsc-filename>
    
    # Proto
    node createProtoSchema.js <schema-name> <proto-filename>
    node commitProtoSchema.js <schema-name> <proto-filename>
  6. Check Node.js version compatibility

    main

    The @google-cloud/pubsub client library is compatible with all current active and maintenance versions of Node.js.

    If you are using an end-of-life (EOL) version of Node.js, you can install client libraries specifically targeting those versions using npm [dist-tags]. These legacy versions follow the naming convention legacy-(version). Note that legacy versions are not tested in continuous integration, may lack security patches, and may have outdated dependencies.

    # Example: Install client libraries compatible with Node.js 8
    npm install @google-cloud/pubsub@legacy-8
  7. Create a topic with ingestion from external sources

    main

    Pub/Sub supports ingesting data from various external cloud and streaming services. Use the following patterns to create topics with ingestion enabled:

    • AWS MSK: Ingest from Amazon Managed Streaming for Apache Kafka.
    • Azure Event Hubs: Ingest from Azure Event Hubs.
    • Confluent Cloud: Ingest from Confluent Cloud.
    • Kinesis: Ingest from Amazon Kinesis.
    • Cloud Storage: Ingest from Google Cloud Storage buckets.
    # AWS MSK
    node createTopicWithAwsMskIngestion.js <topic-name> <cluster-arn> <msk-topic> <role-arn> <gcp-service-account>
    
    # Azure Event Hubs
    node createTopicWithAzureEventHubsIngestion.js <topic-name> <cluster-arn> <msk-topic> <role-arn> <gcp-service-account>
    
    # Confluent Cloud
    node createTopicWithConfluentCloudIngestion.js <topic-name> <bootstrap-server> <cluster-id> <confluent-topic> <identity-pool-id> <gcp-service-account>
    
    # Kinesis
    node createTopicWithKinesisIngestion.js <topic-name> <role-arn> <gcp-service-account> <stream-arn> <consumer-arn>
    
    # Cloud Storage
    node createTopicWithCloudStorageIngestion.js <topic-name> <bucket> <input-format> <text-delimiter> <match-glob> <minimum-object-creation-time>
  8. Configure the client to use gRPC C++ bindings

    main

    In certain workflows or environments, you may want to use the C++ gRPC implementation instead of the default one. To do this, you must install the grpc package and pass it to the PubSub constructor.

    1. Install grpc as a dependency:
      npm install grpc
    2. Pass the grpc instance to the PubSub constructor.
    const {PubSub} = require('@google-cloud/pubsub');
    const grpc = require('grpc');
    const pubsub = new PubSub({grpc});
  9. Create a subscription with advanced configurations

    main

    Pub/Sub supports several specialized subscription types. Use the following command patterns to implement specific behaviors:

    • Dead Letter Policy: For handling failed messages by sending them to a dead-letter topic.
    • Exactly-once delivery: To ensure messages are delivered exactly once.
    • Filtering: To only receive messages that match a specific filter string.
    • Ordering: To enable message ordering.
    • Retry Policy: To configure how the service retries failed deliveries.
    # Dead Letter Policy
    node createSubscriptionWithDeadLetterPolicy.js <topic-name-or-id> <subscription-name-or-id> <dead-letter-topic-name-or-id>
    
    # Exactly-once delivery
    node createSubscriptionWithExactlyOnceDelivery.js <topic-name-or-id> <subscription-name-or-id>
    
    # Filtering
    node createSubscriptionWithFiltering.js <topic-name-or-id> <subscription-name-or-id> <filter-string>
    
    # Ordering enabled
    node createSubscriptionWithOrdering.js <topic-name-or-id> <subscription-name-or-id>
    
    # Retry Policy
    node createSubscriptionWithRetryPolicy.js <topic-name-or-id> <subscription-name-or-id>
  10. Run the benchwrapper gRPC server

    main

    The benchwrapper is a lightweight gRPC server used for benchmarking the Pub/Sub library. To run it, you must install dependencies and set the PUBSUB_EMULATOR_HOST environment variable to point to your local emulator (e.g., localhost:8080). You can specify a custom port using the --port flag.

    cd nodejs-pubsub
    npm install
    export PUBSUB_EMULATOR_HOST=localhost:8080
    npm run benchwrapper -- --port 50051
  11. Explore Google Cloud Pub/Sub Node.js Samples

    main
    The repository contains a comprehensive collection of code samples located in the samples/ directory. These samples demonstrate various Pub/Sub operations, including topic and subscription management, schema handling (Avro and Proto), message publishing (including batching and ordering), and message listening (including exactly-once delivery and flow control). Each sample includes its own README.md with specific instructions for running that particular example. Many samples can be opened and run directly in Google Cloud Shell via the provided links.