gent-daemon 0.2.2

Local daemon, storage and synchronization for Gent chat clusters.
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
use super::*;

fn retained(pair: &Pair, id: &str) -> ConfigurationEdit {
    let store = &pair.stores[1];
    configuration::pending::load(&store.db, store.identity.node.id(), id).unwrap()
}

fn count(pair: &Pair) -> u64 {
    pair.stores[1]
        .db
        .query_row("SELECT COUNT(*) FROM configuration_pending", [], |r| {
            r.get(0)
        })
        .unwrap()
}

#[tokio::test]
async fn frozen_source_retains_its_local_edits_atomically_and_reroutes_after_activation() {
    for allowed in [false, true] {
        let mut pair = Pair::new().await;
        let keys = [credential(&pair, 0), credential(&pair, 1)];
        let origin = pair.stores[0].identity.node.id().to_owned();
        let initial_name = pair.stores[0]
            .identity
            .state(&pair.stores[0].db)
            .unwrap()
            .state()
            .nodes[&origin]
            .name
            .clone();
        if allowed {
            pair.stores[0]
                .execute(Request::Owner {
                    credential: keys[0].clone(),
                    action: OwnerOp::DelegateConfiguration {
                        node_id: origin.clone(),
                        allow: true,
                    },
                })
                .unwrap();
            pair.pump();
        }
        let candidate = prepare(&mut pair);
        let authorization = issue(&mut pair, &candidate);
        let id = Uuid::new_v4().to_string();
        let edit = ConfigurationEdit::RenameNode {
            name: "retired-source-edit".into(),
        };
        pair.stores[0].db.execute_batch("CREATE TRIGGER refuse_payload BEFORE INSERT ON configuration_pending BEGIN SELECT RAISE(ABORT,'payload failure'); END;").unwrap();
        assert!(configure(&mut pair, 0, &id, edit.clone()).is_err());
        assert_eq!(
            pair.stores[0]
                .db
                .query_row(
                    "SELECT COUNT(*) FROM configuration_edits WHERE id=?1",
                    [&id],
                    |r| r.get::<_, usize>(0)
                )
                .unwrap(),
            0
        );
        pair.stores[0]
            .db
            .execute_batch("DROP TRIGGER refuse_payload")
            .unwrap();
        let queued = configure(&mut pair, 0, &id, edit.clone()).unwrap();
        assert_eq!(queued["state"], "queued");
        assert_eq!(queued["payload_retained"], true);
        assert!(configure(&mut pair, 0, &id, ConfigurationEdit::Renew).is_err());
        pair.reopen(0);
        assert_eq!(configure(&mut pair, 0, &id, edit.clone()).unwrap(), queued);
        assert_eq!(
            pair.stores[0]
                .identity
                .state(&pair.stores[0].db)
                .unwrap()
                .checkpoint(),
            &candidate.candidate.base
        );
        assert!(pair.stores[0].require_provisioning_owner().is_err());
        assert_eq!(
            pair.stores[0]
                .authorize_owner_handoff(&keys[0], &candidate)
                .unwrap(),
            authorization
        );
        pair.stores[1]
            .accept_owner_handoff(&keys[1], &candidate.candidate.id, &authorization)
            .unwrap();
        pair.stores[1]
            .activate_owner_handoff(&keys[1], &candidate.candidate.id)
            .unwrap();
        pair.pump();
        let completed = configure(&mut pair, 0, &id, edit.clone()).unwrap();
        assert_eq!(
            completed["state"],
            if allowed { "applied" } else { "rejected" }
        );
        if !allowed {
            assert!(
                completed["reason"]
                    .as_str()
                    .unwrap()
                    .contains("configuration-management grant")
            );
        }
        let expected_name = if allowed {
            "retired-source-edit"
        } else {
            &initial_name
        };
        assert_eq!(
            config::load(pair.homes[0].path()).unwrap().node.name,
            expected_name
        );
        assert_eq!(
            pair.stores[0]
                .db
                .query_row(
                    "SELECT COUNT(*) FROM configuration_pending WHERE id=?1",
                    [&id],
                    |r| r.get::<_, usize>(0)
                )
                .unwrap(),
            0
        );
        pair.reopen(0);
        assert_eq!(configure(&mut pair, 0, &id, edit).unwrap(), completed);
    }
}

#[tokio::test]
async fn full_pending_policy_survives_transport_retirement_and_owner_downtime() {
    let mut pair = Pair::new().await;
    let id = Uuid::new_v4().to_string();
    let policy = Policy {
        rules: vec![
            Rule {
                actor: Selector::All,
                peer: Selector::All,
                permission: Permission::Enumerate,
                effect: Effect::Allow
            };
            2000
        ],
        ..Policy::default()
    };
    let edit = ConfigurationEdit::Policy { policy };
    let original = serde_json::to_vec(&edit).unwrap();
    assert!(original.len() > 128 * 1024);
    let candidate = prepare(&mut pair);
    issue(&mut pair, &candidate);
    let queued = configure(&mut pair, 1, &id, edit.clone()).unwrap();
    assert_eq!(queued["payload_retained"], true);
    let group: Vec<u8> = pair.stores[1]
        .db
        .query_row("SELECT outgoing FROM network_links", [], |r| r.get(0))
        .unwrap();
    let next = pair.stores[0].data_next(&group).unwrap();
    pair.stores[1].data_prepare(&group).unwrap();
    let packet = pair.stores[1].data_outgoing(&group, next).unwrap().unwrap();
    assert!(
        pair.stores[0]
            .data_receive(&packet)
            .unwrap_err()
            .to_string()
            .contains("signing is frozen")
    );
    let receipt = pair.stores[0].transport_receipt(&group, false).unwrap();
    pair.stores[1]
        .transport_confirm(&group, false, Some(&receipt))
        .unwrap();
    assert_eq!(
        pair.stores[1]
            .db
            .query_row("SELECT COUNT(*) FROM network_events", [], |r| r
                .get::<_, u64>(0))
            .unwrap(),
        0
    );
    pair.reopen(1);
    pair.stores[1].maintain().unwrap();
    assert_eq!(serde_json::to_vec(&retained(&pair, &id)).unwrap(), original);
    assert_eq!(configure(&mut pair, 1, &id, edit).unwrap(), queued);
    assert_eq!(count(&pair), 1);
}

#[tokio::test]
async fn result_commit_releases_payload_and_failed_release_preserves_the_pending_request() {
    let mut pair = Pair::new().await;
    let id = Uuid::new_v4().to_string();
    let edit = ConfigurationEdit::RenameNode {
        name: "retained-until-decision".into(),
    };
    configure(&mut pair, 1, &id, edit.clone()).unwrap();
    let origin = pair.stores[1].identity.node.id().to_owned();
    let result = crate::messages::EditResult::Rejected {
        reason: "test decision".into(),
    };
    let fingerprint = hash(&serde_json::to_string(&edit).unwrap());
    pair.stores[1].db.execute_batch("CREATE TRIGGER fail_release BEFORE DELETE ON configuration_pending BEGIN SELECT RAISE(ABORT,'release failure'); END;").unwrap();
    let writer = pair.stores[0].identity.node.id().to_owned();
    {
        let store = &pair.stores[1];
        let tx = store.db.unchecked_transaction().unwrap();
        let session = store.network_session(&tx, store.identity.state(&tx).unwrap());
        assert!(
            session
                .import_configuration_result(
                    &writer,
                    Uuid::parse_str(&id).unwrap(),
                    &fingerprint,
                    result
                )
                .is_err()
        );
        tx.rollback().unwrap();
    }
    assert_eq!(count(&pair), 1);
    assert!(
        pair.stores[1]
            .db
            .query_row(
                "SELECT result IS NULL FROM configuration_edits WHERE origin=?1 AND id=?2",
                params![origin, id],
                |r| r.get::<_, bool>(0)
            )
            .unwrap()
    );
    pair.stores[1]
        .db
        .execute_batch("DROP TRIGGER fail_release;")
        .unwrap();
    pair.pump();
    assert_eq!(count(&pair), 0);
    assert_eq!(
        configure(&mut pair, 1, &id, edit).unwrap()["state"],
        "applied"
    );
    assert_eq!(count(&pair), 0);
    assert!(configuration::pending::load(&pair.stores[1].db, &origin, &id).is_err());
}

#[tokio::test]
async fn legacy_queue_and_full_edit_recover_without_changing_identity_or_fingerprint() {
    for full in [true, false] {
        let mut pair = Pair::new().await;
        let id = Uuid::new_v4().to_string();
        let edit = ConfigurationEdit::RenameNode {
            name: "legacy-payload".into(),
        };
        let queued = configure(&mut pair, 1, &id, edit.clone()).unwrap();
        pair.stores[1]
            .db
            .execute_batch("DROP TABLE configuration_pending; PRAGMA user_version=19;")
            .unwrap();
        if full {
            pair.stores[1]
                .db
                .execute(
                    "UPDATE configuration_edits SET edit=?1,compact=0 WHERE id=?2",
                    params![serde_json::to_vec(&edit).unwrap(), id],
                )
                .unwrap();
            pair.stores[1]
                .db
                .execute("DELETE FROM network_events", [])
                .unwrap();
        }
        pair.reopen(1);
        assert_eq!(
            serde_json::to_vec(&retained(&pair, &id)).unwrap(),
            serde_json::to_vec(&edit).unwrap()
        );
        assert_eq!(configure(&mut pair, 1, &id, edit).unwrap(), queued);
        assert_eq!(
            pair.stores[1]
                .db
                .pragma_query_value(None, "user_version", |r| r.get::<_, u32>(0))
                .unwrap(),
            26
        );
    }
}

#[tokio::test]
async fn missing_legacy_body_is_reported_and_exact_retry_repairs_it_without_reapplying() {
    let mut pair = Pair::new().await;
    let id = Uuid::new_v4().to_string();
    let edit = ConfigurationEdit::RenameNode {
        name: "repair-original".into(),
    };
    configure(&mut pair, 1, &id, edit.clone()).unwrap();
    pair.stores[1]
        .db
        .execute_batch("DELETE FROM configuration_pending; DELETE FROM network_events;")
        .unwrap();
    pair.reopen(1);
    let status = pair
        .owner(
            1,
            OwnerOp::ConfigurationRequests {
                request_id: Some(id.clone()),
            },
        )
        .unwrap();
    assert_eq!(status["payload_retained"], false);
    assert!(configure(&mut pair, 1, &id, ConfigurationEdit::Renew).is_err());
    assert_eq!(count(&pair), 0);
    let before = pair.stores[1]
        .identity
        .state(&pair.stores[1].db)
        .unwrap()
        .checkpoint()
        .clone();
    assert_eq!(
        configure(&mut pair, 1, &id, edit).unwrap()["payload_retained"],
        true
    );
    assert_eq!(
        pair.stores[1]
            .identity
            .state(&pair.stores[1].db)
            .unwrap()
            .checkpoint(),
        &before
    );
    pair.stores[1]
        .db
        .execute(
            "UPDATE configuration_pending SET body=?1",
            [br#"{"op":"renew"}"#.as_slice()],
        )
        .unwrap();
    let origin = pair.stores[1].identity.node.id();
    assert!(configuration::pending::load(&pair.stores[1].db, origin, &id).is_err());
    assert!(
        pair.owner(
            1,
            OwnerOp::ConfigurationRequests {
                request_id: Some(id)
            }
        )
        .is_err()
    );
    pair.stores[1]
        .db
        .execute_batch("DROP TABLE configuration_pending;")
        .unwrap();
    assert!(Store::open(pair.homes[1].path()).is_err());
}

#[tokio::test]
async fn payload_admission_failure_rolls_back_request_and_event_and_preserves_exact_retries() {
    let mut pair = Pair::new().await;
    let edit = ConfigurationEdit::RenameNode {
        name: "capacity".into(),
    };
    let first = Uuid::new_v4().to_string();
    let queued = configure(&mut pair, 1, &first, edit.clone()).unwrap();
    let db = Connection::open(pair.homes[1].path().join("state.sqlite3")).unwrap();
    db.execute_batch("PRAGMA foreign_keys=OFF;").unwrap();
    // Reserve all remaining slots without 4095 expensive network requests.
    db.execute("WITH RECURSIVE n(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM n WHERE x<4095) INSERT INTO configuration_pending SELECT 'quota',CAST(x AS TEXT),x'7b7d' FROM n", []).unwrap();
    assert_eq!(
        configure(&mut pair, 1, &first, edit.clone()).unwrap(),
        queued
    );
    let id = Uuid::new_v4().to_string();
    assert!(
        configure(&mut pair, 1, &id, edit.clone())
            .unwrap_err()
            .to_string()
            .contains("payload quota")
    );
    assert_eq!(
        pair.stores[1]
            .db
            .query_row(
                "SELECT COUNT(*) FROM configuration_edits WHERE id=?1",
                [&id],
                |r| r.get::<_, u64>(0)
            )
            .unwrap(),
        0
    );
    db.execute("DELETE FROM configuration_pending WHERE origin='quota'", [])
        .unwrap();
    db.execute(
        "INSERT INTO configuration_pending VALUES('quota','bytes',zeroblob(2097152))",
        [],
    )
    .unwrap();
    db.execute("WITH RECURSIVE n(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM n WHERE x<31) INSERT INTO configuration_pending SELECT 'quota',CAST(x AS TEXT),zeroblob(2097152) FROM n", []).unwrap();
    assert!(
        configure(&mut pair, 1, &id, edit.clone())
            .unwrap_err()
            .to_string()
            .contains("payload quota")
    );
    db.execute("DELETE FROM configuration_pending WHERE origin='quota'", [])
        .unwrap();
    pair.stores[1].db.execute_batch("CREATE TRIGGER fail_pending BEFORE INSERT ON configuration_pending BEGIN SELECT RAISE(ABORT,'pending failure'); END;").unwrap();
    assert!(configure(&mut pair, 1, &id, edit.clone()).is_err());
    assert_eq!(count(&pair), 1);
    pair.stores[1]
        .db
        .execute_batch("DROP TRIGGER fail_pending;")
        .unwrap();
    configure(&mut pair, 1, &id, edit).unwrap();
    pair.pump();
    assert_eq!(count(&pair), 0);
    assert_eq!(
        pair.stores[1]
            .db
            .query_row(
                "SELECT COUNT(*) FROM configuration_edits WHERE id=?1",
                [&id],
                |r| r.get::<_, u64>(0)
            )
            .unwrap(),
        1
    );
}

#[tokio::test]
async fn bounded_recovery_skips_missing_bodies_and_capacity_never_blocks_startup() {
    let mut pair = Pair::new().await;
    let mut ids = Vec::new();
    for i in 0..10 {
        let id = Uuid::new_v4().to_string();
        configure(
            &mut pair,
            1,
            &id,
            ConfigurationEdit::RenameNode {
                name: format!("pending-{i}"),
            },
        )
        .unwrap();
        ids.push(id);
    }
    pair.stores[1]
        .db
        .execute("DELETE FROM configuration_pending", [])
        .unwrap();
    for id in &ids[..8] {
        pair.stores[1]
            .db
            .execute(
                "DELETE FROM network_events WHERE json_extract(body,'$.event.request_id')=?1",
                [id],
            )
            .unwrap();
    }
    pair.reopen(1);
    assert_eq!(count(&pair), 0);
    pair.stores[1].maintain().unwrap();
    assert_eq!(count(&pair), 2);
    for id in &ids[8..] {
        retained(&pair, id);
    }
    let db = Connection::open(pair.homes[1].path().join("state.sqlite3")).unwrap();
    db.execute_batch("PRAGMA foreign_keys=OFF; DELETE FROM configuration_pending;")
        .unwrap();
    db.execute("WITH RECURSIVE n(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM n WHERE x<4096) INSERT INTO configuration_pending SELECT 'quota',CAST(x AS TEXT),x'7b7d' FROM n", []).unwrap();
    // Startup and receipt handling must remain possible when the payload cache
    // is full; otherwise old decisions could never release capacity.
    pair.reopen(1);
    pair.stores[1].maintain().unwrap();
    assert_eq!(count(&pair), 4096);
    db.execute("DELETE FROM configuration_pending WHERE origin='quota'", [])
        .unwrap();
    for _ in 0..3 {
        pair.stores[1].maintain().unwrap();
    }
    assert_eq!(count(&pair), 2);
    for id in &ids[8..] {
        retained(&pair, id);
    }
}