@feltdb/core 0.6.12 → 0.6.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/agent-registry.js +1 -3
  2. package/dist/agent-runtime.js +8 -7
  3. package/dist/analytics-backend.js +3 -1
  4. package/dist/application-contract.js +1 -0
  5. package/dist/application-manifest.js +1 -0
  6. package/dist/artifact.js +2 -0
  7. package/dist/authorization.js +2 -0
  8. package/dist/bundle.js +2 -0
  9. package/dist/capability.js +1 -3
  10. package/dist/cell.js +9 -4
  11. package/dist/cli/application.js +1 -1
  12. package/dist/cli/browser-opening.js +35 -0
  13. package/dist/cli/commands.js +50 -17
  14. package/dist/cli/index.js +1 -1
  15. package/dist/collection.js +39 -31
  16. package/dist/create/cli.js +7 -5
  17. package/dist/create/create.js +9 -7
  18. package/dist/create/development-handoff.js +4 -0
  19. package/dist/create/docker-compose-generator.js +4 -4
  20. package/dist/create/package-versions.js +1 -1
  21. package/dist/create/server-source/crates/feltdb/src/bin/feltdb_node.rs +497 -27
  22. package/dist/create/server-source/crates/feltdb/src/causal_backlog_bound.rs +452 -0
  23. package/dist/create/server-source/crates/feltdb/src/causal_dependency_barrier.rs +208 -0
  24. package/dist/create/server-source/crates/feltdb/src/convergence.rs +16 -0
  25. package/dist/create/server-source/crates/feltdb/src/dedup_bound_investigation.rs +402 -0
  26. package/dist/create/server-source/crates/feltdb/src/distributed_transactions.rs +765 -24
  27. package/dist/create/server-source/crates/feltdb/src/durable_operation_identity.rs +418 -0
  28. package/dist/create/server-source/crates/feltdb/src/lib.rs +4 -0
  29. package/dist/create/server-source/crates/feltdb/src/replica_membership.rs +661 -0
  30. package/dist/db.js +19 -13
  31. package/dist/development-runtime-bridge.js +1 -1
  32. package/dist/distributed-indexing.js +7 -5
  33. package/dist/file-db.js +8 -3
  34. package/dist/flowspec.js +2 -1
  35. package/dist/http-client.js +2 -0
  36. package/dist/http-db.js +16 -1
  37. package/dist/identity.js +1 -0
  38. package/dist/index-analytics.js +6 -7
  39. package/dist/index-backend.js +3 -3
  40. package/dist/index-dashboard.js +10 -13
  41. package/dist/index-manager.js +12 -11
  42. package/dist/index-monitoring.js +9 -4
  43. package/dist/index-store.js +2 -0
  44. package/dist/indexeddb-db.js +27 -23
  45. package/dist/memory-db.js +7 -4
  46. package/dist/observe.js +2 -0
  47. package/dist/provider.js +2 -0
  48. package/dist/query-planner.js +2 -4
  49. package/dist/reactive-graph.js +6 -8
  50. package/dist/release.js +2 -0
  51. package/dist/sharding.js +11 -6
  52. package/dist/state-contract.js +3 -3
  53. package/dist/studio-app/assets/{feltdb_wasm-CJv3wHzi.js → feltdb_wasm-C9xpYtna.js} +1 -1
  54. package/dist/studio-app/assets/feltdb_wasm_bg-BsXHw7eX.wasm +0 -0
  55. package/dist/studio-app/assets/{index-DospFFYE.js → index-D4RZ44qs.js} +4 -4
  56. package/dist/studio-app/index.html +1 -1
  57. package/dist/sync-contract.js +9 -2
  58. package/dist/telemetry.d.ts.map +1 -1
  59. package/dist/telemetry.js +32 -12
  60. package/dist/transaction.js +4 -2
  61. package/dist/wasm/feltdb_wasm_bg.wasm +0 -0
  62. package/dist/worker.js +2 -0
  63. package/dist/workload.js +2 -0
  64. package/dist/workspace/development-node.js +11 -10
  65. package/dist/workspace/investigation-lifecycle-manager.js +2 -0
  66. package/dist/workspace/investigation-supervisor.js +5 -3
  67. package/dist/workspace/workspace-connection.js +14 -5
  68. package/package.json +1 -1
  69. package/dist/studio-app/assets/feltdb_wasm_bg-C8TG8r2n.wasm +0 -0
@@ -0,0 +1,661 @@
1
+ //! Durable replica membership.
2
+ //!
3
+ //! The question this exists to answer, and which nothing in FeltDB could
4
+ //! answer before:
5
+ //!
6
+ //! > which replicas must be caught up before this node may reclaim
7
+ //! > replication history?
8
+ //!
9
+ //! `adrs/replication-retention-and-recovery-lag.md` found that "every required
10
+ //! replica" had no referent. `membership` in this codebase meant *authorization*
11
+ //! membership -- users and organisations -- and replication peers came from
12
+ //! `--send` / `--recv` flags at startup. Three things were conflated:
13
+ //!
14
+ //! ```text
15
+ //! configured peer != cluster member
16
+ //! connected peer != required replica
17
+ //! removed replica != temporarily offline replica
18
+ //! ```
19
+ //!
20
+ //! This module separates them. It stores membership durably, keyed to explicit
21
+ //! state transitions, and it is deliberately the *only* thing that can change
22
+ //! which replicas are required.
23
+ //!
24
+ //! ## The rule that matters
25
+ //!
26
+ //! **Only an explicit transition to `Removed` takes a replica out of the
27
+ //! reclamation set.** Not going offline, not being unreachable, not a stale
28
+ //! `last_seen_at`, not being absent from this node's connection flags. There is
29
+ //! no code path here that derives `required_for_reclamation` from liveness, and
30
+ //! that absence is the feature: otherwise a replica that is merely switched off
31
+ //! becomes irrelevant to reclamation, and the history it still needs is deleted
32
+ //! while it is not there to object.
33
+ //!
34
+ //! `Suspected` exists to record that a replica looks unreachable. It changes
35
+ //! nothing about whether it is required, and there are tests asserting exactly
36
+ //! that.
37
+ //!
38
+ //! ## Deliberately not here
39
+ //!
40
+ //! No compaction frontier, no acknowledgement tracking, no checkpoint, no
41
+ //! change to the operation log. This establishes the authority the next change
42
+ //! consumes; it reclaims nothing and deletes nothing.
43
+
44
+ use serde::{Deserialize, Serialize};
45
+ use std::collections::BTreeMap;
46
+ use std::path::{Path, PathBuf};
47
+
48
+ fn now_ms() -> u64 {
49
+ std::time::SystemTime::now()
50
+ .duration_since(std::time::UNIX_EPOCH)
51
+ .map(|elapsed| elapsed.as_millis() as u64)
52
+ .unwrap_or(0)
53
+ }
54
+
55
+ /// Where a replica stands in the cluster.
56
+ ///
57
+ /// Explicit rather than inferred. A status is changed by an operation someone
58
+ /// performed, never by this module observing a connection.
59
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
60
+ #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
61
+ pub enum ReplicaStatus {
62
+ /// Admitted to the cluster but not yet approved: it is being seeded and is
63
+ /// not yet a replica anyone should be waiting for.
64
+ Joining,
65
+ /// A full member. Required for reclamation.
66
+ Active,
67
+ /// Looks unreachable. **Still required for reclamation** -- this status is
68
+ /// an observation, not a decision.
69
+ Suspected,
70
+ /// Explicitly removed. The only status that leaves the reclamation set, and
71
+ /// terminal: a removed replica rejoins by joining again, not by being seen.
72
+ Removed,
73
+ }
74
+
75
+ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
76
+ pub struct Replica {
77
+ pub replica_id: String,
78
+ pub node_id: String,
79
+ pub status: ReplicaStatus,
80
+ pub joined_at_ms: u64,
81
+ pub last_seen_at_ms: Option<u64>,
82
+ /// Whether history must be retained on this replica's behalf.
83
+ ///
84
+ /// Stored rather than derived from `status` at read time, so that the value
85
+ /// which authorises deletion is one somebody wrote down and an audit can
86
+ /// read back, rather than the output of a rule that could later be changed
87
+ /// underneath the data.
88
+ pub required_for_reclamation: bool,
89
+ }
90
+
91
+ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
92
+ pub struct ReplicationCluster {
93
+ pub cluster_id: String,
94
+ pub created_at_ms: u64,
95
+ /// Keyed by `replica_id`, ordered so that reads are deterministic.
96
+ pub replicas: BTreeMap<String, Replica>,
97
+ }
98
+
99
+ #[derive(Debug)]
100
+ pub enum MembershipError {
101
+ NoCluster,
102
+ ClusterExists(String),
103
+ UnknownReplica(String),
104
+ ReplicaExists(String),
105
+ NotJoining(String),
106
+ Io(String),
107
+ }
108
+
109
+ impl std::fmt::Display for MembershipError {
110
+ fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111
+ match self {
112
+ Self::NoCluster => write!(out, "no cluster has been created"),
113
+ Self::ClusterExists(id) => write!(out, "cluster {id} already exists"),
114
+ Self::UnknownReplica(id) => write!(out, "unknown replica {id}"),
115
+ Self::ReplicaExists(id) => write!(out, "replica {id} already exists"),
116
+ Self::NotJoining(id) => write!(out, "replica {id} is not JOINING"),
117
+ Self::Io(message) => write!(out, "membership store: {message}"),
118
+ }
119
+ }
120
+ }
121
+
122
+ /// Durable membership for one node.
123
+ ///
124
+ /// Persisted beside the operation log and never reconstructed from connection
125
+ /// flags: a restart that rebuilt membership from `--send`/`--recv` would make
126
+ /// the reclamation set a function of how the process happened to be launched.
127
+ pub struct MembershipStore {
128
+ path: PathBuf,
129
+ cluster: Option<ReplicationCluster>,
130
+ }
131
+
132
+ impl MembershipStore {
133
+ /// Open a store, loading any cluster already on disk.
134
+ pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, MembershipError> {
135
+ let path = path.as_ref().to_path_buf();
136
+ let cluster = if path.exists() {
137
+ let bytes = std::fs::read(&path).map_err(|e| MembershipError::Io(e.to_string()))?;
138
+ Some(serde_json::from_slice(&bytes).map_err(|e| MembershipError::Io(e.to_string()))?)
139
+ } else {
140
+ None
141
+ };
142
+ Ok(Self { path, cluster })
143
+ }
144
+
145
+ /// Write the cluster durably: temp file, fsync, rename, fsync the
146
+ /// directory. Membership is what will later authorise deleting history, so
147
+ /// it is written with the same care as the log it will authorise deleting.
148
+ fn persist(&self) -> Result<(), MembershipError> {
149
+ let Some(cluster) = &self.cluster else { return Ok(()) };
150
+ if let Some(parent) = self.path.parent() {
151
+ std::fs::create_dir_all(parent).map_err(|e| MembershipError::Io(e.to_string()))?;
152
+ }
153
+ let temp = self.path.with_extension("tmp");
154
+ let bytes = serde_json::to_vec_pretty(cluster)
155
+ .map_err(|e| MembershipError::Io(e.to_string()))?;
156
+ {
157
+ use std::io::Write;
158
+ let mut file = std::fs::File::create(&temp)
159
+ .map_err(|e| MembershipError::Io(e.to_string()))?;
160
+ file.write_all(&bytes).map_err(|e| MembershipError::Io(e.to_string()))?;
161
+ file.sync_all().map_err(|e| MembershipError::Io(e.to_string()))?;
162
+ }
163
+ std::fs::rename(&temp, &self.path).map_err(|e| MembershipError::Io(e.to_string()))?;
164
+ if let Some(parent) = self.path.parent() {
165
+ if let Ok(dir) = std::fs::File::open(parent) {
166
+ // Best effort: the rename is durable on the filesystems this
167
+ // runs on once the directory entry is synced.
168
+ let _ = dir.sync_all();
169
+ }
170
+ }
171
+ Ok(())
172
+ }
173
+
174
+ pub fn cluster(&self) -> Option<&ReplicationCluster> {
175
+ self.cluster.as_ref()
176
+ }
177
+
178
+ pub fn create_cluster(&mut self, cluster_id: &str) -> Result<(), MembershipError> {
179
+ if let Some(existing) = &self.cluster {
180
+ return Err(MembershipError::ClusterExists(existing.cluster_id.clone()));
181
+ }
182
+ self.cluster = Some(ReplicationCluster {
183
+ cluster_id: cluster_id.to_string(),
184
+ created_at_ms: now_ms(),
185
+ replicas: BTreeMap::new(),
186
+ });
187
+ self.persist()
188
+ }
189
+
190
+ fn cluster_mut(&mut self) -> Result<&mut ReplicationCluster, MembershipError> {
191
+ self.cluster.as_mut().ok_or(MembershipError::NoCluster)
192
+ }
193
+
194
+ /// Admit a replica as `Joining`. It is not yet required for reclamation:
195
+ /// it is being seeded and holds nothing anyone is waiting on.
196
+ pub fn join_replica(&mut self, replica_id: &str, node_id: &str) -> Result<(), MembershipError> {
197
+ let cluster = self.cluster_mut()?;
198
+ if cluster.replicas.contains_key(replica_id) {
199
+ return Err(MembershipError::ReplicaExists(replica_id.to_string()));
200
+ }
201
+ cluster.replicas.insert(
202
+ replica_id.to_string(),
203
+ Replica {
204
+ replica_id: replica_id.to_string(),
205
+ node_id: node_id.to_string(),
206
+ status: ReplicaStatus::Joining,
207
+ joined_at_ms: now_ms(),
208
+ last_seen_at_ms: None,
209
+ required_for_reclamation: false,
210
+ },
211
+ );
212
+ self.persist()
213
+ }
214
+
215
+ /// Promote a `Joining` replica to `Active`, which is what makes it
216
+ /// required. Approval is the moment history starts being retained on its
217
+ /// behalf, so it is explicit.
218
+ pub fn approve_replica(&mut self, replica_id: &str) -> Result<(), MembershipError> {
219
+ let cluster = self.cluster_mut()?;
220
+ let replica = cluster
221
+ .replicas
222
+ .get_mut(replica_id)
223
+ .ok_or_else(|| MembershipError::UnknownReplica(replica_id.to_string()))?;
224
+ if replica.status != ReplicaStatus::Joining {
225
+ return Err(MembershipError::NotJoining(replica_id.to_string()));
226
+ }
227
+ replica.status = ReplicaStatus::Active;
228
+ replica.required_for_reclamation = true;
229
+ self.persist()
230
+ }
231
+
232
+ /// Record that a replica looks unreachable.
233
+ ///
234
+ /// This does **not** change `required_for_reclamation`, and that is the
235
+ /// whole point of the status existing separately from removal.
236
+ pub fn suspect_replica(&mut self, replica_id: &str) -> Result<(), MembershipError> {
237
+ let cluster = self.cluster_mut()?;
238
+ let replica = cluster
239
+ .replicas
240
+ .get_mut(replica_id)
241
+ .ok_or_else(|| MembershipError::UnknownReplica(replica_id.to_string()))?;
242
+ if replica.status == ReplicaStatus::Removed {
243
+ // A removed replica is not suspected; it is gone.
244
+ return Ok(());
245
+ }
246
+ replica.status = ReplicaStatus::Suspected;
247
+ self.persist()
248
+ }
249
+
250
+ /// Record contact with a replica.
251
+ ///
252
+ /// Reinstates a `Suspected` replica, because suspicion is an observation
253
+ /// and this is a contrary observation. It never resurrects a `Removed`
254
+ /// one: removal is a decision, and only an explicit join reverses it.
255
+ pub fn mark_seen(&mut self, replica_id: &str) -> Result<(), MembershipError> {
256
+ let cluster = self.cluster_mut()?;
257
+ let replica = cluster
258
+ .replicas
259
+ .get_mut(replica_id)
260
+ .ok_or_else(|| MembershipError::UnknownReplica(replica_id.to_string()))?;
261
+ replica.last_seen_at_ms = Some(now_ms());
262
+ if replica.status == ReplicaStatus::Suspected {
263
+ replica.status = ReplicaStatus::Active;
264
+ }
265
+ self.persist()
266
+ }
267
+
268
+ /// Remove a replica from the cluster. The only operation that takes a
269
+ /// replica out of the reclamation set.
270
+ pub fn remove_replica(&mut self, replica_id: &str) -> Result<(), MembershipError> {
271
+ let cluster = self.cluster_mut()?;
272
+ let replica = cluster
273
+ .replicas
274
+ .get_mut(replica_id)
275
+ .ok_or_else(|| MembershipError::UnknownReplica(replica_id.to_string()))?;
276
+ replica.status = ReplicaStatus::Removed;
277
+ replica.required_for_reclamation = false;
278
+ self.persist()
279
+ }
280
+
281
+ /// Every replica the cluster currently has, removed ones excluded.
282
+ pub fn get_members(&self) -> Vec<Replica> {
283
+ self.cluster
284
+ .as_ref()
285
+ .map(|cluster| {
286
+ cluster
287
+ .replicas
288
+ .values()
289
+ .filter(|replica| replica.status != ReplicaStatus::Removed)
290
+ .cloned()
291
+ .collect()
292
+ })
293
+ .unwrap_or_default()
294
+ }
295
+
296
+ /// Every replica ever recorded, including removed ones, for audit.
297
+ pub fn all_replicas(&self) -> Vec<Replica> {
298
+ self.cluster
299
+ .as_ref()
300
+ .map(|cluster| cluster.replicas.values().cloned().collect())
301
+ .unwrap_or_default()
302
+ }
303
+
304
+ /// The replicas whose acknowledgement is required before history may be
305
+ /// reclaimed on their behalf.
306
+ ///
307
+ /// Read straight from the stored flag. Nothing about connectivity, recency,
308
+ /// or this process's configuration enters into it.
309
+ pub fn get_required_replicas(&self) -> Vec<Replica> {
310
+ self.cluster
311
+ .as_ref()
312
+ .map(|cluster| {
313
+ cluster
314
+ .replicas
315
+ .values()
316
+ .filter(|replica| {
317
+ replica.required_for_reclamation && replica.status != ReplicaStatus::Removed
318
+ })
319
+ .cloned()
320
+ .collect()
321
+ })
322
+ .unwrap_or_default()
323
+ }
324
+ }
325
+
326
+ #[cfg(test)]
327
+ mod tests {
328
+ use super::*;
329
+
330
+ fn store(dir: &tempfile::TempDir) -> MembershipStore {
331
+ MembershipStore::open(dir.path().join("membership.json")).expect("open")
332
+ }
333
+
334
+ fn ids(replicas: &[Replica]) -> Vec<String> {
335
+ let mut out: Vec<String> = replicas.iter().map(|r| r.replica_id.clone()).collect();
336
+ out.sort();
337
+ out
338
+ }
339
+
340
+ // -- the headline acceptance test -------------------------------------
341
+
342
+ #[test]
343
+ fn membership_survives_restart_and_only_removal_changes_the_reclamation_set() {
344
+ let dir = tempfile::tempdir().unwrap();
345
+
346
+ {
347
+ let mut cluster = store(&dir);
348
+ cluster.create_cluster("c1").expect("create");
349
+ for (replica, node) in [("ra", "A"), ("rb", "B"), ("rc", "C")] {
350
+ cluster.join_replica(replica, node).expect("join");
351
+ cluster.approve_replica(replica).expect("approve");
352
+ }
353
+ assert_eq!(ids(&cluster.get_required_replicas()), ["ra", "rb", "rc"]);
354
+ }
355
+
356
+ // Restart: a new store over the same path, with no configuration
357
+ // passed to it at all.
358
+ let mut restarted = store(&dir);
359
+ assert_eq!(
360
+ ids(&restarted.get_members()),
361
+ ["ra", "rb", "rc"],
362
+ "membership is durable, not reconstructed from how the process was launched"
363
+ );
364
+ assert_eq!(restarted.cluster().expect("cluster").cluster_id, "c1");
365
+
366
+ // C goes offline. It is suspected, and it stays required.
367
+ restarted.suspect_replica("rc").expect("suspect");
368
+ let suspected = restarted
369
+ .get_members()
370
+ .into_iter()
371
+ .find(|r| r.replica_id == "rc")
372
+ .expect("rc");
373
+ assert_eq!(suspected.status, ReplicaStatus::Suspected);
374
+ assert!(suspected.required_for_reclamation);
375
+ assert_eq!(
376
+ ids(&restarted.get_required_replicas()),
377
+ ["ra", "rb", "rc"],
378
+ "an offline replica is still owed its history: being unreachable is not consent"
379
+ );
380
+
381
+ // Only an explicit removal changes it.
382
+ restarted.remove_replica("rc").expect("remove");
383
+ assert_eq!(
384
+ ids(&restarted.get_required_replicas()),
385
+ ["ra", "rb"],
386
+ "removal is the only thing that takes a replica out of the reclamation set"
387
+ );
388
+ assert_eq!(
389
+ ids(&restarted.get_members()),
390
+ ["ra", "rb"],
391
+ "and out of the membership"
392
+ );
393
+
394
+ // And that decision is durable too.
395
+ let after_removal = store(&dir);
396
+ assert_eq!(ids(&after_removal.get_required_replicas()), ["ra", "rb"]);
397
+ assert_eq!(
398
+ after_removal.all_replicas().len(),
399
+ 3,
400
+ "the removed replica is retained for audit, not erased"
401
+ );
402
+ }
403
+
404
+ // -- the critical rule, from several directions ------------------------
405
+
406
+ #[test]
407
+ fn membership_a_stale_last_seen_never_changes_what_is_required() {
408
+ // There is no code path that derives `required_for_reclamation` from
409
+ // liveness, and this asserts the absence: a replica untouched since
410
+ // the epoch is still required.
411
+ let dir = tempfile::tempdir().unwrap();
412
+ let mut cluster = store(&dir);
413
+ cluster.create_cluster("c1").unwrap();
414
+ cluster.join_replica("rc", "C").unwrap();
415
+ cluster.approve_replica("rc").unwrap();
416
+
417
+ cluster.suspect_replica("rc").unwrap();
418
+ let ancient = cluster.all_replicas().into_iter().next().unwrap();
419
+ assert_eq!(ancient.last_seen_at_ms, None, "never seen at all");
420
+ assert!(
421
+ ancient.required_for_reclamation,
422
+ "a replica that has never been seen is still required: silence is not removal"
423
+ );
424
+ assert_eq!(ids(&cluster.get_required_replicas()), ["rc"]);
425
+ }
426
+
427
+ #[test]
428
+ fn membership_suspicion_is_reversible_and_removal_is_not() {
429
+ let dir = tempfile::tempdir().unwrap();
430
+ let mut cluster = store(&dir);
431
+ cluster.create_cluster("c1").unwrap();
432
+ cluster.join_replica("rc", "C").unwrap();
433
+ cluster.approve_replica("rc").unwrap();
434
+
435
+ cluster.suspect_replica("rc").unwrap();
436
+ cluster.mark_seen("rc").unwrap();
437
+ let seen = cluster.get_members().into_iter().next().unwrap();
438
+ assert_eq!(seen.status, ReplicaStatus::Active, "contact reinstates a suspected replica");
439
+ assert!(seen.last_seen_at_ms.is_some());
440
+
441
+ cluster.remove_replica("rc").unwrap();
442
+ cluster.mark_seen("rc").unwrap();
443
+ let after = cluster.all_replicas().into_iter().next().unwrap();
444
+ assert_eq!(
445
+ after.status,
446
+ ReplicaStatus::Removed,
447
+ "contact does NOT resurrect a removed replica: removal is a decision, not an observation"
448
+ );
449
+ assert!(!after.required_for_reclamation);
450
+ assert!(cluster.get_required_replicas().is_empty());
451
+ }
452
+
453
+ #[test]
454
+ fn membership_a_joining_replica_is_a_member_but_not_yet_required() {
455
+ // A replica being seeded holds nothing anyone is waiting on, so it does
456
+ // not pin history. Approval is the moment retention starts on its
457
+ // behalf, which is why approval is explicit.
458
+ let dir = tempfile::tempdir().unwrap();
459
+ let mut cluster = store(&dir);
460
+ cluster.create_cluster("c1").unwrap();
461
+ cluster.join_replica("rd", "D").unwrap();
462
+
463
+ assert_eq!(ids(&cluster.get_members()), ["rd"]);
464
+ assert!(cluster.get_required_replicas().is_empty());
465
+
466
+ cluster.approve_replica("rd").unwrap();
467
+ assert_eq!(ids(&cluster.get_required_replicas()), ["rd"]);
468
+ }
469
+
470
+ #[test]
471
+ fn membership_a_removed_replica_rejoins_by_joining_not_by_appearing() {
472
+ let dir = tempfile::tempdir().unwrap();
473
+ let mut cluster = store(&dir);
474
+ cluster.create_cluster("c1").unwrap();
475
+ cluster.join_replica("rc", "C").unwrap();
476
+ cluster.approve_replica("rc").unwrap();
477
+ cluster.remove_replica("rc").unwrap();
478
+
479
+ // Its identity is still recorded, so a re-join is a deliberate act
480
+ // rather than an accident of reconnecting.
481
+ assert!(matches!(
482
+ cluster.join_replica("rc", "C"),
483
+ Err(MembershipError::ReplicaExists(_))
484
+ ));
485
+ assert!(cluster.get_required_replicas().is_empty());
486
+ }
487
+
488
+ // -- configured peer is not a cluster member ---------------------------
489
+
490
+ #[test]
491
+ fn membership_is_empty_until_someone_creates_it() {
492
+ // A node with peers configured has no members. This is the separation
493
+ // the ADR found missing: connection configuration says nothing about
494
+ // who is owed history.
495
+ let dir = tempfile::tempdir().unwrap();
496
+ let cluster = store(&dir);
497
+ assert!(cluster.cluster().is_none());
498
+ assert!(cluster.get_members().is_empty());
499
+ assert!(cluster.get_required_replicas().is_empty());
500
+ }
501
+
502
+ #[test]
503
+ fn membership_operations_need_a_cluster() {
504
+ let dir = tempfile::tempdir().unwrap();
505
+ let mut cluster = store(&dir);
506
+ assert!(matches!(cluster.join_replica("ra", "A"), Err(MembershipError::NoCluster)));
507
+ cluster.create_cluster("c1").unwrap();
508
+ assert!(matches!(
509
+ cluster.create_cluster("c2"),
510
+ Err(MembershipError::ClusterExists(_))
511
+ ));
512
+ }
513
+
514
+ #[test]
515
+ fn membership_approval_requires_joining_first() {
516
+ let dir = tempfile::tempdir().unwrap();
517
+ let mut cluster = store(&dir);
518
+ cluster.create_cluster("c1").unwrap();
519
+ assert!(matches!(
520
+ cluster.approve_replica("ghost"),
521
+ Err(MembershipError::UnknownReplica(_))
522
+ ));
523
+ cluster.join_replica("ra", "A").unwrap();
524
+ cluster.approve_replica("ra").unwrap();
525
+ assert!(
526
+ matches!(cluster.approve_replica("ra"), Err(MembershipError::NotJoining(_))),
527
+ "approving twice is not a silent no-op"
528
+ );
529
+ }
530
+
531
+ // -- replication membership is not authorization membership ------------
532
+
533
+ #[test]
534
+ fn membership_is_not_the_authorization_membership_of_the_same_name() {
535
+ // The ADR found that `membership` in this codebase meant users and
536
+ // organisations, in policy_evaluation.rs, and that replication had no
537
+ // membership at all. These are different concepts with the same word,
538
+ // and the failure mode is that one silently starts standing in for the
539
+ // other.
540
+ //
541
+ // The behavioural separation: this store's contents are exactly what
542
+ // was explicitly joined here. Authorization records live in the
543
+ // application's own collections and cannot reach this file -- there is
544
+ // no read path from one to the other, and the reclamation set below is
545
+ // unchanged by any amount of authorization data.
546
+ let dir = tempfile::tempdir().unwrap();
547
+ let mut cluster = store(&dir);
548
+ cluster.create_cluster("c1").unwrap();
549
+ cluster.join_replica("ra", "A").unwrap();
550
+ cluster.approve_replica("ra").unwrap();
551
+
552
+ // An application's authorization membership: a user in an organisation.
553
+ // Written where application state lives, which is a different place
554
+ // entirely.
555
+ let mut application_state = crate::state_hash::CanonicalState::new();
556
+ application_state.set_record(
557
+ "memberships".to_string(),
558
+ "user-1:org-1".to_string(),
559
+ serde_json::json!({ "user_id": "user-1", "organization_id": "org-1", "role": "admin" }),
560
+ );
561
+ assert_eq!(application_state.records.len(), 1);
562
+
563
+ assert_eq!(
564
+ ids(&cluster.get_required_replicas()),
565
+ ["ra"],
566
+ "the reclamation set is what was joined as a replica, and nothing else"
567
+ );
568
+ let reopened = store(&dir);
569
+ assert_eq!(ids(&reopened.get_required_replicas()), ["ra"]);
570
+ assert!(
571
+ reopened
572
+ .all_replicas()
573
+ .iter()
574
+ .all(|replica| replica.node_id == "A"),
575
+ "no authorization principal became a replica"
576
+ );
577
+ }
578
+
579
+ // -- durability and concurrency ----------------------------------------
580
+
581
+ #[test]
582
+ fn membership_every_transition_is_durable_immediately() {
583
+ // Not just at shutdown: each operation persists, because the process
584
+ // that is about to be killed is the one whose membership matters.
585
+ let dir = tempfile::tempdir().unwrap();
586
+ let mut cluster = store(&dir);
587
+ cluster.create_cluster("c1").unwrap();
588
+ assert_eq!(store(&dir).cluster().expect("cluster").cluster_id, "c1");
589
+
590
+ cluster.join_replica("ra", "A").unwrap();
591
+ assert_eq!(ids(&store(&dir).get_members()), ["ra"]);
592
+
593
+ cluster.approve_replica("ra").unwrap();
594
+ assert_eq!(ids(&store(&dir).get_required_replicas()), ["ra"]);
595
+
596
+ cluster.suspect_replica("ra").unwrap();
597
+ assert_eq!(
598
+ ids(&store(&dir).get_required_replicas()),
599
+ ["ra"],
600
+ "suspicion is durable and still does not change what is required"
601
+ );
602
+
603
+ cluster.remove_replica("ra").unwrap();
604
+ assert!(store(&dir).get_required_replicas().is_empty());
605
+ }
606
+
607
+ #[test]
608
+ fn membership_concurrent_transitions_do_not_lose_updates() {
609
+ use std::sync::{Arc, Mutex};
610
+ let dir = tempfile::tempdir().unwrap();
611
+ let path = dir.path().join("membership.json");
612
+ let shared = Arc::new(Mutex::new(MembershipStore::open(&path).unwrap()));
613
+ shared.lock().unwrap().create_cluster("c1").unwrap();
614
+
615
+ let mut threads = Vec::new();
616
+ for index in 0..8 {
617
+ let shared = Arc::clone(&shared);
618
+ threads.push(std::thread::spawn(move || {
619
+ let replica = format!("r{index}");
620
+ let mut guard = shared.lock().unwrap();
621
+ guard.join_replica(&replica, &format!("N{index}")).unwrap();
622
+ guard.approve_replica(&replica).unwrap();
623
+ }));
624
+ }
625
+ for thread in threads {
626
+ thread.join().unwrap();
627
+ }
628
+
629
+ assert_eq!(shared.lock().unwrap().get_required_replicas().len(), 8);
630
+
631
+ // And the file on disk agrees: no interleaved write left it torn or
632
+ // holding a partial set.
633
+ let reloaded = MembershipStore::open(&path).unwrap();
634
+ assert_eq!(
635
+ reloaded.get_required_replicas().len(),
636
+ 8,
637
+ "the durable record holds every transition, not the last writer's view"
638
+ );
639
+ }
640
+
641
+ #[test]
642
+ fn membership_a_torn_write_cannot_be_observed() {
643
+ // The write is temp-file plus rename, so a reader either sees the
644
+ // previous cluster or the next one. This asserts the temp file is not
645
+ // left behind as a readable half-state at the real path.
646
+ let dir = tempfile::tempdir().unwrap();
647
+ let path = dir.path().join("membership.json");
648
+ let mut cluster = MembershipStore::open(&path).unwrap();
649
+ cluster.create_cluster("c1").unwrap();
650
+ for index in 0..20 {
651
+ cluster.join_replica(&format!("r{index}"), &format!("N{index}")).unwrap();
652
+ let observed = MembershipStore::open(&path).unwrap();
653
+ assert_eq!(
654
+ observed.get_members().len(),
655
+ index + 1,
656
+ "every observation is of a complete cluster"
657
+ );
658
+ }
659
+ assert!(!path.with_extension("tmp").exists(), "no temp file is left at rest");
660
+ }
661
+ }