use crate::{
key::{StableKey, StableKeyError},
schema::SchemaMetadata,
slot::{MemoryManagerSlot, MemoryManagerSlotError},
text::{DiagnosticTextError, validate_diagnostic_text},
};
use serde::{Deserialize, Deserializer, Serialize, de::Error as _};
use std::collections::BTreeSet;
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct AllocationDeclaration {
pub(crate) stable_key: StableKey,
pub(crate) slot: MemoryManagerSlot,
#[serde(deserialize_with = "deserialize_label")]
pub(crate) label: Option<String>,
pub(crate) schema: SchemaMetadata,
}
impl AllocationDeclaration {
pub fn new(
stable_key: impl AsRef<str>,
slot: MemoryManagerSlot,
label: Option<String>,
schema: SchemaMetadata,
) -> Result<Self, DeclarationSnapshotError> {
let stable_key = StableKey::parse(stable_key).map_err(DeclarationSnapshotError::Key)?;
validate_label(label.as_deref())?;
Ok(Self {
stable_key,
slot,
label,
schema,
})
}
pub fn memory_manager(
stable_key: impl AsRef<str>,
id: u8,
label: impl Into<String>,
) -> Result<Self, DeclarationSnapshotError> {
Self::memory_manager_with_schema(stable_key, id, label, SchemaMetadata::default())
}
pub fn memory_manager_unlabeled(
stable_key: impl AsRef<str>,
id: u8,
) -> Result<Self, DeclarationSnapshotError> {
Self::memory_manager_unlabeled_with_schema(stable_key, id, SchemaMetadata::default())
}
pub fn memory_manager_with_schema(
stable_key: impl AsRef<str>,
id: u8,
label: impl Into<String>,
schema: SchemaMetadata,
) -> Result<Self, DeclarationSnapshotError> {
let slot =
MemoryManagerSlot::new(id).map_err(DeclarationSnapshotError::MemoryManagerSlot)?;
Self::new(stable_key, slot, Some(label.into()), schema)
}
pub fn memory_manager_unlabeled_with_schema(
stable_key: impl AsRef<str>,
id: u8,
schema: SchemaMetadata,
) -> Result<Self, DeclarationSnapshotError> {
let slot =
MemoryManagerSlot::new(id).map_err(DeclarationSnapshotError::MemoryManagerSlot)?;
Self::new(stable_key, slot, None, schema)
}
#[must_use]
pub const fn stable_key(&self) -> &StableKey {
&self.stable_key
}
#[must_use]
pub const fn slot(&self) -> &MemoryManagerSlot {
&self.slot
}
#[must_use]
pub fn label(&self) -> Option<&str> {
self.label.as_deref()
}
#[must_use]
pub const fn schema(&self) -> &SchemaMetadata {
&self.schema
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct DeclarationSnapshot {
declarations: Vec<AllocationDeclaration>,
runtime_fingerprint: Option<String>,
}
impl<'de> Deserialize<'de> for DeclarationSnapshot {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
#[serde(rename = "DeclarationSnapshot", deny_unknown_fields)]
struct Snapshot {
#[serde(deserialize_with = "crate::cbor::deserialize_records")]
declarations: Vec<AllocationDeclaration>,
#[serde(deserialize_with = "crate::cbor::deserialize_present_option")]
runtime_fingerprint: Option<String>,
}
let snapshot = Snapshot::deserialize(deserializer)?;
let checked = Self::new(snapshot.declarations).map_err(D::Error::custom)?;
match snapshot.runtime_fingerprint {
Some(fingerprint) => checked
.with_runtime_fingerprint(fingerprint)
.map_err(D::Error::custom),
None => Ok(checked),
}
}
}
impl DeclarationSnapshot {
pub fn new(declarations: Vec<AllocationDeclaration>) -> Result<Self, DeclarationSnapshotError> {
validate_declaration_set(&declarations)?;
Ok(Self {
declarations,
runtime_fingerprint: None,
})
}
pub fn with_runtime_fingerprint(
mut self,
fingerprint: impl Into<String>,
) -> Result<Self, DeclarationSnapshotError> {
let fingerprint = fingerprint.into();
validate_runtime_fingerprint(Some(&fingerprint))?;
self.runtime_fingerprint = Some(fingerprint);
Ok(self)
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.declarations.is_empty()
}
#[must_use]
pub const fn len(&self) -> usize {
self.declarations.len()
}
#[must_use]
pub fn declarations(&self) -> &[AllocationDeclaration] {
&self.declarations
}
#[must_use]
pub fn runtime_fingerprint(&self) -> Option<&str> {
self.runtime_fingerprint.as_deref()
}
pub(crate) fn into_parts(self) -> (Vec<AllocationDeclaration>, Option<String>) {
(self.declarations, self.runtime_fingerprint)
}
}
#[non_exhaustive]
#[derive(Clone, Debug, Eq, thiserror::Error, PartialEq)]
pub enum DeclarationSnapshotError {
#[error("at most 255 allocation declarations are supported")]
TooManyDeclarations,
#[error(transparent)]
Key(StableKeyError),
#[error(transparent)]
MemoryManagerSlot(MemoryManagerSlotError),
#[error("stable key '{0}' is declared more than once")]
DuplicateStableKey(StableKey),
#[error("allocation slot '{0:?}' is declared more than once")]
DuplicateSlot(MemoryManagerSlot),
#[error("allocation declaration label must not be empty when present")]
EmptyLabel,
#[error("allocation declaration label must be at most 256 bytes")]
LabelTooLong,
#[error("allocation declaration label must be ASCII")]
NonAsciiLabel,
#[error("allocation declaration label must not contain ASCII control characters")]
ControlCharacterLabel,
#[error("runtime_fingerprint must not be empty when present")]
EmptyRuntimeFingerprint,
#[error("runtime_fingerprint must be at most 256 bytes")]
RuntimeFingerprintTooLong,
#[error("runtime_fingerprint must be ASCII")]
NonAsciiRuntimeFingerprint,
#[error("runtime_fingerprint must not contain ASCII control characters")]
ControlCharacterRuntimeFingerprint,
}
fn validate_label(label: Option<&str>) -> Result<(), DeclarationSnapshotError> {
let Some(label) = label else {
return Ok(());
};
validate_diagnostic_text(label).map_err(|error| match error {
DiagnosticTextError::Empty => DeclarationSnapshotError::EmptyLabel,
DiagnosticTextError::TooLong => DeclarationSnapshotError::LabelTooLong,
DiagnosticTextError::NonAscii => DeclarationSnapshotError::NonAsciiLabel,
DiagnosticTextError::ControlCharacter => DeclarationSnapshotError::ControlCharacterLabel,
})
}
fn deserialize_label<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<Option<String>, D::Error> {
let label = Option::<String>::deserialize(deserializer)?;
validate_label(label.as_deref()).map_err(D::Error::custom)?;
Ok(label)
}
pub fn validate_runtime_fingerprint(
fingerprint: Option<&str>,
) -> Result<(), DeclarationSnapshotError> {
let Some(fingerprint) = fingerprint else {
return Ok(());
};
validate_diagnostic_text(fingerprint).map_err(|error| match error {
DiagnosticTextError::Empty => DeclarationSnapshotError::EmptyRuntimeFingerprint,
DiagnosticTextError::TooLong => DeclarationSnapshotError::RuntimeFingerprintTooLong,
DiagnosticTextError::NonAscii => DeclarationSnapshotError::NonAsciiRuntimeFingerprint,
DiagnosticTextError::ControlCharacter => {
DeclarationSnapshotError::ControlCharacterRuntimeFingerprint
}
})
}
fn validate_declaration_set(
declarations: &[AllocationDeclaration],
) -> Result<(), DeclarationSnapshotError> {
if declarations.len() > crate::constants::MAX_ALLOCATIONS {
return Err(DeclarationSnapshotError::TooManyDeclarations);
}
let mut keys = BTreeSet::new();
let mut slots = [false; crate::constants::MAX_ALLOCATIONS];
for declaration in declarations {
let occupied = &mut slots[usize::from(declaration.slot.id())];
if *occupied {
return Err(DeclarationSnapshotError::DuplicateSlot(
declaration.slot.clone(),
));
}
*occupied = true;
if !keys.insert(&declaration.stable_key) {
return Err(DeclarationSnapshotError::DuplicateStableKey(
declaration.stable_key.clone(),
));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::slot::MemoryManagerSlot;
fn declaration(key: &str, id: u8) -> AllocationDeclaration {
AllocationDeclaration::new(
key,
MemoryManagerSlot::new(id).expect("usable slot"),
None,
SchemaMetadata::default(),
)
.expect("declaration")
}
#[test]
fn declaration_rejects_unbounded_label_metadata() {
let err = AllocationDeclaration::new(
"app.users.v1",
MemoryManagerSlot::new(100).expect("usable slot"),
Some("x".repeat(257)),
SchemaMetadata::default(),
)
.expect_err("label too long");
assert_eq!(err, DeclarationSnapshotError::LabelTooLong);
}
#[test]
fn memory_manager_declaration_constructor_builds_common_declaration() {
let declaration = AllocationDeclaration::memory_manager("app.orders.v1", 100, "orders")
.expect("declaration");
assert_eq!(declaration.stable_key.as_str(), "app.orders.v1");
assert_eq!(
declaration.slot,
MemoryManagerSlot::new(100).expect("usable slot")
);
assert_eq!(declaration.label.as_deref(), Some("orders"));
assert_eq!(declaration.schema, SchemaMetadata::default());
}
#[test]
fn memory_manager_declaration_constructor_rejects_invalid_slot() {
let err = AllocationDeclaration::memory_manager("app.orders.v1", u8::MAX, "orders")
.expect_err("sentinel must fail");
assert!(matches!(
err,
DeclarationSnapshotError::MemoryManagerSlot(_)
));
}
#[test]
fn snapshot_decode_rejects_unusable_memory_manager_slot() {
let snapshot = DeclarationSnapshot::new(vec![declaration("app.orders.v1", 100)]).unwrap();
let mut value = serde_json::to_value(snapshot).unwrap();
value["declarations"][0]["slot"]["slot"]["MemoryManagerId"] = serde_json::json!(255);
assert!(serde_json::from_value::<DeclarationSnapshot>(value).is_err());
}
#[test]
fn snapshot_rejects_unbounded_runtime_fingerprint() {
let snapshot =
DeclarationSnapshot::new(vec![declaration("app.users.v1", 100)]).expect("snapshot");
let err = snapshot
.with_runtime_fingerprint("x".repeat(257))
.expect_err("fingerprint too long");
assert_eq!(err, DeclarationSnapshotError::RuntimeFingerprintTooLong);
}
#[test]
fn rejects_duplicate_keys() {
let err = DeclarationSnapshot::new(vec![
declaration("app.users.v1", 100),
declaration("app.users.v1", 101),
])
.expect_err("duplicate key");
assert_eq!(
err,
DeclarationSnapshotError::DuplicateStableKey(StableKey::parse("app.users.v1").unwrap())
);
}
#[test]
fn rejects_duplicate_slots() {
for second_key in ["app.orders.v1", "app.users.v1"] {
let err = DeclarationSnapshot::new(vec![
declaration("app.users.v1", 100),
declaration(second_key, 100),
])
.expect_err("duplicate slot precedes duplicate key");
assert_eq!(
err,
DeclarationSnapshotError::DuplicateSlot(MemoryManagerSlot::new(100).unwrap())
);
}
}
}