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