diff --git a/src/application/command.rs b/src/application/command.rs index 9b236c90..c6261275 100644 --- a/src/application/command.rs +++ b/src/application/command.rs @@ -352,6 +352,11 @@ impl CommandSpec { pub(crate) fn from_contract( contract: &crate::command::TypedCommandContract, ) -> ApplicationResult { + 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 diff --git a/src/command/tests.rs b/src/command/tests.rs index a60f5002..e983c14e 100644 --- a/src/command/tests.rs +++ b/src/command/tests.rs @@ -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::>("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, @@ -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)] @@ -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] @@ -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::>("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()); +} diff --git a/src/command/typed_command.rs b/src/command/typed_command.rs index bfa70a1d..bcaa4e4e 100644 --- a/src/command/typed_command.rs +++ b/src/command/typed_command.rs @@ -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 { let mut roles = self.roles.clone(); roles.sort(); roles.dedup(); @@ -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, @@ -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( @@ -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!({ diff --git a/src/microsvc/service/routes/erased.rs b/src/microsvc/service/routes/erased.rs index 46583bdd..1cfe29f9 100644 --- a/src/microsvc/service/routes/erased.rs +++ b/src/microsvc/service/routes/erased.rs @@ -95,12 +95,12 @@ pub(in crate::microsvc::service) trait ErasedCausalHandler: 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, - ); + ) -> Result<(), String>; #[cfg(any(feature = "graphql", feature = "runtime-tokio"))] fn storage_identity(&self, dependencies: &D) -> CausalStorageIdentity; diff --git a/src/microsvc/service/routes/execute.rs b/src/microsvc/service/routes/execute.rs index 7b16fc13..ccb0abda 100644 --- a/src/microsvc/service/routes/execute.rs +++ b/src/microsvc/service/routes/execute.rs @@ -84,9 +84,9 @@ where handle: Arc>, requires_clock: bool, requires_scheduling: bool, - ) -> Self { - Self { - fingerprint: CommandContractFingerprint::new(contract.fingerprint_bytes()), + ) -> Result { + Ok(Self { + fingerprint: CommandContractFingerprint::new(contract.fingerprint_bytes()?), contract, guard, handle, @@ -95,7 +95,7 @@ where #[cfg(feature = "graphql")] direct_projection_bootstrap: tokio::sync::OnceCell::new(), _types: std::marker::PhantomData, - } + }) } } @@ -623,9 +623,12 @@ where fn bind_direct_projection( &mut self, direct_projection: Option, - ) { - 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"))] diff --git a/src/microsvc/service/routes/registry.rs b/src/microsvc/service/routes/registry.rs index 2d72b415..693813fb 100644 --- a/src/microsvc/service/routes/registry.rs +++ b/src/microsvc/service/routes/registry.rs @@ -471,7 +471,8 @@ impl Routes { handle, requires_clock, requires.contains(&crate::schedule::Capability::Scheduling), - ), + ) + .unwrap_or_else(|error| panic!("typed command contract cannot compile: {error}")), )), ); mount @@ -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(()) diff --git a/src/postgres_repo/mod.rs b/src/postgres_repo/mod.rs index c27111ea..f0652738 100644 --- a/src/postgres_repo/mod.rs +++ b/src/postgres_repo/mod.rs @@ -2,7 +2,7 @@ //! //! The event-store/snapshot/outbox/inbox logic lives once in //! [`crate::sqlx_repo::repo`]; this module carries only what is genuinely -//! Postgres-specific: the schema SQL, the epoch-`f64`/`to_timestamp()` +//! Postgres-specific: the schema SQL, the integer-microsecond `timestamptz` //! timestamp codec, the unique-violation predicate, and the CTE + //! `FOR UPDATE SKIP LOCKED` outbox claim. It is feature-gated behind //! `postgres` and async-only. @@ -19,8 +19,8 @@ use crate::outbox_worker::ClaimOutboxMessages; use crate::repository::RepositoryError; use crate::sqlx_repo::read_model::quote_identifier; use crate::sqlx_repo::repo::{ - embedded_migrator, outbox_message_from_row, system_time_epoch_secs, SqlxOutboxStore, - SqlxRepository, POSTGRES_MIGRATIONS, + embedded_migrator, outbox_message_from_row, SqlxOutboxStore, SqlxRepository, + POSTGRES_MIGRATIONS, }; use crate::sqlx_repo::{ self, is_postgres_unique_violation, read_model_i64_from_u64 as sqlx_read_model_i64_from_u64, @@ -60,13 +60,13 @@ impl crate::sqlx_repo::repo::SqlxRepoBackend for Postgres { const OWNERSHIP_FENCE_REGISTRATION_LOCK: &'static str = " FOR UPDATE"; const COMMAND_LEDGER_SELECT: &'static str = "command_name, command_contract_hash, \ input_hash, state, causation_id, attempt_token, attempt_number, external_binding, \ - EXTRACT(EPOCH FROM lease_expires_at)::double precision AS lease_expires_at, \ + (EXTRACT(EPOCH FROM lease_expires_at) * 1000000)::bigint AS lease_expires_at, \ outcome::text AS outcome, \ - EXTRACT(EPOCH FROM created_at)::double precision AS created_at, \ - EXTRACT(EPOCH FROM updated_at)::double precision AS updated_at, \ - EXTRACT(EPOCH FROM completed_at)::double precision AS completed_at, \ - EXTRACT(EPOCH FROM retention_expires_at)::double precision AS retention_expires_at, \ - EXTRACT(EPOCH FROM compacted_at)::double precision AS compacted_at"; + (EXTRACT(EPOCH FROM created_at) * 1000000)::bigint AS created_at, \ + (EXTRACT(EPOCH FROM updated_at) * 1000000)::bigint AS updated_at, \ + (EXTRACT(EPOCH FROM completed_at) * 1000000)::bigint AS completed_at, \ + (EXTRACT(EPOCH FROM retention_expires_at) * 1000000)::bigint AS retention_expires_at, \ + (EXTRACT(EPOCH FROM compacted_at) * 1000000)::bigint AS compacted_at"; const COMMAND_LEDGER_LOCK_SUFFIX: &'static str = " FOR UPDATE"; const SCHEDULE_CLAIM_LOCK_SUFFIX: &'static str = " FOR UPDATE SKIP LOCKED"; const COMMAND_LEDGER_COMPACTION_LOCK_SUFFIX: &'static str = " FOR UPDATE SKIP LOCKED"; @@ -77,7 +77,7 @@ impl crate::sqlx_repo::repo::SqlxRepoBackend for Postgres { payload_codec_version, \ metadata::text AS metadata, \ sequence, \ - EXTRACT(EPOCH FROM recorded_at)::double precision AS recorded_at"; + (EXTRACT(EPOCH FROM recorded_at) * 1000000)::bigint AS recorded_at"; const SNAPSHOT_SELECT: &'static str = "aggregate_type, \ aggregate_id, \ version, \ @@ -86,7 +86,7 @@ impl crate::sqlx_repo::repo::SqlxRepoBackend for Postgres { payload_codec, \ payload_codec_version, \ metadata::text AS metadata, \ - EXTRACT(EPOCH FROM recorded_at)::double precision AS recorded_at"; + (EXTRACT(EPOCH FROM recorded_at) * 1000000)::bigint AS recorded_at"; const OUTBOX_SELECT: &'static str = "message_id, \ event_type, \ payload, \ @@ -94,9 +94,9 @@ impl crate::sqlx_repo::repo::SqlxRepoBackend for Postgres { payload_codec_version, \ metadata::text AS metadata, \ status, \ - EXTRACT(EPOCH FROM created_at)::double precision AS created_at, \ + (EXTRACT(EPOCH FROM created_at) * 1000000)::bigint AS created_at, \ claimed_by, \ - EXTRACT(EPOCH FROM claimed_until)::double precision AS claimed_until, \ + (EXTRACT(EPOCH FROM claimed_until) * 1000000)::bigint AS claimed_until, \ attempts, \ last_error, \ destination, \ @@ -105,14 +105,16 @@ impl crate::sqlx_repo::repo::SqlxRepoBackend for Postgres { source_sequence, \ correlation_id, \ causation_id, \ - EXTRACT(EPOCH FROM next_available_at)::double precision AS next_available_at"; + (EXTRACT(EPOCH FROM next_available_at) * 1000000)::bigint AS next_available_at"; const ORDER_BY_CREATED_AT: &'static str = "created_at"; const OUTBOX_OLDEST_CREATED_AT_SELECT: &'static str = - "EXTRACT(EPOCH FROM MIN(created_at))::double precision AS oldest_created_at"; + "(EXTRACT(EPOCH FROM MIN(created_at)) * 1000000)::bigint AS oldest_created_at"; const TABLE_DIALECT: TableSqlDialect = TableSqlDialect::Postgres; - /// Epoch seconds; stored via `to_timestamp(...)` into `timestamptz`. - type TimestampValue = f64; + /// Microseconds since the UNIX epoch, `timestamptz`'s own resolution. + /// Integer microseconds round-trip exactly; `f64` epoch seconds lose + /// about 240 ns at present-day magnitudes. + type TimestampValue = i64; /// sqlx 0.9.0 does not undo a `BEGIN` whose future is dropped before the /// server answers: `transaction_depth` is still zero, so its drop guard @@ -143,44 +145,43 @@ impl crate::sqlx_repo::repo::SqlxRepoBackend for Postgres { is_postgres_unique_violation(err) } - fn timestamp_value(timestamp: SystemTime) -> Result { - system_time_epoch_secs::(timestamp) + fn timestamp_value(timestamp: SystemTime) -> Result { + system_time_epoch_micros(timestamp) } - fn push_timestamp(sep: &mut Separated<'_, Postgres, &'static str>, value: &f64) { - sep.push("to_timestamp(") + fn push_timestamp(sep: &mut Separated<'_, Postgres, &'static str>, value: &i64) { + sep.push(EPOCH_PLUS) .push_bind_unseparated(*value) - .push_unseparated(")"); + .push_unseparated(MICROSECONDS); } fn push_optional_timestamp( sep: &mut Separated<'_, Postgres, &'static str>, - value: Option<&f64>, + value: Option<&i64>, ) { - // NULL stays NULL through to_timestamp; the cast keeps `$n` typed. - sep.push("to_timestamp(") + // NULL stays NULL through the interval product; the cast keeps `$n` typed. + sep.push(EPOCH_PLUS) .push_bind_unseparated(value.copied()) - .push_unseparated("::double precision)"); + .push_unseparated("::bigint") + .push_unseparated(MICROSECONDS); } - fn push_timestamp_assign(builder: &mut QueryBuilder, value: &f64) { - builder.push("to_timestamp("); - builder.push_bind(*value); - builder.push(")"); + fn push_timestamp_assign(builder: &mut QueryBuilder, value: &i64) { + push_micros(builder, *value); } fn push_timestamp_cmp( builder: &mut QueryBuilder, column: &'static str, op: &'static str, - epoch_secs: f64, - ) { + value: SystemTime, + ) -> Result<(), RepositoryError> { builder.push(column); builder.push(" "); builder.push(op); - builder.push(" to_timestamp("); - builder.push_bind(epoch_secs); - builder.push(")"); + builder.push(" "); + push_micros(builder, system_time_epoch_micros(value)?); + Ok(()) } fn push_command_ledger_now(builder: &mut QueryBuilder) { @@ -188,19 +189,20 @@ impl crate::sqlx_repo::repo::SqlxRepoBackend for Postgres { } fn push_command_ledger_now_epoch(builder: &mut QueryBuilder) { - builder.push("EXTRACT(EPOCH FROM clock_timestamp())::double precision"); + builder.push("(EXTRACT(EPOCH FROM clock_timestamp()) * 1000000)::bigint"); } fn push_command_ledger_deadline(builder: &mut QueryBuilder, duration: Duration) { - builder.push("(clock_timestamp() + make_interval(secs => "); - builder.push_bind(duration.as_secs_f64()); - builder.push("))"); + let micros = i64::try_from(duration.as_micros()).unwrap_or(i64::MAX); + builder.push("(clock_timestamp() + ("); + builder.push_bind(micros); + builder.push(MICROSECONDS); + builder.push(")"); } - fn push_command_ledger_deadline_is_live(builder: &mut QueryBuilder, deadline: &f64) { - builder.push("to_timestamp("); - builder.push_bind(*deadline); - builder.push(") > clock_timestamp()"); + fn push_command_ledger_deadline_is_live(builder: &mut QueryBuilder, deadline: &i64) { + push_micros(builder, *deadline); + builder.push(" > clock_timestamp()"); } fn push_command_ledger_json(builder: &mut QueryBuilder, json: &str) { @@ -212,7 +214,7 @@ impl crate::sqlx_repo::repo::SqlxRepoBackend for Postgres { row: &sqlx::postgres::PgRow, column: &'static str, ) -> Result { - system_time_from_epoch_secs(row.try_get(column).map_err(|err| { + system_time_from_epoch_micros(row.try_get(column).map_err(|err| { repository_storage_error(&format!("decode {column} timestamp row"), err) })?) } @@ -221,11 +223,11 @@ impl crate::sqlx_repo::repo::SqlxRepoBackend for Postgres { row: &sqlx::postgres::PgRow, column: &'static str, ) -> Result, RepositoryError> { - row.try_get::, _>(column) + row.try_get::, _>(column) .map_err(|err| { repository_storage_error(&format!("decode {column} timestamp row"), err) })? - .map(system_time_from_epoch_secs) + .map(system_time_from_epoch_micros) .transpose() } @@ -259,11 +261,11 @@ impl crate::sqlx_repo::repo::SqlxRepoBackend for Postgres { } let now = SystemTime::now(); - let now_epoch = system_time_epoch_secs::(now)?; + let now_epoch = system_time_epoch_micros(now)?; let claimed_until = now.checked_add(request.lease).ok_or_else(|| { RepositoryError::Model("failed to compute outbox lease deadline".into()) })?; - let claimed_until_epoch = system_time_epoch_secs::(claimed_until)?; + let claimed_until_epoch = system_time_epoch_micros(claimed_until)?; let limit = sqlx_repository_i64_from_u64( POSTGRES_BACKEND, request.batch_size as u64, @@ -282,8 +284,8 @@ impl crate::sqlx_repo::repo::SqlxRepoBackend for Postgres { SELECT message_id FROM outbox_messages WHERE ( - (status = $1 AND next_available_at <= to_timestamp($2)) - OR (status = $3 AND (claimed_until IS NULL OR claimed_until <= to_timestamp($2))) + (status = $1 AND next_available_at <= TIMESTAMPTZ 'epoch' + $2 * INTERVAL '1 microsecond') + OR (status = $3 AND (claimed_until IS NULL OR claimed_until <= TIMESTAMPTZ 'epoch' + $2 * INTERVAL '1 microsecond')) ) AND ($4::text IS NULL OR destination = $4) AND ($9::text[] IS NULL OR message_id = ANY($9::text[])) @@ -294,7 +296,7 @@ impl crate::sqlx_repo::repo::SqlxRepoBackend for Postgres { UPDATE outbox_messages AS message SET status = $6, claimed_by = $7, - claimed_until = to_timestamp($8), + claimed_until = TIMESTAMPTZ 'epoch' + $8 * INTERVAL '1 microsecond', attempts = attempts + 1, updated_at = now() FROM candidates @@ -306,9 +308,9 @@ impl crate::sqlx_repo::repo::SqlxRepoBackend for Postgres { message.payload_codec_version, message.metadata::text AS metadata, message.status, - EXTRACT(EPOCH FROM message.created_at)::double precision AS created_at, + (EXTRACT(EPOCH FROM message.created_at) * 1000000)::bigint AS created_at, message.claimed_by, - EXTRACT(EPOCH FROM message.claimed_until)::double precision AS claimed_until, + (EXTRACT(EPOCH FROM message.claimed_until) * 1000000)::bigint AS claimed_until, message.attempts, message.last_error, message.destination, @@ -317,7 +319,7 @@ impl crate::sqlx_repo::repo::SqlxRepoBackend for Postgres { message.source_sequence, message.correlation_id, message.causation_id, - EXTRACT(EPOCH FROM message.next_available_at)::double precision AS next_available_at + (EXTRACT(EPOCH FROM message.next_available_at) * 1000000)::bigint AS next_available_at "#, ) .bind(OutboxMessageStatus::Pending.as_str()) @@ -537,13 +539,41 @@ fn push_postgres_type_cast(builder: &mut QueryBuilder, column: &TableC } } -fn system_time_from_epoch_secs(value: f64) -> Result { - if !value.is_finite() || value < 0.0 { - return Err(RepositoryError::Model(format!( - "postgres recorded_at epoch value {value} is invalid" - ))); - } - Ok(UNIX_EPOCH + Duration::from_secs_f64(value)) +/// `timestamptz` written from integer microseconds: `EPOCH_PLUS $n MICROSECONDS`. +const EPOCH_PLUS: &str = "(TIMESTAMPTZ 'epoch' + "; +const MICROSECONDS: &str = " * INTERVAL '1 microsecond')"; + +fn push_micros(builder: &mut QueryBuilder, micros: i64) { + builder.push(EPOCH_PLUS); + builder.push_bind(micros); + builder.push(MICROSECONDS); +} + +/// Microseconds since the UNIX epoch, truncating sub-microsecond precision +/// that `timestamptz` cannot store. +fn system_time_epoch_micros(timestamp: SystemTime) -> Result { + let micros = timestamp + .duration_since(UNIX_EPOCH) + .map_err(|err| { + RepositoryError::Model(format!( + "timestamp before UNIX epoch cannot be stored in postgres: {err}" + )) + })? + .as_micros(); + i64::try_from(micros).map_err(|_| { + RepositoryError::Model(format!( + "timestamp {micros} us after the UNIX epoch does not fit postgres timestamptz" + )) + }) +} + +fn system_time_from_epoch_micros(micros: i64) -> Result { + let micros = u64::try_from(micros).map_err(|_| { + RepositoryError::Model(format!( + "postgres timestamp {micros} us is before the UNIX epoch" + )) + })?; + Ok(UNIX_EPOCH + Duration::from_micros(micros)) } fn repository_storage_error(operation: &str, err: sqlx::Error) -> RepositoryError { diff --git a/src/sqlite_repo/mod.rs b/src/sqlite_repo/mod.rs index 99ceccb7..01b33bc4 100644 --- a/src/sqlite_repo/mod.rs +++ b/src/sqlite_repo/mod.rs @@ -24,7 +24,7 @@ use crate::outbox_worker::ClaimOutboxMessages; use crate::repository::RepositoryError; use crate::sqlx_repo::read_model::quote_identifier; use crate::sqlx_repo::repo::{ - embedded_migrator, SqlxOutboxStore, SqlxRepository, SQLITE_MIGRATIONS, + embedded_migrator, system_time_epoch_secs, SqlxOutboxStore, SqlxRepository, SQLITE_MIGRATIONS, }; use crate::sqlx_repo::{ self, is_sqlite_unique_constraint, read_model_i64_from_u64 as sqlx_read_model_i64_from_u64, @@ -109,14 +109,15 @@ impl crate::sqlx_repo::repo::SqlxRepoBackend for Sqlite { builder: &mut QueryBuilder, column: &'static str, op: &'static str, - epoch_secs: f64, - ) { + value: SystemTime, + ) -> Result<(), RepositoryError> { builder.push("CAST("); builder.push(column); builder.push(" AS REAL) "); builder.push(op); builder.push(" "); - builder.push_bind(epoch_secs); + builder.push_bind(system_time_epoch_secs::(value)?); + Ok(()) } fn push_command_ledger_now(builder: &mut QueryBuilder) { diff --git a/src/sqlx_repo/repo/backend.rs b/src/sqlx_repo/repo/backend.rs index abc698b0..ad54bcc6 100644 --- a/src/sqlx_repo/repo/backend.rs +++ b/src/sqlx_repo/repo/backend.rs @@ -343,8 +343,8 @@ pub trait SqlxRepoBackend: SqlxReadModelBackend { /// Encode a [`SystemTime`] into this backend's stored representation. fn timestamp_value(timestamp: SystemTime) -> Result; - /// Push a timestamp value into a separated bind list (Postgres wraps the - /// bind in `to_timestamp(...)`). + /// Push a timestamp value into a separated bind list (Postgres turns the + /// microsecond bind into a `timestamptz`). fn push_timestamp(sep: &mut Separated<'_, Self, &'static str>, value: &Self::TimestampValue); /// Push an optional timestamp value into a separated bind list, binding a @@ -357,15 +357,15 @@ pub trait SqlxRepoBackend: SqlxReadModelBackend { /// Push ` = ` right-hand side into a builder. fn push_timestamp_assign(builder: &mut QueryBuilder, value: &Self::TimestampValue); - /// Push ` ` comparing a stored timestamp column against - /// epoch seconds (Postgres: `column op to_timestamp($n)`; SQLite: - /// `CAST(column AS REAL) op ?`). + /// Push ` ` comparing a stored timestamp column + /// against `value` in the backend's exact encoding (Postgres: integer + /// microseconds into `timestamptz`; SQLite: `CAST(column AS REAL) op ?`). fn push_timestamp_cmp( builder: &mut QueryBuilder, column: &'static str, op: &'static str, - epoch_secs: f64, - ); + value: SystemTime, + ) -> Result<(), RepositoryError>; /// Push a non-transaction-start database clock expression. PostgreSQL uses /// `clock_timestamp()` so time spent waiting for a row lock counts against @@ -375,7 +375,8 @@ pub trait SqlxRepoBackend: SqlxReadModelBackend { /// Push the same database clock as epoch seconds for decoding into /// [`SystemTime`]. This is distinct from [`Self::push_command_ledger_now`] /// because PostgreSQL write/comparison expressions require `timestamptz` - /// while this framework's portable timestamp decoder consumes `f64`. + /// while the decoder reads the backend's encoded value (Postgres: integer + /// microseconds). fn push_command_ledger_now_epoch(builder: &mut QueryBuilder); /// Push database-now plus a caller-validated positive duration. diff --git a/src/sqlx_repo/repo/executor.rs b/src/sqlx_repo/repo/executor.rs index 90725414..9d418f24 100644 --- a/src/sqlx_repo/repo/executor.rs +++ b/src/sqlx_repo/repo/executor.rs @@ -65,12 +65,7 @@ where operator, value, } => { - DB::push_timestamp_cmp( - &mut builder, - column, - operator, - system_time_epoch_secs::(*value)?, - ); + DB::push_timestamp_cmp(&mut builder, column, operator, *value)?; } SqlPart::LedgerNow => DB::push_command_ledger_now(&mut builder), SqlPart::LedgerNowEpoch => DB::push_command_ledger_now_epoch(&mut builder), diff --git a/src/sqlx_repo/repo/mod.rs b/src/sqlx_repo/repo/mod.rs index 303bc32f..2d42a416 100644 --- a/src/sqlx_repo/repo/mod.rs +++ b/src/sqlx_repo/repo/mod.rs @@ -5,7 +5,7 @@ //! pattern to the whole repository surface: the SQL statements and row codecs //! are identical across the two backends because `QueryBuilder` renders the //! right placeholder dialect. What genuinely differs — schema SQL, bind-param -//! chunking, the timestamp codec (Postgres epoch-`f64`/`to_timestamp()` vs +//! chunking, the timestamp codec (Postgres integer-microsecond `timestamptz` vs //! SQLite `"secs.nanos"` text), the unique-violation predicate, conflict //! recovery (SQLite can re-read in the failed transaction; a failed Postgres //! statement aborts it), and the outbox `claim` strategy — lives behind the diff --git a/tests/common/src/repository/storage.rs b/tests/common/src/repository/storage.rs index 5fc536f9..c61caa0c 100644 --- a/tests/common/src/repository/storage.rs +++ b/tests/common/src/repository/storage.rs @@ -460,6 +460,12 @@ where assert_eq!(claimed, ["immediate", "past"]); } +/// `at` truncated to a whole millisecond, which every backend round-trips. +fn whole_millis(at: SystemTime) -> SystemTime { + let since = at.duration_since(SystemTime::UNIX_EPOCH).unwrap(); + SystemTime::UNIX_EPOCH + Duration::from_millis(since.as_millis() as u64) +} + /// A scheduled row outlives the process that wrote it and fires once due; a /// row released with no delay is claimable again at once. pub async fn scheduled_message_survives_restart_and_fires_when_due(backend: &B) @@ -472,7 +478,7 @@ where let timer_id = unique_id("timer"); let timer = OutboxMessage::create_to(&timer_id, "Timeout", "saga", b"t".to_vec()) .unwrap() - .deliver_after(SystemTime::now(), delay); + .deliver_after(whole_millis(SystemTime::now()), delay); let due_at = timer.deliver_at.unwrap(); backend .repository() @@ -484,16 +490,9 @@ where let outbox = B::outbox_store(&reopened); let pending = outbox.pending(10).await.unwrap(); assert_eq!(pending.len(), 1); - // To the millisecond: Postgres reads the timestamp back through a float - // and loses sub-microsecond precision. - let persisted = pending[0].deliver_at.expect("schedule persisted"); - let skew = persisted - .duration_since(due_at) - .unwrap_or_else(|error| error.duration()); - assert!( - skew < Duration::from_millis(1), - "schedule persisted: {persisted:?} vs {due_at:?}" - ); + // Exact: every backend stores at least microsecond resolution, and the + // schedule above is a whole millisecond. + assert_eq!(pending[0].deliver_at, Some(due_at), "schedule persisted"); let early = outbox .claim(ClaimOutboxMessages::new("w", 10, LEASE)) .await