Skip to content
Merged
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
5 changes: 5 additions & 0 deletions src/application/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,11 @@ impl CommandSpec {
pub(crate) fn from_contract(
contract: &crate::command::TypedCommandContract,
) -> ApplicationResult<Self> {
contract
.projections
.clone()
.canonicalize_and_validate(&contract.name)
.map_err(ApplicationError::InvalidSpec)?;
let projection_contract = serde_json::to_value(&contract.projections)?;
let applies = serde_json::to_value(&contract.projections.previews)?;
let direct_projection = contract
Expand Down
39 changes: 34 additions & 5 deletions src/command/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ fn command_ledger_fingerprint_preserves_the_v1_canonical_contract() {
// The v1 digest includes historical field/scalar names. Module ownership
// must not change the identity used to recognize a command retry.
let (_, contract) = typed_command::<Input, Succeeded<Payload>>("core.fingerprint").into_parts();
let digest = contract.fingerprint_bytes();
let digest = contract.fingerprint_bytes().unwrap();
let hex: String = digest.iter().map(|byte| format!("{byte:02x}")).collect();
assert_eq!(
hex,
Expand All @@ -23,10 +23,16 @@ fn unsigned_range_is_part_of_command_retry_identity() {
signed.input.fields[0].type_name = "BigInt".into();
let mut unsigned = signed.clone();
unsigned.input.fields[0].unsigned_integer = Some(CommandUnsignedInteger::U64);
assert_ne!(signed.fingerprint_bytes(), unsigned.fingerprint_bytes());
assert_ne!(
signed.fingerprint_bytes().unwrap(),
unsigned.fingerprint_bytes().unwrap()
);
let mut narrower = unsigned.clone();
narrower.input.fields[0].unsigned_integer = Some(CommandUnsignedInteger::U32);
assert_ne!(unsigned.fingerprint_bytes(), narrower.fingerprint_bytes());
assert_ne!(
unsigned.fingerprint_bytes().unwrap(),
narrower.fingerprint_bytes().unwrap()
);
}

#[allow(dead_code)]
Expand Down Expand Up @@ -561,8 +567,14 @@ fn per_route_fingerprint_is_stable_and_contract_sensitive() {
.roles(["admin", "writer"])
.into_contract();

assert_eq!(first.fingerprint_bytes(), reordered.fingerprint_bytes());
assert_ne!(first.fingerprint_bytes(), renamed.fingerprint_bytes());
assert_eq!(
first.fingerprint_bytes().unwrap(),
reordered.fingerprint_bytes().unwrap()
);
assert_ne!(
first.fingerprint_bytes().unwrap(),
renamed.fingerprint_bytes().unwrap()
);
}

#[test]
Expand Down Expand Up @@ -595,3 +607,20 @@ fn binding_canonicalizes_fields_and_roles() {
let second = TypedServiceCommandBinding::from_contracts("todos", &[second]).unwrap();
assert_eq!(first, second);
}

#[test]
fn invalid_projection_declaration_is_an_error_not_a_panic() {
// A hand-built or deserialized contract can carry declaration errors that
// never went through validation; fingerprinting reports them.
let mut contract =
typed_command::<Input, Succeeded<Payload>>("core.invalid-projection").into_contract();
contract
.projections
.declaration_errors
.push("bad declaration".into());
let error = contract.fingerprint_bytes().unwrap_err();
assert!(error.contains("core.invalid-projection"), "{error}");
assert!(error.contains("bad declaration"), "{error}");
assert!(contract.canonical_value().is_err());
assert!(crate::application::CommandSpec::from_contract(&contract).is_err());
}
25 changes: 14 additions & 11 deletions src/command/typed_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,23 @@ impl TypedCommandContract {
/// deployment may add unrelated routes without invalidating safe retries
/// for this command. The explicit domain/version prevents this byte digest
/// from aliasing any other SHA-256 use in the framework.
pub(crate) fn fingerprint_bytes(&self) -> [u8; 32] {
///
/// Fails when the contract's domain-event projections are invalid.
pub(crate) fn fingerprint_bytes(&self) -> Result<[u8; 32], String> {
let mut digest = Sha256::new();
digest.update(b"distributed.typed-command-contract.v1");
digest.update([0]);
digest.update(
serde_json::to_vec(&self.canonical_value())
.expect("canonical typed command contract serialization cannot fail"),
serde_json::to_vec(&self.canonical_value()?)
.expect("serializing a JSON value cannot fail"),
);
digest.finalize().into()
Ok(digest.finalize().into())
}

pub(crate) fn canonical_value(&self) -> serde_json::Value {
/// The contract's canonical JSON. Fails when its domain-event
/// projections are invalid, which a hand-built or deserialized contract
/// can be.
pub(crate) fn canonical_value(&self) -> Result<serde_json::Value, String> {
let mut roles = self.roles.clone();
roles.sort();
roles.dedup();
Expand All @@ -74,10 +79,8 @@ impl TypedCommandContract {
.as_ref()
.map(CommandProjectedModel::canonical_value);
let mut projections = self.projections.clone();
projections
.canonicalize_and_validate(&self.name)
.expect("validated command projection declarations are canonical");
canonical_json(&serde_json::json!({
projections.canonicalize_and_validate(&self.name)?;
Ok(canonical_json(&serde_json::json!({
"name": self.name,
"field_name": self.field_name,
"roles": roles,
Expand All @@ -88,7 +91,7 @@ impl TypedCommandContract {
"projected_model": projected_model,
"direct_projection": direct_projection,
"projections": projections,
}))
})))
}

pub(crate) fn resolve_direct_projection_target_from_session(
Expand Down Expand Up @@ -257,7 +260,7 @@ impl TypedServiceCommandBinding {
contract.name.clone(),
(contract.input_type_id, contract.output_type_id),
);
canonical.push(contract.canonical_value());
canonical.push(contract.canonical_value()?);
}

let material = canonical_json(&serde_json::json!({
Expand Down
4 changes: 2 additions & 2 deletions src/microsvc/service/routes/erased.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,12 @@ pub(in crate::microsvc::service) trait ErasedCausalHandler<D>:
fn contract_fingerprint(&self) -> &CommandContractFingerprint;

/// Bind the Surface-resolved owner of an `Atomic` command's projection.
/// The only way a registered contract changes.
/// The only way a registered contract changes; on error it is unchanged.
#[cfg(feature = "graphql")]
fn bind_direct_projection(
&mut self,
direct_projection: Option<crate::command::CommandDirectProjectionTarget>,
);
) -> Result<(), String>;

#[cfg(any(feature = "graphql", feature = "runtime-tokio"))]
fn storage_identity(&self, dependencies: &D) -> CausalStorageIdentity;
Expand Down
17 changes: 10 additions & 7 deletions src/microsvc/service/routes/execute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,9 @@ where
handle: Arc<PreparedHandlerFn<A, I, K>>,
requires_clock: bool,
requires_scheduling: bool,
) -> Self {
Self {
fingerprint: CommandContractFingerprint::new(contract.fingerprint_bytes()),
) -> Result<Self, String> {
Ok(Self {
fingerprint: CommandContractFingerprint::new(contract.fingerprint_bytes()?),
contract,
guard,
handle,
Expand All @@ -95,7 +95,7 @@ where
#[cfg(feature = "graphql")]
direct_projection_bootstrap: tokio::sync::OnceCell::new(),
_types: std::marker::PhantomData,
}
})
}
}

Expand Down Expand Up @@ -623,9 +623,12 @@ where
fn bind_direct_projection(
&mut self,
direct_projection: Option<crate::command::CommandDirectProjectionTarget>,
) {
self.contract.direct_projection = direct_projection;
self.fingerprint = CommandContractFingerprint::new(self.contract.fingerprint_bytes());
) -> Result<(), String> {
let mut contract = self.contract.clone();
contract.direct_projection = direct_projection;
self.fingerprint = CommandContractFingerprint::new(contract.fingerprint_bytes()?);
self.contract = contract;
Ok(())
}

#[cfg(any(feature = "graphql", feature = "runtime-tokio"))]
Expand Down
16 changes: 12 additions & 4 deletions src/microsvc/service/routes/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -471,7 +471,8 @@ impl<D: Send + Sync + 'static> Routes<D> {
handle,
requires_clock,
requires.contains(&crate::schedule::Capability::Scheduling),
),
)
.unwrap_or_else(|error| panic!("typed command contract cannot compile: {error}")),
)),
);
mount
Expand Down Expand Up @@ -804,16 +805,23 @@ where
{
return Err(GraphqlServiceBindError::TypeIdMismatch);
}
let current_canonical = current_without_owner
.canonical_value()
.map_err(GraphqlServiceBindError::InvalidInventory)?;
let bound_canonical = bound_without_owner
.canonical_value()
.map_err(GraphqlServiceBindError::InvalidInventory)?;
if current.consistency != bound.consistency
|| current.projected_model != bound.projected_model
|| current_without_owner.canonical_value()
!= bound_without_owner.canonical_value()
|| current_canonical != bound_canonical
{
return Err(GraphqlServiceBindError::StructuralFingerprintMismatch(
format!("executable route `{}`", current.name),
));
}
handler.bind_direct_projection(bound.direct_projection.clone());
handler
.bind_direct_projection(bound.direct_projection.clone())
.map_err(GraphqlServiceBindError::InvalidInventory)?;
}
}
Ok(())
Expand Down
Loading
Loading