Skip to main content

allsource_core/application/dto/
event_dto.rs

1use crate::domain::entities::Event;
2use chrono::{DateTime, Utc};
3use serde::{Deserialize, Serialize};
4use uuid::Uuid;
5
6/// DTO for ingesting a new event
7#[derive(Debug, Deserialize)]
8pub struct IngestEventRequest {
9    pub event_type: String,
10    pub entity_id: String,
11    pub tenant_id: Option<String>, // Optional, defaults to "default"
12    pub payload: serde_json::Value,
13    pub metadata: Option<serde_json::Value>,
14    /// Optional optimistic concurrency control: if set, the write is rejected
15    /// with 409 Conflict unless the entity's current version matches this value.
16    pub expected_version: Option<u64>,
17    /// Start of the interval during which the fact is true. Defaults to the record time.
18    #[serde(default)]
19    pub valid_from: Option<DateTime<Utc>>,
20    /// End of the interval during which the fact is true. Absent means open-ended.
21    #[serde(default)]
22    pub valid_to: Option<DateTime<Utc>>,
23}
24
25/// DTO for event ingestion response
26#[derive(Debug, Serialize)]
27pub struct IngestEventResponse {
28    pub event_id: Uuid,
29    pub timestamp: DateTime<Utc>,
30    /// Effective start of the valid interval (the record time when none was given)
31    pub valid_from: DateTime<Utc>,
32    /// Record time assigned by the server; the caller cannot set it
33    pub recorded_at: DateTime<Utc>,
34    /// The entity's version after this event was appended
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub version: Option<u64>,
37}
38
39impl IngestEventResponse {
40    pub fn from_event(event: &Event) -> Self {
41        Self {
42            event_id: event.id(),
43            timestamp: event.timestamp(),
44            valid_from: event.effective_valid_from(),
45            recorded_at: event.timestamp(),
46            version: None,
47        }
48    }
49}
50
51/// DTO for querying events
52#[derive(Debug, Default, Deserialize)]
53pub struct QueryEventsRequest {
54    /// Filter by entity ID
55    pub entity_id: Option<String>,
56
57    /// Filter by event type
58    pub event_type: Option<String>,
59
60    /// Tenant ID (required for multi-tenancy)
61    pub tenant_id: Option<String>,
62
63    /// Time-travel: get events as of this timestamp
64    pub as_of: Option<DateTime<Utc>>,
65
66    /// Get events since this timestamp
67    pub since: Option<DateTime<Utc>>,
68
69    /// Get events until this timestamp
70    pub until: Option<DateTime<Utc>>,
71
72    /// Valid time: keep events whose valid interval contains this instant
73    /// (`valid_from <= V` and `valid_to` unset or after `V`). Independent of
74    /// `as_of`, which bounds record time; both may be set and must both hold.
75    pub as_of_valid: Option<DateTime<Utc>>,
76
77    /// Valid time: keep events whose `valid_from` is at or after this instant.
78    pub since_valid: Option<DateTime<Utc>>,
79
80    /// Valid time: keep events whose `valid_from` is at or before this instant.
81    pub until_valid: Option<DateTime<Utc>>,
82
83    /// Limit number of results
84    pub limit: Option<usize>,
85
86    /// Filter by event type prefix (e.g., "index." matches "index.created", "index.updated")
87    pub event_type_prefix: Option<String>,
88
89    /// Exclude events whose type starts with ANY of these prefixes
90    /// (comma-separated, e.g. `"audit.,service.,_system."`). Applied before the
91    /// limit so excluded events don't consume the result window — lets callers
92    /// drop high-frequency/operational namespaces from a recent-activity feed.
93    pub exclude_event_type_prefix: Option<String>,
94
95    /// Filter by payload fields (JSON string, e.g., `{"user_id":"abc-123"}`).
96    /// Matches events where payload contains ALL specified key-value pairs.
97    pub payload_filter: Option<String>,
98}
99
100/// DTO for query response
101#[derive(Debug, Serialize)]
102pub struct QueryEventsResponse {
103    pub events: Vec<EventDto>,
104    pub count: usize,
105    pub total_count: usize,
106    pub has_more: bool,
107    /// Current version of the entity (present only when query filters by entity_id)
108    #[serde(skip_serializing_if = "Option::is_none")]
109    pub entity_version: Option<u64>,
110    /// Present only after a bounded, strict read of this retained entity.
111    #[serde(skip_serializing_if = "Option::is_none")]
112    pub archive_integrity: Option<RetainedEntityIntegrity>,
113}
114
115#[derive(Debug, Serialize)]
116pub struct RetainedEntityIntegrity {
117    pub protocol: &'static str,
118    pub tenant_id: String,
119    pub entity_id: String,
120}
121
122/// DTO for a single event in responses
123#[derive(Debug, Serialize, Deserialize, Clone)]
124pub struct EventDto {
125    pub id: Uuid,
126    pub event_type: String,
127    pub entity_id: String,
128    pub tenant_id: String,
129    pub payload: serde_json::Value,
130    pub timestamp: DateTime<Utc>,
131    pub metadata: Option<serde_json::Value>,
132    pub version: i64,
133}
134
135impl From<&Event> for EventDto {
136    fn from(event: &Event) -> Self {
137        Self {
138            id: event.id(),
139            event_type: event.event_type().to_string(),
140            entity_id: event.entity_id().to_string(),
141            tenant_id: event.tenant_id().to_string(),
142            payload: event.payload().clone(),
143            timestamp: event.timestamp(),
144            metadata: event.metadata().cloned(),
145            version: event.version(),
146        }
147    }
148}
149
150impl From<Event> for EventDto {
151    fn from(event: Event) -> Self {
152        EventDto::from(&event)
153    }
154}
155
156/// Request parameters for listing entities
157#[derive(Debug, Default, Deserialize)]
158pub struct ListEntitiesRequest {
159    /// Filter entities by event type prefix
160    pub event_type_prefix: Option<String>,
161    /// Filter by payload fields (JSON string)
162    pub payload_filter: Option<String>,
163    /// Limit number of entities returned
164    pub limit: Option<usize>,
165    /// Offset for pagination
166    pub offset: Option<usize>,
167    /// Sort direction by last-event time: `desc` (newest activity first, the
168    /// default) or `asc` (oldest activity first). Entities with the same
169    /// last-event time are tie-broken by `entity_id` ascending so offset
170    /// pagination is stable.
171    pub order: Option<String>,
172}
173
174/// A single entity summary in the list response
175#[derive(Debug, Serialize)]
176pub struct EntitySummary {
177    pub entity_id: String,
178    pub event_count: usize,
179    pub last_event_type: String,
180    pub last_event_at: DateTime<Utc>,
181}
182
183/// Response from listing entities
184#[derive(Debug, Serialize)]
185pub struct ListEntitiesResponse {
186    pub entities: Vec<EntitySummary>,
187    pub total: usize,
188    pub has_more: bool,
189}
190
191/// Request parameters for detecting duplicate entities
192#[derive(Debug, Deserialize)]
193pub struct DetectDuplicatesRequest {
194    /// Required: event type prefix to scope the search (no full-store scans)
195    pub event_type_prefix: String,
196    /// Comma-separated list of payload field names to group by (e.g., "name,user_id")
197    pub group_by: String,
198    /// Limit number of duplicate groups returned
199    pub limit: Option<usize>,
200    /// Offset for pagination
201    pub offset: Option<usize>,
202}
203
204/// A group of entities that share the same payload field values
205#[derive(Debug, Serialize)]
206pub struct DuplicateGroup {
207    /// The shared field values that define this group
208    pub key: serde_json::Value,
209    /// Entity IDs in this group
210    pub entity_ids: Vec<String>,
211    /// Number of entities in this group
212    pub count: usize,
213}
214
215/// Response from duplicate entity detection
216#[derive(Debug, Serialize)]
217pub struct DetectDuplicatesResponse {
218    /// Groups where count > 1
219    pub duplicates: Vec<DuplicateGroup>,
220    /// Total number of duplicate groups found
221    pub total: usize,
222    /// Whether more results are available
223    pub has_more: bool,
224}
225
226/// DTO for batch ingesting multiple events
227#[derive(Debug, Deserialize)]
228pub struct IngestEventsBatchRequest {
229    pub events: Vec<IngestEventRequest>,
230}
231
232/// DTO for batch ingestion response
233#[derive(Debug, Serialize)]
234pub struct IngestEventsBatchResponse {
235    /// Total number of events submitted
236    pub total: usize,
237    /// Number of events successfully ingested
238    pub ingested: usize,
239    /// Individual results for each event
240    pub events: Vec<IngestEventResponse>,
241}
242
243#[cfg(test)]
244mod tests {
245    use super::*;
246
247    #[test]
248    fn test_ingest_request_without_valid_fields_deserialises() {
249        let req: IngestEventRequest =
250            serde_json::from_str(r#"{"event_type":"user.created","entity_id":"u1","payload":{}}"#)
251                .unwrap();
252        assert_eq!(req.valid_from, None);
253        assert_eq!(req.valid_to, None);
254    }
255
256    #[test]
257    fn test_ingest_request_reads_valid_fields() {
258        let req: IngestEventRequest = serde_json::from_str(
259            r#"{"event_type":"user.created","entity_id":"u1","payload":{},"valid_from":"2026-01-15T00:00:00Z"}"#,
260        )
261        .unwrap();
262        assert_eq!(
263            req.valid_from.unwrap().to_rfc3339(),
264            "2026-01-15T00:00:00+00:00"
265        );
266        assert_eq!(req.valid_to, None);
267    }
268}