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