@feltdb/core 0.12.0 → 0.12.2

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 (138) hide show
  1. package/dist/agent-state.d.ts +489 -0
  2. package/dist/agent-state.d.ts.map +1 -0
  3. package/dist/agent-state.js +993 -0
  4. package/dist/build-identity.json +28 -0
  5. package/dist/cli/commands.js +88 -43
  6. package/dist/collection.d.ts +41 -4
  7. package/dist/collection.d.ts.map +1 -1
  8. package/dist/collection.js +116 -47
  9. package/dist/composition.d.ts.map +1 -1
  10. package/dist/composition.js +11 -1
  11. package/dist/create/build-identity.json +28 -0
  12. package/dist/create/cli.js +3 -3
  13. package/dist/create/create.js +17 -19
  14. package/dist/create/package-versions.js +1 -1
  15. package/dist/create/server-source/Cargo.lock +18 -3
  16. package/dist/create/server-source/Cargo.toml +4 -2
  17. package/dist/create/server-source/crates/feltdb/Cargo.toml +20 -0
  18. package/dist/create/server-source/crates/feltdb/LICENSE +21 -0
  19. package/dist/create/server-source/crates/feltdb/README.md +75 -0
  20. package/dist/create/server-source/crates/feltdb/src/agent_state.rs +320 -0
  21. package/dist/create/server-source/crates/feltdb/src/agent_transition_contract.rs +1545 -0
  22. package/dist/create/server-source/crates/feltdb/src/authority.rs +145 -15
  23. package/dist/create/server-source/crates/feltdb/src/lib.rs +238 -23
  24. package/dist/create/server-source/crates/feltdb/src/query_performance.rs +4 -1
  25. package/dist/create/server-source/crates/feltdb/src/state_model.rs +850 -155
  26. package/dist/create/server-source/crates/feltdb/tests/agent_state_native.rs +1188 -0
  27. package/dist/create/server-source/crates/feltdb/tests/agent_transition_contract_conformance.rs +2884 -0
  28. package/dist/create/server-source/crates/feltdb/tests/authority_transaction_identity.rs +534 -0
  29. package/dist/create/server-source/crates/feltdb/tests/fixtures/agent_transition_corpus.json +23340 -0
  30. package/dist/create/server-source/crates/feltdb/tests/generalized_version_control_substrate_completion.rs +31 -13
  31. package/dist/create/server-source/crates/feltdb/tests/state_ref_authority.rs +918 -0
  32. package/dist/create/server-source/crates/feltdb/tests/workload_envelope_contract.rs +15 -2
  33. package/dist/create/server-source/crates/feltdb-client/Cargo.toml +29 -0
  34. package/dist/create/server-source/crates/feltdb-client/LICENSE +21 -0
  35. package/dist/create/server-source/crates/feltdb-client/README.md +70 -0
  36. package/dist/create/server-source/crates/feltdb-client/src/application.rs +527 -0
  37. package/dist/create/server-source/crates/feltdb-client/src/authority.rs +679 -0
  38. package/dist/create/server-source/crates/feltdb-client/src/control.rs +292 -0
  39. package/dist/create/server-source/crates/feltdb-client/src/error.rs +227 -0
  40. package/dist/create/server-source/crates/feltdb-client/src/events.rs +146 -0
  41. package/dist/create/server-source/crates/feltdb-client/src/lib.rs +466 -0
  42. package/dist/create/server-source/crates/feltdb-client/tests/fixtures/README.md +4 -0
  43. package/dist/create/server-source/crates/feltdb-client/tests/fixtures/private-ca.pem +20 -0
  44. package/dist/create/server-source/crates/feltdb-client/tests/fixtures/server-key.pem +28 -0
  45. package/dist/create/server-source/crates/feltdb-client/tests/fixtures/server.pem +20 -0
  46. package/dist/create/server-source/crates/feltdb-client/tests/private_ca.rs +95 -0
  47. package/dist/create/server-source/crates/feltdb-server/Cargo.toml +24 -1
  48. package/dist/create/server-source/crates/feltdb-server/LICENSE +21 -0
  49. package/dist/create/server-source/crates/feltdb-server/README.md +12 -1
  50. package/dist/create/server-source/crates/feltdb-server/benches/query_shape_observer.rs +136 -0
  51. package/dist/create/server-source/crates/feltdb-server/src/app_state.rs +3 -0
  52. package/dist/create/server-source/crates/feltdb-server/src/backup.rs +6 -2
  53. package/dist/create/server-source/crates/feltdb-server/src/lib.rs +21 -0
  54. package/dist/create/server-source/crates/feltdb-server/src/main.rs +75 -8
  55. package/dist/create/server-source/crates/feltdb-server/src/query_shape.rs +1137 -0
  56. package/dist/create/server-source/crates/feltdb-server/tests/fixtures/query-shape-trace.expected.json +300 -0
  57. package/dist/create/server-source/crates/feltdb-server/tests/fixtures/query-shape-trace.json +25 -0
  58. package/dist/create/server-source/crates/feltdb-server/tests/query_shape_trace.rs +128 -0
  59. package/dist/create/server-source/crates/feltdb-server/tests/rust_client.rs +683 -0
  60. package/dist/create/server-source/crates/feltdb-wasm/Cargo.toml +3 -1
  61. package/dist/create/template/default-project/README.md +12 -7
  62. package/dist/create/template/default-project/src/pages/Dashboard.tsx +1 -1
  63. package/dist/create/template/dot-feltdb-README.md +3 -3
  64. package/dist/db.d.ts.map +1 -1
  65. package/dist/db.js +43 -17
  66. package/dist/development-runtime-bridge.d.ts.map +1 -1
  67. package/dist/development-runtime-bridge.js +22 -1
  68. package/dist/embedded-transaction.d.ts +75 -8
  69. package/dist/embedded-transaction.d.ts.map +1 -1
  70. package/dist/embedded-transaction.js +124 -18
  71. package/dist/error-codes.d.ts +2 -0
  72. package/dist/error-codes.d.ts.map +1 -1
  73. package/dist/error-codes.js +2 -0
  74. package/dist/feltdb.d.ts +1 -11
  75. package/dist/feltdb.d.ts.map +1 -1
  76. package/dist/file-db.d.ts +6 -0
  77. package/dist/file-db.d.ts.map +1 -1
  78. package/dist/file-db.js +43 -11
  79. package/dist/index-core.d.ts +1 -0
  80. package/dist/index-core.d.ts.map +1 -1
  81. package/dist/index-core.js +1 -0
  82. package/dist/indexeddb-db.d.ts.map +1 -1
  83. package/dist/indexeddb-db.js +65 -41
  84. package/dist/memory-db.d.ts.map +1 -1
  85. package/dist/memory-db.js +29 -8
  86. package/dist/studio/{KeyManagementPanel-DZuSeWBK.js → KeyManagementPanel-D5FMvvU9.js} +1 -0
  87. package/dist/studio/app.d.ts.map +1 -1
  88. package/dist/studio/components/GlobalSearch.d.ts.map +1 -1
  89. package/dist/studio/components/KeyManagementPanel.d.ts.map +1 -1
  90. package/dist/studio/components/KeyManagementPanel.js +1 -1
  91. package/dist/studio/components/RouteErrorBoundary.d.ts +5 -0
  92. package/dist/studio/components/RouteErrorBoundary.d.ts.map +1 -0
  93. package/dist/studio/components/index.js +2 -2
  94. package/dist/studio/{components-BHTKlUgT.js → components-B4eKIUN5.js} +3 -2
  95. package/dist/studio/control-plane/Agents.d.ts.map +1 -1
  96. package/dist/studio/control-plane/Data.d.ts.map +1 -1
  97. package/dist/studio/control-plane/Instance.d.ts.map +1 -1
  98. package/dist/studio/control-plane/Operations.d.ts.map +1 -1
  99. package/dist/studio/control-plane/Overview.d.ts.map +1 -1
  100. package/dist/studio/control-plane/Schema.d.ts.map +1 -1
  101. package/dist/studio/control-plane/State.d.ts +11 -0
  102. package/dist/studio/control-plane/State.d.ts.map +1 -1
  103. package/dist/studio/control-plane/context.d.ts +4 -1
  104. package/dist/studio/control-plane/context.d.ts.map +1 -1
  105. package/dist/studio/control-plane/index.d.ts +1 -1
  106. package/dist/studio/control-plane/index.d.ts.map +1 -1
  107. package/dist/studio/control-plane/index.js +2 -2
  108. package/dist/studio/control-plane/primitives.d.ts +22 -2
  109. package/dist/studio/control-plane/primitives.d.ts.map +1 -1
  110. package/dist/studio/control-plane-fxMcJn74.js +4173 -0
  111. package/dist/studio/index.js +307 -235
  112. package/dist/studio/studio.css +1 -1
  113. package/dist/studio/utils/control-plane-api.d.ts.map +1 -1
  114. package/dist/studio/utils/control-plane-api.js +4 -3
  115. package/dist/studio/utils/service-api.d.ts.map +1 -1
  116. package/dist/studio/utils/service-api.js +5 -4
  117. package/dist/studio-app/assets/{feltdb_wasm-DYfWAV0E.js → feltdb_wasm-BatwwogY.js} +1 -1
  118. package/dist/studio-app/assets/feltdb_wasm_bg-BX0newOr.wasm +0 -0
  119. package/dist/studio-app/assets/index-CiC8VY-a.css +1 -0
  120. package/dist/studio-app/assets/index-DoVvbIay.js +30 -0
  121. package/dist/studio-app/index.html +2 -2
  122. package/dist/telemetry.d.ts +1 -0
  123. package/dist/telemetry.d.ts.map +1 -1
  124. package/dist/telemetry.js +4 -3
  125. package/dist/transaction-identity.d.ts +62 -0
  126. package/dist/transaction-identity.d.ts.map +1 -0
  127. package/dist/transaction-identity.js +138 -0
  128. package/dist/transaction.d.ts +50 -5
  129. package/dist/transaction.d.ts.map +1 -1
  130. package/dist/transaction.js +28 -0
  131. package/dist/wasm/feltdb_wasm_bg.wasm +0 -0
  132. package/dist/wasm/package.json +1 -1
  133. package/package.json +2 -2
  134. package/dist/create/server-source/crates/feltdb-wasm/test.db +0 -0
  135. package/dist/studio/control-plane-DP8ljTDO.js +0 -3207
  136. package/dist/studio-app/assets/feltdb_wasm_bg-DHiOUhoQ.wasm +0 -0
  137. package/dist/studio-app/assets/index-6f6KVx5R.js +0 -30
  138. package/dist/studio-app/assets/index-BrsF-kWL.css +0 -1
@@ -0,0 +1,534 @@
1
+ //! Transaction identity at the process authority's commit boundary.
2
+ //!
3
+ //! A transaction id names one payload. The authority, not its clients, binds an
4
+ //! id to the payload it first committed, so that an id reused for different
5
+ //! contents is refused instead of being answered "duplicate" and silently
6
+ //! discarded. These tests hold `AuthorityClient::commit` and
7
+ //! `EmbeddedAuthority::commit` to that contract over the real socket, across
8
+ //! restart, and against logs written before the binding existed.
9
+ #![cfg(unix)]
10
+
11
+ use feltdb::{
12
+ authority::{
13
+ AuthorityClient, AuthorityError, AuthorityServer, AuthorityTransaction, EmbeddedAuthority,
14
+ FeltDbAuthority,
15
+ },
16
+ AtomicCommit, AtomicMutation, AtomicPrecondition, FeltDb, RecordPrecondition,
17
+ };
18
+ use serde_json::{json, Value};
19
+ use std::{
20
+ path::{Path, PathBuf},
21
+ process::{Child, Command},
22
+ sync::Arc,
23
+ time::Duration,
24
+ };
25
+ use tempfile::TempDir;
26
+ use tokio::{
27
+ io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
28
+ net::UnixListener,
29
+ };
30
+
31
+ static PROCESS_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(());
32
+
33
+ struct RunningAuthority {
34
+ child: Child,
35
+ socket: PathBuf,
36
+ storage: PathBuf,
37
+ }
38
+
39
+ impl Drop for RunningAuthority {
40
+ fn drop(&mut self) {
41
+ let _ = self.child.kill();
42
+ let _ = self.child.wait();
43
+ }
44
+ }
45
+
46
+ fn start(directory: &TempDir) -> RunningAuthority {
47
+ let socket = directory.path().join("authority.sock");
48
+ let storage = directory.path().join("authority.db");
49
+ let child = Command::new(env!("CARGO_BIN_EXE_feltdb-authority"))
50
+ .arg(&socket)
51
+ .arg(&storage)
52
+ .spawn()
53
+ .expect("authority starts");
54
+ for _ in 0..400 {
55
+ if socket.exists() {
56
+ return RunningAuthority {
57
+ child,
58
+ socket,
59
+ storage,
60
+ };
61
+ }
62
+ std::thread::sleep(Duration::from_millis(5));
63
+ }
64
+ panic!("authority socket was not ready");
65
+ }
66
+
67
+ fn stop(mut authority: RunningAuthority) -> PathBuf {
68
+ authority.child.kill().unwrap();
69
+ authority.child.wait().unwrap();
70
+ let _ = std::fs::remove_file(&authority.socket);
71
+ authority.storage.clone()
72
+ }
73
+
74
+ /// A transaction writing `value` to one record. The id is the caller's.
75
+ fn put(id: &str, key: &str, value: Value) -> AuthorityTransaction {
76
+ AuthorityTransaction {
77
+ transaction_id: id.into(),
78
+ base_revision: None,
79
+ preconditions: vec![],
80
+ record_preconditions: vec![],
81
+ mutations: vec![AtomicMutation {
82
+ capability: "items".into(),
83
+ key: key.into(),
84
+ value: Some(value),
85
+ }],
86
+ audit: None,
87
+ }
88
+ }
89
+
90
+ /// `payload_binding` as the wire carries it, read without depending on the Rust field.
91
+ fn binding(commit: &AtomicCommit) -> Value {
92
+ serde_json::to_value(commit).unwrap()["payload_binding"].clone()
93
+ }
94
+
95
+ async fn rows(authority: &impl FeltDbAuthority) -> Vec<Value> {
96
+ authority
97
+ .read_authoritative()
98
+ .await
99
+ .unwrap()
100
+ .rows
101
+ .into_iter()
102
+ .map(|row| json!({"key": row.key, "value": row.value}))
103
+ .collect()
104
+ }
105
+
106
+ fn code(error: &AuthorityError) -> &str {
107
+ &error.code
108
+ }
109
+
110
+ /* ----------------------------- 1. same id, same payload ----------------------------- */
111
+
112
+ #[tokio::test]
113
+ async fn same_id_same_payload_is_a_verified_duplicate_of_the_original() {
114
+ let directory = TempDir::new().unwrap();
115
+ let authority = EmbeddedAuthority::open(directory.path().join("a.db")).unwrap();
116
+ let first = authority
117
+ .commit(put("tx-1", "items:a", json!({"n": 1})))
118
+ .await
119
+ .unwrap();
120
+ assert!(!first.duplicate);
121
+ // Later commits move the authority on; the duplicate still describes the original.
122
+ for i in 0..3 {
123
+ authority
124
+ .commit(put(&format!("later-{i}"), &format!("items:l{i}"), json!({"i": i})))
125
+ .await
126
+ .unwrap();
127
+ }
128
+ let again = authority
129
+ .commit(put("tx-1", "items:a", json!({"n": 1})))
130
+ .await
131
+ .unwrap();
132
+ assert!(again.duplicate);
133
+ assert_eq!(binding(&again), json!("verified"));
134
+ assert_eq!(again.commit_revision, first.commit_revision);
135
+ assert_eq!(again.state_before, first.state_before);
136
+ assert_eq!(again.state_after, first.state_after);
137
+ assert_eq!(authority.current_revision().await.unwrap(), 4);
138
+ }
139
+
140
+ /* --------------------------- 2. same id, different payload -------------------------- */
141
+
142
+ #[tokio::test]
143
+ async fn same_id_different_payload_is_an_idempotency_conflict_and_applies_nothing() {
144
+ let directory = TempDir::new().unwrap();
145
+ let authority = EmbeddedAuthority::open(directory.path().join("a.db")).unwrap();
146
+ authority
147
+ .commit(put("tx-1", "items:a", json!({"n": 1})))
148
+ .await
149
+ .unwrap();
150
+ let before_rows = rows(&authority).await;
151
+ let before_revision = authority.current_revision().await.unwrap();
152
+
153
+ let mut variants = vec![
154
+ put("tx-1", "items:a", json!({"n": 2})),
155
+ put("tx-1", "items:other", json!({"n": 1})),
156
+ ];
157
+ let mut with_base = put("tx-1", "items:a", json!({"n": 1}));
158
+ with_base.base_revision = Some(1);
159
+ variants.push(with_base);
160
+ let mut with_audit = put("tx-1", "items:a", json!({"n": 1}));
161
+ with_audit.audit = Some(json!({"by": "someone else"}));
162
+ variants.push(with_audit);
163
+ let mut with_precondition = put("tx-1", "items:a", json!({"n": 1}));
164
+ with_precondition.preconditions = vec![AtomicPrecondition {
165
+ capability: "items".into(),
166
+ key: "items:a".into(),
167
+ expected_version: None,
168
+ }];
169
+ variants.push(with_precondition);
170
+ let mut with_record_precondition = put("tx-1", "items:a", json!({"n": 1}));
171
+ with_record_precondition.record_preconditions = vec![RecordPrecondition {
172
+ capability: "items".into(),
173
+ key: "items:a".into(),
174
+ require_absent: false,
175
+ expected_version: Some(1),
176
+ expected_epoch: None,
177
+ expected_lease_id: None,
178
+ }];
179
+ variants.push(with_record_precondition);
180
+ let mut two_mutations = put("tx-1", "items:a", json!({"n": 1}));
181
+ two_mutations.mutations.push(AtomicMutation {
182
+ capability: "items".into(),
183
+ key: "items:extra".into(),
184
+ value: Some(json!({})),
185
+ });
186
+ variants.push(two_mutations);
187
+
188
+ for (index, variant) in variants.into_iter().enumerate() {
189
+ let error = authority.commit(variant).await.unwrap_err();
190
+ assert_eq!(code(&error), "IDEMPOTENCY_CONFLICT", "variant {index}: {error}");
191
+ assert!(error.message.contains("tx-1"), "the id is named: {error}");
192
+ }
193
+ assert_eq!(rows(&authority).await, before_rows, "a conflict writes nothing");
194
+ assert_eq!(authority.current_revision().await.unwrap(), before_revision);
195
+ let original = authority
196
+ .commit(put("tx-1", "items:a", json!({"n": 1})))
197
+ .await
198
+ .unwrap();
199
+ assert_eq!(binding(&original), json!("verified"), "the recorded identity is unchanged");
200
+ }
201
+
202
+ #[tokio::test]
203
+ async fn property_order_in_the_payload_does_not_change_its_identity() {
204
+ let directory = TempDir::new().unwrap();
205
+ let authority = EmbeddedAuthority::open(directory.path().join("a.db")).unwrap();
206
+ let a: Value = serde_json::from_str(r#"{"x":1,"y":{"p":1,"q":[1,{"b":2,"a":1}]}}"#).unwrap();
207
+ let b: Value = serde_json::from_str(r#"{"y":{"q":[1,{"a":1,"b":2}],"p":1},"x":1}"#).unwrap();
208
+ authority.commit(put("tx-1", "items:a", a)).await.unwrap();
209
+ let again = authority.commit(put("tx-1", "items:a", b)).await.unwrap();
210
+ assert_eq!(binding(&again), json!("verified"));
211
+ // Array order does mean something.
212
+ let c: Value = serde_json::from_str(r#"{"x":1,"y":{"p":1,"q":[{"a":1,"b":2},1]}}"#).unwrap();
213
+ let error = authority.commit(put("tx-1", "items:a", c)).await.unwrap_err();
214
+ assert_eq!(code(&error), "IDEMPOTENCY_CONFLICT");
215
+ }
216
+
217
+ /* ---------------------------------- 3-4. concurrency --------------------------------- */
218
+
219
+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
220
+ async fn concurrent_identical_requests_apply_once_and_the_rest_observe_it() {
221
+ let directory = TempDir::new().unwrap();
222
+ let authority = Arc::new(EmbeddedAuthority::open(directory.path().join("a.db")).unwrap());
223
+ let tasks: Vec<_> = (0..24)
224
+ .map(|_| {
225
+ let authority = authority.clone();
226
+ tokio::spawn(async move { authority.commit(put("race", "items:k", json!({"who": 0}))).await })
227
+ })
228
+ .collect();
229
+ let mut applied = 0;
230
+ for task in tasks {
231
+ let commit = task.await.unwrap().unwrap();
232
+ if commit.duplicate {
233
+ assert_eq!(binding(&commit), json!("verified"));
234
+ } else {
235
+ applied += 1;
236
+ }
237
+ }
238
+ assert_eq!(applied, 1, "exactly one application");
239
+ assert_eq!(authority.current_revision().await.unwrap(), 1);
240
+ }
241
+
242
+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
243
+ async fn concurrent_conflicting_requests_apply_at_most_one_payload() {
244
+ let directory = TempDir::new().unwrap();
245
+ let authority = Arc::new(EmbeddedAuthority::open(directory.path().join("a.db")).unwrap());
246
+ let tasks: Vec<_> = (0..30)
247
+ .map(|index| {
248
+ let authority = authority.clone();
249
+ tokio::spawn(async move {
250
+ let who = index % 3;
251
+ (who, authority.commit(put("race", "items:k", json!({"who": who}))).await)
252
+ })
253
+ })
254
+ .collect();
255
+ let mut outcomes = vec![];
256
+ for task in tasks {
257
+ outcomes.push(task.await.unwrap());
258
+ }
259
+ let applied: Vec<_> = outcomes
260
+ .iter()
261
+ .filter(|(_, result)| matches!(result, Ok(commit) if !commit.duplicate))
262
+ .collect();
263
+ assert_eq!(applied.len(), 1, "exactly one payload is applied");
264
+ let winner = applied[0].0;
265
+ for (who, result) in &outcomes {
266
+ match result {
267
+ Ok(commit) => {
268
+ assert_eq!(*who, winner, "only the winning payload is ever acknowledged");
269
+ assert!(!commit.duplicate || binding(commit) == json!("verified"));
270
+ }
271
+ Err(error) => {
272
+ assert_ne!(*who, winner);
273
+ assert_eq!(code(error), "IDEMPOTENCY_CONFLICT");
274
+ }
275
+ }
276
+ }
277
+ let stored = rows(authority.as_ref()).await;
278
+ assert_eq!(stored.len(), 1);
279
+ assert_eq!(stored[0]["value"]["who"], json!(winner));
280
+ assert_eq!(authority.current_revision().await.unwrap(), 1);
281
+ }
282
+
283
+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
284
+ async fn concurrent_clients_over_the_socket_get_the_same_answers() {
285
+ let _process_test = PROCESS_TESTS.lock().unwrap_or_else(|e| e.into_inner());
286
+ let directory = TempDir::new().unwrap();
287
+ let authority = start(&directory);
288
+ let socket = authority.socket.clone();
289
+ let tasks: Vec<_> = (0..20)
290
+ .map(|index| {
291
+ let socket = socket.clone();
292
+ tokio::spawn(async move {
293
+ let who = index % 2;
294
+ (who, AuthorityClient::connect(socket).commit(put("race", "items:k", json!({"who": who}))).await)
295
+ })
296
+ })
297
+ .collect();
298
+ let mut applied = vec![];
299
+ let mut conflicts = 0;
300
+ let mut duplicates = 0;
301
+ let mut outcomes = vec![];
302
+ for task in tasks {
303
+ outcomes.push(task.await.unwrap());
304
+ }
305
+ for (who, result) in &outcomes {
306
+ match result {
307
+ Ok(commit) if commit.duplicate => duplicates += 1,
308
+ Ok(_) => applied.push(*who),
309
+ Err(error) => {
310
+ assert_eq!(code(error), "IDEMPOTENCY_CONFLICT", "{error}");
311
+ conflicts += 1;
312
+ }
313
+ }
314
+ }
315
+ assert_eq!(applied.len(), 1);
316
+ assert_eq!(applied.len() + duplicates + conflicts, 20);
317
+ let winner = applied[0];
318
+ assert!(outcomes.iter().filter(|(who, _)| *who != winner).all(|(_, r)| r.is_err()));
319
+ let client = AuthorityClient::connect(&socket);
320
+ let stored = rows(&client).await;
321
+ assert_eq!(stored.len(), 1);
322
+ assert_eq!(stored[0]["value"]["who"], json!(winner));
323
+ }
324
+
325
+ /* --------------------------------- 5. crash and restart ------------------------------- */
326
+
327
+ #[tokio::test]
328
+ async fn identity_survives_a_killed_authority() {
329
+ let _process_test = PROCESS_TESTS.lock().unwrap_or_else(|e| e.into_inner());
330
+ let directory = TempDir::new().unwrap();
331
+ let authority = start(&directory);
332
+ let first = AuthorityClient::connect(&authority.socket)
333
+ .commit(put("tx-1", "items:a", json!({"n": 1})))
334
+ .await
335
+ .unwrap();
336
+ stop(authority);
337
+
338
+ let restarted = start(&directory);
339
+ let client = AuthorityClient::connect(&restarted.socket);
340
+ let again = client.commit(put("tx-1", "items:a", json!({"n": 1}))).await.unwrap();
341
+ assert!(again.duplicate);
342
+ assert_eq!(binding(&again), json!("verified"));
343
+ assert_eq!(again.commit_revision, first.commit_revision);
344
+ let error = client.commit(put("tx-1", "items:a", json!({"n": 2}))).await.unwrap_err();
345
+ assert_eq!(code(&error), "IDEMPOTENCY_CONFLICT");
346
+ assert_eq!(client.current_revision().await.unwrap(), 1);
347
+ }
348
+
349
+ #[tokio::test]
350
+ async fn a_torn_commit_was_never_acknowledged_so_its_retry_is_a_first_use() {
351
+ use std::io::Write;
352
+ let _process_test = PROCESS_TESTS.lock().unwrap_or_else(|e| e.into_inner());
353
+ let directory = TempDir::new().unwrap();
354
+ let authority = start(&directory);
355
+ AuthorityClient::connect(&authority.socket)
356
+ .commit(put("tx-1", "items:a", json!({"n": 1})))
357
+ .await
358
+ .unwrap();
359
+ let storage = stop(authority);
360
+ // A crash inside the next transaction's record, after its payload hash was written.
361
+ let mut log = std::fs::OpenOptions::new().append(true).open(&storage).unwrap();
362
+ log.write_all(br#"{"record_type":"feltdb.transaction.v1","transaction_id":"tx-2","payload_hash":"sha256:abc""#)
363
+ .unwrap();
364
+ log.sync_all().unwrap();
365
+
366
+ let recovered = start(&directory);
367
+ let client = AuthorityClient::connect(&recovered.socket);
368
+ let retried = client.commit(put("tx-2", "items:b", json!({"n": 2}))).await.unwrap();
369
+ assert!(!retried.duplicate, "the torn record was discarded, not remembered");
370
+ assert_eq!(client.current_revision().await.unwrap(), 2);
371
+ }
372
+
373
+ /* --------------------------- 6. logs written before the binding ------------------------ */
374
+
375
+ #[tokio::test]
376
+ async fn an_id_committed_without_a_hash_is_legacy_unverified_and_never_adopted() {
377
+ let directory = TempDir::new().unwrap();
378
+ let path = directory.path().join("legacy.db");
379
+ {
380
+ // What the authority did before it bound ids: no payload hash.
381
+ let db = FeltDb::open(&path).unwrap();
382
+ db.apply_atomic_transaction(
383
+ "old-1",
384
+ None,
385
+ &[],
386
+ &[AtomicMutation {
387
+ capability: "items".into(),
388
+ key: "items:a".into(),
389
+ value: Some(json!({"n": 1})),
390
+ }],
391
+ None,
392
+ )
393
+ .unwrap();
394
+ }
395
+ for pass in 0..2 {
396
+ // Pass 1 reopens the log after pass 0's retries, to show they recorded nothing.
397
+ let authority = EmbeddedAuthority::open(&path).unwrap();
398
+ let same = authority.commit(put("old-1", "items:a", json!({"n": 1}))).await.unwrap();
399
+ assert!(same.duplicate, "pass {pass}");
400
+ assert_eq!(binding(&same), json!("legacy_unverified"), "pass {pass}");
401
+ // There is nothing to compare a different payload against: it is the same answer,
402
+ // labelled, and it applies nothing.
403
+ let different = authority.commit(put("old-1", "items:a", json!({"n": 99}))).await.unwrap();
404
+ assert!(different.duplicate);
405
+ assert_eq!(binding(&different), json!("legacy_unverified"));
406
+ assert_eq!(rows(&authority).await[0]["value"]["n"], json!(1));
407
+ }
408
+ let db = FeltDb::open(&path).unwrap();
409
+ assert_eq!(db.applied_transaction_payload_hash("old-1").unwrap(), None, "the retry did not give the legacy id a hash");
410
+ // New ids written afterwards are bound.
411
+ let authority = EmbeddedAuthority::from_db(db);
412
+ authority.commit(put("new-1", "items:b", json!({"n": 1}))).await.unwrap();
413
+ let error = authority.commit(put("new-1", "items:b", json!({"n": 2}))).await.unwrap_err();
414
+ assert_eq!(code(&error), "IDEMPOTENCY_CONFLICT");
415
+ }
416
+
417
+ #[tokio::test]
418
+ async fn a_recorded_hash_this_build_cannot_judge_fails_closed() {
419
+ let directory = TempDir::new().unwrap();
420
+ let path = directory.path().join("future.db");
421
+ {
422
+ let db = FeltDb::open(&path).unwrap();
423
+ for (id, hash) in [
424
+ ("future", "authority-tx9:sha256:0000000000000000000000000000000000000000000000000000000000000000"),
425
+ ("other-form", "sha256:abc"),
426
+ ] {
427
+ db.apply_atomic_transaction_content_addressed(
428
+ id,
429
+ Some(hash),
430
+ None,
431
+ &[],
432
+ &[AtomicMutation {
433
+ capability: "items".into(),
434
+ key: format!("items:{id}"),
435
+ value: Some(json!({"id": id})),
436
+ }],
437
+ None,
438
+ )
439
+ .unwrap();
440
+ }
441
+ }
442
+ let authority = EmbeddedAuthority::open(&path).unwrap();
443
+ for id in ["future", "other-form"] {
444
+ let error = authority
445
+ .commit(put(id, &format!("items:{id}"), json!({"id": id})))
446
+ .await
447
+ .unwrap_err();
448
+ assert_eq!(code(&error), "IDEMPOTENCY_UNVERIFIABLE", "{id}: {error}");
449
+ }
450
+ assert_eq!(authority.current_revision().await.unwrap(), 2, "nothing was applied");
451
+ }
452
+
453
+ /* ---------------------- 7. outcomes a caller can be misled about ----------------------- */
454
+
455
+ #[tokio::test]
456
+ async fn a_conflict_crosses_the_socket_as_a_conflict_not_as_a_generic_error() {
457
+ let _process_test = PROCESS_TESTS.lock().unwrap_or_else(|e| e.into_inner());
458
+ let directory = TempDir::new().unwrap();
459
+ let authority = start(&directory);
460
+ let client = AuthorityClient::connect(&authority.socket);
461
+ client.commit(put("tx-1", "items:a", json!({"n": 1}))).await.unwrap();
462
+ let error = client.commit(put("tx-1", "items:a", json!({"n": 2}))).await.unwrap_err();
463
+ assert_eq!(code(&error), "IDEMPOTENCY_CONFLICT");
464
+ assert_ne!(code(&error), "AUTHORITY_ERROR");
465
+ assert_ne!(code(&error), "AUTHORITY_UNAVAILABLE");
466
+ }
467
+
468
+ /// A socket that reads one request line and then does `after` with the connection.
469
+ async fn fake_authority(path: &Path, reply: Option<Vec<u8>>) {
470
+ let listener = UnixListener::bind(path).unwrap();
471
+ tokio::spawn(async move {
472
+ let (stream, _) = listener.accept().await.unwrap();
473
+ let (reader, mut writer) = stream.into_split();
474
+ let mut lines = BufReader::new(reader).lines();
475
+ let _ = lines.next_line().await;
476
+ if let Some(reply) = reply {
477
+ let _ = writer.write_all(&reply).await;
478
+ }
479
+ // dropping the stream closes it
480
+ });
481
+ }
482
+
483
+ #[tokio::test]
484
+ async fn a_commit_that_may_have_reached_the_authority_is_reported_as_unknown_not_failed() {
485
+ let directory = TempDir::new().unwrap();
486
+ // The authority read the request and went away without answering.
487
+ let silent = directory.path().join("silent.sock");
488
+ fake_authority(&silent, None).await;
489
+ let error = AuthorityClient::connect(&silent)
490
+ .commit(put("tx-1", "items:a", json!({})))
491
+ .await
492
+ .unwrap_err();
493
+ assert_eq!(code(&error), "COMMIT_OUTCOME_UNKNOWN", "{error}");
494
+
495
+ // It answered with something that is not a response.
496
+ let garbled = directory.path().join("garbled.sock");
497
+ fake_authority(&garbled, Some(b"not json\n".to_vec())).await;
498
+ let error = AuthorityClient::connect(&garbled)
499
+ .commit(put("tx-1", "items:a", json!({})))
500
+ .await
501
+ .unwrap_err();
502
+ assert_eq!(code(&error), "COMMIT_OUTCOME_UNKNOWN", "{error}");
503
+
504
+ // Nothing was listening: the request never left, so a plain failure is truthful.
505
+ let error = AuthorityClient::connect(directory.path().join("absent.sock"))
506
+ .commit(put("tx-1", "items:a", json!({})))
507
+ .await
508
+ .unwrap_err();
509
+ assert_eq!(code(&error), "AUTHORITY_UNAVAILABLE");
510
+
511
+ // Reads have no outcome to be unsure about; they keep their codes.
512
+ let error = AuthorityClient::connect(&silent).current_revision().await.unwrap_err();
513
+ assert_ne!(code(&error), "COMMIT_OUTCOME_UNKNOWN");
514
+ }
515
+
516
+ #[tokio::test]
517
+ async fn a_server_in_this_process_binds_ids_too() {
518
+ // The same contract through AuthorityServer::open, without the binary.
519
+ let directory = TempDir::new().unwrap();
520
+ let socket = directory.path().join("s.sock");
521
+ let server = AuthorityServer::open(&socket, directory.path().join("s.db")).unwrap();
522
+ let handle = tokio::spawn(server.serve());
523
+ for _ in 0..400 {
524
+ if socket.exists() {
525
+ break;
526
+ }
527
+ tokio::time::sleep(Duration::from_millis(5)).await;
528
+ }
529
+ let client = AuthorityClient::connect(&socket);
530
+ client.commit(put("tx-1", "items:a", json!({"n": 1}))).await.unwrap();
531
+ let error = client.commit(put("tx-1", "items:a", json!({"n": 2}))).await.unwrap_err();
532
+ assert_eq!(code(&error), "IDEMPOTENCY_CONFLICT");
533
+ handle.abort();
534
+ }