wsb-daemon 0.275.7622

wsb's daemon: the workbench, the GitHub mirror's schedule and peer continuity, for every workspace on the machine
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
//! Boards: every GitHub Projects board of the token's account and its
//! organisations — the company's boards — what is on them, which projects
//! work from each, and everything a person does to one.
//!
//! Boards belong to no worktree, so these are the machine's routes: the
//! workbench opens on them. Reads come from the machine's mirror. Writes go
//! to GitHub FIRST and are mirrored from the item GitHub hands back —
//! `wsb_github::Service` is the one implementation of that, and this is how a
//! page reaches it.

use std::collections::BTreeMap;
use std::sync::Arc;

use axum::extract::{Path, State};
use axum::response::sse::{Event, KeepAlive, Sse};
use axum::routing::{get, post};
use axum::{Json, Router};
use serde::Deserialize;
use serde_json::json;

use crate::machine::MachineState;
use crate::web::github::{self, Refusal};
use wsb_github::boards::BoardRef;
use wsb_github::client::{GitHubProjectItem, ProjectFieldWrite};

pub fn routes() -> Router<Arc<MachineState>> {
    Router::new()
        .route("/api/v1/boards", get(list_boards))
        .route("/api/v1/boards/refresh", post(refresh_boards))
        .route("/api/v1/github/events", get(events))
        .route("/api/v1/boards/:board/items", get(board_items).post(add_item))
        .route("/api/v1/boards/:board/items/:item", axum::routing::delete(remove_item))
        .route("/api/v1/boards/:board/items/:item/field", post(set_field))
        .route("/api/v1/boards/:board/items/:item/position", post(set_position))
        .route("/api/v1/boards/:board/items/:item/archived", post(set_archived))
        .route("/api/v1/boards/:board/items/:item/draft", post(edit_draft))
        .route("/api/v1/boards/:board/columns", post(add_column))
        .route("/api/v1/boards/:board/columns/:option", axum::routing::delete(remove_column))
}

/// Which projects of the workshop work from which boards.
#[derive(Debug, Default)]
struct Using {
    /// Every board some project lists, once each.
    boards: Vec<BoardRef>,
    /// The projects that list each board, by `owner/number`.
    projects: BTreeMap<String, Vec<String>>,
    /// The workspaces whose settings do not read, said rather than skipped.
    problems: Vec<String>,
}

/// `boards` in each workspace's main worktree's committed
/// `.wsb/project.json`. With no workshop, no project lists anything.
fn projects_using() -> Using {
    let mut using = Using::default();
    let workshop = match wsb_prj::Workshop::from_env() {
        Ok(workshop) => workshop,
        Err(wsb_prj::WorkshopError::NotSet) => return using,
        Err(error) => {
            using.problems.push(error.to_string());
            return using;
        }
    };
    let workspaces = match workshop.workspaces() {
        Ok(workspaces) => workspaces,
        Err(error) => {
            using.problems.push(error.to_string());
            return using;
        }
    };
    for workspace in workspaces {
        match wsb_github::boards::read(&workspace.main_worktree()) {
            Ok(boards) => {
                for board in boards {
                    let projects = using.projects.entry(board.to_string()).or_default();
                    if projects.is_empty() {
                        using.boards.push(board);
                    }
                    projects.push(workspace.name().to_string());
                }
            }
            Err(error) => using.problems.push(format!("{}: {error:#}", workspace.name())),
        }
    }
    using
}

/// Every board, the most recently changed first, owner by owner as well,
/// with which projects work from each, how current each owner's list is,
/// and why anything could not be listed.
async fn list_boards(State(machine): State<Arc<MachineState>>) -> Result<Json<serde_json::Value>, Refusal> {
    let github = github::of_machine(&machine)?;
    let service = github.service.clone();
    let (using, all) = github::blocking(move || {
        let using = projects_using();
        service.all_boards(&using.boards).map(|all| (using, all))
    })
    .await?;
    let mut problems = using.problems;
    problems.extend(all.problems);
    Ok(Json(json!({
        "boards": all.boards,
        "recent": all.recent,
        "owners": all.owners,
        "projects": using.projects,
        "account": all.account,
        "problems": problems,
    })))
}

/// Ask GitHub about the boards now — who the token is, every owner's list,
/// the cards of every board — and say what moved. The rest of the machine's
/// mirror is left to its schedule.
async fn refresh_boards(
    State(machine): State<Arc<MachineState>>,
) -> Result<Json<wsb_github::sync::SyncReport>, Refusal> {
    let github = github::of_machine(&machine)?;
    let client = match github::client() {
        Ok(client) => client,
        // No login is a result to show, not a refusal: nothing was asked, and
        // the boards already held are still the answer.
        Err(_) => {
            return Ok(Json(wsb_github::sync::SyncReport {
                no_token: true,
                ..Default::default()
            }))
        }
    };
    let boards = github::blocking(|| Ok(projects_using().boards)).await?;
    Ok(Json(github.service.refresh_boards(&client, &boards).await))
}

/// `GET /api/v1/github/events` — `github` whenever the machine's mirror
/// moves, boards, cards and gists alike: which scopes, so a page re-reads
/// only what it shows.
async fn events(
    State(machine): State<Arc<MachineState>>,
) -> Result<Sse<impl futures::Stream<Item = Result<Event, std::convert::Infallible>>>, Refusal> {
    let mut changed = github::of_machine(&machine)?.changed_tx.subscribe();
    let stream = async_stream::stream! {
        yield Ok(Event::default().event("connected").data("{}"));
        loop {
            let scopes = match changed.recv().await {
                Ok(change) => change,
                // Behind: anything may have moved.
                Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => github::GitHubChanged { scopes: Vec::new() },
                Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
            };
            if let Ok(json) = serde_json::to_string(&scopes) {
                yield Ok(Event::default().event("github").data(json));
            }
        }
    };
    Ok(Sse::new(stream).keep_alive(KeepAlive::default()))
}

/// One board's cards.
///
/// Cards are kept current by the machine's schedule. A board whose cards have
/// never been read — one created a moment ago — is read now, because somebody
/// just opened it.
async fn board_items(
    State(machine): State<Arc<MachineState>>,
    Path(board): Path<String>,
) -> Result<Json<serde_json::Value>, Refusal> {
    let github = github::of_machine(&machine)?;
    let service = github.service.clone();
    let id = board.clone();
    let mut cards = github::blocking(move || service.cards(&id)).await?;
    if !cards.sync.ever_synced {
        if let Ok(client) = github::client() {
            let known = known_board(&machine, &board).await?;
            let report = github.service.refresh_board(&client, &known, true).await;
            if let Some((scope, error)) = report.failed.first() {
                tracing::debug!(%scope, %error, "a board opened for the first time could not be read");
            }
            let service = github.service.clone();
            let id = board.clone();
            cards = github::blocking(move || service.cards(&id)).await?;
        }
    }
    Ok(Json(json!({ "items": cards.items, "sync": cards.sync })))
}

/// The board with this node id, among every board the mirror lists.
async fn known_board(machine: &MachineState, id: &str) -> Result<wsb_github::client::GitHubProject, Refusal> {
    let github = github::of_machine(machine)?;
    let service = github.service.clone();
    let all = github::blocking(move || service.all_boards(&[])).await?;
    all.boards.into_iter().find(|board| board.id == id).ok_or_else(|| {
        github::failure(wsb_github::Failure::Invalid(format!(
            "board {id} is not one the mirror lists for this account or its organisations"
        )))
    })
}

/// Which board a write is for, checked rather than trusted.
///
/// Every mutation names the board in its body as well as its path. A write
/// that took only the path could be pointed at a card on another board by a
/// caller that got one of the two wrong — and a card moved on the wrong board
/// is not something the answer would reveal.
fn same_board(path: &str, body: &str) -> Result<(), Refusal> {
    if path == body {
        return Ok(());
    }
    Err(github::failure(wsb_github::Failure::Invalid(format!(
        "the path names board {path} and the body names {body}"
    ))))
}

fn item(card: GitHubProjectItem) -> Json<serde_json::Value> {
    Json(json!({ "item": card }))
}

#[derive(Debug, Deserialize)]
pub struct FieldRequest {
    /// The board, by node id.
    pub project: String,
    /// The field being written.
    pub field: String,
    /// The value, or `null` to take the field's value off the card: an empty
    /// text IS a value, and clearing is its own act.
    pub value: Option<ProjectFieldWrite>,
}

/// Set or clear one field on one card.
async fn set_field(
    State(machine): State<Arc<MachineState>>,
    Path((project, card)): Path<(String, String)>,
    Json(body): Json<FieldRequest>,
) -> Result<Json<serde_json::Value>, Refusal> {
    same_board(&project, &body.project)?;
    let github = github::of_machine(&machine)?;
    let client = github::client()?;
    github
        .service
        .set_field(&client, &project, &card, &body.field, body.value.as_ref())
        .await
        .map(item)
        .map_err(github::failure)
}

#[derive(Debug, Deserialize)]
pub struct PositionRequest {
    pub project: String,
    /// The card this one lands behind. `null` puts it first.
    pub after: Option<String>,
}

/// Order one card against the others.
async fn set_position(
    State(machine): State<Arc<MachineState>>,
    Path((project, card)): Path<(String, String)>,
    Json(body): Json<PositionRequest>,
) -> Result<Json<serde_json::Value>, Refusal> {
    same_board(&project, &body.project)?;
    let github = github::of_machine(&machine)?;
    let client = github::client()?;
    github
        .service
        .move_card(&client, &project, &card, body.after.as_deref())
        .await
        .map(item)
        .map_err(github::failure)
}

#[derive(Debug, Deserialize)]
pub struct ArchiveRequest {
    pub project: String,
    /// Archived, or brought back — stated rather than toggled.
    pub archived: bool,
}

/// Archive a card, or bring it back.
async fn set_archived(
    State(machine): State<Arc<MachineState>>,
    Path((project, card)): Path<(String, String)>,
    Json(body): Json<ArchiveRequest>,
) -> Result<Json<serde_json::Value>, Refusal> {
    same_board(&project, &body.project)?;
    let github = github::of_machine(&machine)?;
    let client = github::client()?;
    github
        .service
        .set_archived(&client, &project, &card, body.archived)
        .await
        .map(item)
        .map_err(github::failure)
}

#[derive(Debug, Deserialize)]
pub struct DraftRequest {
    pub project: String,
    /// What the card points at — the draft itself, not the card. A draft is
    /// edited by its content id and moved by its item id.
    pub content: String,
    pub title: String,
    #[serde(default)]
    pub body: String,
}

/// Rewrite a draft card's title and body.
async fn edit_draft(
    State(machine): State<Arc<MachineState>>,
    Path((project, card)): Path<(String, String)>,
    Json(body): Json<DraftRequest>,
) -> Result<Json<serde_json::Value>, Refusal> {
    same_board(&project, &body.project)?;
    let github = github::of_machine(&machine)?;
    let client = github::client()?;
    github
        .service
        .edit_draft(&client, &project, &card, &body.content, &body.title, &body.body)
        .await
        .map(item)
        .map_err(github::failure)
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum AddRequest {
    /// An issue or pull request that already exists, by its URL.
    Existing { project: String, url: String },
    /// A card that lives only on the board.
    Draft {
        project: String,
        title: String,
        #[serde(default)]
        body: String,
    },
}

impl AddRequest {
    fn project(&self) -> &str {
        match self {
            Self::Existing { project, .. } | Self::Draft { project, .. } => project,
        }
    }
}

/// Put something new on the board.
async fn add_item(
    State(machine): State<Arc<MachineState>>,
    Path(project): Path<String>,
    Json(body): Json<AddRequest>,
) -> Result<Json<serde_json::Value>, Refusal> {
    same_board(&project, body.project())?;
    let github = github::of_machine(&machine)?;
    let client = github::client()?;
    let added = match &body {
        AddRequest::Existing { url, .. } => github.service.add_existing(&client, &project, url).await,
        AddRequest::Draft { title, body, .. } => {
            github.service.add_draft(&client, &project, title, body).await
        }
    };
    added.map(item).map_err(github::failure)
}

#[derive(Debug, Deserialize)]
pub struct RemoveRequest {
    pub project: String,
}

/// Take a card off the board. The issue itself is untouched.
async fn remove_item(
    State(machine): State<Arc<MachineState>>,
    Path((project, card)): Path<(String, String)>,
    Json(body): Json<RemoveRequest>,
) -> Result<Json<serde_json::Value>, Refusal> {
    same_board(&project, &body.project)?;
    let github = github::of_machine(&machine)?;
    let client = github::client()?;
    github
        .service
        .remove_card(&client, &project, &card)
        .await
        .map_err(github::failure)?;
    Ok(Json(json!({ "removed": card })))
}

#[derive(Debug, Deserialize)]
pub struct AddColumnRequest {
    pub project: String,
    pub field: String,
    pub name: String,
    pub color: String,
    pub description: String,
}

/// Add a column option to the board's live single-select field.
async fn add_column(
    State(machine): State<Arc<MachineState>>,
    Path(project): Path<String>,
    Json(body): Json<AddColumnRequest>,
) -> Result<Json<serde_json::Value>, Refusal> {
    same_board(&project, &body.project)?;
    let github = github::of_machine(&machine)?;
    let client = github::client()?;
    let (board, items) = github
        .service
        .add_column(&client, &project, &body.field, &body.name, &body.color, &body.description)
        .await
        .map_err(github::failure)?;
    Ok(Json(json!({ "project": board, "items": items })))
}

#[derive(Debug, Deserialize)]
pub struct RemoveColumnRequest {
    pub project: String,
    pub field: String,
}

/// Remove one column option. GitHub clears that value from affected cards;
/// every card is read again before the mirror changes.
async fn remove_column(
    State(machine): State<Arc<MachineState>>,
    Path((project, option)): Path<(String, String)>,
    Json(body): Json<RemoveColumnRequest>,
) -> Result<Json<serde_json::Value>, Refusal> {
    same_board(&project, &body.project)?;
    let github = github::of_machine(&machine)?;
    let client = github::client()?;
    let (board, items) = github
        .service
        .remove_column(&client, &project, &body.field, &option)
        .await
        .map_err(github::failure)?;
    Ok(Json(json!({ "project": board, "items": items })))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// TEST20123: the boards page says which projects work from each board:
    /// every workspace's main worktree's committed `boards`, a board listed by
    /// two projects once with both, and a workspace whose settings do not
    /// read named as a problem rather than dropped.
    #[test]
    fn test20123_each_board_carries_the_projects_that_work_from_it() {
        let prj = tempfile::tempdir().expect("a workshop");
        let machine = tempfile::tempdir().expect("a machine folder");
        let _env = wsb::test_environment::Environment::set(&[
            ("PRJ", &prj.path().to_string_lossy()),
            (wsb::daemon::MACHINE_DIR_ENV, &machine.path().to_string_lossy()),
        ]);
        let lists = |project: &str, boards: &[&str]| {
            let main = prj.path().join(project).join("main-worktree");
            std::fs::create_dir_all(&main).expect("a main worktree");
            wsb::settings::ProjectSettings {
                boards: boards.iter().map(|board| board.to_string()).collect(),
                ..Default::default()
            }
            .save(&main)
            .expect("the settings are written");
        };
        lists("alpha", &["acme/1", "acme/2"]);
        lists("beta", &["acme/2"]);
        lists("gamma", &[]);
        let broken = prj.path().join("delta/main-worktree/.wsb");
        std::fs::create_dir_all(&broken).expect("a settings folder");
        std::fs::write(broken.join("project.json"), "{ not json").expect("broken settings");

        let using = projects_using();

        assert_eq!(
            using.boards.iter().map(ToString::to_string).collect::<Vec<_>>(),
            ["acme/1", "acme/2"],
            "each listed board once"
        );
        assert_eq!(using.projects["acme/1"], ["alpha"]);
        assert_eq!(using.projects["acme/2"], ["alpha", "beta"]);
        assert_eq!(using.projects.len(), 2, "{:?}", using.projects);
        assert_eq!(using.problems.len(), 1, "{:?}", using.problems);
        assert!(using.problems[0].starts_with("delta: "), "{:?}", using.problems);
    }

    #[test]
    fn a_write_naming_two_boards_is_refused() {
        assert!(same_board("PVT_1", "PVT_1").is_ok());
        let (status, body) = same_board("PVT_1", "PVT_2").expect_err("two boards");
        assert_eq!(status, axum::http::StatusCode::BAD_REQUEST);
        assert!(body.0.error.contains("PVT_1") && body.0.error.contains("PVT_2"));
    }
}