|
1 | 1 | # Pub-Sub-Client # |
2 | 2 |
|
3 | | -Rust library to access Google Cloud Pub/Sub. |
| 3 | +Rust library to access Google Cloud Pub/Sub. Currently only pulling from a subscription as well as acknowledging pulled messages is supported. |
| 4 | + |
| 5 | +Messages can either be pulled as raw or, if the payload is JSON data, deserialized into domain messages (structs or enums) via [Serde](https://serde.rs/) and [Serde JSON](https://docs.serde.rs/serde_json). Both raw `ReceivedMessages` and `MessageEnvelopes` holding deserialized messages, expose metadata like message ID, acknowledge ID, attributes, etc. |
| 6 | + |
| 7 | +Aside from straight forward deserialization it is also possible to first transform the pulled JSON values before deserizlizing into domain messages which allows for generally adjusting the JSON structure as well as schema evolution. |
| 8 | + |
| 9 | +## Usage |
| 10 | + |
| 11 | +Typically we want to deserialize into a domain message: |
| 12 | + |
| 13 | +``` rust |
| 14 | +#[derive(Debug, Deserialize)] |
| 15 | +struct Message { |
| 16 | + text: String, |
| 17 | +} |
| 18 | +``` |
| 19 | + |
| 20 | +First create a `PubSubClient`, giving the path to a service account key file and the duration to refresh access tokens before they expire: |
| 21 | + |
| 22 | +``` rust |
| 23 | +let pub_sub_client = PubSubClient::new( |
| 24 | + "secrets/cryptic-hawk-336616-e228f9680cbc.json", |
| 25 | + Duration::from_secs(30), |
| 26 | +)?; |
| 27 | +``` |
| 28 | + |
| 29 | +Things could go wrong, e.g. if the service account key file does not exist or is malformed, hence a `Result` is returned. |
| 30 | + |
| 31 | +Next we call `pull` to get at most the given `42` messages from the given `SUBSCRIPTION`; we do not use a request timeout here for simplicity: |
| 32 | + |
| 33 | +``` rust |
| 34 | +let envelopes = pub_sub_client |
| 35 | + .pull::<Message>(SUBSCRIPTION, 42, None) |
| 36 | + .await?; |
| 37 | +``` |
| 38 | + |
| 39 | +Of course pulling which happens via HTTP could fail, hence we get back another `Result`. |
| 40 | + |
| 41 | +Finally we handle the pulled messages; for simplicity we only deal with the happy path here, i.e. when the deserialization was successful: |
| 42 | + |
| 43 | +``` rust |
| 44 | +for envelope in envelopes { |
| 45 | + let envelope = envelope?; |
| 46 | + println!("Message text: {}", envelope.message.text); |
| 47 | + |
| 48 | + pub_sub_client |
| 49 | + .acknowledge(SUBSCRIPTION, vec![&envelope.ack_id], None) |
| 50 | + .await?; |
| 51 | + println!("Successfully acknowledged"); |
| 52 | +} |
| 53 | +``` |
| 54 | + |
| 55 | +For successfully deserialized messages we call `acknowledge` with the acknowledge ID taken from the envelope. |
4 | 56 |
|
5 | 57 | ## Contribution policy ## |
6 | 58 |
|
|
0 commit comments