Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions aimdb-client/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,16 @@ frames mapping onto the session engine's role-neutral message set. It declares
version, so a 3.x peer is refused at the handshake (and a WebSocket upgrade
with `?v=3.x`).

### RPC errors

Error replies have the shape `{"t":"reply","id":N,"err":CODE,"msg"?}`.
`not_found`, `unsupported`, `denied` and `internal` describe record lookup,
capability, permission and engine/transport failures. `invalid_value` means the
request was understood but the record's type or codec rejected the supplied
value; the optional `msg` carries the deserializer's explanation, and no write
was applied. Decoders map an unknown future `err` code to `internal`, so adding
codes remains backward-compatible.

### Write timestamps (AimX 4.0)

Every record value on the wire carries `ts`, the time it was written into the
Expand Down
17 changes: 17 additions & 0 deletions aimdb-client/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -589,6 +589,9 @@ fn rpc_err(e: RpcError) -> ClientError {
use drain_record for unread events or subscribe for new ones)",
None,
),
RpcError::InvalidValue(message) => {
ClientError::server_error("invalid_value", message, None)
}
// `Internal` today, plus any future non-exhaustive variant.
_ => ClientError::server_error("internal", "engine/transport failure", None),
}
Expand Down Expand Up @@ -847,4 +850,18 @@ mod tests {
ClientError::ServerError { code, .. } if code == "denied"
));
}

#[test]
fn a_rejected_record_value_keeps_its_own_code_and_detail() {
let err = rpc_err(RpcError::InvalidValue(
"list exceeds maximum length of 2".to_string(),
));
match err {
ClientError::ServerError { code, message, .. } => {
assert_eq!(code, "invalid_value");
assert_eq!(message, "list exceeds maximum length of 2");
}
other => panic!("expected ServerError, got {other:?}"),
}
}
}
70 changes: 70 additions & 0 deletions aimdb-client/tests/aimx_session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,76 @@ async fn aimx_roundtrip_over_uds_production_server() {
drop(conn); // stops the client engine
}

/// A value the record rejects is a caller error, not an engine/transport
/// failure, and the healthy session accepts a corrected write afterwards.
#[tokio::test]
async fn rejected_record_value_is_invalid_value_and_keeps_the_session_alive() {
let key_setting = aimdb_core::Name::<Setting>::new("setting");
let dir = tempfile::tempdir().unwrap();
let sock = dir.path().join("aimdb.sock");

let mut policy = SecurityPolicy::read_write();
policy.allow_write_key("setting");
let config = AimxConfig::uds_default()
.socket_path(sock.to_str().unwrap())
.security_policy(policy);

let mut builder = AimDbBuilder::new()
.runtime(Arc::new(TokioAdapter))
.with_connector(UdsServer::from_config(config));
builder.configure(key_setting, |reg| {
reg.buffer(BufferCfg::SingleLatest).with_remote_access();
});
let (_db, runner) = builder.build().await.expect("build db");
tokio::spawn(runner.run());

let conn = tokio::time::timeout(
Duration::from_secs(5),
AimxConnection::connect(sock.to_str().unwrap()),
)
.await
.expect("connect timed out")
.expect("connect");
tokio::time::timeout(
Duration::from_secs(5),
conn.set_record("setting", json!({ "level": 7 })),
)
.await
.expect("initial accepted set timed out")
.expect("the initial value succeeds");
let err = tokio::time::timeout(
Duration::from_secs(5),
conn.set_record("setting", json!({ "level": "seven" })),
)
.await
.expect("rejected set timed out")
.expect_err("the record rejects a string for u64");
match err {
aimdb_client::ClientError::ServerError { code, message, .. } => {
assert_eq!(code, "invalid_value");
assert!(message.contains("invalid type"), "{message}");
}
other => panic!("expected a typed server error, got {other:?}"),
}

let unchanged = tokio::time::timeout(Duration::from_secs(5), conn.get_record("setting"))
.await
.expect("read after rejected set timed out")
.expect("read after rejected set");
assert_eq!(unchanged.value["level"], 7);

let reply = tokio::time::timeout(
Duration::from_secs(5),
conn.set_record("setting", json!({ "level": 8 })),
)
.await
.expect("accepted set timed out")
.expect("a corrected value succeeds on the same connection");
assert_eq!(reply["value"], json!({ "level": 8 }));

drop(conn);
}

/// One wildcard subscription fans in every matching record: events arrive
/// tagged with the concrete record topic, and matched records with a current
/// value are delivered up front as snapshots.
Expand Down
85 changes: 85 additions & 0 deletions aimdb-core/src/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
//! `RecordValue::as_json` route through it. This mirrors the connector
//! layer's typed route and `IngestFn` callbacks.

use alloc::string::{String, ToString};
use alloc::vec::Vec;
use serde::{de::DeserializeOwned, Serialize};

Expand All @@ -39,6 +40,17 @@ pub trait RemoteSerialize: Sized {
/// Deserialize a JSON value into `Self`, or `None` on schema mismatch.
fn from_json(value: &serde_json::Value) -> Option<Self>;

/// Deserialize a JSON value into `Self`, or explain why it was rejected.
///
/// The default keeps manual [`RemoteSerialize`] implementations source-
/// compatible but cannot recover a specific reason from [`from_json`].
/// The blanket Serde implementation overrides this and preserves the
/// deserializer's message for remote-callers.
fn from_json_with_error(value: &serde_json::Value) -> Result<Self, String> {
Self::from_json(value)
.ok_or_else(|| String::from("the record's JSON codec rejected the value"))
}

/// Serialize this value to owned JSON bytes.
///
/// The default preserves compatibility with manual implementations by
Expand All @@ -59,6 +71,17 @@ pub trait RemoteSerialize: Sized {
let value = serde_json::from_slice(bytes).ok()?;
Self::from_json(&value)
}

/// Deserialize one complete JSON value from `bytes`, or explain the
/// rejection. The blanket Serde implementation preserves both parse and
/// deserialize errors; manual codecs inherit the generic fallback.
fn from_json_slice_with_error(bytes: &[u8]) -> Result<Self, String> {
if let Some(value) = Self::from_json_slice(bytes) {
return Ok(value);
}
let value = serde_json::from_slice(bytes).map_err(|e| e.to_string())?;
Self::from_json_with_error(&value)
}
}

impl<T> RemoteSerialize for T
Expand All @@ -73,13 +96,21 @@ where
serde_json::from_value(value.clone()).ok()
}

fn from_json_with_error(value: &serde_json::Value) -> Result<Self, String> {
serde_json::from_value(value.clone()).map_err(|e| e.to_string())
}

fn to_json_vec(&self) -> Option<Vec<u8>> {
serde_json::to_vec(self).ok()
}

fn from_json_slice(bytes: &[u8]) -> Option<Self> {
serde_json::from_slice(bytes).ok()
}

fn from_json_slice_with_error(bytes: &[u8]) -> Result<Self, String> {
serde_json::from_slice(bytes).map_err(|e| e.to_string())
}
}

/// Type-erased JSON codec for one record type.
Expand All @@ -95,6 +126,16 @@ pub trait JsonCodec<T>: Send + Sync {
/// Decode a JSON value into `T`, or `None` on schema mismatch.
fn decode(&self, value: &serde_json::Value) -> Option<T>;

/// Decode a JSON value into `T`, or explain why the codec rejected it.
///
/// Existing custom codecs keep implementing only [`decode`](Self::decode);
/// they inherit a generic error. [`SerdeJsonCodec`] overrides this to carry
/// the underlying deserializer message.
fn decode_with_error(&self, value: &serde_json::Value) -> Result<T, String> {
self.decode(value)
.ok_or_else(|| String::from("the record's JSON codec rejected the value"))
}

/// Encode a typed value into owned JSON bytes.
///
/// Defaulted through [`encode`](Self::encode) so existing custom codecs
Expand All @@ -111,6 +152,17 @@ pub trait JsonCodec<T>: Send + Sync {
let value = serde_json::from_slice(bytes).ok()?;
self.decode(&value)
}

/// Decode one complete JSON value from a byte slice, or explain the
/// rejection. Custom codecs inherit a parser error followed by the generic
/// [`decode_with_error`](Self::decode_with_error) fallback.
fn decode_slice_with_error(&self, bytes: &[u8]) -> Result<T, String> {
if let Some(value) = self.decode_slice(bytes) {
return Ok(value);
}
let value = serde_json::from_slice(bytes).map_err(|e| e.to_string())?;
self.decode_with_error(&value)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Preserve the byte decoder’s rejection. A custom decode_slice can reject duplicate object keys. This fallback parses the same bytes into serde_json::Value, which collapses the duplicates. If the tree decoder accepts the resulting object, set_from_json_bytes commits a write the codec previously rejected.

Please map self.decode_slice(bytes) returning None directly to a generic error and apply the same change to RemoteSerialize::from_json_slice_with_error. The Serde overrides already preserve detailed errors. A regression test where the byte decoder rejects duplicate keys and the tree decoder accepts the collapsed object would cover this case.

}
}

/// Zero-sized serde-backed [`JsonCodec`].
Expand All @@ -129,13 +181,21 @@ impl<T: RemoteSerialize> JsonCodec<T> for SerdeJsonCodec {
T::from_json(value)
}

fn decode_with_error(&self, value: &serde_json::Value) -> Result<T, String> {
T::from_json_with_error(value)
}

fn encode_to_vec(&self, value: &T) -> Option<Vec<u8>> {
value.to_json_vec()
}

fn decode_slice(&self, bytes: &[u8]) -> Option<T> {
T::from_json_slice(bytes)
}

fn decode_slice_with_error(&self, bytes: &[u8]) -> Result<T, String> {
T::from_json_slice_with_error(bytes)
}
}

#[cfg(test)]
Expand Down Expand Up @@ -243,4 +303,29 @@ mod tests {
);
}
}

#[test]
fn serde_codec_preserves_the_rejection_reason() {
let value_error = <SerdeJsonCodec as JsonCodec<u32>>::decode_with_error(
&SerdeJsonCodec,
&json!("not a number"),
)
.unwrap_err();
assert!(value_error.contains("invalid type"), "{value_error}");

let parse_error = <SerdeJsonCodec as JsonCodec<u32>>::decode_slice_with_error(
&SerdeJsonCodec,
b"not json",
)
.unwrap_err();
assert!(parse_error.contains("expected ident"), "{parse_error}");
}

#[test]
fn custom_codecs_keep_working_with_a_generic_rejection_reason() {
let reason = TreeOnlyCodec
.decode_with_error(&json!({ "name": 7 }))
.unwrap_err();
assert_eq!(reason, "the record's JSON codec rejected the value");
}
}
31 changes: 31 additions & 0 deletions aimdb-core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,19 @@ pub enum DbError {
#[error("Invalid operation '{operation}': {reason}")]
InvalidOperation { operation: String, reason: String },

/// A remote value did not match the record's type or failed its validation.
///
/// This is a caller error: the engine and transport are healthy, and the
/// write was not applied. `reason` is the codec/deserializer's explanation
/// when available.
#[error("Invalid value for record type '{type_name}': {reason}")]
InvalidRecordValue {
/// Fully qualified record value type, for diagnostics.
type_name: String,
/// Why the record's codec rejected the value.
reason: String,
},

/// Permission denied for operation
#[error("Permission denied: {operation}")]
PermissionDenied { operation: String },
Expand Down Expand Up @@ -249,6 +262,14 @@ impl DbError {
}
}

/// Builds an [`InvalidRecordValue`](DbError::InvalidRecordValue).
pub fn invalid_record_value(type_name: impl Into<String>, reason: impl Into<String>) -> Self {
DbError::InvalidRecordValue {
type_name: type_name.into(),
reason: reason.into(),
}
}

/// Builds a [`RecordKeyNotFound`](DbError::RecordKeyNotFound).
pub fn record_key_not_found(key: impl Into<String>) -> Self {
DbError::RecordKeyNotFound { key: key.into() }
Expand Down Expand Up @@ -323,6 +344,8 @@ impl DbError {
| Self::InvalidOperation { .. }
| Self::PermissionDenied { .. } => DbErrorKind::Usage,

Self::InvalidRecordValue { .. } => DbErrorKind::Data,

Self::RuntimeError { .. } | Self::Internal { .. } => DbErrorKind::Internal,

#[cfg(feature = "std")]
Expand Down Expand Up @@ -403,6 +426,10 @@ mod tests {
DbError::permission_denied("write"),
DbError::PermissionDenied { .. }
));
assert!(matches!(
DbError::invalid_record_value("Temperature", "expected f32"),
DbError::InvalidRecordValue { .. }
));
assert!(matches!(
DbError::record_key_not_found("k"),
DbError::RecordKeyNotFound { .. }
Expand Down Expand Up @@ -509,6 +536,10 @@ mod tests {
Usage
);
assert_eq!(DbError::permission_denied("op").kind(), Usage);
assert_eq!(
DbError::invalid_record_value("Temperature", "expected f32").kind(),
Data
);

assert_eq!(DbError::runtime_error("m").kind(), Internal);
assert_eq!(
Expand Down
Loading