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