summaryrefslogtreecommitdiffstats
path: root/src/api/peers.rs
blob: b12e3bfe0da4c982a5b4800255ed62633b5e0f5d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
//! /peers handlers.

use std::sync::Arc;

use axum::{
    extract::{Path, Query, State},
    http::StatusCode,
    Json,
};
use serde::{Deserialize, Serialize};
use tokio::sync::Mutex;
use tokio::time::Instant;
use tracing::warn;
use utoipa::ToSchema;

use super::store_status;
use crate::peer::forgotten_path;
use crate::replica::Epoch;
use crate::state::{unix_millis, AppState, HelloState, Liveness, PeerMembership, PeerState};
use crate::store;

#[derive(Debug, Serialize, ToSchema)]
#[serde(rename_all = "lowercase")]
pub(crate) enum PeerLivenessStatus {
    Active,
    Dormant,
}

#[derive(Debug, Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub(crate) struct EpochInfo {
    generation: u64,
    /// Hex-encoded snapshot hash; all zeros for the genesis epoch.
    id: String,
}

impl From<Epoch> for EpochInfo {
    fn from(epoch: Epoch) -> Self {
        Self {
            generation: epoch.generation,
            id: epoch.id_hex(),
        }
    }
}

#[derive(Debug, Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub(crate) struct PeerStatus {
    public_key: String,
    validated_cluster: Option<String>,
    status: PeerLivenessStatus,
    handshake_complete: bool,
    last_seen_secs_ago: Option<u64>,
    dormant_for_secs: Option<u64>,
    has_pending_delivery: bool,
    /// Epoch the peer last advertised; absent until it has sent a message.
    epoch: Option<EpochInfo>,
    /// Whether that epoch equals ours, i.e. whether we sync with this peer.
    same_epoch: Option<bool>,
}

#[derive(Debug, Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub(crate) struct PeerListResponse {
    local_epoch: EpochInfo,
    peers: Vec<PeerStatus>,
}

#[derive(Debug, Deserialize)]
pub(crate) struct DeletePeerQuery {
    #[serde(default)]
    force: bool,
}

#[utoipa::path(
    get,
    path = "/peers",
    tag = "Peers",
    responses(
        (
            status = 200,
            description = "Lists known peers and their local replication status",
            body = PeerListResponse
        )
    )
)]
pub(crate) async fn list_peers(
    State(state): State<AppState>,
) -> Result<Json<PeerListResponse>, StatusCode> {
    let snapshot: Vec<(String, Arc<Mutex<PeerState>>)> = state
        .peer_states
        .read()
        .await
        .iter()
        .map(|(pk, m)| (pk.clone(), Arc::clone(m)))
        .collect();

    let now = Instant::now();
    let local_epoch = state.local_epoch();
    let mut peers = Vec::with_capacity(snapshot.len());

    for (public_key, peer_state_mutex) in snapshot {
        let ps = peer_state_mutex.lock().await;

        let (status, dormant_for_secs) = match ps.liveness {
            Liveness::Active => (PeerLivenessStatus::Active, None),
            Liveness::Dormant { since } => (
                PeerLivenessStatus::Dormant,
                Some(now.saturating_duration_since(since).as_secs()),
            ),
        };

        peers.push(PeerStatus {
            public_key,
            validated_cluster: match &ps.membership {
                PeerMembership::Unknown => None,
                PeerMembership::Member { cluster_id } => Some(cluster_id.clone()),
            },
            status,
            handshake_complete: ps.hello_state == HelloState::Established,
            last_seen_secs_ago: ps
                .last_seen
                .map(|t| now.saturating_duration_since(t).as_secs()),
            dormant_for_secs,
            has_pending_delivery: ps.pending_outbound_sync.is_some(),
            epoch: ps.epoch.map(EpochInfo::from),
            same_epoch: ps.epoch.map(|epoch| epoch == local_epoch),
        });
    }

    peers.sort_by(|a, b| a.public_key.cmp(&b.public_key));
    Ok(Json(PeerListResponse {
        local_epoch: local_epoch.into(),
        peers,
    }))
}

#[utoipa::path(
    delete,
    path = "/peers/{peer}",
    tag = "Peers",
    params(
        ("peer" = String, Path, description = "Peer public key"),
        ("force" = Option<bool>, Query, description = "Also forget a peer that is currently alive; it returns on its next message")
    ),
    responses(
        (status = 204, description = "Cluster-wide forget recorded"),
        (status = 400, description = "Not a public key, or the local node's own key"),
        (status = 409, description = "Peer is alive; pass force=true"),
        (status = 503, description = "Node is not ready")
    )
)]
pub(crate) async fn delete_peer(
    State(state): State<AppState>,
    Path(peer): Path<String>,
    Query(query): Query<DeletePeerQuery>,
) -> Result<StatusCode, StatusCode> {
    if !state.is_ready().await {
        return Err(StatusCode::SERVICE_UNAVAILABLE);
    }
    if peer.is_empty() || peer == state.local_id() {
        return Err(StatusCode::BAD_REQUEST);
    }

    // Unknown locally is fine: other nodes may still know the peer.
    if let Some(peer_state_mutex) = state.get_peer_state(&peer).await {
        if peer_state_mutex
            .lock()
            .await
            .is_alive(&state.timing, Instant::now())
            && !query.force
        {
            return Err(StatusCode::CONFLICT);
        }
    }

    let record = serde_json::json!({ "at": unix_millis(), "by": state.local_id() });

    let peer_clone = peer.clone();
    state
        .mutate_doc(move |doc| store::write_path(doc, &forgotten_path(&peer_clone), &record))
        .await
        .map_err(|e| store_status(e, "Failed to write forget record"))?;

    if state.peer_states.write().await.remove(&peer).is_some() {
        warn!(peer = %peer, "Peer forgotten cluster-wide by operator");
    }

    Ok(StatusCode::NO_CONTENT)
}