Skip to main content

encore/
pubsub.rs

1//! Pub/Sub topics and subscriptions. Topics are typed by the message they
2//! carry and declared at module scope; a subscription names its topic and the
3//! function that handles its messages.
4//!
5//! ```no_run
6//! use encore::pubsub::{Message, Subscription, Topic};
7//! use serde::{Deserialize, Serialize};
8//!
9//! #[derive(Serialize, Deserialize)]
10//! struct SignupEvent {
11//!     user_id: String,
12//! }
13//!
14//! static SIGNUPS: Topic<SignupEvent> = Topic::new("signups");
15//!
16//! #[encore::pubsub::register]
17//! static WELCOME: Subscription<SignupEvent> =
18//!     Subscription::new(&SIGNUPS, "send-welcome", send_welcome);
19//!
20//! async fn send_welcome(msg: Message<SignupEvent>) -> Result<(), encore::Error> {
21//!     println!("welcome, {}", msg.data.user_id);
22//!     Ok(())
23//! }
24//!
25//! async fn signed_up(user_id: String) -> Result<(), encore::Error> {
26//!     SIGNUPS.publish(&SignupEvent { user_id }).await?;
27//!     Ok(())
28//! }
29//! ```
30//!
31//! # Encodings
32//!
33//! A topic's second type argument says how its messages are encoded: [`Json`]
34//! unless said otherwise, [`Raw`] for bytes passed through as they are, and —
35//! with the `protobuf` feature — `Protobuf`. It is part of the topic's type, so
36//! a publisher and a subscriber cannot disagree about it, and Encore can read
37//! it from the declaration.
38//!
39//! # Ordered topics
40//!
41//! An [`OrderedTopic`] delivers the messages that share an ordering key in the
42//! order they were published. Its `publish` takes the key.
43//!
44//! # Running subscriptions
45//!
46//! A `static` does nothing until it is used, so something has to start a
47//! subscription. [`#[encore::pubsub::register]`](macro@register)
48//! registers one to be started with the app, by [`crate::initialize`] or
49//! [`crate::run_blocking`]. One declared without it is started by hand, with
50//! [`Subscription::start`].
51//!
52//! # Tests
53//!
54//! Under `encore test` each test publishes to topics of its own, and nothing
55//! handles what it publishes: no subscription is started. The test reads back
56//! what it — and the code it called — published with
57//! [`testing::published`](crate::testing::published), and calls a handler
58//! itself when it wants one run.
59
60use std::collections::HashMap;
61use std::fmt;
62use std::future::Future;
63use std::marker::PhantomData;
64use std::pin::Pin;
65use std::sync::atomic::{AtomicBool, Ordering};
66use std::sync::Arc;
67use std::time::{Duration, SystemTime};
68
69use encore_sdk_core::pubsub as core_pubsub;
70use serde::de::DeserializeOwned;
71use serde::Serialize;
72
73use crate::error::{ErrCode, Error};
74use crate::runtime::core;
75use crate::testing;
76
77/// Registers a subscription to be started with the app.
78///
79/// Put it on the `static`. It also lets the handler be given as the plain
80/// name of an `async fn`, in place of the boxing closure [`Subscription::new`]
81/// takes.
82///
83/// ```no_run
84/// # use encore::pubsub::{Message, Subscription, Topic};
85/// # static SIGNUPS: Topic<String> = Topic::new("signups");
86/// #[encore::pubsub::register]
87/// static WELCOME: Subscription<String> =
88///     Subscription::new(&SIGNUPS, "send-welcome", send_welcome).max_concurrency(4);
89///
90/// async fn send_welcome(msg: Message<String>) -> Result<(), encore::Error> {
91///     Ok(())
92/// }
93/// ```
94pub use encore_macros::register;
95
96/// A message, as a subscription's handler receives it.
97#[derive(Debug, Clone)]
98pub struct Message<T> {
99    /// The message's id, unique within its topic.
100    pub id: String,
101    /// The message, decoded.
102    pub data: T,
103    /// The message as it was sent, before decoding.
104    pub raw_data: Vec<u8>,
105    /// The attributes it was published with.
106    pub attributes: HashMap<String, String>,
107    pub publish_time: SystemTime,
108    /// Which attempt at delivering the message this is, from 1.
109    pub delivery_attempt: u32,
110    /// The key it was published with, on an [`OrderedTopic`].
111    pub ordering_key: Option<String>,
112}
113
114/// How a topic's messages are encoded. Implemented by the encodings, for the
115/// message types each can carry.
116pub trait Encoding<T> {
117    fn encode(value: &T) -> Result<Vec<u8>, Error>;
118    fn decode(raw: &[u8]) -> Result<T, Error>;
119}
120
121/// JSON, for a message type that is `Serialize` and `Deserialize`. The default.
122pub enum Json {}
123
124impl<T: Serialize + DeserializeOwned> Encoding<T> for Json {
125    fn encode(value: &T) -> Result<Vec<u8>, Error> {
126        serde_json::to_vec(value).map_err(|e| Error::wrap(ErrCode::InvalidArgument, e))
127    }
128
129    fn decode(raw: &[u8]) -> Result<T, Error> {
130        serde_json::from_slice(raw).map_err(|e| Error::wrap(ErrCode::InvalidArgument, e))
131    }
132}
133
134/// No encoding: the message is the bytes, as a `Vec<u8>`.
135pub enum Raw {}
136
137impl Encoding<Vec<u8>> for Raw {
138    fn encode(value: &Vec<u8>) -> Result<Vec<u8>, Error> {
139        Ok(value.clone())
140    }
141
142    fn decode(raw: &[u8]) -> Result<Vec<u8>, Error> {
143        Ok(raw.to_vec())
144    }
145}
146
147/// Protocol Buffers, for a `prost` message type.
148#[cfg(feature = "protobuf")]
149pub enum Protobuf {}
150
151#[cfg(feature = "protobuf")]
152impl<T: prost::Message + Default> Encoding<T> for Protobuf {
153    fn encode(value: &T) -> Result<Vec<u8>, Error> {
154        Ok(value.encode_to_vec())
155    }
156
157    fn decode(raw: &[u8]) -> Result<T, Error> {
158        T::decode(raw).map_err(|e| Error::wrap(ErrCode::InvalidArgument, e))
159    }
160}
161
162/// Marks a [`Topic`] whose messages are delivered in no particular order.
163pub enum Unordered {}
164
165/// Marks a [`Topic`] that orders messages by key: an [`OrderedTopic`].
166pub enum Ordered {}
167
168/// A pub/sub topic carrying messages of type `T`, encoded as `E`.
169pub struct Topic<T, E = Json, O = Unordered> {
170    name: &'static str,
171    /// Read by Encore's parser from the declaration, not by the runtime.
172    #[allow(dead_code)]
173    exactly_once: bool,
174    _marker: PhantomData<Carries<T, E, O>>,
175}
176
177/// What a topic's type parameters stand for, none of which it holds.
178type Carries<T, E, O> = fn() -> (T, E, O);
179
180/// A [`Topic`] that delivers the messages sharing an ordering key in the order
181/// they were published.
182pub type OrderedTopic<T, E = Json> = Topic<T, E, Ordered>;
183
184/// Options for publishing a message.
185#[derive(Debug, Clone, Default)]
186pub struct PublishOptions {
187    /// Attributes delivered alongside the message.
188    pub attributes: HashMap<String, String>,
189}
190
191impl<T, E, O> Topic<T, E, O> {
192    /// Declare a topic. `const` so it can initialize a module-scope `static`,
193    /// whose type gives the message type and the encoding.
194    ///
195    /// Options follow the name, each a method of its own:
196    ///
197    /// ```no_run
198    /// use encore::pubsub::{OrderedTopic, Raw, Topic};
199    ///
200    /// static EVENTS: Topic<String> = Topic::new("events");
201    /// static PAYMENTS: Topic<String> = Topic::new("payments").exactly_once();
202    /// static BLOBS: Topic<Vec<u8>, Raw> = Topic::new("blobs");
203    /// static CHANGES: OrderedTopic<String> = OrderedTopic::new("changes");
204    /// ```
205    pub const fn new(name: &'static str) -> Self {
206        Self {
207            name,
208            exactly_once: false,
209            _marker: PhantomData,
210        }
211    }
212
213    /// Reference an existing topic by name: one another service declares,
214    /// possibly in another language. To declare a new topic, use
215    /// [`Topic::new`] instead.
216    ///
217    /// The name must be a string literal, so Encore can resolve it statically.
218    /// A named topic takes no options: it is configured where it is declared.
219    /// Its message type and encoding are the author's claim: across languages
220    /// they cannot be checked.
221    ///
222    /// ```no_run
223    /// static SIGNUPS: encore::pubsub::Topic<String> = encore::pubsub::Topic::named("signups");
224    /// ```
225    pub const fn named(name: &'static str) -> Self {
226        Self::new(name)
227    }
228
229    /// Has each message delivered exactly once, rather than at least once.
230    ///
231    /// Part of the declaration: it takes the topic by value, so it cannot be
232    /// called on the `static`.
233    pub const fn exactly_once(mut self) -> Self {
234        self.exactly_once = true;
235        self
236    }
237
238    /// The name the topic was declared with.
239    pub const fn name(&self) -> &'static str {
240        self.name
241    }
242}
243
244impl<T, E: Encoding<T>, O> Topic<T, E, O> {
245    /// Encodes and publishes a message: to the app's topic, or under `encore
246    /// test` to the current test's instance of it, where it is also noted for
247    /// the test to read back.
248    async fn send(
249        &self,
250        data: &T,
251        attributes: HashMap<String, String>,
252        ordering_key: Option<&str>,
253    ) -> Result<String, Error> {
254        let payload = E::encode(data)?;
255        let ordering_key = ordering_key.map(str::to_owned);
256        let unavailable = |e: anyhow::Error| Error::wrap(ErrCode::Unavailable, format!("{e:#}"));
257        match testing::active()? {
258            Some(test) => {
259                let id = test
260                    .topic(self.name)?
261                    .publish(payload.clone(), attributes.clone(), ordering_key.clone())
262                    .await
263                    .map_err(unavailable)?;
264                test.note_published(
265                    self.name,
266                    testing::Published {
267                        id: id.clone(),
268                        payload,
269                        attributes,
270                        ordering_key,
271                        publish_time: SystemTime::now(),
272                    },
273                );
274                Ok(id)
275            }
276            None => core()
277                .pubsub()
278                .topic(self.name.into())
279                .ok_or_else(|| {
280                    Error::not_found(format!("topic {:?} is not configured", self.name))
281                })?
282                .publish(payload, attributes, ordering_key)
283                .await
284                .map_err(unavailable),
285        }
286    }
287
288    /// What the current test has published to the topic, decoded.
289    pub(crate) fn published_in(&self, test: &testing::Scope) -> Result<Vec<Message<T>>, Error> {
290        test.published(self.name)
291            .into_iter()
292            .map(|published| {
293                Ok(Message {
294                    data: E::decode(&published.payload)?,
295                    id: published.id,
296                    raw_data: published.payload,
297                    ordering_key: published.ordering_key,
298                    attributes: published.attributes,
299                    publish_time: published.publish_time,
300                    delivery_attempt: 1,
301                })
302            })
303            .collect()
304    }
305}
306
307impl<T, E: Encoding<T>> Topic<T, E, Unordered> {
308    /// Publish a message, returning its id.
309    pub async fn publish(&self, data: &T) -> Result<String, Error> {
310        self.send(data, HashMap::new(), None).await
311    }
312
313    /// Publish a message with explicit options: attributes delivered alongside
314    /// it.
315    pub async fn publish_with(&self, data: &T, options: PublishOptions) -> Result<String, Error> {
316        self.send(data, options.attributes, None).await
317    }
318}
319
320impl<T, E: Encoding<T>> Topic<T, E, Ordered> {
321    /// Publish a message, returning its id. Messages published with the same
322    /// `ordering_key` are delivered in the order they were published.
323    pub async fn publish(&self, data: &T, ordering_key: &str) -> Result<String, Error> {
324        self.publish_with(data, ordering_key, PublishOptions::default())
325            .await
326    }
327
328    /// Publish a message with explicit options: attributes delivered alongside
329    /// it.
330    pub async fn publish_with(
331        &self,
332        data: &T,
333        ordering_key: &str,
334        options: PublishOptions,
335    ) -> Result<String, Error> {
336        if ordering_key.is_empty() {
337            return Err(Error::invalid_argument(format!(
338                "the ordering key for topic {} cannot be empty",
339                self.name
340            )));
341        }
342        self.send(data, options.attributes, Some(ordering_key))
343            .await
344    }
345}
346
347/// A subscription's handler: a function returning the future that handles a
348/// message. An error has the message delivered again, as the retry policy says.
349pub type Handler<T> = fn(Message<T>) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send>>;
350
351/// A subscription to a topic: every message published to the topic is handed
352/// to its handler.
353pub struct Subscription<T> {
354    name: &'static str,
355    topic: &'static str,
356    decode: fn(&[u8]) -> Result<T, Error>,
357    handler: Handler<T>,
358    started: AtomicBool,
359}
360
361impl<T> Subscription<T> {
362    /// Declare a subscription to `topic`. `const` so it can initialize a
363    /// module-scope `static`.
364    ///
365    /// The handler is a function, boxing the future that handles a message:
366    /// `|msg| Box::pin(send_welcome(msg))`. Under
367    /// [`#[encore::pubsub::register]`](macro@register), which also has
368    /// the subscription started with the app, it can be just `send_welcome`.
369    ///
370    /// Options follow, each a method of its own:
371    ///
372    /// ```no_run
373    /// # use std::time::Duration;
374    /// # use encore::pubsub::{Message, Subscription, Topic};
375    /// # static SIGNUPS: Topic<String> = Topic::new("signups");
376    /// # async fn send_welcome(_: Message<String>) -> Result<(), encore::Error> { Ok(()) }
377    /// static WELCOME: Subscription<String> =
378    ///     Subscription::new(&SIGNUPS, "send-welcome", |msg| Box::pin(send_welcome(msg)))
379    ///         .ack_deadline(Duration::from_secs(60))
380    ///         .max_retries(5);
381    /// ```
382    pub const fn new<E: Encoding<T>, O>(
383        topic: &'static Topic<T, E, O>,
384        name: &'static str,
385        handler: Handler<T>,
386    ) -> Self {
387        Self {
388            name,
389            topic: topic.name,
390            decode: E::decode,
391            handler,
392            started: AtomicBool::new(false),
393        }
394    }
395
396    /// How long the handler has to finish before the message is delivered
397    /// again. 30 seconds if not given.
398    ///
399    /// The options are part of the declaration, read by Encore's parser: each
400    /// takes the subscription by value, so it cannot be called on the `static`.
401    pub const fn ack_deadline(self, _deadline: Duration) -> Self {
402        self
403    }
404
405    /// How long an undelivered message is kept. Seven days if not given.
406    pub const fn message_retention(self, _retention: Duration) -> Self {
407        self
408    }
409
410    /// The shortest wait before a failed message is delivered again. 10
411    /// seconds if not given.
412    pub const fn min_backoff(self, _backoff: Duration) -> Self {
413        self
414    }
415
416    /// The longest wait before a failed message is delivered again. 10 minutes
417    /// if not given.
418    pub const fn max_backoff(self, _backoff: Duration) -> Self {
419        self
420    }
421
422    /// How many times a failed message is delivered again before it is given
423    /// up on. 100 if not given; -1 to never give up, -2 to never retry.
424    pub const fn max_retries(self, _retries: i32) -> Self {
425        self
426    }
427
428    /// How many messages are handled at once. Unlimited if not given.
429    pub const fn max_concurrency(self, _concurrency: u32) -> Self {
430        self
431    }
432
433    /// The name the subscription was declared with.
434    pub const fn name(&self) -> &'static str {
435        self.name
436    }
437}
438
439impl<T: Send + 'static> Subscription<T> {
440    /// Starts handling the topic's messages, if it has not been started.
441    ///
442    /// A subscription under [`#[encore::pubsub::register]`](macro@register)
443    /// is started with the app; this is for one that is not.
444    pub fn start(&'static self) -> Result<(), Error> {
445        if self.started.swap(true, Ordering::SeqCst) {
446            return Ok(());
447        }
448        let subscription = core()
449            .pubsub()
450            .subscription(core_pubsub::SubName {
451                topic: self.topic.into(),
452                subscription: self.name.into(),
453            })
454            .ok_or_else(|| {
455                Error::not_found(format!(
456                    "subscription {:?} on topic {:?} is not configured",
457                    self.name, self.topic
458                ))
459            })?;
460        let (topic, name) = (self.topic, self.name);
461        core().tokio_handle().spawn(async move {
462            let handler = Arc::new(Runner { subscription: self });
463            if let Err(err) = subscription.subscribe(handler).await {
464                eprintln!("encore: subscription {name:?} on topic {topic:?} stopped: {err}");
465            }
466        });
467        Ok(())
468    }
469}
470
471/// Hands the runtime's messages to a subscription's handler.
472struct Runner<T: 'static> {
473    subscription: &'static Subscription<T>,
474}
475
476impl<T> fmt::Debug for Runner<T> {
477    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
478        f.debug_struct("Subscription")
479            .field("topic", &self.subscription.topic)
480            .field("name", &self.subscription.name)
481            .finish()
482    }
483}
484
485impl<T: Send + 'static> core_pubsub::SubscriptionHandler for Runner<T> {
486    fn handle_message(
487        &self,
488        msg: Arc<core_pubsub::Message>,
489        span_ctx: encore_sdk_core::telemetry::SpanContext,
490    ) -> Pin<Box<dyn Future<Output = Result<(), encore_sdk_core::api::Error>> + Send + 'static>>
491    {
492        use encore_sdk_core::telemetry::opentelemetry::trace::{FutureExt, TraceContextExt};
493        use encore_sdk_core::telemetry::opentelemetry::Context;
494
495        let subscription = self.subscription;
496        // What the handler does is traced under the delivery's span.
497        let delivery = Context::new().with_remote_span_context(span_ctx);
498        let handle = async move {
499            let failed =
500                |err: Error| encore_sdk_core::api::Error::internal(anyhow::anyhow!("{err}"));
501            let message = Message {
502                id: msg.id.clone(),
503                data: (subscription.decode)(&msg.data.raw_body).map_err(failed)?,
504                raw_data: msg.data.raw_body.clone(),
505                ordering_key: msg.ordering_key.clone(),
506                attributes: msg.data.attrs.clone(),
507                publish_time: msg.publish_time.into(),
508                delivery_attempt: msg.attempt,
509            };
510            (subscription.handler)(message).await.map_err(failed)
511        };
512        Box::pin(handle.with_context(delivery))
513    }
514}
515
516/// What `#[encore::pubsub::register]` expands to. Not for use by hand: it
517/// changes with the macro.
518#[doc(hidden)]
519pub mod __private {
520    use super::*;
521
522    pub use linkme;
523
524    /// A subscription, whatever its message type.
525    pub trait AnySubscription: Sync {
526        fn start(&'static self) -> Result<(), Error>;
527    }
528
529    impl<T: Send + 'static> AnySubscription for Subscription<T> {
530        fn start(&'static self) -> Result<(), Error> {
531            Subscription::start(self)
532        }
533    }
534
535    /// Every subscription registered to be started with the app, collected at
536    /// link time: a `static` says nothing of itself until it is used.
537    #[linkme::distributed_slice]
538    pub static SUBSCRIPTIONS: [&'static dyn AnySubscription];
539}
540
541/// Starts every subscription registered with
542/// [`#[encore::pubsub::register]`](macro@register). Called when the
543/// app starts; not under `encore test`, where nothing handles what a test
544/// publishes.
545pub(crate) fn start_registered() {
546    if core().postgres().isolates_instances() {
547        return;
548    }
549    for subscription in __private::SUBSCRIPTIONS {
550        if let Err(err) = subscription.start() {
551            eprintln!("encore: {err}");
552        }
553    }
554    core().pubsub().subscriptions_started();
555}