Skip to main content

allsource_core/infrastructure/web/
api.rs

1#[cfg(feature = "replication")]
2use crate::infrastructure::replication::ReplicationMode;
3use crate::{
4    application::{
5        dto::{
6            AckRequest, ConsumerEventDto, ConsumerEventsResponse, ConsumerResponse,
7            DetectDuplicatesRequest, DetectDuplicatesResponse, DuplicateGroup, EntitySummary,
8            EventDto, IngestEventRequest, IngestEventResponse, IngestEventsBatchRequest,
9            IngestEventsBatchResponse, ListEntitiesRequest, ListEntitiesResponse,
10            QueryEventsRequest, QueryEventsResponse, RegisterConsumerRequest,
11        },
12        services::{
13            analytics::{
14                AnalyticsEngine, CorrelationRequest, CorrelationResponse, EventFrequencyRequest,
15                EventFrequencyResponse, StatsSummaryRequest, StatsSummaryResponse,
16            },
17            pipeline::{PipelineConfig, PipelineStats},
18            replay::{ReplayProgress, StartReplayRequest, StartReplayResponse},
19            schema::{
20                CompatibilityMode, RegisterSchemaRequest, RegisterSchemaResponse,
21                ValidateEventRequest, ValidateEventResponse,
22            },
23            webhook::{RegisterWebhookRequest, UpdateWebhookRequest},
24        },
25    },
26    domain::{
27        entities::{Event, SchemaEnforcement},
28        value_objects::TenantId,
29    },
30    error::Result,
31    infrastructure::{
32        persistence::compaction::CompactionResult,
33        query::{
34            geospatial::GeoQueryRequest,
35            graphql::{GraphQLError, GraphQLRequest, GraphQLResponse},
36        },
37        security::middleware::OptionalAuth,
38        web::{api_v1::AppState, conditional::conditional_json},
39    },
40    store::{EventStore, EventTypeInfo, StreamInfo},
41};
42use axum::{
43    Json, Router,
44    extract::{Path, Query, State, WebSocketUpgrade},
45    http::HeaderMap,
46    response::{IntoResponse, Response},
47    routing::{get, post, put},
48};
49use serde::Deserialize;
50use std::sync::Arc;
51use tower_http::{
52    cors::{Any, CorsLayer},
53    trace::TraceLayer,
54};
55
56type SharedStore = Arc<EventStore>;
57
58/// Events one `/api/v1/events/query` response may carry.
59///
60/// The page is cloned out of the store and serialized to JSON, so this is
61/// the ceiling on what one request can make the process allocate. A caller
62/// wanting more pages through it: `has_more` and `offset` already say so.
63const MAX_QUERY_PAGE: usize = 10_000;
64
65/// Wait for follower ACK(s) in semi-sync/sync replication modes.
66///
67/// In async mode (default), returns immediately. In semi-sync mode, waits for
68/// at least 1 follower to ACK the current WAL offset. In sync mode, waits for
69/// all followers. If the timeout expires, logs a warning and continues (degraded mode).
70#[cfg(feature = "replication")]
71async fn await_replication_ack(state: &AppState) {
72    let shipper_guard = state.wal_shipper.read().await;
73    if let Some(ref shipper) = *shipper_guard {
74        let mode = shipper.replication_mode();
75        if mode == ReplicationMode::Async {
76            return;
77        }
78
79        let target_offset = shipper.current_leader_offset();
80        if target_offset == 0 {
81            return;
82        }
83
84        let shipper = Arc::clone(shipper);
85        // Drop the read guard before the async wait to avoid holding it across await
86        drop(shipper_guard);
87
88        let timer = state
89            .store
90            .metrics()
91            .replication_ack_wait_seconds
92            .start_timer();
93        let acked = shipper.wait_for_ack(target_offset).await;
94        timer.observe_duration();
95
96        if !acked {
97            tracing::warn!(
98                "Replication ACK timeout in {} mode (offset {}). \
99                 Write succeeded locally but follower confirmation pending.",
100                mode,
101                target_offset,
102            );
103        }
104    }
105}
106#[cfg(not(feature = "replication"))]
107async fn await_replication_ack(_state: &AppState) {
108    // No-op in community edition
109}
110
111pub async fn serve(store: SharedStore, addr: &str) -> anyhow::Result<()> {
112    let app = Router::new()
113        .route("/health", get(health))
114        .route("/metrics", get(prometheus_metrics)) // v0.6: Prometheus metrics endpoint
115        .route("/api/v1/events", post(ingest_event))
116        .route("/api/v1/events/batch", post(ingest_events_batch))
117        .route("/api/v1/events/query", get(query_events))
118        .route("/api/v1/events/{event_id}", get(get_event_by_id))
119        .route("/api/v1/events/stream", get(events_websocket)) // v0.2: WebSocket streaming
120        // v0.10: Stream and event type discovery endpoints
121        .route("/api/v1/streams", get(list_streams))
122        .route("/api/v1/event-types", get(list_event_types))
123        .route("/api/v1/entities/duplicates", get(detect_duplicates))
124        .route("/api/v1/entities/{entity_id}/state", get(get_entity_state))
125        .route(
126            "/api/v1/entities/{entity_id}/snapshot",
127            get(get_entity_snapshot),
128        )
129        .route("/api/v1/stats", get(get_stats))
130        // v0.2: Advanced analytics endpoints
131        .route("/api/v1/analytics/frequency", get(analytics_frequency))
132        .route("/api/v1/analytics/summary", get(analytics_summary))
133        .route("/api/v1/analytics/correlation", get(analytics_correlation))
134        // v0.2: Compaction endpoints
135        .route("/api/v1/compaction/trigger", post(trigger_compaction))
136        .route("/api/v1/compaction/stats", get(compaction_stats))
137        // v0.5: Schema registry endpoints
138        .route("/api/v1/schemas", post(register_schema))
139        .route("/api/v1/schemas", get(list_subjects))
140        .route("/api/v1/schemas/{subject}", get(get_schema))
141        .route(
142            "/api/v1/schemas/{subject}/versions",
143            get(list_schema_versions),
144        )
145        .route("/api/v1/schemas/validate", post(validate_event_schema))
146        .route(
147            "/api/v1/schemas/{subject}/compatibility",
148            put(set_compatibility_mode),
149        )
150        // v0.5: Replay and projection rebuild endpoints
151        .route("/api/v1/replay", post(start_replay))
152        .route("/api/v1/replay", get(list_replays))
153        .route("/api/v1/replay/{replay_id}", get(get_replay_progress))
154        .route("/api/v1/replay/{replay_id}/cancel", post(cancel_replay))
155        .route(
156            "/api/v1/replay/{replay_id}",
157            axum::routing::delete(delete_replay),
158        )
159        // v0.5: Stream processing pipeline endpoints
160        .route("/api/v1/pipelines", post(register_pipeline))
161        .route("/api/v1/pipelines", get(list_pipelines))
162        .route("/api/v1/pipelines/stats", get(all_pipeline_stats))
163        .route("/api/v1/pipelines/{pipeline_id}", get(get_pipeline))
164        .route(
165            "/api/v1/pipelines/{pipeline_id}",
166            axum::routing::delete(remove_pipeline),
167        )
168        .route(
169            "/api/v1/pipelines/{pipeline_id}/stats",
170            get(get_pipeline_stats),
171        )
172        .route("/api/v1/pipelines/{pipeline_id}/reset", put(reset_pipeline))
173        // v0.7: Projection State API for Query Service integration
174        .route("/api/v1/projections", get(list_projections))
175        .route("/api/v1/projections/{name}", get(get_projection))
176        .route(
177            "/api/v1/projections/{name}",
178            axum::routing::delete(delete_projection),
179        )
180        .route("/api/v1/projections/{name}/reset", post(reset_projection))
181        // v0.11: Webhook management endpoints
182        .route("/api/v1/webhooks", post(register_webhook))
183        .route("/api/v1/webhooks", get(list_webhooks))
184        .route("/api/v1/webhooks/{webhook_id}", get(get_webhook))
185        .route("/api/v1/webhooks/{webhook_id}", put(update_webhook))
186        .route(
187            "/api/v1/webhooks/{webhook_id}",
188            axum::routing::delete(delete_webhook),
189        )
190        .route(
191            "/api/v1/webhooks/{webhook_id}/deliveries",
192            get(list_webhook_deliveries),
193        )
194        // v2.0: Advanced query features
195        .route("/api/v1/graphql", post(graphql_query))
196        .route("/api/v1/geospatial/query", post(geo_query))
197        .route("/api/v1/geospatial/stats", get(geo_stats))
198        .route("/api/v1/exactly-once/stats", get(exactly_once_stats))
199        .route(
200            "/api/v1/schema-evolution/history/{event_type}",
201            get(schema_evolution_history),
202        )
203        .route(
204            "/api/v1/schema-evolution/schema/{event_type}",
205            get(schema_evolution_schema),
206        )
207        .route(
208            "/api/v1/schema-evolution/stats",
209            get(schema_evolution_stats),
210        )
211        .layer(
212            CorsLayer::new()
213                .allow_origin(Any)
214                .allow_methods(Any)
215                .allow_headers(Any),
216        )
217        .layer(TraceLayer::new_for_http())
218        .with_state(store);
219
220    let listener = tokio::net::TcpListener::bind(addr).await?;
221    axum::serve(listener, app).await?;
222
223    Ok(())
224}
225
226pub async fn health() -> impl IntoResponse {
227    Json(serde_json::json!({
228        "status": "healthy",
229        "service": "allsource-core",
230        "version": env!("CARGO_PKG_VERSION")
231    }))
232}
233
234// v0.6: Prometheus metrics endpoint
235pub async fn prometheus_metrics(State(store): State<SharedStore>) -> impl IntoResponse {
236    let metrics = store.metrics();
237
238    match metrics.encode() {
239        Ok(encoded) => Response::builder()
240            .status(200)
241            .header("Content-Type", "text/plain; version=0.0.4")
242            .body(encoded)
243            .unwrap()
244            .into_response(),
245        Err(e) => Response::builder()
246            .status(500)
247            .body(format!("Error encoding metrics: {e}"))
248            .unwrap()
249            .into_response(),
250    }
251}
252
253pub async fn ingest_event(
254    State(store): State<SharedStore>,
255    Json(req): Json<IngestEventRequest>,
256) -> Result<Json<IngestEventResponse>> {
257    super::read_model_api::protect_ingest(&req.event_type, &req.entity_id)?;
258    let expected_version = req.expected_version;
259
260    let tenant_id = req.tenant_id.unwrap_or_else(|| "default".to_string());
261    let event = Event::from_strings(
262        req.event_type,
263        req.entity_id,
264        tenant_id,
265        req.payload,
266        req.metadata,
267    )?;
268
269    let event_id = event.id;
270    let timestamp = event.timestamp;
271
272    let new_version =
273        super::archive_work::append(Arc::clone(&store), event, expected_version).await?;
274
275    tracing::info!("Event ingested: {}", event_id);
276
277    Ok(Json(IngestEventResponse {
278        event_id,
279        timestamp,
280        version: Some(new_version),
281    }))
282}
283
284/// Ingest a single event with semi-sync/sync replication ACK waiting.
285///
286/// Used by the v1 API. Tenant comes from `req.tenant_id` — the Control Plane
287/// delegation layer sets it from the authenticated caller before forwarding.
288/// Core is internal-only and does not authenticate public traffic.
289/// Look up the tenant's `SchemaEnforcement` mode and, if non-permissive,
290/// validate the event payload against any registered schema for the
291/// event_type.
292///
293/// Fast path: `Permissive` (default for unconfigured tenants AND for tenants
294/// not present in the repo, like dev/test setups) returns `Ok(())` without
295/// touching the schema registry — preserves the pre-v0.21.5 ingest cost.
296///
297/// `Warn`: validation runs, violations log at WARN, the write proceeds.
298/// `Strict`: violations return `AllSourceError::SchemaViolation` → 422 with
299/// the structured body the HTTP layer builds in `error.rs`.
300///
301/// If no schema is registered for the event_type, validation is a no-op
302/// regardless of mode — this matches the principle that schemas are
303/// opt-in per event_type, not per tenant.
304async fn enforce_schema_if_configured(
305    state: &AppState,
306    tenant_id: &str,
307    event: &Event,
308) -> Result<()> {
309    // Cheapest possible lookup: parse the tenant_id; if it fails, treat as
310    // permissive (defensive — Event::from_strings already validated, but
311    // this keeps the contract clear).
312    let Ok(parsed) = TenantId::new(tenant_id.to_string()) else {
313        return Ok(());
314    };
315    let mode = match state.tenant_repo.find_by_id(&parsed).await {
316        Ok(Some(t)) => t.schema_enforcement(),
317        // Unknown tenant → permissive. Avoids breaking the default tenant
318        // and any dev setups that ingest without pre-registering tenants.
319        _ => SchemaEnforcement::Permissive,
320    };
321    if matches!(mode, SchemaEnforcement::Permissive) {
322        return Ok(());
323    }
324
325    // Schema lookup keyed by event_type. Latest version only (None) — schema
326    // evolution is a separate concern; tenants pin a version via their own
327    // registration flow if they need to.
328    let registry = state.store.schema_registry();
329    let Ok(schema) = registry.get_schema(event.event_type.as_str(), None) else {
330        // No schema registered for this event_type → fast path, regardless
331        // of enforcement mode. Schemas are opt-in.
332        return Ok(());
333    };
334
335    let result = registry
336        .validate(
337            event.event_type.as_str(),
338            Some(schema.version),
339            &event.payload,
340        )
341        .map_err(|e| crate::error::AllSourceError::InternalError(e.to_string()))?;
342
343    if result.valid {
344        return Ok(());
345    }
346
347    match mode {
348        SchemaEnforcement::Strict => Err(crate::error::AllSourceError::SchemaViolation {
349            event_type: event.event_type.as_str().to_string(),
350            schema_version: result.schema_version,
351            errors: result.errors,
352        }),
353        SchemaEnforcement::Warn => {
354            tracing::warn!(
355                tenant = %tenant_id,
356                event_type = %event.event_type.as_str(),
357                schema_version = result.schema_version,
358                errors = ?result.errors,
359                "schema violation (warn mode — write accepted)"
360            );
361            Ok(())
362        }
363        // Already handled above
364        SchemaEnforcement::Permissive => Ok(()),
365    }
366}
367
368pub async fn ingest_event_v1(
369    State(state): State<AppState>,
370    Json(req): Json<IngestEventRequest>,
371) -> Result<Json<IngestEventResponse>> {
372    super::read_model_api::protect_ingest(&req.event_type, &req.entity_id)?;
373    let expected_version = req.expected_version;
374
375    let tenant_id = req.tenant_id.unwrap_or_else(|| "default".to_string());
376
377    let event = Event::from_strings(
378        req.event_type,
379        req.entity_id,
380        tenant_id.clone(),
381        req.payload,
382        req.metadata,
383    )?;
384
385    // Per-tenant schema enforcement (Permissive is the fast path — no
386    // tenant lookup, no schema query). See neotoma-gaps bead t-0795.
387    enforce_schema_if_configured(&state, &tenant_id, &event).await?;
388
389    let event_id = event.id;
390    let timestamp = event.timestamp;
391
392    let new_version =
393        super::archive_work::append(Arc::clone(&state.store), event, expected_version).await?;
394
395    // Semi-sync/sync: wait for follower ACK(s) before returning
396    await_replication_ack(&state).await;
397
398    tracing::info!("Event ingested: {}", event_id);
399
400    Ok(Json(IngestEventResponse {
401        event_id,
402        timestamp,
403        version: Some(new_version),
404    }))
405}
406
407/// Batch ingest multiple events in a single request
408///
409/// This endpoint allows ingesting multiple events atomically, which is more
410/// efficient than making individual requests for each event.
411pub async fn ingest_events_batch(
412    State(store): State<SharedStore>,
413    Json(req): Json<IngestEventsBatchRequest>,
414) -> Result<Json<IngestEventsBatchResponse>> {
415    for event in &req.events {
416        super::read_model_api::protect_ingest(&event.event_type, &event.entity_id)?;
417    }
418    let total = req.events.len();
419    let mut ingested_events = Vec::with_capacity(total);
420
421    for event_req in req.events {
422        let tenant_id = event_req.tenant_id.unwrap_or_else(|| "default".to_string());
423        let expected_version = event_req.expected_version;
424
425        let event = Event::from_strings(
426            event_req.event_type,
427            event_req.entity_id,
428            tenant_id,
429            event_req.payload,
430            event_req.metadata,
431        )?;
432
433        // Note: the non-v1 batch path uses State<SharedStore>, not AppState,
434        // so it has no tenant_repo to check enforcement against. Schema
435        // enforcement is wired through the v1 batch handler below — this
436        // path remains permissive (it predates the tenant_repo wiring).
437
438        let event_id = event.id;
439        let timestamp = event.timestamp;
440
441        let new_version =
442            super::archive_work::append(Arc::clone(&store), event, expected_version).await?;
443
444        ingested_events.push(IngestEventResponse {
445            event_id,
446            timestamp,
447            version: Some(new_version),
448        });
449    }
450
451    let ingested = ingested_events.len();
452    tracing::info!("Batch ingested {} events", ingested);
453
454    Ok(Json(IngestEventsBatchResponse {
455        total,
456        ingested,
457        events: ingested_events,
458    }))
459}
460
461/// Batch ingest with semi-sync/sync replication ACK waiting.
462///
463/// Used by the v1 API. Per-event tenant comes from `event_req.tenant_id` — the
464/// Control Plane delegation layer sets it from the authenticated caller before
465/// forwarding. Core is internal-only and does not authenticate public traffic.
466pub async fn ingest_events_batch_v1(
467    State(state): State<AppState>,
468    Json(req): Json<IngestEventsBatchRequest>,
469) -> Result<Json<IngestEventsBatchResponse>> {
470    for event in &req.events {
471        super::read_model_api::protect_ingest(&event.event_type, &event.entity_id)?;
472    }
473    let total = req.events.len();
474    let mut ingested_events = Vec::with_capacity(total);
475
476    for event_req in req.events {
477        let tenant_id = event_req.tenant_id.unwrap_or_else(|| "default".to_string());
478        let expected_version = event_req.expected_version;
479
480        let event = Event::from_strings(
481            event_req.event_type,
482            event_req.entity_id,
483            tenant_id.clone(),
484            event_req.payload,
485            event_req.metadata,
486        )?;
487
488        enforce_schema_if_configured(&state, &tenant_id, &event).await?;
489
490        let event_id = event.id;
491        let timestamp = event.timestamp;
492
493        let new_version =
494            super::archive_work::append(Arc::clone(&state.store), event, expected_version).await?;
495
496        ingested_events.push(IngestEventResponse {
497            event_id,
498            timestamp,
499            version: Some(new_version),
500        });
501    }
502
503    // Semi-sync/sync: wait for follower ACK(s) after all events are ingested
504    await_replication_ack(&state).await;
505
506    let ingested = ingested_events.len();
507    tracing::info!("Batch ingested {} events", ingested);
508
509    Ok(Json(IngestEventsBatchResponse {
510        total,
511        ingested,
512        events: ingested_events,
513    }))
514}
515
516/// Sort-order query parameter for `GET /api/v1/events/query`. Kept separate
517/// from `QueryEventsRequest` so ordering is purely an HTTP-layer concern and
518/// the internal query DTO (used by ~50 call sites) stays untouched.
519#[derive(Debug, Deserialize)]
520pub struct EventOrderParam {
521    /// `asc` (oldest first, the default) or `desc` (newest first).
522    pub order: Option<String>,
523}
524
525/// Pagination offset for `GET /api/v1/events/query`. Separate from
526/// `QueryEventsRequest` for the same reason as `EventOrderParam`: offset is an
527/// HTTP-layer windowing concern, not part of the internal query predicate that
528/// `store.query()` and its ~50 call sites evaluate.
529#[derive(Debug, Deserialize)]
530pub struct EventOffsetParam {
531    /// Number of matching events to skip before applying `limit`. Default 0.
532    pub offset: Option<usize>,
533}
534
535/// Opt-in integrity protocol. Omission preserves the legacy tolerant query.
536#[derive(Debug, Default, Deserialize)]
537pub struct EventIntegrityParam {
538    pub integrity: Option<String>,
539}
540
541/// `GET /api/v1/events/query`, conditional per the latest-state contract.
542/// The body carries no request-time field, so equal results share a tag.
543pub async fn query_events(
544    auth: OptionalAuth,
545    req: Query<QueryEventsRequest>,
546    order_param: Query<EventOrderParam>,
547    offset_param: Query<EventOffsetParam>,
548    integrity_param: Query<EventIntegrityParam>,
549    store: State<SharedStore>,
550    headers: HeaderMap,
551) -> Result<Response> {
552    let Json(body) =
553        query_events_json(auth, req, order_param, offset_param, integrity_param, store).await?;
554    conditional_json(&headers, &body)
555}
556
557pub async fn query_events_json(
558    OptionalAuth(auth): OptionalAuth,
559    Query(req): Query<QueryEventsRequest>,
560    Query(order_param): Query<EventOrderParam>,
561    Query(offset_param): Query<EventOffsetParam>,
562    Query(integrity_param): Query<EventIntegrityParam>,
563    State(store): State<SharedStore>,
564) -> Result<Json<QueryEventsResponse>> {
565    let offset = offset_param.offset.unwrap_or(0);
566    let queried_entity_id = req.entity_id.clone();
567
568    // Sort order. Default is ascending (oldest first) to preserve replay
569    // semantics for existing consumers. `order=desc` returns newest first,
570    // so `?entity_id=<id>&limit=1&order=desc` reliably yields the latest
571    // event for an entity (issue #177).
572    let descending = match order_param.order.as_deref() {
573        None => false,
574        Some(o) if o.eq_ignore_ascii_case("asc") => false,
575        Some(o) if o.eq_ignore_ascii_case("desc") => true,
576        Some(other) => {
577            return Err(crate::error::AllSourceError::InvalidInput(format!(
578                "invalid 'order' value '{other}': expected 'asc' or 'desc'"
579            )));
580        }
581    };
582
583    // Tenant resolution. Since Core is internal-only (bead t-0ff8), the only
584    // callers are Control Plane's delegation layer and other internal Fly
585    // services. Request param wins — that's what the gateway sets authoritatively
586    // from the authenticated caller's identity. Auth-context fallback is kept
587    // as a defense-in-depth for any internal caller that forgets to pass
588    // tenant_id but is authenticated (legacy; audit and remove once all
589    // internal callers are confirmed to set tenant_id explicitly).
590    let enforced_tenant = req
591        .tenant_id
592        .clone()
593        .or_else(|| auth.as_ref().map(|a| a.tenant_id().to_string()));
594
595    let retained_prefix = integrity_param.integrity.as_deref() == Some("retained-prefix-v1");
596    if retained_prefix
597        && (enforced_tenant.as_deref().is_none_or(str::is_empty)
598            || req.event_type_prefix.as_deref().is_none_or(str::is_empty)
599            || req.entity_id.is_some())
600    {
601        return Err(crate::error::AllSourceError::InvalidInput(
602            "Strict prefix read requires tenant_id and nonempty event_type_prefix without entity_id".into(),
603        ));
604    }
605    if let Some(protocol) = integrity_param.integrity.filter(|_| !retained_prefix) {
606        return super::retained_query::query(
607            store,
608            QueryEventsRequest {
609                tenant_id: enforced_tenant,
610                ..req
611            },
612            offset,
613            descending,
614            &protocol,
615        )
616        .await
617        .map(Json);
618    }
619
620    // FAIL CLOSED (tenant isolation): the public events query must NEVER return
621    // cross-tenant results. The gateway always injects an auth-derived tenant_id
622    // (and overwrites any client-supplied one); if neither a request tenant nor
623    // an auth tenant is present we return an empty result rather than scanning
624    // across tenants. A genuine cross-tenant/admin scan is a separate, explicit
625    // internal path — it does not ride this endpoint.
626    if enforced_tenant.as_deref().unwrap_or("").is_empty() {
627        return Ok(Json(QueryEventsResponse {
628            events: Vec::new(),
629            count: 0,
630            total_count: 0,
631            has_more: false,
632            entity_version: None,
633            archive_integrity: None,
634        }));
635    }
636
637    // One windowed pass: the store sorts borrowed matches, applies `offset` and
638    // `limit`, and clones only the page — while still reporting the pre-window
639    // match count for `total_count`/`has_more`. Asking for the total used to
640    // mean a second, unlimited query that cloned the whole history, so
641    // `?entity_id=X&limit=1&order=desc` cost as much as fetching everything
642    // (issue #251). Offset is applied before limit so `offset=N&limit=N` walks
643    // pages instead of returning page one forever (issue #250).
644    // The window is what gets cloned and serialized, so an uncapped `limit`
645    // lets a caller choose an allocation large enough to end the process.
646    // `has_more` already tells a paginator to come back, so the clamp costs
647    // one extra round trip and nothing else.
648    let requested_limit = req.limit;
649    let scoped_req = QueryEventsRequest {
650        tenant_id: enforced_tenant,
651        limit: Some(req.limit.unwrap_or(MAX_QUERY_PAGE).min(MAX_QUERY_PAGE)),
652        ..req
653    };
654    if requested_limit.is_some_and(|limit| limit > MAX_QUERY_PAGE) {
655        tracing::debug!(
656            requested = requested_limit,
657            served = MAX_QUERY_PAGE,
658            "query limit clamped to the maximum page size"
659        );
660    }
661    let (limited_events, total_count) = if retained_prefix {
662        super::archive_work::prefix_query(Arc::clone(&store), scoped_req, offset, descending)
663            .await?
664    } else {
665        store.query_window(&scoped_req, offset, descending)?
666    };
667
668    let count = limited_events.len();
669    // `has_more` is relative to the window actually served, not to the page
670    // size — a paginator that trusts a bare `count < total_count` never
671    // terminates once an offset is in play.
672    let has_more = offset + count < total_count;
673    let events: Vec<EventDto> = limited_events.iter().map(EventDto::from).collect();
674
675    // Include entity_version only when filtering by a single entity_id
676    let entity_version = queried_entity_id
677        .as_deref()
678        .map(|eid| store.get_entity_version(eid));
679
680    tracing::debug!("Query returned {} events (total: {})", count, total_count);
681
682    Ok(Json(QueryEventsResponse {
683        events,
684        count,
685        total_count,
686        has_more,
687        entity_version,
688        archive_integrity: None,
689    }))
690}
691
692pub async fn list_entities(
693    State(store): State<SharedStore>,
694    Query(req): Query<ListEntitiesRequest>,
695) -> Result<Json<ListEntitiesResponse>> {
696    use std::collections::HashMap;
697
698    // Get all events matching the filters
699    let query_req = QueryEventsRequest {
700        entity_id: None,
701        event_type: None,
702        tenant_id: None,
703        as_of: None,
704        since: None,
705        until: None,
706        limit: None,
707        event_type_prefix: req.event_type_prefix,
708        exclude_event_type_prefix: None,
709        payload_filter: req.payload_filter,
710    };
711    let events = store.query(&query_req)?;
712
713    // Group by entity_id
714    let mut entity_map: HashMap<String, Vec<&Event>> = HashMap::new();
715    for event in &events {
716        entity_map
717            .entry(event.entity_id().to_string())
718            .or_default()
719            .push(event);
720    }
721
722    // Sort direction by last-event time. Default is `desc` (newest activity
723    // first) to preserve the endpoint's long-standing behavior; `order=asc`
724    // returns oldest activity first (issue #178).
725    let ascending = match req.order.as_deref() {
726        None => false,
727        Some(o) if o.eq_ignore_ascii_case("desc") => false,
728        Some(o) if o.eq_ignore_ascii_case("asc") => true,
729        Some(other) => {
730            return Err(crate::error::AllSourceError::InvalidInput(format!(
731                "invalid 'order' value '{other}': expected 'asc' or 'desc'"
732            )));
733        }
734    };
735
736    // Build entity summaries, then sort by last-event time in the requested
737    // direction. Ties are broken by `entity_id` (always ascending) so the
738    // total order is deterministic — required for stable offset pagination.
739    let mut summaries: Vec<EntitySummary> = entity_map
740        .into_iter()
741        .map(|(entity_id, events)| {
742            let last = events.iter().max_by_key(|e| e.timestamp()).unwrap();
743            EntitySummary {
744                entity_id,
745                event_count: events.len(),
746                last_event_type: last.event_type_str().to_string(),
747                last_event_at: last.timestamp(),
748            }
749        })
750        .collect();
751    summaries.sort_by(|a, b| {
752        let by_time = a.last_event_at.cmp(&b.last_event_at);
753        let by_time = if ascending {
754            by_time
755        } else {
756            by_time.reverse()
757        };
758        by_time.then_with(|| a.entity_id.cmp(&b.entity_id))
759    });
760
761    let total = summaries.len();
762
763    // Apply offset and limit
764    let offset = req.offset.unwrap_or(0);
765    let summaries: Vec<EntitySummary> = summaries.into_iter().skip(offset).collect::<Vec<_>>();
766    let summaries = if let Some(limit) = req.limit {
767        let has_more = summaries.len() > limit;
768        let truncated: Vec<EntitySummary> = summaries.into_iter().take(limit).collect();
769        return Ok(Json(ListEntitiesResponse {
770            entities: truncated,
771            total,
772            has_more,
773        }));
774    } else {
775        summaries
776    };
777
778    Ok(Json(ListEntitiesResponse {
779        entities: summaries,
780        total,
781        has_more: false,
782    }))
783}
784
785pub async fn detect_duplicates(
786    State(store): State<SharedStore>,
787    Query(req): Query<DetectDuplicatesRequest>,
788) -> Result<Json<DetectDuplicatesResponse>> {
789    use std::collections::HashMap;
790
791    let group_by_fields: Vec<&str> = req.group_by.split(',').map(str::trim).collect();
792
793    // Query events scoped by the required prefix
794    let query_req = QueryEventsRequest {
795        entity_id: None,
796        event_type: None,
797        tenant_id: None,
798        as_of: None,
799        since: None,
800        until: None,
801        limit: None,
802        event_type_prefix: Some(req.event_type_prefix),
803        exclude_event_type_prefix: None,
804        payload_filter: None,
805    };
806    let events = store.query(&query_req)?;
807
808    // For each entity, extract the latest event's payload fields specified by group_by
809    // Then group entities by those field values
810    let mut entity_latest: HashMap<String, &Event> = HashMap::new();
811    for event in &events {
812        let eid = event.entity_id().to_string();
813        entity_latest
814            .entry(eid)
815            .and_modify(|existing| {
816                if event.timestamp() > existing.timestamp() {
817                    *existing = event;
818                }
819            })
820            .or_insert(event);
821    }
822
823    // Group entities by their payload field values
824    let mut groups: HashMap<String, Vec<String>> = HashMap::new();
825    for (entity_id, event) in &entity_latest {
826        let payload = event.payload();
827        let mut key_parts = serde_json::Map::new();
828        for field in &group_by_fields {
829            let value = payload
830                .get(*field)
831                .cloned()
832                .unwrap_or(serde_json::Value::Null);
833            key_parts.insert((*field).to_string(), value);
834        }
835        let key_str = serde_json::to_string(&key_parts).unwrap_or_default();
836        groups.entry(key_str).or_default().push(entity_id.clone());
837    }
838
839    // Filter to groups with count > 1 (actual duplicates)
840    let mut duplicate_groups: Vec<DuplicateGroup> = groups
841        .into_iter()
842        .filter(|(_, ids)| ids.len() > 1)
843        .map(|(key_str, mut ids)| {
844            ids.sort();
845            let key: serde_json::Value =
846                serde_json::from_str(&key_str).unwrap_or(serde_json::Value::Null);
847            let count = ids.len();
848            DuplicateGroup {
849                key,
850                entity_ids: ids,
851                count,
852            }
853        })
854        .collect();
855
856    // Sort by count descending for consistent output
857    duplicate_groups.sort_by_key(|a| std::cmp::Reverse(a.count));
858
859    let total = duplicate_groups.len();
860
861    // Apply offset and limit
862    let offset = req.offset.unwrap_or(0);
863    let duplicate_groups: Vec<DuplicateGroup> = duplicate_groups.into_iter().skip(offset).collect();
864
865    if let Some(limit) = req.limit {
866        let has_more = duplicate_groups.len() > limit;
867        let truncated: Vec<DuplicateGroup> = duplicate_groups.into_iter().take(limit).collect();
868        return Ok(Json(DetectDuplicatesResponse {
869            duplicates: truncated,
870            total,
871            has_more,
872        }));
873    }
874
875    Ok(Json(DetectDuplicatesResponse {
876        duplicates: duplicate_groups,
877        total,
878        has_more: false,
879    }))
880}
881
882#[derive(Deserialize)]
883pub struct EntityStateParams {
884    as_of: Option<chrono::DateTime<chrono::Utc>>,
885    /// Tenant to scope to (the gateway injects the authenticated tenant).
886    ///
887    /// When present, reconstruction folds only that tenant's events (#230).
888    tenant_id: Option<String>,
889    /// Include the folded events as `history[]`. Defaults to `false`.
890    #[serde(default)]
891    history: bool,
892}
893
894pub async fn get_entity_state(
895    State(store): State<SharedStore>,
896    headers: HeaderMap,
897    Path(entity_id): Path<String>,
898    Query(params): Query<EntityStateParams>,
899) -> Result<Response> {
900    let state = store.entity_state(
901        &entity_id,
902        params.as_of,
903        params.tenant_id.as_deref(),
904        params.history,
905    )?;
906
907    tracing::info!("State reconstructed for entity: {}", entity_id);
908
909    conditional_json(&headers, &state)
910}
911
912/// The latest-state contract gives `/snapshot` the same body as `/state`.
913pub async fn get_entity_snapshot(
914    state: State<SharedStore>,
915    headers: HeaderMap,
916    path: Path<String>,
917    params: Query<EntityStateParams>,
918) -> Result<Response> {
919    get_entity_state(state, headers, path, params).await
920}
921
922/// Query parameters for the stats endpoint.
923#[derive(Debug, Deserialize)]
924pub struct StatsParams {
925    /// Tenant to scope to (the gateway injects the authenticated tenant).
926    ///
927    /// Absent = global, whole-store totals. That form is internal/admin only and
928    /// must never be reachable by a tenant — the gateway routes its public
929    /// `GET /api/v1/stats` through here with this parameter forced (#230).
930    pub tenant_id: Option<String>,
931}
932
933pub async fn get_stats(
934    State(store): State<SharedStore>,
935    Query(params): Query<StatsParams>,
936) -> impl IntoResponse {
937    match params.tenant_id.as_deref() {
938        Some(tenant_id) => {
939            Json(serde_json::to_value(store.stats_for_tenant(tenant_id)).unwrap_or_default())
940        }
941        None => Json(serde_json::to_value(store.stats()).unwrap_or_default()),
942    }
943}
944
945// v0.10: List all streams (entity_ids) in the event store
946/// Query parameters for listing streams
947#[derive(Debug, Deserialize)]
948pub struct ListStreamsParams {
949    /// Tenant to scope to (the gateway injects the authenticated tenant).
950    pub tenant_id: Option<String>,
951    /// Optional limit on number of streams to return
952    pub limit: Option<usize>,
953    /// Optional offset for pagination
954    pub offset: Option<usize>,
955}
956
957/// Response for listing streams
958#[derive(Debug, serde::Serialize)]
959pub struct ListStreamsResponse {
960    pub streams: Vec<StreamInfo>,
961    pub total: usize,
962}
963
964pub async fn list_streams(
965    OptionalAuth(auth): OptionalAuth,
966    State(store): State<SharedStore>,
967    Query(params): Query<ListStreamsParams>,
968) -> Json<ListStreamsResponse> {
969    // Tenant-scoped + fail closed: no tenant → empty, never a cross-tenant list.
970    let tenant = params
971        .tenant_id
972        .clone()
973        .or_else(|| auth.as_ref().map(|a| a.tenant_id().to_string()))
974        .filter(|t| !t.is_empty());
975    let Some(tenant) = tenant else {
976        return Json(ListStreamsResponse {
977            streams: vec![],
978            total: 0,
979        });
980    };
981    let mut streams = store.list_streams_for_tenant(&tenant);
982    let total = streams.len();
983
984    // Sort by last_event_at descending (most recent first)
985    streams.sort_by_key(|a| std::cmp::Reverse(a.last_event_at));
986
987    // Apply pagination
988    if let Some(offset) = params.offset {
989        if offset < streams.len() {
990            streams = streams[offset..].to_vec();
991        } else {
992            streams = vec![];
993        }
994    }
995
996    if let Some(limit) = params.limit {
997        streams.truncate(limit);
998    }
999
1000    tracing::debug!("Listed {} streams (total: {})", streams.len(), total);
1001
1002    Json(ListStreamsResponse { streams, total })
1003}
1004
1005// v0.10: List all event types in the event store
1006/// Query parameters for listing event types
1007#[derive(Debug, Deserialize)]
1008pub struct ListEventTypesParams {
1009    /// Tenant to scope to (the gateway injects the authenticated tenant).
1010    pub tenant_id: Option<String>,
1011    /// Optional limit on number of event types to return
1012    pub limit: Option<usize>,
1013    /// Optional offset for pagination
1014    pub offset: Option<usize>,
1015}
1016
1017/// Response for listing event types
1018#[derive(Debug, serde::Serialize)]
1019pub struct ListEventTypesResponse {
1020    pub event_types: Vec<EventTypeInfo>,
1021    pub total: usize,
1022}
1023
1024pub async fn list_event_types(
1025    OptionalAuth(auth): OptionalAuth,
1026    State(store): State<SharedStore>,
1027    Query(params): Query<ListEventTypesParams>,
1028) -> Json<ListEventTypesResponse> {
1029    // Tenant-scoped + fail closed: no tenant → empty, never cross-tenant types.
1030    let tenant = params
1031        .tenant_id
1032        .clone()
1033        .or_else(|| auth.as_ref().map(|a| a.tenant_id().to_string()))
1034        .filter(|t| !t.is_empty());
1035    let Some(tenant) = tenant else {
1036        return Json(ListEventTypesResponse {
1037            event_types: vec![],
1038            total: 0,
1039        });
1040    };
1041    let mut event_types = store.list_event_types_for_tenant(&tenant);
1042    let total = event_types.len();
1043
1044    // Sort by event_count descending (most used first)
1045    event_types.sort_by_key(|a| std::cmp::Reverse(a.event_count));
1046
1047    // Apply pagination
1048    if let Some(offset) = params.offset {
1049        if offset < event_types.len() {
1050            event_types = event_types[offset..].to_vec();
1051        } else {
1052            event_types = vec![];
1053        }
1054    }
1055
1056    if let Some(limit) = params.limit {
1057        event_types.truncate(limit);
1058    }
1059
1060    tracing::debug!(
1061        "Listed {} event types (total: {})",
1062        event_types.len(),
1063        total
1064    );
1065
1066    Json(ListEventTypesResponse { event_types, total })
1067}
1068
1069// v0.2: WebSocket endpoint for real-time event streaming
1070#[derive(Debug, Deserialize)]
1071pub struct WebSocketParams {
1072    pub consumer_id: Option<String>,
1073}
1074
1075pub async fn events_websocket(
1076    ws: WebSocketUpgrade,
1077    State(store): State<SharedStore>,
1078    Query(params): Query<WebSocketParams>,
1079) -> Response {
1080    let websocket_manager = store.websocket_manager();
1081
1082    ws.on_upgrade(move |socket| async move {
1083        if let Some(consumer_id) = params.consumer_id {
1084            websocket_manager
1085                .handle_socket_with_consumer(socket, consumer_id, store)
1086                .await;
1087        } else {
1088            websocket_manager.handle_socket(socket).await;
1089        }
1090    })
1091}
1092
1093// v0.2: Event frequency analytics endpoint
1094pub async fn analytics_frequency(
1095    State(store): State<SharedStore>,
1096    Query(req): Query<EventFrequencyRequest>,
1097) -> Result<Json<EventFrequencyResponse>> {
1098    let response = AnalyticsEngine::event_frequency(&store, &req)?;
1099
1100    tracing::debug!(
1101        "Frequency analysis returned {} buckets",
1102        response.buckets.len()
1103    );
1104
1105    Ok(Json(response))
1106}
1107
1108// v0.2: Statistical summary endpoint
1109pub async fn analytics_summary(
1110    State(store): State<SharedStore>,
1111    Query(req): Query<StatsSummaryRequest>,
1112) -> Result<Json<StatsSummaryResponse>> {
1113    let response = AnalyticsEngine::stats_summary(&store, &req)?;
1114
1115    tracing::debug!(
1116        "Stats summary: {} events across {} entities",
1117        response.total_events,
1118        response.unique_entities
1119    );
1120
1121    Ok(Json(response))
1122}
1123
1124// v0.2: Event correlation analysis endpoint
1125pub async fn analytics_correlation(
1126    State(store): State<SharedStore>,
1127    Query(req): Query<CorrelationRequest>,
1128) -> Result<Json<CorrelationResponse>> {
1129    let response = AnalyticsEngine::analyze_correlation(&store, req)?;
1130
1131    tracing::debug!(
1132        "Correlation analysis: {}/{} correlated pairs ({:.2}%)",
1133        response.correlated_pairs,
1134        response.total_a,
1135        response.correlation_percentage
1136    );
1137
1138    Ok(Json(response))
1139}
1140
1141// v0.2: Trigger manual compaction
1142pub async fn trigger_compaction(
1143    State(store): State<SharedStore>,
1144) -> Result<Json<CompactionResult>> {
1145    let compaction_manager = store.compaction_manager().ok_or_else(|| {
1146        crate::error::AllSourceError::InternalError(
1147            "Compaction not enabled (no Parquet storage)".to_string(),
1148        )
1149    })?;
1150
1151    tracing::info!("📦 Manual compaction triggered via API");
1152
1153    let result = compaction_manager.compact_now()?;
1154
1155    Ok(Json(result))
1156}
1157
1158// v0.2: Get compaction statistics
1159pub async fn compaction_stats(State(store): State<SharedStore>) -> Result<Json<serde_json::Value>> {
1160    let compaction_manager = store.compaction_manager().ok_or_else(|| {
1161        crate::error::AllSourceError::InternalError(
1162            "Compaction not enabled (no Parquet storage)".to_string(),
1163        )
1164    })?;
1165
1166    let stats = compaction_manager.stats();
1167    let config = compaction_manager.config();
1168    // `total_compactions` counts this process only, so it cannot distinguish
1169    // "never ran" from "ran, then restarted". Staleness survives a restart and
1170    // is what an alarm can read (gh#321).
1171    let last_compaction = compaction_manager.last_compaction();
1172    let seconds_since_last_compaction =
1173        last_compaction.map(|at| (chrono::Utc::now() - at).num_seconds().max(0));
1174
1175    Ok(Json(serde_json::json!({
1176        "stats": stats,
1177        "last_compaction_at": last_compaction,
1178        "seconds_since_last_compaction": seconds_since_last_compaction,
1179        "sweep_cursor": compaction_manager.sweep_cursor(),
1180        "last_sweep_paused": compaction_manager.last_sweep_paused(),
1181        "config": {
1182            "min_files_to_compact": config.min_files_to_compact,
1183            "target_file_size": config.target_file_size,
1184            "max_file_size": config.max_file_size,
1185            "small_file_threshold": config.small_file_threshold,
1186            "compaction_interval_seconds": config.compaction_interval_seconds,
1187            "auto_compact": config.auto_compact,
1188            "strategy": config.strategy
1189        }
1190    })))
1191}
1192
1193// v0.5: Register a new schema
1194pub async fn register_schema(
1195    State(store): State<SharedStore>,
1196    Json(req): Json<RegisterSchemaRequest>,
1197) -> Result<Json<RegisterSchemaResponse>> {
1198    let schema_registry = store.schema_registry();
1199
1200    let response =
1201        schema_registry.register_schema(req.subject, req.schema, req.description, req.tags)?;
1202
1203    tracing::info!(
1204        "📋 Schema registered: v{} for '{}'",
1205        response.version,
1206        response.subject
1207    );
1208
1209    Ok(Json(response))
1210}
1211
1212// v0.5: Get a schema by subject and optional version
1213#[derive(Deserialize)]
1214pub struct GetSchemaParams {
1215    version: Option<u32>,
1216}
1217
1218pub async fn get_schema(
1219    State(store): State<SharedStore>,
1220    Path(subject): Path<String>,
1221    Query(params): Query<GetSchemaParams>,
1222) -> Result<Json<serde_json::Value>> {
1223    let schema_registry = store.schema_registry();
1224
1225    let schema = schema_registry.get_schema(&subject, params.version)?;
1226
1227    tracing::debug!("Retrieved schema v{} for '{}'", schema.version, subject);
1228
1229    Ok(Json(serde_json::json!({
1230        "id": schema.id,
1231        "subject": schema.subject,
1232        "version": schema.version,
1233        "schema": schema.schema,
1234        "created_at": schema.created_at,
1235        "description": schema.description,
1236        "tags": schema.tags
1237    })))
1238}
1239
1240// v0.5: List all versions of a schema subject
1241pub async fn list_schema_versions(
1242    State(store): State<SharedStore>,
1243    Path(subject): Path<String>,
1244) -> Result<Json<serde_json::Value>> {
1245    let schema_registry = store.schema_registry();
1246
1247    let versions = schema_registry.list_versions(&subject)?;
1248
1249    Ok(Json(serde_json::json!({
1250        "subject": subject,
1251        "versions": versions
1252    })))
1253}
1254
1255// v0.5: List all schema subjects
1256pub async fn list_subjects(State(store): State<SharedStore>) -> Json<serde_json::Value> {
1257    let schema_registry = store.schema_registry();
1258
1259    let subjects = schema_registry.list_subjects();
1260
1261    Json(serde_json::json!({
1262        "subjects": subjects,
1263        "total": subjects.len()
1264    }))
1265}
1266
1267// v0.5: Validate an event against a schema
1268pub async fn validate_event_schema(
1269    State(store): State<SharedStore>,
1270    Json(req): Json<ValidateEventRequest>,
1271) -> Result<Json<ValidateEventResponse>> {
1272    let schema_registry = store.schema_registry();
1273
1274    let response = schema_registry.validate(&req.subject, req.version, &req.payload)?;
1275
1276    if response.valid {
1277        tracing::debug!(
1278            "✅ Event validated against schema '{}' v{}",
1279            req.subject,
1280            response.schema_version
1281        );
1282    } else {
1283        tracing::warn!(
1284            "❌ Event validation failed for '{}': {:?}",
1285            req.subject,
1286            response.errors
1287        );
1288    }
1289
1290    Ok(Json(response))
1291}
1292
1293// v0.5: Set compatibility mode for a subject
1294#[derive(Deserialize)]
1295pub struct SetCompatibilityRequest {
1296    compatibility: CompatibilityMode,
1297}
1298
1299pub async fn set_compatibility_mode(
1300    State(store): State<SharedStore>,
1301    Path(subject): Path<String>,
1302    Json(req): Json<SetCompatibilityRequest>,
1303) -> Json<serde_json::Value> {
1304    let schema_registry = store.schema_registry();
1305
1306    schema_registry.set_compatibility_mode(subject.clone(), req.compatibility);
1307
1308    tracing::info!(
1309        "🔧 Set compatibility mode for '{}' to {:?}",
1310        subject,
1311        req.compatibility
1312    );
1313
1314    Json(serde_json::json!({
1315        "subject": subject,
1316        "compatibility": req.compatibility
1317    }))
1318}
1319
1320// v0.5: Start a replay operation
1321pub async fn start_replay(
1322    State(store): State<SharedStore>,
1323    Json(req): Json<StartReplayRequest>,
1324) -> Result<Json<StartReplayResponse>> {
1325    let replay_manager = store.replay_manager();
1326
1327    let response = replay_manager.start_replay(store, req)?;
1328
1329    tracing::info!(
1330        "🔄 Started replay {} with {} events",
1331        response.replay_id,
1332        response.total_events
1333    );
1334
1335    Ok(Json(response))
1336}
1337
1338// v0.5: Get replay progress
1339pub async fn get_replay_progress(
1340    State(store): State<SharedStore>,
1341    Path(replay_id): Path<uuid::Uuid>,
1342) -> Result<Json<ReplayProgress>> {
1343    let replay_manager = store.replay_manager();
1344
1345    let progress = replay_manager.get_progress(replay_id)?;
1346
1347    Ok(Json(progress))
1348}
1349
1350// v0.5: List all replay operations
1351pub async fn list_replays(State(store): State<SharedStore>) -> Json<serde_json::Value> {
1352    let replay_manager = store.replay_manager();
1353
1354    let replays = replay_manager.list_replays();
1355
1356    Json(serde_json::json!({
1357        "replays": replays,
1358        "total": replays.len()
1359    }))
1360}
1361
1362// v0.5: Cancel a running replay
1363pub async fn cancel_replay(
1364    State(store): State<SharedStore>,
1365    Path(replay_id): Path<uuid::Uuid>,
1366) -> Result<Json<serde_json::Value>> {
1367    let replay_manager = store.replay_manager();
1368
1369    replay_manager.cancel_replay(replay_id)?;
1370
1371    tracing::info!("🛑 Cancelled replay {}", replay_id);
1372
1373    Ok(Json(serde_json::json!({
1374        "replay_id": replay_id,
1375        "status": "cancelled"
1376    })))
1377}
1378
1379// v0.5: Delete a completed replay
1380pub async fn delete_replay(
1381    State(store): State<SharedStore>,
1382    Path(replay_id): Path<uuid::Uuid>,
1383) -> Result<Json<serde_json::Value>> {
1384    let replay_manager = store.replay_manager();
1385
1386    let deleted = replay_manager.delete_replay(replay_id)?;
1387
1388    if deleted {
1389        tracing::info!("🗑️  Deleted replay {}", replay_id);
1390    }
1391
1392    Ok(Json(serde_json::json!({
1393        "replay_id": replay_id,
1394        "deleted": deleted
1395    })))
1396}
1397
1398// v0.5: Register a new pipeline
1399pub async fn register_pipeline(
1400    State(store): State<SharedStore>,
1401    Json(config): Json<PipelineConfig>,
1402) -> Result<Json<serde_json::Value>> {
1403    let pipeline_manager = store.pipeline_manager();
1404
1405    let pipeline_id = pipeline_manager.register(config.clone());
1406
1407    tracing::info!(
1408        "🔀 Pipeline registered: {} (name: {})",
1409        pipeline_id,
1410        config.name
1411    );
1412
1413    Ok(Json(serde_json::json!({
1414        "pipeline_id": pipeline_id,
1415        "name": config.name,
1416        "enabled": config.enabled
1417    })))
1418}
1419
1420// v0.5: List all pipelines
1421pub async fn list_pipelines(State(store): State<SharedStore>) -> Json<serde_json::Value> {
1422    let pipeline_manager = store.pipeline_manager();
1423
1424    let pipelines = pipeline_manager.list();
1425
1426    tracing::debug!("Listed {} pipelines", pipelines.len());
1427
1428    Json(serde_json::json!({
1429        "pipelines": pipelines,
1430        "total": pipelines.len()
1431    }))
1432}
1433
1434// v0.5: Get a specific pipeline
1435pub async fn get_pipeline(
1436    State(store): State<SharedStore>,
1437    Path(pipeline_id): Path<uuid::Uuid>,
1438) -> Result<Json<PipelineConfig>> {
1439    let pipeline_manager = store.pipeline_manager();
1440
1441    let pipeline = pipeline_manager.get(pipeline_id).ok_or_else(|| {
1442        crate::error::AllSourceError::ValidationError(format!("Pipeline not found: {pipeline_id}"))
1443    })?;
1444
1445    Ok(Json(pipeline.config().clone()))
1446}
1447
1448// v0.5: Remove a pipeline
1449pub async fn remove_pipeline(
1450    State(store): State<SharedStore>,
1451    Path(pipeline_id): Path<uuid::Uuid>,
1452) -> Result<Json<serde_json::Value>> {
1453    let pipeline_manager = store.pipeline_manager();
1454
1455    let removed = pipeline_manager.remove(pipeline_id);
1456
1457    if removed {
1458        tracing::info!("🗑️  Removed pipeline {}", pipeline_id);
1459    }
1460
1461    Ok(Json(serde_json::json!({
1462        "pipeline_id": pipeline_id,
1463        "removed": removed
1464    })))
1465}
1466
1467// v0.5: Get statistics for all pipelines
1468pub async fn all_pipeline_stats(State(store): State<SharedStore>) -> Json<serde_json::Value> {
1469    let pipeline_manager = store.pipeline_manager();
1470
1471    let stats = pipeline_manager.all_stats();
1472
1473    Json(serde_json::json!({
1474        "stats": stats,
1475        "total": stats.len()
1476    }))
1477}
1478
1479// v0.5: Get statistics for a specific pipeline
1480pub async fn get_pipeline_stats(
1481    State(store): State<SharedStore>,
1482    Path(pipeline_id): Path<uuid::Uuid>,
1483) -> Result<Json<PipelineStats>> {
1484    let pipeline_manager = store.pipeline_manager();
1485
1486    let pipeline = pipeline_manager.get(pipeline_id).ok_or_else(|| {
1487        crate::error::AllSourceError::ValidationError(format!("Pipeline not found: {pipeline_id}"))
1488    })?;
1489
1490    Ok(Json(pipeline.stats()))
1491}
1492
1493// v0.5: Reset a pipeline's state
1494pub async fn reset_pipeline(
1495    State(store): State<SharedStore>,
1496    Path(pipeline_id): Path<uuid::Uuid>,
1497) -> Result<Json<serde_json::Value>> {
1498    let pipeline_manager = store.pipeline_manager();
1499
1500    let pipeline = pipeline_manager.get(pipeline_id).ok_or_else(|| {
1501        crate::error::AllSourceError::ValidationError(format!("Pipeline not found: {pipeline_id}"))
1502    })?;
1503
1504    pipeline.reset();
1505
1506    tracing::info!("🔄 Reset pipeline {}", pipeline_id);
1507
1508    Ok(Json(serde_json::json!({
1509        "pipeline_id": pipeline_id,
1510        "reset": true
1511    })))
1512}
1513
1514// =============================================================================
1515// v0.11: Single Event Lookup by ID
1516// =============================================================================
1517
1518/// Get a single event by UUID
1519pub async fn get_event_by_id(
1520    State(store): State<SharedStore>,
1521    Path(event_id): Path<uuid::Uuid>,
1522) -> Result<Json<serde_json::Value>> {
1523    let event = store.get_event_by_id(&event_id)?.ok_or_else(|| {
1524        crate::error::AllSourceError::EntityNotFound(format!("Event '{event_id}' not found"))
1525    })?;
1526
1527    let dto = EventDto::from(&event);
1528
1529    tracing::debug!("Event retrieved by ID: {}", event_id);
1530
1531    Ok(Json(serde_json::json!({
1532        "event": dto,
1533        "found": true
1534    })))
1535}
1536
1537// =============================================================================
1538// v0.7: Projection State API for Query Service Integration
1539// =============================================================================
1540
1541/// List all registered projections
1542pub async fn list_projections(State(store): State<SharedStore>) -> Json<serde_json::Value> {
1543    let projection_manager = store.projection_manager();
1544    let status_map = store.projection_status();
1545
1546    let projections: Vec<serde_json::Value> = projection_manager
1547        .list_projections()
1548        .iter()
1549        .map(|(name, projection)| {
1550            let status = status_map
1551                .get(name)
1552                .map_or_else(|| "running".to_string(), |s| s.value().clone());
1553            serde_json::json!({
1554                "name": name,
1555                "type": format!("{:?}", projection.name()),
1556                "status": status,
1557            })
1558        })
1559        .collect();
1560
1561    tracing::debug!("Listed {} projections", projections.len());
1562
1563    Json(serde_json::json!({
1564        "projections": projections,
1565        "total": projections.len()
1566    }))
1567}
1568
1569/// Get projection metadata by name
1570pub async fn get_projection(
1571    State(store): State<SharedStore>,
1572    Path(name): Path<String>,
1573) -> Result<Json<serde_json::Value>> {
1574    let projection_manager = store.projection_manager();
1575
1576    let projection = projection_manager.get_projection(&name).ok_or_else(|| {
1577        crate::error::AllSourceError::EntityNotFound(format!("Projection '{name}' not found"))
1578    })?;
1579
1580    Ok(Json(serde_json::json!({
1581        "name": projection.name(),
1582        "found": true
1583    })))
1584}
1585
1586/// Delete (clear) a projection by name
1587///
1588/// Removes all state from the projection. The projection definition remains
1589/// registered but its accumulated state is cleared.
1590pub async fn delete_projection(
1591    State(store): State<SharedStore>,
1592    Path(name): Path<String>,
1593) -> Result<Json<serde_json::Value>> {
1594    let projection_manager = store.projection_manager();
1595
1596    let projection = projection_manager.get_projection(&name).ok_or_else(|| {
1597        crate::error::AllSourceError::EntityNotFound(format!("Projection '{name}' not found"))
1598    })?;
1599
1600    projection.clear();
1601
1602    tracing::info!("Projection deleted (cleared): {}", name);
1603
1604    Ok(Json(serde_json::json!({
1605        "projection": name,
1606        "deleted": true
1607    })))
1608}
1609
1610/// Reset a projection to its initial state
1611///
1612/// Clears all accumulated state and reprocesses events from the beginning.
1613pub async fn reset_projection(
1614    State(store): State<SharedStore>,
1615    Path(name): Path<String>,
1616) -> Result<Json<serde_json::Value>> {
1617    let reprocessed = store.reset_projection(&name)?;
1618
1619    tracing::info!(
1620        "Projection reset: {} ({} events reprocessed)",
1621        name,
1622        reprocessed
1623    );
1624
1625    Ok(Json(serde_json::json!({
1626        "projection": name,
1627        "reset": true,
1628        "events_reprocessed": reprocessed
1629    })))
1630}
1631
1632/// Pause a projection
1633///
1634/// Sets the projection status to "paused" so it stops processing new events.
1635pub async fn pause_projection(
1636    State(store): State<SharedStore>,
1637    Path(name): Path<String>,
1638) -> Result<Json<serde_json::Value>> {
1639    let projection_manager = store.projection_manager();
1640
1641    // Verify projection exists
1642    let _projection = projection_manager.get_projection(&name).ok_or_else(|| {
1643        crate::error::AllSourceError::EntityNotFound(format!("Projection '{name}' not found"))
1644    })?;
1645
1646    store
1647        .projection_status()
1648        .insert(name.clone(), "paused".to_string());
1649
1650    tracing::info!("Projection paused: {}", name);
1651
1652    Ok(Json(serde_json::json!({
1653        "projection": name,
1654        "status": "paused"
1655    })))
1656}
1657
1658/// Start (resume) a projection
1659///
1660/// Sets the projection status to "running" so it resumes processing events.
1661pub async fn start_projection(
1662    State(store): State<SharedStore>,
1663    Path(name): Path<String>,
1664) -> Result<Json<serde_json::Value>> {
1665    let projection_manager = store.projection_manager();
1666
1667    // Verify projection exists
1668    let _projection = projection_manager.get_projection(&name).ok_or_else(|| {
1669        crate::error::AllSourceError::EntityNotFound(format!("Projection '{name}' not found"))
1670    })?;
1671
1672    store
1673        .projection_status()
1674        .insert(name.clone(), "running".to_string());
1675
1676    tracing::info!("Projection started: {}", name);
1677
1678    Ok(Json(serde_json::json!({
1679        "projection": name,
1680        "status": "running"
1681    })))
1682}
1683
1684// =============================================================================
1685// v0.11: Webhook Management API
1686// =============================================================================
1687
1688/// Query parameters for listing webhooks
1689#[derive(Debug, Deserialize)]
1690pub struct ListWebhooksParams {
1691    pub tenant_id: Option<String>,
1692}
1693
1694/// Register a new webhook subscription
1695pub async fn register_webhook(
1696    State(store): State<SharedStore>,
1697    Json(req): Json<RegisterWebhookRequest>,
1698) -> Json<serde_json::Value> {
1699    let registry = store.webhook_registry();
1700    let webhook = registry.register(req);
1701
1702    tracing::info!("Webhook registered: {} -> {}", webhook.id, webhook.url);
1703
1704    Json(serde_json::json!({
1705        "webhook": webhook,
1706        "created": true
1707    }))
1708}
1709
1710/// List webhooks, optionally filtered by tenant_id
1711pub async fn list_webhooks(
1712    State(store): State<SharedStore>,
1713    Query(params): Query<ListWebhooksParams>,
1714) -> Json<serde_json::Value> {
1715    let registry = store.webhook_registry();
1716
1717    let webhooks = if let Some(tenant_id) = params.tenant_id {
1718        registry.list_by_tenant(&tenant_id)
1719    } else {
1720        // Without tenant filter, return empty (tenants should always filter)
1721        vec![]
1722    };
1723
1724    let total = webhooks.len();
1725
1726    Json(serde_json::json!({
1727        "webhooks": webhooks,
1728        "total": total
1729    }))
1730}
1731
1732/// Get a specific webhook by ID
1733pub async fn get_webhook(
1734    State(store): State<SharedStore>,
1735    Path(webhook_id): Path<uuid::Uuid>,
1736) -> Result<Json<serde_json::Value>> {
1737    let registry = store.webhook_registry();
1738
1739    let webhook = registry.get(webhook_id).ok_or_else(|| {
1740        crate::error::AllSourceError::EntityNotFound(format!("Webhook '{webhook_id}' not found"))
1741    })?;
1742
1743    Ok(Json(serde_json::json!({
1744        "webhook": webhook,
1745        "found": true
1746    })))
1747}
1748
1749/// Update a webhook subscription
1750pub async fn update_webhook(
1751    State(store): State<SharedStore>,
1752    Path(webhook_id): Path<uuid::Uuid>,
1753    Json(req): Json<UpdateWebhookRequest>,
1754) -> Result<Json<serde_json::Value>> {
1755    let registry = store.webhook_registry();
1756
1757    let webhook = registry.update(webhook_id, req).ok_or_else(|| {
1758        crate::error::AllSourceError::EntityNotFound(format!("Webhook '{webhook_id}' not found"))
1759    })?;
1760
1761    tracing::info!("Webhook updated: {}", webhook_id);
1762
1763    Ok(Json(serde_json::json!({
1764        "webhook": webhook,
1765        "updated": true
1766    })))
1767}
1768
1769/// Delete a webhook subscription
1770pub async fn delete_webhook(
1771    State(store): State<SharedStore>,
1772    Path(webhook_id): Path<uuid::Uuid>,
1773) -> Result<Json<serde_json::Value>> {
1774    let registry = store.webhook_registry();
1775
1776    let webhook = registry.delete(webhook_id).ok_or_else(|| {
1777        crate::error::AllSourceError::EntityNotFound(format!("Webhook '{webhook_id}' not found"))
1778    })?;
1779
1780    tracing::info!("Webhook deleted: {} ({})", webhook_id, webhook.url);
1781
1782    Ok(Json(serde_json::json!({
1783        "webhook_id": webhook_id,
1784        "deleted": true
1785    })))
1786}
1787
1788/// Query parameters for listing webhook deliveries
1789#[derive(Debug, Deserialize)]
1790pub struct ListDeliveriesParams {
1791    pub limit: Option<usize>,
1792}
1793
1794/// List delivery history for a webhook
1795pub async fn list_webhook_deliveries(
1796    State(store): State<SharedStore>,
1797    Path(webhook_id): Path<uuid::Uuid>,
1798    Query(params): Query<ListDeliveriesParams>,
1799) -> Result<Json<serde_json::Value>> {
1800    let registry = store.webhook_registry();
1801
1802    // Verify webhook exists
1803    registry.get(webhook_id).ok_or_else(|| {
1804        crate::error::AllSourceError::EntityNotFound(format!("Webhook '{webhook_id}' not found"))
1805    })?;
1806
1807    let limit = params.limit.unwrap_or(50);
1808    let deliveries = registry.get_deliveries(webhook_id, limit);
1809    let total = deliveries.len();
1810
1811    Ok(Json(serde_json::json!({
1812        "webhook_id": webhook_id,
1813        "deliveries": deliveries,
1814        "total": total
1815    })))
1816}
1817
1818// =============================================================================
1819// v2.0: Advanced Query Features
1820// =============================================================================
1821
1822/// EventQL: Execute SQL queries over events using DataFusion
1823#[cfg(feature = "analytics")]
1824pub async fn eventql_query(
1825    State(store): State<SharedStore>,
1826    Json(req): Json<crate::infrastructure::query::eventql::EventQLRequest>,
1827) -> Result<Json<serde_json::Value>> {
1828    let events = store.snapshot_events();
1829    match crate::infrastructure::query::eventql::execute_eventql(&events, &req).await {
1830        Ok(response) => Ok(Json(serde_json::json!({
1831            "columns": response.columns,
1832            "rows": response.rows,
1833            "row_count": response.row_count,
1834        }))),
1835        Err(e) => Err(crate::error::AllSourceError::InvalidQuery(e)),
1836    }
1837}
1838
1839/// GraphQL: Execute GraphQL queries
1840pub async fn graphql_query(
1841    State(store): State<SharedStore>,
1842    Json(req): Json<GraphQLRequest>,
1843) -> Json<serde_json::Value> {
1844    let fields = match crate::infrastructure::query::graphql::parse_query(&req.query) {
1845        Ok(f) => f,
1846        Err(e) => {
1847            return Json(
1848                serde_json::to_value(GraphQLResponse {
1849                    data: None,
1850                    errors: vec![GraphQLError { message: e }],
1851                })
1852                .unwrap(),
1853            );
1854        }
1855    };
1856
1857    let mut data = serde_json::Map::new();
1858    let mut errors = Vec::new();
1859
1860    for field in &fields {
1861        match field.name.as_str() {
1862            "events" => {
1863                let request = crate::application::dto::QueryEventsRequest {
1864                    entity_id: field.arguments.get("entity_id").cloned(),
1865                    event_type: field.arguments.get("event_type").cloned(),
1866                    tenant_id: field.arguments.get("tenant_id").cloned(),
1867                    limit: field.arguments.get("limit").and_then(|l| l.parse().ok()),
1868                    as_of: None,
1869                    since: None,
1870                    until: None,
1871                    event_type_prefix: None,
1872                    exclude_event_type_prefix: None,
1873                    payload_filter: None,
1874                };
1875                match store.query(&request) {
1876                    Ok(events) => {
1877                        let json_events: Vec<serde_json::Value> = events
1878                            .iter()
1879                            .map(|e| {
1880                                crate::infrastructure::query::graphql::event_to_json(
1881                                    e,
1882                                    &field.fields,
1883                                )
1884                            })
1885                            .collect();
1886                        data.insert("events".to_string(), serde_json::Value::Array(json_events));
1887                    }
1888                    Err(e) => errors.push(GraphQLError {
1889                        message: format!("events query failed: {e}"),
1890                    }),
1891                }
1892            }
1893            "event" => {
1894                if let Some(id_str) = field.arguments.get("id") {
1895                    if let Ok(id) = uuid::Uuid::parse_str(id_str) {
1896                        match store.get_event_by_id(&id) {
1897                            Ok(Some(event)) => {
1898                                data.insert(
1899                                    "event".to_string(),
1900                                    crate::infrastructure::query::graphql::event_to_json(
1901                                        &event,
1902                                        &field.fields,
1903                                    ),
1904                                );
1905                            }
1906                            Ok(None) => {
1907                                data.insert("event".to_string(), serde_json::Value::Null);
1908                            }
1909                            Err(e) => errors.push(GraphQLError {
1910                                message: format!("event lookup failed: {e}"),
1911                            }),
1912                        }
1913                    } else {
1914                        errors.push(GraphQLError {
1915                            message: format!("Invalid UUID: {id_str}"),
1916                        });
1917                    }
1918                } else {
1919                    errors.push(GraphQLError {
1920                        message: "event query requires 'id' argument".to_string(),
1921                    });
1922                }
1923            }
1924            "projections" => {
1925                let pm = store.projection_manager();
1926                let names: Vec<serde_json::Value> = pm
1927                    .list_projections()
1928                    .iter()
1929                    .map(|(name, _)| serde_json::Value::String(name.clone()))
1930                    .collect();
1931                data.insert("projections".to_string(), serde_json::Value::Array(names));
1932            }
1933            "stats" => {
1934                let stats = store.stats();
1935                data.insert(
1936                    "stats".to_string(),
1937                    serde_json::json!({
1938                        "total_events": stats.total_events,
1939                        "total_entities": stats.total_entities,
1940                        "total_event_types": stats.total_event_types,
1941                    }),
1942                );
1943            }
1944            "__schema" => {
1945                data.insert(
1946                    "__schema".to_string(),
1947                    crate::infrastructure::query::graphql::introspection_schema(),
1948                );
1949            }
1950            other => {
1951                errors.push(GraphQLError {
1952                    message: format!("Unknown field: {other}"),
1953                });
1954            }
1955        }
1956    }
1957
1958    Json(
1959        serde_json::to_value(GraphQLResponse {
1960            data: Some(serde_json::Value::Object(data)),
1961            errors,
1962        })
1963        .unwrap(),
1964    )
1965}
1966
1967/// Geospatial: Query events by location
1968pub async fn geo_query(
1969    State(store): State<SharedStore>,
1970    Json(req): Json<GeoQueryRequest>,
1971) -> Json<serde_json::Value> {
1972    let events = store.snapshot_events();
1973    let geo_index = store.geo_index();
1974    let results =
1975        crate::infrastructure::query::geospatial::execute_geo_query(&events, &geo_index, &req);
1976    let total = results.len();
1977    Json(serde_json::json!({
1978        "results": results,
1979        "total": total,
1980    }))
1981}
1982
1983/// Geospatial index stats
1984pub async fn geo_stats(State(store): State<SharedStore>) -> Json<serde_json::Value> {
1985    let stats = store.geo_index().stats();
1986    Json(serde_json::json!(stats))
1987}
1988
1989/// Exactly-once processing stats
1990pub async fn exactly_once_stats(State(store): State<SharedStore>) -> Json<serde_json::Value> {
1991    let stats = store.exactly_once().stats();
1992    Json(serde_json::json!(stats))
1993}
1994
1995/// Schema evolution history for an event type
1996pub async fn schema_evolution_history(
1997    State(store): State<SharedStore>,
1998    Path(event_type): Path<String>,
1999) -> Json<serde_json::Value> {
2000    let mgr = store.schema_evolution();
2001    let history = mgr.get_history(&event_type);
2002    let version = mgr.get_version(&event_type);
2003    Json(serde_json::json!({
2004        "event_type": event_type,
2005        "current_version": version,
2006        "history": history,
2007    }))
2008}
2009
2010/// Current inferred schema for an event type
2011pub async fn schema_evolution_schema(
2012    State(store): State<SharedStore>,
2013    Path(event_type): Path<String>,
2014) -> Json<serde_json::Value> {
2015    let mgr = store.schema_evolution();
2016    if let Some(schema) = mgr.get_schema(&event_type) {
2017        let json_schema = crate::application::services::schema_evolution::to_json_schema(&schema);
2018        Json(serde_json::json!({
2019            "event_type": event_type,
2020            "version": mgr.get_version(&event_type),
2021            "inferred_schema": schema,
2022            "json_schema": json_schema,
2023        }))
2024    } else {
2025        Json(serde_json::json!({
2026            "event_type": event_type,
2027            "error": "No schema inferred for this event type"
2028        }))
2029    }
2030}
2031
2032/// Schema evolution stats
2033pub async fn schema_evolution_stats(State(store): State<SharedStore>) -> Json<serde_json::Value> {
2034    let stats = store.schema_evolution().stats();
2035    let event_types = store.schema_evolution().list_event_types();
2036    Json(serde_json::json!({
2037        "stats": stats,
2038        "tracked_event_types": event_types,
2039    }))
2040}
2041
2042// =============================================================================
2043// Sync Protocol Endpoints (v0.11: embedded↔server bidirectional sync)
2044// =============================================================================
2045
2046/// POST /api/v1/sync/pull — Client sends version vector, server returns delta events.
2047#[cfg(feature = "embedded-sync")]
2048pub async fn sync_pull_handler(
2049    State(state): State<AppState>,
2050    Json(request): Json<crate::embedded::sync_types::SyncPullRequest>,
2051) -> Result<Json<crate::embedded::sync_types::SyncPullResponse>> {
2052    use crate::infrastructure::cluster::{crdt::ReplicatedEvent, hlc::HlcTimestamp};
2053
2054    let store = &state.store;
2055
2056    // Compute "since" threshold from the client's version vector
2057    // We return all events the client hasn't seen yet
2058    let since = request
2059        .version_vector
2060        .values()
2061        .map(|ts| ts.physical_ms)
2062        .min()
2063        .and_then(|ms| chrono::DateTime::from_timestamp_millis(ms as i64));
2064
2065    let events = store.query(&crate::application::dto::QueryEventsRequest {
2066        entity_id: None,
2067        event_type: None,
2068        tenant_id: None,
2069        as_of: None,
2070        since,
2071        until: None,
2072        limit: None,
2073        event_type_prefix: None,
2074        exclude_event_type_prefix: None,
2075        payload_filter: None,
2076    })?;
2077
2078    // Convert domain events to ReplicatedEvent wire format
2079    let mut replicated = Vec::with_capacity(events.len());
2080    let mut last_ms = 0u64;
2081    let mut logical = 0u32;
2082
2083    for event in &events {
2084        let event_ms = event.timestamp().timestamp_millis() as u64;
2085        if event_ms == last_ms {
2086            logical += 1;
2087        } else {
2088            last_ms = event_ms;
2089            logical = 0;
2090        }
2091
2092        replicated.push(ReplicatedEvent {
2093            event_id: event.id().to_string(),
2094            hlc_timestamp: HlcTimestamp::new(event_ms, logical, 0),
2095            origin_region: "server".to_string(),
2096            event_data: serde_json::json!({
2097                "event_type": event.event_type_str(),
2098                "entity_id": event.entity_id_str(),
2099                "tenant_id": event.tenant_id_str(),
2100                "payload": event.payload,
2101                "metadata": event.metadata,
2102            }),
2103        });
2104    }
2105
2106    Ok(Json(crate::embedded::sync_types::SyncPullResponse {
2107        events: replicated,
2108        version_vector: std::collections::BTreeMap::new(),
2109    }))
2110}
2111
2112/// POST /api/v1/sync/push — Client pushes events, server applies CRDT resolution.
2113#[cfg(feature = "embedded-sync")]
2114pub async fn sync_push_handler(
2115    State(store): State<SharedStore>,
2116    Json(request): Json<crate::embedded::sync_types::SyncPushRequest>,
2117) -> Result<Json<crate::embedded::sync_types::SyncPushResponse>> {
2118    for event in &request.events {
2119        super::read_model_api::protect_ingest(
2120            event
2121                .event_data
2122                .get("event_type")
2123                .and_then(|value| value.as_str())
2124                .unwrap_or("unknown"),
2125            event
2126                .event_data
2127                .get("entity_id")
2128                .and_then(|value| value.as_str())
2129                .unwrap_or("unknown"),
2130        )?;
2131    }
2132
2133    let mut accepted = 0usize;
2134    let mut skipped = 0usize;
2135
2136    for rep_event in &request.events {
2137        let event_data = &rep_event.event_data;
2138        let event_type = event_data
2139            .get("event_type")
2140            .and_then(|v| v.as_str())
2141            .unwrap_or("unknown")
2142            .to_string();
2143        let entity_id = event_data
2144            .get("entity_id")
2145            .and_then(|v| v.as_str())
2146            .unwrap_or("unknown")
2147            .to_string();
2148        let tenant_id = event_data
2149            .get("tenant_id")
2150            .and_then(|v| v.as_str())
2151            .unwrap_or("default")
2152            .to_string();
2153        let payload = event_data
2154            .get("payload")
2155            .cloned()
2156            .unwrap_or(serde_json::json!({}));
2157        let metadata = event_data.get("metadata").cloned();
2158
2159        match Event::from_strings(event_type, entity_id, tenant_id, payload, metadata) {
2160            Ok(domain_event) => {
2161                store.ingest(&domain_event)?;
2162                accepted += 1;
2163            }
2164            Err(_) => {
2165                skipped += 1;
2166            }
2167        }
2168    }
2169
2170    Ok(Json(crate::embedded::sync_types::SyncPushResponse {
2171        accepted,
2172        skipped,
2173        version_vector: std::collections::BTreeMap::new(),
2174    }))
2175}
2176
2177// =============================================================================
2178// Consumer endpoints for durable subscriptions (v0.14)
2179// =============================================================================
2180
2181/// POST /api/v1/consumers — Register a durable consumer
2182pub async fn register_consumer(
2183    State(store): State<SharedStore>,
2184    Json(req): Json<RegisterConsumerRequest>,
2185) -> Result<Json<ConsumerResponse>> {
2186    let consumer = store
2187        .consumer_registry()
2188        .register(&req.consumer_id, &req.event_type_filters);
2189
2190    Ok(Json(ConsumerResponse {
2191        consumer_id: consumer.consumer_id,
2192        event_type_filters: consumer.event_type_filters,
2193        cursor_position: consumer.cursor_position,
2194    }))
2195}
2196
2197/// GET /api/v1/consumers/{consumer_id} — Get consumer metadata and cursor position
2198pub async fn get_consumer(
2199    State(store): State<SharedStore>,
2200    Path(consumer_id): Path<String>,
2201) -> Result<Json<ConsumerResponse>> {
2202    let consumer = store.consumer_registry().get_or_create(&consumer_id);
2203
2204    Ok(Json(ConsumerResponse {
2205        consumer_id: consumer.consumer_id,
2206        event_type_filters: consumer.event_type_filters,
2207        cursor_position: consumer.cursor_position,
2208    }))
2209}
2210
2211/// GET /api/v1/consumers/{consumer_id}/events — Poll for events since last ack
2212#[derive(Debug, Deserialize)]
2213pub struct ConsumerPollQuery {
2214    pub limit: Option<usize>,
2215}
2216
2217pub async fn poll_consumer_events(
2218    State(store): State<SharedStore>,
2219    Path(consumer_id): Path<String>,
2220    Query(query): Query<ConsumerPollQuery>,
2221) -> Result<Json<ConsumerEventsResponse>> {
2222    let consumer = store.consumer_registry().get_or_create(&consumer_id);
2223    let offset = consumer.cursor_position.unwrap_or(0);
2224    let limit = query.limit.unwrap_or(100);
2225
2226    let events = store.events_after_offset(offset, &consumer.event_type_filters, limit);
2227    let count = events.len();
2228
2229    let consumer_events: Vec<ConsumerEventDto> = events
2230        .into_iter()
2231        .map(|(position, event)| ConsumerEventDto {
2232            position,
2233            event: EventDto::from(&event),
2234        })
2235        .collect();
2236
2237    Ok(Json(ConsumerEventsResponse {
2238        events: consumer_events,
2239        count,
2240    }))
2241}
2242
2243/// POST /api/v1/consumers/{consumer_id}/ack — Acknowledge processed events
2244pub async fn ack_consumer(
2245    State(store): State<SharedStore>,
2246    Path(consumer_id): Path<String>,
2247    Json(req): Json<AckRequest>,
2248) -> Result<Json<serde_json::Value>> {
2249    let max_offset = store.total_events() as u64;
2250
2251    store
2252        .consumer_registry()
2253        .ack(&consumer_id, req.position, max_offset)
2254        .map_err(crate::error::AllSourceError::InvalidInput)?;
2255
2256    Ok(Json(serde_json::json!({
2257        "status": "ok",
2258        "consumer_id": consumer_id,
2259        "position": req.position,
2260    })))
2261}
2262
2263#[cfg(test)]
2264mod tests {
2265    use super::*;
2266    use crate::{domain::entities::Event, store::EventStore};
2267
2268    fn create_test_store() -> Arc<EventStore> {
2269        Arc::new(EventStore::new())
2270    }
2271
2272    /// Call the REAL `GET /api/v1/events/query` handler with `query` as the
2273    /// query string, parsed through the same extractors the router uses.
2274    ///
2275    /// Tests that hand the handler DTOs they built themselves cannot see
2276    /// parameters the DTOs never declare (issue #250) and cannot exercise the
2277    /// ordering/windowing composition the handler delegates to the store
2278    /// (issue #251), so ordering and pagination guards go through here.
2279    /// `tenant_id` is defaulted to the one `create_test_event` stamps.
2280    async fn query_page(store: &SharedStore, query: &str) -> QueryEventsResponse {
2281        use axum::extract::{Query, State};
2282
2283        let uri: axum::http::Uri = format!("/api/v1/events/query?tenant_id=test-stream&{query}")
2284            .parse()
2285            .unwrap();
2286        query_events_json(
2287            OptionalAuth(None),
2288            Query::try_from_uri(&uri).unwrap(),
2289            Query::try_from_uri(&uri).unwrap(),
2290            Query::try_from_uri(&uri).unwrap(),
2291            Query::try_from_uri(&uri).unwrap(),
2292            State(store.clone()),
2293        )
2294        .await
2295        .unwrap()
2296        .0
2297    }
2298
2299    fn create_test_event(entity_id: &str, event_type: &str) -> Event {
2300        Event::from_strings(
2301            event_type.to_string(),
2302            entity_id.to_string(),
2303            "test-stream".to_string(),
2304            serde_json::json!({
2305                "name": "Test",
2306                "value": 42
2307            }),
2308            None,
2309        )
2310        .unwrap()
2311    }
2312
2313    #[tokio::test]
2314    async fn test_query_events_has_more_and_total_count() {
2315        let store = create_test_store();
2316
2317        // Ingest 50 events
2318        for i in 0..50 {
2319            store
2320                .ingest(&create_test_event(&format!("entity-{i}"), "user.created"))
2321                .unwrap();
2322        }
2323
2324        // Query with limit=10 — should get has_more=true, total_count=50
2325        let req = QueryEventsRequest {
2326            entity_id: None,
2327            event_type: None,
2328            tenant_id: None,
2329            as_of: None,
2330            since: None,
2331            until: None,
2332            limit: Some(10),
2333            event_type_prefix: None,
2334            exclude_event_type_prefix: None,
2335            payload_filter: None,
2336        };
2337
2338        let requested_limit = req.limit;
2339        let unlimited_req = QueryEventsRequest {
2340            limit: None,
2341            ..QueryEventsRequest {
2342                entity_id: req.entity_id,
2343                event_type: req.event_type,
2344                tenant_id: req.tenant_id,
2345                as_of: req.as_of,
2346                since: req.since,
2347                until: req.until,
2348                limit: None,
2349                event_type_prefix: req.event_type_prefix,
2350                exclude_event_type_prefix: None,
2351                payload_filter: req.payload_filter,
2352            }
2353        };
2354        let all_events = store.query(&unlimited_req).unwrap();
2355        let total_count = all_events.len();
2356        let limited_events: Vec<Event> = if let Some(limit) = requested_limit {
2357            all_events.into_iter().take(limit).collect()
2358        } else {
2359            all_events
2360        };
2361        let count = limited_events.len();
2362        let has_more = count < total_count;
2363
2364        assert_eq!(count, 10);
2365        assert_eq!(total_count, 50);
2366        assert!(has_more);
2367    }
2368
2369    // Regression guard for issue #250: `GET /api/v1/events/query` must honour
2370    // `offset`. It used to be dropped silently (the DTO did not declare it), so
2371    // every page returned the same first `limit` events and `has_more` stayed
2372    // true — the Rust SDK's `EventPaginator` (and the Go SDK's `QueryOptions`)
2373    // both send `offset`, so `collect_all()` looped forever accumulating
2374    // duplicates. Drives the REAL handler through query-string deserialization,
2375    // because the bug lived in the wire layer: a hand-rolled test that builds
2376    // the DTO in code cannot see a field the DTO never declares.
2377    #[tokio::test]
2378    async fn query_events_honours_offset_pagination() {
2379        use axum::extract::{Query, State};
2380
2381        let store = create_test_store();
2382        for i in 0..25 {
2383            store
2384                .ingest(&create_test_event(&format!("e-{i:02}"), "user.created"))
2385                .unwrap();
2386        }
2387
2388        // Parse a real query string through the same extractors the router uses.
2389        async fn page(store: &SharedStore, limit: usize, offset: usize) -> QueryEventsResponse {
2390            let uri: axum::http::Uri =
2391                format!("/api/v1/events/query?tenant_id=test-stream&limit={limit}&offset={offset}")
2392                    .parse()
2393                    .unwrap();
2394            let req: Query<QueryEventsRequest> = Query::try_from_uri(&uri).unwrap();
2395            let order: Query<EventOrderParam> = Query::try_from_uri(&uri).unwrap();
2396            let off: Query<EventOffsetParam> = Query::try_from_uri(&uri).unwrap();
2397            assert_eq!(off.0.offset, Some(offset), "offset must deserialize");
2398            query_events_json(
2399                OptionalAuth(None),
2400                req,
2401                order,
2402                off,
2403                Query::try_from_uri(&uri).unwrap(),
2404                State(store.clone()),
2405            )
2406            .await
2407            .unwrap()
2408            .0
2409        }
2410
2411        let p1 = page(&store, 10, 0).await;
2412        let p2 = page(&store, 10, 10).await;
2413        let p3 = page(&store, 10, 20).await;
2414
2415        assert_eq!(p1.count, 10);
2416        assert_eq!(p2.count, 10);
2417        assert_eq!(p3.count, 5, "last page returns the remainder");
2418        assert_eq!(p1.total_count, 25);
2419
2420        // The core failure: page 2 must not be page 1 again.
2421        let ids = |r: &QueryEventsResponse| -> Vec<String> {
2422            r.events.iter().map(|e| e.entity_id.clone()).collect()
2423        };
2424        assert_ne!(ids(&p1), ids(&p2), "offset=10 must skip the first page");
2425
2426        let mut all = ids(&p1);
2427        all.extend(ids(&p2));
2428        all.extend(ids(&p3));
2429        let unique: std::collections::HashSet<_> = all.iter().cloned().collect();
2430        assert_eq!(
2431            unique.len(),
2432            25,
2433            "paging the whole set must yield 25 distinct entities, not duplicates"
2434        );
2435
2436        // `has_more` must account for the offset, otherwise a paginator that
2437        // trusts it never terminates.
2438        assert!(p1.has_more, "25 events, page 1 of 10 → more remain");
2439        assert!(p2.has_more, "25 events, page 2 of 10 → more remain");
2440        assert!(!p3.has_more, "offset=20 + count=5 == total → exhausted");
2441
2442        // Past the end: empty page, and exhausted rather than "more".
2443        let past = page(&store, 10, 100).await;
2444        assert_eq!(past.count, 0);
2445        assert!(!past.has_more, "offset beyond the match set is exhausted");
2446    }
2447
2448    /// Router carrying the latest-state routes, driven end to end so query
2449    /// parsing, headers and status codes are all exercised.
2450    fn latest_state_app(store: &SharedStore) -> Router {
2451        Router::new()
2452            .route("/api/v1/entities/{entity_id}/state", get(get_entity_state))
2453            .route(
2454                "/api/v1/entities/{entity_id}/snapshot",
2455                get(get_entity_snapshot),
2456            )
2457            .route("/api/v1/events/query", get(query_events))
2458            .with_state(store.clone())
2459    }
2460
2461    async fn send(
2462        app: &Router,
2463        uri: &str,
2464        if_none_match: Option<&str>,
2465    ) -> (axum::http::StatusCode, Option<String>, Vec<u8>) {
2466        use axum::{
2467            body::{Body, to_bytes},
2468            http::{Request, header},
2469        };
2470        use tower::ServiceExt;
2471
2472        let mut request = Request::builder().uri(uri);
2473        if let Some(tag) = if_none_match {
2474            request = request.header(header::IF_NONE_MATCH, tag);
2475        }
2476        let response = app
2477            .clone()
2478            .oneshot(request.body(Body::empty()).unwrap())
2479            .await
2480            .unwrap();
2481        let status = response.status();
2482        let etag = response
2483            .headers()
2484            .get(header::ETAG)
2485            .map(|v| v.to_str().unwrap().to_string());
2486        let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
2487        (status, etag, body.to_vec())
2488    }
2489
2490    fn json_body(body: &[u8]) -> serde_json::Value {
2491        serde_json::from_slice(body).unwrap()
2492    }
2493
2494    #[tokio::test]
2495    async fn entity_state_omits_history_by_default_and_reports_version() {
2496        let store = create_test_store();
2497        for _ in 0..3 {
2498            store
2499                .ingest(&create_test_event("user-1", "user.updated"))
2500                .unwrap();
2501        }
2502        let app = latest_state_app(&store);
2503
2504        for route in ["state", "snapshot"] {
2505            for tenant in ["", "?tenant_id=test-stream"] {
2506                let uri = format!("/api/v1/entities/user-1/{route}{tenant}");
2507                let (status, etag, body) = send(&app, &uri, None).await;
2508                let body = json_body(&body);
2509
2510                assert_eq!(status, axum::http::StatusCode::OK, "GET {uri}");
2511                assert!(etag.is_some(), "GET {uri} must carry an ETag");
2512                assert!(body.get("history").is_none(), "GET {uri}");
2513                assert_eq!(body["event_count"], 3, "GET {uri}");
2514                assert_eq!(body["version"], 3, "GET {uri}");
2515                assert_eq!(body["current_state"]["name"], "Test", "GET {uri}");
2516            }
2517        }
2518    }
2519
2520    #[tokio::test]
2521    async fn entity_state_history_true_restores_history() {
2522        let store = create_test_store();
2523        for _ in 0..2 {
2524            store
2525                .ingest(&create_test_event("user-1", "user.updated"))
2526                .unwrap();
2527        }
2528        let app = latest_state_app(&store);
2529
2530        let (_, _, body) = send(&app, "/api/v1/entities/user-1/state?history=true", None).await;
2531        let body = json_body(&body);
2532
2533        assert_eq!(body["history"].as_array().unwrap().len(), 2);
2534        assert_eq!(body["version"], 2);
2535    }
2536
2537    #[tokio::test]
2538    async fn entity_state_version_counts_only_the_scoped_tenant() {
2539        let store = create_test_store();
2540        store
2541            .ingest(&create_test_event("shared-id", "user.updated"))
2542            .unwrap();
2543        for _ in 0..4 {
2544            store
2545                .ingest(
2546                    &Event::from_strings(
2547                        "user.updated".to_string(),
2548                        "shared-id".to_string(),
2549                        "other-tenant".to_string(),
2550                        serde_json::json!({"name": "Other"}),
2551                        None,
2552                    )
2553                    .unwrap(),
2554                )
2555                .unwrap();
2556        }
2557        let app = latest_state_app(&store);
2558
2559        let (_, _, body) = send(
2560            &app,
2561            "/api/v1/entities/shared-id/state?tenant_id=test-stream",
2562            None,
2563        )
2564        .await;
2565        let body = json_body(&body);
2566
2567        assert_eq!(body["version"], 1);
2568        assert_eq!(body["current_state"]["name"], "Test");
2569    }
2570
2571    #[tokio::test]
2572    async fn entity_state_answers_304_until_the_entity_changes() {
2573        let store = create_test_store();
2574        store
2575            .ingest(&create_test_event("user-1", "user.updated"))
2576            .unwrap();
2577        let app = latest_state_app(&store);
2578        let uri = "/api/v1/entities/user-1/state?tenant_id=test-stream";
2579
2580        let (_, etag, _) = send(&app, uri, None).await;
2581        let etag = etag.unwrap();
2582        let (status, again, body) = send(&app, uri, Some(&etag)).await;
2583        assert_eq!(status, axum::http::StatusCode::NOT_MODIFIED);
2584        assert_eq!(again.as_deref(), Some(etag.as_str()));
2585        assert!(body.is_empty());
2586
2587        store
2588            .ingest(&create_test_event("user-1", "user.updated"))
2589            .unwrap();
2590        let (status, changed, _) = send(&app, uri, Some(&etag)).await;
2591        assert_eq!(status, axum::http::StatusCode::OK);
2592        assert_ne!(changed.as_deref(), Some(etag.as_str()));
2593    }
2594
2595    #[tokio::test]
2596    async fn entity_state_for_unknown_entity_is_404_without_etag() {
2597        let store = create_test_store();
2598        let app = latest_state_app(&store);
2599
2600        let (status, etag, _) = send(&app, "/api/v1/entities/missing/state", None).await;
2601
2602        assert_eq!(status, axum::http::StatusCode::NOT_FOUND);
2603        assert!(etag.is_none());
2604    }
2605
2606    #[tokio::test]
2607    async fn events_query_is_conditional_and_its_tag_is_stable() {
2608        let store = create_test_store();
2609        store
2610            .ingest(&create_test_event("user-1", "user.created"))
2611            .unwrap();
2612        let app = latest_state_app(&store);
2613        let uri = "/api/v1/events/query?tenant_id=test-stream&entity_id=user-1";
2614
2615        let (status, first, body) = send(&app, uri, None).await;
2616        assert_eq!(status, axum::http::StatusCode::OK);
2617        assert_eq!(json_body(&body)["count"], 1);
2618        let (_, second, _) = send(&app, uri, None).await;
2619        assert_eq!(first, second, "an unchanged result must keep its tag");
2620
2621        let first = first.unwrap();
2622        let (status, _, body) = send(&app, uri, Some(&first)).await;
2623        assert_eq!(status, axum::http::StatusCode::NOT_MODIFIED);
2624        assert!(body.is_empty());
2625
2626        let (status, _, _) = send(&app, uri, Some("*")).await;
2627        assert_eq!(status, axum::http::StatusCode::NOT_MODIFIED);
2628    }
2629
2630    // Regression guard for issue #251: a bounded page must cost the page, not the
2631    // whole match set. The handler used to re-run the query with `limit: None`
2632    // just to compute `total_count`, so `?entity_id=E&limit=1&order=desc` — the
2633    // documented "latest event for an entity" read — cloned and sorted the
2634    // entity's entire history on every request.
2635    //
2636    // Cost is measured by counting `Event` CLONES (`crate::clone_probe`), NOT
2637    // with Core's `query_results_total` metric: that counter is incremented with
2638    // `results.len()`, i.e. rows RETURNED, so it reads 1 whether the store
2639    // clones one event or clones 200 and discards 199 — it cannot fail on a
2640    // revert of the store-side windowing. Drives the REAL handler through
2641    // query-string deserialization so the count is what an HTTP caller pays.
2642    #[test]
2643    fn query_events_limit_does_not_materialize_whole_history() {
2644        const HISTORY: usize = 200;
2645
2646        let store = create_test_store();
2647        for _ in 0..HISTORY {
2648            store
2649                .ingest(&create_test_event("entity-hot", "user.updated"))
2650                .unwrap();
2651        }
2652
2653        // `clone_probe` is thread-local, so the handler future is driven to
2654        // completion on THIS thread (current-thread runtime, inside the measured
2655        // closure) — every clone the request makes is therefore counted.
2656        let runtime = tokio::runtime::Builder::new_current_thread()
2657            .enable_all()
2658            .build()
2659            .unwrap();
2660        let (resp, materialized) = crate::clone_probe::measure(|| {
2661            runtime.block_on(query_page(
2662                &store,
2663                "entity_id=entity-hot&limit=1&order=desc",
2664            ))
2665        });
2666
2667        // The page itself stays correct: one event, and the total/has_more pair
2668        // still describes the full match set.
2669        assert_eq!(resp.count, 1);
2670        assert_eq!(resp.events.len(), 1);
2671        assert_eq!(resp.total_count, HISTORY);
2672        assert!(resp.has_more);
2673
2674        assert_eq!(
2675            materialized, 1,
2676            "limit=1 materialized {materialized} events out of {HISTORY}: \
2677             `limit` must bound what a request materializes, not just what it \
2678             returns"
2679        );
2680    }
2681
2682    /// Like [`query_page`] but surfaces the handler's error instead of
2683    /// unwrapping — for the parameter values that must be REJECTED.
2684    async fn query_page_result(
2685        store: &SharedStore,
2686        query: &str,
2687    ) -> Result<Json<QueryEventsResponse>> {
2688        use axum::extract::{Query, State};
2689
2690        let uri: axum::http::Uri = format!("/api/v1/events/query?tenant_id=test-stream&{query}")
2691            .parse()
2692            .unwrap();
2693        query_events_json(
2694            OptionalAuth(None),
2695            Query::try_from_uri(&uri).unwrap(),
2696            Query::try_from_uri(&uri).unwrap(),
2697            Query::try_from_uri(&uri).unwrap(),
2698            Query::try_from_uri(&uri).unwrap(),
2699            State(store.clone()),
2700        )
2701        .await
2702    }
2703
2704    // A filter the server cannot apply must be an ERROR, not silence. The
2705    // payload filter is parsed inside the per-event predicate with `if let
2706    // Ok(..)`, so an unparseable one simply never matched anything and the
2707    // query answered as if no filter had been sent — the caller asked for
2708    // "events where user_id = alice" and got the tenant's whole stream, with a
2709    // `total_count` that agreed. Fails OPEN, which is the dangerous direction
2710    // for a filter, and the endpoint already rejects an unusable `order`, so
2711    // silence here was also inconsistent.
2712    #[tokio::test]
2713    async fn query_events_rejects_a_payload_filter_it_cannot_apply() {
2714        let store = create_test_store();
2715        for name in ["alice", "bob", "carol"] {
2716            let mut event = create_test_event(name, "user.created");
2717            event.payload = serde_json::json!({ "user_id": name });
2718            store.ingest(&event).unwrap();
2719        }
2720
2721        // A well-formed filter still filters — the guard must not reject the
2722        // shape callers actually send (`{"user_id":"alice"}`, percent-encoded).
2723        let ok = query_page(&store, "payload_filter=%7B%22user_id%22%3A%22alice%22%7D").await;
2724        assert_eq!(ok.count, 1, "a valid payload_filter must still work");
2725        assert_eq!(ok.total_count, 1);
2726
2727        for bad in [
2728            "not-json",                    // not JSON at all
2729            "%7B%22user_id%22%3A%22alice", // truncated object
2730            "%5B%22alice%22%5D",           // valid JSON, but an array, not an object
2731            "42",                          // valid JSON, but a scalar
2732        ] {
2733            let result = query_page_result(&store, &format!("payload_filter={bad}")).await;
2734            let Err(err) = result else {
2735                let resp = result.unwrap().0;
2736                panic!(
2737                    "payload_filter={bad} was silently ignored: returned {} of {} \
2738                     events unfiltered instead of rejecting a filter the server \
2739                     cannot apply",
2740                    resp.count, resp.total_count
2741                );
2742            };
2743            assert!(
2744                matches!(err, crate::error::AllSourceError::InvalidInput(_)),
2745                "payload_filter={bad} must be a 400, got {err:?}"
2746            );
2747        }
2748    }
2749
2750    // `order` is the other parameter whose only legal values are a closed set.
2751    // It is validated, but nothing pinned that: collapsing the match to a
2752    // `_ => false` default arm would make `?order=descending` silently return
2753    // OLDEST-first — a paginator would read the wrong end of the stream and
2754    // nothing in the response would say so.
2755    #[tokio::test]
2756    async fn query_events_rejects_an_unusable_order_value() {
2757        let store = create_test_store();
2758        store
2759            .ingest(&create_test_event("e-1", "user.created"))
2760            .unwrap();
2761
2762        for bad in ["descending", "DESCENDING", "newest", "1", "asc%20"] {
2763            let result = query_page_result(&store, &format!("order={bad}")).await;
2764            let Err(err) = result else {
2765                panic!("order={bad} must be rejected, not silently defaulted");
2766            };
2767            assert!(
2768                matches!(err, crate::error::AllSourceError::InvalidInput(_)),
2769                "order={bad} must be a 400, got {err:?}"
2770            );
2771        }
2772
2773        // The accepted spellings stay accepted, in any case.
2774        for good in ["asc", "ASC", "desc", "DeSc"] {
2775            let accepted = query_page_result(&store, &format!("order={good}"))
2776                .await
2777                .unwrap_or_else(|e| panic!("order={good} must be accepted: {e:?}"));
2778            assert_eq!(accepted.0.count, 1, "order={good}");
2779        }
2780    }
2781
2782    // `exclude_event_type_prefix` had no test anywhere in Core — not at this
2783    // handler, not in the store — despite being an HTTP-exposed filter the
2784    // Query Service forwards verbatim, and despite #251 having just rewritten
2785    // the code that decides WHEN it runs relative to the window. Its contract
2786    // is more than "drop these events": the DTO promises exclusion happens
2787    // BEFORE the limit, so excluded events never consume the result window, and
2788    // the prefixes are comma-separated. Both claims are only observable in
2789    // composition with `limit`/`offset`, so this drives the real handler.
2790    #[tokio::test]
2791    async fn query_events_exclude_prefix_applies_before_the_window() {
2792        const TYPES: [&str; 4] = [
2793            "audit.write",
2794            "user.created",
2795            "service.ping",
2796            "user.updated",
2797        ];
2798        let store = create_test_store();
2799        let base = chrono::Utc::now() - chrono::Duration::hours(24);
2800        let mut kept = Vec::new();
2801        for i in 0..12i64 {
2802            let mut event = create_test_event("org-1", TYPES[i as usize % 4]);
2803            event.timestamp = base + chrono::Duration::minutes(i);
2804            event.version = i + 1;
2805            if i % 2 == 1 {
2806                kept.push(event.id);
2807            }
2808            store.ingest(&event).unwrap();
2809        }
2810        assert_eq!(kept.len(), 6, "half the stream is user.*");
2811
2812        // A page of 3 must be 3 SURVIVING events. Excluding after the window
2813        // instead would serve 3 minus however many the page happened to hit —
2814        // here 1 — while still reporting a plausible-looking count.
2815        let page = query_page(
2816            &store,
2817            "exclude_event_type_prefix=audit.,%20service.&limit=3",
2818        )
2819        .await;
2820        assert_eq!(
2821            page.events.iter().map(|e| e.id).collect::<Vec<_>>(),
2822            kept[..3].to_vec(),
2823            "limit=3 must yield 3 non-excluded events: exclusion runs before \
2824             the window, and the prefix list is comma-separated (whitespace \
2825             trimmed)"
2826        );
2827        assert!(
2828            page.events
2829                .iter()
2830                .all(|e| !e.event_type.starts_with("audit.")
2831                    && !e.event_type.starts_with("service.")),
2832            "excluded namespaces must not appear: {:?}",
2833            page.events
2834                .iter()
2835                .map(|e| &e.event_type)
2836                .collect::<Vec<_>>()
2837        );
2838        assert_eq!(
2839            page.total_count, 6,
2840            "total_count is the post-exclusion match set, not the 12 ingested"
2841        );
2842        assert!(page.has_more);
2843
2844        // Paging the excluded view walks the 6 survivors exactly once and stops.
2845        let mut walked = Vec::new();
2846        for offset in [0, 3, 6] {
2847            let p = query_page(
2848                &store,
2849                &format!("exclude_event_type_prefix=audit.,service.&limit=3&offset={offset}"),
2850            )
2851            .await;
2852            assert_eq!(
2853                p.has_more,
2854                offset + p.count < 6,
2855                "has_more must terminate on the excluded view (offset={offset})"
2856            );
2857            walked.extend(p.events.iter().map(|e| e.id));
2858        }
2859        assert_eq!(
2860            walked, kept,
2861            "exclusion + paging must cover the survivors once"
2862        );
2863
2864        // Composes with order=desc: newest survivor first, not newest event.
2865        let desc = query_page(
2866            &store,
2867            "exclude_event_type_prefix=audit.,service.&limit=1&order=desc",
2868        )
2869        .await;
2870        assert_eq!(
2871            desc.events[0].id,
2872            *kept.last().unwrap(),
2873            "order=desc&limit=1 over an excluded view is the newest SURVIVOR"
2874        );
2875
2876        // One prefix excludes only its namespace; a prefix matching nothing
2877        // excludes nothing.
2878        let audit_only = query_page(&store, "exclude_event_type_prefix=audit.").await;
2879        assert_eq!(audit_only.total_count, 9, "12 minus the 3 audit.* events");
2880        let nothing = query_page(&store, "exclude_event_type_prefix=nosuch.").await;
2881        assert_eq!(nothing.total_count, 12);
2882    }
2883
2884    // `since`/`until`/`as_of` must narrow the result set on EVERY query shape,
2885    // including the one no index narrows: scoped by tenant only, which is what
2886    // the gateway forwards for "this tenant's activity since T" (the Query
2887    // Service passes all three straight through — `@core_compat_filters`).
2888    // Those three filters are evaluated against index entries, and the
2889    // full-scan branch of the store never consults the index, so a tenant-only
2890    // query silently ignored the window and answered with the whole history —
2891    // with `total_count`/`has_more` describing that history too, so a paginator
2892    // walked events the caller had explicitly excluded.
2893    //
2894    // Driven through the real handler and real query-string deserialization:
2895    // the parameters exist on the DTO and parse fine, so nothing at the wire
2896    // layer reveals that no code downstream reads them on this path.
2897    #[tokio::test]
2898    async fn query_events_honours_time_window_without_an_entity_or_type_filter() {
2899        use chrono::{SecondsFormat, SubsecRound};
2900
2901        let store = create_test_store();
2902        // FIXED base, not `Utc::now()`, and truncated to whole seconds.
2903        //
2904        // This test previously seeded from `Utc::now()`, which made it depend on
2905        // the host clock's resolution: Linux hands back nanoseconds, macOS does
2906        // not. `SecondsFormat::Micros` truncates DOWNWARDS, so with a
2907        // nanosecond-bearing base the string `until=<t>` names an instant
2908        // fractionally BEFORE the event stamped at `t`, and an inclusive window
2909        // silently drops its boundary event. It passed on every developer
2910        // machine and failed only in CI — the worst kind of flake.
2911        //
2912        // The nanoseconds below are deliberate: they make the round-trip
2913        // assertion in `at` fail loudly if the `trunc_subsecs(0)` is ever
2914        // removed, on every platform rather than only on one.
2915        let base = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00.123456789Z")
2916            .unwrap()
2917            .to_utc()
2918            .trunc_subsecs(0);
2919        let mut ids = Vec::new();
2920        for i in 0..5i64 {
2921            let mut event = create_test_event(&format!("e-{i}"), "user.created");
2922            event.timestamp = base + chrono::Duration::hours(i);
2923            event.version = i + 1;
2924            ids.push(event.id);
2925            store.ingest(&event).unwrap();
2926        }
2927        // `Z`-suffixed so the timestamp survives a query string — an offset of
2928        // `+00:00` would be decoded as a space.
2929        let at = |h: i64| {
2930            let t = base + chrono::Duration::hours(h);
2931            let s = t.to_rfc3339_opts(SecondsFormat::Micros, true);
2932            // Pin the invariant the whole test rests on: the formatted string
2933            // must name the SAME instant the event carries. If a future edit
2934            // drops the `trunc_subsecs(0)` above, this fails on every platform
2935            // rather than only on the ones with a nanosecond clock.
2936            assert_eq!(
2937                chrono::DateTime::parse_from_rfc3339(&s).unwrap().to_utc(),
2938                t,
2939                "query-string timestamp must round-trip exactly, else the window \
2940                 boundary silently excludes the event stamped at it"
2941            );
2942            s
2943        };
2944
2945        for (qs, expected) in [
2946            (format!("since={}", at(2)), vec![ids[2], ids[3], ids[4]]),
2947            (format!("until={}", at(1)), vec![ids[0], ids[1]]),
2948            (format!("as_of={}", at(1)), vec![ids[0], ids[1]]),
2949            (
2950                format!("since={}&until={}", at(1), at(3)),
2951                vec![ids[1], ids[2], ids[3]],
2952            ),
2953        ] {
2954            let resp = query_page(&store, &qs).await;
2955            let got: Vec<_> = resp.events.iter().map(|e| e.id).collect();
2956            assert_eq!(got, expected, "?{qs} must return only the window");
2957            assert_eq!(resp.count, expected.len(), "?{qs}");
2958            assert_eq!(
2959                resp.total_count,
2960                expected.len(),
2961                "?{qs}: total_count must count the window, not the history"
2962            );
2963            assert!(!resp.has_more, "?{qs}: the whole window was served");
2964        }
2965
2966        // The window composes with paging: page 2 of a `since` window is the
2967        // second page OF THAT WINDOW, and `has_more` terminates on it.
2968        let page1 = query_page(&store, &format!("since={}&limit=2", at(2))).await;
2969        let page2 = query_page(&store, &format!("since={}&limit=2&offset=2", at(2))).await;
2970        assert_eq!(
2971            page1.events.iter().map(|e| e.id).collect::<Vec<_>>(),
2972            vec![ids[2], ids[3]]
2973        );
2974        assert!(page1.has_more, "3 in the window, 2 served");
2975        assert_eq!(
2976            page2.events.iter().map(|e| e.id).collect::<Vec<_>>(),
2977            vec![ids[4]]
2978        );
2979        assert!(!page2.has_more, "offset 2 + count 1 == the window's 3");
2980        assert_eq!(page2.total_count, 3);
2981
2982        // …and with `order=desc`.
2983        let desc = query_page(&store, &format!("since={}&order=desc", at(2))).await;
2984        assert_eq!(
2985            desc.events.iter().map(|e| e.id).collect::<Vec<_>>(),
2986            vec![ids[4], ids[3], ids[2]]
2987        );
2988
2989        // An empty window is empty, not "everything".
2990        let empty = query_page(&store, &format!("since={}", at(99))).await;
2991        assert_eq!(empty.count, 0);
2992        assert_eq!(empty.total_count, 0);
2993        assert!(!empty.has_more);
2994    }
2995
2996    // Tenant-isolation gate: the public events query must fail CLOSED — a request
2997    // with no auth context and no tenant_id returns nothing, never a cross-tenant
2998    // scan. Calls the real handler so the boundary check is exercised.
2999    #[tokio::test]
3000    async fn query_events_fails_closed_without_tenant() {
3001        use axum::extract::{Query, State};
3002
3003        let store = create_test_store();
3004        for i in 0..5 {
3005            store
3006                .ingest(&create_test_event(&format!("e-{i}"), "user.created"))
3007                .unwrap();
3008        }
3009
3010        let resp = query_events_json(
3011            OptionalAuth(None),
3012            Query(QueryEventsRequest::default()),
3013            Query(EventOrderParam { order: None }),
3014            Query(EventOffsetParam { offset: None }),
3015            Query(EventIntegrityParam::default()),
3016            State(store.clone()),
3017        )
3018        .await
3019        .unwrap();
3020        assert_eq!(
3021            resp.0.total_count, 0,
3022            "a no-tenant query must NOT return cross-tenant events"
3023        );
3024        assert_eq!(resp.0.count, 0);
3025
3026        // The same query scoped to the events' tenant returns them.
3027        // (create_test_event stamps tenant "test-stream" — the 3rd from_strings arg.)
3028        let scoped = query_events_json(
3029            OptionalAuth(None),
3030            Query(QueryEventsRequest {
3031                tenant_id: Some("test-stream".to_string()),
3032                ..QueryEventsRequest::default()
3033            }),
3034            Query(EventOrderParam { order: None }),
3035            Query(EventOffsetParam { offset: None }),
3036            Query(EventIntegrityParam::default()),
3037            State(store),
3038        )
3039        .await
3040        .unwrap();
3041        assert_eq!(
3042            scoped.0.total_count, 5,
3043            "tenant-scoped query returns its events"
3044        );
3045    }
3046
3047    // The dashboard's streams + event-types counts must be per-tenant. These
3048    // endpoints used to scan ALL tenants (platform totals shown as "yours", and a
3049    // cross-tenant spill). Assert each tenant sees only its own, and no-tenant
3050    // fails closed.
3051    #[tokio::test]
3052    async fn list_streams_and_types_are_tenant_scoped() {
3053        use crate::domain::entities::Event;
3054        use axum::extract::{Query, State};
3055
3056        let store = create_test_store();
3057        let ev = |entity: &str, etype: &str, tenant: &str| {
3058            Event::from_strings(
3059                etype.to_string(),
3060                entity.to_string(),
3061                tenant.to_string(),
3062                serde_json::json!({}),
3063                None,
3064            )
3065            .unwrap()
3066        };
3067        // tenant A: 2 entities, 2 types. tenant B: 1 entity, 1 type.
3068        store.ingest(&ev("e1", "order.placed", "tenant-a")).unwrap();
3069        store.ingest(&ev("e2", "user.created", "tenant-a")).unwrap();
3070        store
3071            .ingest(&ev("e9", "thing.happened", "tenant-b"))
3072            .unwrap();
3073
3074        let streams = |tid: Option<&str>| {
3075            list_streams(
3076                OptionalAuth(None),
3077                State(store.clone()),
3078                Query(ListStreamsParams {
3079                    tenant_id: tid.map(String::from),
3080                    limit: None,
3081                    offset: None,
3082                }),
3083            )
3084        };
3085        assert_eq!(
3086            streams(Some("tenant-a")).await.0.total,
3087            2,
3088            "tenant-a streams"
3089        );
3090        assert_eq!(
3091            streams(Some("tenant-b")).await.0.total,
3092            1,
3093            "tenant-b streams"
3094        );
3095        assert_eq!(
3096            streams(None).await.0.total,
3097            0,
3098            "no tenant -> no streams (fail closed)"
3099        );
3100
3101        let types = |tid: Option<&str>| {
3102            list_event_types(
3103                OptionalAuth(None),
3104                State(store.clone()),
3105                Query(ListEventTypesParams {
3106                    tenant_id: tid.map(String::from),
3107                    limit: None,
3108                    offset: None,
3109                }),
3110            )
3111        };
3112        assert_eq!(
3113            types(Some("tenant-a")).await.0.total,
3114            2,
3115            "tenant-a event types"
3116        );
3117        assert_eq!(
3118            types(Some("tenant-b")).await.0.total,
3119            1,
3120            "tenant-b event types"
3121        );
3122        assert_eq!(
3123            types(None).await.0.total,
3124            0,
3125            "no tenant -> no types (fail closed)"
3126        );
3127    }
3128
3129    #[tokio::test]
3130    async fn test_query_events_no_more_results() {
3131        let store = create_test_store();
3132
3133        // Ingest 5 events
3134        for i in 0..5 {
3135            store
3136                .ingest(&create_test_event(&format!("entity-{i}"), "user.created"))
3137                .unwrap();
3138        }
3139
3140        // Query with limit=100 — should get has_more=false, total_count=5
3141        let all_events = store
3142            .query(&QueryEventsRequest {
3143                entity_id: None,
3144                event_type: None,
3145                tenant_id: None,
3146                as_of: None,
3147                since: None,
3148                until: None,
3149                limit: None,
3150                event_type_prefix: None,
3151                exclude_event_type_prefix: None,
3152                payload_filter: None,
3153            })
3154            .unwrap();
3155        let total_count = all_events.len();
3156        let limited_events: Vec<Event> = all_events.into_iter().take(100).collect();
3157        let count = limited_events.len();
3158        let has_more = count < total_count;
3159
3160        assert_eq!(count, 5);
3161        assert_eq!(total_count, 5);
3162        assert!(!has_more);
3163    }
3164
3165    // Regression test for issue #177: `order=desc` + `limit=1` must return
3166    // the NEWEST event for an entity, not the oldest. Mirrors the ordering
3167    // logic in `query_events` (store.query → reverse-if-desc → take(limit)).
3168    #[tokio::test]
3169    async fn test_query_events_order_desc_returns_latest() {
3170        // Drives the REAL handler. An earlier version of this test rebuilt the
3171        // ordering inline (`ascending.clone(); reverse(); take(1)`) and never
3172        // called `query_events`, so it could not fail on a mis-composition in
3173        // the code that actually serves `order=desc` — which since issue #251
3174        // lives in `EventStore::query_window`, not in the handler.
3175        let store = create_test_store();
3176
3177        // Five events for the same entity with strictly increasing timestamps —
3178        // mimics a backfill appending corrected events.
3179        let base = chrono::Utc::now();
3180        let mut ascending_ids = Vec::new();
3181        for i in 0..5i64 {
3182            let mut event = create_test_event("org-1", "auth.org.updated");
3183            event.timestamp = base + chrono::Duration::seconds(i);
3184            event.version = i + 1;
3185            ascending_ids.push(event.id);
3186            store.ingest(&event).unwrap();
3187        }
3188        let newest_ts = base + chrono::Duration::seconds(4);
3189
3190        // The documented "latest event for an entity" read.
3191        let latest = query_page(&store, "entity_id=org-1&limit=1&order=desc").await;
3192        assert_eq!(latest.count, 1);
3193        assert_eq!(
3194            latest.events[0].id,
3195            ascending_ids[4],
3196            "order=desc&limit=1 must yield the NEWEST event, got the one at \
3197             ascending position {:?}",
3198            ascending_ids
3199                .iter()
3200                .position(|id| *id == latest.events[0].id)
3201        );
3202        assert_eq!(latest.events[0].timestamp, newest_ts);
3203        assert_eq!(latest.total_count, 5, "total is the full match set");
3204        assert!(latest.has_more);
3205
3206        // Default order (and an explicit `asc`) still yields the OLDEST.
3207        for qs in [
3208            "entity_id=org-1&limit=1",
3209            "entity_id=org-1&limit=1&order=asc",
3210        ] {
3211            let oldest = query_page(&store, qs).await;
3212            assert_eq!(oldest.events[0].id, ascending_ids[0], "{qs}");
3213            assert_eq!(oldest.events[0].timestamp, base);
3214        }
3215
3216        // An unbounded desc page is the exact reverse of the ascending one —
3217        // reversal must apply to the whole match set, not just to the page.
3218        let all_desc = query_page(&store, "entity_id=org-1&order=desc").await;
3219        let got: Vec<_> = all_desc.events.iter().map(|e| e.id).collect();
3220        let expected: Vec<_> = ascending_ids.iter().rev().copied().collect();
3221        assert_eq!(got, expected, "order=desc must return newest-first");
3222    }
3223
3224    // Regression guard for issue #251's relocation of the ordering: `order=desc`
3225    // moved out of the handler and into `EventStore::query_window`, where it now
3226    // composes with `offset` and `limit`. The contract is reverse-THEN-skip-THEN-
3227    // take: `order=desc&offset=1&limit=2` is "the 2nd and 3rd newest". Skipping
3228    // before reversing (or reversing only the page) returns a different, quietly
3229    // wrong page — with the same count, total_count and has_more.
3230    #[tokio::test]
3231    async fn query_events_desc_composes_with_offset_and_limit() {
3232        let store = create_test_store();
3233        let base = chrono::Utc::now();
3234        let mut ascending_ids = Vec::new();
3235        for i in 0..5i64 {
3236            let mut event = create_test_event("org-1", "auth.org.updated");
3237            event.timestamp = base + chrono::Duration::seconds(i);
3238            event.version = i + 1;
3239            ascending_ids.push(event.id);
3240            store.ingest(&event).unwrap();
3241        }
3242        let newest_first: Vec<_> = ascending_ids.iter().rev().copied().collect();
3243
3244        for (offset, limit) in [(0, 2), (1, 2), (2, 2), (3, 2), (4, 2), (5, 2), (1, 4)] {
3245            let page = query_page(
3246                &store,
3247                &format!("entity_id=org-1&order=desc&offset={offset}&limit={limit}"),
3248            )
3249            .await;
3250            let got: Vec<_> = page.events.iter().map(|e| e.id).collect();
3251            let expected: Vec<_> = newest_first
3252                .iter()
3253                .skip(offset)
3254                .take(limit)
3255                .copied()
3256                .collect();
3257            assert_eq!(
3258                got, expected,
3259                "order=desc&offset={offset}&limit={limit} must reverse, then \
3260                 skip, then take"
3261            );
3262            assert_eq!(page.count, expected.len());
3263            assert_eq!(page.total_count, 5);
3264            assert_eq!(
3265                page.has_more,
3266                offset + expected.len() < 5,
3267                "has_more must account for the offset (offset={offset})"
3268            );
3269        }
3270
3271        // Walking the whole entity newest-first must visit every event exactly
3272        // once — the property a `order=desc` paginator depends on.
3273        let mut walked = Vec::new();
3274        for offset in (0..5).step_by(2) {
3275            let page = query_page(
3276                &store,
3277                &format!("entity_id=org-1&order=desc&offset={offset}&limit=2"),
3278            )
3279            .await;
3280            walked.extend(page.events.iter().map(|e| e.id));
3281        }
3282        assert_eq!(walked, newest_first, "desc paging must cover the set once");
3283    }
3284
3285    #[tokio::test]
3286    async fn test_list_entities_by_type_prefix() {
3287        let store = create_test_store();
3288
3289        // 3 index entities
3290        store
3291            .ingest(&create_test_event("idx-1", "index.created"))
3292            .unwrap();
3293        store
3294            .ingest(&create_test_event("idx-1", "index.updated"))
3295            .unwrap();
3296        store
3297            .ingest(&create_test_event("idx-2", "index.created"))
3298            .unwrap();
3299        store
3300            .ingest(&create_test_event("idx-3", "index.created"))
3301            .unwrap();
3302        // 2 trade entities
3303        store
3304            .ingest(&create_test_event("trade-1", "trade.created"))
3305            .unwrap();
3306        store
3307            .ingest(&create_test_event("trade-2", "trade.created"))
3308            .unwrap();
3309
3310        // List entities for index.*
3311        let req = ListEntitiesRequest {
3312            event_type_prefix: Some("index.".to_string()),
3313            ..Default::default()
3314        };
3315        let query_req = QueryEventsRequest {
3316            entity_id: None,
3317            event_type: None,
3318            tenant_id: None,
3319            as_of: None,
3320            since: None,
3321            until: None,
3322            limit: None,
3323            event_type_prefix: req.event_type_prefix,
3324            exclude_event_type_prefix: None,
3325            payload_filter: req.payload_filter,
3326        };
3327        let events = store.query(&query_req).unwrap();
3328
3329        // Group and verify
3330        let mut entity_map: std::collections::HashMap<String, Vec<&Event>> =
3331            std::collections::HashMap::new();
3332        for event in &events {
3333            entity_map
3334                .entry(event.entity_id().to_string())
3335                .or_default()
3336                .push(event);
3337        }
3338
3339        assert_eq!(entity_map.len(), 3); // idx-1, idx-2, idx-3
3340        assert_eq!(entity_map["idx-1"].len(), 2); // 2 events for idx-1
3341        assert_eq!(entity_map["idx-2"].len(), 1);
3342        assert_eq!(entity_map["idx-3"].len(), 1);
3343    }
3344
3345    // Issue #178: `list_entities` accepts an `order` param and pages
3346    // deterministically over the resulting sort.
3347    #[tokio::test]
3348    async fn test_list_entities_order_and_pagination() {
3349        let store = create_test_store();
3350
3351        // Three entities with strictly increasing last-event times.
3352        let base = chrono::Utc::now();
3353        for (i, eid) in ["org-a", "org-b", "org-c"].iter().enumerate() {
3354            let mut event = create_test_event(eid, "auth.org.created");
3355            event.timestamp = base + chrono::Duration::seconds(i as i64);
3356            store.ingest(&event).unwrap();
3357        }
3358        let prefix = || Some("auth.org.".to_string());
3359
3360        // Default: newest activity first (desc) — preserves prior behavior.
3361        let desc = list_entities(
3362            State(store.clone()),
3363            Query(ListEntitiesRequest {
3364                event_type_prefix: prefix(),
3365                ..Default::default()
3366            }),
3367        )
3368        .await
3369        .unwrap();
3370        let desc_ids: Vec<&str> = desc
3371            .0
3372            .entities
3373            .iter()
3374            .map(|e| e.entity_id.as_str())
3375            .collect();
3376        assert_eq!(desc_ids, ["org-c", "org-b", "org-a"]);
3377
3378        // order=asc: oldest activity first.
3379        let asc = list_entities(
3380            State(store.clone()),
3381            Query(ListEntitiesRequest {
3382                event_type_prefix: prefix(),
3383                order: Some("asc".to_string()),
3384                ..Default::default()
3385            }),
3386        )
3387        .await
3388        .unwrap();
3389        let asc_ids: Vec<&str> = asc
3390            .0
3391            .entities
3392            .iter()
3393            .map(|e| e.entity_id.as_str())
3394            .collect();
3395        assert_eq!(asc_ids, ["org-a", "org-b", "org-c"]);
3396
3397        // Offset pagination over the deterministic asc order: page 2, size 1.
3398        let page2 = list_entities(
3399            State(store.clone()),
3400            Query(ListEntitiesRequest {
3401                event_type_prefix: prefix(),
3402                order: Some("asc".to_string()),
3403                limit: Some(1),
3404                offset: Some(1),
3405                ..Default::default()
3406            }),
3407        )
3408        .await
3409        .unwrap();
3410        assert_eq!(page2.0.entities.len(), 1);
3411        assert_eq!(page2.0.entities[0].entity_id, "org-b");
3412        assert_eq!(page2.0.total, 3);
3413        assert!(page2.0.has_more);
3414
3415        // Invalid order value is rejected.
3416        let err = list_entities(
3417            State(store.clone()),
3418            Query(ListEntitiesRequest {
3419                event_type_prefix: prefix(),
3420                order: Some("sideways".to_string()),
3421                ..Default::default()
3422            }),
3423        )
3424        .await;
3425        assert!(err.is_err(), "invalid order value must be rejected");
3426    }
3427
3428    fn create_test_event_with_payload(
3429        entity_id: &str,
3430        event_type: &str,
3431        payload: serde_json::Value,
3432    ) -> Event {
3433        Event::from_strings(
3434            event_type.to_string(),
3435            entity_id.to_string(),
3436            "test-stream".to_string(),
3437            payload,
3438            None,
3439        )
3440        .unwrap()
3441    }
3442
3443    #[tokio::test]
3444    async fn test_detect_duplicates_by_payload_fields() {
3445        let store = create_test_store();
3446
3447        // Create entities with duplicate "name" field values
3448        store
3449            .ingest(&create_test_event_with_payload(
3450                "idx-1",
3451                "index.created",
3452                serde_json::json!({"name": "S&P 500", "user_id": "alice"}),
3453            ))
3454            .unwrap();
3455        store
3456            .ingest(&create_test_event_with_payload(
3457                "idx-2",
3458                "index.created",
3459                serde_json::json!({"name": "S&P 500", "user_id": "bob"}),
3460            ))
3461            .unwrap();
3462        store
3463            .ingest(&create_test_event_with_payload(
3464                "idx-3",
3465                "index.created",
3466                serde_json::json!({"name": "NASDAQ", "user_id": "alice"}),
3467            ))
3468            .unwrap();
3469        store
3470            .ingest(&create_test_event_with_payload(
3471                "idx-4",
3472                "index.created",
3473                serde_json::json!({"name": "NASDAQ", "user_id": "carol"}),
3474            ))
3475            .unwrap();
3476        store
3477            .ingest(&create_test_event_with_payload(
3478                "idx-5",
3479                "index.created",
3480                serde_json::json!({"name": "DAX", "user_id": "dave"}),
3481            ))
3482            .unwrap();
3483
3484        // Group by name — should find 2 groups: "S&P 500" (idx-1, idx-2) and "NASDAQ" (idx-3, idx-4)
3485        let query_req = QueryEventsRequest {
3486            entity_id: None,
3487            event_type: None,
3488            tenant_id: None,
3489            as_of: None,
3490            since: None,
3491            until: None,
3492            limit: None,
3493            event_type_prefix: Some("index.".to_string()),
3494            exclude_event_type_prefix: None,
3495            payload_filter: None,
3496        };
3497        let events = store.query(&query_req).unwrap();
3498
3499        // Manually replicate the handler logic for testing
3500        let group_by_fields = vec!["name"];
3501        let mut entity_latest: std::collections::HashMap<String, &Event> =
3502            std::collections::HashMap::new();
3503        for event in &events {
3504            let eid = event.entity_id().to_string();
3505            entity_latest
3506                .entry(eid)
3507                .and_modify(|existing| {
3508                    if event.timestamp() > existing.timestamp() {
3509                        *existing = event;
3510                    }
3511                })
3512                .or_insert(event);
3513        }
3514
3515        let mut groups: std::collections::HashMap<String, Vec<String>> =
3516            std::collections::HashMap::new();
3517        for (entity_id, event) in &entity_latest {
3518            let payload = event.payload();
3519            let mut key_parts = serde_json::Map::new();
3520            for field in &group_by_fields {
3521                let value = payload
3522                    .get(*field)
3523                    .cloned()
3524                    .unwrap_or(serde_json::Value::Null);
3525                key_parts.insert((*field).to_string(), value);
3526            }
3527            let key_str = serde_json::to_string(&key_parts).unwrap_or_default();
3528            groups.entry(key_str).or_default().push(entity_id.clone());
3529        }
3530
3531        let duplicate_groups: Vec<_> = groups
3532            .into_iter()
3533            .filter(|(_, ids)| ids.len() > 1)
3534            .collect();
3535
3536        assert_eq!(duplicate_groups.len(), 2); // S&P 500 and NASDAQ groups
3537        for (_, ids) in &duplicate_groups {
3538            assert_eq!(ids.len(), 2);
3539        }
3540    }
3541
3542    #[tokio::test]
3543    async fn test_detect_duplicates_no_duplicates() {
3544        let store = create_test_store();
3545
3546        // All unique names
3547        store
3548            .ingest(&create_test_event_with_payload(
3549                "idx-1",
3550                "index.created",
3551                serde_json::json!({"name": "A"}),
3552            ))
3553            .unwrap();
3554        store
3555            .ingest(&create_test_event_with_payload(
3556                "idx-2",
3557                "index.created",
3558                serde_json::json!({"name": "B"}),
3559            ))
3560            .unwrap();
3561
3562        let query_req = QueryEventsRequest {
3563            entity_id: None,
3564            event_type: None,
3565            tenant_id: None,
3566            as_of: None,
3567            since: None,
3568            until: None,
3569            limit: None,
3570            event_type_prefix: Some("index.".to_string()),
3571            exclude_event_type_prefix: None,
3572            payload_filter: None,
3573        };
3574        let events = store.query(&query_req).unwrap();
3575
3576        let mut entity_latest: std::collections::HashMap<String, &Event> =
3577            std::collections::HashMap::new();
3578        for event in &events {
3579            entity_latest
3580                .entry(event.entity_id().to_string())
3581                .or_insert(event);
3582        }
3583
3584        let mut groups: std::collections::HashMap<String, Vec<String>> =
3585            std::collections::HashMap::new();
3586        for (entity_id, event) in &entity_latest {
3587            let key_str =
3588                serde_json::to_string(&serde_json::json!({"name": event.payload().get("name")}))
3589                    .unwrap();
3590            groups.entry(key_str).or_default().push(entity_id.clone());
3591        }
3592
3593        let duplicate_groups: Vec<_> = groups
3594            .into_iter()
3595            .filter(|(_, ids)| ids.len() > 1)
3596            .collect();
3597
3598        assert_eq!(duplicate_groups.len(), 0); // No duplicates
3599    }
3600
3601    #[tokio::test]
3602    async fn test_detect_duplicates_multi_field_group_by() {
3603        let store = create_test_store();
3604
3605        // Two entities with same name AND user_id = true duplicate
3606        store
3607            .ingest(&create_test_event_with_payload(
3608                "idx-1",
3609                "index.created",
3610                serde_json::json!({"name": "S&P 500", "user_id": "alice"}),
3611            ))
3612            .unwrap();
3613        store
3614            .ingest(&create_test_event_with_payload(
3615                "idx-2",
3616                "index.created",
3617                serde_json::json!({"name": "S&P 500", "user_id": "alice"}),
3618            ))
3619            .unwrap();
3620        // Same name but different user_id = NOT a duplicate in multi-field group
3621        store
3622            .ingest(&create_test_event_with_payload(
3623                "idx-3",
3624                "index.created",
3625                serde_json::json!({"name": "S&P 500", "user_id": "bob"}),
3626            ))
3627            .unwrap();
3628
3629        let query_req = QueryEventsRequest {
3630            entity_id: None,
3631            event_type: None,
3632            tenant_id: None,
3633            as_of: None,
3634            since: None,
3635            until: None,
3636            limit: None,
3637            event_type_prefix: Some("index.".to_string()),
3638            exclude_event_type_prefix: None,
3639            payload_filter: None,
3640        };
3641        let events = store.query(&query_req).unwrap();
3642
3643        let group_by_fields = vec!["name", "user_id"];
3644        let mut entity_latest: std::collections::HashMap<String, &Event> =
3645            std::collections::HashMap::new();
3646        for event in &events {
3647            entity_latest
3648                .entry(event.entity_id().to_string())
3649                .and_modify(|existing| {
3650                    if event.timestamp() > existing.timestamp() {
3651                        *existing = event;
3652                    }
3653                })
3654                .or_insert(event);
3655        }
3656
3657        let mut groups: std::collections::HashMap<String, Vec<String>> =
3658            std::collections::HashMap::new();
3659        for (entity_id, event) in &entity_latest {
3660            let payload = event.payload();
3661            let mut key_parts = serde_json::Map::new();
3662            for field in &group_by_fields {
3663                let value = payload
3664                    .get(*field)
3665                    .cloned()
3666                    .unwrap_or(serde_json::Value::Null);
3667                key_parts.insert((*field).to_string(), value);
3668            }
3669            let key_str = serde_json::to_string(&key_parts).unwrap_or_default();
3670            groups.entry(key_str).or_default().push(entity_id.clone());
3671        }
3672
3673        let duplicate_groups: Vec<_> = groups
3674            .into_iter()
3675            .filter(|(_, ids)| ids.len() > 1)
3676            .collect();
3677
3678        // Only 1 duplicate group: name=S&P 500, user_id=alice (idx-1, idx-2)
3679        assert_eq!(duplicate_groups.len(), 1);
3680        let (_, ref ids) = duplicate_groups[0];
3681        assert_eq!(ids.len(), 2);
3682        let mut sorted_ids = ids.clone();
3683        sorted_ids.sort();
3684        assert_eq!(sorted_ids, vec!["idx-1", "idx-2"]);
3685    }
3686
3687    #[tokio::test]
3688    async fn test_projection_manager_list_projections() {
3689        let store = create_test_store();
3690
3691        // List projections (built-in projections should be available)
3692        let projection_manager = store.projection_manager();
3693        let projections = projection_manager.list_projections();
3694
3695        // Should have entity_snapshots and event_counters
3696        assert!(projections.len() >= 2);
3697
3698        let names: Vec<&str> = projections.iter().map(|(name, _)| name.as_str()).collect();
3699        assert!(names.contains(&"entity_snapshots"));
3700        assert!(names.contains(&"event_counters"));
3701    }
3702
3703    #[tokio::test]
3704    async fn test_projection_state_after_event_ingestion() {
3705        let store = create_test_store();
3706
3707        // Ingest an event
3708        let event = create_test_event("user-456", "user.created");
3709        store.ingest(&event).unwrap();
3710
3711        // Get projection state
3712        let projection_manager = store.projection_manager();
3713        let snapshot_projection = projection_manager
3714            .get_projection("entity_snapshots")
3715            .unwrap();
3716
3717        let state = snapshot_projection.get_state("user-456");
3718        assert!(state.is_some());
3719        let state = state.unwrap();
3720        assert_eq!(state["name"], "Test");
3721        assert_eq!(state["value"], 42);
3722    }
3723
3724    #[tokio::test]
3725    async fn test_event_counter_projection() {
3726        let store = create_test_store();
3727
3728        // Ingest events of different types
3729        store
3730            .ingest(&create_test_event("user-1", "user.created"))
3731            .unwrap();
3732        store
3733            .ingest(&create_test_event("user-2", "user.created"))
3734            .unwrap();
3735        store
3736            .ingest(&create_test_event("user-1", "user.updated"))
3737            .unwrap();
3738
3739        // Get event counter projection
3740        let projection_manager = store.projection_manager();
3741        let counter_projection = projection_manager.get_projection("event_counters").unwrap();
3742
3743        // Check counts
3744        let created_state = counter_projection.get_state("user.created");
3745        assert!(created_state.is_some());
3746        assert_eq!(created_state.unwrap()["count"], 2);
3747
3748        let updated_state = counter_projection.get_state("user.updated");
3749        assert!(updated_state.is_some());
3750        assert_eq!(updated_state.unwrap()["count"], 1);
3751    }
3752
3753    #[tokio::test]
3754    async fn test_get_nonexistent_projection() {
3755        let store = create_test_store();
3756        let projection_manager = store.projection_manager();
3757
3758        // Requesting a non-existent projection should return None
3759        let projection = projection_manager.get_projection("nonexistent_projection");
3760        assert!(projection.is_none());
3761    }
3762
3763    #[tokio::test]
3764    async fn test_get_nonexistent_entity_state() {
3765        let store = create_test_store();
3766        let projection_manager = store.projection_manager();
3767
3768        // Get state for non-existent entity
3769        let snapshot_projection = projection_manager
3770            .get_projection("entity_snapshots")
3771            .unwrap();
3772        let state = snapshot_projection.get_state("nonexistent-entity-xyz");
3773        assert!(state.is_none());
3774    }
3775
3776    #[tokio::test]
3777    async fn test_projection_manager_get_entity_snapshots() {
3778        let store = create_test_store();
3779        let projection_manager = store.projection_manager();
3780
3781        // Get entity_snapshots projection specifically
3782        let projection = projection_manager.get_projection("entity_snapshots");
3783        assert!(projection.is_some());
3784        assert_eq!(projection.unwrap().name(), "entity_snapshots");
3785    }
3786
3787    #[tokio::test]
3788    async fn test_projection_manager_get_event_counters() {
3789        let store = create_test_store();
3790        let projection_manager = store.projection_manager();
3791
3792        // Get event_counters projection specifically
3793        let projection = projection_manager.get_projection("event_counters");
3794        assert!(projection.is_some());
3795        assert_eq!(projection.unwrap().name(), "event_counters");
3796    }
3797
3798    #[tokio::test]
3799    async fn test_bulk_projection_state_access() {
3800        let store = create_test_store();
3801
3802        // Ingest multiple events for different entities
3803        for i in 0..5 {
3804            let event = create_test_event(&format!("bulk-user-{i}"), "user.created");
3805            store.ingest(&event).unwrap();
3806        }
3807
3808        // Get projection and verify bulk access
3809        let projection_manager = store.projection_manager();
3810        let snapshot_projection = projection_manager
3811            .get_projection("entity_snapshots")
3812            .unwrap();
3813
3814        // Verify we can access all entities
3815        for i in 0..5 {
3816            let state = snapshot_projection.get_state(&format!("bulk-user-{i}"));
3817            assert!(state.is_some(), "Entity bulk-user-{i} should have state");
3818        }
3819    }
3820
3821    /// Pins the poll wire shape the Rust SDK's `poll_consumer_events` decodes:
3822    /// `ConsumerEventDto` flattens the event, so its fields sit next to
3823    /// `position` rather than nested under an `event` key.
3824    #[tokio::test]
3825    async fn poll_consumer_events_flattens_event_alongside_position() {
3826        let store = create_test_store();
3827        store
3828            .ingest(&create_test_event("user-1", "user.created"))
3829            .unwrap();
3830        store
3831            .ingest(&create_test_event("user-2", "user.updated"))
3832            .unwrap();
3833        store.consumer_registry().register("w1", &[]);
3834
3835        let resp = poll_consumer_events(
3836            State(Arc::clone(&store)),
3837            Path("w1".to_string()),
3838            Query(ConsumerPollQuery { limit: Some(10) }),
3839        )
3840        .await
3841        .unwrap();
3842
3843        let body = serde_json::to_value(&resp.0).unwrap();
3844        assert_eq!(body["count"], 2);
3845        let first = &body["events"][0];
3846        assert_eq!(first["position"], 1);
3847        assert!(
3848            first.get("event").is_none(),
3849            "event must be flattened, not nested: got {first:?}"
3850        );
3851        assert_eq!(first["event_type"], "user.created");
3852        assert_eq!(first["entity_id"], "user-1");
3853    }
3854}