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