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;
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 {
pub attributes: HashMap<String, String>,
}
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 name(&self) -> &'static str {
self.name
}
}
impl<T, E: Encoding<T>, O> Topic<T, E, O> {
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),
}
}
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
}
}
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!(
"the ordering key for topic {} cannot be empty",
self.name
)));
}
self.send(data, options.attributes, Some(ordering_key))
.await
}
}
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_retries(self, _retries: i32) -> Self {
self
}
pub const fn max_concurrency(self, _concurrency: u32) -> 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(())
}
}
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 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))
}
}
#[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();
}