use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, OnceLock};
use std::time::Duration;
use crate::{Config, Error, Event, Events, Incoming, OwnedMessage, Status, TokenProvider};
use tokio::runtime::Runtime;
use tokio::sync::Mutex;
use tokio_util::sync::CancellationToken;
const WORKER_THREADS: usize = 2;
static RUNTIME: OnceLock<Runtime> = OnceLock::new();
static ON_THREAD_START: OnceLock<fn()> = OnceLock::new();
pub fn set_on_thread_start(hook: fn()) {
let _ = ON_THREAD_START.set(hook);
}
pub fn runtime() -> &'static Runtime {
RUNTIME.get_or_init(|| {
let mut builder = tokio::runtime::Builder::new_multi_thread();
builder
.worker_threads(WORKER_THREADS)
.thread_name("wse")
.enable_all();
if let Some(hook) = ON_THREAD_START.get() {
builder.on_thread_start(*hook);
}
builder.build().expect("the WSE runtime starts")
})
}
async fn on_runtime<T: Send + 'static>(
work: impl Future<Output = Result<T, NativeError>> + Send + 'static,
) -> Result<T, NativeError> {
struct AbortOnDrop<T>(tokio::task::JoinHandle<T>);
impl<T> Drop for AbortOnDrop<T> {
fn drop(&mut self) {
self.0.abort();
}
}
let mut task = AbortOnDrop(runtime().spawn(work));
match (&mut task.0).await {
Ok(result) => result,
Err(error) if error.is_panic() => {
Err(NativeError::new(ErrorKind::Internal, "the call panicked"))
}
Err(_) => Err(NativeError::new(
ErrorKind::Cancelled,
"the call was cancelled",
)),
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ErrorKind {
Config,
Connect,
Auth,
Timeout,
Encryption,
Signing,
GaveUp,
NotConnected,
Full,
Closed,
Encode,
Decode,
Cancelled,
Busy,
Internal,
Unknown,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NativeError {
pub kind: ErrorKind,
pub message: String,
}
impl NativeError {
pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
Self {
kind,
message: message.into(),
}
}
}
impl std::fmt::Display for NativeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for NativeError {}
impl From<Error> for NativeError {
fn from(error: Error) -> Self {
let kind = match &error {
Error::Config(_) => ErrorKind::Config,
Error::Connect(_) => ErrorKind::Connect,
Error::Auth(_) => ErrorKind::Auth,
Error::Timeout(_) => ErrorKind::Timeout,
Error::Encryption(_) => ErrorKind::Encryption,
Error::Signing(_) => ErrorKind::Signing,
Error::GaveUp(_) => ErrorKind::GaveUp,
Error::NotConnected => ErrorKind::NotConnected,
Error::Full => ErrorKind::Full,
Error::Closed => ErrorKind::Closed,
Error::Panicked => ErrorKind::Internal,
Error::Encode(_) => ErrorKind::Encode,
Error::Decode(_) => ErrorKind::Decode,
};
Self::new(kind, error.to_string())
}
}
#[derive(Clone, Debug, Default)]
pub struct NativeConfig {
pub url: String,
pub token: Option<String>,
pub topics: Vec<String>,
pub msgpack: bool,
pub headers: Vec<(String, String)>,
pub send_queue: u32,
pub reconnect: Option<bool>,
pub reconnect_base_delay_ms: u64,
pub reconnect_max_delay_ms: u64,
pub reconnect_factor: f64,
pub reconnect_jitter: Option<bool>,
pub reconnect_max_attempts: u32,
pub connect_timeout_ms: u64,
pub ready_timeout_ms: u64,
pub idle_timeout_ms: u64,
pub recovery_timeout_ms: u64,
pub server_identity_keys: Vec<String>,
pub signing_key: Option<Vec<u8>>,
pub server_signing_keys: Vec<String>,
pub trust: NativeTrust,
pub insecure: bool,
pub delivery: Option<NativeDelivery>,
pub offline: Option<NativeOffline>,
}
#[derive(Clone, Debug, Default)]
pub struct NativeOffline {
pub disabled: bool,
pub path: Option<String>,
pub max_messages: u32,
pub max_bytes: u64,
pub max_age_ms: u64,
}
#[derive(Clone, Debug, Default)]
pub struct NativeSendOptions {
pub id: Option<String>,
pub ttl_ms: u64,
pub requires: Vec<String>,
pub correlation_id: Option<String>,
pub priority: u8,
pub live: bool,
}
impl From<NativeSendOptions> for crate::SendOptions {
fn from(native: NativeSendOptions) -> Self {
Self {
id: native.id,
ttl: (native.ttl_ms > 0).then(|| Duration::from_millis(native.ttl_ms)),
requires: native.requires,
correlation_id: native.correlation_id,
priority: (native.priority > 0).then_some(native.priority),
live: native.live,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct NativeDelivery {
pub consumer: String,
pub schema: Option<String>,
pub realm: Option<String>,
pub checkpoint: Option<String>,
pub max_held: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NativeSubscription {
Requested,
Active,
Denied,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NativeContinuity {
Continuous,
ResyncRequired,
Resyncing,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NativeTopicState {
pub topic: String,
pub subscription: NativeSubscription,
pub continuity: NativeContinuity,
pub reason: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StreamPosition {
pub topic: String,
pub epoch: u32,
pub offset: u64,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum NativeTrust {
#[default]
Platform,
Mozilla,
Roots(Vec<Vec<u8>>),
}
pub trait TokenSource: Send + Sync + 'static {
fn token(&self) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send>>;
}
fn config_of(
native: NativeConfig,
tokens: Option<Arc<dyn TokenSource>>,
) -> Result<Config, NativeError> {
if native.url.starts_with("ws://") && !native.insecure {
return Err(NativeError::new(
ErrorKind::Config,
"ws:// sends everything in the clear: use wss://, or set insecure (for development)",
));
}
let tls = native
.url
.starts_with("wss://")
.then(|| tls_of(native.trust))
.transpose()?;
let mut config = Config::new(native.url);
config.tls = tls;
config.delivery = native.delivery.map(|native| {
let mut delivery = crate::Delivery::new(native.consumer);
delivery.schema = native.schema;
delivery.realm = native.realm;
delivery.checkpoint = native.checkpoint;
delivery.max_held = native.max_held as usize;
delivery
});
config.offline = match native.offline {
None => Some(crate::Offline::in_memory()),
Some(native) if native.disabled => None,
Some(native) => {
let mut offline = match native.path {
Some(path) => crate::Offline::in_file(path),
None => crate::Offline::in_memory(),
};
if native.max_messages > 0 {
offline.max_messages = native.max_messages as usize;
}
if native.max_bytes > 0 {
offline.max_bytes = usize::try_from(native.max_bytes).unwrap_or(usize::MAX);
}
if native.max_age_ms > 0 {
offline.max_age = Duration::from_millis(native.max_age_ms);
}
Some(offline)
}
};
config.token = native.token;
if let Some(source) = tokens {
config.token_provider = Some(TokenProvider::new(move || source.token()));
}
config.topics = native.topics;
if native.msgpack {
config.format = crate::Format::Msgpack;
}
config.headers = native.headers;
if native.send_queue > 0 {
config.send_queue = native.send_queue as usize;
}
let ms = |value: u64, default: Duration| {
if value == 0 {
default
} else {
Duration::from_millis(value)
}
};
if let Some(reconnect) = native.reconnect {
config.reconnect.enabled = reconnect;
}
config.reconnect.base_delay = ms(native.reconnect_base_delay_ms, config.reconnect.base_delay);
config.reconnect.max_delay = ms(native.reconnect_max_delay_ms, config.reconnect.max_delay);
if native.reconnect_factor.is_finite() && native.reconnect_factor > 0.0 {
config.reconnect.factor = native.reconnect_factor;
}
if let Some(jitter) = native.reconnect_jitter {
config.reconnect.jitter = jitter;
}
if native.reconnect_max_attempts > 0 {
config.reconnect.max_attempts = Some(native.reconnect_max_attempts);
}
config.connect_timeout = ms(native.connect_timeout_ms, config.connect_timeout);
config.ready_timeout = ms(native.ready_timeout_ms, config.ready_timeout);
config.idle_timeout = ms(native.idle_timeout_ms, config.idle_timeout);
if native.recovery_timeout_ms > 0 {
config.recovery_timeout = Duration::from_millis(native.recovery_timeout_ms);
}
if !native.server_identity_keys.is_empty() {
config.encryption = Some(crate::Encryption::pinned(native.server_identity_keys));
}
config.signing_key = native.signing_key;
config.server_signing_keys = native.server_signing_keys;
Ok(config)
}
fn tls_of(trust: NativeTrust) -> Result<Arc<dyn std::any::Any + Send + Sync>, NativeError> {
let config = match trust {
NativeTrust::Platform => {
#[cfg(target_os = "android")]
if !ANDROID_VERIFIER.load(std::sync::atomic::Ordering::Acquire) {
return Err(NativeError::new(
ErrorKind::Config,
"Android's certificate verifier is not set up: the Kotlin library and the \
Flutter package set it up as the app starts (WseTls.init(context) by hand)",
));
}
static PLATFORM: OnceLock<Arc<rustls::ClientConfig>> = OnceLock::new();
match PLATFORM.get() {
Some(config) => config.clone(),
None => {
let builder = crate::connection::tls_builder();
let verifier =
rustls_platform_verifier::Verifier::new(builder.crypto_provider().clone())
.map_err(|e| {
NativeError::new(
ErrorKind::Config,
format!("the system's certificate verifier: {e}"),
)
})?;
let config = builder
.dangerous()
.with_custom_certificate_verifier(Arc::new(verifier))
.with_no_client_auth();
PLATFORM.get_or_init(|| Arc::new(config)).clone()
}
}
}
NativeTrust::Mozilla => crate::connection::default_tls(),
NativeTrust::Roots(certificates) => {
use rustls::pki_types::CertificateDer;
use rustls::pki_types::pem::PemObject;
let bad = |e: &dyn std::fmt::Display| {
NativeError::new(ErrorKind::Config, format!("a trusted root: {e}"))
};
let mut roots = rustls::RootCertStore::empty();
for certificate in certificates {
if memchr::memmem::find(&certificate, b"-----BEGIN").is_some() {
for der in CertificateDer::pem_slice_iter(&certificate) {
roots.add(der.map_err(|e| bad(&e))?).map_err(|e| bad(&e))?;
}
} else {
roots
.add(CertificateDer::from(certificate))
.map_err(|e| bad(&e))?;
}
}
if roots.is_empty() {
return Err(bad(&"no certificate given"));
}
Arc::new(
crate::connection::tls_builder()
.with_root_certificates(roots)
.with_no_client_auth(),
)
}
};
Ok(config)
}
#[cfg(target_os = "android")]
static ANDROID_VERIFIER: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
#[cfg(target_os = "android")]
pub unsafe fn init_android(
env: *mut std::ffi::c_void,
context: *mut std::ffi::c_void,
) -> Result<(), NativeError> {
let mut unowned = unsafe { jni::EnvUnowned::from_raw(env.cast()) };
let outcome = unowned
.with_env(|env| -> Result<(), jni::errors::Error> {
let context = unsafe { jni::objects::JObject::from_raw(env, context.cast()) };
rustls_platform_verifier::android::init_with_env(env, context)
})
.into_outcome();
match outcome {
jni::Outcome::Ok(()) => {
ANDROID_VERIFIER.store(true, std::sync::atomic::Ordering::Release);
Ok(())
}
jni::Outcome::Err(e) => Err(NativeError::new(
ErrorKind::Config,
format!("Android's certificate verifier: {e}"),
)),
jni::Outcome::Panic(_) => Err(NativeError::new(
ErrorKind::Internal,
"Android's certificate verifier panicked as it was set up",
)),
}
}
pub fn generate_signing_key() -> Vec<u8> {
crate::generate_key()
}
pub fn signing_public_key(pkcs8: &[u8]) -> Result<String, NativeError> {
Ok(crate::public_key(pkcs8)?)
}
#[derive(Clone, Debug, Default)]
pub struct CancelToken(CancellationToken);
impl CancelToken {
pub fn new() -> Self {
Self::default()
}
pub fn cancel(&self) {
self.0.cancel();
}
pub fn is_cancelled(&self) -> bool {
self.0.is_cancelled()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NativeSignature {
pub body: String,
pub sig: String,
pub kid: String,
pub verified: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NativeMessage {
pub kind: String,
pub topic: Option<String>,
pub epoch: Option<u32>,
pub offset: Option<u64>,
pub id: Option<String>,
pub correlation_id: Option<String>,
pub priority: Option<u8>,
pub timestamp: Option<String>,
pub json: Option<String>,
pub payload_error: Option<String>,
pub signature: Option<NativeSignature>,
pub generation: u32,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TopicRecovery {
pub topic: String,
pub recovered: bool,
pub count: u64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Item {
Message(NativeMessage),
Binary(Vec<u8>),
Connected {
connection_id: String,
user_id: Option<String>,
reconnected: bool,
recovery: bool,
},
Disconnected {
code: Option<u16>,
reason: String,
retry_in_ms: u64,
attempt: u32,
},
Paused {
reasons: Vec<String>,
},
Subscribed {
topics: Vec<String>,
failed: Vec<String>,
recovery: Vec<TopicRecovery>,
},
Gap {
topic: String,
epoch: u32,
first: Option<u64>,
last: Option<u64>,
reason: String,
},
ServerError {
code: String,
message: String,
details_json: String,
},
Closed {
error: Option<NativeError>,
},
Resync {
round: u64,
topics: Vec<String>,
reasons: Vec<String>,
committed: Vec<StreamPosition>,
},
Continuity {
topic: String,
continuity: NativeContinuity,
reason: Option<String>,
},
CheckpointRejected {
reason: String,
},
Delivered {
ids: Vec<String>,
},
NotDelivered {
reason: String,
ids: Vec<String>,
},
StorageFailed {
operation: String,
message: String,
},
Unknown {
name: String,
},
}
impl Item {
fn size(&self) -> usize {
64 + match self {
Item::Message(m) => {
m.kind.len()
+ m.topic.as_ref().map_or(0, String::len)
+ m.json.as_ref().map_or(0, String::len)
+ m.signature
.as_ref()
.map_or(0, |s| s.body.len() + s.sig.len())
}
Item::Binary(bytes) => bytes.len(),
Item::ServerError { details_json, .. } => details_json.len(),
_ => 0,
}
}
}
fn message_of(message: &OwnedMessage) -> NativeMessage {
let position = message.position();
let (json, payload_error) = match message.payload_json() {
Some(text) => (Some(text.to_owned()), None),
None if !message.has_payload() => (None, None),
None => match message.payload_value() {
Ok(serde_json::Value::Null) => (None, None),
Ok(value) => (Some(value.to_string()), None),
Err(error) => (None, Some(error.to_string())),
},
};
NativeMessage {
kind: message.kind().to_owned(),
topic: message.topic().map(str::to_owned),
epoch: position.map(|p| p.epoch),
offset: position.map(|p| p.offset),
id: message.id().map(str::to_owned),
correlation_id: message.correlation_id().map(str::to_owned),
priority: message.priority(),
timestamp: message.timestamp().map(str::to_owned),
json,
payload_error,
signature: message.signature().map(|s| NativeSignature {
body: s.body.clone(),
sig: s.sig.clone(),
kid: s.kid.clone(),
verified: s.verified,
}),
generation: message.generation,
}
}
fn subscription_of(subscription: crate::Subscription) -> NativeSubscription {
match subscription {
crate::Subscription::Requested => NativeSubscription::Requested,
crate::Subscription::Active => NativeSubscription::Active,
crate::Subscription::Denied => NativeSubscription::Denied,
}
}
fn continuity_of(continuity: crate::Continuity) -> NativeContinuity {
match continuity {
crate::Continuity::Continuous => NativeContinuity::Continuous,
crate::Continuity::ResyncRequired => NativeContinuity::ResyncRequired,
crate::Continuity::Resyncing => NativeContinuity::Resyncing,
}
}
fn item_of(incoming: Incoming) -> Item {
match incoming {
Incoming::Message(message) => Item::Message(message_of(&message)),
Incoming::Binary(bytes) => Item::Binary(bytes.to_vec()),
Incoming::Event(event) => match event {
Event::Connected(c) => Item::Connected {
connection_id: c.connection_id,
user_id: c.user_id,
reconnected: c.reconnected,
recovery: c.recovery,
},
Event::Disconnected(d) => Item::Disconnected {
code: d.code,
reason: d.reason,
retry_in_ms: u64::try_from(d.retry_in.as_millis()).unwrap_or(u64::MAX),
attempt: d.attempt,
},
Event::Paused(p) => Item::Paused { reasons: p.reasons },
Event::Subscribed(s) => Item::Subscribed {
topics: s.topics,
failed: s.failed,
recovery: s
.recovery
.into_iter()
.map(|r| TopicRecovery {
topic: r.topic,
recovered: r.recovered,
count: r.count,
})
.collect(),
},
Event::Gap(g) => Item::Gap {
reason: g.reason.as_str().to_owned(),
topic: g.topic,
epoch: g.epoch,
first: g.first,
last: g.last,
},
Event::ServerError(e) => Item::ServerError {
code: e.code,
message: e.message,
details_json: e.details.to_string(),
},
Event::Resync(r) => Item::Resync {
round: r.round,
topics: r.topics,
reasons: r.reasons,
committed: r
.committed
.into_iter()
.map(|p| StreamPosition {
topic: p.topic,
epoch: p.epoch,
offset: p.offset,
})
.collect(),
},
Event::Continuity(c) => Item::Continuity {
topic: c.topic,
continuity: continuity_of(c.continuity),
reason: c.reason,
},
Event::CheckpointRejected(c) => Item::CheckpointRejected { reason: c.reason },
Event::Delivered(ids) => Item::Delivered { ids },
Event::NotDelivered(n) => Item::NotDelivered {
reason: n.reason,
ids: n.ids,
},
Event::StorageFailed(s) => Item::StorageFailed {
operation: s.operation,
message: s.message,
},
Event::Closed(error) => Item::Closed {
error: error.map(NativeError::from),
},
},
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BatchKind {
Items,
End,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Batch {
pub id: u64,
pub kind: BatchKind,
pub items: Vec<Item>,
}
struct Reader {
events: Events,
pending: Option<Batch>,
next_id: u64,
ended: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NativeStatus {
Connecting,
Connected,
Reconnecting,
Paused,
Closed,
}
pub struct NativeClient {
client: crate::Client,
reader: Mutex<Reader>,
}
impl NativeClient {
pub async fn connect(
config: NativeConfig,
tokens: Option<Arc<dyn TokenSource>>,
cancel: &CancelToken,
) -> Result<Self, NativeError> {
let config = config_of(config, tokens)?;
let cancel = cancel.0.clone();
let (client, events) = on_runtime(async move {
tokio::select! {
connected = crate::connect(config) => connected.map_err(NativeError::from),
() = cancel.cancelled() => Err(NativeError::new(ErrorKind::Cancelled, "connect was cancelled")),
}
})
.await?;
Ok(Self::of(client, events))
}
pub async fn start(
config: NativeConfig,
tokens: Option<Arc<dyn TokenSource>>,
) -> Result<Self, NativeError> {
let config = config_of(config, tokens)?;
let (client, events) =
on_runtime(async move { crate::start(config).await.map_err(NativeError::from) })
.await?;
Ok(Self::of(client, events))
}
fn of(client: crate::Client, events: crate::Events) -> Self {
Self {
client,
reader: Mutex::new(Reader {
events,
pending: None,
next_id: 1,
ended: false,
}),
}
}
pub fn topic_states(&self) -> Vec<NativeTopicState> {
self.client
.topic_states()
.into_iter()
.map(|state| NativeTopicState {
topic: state.topic,
subscription: subscription_of(state.subscription),
continuity: continuity_of(state.continuity),
reason: state.reason,
})
.collect()
}
pub fn commit(&self, topic: &str, epoch: u32, offset: u64, generation: u32) {
self.client.commit_at(topic, epoch, offset, generation);
}
pub fn checkpoint(&self) -> String {
self.client.checkpoint()
}
pub fn kept(&self) -> u32 {
u32::try_from(self.client.kept()).unwrap_or(u32::MAX)
}
pub fn clear(&self) -> Result<(), NativeError> {
Ok(self.client.clear()?)
}
pub fn try_send_with(
&self,
kind: &str,
json: &str,
options: NativeSendOptions,
) -> Result<String, NativeError> {
let payload = raw_json(json)?;
Ok(self
.client
.try_send_with(kind, &*payload, &options.into())?)
}
pub async fn send_with(
&self,
kind: String,
json: String,
options: NativeSendOptions,
cancel: &CancelToken,
) -> Result<String, NativeError> {
let payload = raw_json(&json)?;
let client = self.client.clone();
let cancel = cancel.0.clone();
let options: crate::SendOptions = options.into();
on_runtime(async move {
tokio::select! {
biased;
() = cancel.cancelled() => Err(cancelled("send_with")),
sent = client.send_with(&kind, &*payload, &options) => sent.map_err(NativeError::from),
}
})
.await
}
pub fn resynced(&self, round: u64) {
let _ = self.client.resynced(round);
}
pub fn resync(&self, topics: Vec<String>) {
let _ = self.client.resync(topics);
}
pub fn try_send(&self, kind: &str, json: &str) -> Result<(), NativeError> {
let payload = raw_json(json)?;
Ok(self.client.try_send(kind, &*payload)?)
}
pub async fn send(
&self,
kind: String,
json: String,
cancel: &CancelToken,
) -> Result<(), NativeError> {
let payload = raw_json(&json)?;
let client = self.client.clone();
let cancel = cancel.0.clone();
on_runtime(async move {
tokio::select! {
biased;
() = cancel.cancelled() => Err(cancelled("send")),
sent = client.send(&kind, &*payload) => sent.map_err(NativeError::from),
}
})
.await
}
pub fn try_send_requiring(
&self,
kind: &str,
json: &str,
topics: Vec<String>,
) -> Result<(), NativeError> {
let payload = raw_json(json)?;
Ok(self.client.try_send_requiring(kind, &*payload, topics)?)
}
pub async fn send_requiring(
&self,
kind: String,
json: String,
topics: Vec<String>,
cancel: &CancelToken,
) -> Result<(), NativeError> {
let payload = raw_json(&json)?;
let client = self.client.clone();
let cancel = cancel.0.clone();
on_runtime(async move {
tokio::select! {
biased;
() = cancel.cancelled() => Err(cancelled("send_requiring")),
sent = client.send_requiring(&kind, &*payload, topics) => sent.map_err(NativeError::from),
}
})
.await
}
pub fn try_send_live(&self, kind: &str, json: &str) -> Result<(), NativeError> {
let payload = raw_json(json)?;
Ok(self.client.try_send_live(kind, &*payload)?)
}
pub async fn send_live(
&self,
kind: String,
json: String,
cancel: &CancelToken,
) -> Result<(), NativeError> {
let payload = raw_json(&json)?;
let client = self.client.clone();
let cancel = cancel.0.clone();
on_runtime(async move {
tokio::select! {
biased;
() = cancel.cancelled() => Err(cancelled("send_live")),
sent = client.send_live(&kind, &*payload) => sent.map_err(NativeError::from),
}
})
.await
}
pub async fn send_signed(
&self,
kind: String,
json: String,
nonce: Option<String>,
cancel: &CancelToken,
) -> Result<String, NativeError> {
let payload = raw_json(&json)?;
let client = self.client.clone();
let cancel = cancel.0.clone();
on_runtime(async move {
tokio::select! {
biased;
() = cancel.cancelled() => Err(cancelled("send_signed")),
sent = client.send_signed(&kind, &*payload, nonce.as_deref()) => {
sent.map_err(NativeError::from)
}
}
})
.await
}
pub fn subscribe(&self, topics: Vec<String>) -> Result<(), NativeError> {
Ok(self.client.subscribe(topics)?)
}
pub fn unsubscribe(&self, topics: Vec<String>) -> Result<(), NativeError> {
Ok(self.client.unsubscribe(topics)?)
}
pub fn reconnect(&self) -> Result<(), NativeError> {
Ok(self.client.reconnect()?)
}
pub fn pause(&self, reason: String) -> Result<(), NativeError> {
Ok(self.client.pause(reason)?)
}
pub fn resume(&self, reason: String) -> Result<(), NativeError> {
Ok(self.client.resume(reason)?)
}
pub fn status(&self) -> NativeStatus {
match self.client.status() {
Status::Connecting => NativeStatus::Connecting,
Status::Connected => NativeStatus::Connected,
Status::Reconnecting => NativeStatus::Reconnecting,
Status::Paused => NativeStatus::Paused,
_ => NativeStatus::Closed,
}
}
pub fn connection_id(&self) -> Option<String> {
self.client.connection_id()
}
pub fn user_id(&self) -> Option<String> {
self.client.user_id()
}
pub async fn next_batch(
&self,
ack: u64,
max_items: u32,
max_bytes: u32,
cancel: &CancelToken,
) -> Result<Batch, NativeError> {
let mut reader = self
.reader
.try_lock()
.map_err(|_| NativeError::new(ErrorKind::Busy, "another call reads the events"))?;
if let Some(pending) = &reader.pending {
if pending.id != ack {
return Ok(pending.clone());
}
reader.pending = None;
}
if reader.ended {
let id = reader.next_id;
return Ok(Batch {
id,
kind: BatchKind::End,
items: Vec::new(),
});
}
let max_items = max_items.max(1) as usize;
let max_bytes = max_bytes.max(1) as usize;
let id = reader.next_id;
reader.next_id += 1;
let mut batch = Room {
items: Vec::new(),
bytes: 0,
max_items,
max_bytes,
};
let first = tokio::select! {
first = reader.events.next() => first,
() = cancel.0.cancelled() => return Err(NativeError::new(ErrorKind::Cancelled, "next_batch was cancelled")),
};
let Some(first) = first else {
reader.ended = true;
let batch = Batch {
id,
kind: BatchKind::End,
items: Vec::new(),
};
reader.pending = Some(batch.clone());
return Ok(batch);
};
batch.push(item_of(first));
while batch.has_room() {
let Some(incoming) = reader.events.try_next() else {
break;
};
batch.push(item_of(incoming));
}
let batch = Batch {
id,
kind: BatchKind::Items,
items: batch.items,
};
reader.pending = Some(batch.clone());
Ok(batch)
}
pub async fn disconnect(&self, deadline_ms: u64) {
let client = self.client.clone();
let deadline = Duration::from_millis(deadline_ms.max(1));
let _ = on_runtime(async move {
client.close_within(deadline).await;
Ok(())
})
.await;
}
}
struct Room {
items: Vec<Item>,
bytes: usize,
max_items: usize,
max_bytes: usize,
}
impl Room {
fn has_room(&self) -> bool {
self.items.is_empty() || (self.items.len() < self.max_items && self.bytes < self.max_bytes)
}
fn push(&mut self, item: Item) {
self.bytes += item.size();
self.items.push(item);
}
}
fn cancelled(call: &str) -> NativeError {
NativeError::new(ErrorKind::Cancelled, format!("{call} was cancelled"))
}
fn raw_json(json: &str) -> Result<Box<serde_json::value::RawValue>, NativeError> {
serde_json::value::RawValue::from_string(json.to_owned())
.map_err(|e| NativeError::new(ErrorKind::Encode, format!("the payload is not JSON: {e}")))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::decode::{json_envelope, msgpack_envelope};
fn from_json(text: &str) -> NativeMessage {
message_of(&json_envelope(text).unwrap().into_message(None).to_owned())
}
fn from_msgpack(bytes: &[u8]) -> NativeMessage {
message_of(
&msgpack_envelope(bytes)
.unwrap()
.into_message(None)
.to_owned(),
)
}
fn packed(value: &serde_json::Value) -> Vec<u8> {
rmp_serde::to_vec_named(value).unwrap()
}
#[test]
fn a_payload_reads_the_same_in_json_and_msgpack() {
let cases = [
(serde_json::json!({"t": "m"}), None),
(serde_json::json!({"t": "m", "p": null}), None),
(
serde_json::json!({"t": "m", "p": 18446744073709551615u64}),
Some("18446744073709551615"),
),
(serde_json::json!({"t": "m", "p": -2.5}), Some("-2.5")),
(
serde_json::json!({"t": "m", "p": {"a": [1, null]}}),
Some(r#"{"a":[1,null]}"#),
),
];
for (message, payload) in cases {
let text = message.to_string();
let json = from_json(&text);
let msgpack = from_msgpack(&packed(&message));
assert_eq!(json.json.as_deref(), payload, "json {text}");
assert_eq!(msgpack.json.as_deref(), payload, "msgpack {text}");
assert_eq!(json.payload_error, None);
assert_eq!(msgpack.payload_error, None);
}
}
#[test]
fn a_signing_key_and_its_public_key() {
let key = generate_signing_key();
let public = signing_public_key(&key).unwrap();
assert_eq!(public.len(), 88);
assert_ne!(generate_signing_key(), key);
assert_eq!(
signing_public_key(b"not a key").unwrap_err().kind,
ErrorKind::Config
);
}
#[test]
fn a_msgpack_payload_json_cannot_show_is_an_error() {
let bytes = [0x82, 0xa1, b't', 0xa1, b'm', 0xa1, b'p', 0x81, 0x01, 0x02];
let message = from_msgpack(&bytes);
assert_eq!(message.json, None);
assert!(message.payload_error.is_some());
}
}