Skip to main content

allsource_core/infrastructure/web/
api.rs

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