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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
//! The machine's own state, over HTTP.
//!
//! What belongs to no worktree: which machine this is, what is waiting
//! between it and its peers, and adding a checkout outside `$PRJ` by its
//! path. The projects and worktrees themselves are `/api/v1/projects`
//! (`handlers::prj`); everything one worktree holds lives under
//! `/api/v1/worktrees/{id}/` and is served by that worktree's own router.
use std::sync::Arc;
use axum::{
extract::State,
routing::{get, post},
Json, Router,
};
use serde::{Deserialize, Serialize};
use crate::machine::MachineState;
pub fn routes() -> Router<Arc<MachineState>> {
Router::new()
.route(wsb::cli::machine::ROUTE, get(machine))
.route(wsb::cli::machine::RENAME, post(rename))
.route("/api/v1/machine/conflicts", get(conflicts))
.route("/api/v1/worktrees", post(add))
}
/// This machine, as the page's chrome shows it.
#[derive(Debug, Serialize)]
pub struct MachineView {
pub id: String,
pub name: String,
pub fingerprint: String,
pub version: String,
pub peer_port: u16,
pub started_at: u64,
}
async fn machine(State(machine): State<Arc<MachineState>>) -> Json<MachineView> {
Json(MachineView {
id: machine.identity.id().to_string(),
name: machine.identity.name(),
fingerprint: machine.identity.fingerprint().to_string(),
version: wsb::get_version().to_string(),
peer_port: machine.peers.peer_port(),
started_at: machine.started_at,
})
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RenameRequest {
pub name: String,
}
/// Call this machine something else: in its identity file under the
/// workshop's `.state`, and to every peer from its next connection on.
async fn rename(
State(machine): State<Arc<MachineState>>,
Json(body): Json<RenameRequest>,
) -> Result<Json<MachineView>, (axum::http::StatusCode, Json<super::sessions::ErrorResponse>)> {
machine.identity.rename(&machine.machine_dir, &body.name).map_err(|error| {
(axum::http::StatusCode::BAD_REQUEST, Json(super::sessions::ErrorResponse { error }))
})?;
Ok(self::machine(State(machine)).await)
}
/// Every unresolved conflict on this machine, counted by where it is.
///
/// Read by the workbench chrome rather than by a page about one relationship:
/// "something between two machines is waiting for me" has to be visible from
/// wherever you are, and a count nobody sees until they open the right peer is
/// a decision that never gets made.
#[derive(Debug, Serialize)]
pub struct PeerCensus {
pub total: usize,
pub worktrees: Vec<WorktreePeerState>,
}
#[derive(Debug, Serialize)]
pub struct WorktreePeerState {
pub worktree: String,
pub display_name: String,
pub total: usize,
pub repositories: Vec<RepositoryPeerState>,
}
#[derive(Debug, Serialize)]
pub struct RepositoryPeerState {
/// Worktree-relative; the superproject is the empty string, exactly as
/// the tree addresses it.
pub repository: String,
pub conflicts: usize,
/// Paths waiting to come ONTO this machine, summed over peers.
///
/// Separate from `outgoing` because they are different facts about
/// different machines and a person acts on them differently: what is
/// coming here is this machine's to take, and what would leave is the
/// peer's to accept. One "pending" number could say neither.
pub incoming: usize,
/// Paths waiting to go TO a peer, summed over peers.
pub outgoing: usize,
/// Which machines this repository has anything pending WITH, by name. A
/// count alone cannot be acted on — the decision is per peer.
pub peers: Vec<String>,
}
async fn conflicts(State(machine): State<Arc<MachineState>>) -> Json<PeerCensus> {
let counts = machine.store.conflict_counts().unwrap_or_default();
let names: std::collections::BTreeMap<String, String> = machine
.store
.peers()
.unwrap_or_default()
.into_iter()
.map(|peer| (peer.id.to_string(), peer.name))
.collect();
// A continuity id names a worktree by its family and name; the page names
// it as the projects list does.
let titles: std::collections::BTreeMap<String, String> = machine
.store
.worktrees()
.unwrap_or_default()
.into_iter()
.filter_map(|worktree| {
let title = worktree.display_name();
worktree.shared.map(|shared| (shared.to_string(), title))
})
.collect();
// Grouped here rather than in SQL: the shape the page reads is a tree, and
// three ordered scalars are what a GROUP BY can return.
let mut worktrees: Vec<WorktreePeerState> = Vec::new();
for count in counts {
let worktree = match worktrees
.iter_mut()
.find(|held| held.worktree == count.worktree)
{
Some(held) => held,
None => {
worktrees.push(WorktreePeerState {
display_name: titles
.get(&count.worktree)
.cloned()
// A conflict recorded against a worktree this machine
// no longer registers is still a conflict; named by its
// id rather than dropped.
.unwrap_or_else(|| count.worktree.clone()),
worktree: count.worktree.clone(),
total: 0,
repositories: Vec::new(),
});
worktrees.last_mut().expect("just pushed")
}
};
worktree.total += count.conflicts;
let peer = names
.get(&count.peer)
.cloned()
.unwrap_or_else(|| count.peer.clone());
match worktree
.repositories
.iter_mut()
.find(|held| held.repository == count.repository)
{
Some(held) => {
held.conflicts += count.conflicts;
if !held.peers.contains(&peer) {
held.peers.push(peer);
}
}
None => worktree.repositories.push(RepositoryPeerState {
repository: count.repository.clone(),
conflicts: count.conflicts,
incoming: 0,
outgoing: 0,
peers: vec![peer],
}),
}
}
// What is waiting to MOVE, from the last reconciliation of every
// relationship. Conflicts are persisted — they outlive the process that
// found them — while pending transfers are observed state and live only
// for as long as this daemon runs, so the two come from different places
// and are merged here rather than in either of them.
//
// A repository with nothing in conflict but files waiting to cross must
// still appear, which is why this can add rows rather than only filling in
// the ones conflicts created.
for (peer, shared_worktree, statuses) in machine.observed_statuses() {
let peer_name = names.get(&peer).cloned().unwrap_or(peer);
let worktree = match worktrees
.iter_mut()
.find(|held| held.worktree == shared_worktree)
{
Some(held) => held,
None => {
worktrees.push(WorktreePeerState {
display_name: titles
.get(&shared_worktree)
.cloned()
.unwrap_or_else(|| shared_worktree.clone()),
worktree: shared_worktree.clone(),
total: 0,
repositories: Vec::new(),
});
worktrees.last_mut().expect("just pushed")
}
};
for status in statuses {
if status.incoming == 0 && status.outgoing == 0 {
continue;
}
let repository = status.repository.to_string();
match worktree
.repositories
.iter_mut()
.find(|held| held.repository == repository)
{
Some(held) => {
held.incoming += status.incoming;
held.outgoing += status.outgoing;
if !held.peers.contains(&peer_name) {
held.peers.push(peer_name.clone());
}
}
None => worktree.repositories.push(RepositoryPeerState {
repository,
conflicts: 0,
incoming: status.incoming,
outgoing: status.outgoing,
peers: vec![peer_name.clone()],
}),
}
}
}
// Read by a person, so ordered the way they read it: by name.
for worktree in &mut worktrees {
worktree.repositories.sort_by(|a, b| a.repository.cmp(&b.repository));
for repository in &mut worktree.repositories {
repository.peers.sort();
}
}
Json(PeerCensus {
total: worktrees.iter().map(|worktree| worktree.total).sum(),
worktrees,
})
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AddRequest {
/// A directory anywhere inside the checkout. Resolved to its super root
/// the same way every command does.
pub path: String,
}
/// Open a checkout by its path — how one outside `$PRJ` joins the list.
async fn add(
State(machine): State<Arc<MachineState>>,
Json(body): Json<AddRequest>,
) -> Result<Json<wsb::daemon::WorktreeInfo>, (axum::http::StatusCode, Json<serde_json::Value>)> {
let runtime = machine
.resolve(std::path::Path::new(&body.path))
.await
.map_err(|error| {
(
axum::http::StatusCode::BAD_REQUEST,
Json(serde_json::json!({ "error": error })),
)
})?;
crate::web::spawn_worktree_services_once(&runtime);
Ok(Json(crate::control::worktree_info(&runtime)))
}
#[cfg(test)]
#[path = "machine_tests.rs"]
mod tests;