sapphire-framework-server 0.29.0

App server skeleton for sapphire-framework: owns a workspace's cache and serves it over IPC
Documentation
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
//! The server's one workspace end to end (#215): `workspace.init` selects what it creates,
//! `workspace.current` reports it, sync is switched on and off for it, and a restarting
//! server comes back to it — and to its sync — from `workspace.toml`, or from the list an
//! older server kept.
//!
//! Each test owns its `AppContext` (the directories are first-writer-wins per context), so
//! the file one test writes is never the one another reads.

use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use sapphire_backend::protocol as proto;
use sapphire_framework_server::sync::testing::StubBridge;
use sapphire_framework_server::{AppServer, SyncRuntime};
use sapphire_ipc::{Client, ClientInfo, Endpoint, ManagedBy, connect_or_absent};
use sapphire_workspace::{AppContext, AppKind};

static CTX_A: AppContext = AppContext::new("sapphire-hostreg-a");
static CTX_B: AppContext = AppContext::new("sapphire-hostreg-b");

const VARS_A: [&str; 3] = [
    "SAPPHIRE_HOSTREG_A_CACHE_DIR",
    "SAPPHIRE_HOSTREG_A_DATA_DIR",
    "SAPPHIRE_HOSTREG_A_CONFIG_DIR",
];
const VARS_B: [&str; 3] = [
    "SAPPHIRE_HOSTREG_B_CACHE_DIR",
    "SAPPHIRE_HOSTREG_B_DATA_DIR",
    "SAPPHIRE_HOSTREG_B_CONFIG_DIR",
];

/// Point the context's directories at this test's scratch tree, and put them back on drop.
struct EnvGuard {
    vars: [&'static str; 3],
    previous: [Option<std::ffi::OsString>; 3],
    _lock: std::sync::MutexGuard<'static, ()>,
}

impl Drop for EnvGuard {
    fn drop(&mut self) {
        // SAFETY: `self._lock` still serialises the environment; it is dropped only after
        // this method returns.
        for (name, previous) in self.vars.iter().zip(self.previous.iter_mut()) {
            match previous.take() {
                Some(value) => unsafe { std::env::set_var(name, value) },
                None => unsafe { std::env::remove_var(name) },
            }
        }
    }
}

/// Point `ctx`'s directories (named by `vars`) at `tmp` while holding the environment lock.
fn point_at(ctx: &'static AppContext, vars: [&'static str; 3], tmp: &std::path::Path) -> EnvGuard {
    // The contexts are first-writer-wins, so every test in this binary serialises on the
    // environment even though each has a context of its own.
    static ENV: std::sync::Mutex<()> = std::sync::Mutex::new(());
    let lock = ENV.lock().unwrap_or_else(|e| e.into_inner());
    let previous = vars.map(std::env::var_os);
    // SAFETY (via the lock above): serialised against every other use in this binary.
    for (name, dir) in vars
        .iter()
        .zip(["cache", "data", "config"].map(|cat| tmp.join(cat)))
    {
        unsafe { std::env::set_var(name, dir) };
    }
    ctx.init(AppKind::Server);
    EnvGuard {
        vars,
        previous,
        _lock: lock,
    }
}

/// Wait until the server listens on `endpoint`.
async fn wait_until_listening(endpoint: &Endpoint) {
    let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
    while !sapphire_ipc::probe(endpoint).await.unwrap() {
        assert!(
            tokio::time::Instant::now() < deadline,
            "the server never started listening"
        );
        tokio::time::sleep(Duration::from_millis(20)).await;
    }
}

/// Start a sync-mounted server on `endpoint` against a fresh stub bridge.
async fn start(
    ctx: &'static AppContext,
    endpoint: &Endpoint,
) -> (StubBridge, tokio::task::JoinHandle<()>) {
    let (stub, bridge) = StubBridge::start().await;
    let runtime = Arc::new(SyncRuntime::new(
        ctx,
        bridge,
        PathBuf::from("/bin/true"),
        ManagedBy::Service,
    ));
    let server = AppServer::new(ctx, "0.0.0")
        .endpoint(endpoint.clone())
        .sync(runtime);
    let task = tokio::spawn(async move { server.run().await.unwrap() });
    wait_until_listening(endpoint).await;
    (stub, task)
}

async fn client(ctx: &'static AppContext, endpoint: &Endpoint) -> Client {
    let info = ClientInfo {
        kind: "test".into(),
        version: "0.0.0".into(),
        api: proto::API_VERSION,
        app_api: None,
        pid: std::process::id(),
    };
    connect_or_absent(endpoint, ctx.app_name, info)
        .await
        .unwrap()
        .unwrap()
        .0
}

async fn current(c: &Client) -> Option<proto::CurrentWorkspace> {
    c.call::<_, proto::WorkspaceCurrentResult>(proto::WORKSPACE_CURRENT, serde_json::json!({}))
        .await
        .unwrap()
        .workspace
}

async fn init(c: &Client, dir: PathBuf) -> proto::WorkspaceInitResult {
    c.call(proto::WORKSPACE_INIT, proto::WorkspaceInitParams { dir })
        .await
        .unwrap()
}

async fn stop(ctx: &'static AppContext, endpoint: &Endpoint, task: tokio::task::JoinHandle<()>) {
    let c = client(ctx, endpoint).await;
    let _: serde_json::Value = c
        .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
        .await
        .unwrap();
    task.await.unwrap();
}

async fn until(what: &str, mut done: impl FnMut() -> bool) {
    let deadline = std::time::Instant::now() + Duration::from_secs(10);
    while !done() {
        assert!(std::time::Instant::now() < deadline, "never: {what}");
        tokio::time::sleep(Duration::from_millis(20)).await;
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn init_selects_and_sync_switches_on_and_off_for_the_current_workspace() {
    let tmp = tempfile::tempdir().unwrap();
    let _env = point_at(&CTX_A, VARS_A, tmp.path());
    let endpoint = Endpoint::in_dir("sapphire-hostreg-a", tmp.path().join("run"));
    std::fs::create_dir_all(tmp.path().join("run")).unwrap();
    let (stub, task) = start(&CTX_A, &endpoint).await;
    let c = client(&CTX_A, &endpoint).await;
    assert!(current(&c).await.is_none(), "no workspace before the first");

    let root = tmp.path().join("notes");
    std::fs::create_dir_all(&root).unwrap();
    let made = init(&c, root.clone()).await;
    let ws = current(&c).await.unwrap();
    assert_eq!(ws.root, made.root);
    assert!(ws.reachable);
    assert!(!ws.sync.enabled);
    assert_eq!(ws.workspace_id, None, "describing never mints a sync id");

    let enabled: proto::SyncEnableResult = c
        .call(proto::SYNC_ENABLE, serde_json::json!({}))
        .await
        .unwrap();
    let ws = current(&c).await.unwrap();
    assert!(ws.sync.enabled);
    assert_eq!(ws.workspace_id, Some(enabled.workspace_id));

    let _: proto::Ack = c
        .call(proto::SYNC_DISABLE, serde_json::json!({}))
        .await
        .unwrap();
    let ws = current(&c).await.unwrap();
    assert!(!ws.sync.enabled);
    assert_eq!(
        ws.workspace_id,
        Some(enabled.workspace_id),
        "a disabled workspace keeps its id"
    );
    drop(stub);
    drop(c);
    stop(&CTX_A, &endpoint, task).await;
}

#[tokio::test(flavor = "multi_thread")]
async fn serve_comes_back_to_the_workspace_and_its_sync() {
    let tmp = tempfile::tempdir().unwrap();
    let _env = point_at(&CTX_B, VARS_B, tmp.path());
    std::fs::create_dir_all(tmp.path().join("run")).unwrap();
    let endpoint = Endpoint::in_dir("sapphire-hostreg-b", tmp.path().join("run"));

    let (_stub, task) = start(&CTX_B, &endpoint).await;
    let c = client(&CTX_B, &endpoint).await;
    let root = tmp.path().join("kept");
    std::fs::create_dir_all(&root).unwrap();
    let made = init(&c, root).await;
    let e: proto::SyncEnableResult = c
        .call(proto::SYNC_ENABLE, serde_json::json!({}))
        .await
        .unwrap();
    drop(c);
    stop(&CTX_B, &endpoint, task).await;

    let (stub, task) = start(&CTX_B, &endpoint).await;
    until("the workspace's sync to come back", || {
        stub.last_workspaces().contains(&e.workspace_id)
    })
    .await;
    let c = client(&CTX_B, &endpoint).await;
    assert_eq!(current(&c).await.unwrap().root, made.root);
    drop(c);
    stop(&CTX_B, &endpoint, task).await;
}

static CTX_D: AppContext = AppContext::new("sapphire-hostreg-d");
const VARS_D: [&str; 3] = [
    "SAPPHIRE_HOSTREG_D_CACHE_DIR",
    "SAPPHIRE_HOSTREG_D_DATA_DIR",
    "SAPPHIRE_HOSTREG_D_CONFIG_DIR",
];

#[tokio::test(flavor = "multi_thread")]
async fn a_workspace_gone_while_stopped_stays_selected_and_unreachable() {
    let tmp = tempfile::tempdir().unwrap();
    let _env = point_at(&CTX_D, VARS_D, tmp.path());
    std::fs::create_dir_all(tmp.path().join("run")).unwrap();
    let endpoint = Endpoint::in_dir("sapphire-hostreg-d", tmp.path().join("run"));
    let (_stub, task) = start(&CTX_D, &endpoint).await;
    let c = client(&CTX_D, &endpoint).await;
    let root = tmp.path().join("vanishing");
    std::fs::create_dir_all(&root).unwrap();
    let made = init(&c, root.clone()).await;
    drop(c);
    stop(&CTX_D, &endpoint, task).await;
    std::fs::remove_dir_all(&root).unwrap();

    let (_stub, task) = start(&CTX_D, &endpoint).await;
    let c = client(&CTX_D, &endpoint).await;
    let ws = current(&c).await.expect("still the selected workspace");
    assert_eq!(ws.root, made.root);
    assert!(!ws.reachable);
    let err = c
        .call::<_, proto::ReadResult>(
            proto::READ_FILE,
            proto::PathParams {
                path: PathBuf::from("a.md"),
            },
        )
        .await;
    assert!(
        err.is_err(),
        "nothing to read from a workspace that is gone"
    );
    drop(c);
    stop(&CTX_D, &endpoint, task).await;
}

static CTX_C: AppContext = AppContext::new("sapphire-hostreg-c");
const VARS_C: [&str; 3] = [
    "SAPPHIRE_HOSTREG_C_CACHE_DIR",
    "SAPPHIRE_HOSTREG_C_DATA_DIR",
    "SAPPHIRE_HOSTREG_C_CONFIG_DIR",
];

#[tokio::test(flavor = "multi_thread")]
async fn the_cli_renders_the_current_workspace_or_says_there_is_none() {
    let tmp = tempfile::tempdir().unwrap();
    let _env = point_at(&CTX_C, VARS_C, tmp.path());
    std::fs::create_dir_all(tmp.path().join("run")).unwrap();
    let endpoint = Endpoint::in_dir("sapphire-hostreg-c", tmp.path().join("run"));
    let (_stub, task) = start(&CTX_C, &endpoint).await;
    let c = client(&CTX_C, &endpoint).await;

    let mut out = String::new();
    let code = sapphire_framework_server::render_workspace(&c, &mut out)
        .await
        .unwrap();
    assert_eq!(code, 1);
    assert!(out.contains("no workspace yet"), "{out}");

    let root = tmp.path().join("notes");
    std::fs::create_dir_all(&root).unwrap();
    init(&c, root).await;
    let mut out = String::new();
    let code = sapphire_framework_server::render_workspace(&c, &mut out)
        .await
        .unwrap();
    assert_eq!(code, 0);
    assert!(out.contains("notes"), "{out}");
    assert!(out.contains("not synced"), "{out}");
    drop(c);
    stop(&CTX_C, &endpoint, task).await;
}

static CTX_E: AppContext = AppContext::new("sapphire-hostreg-e");
const VARS_E: [&str; 3] = [
    "SAPPHIRE_HOSTREG_E_CACHE_DIR",
    "SAPPHIRE_HOSTREG_E_DATA_DIR",
    "SAPPHIRE_HOSTREG_E_CONFIG_DIR",
];

#[tokio::test(flavor = "multi_thread")]
async fn an_older_servers_list_becomes_the_selection() {
    let tmp = tempfile::tempdir().unwrap();
    let _env = point_at(&CTX_E, VARS_E, tmp.path());
    std::fs::create_dir_all(tmp.path().join("run")).unwrap();
    let endpoint = Endpoint::in_dir("sapphire-hostreg-e", tmp.path().join("run"));
    let synced = tmp.path().join("synced");
    std::fs::create_dir_all(synced.join(".sapphire-hostreg-e")).unwrap();
    let synced = synced.canonicalize().unwrap();
    // The config directory is `<category root>/<app name>`.
    let config = tmp.path().join("config").join(CTX_E.app_name);
    std::fs::create_dir_all(&config).unwrap();
    std::fs::write(
        config.join("workspaces.toml"),
        format!(
            "[workspace.other]\nroot = \"/nowhere\"\n\n[workspace.synced]\nroot = {:?}\nsynced = true\n",
            synced.display().to_string()
        ),
    )
    .unwrap();

    let (stub, task) = start(&CTX_E, &endpoint).await;
    let c = client(&CTX_E, &endpoint).await;
    assert_eq!(current(&c).await.unwrap().root, synced);
    until("the migrated workspace to sync", || {
        !stub.last_workspaces().is_empty()
    })
    .await;
    drop(c);
    stop(&CTX_E, &endpoint, task).await;
}

static CTX_F: AppContext = AppContext::new("sapphire-hostreg-f");
const VARS_F: [&str; 3] = [
    "SAPPHIRE_HOSTREG_F_CACHE_DIR",
    "SAPPHIRE_HOSTREG_F_DATA_DIR",
    "SAPPHIRE_HOSTREG_F_CONFIG_DIR",
];

async fn search(c: &Client, query: &str) -> Vec<String> {
    let result: proto::SearchResult = c
        .call(
            proto::SEARCH,
            proto::SearchParams {
                query: query.into(),
                limit: 10,
                mode: sapphire_backend::SearchMode::Fts,
            },
        )
        .await
        .unwrap();
    result.hits.into_iter().map(|h| h.path).collect()
}

#[tokio::test(flavor = "multi_thread")]
async fn a_moved_workspace_keeps_its_files_its_sync_and_its_replica() {
    let tmp = tempfile::tempdir().unwrap();
    let _env = point_at(&CTX_F, VARS_F, tmp.path());
    std::fs::create_dir_all(tmp.path().join("run")).unwrap();
    let endpoint = Endpoint::in_dir("sapphire-hostreg-f", tmp.path().join("run"));
    let (stub, task) = start(&CTX_F, &endpoint).await;
    let c = client(&CTX_F, &endpoint).await;

    let wrong = tmp.path().join("wrong");
    std::fs::create_dir_all(&wrong).unwrap();
    let made = init(&c, wrong).await;
    let enabled: proto::SyncEnableResult = c
        .call(proto::SYNC_ENABLE, serde_json::json!({}))
        .await
        .unwrap();
    let _: proto::Ack = c
        .call(
            proto::WRITE_FILE,
            proto::ContentParams {
                path: PathBuf::from("a.md"),
                content: "the quick brown fox".into(),
            },
        )
        .await
        .unwrap();
    let old_replica = CTX_F
        .cache_dir_for(&made.root)
        .join("sync")
        .join("sync.redb");
    assert!(old_replica.is_file());

    std::fs::create_dir_all(tmp.path().join("right")).unwrap();
    let to = tmp.path().join("right").join("notes");
    let moved: proto::CurrentWorkspace = c
        .call(
            proto::WORKSPACE_MOVE,
            proto::WorkspaceMoveParams { dir: to.clone() },
        )
        .await
        .unwrap();
    let to = to.canonicalize().unwrap();
    assert_eq!(moved.root, to);
    assert!(!made.root.exists(), "the old folder is gone");
    assert!(moved.reachable);
    assert!(moved.sync.enabled, "still synced");
    assert_eq!(moved.workspace_id, Some(enabled.workspace_id));
    assert!(stub.last_workspaces().contains(&enabled.workspace_id));
    assert!(
        !CTX_F.cache_dir_for(&made.root).exists(),
        "the old cache is gone"
    );
    let replica = CTX_F.cache_dir_for(&to).join("sync").join("sync.redb");
    assert!(replica.is_file(), "the replica came along");

    let read: proto::ReadResult = c
        .call(
            proto::READ_FILE,
            proto::PathParams {
                path: PathBuf::from("a.md"),
            },
        )
        .await
        .unwrap();
    assert_eq!(read.content, "the quick brown fox");
    // The index names files by their absolute path, so a stale one names the old root.
    let moved_file = to.join("a.md").to_string_lossy().into_owned();
    let deadline = std::time::Instant::now() + Duration::from_secs(10);
    while search(&c, "brown").await != [moved_file.clone()] {
        assert!(
            std::time::Instant::now() < deadline,
            "the index is rebuilt at the new root: {:?}",
            search(&c, "brown").await
        );
        tokio::time::sleep(Duration::from_millis(50)).await;
    }

    // Onto an existing folder is refused, and changes nothing.
    let err = c
        .call::<_, proto::CurrentWorkspace>(
            proto::WORKSPACE_MOVE,
            proto::WorkspaceMoveParams {
                dir: tmp.path().join("right"),
            },
        )
        .await
        .unwrap_err();
    assert!(err.to_string().contains("already exists"), "{err}");
    assert_eq!(current(&c).await.unwrap().root, to);

    drop(c);
    stop(&CTX_F, &endpoint, task).await;

    // A restart comes back to the new root.
    let (_stub, task) = start(&CTX_F, &endpoint).await;
    let c = client(&CTX_F, &endpoint).await;
    assert_eq!(current(&c).await.unwrap().root, to);
    drop(c);
    stop(&CTX_F, &endpoint, task).await;
}

static CTX_G: AppContext = AppContext::new("sapphire-hostreg-g");
const VARS_G: [&str; 3] = [
    "SAPPHIRE_HOSTREG_G_CACHE_DIR",
    "SAPPHIRE_HOSTREG_G_DATA_DIR",
    "SAPPHIRE_HOSTREG_G_CONFIG_DIR",
];

#[tokio::test(flavor = "multi_thread")]
async fn a_removed_workspace_is_let_go_and_deleted_only_when_asked() {
    let tmp = tempfile::tempdir().unwrap();
    let _env = point_at(&CTX_G, VARS_G, tmp.path());
    std::fs::create_dir_all(tmp.path().join("run")).unwrap();
    let endpoint = Endpoint::in_dir("sapphire-hostreg-g", tmp.path().join("run"));
    let (stub, task) = start(&CTX_G, &endpoint).await;
    let c = client(&CTX_G, &endpoint).await;

    let kept = tmp.path().join("kept");
    std::fs::create_dir_all(&kept).unwrap();
    std::fs::write(kept.join("a.md"), "keep me").unwrap();
    init(&c, kept.clone()).await;
    let enabled: proto::SyncEnableResult = c
        .call(proto::SYNC_ENABLE, serde_json::json!({}))
        .await
        .unwrap();
    let _: proto::Ack = c
        .call(
            proto::WORKSPACE_REMOVE,
            proto::WorkspaceRemoveParams { delete: false },
        )
        .await
        .unwrap();
    assert!(current(&c).await.is_none());
    assert!(kept.join("a.md").is_file(), "the files stay");
    assert!(!stub.last_workspaces().contains(&enabled.workspace_id));

    let doomed = tmp.path().join("doomed");
    std::fs::create_dir_all(&doomed).unwrap();
    std::fs::write(doomed.join("b.md"), "delete me").unwrap();
    let made = init(&c, doomed.clone()).await;
    let _: proto::Ack = c
        .call(
            proto::WORKSPACE_REMOVE,
            proto::WorkspaceRemoveParams { delete: true },
        )
        .await
        .unwrap();
    assert!(current(&c).await.is_none());
    assert!(!doomed.exists(), "the folder is deleted");
    assert!(!CTX_G.cache_dir_for(&made.root).exists(), "and its cache");
    drop(c);
    stop(&CTX_G, &endpoint, task).await;

    let (_stub, task) = start(&CTX_G, &endpoint).await;
    let c = client(&CTX_G, &endpoint).await;
    assert!(
        current(&c).await.is_none(),
        "a restart does not bring it back"
    );
    drop(c);
    stop(&CTX_G, &endpoint, task).await;
}