@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
@@ -0,0 +1,466 @@
1
+ //! # feltdb-client
2
+ //!
3
+ //! A native async Rust client for a FeltDB server (`feltdb-server`): the Rust counterpart of
4
+ //! `@feltdb/core`'s server runtime. It owns no state: every read and write is a request to the
5
+ //! authority, which alone decides what commits.
6
+ //!
7
+ //! ```no_run
8
+ //! use feltdb_client::{Client, Operation, Transaction};
9
+ //! use serde_json::json;
10
+ //!
11
+ //! # async fn run() -> feltdb_client::Result<()> {
12
+ //! let client = Client::builder("http://127.0.0.1:7700")
13
+ //! .token(std::env::var("FELTDB_TOKEN").unwrap_or_default())
14
+ //! .build()?;
15
+ //!
16
+ //! // Several records, one atomic commit. The id makes a retry safe: resubmitting it after an
17
+ //! // uncertain outcome is recognized as a duplicate, never applied twice.
18
+ //! let receipt = client
19
+ //! .commit(
20
+ //! &Transaction::new("ship-o-1")
21
+ //! .operation(Operation::put("orders", "o-1", json!({ "status": "shipped" })))
22
+ //! .operation(Operation::create("audit", "a-1", json!({ "order": "o-1" }))),
23
+ //! )
24
+ //! .await?;
25
+ //! assert!(!receipt.duplicate);
26
+ //!
27
+ //! let order = client.get("orders", "o-1").await?;
28
+ //! # let _ = order;
29
+ //! # Ok(())
30
+ //! # }
31
+ //! ```
32
+ //!
33
+ //! ## Two surfaces, as on the server
34
+ //!
35
+ //! * **The authority** ([`Client`]): records, atomic transactions with preconditions and read-basis
36
+ //! fences, compare-and-set, the bounded query, the committed revision and the event stream. This
37
+ //! is the direct authority surface: the routes `@feltdb/core` uses without an `applicationId`.
38
+ //! * **An application** ([`Application`], from [`Client::application`]): the canonical `/v1`
39
+ //! Service API, scoped to one application and environment and authorized against its contract:
40
+ //! contract discovery, canonical queries, transactions, read bases, events and replay.
41
+ //!
42
+ //! * **The control plane** ([`Control`], from [`Client::control`]): tenants, applications, the
43
+ //! draft → revision → promotion lifecycle of an application's contract, and online backup; and
44
+ //! the server's [`Client::health`].
45
+ //!
46
+ //! Anything else the server exposes is reachable with [`Client::request`].
47
+ //!
48
+ //! ## Outcomes
49
+ //!
50
+ //! A refusal is an [`Error::Api`] carrying the server's stable `code` and, for a refused
51
+ //! transaction, the structured [`PreconditionFailure`]. A write that was sent but not answered is
52
+ //! [`Error::is_outcome_unknown`]: resubmit the same transaction id to learn what happened.
53
+ //!
54
+ //! ## Wire types
55
+ //!
56
+ //! Request and response documents that the server defines in `feltdb` are used directly, so the
57
+ //! two sides cannot disagree about a field: [`ReadSet`], [`ReadBasis`], [`PreconditionFailure`] and
58
+ //! the canonical query and transaction types in [`wire`]. `feltdb` itself is re-exported at the
59
+ //! exact version this client is built against.
60
+
61
+ mod application;
62
+ mod authority;
63
+ mod control;
64
+ mod error;
65
+ mod events;
66
+
67
+ use std::{
68
+ sync::{Arc, RwLock},
69
+ time::Duration,
70
+ };
71
+
72
+ use serde::{de::DeserializeOwned, Serialize};
73
+ use serde_json::Value;
74
+
75
+ pub use application::{
76
+ AppCommit, AppTransaction, Application, ApplicationInfo, ReplayPage, StateVersion,
77
+ };
78
+ pub use authority::{
79
+ BoundedQuery, CasConflict, CasOutcome, CasRequest, CommitReceipt, Condition, Direction,
80
+ Operation, Precondition, QueryPage, Record, Revision, Transaction,
81
+ };
82
+ pub use control::{ApplicationRecord, Control, Health, Promotion, Tenant};
83
+ pub use error::{ApiError, Error, Result};
84
+ pub use events::{EventStream, ServerEvent};
85
+ pub use feltdb;
86
+ pub use feltdb::{
87
+ PreconditionFailure, ReadBasis, ReadCondition, ReadPredicate, ReadRecord, ReadSet,
88
+ TransactionStatus,
89
+ };
90
+ pub use reqwest::Method;
91
+
92
+ /// The canonical application contract's wire types, from `feltdb::state_contract`.
93
+ pub mod wire {
94
+ pub use feltdb::state_contract::{
95
+ AggregateDefinition, AggregateFunction, CanonicalQuery, QueryFilter, QueryOrder,
96
+ QueryReference, QueryResult, SortDirection, TransactionOperation, TransactionOperationKind,
97
+ TransactionPrecondition, TransactionResult,
98
+ };
99
+ }
100
+
101
+ /// The protocol version this client speaks; the server refuses one it does not.
102
+ const PROTOCOL_VERSION: &str = "1";
103
+ const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
104
+
105
+ /// Which authority a request is addressed to, for servers that host several tenants.
106
+ #[derive(Debug, Clone, PartialEq, Eq)]
107
+ enum AuthorityScope {
108
+ Tenant {
109
+ tenant_id: String,
110
+ environment_id: Option<String>,
111
+ },
112
+ Platform,
113
+ }
114
+
115
+ /// Configures a [`Client`].
116
+ #[derive(Debug, Clone)]
117
+ pub struct ClientBuilder {
118
+ url: String,
119
+ token: Option<String>,
120
+ scope: Option<AuthorityScope>,
121
+ timeout: Duration,
122
+ root_certificates: Vec<Vec<u8>>,
123
+ }
124
+
125
+ impl ClientBuilder {
126
+ /// Authenticate with a bearer token: an API key from `feltdb-server keys create`, or an
127
+ /// application session's access token.
128
+ pub fn token(mut self, token: impl Into<String>) -> Self {
129
+ let token = token.into();
130
+ self.token = (!token.is_empty()).then_some(token);
131
+ self
132
+ }
133
+
134
+ /// Bind every request to one tenant. A request the server resolves to another tenant is refused
135
+ /// with `AUTHORITY_SCOPE_MISMATCH` instead of being served.
136
+ pub fn tenant(mut self, tenant_id: impl Into<String>) -> Self {
137
+ self.scope = Some(AuthorityScope::Tenant {
138
+ tenant_id: tenant_id.into(),
139
+ environment_id: None,
140
+ });
141
+ self
142
+ }
143
+
144
+ /// Bind every request to one tenant and one of its environments.
145
+ pub fn tenant_environment(
146
+ mut self,
147
+ tenant_id: impl Into<String>,
148
+ environment_id: impl Into<String>,
149
+ ) -> Self {
150
+ self.scope = Some(AuthorityScope::Tenant {
151
+ tenant_id: tenant_id.into(),
152
+ environment_id: Some(environment_id.into()),
153
+ });
154
+ self
155
+ }
156
+
157
+ /// Address the platform authority rather than a tenant's.
158
+ pub fn platform(mut self) -> Self {
159
+ self.scope = Some(AuthorityScope::Platform);
160
+ self
161
+ }
162
+
163
+ /// How long one request may take before it is abandoned (30 seconds by default). Event streams
164
+ /// are exempt: they stay open until closed.
165
+ pub fn timeout(mut self, timeout: Duration) -> Self {
166
+ self.timeout = timeout;
167
+ self
168
+ }
169
+
170
+ /// Trust a PEM certificate authority in addition to the bundled public roots, for a server
171
+ /// whose certificate a private CA issued. Certificate verification is never disabled. A PEM
172
+ /// that does not parse is refused by [`ClientBuilder::build`].
173
+ pub fn add_root_certificate_pem(mut self, pem: impl Into<Vec<u8>>) -> Self {
174
+ self.root_certificates.push(pem.into());
175
+ self
176
+ }
177
+
178
+ pub fn build(self) -> Result<Client> {
179
+ let url = self.url.trim_end_matches('/').to_owned();
180
+ let parsed = reqwest::Url::parse(&url)
181
+ .map_err(|error| Error::InvalidRequest(format!("server URL {url:?}: {error}")))?;
182
+ if !matches!(parsed.scheme(), "http" | "https") {
183
+ return Err(Error::InvalidRequest(format!(
184
+ "server URL {url:?} must be http or https"
185
+ )));
186
+ }
187
+ let mut http = reqwest::Client::builder();
188
+ for pem in &self.root_certificates {
189
+ // `Certificate::from_pem` accepts anything and adds nothing for input that holds no
190
+ // certificate; parse the bundle so a wrong file is refused here, not at a handshake.
191
+ let certificates = reqwest::Certificate::from_pem_bundle(pem)
192
+ .ok()
193
+ .filter(|certificates| !certificates.is_empty())
194
+ .ok_or_else(|| {
195
+ Error::InvalidRequest("root certificate is not a PEM certificate".into())
196
+ })?;
197
+ for certificate in certificates {
198
+ http = http.add_root_certificate(certificate);
199
+ }
200
+ }
201
+ let http = http
202
+ .build()
203
+ .map_err(|source| Error::transport(source, false))?;
204
+ Ok(Client {
205
+ inner: Arc::new(Inner {
206
+ http,
207
+ url,
208
+ token: RwLock::new(self.token),
209
+ scope: self.scope,
210
+ timeout: self.timeout,
211
+ }),
212
+ })
213
+ }
214
+ }
215
+
216
+ struct Inner {
217
+ http: reqwest::Client,
218
+ url: String,
219
+ token: RwLock<Option<String>>,
220
+ scope: Option<AuthorityScope>,
221
+ timeout: Duration,
222
+ }
223
+
224
+ /// A connection to one FeltDB server. Cheap to clone; clones share the connection pool and token.
225
+ #[derive(Clone)]
226
+ pub struct Client {
227
+ inner: Arc<Inner>,
228
+ }
229
+
230
+ impl std::fmt::Debug for Client {
231
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232
+ f.debug_struct("Client")
233
+ .field("url", &self.inner.url)
234
+ .field("scope", &self.inner.scope)
235
+ .finish_non_exhaustive()
236
+ }
237
+ }
238
+
239
+ impl Client {
240
+ /// Start configuring a client for the server at `url`, e.g. `http://127.0.0.1:7700`.
241
+ pub fn builder(url: impl Into<String>) -> ClientBuilder {
242
+ ClientBuilder {
243
+ url: url.into(),
244
+ token: None,
245
+ scope: None,
246
+ timeout: DEFAULT_TIMEOUT,
247
+ root_certificates: Vec::new(),
248
+ }
249
+ }
250
+
251
+ /// The server URL, without a trailing slash.
252
+ pub fn url(&self) -> &str {
253
+ &self.inner.url
254
+ }
255
+
256
+ /// Replace the bearer token (or clear it with an empty string) for this client and its clones.
257
+ pub fn set_token(&self, token: impl Into<String>) {
258
+ let token = token.into();
259
+ *self
260
+ .inner
261
+ .token
262
+ .write()
263
+ .unwrap_or_else(|poisoned| poisoned.into_inner()) =
264
+ (!token.is_empty()).then_some(token);
265
+ }
266
+
267
+ /// A handle on one application's canonical Service API, in its `production` environment
268
+ /// unless [`Application::environment`] says otherwise.
269
+ pub fn application(&self, application_id: impl Into<String>) -> Application {
270
+ Application::new(self.clone(), application_id.into())
271
+ }
272
+
273
+ /// Any server route, for what this client does not name. `path` starts with `/` and may carry
274
+ /// a query string. An empty success (`204`) is `Value::Null`.
275
+ pub async fn request<B: Serialize + ?Sized>(
276
+ &self,
277
+ method: Method,
278
+ path: &str,
279
+ body: Option<&B>,
280
+ ) -> Result<Value> {
281
+ self.send(method, path, body).await
282
+ }
283
+
284
+ /// [`Client::request`] with extra headers, e.g. a route's `if-version` precondition.
285
+ pub async fn request_with_headers<B: Serialize + ?Sized>(
286
+ &self,
287
+ method: Method,
288
+ path: &str,
289
+ headers: &[(&str, &str)],
290
+ body: Option<&B>,
291
+ ) -> Result<Value> {
292
+ self.send_with_headers(method, path, headers, body).await
293
+ }
294
+
295
+ async fn send_with_headers<T: DeserializeOwned, B: Serialize + ?Sized>(
296
+ &self,
297
+ method: Method,
298
+ path: &str,
299
+ headers: &[(&str, &str)],
300
+ body: Option<&B>,
301
+ ) -> Result<T> {
302
+ let mutating = !matches!(method, Method::GET | Method::HEAD | Method::OPTIONS);
303
+ let mut builder = self.builder_for(method, path).timeout(self.inner.timeout);
304
+ for (name, value) in headers {
305
+ builder = builder.header(*name, *value);
306
+ }
307
+ if let Some(body) = body {
308
+ builder = builder.json(body);
309
+ }
310
+ let response = self.respond(builder, mutating).await?;
311
+ decode(response, mutating).await
312
+ }
313
+
314
+ fn builder_for(&self, method: Method, path: &str) -> reqwest::RequestBuilder {
315
+ let mut builder = self
316
+ .inner
317
+ .http
318
+ .request(method, format!("{}{path}", self.inner.url))
319
+ .header("FeltDB-Protocol", PROTOCOL_VERSION);
320
+ if let Some(token) = self
321
+ .inner
322
+ .token
323
+ .read()
324
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
325
+ .as_deref()
326
+ {
327
+ builder = builder.bearer_auth(token);
328
+ }
329
+ match &self.inner.scope {
330
+ Some(AuthorityScope::Tenant {
331
+ tenant_id,
332
+ environment_id,
333
+ }) => {
334
+ builder = builder.header("FeltDB-Tenant-Id", tenant_id);
335
+ if let Some(environment_id) = environment_id {
336
+ builder = builder.header("FeltDB-Environment-Id", environment_id);
337
+ }
338
+ }
339
+ Some(AuthorityScope::Platform) => {
340
+ builder = builder.header("FeltDB-Authority-Mode", "platform");
341
+ }
342
+ None => {}
343
+ }
344
+ builder
345
+ }
346
+
347
+ /// Send a request and return the raw response, mapping a refusal to [`Error::Api`].
348
+ async fn exchange<B: Serialize + ?Sized>(
349
+ &self,
350
+ method: Method,
351
+ path: &str,
352
+ body: Option<&B>,
353
+ ) -> Result<reqwest::Response> {
354
+ let mutating = !matches!(method, Method::GET | Method::HEAD | Method::OPTIONS);
355
+ let mut builder = self.builder_for(method, path).timeout(self.inner.timeout);
356
+ if let Some(body) = body {
357
+ builder = builder.json(body);
358
+ }
359
+ self.respond(builder, mutating).await
360
+ }
361
+
362
+ async fn respond(
363
+ &self,
364
+ builder: reqwest::RequestBuilder,
365
+ mutating: bool,
366
+ ) -> Result<reqwest::Response> {
367
+ let response = builder
368
+ .send()
369
+ .await
370
+ .map_err(|source| Error::transport(source, mutating))?;
371
+ if response.status().is_success() {
372
+ return Ok(response);
373
+ }
374
+ let status = response.status().as_u16();
375
+ let text = response
376
+ .text()
377
+ .await
378
+ .map_err(|source| Error::transport(source, mutating))?;
379
+ Err(Error::Api(Box::new(ApiError::from_body(status, &text))))
380
+ }
381
+
382
+ async fn send<T: DeserializeOwned, B: Serialize + ?Sized>(
383
+ &self,
384
+ method: Method,
385
+ path: &str,
386
+ body: Option<&B>,
387
+ ) -> Result<T> {
388
+ let mutating = !matches!(method, Method::GET | Method::HEAD | Method::OPTIONS);
389
+ let response = self.exchange(method, path, body).await?;
390
+ decode(response, mutating).await
391
+ }
392
+
393
+ async fn open_events(&self, path: &str, cursor: Option<&str>) -> Result<EventStream> {
394
+ let mut builder = self.builder_for(Method::GET, path);
395
+ if let Some(cursor) = cursor {
396
+ builder = builder.header("Last-Event-ID", cursor);
397
+ }
398
+ let response = builder
399
+ .send()
400
+ .await
401
+ .map_err(|source| Error::transport(source, false))?;
402
+ if !response.status().is_success() {
403
+ let status = response.status().as_u16();
404
+ let text = response
405
+ .text()
406
+ .await
407
+ .map_err(|source| Error::transport(source, false))?;
408
+ return Err(Error::Api(Box::new(ApiError::from_body(status, &text))));
409
+ }
410
+ Ok(EventStream::new(response, cursor.map(str::to_owned)))
411
+ }
412
+ }
413
+
414
+ async fn decode<T: DeserializeOwned>(response: reqwest::Response, mutating: bool) -> Result<T> {
415
+ let status = response.status().as_u16();
416
+ let bytes = response
417
+ .bytes()
418
+ .await
419
+ .map_err(|source| Error::transport(source, mutating))?;
420
+ let bytes: &[u8] = if bytes.is_empty() { b"null" } else { &bytes };
421
+ serde_json::from_slice(bytes).map_err(|source| Error::Decode { status, source })
422
+ }
423
+
424
+ /// Percent-encode one path segment or query value, for paths passed to [`Client::request`].
425
+ /// Identifiers such as revision ids may contain `/` and `:`, which must not reach the path raw.
426
+ pub fn path_segment(value: &str) -> String {
427
+ encode(value)
428
+ }
429
+
430
+ fn encode(value: &str) -> String {
431
+ let mut out = String::with_capacity(value.len());
432
+ for byte in value.bytes() {
433
+ if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
434
+ out.push(byte as char);
435
+ } else {
436
+ out.push_str(&format!("%{byte:02X}"));
437
+ }
438
+ }
439
+ out
440
+ }
441
+
442
+ #[cfg(test)]
443
+ mod tests {
444
+ use super::*;
445
+
446
+ #[test]
447
+ fn path_segments_are_encoded() {
448
+ assert_eq!(encode("o-1"), "o-1");
449
+ assert_eq!(encode("a/b c:é"), "a%2Fb%20c%3A%C3%A9");
450
+ }
451
+
452
+ #[test]
453
+ fn a_url_that_is_not_http_is_refused() {
454
+ assert!(matches!(
455
+ Client::builder("ftp://example.com").build(),
456
+ Err(Error::InvalidRequest(_))
457
+ ));
458
+ assert_eq!(
459
+ Client::builder("http://127.0.0.1:7700/")
460
+ .build()
461
+ .unwrap()
462
+ .url(),
463
+ "http://127.0.0.1:7700"
464
+ );
465
+ }
466
+ }
@@ -0,0 +1,4 @@
1
+ Test-only TLS material for `tests/private_ca.rs`: a throwaway certificate authority
2
+ (`private-ca.pem`) and a `localhost` / `127.0.0.1` server certificate it signed
3
+ (`server.pem`, key `server-key.pem`). The CA's own key was discarded after signing.
4
+ Nothing here protects anything; `tests/` is excluded from the published crate.
@@ -0,0 +1,20 @@
1
+ -----BEGIN CERTIFICATE-----
2
+ MIIDQzCCAiugAwIBAgIUEo4ejwkWMTqDDfYQV4Y+0q94nQswDQYJKoZIhvcNAQEL
3
+ BQAwKDEmMCQGA1UEAwwdZmVsdGRiLWNsaWVudCB0ZXN0IHByaXZhdGUgQ0EwIBcN
4
+ MjYxMDIyMDQxMDI0WhgPMjEyNjA5MjgwNDEwMjRaMCgxJjAkBgNVBAMMHWZlbHRk
5
+ Yi1jbGllbnQgdGVzdCBwcml2YXRlIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
6
+ MIIBCgKCAQEAmlEZ5GPlHa/RoaNGIPG10zIhIUfIzeNLoXtVlov+mYwxl587dlN1
7
+ r9NVuDa03zxD4C/gFiJ3uhnx4D7XYZmv1KmGpMe9TkuwwTQdUzNAW77HR4zhZJ63
8
+ gjJmR9vuFh3ZSZz/4Obo/q7sw9LlioeeBBGuHPSomlX6tJhxbE9RrccwXiJhogZq
9
+ JesAVg1zE3+X8pc/yqxjGR/odCNLS0K0IZdryWAtCgA4jaEBbPZsSdijxVvE8Z7T
10
+ 4oT/ayLcDnBS7RZrEiLlXFnMd7NFxEeVH0Vst1tVJWmysNsZDv6X425KZV+oXK7q
11
+ lSVjL1TnDqsffiATYGW2NaJh2mHoCFlztwIDAQABo2MwYTAdBgNVHQ4EFgQUPtQZ
12
+ FXUMMOsq8/kYn4D00tqjhEMwHwYDVR0jBBgwFo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BAQA+GaxqRADunwafJpff5XzpDISMJnxgN7N43iGYV0zy59r9
15
+ R2YaWs3Q5Q1Us5geh2t9tuAEF67dh+FEqRbsxtiGob8CN5s6lqX6Vqhd3wEI9ay/
16
+ RbHvIjT3yY7yXzwhpCJVVKXO9x+6+UZnD0Iu5MRXNN+8msmSAAHstJ8Y/ldKOpDA
17
+ L/PA+8BmEdDZlaP8m9a+vAlV7zXhLiFz/xjWSWcW/vgt+AZ1SDeMqUh46KRYqrhE
18
+ HYsVuUdu6VRlnnJkc0v8BSb9qfwAxVIsMor9SUizm4eg95m+VEIAQEOt9UjEz5a0
19
+ uxLAOzN5gczgQ9jJFRnC07f5Nrs4tkOzzoBDqC6y
20
+ -----END CERTIFICATE-----
@@ -0,0 +1,95 @@
1
+ //! A server whose certificate a private CA issued: refused by default, served once that CA is
2
+ //! trusted. The fixtures are a test CA and a `localhost`/`127.0.0.1` certificate it signed.
3
+
4
+ use std::sync::Arc;
5
+
6
+ use feltdb_client::{Client, Error, Method};
7
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
8
+ use tokio_rustls::rustls::pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer};
9
+ use tokio_rustls::rustls::ServerConfig;
10
+
11
+ const PRIVATE_CA: &str = include_str!("fixtures/private-ca.pem");
12
+ const SERVER_CERTIFICATE: &str = include_str!("fixtures/server.pem");
13
+ const SERVER_KEY: &str = include_str!("fixtures/server-key.pem");
14
+
15
+ /// An HTTPS server that answers every request with `{"ok":true}`.
16
+ async fn private_ca_server() -> u16 {
17
+ let certificates = CertificateDer::pem_slice_iter(SERVER_CERTIFICATE.as_bytes())
18
+ .collect::<Result<Vec<_>, _>>()
19
+ .unwrap();
20
+ let key = PrivateKeyDer::from_pem_slice(SERVER_KEY.as_bytes()).unwrap();
21
+ let config = ServerConfig::builder()
22
+ .with_no_client_auth()
23
+ .with_single_cert(certificates, key)
24
+ .unwrap();
25
+ let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(config));
26
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
27
+ let port = listener.local_addr().unwrap().port();
28
+ tokio::spawn(async move {
29
+ while let Ok((stream, _)) = listener.accept().await {
30
+ let acceptor = acceptor.clone();
31
+ tokio::spawn(async move {
32
+ // A client that does not trust the CA aborts the handshake.
33
+ let Ok(mut stream) = acceptor.accept(stream).await else {
34
+ return;
35
+ };
36
+ let mut request = Vec::new();
37
+ let mut chunk = [0_u8; 1024];
38
+ while !request.windows(4).any(|window| window == b"\r\n\r\n") {
39
+ match stream.read(&mut chunk).await {
40
+ Ok(0) | Err(_) => return,
41
+ Ok(read) => request.extend_from_slice(&chunk[..read]),
42
+ }
43
+ }
44
+ let body = br#"{"ok":true}"#;
45
+ let head = format!(
46
+ "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
47
+ body.len()
48
+ );
49
+ let _ = stream.write_all(head.as_bytes()).await;
50
+ let _ = stream.write_all(body).await;
51
+ let _ = stream.shutdown().await;
52
+ });
53
+ }
54
+ });
55
+ port
56
+ }
57
+
58
+ #[tokio::test]
59
+ async fn a_private_ca_is_refused_until_it_is_trusted() {
60
+ let port = private_ca_server().await;
61
+ for host in ["localhost", "127.0.0.1"] {
62
+ let url = format!("https://{host}:{port}");
63
+
64
+ let untrusting = Client::builder(&url).build().unwrap();
65
+ let refused = untrusting
66
+ .request::<()>(Method::GET, "/health", None)
67
+ .await
68
+ .unwrap_err();
69
+ assert!(
70
+ matches!(refused, Error::Transport { .. }),
71
+ "{host}: an unknown issuer fails the handshake: {refused:?}"
72
+ );
73
+
74
+ let trusting = Client::builder(&url)
75
+ .add_root_certificate_pem(PRIVATE_CA)
76
+ .build()
77
+ .unwrap();
78
+ let answer = trusting
79
+ .request::<()>(Method::GET, "/health", None)
80
+ .await
81
+ .unwrap();
82
+ assert_eq!(answer, serde_json::json!({ "ok": true }), "{host}");
83
+ }
84
+ }
85
+
86
+ #[test]
87
+ fn a_root_certificate_that_is_not_pem_is_refused() {
88
+ let built = Client::builder("https://localhost:1")
89
+ .add_root_certificate_pem("not a certificate")
90
+ .build();
91
+ assert!(
92
+ matches!(built, Err(Error::InvalidRequest(ref message)) if message.contains("root certificate")),
93
+ "{built:?}"
94
+ );
95
+ }
@@ -2,6 +2,17 @@
2
2
  name = "feltdb-server"
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 = "The FeltDB server: the managed FeltDB authority over HTTP (scoped state, transactions, CAS, history, principals, events), installed as the `feltdb-server` binary"
8
+ license = "MIT"
9
+ repository = "https://github.com/rkendel1/flow_db"
10
+ readme = "README.md"
11
+ keywords = ["database", "server", "transactions", "durable", "feltdb"]
12
+ categories = ["database-implementations", "web-programming::http-server"]
13
+ # The integration tests and benches read repository fixtures by path and cannot run from a
14
+ # packaged copy, so they stay in the repository.
15
+ exclude = ["tests/", "benches/", "target/"]
5
16
 
6
17
  [dependencies]
7
18
  axum = { version = "0.8", features = ["json", "tokio"] }
@@ -10,7 +21,10 @@ argon2 = "0.5"
10
21
  password-hash = "0.5"
11
22
  base64 = "0.22"
12
23
  hmac = "0.12"
13
- feltdb = { path = "../feltdb" }
24
+ # Exact: the server uses `unstable-internals`, which carries no semver promise, so a release of
25
+ # this crate is built against the one `feltdb` release it was tested with. The workspace shares one
26
+ # version, so this moves with every release (a mismatch fails to resolve, it cannot drift silently).
27
+ feltdb = { version = "=0.2.1", path = "../feltdb", features = ["unstable-internals"] }
14
28
  futures-core = "0.3"
15
29
  rand = "0.8"
16
30
  ring = "0.17"
@@ -24,6 +38,11 @@ tracing = "0.1"
24
38
  tracing-subscriber = { version = "0.3", features = ["env-filter"] }
25
39
  uuid = { version = "1.6", features = ["v4"] }
26
40
 
41
+ [dev-dependencies]
42
+ # The Rust client is tested against this server's real binary (tests/rust_client.rs). A path-only
43
+ # dev-dependency is dropped from the published package.
44
+ feltdb-client = { path = "../feltdb-client" }
45
+
27
46
  [[bench]]
28
47
  name = "query_shape_observer"
29
48
  harness = false