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 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.merge(super::search_api::router(super::search_api::start(
513        Arc::clone(&app_state.store),
514    )));
515
516    let app = app
517        .with_state(app_state.clone())
518        // IMPORTANT: Middleware layers execute from bottom to top in Tower/Axum
519        // Read-only middleware runs after auth (applied before rate limit layer)
520        .layer(middleware::from_fn_with_state(
521            app_state,
522            read_only_middleware,
523        ))
524        .layer(middleware::from_fn_with_state(
525            rate_limit_state,
526            rate_limit_middleware,
527        ))
528        .layer(middleware::from_fn_with_state(auth_state, auth_middleware))
529        .layer(
530            CorsLayer::new()
531                .allow_origin(Any)
532                .allow_methods(Any)
533                .allow_headers(Any),
534        )
535        .layer(TraceLayer::new_for_http());
536
537    // Prime API — nested router with its own state (feature-gated)
538    #[cfg(feature = "prime")]
539    let app = {
540        let data_dir =
541            std::env::var("PRIME_DATA_DIR").unwrap_or_else(|_| "/tmp/prime-data".to_string());
542        match crate::prime::Prime::open(&data_dir).await {
543            Ok(prime) => {
544                let prime_state = Arc::new(super::prime_api::PrimeState { prime });
545                tracing::info!("Prime API enabled at /api/v1/prime/*");
546                app.nest(
547                    "/api/v1/prime",
548                    super::prime_api::prime_router().with_state(prime_state),
549                )
550            }
551            Err(e) => {
552                tracing::warn!("Prime API disabled: failed to open Prime: {e}");
553                app
554            }
555        }
556    };
557
558    let app = app
559        .layer(middleware::from_fn(super::response_limit::bounded))
560        .layer(middleware::from_fn_with_state(
561            http_metrics,
562            super::http_metrics::record,
563        ))
564        .layer(super::response_limit::compression());
565    gate.open(app);
566    Ok(())
567}
568
569/// Write paths that should be rejected when running as a follower.
570const WRITE_PATHS: &[&str] = &[
571    "/api/v1/events",
572    "/api/v1/events/batch",
573    "/api/v1/projections/",
574    "/api/v1/read-models/",
575    "/api/v1/views",
576    "/api/v1/schemas",
577    "/api/v1/replay",
578    "/api/v1/pipelines",
579    "/api/v1/compaction/trigger",
580    "/api/v1/audit/events",
581    "/api/v1/config",
582    "/api/v1/tenants",
583    "/api/v1/webhooks",
584    "/api/v1/demo/seed",
585];
586
587/// Returns true if this request is a write operation that should be blocked on followers.
588fn is_write_request(method: &axum::http::Method, path: &str) -> bool {
589    use axum::http::Method;
590    // Only POST/PUT/DELETE are writes
591    if method != Method::POST && method != Method::PUT && method != Method::DELETE {
592        return false;
593    }
594    WRITE_PATHS
595        .iter()
596        .any(|write_path| path.starts_with(write_path))
597}
598
599/// Returns true if the request targets an internal or cluster endpoint (not subject to read-only checks).
600fn is_internal_request(path: &str) -> bool {
601    path.starts_with("/internal/")
602        || path.starts_with("/api/v1/cluster/")
603        || path.starts_with("/api/v1/geo/")
604}
605
606/// Middleware that rejects write requests when the node is a follower.
607///
608/// Returns HTTP 409 Conflict with `{"error": "read_only", "message": "..."}`.
609/// Internal endpoints (`/internal/*`) are exempt — they are used by the sentinel
610/// to trigger promotion and repointing during failover.
611async fn read_only_middleware(
612    State(state): State<AppState>,
613    request: axum::extract::Request,
614    next: axum::middleware::Next,
615) -> axum::response::Response {
616    let path = request.uri().path();
617    if state.role.load().is_follower()
618        && is_write_request(request.method(), path)
619        && !is_internal_request(path)
620    {
621        return (
622            axum::http::StatusCode::CONFLICT,
623            axum::Json(serde_json::json!({
624                "error": "read_only",
625                "message": "This node is a read-only follower"
626            })),
627        )
628            .into_response();
629    }
630    next.run(request).await
631}
632
633/// Health endpoint with system stream health reporting.
634///
635/// Reports overall health plus detailed system metadata health when
636/// event-sourced system repositories are configured.
637async fn health_v1(State(state): State<AppState>) -> impl IntoResponse {
638    let has_system_repos = state.service_container.has_system_repositories();
639
640    let system_streams = if has_system_repos {
641        let (tenant_count, config_count, total_events) =
642            if let Some(store) = state.service_container.system_store() {
643                use crate::domain::value_objects::system_stream::SystemDomain;
644                (
645                    store.count_stream(SystemDomain::Tenant),
646                    store.count_stream(SystemDomain::Config),
647                    store.total_events(),
648                )
649            } else {
650                (0, 0, 0)
651            };
652
653        serde_json::json!({
654            "status": "healthy",
655            "mode": "event-sourced",
656            "total_events": total_events,
657            "tenant_events": tenant_count,
658            "config_events": config_count,
659        })
660    } else {
661        serde_json::json!({
662            "status": "disabled",
663            "mode": "in-memory",
664        })
665    };
666
667    let replication = {
668        #[cfg(feature = "replication")]
669        {
670            let shipper_guard = state.wal_shipper.read().await;
671            if let Some(ref shipper) = *shipper_guard {
672                serde_json::to_value(shipper.status()).unwrap_or_default()
673            } else if let Some(ref receiver) = state.wal_receiver {
674                serde_json::to_value(receiver.status()).unwrap_or_default()
675            } else {
676                serde_json::json!(null)
677            }
678        }
679        #[cfg(not(feature = "replication"))]
680        serde_json::json!({"edition": "community", "status": "not_available"})
681    };
682
683    let current_role = state.role.load();
684
685    Json(serde_json::json!({
686        "status": "healthy",
687        "service": "allsource-core",
688        "version": env!("CARGO_PKG_VERSION"),
689        "role": current_role,
690        "system_streams": system_streams,
691        "replication": replication,
692    }))
693}
694
695/// POST /internal/promote — Promote this follower to leader.
696///
697/// Called by the sentinel process during automated failover.
698/// Switches the node role to leader, stops WAL receiving, and starts
699/// a WAL shipper on the replication port so other followers can connect.
700#[cfg(feature = "replication")]
701async fn promote_handler(State(state): State<AppState>) -> impl IntoResponse {
702    let current_role = state.role.load();
703    if current_role == NodeRole::Leader {
704        return (
705            axum::http::StatusCode::OK,
706            Json(serde_json::json!({
707                "status": "already_leader",
708                "message": "This node is already the leader",
709            })),
710        );
711    }
712
713    tracing::info!("PROMOTE: Switching role from follower to leader");
714
715    // 1. Switch role — the read-only middleware will immediately start accepting writes
716    state.role.store(NodeRole::Leader);
717
718    // 2. Signal the WAL receiver to stop (it will stop reconnecting)
719    if let Some(ref receiver) = state.wal_receiver {
720        receiver.shutdown();
721        tracing::info!("PROMOTE: WAL receiver shutdown signalled");
722    }
723
724    // 3. Start a new WAL shipper so remaining followers can connect
725    let replication_port = state.replication_port;
726    let (mut shipper, tx) = WalShipper::new();
727    state.store.enable_wal_replication(tx);
728    shipper.set_store(Arc::clone(&state.store));
729    shipper.set_metrics(state.store.metrics());
730    let shipper = Arc::new(shipper);
731
732    // Install into AppState so health endpoint reports shipper status
733    {
734        let mut shipper_guard = state.wal_shipper.write().await;
735        *shipper_guard = Some(Arc::clone(&shipper));
736    }
737
738    // Spawn the shipper server
739    let shipper_clone = Arc::clone(&shipper);
740    tokio::spawn(async move {
741        if let Err(e) = shipper_clone.serve(replication_port).await {
742            tracing::error!("Promoted WAL shipper error: {}", e);
743        }
744    });
745
746    tracing::info!(
747        "PROMOTE: Now accepting writes. WAL shipper listening on port {}",
748        replication_port,
749    );
750
751    (
752        axum::http::StatusCode::OK,
753        Json(serde_json::json!({
754            "status": "promoted",
755            "role": "leader",
756            "replication_port": replication_port,
757        })),
758    )
759}
760
761/// POST /internal/repoint?leader=host:port — Switch replication target.
762///
763/// Called by the sentinel process to tell a follower to disconnect from
764/// the old leader and reconnect to a newly promoted leader.
765#[cfg(feature = "replication")]
766async fn repoint_handler(
767    State(state): State<AppState>,
768    axum::extract::Query(params): axum::extract::Query<std::collections::HashMap<String, String>>,
769) -> impl IntoResponse {
770    let current_role = state.role.load();
771    if current_role != NodeRole::Follower {
772        return (
773            axum::http::StatusCode::CONFLICT,
774            Json(serde_json::json!({
775                "error": "not_follower",
776                "message": "Repoint only applies to follower nodes",
777            })),
778        );
779    }
780
781    let new_leader = match params.get("leader") {
782        Some(l) if !l.is_empty() => l.clone(),
783        _ => {
784            return (
785                axum::http::StatusCode::BAD_REQUEST,
786                Json(serde_json::json!({
787                    "error": "missing_leader",
788                    "message": "Query parameter 'leader' is required (e.g. ?leader=new-leader:3910)",
789                })),
790            );
791        }
792    };
793
794    tracing::info!("REPOINT: Switching replication target to {}", new_leader);
795
796    if let Some(ref receiver) = state.wal_receiver {
797        receiver.repoint(&new_leader);
798        tracing::info!("REPOINT: WAL receiver repointed to {}", new_leader);
799    } else {
800        tracing::warn!("REPOINT: No WAL receiver to repoint");
801    }
802
803    (
804        axum::http::StatusCode::OK,
805        Json(serde_json::json!({
806            "status": "repointed",
807            "new_leader": new_leader,
808        })),
809    )
810}
811
812// =============================================================================
813// Cluster Management Handlers (v1.8)
814// =============================================================================
815
816/// GET /api/v1/cluster/status — Get cluster status including term, leader, and members
817async fn cluster_status_handler(State(state): State<AppState>) -> impl IntoResponse {
818    let Some(ref cm) = state.cluster_manager else {
819        return (
820            axum::http::StatusCode::SERVICE_UNAVAILABLE,
821            Json(serde_json::json!({
822                "error": "cluster_not_enabled",
823                "message": "Cluster mode is not enabled on this node"
824            })),
825        );
826    };
827
828    let status = cm.status().await;
829    (
830        axum::http::StatusCode::OK,
831        Json(serde_json::to_value(status).unwrap()),
832    )
833}
834
835/// GET /api/v1/cluster/members — List all cluster members
836async fn cluster_list_members_handler(State(state): State<AppState>) -> impl IntoResponse {
837    let Some(ref cm) = state.cluster_manager else {
838        return (
839            axum::http::StatusCode::SERVICE_UNAVAILABLE,
840            Json(serde_json::json!({
841                "error": "cluster_not_enabled",
842                "message": "Cluster mode is not enabled on this node"
843            })),
844        );
845    };
846
847    let members = cm.all_members();
848    (
849        axum::http::StatusCode::OK,
850        Json(serde_json::json!({
851            "members": members,
852            "count": members.len(),
853        })),
854    )
855}
856
857/// POST /api/v1/cluster/members — Add a member to the cluster
858async fn cluster_add_member_handler(
859    State(state): State<AppState>,
860    Json(member): Json<ClusterMember>,
861) -> impl IntoResponse {
862    let Some(ref cm) = state.cluster_manager else {
863        return (
864            axum::http::StatusCode::SERVICE_UNAVAILABLE,
865            Json(serde_json::json!({
866                "error": "cluster_not_enabled",
867                "message": "Cluster mode is not enabled on this node"
868            })),
869        );
870    };
871
872    let node_id = member.node_id;
873    cm.add_member(member).await;
874
875    tracing::info!("Cluster member {} added", node_id);
876    (
877        axum::http::StatusCode::OK,
878        Json(serde_json::json!({
879            "status": "added",
880            "node_id": node_id,
881        })),
882    )
883}
884
885/// DELETE /api/v1/cluster/members/{node_id} — Remove a member from the cluster
886async fn cluster_remove_member_handler(
887    State(state): State<AppState>,
888    Path(node_id): Path<u32>,
889) -> impl IntoResponse {
890    let Some(ref cm) = state.cluster_manager else {
891        return (
892            axum::http::StatusCode::SERVICE_UNAVAILABLE,
893            Json(serde_json::json!({
894                "error": "cluster_not_enabled",
895                "message": "Cluster mode is not enabled on this node"
896            })),
897        );
898    };
899
900    match cm.remove_member(node_id).await {
901        Some(_) => {
902            tracing::info!("Cluster member {} removed", node_id);
903            (
904                axum::http::StatusCode::OK,
905                Json(serde_json::json!({
906                    "status": "removed",
907                    "node_id": node_id,
908                })),
909            )
910        }
911        None => (
912            axum::http::StatusCode::NOT_FOUND,
913            Json(serde_json::json!({
914                "error": "not_found",
915                "message": format!("Node {} not found in cluster", node_id),
916            })),
917        ),
918    }
919}
920
921/// POST /api/v1/cluster/members/{node_id}/heartbeat — Update member heartbeat
922#[derive(serde::Deserialize)]
923struct HeartbeatRequest {
924    wal_offset: u64,
925    #[serde(default = "default_true")]
926    healthy: bool,
927}
928
929fn default_true() -> bool {
930    true
931}
932
933async fn cluster_heartbeat_handler(
934    State(state): State<AppState>,
935    Path(node_id): Path<u32>,
936    Json(req): Json<HeartbeatRequest>,
937) -> impl IntoResponse {
938    let Some(ref cm) = state.cluster_manager else {
939        return (
940            axum::http::StatusCode::SERVICE_UNAVAILABLE,
941            Json(serde_json::json!({
942                "error": "cluster_not_enabled",
943                "message": "Cluster mode is not enabled on this node"
944            })),
945        );
946    };
947
948    cm.update_member_heartbeat(node_id, req.wal_offset, req.healthy);
949    (
950        axum::http::StatusCode::OK,
951        Json(serde_json::json!({
952            "status": "updated",
953            "node_id": node_id,
954        })),
955    )
956}
957
958/// POST /api/v1/cluster/vote — Handle a vote request (simplified Raft RequestVote)
959async fn cluster_vote_handler(
960    State(state): State<AppState>,
961    Json(request): Json<VoteRequest>,
962) -> impl IntoResponse {
963    let Some(ref cm) = state.cluster_manager else {
964        return (
965            axum::http::StatusCode::SERVICE_UNAVAILABLE,
966            Json(serde_json::json!({
967                "error": "cluster_not_enabled",
968                "message": "Cluster mode is not enabled on this node"
969            })),
970        );
971    };
972
973    let response = cm.handle_vote_request(&request).await;
974    (
975        axum::http::StatusCode::OK,
976        Json(serde_json::to_value(response).unwrap()),
977    )
978}
979
980/// POST /api/v1/cluster/election — Trigger a leader election (manual failover)
981async fn cluster_election_handler(State(state): State<AppState>) -> impl IntoResponse {
982    let Some(ref cm) = state.cluster_manager else {
983        return (
984            axum::http::StatusCode::SERVICE_UNAVAILABLE,
985            Json(serde_json::json!({
986                "error": "cluster_not_enabled",
987                "message": "Cluster mode is not enabled on this node"
988            })),
989        );
990    };
991
992    // Select best candidate deterministically
993    let candidate = cm.select_leader_candidate();
994
995    match candidate {
996        Some(candidate_id) => {
997            let new_term = cm.start_election().await;
998            tracing::info!(
999                "Cluster election started: term={}, candidate={}",
1000                new_term,
1001                candidate_id,
1002            );
1003
1004            // If this node is the candidate, become leader immediately
1005            // (In a full Raft, we'd collect votes from a majority first)
1006            if candidate_id == cm.self_id() {
1007                cm.become_leader(new_term).await;
1008                tracing::info!("Node {} became leader at term {}", candidate_id, new_term);
1009            }
1010
1011            (
1012                axum::http::StatusCode::OK,
1013                Json(serde_json::json!({
1014                    "status": "election_started",
1015                    "term": new_term,
1016                    "candidate_id": candidate_id,
1017                    "self_is_leader": candidate_id == cm.self_id(),
1018                })),
1019            )
1020        }
1021        None => (
1022            axum::http::StatusCode::CONFLICT,
1023            Json(serde_json::json!({
1024                "error": "no_candidates",
1025                "message": "No healthy members available for leader election",
1026            })),
1027        ),
1028    }
1029}
1030
1031/// GET /api/v1/cluster/partitions — Get partition distribution across nodes
1032async fn cluster_partitions_handler(State(state): State<AppState>) -> impl IntoResponse {
1033    let Some(ref cm) = state.cluster_manager else {
1034        return (
1035            axum::http::StatusCode::SERVICE_UNAVAILABLE,
1036            Json(serde_json::json!({
1037                "error": "cluster_not_enabled",
1038                "message": "Cluster mode is not enabled on this node"
1039            })),
1040        );
1041    };
1042
1043    let registry = cm.registry();
1044    let distribution = registry.partition_distribution();
1045    let total_partitions: usize = distribution.values().map(std::vec::Vec::len).sum();
1046
1047    (
1048        axum::http::StatusCode::OK,
1049        Json(serde_json::json!({
1050            "total_partitions": total_partitions,
1051            "node_count": registry.node_count(),
1052            "healthy_node_count": registry.healthy_node_count(),
1053            "distribution": distribution,
1054        })),
1055    )
1056}
1057
1058// =============================================================================
1059// Geo-Replication Handlers (v1.9)
1060// =============================================================================
1061
1062/// GET /api/v1/geo/status — Get geo-replication status
1063async fn geo_status_handler(State(state): State<AppState>) -> impl IntoResponse {
1064    let Some(ref geo) = state.geo_replication else {
1065        return (
1066            axum::http::StatusCode::SERVICE_UNAVAILABLE,
1067            Json(serde_json::json!({
1068                "error": "geo_replication_not_enabled",
1069                "message": "Geo-replication is not enabled on this node"
1070            })),
1071        );
1072    };
1073
1074    let status = geo.status();
1075    (
1076        axum::http::StatusCode::OK,
1077        Json(serde_json::to_value(status).unwrap()),
1078    )
1079}
1080
1081/// POST /api/v1/geo/sync — Receive replicated events from a peer region
1082async fn geo_sync_handler(
1083    State(state): State<AppState>,
1084    Json(request): Json<GeoSyncRequest>,
1085) -> impl IntoResponse {
1086    let Some(ref geo) = state.geo_replication else {
1087        return (
1088            axum::http::StatusCode::SERVICE_UNAVAILABLE,
1089            Json(serde_json::json!({
1090                "error": "geo_replication_not_enabled",
1091                "message": "Geo-replication is not enabled on this node"
1092            })),
1093        );
1094    };
1095
1096    tracing::info!(
1097        "Geo-sync received from region '{}': {} events",
1098        request.source_region,
1099        request.events.len(),
1100    );
1101
1102    let response = geo.receive_sync(&request);
1103    (
1104        axum::http::StatusCode::OK,
1105        Json(serde_json::to_value(response).unwrap()),
1106    )
1107}
1108
1109/// GET /api/v1/geo/peers — List peer regions and their health
1110async fn geo_peers_handler(State(state): State<AppState>) -> impl IntoResponse {
1111    let Some(ref geo) = state.geo_replication else {
1112        return (
1113            axum::http::StatusCode::SERVICE_UNAVAILABLE,
1114            Json(serde_json::json!({
1115                "error": "geo_replication_not_enabled",
1116                "message": "Geo-replication is not enabled on this node"
1117            })),
1118        );
1119    };
1120
1121    let status = geo.status();
1122    (
1123        axum::http::StatusCode::OK,
1124        Json(serde_json::json!({
1125            "region_id": status.region_id,
1126            "peers": status.peers,
1127        })),
1128    )
1129}
1130
1131/// POST /api/v1/geo/failover — Trigger regional failover
1132async fn geo_failover_handler(State(state): State<AppState>) -> impl IntoResponse {
1133    let Some(ref geo) = state.geo_replication else {
1134        return (
1135            axum::http::StatusCode::SERVICE_UNAVAILABLE,
1136            Json(serde_json::json!({
1137                "error": "geo_replication_not_enabled",
1138                "message": "Geo-replication is not enabled on this node"
1139            })),
1140        );
1141    };
1142
1143    match geo.select_failover_region() {
1144        Some(failover_region) => {
1145            tracing::info!(
1146                "Geo-failover: selected region '{}' as failover target",
1147                failover_region,
1148            );
1149            (
1150                axum::http::StatusCode::OK,
1151                Json(serde_json::json!({
1152                    "status": "failover_target_selected",
1153                    "failover_region": failover_region,
1154                    "message": "Region selected for failover. DNS/routing update required externally.",
1155                })),
1156            )
1157        }
1158        None => (
1159            axum::http::StatusCode::CONFLICT,
1160            Json(serde_json::json!({
1161                "error": "no_healthy_peers",
1162                "message": "No healthy peer regions available for failover",
1163            })),
1164        ),
1165    }
1166}
1167
1168/// Listen for shutdown signals (SIGTERM for serverless, SIGINT for local dev)
1169pub async fn shutdown_signal() {
1170    let ctrl_c = async {
1171        tokio::signal::ctrl_c()
1172            .await
1173            .expect("failed to install Ctrl+C handler");
1174    };
1175
1176    #[cfg(unix)]
1177    let terminate = async {
1178        tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
1179            .expect("failed to install SIGTERM handler")
1180            .recv()
1181            .await;
1182    };
1183
1184    #[cfg(not(unix))]
1185    let terminate = std::future::pending::<()>();
1186
1187    tokio::select! {
1188        () = ctrl_c => {
1189            tracing::info!("📤 Received Ctrl+C, initiating graceful shutdown...");
1190        }
1191        () = terminate => {
1192            tracing::info!("📤 Received SIGTERM, initiating graceful shutdown...");
1193        }
1194    }
1195}