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 encore_sdk_core::reqctx::Values;
use serde::de::DeserializeOwned;
use serde::Serialize;
use crate::error::{ErrCode, Error};
use crate::runtime::core;
use crate::testing;
pub use encore_macros::register;
#[derive(Debug, Clone)]
pub struct Message<T> {
pub id: String,
pub data: T,
pub raw_data: Vec<u8>,
pub attributes: HashMap<String, String>,
pub publish_time: SystemTime,
pub delivery_attempt: u32,
pub ordering_key: Option<String>,
}
pub trait Encoding<T> {
fn encode(value: &T) -> Result<Vec<u8>, Error>;
fn decode(raw: &[u8]) -> Result<T, Error>;
}
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))
}
}
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())
}
}
#[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))
}
}
pub enum Unordered {}
pub enum Ordered {}
pub struct Topic<T, E = Json, O = Unordered> {
name: &'static str,
#[allow(dead_code)]
exactly_once: bool,
_marker: PhantomData<Carries<T, E, O>>,
}
type Carries<T, E, O> = fn() -> (T, E, O);
pub type OrderedTopic<T, E = Json> = Topic<T, E, Ordered>;
#[derive(Debug, Clone, Default)]
pub struct PublishOptions {
attributes: HashMap<String, String>,
}
impl PublishOptions {
pub fn new() -> Self {
Self::default()
}
pub fn attribute(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.attributes.insert(key.into(), value.into());
self
}
pub fn attributes<K, V>(mut self, attributes: impl IntoIterator<Item = (K, V)>) -> Self
where
K: Into<String>,
V: Into<String>,
{
extend(&mut self.attributes, attributes);
self
}
}
fn extend<K: Into<String>, V: Into<String>>(
into: &mut HashMap<String, String>,
attributes: impl IntoIterator<Item = (K, V)>,
) {
into.extend(attributes.into_iter().map(|(k, v)| (k.into(), v.into())));
}
impl<T, E, O> Topic<T, E, O> {
pub const fn new(name: &'static str) -> Self {
Self {
name,
exactly_once: false,
_marker: PhantomData,
}
}
pub const fn named(name: &'static str) -> Self {
Self::new(name)
}
pub const fn exactly_once(mut self) -> Self {
self.exactly_once = true;
self
}
pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
self
}
pub const fn name(&self) -> &'static str {
self.name
}
pub const fn reference<P: TopicPerms>(&'static self) -> TopicRef<P::Id, T, E, O> {
TopicRef {
name: self.name,
perms: PhantomData,
_marker: PhantomData,
}
}
}
impl<T, E: Encoding<T>, O> Topic<T, E, O> {
fn topic(&self) -> Result<core_pubsub::TopicObj, Error> {
core()
.pubsub()
.topic(self.name.into())
.ok_or_else(|| Error::not_found(format!("topic {:?} is not configured", self.name)))
}
fn record(
&self,
test: &testing::Scope,
payload: Vec<u8>,
mut attributes: HashMap<String, String>,
ordering_key: Option<String>,
) -> Result<String, Error> {
core().reqctx_fields().retain_published(&mut attributes);
Ok(test
.core_scope()?
.record_published(self.name, payload, attributes, ordering_key))
}
async fn send(
&self,
data: &T,
mut attributes: HashMap<String, String>,
ordering_key: Option<&str>,
) -> Result<String, Error> {
use encore_sdk_core::telemetry::opentelemetry::trace::FutureExt as _;
use encore_sdk_core::telemetry::opentelemetry::Context;
let payload = E::encode(data)?;
let ordering_key = ordering_key.map(str::to_owned);
let cx = testing::outgoing(&Context::current());
Values::of(&cx).to_attributes(&mut attributes);
if core().system_test().is_none() {
if let Some(test) = testing::active()? {
return self.record(&test, payload, attributes, ordering_key);
}
}
self.topic()?
.publish(payload, attributes, ordering_key)
.with_context(cx)
.await
.map_err(unavailable)
}
async fn send_batch(&self, messages: Vec<Outgoing<'_, T>>) -> Result<Vec<String>, BatchError> {
let count = messages.len();
if count == 0 {
return Ok(Vec::new());
}
if count > MAX_BATCH_SIZE {
return Err(BatchError::refused(
count,
Error::invalid_argument(format!(
"batch has {count} messages, exceeding the maximum of {MAX_BATCH_SIZE}"
)),
));
}
use encore_sdk_core::telemetry::opentelemetry::trace::FutureExt as _;
use encore_sdk_core::telemetry::opentelemetry::Context;
let mut outgoing = Vec::with_capacity(count);
let mut unsendable = Vec::new();
for (i, msg) in messages.into_iter().enumerate() {
let payload = match msg.ordering_key {
Some("") => Err(Error::invalid_argument(format!(
"ordering key for topic {:?} cannot be empty",
self.name
))),
_ => E::encode(msg.data),
};
match payload {
Ok(payload) => outgoing.push(core_pubsub::OutgoingMessage {
payload,
attrs: msg.attributes.clone(),
ordering_key: msg.ordering_key.map(str::to_owned),
}),
Err(err) => unsendable.push((i, err)),
}
}
if let Some(&(first, _)) = unsendable.first() {
return Err(BatchError::unsendable(count, first, unsendable));
}
let cx = testing::outgoing(&Context::current());
let fields = Values::of(&cx);
for msg in &mut outgoing {
fields.to_attributes(&mut msg.attrs);
}
let refused = |err| BatchError::refused(count, err);
if core().system_test().is_none() {
if let Some(test) = testing::active().map_err(refused)? {
return outgoing
.into_iter()
.map(|msg| self.record(&test, msg.payload, msg.attrs, msg.ordering_key))
.collect::<Result<_, _>>()
.map_err(refused);
}
}
let results = self
.topic()
.map_err(refused)?
.publish_batch(outgoing)
.with_context(cx)
.await
.map_err(|err| refused(Error::wrap(ErrCode::InvalidArgument, format!("{err:#}"))))?;
let results = settle(count, results);
BatchError::check(results)
}
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> {
pub async fn publish(&self, data: &T) -> Result<String, Error> {
self.send(data, HashMap::new(), None).await
}
pub async fn publish_with(&self, data: &T, options: PublishOptions) -> Result<String, Error> {
self.send(data, options.attributes, None).await
}
pub async fn publish_batch(
&self,
messages: &[BatchMessage<'_, T>],
) -> Result<Vec<String>, BatchError> {
let messages = messages
.iter()
.map(|msg| Outgoing {
data: msg.data,
attributes: &msg.attributes,
ordering_key: None,
})
.collect();
self.send_batch(messages).await
}
}
impl<T, E: Encoding<T>> Topic<T, E, Ordered> {
pub async fn publish(&self, data: &T, ordering_key: &str) -> Result<String, Error> {
self.publish_with(data, ordering_key, PublishOptions::default())
.await
}
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!(
"ordering key for topic {:?} cannot be empty",
self.name
)));
}
self.send(data, options.attributes, Some(ordering_key))
.await
}
pub async fn publish_batch(
&self,
messages: &[OrderedBatchMessage<'_, T>],
) -> Result<Vec<String>, BatchError> {
let messages = messages
.iter()
.map(|msg| Outgoing {
data: msg.data,
attributes: &msg.attributes,
ordering_key: Some(msg.ordering_key),
})
.collect();
self.send_batch(messages).await
}
}
fn unavailable(err: anyhow::Error) -> Error {
Error::wrap(ErrCode::Unavailable, format!("{err:#}"))
}
fn settle(
count: usize,
answers: Vec<anyhow::Result<core_pubsub::MessageId>>,
) -> Vec<Result<String, Error>> {
let mut answers = answers.into_iter();
(0..count)
.map(|_| match answers.next() {
Some(Ok(id)) => Ok(id),
Some(Err(err)) => Err(unavailable(err)),
None => Err(Error::unavailable(
"missing publish result for message in batch",
)),
})
.collect()
}
pub const MAX_BATCH_SIZE: usize = core_pubsub::MAX_BATCH_SIZE;
#[derive(Debug)]
pub struct BatchMessage<'a, T> {
pub data: &'a T,
pub attributes: HashMap<String, String>,
}
impl<'a, T> BatchMessage<'a, T> {
pub fn new(data: &'a T) -> Self {
Self {
data,
attributes: HashMap::new(),
}
}
pub fn attribute(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.attributes.insert(key.into(), value.into());
self
}
pub fn attributes<K, V>(mut self, attributes: impl IntoIterator<Item = (K, V)>) -> Self
where
K: Into<String>,
V: Into<String>,
{
extend(&mut self.attributes, attributes);
self
}
}
impl<T> Clone for BatchMessage<'_, T> {
fn clone(&self) -> Self {
Self {
data: self.data,
attributes: self.attributes.clone(),
}
}
}
#[derive(Debug)]
pub struct OrderedBatchMessage<'a, T> {
pub data: &'a T,
pub ordering_key: &'a str,
pub attributes: HashMap<String, String>,
}
impl<'a, T> OrderedBatchMessage<'a, T> {
pub fn new(data: &'a T, ordering_key: &'a str) -> Self {
Self {
data,
ordering_key,
attributes: HashMap::new(),
}
}
pub fn attribute(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.attributes.insert(key.into(), value.into());
self
}
pub fn attributes<K, V>(mut self, attributes: impl IntoIterator<Item = (K, V)>) -> Self
where
K: Into<String>,
V: Into<String>,
{
extend(&mut self.attributes, attributes);
self
}
}
impl<T> Clone for OrderedBatchMessage<'_, T> {
fn clone(&self) -> Self {
Self {
data: self.data,
ordering_key: self.ordering_key,
attributes: self.attributes.clone(),
}
}
}
struct Outgoing<'a, T> {
data: &'a T,
attributes: &'a HashMap<String, String>,
ordering_key: Option<&'a str>,
}
#[derive(Debug, Clone)]
pub struct BatchError {
pub results: Vec<Result<String, Error>>,
}
impl BatchError {
pub fn published(&self) -> impl Iterator<Item = &str> {
self.results.iter().filter_map(|r| r.as_deref().ok())
}
pub fn failed(&self) -> impl Iterator<Item = (usize, &Error)> {
self.results
.iter()
.enumerate()
.filter_map(|(i, r)| r.as_ref().err().map(|err| (i, err)))
}
fn refused(count: usize, err: Error) -> Self {
Self {
results: vec![Err(err); count],
}
}
fn unsendable(count: usize, first: usize, unsendable: Vec<(usize, Error)>) -> Self {
let mut results: Vec<Result<String, Error>> = (0..count)
.map(|_| {
Err(Error::invalid_argument(format!(
"not published: batch was rejected because message {first} is invalid"
)))
})
.collect();
for (i, err) in unsendable {
results[i] = Err(err);
}
Self { results }
}
fn check(results: Vec<Result<String, Error>>) -> Result<Vec<String>, BatchError> {
if results.iter().all(Result::is_ok) {
Ok(results.into_iter().map(Result::unwrap).collect())
} else {
Err(Self { results })
}
}
}
impl fmt::Display for BatchError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let failed = self.failed().count();
let total = self.results.len();
write!(f, "{failed} of {total} messages failed to publish")?;
if let Some((i, err)) = self.failed().next() {
write!(f, "; message {i}: {}", err.message)?;
}
Ok(())
}
}
impl std::error::Error for BatchError {}
impl From<BatchError> for Error {
fn from(err: BatchError) -> Self {
let code = err
.failed()
.next()
.map_or(ErrCode::Unknown, |(_, err)| err.code);
Error::new(code, err.to_string())
}
}
pub mod perms {
use super::{sealed::Sealed, TopicPerms};
pub enum Publisher {}
impl Sealed for Publisher {}
impl TopicPerms for Publisher {
type Id = Self;
}
}
mod sealed {
pub trait Sealed {}
}
pub trait TopicPerms: sealed::Sealed {
#[doc(hidden)]
type Id: TopicPerms;
}
pub struct TopicRef<P, T, E = Json, O = Unordered> {
name: &'static str,
perms: PhantomData<fn() -> P>,
_marker: PhantomData<Carries<T, E, O>>,
}
pub type OrderedTopicRef<P, T, E = Json> = TopicRef<P, T, E, Ordered>;
impl<P, T, E, O> Clone for TopicRef<P, T, E, O> {
fn clone(&self) -> Self {
*self
}
}
impl<P, T, E, O> Copy for TopicRef<P, T, E, O> {}
impl<P, T, E, O> TopicRef<P, T, E, O> {
pub const fn name(&self) -> &'static str {
self.name
}
const fn topic(&self) -> Topic<T, E, O> {
Topic::new(self.name)
}
}
impl<T, E: Encoding<T>> TopicRef<perms::Publisher, T, E, Unordered> {
pub async fn publish(&self, data: &T) -> Result<String, Error> {
self.topic().publish(data).await
}
pub async fn publish_with(&self, data: &T, options: PublishOptions) -> Result<String, Error> {
self.topic().publish_with(data, options).await
}
pub async fn publish_batch(
&self,
messages: &[BatchMessage<'_, T>],
) -> Result<Vec<String>, BatchError> {
self.topic().publish_batch(messages).await
}
}
impl<T, E: Encoding<T>> TopicRef<perms::Publisher, T, E, Ordered> {
pub async fn publish(&self, data: &T, ordering_key: &str) -> Result<String, Error> {
self.topic().publish(data, ordering_key).await
}
pub async fn publish_with(
&self,
data: &T,
ordering_key: &str,
options: PublishOptions,
) -> Result<String, Error> {
self.topic().publish_with(data, ordering_key, options).await
}
pub async fn publish_batch(
&self,
messages: &[OrderedBatchMessage<'_, T>],
) -> Result<Vec<String>, BatchError> {
self.topic().publish_batch(messages).await
}
}
pub trait Publisher<T>: Send + Sync {
fn publish(&self, data: &T) -> impl Future<Output = Result<String, Error>> + Send {
self.publish_with(data, PublishOptions::default())
}
fn publish_with(
&self,
data: &T,
options: PublishOptions,
) -> impl Future<Output = Result<String, Error>> + Send;
fn publish_batch(
&self,
messages: &[BatchMessage<'_, T>],
) -> impl Future<Output = Result<Vec<String>, BatchError>> + Send;
fn name(&self) -> &'static str;
}
pub trait OrderedPublisher<T>: Send + Sync {
fn publish(
&self,
data: &T,
ordering_key: &str,
) -> impl Future<Output = Result<String, Error>> + Send {
self.publish_with(data, ordering_key, PublishOptions::default())
}
fn publish_with(
&self,
data: &T,
ordering_key: &str,
options: PublishOptions,
) -> impl Future<Output = Result<String, Error>> + Send;
fn publish_batch(
&self,
messages: &[OrderedBatchMessage<'_, T>],
) -> impl Future<Output = Result<Vec<String>, BatchError>> + Send;
fn name(&self) -> &'static str;
}
impl<T: Sync, E: Encoding<T>> Publisher<T> for TopicRef<perms::Publisher, T, E, Unordered> {
fn publish_with(
&self,
data: &T,
options: PublishOptions,
) -> impl Future<Output = Result<String, Error>> + Send {
self.publish_with(data, options)
}
fn publish_batch(
&self,
messages: &[BatchMessage<'_, T>],
) -> impl Future<Output = Result<Vec<String>, BatchError>> + Send {
self.publish_batch(messages)
}
fn name(&self) -> &'static str {
self.name
}
}
impl<T: Sync, E: Encoding<T>> OrderedPublisher<T> for TopicRef<perms::Publisher, T, E, Ordered> {
fn publish_with(
&self,
data: &T,
ordering_key: &str,
options: PublishOptions,
) -> impl Future<Output = Result<String, Error>> + Send {
self.publish_with(data, ordering_key, options)
}
fn publish_batch(
&self,
messages: &[OrderedBatchMessage<'_, T>],
) -> impl Future<Output = Result<Vec<String>, BatchError>> + Send {
self.publish_batch(messages)
}
fn name(&self) -> &'static str {
self.name
}
}
pub type Handler<T> = fn(Message<T>) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send>>;
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> {
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),
}
}
pub const fn ack_deadline(self, _deadline: Duration) -> Self {
self
}
pub const fn message_retention(self, _retention: Duration) -> Self {
self
}
pub const fn min_backoff(self, _backoff: Duration) -> Self {
self
}
pub const fn max_backoff(self, _backoff: Duration) -> Self {
self
}
pub const fn max_attempts(self, _attempts: u32) -> Self {
self
}
pub const fn max_concurrency(self, _concurrency: u32) -> Self {
self
}
pub const fn filter(self, _filter: &'static str) -> Self {
self
}
pub const fn worker(self, _worker: &'static str) -> Self {
self
}
pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
self
}
pub const fn name(&self) -> &'static str {
self.name
}
}
impl<T: Send + 'static> Subscription<T> {
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(())
}
}
impl<T: Send + 'static> Subscription<T> {
pub(crate) async fn deliver_in(&'static self, test: &testing::Scope) -> Result<usize, Error> {
use encore_sdk_core::telemetry::opentelemetry::trace::FutureExt;
use encore_sdk_core::telemetry::opentelemetry::Context;
use encore_sdk_core::test_scope::MAX_DELIVERIES;
let scope = test.core_scope()?;
let mut handled = 0;
while let Some(delivery) = scope.next_delivery(self.topic, self.name) {
if handled == MAX_DELIVERIES {
return Err(Error::new(
ErrCode::ResourceExhausted,
format!(
"subscription {:?} processed {MAX_DELIVERIES} messages in a single \
deliver() call and more remain: check whether the handler publishes \
back to its own topic {:?} on every invocation",
self.name, self.topic
),
));
}
let published = delivery.message;
let mut attributes = published.attributes;
let fields = Values::take_attributes(&mut attributes);
let context = fields.in_context(&Context::new());
let outcome = async {
let message = Message {
data: (self.decode)(&published.payload)?,
id: published.id,
raw_data: published.payload,
ordering_key: published.ordering_key,
attributes,
publish_time: published.publish_time,
delivery_attempt: delivery.attempt,
};
(self.handler)(message).await
}
.with_context(context)
.await;
scope.settle_delivery(self.topic, self.name, outcome.is_ok());
outcome?;
handled += 1;
}
Ok(handled)
}
}
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;
let mut attributes = msg.data.attrs.clone();
let fields = Values::take_attributes(&mut attributes);
let mut delivery = Context::new().with_remote_span_context(span_ctx);
if !fields.is_empty() {
delivery = fields.in_context(&delivery);
}
let handle = async move {
let failed = |err: Error| {
let code = encore_sdk_core::api::ErrCode::from(err.code);
encore_sdk_core::api::Error {
code,
message: code.default_public_message().into(),
internal_message: Some(err.message),
stack: None,
details: None,
exception: None,
}
};
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,
publish_time: msg.publish_time.into(),
delivery_attempt: msg.attempt,
};
(subscription.handler)(message).await.map_err(failed)
};
Box::pin(handle.with_context(delivery))
}
}
#[doc(hidden)]
pub mod __private {
use super::*;
pub use linkme;
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)
}
}
#[linkme::distributed_slice]
pub static SUBSCRIPTIONS: [&'static dyn AnySubscription];
}
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();
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
use encore_sdk_core::pubsub::SubscriptionHandler as _;
use super::*;
use crate::reqctx::Field;
static USER: Field<String> = Field::new("user").pubsub();
static EVENTS: Topic<String> = Topic::new("events");
type Seen = (Option<String>, HashMap<String, String>);
static SEEN: Mutex<Vec<Seen>> = Mutex::new(Vec::new());
static AUDIT: Subscription<String> = Subscription::new(&EVENTS, "audit", |msg| {
Box::pin(async move {
SEEN.lock().unwrap().push((USER.get(), msg.attributes));
Ok(())
})
});
#[test]
fn publish_options_add_attributes_one_at_a_time_or_all_at_once() {
let tags = HashMap::from([
("source".to_string(), "web".to_string()),
("tier".to_string(), "free".to_string()),
]);
let options = PublishOptions::new()
.attributes(tags)
.attributes([("tier", "pro")])
.attribute("region", "eu");
let want: HashMap<String, String> = [("source", "web"), ("tier", "pro"), ("region", "eu")]
.into_iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
assert_eq!(options.attributes, want);
}
#[test]
fn a_handler_runs_with_the_fields_its_message_carries() {
let message = Arc::new(core_pubsub::Message {
id: "1".into(),
publish_time: SystemTime::now().into(),
attempt: 1,
ordering_key: None,
data: core_pubsub::MessageData {
attrs: HashMap::from([
("encore-ctx-user".into(), "ImFkYSI".into()),
("source".into(), "test".into()),
]),
raw_body: b"\"hi\"".to_vec(),
},
});
let runner = Runner {
subscription: &AUDIT,
};
let rt = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap();
rt.block_on(runner.handle_message(
message,
encore_sdk_core::telemetry::SpanContext::empty_context(),
))
.unwrap();
let seen = SEEN.lock().unwrap();
assert_eq!(
*seen,
[(
Some("ada".to_string()),
HashMap::from([("source".to_string(), "test".to_string())])
)]
);
}
#[test]
fn each_message_is_answered_for_in_its_place() {
let results = settle(
4,
vec![
Ok("a".to_string()),
Err(anyhow::anyhow!("refused")),
Ok("c".to_string()),
],
);
assert_eq!(results[0].as_deref().unwrap(), "a");
assert_eq!(results[1].as_ref().unwrap_err().code, ErrCode::Unavailable);
assert_eq!(results[2].as_deref().unwrap(), "c");
assert!(results[3].is_err());
assert!(BatchError::check(results).is_err());
}
#[test]
fn a_batch_published_whole_is_its_ids() {
let results = settle(2, vec![Ok("a".into()), Ok("b".into())]);
assert_eq!(BatchError::check(results).unwrap(), ["a", "b"]);
}
}