Skip to main content

allsource_core/infrastructure/web/
api_v1.rs

1/// v1.0 API router with authentication and multi-tenancy
2use crate::infrastructure::di::ServiceContainer;
3#[cfg(feature = "multi-tenant")]
4use crate::infrastructure::web::tenant_api::*;
5use crate::{
6    domain::repositories::TenantRepository,
7    infrastructure::{
8        cluster::{
9            ClusterManager, ClusterMember, GeoReplicationManager, GeoSyncRequest, VoteRequest,
10        },
11        replication::{WalReceiver, WalShipper},
12        security::{
13            auth::AuthManager,
14            middleware::{AuthState, RateLimitState, auth_middleware, rate_limit_middleware},
15            rate_limit::RateLimiter,
16        },
17        web::{audit_api::*, auth_api::*, config_api::*},
18    },
19    store::EventStore,
20};
21use axum::{
22    Json, Router,
23    extract::{Path, State},
24    middleware,
25    response::IntoResponse,
26    routing::{delete, get, post, put},
27};
28use std::sync::Arc;
29use tower_http::{
30    cors::{Any, CorsLayer},
31    trace::TraceLayer,
32};
33
34/// Node role for leader-follower replication
35#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
36#[serde(rename_all = "lowercase")]
37pub enum NodeRole {
38    Leader,
39    Follower,
40}
41
42impl NodeRole {
43    /// Detect role from environment variables.
44    ///
45    /// Checks `ALLSOURCE_ROLE` ("leader" or "follower") first,
46    /// then falls back to `ALLSOURCE_READ_ONLY` ("true" → follower).
47    /// Defaults to `Leader` if neither is set.
48    pub fn from_env() -> Self {
49        if let Ok(role) = std::env::var("ALLSOURCE_ROLE") {
50            match role.to_lowercase().as_str() {
51                "follower" => return NodeRole::Follower,
52                "leader" => return NodeRole::Leader,
53                other => {
54                    tracing::warn!(
55                        "Unknown ALLSOURCE_ROLE value '{}', defaulting to leader",
56                        other
57                    );
58                    return NodeRole::Leader;
59                }
60            }
61        }
62        if let Ok(read_only) = std::env::var("ALLSOURCE_READ_ONLY")
63            && (read_only == "true" || read_only == "1")
64        {
65            return NodeRole::Follower;
66        }
67        NodeRole::Leader
68    }
69
70    pub fn is_follower(self) -> bool {
71        self == NodeRole::Follower
72    }
73
74    fn to_u8(self) -> u8 {
75        match self {
76            NodeRole::Leader => 0,
77            NodeRole::Follower => 1,
78        }
79    }
80
81    fn from_u8(v: u8) -> Self {
82        match v {
83            1 => NodeRole::Follower,
84            _ => NodeRole::Leader,
85        }
86    }
87}
88
89impl std::fmt::Display for NodeRole {
90    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91        match self {
92            NodeRole::Leader => write!(f, "leader"),
93            NodeRole::Follower => write!(f, "follower"),
94        }
95    }
96}
97
98/// Thread-safe, runtime-mutable node role for failover support.
99///
100/// Wraps an `AtomicU8` so the read-only middleware and health endpoint
101/// always see the current role, even after a sentinel-triggered promotion.
102#[derive(Clone)]
103pub struct AtomicNodeRole(Arc<std::sync::atomic::AtomicU8>);
104
105impl AtomicNodeRole {
106    pub fn new(role: NodeRole) -> Self {
107        Self(Arc::new(std::sync::atomic::AtomicU8::new(role.to_u8())))
108    }
109
110    pub fn load(&self) -> NodeRole {
111        NodeRole::from_u8(self.0.load(std::sync::atomic::Ordering::Relaxed))
112    }
113
114    pub fn store(&self, role: NodeRole) {
115        self.0
116            .store(role.to_u8(), std::sync::atomic::Ordering::Relaxed);
117    }
118}
119
120/// Unified application state for all handlers
121#[derive(Clone)]
122pub struct AppState {
123    pub store: Arc<EventStore>,
124    pub auth_manager: Arc<AuthManager>,
125    pub tenant_repo: Arc<dyn TenantRepository>,
126    /// Service container for paywall domain use cases (Creator, Article, Payment, etc.)
127    pub service_container: ServiceContainer,
128    /// Node role for leader-follower replication (runtime-mutable for failover)
129    pub role: AtomicNodeRole,
130    /// WAL shipper for replication status reporting (leader only).
131    /// Wrapped in RwLock so a promoted follower can install a shipper at runtime.
132    pub wal_shipper: Arc<tokio::sync::RwLock<Option<Arc<WalShipper>>>>,
133    /// WAL receiver for replication status reporting (follower only)
134    pub wal_receiver: Option<Arc<WalReceiver>>,
135    /// Replication port used by the WAL shipper (needed for runtime promotion)
136    pub replication_port: u16,
137    /// Cluster manager for multi-node consensus and membership (optional)
138    pub cluster_manager: Option<Arc<ClusterManager>>,
139    /// Geo-replication manager for cross-region replication (optional)
140    pub geo_replication: Option<Arc<GeoReplicationManager>>,
141}
142
143// Enable extracting Arc<EventStore> from AppState
144// This allows handlers that expect State<Arc<EventStore>> to work with AppState
145impl axum::extract::FromRef<AppState> for Arc<EventStore> {
146    fn from_ref(state: &AppState) -> Self {
147        state.store.clone()
148    }
149}
150
151pub async fn serve_v1(
152    store: Arc<EventStore>,
153    auth_manager: Arc<AuthManager>,
154    tenant_repo: Arc<dyn TenantRepository>,
155    rate_limiter: Arc<RateLimiter>,
156    service_container: ServiceContainer,
157    gate: &super::boot_gate::BootGate,
158    role: NodeRole,
159    wal_shipper: Option<Arc<WalShipper>>,
160    wal_receiver: Option<Arc<WalReceiver>>,
161    replication_port: u16,
162    cluster_manager: Option<Arc<ClusterManager>>,
163    geo_replication: Option<Arc<GeoReplicationManager>>,
164) -> anyhow::Result<()> {
165    let app = build_v1_router(
166        store,
167        auth_manager,
168        tenant_repo,
169        rate_limiter,
170        service_container,
171        role,
172        wal_shipper,
173        wal_receiver,
174        replication_port,
175        cluster_manager,
176        geo_replication,
177    )
178    .await;
179    gate.open(app);
180    Ok(())
181}
182
183/// The full v1 router with every layer `serve_v1` serves. The heap replay
184/// drives it in-process, so it must stay the exact production stack.
185pub async fn build_v1_router(
186    store: Arc<EventStore>,
187    auth_manager: Arc<AuthManager>,
188    tenant_repo: Arc<dyn TenantRepository>,
189    rate_limiter: Arc<RateLimiter>,
190    service_container: ServiceContainer,
191    role: NodeRole,
192    wal_shipper: Option<Arc<WalShipper>>,
193    wal_receiver: Option<Arc<WalReceiver>>,
194    replication_port: u16,
195    cluster_manager: Option<Arc<ClusterManager>>,
196    geo_replication: Option<Arc<GeoReplicationManager>>,
197) -> Router {
198    let http_metrics = store.metrics();
199    let app_state = AppState {
200        store,
201        auth_manager: auth_manager.clone(),
202        tenant_repo,
203        service_container,
204        role: AtomicNodeRole::new(role),
205        wal_shipper: Arc::new(tokio::sync::RwLock::new(wal_shipper)),
206        wal_receiver,
207        replication_port,
208        cluster_manager,
209        geo_replication,
210    };
211
212    let auth_state = AuthState {
213        auth_manager: auth_manager.clone(),
214    };
215
216    let rate_limit_state = RateLimitState::new(rate_limiter);
217
218    let app = Router::new()
219        // Public routes (no auth)
220        .route("/health", get(health_v1))
221        .route("/metrics", get(super::api::prometheus_metrics))
222        // Auth routes
223        .route("/api/v1/auth/register", post(register_handler))
224        .route("/api/v1/auth/login", post(login_handler))
225        .route("/api/v1/auth/me", get(me_handler))
226        .route("/api/v1/auth/api-keys", post(create_api_key_handler))
227        .route("/api/v1/auth/api-keys", get(list_api_keys_handler))
228        .route("/api/v1/auth/api-keys/{id}", delete(revoke_api_key_handler))
229        .route("/api/v1/auth/users", get(list_users_handler))
230        .route("/api/v1/auth/users/{id}", delete(delete_user_handler))
231        // Tenant routes (protected — enterprise only)
232        ;
233    #[cfg(feature = "multi-tenant")]
234    let app = app
235        .route("/api/v1/tenants", post(create_tenant_handler))
236        .route("/api/v1/tenants", get(list_tenants_handler))
237        .route("/api/v1/tenants/{id}", get(get_tenant_handler))
238        .route("/api/v1/tenants/{id}", put(update_tenant_handler))
239        .route(
240            "/api/v1/tenants/{id}/metadata",
241            // Qualified path: `patch` is only used here, inside the
242            // `multi-tenant`-gated block, so importing it unconditionally would
243            // warn unused under the community edition.
244            axum::routing::patch(merge_tenant_metadata_handler),
245        )
246        .route("/api/v1/tenants/{id}/stats", get(get_tenant_stats_handler))
247        .route("/api/v1/tenants/{id}/quotas", put(update_quotas_handler))
248        .route(
249            "/api/v1/tenants/{id}/egress",
250            get(super::tenant_egress_api::snapshot)
251                .post(super::tenant_egress_api::mutate)
252                .layer(axum::extract::DefaultBodyLimit::max(2_048)),
253        )
254        .route(
255            "/api/v1/tenants/{id}/usage/increment",
256            post(increment_usage_handler),
257        )
258        .route(
259            "/api/v1/tenants/{id}/usage/queries/admit",
260            post(super::tenant_query_usage_api::admit_query_usage_handler)
261                .layer(axum::extract::DefaultBodyLimit::max(2_048)),
262        )
263        .route(
264            "/api/v1/tenants/{id}/usage/queries",
265            get(super::tenant_query_usage_api::query_usage_handler),
266        )
267        .route(
268            "/api/v1/tenants/{id}/usage/queries/reset",
269            post(super::tenant_query_usage_api::reset_query_usage_handler)
270                .layer(axum::extract::DefaultBodyLimit::max(2_048)),
271        )
272        .route(
273            "/api/v1/tenants/{id}/schema-enforcement",
274            put(update_schema_enforcement_handler),
275        )
276        .route(
277            "/api/v1/tenants/{id}/deactivate",
278            post(deactivate_tenant_handler),
279        )
280        .route(
281            "/api/v1/tenants/{id}/activate",
282            post(activate_tenant_handler),
283        )
284        .route("/api/v1/tenants/{id}", delete(delete_tenant_handler));
285    #[cfg(all(feature = "heap-profile", target_os = "linux"))]
286    let app = app.route(
287        "/api/v1/admin/heap-profile",
288        get(super::heap_profile_api::heap_profile),
289    );
290    let app = app
291        // Audit endpoints (admin only)
292        .route("/api/v1/audit/events", post(log_audit_event))
293        .route("/api/v1/audit/events", get(query_audit_events))
294        // Config endpoints (admin only)
295        .route("/api/v1/config", get(list_configs))
296        .route("/api/v1/config", post(set_config))
297        .route(
298            "/api/v1/config/conditional/set",
299            post(set_config_conditionally),
300        )
301        .route("/api/v1/config/{key}", get(get_config))
302        .route("/api/v1/config/{key}", put(update_config))
303        .route("/api/v1/config/{key}", delete(delete_config))
304        // Demo seeding
305        .route(
306            "/api/v1/demo/seed",
307            post(super::demo_api::demo_seed_handler),
308        )
309        // Event and data routes (protected by auth)
310        .route("/api/v1/events", post(super::api::ingest_event_v1))
311        .route(
312            "/api/v1/events/batch",
313            post(super::api::ingest_events_batch_v1),
314        )
315        .route("/api/v1/events/query", get(super::api::query_events))
316        .route(
317            "/api/v1/events/{event_id}",
318            get(super::api::get_event_by_id),
319        )
320        .route("/api/v1/events/stream", get(super::api::events_websocket))
321        .route("/api/v1/entities", get(super::api::list_entities))
322        .route(
323            "/api/v1/entities/duplicates",
324            get(super::api::detect_duplicates),
325        )
326        .route(
327            "/api/v1/entities/{entity_id}/state",
328            get(super::api::get_entity_state),
329        )
330        .route(
331            "/api/v1/entities/{entity_id}/snapshot",
332            get(super::api::get_entity_snapshot),
333        )
334        .route("/api/v1/stats", get(super::api::get_stats))
335        // v0.10: Stream and event type discovery endpoints
336        .route("/api/v1/streams", get(super::api::list_streams))
337        .route("/api/v1/event-types", get(super::api::list_event_types))
338        // Analytics
339        .route(
340            "/api/v1/analytics/frequency",
341            get(super::api::analytics_frequency),
342        )
343        .route(
344            "/api/v1/analytics/summary",
345            get(super::api::analytics_summary),
346        )
347        .route(
348            "/api/v1/analytics/correlation",
349            get(super::api::analytics_correlation),
350        )
351        // Compaction
352        .route(
353            "/api/v1/compaction/trigger",
354            post(super::api::trigger_compaction),
355        )
356        .route(
357            "/api/v1/compaction/stats",
358            get(super::api::compaction_stats),
359        )
360        // Schemas
361        .route("/api/v1/schemas", post(super::api::register_schema))
362        .route("/api/v1/schemas", get(super::api::list_subjects))
363        .route("/api/v1/schemas/{subject}", get(super::api::get_schema))
364        .route(
365            "/api/v1/schemas/{subject}/versions",
366            get(super::api::list_schema_versions),
367        )
368        .route(
369            "/api/v1/schemas/validate",
370            post(super::api::validate_event_schema),
371        )
372        .route(
373            "/api/v1/schemas/{subject}/compatibility",
374            put(super::api::set_compatibility_mode),
375        )
376        // Replay
377        .route("/api/v1/replay", post(super::api::start_replay))
378        .route("/api/v1/replay", get(super::api::list_replays))
379        .route(
380            "/api/v1/replay/{replay_id}",
381            get(super::api::get_replay_progress),
382        )
383        .route(
384            "/api/v1/replay/{replay_id}/cancel",
385            post(super::api::cancel_replay),
386        )
387        .route(
388            "/api/v1/replay/{replay_id}",
389            delete(super::api::delete_replay),
390        )
391        // Pipelines
392        .route("/api/v1/pipelines", post(super::api::register_pipeline))
393        .route("/api/v1/pipelines", get(super::api::list_pipelines))
394        .route(
395            "/api/v1/pipelines/stats",
396            get(super::api::all_pipeline_stats),
397        )
398        .route(
399            "/api/v1/pipelines/{pipeline_id}",
400            get(super::api::get_pipeline),
401        )
402        .route(
403            "/api/v1/pipelines/{pipeline_id}",
404            delete(super::api::remove_pipeline),
405        )
406        .route(
407            "/api/v1/pipelines/{pipeline_id}/stats",
408            get(super::api::get_pipeline_stats),
409        )
410        .route(
411            "/api/v1/pipelines/{pipeline_id}/reset",
412            put(super::api::reset_pipeline),
413        )
414        // Core's internal projections; tenant read models are under /read-models
415        .route("/api/v1/projections", get(super::api::list_projections))
416        .route(
417            "/api/v1/projections/{name}",
418            get(super::api::get_projection),
419        )
420        .route(
421            "/api/v1/projections/{name}",
422            delete(super::api::delete_projection),
423        )
424        .route(
425            "/api/v1/projections/{name}/reset",
426            post(super::api::reset_projection),
427        )
428        .route(
429            "/api/v1/projections/{name}/pause",
430            post(super::api::pause_projection),
431        )
432        .route(
433            "/api/v1/projections/{name}/start",
434            post(super::api::start_projection),
435        )
436        // v0.11: Webhook management
437        .route("/api/v1/webhooks", post(super::api::register_webhook))
438        .route("/api/v1/webhooks", get(super::api::list_webhooks))
439        .route(
440            "/api/v1/webhooks/{webhook_id}",
441            get(super::api::get_webhook),
442        )
443        .route(
444            "/api/v1/webhooks/{webhook_id}",
445            put(super::api::update_webhook),
446        )
447        .route(
448            "/api/v1/webhooks/{webhook_id}",
449            delete(super::api::delete_webhook),
450        )
451        .route(
452            "/api/v1/webhooks/{webhook_id}/deliveries",
453            get(super::api::list_webhook_deliveries),
454        )
455        .route("/api/v1/event-feed", get(super::read_model_api::feed))
456        .route(
457            "/api/v1/read-models/{name}",
458            get(super::read_model_api::read).put(super::read_model_api::commit),
459        )
460        .route("/api/v1/views", get(super::view_api::list_views))
461        .route(
462            "/api/v1/views/{view}",
463            get(super::view_api::get_view)
464                .put(super::view_api::put_view)
465                .delete(super::view_api::delete_view),
466        )
467        .route(
468            "/api/v1/views/{view}/entities",
469            get(super::view_api::list_entities),
470        )
471        .route(
472            "/api/v1/views/{view}/entities/{key}",
473            get(super::view_api::get_entity),
474        )
475        .route(
476            "/api/v1/views/{view}/changes",
477            get(super::view_api::changes),
478        )
479        .route("/api/v1/admin/views", get(super::view_api::admin_views))
480        // v0.14: Durable consumer subscriptions
481        .route("/api/v1/consumers", post(super::api::register_consumer))
482        .route(
483            "/api/v1/consumers/{consumer_id}",
484            get(super::api::get_consumer),
485        )
486        .route(
487            "/api/v1/consumers/{consumer_id}/events",
488            get(super::api::poll_consumer_events),
489        )
490        .route(
491            "/api/v1/consumers/{consumer_id}/ack",
492            post(super::api::ack_consumer),
493        )
494        // v1.8: Cluster membership management API
495        .route("/api/v1/cluster/status", get(cluster_status_handler))
496        .route("/api/v1/cluster/members", get(cluster_list_members_handler))
497        .route("/api/v1/cluster/members", post(cluster_add_member_handler))
498        .route(
499            "/api/v1/cluster/members/{node_id}",
500            delete(cluster_remove_member_handler),
501        )
502        .route(
503            "/api/v1/cluster/members/{node_id}/heartbeat",
504            post(cluster_heartbeat_handler),
505        )
506        .route("/api/v1/cluster/vote", post(cluster_vote_handler))
507        .route("/api/v1/cluster/election", post(cluster_election_handler))
508        .route(
509            "/api/v1/cluster/partitions",
510            get(cluster_partitions_handler),
511        )
512        // v2.0: Advanced query features
513        .route("/api/v1/graphql", post(super::api::graphql_query))
514        .route("/api/v1/geospatial/query", post(super::api::geo_query))
515        .route("/api/v1/geospatial/stats", get(super::api::geo_stats))
516        .route(
517            "/api/v1/exactly-once/stats",
518            get(super::api::exactly_once_stats),
519        )
520        .route(
521            "/api/v1/schema-evolution/history/{event_type}",
522            get(super::api::schema_evolution_history),
523        )
524        .route(
525            "/api/v1/schema-evolution/schema/{event_type}",
526            get(super::api::schema_evolution_schema),
527        )
528        .route(
529            "/api/v1/schema-evolution/stats",
530            get(super::api::schema_evolution_stats),
531        )
532        // v1.9: Geo-replication API
533        .route("/api/v1/geo/status", get(geo_status_handler))
534        .route("/api/v1/geo/sync", post(geo_sync_handler))
535        .route("/api/v1/geo/peers", get(geo_peers_handler))
536        .route("/api/v1/geo/failover", post(geo_failover_handler));
537    // Internal endpoints for sentinel-driven failover (enterprise only)
538    #[cfg(feature = "replication")]
539    let app = app
540        .route("/internal/promote", post(promote_handler))
541        .route("/internal/repoint", post(repoint_handler));
542    let app = app;
543
544    // v0.11: Bidirectional sync protocol (embedded↔server)
545    #[cfg(feature = "embedded-sync")]
546    let app = app
547        .route("/api/v1/sync/pull", post(super::api::sync_pull_handler))
548        .route("/api/v1/sync/push", post(super::api::sync_push_handler));
549
550    let app = app.merge(super::search_api::router(super::search_api::start(
551        Arc::clone(&app_state.store),
552    )));
553
554    let app = app
555        .with_state(app_state.clone())
556        // IMPORTANT: Middleware layers execute from bottom to top in Tower/Axum
557        // Read-only middleware runs after auth (applied before rate limit layer)
558        .layer(middleware::from_fn_with_state(
559            app_state,
560            read_only_middleware,
561        ))
562        .layer(middleware::from_fn_with_state(
563            rate_limit_state,
564            rate_limit_middleware,
565        ))
566        .layer(middleware::from_fn_with_state(auth_state, auth_middleware))
567        .layer(
568            CorsLayer::new()
569                .allow_origin(Any)
570                .allow_methods(Any)
571                .allow_headers(Any),
572        )
573        .layer(TraceLayer::new_for_http());
574
575    // Prime API — nested router with its own state (feature-gated)
576    #[cfg(feature = "prime")]
577    let app = {
578        let data_dir =
579            std::env::var("PRIME_DATA_DIR").unwrap_or_else(|_| "/tmp/prime-data".to_string());
580        match crate::prime::Prime::open(&data_dir).await {
581            Ok(prime) => {
582                let prime_state = Arc::new(super::prime_api::PrimeState { prime });
583                tracing::info!("Prime API enabled at /api/v1/prime/*");
584                app.nest(
585                    "/api/v1/prime",
586                    super::prime_api::prime_router().with_state(prime_state),
587                )
588            }
589            Err(e) => {
590                tracing::warn!("Prime API disabled: failed to open Prime: {e}");
591                app
592            }
593        }
594    };
595
596    app.layer(middleware::from_fn(super::response_limit::bounded))
597        .layer(middleware::from_fn_with_state(
598            http_metrics,
599            super::http_metrics::record,
600        ))
601        .layer(super::response_limit::compression())
602}
603
604/// Write paths that should be rejected when running as a follower.
605const WRITE_PATHS: &[&str] = &[
606    "/api/v1/events",
607    "/api/v1/events/batch",
608    "/api/v1/projections/",
609    "/api/v1/read-models/",
610    "/api/v1/views",
611    "/api/v1/schemas",
612    "/api/v1/replay",
613    "/api/v1/pipelines",
614    "/api/v1/compaction/trigger",
615    "/api/v1/audit/events",
616    "/api/v1/config",
617    "/api/v1/tenants",
618    "/api/v1/webhooks",
619    "/api/v1/demo/seed",
620];
621
622/// Returns true if this request is a write operation that should be blocked on followers.
623fn is_write_request(method: &axum::http::Method, path: &str) -> bool {
624    use axum::http::Method;
625    // Only POST/PUT/DELETE are writes
626    if method != Method::POST && method != Method::PUT && method != Method::DELETE {
627        return false;
628    }
629    WRITE_PATHS
630        .iter()
631        .any(|write_path| path.starts_with(write_path))
632}
633
634/// Returns true if the request targets an internal or cluster endpoint (not subject to read-only checks).
635fn is_internal_request(path: &str) -> bool {
636    path.starts_with("/internal/")
637        || path.starts_with("/api/v1/cluster/")
638        || path.starts_with("/api/v1/geo/")
639}
640
641/// Middleware that rejects write requests when the node is a follower.
642///
643/// Returns HTTP 409 Conflict with `{"error": "read_only", "message": "..."}`.
644/// Internal endpoints (`/internal/*`) are exempt — they are used by the sentinel
645/// to trigger promotion and repointing during failover.
646async fn read_only_middleware(
647    State(state): State<AppState>,
648    request: axum::extract::Request,
649    next: axum::middleware::Next,
650) -> axum::response::Response {
651    let path = request.uri().path();
652    if state.role.load().is_follower()
653        && is_write_request(request.method(), path)
654        && !is_internal_request(path)
655    {
656        return (
657            axum::http::StatusCode::CONFLICT,
658            axum::Json(serde_json::json!({
659                "error": "read_only",
660                "message": "This node is a read-only follower"
661            })),
662        )
663            .into_response();
664    }
665    next.run(request).await
666}
667
668/// Health endpoint with system stream health reporting.
669///
670/// Reports overall health plus detailed system metadata health when
671/// event-sourced system repositories are configured.
672async fn health_v1(State(state): State<AppState>) -> impl IntoResponse {
673    let has_system_repos = state.service_container.has_system_repositories();
674
675    let system_streams = if has_system_repos {
676        let (tenant_count, config_count, total_events) =
677            if let Some(store) = state.service_container.system_store() {
678                use crate::domain::value_objects::system_stream::SystemDomain;
679                (
680                    store.count_stream(SystemDomain::Tenant),
681                    store.count_stream(SystemDomain::Config),
682                    store.total_events(),
683                )
684            } else {
685                (0, 0, 0)
686            };
687
688        serde_json::json!({
689            "status": "healthy",
690            "mode": "event-sourced",
691            "total_events": total_events,
692            "tenant_events": tenant_count,
693            "config_events": config_count,
694        })
695    } else {
696        serde_json::json!({
697            "status": "disabled",
698            "mode": "in-memory",
699        })
700    };
701
702    let replication = {
703        #[cfg(feature = "replication")]
704        {
705            let shipper_guard = state.wal_shipper.read().await;
706            if let Some(ref shipper) = *shipper_guard {
707                serde_json::to_value(shipper.status()).unwrap_or_default()
708            } else if let Some(ref receiver) = state.wal_receiver {
709                serde_json::to_value(receiver.status()).unwrap_or_default()
710            } else {
711                serde_json::json!(null)
712            }
713        }
714        #[cfg(not(feature = "replication"))]
715        serde_json::json!({"edition": "community", "status": "not_available"})
716    };
717
718    let current_role = state.role.load();
719
720    Json(serde_json::json!({
721        "status": "healthy",
722        "service": "allsource-core",
723        "version": env!("CARGO_PKG_VERSION"),
724        "role": current_role,
725        "system_streams": system_streams,
726        "replication": replication,
727    }))
728}
729
730/// POST /internal/promote — Promote this follower to leader.
731///
732/// Called by the sentinel process during automated failover.
733/// Switches the node role to leader, stops WAL receiving, and starts
734/// a WAL shipper on the replication port so other followers can connect.
735#[cfg(feature = "replication")]
736async fn promote_handler(State(state): State<AppState>) -> impl IntoResponse {
737    let current_role = state.role.load();
738    if current_role == NodeRole::Leader {
739        return (
740            axum::http::StatusCode::OK,
741            Json(serde_json::json!({
742                "status": "already_leader",
743                "message": "This node is already the leader",
744            })),
745        );
746    }
747
748    tracing::info!("PROMOTE: Switching role from follower to leader");
749
750    // 1. Switch role — the read-only middleware will immediately start accepting writes
751    state.role.store(NodeRole::Leader);
752
753    // 2. Signal the WAL receiver to stop (it will stop reconnecting)
754    if let Some(ref receiver) = state.wal_receiver {
755        receiver.shutdown();
756        tracing::info!("PROMOTE: WAL receiver shutdown signalled");
757    }
758
759    // 3. Start a new WAL shipper so remaining followers can connect
760    let replication_port = state.replication_port;
761    let (mut shipper, tx) = WalShipper::new();
762    state.store.enable_wal_replication(tx);
763    shipper.set_store(Arc::clone(&state.store));
764    shipper.set_metrics(state.store.metrics());
765    let shipper = Arc::new(shipper);
766
767    // Install into AppState so health endpoint reports shipper status
768    {
769        let mut shipper_guard = state.wal_shipper.write().await;
770        *shipper_guard = Some(Arc::clone(&shipper));
771    }
772
773    // Spawn the shipper server
774    let shipper_clone = Arc::clone(&shipper);
775    tokio::spawn(async move {
776        if let Err(e) = shipper_clone.serve(replication_port).await {
777            tracing::error!("Promoted WAL shipper error: {}", e);
778        }
779    });
780
781    tracing::info!(
782        "PROMOTE: Now accepting writes. WAL shipper listening on port {}",
783        replication_port,
784    );
785
786    (
787        axum::http::StatusCode::OK,
788        Json(serde_json::json!({
789            "status": "promoted",
790            "role": "leader",
791            "replication_port": replication_port,
792        })),
793    )
794}
795
796/// POST /internal/repoint?leader=host:port — Switch replication target.
797///
798/// Called by the sentinel process to tell a follower to disconnect from
799/// the old leader and reconnect to a newly promoted leader.
800#[cfg(feature = "replication")]
801async fn repoint_handler(
802    State(state): State<AppState>,
803    axum::extract::Query(params): axum::extract::Query<std::collections::HashMap<String, String>>,
804) -> impl IntoResponse {
805    let current_role = state.role.load();
806    if current_role != NodeRole::Follower {
807        return (
808            axum::http::StatusCode::CONFLICT,
809            Json(serde_json::json!({
810                "error": "not_follower",
811                "message": "Repoint only applies to follower nodes",
812            })),
813        );
814    }
815
816    let new_leader = match params.get("leader") {
817        Some(l) if !l.is_empty() => l.clone(),
818        _ => {
819            return (
820                axum::http::StatusCode::BAD_REQUEST,
821                Json(serde_json::json!({
822                    "error": "missing_leader",
823                    "message": "Query parameter 'leader' is required (e.g. ?leader=new-leader:3910)",
824                })),
825            );
826        }
827    };
828
829    tracing::info!("REPOINT: Switching replication target to {}", new_leader);
830
831    if let Some(ref receiver) = state.wal_receiver {
832        receiver.repoint(&new_leader);
833        tracing::info!("REPOINT: WAL receiver repointed to {}", new_leader);
834    } else {
835        tracing::warn!("REPOINT: No WAL receiver to repoint");
836    }
837
838    (
839        axum::http::StatusCode::OK,
840        Json(serde_json::json!({
841            "status": "repointed",
842            "new_leader": new_leader,
843        })),
844    )
845}
846
847// =============================================================================
848// Cluster Management Handlers (v1.8)
849// =============================================================================
850
851/// GET /api/v1/cluster/status — Get cluster status including term, leader, and members
852async fn cluster_status_handler(State(state): State<AppState>) -> impl IntoResponse {
853    let Some(ref cm) = state.cluster_manager else {
854        return (
855            axum::http::StatusCode::SERVICE_UNAVAILABLE,
856            Json(serde_json::json!({
857                "error": "cluster_not_enabled",
858                "message": "Cluster mode is not enabled on this node"
859            })),
860        );
861    };
862
863    let status = cm.status().await;
864    (
865        axum::http::StatusCode::OK,
866        Json(serde_json::to_value(status).unwrap()),
867    )
868}
869
870/// GET /api/v1/cluster/members — List all cluster members
871async fn cluster_list_members_handler(State(state): State<AppState>) -> impl IntoResponse {
872    let Some(ref cm) = state.cluster_manager else {
873        return (
874            axum::http::StatusCode::SERVICE_UNAVAILABLE,
875            Json(serde_json::json!({
876                "error": "cluster_not_enabled",
877                "message": "Cluster mode is not enabled on this node"
878            })),
879        );
880    };
881
882    let members = cm.all_members();
883    (
884        axum::http::StatusCode::OK,
885        Json(serde_json::json!({
886            "members": members,
887            "count": members.len(),
888        })),
889    )
890}
891
892/// POST /api/v1/cluster/members — Add a member to the cluster
893async fn cluster_add_member_handler(
894    State(state): State<AppState>,
895    Json(member): Json<ClusterMember>,
896) -> impl IntoResponse {
897    let Some(ref cm) = state.cluster_manager else {
898        return (
899            axum::http::StatusCode::SERVICE_UNAVAILABLE,
900            Json(serde_json::json!({
901                "error": "cluster_not_enabled",
902                "message": "Cluster mode is not enabled on this node"
903            })),
904        );
905    };
906
907    let node_id = member.node_id;
908    cm.add_member(member).await;
909
910    tracing::info!("Cluster member {} added", node_id);
911    (
912        axum::http::StatusCode::OK,
913        Json(serde_json::json!({
914            "status": "added",
915            "node_id": node_id,
916        })),
917    )
918}
919
920/// DELETE /api/v1/cluster/members/{node_id} — Remove a member from the cluster
921async fn cluster_remove_member_handler(
922    State(state): State<AppState>,
923    Path(node_id): Path<u32>,
924) -> impl IntoResponse {
925    let Some(ref cm) = state.cluster_manager else {
926        return (
927            axum::http::StatusCode::SERVICE_UNAVAILABLE,
928            Json(serde_json::json!({
929                "error": "cluster_not_enabled",
930                "message": "Cluster mode is not enabled on this node"
931            })),
932        );
933    };
934
935    match cm.remove_member(node_id).await {
936        Some(_) => {
937            tracing::info!("Cluster member {} removed", node_id);
938            (
939                axum::http::StatusCode::OK,
940                Json(serde_json::json!({
941                    "status": "removed",
942                    "node_id": node_id,
943                })),
944            )
945        }
946        None => (
947            axum::http::StatusCode::NOT_FOUND,
948            Json(serde_json::json!({
949                "error": "not_found",
950                "message": format!("Node {} not found in cluster", node_id),
951            })),
952        ),
953    }
954}
955
956/// POST /api/v1/cluster/members/{node_id}/heartbeat — Update member heartbeat
957#[derive(serde::Deserialize)]
958struct HeartbeatRequest {
959    wal_offset: u64,
960    #[serde(default = "default_true")]
961    healthy: bool,
962}
963
964fn default_true() -> bool {
965    true
966}
967
968async fn cluster_heartbeat_handler(
969    State(state): State<AppState>,
970    Path(node_id): Path<u32>,
971    Json(req): Json<HeartbeatRequest>,
972) -> impl IntoResponse {
973    let Some(ref cm) = state.cluster_manager else {
974        return (
975            axum::http::StatusCode::SERVICE_UNAVAILABLE,
976            Json(serde_json::json!({
977                "error": "cluster_not_enabled",
978                "message": "Cluster mode is not enabled on this node"
979            })),
980        );
981    };
982
983    cm.update_member_heartbeat(node_id, req.wal_offset, req.healthy);
984    (
985        axum::http::StatusCode::OK,
986        Json(serde_json::json!({
987            "status": "updated",
988            "node_id": node_id,
989        })),
990    )
991}
992
993/// POST /api/v1/cluster/vote — Handle a vote request (simplified Raft RequestVote)
994async fn cluster_vote_handler(
995    State(state): State<AppState>,
996    Json(request): Json<VoteRequest>,
997) -> impl IntoResponse {
998    let Some(ref cm) = state.cluster_manager else {
999        return (
1000            axum::http::StatusCode::SERVICE_UNAVAILABLE,
1001            Json(serde_json::json!({
1002                "error": "cluster_not_enabled",
1003                "message": "Cluster mode is not enabled on this node"
1004            })),
1005        );
1006    };
1007
1008    let response = cm.handle_vote_request(&request).await;
1009    (
1010        axum::http::StatusCode::OK,
1011        Json(serde_json::to_value(response).unwrap()),
1012    )
1013}
1014
1015/// POST /api/v1/cluster/election — Trigger a leader election (manual failover)
1016async fn cluster_election_handler(State(state): State<AppState>) -> impl IntoResponse {
1017    let Some(ref cm) = state.cluster_manager else {
1018        return (
1019            axum::http::StatusCode::SERVICE_UNAVAILABLE,
1020            Json(serde_json::json!({
1021                "error": "cluster_not_enabled",
1022                "message": "Cluster mode is not enabled on this node"
1023            })),
1024        );
1025    };
1026
1027    // Select best candidate deterministically
1028    let candidate = cm.select_leader_candidate();
1029
1030    match candidate {
1031        Some(candidate_id) => {
1032            let new_term = cm.start_election().await;
1033            tracing::info!(
1034                "Cluster election started: term={}, candidate={}",
1035                new_term,
1036                candidate_id,
1037            );
1038
1039            // If this node is the candidate, become leader immediately
1040            // (In a full Raft, we'd collect votes from a majority first)
1041            if candidate_id == cm.self_id() {
1042                cm.become_leader(new_term).await;
1043                tracing::info!("Node {} became leader at term {}", candidate_id, new_term);
1044            }
1045
1046            (
1047                axum::http::StatusCode::OK,
1048                Json(serde_json::json!({
1049                    "status": "election_started",
1050                    "term": new_term,
1051                    "candidate_id": candidate_id,
1052                    "self_is_leader": candidate_id == cm.self_id(),
1053                })),
1054            )
1055        }
1056        None => (
1057            axum::http::StatusCode::CONFLICT,
1058            Json(serde_json::json!({
1059                "error": "no_candidates",
1060                "message": "No healthy members available for leader election",
1061            })),
1062        ),
1063    }
1064}
1065
1066/// GET /api/v1/cluster/partitions — Get partition distribution across nodes
1067async fn cluster_partitions_handler(State(state): State<AppState>) -> impl IntoResponse {
1068    let Some(ref cm) = state.cluster_manager else {
1069        return (
1070            axum::http::StatusCode::SERVICE_UNAVAILABLE,
1071            Json(serde_json::json!({
1072                "error": "cluster_not_enabled",
1073                "message": "Cluster mode is not enabled on this node"
1074            })),
1075        );
1076    };
1077
1078    let registry = cm.registry();
1079    let distribution = registry.partition_distribution();
1080    let total_partitions: usize = distribution.values().map(std::vec::Vec::len).sum();
1081
1082    (
1083        axum::http::StatusCode::OK,
1084        Json(serde_json::json!({
1085            "total_partitions": total_partitions,
1086            "node_count": registry.node_count(),
1087            "healthy_node_count": registry.healthy_node_count(),
1088            "distribution": distribution,
1089        })),
1090    )
1091}
1092
1093// =============================================================================
1094// Geo-Replication Handlers (v1.9)
1095// =============================================================================
1096
1097/// GET /api/v1/geo/status — Get geo-replication status
1098async fn geo_status_handler(State(state): State<AppState>) -> impl IntoResponse {
1099    let Some(ref geo) = state.geo_replication else {
1100        return (
1101            axum::http::StatusCode::SERVICE_UNAVAILABLE,
1102            Json(serde_json::json!({
1103                "error": "geo_replication_not_enabled",
1104                "message": "Geo-replication is not enabled on this node"
1105            })),
1106        );
1107    };
1108
1109    let status = geo.status();
1110    (
1111        axum::http::StatusCode::OK,
1112        Json(serde_json::to_value(status).unwrap()),
1113    )
1114}
1115
1116/// POST /api/v1/geo/sync — Receive replicated events from a peer region
1117async fn geo_sync_handler(
1118    State(state): State<AppState>,
1119    Json(request): Json<GeoSyncRequest>,
1120) -> impl IntoResponse {
1121    let Some(ref geo) = state.geo_replication else {
1122        return (
1123            axum::http::StatusCode::SERVICE_UNAVAILABLE,
1124            Json(serde_json::json!({
1125                "error": "geo_replication_not_enabled",
1126                "message": "Geo-replication is not enabled on this node"
1127            })),
1128        );
1129    };
1130
1131    tracing::info!(
1132        "Geo-sync received from region '{}': {} events",
1133        request.source_region,
1134        request.events.len(),
1135    );
1136
1137    let response = geo.receive_sync(&request);
1138    (
1139        axum::http::StatusCode::OK,
1140        Json(serde_json::to_value(response).unwrap()),
1141    )
1142}
1143
1144/// GET /api/v1/geo/peers — List peer regions and their health
1145async fn geo_peers_handler(State(state): State<AppState>) -> impl IntoResponse {
1146    let Some(ref geo) = state.geo_replication else {
1147        return (
1148            axum::http::StatusCode::SERVICE_UNAVAILABLE,
1149            Json(serde_json::json!({
1150                "error": "geo_replication_not_enabled",
1151                "message": "Geo-replication is not enabled on this node"
1152            })),
1153        );
1154    };
1155
1156    let status = geo.status();
1157    (
1158        axum::http::StatusCode::OK,
1159        Json(serde_json::json!({
1160            "region_id": status.region_id,
1161            "peers": status.peers,
1162        })),
1163    )
1164}
1165
1166/// POST /api/v1/geo/failover — Trigger regional failover
1167async fn geo_failover_handler(State(state): State<AppState>) -> impl IntoResponse {
1168    let Some(ref geo) = state.geo_replication else {
1169        return (
1170            axum::http::StatusCode::SERVICE_UNAVAILABLE,
1171            Json(serde_json::json!({
1172                "error": "geo_replication_not_enabled",
1173                "message": "Geo-replication is not enabled on this node"
1174            })),
1175        );
1176    };
1177
1178    match geo.select_failover_region() {
1179        Some(failover_region) => {
1180            tracing::info!(
1181                "Geo-failover: selected region '{}' as failover target",
1182                failover_region,
1183            );
1184            (
1185                axum::http::StatusCode::OK,
1186                Json(serde_json::json!({
1187                    "status": "failover_target_selected",
1188                    "failover_region": failover_region,
1189                    "message": "Region selected for failover. DNS/routing update required externally.",
1190                })),
1191            )
1192        }
1193        None => (
1194            axum::http::StatusCode::CONFLICT,
1195            Json(serde_json::json!({
1196                "error": "no_healthy_peers",
1197                "message": "No healthy peer regions available for failover",
1198            })),
1199        ),
1200    }
1201}
1202
1203/// Listen for shutdown signals (SIGTERM for serverless, SIGINT for local dev)
1204pub async fn shutdown_signal() {
1205    let ctrl_c = async {
1206        tokio::signal::ctrl_c()
1207            .await
1208            .expect("failed to install Ctrl+C handler");
1209    };
1210
1211    #[cfg(unix)]
1212    let terminate = async {
1213        tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
1214            .expect("failed to install SIGTERM handler")
1215            .recv()
1216            .await;
1217    };
1218
1219    #[cfg(not(unix))]
1220    let terminate = std::future::pending::<()>();
1221
1222    tokio::select! {
1223        () = ctrl_c => {
1224            tracing::info!("📤 Received Ctrl+C, initiating graceful shutdown...");
1225        }
1226        () = terminate => {
1227            tracing::info!("📤 Received SIGTERM, initiating graceful shutdown...");
1228        }
1229    }
1230}