|
| 1 | +//! An example of ingesting messages from a PubSub subscription, applying a |
| 2 | +//! transformation, then submitting those transformations to another PubSub topic. |
| 3 | +
|
| 4 | +use futures_util::{SinkExt, StreamExt, TryFutureExt}; |
| 5 | +use hedwig::{ |
| 6 | + googlepubsub::{ |
| 7 | + AuthFlow, ClientBuilder, ClientBuilderConfig, PubSubConfig, PubSubMessage, PublishError, |
| 8 | + ServiceAccountAuth, StreamSubscriptionConfig, SubscriptionConfig, SubscriptionName, |
| 9 | + TopicConfig, TopicName, |
| 10 | + }, |
| 11 | + validators, Consumer, DecodableMessage, EncodableMessage, Headers, Publisher, |
| 12 | +}; |
| 13 | +use std::{error::Error as StdError, time::SystemTime}; |
| 14 | +use structopt::StructOpt; |
| 15 | + |
| 16 | +const USER_CREATED_TOPIC: &str = "user.created"; |
| 17 | +const USER_UPDATED_TOPIC: &str = "user.updated"; |
| 18 | + |
| 19 | +/// The input data, representing some user being created with the given name |
| 20 | +#[derive(PartialEq, Eq, prost::Message)] |
| 21 | +struct UserCreatedMessage { |
| 22 | + #[prost(string, tag = "1")] |
| 23 | + name: String, |
| 24 | +} |
| 25 | + |
| 26 | +impl EncodableMessage for UserCreatedMessage { |
| 27 | + type Error = validators::ProstValidatorError; |
| 28 | + type Validator = validators::ProstValidator; |
| 29 | + fn topic(&self) -> hedwig::Topic { |
| 30 | + USER_CREATED_TOPIC.into() |
| 31 | + } |
| 32 | + fn encode(&self, validator: &Self::Validator) -> Result<hedwig::ValidatedMessage, Self::Error> { |
| 33 | + Ok(validator.validate( |
| 34 | + uuid::Uuid::new_v4(), |
| 35 | + SystemTime::now(), |
| 36 | + "user.created/1.0", |
| 37 | + Headers::new(), |
| 38 | + self, |
| 39 | + )?) |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +impl DecodableMessage for UserCreatedMessage { |
| 44 | + type Error = validators::ProstDecodeError<validators::prost::SchemaMismatchError>; |
| 45 | + type Decoder = |
| 46 | + validators::ProstDecoder<validators::prost::ExactSchemaMatcher<UserCreatedMessage>>; |
| 47 | + |
| 48 | + fn decode(msg: hedwig::ValidatedMessage, decoder: &Self::Decoder) -> Result<Self, Self::Error> { |
| 49 | + decoder.decode(msg) |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +/// The output data, where the given user has now been assigned an ID and some metadata |
| 54 | +#[derive(PartialEq, Eq, prost::Message)] |
| 55 | +struct UserUpdatedMessage { |
| 56 | + #[prost(string, tag = "1")] |
| 57 | + name: String, |
| 58 | + |
| 59 | + #[prost(int64, tag = "2")] |
| 60 | + id: i64, |
| 61 | + |
| 62 | + #[prost(string, tag = "3")] |
| 63 | + metadata: String, |
| 64 | +} |
| 65 | + |
| 66 | +/// The output message will carry an ack token from the input message, to ack when the output is |
| 67 | +/// successfully published, or nack on failure |
| 68 | +#[derive(Debug)] |
| 69 | +struct TransformedMessage(PubSubMessage<UserUpdatedMessage>); |
| 70 | + |
| 71 | +impl EncodableMessage for TransformedMessage { |
| 72 | + type Error = validators::ProstValidatorError; |
| 73 | + type Validator = validators::ProstValidator; |
| 74 | + |
| 75 | + fn topic(&self) -> hedwig::Topic { |
| 76 | + USER_UPDATED_TOPIC.into() |
| 77 | + } |
| 78 | + |
| 79 | + fn encode(&self, validator: &Self::Validator) -> Result<hedwig::ValidatedMessage, Self::Error> { |
| 80 | + Ok(validator.validate( |
| 81 | + uuid::Uuid::new_v4(), |
| 82 | + SystemTime::now(), |
| 83 | + "user.updated/1.0", |
| 84 | + Headers::new(), |
| 85 | + &self.0.message, |
| 86 | + )?) |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +#[derive(Debug, StructOpt)] |
| 91 | +struct Args { |
| 92 | + /// The name of the pubsub project |
| 93 | + #[structopt(long)] |
| 94 | + project_name: String, |
| 95 | +} |
| 96 | + |
| 97 | +#[tokio::main(flavor = "current_thread")] |
| 98 | +async fn main() -> Result<(), Box<dyn StdError>> { |
| 99 | + let args = Args::from_args(); |
| 100 | + |
| 101 | + println!("Building PubSub clients"); |
| 102 | + |
| 103 | + let builder = ClientBuilder::new( |
| 104 | + ClientBuilderConfig::new().auth_flow(AuthFlow::ServiceAccount(ServiceAccountAuth::EnvVar)), |
| 105 | + PubSubConfig::default(), |
| 106 | + ) |
| 107 | + .await?; |
| 108 | + |
| 109 | + let input_topic_name = TopicName::new(USER_CREATED_TOPIC); |
| 110 | + let subscription_name = SubscriptionName::new("user-metadata-updaters"); |
| 111 | + |
| 112 | + let output_topic_name = TopicName::new(USER_UPDATED_TOPIC); |
| 113 | + const APP_NAME: &str = "user-metadata-updater"; |
| 114 | + |
| 115 | + let mut publisher_client = builder |
| 116 | + .build_publisher(&args.project_name, APP_NAME) |
| 117 | + .await?; |
| 118 | + let mut consumer_client = builder.build_consumer(&args.project_name, APP_NAME).await?; |
| 119 | + |
| 120 | + for topic_name in [&input_topic_name, &output_topic_name] { |
| 121 | + println!("Creating topic {:?}", topic_name); |
| 122 | + |
| 123 | + publisher_client |
| 124 | + .create_topic(TopicConfig { |
| 125 | + name: topic_name.clone(), |
| 126 | + ..TopicConfig::default() |
| 127 | + }) |
| 128 | + .await?; |
| 129 | + } |
| 130 | + |
| 131 | + println!("Creating subscription {:?}", &subscription_name); |
| 132 | + |
| 133 | + consumer_client |
| 134 | + .create_subscription(SubscriptionConfig { |
| 135 | + topic: input_topic_name.clone(), |
| 136 | + name: subscription_name.clone(), |
| 137 | + ..SubscriptionConfig::default() |
| 138 | + }) |
| 139 | + .await?; |
| 140 | + |
| 141 | + println!( |
| 142 | + "Synthesizing input messages for topic {:?}", |
| 143 | + &input_topic_name |
| 144 | + ); |
| 145 | + |
| 146 | + { |
| 147 | + let validator = validators::ProstValidator::new(); |
| 148 | + let mut input_sink = |
| 149 | + Publisher::<UserCreatedMessage>::publish_sink(publisher_client.publisher(), validator); |
| 150 | + |
| 151 | + for i in 1..=10 { |
| 152 | + let message = UserCreatedMessage { |
| 153 | + name: format!("Example Name #{}", i), |
| 154 | + }; |
| 155 | + |
| 156 | + input_sink.feed(message).await?; |
| 157 | + } |
| 158 | + input_sink.flush().await?; |
| 159 | + } |
| 160 | + |
| 161 | + println!("Ingesting input messages, applying transformations, and publishing to destination"); |
| 162 | + |
| 163 | + let mut read_stream = consumer_client |
| 164 | + .stream_subscription( |
| 165 | + subscription_name.clone(), |
| 166 | + StreamSubscriptionConfig::default(), |
| 167 | + ) |
| 168 | + .consume::<UserCreatedMessage>(hedwig::validators::ProstDecoder::new( |
| 169 | + hedwig::validators::prost::ExactSchemaMatcher::new("user.created/1.0"), |
| 170 | + )); |
| 171 | + |
| 172 | + let mut output_sink = Publisher::<TransformedMessage, _>::publish_sink_with_responses( |
| 173 | + publisher_client.publisher(), |
| 174 | + validators::ProstValidator::new(), |
| 175 | + futures_util::sink::unfold((), |_, message: TransformedMessage| async move { |
| 176 | + // if the output is successfully sent, ack the input to mark it as processed |
| 177 | + message.0.ack().await.map(|_success| ()) |
| 178 | + }), |
| 179 | + ); |
| 180 | + |
| 181 | + for i in 1..=10 { |
| 182 | + let PubSubMessage { ack_token, message } = read_stream |
| 183 | + .next() |
| 184 | + .await |
| 185 | + .expect("stream should have 10 elements")?; |
| 186 | + |
| 187 | + assert_eq!(&message.name, &format!("Example Name #{}", i)); |
| 188 | + |
| 189 | + let transformed = TransformedMessage(PubSubMessage { |
| 190 | + ack_token, |
| 191 | + message: UserUpdatedMessage { |
| 192 | + name: message.name, |
| 193 | + id: random_id(), |
| 194 | + metadata: "some metadata".into(), |
| 195 | + }, |
| 196 | + }); |
| 197 | + |
| 198 | + output_sink |
| 199 | + .feed(transformed) |
| 200 | + .or_else(|publish_error| async move { |
| 201 | + // if publishing fails, nack the failed messages to allow later retries |
| 202 | + Err(match publish_error { |
| 203 | + PublishError::Publish { cause, messages } => { |
| 204 | + for failed_transform in messages { |
| 205 | + failed_transform.0.nack().await?; |
| 206 | + } |
| 207 | + Box::<dyn StdError>::from(cause) |
| 208 | + } |
| 209 | + err => Box::<dyn StdError>::from(err), |
| 210 | + }) |
| 211 | + }) |
| 212 | + .await? |
| 213 | + } |
| 214 | + output_sink.flush().await?; |
| 215 | + |
| 216 | + println!("All messages matched and published successfully!"); |
| 217 | + |
| 218 | + println!("Deleting subscription {:?}", &subscription_name); |
| 219 | + |
| 220 | + consumer_client |
| 221 | + .delete_subscription(subscription_name) |
| 222 | + .await?; |
| 223 | + |
| 224 | + for topic_name in [input_topic_name, output_topic_name] { |
| 225 | + println!("Deleting topic {:?}", &topic_name); |
| 226 | + |
| 227 | + publisher_client.delete_topic(topic_name).await?; |
| 228 | + } |
| 229 | + |
| 230 | + println!("Done"); |
| 231 | + |
| 232 | + Ok(()) |
| 233 | +} |
| 234 | + |
| 235 | +fn random_id() -> i64 { |
| 236 | + 4 // chosen by fair dice roll. |
| 237 | + // guaranteed to be random. |
| 238 | +} |
0 commit comments