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
191
192
193
194
195
196
197
198
199
200
201
202
|
//! `/admin/quarantine`: this node's own changes that were not replayed when it rejoined
//! a newer epoch (outside the replay window, or impossible to tell apart).
//!
//! * `GET /admin/quarantine` lists the entries.
//! * `GET /admin/quarantine/{id}` shows the writes: every changed path with the value
//! the old document's merged view holds there (`deleted` if none).
//! * `GET /admin/quarantine/{id}/document` downloads the old document
//! (`AutoCommit::save()`), for inspection with other tools.
//! * `POST /admin/quarantine/{id}/replay` writes them into the current epoch anyway (as
//! fresh writes, so they win over what is there) and removes the entry.
//! * `DELETE /admin/quarantine/{id}` discards the entry.
//!
//! Quarantine lives in memory on the node that holds it.
use std::convert::Infallible;
use automerge::AutoCommit;
use axum::{
extract::{Path, State},
http::{header, StatusCode},
response::{IntoResponse, Response},
Json,
};
use serde::Serialize;
use serde_json::{json, Value as JsonValue};
use tracing::{info, warn};
use uuid::Uuid;
use super::api::error_response;
use super::delta;
use super::kind::Translator;
use super::local::Quarantined;
use super::records::unix_millis;
use super::Host;
use crate::document::replica::Epoch;
use crate::document::store;
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct Summary {
id: String,
/// The epoch the changes were made in.
epoch: String,
/// The epoch the node rejoined.
target: String,
created_at: u64,
reason: String,
paths: usize,
}
fn summary(entry: &Quarantined) -> Summary {
Summary {
id: entry.id.clone(),
epoch: entry.epoch.to_string(),
target: entry.target.to_string(),
created_at: entry.created_at,
reason: entry.reason.clone(),
paths: entry.paths.len(),
}
}
fn not_found() -> Response {
error_response(StatusCode::NOT_FOUND, "no such quarantine entry", None)
}
/// Puts writes a remake had no place for into quarantine, with `document` (the old
/// epoch's) to read them from. Returns the entry's ID, or None if there is nothing.
pub(super) fn add<H: Host>(
host: &H,
epoch: Epoch,
target: Epoch,
document: &AutoCommit,
quarantined: Vec<(Vec<String>, String)>,
) -> Option<String> {
if quarantined.is_empty() {
return None;
}
let mut reasons: Vec<&str> = quarantined
.iter()
.map(|(_, reason)| reason.as_str())
.collect();
reasons.sort_unstable();
reasons.dedup();
let reason = reasons.join("; ");
let paths: Vec<Vec<String>> = quarantined.into_iter().map(|(path, _)| path).collect();
let id = Uuid::new_v4().to_string();
warn!(quarantine = %id, epoch = %epoch, paths = paths.len(), reason = %reason, "Quarantined writes the remake has no place for");
host.remake().add_quarantine(Quarantined {
id: id.clone(),
epoch,
target,
created_at: unix_millis(),
reason,
paths,
document: document.clone(),
});
Some(id)
}
pub(crate) async fn list<H: Host>(State(host): State<H>) -> Response {
Json(host.remake().list_quarantine(summary)).into_response()
}
pub(crate) async fn get<H: Host>(State(host): State<H>, Path(id): Path<String>) -> Response {
let Some((summary, document, paths)) = host.remake().with_quarantined(&id, |entry| {
(summary(entry), entry.document.clone(), entry.paths.clone())
}) else {
return not_found();
};
let writes = tokio::task::spawn_blocking(move || {
paths
.into_iter()
.map(|path| match store::read_path(&document, &path) {
Ok(Some(value)) => json!({ "path": path, "value": value }),
Ok(None) => json!({ "path": path, "deleted": true }),
Err(error) => json!({ "path": path, "error": error.to_string() }),
})
.collect::<Vec<JsonValue>>()
})
.await;
match writes {
Ok(writes) => Json(json!({ "entry": summary, "writes": writes })).into_response(),
Err(_) => error_response(
StatusCode::INTERNAL_SERVER_ERROR,
"reading the writes failed",
None,
),
}
}
pub(crate) async fn document<H: Host>(State(host): State<H>, Path(id): Path<String>) -> Response {
let Some(mut document) = host
.remake()
.with_quarantined(&id, |entry| entry.document.clone())
else {
return not_found();
};
match tokio::task::spawn_blocking(move || document.save()).await {
Ok(bytes) => (
[
(header::CONTENT_TYPE, "application/octet-stream".to_owned()),
(
header::CONTENT_DISPOSITION,
format!("attachment; filename=\"quarantine-{id}.automerge\""),
),
],
bytes,
)
.into_response(),
Err(_) => error_response(
StatusCode::INTERNAL_SERVER_ERROR,
"saving the document failed",
None,
),
}
}
pub(crate) async fn replay<H: Host>(State(host): State<H>, Path(id): Path<String>) -> Response {
if !host.is_node_ready().await {
return error_response(StatusCode::SERVICE_UNAVAILABLE, "node is not ready", None);
}
let Some(entry) = host.remake().take_quarantined(&id) else {
return not_found();
};
let (stats, entry) = host
.commit_doc(move |doc| {
// As they are: the operator decided they belong at their old paths.
let stats =
delta::replay_paths(&entry.document, doc, &entry.paths, &Translator::default());
Ok::<_, Infallible>((stats, entry))
})
.await
.unwrap_or_else(|never| match never {});
if stats.failed > 0 && stats.replayed == 0 {
// Nothing went in; keep the entry for another look.
host.remake().restore_quarantined(entry);
return error_response(
StatusCode::CONFLICT,
"none of the writes could be replayed",
Some(json!({ "failed": stats.failed })),
);
}
info!(quarantine = %id, replayed = stats.replayed, failed = stats.failed, "Replayed quarantined changes");
Json(json!({ "replayed": stats.replayed, "failed": stats.failed })).into_response()
}
pub(crate) async fn discard<H: Host>(State(host): State<H>, Path(id): Path<String>) -> Response {
match host.remake().take_quarantined(&id) {
Some(_) => {
info!(quarantine = %id, "Discarded quarantined changes");
StatusCode::NO_CONTENT.into_response()
}
None => not_found(),
}
}
|