use std::sync::Arc;
use serde::Serialize;
use serde_json::Value;
use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::Result;
use crate::core::models::event::{
EventDetailResponse, EventListResponse, EventManualTriggerResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
#[derive(Debug, Clone)]
pub struct Events {
inner: Arc<Inner>,
}
impl Events {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn list(
&self,
merchant_id: &str,
params: Option<&EventListParams>,
) -> Result<EventListResponse> {
let path = format!("/events/{}", encode_segment(merchant_id));
let bytes = match params {
Some(p) => to_json_vec(p)?,
None => to_json_vec(&Value::Object(Default::default()))?,
};
self.inner
.request(HttpMethod::Post, &path, Some(&bytes), &[], None)
.await
}
pub async fn trigger(
&self,
merchant_id: &str,
params: &EventManualTriggerRequest,
) -> Result<EventManualTriggerResponse> {
let path = format!("/events/{}/trigger", encode_segment(merchant_id));
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn trigger_by_profile(
&self,
params: &EventManualTriggerRequest,
) -> Result<EventManualTriggerResponse> {
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Post,
"/events/profile/trigger",
Some(&body),
&[],
None,
)
.await
}
pub async fn list_delivery_attempts(
&self,
merchant_id: &str,
event_id: &str,
) -> Result<Vec<EventDetailResponse>> {
let path = format!(
"/events/{}/{}/attempts",
encode_segment(merchant_id),
encode_segment(event_id)
);
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn list_by_profile(
&self,
params: Option<&EventListParams>,
) -> Result<EventListResponse> {
let bytes = match params {
Some(p) => to_json_vec(p)?,
None => to_json_vec(&Value::Object(Default::default()))?,
};
self.inner
.request(
HttpMethod::Post,
"/events/profile/list",
Some(&bytes),
&[],
None,
)
.await
}
pub async fn retry_delivery(
&self,
merchant_id: &str,
event_id: &str,
) -> Result<EventDetailResponse> {
let path = format!(
"/events/{}/{}/retry",
encode_segment(merchant_id),
encode_segment(event_id)
);
self.inner
.request(HttpMethod::Post, &path, None, &[], None)
.await
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct EventListParams {
#[serde(skip_serializing_if = "Option::is_none")]
pub created_after: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub created_before: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub limit: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub offset: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub object_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub event_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub event_classes: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub event_types: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub is_delivered: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub delivery_attempts: Option<Vec<String>>,
}
impl EventListParams {
#[must_use]
pub fn new() -> Self {
Self::default()
}
}
#[derive(Debug, Clone, Serialize)]
pub struct EventManualTriggerRequest {
pub object_id: String,
pub event_type: String,
pub reason: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_id: Option<String>,
}
impl EventManualTriggerRequest {
pub fn new(
object_id: impl Into<String>,
event_type: impl Into<String>,
reason: impl Into<String>,
) -> Self {
Self {
object_id: object_id.into(),
event_type: event_type.into(),
reason: reason.into(),
profile_id: None,
}
}
#[must_use]
pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
self.profile_id = Some(profile_id.into());
self
}
}
#[cfg(test)]
mod tests {
use super::{EventListParams, EventManualTriggerRequest};
use crate::http::mock::{Step, client_with};
use serde_json::json;
#[tokio::test]
async fn list_by_profile_posts_the_filter_body_to_the_profile_path() {
let (client, mock) = client_with(vec![Step::ok(r#"{"events":[]}"#)]);
let params = EventListParams {
limit: Some(10),
event_classes: Some(vec!["payments".to_string()]),
..EventListParams::new()
};
client
.events()
.list_by_profile(Some(¶ms))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/events/profile/list");
assert_eq!(seen[0].body_json()["event_classes"], json!(["payments"]));
assert!(seen[0].body_json().get("object_id").is_none());
}
#[tokio::test]
async fn list_by_profile_sends_an_empty_object_when_given_no_params() {
let (client, mock) = client_with(vec![Step::ok(r#"{"events":[]}"#)]);
client.events().list_by_profile(None).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].body_json(), json!({}));
}
#[tokio::test]
async fn list_reads_the_events_keyed_envelope() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"events":[{"event_id":"evt_1","object_id":"pay_1","delivery_attempt":"manual_trigger"}],"total_count":1}"#,
)]);
let out = client.events().list("mer_1", None).await.unwrap();
assert_eq!(out.events.len(), 1);
assert_eq!(out.total_count, Some(1));
assert_eq!(out.events[0].object_id.as_deref(), Some("pay_1"));
assert_eq!(
out.events[0].delivery_attempt.as_deref(),
Some("manual_trigger")
);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].url, "https://api.test/events/mer_1");
}
#[tokio::test]
async fn trigger_posts_the_manual_fire_to_the_merchant_path() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"event_id":"evt_1","object_status":"failed","status_overridden":true}"#,
)]);
let out = client
.events()
.trigger(
"mer_1",
&EventManualTriggerRequest::new(
"pay_1",
"payment_succeeded",
"processor confirmed out of band",
),
)
.await
.unwrap();
assert_eq!(out.status_overridden, Some(true));
assert_eq!(out.object_status.as_deref(), Some("failed"));
assert_eq!(out.event.event.event_id.as_deref(), Some("evt_1"));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/events/mer_1/trigger");
assert_eq!(seen[0].body_json()["event_type"], "payment_succeeded");
assert_eq!(
seen[0].body_json()["reason"],
"processor confirmed out of band"
);
assert!(seen[0].body_json().get("profile_id").is_none());
}
#[tokio::test]
async fn a_jwt_client_triggers_with_a_bearer_and_no_api_key() {
let (client, mock) = client_with(vec![Step::ok(r#"{"status_overridden":false}"#)]);
client
.with_jwt("eyJhbGciOiJIUzI1NiJ9.dashboard.token")
.events()
.trigger(
"mer_1",
&EventManualTriggerRequest::new("pay_1", "payment_succeeded", "reconciled"),
)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].header("authorization"),
Some("Bearer eyJhbGciOiJIUzI1NiJ9.dashboard.token")
);
assert_eq!(seen[0].header("api-key"), None);
}
#[tokio::test]
async fn an_api_key_client_triggers_with_the_key_and_no_bearer() {
let (client, mock) = client_with(vec![Step::ok(r#"{"status_overridden":false}"#)]);
client
.events()
.trigger(
"mer_1",
&EventManualTriggerRequest::new("pay_1", "payment_succeeded", "reconciled"),
)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].header("api-key"), Some("prd_test"));
assert_eq!(seen[0].header("authorization"), None);
}
#[tokio::test]
async fn trigger_by_profile_posts_to_the_profile_trigger_path() {
let (client, mock) = client_with(vec![Step::ok(r#"{"status_overridden":false}"#)]);
client
.events()
.trigger_by_profile(
&EventManualTriggerRequest::new("pay_1", "refund_succeeded", "manual")
.profile_id("pro_1"),
)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].url, "https://api.test/events/profile/trigger");
assert_eq!(seen[0].body_json()["profile_id"], "pro_1");
}
#[tokio::test]
async fn list_delivery_attempts_gets_the_attempts_path() {
let (client, mock) = client_with(vec![Step::ok(
r#"[{"event_id":"evt_2","merchant_id":"mer_1","initial_attempt_id":"evt_1",
"delivery_attempt":"automatic_retry","is_delivery_successful":true,
"attempt_delivered":false,"withheld":null,
"request":{"body":"{}","headers":[]},
"response":{"status_code":500,"body":"boom"},"surprise_field":1}]"#,
)]);
let out = client
.events()
.list_delivery_attempts("mer_1", "evt_1")
.await
.unwrap();
assert_eq!(out[0].event.event_id.as_deref(), Some("evt_2"));
assert_eq!(out[0].event.is_delivery_successful, Some(true));
assert_eq!(out[0].event.attempt_delivered, Some(false));
assert_eq!(out[0].response.as_ref().unwrap()["status_code"], 500);
assert!(out[0].withheld.is_none());
assert_eq!(out[0].event.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/events/mer_1/evt_1/attempts");
}
}