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    // `total_compactions` counts this process only, so it cannot distinguish
1253    // "never ran" from "ran, then restarted". Staleness survives a restart and
1254    // is what an alarm can read (gh#321).
1255    let last_compaction = compaction_manager.last_compaction();
1256    let seconds_since_last_compaction =
1257        last_compaction.map(|at| (chrono::Utc::now() - at).num_seconds().max(0));
1258
1259    Ok(Json(serde_json::json!({
1260        "stats": stats,
1261        "last_compaction_at": last_compaction,
1262        "seconds_since_last_compaction": seconds_since_last_compaction,
1263        "sweep_cursor": compaction_manager.sweep_cursor(),
1264        "last_sweep_paused": compaction_manager.last_sweep_paused(),
1265        "config": {
1266            "min_files_to_compact": config.min_files_to_compact,
1267            "target_file_size": config.target_file_size,
1268            "max_file_size": config.max_file_size,
1269            "small_file_threshold": config.small_file_threshold,
1270            "compaction_interval_seconds": config.compaction_interval_seconds,
1271            "auto_compact": config.auto_compact,
1272            "strategy": config.strategy
1273        }
1274    })))
1275}
1276
1277// v0.5: Register a new schema
1278pub async fn register_schema(
1279    State(store): State<SharedStore>,
1280    Json(req): Json<RegisterSchemaRequest>,
1281) -> Result<Json<RegisterSchemaResponse>> {
1282    let schema_registry = store.schema_registry();
1283
1284    let response =
1285        schema_registry.register_schema(req.subject, req.schema, req.description, req.tags)?;
1286
1287    tracing::info!(
1288        "📋 Schema registered: v{} for '{}'",
1289        response.version,
1290        response.subject
1291    );
1292
1293    Ok(Json(response))
1294}
1295
1296// v0.5: Get a schema by subject and optional version
1297#[derive(Deserialize)]
1298pub struct GetSchemaParams {
1299    version: Option<u32>,
1300}
1301
1302pub async fn get_schema(
1303    State(store): State<SharedStore>,
1304    Path(subject): Path<String>,
1305    Query(params): Query<GetSchemaParams>,
1306) -> Result<Json<serde_json::Value>> {
1307    let schema_registry = store.schema_registry();
1308
1309    let schema = schema_registry.get_schema(&subject, params.version)?;
1310
1311    tracing::debug!("Retrieved schema v{} for '{}'", schema.version, subject);
1312
1313    Ok(Json(serde_json::json!({
1314        "id": schema.id,
1315        "subject": schema.subject,
1316        "version": schema.version,
1317        "schema": schema.schema,
1318        "created_at": schema.created_at,
1319        "description": schema.description,
1320        "tags": schema.tags
1321    })))
1322}
1323
1324// v0.5: List all versions of a schema subject
1325pub async fn list_schema_versions(
1326    State(store): State<SharedStore>,
1327    Path(subject): Path<String>,
1328) -> Result<Json<serde_json::Value>> {
1329    let schema_registry = store.schema_registry();
1330
1331    let versions = schema_registry.list_versions(&subject)?;
1332
1333    Ok(Json(serde_json::json!({
1334        "subject": subject,
1335        "versions": versions
1336    })))
1337}
1338
1339// v0.5: List all schema subjects
1340pub async fn list_subjects(State(store): State<SharedStore>) -> Json<serde_json::Value> {
1341    let schema_registry = store.schema_registry();
1342
1343    let subjects = schema_registry.list_subjects();
1344
1345    Json(serde_json::json!({
1346        "subjects": subjects,
1347        "total": subjects.len()
1348    }))
1349}
1350
1351// v0.5: Validate an event against a schema
1352pub async fn validate_event_schema(
1353    State(store): State<SharedStore>,
1354    Json(req): Json<ValidateEventRequest>,
1355) -> Result<Json<ValidateEventResponse>> {
1356    let schema_registry = store.schema_registry();
1357
1358    let response = schema_registry.validate(&req.subject, req.version, &req.payload)?;
1359
1360    if response.valid {
1361        tracing::debug!(
1362            "✅ Event validated against schema '{}' v{}",
1363            req.subject,
1364            response.schema_version
1365        );
1366    } else {
1367        tracing::warn!(
1368            "❌ Event validation failed for '{}': {:?}",
1369            req.subject,
1370            response.errors
1371        );
1372    }
1373
1374    Ok(Json(response))
1375}
1376
1377// v0.5: Set compatibility mode for a subject
1378#[derive(Deserialize)]
1379pub struct SetCompatibilityRequest {
1380    compatibility: CompatibilityMode,
1381}
1382
1383pub async fn set_compatibility_mode(
1384    State(store): State<SharedStore>,
1385    Path(subject): Path<String>,
1386    Json(req): Json<SetCompatibilityRequest>,
1387) -> Json<serde_json::Value> {
1388    let schema_registry = store.schema_registry();
1389
1390    schema_registry.set_compatibility_mode(subject.clone(), req.compatibility);
1391
1392    tracing::info!(
1393        "🔧 Set compatibility mode for '{}' to {:?}",
1394        subject,
1395        req.compatibility
1396    );
1397
1398    Json(serde_json::json!({
1399        "subject": subject,
1400        "compatibility": req.compatibility
1401    }))
1402}
1403
1404// v0.5: Start a replay operation
1405pub async fn start_replay(
1406    State(store): State<SharedStore>,
1407    Json(req): Json<StartReplayRequest>,
1408) -> Result<Json<StartReplayResponse>> {
1409    let replay_manager = store.replay_manager();
1410
1411    let response = replay_manager.start_replay(store, req)?;
1412
1413    tracing::info!(
1414        "🔄 Started replay {} with {} events",
1415        response.replay_id,
1416        response.total_events
1417    );
1418
1419    Ok(Json(response))
1420}
1421
1422// v0.5: Get replay progress
1423pub async fn get_replay_progress(
1424    State(store): State<SharedStore>,
1425    Path(replay_id): Path<uuid::Uuid>,
1426) -> Result<Json<ReplayProgress>> {
1427    let replay_manager = store.replay_manager();
1428
1429    let progress = replay_manager.get_progress(replay_id)?;
1430
1431    Ok(Json(progress))
1432}
1433
1434// v0.5: List all replay operations
1435pub async fn list_replays(State(store): State<SharedStore>) -> Json<serde_json::Value> {
1436    let replay_manager = store.replay_manager();
1437
1438    let replays = replay_manager.list_replays();
1439
1440    Json(serde_json::json!({
1441        "replays": replays,
1442        "total": replays.len()
1443    }))
1444}
1445
1446// v0.5: Cancel a running replay
1447pub async fn cancel_replay(
1448    State(store): State<SharedStore>,
1449    Path(replay_id): Path<uuid::Uuid>,
1450) -> Result<Json<serde_json::Value>> {
1451    let replay_manager = store.replay_manager();
1452
1453    replay_manager.cancel_replay(replay_id)?;
1454
1455    tracing::info!("🛑 Cancelled replay {}", replay_id);
1456
1457    Ok(Json(serde_json::json!({
1458        "replay_id": replay_id,
1459        "status": "cancelled"
1460    })))
1461}
1462
1463// v0.5: Delete a completed replay
1464pub async fn delete_replay(
1465    State(store): State<SharedStore>,
1466    Path(replay_id): Path<uuid::Uuid>,
1467) -> Result<Json<serde_json::Value>> {
1468    let replay_manager = store.replay_manager();
1469
1470    let deleted = replay_manager.delete_replay(replay_id)?;
1471
1472    if deleted {
1473        tracing::info!("🗑️  Deleted replay {}", replay_id);
1474    }
1475
1476    Ok(Json(serde_json::json!({
1477        "replay_id": replay_id,
1478        "deleted": deleted
1479    })))
1480}
1481
1482// v0.5: Register a new pipeline
1483pub async fn register_pipeline(
1484    State(store): State<SharedStore>,
1485    Json(config): Json<PipelineConfig>,
1486) -> Result<Json<serde_json::Value>> {
1487    let pipeline_manager = store.pipeline_manager();
1488
1489    let pipeline_id = pipeline_manager.register(config.clone());
1490
1491    tracing::info!(
1492        "🔀 Pipeline registered: {} (name: {})",
1493        pipeline_id,
1494        config.name
1495    );
1496
1497    Ok(Json(serde_json::json!({
1498        "pipeline_id": pipeline_id,
1499        "name": config.name,
1500        "enabled": config.enabled
1501    })))
1502}
1503
1504// v0.5: List all pipelines
1505pub async fn list_pipelines(State(store): State<SharedStore>) -> Json<serde_json::Value> {
1506    let pipeline_manager = store.pipeline_manager();
1507
1508    let pipelines = pipeline_manager.list();
1509
1510    tracing::debug!("Listed {} pipelines", pipelines.len());
1511
1512    Json(serde_json::json!({
1513        "pipelines": pipelines,
1514        "total": pipelines.len()
1515    }))
1516}
1517
1518// v0.5: Get a specific pipeline
1519pub async fn get_pipeline(
1520    State(store): State<SharedStore>,
1521    Path(pipeline_id): Path<uuid::Uuid>,
1522) -> Result<Json<PipelineConfig>> {
1523    let pipeline_manager = store.pipeline_manager();
1524
1525    let pipeline = pipeline_manager.get(pipeline_id).ok_or_else(|| {
1526        crate::error::AllSourceError::ValidationError(format!("Pipeline not found: {pipeline_id}"))
1527    })?;
1528
1529    Ok(Json(pipeline.config().clone()))
1530}
1531
1532// v0.5: Remove a pipeline
1533pub async fn remove_pipeline(
1534    State(store): State<SharedStore>,
1535    Path(pipeline_id): Path<uuid::Uuid>,
1536) -> Result<Json<serde_json::Value>> {
1537    let pipeline_manager = store.pipeline_manager();
1538
1539    let removed = pipeline_manager.remove(pipeline_id);
1540
1541    if removed {
1542        tracing::info!("🗑️  Removed pipeline {}", pipeline_id);
1543    }
1544
1545    Ok(Json(serde_json::json!({
1546        "pipeline_id": pipeline_id,
1547        "removed": removed
1548    })))
1549}
1550
1551// v0.5: Get statistics for all pipelines
1552pub async fn all_pipeline_stats(State(store): State<SharedStore>) -> Json<serde_json::Value> {
1553    let pipeline_manager = store.pipeline_manager();
1554
1555    let stats = pipeline_manager.all_stats();
1556
1557    Json(serde_json::json!({
1558        "stats": stats,
1559        "total": stats.len()
1560    }))
1561}
1562
1563// v0.5: Get statistics for a specific pipeline
1564pub async fn get_pipeline_stats(
1565    State(store): State<SharedStore>,
1566    Path(pipeline_id): Path<uuid::Uuid>,
1567) -> Result<Json<PipelineStats>> {
1568    let pipeline_manager = store.pipeline_manager();
1569
1570    let pipeline = pipeline_manager.get(pipeline_id).ok_or_else(|| {
1571        crate::error::AllSourceError::ValidationError(format!("Pipeline not found: {pipeline_id}"))
1572    })?;
1573
1574    Ok(Json(pipeline.stats()))
1575}
1576
1577// v0.5: Reset a pipeline's state
1578pub async fn reset_pipeline(
1579    State(store): State<SharedStore>,
1580    Path(pipeline_id): Path<uuid::Uuid>,
1581) -> Result<Json<serde_json::Value>> {
1582    let pipeline_manager = store.pipeline_manager();
1583
1584    let pipeline = pipeline_manager.get(pipeline_id).ok_or_else(|| {
1585        crate::error::AllSourceError::ValidationError(format!("Pipeline not found: {pipeline_id}"))
1586    })?;
1587
1588    pipeline.reset();
1589
1590    tracing::info!("🔄 Reset pipeline {}", pipeline_id);
1591
1592    Ok(Json(serde_json::json!({
1593        "pipeline_id": pipeline_id,
1594        "reset": true
1595    })))
1596}
1597
1598// =============================================================================
1599// v0.11: Single Event Lookup by ID
1600// =============================================================================
1601
1602/// Get a single event by UUID
1603pub async fn get_event_by_id(
1604    State(store): State<SharedStore>,
1605    Path(event_id): Path<uuid::Uuid>,
1606) -> Result<Json<serde_json::Value>> {
1607    let event = store.get_event_by_id(&event_id)?.ok_or_else(|| {
1608        crate::error::AllSourceError::EntityNotFound(format!("Event '{event_id}' not found"))
1609    })?;
1610
1611    let dto = EventDto::from(&event);
1612
1613    tracing::debug!("Event retrieved by ID: {}", event_id);
1614
1615    Ok(Json(serde_json::json!({
1616        "event": dto,
1617        "found": true
1618    })))
1619}
1620
1621// =============================================================================
1622// v0.7: Projection State API for Query Service Integration
1623// =============================================================================
1624
1625/// List all registered projections
1626pub async fn list_projections(State(store): State<SharedStore>) -> Json<serde_json::Value> {
1627    let projection_manager = store.projection_manager();
1628    let status_map = store.projection_status();
1629
1630    let projections: Vec<serde_json::Value> = projection_manager
1631        .list_projections()
1632        .iter()
1633        .map(|(name, projection)| {
1634            let status = status_map
1635                .get(name)
1636                .map_or_else(|| "running".to_string(), |s| s.value().clone());
1637            serde_json::json!({
1638                "name": name,
1639                "type": format!("{:?}", projection.name()),
1640                "status": status,
1641            })
1642        })
1643        .collect();
1644
1645    tracing::debug!("Listed {} projections", projections.len());
1646
1647    Json(serde_json::json!({
1648        "projections": projections,
1649        "total": projections.len()
1650    }))
1651}
1652
1653/// Get projection metadata by name
1654pub async fn get_projection(
1655    State(store): State<SharedStore>,
1656    Path(name): Path<String>,
1657) -> Result<Json<serde_json::Value>> {
1658    let projection_manager = store.projection_manager();
1659
1660    let projection = projection_manager.get_projection(&name).ok_or_else(|| {
1661        crate::error::AllSourceError::EntityNotFound(format!("Projection '{name}' not found"))
1662    })?;
1663
1664    Ok(Json(serde_json::json!({
1665        "name": projection.name(),
1666        "found": true
1667    })))
1668}
1669
1670/// Get projection state for a specific entity.
1671///
1672/// Resolution order:
1673/// 1. **Registered projection** — if `name` is registered with the projection
1674///    manager, return the projection's own `get_state(entity_id)` output.
1675/// 2. **Projection state cache** — otherwise fall back to whatever was written
1676///    via `save_projection_state` / `bulk_save_projection_states`. This supports
1677///    SDK-managed projections (e.g. the Rust SDK's `ProjectionWorker`) that
1678///    compute state client-side and push it back without registering a
1679///    projection in Core's manager.
1680///
1681/// Returns `found: false` with `state: null` when neither source has state.
1682pub async fn get_projection_state(
1683    State(store): State<SharedStore>,
1684    Path((name, entity_id)): Path<(String, String)>,
1685) -> Result<Json<serde_json::Value>> {
1686    let state = store
1687        .projection_manager()
1688        .get_projection(&name)
1689        .and_then(|p| p.get_state(&entity_id))
1690        .or_else(|| {
1691            store
1692                .projection_state_cache()
1693                .get(&format!("{name}:{entity_id}"))
1694                .map(|entry| entry.value().clone())
1695        });
1696
1697    tracing::debug!("Projection state retrieved: {} / {}", name, entity_id);
1698
1699    Ok(Json(serde_json::json!({
1700        "projection": name,
1701        "entity_id": entity_id,
1702        "state": state,
1703        "found": state.is_some()
1704    })))
1705}
1706
1707/// Delete (clear) a projection by name
1708///
1709/// Removes all state from the projection. The projection definition remains
1710/// registered but its accumulated state is cleared.
1711pub async fn delete_projection(
1712    State(store): State<SharedStore>,
1713    Path(name): Path<String>,
1714) -> Result<Json<serde_json::Value>> {
1715    let projection_manager = store.projection_manager();
1716
1717    let projection = projection_manager.get_projection(&name).ok_or_else(|| {
1718        crate::error::AllSourceError::EntityNotFound(format!("Projection '{name}' not found"))
1719    })?;
1720
1721    projection.clear();
1722
1723    // Also clear any cached state for this projection
1724    let cache = store.projection_state_cache();
1725    let prefix = format!("{name}:");
1726    let keys_to_remove: Vec<String> = cache
1727        .iter()
1728        .filter(|entry| entry.key().starts_with(&prefix))
1729        .map(|entry| entry.key().clone())
1730        .collect();
1731    for key in keys_to_remove {
1732        cache.remove(&key);
1733    }
1734
1735    tracing::info!("Projection deleted (cleared): {}", name);
1736
1737    Ok(Json(serde_json::json!({
1738        "projection": name,
1739        "deleted": true
1740    })))
1741}
1742
1743/// Query parameters for `GET /api/v1/projections/{name}/state`.
1744///
1745/// All optional: with none of them set the endpoint keeps its historical
1746/// behaviour of returning every cached entity for the projection, so existing
1747/// callers (the Query Service's `ProjectionServer` hydration, the SDKs) are
1748/// unaffected. Names match `ListEntitiesRequest` for consistency.
1749#[derive(Debug, Default, Deserialize)]
1750pub struct ProjectionStateSummaryParams {
1751    /// Maximum number of entity states to return. Unbounded when absent.
1752    pub limit: Option<usize>,
1753    /// Number of matching states to skip before applying `limit`. Default 0.
1754    pub offset: Option<usize>,
1755    /// Return only entities whose id starts with this prefix — lets a caller
1756    /// walk one shard of the keyspace without enumerating the whole projection.
1757    pub entity_id_prefix: Option<String>,
1758}
1759
1760/// Get aggregate projection state (all entities).
1761///
1762/// Returns the cached states written via `save_projection_state` /
1763/// `bulk_save_projection_states`. The projection does NOT need to be
1764/// registered with the projection manager — this supports SDK-managed
1765/// projections that push state without server-side registration.
1766///
1767/// Supports `limit`, `offset` and `entity_id_prefix` (issue #249): this is the
1768/// only endpoint that can *enumerate* a projection — `bulk_get_projection_states`
1769/// needs the ids up front — so a projection with one entry per tenant needs a
1770/// way to bound and resume a request. Entities are ordered by `entity_id` so
1771/// offset paging is stable; `total` is the full match set and `has_more` tells
1772/// a paginator when to stop.
1773///
1774/// Returns an empty list when no state has been written.
1775pub async fn get_projection_state_summary(
1776    State(store): State<SharedStore>,
1777    Path(name): Path<String>,
1778    Query(params): Query<ProjectionStateSummaryParams>,
1779) -> Result<Json<serde_json::Value>> {
1780    let cache = store.projection_state_cache();
1781    let prefix = format!("{name}:");
1782    let offset = params.offset.unwrap_or(0);
1783
1784    // Collect the matching keys first and sort them. DashMap iteration order is
1785    // arbitrary, so offset paging is only coherent against a total order — and
1786    // windowing ids instead of values means only the returned page's states are
1787    // cloned, not the whole projection.
1788    let mut entity_ids: Vec<String> = cache
1789        .iter()
1790        .filter_map(|entry| entry.key().strip_prefix(&prefix).map(ToString::to_string))
1791        .filter(|entity_id| {
1792            params
1793                .entity_id_prefix
1794                .as_ref()
1795                .is_none_or(|p| entity_id.starts_with(p))
1796        })
1797        .collect();
1798    entity_ids.sort_unstable();
1799
1800    let total = entity_ids.len();
1801
1802    let page = entity_ids.into_iter().skip(offset);
1803    let page: Vec<String> = match params.limit {
1804        Some(limit) => page.take(limit).collect(),
1805        None => page.collect(),
1806    };
1807
1808    let states: Vec<serde_json::Value> = page
1809        .into_iter()
1810        .filter_map(|entity_id| {
1811            // Skip entries deleted between the key scan and the value read.
1812            cache.get(&format!("{prefix}{entity_id}")).map(|entry| {
1813                serde_json::json!({
1814                    "entity_id": entity_id,
1815                    "state": entry.value().clone()
1816                })
1817            })
1818        })
1819        .collect();
1820
1821    let count = states.len();
1822    // Relative to the window actually served — a paginator that trusts a bare
1823    // `count < total` never terminates once an offset is in play (cf. #250).
1824    let has_more = offset + count < total;
1825
1826    tracing::debug!(
1827        "Projection state summary: {} ({} of {} entities, offset {})",
1828        name,
1829        count,
1830        total,
1831        offset
1832    );
1833
1834    Ok(Json(serde_json::json!({
1835        "projection": name,
1836        "states": states,
1837        "count": count,
1838        "total": total,
1839        "has_more": has_more
1840    })))
1841}
1842
1843/// Reset a projection to its initial state
1844///
1845/// Clears all accumulated state and reprocesses events from the beginning.
1846pub async fn reset_projection(
1847    State(store): State<SharedStore>,
1848    Path(name): Path<String>,
1849) -> Result<Json<serde_json::Value>> {
1850    let reprocessed = store.reset_projection(&name)?;
1851
1852    tracing::info!(
1853        "Projection reset: {} ({} events reprocessed)",
1854        name,
1855        reprocessed
1856    );
1857
1858    Ok(Json(serde_json::json!({
1859        "projection": name,
1860        "reset": true,
1861        "events_reprocessed": reprocessed
1862    })))
1863}
1864
1865/// Pause a projection
1866///
1867/// Sets the projection status to "paused" so it stops processing new events.
1868pub async fn pause_projection(
1869    State(store): State<SharedStore>,
1870    Path(name): Path<String>,
1871) -> Result<Json<serde_json::Value>> {
1872    let projection_manager = store.projection_manager();
1873
1874    // Verify projection exists
1875    let _projection = projection_manager.get_projection(&name).ok_or_else(|| {
1876        crate::error::AllSourceError::EntityNotFound(format!("Projection '{name}' not found"))
1877    })?;
1878
1879    store
1880        .projection_status()
1881        .insert(name.clone(), "paused".to_string());
1882
1883    tracing::info!("Projection paused: {}", name);
1884
1885    Ok(Json(serde_json::json!({
1886        "projection": name,
1887        "status": "paused"
1888    })))
1889}
1890
1891/// Start (resume) a projection
1892///
1893/// Sets the projection status to "running" so it resumes processing events.
1894pub async fn start_projection(
1895    State(store): State<SharedStore>,
1896    Path(name): Path<String>,
1897) -> Result<Json<serde_json::Value>> {
1898    let projection_manager = store.projection_manager();
1899
1900    // Verify projection exists
1901    let _projection = projection_manager.get_projection(&name).ok_or_else(|| {
1902        crate::error::AllSourceError::EntityNotFound(format!("Projection '{name}' not found"))
1903    })?;
1904
1905    store
1906        .projection_status()
1907        .insert(name.clone(), "running".to_string());
1908
1909    tracing::info!("Projection started: {}", name);
1910
1911    Ok(Json(serde_json::json!({
1912        "projection": name,
1913        "status": "running"
1914    })))
1915}
1916
1917/// Request body for saving projection state
1918#[derive(Debug, Deserialize)]
1919pub struct SaveProjectionStateRequest {
1920    pub state: serde_json::Value,
1921}
1922
1923/// Save/update projection state for an entity
1924///
1925/// This endpoint allows external services (like Elixir Query Service) to
1926/// store computed projection state back to the Core for persistence.
1927pub async fn save_projection_state(
1928    State(store): State<SharedStore>,
1929    Path((name, entity_id)): Path<(String, String)>,
1930    Json(req): Json<SaveProjectionStateRequest>,
1931) -> Result<Json<serde_json::Value>> {
1932    let projection_cache = store.projection_state_cache();
1933
1934    // Store in the projection state cache
1935    projection_cache.insert(format!("{name}:{entity_id}"), req.state.clone());
1936
1937    tracing::info!("Projection state saved: {} / {}", name, entity_id);
1938
1939    Ok(Json(serde_json::json!({
1940        "projection": name,
1941        "entity_id": entity_id,
1942        "saved": true
1943    })))
1944}
1945
1946/// Bulk get projection states for multiple entities
1947///
1948/// Efficient endpoint for fetching multiple entity states in a single request.
1949#[derive(Debug, Deserialize)]
1950pub struct BulkGetStateRequest {
1951    pub entity_ids: Vec<String>,
1952}
1953
1954/// Bulk save projection states for multiple entities
1955///
1956/// Efficient endpoint for saving multiple entity states in a single request.
1957#[derive(Debug, Deserialize)]
1958pub struct BulkSaveStateRequest {
1959    pub states: Vec<BulkSaveStateItem>,
1960}
1961
1962#[derive(Debug, Deserialize)]
1963pub struct BulkSaveStateItem {
1964    pub entity_id: String,
1965    pub state: serde_json::Value,
1966}
1967
1968pub async fn bulk_get_projection_states(
1969    State(store): State<SharedStore>,
1970    Path(name): Path<String>,
1971    Json(req): Json<BulkGetStateRequest>,
1972) -> Result<Json<serde_json::Value>> {
1973    // Same fallback rule as `get_projection_state`: registered projection
1974    // wins, cache is the fallback. This lets SDK-managed projections read
1975    // their pushed-back state without registering in Core's projection manager.
1976    let projection = store.projection_manager().get_projection(&name);
1977    let cache = store.projection_state_cache();
1978
1979    let states: Vec<serde_json::Value> = req
1980        .entity_ids
1981        .iter()
1982        .map(|entity_id| {
1983            let state = projection
1984                .as_ref()
1985                .and_then(|p| p.get_state(entity_id))
1986                .or_else(|| {
1987                    cache
1988                        .get(&format!("{name}:{entity_id}"))
1989                        .map(|entry| entry.value().clone())
1990                });
1991            serde_json::json!({
1992                "entity_id": entity_id,
1993                "state": state,
1994                "found": state.is_some()
1995            })
1996        })
1997        .collect();
1998
1999    tracing::debug!(
2000        "Bulk projection state retrieved: {} entities from {}",
2001        states.len(),
2002        name
2003    );
2004
2005    Ok(Json(serde_json::json!({
2006        "projection": name,
2007        "states": states,
2008        "total": states.len()
2009    })))
2010}
2011
2012/// Bulk save projection states for multiple entities
2013///
2014/// This endpoint allows efficient batch saving of projection states,
2015/// critical for high-throughput event processing pipelines.
2016pub async fn bulk_save_projection_states(
2017    State(store): State<SharedStore>,
2018    Path(name): Path<String>,
2019    Json(req): Json<BulkSaveStateRequest>,
2020) -> Result<Json<serde_json::Value>> {
2021    let projection_cache = store.projection_state_cache();
2022
2023    let mut saved_count = 0;
2024    for item in &req.states {
2025        projection_cache.insert(format!("{name}:{}", item.entity_id), item.state.clone());
2026        saved_count += 1;
2027    }
2028
2029    tracing::info!(
2030        "Bulk projection state saved: {} entities for {}",
2031        saved_count,
2032        name
2033    );
2034
2035    Ok(Json(serde_json::json!({
2036        "projection": name,
2037        "saved": saved_count,
2038        "total": req.states.len()
2039    })))
2040}
2041
2042// =============================================================================
2043// v0.11: Webhook Management API
2044// =============================================================================
2045
2046/// Query parameters for listing webhooks
2047#[derive(Debug, Deserialize)]
2048pub struct ListWebhooksParams {
2049    pub tenant_id: Option<String>,
2050}
2051
2052/// Register a new webhook subscription
2053pub async fn register_webhook(
2054    State(store): State<SharedStore>,
2055    Json(req): Json<RegisterWebhookRequest>,
2056) -> Json<serde_json::Value> {
2057    let registry = store.webhook_registry();
2058    let webhook = registry.register(req);
2059
2060    tracing::info!("Webhook registered: {} -> {}", webhook.id, webhook.url);
2061
2062    Json(serde_json::json!({
2063        "webhook": webhook,
2064        "created": true
2065    }))
2066}
2067
2068/// List webhooks, optionally filtered by tenant_id
2069pub async fn list_webhooks(
2070    State(store): State<SharedStore>,
2071    Query(params): Query<ListWebhooksParams>,
2072) -> Json<serde_json::Value> {
2073    let registry = store.webhook_registry();
2074
2075    let webhooks = if let Some(tenant_id) = params.tenant_id {
2076        registry.list_by_tenant(&tenant_id)
2077    } else {
2078        // Without tenant filter, return empty (tenants should always filter)
2079        vec![]
2080    };
2081
2082    let total = webhooks.len();
2083
2084    Json(serde_json::json!({
2085        "webhooks": webhooks,
2086        "total": total
2087    }))
2088}
2089
2090/// Get a specific webhook by ID
2091pub async fn get_webhook(
2092    State(store): State<SharedStore>,
2093    Path(webhook_id): Path<uuid::Uuid>,
2094) -> Result<Json<serde_json::Value>> {
2095    let registry = store.webhook_registry();
2096
2097    let webhook = registry.get(webhook_id).ok_or_else(|| {
2098        crate::error::AllSourceError::EntityNotFound(format!("Webhook '{webhook_id}' not found"))
2099    })?;
2100
2101    Ok(Json(serde_json::json!({
2102        "webhook": webhook,
2103        "found": true
2104    })))
2105}
2106
2107/// Update a webhook subscription
2108pub async fn update_webhook(
2109    State(store): State<SharedStore>,
2110    Path(webhook_id): Path<uuid::Uuid>,
2111    Json(req): Json<UpdateWebhookRequest>,
2112) -> Result<Json<serde_json::Value>> {
2113    let registry = store.webhook_registry();
2114
2115    let webhook = registry.update(webhook_id, req).ok_or_else(|| {
2116        crate::error::AllSourceError::EntityNotFound(format!("Webhook '{webhook_id}' not found"))
2117    })?;
2118
2119    tracing::info!("Webhook updated: {}", webhook_id);
2120
2121    Ok(Json(serde_json::json!({
2122        "webhook": webhook,
2123        "updated": true
2124    })))
2125}
2126
2127/// Delete a webhook subscription
2128pub async fn delete_webhook(
2129    State(store): State<SharedStore>,
2130    Path(webhook_id): Path<uuid::Uuid>,
2131) -> Result<Json<serde_json::Value>> {
2132    let registry = store.webhook_registry();
2133
2134    let webhook = registry.delete(webhook_id).ok_or_else(|| {
2135        crate::error::AllSourceError::EntityNotFound(format!("Webhook '{webhook_id}' not found"))
2136    })?;
2137
2138    tracing::info!("Webhook deleted: {} ({})", webhook_id, webhook.url);
2139
2140    Ok(Json(serde_json::json!({
2141        "webhook_id": webhook_id,
2142        "deleted": true
2143    })))
2144}
2145
2146/// Query parameters for listing webhook deliveries
2147#[derive(Debug, Deserialize)]
2148pub struct ListDeliveriesParams {
2149    pub limit: Option<usize>,
2150}
2151
2152/// List delivery history for a webhook
2153pub async fn list_webhook_deliveries(
2154    State(store): State<SharedStore>,
2155    Path(webhook_id): Path<uuid::Uuid>,
2156    Query(params): Query<ListDeliveriesParams>,
2157) -> Result<Json<serde_json::Value>> {
2158    let registry = store.webhook_registry();
2159
2160    // Verify webhook exists
2161    registry.get(webhook_id).ok_or_else(|| {
2162        crate::error::AllSourceError::EntityNotFound(format!("Webhook '{webhook_id}' not found"))
2163    })?;
2164
2165    let limit = params.limit.unwrap_or(50);
2166    let deliveries = registry.get_deliveries(webhook_id, limit);
2167    let total = deliveries.len();
2168
2169    Ok(Json(serde_json::json!({
2170        "webhook_id": webhook_id,
2171        "deliveries": deliveries,
2172        "total": total
2173    })))
2174}
2175
2176// =============================================================================
2177// v2.0: Advanced Query Features
2178// =============================================================================
2179
2180/// EventQL: Execute SQL queries over events using DataFusion
2181#[cfg(feature = "analytics")]
2182pub async fn eventql_query(
2183    State(store): State<SharedStore>,
2184    Json(req): Json<crate::infrastructure::query::eventql::EventQLRequest>,
2185) -> Result<Json<serde_json::Value>> {
2186    let events = store.snapshot_events();
2187    match crate::infrastructure::query::eventql::execute_eventql(&events, &req).await {
2188        Ok(response) => Ok(Json(serde_json::json!({
2189            "columns": response.columns,
2190            "rows": response.rows,
2191            "row_count": response.row_count,
2192        }))),
2193        Err(e) => Err(crate::error::AllSourceError::InvalidQuery(e)),
2194    }
2195}
2196
2197/// GraphQL: Execute GraphQL queries
2198pub async fn graphql_query(
2199    State(store): State<SharedStore>,
2200    Json(req): Json<GraphQLRequest>,
2201) -> Json<serde_json::Value> {
2202    let fields = match crate::infrastructure::query::graphql::parse_query(&req.query) {
2203        Ok(f) => f,
2204        Err(e) => {
2205            return Json(
2206                serde_json::to_value(GraphQLResponse {
2207                    data: None,
2208                    errors: vec![GraphQLError { message: e }],
2209                })
2210                .unwrap(),
2211            );
2212        }
2213    };
2214
2215    let mut data = serde_json::Map::new();
2216    let mut errors = Vec::new();
2217
2218    for field in &fields {
2219        match field.name.as_str() {
2220            "events" => {
2221                let request = crate::application::dto::QueryEventsRequest {
2222                    entity_id: field.arguments.get("entity_id").cloned(),
2223                    event_type: field.arguments.get("event_type").cloned(),
2224                    tenant_id: field.arguments.get("tenant_id").cloned(),
2225                    limit: field.arguments.get("limit").and_then(|l| l.parse().ok()),
2226                    as_of: None,
2227                    since: None,
2228                    until: None,
2229                    event_type_prefix: None,
2230                    exclude_event_type_prefix: None,
2231                    payload_filter: None,
2232                };
2233                match store.query(&request) {
2234                    Ok(events) => {
2235                        let json_events: Vec<serde_json::Value> = events
2236                            .iter()
2237                            .map(|e| {
2238                                crate::infrastructure::query::graphql::event_to_json(
2239                                    e,
2240                                    &field.fields,
2241                                )
2242                            })
2243                            .collect();
2244                        data.insert("events".to_string(), serde_json::Value::Array(json_events));
2245                    }
2246                    Err(e) => errors.push(GraphQLError {
2247                        message: format!("events query failed: {e}"),
2248                    }),
2249                }
2250            }
2251            "event" => {
2252                if let Some(id_str) = field.arguments.get("id") {
2253                    if let Ok(id) = uuid::Uuid::parse_str(id_str) {
2254                        match store.get_event_by_id(&id) {
2255                            Ok(Some(event)) => {
2256                                data.insert(
2257                                    "event".to_string(),
2258                                    crate::infrastructure::query::graphql::event_to_json(
2259                                        &event,
2260                                        &field.fields,
2261                                    ),
2262                                );
2263                            }
2264                            Ok(None) => {
2265                                data.insert("event".to_string(), serde_json::Value::Null);
2266                            }
2267                            Err(e) => errors.push(GraphQLError {
2268                                message: format!("event lookup failed: {e}"),
2269                            }),
2270                        }
2271                    } else {
2272                        errors.push(GraphQLError {
2273                            message: format!("Invalid UUID: {id_str}"),
2274                        });
2275                    }
2276                } else {
2277                    errors.push(GraphQLError {
2278                        message: "event query requires 'id' argument".to_string(),
2279                    });
2280                }
2281            }
2282            "projections" => {
2283                let pm = store.projection_manager();
2284                let names: Vec<serde_json::Value> = pm
2285                    .list_projections()
2286                    .iter()
2287                    .map(|(name, _)| serde_json::Value::String(name.clone()))
2288                    .collect();
2289                data.insert("projections".to_string(), serde_json::Value::Array(names));
2290            }
2291            "stats" => {
2292                let stats = store.stats();
2293                data.insert(
2294                    "stats".to_string(),
2295                    serde_json::json!({
2296                        "total_events": stats.total_events,
2297                        "total_entities": stats.total_entities,
2298                        "total_event_types": stats.total_event_types,
2299                    }),
2300                );
2301            }
2302            "__schema" => {
2303                data.insert(
2304                    "__schema".to_string(),
2305                    crate::infrastructure::query::graphql::introspection_schema(),
2306                );
2307            }
2308            other => {
2309                errors.push(GraphQLError {
2310                    message: format!("Unknown field: {other}"),
2311                });
2312            }
2313        }
2314    }
2315
2316    Json(
2317        serde_json::to_value(GraphQLResponse {
2318            data: Some(serde_json::Value::Object(data)),
2319            errors,
2320        })
2321        .unwrap(),
2322    )
2323}
2324
2325/// Geospatial: Query events by location
2326pub async fn geo_query(
2327    State(store): State<SharedStore>,
2328    Json(req): Json<GeoQueryRequest>,
2329) -> Json<serde_json::Value> {
2330    let events = store.snapshot_events();
2331    let geo_index = store.geo_index();
2332    let results =
2333        crate::infrastructure::query::geospatial::execute_geo_query(&events, &geo_index, &req);
2334    let total = results.len();
2335    Json(serde_json::json!({
2336        "results": results,
2337        "total": total,
2338    }))
2339}
2340
2341/// Geospatial index stats
2342pub async fn geo_stats(State(store): State<SharedStore>) -> Json<serde_json::Value> {
2343    let stats = store.geo_index().stats();
2344    Json(serde_json::json!(stats))
2345}
2346
2347/// Exactly-once processing stats
2348pub async fn exactly_once_stats(State(store): State<SharedStore>) -> Json<serde_json::Value> {
2349    let stats = store.exactly_once().stats();
2350    Json(serde_json::json!(stats))
2351}
2352
2353/// Schema evolution history for an event type
2354pub async fn schema_evolution_history(
2355    State(store): State<SharedStore>,
2356    Path(event_type): Path<String>,
2357) -> Json<serde_json::Value> {
2358    let mgr = store.schema_evolution();
2359    let history = mgr.get_history(&event_type);
2360    let version = mgr.get_version(&event_type);
2361    Json(serde_json::json!({
2362        "event_type": event_type,
2363        "current_version": version,
2364        "history": history,
2365    }))
2366}
2367
2368/// Current inferred schema for an event type
2369pub async fn schema_evolution_schema(
2370    State(store): State<SharedStore>,
2371    Path(event_type): Path<String>,
2372) -> Json<serde_json::Value> {
2373    let mgr = store.schema_evolution();
2374    if let Some(schema) = mgr.get_schema(&event_type) {
2375        let json_schema = crate::application::services::schema_evolution::to_json_schema(&schema);
2376        Json(serde_json::json!({
2377            "event_type": event_type,
2378            "version": mgr.get_version(&event_type),
2379            "inferred_schema": schema,
2380            "json_schema": json_schema,
2381        }))
2382    } else {
2383        Json(serde_json::json!({
2384            "event_type": event_type,
2385            "error": "No schema inferred for this event type"
2386        }))
2387    }
2388}
2389
2390/// Schema evolution stats
2391pub async fn schema_evolution_stats(State(store): State<SharedStore>) -> Json<serde_json::Value> {
2392    let stats = store.schema_evolution().stats();
2393    let event_types = store.schema_evolution().list_event_types();
2394    Json(serde_json::json!({
2395        "stats": stats,
2396        "tracked_event_types": event_types,
2397    }))
2398}
2399
2400// =============================================================================
2401// Sync Protocol Endpoints (v0.11: embedded↔server bidirectional sync)
2402// =============================================================================
2403
2404/// POST /api/v1/sync/pull — Client sends version vector, server returns delta events.
2405#[cfg(feature = "embedded-sync")]
2406pub async fn sync_pull_handler(
2407    State(state): State<AppState>,
2408    Json(request): Json<crate::embedded::sync_types::SyncPullRequest>,
2409) -> Result<Json<crate::embedded::sync_types::SyncPullResponse>> {
2410    use crate::infrastructure::cluster::{crdt::ReplicatedEvent, hlc::HlcTimestamp};
2411
2412    let store = &state.store;
2413
2414    // Compute "since" threshold from the client's version vector
2415    // We return all events the client hasn't seen yet
2416    let since = request
2417        .version_vector
2418        .values()
2419        .map(|ts| ts.physical_ms)
2420        .min()
2421        .and_then(|ms| chrono::DateTime::from_timestamp_millis(ms as i64));
2422
2423    let events = store.query(&crate::application::dto::QueryEventsRequest {
2424        entity_id: None,
2425        event_type: None,
2426        tenant_id: None,
2427        as_of: None,
2428        since,
2429        until: None,
2430        limit: None,
2431        event_type_prefix: None,
2432        exclude_event_type_prefix: None,
2433        payload_filter: None,
2434    })?;
2435
2436    // Convert domain events to ReplicatedEvent wire format
2437    let mut replicated = Vec::with_capacity(events.len());
2438    let mut last_ms = 0u64;
2439    let mut logical = 0u32;
2440
2441    for event in &events {
2442        let event_ms = event.timestamp().timestamp_millis() as u64;
2443        if event_ms == last_ms {
2444            logical += 1;
2445        } else {
2446            last_ms = event_ms;
2447            logical = 0;
2448        }
2449
2450        replicated.push(ReplicatedEvent {
2451            event_id: event.id().to_string(),
2452            hlc_timestamp: HlcTimestamp::new(event_ms, logical, 0),
2453            origin_region: "server".to_string(),
2454            event_data: serde_json::json!({
2455                "event_type": event.event_type_str(),
2456                "entity_id": event.entity_id_str(),
2457                "tenant_id": event.tenant_id_str(),
2458                "payload": event.payload,
2459                "metadata": event.metadata,
2460            }),
2461        });
2462    }
2463
2464    Ok(Json(crate::embedded::sync_types::SyncPullResponse {
2465        events: replicated,
2466        version_vector: std::collections::BTreeMap::new(),
2467    }))
2468}
2469
2470/// POST /api/v1/sync/push — Client pushes events, server applies CRDT resolution.
2471#[cfg(feature = "embedded-sync")]
2472pub async fn sync_push_handler(
2473    State(state): State<AppState>,
2474    Json(request): Json<crate::embedded::sync_types::SyncPushRequest>,
2475) -> Result<Json<crate::embedded::sync_types::SyncPushResponse>> {
2476    let store = &state.store;
2477
2478    let mut accepted = 0usize;
2479    let mut skipped = 0usize;
2480
2481    for rep_event in &request.events {
2482        let event_data = &rep_event.event_data;
2483        let event_type = event_data
2484            .get("event_type")
2485            .and_then(|v| v.as_str())
2486            .unwrap_or("unknown")
2487            .to_string();
2488        let entity_id = event_data
2489            .get("entity_id")
2490            .and_then(|v| v.as_str())
2491            .unwrap_or("unknown")
2492            .to_string();
2493        let tenant_id = event_data
2494            .get("tenant_id")
2495            .and_then(|v| v.as_str())
2496            .unwrap_or("default")
2497            .to_string();
2498        let payload = event_data
2499            .get("payload")
2500            .cloned()
2501            .unwrap_or(serde_json::json!({}));
2502        let metadata = event_data.get("metadata").cloned();
2503
2504        match Event::from_strings(event_type, entity_id, tenant_id, payload, metadata) {
2505            Ok(domain_event) => {
2506                store.ingest(&domain_event)?;
2507                accepted += 1;
2508            }
2509            Err(_) => {
2510                skipped += 1;
2511            }
2512        }
2513    }
2514
2515    Ok(Json(crate::embedded::sync_types::SyncPushResponse {
2516        accepted,
2517        skipped,
2518        version_vector: std::collections::BTreeMap::new(),
2519    }))
2520}
2521
2522// =============================================================================
2523// Consumer endpoints for durable subscriptions (v0.14)
2524// =============================================================================
2525
2526/// POST /api/v1/consumers — Register a durable consumer
2527pub async fn register_consumer(
2528    State(store): State<SharedStore>,
2529    Json(req): Json<RegisterConsumerRequest>,
2530) -> Result<Json<ConsumerResponse>> {
2531    let consumer = store
2532        .consumer_registry()
2533        .register(&req.consumer_id, &req.event_type_filters);
2534
2535    Ok(Json(ConsumerResponse {
2536        consumer_id: consumer.consumer_id,
2537        event_type_filters: consumer.event_type_filters,
2538        cursor_position: consumer.cursor_position,
2539    }))
2540}
2541
2542/// GET /api/v1/consumers/{consumer_id} — Get consumer metadata and cursor position
2543pub async fn get_consumer(
2544    State(store): State<SharedStore>,
2545    Path(consumer_id): Path<String>,
2546) -> Result<Json<ConsumerResponse>> {
2547    let consumer = store.consumer_registry().get_or_create(&consumer_id);
2548
2549    Ok(Json(ConsumerResponse {
2550        consumer_id: consumer.consumer_id,
2551        event_type_filters: consumer.event_type_filters,
2552        cursor_position: consumer.cursor_position,
2553    }))
2554}
2555
2556/// GET /api/v1/consumers/{consumer_id}/events — Poll for events since last ack
2557#[derive(Debug, Deserialize)]
2558pub struct ConsumerPollQuery {
2559    pub limit: Option<usize>,
2560}
2561
2562pub async fn poll_consumer_events(
2563    State(store): State<SharedStore>,
2564    Path(consumer_id): Path<String>,
2565    Query(query): Query<ConsumerPollQuery>,
2566) -> Result<Json<ConsumerEventsResponse>> {
2567    let consumer = store.consumer_registry().get_or_create(&consumer_id);
2568    let offset = consumer.cursor_position.unwrap_or(0);
2569    let limit = query.limit.unwrap_or(100);
2570
2571    let events = store.events_after_offset(offset, &consumer.event_type_filters, limit);
2572    let count = events.len();
2573
2574    let consumer_events: Vec<ConsumerEventDto> = events
2575        .into_iter()
2576        .map(|(position, event)| ConsumerEventDto {
2577            position,
2578            event: EventDto::from(&event),
2579        })
2580        .collect();
2581
2582    Ok(Json(ConsumerEventsResponse {
2583        events: consumer_events,
2584        count,
2585    }))
2586}
2587
2588/// POST /api/v1/consumers/{consumer_id}/ack — Acknowledge processed events
2589pub async fn ack_consumer(
2590    State(store): State<SharedStore>,
2591    Path(consumer_id): Path<String>,
2592    Json(req): Json<AckRequest>,
2593) -> Result<Json<serde_json::Value>> {
2594    let max_offset = store.total_events() as u64;
2595
2596    store
2597        .consumer_registry()
2598        .ack(&consumer_id, req.position, max_offset)
2599        .map_err(crate::error::AllSourceError::InvalidInput)?;
2600
2601    Ok(Json(serde_json::json!({
2602        "status": "ok",
2603        "consumer_id": consumer_id,
2604        "position": req.position,
2605    })))
2606}
2607
2608#[cfg(test)]
2609mod tests {
2610    use super::*;
2611    use crate::{domain::entities::Event, store::EventStore};
2612
2613    fn create_test_store() -> Arc<EventStore> {
2614        Arc::new(EventStore::new())
2615    }
2616
2617    /// Call the REAL `GET /api/v1/events/query` handler with `query` as the
2618    /// query string, parsed through the same extractors the router uses.
2619    ///
2620    /// Tests that hand the handler DTOs they built themselves cannot see
2621    /// parameters the DTOs never declare (issue #250) and cannot exercise the
2622    /// ordering/windowing composition the handler delegates to the store
2623    /// (issue #251), so ordering and pagination guards go through here.
2624    /// `tenant_id` is defaulted to the one `create_test_event` stamps.
2625    async fn query_page(store: &SharedStore, query: &str) -> QueryEventsResponse {
2626        use axum::extract::{Query, State};
2627
2628        let uri: axum::http::Uri = format!("/api/v1/events/query?tenant_id=test-stream&{query}")
2629            .parse()
2630            .unwrap();
2631        query_events(
2632            OptionalAuth(None),
2633            Query::try_from_uri(&uri).unwrap(),
2634            Query::try_from_uri(&uri).unwrap(),
2635            Query::try_from_uri(&uri).unwrap(),
2636            Query::try_from_uri(&uri).unwrap(),
2637            State(store.clone()),
2638        )
2639        .await
2640        .unwrap()
2641        .0
2642    }
2643
2644    fn create_test_event(entity_id: &str, event_type: &str) -> Event {
2645        Event::from_strings(
2646            event_type.to_string(),
2647            entity_id.to_string(),
2648            "test-stream".to_string(),
2649            serde_json::json!({
2650                "name": "Test",
2651                "value": 42
2652            }),
2653            None,
2654        )
2655        .unwrap()
2656    }
2657
2658    #[tokio::test]
2659    async fn test_query_events_has_more_and_total_count() {
2660        let store = create_test_store();
2661
2662        // Ingest 50 events
2663        for i in 0..50 {
2664            store
2665                .ingest(&create_test_event(&format!("entity-{i}"), "user.created"))
2666                .unwrap();
2667        }
2668
2669        // Query with limit=10 — should get has_more=true, total_count=50
2670        let req = QueryEventsRequest {
2671            entity_id: None,
2672            event_type: None,
2673            tenant_id: None,
2674            as_of: None,
2675            since: None,
2676            until: None,
2677            limit: Some(10),
2678            event_type_prefix: None,
2679            exclude_event_type_prefix: None,
2680            payload_filter: None,
2681        };
2682
2683        let requested_limit = req.limit;
2684        let unlimited_req = QueryEventsRequest {
2685            limit: None,
2686            ..QueryEventsRequest {
2687                entity_id: req.entity_id,
2688                event_type: req.event_type,
2689                tenant_id: req.tenant_id,
2690                as_of: req.as_of,
2691                since: req.since,
2692                until: req.until,
2693                limit: None,
2694                event_type_prefix: req.event_type_prefix,
2695                exclude_event_type_prefix: None,
2696                payload_filter: req.payload_filter,
2697            }
2698        };
2699        let all_events = store.query(&unlimited_req).unwrap();
2700        let total_count = all_events.len();
2701        let limited_events: Vec<Event> = if let Some(limit) = requested_limit {
2702            all_events.into_iter().take(limit).collect()
2703        } else {
2704            all_events
2705        };
2706        let count = limited_events.len();
2707        let has_more = count < total_count;
2708
2709        assert_eq!(count, 10);
2710        assert_eq!(total_count, 50);
2711        assert!(has_more);
2712    }
2713
2714    // Regression guard for issue #250: `GET /api/v1/events/query` must honour
2715    // `offset`. It used to be dropped silently (the DTO did not declare it), so
2716    // every page returned the same first `limit` events and `has_more` stayed
2717    // true — the Rust SDK's `EventPaginator` (and the Go SDK's `QueryOptions`)
2718    // both send `offset`, so `collect_all()` looped forever accumulating
2719    // duplicates. Drives the REAL handler through query-string deserialization,
2720    // because the bug lived in the wire layer: a hand-rolled test that builds
2721    // the DTO in code cannot see a field the DTO never declares.
2722    #[tokio::test]
2723    async fn query_events_honours_offset_pagination() {
2724        use axum::extract::{Query, State};
2725
2726        let store = create_test_store();
2727        for i in 0..25 {
2728            store
2729                .ingest(&create_test_event(&format!("e-{i:02}"), "user.created"))
2730                .unwrap();
2731        }
2732
2733        // Parse a real query string through the same extractors the router uses.
2734        async fn page(store: &SharedStore, limit: usize, offset: usize) -> QueryEventsResponse {
2735            let uri: axum::http::Uri =
2736                format!("/api/v1/events/query?tenant_id=test-stream&limit={limit}&offset={offset}")
2737                    .parse()
2738                    .unwrap();
2739            let req: Query<QueryEventsRequest> = Query::try_from_uri(&uri).unwrap();
2740            let order: Query<EventOrderParam> = Query::try_from_uri(&uri).unwrap();
2741            let off: Query<EventOffsetParam> = Query::try_from_uri(&uri).unwrap();
2742            assert_eq!(off.0.offset, Some(offset), "offset must deserialize");
2743            query_events(
2744                OptionalAuth(None),
2745                req,
2746                order,
2747                off,
2748                Query::try_from_uri(&uri).unwrap(),
2749                State(store.clone()),
2750            )
2751            .await
2752            .unwrap()
2753            .0
2754        }
2755
2756        let p1 = page(&store, 10, 0).await;
2757        let p2 = page(&store, 10, 10).await;
2758        let p3 = page(&store, 10, 20).await;
2759
2760        assert_eq!(p1.count, 10);
2761        assert_eq!(p2.count, 10);
2762        assert_eq!(p3.count, 5, "last page returns the remainder");
2763        assert_eq!(p1.total_count, 25);
2764
2765        // The core failure: page 2 must not be page 1 again.
2766        let ids = |r: &QueryEventsResponse| -> Vec<String> {
2767            r.events.iter().map(|e| e.entity_id.clone()).collect()
2768        };
2769        assert_ne!(ids(&p1), ids(&p2), "offset=10 must skip the first page");
2770
2771        let mut all = ids(&p1);
2772        all.extend(ids(&p2));
2773        all.extend(ids(&p3));
2774        let unique: std::collections::HashSet<_> = all.iter().cloned().collect();
2775        assert_eq!(
2776            unique.len(),
2777            25,
2778            "paging the whole set must yield 25 distinct entities, not duplicates"
2779        );
2780
2781        // `has_more` must account for the offset, otherwise a paginator that
2782        // trusts it never terminates.
2783        assert!(p1.has_more, "25 events, page 1 of 10 → more remain");
2784        assert!(p2.has_more, "25 events, page 2 of 10 → more remain");
2785        assert!(!p3.has_more, "offset=20 + count=5 == total → exhausted");
2786
2787        // Past the end: empty page, and exhausted rather than "more".
2788        let past = page(&store, 10, 100).await;
2789        assert_eq!(past.count, 0);
2790        assert!(!past.has_more, "offset beyond the match set is exhausted");
2791    }
2792
2793    // Regression guard for issue #249: `GET /api/v1/projections/{name}/state`
2794    // must honour `limit`, `offset` and `entity_id_prefix`. The handler used to
2795    // take only `Path(name)`, so query parameters were dropped on the floor and
2796    // the response grew linearly with the number of cached entities — a caller
2797    // with one entry per tenant had no way to bound a request or resume one.
2798    // Driven through a real router so query-string deserialization is exercised:
2799    // a test that hands the handler a DTO it built itself cannot fail on
2800    // parameters the handler never declares.
2801    #[tokio::test]
2802    async fn projection_state_summary_honours_limit_offset_and_prefix() {
2803        use axum::{
2804            body::{Body, to_bytes},
2805            http::Request,
2806        };
2807        use tower::ServiceExt; // for `oneshot`
2808
2809        let store = create_test_store();
2810        let cache = store.projection_state_cache();
2811        for i in 0..25 {
2812            cache.insert(
2813                format!("demo:tenant-{i:02}"),
2814                serde_json::json!({ "n": i as u64 }),
2815            );
2816        }
2817        // A neighbouring projection and a same-prefix-looking key must not leak.
2818        cache.insert(
2819            "other:tenant-99".to_string(),
2820            serde_json::json!({ "n": 99 }),
2821        );
2822
2823        let app = Router::new()
2824            .route(
2825                "/api/v1/projections/{name}/state",
2826                get(get_projection_state_summary),
2827            )
2828            .with_state(store.clone());
2829
2830        async fn fetch(app: &Router, uri: &str) -> serde_json::Value {
2831            let resp = app
2832                .clone()
2833                .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())
2834                .await
2835                .unwrap();
2836            assert_eq!(resp.status(), axum::http::StatusCode::OK, "GET {uri}");
2837            let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
2838            serde_json::from_slice(&bytes).unwrap()
2839        }
2840
2841        let ids = |body: &serde_json::Value| -> Vec<String> {
2842            body["states"]
2843                .as_array()
2844                .unwrap()
2845                .iter()
2846                .map(|s| s["entity_id"].as_str().unwrap().to_string())
2847                .collect()
2848        };
2849
2850        // No params: unchanged behaviour — the whole projection, scoped to it.
2851        let all = fetch(&app, "/api/v1/projections/demo/state").await;
2852        assert_eq!(all["total"], 25);
2853        assert_eq!(ids(&all).len(), 25);
2854
2855        // limit bounds the body; total still reports the full match set.
2856        let p1 = fetch(&app, "/api/v1/projections/demo/state?limit=10").await;
2857        assert_eq!(ids(&p1).len(), 10, "limit must bound the response");
2858        assert_eq!(p1["total"], 25);
2859        assert_eq!(p1["count"], 10);
2860        assert_eq!(p1["has_more"], true);
2861
2862        // offset resumes where the previous page stopped.
2863        let p2 = fetch(&app, "/api/v1/projections/demo/state?limit=10&offset=10").await;
2864        let p3 = fetch(&app, "/api/v1/projections/demo/state?limit=10&offset=20").await;
2865        assert_eq!(ids(&p3).len(), 5, "last page returns the remainder");
2866        assert_eq!(p3["has_more"], false, "offset + count == total → exhausted");
2867        assert_ne!(ids(&p1), ids(&p2), "offset=10 must skip the first page");
2868
2869        let mut walked = ids(&p1);
2870        walked.extend(ids(&p2));
2871        walked.extend(ids(&p3));
2872        let unique: std::collections::HashSet<_> = walked.iter().cloned().collect();
2873        assert_eq!(
2874            unique.len(),
2875            25,
2876            "paging the whole projection must yield 25 distinct entities"
2877        );
2878
2879        // Paging is only meaningful over a stable order — DashMap iteration is not.
2880        let mut sorted = walked.clone();
2881        sorted.sort();
2882        assert_eq!(walked, sorted, "pages must be ordered by entity_id");
2883
2884        // Past the end: empty page, exhausted rather than "more".
2885        let past = fetch(&app, "/api/v1/projections/demo/state?limit=10&offset=100").await;
2886        assert_eq!(past["count"], 0);
2887        assert_eq!(past["has_more"], false);
2888        assert_eq!(past["total"], 25);
2889
2890        // entity_id_prefix narrows to one shard of the keyspace.
2891        let shard = fetch(
2892            &app,
2893            "/api/v1/projections/demo/state?entity_id_prefix=tenant-1",
2894        )
2895        .await;
2896        assert_eq!(shard["total"], 10, "tenant-10..tenant-19");
2897        assert!(
2898            ids(&shard).iter().all(|id| id.starts_with("tenant-1")),
2899            "entity_id_prefix must filter"
2900        );
2901
2902        // The projection scope itself still holds under paging.
2903        let other = fetch(&app, "/api/v1/projections/other/state?limit=10").await;
2904        assert_eq!(ids(&other), vec!["tenant-99".to_string()]);
2905    }
2906
2907    // Regression guard for issue #251: a bounded page must cost the page, not the
2908    // whole match set. The handler used to re-run the query with `limit: None`
2909    // just to compute `total_count`, so `?entity_id=E&limit=1&order=desc` — the
2910    // documented "latest event for an entity" read — cloned and sorted the
2911    // entity's entire history on every request.
2912    //
2913    // Cost is measured by counting `Event` CLONES (`crate::clone_probe`), NOT
2914    // with Core's `query_results_total` metric: that counter is incremented with
2915    // `results.len()`, i.e. rows RETURNED, so it reads 1 whether the store
2916    // clones one event or clones 200 and discards 199 — it cannot fail on a
2917    // revert of the store-side windowing. Drives the REAL handler through
2918    // query-string deserialization so the count is what an HTTP caller pays.
2919    #[test]
2920    fn query_events_limit_does_not_materialize_whole_history() {
2921        const HISTORY: usize = 200;
2922
2923        let store = create_test_store();
2924        for _ in 0..HISTORY {
2925            store
2926                .ingest(&create_test_event("entity-hot", "user.updated"))
2927                .unwrap();
2928        }
2929
2930        // `clone_probe` is thread-local, so the handler future is driven to
2931        // completion on THIS thread (current-thread runtime, inside the measured
2932        // closure) — every clone the request makes is therefore counted.
2933        let runtime = tokio::runtime::Builder::new_current_thread()
2934            .enable_all()
2935            .build()
2936            .unwrap();
2937        let (resp, materialized) = crate::clone_probe::measure(|| {
2938            runtime.block_on(query_page(
2939                &store,
2940                "entity_id=entity-hot&limit=1&order=desc",
2941            ))
2942        });
2943
2944        // The page itself stays correct: one event, and the total/has_more pair
2945        // still describes the full match set.
2946        assert_eq!(resp.count, 1);
2947        assert_eq!(resp.events.len(), 1);
2948        assert_eq!(resp.total_count, HISTORY);
2949        assert!(resp.has_more);
2950
2951        assert_eq!(
2952            materialized, 1,
2953            "limit=1 materialized {materialized} events out of {HISTORY}: \
2954             `limit` must bound what a request materializes, not just what it \
2955             returns"
2956        );
2957    }
2958
2959    /// Like [`query_page`] but surfaces the handler's error instead of
2960    /// unwrapping — for the parameter values that must be REJECTED.
2961    async fn query_page_result(
2962        store: &SharedStore,
2963        query: &str,
2964    ) -> Result<Json<QueryEventsResponse>> {
2965        use axum::extract::{Query, State};
2966
2967        let uri: axum::http::Uri = format!("/api/v1/events/query?tenant_id=test-stream&{query}")
2968            .parse()
2969            .unwrap();
2970        query_events(
2971            OptionalAuth(None),
2972            Query::try_from_uri(&uri).unwrap(),
2973            Query::try_from_uri(&uri).unwrap(),
2974            Query::try_from_uri(&uri).unwrap(),
2975            Query::try_from_uri(&uri).unwrap(),
2976            State(store.clone()),
2977        )
2978        .await
2979    }
2980
2981    // A filter the server cannot apply must be an ERROR, not silence. The
2982    // payload filter is parsed inside the per-event predicate with `if let
2983    // Ok(..)`, so an unparseable one simply never matched anything and the
2984    // query answered as if no filter had been sent — the caller asked for
2985    // "events where user_id = alice" and got the tenant's whole stream, with a
2986    // `total_count` that agreed. Fails OPEN, which is the dangerous direction
2987    // for a filter, and the endpoint already rejects an unusable `order`, so
2988    // silence here was also inconsistent.
2989    #[tokio::test]
2990    async fn query_events_rejects_a_payload_filter_it_cannot_apply() {
2991        let store = create_test_store();
2992        for name in ["alice", "bob", "carol"] {
2993            let mut event = create_test_event(name, "user.created");
2994            event.payload = serde_json::json!({ "user_id": name });
2995            store.ingest(&event).unwrap();
2996        }
2997
2998        // A well-formed filter still filters — the guard must not reject the
2999        // shape callers actually send (`{"user_id":"alice"}`, percent-encoded).
3000        let ok = query_page(&store, "payload_filter=%7B%22user_id%22%3A%22alice%22%7D").await;
3001        assert_eq!(ok.count, 1, "a valid payload_filter must still work");
3002        assert_eq!(ok.total_count, 1);
3003
3004        for bad in [
3005            "not-json",                    // not JSON at all
3006            "%7B%22user_id%22%3A%22alice", // truncated object
3007            "%5B%22alice%22%5D",           // valid JSON, but an array, not an object
3008            "42",                          // valid JSON, but a scalar
3009        ] {
3010            let result = query_page_result(&store, &format!("payload_filter={bad}")).await;
3011            let Err(err) = result else {
3012                let resp = result.unwrap().0;
3013                panic!(
3014                    "payload_filter={bad} was silently ignored: returned {} of {} \
3015                     events unfiltered instead of rejecting a filter the server \
3016                     cannot apply",
3017                    resp.count, resp.total_count
3018                );
3019            };
3020            assert!(
3021                matches!(err, crate::error::AllSourceError::InvalidInput(_)),
3022                "payload_filter={bad} must be a 400, got {err:?}"
3023            );
3024        }
3025    }
3026
3027    // `order` is the other parameter whose only legal values are a closed set.
3028    // It is validated, but nothing pinned that: collapsing the match to a
3029    // `_ => false` default arm would make `?order=descending` silently return
3030    // OLDEST-first — a paginator would read the wrong end of the stream and
3031    // nothing in the response would say so.
3032    #[tokio::test]
3033    async fn query_events_rejects_an_unusable_order_value() {
3034        let store = create_test_store();
3035        store
3036            .ingest(&create_test_event("e-1", "user.created"))
3037            .unwrap();
3038
3039        for bad in ["descending", "DESCENDING", "newest", "1", "asc%20"] {
3040            let result = query_page_result(&store, &format!("order={bad}")).await;
3041            let Err(err) = result else {
3042                panic!("order={bad} must be rejected, not silently defaulted");
3043            };
3044            assert!(
3045                matches!(err, crate::error::AllSourceError::InvalidInput(_)),
3046                "order={bad} must be a 400, got {err:?}"
3047            );
3048        }
3049
3050        // The accepted spellings stay accepted, in any case.
3051        for good in ["asc", "ASC", "desc", "DeSc"] {
3052            let accepted = query_page_result(&store, &format!("order={good}"))
3053                .await
3054                .unwrap_or_else(|e| panic!("order={good} must be accepted: {e:?}"));
3055            assert_eq!(accepted.0.count, 1, "order={good}");
3056        }
3057    }
3058
3059    // `exclude_event_type_prefix` had no test anywhere in Core — not at this
3060    // handler, not in the store — despite being an HTTP-exposed filter the
3061    // Query Service forwards verbatim, and despite #251 having just rewritten
3062    // the code that decides WHEN it runs relative to the window. Its contract
3063    // is more than "drop these events": the DTO promises exclusion happens
3064    // BEFORE the limit, so excluded events never consume the result window, and
3065    // the prefixes are comma-separated. Both claims are only observable in
3066    // composition with `limit`/`offset`, so this drives the real handler.
3067    #[tokio::test]
3068    async fn query_events_exclude_prefix_applies_before_the_window() {
3069        const TYPES: [&str; 4] = [
3070            "audit.write",
3071            "user.created",
3072            "service.ping",
3073            "user.updated",
3074        ];
3075        let store = create_test_store();
3076        let base = chrono::Utc::now() - chrono::Duration::hours(24);
3077        let mut kept = Vec::new();
3078        for i in 0..12i64 {
3079            let mut event = create_test_event("org-1", TYPES[i as usize % 4]);
3080            event.timestamp = base + chrono::Duration::minutes(i);
3081            event.version = i + 1;
3082            if i % 2 == 1 {
3083                kept.push(event.id);
3084            }
3085            store.ingest(&event).unwrap();
3086        }
3087        assert_eq!(kept.len(), 6, "half the stream is user.*");
3088
3089        // A page of 3 must be 3 SURVIVING events. Excluding after the window
3090        // instead would serve 3 minus however many the page happened to hit —
3091        // here 1 — while still reporting a plausible-looking count.
3092        let page = query_page(
3093            &store,
3094            "exclude_event_type_prefix=audit.,%20service.&limit=3",
3095        )
3096        .await;
3097        assert_eq!(
3098            page.events.iter().map(|e| e.id).collect::<Vec<_>>(),
3099            kept[..3].to_vec(),
3100            "limit=3 must yield 3 non-excluded events: exclusion runs before \
3101             the window, and the prefix list is comma-separated (whitespace \
3102             trimmed)"
3103        );
3104        assert!(
3105            page.events
3106                .iter()
3107                .all(|e| !e.event_type.starts_with("audit.")
3108                    && !e.event_type.starts_with("service.")),
3109            "excluded namespaces must not appear: {:?}",
3110            page.events
3111                .iter()
3112                .map(|e| &e.event_type)
3113                .collect::<Vec<_>>()
3114        );
3115        assert_eq!(
3116            page.total_count, 6,
3117            "total_count is the post-exclusion match set, not the 12 ingested"
3118        );
3119        assert!(page.has_more);
3120
3121        // Paging the excluded view walks the 6 survivors exactly once and stops.
3122        let mut walked = Vec::new();
3123        for offset in [0, 3, 6] {
3124            let p = query_page(
3125                &store,
3126                &format!("exclude_event_type_prefix=audit.,service.&limit=3&offset={offset}"),
3127            )
3128            .await;
3129            assert_eq!(
3130                p.has_more,
3131                offset + p.count < 6,
3132                "has_more must terminate on the excluded view (offset={offset})"
3133            );
3134            walked.extend(p.events.iter().map(|e| e.id));
3135        }
3136        assert_eq!(
3137            walked, kept,
3138            "exclusion + paging must cover the survivors once"
3139        );
3140
3141        // Composes with order=desc: newest survivor first, not newest event.
3142        let desc = query_page(
3143            &store,
3144            "exclude_event_type_prefix=audit.,service.&limit=1&order=desc",
3145        )
3146        .await;
3147        assert_eq!(
3148            desc.events[0].id,
3149            *kept.last().unwrap(),
3150            "order=desc&limit=1 over an excluded view is the newest SURVIVOR"
3151        );
3152
3153        // One prefix excludes only its namespace; a prefix matching nothing
3154        // excludes nothing.
3155        let audit_only = query_page(&store, "exclude_event_type_prefix=audit.").await;
3156        assert_eq!(audit_only.total_count, 9, "12 minus the 3 audit.* events");
3157        let nothing = query_page(&store, "exclude_event_type_prefix=nosuch.").await;
3158        assert_eq!(nothing.total_count, 12);
3159    }
3160
3161    // `since`/`until`/`as_of` must narrow the result set on EVERY query shape,
3162    // including the one no index narrows: scoped by tenant only, which is what
3163    // the gateway forwards for "this tenant's activity since T" (the Query
3164    // Service passes all three straight through — `@core_compat_filters`).
3165    // Those three filters are evaluated against index entries, and the
3166    // full-scan branch of the store never consults the index, so a tenant-only
3167    // query silently ignored the window and answered with the whole history —
3168    // with `total_count`/`has_more` describing that history too, so a paginator
3169    // walked events the caller had explicitly excluded.
3170    //
3171    // Driven through the real handler and real query-string deserialization:
3172    // the parameters exist on the DTO and parse fine, so nothing at the wire
3173    // layer reveals that no code downstream reads them on this path.
3174    #[tokio::test]
3175    async fn query_events_honours_time_window_without_an_entity_or_type_filter() {
3176        use chrono::{SecondsFormat, SubsecRound};
3177
3178        let store = create_test_store();
3179        // FIXED base, not `Utc::now()`, and truncated to whole seconds.
3180        //
3181        // This test previously seeded from `Utc::now()`, which made it depend on
3182        // the host clock's resolution: Linux hands back nanoseconds, macOS does
3183        // not. `SecondsFormat::Micros` truncates DOWNWARDS, so with a
3184        // nanosecond-bearing base the string `until=<t>` names an instant
3185        // fractionally BEFORE the event stamped at `t`, and an inclusive window
3186        // silently drops its boundary event. It passed on every developer
3187        // machine and failed only in CI — the worst kind of flake.
3188        //
3189        // The nanoseconds below are deliberate: they make the round-trip
3190        // assertion in `at` fail loudly if the `trunc_subsecs(0)` is ever
3191        // removed, on every platform rather than only on one.
3192        let base = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00.123456789Z")
3193            .unwrap()
3194            .to_utc()
3195            .trunc_subsecs(0);
3196        let mut ids = Vec::new();
3197        for i in 0..5i64 {
3198            let mut event = create_test_event(&format!("e-{i}"), "user.created");
3199            event.timestamp = base + chrono::Duration::hours(i);
3200            event.version = i + 1;
3201            ids.push(event.id);
3202            store.ingest(&event).unwrap();
3203        }
3204        // `Z`-suffixed so the timestamp survives a query string — an offset of
3205        // `+00:00` would be decoded as a space.
3206        let at = |h: i64| {
3207            let t = base + chrono::Duration::hours(h);
3208            let s = t.to_rfc3339_opts(SecondsFormat::Micros, true);
3209            // Pin the invariant the whole test rests on: the formatted string
3210            // must name the SAME instant the event carries. If a future edit
3211            // drops the `trunc_subsecs(0)` above, this fails on every platform
3212            // rather than only on the ones with a nanosecond clock.
3213            assert_eq!(
3214                chrono::DateTime::parse_from_rfc3339(&s).unwrap().to_utc(),
3215                t,
3216                "query-string timestamp must round-trip exactly, else the window \
3217                 boundary silently excludes the event stamped at it"
3218            );
3219            s
3220        };
3221
3222        for (qs, expected) in [
3223            (format!("since={}", at(2)), vec![ids[2], ids[3], ids[4]]),
3224            (format!("until={}", at(1)), vec![ids[0], ids[1]]),
3225            (format!("as_of={}", at(1)), vec![ids[0], ids[1]]),
3226            (
3227                format!("since={}&until={}", at(1), at(3)),
3228                vec![ids[1], ids[2], ids[3]],
3229            ),
3230        ] {
3231            let resp = query_page(&store, &qs).await;
3232            let got: Vec<_> = resp.events.iter().map(|e| e.id).collect();
3233            assert_eq!(got, expected, "?{qs} must return only the window");
3234            assert_eq!(resp.count, expected.len(), "?{qs}");
3235            assert_eq!(
3236                resp.total_count,
3237                expected.len(),
3238                "?{qs}: total_count must count the window, not the history"
3239            );
3240            assert!(!resp.has_more, "?{qs}: the whole window was served");
3241        }
3242
3243        // The window composes with paging: page 2 of a `since` window is the
3244        // second page OF THAT WINDOW, and `has_more` terminates on it.
3245        let page1 = query_page(&store, &format!("since={}&limit=2", at(2))).await;
3246        let page2 = query_page(&store, &format!("since={}&limit=2&offset=2", at(2))).await;
3247        assert_eq!(
3248            page1.events.iter().map(|e| e.id).collect::<Vec<_>>(),
3249            vec![ids[2], ids[3]]
3250        );
3251        assert!(page1.has_more, "3 in the window, 2 served");
3252        assert_eq!(
3253            page2.events.iter().map(|e| e.id).collect::<Vec<_>>(),
3254            vec![ids[4]]
3255        );
3256        assert!(!page2.has_more, "offset 2 + count 1 == the window's 3");
3257        assert_eq!(page2.total_count, 3);
3258
3259        // …and with `order=desc`.
3260        let desc = query_page(&store, &format!("since={}&order=desc", at(2))).await;
3261        assert_eq!(
3262            desc.events.iter().map(|e| e.id).collect::<Vec<_>>(),
3263            vec![ids[4], ids[3], ids[2]]
3264        );
3265
3266        // An empty window is empty, not "everything".
3267        let empty = query_page(&store, &format!("since={}", at(99))).await;
3268        assert_eq!(empty.count, 0);
3269        assert_eq!(empty.total_count, 0);
3270        assert!(!empty.has_more);
3271    }
3272
3273    // Tenant-isolation gate: the public events query must fail CLOSED — a request
3274    // with no auth context and no tenant_id returns nothing, never a cross-tenant
3275    // scan. Calls the real handler so the boundary check is exercised.
3276    #[tokio::test]
3277    async fn query_events_fails_closed_without_tenant() {
3278        use axum::extract::{Query, State};
3279
3280        let store = create_test_store();
3281        for i in 0..5 {
3282            store
3283                .ingest(&create_test_event(&format!("e-{i}"), "user.created"))
3284                .unwrap();
3285        }
3286
3287        let resp = query_events(
3288            OptionalAuth(None),
3289            Query(QueryEventsRequest::default()),
3290            Query(EventOrderParam { order: None }),
3291            Query(EventOffsetParam { offset: None }),
3292            Query(EventIntegrityParam::default()),
3293            State(store.clone()),
3294        )
3295        .await
3296        .unwrap();
3297        assert_eq!(
3298            resp.0.total_count, 0,
3299            "a no-tenant query must NOT return cross-tenant events"
3300        );
3301        assert_eq!(resp.0.count, 0);
3302
3303        // The same query scoped to the events' tenant returns them.
3304        // (create_test_event stamps tenant "test-stream" — the 3rd from_strings arg.)
3305        let scoped = query_events(
3306            OptionalAuth(None),
3307            Query(QueryEventsRequest {
3308                tenant_id: Some("test-stream".to_string()),
3309                ..QueryEventsRequest::default()
3310            }),
3311            Query(EventOrderParam { order: None }),
3312            Query(EventOffsetParam { offset: None }),
3313            Query(EventIntegrityParam::default()),
3314            State(store),
3315        )
3316        .await
3317        .unwrap();
3318        assert_eq!(
3319            scoped.0.total_count, 5,
3320            "tenant-scoped query returns its events"
3321        );
3322    }
3323
3324    // The dashboard's streams + event-types counts must be per-tenant. These
3325    // endpoints used to scan ALL tenants (platform totals shown as "yours", and a
3326    // cross-tenant spill). Assert each tenant sees only its own, and no-tenant
3327    // fails closed.
3328    #[tokio::test]
3329    async fn list_streams_and_types_are_tenant_scoped() {
3330        use crate::domain::entities::Event;
3331        use axum::extract::{Query, State};
3332
3333        let store = create_test_store();
3334        let ev = |entity: &str, etype: &str, tenant: &str| {
3335            Event::from_strings(
3336                etype.to_string(),
3337                entity.to_string(),
3338                tenant.to_string(),
3339                serde_json::json!({}),
3340                None,
3341            )
3342            .unwrap()
3343        };
3344        // tenant A: 2 entities, 2 types. tenant B: 1 entity, 1 type.
3345        store.ingest(&ev("e1", "order.placed", "tenant-a")).unwrap();
3346        store.ingest(&ev("e2", "user.created", "tenant-a")).unwrap();
3347        store
3348            .ingest(&ev("e9", "thing.happened", "tenant-b"))
3349            .unwrap();
3350
3351        let streams = |tid: Option<&str>| {
3352            list_streams(
3353                OptionalAuth(None),
3354                State(store.clone()),
3355                Query(ListStreamsParams {
3356                    tenant_id: tid.map(String::from),
3357                    limit: None,
3358                    offset: None,
3359                }),
3360            )
3361        };
3362        assert_eq!(
3363            streams(Some("tenant-a")).await.0.total,
3364            2,
3365            "tenant-a streams"
3366        );
3367        assert_eq!(
3368            streams(Some("tenant-b")).await.0.total,
3369            1,
3370            "tenant-b streams"
3371        );
3372        assert_eq!(
3373            streams(None).await.0.total,
3374            0,
3375            "no tenant -> no streams (fail closed)"
3376        );
3377
3378        let types = |tid: Option<&str>| {
3379            list_event_types(
3380                OptionalAuth(None),
3381                State(store.clone()),
3382                Query(ListEventTypesParams {
3383                    tenant_id: tid.map(String::from),
3384                    limit: None,
3385                    offset: None,
3386                }),
3387            )
3388        };
3389        assert_eq!(
3390            types(Some("tenant-a")).await.0.total,
3391            2,
3392            "tenant-a event types"
3393        );
3394        assert_eq!(
3395            types(Some("tenant-b")).await.0.total,
3396            1,
3397            "tenant-b event types"
3398        );
3399        assert_eq!(
3400            types(None).await.0.total,
3401            0,
3402            "no tenant -> no types (fail closed)"
3403        );
3404    }
3405
3406    #[tokio::test]
3407    async fn test_query_events_no_more_results() {
3408        let store = create_test_store();
3409
3410        // Ingest 5 events
3411        for i in 0..5 {
3412            store
3413                .ingest(&create_test_event(&format!("entity-{i}"), "user.created"))
3414                .unwrap();
3415        }
3416
3417        // Query with limit=100 — should get has_more=false, total_count=5
3418        let all_events = store
3419            .query(&QueryEventsRequest {
3420                entity_id: None,
3421                event_type: None,
3422                tenant_id: None,
3423                as_of: None,
3424                since: None,
3425                until: None,
3426                limit: None,
3427                event_type_prefix: None,
3428                exclude_event_type_prefix: None,
3429                payload_filter: None,
3430            })
3431            .unwrap();
3432        let total_count = all_events.len();
3433        let limited_events: Vec<Event> = all_events.into_iter().take(100).collect();
3434        let count = limited_events.len();
3435        let has_more = count < total_count;
3436
3437        assert_eq!(count, 5);
3438        assert_eq!(total_count, 5);
3439        assert!(!has_more);
3440    }
3441
3442    // Regression test for issue #177: `order=desc` + `limit=1` must return
3443    // the NEWEST event for an entity, not the oldest. Mirrors the ordering
3444    // logic in `query_events` (store.query → reverse-if-desc → take(limit)).
3445    #[tokio::test]
3446    async fn test_query_events_order_desc_returns_latest() {
3447        // Drives the REAL handler. An earlier version of this test rebuilt the
3448        // ordering inline (`ascending.clone(); reverse(); take(1)`) and never
3449        // called `query_events`, so it could not fail on a mis-composition in
3450        // the code that actually serves `order=desc` — which since issue #251
3451        // lives in `EventStore::query_window`, not in the handler.
3452        let store = create_test_store();
3453
3454        // Five events for the same entity with strictly increasing timestamps —
3455        // mimics a backfill appending corrected events.
3456        let base = chrono::Utc::now();
3457        let mut ascending_ids = Vec::new();
3458        for i in 0..5i64 {
3459            let mut event = create_test_event("org-1", "auth.org.updated");
3460            event.timestamp = base + chrono::Duration::seconds(i);
3461            event.version = i + 1;
3462            ascending_ids.push(event.id);
3463            store.ingest(&event).unwrap();
3464        }
3465        let newest_ts = base + chrono::Duration::seconds(4);
3466
3467        // The documented "latest event for an entity" read.
3468        let latest = query_page(&store, "entity_id=org-1&limit=1&order=desc").await;
3469        assert_eq!(latest.count, 1);
3470        assert_eq!(
3471            latest.events[0].id,
3472            ascending_ids[4],
3473            "order=desc&limit=1 must yield the NEWEST event, got the one at \
3474             ascending position {:?}",
3475            ascending_ids
3476                .iter()
3477                .position(|id| *id == latest.events[0].id)
3478        );
3479        assert_eq!(latest.events[0].timestamp, newest_ts);
3480        assert_eq!(latest.total_count, 5, "total is the full match set");
3481        assert!(latest.has_more);
3482
3483        // Default order (and an explicit `asc`) still yields the OLDEST.
3484        for qs in [
3485            "entity_id=org-1&limit=1",
3486            "entity_id=org-1&limit=1&order=asc",
3487        ] {
3488            let oldest = query_page(&store, qs).await;
3489            assert_eq!(oldest.events[0].id, ascending_ids[0], "{qs}");
3490            assert_eq!(oldest.events[0].timestamp, base);
3491        }
3492
3493        // An unbounded desc page is the exact reverse of the ascending one —
3494        // reversal must apply to the whole match set, not just to the page.
3495        let all_desc = query_page(&store, "entity_id=org-1&order=desc").await;
3496        let got: Vec<_> = all_desc.events.iter().map(|e| e.id).collect();
3497        let expected: Vec<_> = ascending_ids.iter().rev().copied().collect();
3498        assert_eq!(got, expected, "order=desc must return newest-first");
3499    }
3500
3501    // Regression guard for issue #251's relocation of the ordering: `order=desc`
3502    // moved out of the handler and into `EventStore::query_window`, where it now
3503    // composes with `offset` and `limit`. The contract is reverse-THEN-skip-THEN-
3504    // take: `order=desc&offset=1&limit=2` is "the 2nd and 3rd newest". Skipping
3505    // before reversing (or reversing only the page) returns a different, quietly
3506    // wrong page — with the same count, total_count and has_more.
3507    #[tokio::test]
3508    async fn query_events_desc_composes_with_offset_and_limit() {
3509        let store = create_test_store();
3510        let base = chrono::Utc::now();
3511        let mut ascending_ids = Vec::new();
3512        for i in 0..5i64 {
3513            let mut event = create_test_event("org-1", "auth.org.updated");
3514            event.timestamp = base + chrono::Duration::seconds(i);
3515            event.version = i + 1;
3516            ascending_ids.push(event.id);
3517            store.ingest(&event).unwrap();
3518        }
3519        let newest_first: Vec<_> = ascending_ids.iter().rev().copied().collect();
3520
3521        for (offset, limit) in [(0, 2), (1, 2), (2, 2), (3, 2), (4, 2), (5, 2), (1, 4)] {
3522            let page = query_page(
3523                &store,
3524                &format!("entity_id=org-1&order=desc&offset={offset}&limit={limit}"),
3525            )
3526            .await;
3527            let got: Vec<_> = page.events.iter().map(|e| e.id).collect();
3528            let expected: Vec<_> = newest_first
3529                .iter()
3530                .skip(offset)
3531                .take(limit)
3532                .copied()
3533                .collect();
3534            assert_eq!(
3535                got, expected,
3536                "order=desc&offset={offset}&limit={limit} must reverse, then \
3537                 skip, then take"
3538            );
3539            assert_eq!(page.count, expected.len());
3540            assert_eq!(page.total_count, 5);
3541            assert_eq!(
3542                page.has_more,
3543                offset + expected.len() < 5,
3544                "has_more must account for the offset (offset={offset})"
3545            );
3546        }
3547
3548        // Walking the whole entity newest-first must visit every event exactly
3549        // once — the property a `order=desc` paginator depends on.
3550        let mut walked = Vec::new();
3551        for offset in (0..5).step_by(2) {
3552            let page = query_page(
3553                &store,
3554                &format!("entity_id=org-1&order=desc&offset={offset}&limit=2"),
3555            )
3556            .await;
3557            walked.extend(page.events.iter().map(|e| e.id));
3558        }
3559        assert_eq!(walked, newest_first, "desc paging must cover the set once");
3560    }
3561
3562    #[tokio::test]
3563    async fn test_list_entities_by_type_prefix() {
3564        let store = create_test_store();
3565
3566        // 3 index entities
3567        store
3568            .ingest(&create_test_event("idx-1", "index.created"))
3569            .unwrap();
3570        store
3571            .ingest(&create_test_event("idx-1", "index.updated"))
3572            .unwrap();
3573        store
3574            .ingest(&create_test_event("idx-2", "index.created"))
3575            .unwrap();
3576        store
3577            .ingest(&create_test_event("idx-3", "index.created"))
3578            .unwrap();
3579        // 2 trade entities
3580        store
3581            .ingest(&create_test_event("trade-1", "trade.created"))
3582            .unwrap();
3583        store
3584            .ingest(&create_test_event("trade-2", "trade.created"))
3585            .unwrap();
3586
3587        // List entities for index.*
3588        let req = ListEntitiesRequest {
3589            event_type_prefix: Some("index.".to_string()),
3590            ..Default::default()
3591        };
3592        let query_req = QueryEventsRequest {
3593            entity_id: None,
3594            event_type: None,
3595            tenant_id: None,
3596            as_of: None,
3597            since: None,
3598            until: None,
3599            limit: None,
3600            event_type_prefix: req.event_type_prefix,
3601            exclude_event_type_prefix: None,
3602            payload_filter: req.payload_filter,
3603        };
3604        let events = store.query(&query_req).unwrap();
3605
3606        // Group and verify
3607        let mut entity_map: std::collections::HashMap<String, Vec<&Event>> =
3608            std::collections::HashMap::new();
3609        for event in &events {
3610            entity_map
3611                .entry(event.entity_id().to_string())
3612                .or_default()
3613                .push(event);
3614        }
3615
3616        assert_eq!(entity_map.len(), 3); // idx-1, idx-2, idx-3
3617        assert_eq!(entity_map["idx-1"].len(), 2); // 2 events for idx-1
3618        assert_eq!(entity_map["idx-2"].len(), 1);
3619        assert_eq!(entity_map["idx-3"].len(), 1);
3620    }
3621
3622    // Issue #178: `list_entities` accepts an `order` param and pages
3623    // deterministically over the resulting sort.
3624    #[tokio::test]
3625    async fn test_list_entities_order_and_pagination() {
3626        let store = create_test_store();
3627
3628        // Three entities with strictly increasing last-event times.
3629        let base = chrono::Utc::now();
3630        for (i, eid) in ["org-a", "org-b", "org-c"].iter().enumerate() {
3631            let mut event = create_test_event(eid, "auth.org.created");
3632            event.timestamp = base + chrono::Duration::seconds(i as i64);
3633            store.ingest(&event).unwrap();
3634        }
3635        let prefix = || Some("auth.org.".to_string());
3636
3637        // Default: newest activity first (desc) — preserves prior behavior.
3638        let desc = list_entities(
3639            State(store.clone()),
3640            Query(ListEntitiesRequest {
3641                event_type_prefix: prefix(),
3642                ..Default::default()
3643            }),
3644        )
3645        .await
3646        .unwrap();
3647        let desc_ids: Vec<&str> = desc
3648            .0
3649            .entities
3650            .iter()
3651            .map(|e| e.entity_id.as_str())
3652            .collect();
3653        assert_eq!(desc_ids, ["org-c", "org-b", "org-a"]);
3654
3655        // order=asc: oldest activity first.
3656        let asc = list_entities(
3657            State(store.clone()),
3658            Query(ListEntitiesRequest {
3659                event_type_prefix: prefix(),
3660                order: Some("asc".to_string()),
3661                ..Default::default()
3662            }),
3663        )
3664        .await
3665        .unwrap();
3666        let asc_ids: Vec<&str> = asc
3667            .0
3668            .entities
3669            .iter()
3670            .map(|e| e.entity_id.as_str())
3671            .collect();
3672        assert_eq!(asc_ids, ["org-a", "org-b", "org-c"]);
3673
3674        // Offset pagination over the deterministic asc order: page 2, size 1.
3675        let page2 = list_entities(
3676            State(store.clone()),
3677            Query(ListEntitiesRequest {
3678                event_type_prefix: prefix(),
3679                order: Some("asc".to_string()),
3680                limit: Some(1),
3681                offset: Some(1),
3682                ..Default::default()
3683            }),
3684        )
3685        .await
3686        .unwrap();
3687        assert_eq!(page2.0.entities.len(), 1);
3688        assert_eq!(page2.0.entities[0].entity_id, "org-b");
3689        assert_eq!(page2.0.total, 3);
3690        assert!(page2.0.has_more);
3691
3692        // Invalid order value is rejected.
3693        let err = list_entities(
3694            State(store.clone()),
3695            Query(ListEntitiesRequest {
3696                event_type_prefix: prefix(),
3697                order: Some("sideways".to_string()),
3698                ..Default::default()
3699            }),
3700        )
3701        .await;
3702        assert!(err.is_err(), "invalid order value must be rejected");
3703    }
3704
3705    fn create_test_event_with_payload(
3706        entity_id: &str,
3707        event_type: &str,
3708        payload: serde_json::Value,
3709    ) -> Event {
3710        Event::from_strings(
3711            event_type.to_string(),
3712            entity_id.to_string(),
3713            "test-stream".to_string(),
3714            payload,
3715            None,
3716        )
3717        .unwrap()
3718    }
3719
3720    #[tokio::test]
3721    async fn test_detect_duplicates_by_payload_fields() {
3722        let store = create_test_store();
3723
3724        // Create entities with duplicate "name" field values
3725        store
3726            .ingest(&create_test_event_with_payload(
3727                "idx-1",
3728                "index.created",
3729                serde_json::json!({"name": "S&P 500", "user_id": "alice"}),
3730            ))
3731            .unwrap();
3732        store
3733            .ingest(&create_test_event_with_payload(
3734                "idx-2",
3735                "index.created",
3736                serde_json::json!({"name": "S&P 500", "user_id": "bob"}),
3737            ))
3738            .unwrap();
3739        store
3740            .ingest(&create_test_event_with_payload(
3741                "idx-3",
3742                "index.created",
3743                serde_json::json!({"name": "NASDAQ", "user_id": "alice"}),
3744            ))
3745            .unwrap();
3746        store
3747            .ingest(&create_test_event_with_payload(
3748                "idx-4",
3749                "index.created",
3750                serde_json::json!({"name": "NASDAQ", "user_id": "carol"}),
3751            ))
3752            .unwrap();
3753        store
3754            .ingest(&create_test_event_with_payload(
3755                "idx-5",
3756                "index.created",
3757                serde_json::json!({"name": "DAX", "user_id": "dave"}),
3758            ))
3759            .unwrap();
3760
3761        // Group by name — should find 2 groups: "S&P 500" (idx-1, idx-2) and "NASDAQ" (idx-3, idx-4)
3762        let query_req = QueryEventsRequest {
3763            entity_id: None,
3764            event_type: None,
3765            tenant_id: None,
3766            as_of: None,
3767            since: None,
3768            until: None,
3769            limit: None,
3770            event_type_prefix: Some("index.".to_string()),
3771            exclude_event_type_prefix: None,
3772            payload_filter: None,
3773        };
3774        let events = store.query(&query_req).unwrap();
3775
3776        // Manually replicate the handler logic for testing
3777        let group_by_fields = vec!["name"];
3778        let mut entity_latest: std::collections::HashMap<String, &Event> =
3779            std::collections::HashMap::new();
3780        for event in &events {
3781            let eid = event.entity_id().to_string();
3782            entity_latest
3783                .entry(eid)
3784                .and_modify(|existing| {
3785                    if event.timestamp() > existing.timestamp() {
3786                        *existing = event;
3787                    }
3788                })
3789                .or_insert(event);
3790        }
3791
3792        let mut groups: std::collections::HashMap<String, Vec<String>> =
3793            std::collections::HashMap::new();
3794        for (entity_id, event) in &entity_latest {
3795            let payload = event.payload();
3796            let mut key_parts = serde_json::Map::new();
3797            for field in &group_by_fields {
3798                let value = payload
3799                    .get(*field)
3800                    .cloned()
3801                    .unwrap_or(serde_json::Value::Null);
3802                key_parts.insert((*field).to_string(), value);
3803            }
3804            let key_str = serde_json::to_string(&key_parts).unwrap_or_default();
3805            groups.entry(key_str).or_default().push(entity_id.clone());
3806        }
3807
3808        let duplicate_groups: Vec<_> = groups
3809            .into_iter()
3810            .filter(|(_, ids)| ids.len() > 1)
3811            .collect();
3812
3813        assert_eq!(duplicate_groups.len(), 2); // S&P 500 and NASDAQ groups
3814        for (_, ids) in &duplicate_groups {
3815            assert_eq!(ids.len(), 2);
3816        }
3817    }
3818
3819    #[tokio::test]
3820    async fn test_detect_duplicates_no_duplicates() {
3821        let store = create_test_store();
3822
3823        // All unique names
3824        store
3825            .ingest(&create_test_event_with_payload(
3826                "idx-1",
3827                "index.created",
3828                serde_json::json!({"name": "A"}),
3829            ))
3830            .unwrap();
3831        store
3832            .ingest(&create_test_event_with_payload(
3833                "idx-2",
3834                "index.created",
3835                serde_json::json!({"name": "B"}),
3836            ))
3837            .unwrap();
3838
3839        let query_req = QueryEventsRequest {
3840            entity_id: None,
3841            event_type: None,
3842            tenant_id: None,
3843            as_of: None,
3844            since: None,
3845            until: None,
3846            limit: None,
3847            event_type_prefix: Some("index.".to_string()),
3848            exclude_event_type_prefix: None,
3849            payload_filter: None,
3850        };
3851        let events = store.query(&query_req).unwrap();
3852
3853        let mut entity_latest: std::collections::HashMap<String, &Event> =
3854            std::collections::HashMap::new();
3855        for event in &events {
3856            entity_latest
3857                .entry(event.entity_id().to_string())
3858                .or_insert(event);
3859        }
3860
3861        let mut groups: std::collections::HashMap<String, Vec<String>> =
3862            std::collections::HashMap::new();
3863        for (entity_id, event) in &entity_latest {
3864            let key_str =
3865                serde_json::to_string(&serde_json::json!({"name": event.payload().get("name")}))
3866                    .unwrap();
3867            groups.entry(key_str).or_default().push(entity_id.clone());
3868        }
3869
3870        let duplicate_groups: Vec<_> = groups
3871            .into_iter()
3872            .filter(|(_, ids)| ids.len() > 1)
3873            .collect();
3874
3875        assert_eq!(duplicate_groups.len(), 0); // No duplicates
3876    }
3877
3878    #[tokio::test]
3879    async fn test_detect_duplicates_multi_field_group_by() {
3880        let store = create_test_store();
3881
3882        // Two entities with same name AND user_id = true duplicate
3883        store
3884            .ingest(&create_test_event_with_payload(
3885                "idx-1",
3886                "index.created",
3887                serde_json::json!({"name": "S&P 500", "user_id": "alice"}),
3888            ))
3889            .unwrap();
3890        store
3891            .ingest(&create_test_event_with_payload(
3892                "idx-2",
3893                "index.created",
3894                serde_json::json!({"name": "S&P 500", "user_id": "alice"}),
3895            ))
3896            .unwrap();
3897        // Same name but different user_id = NOT a duplicate in multi-field group
3898        store
3899            .ingest(&create_test_event_with_payload(
3900                "idx-3",
3901                "index.created",
3902                serde_json::json!({"name": "S&P 500", "user_id": "bob"}),
3903            ))
3904            .unwrap();
3905
3906        let query_req = QueryEventsRequest {
3907            entity_id: None,
3908            event_type: None,
3909            tenant_id: None,
3910            as_of: None,
3911            since: None,
3912            until: None,
3913            limit: None,
3914            event_type_prefix: Some("index.".to_string()),
3915            exclude_event_type_prefix: None,
3916            payload_filter: None,
3917        };
3918        let events = store.query(&query_req).unwrap();
3919
3920        let group_by_fields = vec!["name", "user_id"];
3921        let mut entity_latest: std::collections::HashMap<String, &Event> =
3922            std::collections::HashMap::new();
3923        for event in &events {
3924            entity_latest
3925                .entry(event.entity_id().to_string())
3926                .and_modify(|existing| {
3927                    if event.timestamp() > existing.timestamp() {
3928                        *existing = event;
3929                    }
3930                })
3931                .or_insert(event);
3932        }
3933
3934        let mut groups: std::collections::HashMap<String, Vec<String>> =
3935            std::collections::HashMap::new();
3936        for (entity_id, event) in &entity_latest {
3937            let payload = event.payload();
3938            let mut key_parts = serde_json::Map::new();
3939            for field in &group_by_fields {
3940                let value = payload
3941                    .get(*field)
3942                    .cloned()
3943                    .unwrap_or(serde_json::Value::Null);
3944                key_parts.insert((*field).to_string(), value);
3945            }
3946            let key_str = serde_json::to_string(&key_parts).unwrap_or_default();
3947            groups.entry(key_str).or_default().push(entity_id.clone());
3948        }
3949
3950        let duplicate_groups: Vec<_> = groups
3951            .into_iter()
3952            .filter(|(_, ids)| ids.len() > 1)
3953            .collect();
3954
3955        // Only 1 duplicate group: name=S&P 500, user_id=alice (idx-1, idx-2)
3956        assert_eq!(duplicate_groups.len(), 1);
3957        let (_, ref ids) = duplicate_groups[0];
3958        assert_eq!(ids.len(), 2);
3959        let mut sorted_ids = ids.clone();
3960        sorted_ids.sort();
3961        assert_eq!(sorted_ids, vec!["idx-1", "idx-2"]);
3962    }
3963
3964    #[tokio::test]
3965    async fn test_projection_state_cache() {
3966        let store = create_test_store();
3967
3968        // Test cache insertion
3969        let cache = store.projection_state_cache();
3970        cache.insert(
3971            "entity_snapshots:user-123".to_string(),
3972            serde_json::json!({"name": "Test User", "age": 30}),
3973        );
3974
3975        // Test cache retrieval
3976        let state = cache.get("entity_snapshots:user-123");
3977        assert!(state.is_some());
3978        let state = state.unwrap();
3979        assert_eq!(state["name"], "Test User");
3980        assert_eq!(state["age"], 30);
3981    }
3982
3983    #[tokio::test]
3984    async fn test_projection_manager_list_projections() {
3985        let store = create_test_store();
3986
3987        // List projections (built-in projections should be available)
3988        let projection_manager = store.projection_manager();
3989        let projections = projection_manager.list_projections();
3990
3991        // Should have entity_snapshots and event_counters
3992        assert!(projections.len() >= 2);
3993
3994        let names: Vec<&str> = projections.iter().map(|(name, _)| name.as_str()).collect();
3995        assert!(names.contains(&"entity_snapshots"));
3996        assert!(names.contains(&"event_counters"));
3997    }
3998
3999    #[tokio::test]
4000    async fn test_projection_state_after_event_ingestion() {
4001        let store = create_test_store();
4002
4003        // Ingest an event
4004        let event = create_test_event("user-456", "user.created");
4005        store.ingest(&event).unwrap();
4006
4007        // Get projection state
4008        let projection_manager = store.projection_manager();
4009        let snapshot_projection = projection_manager
4010            .get_projection("entity_snapshots")
4011            .unwrap();
4012
4013        let state = snapshot_projection.get_state("user-456");
4014        assert!(state.is_some());
4015        let state = state.unwrap();
4016        assert_eq!(state["name"], "Test");
4017        assert_eq!(state["value"], 42);
4018    }
4019
4020    #[tokio::test]
4021    async fn test_projection_state_cache_multiple_entities() {
4022        let store = create_test_store();
4023        let cache = store.projection_state_cache();
4024
4025        // Insert multiple entities
4026        for i in 0..10 {
4027            cache.insert(
4028                format!("entity_snapshots:entity-{i}"),
4029                serde_json::json!({"id": i, "status": "active"}),
4030            );
4031        }
4032
4033        // Verify all insertions
4034        assert_eq!(cache.len(), 10);
4035
4036        // Verify each entity
4037        for i in 0..10 {
4038            let key = format!("entity_snapshots:entity-{i}");
4039            let state = cache.get(&key);
4040            assert!(state.is_some());
4041            assert_eq!(state.unwrap()["id"], i);
4042        }
4043    }
4044
4045    #[tokio::test]
4046    async fn test_projection_state_update() {
4047        let store = create_test_store();
4048        let cache = store.projection_state_cache();
4049
4050        // Initial state
4051        cache.insert(
4052            "entity_snapshots:user-789".to_string(),
4053            serde_json::json!({"balance": 100}),
4054        );
4055
4056        // Update state
4057        cache.insert(
4058            "entity_snapshots:user-789".to_string(),
4059            serde_json::json!({"balance": 150}),
4060        );
4061
4062        // Verify update
4063        let state = cache.get("entity_snapshots:user-789").unwrap();
4064        assert_eq!(state["balance"], 150);
4065    }
4066
4067    #[tokio::test]
4068    async fn test_event_counter_projection() {
4069        let store = create_test_store();
4070
4071        // Ingest events of different types
4072        store
4073            .ingest(&create_test_event("user-1", "user.created"))
4074            .unwrap();
4075        store
4076            .ingest(&create_test_event("user-2", "user.created"))
4077            .unwrap();
4078        store
4079            .ingest(&create_test_event("user-1", "user.updated"))
4080            .unwrap();
4081
4082        // Get event counter projection
4083        let projection_manager = store.projection_manager();
4084        let counter_projection = projection_manager.get_projection("event_counters").unwrap();
4085
4086        // Check counts
4087        let created_state = counter_projection.get_state("user.created");
4088        assert!(created_state.is_some());
4089        assert_eq!(created_state.unwrap()["count"], 2);
4090
4091        let updated_state = counter_projection.get_state("user.updated");
4092        assert!(updated_state.is_some());
4093        assert_eq!(updated_state.unwrap()["count"], 1);
4094    }
4095
4096    #[tokio::test]
4097    async fn test_projection_state_cache_key_format() {
4098        let store = create_test_store();
4099        let cache = store.projection_state_cache();
4100
4101        // Test standard key format: {projection_name}:{entity_id}
4102        let key = "orders:order-12345".to_string();
4103        cache.insert(key.clone(), serde_json::json!({"total": 99.99}));
4104
4105        let state = cache.get(&key).unwrap();
4106        assert_eq!(state["total"], 99.99);
4107    }
4108
4109    #[tokio::test]
4110    async fn test_projection_state_cache_removal() {
4111        let store = create_test_store();
4112        let cache = store.projection_state_cache();
4113
4114        // Insert and then remove
4115        cache.insert(
4116            "test:entity-1".to_string(),
4117            serde_json::json!({"data": "value"}),
4118        );
4119        assert_eq!(cache.len(), 1);
4120
4121        cache.remove("test:entity-1");
4122        assert_eq!(cache.len(), 0);
4123        assert!(cache.get("test:entity-1").is_none());
4124    }
4125
4126    #[tokio::test]
4127    async fn test_get_nonexistent_projection() {
4128        let store = create_test_store();
4129        let projection_manager = store.projection_manager();
4130
4131        // Requesting a non-existent projection should return None
4132        let projection = projection_manager.get_projection("nonexistent_projection");
4133        assert!(projection.is_none());
4134    }
4135
4136    #[tokio::test]
4137    async fn test_get_nonexistent_entity_state() {
4138        let store = create_test_store();
4139        let projection_manager = store.projection_manager();
4140
4141        // Get state for non-existent entity
4142        let snapshot_projection = projection_manager
4143            .get_projection("entity_snapshots")
4144            .unwrap();
4145        let state = snapshot_projection.get_state("nonexistent-entity-xyz");
4146        assert!(state.is_none());
4147    }
4148
4149    #[tokio::test]
4150    async fn test_projection_state_cache_concurrent_access() {
4151        let store = create_test_store();
4152        let cache = store.projection_state_cache();
4153
4154        // Simulate concurrent writes
4155        let handles: Vec<_> = (0..10)
4156            .map(|i| {
4157                let cache_clone = cache.clone();
4158                tokio::spawn(async move {
4159                    cache_clone.insert(
4160                        format!("concurrent:entity-{i}"),
4161                        serde_json::json!({"thread": i}),
4162                    );
4163                })
4164            })
4165            .collect();
4166
4167        for handle in handles {
4168            handle.await.unwrap();
4169        }
4170
4171        // All 10 entries should be present
4172        assert_eq!(cache.len(), 10);
4173    }
4174
4175    #[tokio::test]
4176    async fn test_projection_state_large_payload() {
4177        let store = create_test_store();
4178        let cache = store.projection_state_cache();
4179
4180        // Create a large JSON payload (~10KB)
4181        let large_array: Vec<serde_json::Value> = (0..1000)
4182            .map(|i| serde_json::json!({"item": i, "description": "test item with some padding data to increase size"}))
4183            .collect();
4184
4185        cache.insert(
4186            "large:entity-1".to_string(),
4187            serde_json::json!({"items": large_array}),
4188        );
4189
4190        let state = cache.get("large:entity-1").unwrap();
4191        let items = state["items"].as_array().unwrap();
4192        assert_eq!(items.len(), 1000);
4193    }
4194
4195    #[tokio::test]
4196    async fn test_projection_state_complex_json() {
4197        let store = create_test_store();
4198        let cache = store.projection_state_cache();
4199
4200        // Complex nested JSON structure
4201        let complex_state = serde_json::json!({
4202            "user": {
4203                "id": "user-123",
4204                "profile": {
4205                    "name": "John Doe",
4206                    "email": "john@example.com",
4207                    "settings": {
4208                        "theme": "dark",
4209                        "notifications": true
4210                    }
4211                },
4212                "roles": ["admin", "user"],
4213                "metadata": {
4214                    "created_at": "2025-01-01T00:00:00Z",
4215                    "last_login": null
4216                }
4217            }
4218        });
4219
4220        cache.insert("complex:user-123".to_string(), complex_state);
4221
4222        let state = cache.get("complex:user-123").unwrap();
4223        assert_eq!(state["user"]["profile"]["name"], "John Doe");
4224        assert_eq!(state["user"]["roles"][0], "admin");
4225        assert!(state["user"]["metadata"]["last_login"].is_null());
4226    }
4227
4228    #[tokio::test]
4229    async fn test_projection_state_cache_iteration() {
4230        let store = create_test_store();
4231        let cache = store.projection_state_cache();
4232
4233        // Insert entries
4234        for i in 0..5 {
4235            cache.insert(format!("iter:entity-{i}"), serde_json::json!({"index": i}));
4236        }
4237
4238        // Iterate over all entries
4239        let entries: Vec<_> = cache.iter().map(|entry| entry.key().clone()).collect();
4240        assert_eq!(entries.len(), 5);
4241    }
4242
4243    #[tokio::test]
4244    async fn test_projection_manager_get_entity_snapshots() {
4245        let store = create_test_store();
4246        let projection_manager = store.projection_manager();
4247
4248        // Get entity_snapshots projection specifically
4249        let projection = projection_manager.get_projection("entity_snapshots");
4250        assert!(projection.is_some());
4251        assert_eq!(projection.unwrap().name(), "entity_snapshots");
4252    }
4253
4254    #[tokio::test]
4255    async fn test_projection_manager_get_event_counters() {
4256        let store = create_test_store();
4257        let projection_manager = store.projection_manager();
4258
4259        // Get event_counters projection specifically
4260        let projection = projection_manager.get_projection("event_counters");
4261        assert!(projection.is_some());
4262        assert_eq!(projection.unwrap().name(), "event_counters");
4263    }
4264
4265    #[tokio::test]
4266    async fn test_projection_state_cache_overwrite() {
4267        let store = create_test_store();
4268        let cache = store.projection_state_cache();
4269
4270        // Initial value
4271        cache.insert(
4272            "overwrite:entity-1".to_string(),
4273            serde_json::json!({"version": 1}),
4274        );
4275
4276        // Overwrite with new value
4277        cache.insert(
4278            "overwrite:entity-1".to_string(),
4279            serde_json::json!({"version": 2}),
4280        );
4281
4282        // Overwrite again
4283        cache.insert(
4284            "overwrite:entity-1".to_string(),
4285            serde_json::json!({"version": 3}),
4286        );
4287
4288        let state = cache.get("overwrite:entity-1").unwrap();
4289        assert_eq!(state["version"], 3);
4290
4291        // Should still be only 1 entry
4292        assert_eq!(cache.len(), 1);
4293    }
4294
4295    #[tokio::test]
4296    async fn test_projection_state_multiple_projections() {
4297        let store = create_test_store();
4298        let cache = store.projection_state_cache();
4299
4300        // Store states for different projections
4301        cache.insert(
4302            "entity_snapshots:user-1".to_string(),
4303            serde_json::json!({"name": "Alice"}),
4304        );
4305        cache.insert(
4306            "event_counters:user.created".to_string(),
4307            serde_json::json!({"count": 5}),
4308        );
4309        cache.insert(
4310            "custom_projection:order-1".to_string(),
4311            serde_json::json!({"total": 150.0}),
4312        );
4313
4314        // Verify each projection's state
4315        assert_eq!(
4316            cache.get("entity_snapshots:user-1").unwrap()["name"],
4317            "Alice"
4318        );
4319        assert_eq!(
4320            cache.get("event_counters:user.created").unwrap()["count"],
4321            5
4322        );
4323        assert_eq!(
4324            cache.get("custom_projection:order-1").unwrap()["total"],
4325            150.0
4326        );
4327    }
4328
4329    #[tokio::test]
4330    async fn test_bulk_projection_state_access() {
4331        let store = create_test_store();
4332
4333        // Ingest multiple events for different entities
4334        for i in 0..5 {
4335            let event = create_test_event(&format!("bulk-user-{i}"), "user.created");
4336            store.ingest(&event).unwrap();
4337        }
4338
4339        // Get projection and verify bulk access
4340        let projection_manager = store.projection_manager();
4341        let snapshot_projection = projection_manager
4342            .get_projection("entity_snapshots")
4343            .unwrap();
4344
4345        // Verify we can access all entities
4346        for i in 0..5 {
4347            let state = snapshot_projection.get_state(&format!("bulk-user-{i}"));
4348            assert!(state.is_some(), "Entity bulk-user-{i} should have state");
4349        }
4350    }
4351
4352    #[tokio::test]
4353    async fn test_bulk_save_projection_states() {
4354        let store = create_test_store();
4355        let cache = store.projection_state_cache();
4356
4357        // Simulate bulk save request
4358        let states = vec![
4359            BulkSaveStateItem {
4360                entity_id: "bulk-entity-1".to_string(),
4361                state: serde_json::json!({"name": "Entity 1", "value": 100}),
4362            },
4363            BulkSaveStateItem {
4364                entity_id: "bulk-entity-2".to_string(),
4365                state: serde_json::json!({"name": "Entity 2", "value": 200}),
4366            },
4367            BulkSaveStateItem {
4368                entity_id: "bulk-entity-3".to_string(),
4369                state: serde_json::json!({"name": "Entity 3", "value": 300}),
4370            },
4371        ];
4372
4373        let projection_name = "test_projection";
4374
4375        // Save states to cache (simulating bulk_save_projection_states handler)
4376        for item in &states {
4377            cache.insert(
4378                format!("{projection_name}:{}", item.entity_id),
4379                item.state.clone(),
4380            );
4381        }
4382
4383        // Verify all states were saved
4384        assert_eq!(cache.len(), 3);
4385
4386        let state1 = cache.get("test_projection:bulk-entity-1").unwrap();
4387        assert_eq!(state1["name"], "Entity 1");
4388        assert_eq!(state1["value"], 100);
4389
4390        let state2 = cache.get("test_projection:bulk-entity-2").unwrap();
4391        assert_eq!(state2["name"], "Entity 2");
4392        assert_eq!(state2["value"], 200);
4393
4394        let state3 = cache.get("test_projection:bulk-entity-3").unwrap();
4395        assert_eq!(state3["name"], "Entity 3");
4396        assert_eq!(state3["value"], 300);
4397    }
4398
4399    #[tokio::test]
4400    async fn test_bulk_save_empty_states() {
4401        let store = create_test_store();
4402        let cache = store.projection_state_cache();
4403
4404        // Clear cache
4405        cache.clear();
4406
4407        // Empty states should work fine
4408        let states: Vec<BulkSaveStateItem> = vec![];
4409        assert_eq!(states.len(), 0);
4410
4411        // Cache should remain empty
4412        assert_eq!(cache.len(), 0);
4413    }
4414
4415    #[tokio::test]
4416    async fn test_bulk_save_overwrites_existing() {
4417        let store = create_test_store();
4418        let cache = store.projection_state_cache();
4419
4420        // Insert initial state
4421        cache.insert(
4422            "test:entity-1".to_string(),
4423            serde_json::json!({"version": 1, "data": "initial"}),
4424        );
4425
4426        // Bulk save with updated state
4427        let new_state = serde_json::json!({"version": 2, "data": "updated"});
4428        cache.insert("test:entity-1".to_string(), new_state);
4429
4430        // Verify overwrite
4431        let state = cache.get("test:entity-1").unwrap();
4432        assert_eq!(state["version"], 2);
4433        assert_eq!(state["data"], "updated");
4434    }
4435
4436    #[tokio::test]
4437    async fn test_bulk_save_high_volume() {
4438        let store = create_test_store();
4439        let cache = store.projection_state_cache();
4440
4441        // Simulate high volume save (1000 entities)
4442        for i in 0..1000 {
4443            cache.insert(
4444                format!("volume_test:entity-{i}"),
4445                serde_json::json!({"index": i, "status": "active"}),
4446            );
4447        }
4448
4449        // Verify count
4450        assert_eq!(cache.len(), 1000);
4451
4452        // Spot check some entries
4453        assert_eq!(cache.get("volume_test:entity-0").unwrap()["index"], 0);
4454        assert_eq!(cache.get("volume_test:entity-500").unwrap()["index"], 500);
4455        assert_eq!(cache.get("volume_test:entity-999").unwrap()["index"], 999);
4456    }
4457
4458    #[tokio::test]
4459    async fn test_bulk_save_different_projections() {
4460        let store = create_test_store();
4461        let cache = store.projection_state_cache();
4462
4463        // Save to multiple projections in bulk
4464        let projections = ["entity_snapshots", "event_counters", "custom_analytics"];
4465
4466        for proj in &projections {
4467            for i in 0..5 {
4468                cache.insert(
4469                    format!("{proj}:entity-{i}"),
4470                    serde_json::json!({"projection": proj, "id": i}),
4471                );
4472            }
4473        }
4474
4475        // Verify total count (3 projections * 5 entities)
4476        assert_eq!(cache.len(), 15);
4477
4478        // Verify each projection
4479        for proj in &projections {
4480            let state = cache.get(&format!("{proj}:entity-0")).unwrap();
4481            assert_eq!(state["projection"], *proj);
4482        }
4483    }
4484
4485    // -------------------------------------------------------------------------
4486    // Cache-fallback tests for the projection-state read handlers (v0.19.1).
4487    //
4488    // SDK-managed projections write state via save_projection_state /
4489    // bulk_save_projection_states without registering in projection_manager.
4490    // These tests verify the read handlers fall back to the cache instead of
4491    // 404-ing. Registered projection wins where both exist; cache fills the
4492    // gap when not.
4493    // -------------------------------------------------------------------------
4494
4495    #[tokio::test]
4496    async fn get_projection_state_falls_back_to_cache_when_unregistered() {
4497        let store = create_test_store();
4498        store.projection_state_cache().insert(
4499            "assets:BTC".to_string(),
4500            serde_json::json!({"symbol": "BTC", "altname": "Bitcoin"}),
4501        );
4502
4503        let resp = get_projection_state(
4504            State(Arc::clone(&store)),
4505            Path(("assets".to_string(), "BTC".to_string())),
4506        )
4507        .await
4508        .expect("should not error when projection is not registered");
4509
4510        assert_eq!(resp.0["found"], serde_json::Value::Bool(true));
4511        assert_eq!(resp.0["state"]["symbol"], "BTC");
4512        assert_eq!(resp.0["state"]["altname"], "Bitcoin");
4513    }
4514
4515    #[tokio::test]
4516    async fn get_projection_state_returns_not_found_when_absent_everywhere() {
4517        let store = create_test_store();
4518
4519        let resp = get_projection_state(
4520            State(Arc::clone(&store)),
4521            Path(("assets".to_string(), "UNKNOWN".to_string())),
4522        )
4523        .await
4524        .unwrap();
4525
4526        assert_eq!(resp.0["found"], serde_json::Value::Bool(false));
4527        assert_eq!(resp.0["state"], serde_json::Value::Null);
4528    }
4529
4530    #[tokio::test]
4531    async fn get_projection_state_registered_wins_over_cache() {
4532        let store = create_test_store();
4533
4534        // Ingest an event so entity_snapshots (a registered projection) has state.
4535        let event = create_test_event("user-777", "user.created");
4536        store.ingest(&event).unwrap();
4537
4538        // Plant a conflicting cache entry for the same (projection, entity).
4539        store.projection_state_cache().insert(
4540            "entity_snapshots:user-777".to_string(),
4541            serde_json::json!({"stolen": "value"}),
4542        );
4543
4544        let resp = get_projection_state(
4545            State(Arc::clone(&store)),
4546            Path(("entity_snapshots".to_string(), "user-777".to_string())),
4547        )
4548        .await
4549        .unwrap();
4550
4551        // Registered projection wins — cache fallback is only consulted when
4552        // the registered projection has no state for this entity.
4553        assert_eq!(resp.0["found"], serde_json::Value::Bool(true));
4554        assert!(
4555            resp.0["state"].get("stolen").is_none(),
4556            "cache entry must not shadow registered projection state: got {:?}",
4557            resp.0["state"]
4558        );
4559    }
4560
4561    #[tokio::test]
4562    async fn get_projection_state_summary_returns_cache_without_registration() {
4563        let store = create_test_store();
4564        let cache = store.projection_state_cache();
4565        cache.insert("assets:BTC".into(), serde_json::json!({"symbol": "BTC"}));
4566        cache.insert("assets:ETH".into(), serde_json::json!({"symbol": "ETH"}));
4567        // Different projection name — must not appear in the summary.
4568        cache.insert("trades:t-1".into(), serde_json::json!({"x": 1}));
4569
4570        let resp = get_projection_state_summary(
4571            State(Arc::clone(&store)),
4572            Path("assets".to_string()),
4573            Query(ProjectionStateSummaryParams::default()),
4574        )
4575        .await
4576        .unwrap();
4577
4578        assert_eq!(resp.0["total"], 2);
4579        let states = resp.0["states"].as_array().unwrap();
4580        let entity_ids: Vec<&str> = states
4581            .iter()
4582            .map(|s| s["entity_id"].as_str().unwrap())
4583            .collect();
4584        assert!(entity_ids.contains(&"BTC"));
4585        assert!(entity_ids.contains(&"ETH"));
4586    }
4587
4588    #[tokio::test]
4589    async fn bulk_get_projection_states_falls_back_to_cache() {
4590        let store = create_test_store();
4591        let cache = store.projection_state_cache();
4592        cache.insert("assets:BTC".into(), serde_json::json!({"symbol": "BTC"}));
4593        cache.insert("assets:ETH".into(), serde_json::json!({"symbol": "ETH"}));
4594
4595        let req = BulkGetStateRequest {
4596            entity_ids: vec!["BTC".into(), "ETH".into(), "MISSING".into()],
4597        };
4598
4599        let resp = bulk_get_projection_states(
4600            State(Arc::clone(&store)),
4601            Path("assets".to_string()),
4602            Json(req),
4603        )
4604        .await
4605        .unwrap();
4606
4607        assert_eq!(resp.0["total"], 3);
4608        let states = resp.0["states"].as_array().unwrap();
4609        let by_id: std::collections::HashMap<&str, &serde_json::Value> = states
4610            .iter()
4611            .map(|s| (s["entity_id"].as_str().unwrap(), s))
4612            .collect();
4613
4614        assert_eq!(by_id["BTC"]["found"], serde_json::Value::Bool(true));
4615        assert_eq!(by_id["BTC"]["state"]["symbol"], "BTC");
4616        assert_eq!(by_id["ETH"]["found"], serde_json::Value::Bool(true));
4617        assert_eq!(by_id["MISSING"]["found"], serde_json::Value::Bool(false));
4618    }
4619
4620    /// Pins the poll wire shape the Rust SDK's `poll_consumer_events` decodes:
4621    /// `ConsumerEventDto` flattens the event, so its fields sit next to
4622    /// `position` rather than nested under an `event` key.
4623    #[tokio::test]
4624    async fn poll_consumer_events_flattens_event_alongside_position() {
4625        let store = create_test_store();
4626        store
4627            .ingest(&create_test_event("user-1", "user.created"))
4628            .unwrap();
4629        store
4630            .ingest(&create_test_event("user-2", "user.updated"))
4631            .unwrap();
4632        store.consumer_registry().register("w1", &[]);
4633
4634        let resp = poll_consumer_events(
4635            State(Arc::clone(&store)),
4636            Path("w1".to_string()),
4637            Query(ConsumerPollQuery { limit: Some(10) }),
4638        )
4639        .await
4640        .unwrap();
4641
4642        let body = serde_json::to_value(&resp.0).unwrap();
4643        assert_eq!(body["count"], 2);
4644        let first = &body["events"][0];
4645        assert_eq!(first["position"], 1);
4646        assert!(
4647            first.get("event").is_none(),
4648            "event must be flattened, not nested: got {first:?}"
4649        );
4650        assert_eq!(first["event_type"], "user.created");
4651        assert_eq!(first["entity_id"], "user-1");
4652    }
4653}