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