@feltdb/core 0.12.1 → 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 (112) hide show
  1. package/dist/build-identity.json +13 -4
  2. package/dist/cli/commands.js +88 -43
  3. package/dist/collection.d.ts +41 -4
  4. package/dist/collection.d.ts.map +1 -1
  5. package/dist/collection.js +116 -47
  6. package/dist/composition.d.ts.map +1 -1
  7. package/dist/composition.js +11 -1
  8. package/dist/create/build-identity.json +13 -4
  9. package/dist/create/cli.js +3 -3
  10. package/dist/create/create.js +17 -19
  11. package/dist/create/package-versions.js +1 -1
  12. package/dist/create/server-source/Cargo.lock +18 -3
  13. package/dist/create/server-source/Cargo.toml +4 -2
  14. package/dist/create/server-source/crates/feltdb/Cargo.toml +20 -0
  15. package/dist/create/server-source/crates/feltdb/LICENSE +21 -0
  16. package/dist/create/server-source/crates/feltdb/README.md +75 -0
  17. package/dist/create/server-source/crates/feltdb/src/agent_state.rs +320 -0
  18. package/dist/create/server-source/crates/feltdb/src/agent_transition_contract.rs +1545 -0
  19. package/dist/create/server-source/crates/feltdb/src/authority.rs +145 -15
  20. package/dist/create/server-source/crates/feltdb/src/lib.rs +227 -23
  21. package/dist/create/server-source/crates/feltdb/src/state_model.rs +1 -5
  22. package/dist/create/server-source/crates/feltdb/tests/agent_state_native.rs +1188 -0
  23. package/dist/create/server-source/crates/feltdb/tests/agent_transition_contract_conformance.rs +2884 -0
  24. package/dist/create/server-source/crates/feltdb/tests/authority_transaction_identity.rs +534 -0
  25. package/dist/create/server-source/crates/feltdb/tests/fixtures/agent_transition_corpus.json +23340 -0
  26. package/dist/create/server-source/crates/feltdb-client/Cargo.toml +29 -0
  27. package/dist/create/server-source/crates/feltdb-client/LICENSE +21 -0
  28. package/dist/create/server-source/crates/feltdb-client/README.md +70 -0
  29. package/dist/create/server-source/crates/feltdb-client/src/application.rs +527 -0
  30. package/dist/create/server-source/crates/feltdb-client/src/authority.rs +679 -0
  31. package/dist/create/server-source/crates/feltdb-client/src/control.rs +292 -0
  32. package/dist/create/server-source/crates/feltdb-client/src/error.rs +227 -0
  33. package/dist/create/server-source/crates/feltdb-client/src/events.rs +146 -0
  34. package/dist/create/server-source/crates/feltdb-client/src/lib.rs +466 -0
  35. package/dist/create/server-source/crates/feltdb-client/tests/fixtures/README.md +4 -0
  36. package/dist/create/server-source/crates/feltdb-client/tests/fixtures/private-ca.pem +20 -0
  37. package/dist/create/server-source/crates/feltdb-client/tests/fixtures/server-key.pem +28 -0
  38. package/dist/create/server-source/crates/feltdb-client/tests/fixtures/server.pem +20 -0
  39. package/dist/create/server-source/crates/feltdb-client/tests/private_ca.rs +95 -0
  40. package/dist/create/server-source/crates/feltdb-server/Cargo.toml +20 -1
  41. package/dist/create/server-source/crates/feltdb-server/LICENSE +21 -0
  42. package/dist/create/server-source/crates/feltdb-server/README.md +12 -1
  43. package/dist/create/server-source/crates/feltdb-server/src/backup.rs +6 -2
  44. package/dist/create/server-source/crates/feltdb-server/src/lib.rs +20 -0
  45. package/dist/create/server-source/crates/feltdb-server/src/main.rs +1 -3
  46. package/dist/create/server-source/crates/feltdb-server/tests/rust_client.rs +683 -0
  47. package/dist/create/server-source/crates/feltdb-wasm/Cargo.toml +3 -1
  48. package/dist/create/template/default-project/README.md +12 -7
  49. package/dist/create/template/default-project/src/pages/Dashboard.tsx +1 -1
  50. package/dist/create/template/dot-feltdb-README.md +3 -3
  51. package/dist/db.d.ts.map +1 -1
  52. package/dist/db.js +43 -17
  53. package/dist/development-runtime-bridge.d.ts.map +1 -1
  54. package/dist/development-runtime-bridge.js +22 -1
  55. package/dist/embedded-transaction.d.ts +75 -8
  56. package/dist/embedded-transaction.d.ts.map +1 -1
  57. package/dist/embedded-transaction.js +124 -18
  58. package/dist/error-codes.d.ts +2 -0
  59. package/dist/error-codes.d.ts.map +1 -1
  60. package/dist/error-codes.js +2 -0
  61. package/dist/feltdb.d.ts +1 -11
  62. package/dist/feltdb.d.ts.map +1 -1
  63. package/dist/file-db.d.ts +6 -0
  64. package/dist/file-db.d.ts.map +1 -1
  65. package/dist/file-db.js +43 -11
  66. package/dist/indexeddb-db.d.ts.map +1 -1
  67. package/dist/indexeddb-db.js +65 -41
  68. package/dist/memory-db.d.ts.map +1 -1
  69. package/dist/memory-db.js +29 -8
  70. package/dist/studio/{KeyManagementPanel-DZuSeWBK.js → KeyManagementPanel-D5FMvvU9.js} +1 -0
  71. package/dist/studio/app.d.ts.map +1 -1
  72. package/dist/studio/components/KeyManagementPanel.d.ts.map +1 -1
  73. package/dist/studio/components/KeyManagementPanel.js +1 -1
  74. package/dist/studio/components/RouteErrorBoundary.d.ts +5 -0
  75. package/dist/studio/components/RouteErrorBoundary.d.ts.map +1 -0
  76. package/dist/studio/components/index.js +2 -2
  77. package/dist/studio/{components-Bivm2lX6.js → components-B4eKIUN5.js} +1 -1
  78. package/dist/studio/control-plane/Agents.d.ts.map +1 -1
  79. package/dist/studio/control-plane/Data.d.ts.map +1 -1
  80. package/dist/studio/control-plane/Instance.d.ts.map +1 -1
  81. package/dist/studio/control-plane/Overview.d.ts.map +1 -1
  82. package/dist/studio/control-plane/Schema.d.ts.map +1 -1
  83. package/dist/studio/control-plane/context.d.ts +4 -1
  84. package/dist/studio/control-plane/context.d.ts.map +1 -1
  85. package/dist/studio/control-plane/index.js +2 -2
  86. package/dist/studio/control-plane/primitives.d.ts +8 -0
  87. package/dist/studio/control-plane/primitives.d.ts.map +1 -1
  88. package/dist/studio/{control-plane-CLm69XwX.js → control-plane-fxMcJn74.js} +1371 -1319
  89. package/dist/studio/index.js +146 -105
  90. package/dist/studio/utils/control-plane-api.d.ts.map +1 -1
  91. package/dist/studio/utils/control-plane-api.js +4 -3
  92. package/dist/studio/utils/service-api.d.ts.map +1 -1
  93. package/dist/studio/utils/service-api.js +5 -4
  94. package/dist/studio-app/assets/{feltdb_wasm-DACcD-zs.js → feltdb_wasm-BatwwogY.js} +1 -1
  95. package/dist/studio-app/assets/feltdb_wasm_bg-BX0newOr.wasm +0 -0
  96. package/dist/studio-app/assets/index-DoVvbIay.js +30 -0
  97. package/dist/studio-app/index.html +1 -1
  98. package/dist/telemetry.d.ts +1 -0
  99. package/dist/telemetry.d.ts.map +1 -1
  100. package/dist/telemetry.js +4 -3
  101. package/dist/transaction-identity.d.ts +62 -0
  102. package/dist/transaction-identity.d.ts.map +1 -0
  103. package/dist/transaction-identity.js +138 -0
  104. package/dist/transaction.d.ts +50 -5
  105. package/dist/transaction.d.ts.map +1 -1
  106. package/dist/transaction.js +28 -0
  107. package/dist/wasm/feltdb_wasm_bg.wasm +0 -0
  108. package/dist/wasm/package.json +1 -1
  109. package/package.json +1 -1
  110. package/dist/create/server-source/crates/feltdb-wasm/test.db +0 -0
  111. package/dist/studio-app/assets/feltdb_wasm_bg-BejThWID.wasm +0 -0
  112. package/dist/studio-app/assets/index-CoZaxnlm.js +0 -30
@@ -362,13 +362,13 @@ Learn more: https://github.com/rkendel1/feltdb`);
362
362
  }
363
363
  }
364
364
  else {
365
- console.log('Project is ready. Start the application with:');
365
+ console.log('Project is ready. Start it with:');
366
366
  console.log(` cd ${projectName}`);
367
367
  if (!shouldInstall)
368
368
  console.log(' npm install');
369
- console.log(' npm run dev');
370
- console.log('Start FeltDB development tooling separately with:');
371
369
  console.log(' npm run feltdb:dev');
370
+ console.log('This starts the application, the development authority, and Studio together.');
371
+ console.log('Do not also run npm run dev: that second copy is not managed by FeltDB.');
372
372
  }
373
373
  }
374
374
  catch (error) {
@@ -196,6 +196,12 @@ ${hasAgents ? ` agent WorkspaceAssistant {
196
196
  tsconfig.compilerOptions.types = ['vite/client'];
197
197
  }
198
198
  fs.writeFileSync(path.join(projectDir, 'tsconfig.json'), JSON.stringify(tsconfig, null, 2));
199
+ // Browsers do not expose VITE_* through process.env, so a local database must be handed its
200
+ // namespace explicitly; otherwise it opens the shared `default` store and `feltdb dev` cannot
201
+ // recognise the application. A managed (remote) runtime resolves its target from its URL.
202
+ const createDatabaseCall = runtime === 'managed'
203
+ ? 'createFeltDB()'
204
+ : `createFeltDB({ namespace: import.meta.env.VITE_FELTDB_NAMESPACE || ${JSON.stringify(applicationName)} })`;
199
205
  // Create main application files
200
206
  const feltdbTs = `import { configureDevelopmentRuntimeBridge, createFeltDB } from '@feltdb/core';
201
207
 
@@ -209,7 +215,7 @@ configureDevelopmentRuntimeBridge({
209
215
  applicationUrl: import.meta.env.VITE_FELTDB_APPLICATION_URL,
210
216
  });
211
217
 
212
- export const db = createFeltDB();
218
+ export const db = ${createDatabaseCall};
213
219
 
214
220
  // Collections
215
221
  export const projects = db.collection('Project');
@@ -1193,7 +1199,7 @@ root.render(
1193
1199
  }
1194
1200
  fs.writeFileSync(path.join(projectDir, 'feltdb.flow'), fs.readFileSync(path.join(canonicalTemplate, 'feltdb.flow'), 'utf8').replace('app FeltDBStarter', `app ${appName}`));
1195
1201
  const databasePath = path.join(srcDir, 'feltdb.ts');
1196
- fs.writeFileSync(databasePath, fs.readFileSync(databasePath, 'utf8').replace(/export const managedRuntime[\s\S]*?\n\} : \{ namespace: import\.meta\.env\.VITE_FELTDB_NAMESPACE \|\| 'feltdb-starter', browser: true \}\);/, `export const managedRuntime = ${runtime === 'managed'};\nexport const db = createFeltDB();`));
1202
+ fs.writeFileSync(databasePath, fs.readFileSync(databasePath, 'utf8').replace(/export const managedRuntime[\s\S]*?\n\} : \{ namespace: import\.meta\.env\.VITE_FELTDB_NAMESPACE \|\| 'feltdb-starter', browser: true \}\);/, `export const managedRuntime = ${runtime === 'managed'};\nexport const db = ${createDatabaseCall};`));
1197
1203
  }
1198
1204
  }
1199
1205
  else {
@@ -1558,22 +1564,17 @@ A FeltDB Workspace application demonstrating local-first database capabilities.
1558
1564
 
1559
1565
  ## Quick Start
1560
1566
 
1561
- Start the application:
1567
+ Start everything:
1562
1568
 
1563
1569
  \`\`\`bash
1564
1570
  npm install
1565
- npm run dev
1566
- \`\`\`
1567
-
1568
- The application will be available at http://localhost:5173 (or your configured port).
1569
-
1570
- In a second terminal, start FeltDB authority, pairing, and Studio and attach it
1571
- to the application explicitly:
1572
-
1573
- \`\`\`bash
1574
1571
  npm run feltdb:dev
1575
1572
  \`\`\`
1576
1573
 
1574
+ \`feltdb dev\` starts the application, the development authority, pairing, and Studio together
1575
+ and prints the address of each. Do not also run \`npm run dev\`: that second copy is not
1576
+ managed by FeltDB, so Studio cannot see it.
1577
+
1577
1578
  ## FeltDB Workspace Showcase
1578
1579
 
1579
1580
  This application demonstrates core FeltDB capabilities:
@@ -1698,17 +1699,14 @@ Never expose \`FELTDB_MANAGED_CONTROL_API_KEY\` or \`FELTDB_TOKEN\` through a \`
1698
1699
 
1699
1700
  ## Development
1700
1701
 
1701
- ### Start Development Server
1702
- \`\`\`bash
1703
- npm run dev
1704
- \`\`\`
1705
-
1706
- ### Start FeltDB Development Tooling
1707
-
1702
+ ### Start the Development Environment
1708
1703
  \`\`\`bash
1709
1704
  npm run feltdb:dev
1710
1705
  \`\`\`
1711
1706
 
1707
+ This runs the application (\`npm run dev\` under FeltDB's management), the development authority,
1708
+ and Studio. Running \`npm run dev\` yourself starts an unmanaged second copy.
1709
+
1712
1710
  ### Build for Production
1713
1711
  \`\`\`bash
1714
1712
  npm run build
@@ -1,4 +1,4 @@
1
1
  // One release train keeps generated applications installable. The repository
2
2
  // validation script checks these values against every workspace manifest.
3
- export const FELTDB_PACKAGE_VERSION = '0.12.1';
3
+ export const FELTDB_PACKAGE_VERSION = '0.12.2';
4
4
  export const feltdbPackageRange = `^${FELTDB_PACKAGE_VERSION}`;
@@ -494,13 +494,14 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
494
494
 
495
495
  [[package]]
496
496
  name = "feltdb"
497
- version = "0.2.0"
497
+ version = "0.2.1"
498
498
  dependencies = [
499
499
  "async-stream",
500
500
  "async-trait",
501
501
  "bincode",
502
502
  "criterion",
503
503
  "ed25519-dalek",
504
+ "feltdb",
504
505
  "rand 0.8.7",
505
506
  "serde",
506
507
  "serde_json",
@@ -510,15 +511,29 @@ dependencies = [
510
511
  "wasmi",
511
512
  ]
512
513
 
514
+ [[package]]
515
+ name = "feltdb-client"
516
+ version = "0.2.1"
517
+ dependencies = [
518
+ "feltdb",
519
+ "reqwest",
520
+ "serde",
521
+ "serde_json",
522
+ "tokio",
523
+ "tokio-rustls",
524
+ "uuid",
525
+ ]
526
+
513
527
  [[package]]
514
528
  name = "feltdb-server"
515
- version = "0.2.0"
529
+ version = "0.2.1"
516
530
  dependencies = [
517
531
  "argon2",
518
532
  "async-stream",
519
533
  "axum",
520
534
  "base64",
521
535
  "feltdb",
536
+ "feltdb-client",
522
537
  "futures-core",
523
538
  "hmac",
524
539
  "password-hash",
@@ -537,7 +552,7 @@ dependencies = [
537
552
 
538
553
  [[package]]
539
554
  name = "feltdb-wasm"
540
- version = "0.2.0"
555
+ version = "0.2.1"
541
556
  dependencies = [
542
557
  "feltdb",
543
558
  "getrandom 0.2.17",
@@ -1,16 +1,18 @@
1
1
  [workspace]
2
- members = ["crates/feltdb", "crates/feltdb-server", "crates/feltdb-wasm"]
2
+ members = ["crates/feltdb", "crates/feltdb-client", "crates/feltdb-server", "crates/feltdb-wasm"]
3
3
  # The deterministic contracts' WASM implementations are their own
4
4
  # dependency-free workspaces: they are only ever built for
5
5
  # wasm32-unknown-unknown, and a second implementation that inherited this
6
6
  # workspace's dependencies would stop being an independent one.
7
7
  exclude = [
8
+ "crates/feltdb-public-api-check",
8
9
  "crates/feltdb-trigger-contract-wasm",
9
10
  "crates/feltdb-state-diff-contract-wasm",
10
11
  "crates/feltdb-state-conflict-contract-wasm",
12
+ "crates/feltdb-agent-transition-contract-wasm",
11
13
  ]
12
14
  resolver = "2"
13
15
 
14
16
  [workspace.package]
15
- version = "0.2.0"
17
+ version = "0.2.1"
16
18
  edition = "2021"
@@ -2,6 +2,23 @@
2
2
  name = "feltdb"
3
3
  version.workspace = true
4
4
  edition.workspace = true
5
+ # The oldest toolchain CI builds and tests this workspace with (.github/workflows/ci.yml).
6
+ rust-version = "1.96"
7
+ description = "Embedded durable state store: an append-only log with atomic multi-record transactions, version-conditional writes, and idempotent retries"
8
+ license = "MIT"
9
+ repository = "https://github.com/rkendel1/flow_db"
10
+ readme = "README.md"
11
+ keywords = ["database", "embedded", "transactions", "durable", "idempotency"]
12
+ categories = ["database-implementations", "data-structures"]
13
+ # The integration tests and benches read repository files by path (docs, sibling crates) and
14
+ # cannot run from a packaged copy, so they stay in the repository.
15
+ exclude = ["tests/", "benches/", "target/"]
16
+
17
+ [features]
18
+ default = []
19
+ # Implementation, fault-injection and diagnostic modules. Not part of the supported API: no
20
+ # compatibility promise covers anything this exposes. The workspace's own crates enable it.
21
+ unstable-internals = []
5
22
 
6
23
  [dependencies]
7
24
  serde = { version = "1", features = ["derive"] }
@@ -18,6 +35,9 @@ bincode = "1"
18
35
  tokio = { version = "1", features = ["net", "io-util", "rt-multi-thread"] }
19
36
 
20
37
  [dev-dependencies]
38
+ # The integration tests and benches exercise internals, so they build the crate with them. Packages
39
+ # that want only the supported API depend on `feltdb` without the feature.
40
+ feltdb = { path = ".", features = ["unstable-internals"] }
21
41
  criterion = { version = "0.5", features = ["html_reports"] }
22
42
  sha2 = "0.10"
23
43
  tempfile = "3"
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 FeltDB Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,75 @@
1
+ # feltdb
2
+
3
+ An embedded, durable state store for Rust. Records live in an append-only log on local disk. Several
4
+ records can change in one atomic transaction, a write can be conditional on the version you read, and a
5
+ transaction can carry an identity so that a retry after an uncertain outcome is recognized instead of
6
+ applied twice.
7
+
8
+ ```toml
9
+ [dependencies]
10
+ feltdb = "0.2"
11
+ serde_json = "1"
12
+ ```
13
+
14
+ ```rust
15
+ use feltdb::{FeltDb, FlowError};
16
+ use serde_json::json;
17
+
18
+ fn main() -> Result<(), Box<dyn std::error::Error>> {
19
+ let db = FeltDb::open("app.db")?;
20
+
21
+ // Create only if absent. A second create is refused in a way you can branch on.
22
+ db.insert_if_absent("orders:o-1", json!({ "status": "pending" }))?;
23
+ assert!(matches!(
24
+ db.insert_if_absent("orders:o-1", json!({})),
25
+ Err(FlowError::PreconditionFailed(_))
26
+ ));
27
+ Ok(())
28
+ }
29
+ ```
30
+
31
+ The crate documentation on docs.rs has a longer, tested example covering atomic transactions and safe
32
+ retries.
33
+
34
+ ## What you can rely on
35
+
36
+ - Acknowledged writes and committed transaction ids survive closing and reopening the database, and a
37
+ process kill.
38
+ - An interrupted, unacknowledged append is discarded on open and reported; its retry is treated as a
39
+ first use.
40
+ - A transaction id names one payload. Reusing an id with a different payload hash fails with
41
+ `FlowError::TransactionIdPayloadMismatch` and writes nothing.
42
+
43
+ ## What is not promised
44
+
45
+ - **Power-loss durability is unproven.** A flush hands bytes to the operating system; it does not force
46
+ them to stable storage. What survives a power cut depends on the filesystem, mount options and the
47
+ drive. See the repository's
48
+ [crash durability](https://github.com/rkendel1/flow_db/blob/main/docs/architecture/crash-durability.md)
49
+ note.
50
+ - **Only the supported API is covered by semver.** While the version is `0.x`, a breaking change to a
51
+ supported item is a minor-version bump. Everything behind the `unstable-internals` feature (fault
52
+ injection, diagnostics, implementation modules) carries no promise at all; do not enable it in
53
+ application code. The supported surface is listed in
54
+ [the Rust API contract](https://github.com/rkendel1/flow_db/blob/main/docs/reference/feltdb-rust-api.md).
55
+ - Plain `insert`, `update` and `delete` are unconditional: `insert` replaces, `update` of a missing key
56
+ creates it, `delete` of a missing key succeeds. Use `insert_if_absent` or `compare_and_set_json` when
57
+ you need a guard.
58
+
59
+ ## Targets
60
+
61
+ Built and tested on native targets. `wasm32-wasip1` compiles. `wasm32-unknown-unknown` compiles only if
62
+ your crate enables `getrandom`'s `js` feature.
63
+
64
+ ## Binaries
65
+
66
+ The package also builds `feltdb-authority`, `feltdb-authority-client` and `feltdb_node`, the process
67
+ authority and its client. `cargo install feltdb` installs them. Most applications want only the library.
68
+
69
+ ## Minimum Rust version
70
+
71
+ 1.96, the oldest toolchain the project's CI builds and tests with.
72
+
73
+ ## License
74
+
75
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,320 @@
1
+ //! Durable agent state: the production implementation of
2
+ //! [`crate::agent_transition_contract`].
3
+ //!
4
+ //! This module contains **no lifecycle logic**. Every rule about who may do
5
+ //! what, when, and on what evidence lives in the contract; this module only
6
+ //! performs the five steps the contract's documentation requires of a caller:
7
+ //!
8
+ //! ```text
9
+ //! 1. read the records the operation names, with their versions
10
+ //! 2. take the authority's time
11
+ //! 3. ask the contract to decide
12
+ //! 4. commit its writes and guards in one guarded transaction
13
+ //! 5. report success only if that commit succeeded
14
+ //! ```
15
+ //!
16
+ //! Step 4 is what makes step 3 true. A decision was valid for the records read
17
+ //! in step 1; the commit carries a precondition for each of them, so if any
18
+ //! record changed in between, nothing is written. Lease expiry is judged twice,
19
+ //! both times on the authority's clock: by the contract at decision time, and by
20
+ //! the transaction (`expected_lease_id`) at commit time.
21
+ //!
22
+ //! # Retries
23
+ //!
24
+ //! A lost race is [`AgentStateError::Conflict`], reported, never retried here.
25
+ //! A caller that wants to try again calls [`AgentState::apply`] again, which
26
+ //! re-reads current state and asks the contract again. The same writes are
27
+ //! never resent.
28
+
29
+ use crate::agent_transition_contract::{
30
+ evaluate, AgentTransitionInput, Decision, ErrorCode, Expect, Guard, Observation, Operation,
31
+ Records, Stored, Write, AGENT_TRANSITION_CONTRACT_ID, AGENT_TRANSITION_CONTRACT_VERSION,
32
+ HANDOFF_COLLECTION, INTENT_COLLECTION, TASK_COLLECTION,
33
+ };
34
+ use crate::{AtomicMutation, FeltDb, FlowError, PreconditionFailure, RecordPrecondition};
35
+ use serde_json::Value;
36
+ use std::sync::Arc;
37
+
38
+ /// The time source decisions are made against.
39
+ ///
40
+ /// Production uses [`FeltDb::authority_time_ms`]. A test may inject its own to
41
+ /// drive the contract through a lifecycle without sleeping. The commit-time
42
+ /// lease predicate always uses the authority's real clock.
43
+ pub trait AuthorityClock: Send + Sync {
44
+ fn now_ms(&self) -> u64;
45
+ }
46
+
47
+ struct DatabaseClock(FeltDb);
48
+
49
+ impl AuthorityClock for DatabaseClock {
50
+ fn now_ms(&self) -> u64 {
51
+ self.0.authority_time_ms()
52
+ }
53
+ }
54
+
55
+ #[derive(Debug)]
56
+ pub enum AgentStateError {
57
+ /// The contract refused the operation. Nothing was written.
58
+ Refused(ErrorCode),
59
+ /// The decision was valid when made, but a record it depended on changed
60
+ /// before the commit. Nothing was written. Re-read and decide again.
61
+ Conflict(PreconditionFailure),
62
+ /// The store failed. Whether anything was written is the store's report.
63
+ Storage(FlowError),
64
+ }
65
+
66
+ impl std::fmt::Display for AgentStateError {
67
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68
+ match self {
69
+ Self::Refused(code) => write!(f, "{}", code.as_str()),
70
+ Self::Conflict(failure) => write!(f, "CONFLICT: {failure}"),
71
+ Self::Storage(error) => write!(f, "STORAGE: {error}"),
72
+ }
73
+ }
74
+ }
75
+
76
+ impl std::error::Error for AgentStateError {}
77
+
78
+ /// A record the commit wrote, with the version it now has.
79
+ #[derive(Debug, Clone, PartialEq)]
80
+ pub struct Written {
81
+ pub collection: String,
82
+ pub id: String,
83
+ pub version: u64,
84
+ }
85
+
86
+ #[derive(Debug, Clone, PartialEq)]
87
+ pub enum Applied {
88
+ Committed(Vec<Written>),
89
+ /// A recognized repeat: nothing changed, and nothing needed to.
90
+ Noop,
91
+ }
92
+
93
+ /// A decision, with nothing yet committed.
94
+ #[derive(Debug, Clone)]
95
+ pub struct Prepared {
96
+ decision: Decision,
97
+ }
98
+
99
+ impl Prepared {
100
+ pub fn decision(&self) -> &Decision {
101
+ &self.decision
102
+ }
103
+ }
104
+
105
+ #[derive(Clone)]
106
+ pub struct AgentState {
107
+ db: FeltDb,
108
+ clock: Arc<dyn AuthorityClock>,
109
+ }
110
+
111
+ fn key(collection: &str, id: &str) -> String {
112
+ format!("{collection}:{id}")
113
+ }
114
+
115
+ impl AgentState {
116
+ pub fn new(db: FeltDb) -> Self {
117
+ let clock = Arc::new(DatabaseClock(db.clone()));
118
+ Self { db, clock }
119
+ }
120
+
121
+ pub fn with_clock(db: FeltDb, clock: Arc<dyn AuthorityClock>) -> Self {
122
+ Self { db, clock }
123
+ }
124
+
125
+ /// One record and its authority version, or `None`.
126
+ ///
127
+ /// The version is the document's `__version`, defaulting to 1 where the
128
+ /// record was never written under a version precondition: the same reading
129
+ /// the transaction's precondition makes.
130
+ pub fn read(
131
+ &self,
132
+ collection: &str,
133
+ id: &str,
134
+ ) -> Result<Option<(u64, Value)>, AgentStateError> {
135
+ let Some(mut value) = self
136
+ .db
137
+ .get_value(&key(collection, id))
138
+ .map_err(AgentStateError::Storage)?
139
+ else {
140
+ return Ok(None);
141
+ };
142
+ let version = value.get("__version").and_then(Value::as_u64).unwrap_or(1);
143
+ if let Some(object) = value.as_object_mut() {
144
+ object.remove("__version");
145
+ }
146
+ Ok(Some((version, value)))
147
+ }
148
+
149
+ fn stored<T: serde::de::DeserializeOwned>(
150
+ &self,
151
+ collection: &str,
152
+ id: &str,
153
+ ) -> Result<Option<Stored<T>>, AgentStateError> {
154
+ match self.read(collection, id)? {
155
+ None => Ok(None),
156
+ Some((version, value)) => match serde_json::from_value(value) {
157
+ Ok(value) => Ok(Some(Stored { value, version })),
158
+ // Stored state that does not parse is not decided around.
159
+ Err(_) => Err(AgentStateError::Refused(ErrorCode::ContractInputInvalid)),
160
+ },
161
+ }
162
+ }
163
+
164
+ /// Step 1: read exactly the records the operation names.
165
+ fn gather(&self, op: &Operation) -> Result<Records, AgentStateError> {
166
+ let mut records = Records::default();
167
+ if let Some(handoff_id) = &op.handoff_id {
168
+ records.handoff = self.stored(HANDOFF_COLLECTION, handoff_id)?;
169
+ }
170
+ let task_id = op
171
+ .task_id
172
+ .clone()
173
+ .or_else(|| records.handoff.as_ref().map(|h| h.value.task_id.clone()));
174
+ if let Some(task_id) = &task_id {
175
+ records.task = self.stored(TASK_COLLECTION, task_id)?;
176
+ if let Some(key_) = &op.idempotency_key {
177
+ records.intent = self.stored(INTENT_COLLECTION, &format!("{task_id}~{key_}"))?;
178
+ }
179
+ }
180
+ if matches!(
181
+ op.op.as_str(),
182
+ "checkpoint" | "record_outcome" | "reconcile"
183
+ ) {
184
+ let mut seen = Vec::new();
185
+ for reference in op.evidence.iter().flatten().filter(|r| r.kind == "record") {
186
+ let (collection, id) = (
187
+ reference.collection.clone().unwrap_or_default(),
188
+ reference.id.clone().unwrap_or_default(),
189
+ );
190
+ if let Some((version, _)) = self.read(&collection, &id)? {
191
+ // A record cited twice is observed once; the contract refuses
192
+ // the duplicate citation.
193
+ if !seen
194
+ .iter()
195
+ .any(|o: &Observation| o.collection == collection && o.id == id)
196
+ {
197
+ seen.push(Observation {
198
+ collection,
199
+ id,
200
+ version,
201
+ });
202
+ }
203
+ }
204
+ }
205
+ records.evidence = Some(seen);
206
+ }
207
+ Ok(records)
208
+ }
209
+
210
+ /// Steps 1 to 3. Reads, takes the authority's time and decides. Writes
211
+ /// nothing.
212
+ pub fn prepare(&self, operation: &Operation) -> Result<Prepared, AgentStateError> {
213
+ let records = self.gather(operation)?;
214
+ let input = AgentTransitionInput {
215
+ contract: AGENT_TRANSITION_CONTRACT_ID.to_string(),
216
+ now_ms: self.clock.now_ms(),
217
+ operation: operation.clone(),
218
+ records,
219
+ version: AGENT_TRANSITION_CONTRACT_VERSION,
220
+ };
221
+ evaluate(&input)
222
+ .map(|decision| Prepared { decision })
223
+ .map_err(AgentStateError::Refused)
224
+ }
225
+
226
+ /// Steps 4 and 5: one guarded transaction carrying every write and guard
227
+ /// the contract returned, each with the precondition it attached.
228
+ ///
229
+ /// Nothing is retried. A fresh transaction id is used per call, so a failed
230
+ /// precondition never consumes an id and a repeated call is a new decision's
231
+ /// commit, not a replay.
232
+ pub fn commit(&self, prepared: &Prepared) -> Result<Applied, AgentStateError> {
233
+ let (writes, guards) = match &prepared.decision {
234
+ Decision::Noop => return Ok(Applied::Noop),
235
+ Decision::Commit { writes, guards } => (writes, guards),
236
+ };
237
+ let mut preconditions: Vec<RecordPrecondition> = Vec::new();
238
+ let mut mutations: Vec<AtomicMutation> = Vec::new();
239
+ for Write {
240
+ collection,
241
+ id,
242
+ expect,
243
+ value,
244
+ } in writes
245
+ {
246
+ preconditions.push(precondition(collection, id, expect));
247
+ mutations.push(AtomicMutation {
248
+ capability: (*collection).to_string(),
249
+ key: key(collection, id),
250
+ value: Some(value.clone()),
251
+ });
252
+ }
253
+ for Guard {
254
+ collection,
255
+ id,
256
+ version,
257
+ lease_id,
258
+ } in guards
259
+ {
260
+ preconditions.push(precondition(
261
+ collection,
262
+ id,
263
+ &Expect::Version {
264
+ version: *version,
265
+ lease_id: lease_id.clone(),
266
+ },
267
+ ));
268
+ }
269
+ let transaction_id = format!("agent-state-{:032x}", rand::random::<u128>());
270
+ match self.db.apply_atomic_transaction_guarded(
271
+ &transaction_id,
272
+ None,
273
+ None,
274
+ &[],
275
+ &preconditions,
276
+ &mutations,
277
+ None,
278
+ ) {
279
+ Ok(_) => Ok(Applied::Committed(
280
+ writes
281
+ .iter()
282
+ .map(|w| Written {
283
+ collection: w.collection.to_string(),
284
+ id: w.id.clone(),
285
+ version: match &w.expect {
286
+ Expect::Absent => 1,
287
+ Expect::Version { version, .. } => version + 1,
288
+ },
289
+ })
290
+ .collect(),
291
+ )),
292
+ Err(FlowError::PreconditionFailed(failure)) => Err(AgentStateError::Conflict(*failure)),
293
+ Err(other) => Err(AgentStateError::Storage(other)),
294
+ }
295
+ }
296
+
297
+ /// Decide and commit.
298
+ pub fn apply(&self, operation: &Operation) -> Result<Applied, AgentStateError> {
299
+ self.commit(&self.prepare(operation)?)
300
+ }
301
+ }
302
+
303
+ fn precondition(collection: &str, id: &str, expect: &Expect) -> RecordPrecondition {
304
+ let base = RecordPrecondition {
305
+ capability: collection.to_string(),
306
+ key: key(collection, id),
307
+ ..Default::default()
308
+ };
309
+ match expect {
310
+ Expect::Absent => RecordPrecondition {
311
+ require_absent: true,
312
+ ..base
313
+ },
314
+ Expect::Version { version, lease_id } => RecordPrecondition {
315
+ expected_version: Some(*version),
316
+ expected_lease_id: lease_id.clone(),
317
+ ..base
318
+ },
319
+ }
320
+ }