Skip to main content

allsource_core/infrastructure/web/
api.rs

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