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