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    pub use crate::generated::gapic::builder::schema_service;
84    /// Request and client builders for the [Subscriber][crate::client::Subscriber] client.
85    pub mod subscriber {
86        pub use crate::subscriber::builder::ClientBuilder;
87        pub use crate::subscriber::builder::Subscribe;
88    }
89    pub use crate::generated::gapic::builder::subscription_admin;
90    pub use crate::generated::gapic::builder::topic_admin;
91}
92
93/// The messages and enums that are part of this client library.
94pub mod model {
95    pub use crate::generated::gapic::model::*;
96    pub use crate::generated::gapic_dataplane::model::PubsubMessage as Message;
97    pub(crate) use crate::generated::gapic_dataplane::model::*;
98}
99
100/// Clients to interact with Cloud Pub/Sub.
101///
102/// This module contains the primary entry points for the library, including
103/// clients for publishing and receiving messages, as well as managing topics,
104/// subscriptions, and schemas.
105///
106/// # Example: Publishing Messages
107///
108/// ```
109/// # async fn sample() -> anyhow::Result<()> {
110/// use google_cloud_pubsub::client::Publisher;
111/// use google_cloud_pubsub::model::Message;
112///
113/// // Create a publisher that handles batching for a specific topic.
114/// let publisher = Publisher::builder("projects/my-project/topics/my-topic").build().await?;
115///
116/// // Publish several messages.
117/// // The client will automatically batch them in the background.
118/// let mut futures = Vec::new();
119/// for i in 0..10 {
120///     let msg = Message::new().set_data(format!("message {}", i));
121///     futures.push(publisher.publish(msg));
122/// }
123///
124/// // The futures resolve to the server-assigned message IDs.
125/// // You can await them to get the results. Messages will still be sent even
126/// // if the futures are dropped.
127/// for (i, future) in futures.into_iter().enumerate() {
128///     let message_id = future.await?;
129///     println!("Message {} sent with ID: {}", i, message_id);
130/// }
131/// # Ok(())
132/// # }
133/// ```
134///
135/// # Example: Receiving Messages
136///
137/// ```
138/// # async fn sample() -> anyhow::Result<()> {
139/// use google_cloud_pubsub::client::Subscriber;
140///
141/// // Create a subscriber client.
142/// let client = Subscriber::builder().build().await?;
143///
144/// // Start a message stream from a subscription.
145/// let mut stream = client
146///     .subscribe("projects/my-project/subscriptions/my-subscription")
147///     .build();
148///
149/// // Receive messages from the stream.
150/// while let Some((m, h)) = stream.next().await.transpose()? {
151///     println!("Received message m={m:?}");
152///
153///     // Acknowledge the message.
154///     h.ack();
155/// }
156/// # Ok(()) }
157/// ```
158pub mod client {
159    pub use crate::generated::gapic::client::*;
160    pub use crate::publisher::client::BasePublisher;
161    pub use crate::publisher::client::Publisher;
162    pub use crate::subscriber::client::Subscriber;
163}
164
165pub mod error;
166pub mod retry_policy;
167
168/// Traits to mock the clients in this library.
169pub mod stub {
170    pub use crate::generated::gapic::stub::*;
171}
172
173const DEFAULT_HOST: &str = "https://pubsub.googleapis.com";
174
175mod info {
176    use std::sync::LazyLock;
177
178    const NAME: &str = env!("CARGO_PKG_NAME");
179    const VERSION: &str = env!("CARGO_PKG_VERSION");
180    pub(crate) static X_GOOG_API_CLIENT_HEADER: LazyLock<String> = LazyLock::new(|| {
181        let ac = gaxi::api_header::XGoogApiClient {
182            name: NAME,
183            version: VERSION,
184            library_type: gaxi::api_header::GAPIC,
185        };
186        ac.grpc_header_value()
187    });
188}
189
190#[allow(dead_code)]
191pub(crate) mod google {
192    pub mod pubsub {
193        #[allow(clippy::enum_variant_names)]
194        pub mod v1 {
195            include!("generated/protos/pubsub/google.pubsub.v1.rs");
196            include!("generated/convert/pubsub/convert.rs");
197        }
198    }
199}