Skip to main content

google_cloud_pubsub/
lib.rs

1// Copyright 2025 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//     https://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//! Google Cloud Client Libraries for Rust - Pub/Sub
16//!
17//! This crate contains traits, types, and functions to interact with
18//! [Pub/Sub]. Most applications will use the structs defined in the
19//! [client] module.
20//!
21//! For publishing messages:
22//! * [Publisher][client::Publisher]
23//!
24//! For receiving messages:
25//! * [Subscriber][client::Subscriber]
26//!
27//! For administrative operations:
28//! * [TopicAdmin][client::TopicAdmin]
29//! * [SubscriptionAdmin][client::SubscriptionAdmin]
30//! * [SchemaService][client::SchemaService]
31//!
32//! **NOTE:** This crate used to contain a different implementation, with a
33//! different surface. [@yoshidan](https://github.com/yoshidan) generously
34//! donated the crate name to Google. Their crate continues to live as
35//! [gcloud-pubsub].
36//!
37//! # Features
38//!
39//! - `default-rustls-provider`: enabled by default. Use the default rustls crypto
40//!   provider ([aws-lc-rs]) for TLS and authentication. Applications with specific
41//!   requirements for cryptography (such as exclusively using the [ring] crate)
42//!   should disable this default and call
43//!   `rustls::crypto::CryptoProvider::install_default()`.
44//! - `unstable-stream`: enable the (unstable) features to convert several types to
45//!   a `future::Stream`.
46//!
47//! [aws-lc-rs]: https://crates.io/crates/aws-lc-rs
48//! [pub/sub]: https://cloud.google.com/pubsub
49//! [gcloud-pubsub]: https://crates.io/crates/gcloud-pubsub
50//! [ring]: https://crates.io/crates/ring
51
52#![cfg_attr(docsrs, feature(doc_cfg))]
53
54#[allow(rustdoc::broken_intra_doc_links)]
55pub(crate) mod generated;
56
57/// Types related to publishing messages with a [Publisher][client::Publisher]
58/// client.
59pub mod publisher;
60/// Types related to receiving messages with a [Subscriber][client::Subscriber]
61/// client.
62pub mod subscriber;
63
64pub use google_cloud_gax::Result;
65pub use google_cloud_gax::error::Error;
66// Define some shortcuts for imported crates.
67pub(crate) use google_cloud_gax::client_builder::ClientBuilder;
68pub(crate) use google_cloud_gax::client_builder::Result as ClientBuilderResult;
69pub(crate) use google_cloud_gax::client_builder::internal::ClientFactory;
70pub(crate) use google_cloud_gax::client_builder::internal::new_builder as new_client_builder;
71pub(crate) use google_cloud_gax::options::RequestOptions;
72pub(crate) use google_cloud_gax::options::internal::RequestBuilder;
73pub(crate) use google_cloud_gax::response::Response;
74
75/// Request and client builders.
76pub mod builder {
77    /// Request and client builders for the [Publisher][crate::client::Publisher] client.
78    pub mod publisher {
79        pub use crate::publisher::builder::BasePublisherBuilder;
80        pub use crate::publisher::builder::PublisherBuilder;
81        pub use crate::publisher::builder::PublisherPartialBuilder;
82    }
83    /// Request and client builders for the [SchemaService][crate::client::SchemaService] client.
84    pub use crate::generated::gapic::builder::schema_service;
85    /// Request and client builders for the [Subscriber][crate::client::Subscriber] client.
86    pub mod subscriber {
87        pub use crate::subscriber::builder::ClientBuilder;
88        pub use crate::subscriber::builder::Subscribe;
89    }
90    /// Request and client builders for the [SubscriptionAdmin][crate::client::SubscriptionAdmin] client.
91    pub use crate::generated::gapic::builder::subscription_admin;
92    /// Request and client builders for the [TopicAdmin][crate::client::TopicAdmin] client.
93    pub use crate::generated::gapic::builder::topic_admin;
94}
95
96/// The messages and enums that are part of this client library.
97pub mod model {
98    pub use crate::generated::gapic::model::*;
99    pub use crate::generated::gapic_dataplane::model::PubsubMessage as Message;
100    pub(crate) use crate::generated::gapic_dataplane::model::*;
101}
102
103/// Clients to interact with Cloud Pub/Sub.
104///
105/// This module contains the primary entry points for the library, including
106/// clients for publishing and receiving messages, as well as managing topics,
107/// subscriptions, and schemas.
108///
109/// # Example: Publishing Messages
110///
111/// ```
112/// # async fn sample() -> anyhow::Result<()> {
113/// use google_cloud_pubsub::client::Publisher;
114/// use google_cloud_pubsub::model::Message;
115///
116/// // Create a publisher that handles batching for a specific topic.
117/// let publisher = Publisher::builder("projects/my-project/topics/my-topic").build().await?;
118///
119/// // Publish several messages.
120/// // The client will automatically batch them in the background.
121/// let mut futures = Vec::new();
122/// for i in 0..10 {
123///     let msg = Message::new().set_data(format!("message {}", i));
124///     futures.push(publisher.publish(msg));
125/// }
126///
127/// // The futures resolve to the server-assigned message IDs.
128/// // You can await them to get the results. Messages will still be sent even
129/// // if the futures are dropped.
130/// for (i, future) in futures.into_iter().enumerate() {
131///     let message_id = future.await?;
132///     println!("Message {} sent with ID: {}", i, message_id);
133/// }
134/// # Ok(())
135/// # }
136/// ```
137///
138/// # Example: Receiving Messages
139///
140/// ```
141/// # async fn sample() -> anyhow::Result<()> {
142/// use google_cloud_pubsub::client::Subscriber;
143///
144/// // Create a subscriber client.
145/// let client = Subscriber::builder().build().await?;
146///
147/// // Start a message stream from a subscription.
148/// let mut stream = client
149///     .subscribe("projects/my-project/subscriptions/my-subscription")
150///     .build();
151///
152/// // Receive messages from the stream.
153/// while let Some((m, h)) = stream.next().await.transpose()? {
154///     println!("Received message m={m:?}");
155///
156///     // Acknowledge the message.
157///     h.ack();
158/// }
159/// # Ok(()) }
160/// ```
161pub mod client {
162    pub use crate::generated::gapic::client::*;
163    pub use crate::publisher::client::BasePublisher;
164    pub use crate::publisher::client::Publisher;
165    pub use crate::subscriber::client::Subscriber;
166}
167
168pub mod error;
169
170/// Traits to mock the clients in this library.
171pub mod stub {
172    pub use crate::generated::gapic::stub::*;
173}
174
175const DEFAULT_HOST: &str = "https://pubsub.googleapis.com";
176
177mod info {
178    use std::sync::LazyLock;
179
180    const NAME: &str = env!("CARGO_PKG_NAME");
181    const VERSION: &str = env!("CARGO_PKG_VERSION");
182    pub(crate) static X_GOOG_API_CLIENT_HEADER: LazyLock<String> = LazyLock::new(|| {
183        let ac = gaxi::api_header::XGoogApiClient {
184            name: NAME,
185            version: VERSION,
186            library_type: gaxi::api_header::GAPIC,
187        };
188        ac.grpc_header_value()
189    });
190}
191
192#[allow(dead_code)]
193pub(crate) mod google {
194    pub mod pubsub {
195        #[allow(clippy::enum_variant_names)]
196        pub mod v1 {
197            include!("generated/protos/pubsub/google.pubsub.v1.rs");
198            include!("generated/convert/pubsub/convert.rs");
199        }
200    }
201}