encore-dev 2.0.0-beta.4

Rust SDK for Encore applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//! Pub/Sub topics and subscriptions. Topics are typed by the message they
//! carry and declared at module scope; a subscription names its topic and the
//! function that handles its messages.
//!
//! ```no_run
//! use encore::pubsub::{Message, Subscription, Topic};
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Serialize, Deserialize)]
//! struct SignupEvent {
//!     user_id: String,
//! }
//!
//! static SIGNUPS: Topic<SignupEvent> = Topic::new("signups");
//!
//! #[encore::pubsub::register]
//! static WELCOME: Subscription<SignupEvent> =
//!     Subscription::new(&SIGNUPS, "send-welcome", send_welcome);
//!
//! async fn send_welcome(msg: Message<SignupEvent>) -> Result<(), encore::Error> {
//!     println!("welcome, {}", msg.data.user_id);
//!     Ok(())
//! }
//!
//! async fn signed_up(user_id: String) -> Result<(), encore::Error> {
//!     SIGNUPS.publish(&SignupEvent { user_id }).await?;
//!     Ok(())
//! }
//! ```
//!
//! # Encodings
//!
//! A topic's second type argument says how its messages are encoded: [`Json`]
//! unless said otherwise, [`Raw`] for bytes passed through as they are, and —
//! with the `protobuf` feature — `Protobuf`. It is part of the topic's type, so
//! a publisher and a subscriber cannot disagree about it, and Encore can read
//! it from the declaration.
//!
//! # Ordered topics
//!
//! An [`OrderedTopic`] delivers the messages that share an ordering key in the
//! order they were published. Its `publish` takes the key.
//!
//! # Running subscriptions
//!
//! A `static` does nothing until it is used, so something has to start a
//! subscription. [`#[encore::pubsub::register]`](macro@register)
//! registers one to be started with the app, by [`crate::initialize`] or
//! [`crate::run_blocking`]. One declared without it is started by hand, with
//! [`Subscription::start`].
//!
//! # Tests
//!
//! Under `encore test` each test publishes to topics of its own, and nothing
//! handles what it publishes: no subscription is started. The test reads back
//! what it — and the code it called — published with
//! [`testing::published`](crate::testing::published), and calls a handler
//! itself when it wants one run.

use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, SystemTime};

use encore_sdk_core::pubsub as core_pubsub;
use serde::de::DeserializeOwned;
use serde::Serialize;

use crate::error::{ErrCode, Error};
use crate::runtime::core;
use crate::testing;

/// Registers a subscription to be started with the app.
///
/// Put it on the `static`. It also lets the handler be given as the plain
/// name of an `async fn`, in place of the boxing closure [`Subscription::new`]
/// takes.
///
/// ```no_run
/// # use encore::pubsub::{Message, Subscription, Topic};
/// # static SIGNUPS: Topic<String> = Topic::new("signups");
/// #[encore::pubsub::register]
/// static WELCOME: Subscription<String> =
///     Subscription::new(&SIGNUPS, "send-welcome", send_welcome).max_concurrency(4);
///
/// async fn send_welcome(msg: Message<String>) -> Result<(), encore::Error> {
///     Ok(())
/// }
/// ```
pub use encore_macros::register;

/// A message, as a subscription's handler receives it.
#[derive(Debug, Clone)]
pub struct Message<T> {
    /// The message's id, unique within its topic.
    pub id: String,
    /// The message, decoded.
    pub data: T,
    /// The message as it was sent, before decoding.
    pub raw_data: Vec<u8>,
    /// The attributes it was published with.
    pub attributes: HashMap<String, String>,
    pub publish_time: SystemTime,
    /// Which attempt at delivering the message this is, from 1.
    pub delivery_attempt: u32,
    /// The key it was published with, on an [`OrderedTopic`].
    pub ordering_key: Option<String>,
}

/// How a topic's messages are encoded. Implemented by the encodings, for the
/// message types each can carry.
pub trait Encoding<T> {
    fn encode(value: &T) -> Result<Vec<u8>, Error>;
    fn decode(raw: &[u8]) -> Result<T, Error>;
}

/// JSON, for a message type that is `Serialize` and `Deserialize`. The default.
pub enum Json {}

impl<T: Serialize + DeserializeOwned> Encoding<T> for Json {
    fn encode(value: &T) -> Result<Vec<u8>, Error> {
        serde_json::to_vec(value).map_err(|e| Error::wrap(ErrCode::InvalidArgument, e))
    }

    fn decode(raw: &[u8]) -> Result<T, Error> {
        serde_json::from_slice(raw).map_err(|e| Error::wrap(ErrCode::InvalidArgument, e))
    }
}

/// No encoding: the message is the bytes, as a `Vec<u8>`.
pub enum Raw {}

impl Encoding<Vec<u8>> for Raw {
    fn encode(value: &Vec<u8>) -> Result<Vec<u8>, Error> {
        Ok(value.clone())
    }

    fn decode(raw: &[u8]) -> Result<Vec<u8>, Error> {
        Ok(raw.to_vec())
    }
}

/// Protocol Buffers, for a `prost` message type.
#[cfg(feature = "protobuf")]
pub enum Protobuf {}

#[cfg(feature = "protobuf")]
impl<T: prost::Message + Default> Encoding<T> for Protobuf {
    fn encode(value: &T) -> Result<Vec<u8>, Error> {
        Ok(value.encode_to_vec())
    }

    fn decode(raw: &[u8]) -> Result<T, Error> {
        T::decode(raw).map_err(|e| Error::wrap(ErrCode::InvalidArgument, e))
    }
}

/// Marks a [`Topic`] whose messages are delivered in no particular order.
pub enum Unordered {}

/// Marks a [`Topic`] that orders messages by key: an [`OrderedTopic`].
pub enum Ordered {}

/// A pub/sub topic carrying messages of type `T`, encoded as `E`.
pub struct Topic<T, E = Json, O = Unordered> {
    name: &'static str,
    /// Read by Encore's parser from the declaration, not by the runtime.
    #[allow(dead_code)]
    exactly_once: bool,
    _marker: PhantomData<Carries<T, E, O>>,
}

/// What a topic's type parameters stand for, none of which it holds.
type Carries<T, E, O> = fn() -> (T, E, O);

/// A [`Topic`] that delivers the messages sharing an ordering key in the order
/// they were published.
pub type OrderedTopic<T, E = Json> = Topic<T, E, Ordered>;

/// Options for publishing a message.
#[derive(Debug, Clone, Default)]
pub struct PublishOptions {
    /// Attributes delivered alongside the message.
    pub attributes: HashMap<String, String>,
}

impl<T, E, O> Topic<T, E, O> {
    /// Declare a topic. `const` so it can initialize a module-scope `static`,
    /// whose type gives the message type and the encoding.
    ///
    /// Options follow the name, each a method of its own:
    ///
    /// ```no_run
    /// use encore::pubsub::{OrderedTopic, Raw, Topic};
    ///
    /// static EVENTS: Topic<String> = Topic::new("events");
    /// static PAYMENTS: Topic<String> = Topic::new("payments").exactly_once();
    /// static BLOBS: Topic<Vec<u8>, Raw> = Topic::new("blobs");
    /// static CHANGES: OrderedTopic<String> = OrderedTopic::new("changes");
    /// ```
    pub const fn new(name: &'static str) -> Self {
        Self {
            name,
            exactly_once: false,
            _marker: PhantomData,
        }
    }

    /// Reference an existing topic by name: one another service declares,
    /// possibly in another language. To declare a new topic, use
    /// [`Topic::new`] instead.
    ///
    /// The name must be a string literal, so Encore can resolve it statically.
    /// A named topic takes no options: it is configured where it is declared.
    /// Its message type and encoding are the author's claim: across languages
    /// they cannot be checked.
    ///
    /// ```no_run
    /// static SIGNUPS: encore::pubsub::Topic<String> = encore::pubsub::Topic::named("signups");
    /// ```
    pub const fn named(name: &'static str) -> Self {
        Self::new(name)
    }

    /// Has each message delivered exactly once, rather than at least once.
    ///
    /// Part of the declaration: it takes the topic by value, so it cannot be
    /// called on the `static`.
    pub const fn exactly_once(mut self) -> Self {
        self.exactly_once = true;
        self
    }

    /// The name the topic was declared with.
    pub const fn name(&self) -> &'static str {
        self.name
    }
}

impl<T, E: Encoding<T>, O> Topic<T, E, O> {
    /// Encodes and publishes a message: to the app's topic, or under `encore
    /// test` to the current test's instance of it, where it is also noted for
    /// the test to read back.
    async fn send(
        &self,
        data: &T,
        attributes: HashMap<String, String>,
        ordering_key: Option<&str>,
    ) -> Result<String, Error> {
        let payload = E::encode(data)?;
        let ordering_key = ordering_key.map(str::to_owned);
        let unavailable = |e: anyhow::Error| Error::wrap(ErrCode::Unavailable, format!("{e:#}"));
        match testing::active()? {
            Some(test) => {
                let id = test
                    .topic(self.name)?
                    .publish(payload.clone(), attributes.clone(), ordering_key.clone())
                    .await
                    .map_err(unavailable)?;
                test.note_published(
                    self.name,
                    testing::Published {
                        id: id.clone(),
                        payload,
                        attributes,
                        ordering_key,
                        publish_time: SystemTime::now(),
                    },
                );
                Ok(id)
            }
            None => core()
                .pubsub()
                .topic(self.name.into())
                .ok_or_else(|| {
                    Error::not_found(format!("topic {:?} is not configured", self.name))
                })?
                .publish(payload, attributes, ordering_key)
                .await
                .map_err(unavailable),
        }
    }

    /// What the current test has published to the topic, decoded.
    pub(crate) fn published_in(&self, test: &testing::Scope) -> Result<Vec<Message<T>>, Error> {
        test.published(self.name)
            .into_iter()
            .map(|published| {
                Ok(Message {
                    data: E::decode(&published.payload)?,
                    id: published.id,
                    raw_data: published.payload,
                    ordering_key: published.ordering_key,
                    attributes: published.attributes,
                    publish_time: published.publish_time,
                    delivery_attempt: 1,
                })
            })
            .collect()
    }
}

impl<T, E: Encoding<T>> Topic<T, E, Unordered> {
    /// Publish a message, returning its id.
    pub async fn publish(&self, data: &T) -> Result<String, Error> {
        self.send(data, HashMap::new(), None).await
    }

    /// Publish a message with explicit options: attributes delivered alongside
    /// it.
    pub async fn publish_with(&self, data: &T, options: PublishOptions) -> Result<String, Error> {
        self.send(data, options.attributes, None).await
    }
}

impl<T, E: Encoding<T>> Topic<T, E, Ordered> {
    /// Publish a message, returning its id. Messages published with the same
    /// `ordering_key` are delivered in the order they were published.
    pub async fn publish(&self, data: &T, ordering_key: &str) -> Result<String, Error> {
        self.publish_with(data, ordering_key, PublishOptions::default())
            .await
    }

    /// Publish a message with explicit options: attributes delivered alongside
    /// it.
    pub async fn publish_with(
        &self,
        data: &T,
        ordering_key: &str,
        options: PublishOptions,
    ) -> Result<String, Error> {
        if ordering_key.is_empty() {
            return Err(Error::invalid_argument(format!(
                "the ordering key for topic {} cannot be empty",
                self.name
            )));
        }
        self.send(data, options.attributes, Some(ordering_key))
            .await
    }
}

/// A subscription's handler: a function returning the future that handles a
/// message. An error has the message delivered again, as the retry policy says.
pub type Handler<T> = fn(Message<T>) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send>>;

/// A subscription to a topic: every message published to the topic is handed
/// to its handler.
pub struct Subscription<T> {
    name: &'static str,
    topic: &'static str,
    decode: fn(&[u8]) -> Result<T, Error>,
    handler: Handler<T>,
    started: AtomicBool,
}

impl<T> Subscription<T> {
    /// Declare a subscription to `topic`. `const` so it can initialize a
    /// module-scope `static`.
    ///
    /// The handler is a function, boxing the future that handles a message:
    /// `|msg| Box::pin(send_welcome(msg))`. Under
    /// [`#[encore::pubsub::register]`](macro@register), which also has
    /// the subscription started with the app, it can be just `send_welcome`.
    ///
    /// Options follow, each a method of its own:
    ///
    /// ```no_run
    /// # use std::time::Duration;
    /// # use encore::pubsub::{Message, Subscription, Topic};
    /// # static SIGNUPS: Topic<String> = Topic::new("signups");
    /// # async fn send_welcome(_: Message<String>) -> Result<(), encore::Error> { Ok(()) }
    /// static WELCOME: Subscription<String> =
    ///     Subscription::new(&SIGNUPS, "send-welcome", |msg| Box::pin(send_welcome(msg)))
    ///         .ack_deadline(Duration::from_secs(60))
    ///         .max_retries(5);
    /// ```
    pub const fn new<E: Encoding<T>, O>(
        topic: &'static Topic<T, E, O>,
        name: &'static str,
        handler: Handler<T>,
    ) -> Self {
        Self {
            name,
            topic: topic.name,
            decode: E::decode,
            handler,
            started: AtomicBool::new(false),
        }
    }

    /// How long the handler has to finish before the message is delivered
    /// again. 30 seconds if not given.
    ///
    /// The options are part of the declaration, read by Encore's parser: each
    /// takes the subscription by value, so it cannot be called on the `static`.
    pub const fn ack_deadline(self, _deadline: Duration) -> Self {
        self
    }

    /// How long an undelivered message is kept. Seven days if not given.
    pub const fn message_retention(self, _retention: Duration) -> Self {
        self
    }

    /// The shortest wait before a failed message is delivered again. 10
    /// seconds if not given.
    pub const fn min_backoff(self, _backoff: Duration) -> Self {
        self
    }

    /// The longest wait before a failed message is delivered again. 10 minutes
    /// if not given.
    pub const fn max_backoff(self, _backoff: Duration) -> Self {
        self
    }

    /// How many times a failed message is delivered again before it is given
    /// up on. 100 if not given; -1 to never give up, -2 to never retry.
    pub const fn max_retries(self, _retries: i32) -> Self {
        self
    }

    /// How many messages are handled at once. Unlimited if not given.
    pub const fn max_concurrency(self, _concurrency: u32) -> Self {
        self
    }

    /// The name the subscription was declared with.
    pub const fn name(&self) -> &'static str {
        self.name
    }
}

impl<T: Send + 'static> Subscription<T> {
    /// Starts handling the topic's messages, if it has not been started.
    ///
    /// A subscription under [`#[encore::pubsub::register]`](macro@register)
    /// is started with the app; this is for one that is not.
    pub fn start(&'static self) -> Result<(), Error> {
        if self.started.swap(true, Ordering::SeqCst) {
            return Ok(());
        }
        let subscription = core()
            .pubsub()
            .subscription(core_pubsub::SubName {
                topic: self.topic.into(),
                subscription: self.name.into(),
            })
            .ok_or_else(|| {
                Error::not_found(format!(
                    "subscription {:?} on topic {:?} is not configured",
                    self.name, self.topic
                ))
            })?;
        let (topic, name) = (self.topic, self.name);
        core().tokio_handle().spawn(async move {
            let handler = Arc::new(Runner { subscription: self });
            if let Err(err) = subscription.subscribe(handler).await {
                eprintln!("encore: subscription {name:?} on topic {topic:?} stopped: {err}");
            }
        });
        Ok(())
    }
}

/// Hands the runtime's messages to a subscription's handler.
struct Runner<T: 'static> {
    subscription: &'static Subscription<T>,
}

impl<T> fmt::Debug for Runner<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Subscription")
            .field("topic", &self.subscription.topic)
            .field("name", &self.subscription.name)
            .finish()
    }
}

impl<T: Send + 'static> core_pubsub::SubscriptionHandler for Runner<T> {
    fn handle_message(
        &self,
        msg: Arc<core_pubsub::Message>,
        span_ctx: encore_sdk_core::telemetry::SpanContext,
    ) -> Pin<Box<dyn Future<Output = Result<(), encore_sdk_core::api::Error>> + Send + 'static>>
    {
        use encore_sdk_core::telemetry::opentelemetry::trace::{FutureExt, TraceContextExt};
        use encore_sdk_core::telemetry::opentelemetry::Context;

        let subscription = self.subscription;
        // What the handler does is traced under the delivery's span.
        let delivery = Context::new().with_remote_span_context(span_ctx);
        let handle = async move {
            let failed =
                |err: Error| encore_sdk_core::api::Error::internal(anyhow::anyhow!("{err}"));
            let message = Message {
                id: msg.id.clone(),
                data: (subscription.decode)(&msg.data.raw_body).map_err(failed)?,
                raw_data: msg.data.raw_body.clone(),
                ordering_key: msg.ordering_key.clone(),
                attributes: msg.data.attrs.clone(),
                publish_time: msg.publish_time.into(),
                delivery_attempt: msg.attempt,
            };
            (subscription.handler)(message).await.map_err(failed)
        };
        Box::pin(handle.with_context(delivery))
    }
}

/// What `#[encore::pubsub::register]` expands to. Not for use by hand: it
/// changes with the macro.
#[doc(hidden)]
pub mod __private {
    use super::*;

    pub use linkme;

    /// A subscription, whatever its message type.
    pub trait AnySubscription: Sync {
        fn start(&'static self) -> Result<(), Error>;
    }

    impl<T: Send + 'static> AnySubscription for Subscription<T> {
        fn start(&'static self) -> Result<(), Error> {
            Subscription::start(self)
        }
    }

    /// Every subscription registered to be started with the app, collected at
    /// link time: a `static` says nothing of itself until it is used.
    #[linkme::distributed_slice]
    pub static SUBSCRIPTIONS: [&'static dyn AnySubscription];
}

/// Starts every subscription registered with
/// [`#[encore::pubsub::register]`](macro@register). Called when the
/// app starts; not under `encore test`, where nothing handles what a test
/// publishes.
pub(crate) fn start_registered() {
    if core().postgres().isolates_instances() {
        return;
    }
    for subscription in __private::SUBSCRIPTIONS {
        if let Err(err) = subscription.start() {
            eprintln!("encore: {err}");
        }
    }
    core().pubsub().subscriptions_started();
}