Skip to main content

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