use std::collections::{BTreeMap, HashMap};
use std::future::Future;
use std::time::Duration;
use encore::pubsub::{
perms, BatchError, BatchMessage, Encoding, Json, Message, OrderedBatchMessage,
OrderedPublisher, OrderedTopic, OrderedTopicRef, PublishOptions, Publisher, Raw, Subscription,
Topic, TopicRef, MAX_BATCH_SIZE,
};
use encore::Error;
use serde::{Deserialize, Serialize};
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct SignupEvent {
user_id: String,
}
static SIGNUPS: Topic<SignupEvent> = Topic::new("signups");
static PAYMENTS: Topic<SignupEvent> = Topic::new("payments").exactly_once();
static BLOBS: Topic<Vec<u8>, Raw> = Topic::new("blobs");
static CHANGES: OrderedTopic<SignupEvent> = OrderedTopic::new("changes").exactly_once();
static ELSEWHERE: Topic<SignupEvent> = Topic::named("elsewhere");
async fn send_welcome(msg: Message<SignupEvent>) -> Result<(), Error> {
let _ = (msg.id, msg.data.user_id, msg.delivery_attempt);
Ok(())
}
async fn store(msg: Message<Vec<u8>>) -> Result<(), Error> {
let _ = msg.raw_data;
Ok(())
}
#[encore::pubsub::register]
static WELCOME: Subscription<SignupEvent> =
Subscription::new(&SIGNUPS, "send-welcome", send_welcome)
.ack_deadline(Duration::from_secs(60))
.message_retention(Duration::from_secs(24 * 60 * 60))
.min_backoff(Duration::from_millis(500))
.max_backoff(Duration::from_secs(60))
.max_retries(5)
.max_concurrency(4);
#[encore::pubsub::register]
static STORE: Subscription<Vec<u8>> = Subscription::new(&BLOBS, "store", store).retry_forever();
#[encore::pubsub::register]
static ORDERED: Subscription<SignupEvent> =
Subscription::new(&CHANGES, "apply", |msg| Box::pin(send_welcome(msg)));
static BY_HAND: Subscription<SignupEvent> =
Subscription::new(&PAYMENTS, "audit", |msg| Box::pin(send_welcome(msg)));
fn assert_send<F: Future + Send>(_: F) {}
#[test]
fn a_topic_publishes_what_its_type_says() {
let event = SignupEvent {
user_id: "ada".to_string(),
};
assert_send(SIGNUPS.publish(&event));
assert_send(ELSEWHERE.publish_with(&event, PublishOptions::new().attribute("source", "test")));
assert_send(BLOBS.publish(&vec![1, 2, 3]));
assert_send(CHANGES.publish(&event, "ada"));
assert_send(CHANGES.publish_with(&event, "ada", PublishOptions::default()));
assert_eq!(SIGNUPS.name(), "signups");
}
#[test]
fn a_batch_is_published_with_the_messages_its_topic_takes() {
let event = SignupEvent {
user_id: "ada".to_string(),
};
assert_send(SIGNUPS.publish_batch(&[
BatchMessage::new(&event),
BatchMessage::new(&event).attribute("source", "import"),
]));
assert_send(BLOBS.publish_batch(&[BatchMessage {
data: &vec![1, 2, 3],
attributes: Default::default(),
}]));
assert_send(CHANGES.publish_batch(&[
OrderedBatchMessage::new(&event, "ada"),
OrderedBatchMessage::new(&event, "grace").attribute("source", "import"),
]));
}
#[test]
fn a_batch_message_adds_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 want = |pairs: &[(&str, &str)]| -> HashMap<String, String> {
pairs
.iter()
.map(|&(k, v)| (k.to_string(), v.to_string()))
.collect()
};
let merged = want(&[("source", "web"), ("tier", "pro"), ("region", "eu")]);
let event = SignupEvent {
user_id: "ada".to_string(),
};
let msg = BatchMessage::new(&event)
.attributes(&tags)
.attributes(vec![("tier", "pro")])
.attribute("region", "eu");
assert_eq!(msg.attributes, merged);
let msg = OrderedBatchMessage::new(&event, "ada")
.attribute("tier", "pro")
.attributes(BTreeMap::from([("tier", "free")]));
assert_eq!(msg.attributes, want(&[("tier", "free")]));
}
struct Unencodable;
enum Refusing {}
impl Encoding<Unencodable> for Refusing {
fn encode(_: &Unencodable) -> Result<Vec<u8>, Error> {
Err(Error::invalid_argument("cannot encode"))
}
fn decode(_: &[u8]) -> Result<Unencodable, Error> {
Err(Error::invalid_argument("cannot decode"))
}
}
static UNENCODABLE: OrderedTopic<Unencodable, Refusing> = OrderedTopic::new("unencodable");
#[tokio::test]
async fn a_batch_that_cannot_be_sent_is_refused_whole() {
let event = SignupEvent {
user_id: "ada".to_string(),
};
assert_eq!(
SIGNUPS.publish_batch(&[]).await.unwrap(),
Vec::<String>::new()
);
let too_many = vec![BatchMessage::new(&event); MAX_BATCH_SIZE + 1];
let err = SIGNUPS.publish_batch(&too_many).await.unwrap_err();
assert_eq!(err.results.len(), MAX_BATCH_SIZE + 1);
assert_eq!(err.failed().count(), MAX_BATCH_SIZE + 1);
assert!(err.to_string().contains("at most 1000"), "{err}");
let err = CHANGES
.publish_batch(&[
OrderedBatchMessage::new(&event, "ada"),
OrderedBatchMessage::new(&event, ""),
])
.await
.unwrap_err();
assert_eq!(err.published().count(), 0);
let messages: Vec<&str> = err.failed().map(|(_, e)| e.message.as_str()).collect();
assert!(messages[0].contains("message 1"), "{messages:?}");
assert!(messages[1].contains("cannot be empty"), "{messages:?}");
let err = UNENCODABLE
.publish_batch(&[OrderedBatchMessage::new(&Unencodable, "a")])
.await
.unwrap_err();
assert_eq!(
err.results[0].as_ref().unwrap_err().message,
"cannot encode"
);
let err: Error = err.into();
assert_eq!(err.code, encore::ErrCode::InvalidArgument);
assert!(err.message.contains("1 of the 1 messages"), "{err}");
}
#[test]
fn a_batch_error_says_what_was_published() {
let err = BatchError {
results: vec![
Ok("1".to_string()),
Err(Error::unavailable("refused")),
Ok("3".to_string()),
],
};
assert_eq!(err.published().collect::<Vec<_>>(), ["1", "3"]);
assert_eq!(err.failed().map(|(i, _)| i).collect::<Vec<_>>(), [1]);
assert_eq!(
err.to_string(),
"1 of the 3 messages were not published; message 1: refused"
);
let err: Error = err.into();
assert_eq!(err.code, encore::ErrCode::Unavailable);
}
#[tokio::test]
async fn an_ordered_topic_needs_a_key() {
let event = SignupEvent {
user_id: "ada".to_string(),
};
let err = CHANGES.publish(&event, "").await.unwrap_err();
assert_eq!(err.code, encore::ErrCode::InvalidArgument, "{err}");
}
#[test]
fn a_subscription_is_declared_with_or_without_the_attribute() {
assert_eq!(WELCOME.name(), "send-welcome");
assert_eq!(STORE.name(), "store");
assert_eq!(ORDERED.name(), "apply");
assert_eq!(BY_HAND.name(), "audit");
let _start: fn(&'static Subscription<SignupEvent>) -> Result<(), Error> = Subscription::start;
}
#[test]
fn an_encoding_round_trips_a_message() {
let event = SignupEvent {
user_id: "ada".to_string(),
};
let json = <Json as Encoding<SignupEvent>>::encode(&event).unwrap();
assert_eq!(json, br#"{"user_id":"ada"}"#);
assert_eq!(
<Json as Encoding<SignupEvent>>::decode(&json).unwrap(),
event
);
assert!(<Json as Encoding<SignupEvent>>::decode(b"not json").is_err());
let raw = <Raw as Encoding<Vec<u8>>>::encode(&vec![0, 159, 146]).unwrap();
assert_eq!(raw, [0, 159, 146]);
assert_eq!(<Raw as Encoding<Vec<u8>>>::decode(&raw).unwrap(), raw);
}
static NOTIFY: TopicRef<perms::Publisher, SignupEvent> = SIGNUPS.reference::<perms::Publisher>();
static APPLY: OrderedTopicRef<perms::Publisher, SignupEvent> =
CHANGES.reference::<perms::Publisher>();
static STORE_REF: TopicRef<perms::Publisher, Vec<u8>, Raw> = BLOBS.reference::<perms::Publisher>();
async fn signed_up(topic: &impl Publisher<SignupEvent>, event: &SignupEvent) -> Result<(), Error> {
topic.publish(event).await?;
topic.publish_with(event, PublishOptions::default()).await?;
topic.publish_batch(&[BatchMessage::new(event)]).await?;
Ok(())
}
async fn changed(
topic: &impl OrderedPublisher<SignupEvent>,
event: &SignupEvent,
) -> Result<(), Error> {
topic.publish(event, "ada").await?;
topic
.publish_with(event, "ada", PublishOptions::default())
.await?;
topic
.publish_batch(&[OrderedBatchMessage::new(event, "ada")])
.await?;
Ok(())
}
fn assert_copy<C: Copy + Send + Sync + 'static>(_: C) {}
#[test]
fn a_reference_is_a_copy_that_publishes_as_its_topic_does() {
let event = SignupEvent {
user_id: "ada".to_string(),
};
assert_copy(NOTIFY);
assert_copy(APPLY);
let copied = NOTIFY;
assert_eq!(copied.name(), "signups");
assert_eq!(NOTIFY.name(), "signups");
assert_eq!(APPLY.name(), "changes");
assert_send(NOTIFY.publish(&event));
assert_send(NOTIFY.publish_with(&event, PublishOptions::default()));
assert_send(NOTIFY.publish_batch(&[BatchMessage::new(&event)]));
assert_send(STORE_REF.publish(&vec![1, 2, 3]));
assert_send(APPLY.publish(&event, "ada"));
assert_send(APPLY.publish_with(&event, "ada", PublishOptions::default()));
assert_send(APPLY.publish_batch(&[OrderedBatchMessage::new(&event, "ada")]));
assert_send(signed_up(&NOTIFY, &event));
assert_send(signed_up(
&ELSEWHERE.reference::<perms::Publisher>(),
&event,
));
assert_send(changed(&APPLY, &event));
assert_eq!(Publisher::name(&NOTIFY), "signups");
assert_eq!(OrderedPublisher::name(&APPLY), "changes");
}
#[tokio::test]
async fn the_traits_publish_through_the_references_own_methods() {
let event = SignupEvent {
user_id: "ada".to_string(),
};
let err = OrderedPublisher::publish(&APPLY, &event, "")
.await
.unwrap_err();
assert_eq!(err.code, encore::ErrCode::InvalidArgument, "{err}");
assert!(Publisher::publish_batch(&NOTIFY, &[])
.await
.unwrap()
.is_empty());
}