encore/pubsub.rs
1//! Pub/Sub topics and subscriptions.
2//!
3//! Declare topics and subscriptions as module-level `static`s. Topics are typed
4//! by their message payload, and subscriptions bind a topic to an async handler
5//! function:
6//!
7//! ```no_run
8//! use encore::pubsub::{Message, Subscription, Topic};
9//! use serde::{Deserialize, Serialize};
10//!
11//! #[derive(Serialize, Deserialize)]
12//! struct SignupEvent {
13//! user_id: String,
14//! }
15//!
16//! static SIGNUPS: Topic<SignupEvent> = Topic::new("signups");
17//!
18//! #[encore::pubsub::register]
19//! static WELCOME: Subscription<SignupEvent> =
20//! Subscription::new(&SIGNUPS, "send-welcome", send_welcome);
21//!
22//! async fn send_welcome(msg: Message<SignupEvent>) -> Result<(), encore::Error> {
23//! println!("welcome, {}", msg.data.user_id);
24//! Ok(())
25//! }
26//!
27//! async fn signed_up(user_id: String) -> Result<(), encore::Error> {
28//! SIGNUPS.publish(&SignupEvent { user_id }).await?;
29//! Ok(())
30//! }
31//! ```
32//!
33//! # Encodings
34//!
35//! A topic's second type parameter specifies its wire encoding: [`Json`] by
36//! default, [`Raw`] for raw byte payloads, or `Protobuf` when the `protobuf`
37//! feature is enabled. Because the encoding is part of the topic's type,
38//! publishers and subscribers stay in agreement and Encore can read it
39//! statically.
40//!
41//! # Ordered topics
42//!
43//! An [`OrderedTopic`] delivers messages sharing the same ordering key in the
44//! order they were published. Pass the ordering key when calling `publish`.
45//!
46//! # Batches
47//!
48//! `publish_batch` publishes up to [`MAX_BATCH_SIZE`] messages in fewer
49//! round-trips than individual publishes, returning message IDs in input order.
50//! Batch publishing is not atomic: on partial failure, [`BatchError`] reports
51//! which messages succeeded and which failed. On an ordered topic, messages
52//! sharing a key are published in order, and if one fails, subsequent messages
53//! with that key are not published.
54//!
55//! # References
56//!
57//! Encore infers service permissions from direct method calls on a `Topic`. To
58//! pass a topic to helper functions, create a permission-scoped reference via
59//! [`Topic::reference`] with [`perms::Publisher`], and accept the [`Publisher`]
60//! (or [`OrderedPublisher`]) trait in the helper.
61//!
62//! # Starting subscriptions
63//!
64//! Rust `static`s are lazy, so subscriptions must be started explicitly.
65//! Annotate subscriptions with [`#[encore::pubsub::register]`](macro@register)
66//! so [`crate::initialize`] or [`crate::run_blocking`] starts them
67//! automatically; otherwise call [`Subscription::start`] manually.
68//!
69//! # Testing
70//!
71//! Under `encore test`, each test has an isolated Pub/Sub scope and
72//! subscriptions do not run automatically. Inspect messages published during a
73//! test with [`testing::published`](crate::testing::published), and invoke
74//! subscription handlers explicitly with
75//! [`testing::deliver`](crate::testing::deliver).
76
77use std::collections::HashMap;
78use std::fmt;
79use std::future::Future;
80use std::marker::PhantomData;
81use std::pin::Pin;
82use std::sync::atomic::{AtomicBool, Ordering};
83use std::sync::Arc;
84use std::time::{Duration, SystemTime};
85
86use encore_sdk_core::pubsub as core_pubsub;
87use encore_sdk_core::reqctx::Values;
88use serde::de::DeserializeOwned;
89use serde::Serialize;
90
91use crate::error::{ErrCode, Error};
92use crate::runtime::core;
93use crate::testing;
94
95/// Registers a subscription `static` to be started automatically when the
96/// application initializes.
97///
98/// Apply this attribute to a `static Subscription<T>`. It also lets you pass an
99/// `async fn` name directly instead of wrapping it in a boxing closure for
100/// [`Subscription::new`].
101///
102/// ```no_run
103/// # use encore::pubsub::{Message, Subscription, Topic};
104/// # static SIGNUPS: Topic<String> = Topic::new("signups");
105/// #[encore::pubsub::register]
106/// static WELCOME: Subscription<String> =
107/// Subscription::new(&SIGNUPS, "send-welcome", send_welcome).max_concurrency(4);
108///
109/// async fn send_welcome(msg: Message<String>) -> Result<(), encore::Error> {
110/// Ok(())
111/// }
112/// ```
113pub use encore_macros::register;
114
115/// A Pub/Sub message delivered to a subscription handler.
116#[derive(Debug, Clone)]
117pub struct Message<T> {
118 /// Unique message ID within the topic.
119 pub id: String,
120 /// Decoded message payload.
121 pub data: T,
122 /// Raw encoded message bytes before decoding.
123 pub raw_data: Vec<u8>,
124 /// Attributes published alongside the message.
125 ///
126 /// On delivered messages, internal `encore-ctx-*` Request Context
127 /// attributes are stripped and exposed through [`crate::reqctx`] instead;
128 /// messages returned by [`testing::published`] retain them as published.
129 pub attributes: HashMap<String, String>,
130 pub publish_time: SystemTime,
131 /// 1-based delivery attempt number. On GCP, it counts the message's failed
132 /// deliveries plus one, so a message redelivered because an earlier one
133 /// with its ordering key failed may keep its number.
134 pub delivery_attempt: u32,
135 /// Ordering key set when published to an [`OrderedTopic`].
136 pub ordering_key: Option<String>,
137}
138
139/// Wire encoding for a topic's messages.
140pub trait Encoding<T> {
141 fn encode(value: &T) -> Result<Vec<u8>, Error>;
142 fn decode(raw: &[u8]) -> Result<T, Error>;
143}
144
145/// JSON encoding for message types implementing `Serialize` and `Deserialize`
146/// (the default topic encoding).
147pub enum Json {}
148
149impl<T: Serialize + DeserializeOwned> Encoding<T> for Json {
150 fn encode(value: &T) -> Result<Vec<u8>, Error> {
151 serde_json::to_vec(value).map_err(|e| Error::wrap(ErrCode::InvalidArgument, e))
152 }
153
154 fn decode(raw: &[u8]) -> Result<T, Error> {
155 serde_json::from_slice(raw).map_err(|e| Error::wrap(ErrCode::InvalidArgument, e))
156 }
157}
158
159/// Raw byte encoding that passes `Vec<u8>` payloads through unmodified.
160pub enum Raw {}
161
162impl Encoding<Vec<u8>> for Raw {
163 fn encode(value: &Vec<u8>) -> Result<Vec<u8>, Error> {
164 Ok(value.clone())
165 }
166
167 fn decode(raw: &[u8]) -> Result<Vec<u8>, Error> {
168 Ok(raw.to_vec())
169 }
170}
171
172/// Protocol Buffers encoding for `prost` message types.
173#[cfg(feature = "protobuf")]
174pub enum Protobuf {}
175
176#[cfg(feature = "protobuf")]
177impl<T: prost::Message + Default> Encoding<T> for Protobuf {
178 fn encode(value: &T) -> Result<Vec<u8>, Error> {
179 Ok(value.encode_to_vec())
180 }
181
182 fn decode(raw: &[u8]) -> Result<T, Error> {
183 T::decode(raw).map_err(|e| Error::wrap(ErrCode::InvalidArgument, e))
184 }
185}
186
187/// Marker type for an unordered [`Topic`].
188pub enum Unordered {}
189
190/// Marker type for an ordered [`Topic`] ([`OrderedTopic`]).
191pub enum Ordered {}
192
193/// A Pub/Sub topic carrying messages of type `T` with encoding `E`.
194pub struct Topic<T, E = Json, O = Unordered> {
195 name: &'static str,
196 /// Read by Encore's parser from the declaration, not by the runtime.
197 #[allow(dead_code)]
198 exactly_once: bool,
199 _marker: PhantomData<Carries<T, E, O>>,
200}
201
202/// What a topic's type parameters stand for, none of which it holds.
203type Carries<T, E, O> = fn() -> (T, E, O);
204
205/// A [`Topic`] that delivers messages sharing an ordering key in publish order.
206///
207/// A message that fails is retried before later messages with its key are
208/// delivered. On GCP, later messages already received when one fails can be
209/// handled before its retry, and are then delivered again after it, so handlers
210/// must be idempotent.
211pub type OrderedTopic<T, E = Json> = Topic<T, E, Ordered>;
212
213/// Options for publishing a single message.
214///
215/// ```no_run
216/// # use std::collections::HashMap;
217/// # use encore::pubsub::{PublishOptions, Topic};
218/// # static SIGNUPS: Topic<String> = Topic::new("signups");
219/// # async fn f(tags: HashMap<String, String>) -> Result<(), encore::Error> {
220/// let event = "ada".to_string();
221/// SIGNUPS
222/// .publish_with(
223/// &event,
224/// PublishOptions::new()
225/// .attributes(tags)
226/// .attribute("source", "web"),
227/// )
228/// .await?;
229/// # Ok(())
230/// # }
231/// ```
232///
233/// Custom attributes are delivered alongside the message. Attributes prefixed
234/// with `encore-ctx-` are reserved for Encore's Request Context propagation.
235#[derive(Debug, Clone, Default)]
236pub struct PublishOptions {
237 attributes: HashMap<String, String>,
238}
239
240impl PublishOptions {
241 /// Creates empty publish options with no attributes.
242 pub fn new() -> Self {
243 Self::default()
244 }
245
246 /// Sets a message attribute, overwriting any existing value with the same key.
247 pub fn attribute(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
248 self.attributes.insert(key.into(), value.into());
249 self
250 }
251
252 /// Adds multiple message attributes from a map or iterator of pairs (such as
253 /// `[("source", "web")]`), overwriting any existing keys.
254 pub fn attributes<K, V>(mut self, attributes: impl IntoIterator<Item = (K, V)>) -> Self
255 where
256 K: Into<String>,
257 V: Into<String>,
258 {
259 extend(&mut self.attributes, attributes);
260 self
261 }
262}
263
264/// Adds `attributes` to `into`, replacing those of the same names.
265fn extend<K: Into<String>, V: Into<String>>(
266 into: &mut HashMap<String, String>,
267 attributes: impl IntoIterator<Item = (K, V)>,
268) {
269 into.extend(attributes.into_iter().map(|(k, v)| (k.into(), v.into())));
270}
271
272impl<T, E, O> Topic<T, E, O> {
273 /// Declares a Pub/Sub topic.
274 ///
275 /// This constructor is `const` so it can initialize a module-scope `static`,
276 /// whose type specifies the message type and encoding. Chain option methods
277 /// directly onto the declaration:
278 ///
279 /// ```no_run
280 /// use encore::pubsub::{OrderedTopic, Raw, Topic};
281 ///
282 /// static EVENTS: Topic<String> = Topic::new("events");
283 /// static PAYMENTS: Topic<String> = Topic::new("payments").exactly_once();
284 /// static BLOBS: Topic<Vec<u8>, Raw> = Topic::new("blobs");
285 /// static CHANGES: OrderedTopic<String> = OrderedTopic::new("changes");
286 /// ```
287 pub const fn new(name: &'static str) -> Self {
288 Self {
289 name,
290 exactly_once: false,
291 _marker: PhantomData,
292 }
293 }
294
295 /// References an existing topic declared by another service (possibly in
296 /// another language). To declare a new topic, use [`Topic::new`].
297 ///
298 /// `name` must be a string literal so Encore can resolve it statically.
299 /// Topic options are defined at the original declaration, not on `named`.
300 /// Ensure that `T` and `E` match the declaring topic's schema, as
301 /// cross-language types cannot be checked by Rust's type checker.
302 ///
303 /// ```no_run
304 /// static SIGNUPS: encore::pubsub::Topic<String> = encore::pubsub::Topic::named("signups");
305 /// ```
306 pub const fn named(name: &'static str) -> Self {
307 Self::new(name)
308 }
309
310 /// Configures the topic for exactly-once delivery instead of at-least-once.
311 pub const fn exactly_once(mut self) -> Self {
312 self.exactly_once = true;
313 self
314 }
315
316 /// Attaches a key/value tag to the topic (for example, `.tag("data", "pci")`)
317 /// for policy and governance tooling.
318 ///
319 /// Call once per tag with unique keys. Both `key` and `value` must be string
320 /// literals so Encore can parse them statically. Keys must start with a
321 /// letter, contain only lowercase letters, digits, `_`, and `-`, and must
322 /// not start with `encore` (reserved for Encore's own tags). Values use the
323 /// same character set or may be empty. Each key and value is at most 63
324 /// characters, and a topic may have at most 32 tags.
325 ///
326 /// ```no_run
327 /// use encore::pubsub::Topic;
328 ///
329 /// static PAYMENTS: Topic<String> = Topic::new("payments").tag("data", "pci");
330 /// ```
331 pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
332 self
333 }
334
335 /// Returns the name this topic was declared with.
336 pub const fn name(&self) -> &'static str {
337 self.name
338 }
339
340 /// Creates a permission-scoped [`TopicRef`] granting permission `P`
341 /// (currently [`perms::Publisher`]).
342 ///
343 /// Unlike `Topic`, a `TopicRef` can be passed to helper functions; the
344 /// calling service is granted the permissions specified in `P`. The type
345 /// parameter `P` must always be written explicitly so Encore can analyze
346 /// permissions statically.
347 ///
348 /// ```no_run
349 /// use encore::pubsub::{perms, Publisher, Topic, TopicRef};
350 ///
351 /// static SIGNUPS: Topic<String> = Topic::new("signups");
352 /// static NOTIFY: TopicRef<perms::Publisher, String> = SIGNUPS.reference::<perms::Publisher>();
353 ///
354 /// // Library code accepts the permission trait.
355 /// async fn notify(topic: &impl Publisher<String>, user: &String) -> Result<(), encore::Error> {
356 /// topic.publish(user).await?;
357 /// Ok(())
358 /// }
359 /// ```
360 ///
361 /// ```compile_fail,E0284
362 /// # use encore::pubsub::{perms, Topic, TopicRef};
363 /// # static SIGNUPS: Topic<String> = Topic::new("signups");
364 /// // Permissions cannot be inferred from the target type.
365 /// static NOTIFY: TopicRef<perms::Publisher, String> = SIGNUPS.reference();
366 /// ```
367 pub const fn reference<P: TopicPerms>(&'static self) -> TopicRef<P::Id, T, E, O> {
368 TopicRef {
369 name: self.name,
370 perms: PhantomData,
371 _marker: PhantomData,
372 }
373 }
374}
375
376impl<T, E: Encoding<T>, O> Topic<T, E, O> {
377 /// The app's topic, which a publish outside a test goes to.
378 fn topic(&self) -> Result<core_pubsub::TopicObj, Error> {
379 core()
380 .pubsub()
381 .topic(self.name.into())
382 .ok_or_else(|| Error::not_found(format!("topic {:?} is not configured", self.name)))
383 }
384
385 /// Records a message the current test published, as the runtime would
386 /// have sent it: with the Request Context fields it keeps. It is sent
387 /// nowhere: nothing handles what a test publishes until it delivers it.
388 fn record(
389 &self,
390 test: &testing::Scope,
391 payload: Vec<u8>,
392 mut attributes: HashMap<String, String>,
393 ordering_key: Option<String>,
394 ) -> Result<String, Error> {
395 core().reqctx_fields().retain_published(&mut attributes);
396 Ok(test
397 .core_scope()?
398 .record_published(self.name, payload, attributes, ordering_key))
399 }
400
401 /// Encodes and publishes a message: to the app's topic, or under `encore
402 /// test` to the current test, which notes it for the test to read back
403 /// and sends it nowhere.
404 ///
405 /// The message carries the Request Context fields of the current
406 /// context, in place of any `encore-ctx-*` attributes given: the runtime
407 /// publishes it with those the app declares with `pubsub`.
408 async fn send(
409 &self,
410 data: &T,
411 mut attributes: HashMap<String, String>,
412 ordering_key: Option<&str>,
413 ) -> Result<String, Error> {
414 use encore_sdk_core::telemetry::opentelemetry::trace::FutureExt as _;
415 use encore_sdk_core::telemetry::opentelemetry::Context;
416
417 let payload = E::encode(data)?;
418 let ordering_key = ordering_key.map(str::to_owned);
419 // In a system test the message carries the test, and is sent: the
420 // subscriptions handle it in the services that declare them.
421 let cx = testing::outgoing(&Context::current());
422 Values::of(&cx).to_attributes(&mut attributes);
423 if core().system_test().is_none() {
424 if let Some(test) = testing::active()? {
425 return self.record(&test, payload, attributes, ordering_key);
426 }
427 }
428 self.topic()?
429 .publish(payload, attributes, ordering_key)
430 .with_context(cx)
431 .await
432 .map_err(unavailable)
433 }
434
435 /// Encodes and publishes a batch of messages, as [`send`](Self::send)
436 /// does each. A batch with a message that cannot be sent as it is — one
437 /// that does not encode, or has an empty ordering key — or more than
438 /// [`MAX_BATCH_SIZE`] messages is not sent at all.
439 async fn send_batch(&self, messages: Vec<Outgoing<'_, T>>) -> Result<Vec<String>, BatchError> {
440 let count = messages.len();
441 if count == 0 {
442 return Ok(Vec::new());
443 }
444 if count > MAX_BATCH_SIZE {
445 return Err(BatchError::refused(
446 count,
447 Error::invalid_argument(format!(
448 "batch has {count} messages, exceeding the maximum of {MAX_BATCH_SIZE}"
449 )),
450 ));
451 }
452
453 use encore_sdk_core::telemetry::opentelemetry::trace::FutureExt as _;
454 use encore_sdk_core::telemetry::opentelemetry::Context;
455
456 let mut outgoing = Vec::with_capacity(count);
457 let mut unsendable = Vec::new();
458 for (i, msg) in messages.into_iter().enumerate() {
459 let payload = match msg.ordering_key {
460 Some("") => Err(Error::invalid_argument(format!(
461 "ordering key for topic {:?} cannot be empty",
462 self.name
463 ))),
464 _ => E::encode(msg.data),
465 };
466 match payload {
467 Ok(payload) => outgoing.push(core_pubsub::OutgoingMessage {
468 payload,
469 attrs: msg.attributes.clone(),
470 ordering_key: msg.ordering_key.map(str::to_owned),
471 }),
472 Err(err) => unsendable.push((i, err)),
473 }
474 }
475 if let Some(&(first, _)) = unsendable.first() {
476 return Err(BatchError::unsendable(count, first, unsendable));
477 }
478
479 // Each message carries the Request Context fields, as one sent alone.
480 // Read once the batch is known to be sendable: which test the batch
481 // is for is the runtime's to say, and a batch refused as it is
482 // needs none.
483 let cx = testing::outgoing(&Context::current());
484 let fields = Values::of(&cx);
485 for msg in &mut outgoing {
486 fields.to_attributes(&mut msg.attrs);
487 }
488
489 let refused = |err| BatchError::refused(count, err);
490 if core().system_test().is_none() {
491 if let Some(test) = testing::active().map_err(refused)? {
492 return outgoing
493 .into_iter()
494 .map(|msg| self.record(&test, msg.payload, msg.attrs, msg.ordering_key))
495 .collect::<Result<_, _>>()
496 .map_err(refused);
497 }
498 }
499 let results = self
500 .topic()
501 .map_err(refused)?
502 .publish_batch(outgoing)
503 .with_context(cx)
504 .await
505 .map_err(|err| refused(Error::wrap(ErrCode::InvalidArgument, format!("{err:#}"))))?;
506 let results = settle(count, results);
507 BatchError::check(results)
508 }
509
510 /// What the current test has published to the topic, decoded.
511 pub(crate) fn published_in(&self, test: &testing::Scope) -> Result<Vec<Message<T>>, Error> {
512 test.published(self.name)
513 .into_iter()
514 .map(|published| {
515 Ok(Message {
516 data: E::decode(&published.payload)?,
517 id: published.id,
518 raw_data: published.payload,
519 ordering_key: published.ordering_key,
520 attributes: published.attributes,
521 publish_time: published.publish_time,
522 delivery_attempt: 1,
523 })
524 })
525 .collect()
526 }
527}
528
529impl<T, E: Encoding<T>> Topic<T, E, Unordered> {
530 /// Publishes a message and returns its message ID.
531 pub async fn publish(&self, data: &T) -> Result<String, Error> {
532 self.send(data, HashMap::new(), None).await
533 }
534
535 /// Publishes a message with explicit [`PublishOptions`] (such as custom
536 /// attributes) and returns its message ID.
537 pub async fn publish_with(&self, data: &T, options: PublishOptions) -> Result<String, Error> {
538 self.send(data, options.attributes, None).await
539 }
540
541 /// Publishes up to [`MAX_BATCH_SIZE`] messages in a batch and returns their
542 /// message IDs in input order.
543 ///
544 /// Batch publishing is not atomic: if some messages fail, [`BatchError`]
545 /// contains both the IDs of published messages and errors for failed ones.
546 /// Passing an empty slice is a no-op.
547 pub async fn publish_batch(
548 &self,
549 messages: &[BatchMessage<'_, T>],
550 ) -> Result<Vec<String>, BatchError> {
551 let messages = messages
552 .iter()
553 .map(|msg| Outgoing {
554 data: msg.data,
555 attributes: &msg.attributes,
556 ordering_key: None,
557 })
558 .collect();
559 self.send_batch(messages).await
560 }
561}
562
563impl<T, E: Encoding<T>> Topic<T, E, Ordered> {
564 /// Publishes a message with an ordering key and returns its message ID.
565 ///
566 /// Messages sharing the same `ordering_key` are delivered in publish order.
567 pub async fn publish(&self, data: &T, ordering_key: &str) -> Result<String, Error> {
568 self.publish_with(data, ordering_key, PublishOptions::default())
569 .await
570 }
571
572 /// Publishes a message with an ordering key and explicit [`PublishOptions`],
573 /// returning its message ID.
574 pub async fn publish_with(
575 &self,
576 data: &T,
577 ordering_key: &str,
578 options: PublishOptions,
579 ) -> Result<String, Error> {
580 if ordering_key.is_empty() {
581 return Err(Error::invalid_argument(format!(
582 "ordering key for topic {:?} cannot be empty",
583 self.name
584 )));
585 }
586 self.send(data, options.attributes, Some(ordering_key))
587 .await
588 }
589
590 /// Publishes up to [`MAX_BATCH_SIZE`] ordered messages in a batch and
591 /// returns their message IDs in input order.
592 ///
593 /// Messages sharing an ordering key are published in order. Batch
594 /// publishing is not atomic: if a message fails, subsequent messages with
595 /// the same ordering key are not published to preserve ordering, and
596 /// [`BatchError`] reports each message's outcome. Passing an empty slice is
597 /// a no-op.
598 pub async fn publish_batch(
599 &self,
600 messages: &[OrderedBatchMessage<'_, T>],
601 ) -> Result<Vec<String>, BatchError> {
602 let messages = messages
603 .iter()
604 .map(|msg| Outgoing {
605 data: msg.data,
606 attributes: &msg.attributes,
607 ordering_key: Some(msg.ordering_key),
608 })
609 .collect();
610 self.send_batch(messages).await
611 }
612}
613
614/// A core error publishing a message, as the SDK's.
615fn unavailable(err: anyhow::Error) -> Error {
616 Error::wrap(ErrCode::Unavailable, format!("{err:#}"))
617}
618
619/// The core's answers for a batch of `count` messages, as the SDK's. A
620/// message the core did not answer for was not published.
621fn settle(
622 count: usize,
623 answers: Vec<anyhow::Result<core_pubsub::MessageId>>,
624) -> Vec<Result<String, Error>> {
625 let mut answers = answers.into_iter();
626 (0..count)
627 .map(|_| match answers.next() {
628 Some(Ok(id)) => Ok(id),
629 Some(Err(err)) => Err(unavailable(err)),
630 None => Err(Error::unavailable(
631 "missing publish result for message in batch",
632 )),
633 })
634 .collect()
635}
636
637/// Maximum number of messages accepted by a single `publish_batch` call.
638pub const MAX_BATCH_SIZE: usize = core_pubsub::MAX_BATCH_SIZE;
639
640/// A single message in a batch passed to [`Topic::publish_batch`], containing
641/// the payload and optional attributes.
642///
643/// ```no_run
644/// # use encore::pubsub::{BatchMessage, Topic};
645/// # static SIGNUPS: Topic<String> = Topic::new("signups");
646/// # async fn f() -> Result<(), encore::Error> {
647/// let (ada, grace) = ("ada".to_string(), "grace".to_string());
648/// let ids = SIGNUPS
649/// .publish_batch(&[
650/// BatchMessage::new(&ada),
651/// BatchMessage::new(&grace).attribute("source", "import"),
652/// ])
653/// .await?;
654/// # Ok(())
655/// # }
656/// ```
657#[derive(Debug)]
658pub struct BatchMessage<'a, T> {
659 pub data: &'a T,
660 /// Custom attributes delivered alongside the message (same rules as
661 /// [`PublishOptions::attributes`]).
662 pub attributes: HashMap<String, String>,
663}
664
665impl<'a, T> BatchMessage<'a, T> {
666 /// Creates a batch message with no attributes.
667 pub fn new(data: &'a T) -> Self {
668 Self {
669 data,
670 attributes: HashMap::new(),
671 }
672 }
673
674 /// Sets a message attribute, overwriting any existing value with the same key.
675 pub fn attribute(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
676 self.attributes.insert(key.into(), value.into());
677 self
678 }
679
680 /// Adds multiple message attributes from a map or iterator of pairs (such as
681 /// `[("source", "web")]`), overwriting any existing keys.
682 pub fn attributes<K, V>(mut self, attributes: impl IntoIterator<Item = (K, V)>) -> Self
683 where
684 K: Into<String>,
685 V: Into<String>,
686 {
687 extend(&mut self.attributes, attributes);
688 self
689 }
690}
691
692impl<T> Clone for BatchMessage<'_, T> {
693 fn clone(&self) -> Self {
694 Self {
695 data: self.data,
696 attributes: self.attributes.clone(),
697 }
698 }
699}
700
701/// A single message in a batch passed to [`OrderedTopic::publish_batch`],
702/// containing the payload, ordering key, and optional attributes.
703#[derive(Debug)]
704pub struct OrderedBatchMessage<'a, T> {
705 pub data: &'a T,
706 /// Non-empty ordering key; messages sharing a key are delivered in publish
707 /// order.
708 pub ordering_key: &'a str,
709 /// Custom attributes delivered alongside the message (same rules as
710 /// [`PublishOptions::attributes`]).
711 pub attributes: HashMap<String, String>,
712}
713
714impl<'a, T> OrderedBatchMessage<'a, T> {
715 /// Creates an ordered batch message with no attributes.
716 pub fn new(data: &'a T, ordering_key: &'a str) -> Self {
717 Self {
718 data,
719 ordering_key,
720 attributes: HashMap::new(),
721 }
722 }
723
724 /// Sets a message attribute, overwriting any existing value with the same key.
725 pub fn attribute(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
726 self.attributes.insert(key.into(), value.into());
727 self
728 }
729
730 /// Adds multiple message attributes from a map or iterator of pairs (such as
731 /// `[("source", "web")]`), overwriting any existing keys.
732 pub fn attributes<K, V>(mut self, attributes: impl IntoIterator<Item = (K, V)>) -> Self
733 where
734 K: Into<String>,
735 V: Into<String>,
736 {
737 extend(&mut self.attributes, attributes);
738 self
739 }
740}
741
742impl<T> Clone for OrderedBatchMessage<'_, T> {
743 fn clone(&self) -> Self {
744 Self {
745 data: self.data,
746 ordering_key: self.ordering_key,
747 attributes: self.attributes.clone(),
748 }
749 }
750}
751
752/// A message of a batch, whichever kind of topic it is for.
753struct Outgoing<'a, T> {
754 data: &'a T,
755 attributes: &'a HashMap<String, String>,
756 ordering_key: Option<&'a str>,
757}
758
759/// Error returned when one or more messages in a `publish_batch` call could not
760/// be published.
761///
762/// `results` contains one entry per input message in order: `Ok(message_id)`
763/// for published messages and `Err(error)` for failed ones. Batch publishing is
764/// not atomic, so some messages may succeed while others fail. If the entire
765/// batch is invalid before sending (for example, exceeding [`MAX_BATCH_SIZE`],
766/// an encoding error, or an empty ordering key), nothing is published and every
767/// entry is an `Err`.
768///
769/// `BatchError` converts into [`Error`] (using the error code of the first
770/// failed message) so it can be propagated with `?`.
771#[derive(Debug, Clone)]
772pub struct BatchError {
773 pub results: Vec<Result<String, Error>>,
774}
775
776impl BatchError {
777 /// Iterates over the IDs of messages that were published, in input order.
778 pub fn published(&self) -> impl Iterator<Item = &str> {
779 self.results.iter().filter_map(|r| r.as_deref().ok())
780 }
781
782 /// Iterates over the index and error of each message that failed to publish.
783 pub fn failed(&self) -> impl Iterator<Item = (usize, &Error)> {
784 self.results
785 .iter()
786 .enumerate()
787 .filter_map(|(i, r)| r.as_ref().err().map(|err| (i, err)))
788 }
789
790 /// A batch of `count` messages refused whole, for `err`.
791 fn refused(count: usize, err: Error) -> Self {
792 Self {
793 results: vec![Err(err); count],
794 }
795 }
796
797 /// A batch of `count` messages refused whole for the messages that cannot
798 /// be sent, the first at index `first`: each says why, and the rest that
799 /// they were not sent because of it.
800 fn unsendable(count: usize, first: usize, unsendable: Vec<(usize, Error)>) -> Self {
801 let mut results: Vec<Result<String, Error>> = (0..count)
802 .map(|_| {
803 Err(Error::invalid_argument(format!(
804 "not published: batch was rejected because message {first} is invalid"
805 )))
806 })
807 .collect();
808 for (i, err) in unsendable {
809 results[i] = Err(err);
810 }
811 Self { results }
812 }
813
814 /// The ids, when every message was published.
815 fn check(results: Vec<Result<String, Error>>) -> Result<Vec<String>, BatchError> {
816 if results.iter().all(Result::is_ok) {
817 Ok(results.into_iter().map(Result::unwrap).collect())
818 } else {
819 Err(Self { results })
820 }
821 }
822}
823
824impl fmt::Display for BatchError {
825 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
826 let failed = self.failed().count();
827 let total = self.results.len();
828 write!(f, "{failed} of {total} messages failed to publish")?;
829 if let Some((i, err)) = self.failed().next() {
830 write!(f, "; message {i}: {}", err.message)?;
831 }
832 Ok(())
833 }
834}
835
836impl std::error::Error for BatchError {}
837
838impl From<BatchError> for Error {
839 fn from(err: BatchError) -> Self {
840 let code = err
841 .failed()
842 .next()
843 .map_or(ErrCode::Unknown, |(_, err)| err.code);
844 Error::new(code, err.to_string())
845 }
846}
847
848/// Permission marker types for [`TopicRef`]. Each permission corresponds to a
849/// trait in [`pubsub`](super).
850pub mod perms {
851 use super::{sealed::Sealed, TopicPerms};
852
853 /// Permission to publish messages ([`Publisher`](super::Publisher) or
854 /// [`OrderedPublisher`](super::OrderedPublisher)).
855 pub enum Publisher {}
856
857 impl Sealed for Publisher {}
858
859 impl TopicPerms for Publisher {
860 type Id = Self;
861 }
862}
863
864mod sealed {
865 pub trait Sealed {}
866}
867
868/// Sealed trait implemented by topic permission markers in [`perms`].
869pub trait TopicPerms: sealed::Sealed {
870 /// Always `Self`. [`Topic::reference`] returns `TopicRef<P::Id, …>`,
871 /// which the compiler cannot work back from to `P`, so `P` is never
872 /// inferred.
873 #[doc(hidden)]
874 type Id: TopicPerms;
875}
876
877/// A copyable, permission-scoped reference to a [`Topic`], created by
878/// [`Topic::reference`].
879///
880/// Exposes only the methods permitted by `P` (for example,
881/// `TopicRef<perms::Publisher, T>` can publish). Library code should accept the
882/// corresponding trait ([`Publisher`] or [`OrderedPublisher`]) instead of
883/// `TopicRef` directly.
884pub struct TopicRef<P, T, E = Json, O = Unordered> {
885 name: &'static str,
886 perms: PhantomData<fn() -> P>,
887 _marker: PhantomData<Carries<T, E, O>>,
888}
889
890/// A permission-scoped reference to an [`OrderedTopic`].
891pub type OrderedTopicRef<P, T, E = Json> = TopicRef<P, T, E, Ordered>;
892
893impl<P, T, E, O> Clone for TopicRef<P, T, E, O> {
894 fn clone(&self) -> Self {
895 *self
896 }
897}
898
899impl<P, T, E, O> Copy for TopicRef<P, T, E, O> {}
900
901impl<P, T, E, O> TopicRef<P, T, E, O> {
902 /// Returns the name of the referenced topic.
903 pub const fn name(&self) -> &'static str {
904 self.name
905 }
906
907 /// The topic, to publish through.
908 const fn topic(&self) -> Topic<T, E, O> {
909 Topic::new(self.name)
910 }
911}
912
913impl<T, E: Encoding<T>> TopicRef<perms::Publisher, T, E, Unordered> {
914 /// See [`Topic::publish`].
915 pub async fn publish(&self, data: &T) -> Result<String, Error> {
916 self.topic().publish(data).await
917 }
918
919 /// See [`Topic::publish_with`].
920 pub async fn publish_with(&self, data: &T, options: PublishOptions) -> Result<String, Error> {
921 self.topic().publish_with(data, options).await
922 }
923
924 /// See [`Topic::publish_batch`].
925 pub async fn publish_batch(
926 &self,
927 messages: &[BatchMessage<'_, T>],
928 ) -> Result<Vec<String>, BatchError> {
929 self.topic().publish_batch(messages).await
930 }
931}
932
933impl<T, E: Encoding<T>> TopicRef<perms::Publisher, T, E, Ordered> {
934 /// See [`Topic::publish`](Topic#method.publish-1).
935 pub async fn publish(&self, data: &T, ordering_key: &str) -> Result<String, Error> {
936 self.topic().publish(data, ordering_key).await
937 }
938
939 /// See [`Topic::publish_with`](Topic#method.publish_with-1).
940 pub async fn publish_with(
941 &self,
942 data: &T,
943 ordering_key: &str,
944 options: PublishOptions,
945 ) -> Result<String, Error> {
946 self.topic().publish_with(data, ordering_key, options).await
947 }
948
949 /// See [`Topic::publish_batch`](Topic#method.publish_batch-1).
950 pub async fn publish_batch(
951 &self,
952 messages: &[OrderedBatchMessage<'_, T>],
953 ) -> Result<Vec<String>, BatchError> {
954 self.topic().publish_batch(messages).await
955 }
956}
957
958/// Trait for publishing messages of type `T` to an unordered topic.
959///
960/// Implemented by [`TopicRef`] when granted [`perms::Publisher`]. Accept
961/// `&impl Publisher<T>` in helper functions so they work with references and
962/// test fakes:
963///
964/// ```no_run
965/// # use encore::pubsub::{perms, Publisher, Topic};
966/// # static SIGNUPS: Topic<String> = Topic::new("signups");
967/// async fn signed_up(topic: &impl Publisher<String>, user: &String) -> Result<(), encore::Error> {
968/// topic.publish(user).await?;
969/// Ok(())
970/// }
971///
972/// # async fn f(user: String) -> Result<(), encore::Error> {
973/// signed_up(&SIGNUPS.reference::<perms::Publisher>(), &user).await?;
974/// # Ok(())
975/// # }
976/// ```
977///
978/// [`Topic`] intentionally does not implement this trait so Encore can track
979/// permissions statically via [`Topic::reference`]:
980///
981/// ```compile_fail,E0277
982/// # use encore::pubsub::{Publisher, Topic};
983/// # static SIGNUPS: Topic<String> = Topic::new("signups");
984/// # async fn signed_up(topic: &impl Publisher<String>) {}
985/// # async fn f() {
986/// signed_up(&SIGNUPS).await;
987/// # }
988/// ```
989///
990/// Methods return `impl Future + Send` (making the trait compatible with
991/// spawned tasks, though not dyn-compatible).
992pub trait Publisher<T>: Send + Sync {
993 /// See [`Topic::publish`].
994 fn publish(&self, data: &T) -> impl Future<Output = Result<String, Error>> + Send {
995 self.publish_with(data, PublishOptions::default())
996 }
997
998 /// See [`Topic::publish_with`].
999 fn publish_with(
1000 &self,
1001 data: &T,
1002 options: PublishOptions,
1003 ) -> impl Future<Output = Result<String, Error>> + Send;
1004
1005 /// See [`Topic::publish_batch`].
1006 fn publish_batch(
1007 &self,
1008 messages: &[BatchMessage<'_, T>],
1009 ) -> impl Future<Output = Result<Vec<String>, BatchError>> + Send;
1010
1011 /// Returns the name of the topic.
1012 fn name(&self) -> &'static str;
1013}
1014
1015/// Trait for publishing messages of type `T` with ordering keys to an ordered
1016/// topic.
1017///
1018/// Implemented by [`OrderedTopicRef`] when granted [`perms::Publisher`]. Accept
1019/// `&impl OrderedPublisher<T>` in helper functions.
1020pub trait OrderedPublisher<T>: Send + Sync {
1021 /// See [`Topic::publish`](Topic#method.publish-1).
1022 fn publish(
1023 &self,
1024 data: &T,
1025 ordering_key: &str,
1026 ) -> impl Future<Output = Result<String, Error>> + Send {
1027 self.publish_with(data, ordering_key, PublishOptions::default())
1028 }
1029
1030 /// See [`Topic::publish_with`](Topic#method.publish_with-1).
1031 fn publish_with(
1032 &self,
1033 data: &T,
1034 ordering_key: &str,
1035 options: PublishOptions,
1036 ) -> impl Future<Output = Result<String, Error>> + Send;
1037
1038 /// See [`Topic::publish_batch`](Topic#method.publish_batch-1).
1039 fn publish_batch(
1040 &self,
1041 messages: &[OrderedBatchMessage<'_, T>],
1042 ) -> impl Future<Output = Result<Vec<String>, BatchError>> + Send;
1043
1044 /// Returns the name of the topic.
1045 fn name(&self) -> &'static str;
1046}
1047
1048impl<T: Sync, E: Encoding<T>> Publisher<T> for TopicRef<perms::Publisher, T, E, Unordered> {
1049 fn publish_with(
1050 &self,
1051 data: &T,
1052 options: PublishOptions,
1053 ) -> impl Future<Output = Result<String, Error>> + Send {
1054 self.publish_with(data, options)
1055 }
1056
1057 fn publish_batch(
1058 &self,
1059 messages: &[BatchMessage<'_, T>],
1060 ) -> impl Future<Output = Result<Vec<String>, BatchError>> + Send {
1061 self.publish_batch(messages)
1062 }
1063
1064 fn name(&self) -> &'static str {
1065 self.name
1066 }
1067}
1068
1069impl<T: Sync, E: Encoding<T>> OrderedPublisher<T> for TopicRef<perms::Publisher, T, E, Ordered> {
1070 fn publish_with(
1071 &self,
1072 data: &T,
1073 ordering_key: &str,
1074 options: PublishOptions,
1075 ) -> impl Future<Output = Result<String, Error>> + Send {
1076 self.publish_with(data, ordering_key, options)
1077 }
1078
1079 fn publish_batch(
1080 &self,
1081 messages: &[OrderedBatchMessage<'_, T>],
1082 ) -> impl Future<Output = Result<Vec<String>, BatchError>> + Send {
1083 self.publish_batch(messages)
1084 }
1085
1086 fn name(&self) -> &'static str {
1087 self.name
1088 }
1089}
1090
1091/// Async handler function signature for a [`Subscription`].
1092///
1093/// Returning `Err` triggers redelivery according to the subscription's retry
1094/// policy.
1095pub type Handler<T> = fn(Message<T>) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send>>;
1096
1097/// A subscription that delivers messages from a [`Topic`] to a handler function.
1098pub struct Subscription<T> {
1099 name: &'static str,
1100 topic: &'static str,
1101 decode: fn(&[u8]) -> Result<T, Error>,
1102 handler: Handler<T>,
1103 started: AtomicBool,
1104}
1105
1106impl<T> Subscription<T> {
1107 /// Declares a subscription to `topic`.
1108 ///
1109 /// This constructor is `const` so it can initialize a module-scope `static`.
1110 /// Pass a closure returning a boxed future (`|msg| Box::pin(send_welcome(msg))`),
1111 /// or annotate the `static` with
1112 /// [`#[encore::pubsub::register]`](macro@register) to pass `send_welcome`
1113 /// directly and start the subscription automatically at startup.
1114 ///
1115 /// ```no_run
1116 /// # use std::time::Duration;
1117 /// # use encore::pubsub::{Message, Subscription, Topic};
1118 /// # static SIGNUPS: Topic<String> = Topic::new("signups");
1119 /// # async fn send_welcome(_: Message<String>) -> Result<(), encore::Error> { Ok(()) }
1120 /// static WELCOME: Subscription<String> =
1121 /// Subscription::new(&SIGNUPS, "send-welcome", |msg| Box::pin(send_welcome(msg)))
1122 /// .ack_deadline(Duration::from_secs(60))
1123 /// .max_attempts(5);
1124 /// ```
1125 pub const fn new<E: Encoding<T>, O>(
1126 topic: &'static Topic<T, E, O>,
1127 name: &'static str,
1128 handler: Handler<T>,
1129 ) -> Self {
1130 Self {
1131 name,
1132 topic: topic.name,
1133 decode: E::decode,
1134 handler,
1135 started: AtomicBool::new(false),
1136 }
1137 }
1138
1139 /// Sets how long a handler has to acknowledge a message before it is
1140 /// redelivered (defaults to 30 seconds).
1141 ///
1142 /// For pull subscriptions, Encore automatically extends the lease for up to
1143 /// 1 hour (or this duration, if longer) while the handler is running; for
1144 /// push subscriptions (such as GCP push), this is the delivery timeout.
1145 pub const fn ack_deadline(self, _deadline: Duration) -> Self {
1146 self
1147 }
1148
1149 /// Sets how long undelivered messages are retained before expiring
1150 /// (defaults to 7 days).
1151 pub const fn message_retention(self, _retention: Duration) -> Self {
1152 self
1153 }
1154
1155 /// Sets the minimum retry backoff after a failed delivery (defaults to 10
1156 /// seconds).
1157 pub const fn min_backoff(self, _backoff: Duration) -> Self {
1158 self
1159 }
1160
1161 /// Sets the maximum retry backoff after a failed delivery (defaults to 10
1162 /// minutes).
1163 pub const fn max_backoff(self, _backoff: Duration) -> Self {
1164 self
1165 }
1166
1167 /// Sets the maximum number of times a message is delivered, including the
1168 /// first delivery, before it is moved to the dead-letter queue (defaults to
1169 /// 100). Must be between 1 (no retries) and 100. On GCP, the minimum is 5,
1170 /// so lower values behave as 5.
1171 pub const fn max_attempts(self, _attempts: u32) -> Self {
1172 self
1173 }
1174
1175 /// Limits how many messages this subscription processes concurrently in
1176 /// each service instance (defaults to 100). Must be at least 1. On an ordered
1177 /// topic, messages sharing an ordering key are processed one at a time.
1178 ///
1179 /// It has no effect on GCP Cloud Run for unordered topics, whose messages
1180 /// are pushed with a concurrency GCP adapts.
1181 pub const fn max_concurrency(self, _concurrency: u32) -> Self {
1182 self
1183 }
1184
1185 /// Filters which messages are delivered to this subscription based on their
1186 /// attributes. Unmatched messages are skipped before delivery (defaults to
1187 /// receiving all messages).
1188 ///
1189 /// Uses a cloud-portable subset of the
1190 /// [expr language](https://expr-lang.org):
1191 ///
1192 /// ```text
1193 /// .filter(r#"attrs.region in ["eu-west-1", "eu-north-1"] and not (attrs.kind startsWith "test-")"#)
1194 /// ```
1195 ///
1196 /// Supported operations:
1197 /// - Comparisons: `attrs.region == "eu"`, `!=`, `in [...]`, `not in [...]`,
1198 /// and `startsWith "eu-"` (use `attrs["iana.org-lang"]` for attribute
1199 /// names containing characters outside letters, digits, and `_`).
1200 /// - Presence checks: `"region" in attrs` and `"region" not in attrs`.
1201 /// Positive value checks evaluate to false if the attribute is missing,
1202 /// while negated checks evaluate to true.
1203 /// - Boolean logic: `and` (`&&`), `or` (`||`), `not (...)` (`!(...)`), and
1204 /// parentheses.
1205 ///
1206 /// Must be a string literal so Encore can parse and validate it against
1207 /// cloud provider limits.
1208 pub const fn filter(self, _filter: &'static str) -> Self {
1209 self
1210 }
1211
1212 /// Assigns this subscription to a named worker declared in the `workers`
1213 /// section of the service's `encore.service.json`.
1214 ///
1215 /// Only that worker process consumes messages for this subscription. If
1216 /// omitted, the service's main process consumes it. Must be a string
1217 /// literal.
1218 pub const fn worker(self, _worker: &'static str) -> Self {
1219 self
1220 }
1221
1222 /// Attaches a key/value tag to the subscription (for example,
1223 /// `.tag("data", "pci")`) for policy and governance tooling.
1224 ///
1225 /// Call once per tag with unique keys. Both `key` and `value` must be string
1226 /// literals so Encore can parse them statically. Keys must start with a
1227 /// letter, contain only lowercase letters, digits, `_`, and `-`, and must
1228 /// not start with `encore` (reserved for Encore's own tags). Values use the
1229 /// same character set or may be empty. Each key and value is at most 63
1230 /// characters, and a subscription may have at most 32 tags.
1231 ///
1232 /// ```no_run
1233 /// # use encore::pubsub::{Message, Subscription, Topic};
1234 /// # static SIGNUPS: Topic<String> = Topic::new("signups");
1235 /// # async fn send_welcome(_: Message<String>) -> Result<(), encore::Error> { Ok(()) }
1236 /// static WELCOME: Subscription<String> =
1237 /// Subscription::new(&SIGNUPS, "send-welcome", |msg| Box::pin(send_welcome(msg)))
1238 /// .tag("team", "growth");
1239 /// ```
1240 pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
1241 self
1242 }
1243
1244 /// Returns the name this subscription was declared with.
1245 pub const fn name(&self) -> &'static str {
1246 self.name
1247 }
1248}
1249
1250impl<T: Send + 'static> Subscription<T> {
1251 /// Starts consuming messages for this subscription if it has not already
1252 /// been started.
1253 ///
1254 /// Subscriptions annotated with
1255 /// [`#[encore::pubsub::register]`](macro@register) are started
1256 /// automatically; call this manually for unregistered subscriptions.
1257 pub fn start(&'static self) -> Result<(), Error> {
1258 if self.started.swap(true, Ordering::SeqCst) {
1259 return Ok(());
1260 }
1261 let subscription = core()
1262 .pubsub()
1263 .subscription(core_pubsub::SubName {
1264 topic: self.topic.into(),
1265 subscription: self.name.into(),
1266 })
1267 .ok_or_else(|| {
1268 Error::not_found(format!(
1269 "subscription {:?} on topic {:?} is not configured",
1270 self.name, self.topic
1271 ))
1272 })?;
1273 let (topic, name) = (self.topic, self.name);
1274 core().tokio_handle().spawn(async move {
1275 let handler = Arc::new(Runner { subscription: self });
1276 if let Err(err) = subscription.subscribe(handler).await {
1277 eprintln!("encore: subscription {name:?} on topic {topic:?} stopped: {err}");
1278 }
1279 });
1280 Ok(())
1281 }
1282}
1283
1284impl<T: Send + 'static> Subscription<T> {
1285 /// Hands the subscription's handler what the test `test` published to
1286 /// its topic and it has not handled: see [`testing::deliver`].
1287 pub(crate) async fn deliver_in(&'static self, test: &testing::Scope) -> Result<usize, Error> {
1288 use encore_sdk_core::telemetry::opentelemetry::trace::FutureExt;
1289 use encore_sdk_core::telemetry::opentelemetry::Context;
1290 use encore_sdk_core::test_scope::MAX_DELIVERIES;
1291
1292 let scope = test.core_scope()?;
1293 let mut handled = 0;
1294 while let Some(delivery) = scope.next_delivery(self.topic, self.name) {
1295 if handled == MAX_DELIVERIES {
1296 return Err(Error::new(
1297 ErrCode::ResourceExhausted,
1298 format!(
1299 "subscription {:?} processed {MAX_DELIVERIES} messages in a single \
1300 deliver() call and more remain: check whether the handler publishes \
1301 back to its own topic {:?} on every invocation",
1302 self.name, self.topic
1303 ),
1304 ));
1305 }
1306 let published = delivery.message;
1307 // The Request Context fields the message carries are the
1308 // handler's context, as in a real delivery.
1309 let mut attributes = published.attributes;
1310 let fields = Values::take_attributes(&mut attributes);
1311 let context = fields.in_context(&Context::new());
1312 let outcome = async {
1313 let message = Message {
1314 data: (self.decode)(&published.payload)?,
1315 id: published.id,
1316 raw_data: published.payload,
1317 ordering_key: published.ordering_key,
1318 attributes,
1319 publish_time: published.publish_time,
1320 delivery_attempt: delivery.attempt,
1321 };
1322 (self.handler)(message).await
1323 }
1324 .with_context(context)
1325 .await;
1326 scope.settle_delivery(self.topic, self.name, outcome.is_ok());
1327 outcome?;
1328 handled += 1;
1329 }
1330 Ok(handled)
1331 }
1332}
1333
1334/// Hands the runtime's messages to a subscription's handler.
1335struct Runner<T: 'static> {
1336 subscription: &'static Subscription<T>,
1337}
1338
1339impl<T> fmt::Debug for Runner<T> {
1340 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1341 f.debug_struct("Subscription")
1342 .field("topic", &self.subscription.topic)
1343 .field("name", &self.subscription.name)
1344 .finish()
1345 }
1346}
1347
1348impl<T: Send + 'static> core_pubsub::SubscriptionHandler for Runner<T> {
1349 fn handle_message(
1350 &self,
1351 msg: Arc<core_pubsub::Message>,
1352 span_ctx: encore_sdk_core::telemetry::SpanContext,
1353 ) -> Pin<Box<dyn Future<Output = Result<(), encore_sdk_core::api::Error>> + Send + 'static>>
1354 {
1355 use encore_sdk_core::telemetry::opentelemetry::trace::{FutureExt, TraceContextExt};
1356 use encore_sdk_core::telemetry::opentelemetry::Context;
1357
1358 let subscription = self.subscription;
1359 // What the handler does is traced under the delivery's span, with the
1360 // Request Context fields the message carries. Their attributes are
1361 // Encore's: the handler reads the fields from its context.
1362 let mut attributes = msg.data.attrs.clone();
1363 let fields = Values::take_attributes(&mut attributes);
1364 let mut delivery = Context::new().with_remote_span_context(span_ctx);
1365 if !fields.is_empty() {
1366 delivery = fields.in_context(&delivery);
1367 }
1368 let handle = async move {
1369 // What the core records of a failure: no client is answered
1370 // with it, so the message is all internal.
1371 let failed = |err: Error| {
1372 let code = encore_sdk_core::api::ErrCode::from(err.code);
1373 encore_sdk_core::api::Error {
1374 code,
1375 message: code.default_public_message().into(),
1376 internal_message: Some(err.message),
1377 stack: None,
1378 details: None,
1379 exception: None,
1380 }
1381 };
1382 let message = Message {
1383 id: msg.id.clone(),
1384 data: (subscription.decode)(&msg.data.raw_body).map_err(failed)?,
1385 raw_data: msg.data.raw_body.clone(),
1386 ordering_key: msg.ordering_key.clone(),
1387 attributes,
1388 publish_time: msg.publish_time.into(),
1389 delivery_attempt: msg.attempt,
1390 };
1391 (subscription.handler)(message).await.map_err(failed)
1392 };
1393 Box::pin(handle.with_context(delivery))
1394 }
1395}
1396
1397/// What `#[encore::pubsub::register]` expands to. Not for use by hand: it
1398/// changes with the macro.
1399#[doc(hidden)]
1400pub mod __private {
1401 use super::*;
1402
1403 pub use linkme;
1404
1405 /// A subscription, whatever its message type.
1406 pub trait AnySubscription: Sync {
1407 fn start(&'static self) -> Result<(), Error>;
1408 }
1409
1410 impl<T: Send + 'static> AnySubscription for Subscription<T> {
1411 fn start(&'static self) -> Result<(), Error> {
1412 Subscription::start(self)
1413 }
1414 }
1415
1416 /// Every subscription registered to be started with the app, collected at
1417 /// link time: a `static` says nothing of itself until it is used.
1418 #[linkme::distributed_slice]
1419 pub static SUBSCRIPTIONS: [&'static dyn AnySubscription];
1420}
1421
1422/// Starts every subscription registered with
1423/// [`#[encore::pubsub::register]`](macro@register). Called when the
1424/// app starts; not under `encore test`, where nothing handles what a test
1425/// publishes.
1426pub(crate) fn start_registered() {
1427 if core().postgres().isolates_instances() {
1428 return;
1429 }
1430 for subscription in __private::SUBSCRIPTIONS {
1431 if let Err(err) = subscription.start() {
1432 eprintln!("encore: {err}");
1433 }
1434 }
1435 core().pubsub().subscriptions_started();
1436}
1437
1438#[cfg(test)]
1439mod tests {
1440 use std::sync::Mutex;
1441
1442 use encore_sdk_core::pubsub::SubscriptionHandler as _;
1443
1444 use super::*;
1445 use crate::reqctx::Field;
1446
1447 static USER: Field<String> = Field::new("user").pubsub();
1448 static EVENTS: Topic<String> = Topic::new("events");
1449 /// The field and attributes each message was handled with.
1450 type Seen = (Option<String>, HashMap<String, String>);
1451 static SEEN: Mutex<Vec<Seen>> = Mutex::new(Vec::new());
1452 static AUDIT: Subscription<String> = Subscription::new(&EVENTS, "audit", |msg| {
1453 Box::pin(async move {
1454 SEEN.lock().unwrap().push((USER.get(), msg.attributes));
1455 Ok(())
1456 })
1457 });
1458
1459 #[test]
1460 fn publish_options_add_attributes_one_at_a_time_or_all_at_once() {
1461 let tags = HashMap::from([
1462 ("source".to_string(), "web".to_string()),
1463 ("tier".to_string(), "free".to_string()),
1464 ]);
1465 // A map, or pairs; a later value for a name replaces an earlier one.
1466 let options = PublishOptions::new()
1467 .attributes(tags)
1468 .attributes([("tier", "pro")])
1469 .attribute("region", "eu");
1470 let want: HashMap<String, String> = [("source", "web"), ("tier", "pro"), ("region", "eu")]
1471 .into_iter()
1472 .map(|(k, v)| (k.to_string(), v.to_string()))
1473 .collect();
1474 assert_eq!(options.attributes, want);
1475 }
1476
1477 #[test]
1478 fn a_handler_runs_with_the_fields_its_message_carries() {
1479 let message = Arc::new(core_pubsub::Message {
1480 id: "1".into(),
1481 publish_time: SystemTime::now().into(),
1482 attempt: 1,
1483 ordering_key: None,
1484 data: core_pubsub::MessageData {
1485 attrs: HashMap::from([
1486 ("encore-ctx-user".into(), "ImFkYSI".into()),
1487 ("source".into(), "test".into()),
1488 ]),
1489 raw_body: b"\"hi\"".to_vec(),
1490 },
1491 });
1492 let runner = Runner {
1493 subscription: &AUDIT,
1494 };
1495 let rt = tokio::runtime::Builder::new_current_thread()
1496 .build()
1497 .unwrap();
1498 rt.block_on(runner.handle_message(
1499 message,
1500 encore_sdk_core::telemetry::SpanContext::empty_context(),
1501 ))
1502 .unwrap();
1503 let seen = SEEN.lock().unwrap();
1504 assert_eq!(
1505 *seen,
1506 [(
1507 Some("ada".to_string()),
1508 HashMap::from([("source".to_string(), "test".to_string())])
1509 )]
1510 );
1511 }
1512
1513 #[test]
1514 fn each_message_is_answered_for_in_its_place() {
1515 let results = settle(
1516 4,
1517 vec![
1518 Ok("a".to_string()),
1519 Err(anyhow::anyhow!("refused")),
1520 Ok("c".to_string()),
1521 ],
1522 );
1523 assert_eq!(results[0].as_deref().unwrap(), "a");
1524 assert_eq!(results[1].as_ref().unwrap_err().code, ErrCode::Unavailable);
1525 assert_eq!(results[2].as_deref().unwrap(), "c");
1526 // Not answered for: not published.
1527 assert!(results[3].is_err());
1528 assert!(BatchError::check(results).is_err());
1529 }
1530
1531 #[test]
1532 fn a_batch_published_whole_is_its_ids() {
1533 let results = settle(2, vec![Ok("a".into()), Ok("b".into())]);
1534 assert_eq!(BatchError::check(results).unwrap(), ["a", "b"]);
1535 }
1536}