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