From 6f0bda326c692fede383f459ffd18cffed6c1136 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 14:18:29 +0100 Subject: [PATCH 1/3] refactor(core): name every event kind in one enum Event kinds were string literals in the store, the daemon's telemetry and exec recording, and core's timeline. `EventKind` in piqueld-core names each one, with a doc comment, and every place that records or compares a kind uses its variant, including SQL, where the kind is now a bound parameter. `Event.kind` stays a `String`: history holds kinds older daemons recorded, and clients may read kinds a newer daemon adds. It is compared through `Event::known_kind` or `==`, as `ApiErrorCode` is. The denial-burst query keeps its literal, since its partial index only serves a literal. Part of PQD-161 --- apps/piqueld/src/api/service/exec.rs | 7 +- apps/piqueld/src/telemetry/journal.rs | 56 +++--- crates/piqueld-core/src/api/error_code.rs | 22 +-- crates/piqueld-core/src/event.rs | 179 ++++++++++++++++++ crates/piqueld-core/src/lib.rs | 2 +- crates/piqueld-core/src/names.rs | 26 +++ crates/piqueld-core/src/timeline.rs | 26 ++- crates/piqueld-store/src/acceptance.rs | 7 +- crates/piqueld-store/src/auth/security.rs | 24 +-- crates/piqueld-store/src/environment/mod.rs | 20 +- crates/piqueld-store/src/journal.rs | 22 ++- .../piqueld-store/src/observability/event.rs | 32 +++- crates/piqueld-store/src/observability/mod.rs | 5 +- .../src/observability/notifications.rs | 40 ++-- crates/piqueld-store/src/operation.rs | 47 +++-- crates/piqueld-store/src/preview/mod.rs | 3 +- crates/piqueld-store/src/promotion/mod.rs | 3 +- crates/piqueld-store/src/repository.rs | 13 +- crates/piqueld-store/src/restore/mod.rs | 7 +- crates/piqueld-store/src/secret/deletion.rs | 3 +- crates/piqueld-store/src/secret/key.rs | 6 +- crates/piqueld-store/src/secret/mod.rs | 6 +- crates/piqueld-store/src/secret/stored/mod.rs | 8 +- crates/piqueld-store/src/status.rs | 14 +- crates/piqueld-store/src/stopped.rs | 5 +- crates/piqueld-store/src/sync.rs | 19 +- crates/piqueld-store/src/telemetry.rs | 11 +- crates/piqueld-store/src/timeline.rs | 5 +- docs/dev/rust-conventions.md | 8 + 29 files changed, 461 insertions(+), 165 deletions(-) diff --git a/apps/piqueld/src/api/service/exec.rs b/apps/piqueld/src/api/service/exec.rs index 9dad27662..78383d181 100644 --- a/apps/piqueld/src/api/service/exec.rs +++ b/apps/piqueld/src/api/service/exec.rs @@ -1,5 +1,6 @@ //! One-off commands in running service tasks, recorded in environment history. use super::{Actor, ApplicationError, ApplicationService}; +use piqueld_core::EventKind; use piqueld_core::{ ApplicationId, EnvironmentId, ServiceName, access::AppPermission, auth::HostOperator, exec::ExecRequest, @@ -89,7 +90,7 @@ impl ExecSession { /// including a disconnected client. pub async fn run(self, io: ExecIo) -> Result { self.record( - "command_started", + EventKind::CommandStarted, &format!("{} started a command in task {}", self.who, self.exec.task), ) .await?; @@ -103,7 +104,7 @@ impl ExecSession { Ok(code) => format!("Command in task {} exited with code {code}", self.exec.task), Err(_) => format!("Command stream in task {} failed", self.exec.task), }; - if let Err(error) = self.record("command_finished", &message).await { + if let Err(error) = self.record(EventKind::CommandFinished, &message).await { tracing::error!(?error, task = %self.exec.task, "could not record command completion"); } Ok(result?) @@ -111,7 +112,7 @@ impl ExecSession { /// Records `kind` with `message` in the environment's history, attributed /// to whoever started the command. - async fn record(&self, kind: &str, message: &str) -> Result<(), ApplicationError> { + async fn record(&self, kind: EventKind, message: &str) -> Result<(), ApplicationError> { Ok(self .owner .store diff --git a/apps/piqueld/src/telemetry/journal.rs b/apps/piqueld/src/telemetry/journal.rs index 6158ce414..82175c4d6 100644 --- a/apps/piqueld/src/telemetry/journal.rs +++ b/apps/piqueld/src/telemetry/journal.rs @@ -27,7 +27,7 @@ use opentelemetry_sdk::trace::{SpanData, SpanEvents, SpanLinks}; use piqueld_core::Phase; use piqueld_core::observability::DiagnosticCode; use piqueld_core::operation::OperationKind; -use piqueld_core::{Event, Operation}; +use piqueld_core::{Event, EventKind, Operation}; use sha2::{Digest as _, Sha256}; use std::collections::HashMap; use std::time::{Duration, SystemTime}; @@ -73,26 +73,21 @@ impl Journal { /// Whether recording `event` needs its operation as stored now. pub(crate) fn needs_operation(event: &Event) -> bool { - Self::attempt_outcome(&event.kind).is_some() + event.known_kind().and_then(Self::attempt_outcome).is_some() } - /// Event kinds that may end an attempt and, with it, the operation, with - /// the attempt's outcome. - const ENDS_ATTEMPTS: [(&str, &str); 6] = [ - ("operation_succeeded", "succeeded"), - ("operation_failed", "failed"), - ("operation_cancelled", "cancelled"), - ("operation_superseded", "superseded"), - ("operation_interrupted", "interrupted"), - ("reconciliation_requested", "requeued"), - ]; - - /// The outcome of the attempt an event of `kind` ends, if it ends one. - fn attempt_outcome(kind: &str) -> Option<&'static str> { - Self::ENDS_ATTEMPTS - .iter() - .find(|(ends, _)| *ends == kind) - .map(|(_, outcome)| *outcome) + /// The outcome of the attempt an event of `kind` ends, if it may end + /// one and, with it, the operation. + fn attempt_outcome(kind: EventKind) -> Option<&'static str> { + Some(match kind { + EventKind::OperationSucceeded => "succeeded", + EventKind::OperationFailed => "failed", + EventKind::OperationCancelled => "cancelled", + EventKind::OperationSuperseded => "superseded", + EventKind::OperationInterrupted => "interrupted", + EventKind::ReconciliationRequested => "requeued", + _ => return None, + }) } /// Exports `event` as a log record, plus any span it ends and the @@ -107,8 +102,11 @@ impl Journal { /// Builds the spans `event` ends, recording deployment and build metrics /// along the way. fn spans(&mut self, event: &Event, context: EventContext<'_>) -> Vec { - match event.kind.as_str() { - "operation_started" => { + let Some(kind) = event.known_kind() else { + return Vec::new(); + }; + match kind { + EventKind::OperationStarted => { if let (Some(operation), Some(attempt)) = (&event.operation_id, event.attempt) { if self.open.len() >= OPEN_ATTEMPTS { self.open.clear(); @@ -118,9 +116,9 @@ impl Journal { } Vec::new() } - "action_succeeded" | "action_failed" | "action_outcome_unknown" => { - self.action(event, context).into_iter().collect() - } + EventKind::ActionSucceeded + | EventKind::ActionFailed + | EventKind::ActionOutcomeUnknown => self.action(event, context).into_iter().collect(), kind => Self::attempt_outcome(kind) .map_or_default(|outcome| self.operation(event, context, outcome)), } @@ -129,9 +127,9 @@ impl Journal { /// The span of a finished action, and its build metrics. fn action(&self, event: &Event, context: EventContext<'_>) -> Option { let action = event.action_id.as_deref()?; - let outcome = match event.kind.as_str() { - "action_succeeded" => "succeeded", - "action_failed" => "failed", + let outcome = match event.known_kind() { + Some(EventKind::ActionSucceeded) => "succeeded", + Some(EventKind::ActionFailed) => "failed", _ => "unknown", }; let duration = event.duration_ms.map(Duration::from_millis); @@ -203,7 +201,7 @@ impl Journal { Some(operation.created_at_ms), operation.attempt, ), - None if event.kind == "operation_succeeded" => { + None if event.kind == EventKind::OperationSucceeded => { (None, None, event.attempt.unwrap_or_default()) } None => return Vec::new(), @@ -211,7 +209,7 @@ impl Journal { let attempt = event.attempt.unwrap_or(attempts); // Deletions never fail: they record each error and keep their attempt // running until it is retried. - if event.kind == "operation_failed" && kind == Some(OperationKind::Delete) { + if event.kind == EventKind::OperationFailed && kind == Some(OperationKind::Delete) { return Vec::new(); } let end = time(event.created_at_ms); diff --git a/crates/piqueld-core/src/api/error_code.rs b/crates/piqueld-core/src/api/error_code.rs index 155cee815..a34e2ac16 100644 --- a/crates/piqueld-core/src/api/error_code.rs +++ b/crates/piqueld-core/src/api/error_code.rs @@ -1,6 +1,6 @@ //! Every stable machine-readable code the API returns. -use crate::names::string_enum; +use crate::names::{compared_as_string, string_enum}; string_enum! { #[serde] @@ -578,25 +578,7 @@ string_enum! { } } -impl From for String { - fn from(code: ApiErrorCode) -> Self { - code.as_str().to_owned() - } -} - -/// Compares a wire `code` with a known one: `error.code == ApiErrorCode::NotFound`. -impl PartialEq for String { - fn eq(&self, code: &ApiErrorCode) -> bool { - self == code.as_str() - } -} - -/// Compares a wire `code` with a known one: `error.code == ApiErrorCode::NotFound`. -impl PartialEq for str { - fn eq(&self, code: &ApiErrorCode) -> bool { - self == code.as_str() - } -} +compared_as_string!(ApiErrorCode); #[cfg(test)] mod tests { diff --git a/crates/piqueld-core/src/event.rs b/crates/piqueld-core/src/event.rs index 9a1f6b4ff..235b92318 100644 --- a/crates/piqueld-core/src/event.rs +++ b/crates/piqueld-core/src/event.rs @@ -1,4 +1,5 @@ //! Informational control-plane history; never used to reconstruct engine state. +use crate::names::{compared_as_string, string_enum}; use crate::{ApplicationId, EnvironmentId}; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; @@ -20,6 +21,10 @@ pub struct Event { /// Execution attempt for attempt-related events. pub attempt: Option, /// Stable event category, such as `operation_failed` or `health_changed`. + // + // An `EventKind`, kept a string so events of kinds a newer daemon adds, + // or that older daemons recorded, still read; compare it with + // `Event::known_kind` or `==`. pub kind: String, /// Sanitized diagnostic or state description. pub message: Option, @@ -61,6 +66,157 @@ pub struct Event { pub created_at_ms: i64, } +impl Event { + /// The event's kind, when this build knows it. + #[must_use] + pub fn known_kind(&self) -> Option { + EventKind::parse(&self.kind) + } +} + +string_enum! { + #[serde] + /// Every kind of event the daemon records, as stored in history and sent + /// as [`Event::kind`]. A kind never changes, but new ones are added. + pub enum EventKind { + // An operation's lifecycle. + /// An apply operation was requested, or applying a fetched manifest + /// changed the application. + ApplicationApplied => "application_applied", + /// A refresh operation was requested. + RefreshRequested => "refresh_requested", + /// A delete operation was requested. + DeletionRequested => "deletion_requested", + /// An operation was requested again, to be retried. + ReconciliationRequested => "reconciliation_requested", + /// A rollback to an earlier deployment was requested. + RollbackRequested => "rollback_requested", + /// A failed rollout could not be rolled back automatically; the + /// message says why. + RollbackUnavailable => "rollback_unavailable", + /// An operation started running. + OperationStarted => "operation_started", + /// An operation succeeded. + OperationSucceeded => "operation_succeeded", + /// An operation failed, or a deletion failed an attempt it retries. + OperationFailed => "operation_failed", + /// An operation was cancelled. + OperationCancelled => "operation_cancelled", + /// A newer request replaced a requested or running operation. + OperationSuperseded => "operation_superseded", + /// The daemon restarted while an operation ran; it runs again. + OperationInterrupted => "operation_interrupted", + /// An operation fetched its manifest; the message is the commit. + ManifestFetched => "manifest_fetched", + /// An operation resolved the release it deploys. + TargetResolved => "target_resolved", + /// An operation published its resolved release to its environment. + TargetPromoted => "target_promoted", + /// A tracked branch moved, starting a deployment of its new head. + BranchSynced => "branch_synced", + /// An operation's environment changed state; the message is the new + /// state. + StatusChanged => "status_changed", + /// The runtime health of an operation's environment changed; the + /// message is the new health. + HealthChanged => "health_changed", + /// An action of an operation changed runtime state. + ResourceMutated => "resource_mutated", + /// An operation planned the steps it runs next, listed in its + /// [`EventDetail::Planned`]. + PlanRecorded => "plan_recorded", + + // A journaled runtime request (action). + /// An action was journaled, before it is requested. + ActionStarted => "action_started", + /// An action's request is about to be sent, as its `retry`th attempt. + ActionRequested => "action_requested", + /// An action's attempt failed and will be retried. + ActionRetry => "action_retry", + /// A running action observed progress, such as a service's rollout, + /// listed in its [`EventDetail::Rollout`]. + ActionProgressed => "action_progressed", + /// An action succeeded. + ActionSucceeded => "action_succeeded", + /// An action failed. + ActionFailed => "action_failed", + /// An action was still open when the daemon stopped, so whether it + /// took effect is unknown. + ActionOutcomeUnknown => "action_outcome_unknown", + + // Applications and environments, outside any operation. + /// An application's configuration was edited, as its + /// [`EventDetail::Edited`] says. + ApplicationEdited => "application_edited", + /// An application was renamed. + ApplicationRenamed => "application_renamed", + /// An application's webhook secret was replaced. + WebhookSecretGenerated => "webhook_secret_generated", + /// An environment was created. + EnvironmentCreated => "environment_created", + /// An environment was renamed. + EnvironmentRenamed => "environment_renamed", + /// An environment's manifest source changed. + EnvironmentSourceChanged => "environment_source_changed", + /// An environment's branch tracking changed. + EnvironmentSyncChanged => "environment_sync_changed", + /// An environment was granted, or lost, every application's + /// telemetry. + EnvironmentTelemetryChanged => "environment_telemetry_changed", + /// An environment was stopped. + EnvironmentStopped => "environment_stopped", + /// A stopped environment was started. + EnvironmentStarted => "environment_started", + /// A preview environment was created. + PreviewCreated => "preview_created", + /// A command started in one of an environment's services. + CommandStarted => "command_started", + /// A command run in an environment's service finished. + CommandFinished => "command_finished", + + // Secrets. + /// A secret's value was stored. + SecretSaved => "secret_saved", + /// A secret was deleted. + SecretDeleted => "secret_deleted", + /// Which environments may use a stored secret changed. + SecretAccessChanged => "secret_access_changed", + /// Secret key recovery discarded the stored values of an application + /// or environment. + SecretValuesDiscarded => "secret_values_discarded", + + // The daemon. + /// An unexpected failure outside any operation, with its diagnostic. + Diagnostic => "diagnostic", + /// A dependency of the daemon, such as certificate renewal or + /// telemetry export, failed or recovered. + DependencyHealthChanged => "dependency_health_changed", + /// The daemon started; the resource is its version. + DaemonStarted => "daemon_started", + + // Security events, in daemon history. + /// An account received `admin` on every application. + AdminGranted => "admin_granted", + /// A token was created without expiry or with `admin`. + PrivilegedTokenCreated => "privileged_token_created", + /// Many requests from one address and account were refused within a + /// minute; the resource is that address. + AccessDenialBurst => "access_denial_burst", + /// An admin recovery link was issued over the Unix socket. + AdminRecoveryIssued => "admin_recovery_issued", + /// A host operator sign-in link was issued over the Unix socket. + OperatorSignInIssued => "operator_sign_in_issued", + /// A credential was used from an address it had not used before. + CredentialNewAddress => "credential_new_address", + /// The secret master key was recovered, discarding stored values. + SecretKeyRecovered => "secret_key_recovered", + /// A notification destination was created, changed or deleted. + NotificationDestinationChanged => "notification_destination_changed", + } +} + +compared_as_string!(EventKind); + /// Structured facts an event records beyond its common fields, tagged by /// `type`. #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize, ToSchema)] @@ -142,3 +298,26 @@ impl std::fmt::Display for EventActor { } } } + +#[cfg(test)] +mod tests { + use super::EventKind; + use std::collections::BTreeSet; + + /// Each kind is stored and sent as its own string and read back as + /// itself, and no two share one. + #[test] + fn kinds_serialize_to_distinct_strings() { + for kind in EventKind::ALL { + let value = kind.as_str(); + assert_eq!(serde_json::to_value(kind).unwrap(), value); + assert_eq!( + serde_json::from_value::(value.into()).unwrap(), + kind + ); + assert_eq!(EventKind::parse(value), Some(kind)); + } + let values = EventKind::ALL.map(EventKind::as_str); + assert_eq!(BTreeSet::from(values).len(), values.len()); + } +} diff --git a/crates/piqueld-core/src/lib.rs b/crates/piqueld-core/src/lib.rs index 5ec1d0d13..1b916d553 100644 --- a/crates/piqueld-core/src/lib.rs +++ b/crates/piqueld-core/src/lib.rs @@ -35,7 +35,7 @@ pub mod urls; pub use api::ApiErrorCode; pub use docker_names::{DockerConfigName, DockerNetworkName, DockerServiceName, DockerVolumeName}; pub use environment::{EnvironmentKind, EnvironmentSource, Preview, PromotedFrom, TrackedBranch}; -pub use event::{Event, EventActor, EventDetail}; +pub use event::{Event, EventActor, EventDetail, EventKind}; pub use identity::{ ApplicationId, ApplicationIdError, EnvironmentId, EnvironmentIdError, ReleaseId, ReleaseIdError, ResourceKind, docker_resource_name, docker_resource_readable_prefix, diff --git a/crates/piqueld-core/src/names.rs b/crates/piqueld-core/src/names.rs index e380e707f..58d872d1b 100644 --- a/crates/piqueld-core/src/names.rs +++ b/crates/piqueld-core/src/names.rs @@ -189,6 +189,32 @@ macro_rules! string_enum { } pub(crate) use string_enum; +// Lets a wire field that stays a `String`, so it still reads values a newer +// daemon adds or old rows hold, be built from and compared with a +// `string_enum!`'s values: `event.kind == EventKind::OperationFailed`. +macro_rules! compared_as_string { + ($($name:ident),+ $(,)?) => {$( + impl From<$name> for String { + fn from(value: $name) -> Self { + value.as_str().to_owned() + } + } + + impl PartialEq<$name> for String { + fn eq(&self, value: &$name) -> bool { + self == value.as_str() + } + } + + impl PartialEq<$name> for str { + fn eq(&self, value: &$name) -> bool { + self == value.as_str() + } + } + )+}; +} +pub(crate) use compared_as_string; + use std::ops::RangeInclusive; /// Byte lengths of one DNS label. diff --git a/crates/piqueld-core/src/timeline.rs b/crates/piqueld-core/src/timeline.rs index 903d457d9..ecfb8f65b 100644 --- a/crates/piqueld-core/src/timeline.rs +++ b/crates/piqueld-core/src/timeline.rs @@ -11,7 +11,8 @@ use crate::observability::{Diagnostic, Elapsed}; use crate::resource::TaskState; use crate::{ - Event, EventDetail, Operation, OperationKind, OperationState, Phase, names::string_enum, + Event, EventDetail, EventKind, Operation, OperationKind, OperationState, Phase, + names::string_enum, }; use serde::{Deserialize, Serialize}; use std::time::Duration; @@ -669,19 +670,22 @@ impl Timeline { self.plan(steps, *coverage); return; } - match event.kind.as_str() { - "target_promoted" => self.promoted_at_ms = Some(event.created_at_ms), - "action_started" => self.start(event), + let Some(kind) = event.known_kind() else { + return; + }; + match kind { + EventKind::TargetPromoted => self.promoted_at_ms = Some(event.created_at_ms), + EventKind::ActionStarted => self.start(event), kind => { let Some(step) = self.action(event) else { return; }; match kind { - "action_requested" => { + EventKind::ActionRequested => { step.retries = event.retry.unwrap_or(1).saturating_sub(1); step.state = StepState::Running; } - "action_progressed" => { + EventKind::ActionProgressed => { if let Some(EventDetail::Rollout { tasks, monitor_seconds, @@ -690,14 +694,16 @@ impl Timeline { step.observe(tasks, *monitor_seconds, event.created_at_ms); } } - "action_retry" => { + EventKind::ActionRetry => { step.state = StepState::Retrying; step.diagnostic.clone_from(&event.diagnostic); } - "action_succeeded" | "action_failed" | "action_outcome_unknown" => { + EventKind::ActionSucceeded + | EventKind::ActionFailed + | EventKind::ActionOutcomeUnknown => { step.state = match kind { - "action_succeeded" => StepState::Succeeded, - "action_failed" => StepState::Failed, + EventKind::ActionSucceeded => StepState::Succeeded, + EventKind::ActionFailed => StepState::Failed, _ => StepState::Interrupted, }; step.finished_at_ms = Some(event.created_at_ms); diff --git a/crates/piqueld-store/src/acceptance.rs b/crates/piqueld-store/src/acceptance.rs index 460ff73ae..5c959513a 100644 --- a/crates/piqueld-store/src/acceptance.rs +++ b/crates/piqueld-store/src/acceptance.rs @@ -4,6 +4,7 @@ use super::{ Actor, Author, Operation, OperationKind, Store, StoreError, StoredApplication, now_ms, }; use crate::{Mutation, MutationResponse, PreviewMutation, PromotionMutation}; +use piqueld_core::EventKind; use piqueld_core::access::{AppPermission, Grants, Target}; use piqueld_core::api::{ AcceptedOperation, CreatedPreview, DeletedApplication, EnvironmentView, SavedApplication, @@ -879,7 +880,8 @@ impl Store { field: edit.field(), }) .map_err(StoreError::corrupt)?; - sqlx::query!("INSERT INTO events(application_id,generation,kind,message,detail_json,resource,created_at_ms) VALUES(?1,?2,'application_edited','Saved application configuration',?3,?4,?5)",app_id,generation,detail,resource,now).execute(&mut **tx).await.map_err(StoreError::database)?; + let event_kind = EventKind::ApplicationEdited.as_str(); + sqlx::query!("INSERT INTO events(application_id,generation,kind,message,detail_json,resource,created_at_ms) VALUES(?1,?2,?6,'Saved application configuration',?3,?4,?5)",app_id,generation,detail,resource,now,event_kind).execute(&mut **tx).await.map_err(StoreError::database)?; (saved, true) }; Self::deploy_saved(tx, &id, &mut saved, deploy).await?; @@ -1031,7 +1033,8 @@ impl Store { sqlx::query!("UPDATE operations SET target_json=json_set(target_json,'$.name',?1) WHERE target_json IS NOT NULL AND id IN (SELECT (SELECT o.id FROM operations o WHERE o.environment_id=e.id ORDER BY o.created_at_ms DESC,o.id DESC LIMIT 1) FROM environments e WHERE e.application_id=?2)",name,id) .execute(&mut **tx).await.map_err(StoreError::database)?; let message = format!("renamed {old_name} to {name}"); - sqlx::query!("INSERT INTO events(application_id,generation,kind,message,created_at_ms) VALUES(?1,?2,'application_renamed',?3,?4)",id,revision,message,now).execute(&mut **tx).await.map_err(StoreError::database)?; + let event_kind = EventKind::ApplicationRenamed.as_str(); + sqlx::query!("INSERT INTO events(application_id,generation,kind,message,created_at_ms) VALUES(?1,?2,?5,?3,?4)",id,revision,message,now,event_kind).execute(&mut **tx).await.map_err(StoreError::database)?; Ok((saved(id, generation), true)) } diff --git a/crates/piqueld-store/src/auth/security.rs b/crates/piqueld-store/src/auth/security.rs index 91fd6f140..45b2f96d2 100644 --- a/crates/piqueld-store/src/auth/security.rs +++ b/crates/piqueld-store/src/auth/security.rs @@ -2,7 +2,7 @@ //! is delivered as a `security` notification (see `process_notification_event`). use crate::auth::access::Holder; use crate::{Attribution, NewCredential, Store, StoreError, now_ms}; -use piqueld_core::access::Grants; +use piqueld_core::{EventKind, access::Grants}; use sqlx::SqliteConnection; /// A security-relevant occurrence, by its event kind. @@ -42,23 +42,23 @@ impl SecurityEvent { /// Event kind in daemon history. #[must_use] - pub const fn kind(self) -> &'static str { + pub const fn kind(self) -> EventKind { match self { - Self::AdminGranted => "admin_granted", - Self::PrivilegedToken => "privileged_token_created", - Self::DenialBurst => "access_denial_burst", - Self::RecoveryIssued => "admin_recovery_issued", - Self::OperatorSignInIssued => "operator_sign_in_issued", - Self::NewAddress => "credential_new_address", - Self::SecretKeyRecovered => "secret_key_recovered", - Self::DestinationChanged => "notification_destination_changed", + Self::AdminGranted => EventKind::AdminGranted, + Self::PrivilegedToken => EventKind::PrivilegedTokenCreated, + Self::DenialBurst => EventKind::AccessDenialBurst, + Self::RecoveryIssued => EventKind::AdminRecoveryIssued, + Self::OperatorSignInIssued => EventKind::OperatorSignInIssued, + Self::NewAddress => EventKind::CredentialNewAddress, + Self::SecretKeyRecovered => EventKind::SecretKeyRecovered, + Self::DestinationChanged => EventKind::NotificationDestinationChanged, } } /// The security event an event kind records, if any. #[must_use] pub fn parse(kind: &str) -> Option { - Self::ALL.into_iter().find(|event| event.kind() == kind) + Self::ALL.into_iter().find(|event| *kind == event.kind()) } } @@ -80,7 +80,7 @@ impl Store { message: &str, actor: Attribution<'_>, ) -> Result<(), StoreError> { - let kind = event.kind(); + let kind = event.kind().as_str(); let now = now_ms(); let operator = actor.operator_uid(); let system = actor.system.map(piqueld_core::sync::SystemActor::as_str); diff --git a/crates/piqueld-store/src/environment/mod.rs b/crates/piqueld-store/src/environment/mod.rs index 96de72143..851a44c9d 100644 --- a/crates/piqueld-store/src/environment/mod.rs +++ b/crates/piqueld-store/src/environment/mod.rs @@ -10,6 +10,7 @@ use super::{ StoredEnvironment, StoredEnvironmentRow, now_ms, }; use crate::SourceChoice; +use piqueld_core::EventKind; use piqueld_core::{ EnvironmentKind, EnvironmentName, EnvironmentSource, PromotedFrom, TrackedBranch, manifest::RenderTarget, @@ -56,7 +57,7 @@ impl Store { .map_err(StoreError::constraint)?; Self::write_status(tx, id, ApplicationState::NotDeployed, now).await?; let message = format!("created environment {name}"); - Self::environment_event_on(tx, id, "environment_created", &message, now).await + Self::environment_event_on(tx, id, EventKind::EnvironmentCreated, &message, now).await } /// The `branch`, `pinned_commit`, and `promoted_from` columns of `source`. @@ -166,7 +167,7 @@ impl Store { .await .map_err(StoreError::constraint)?; let message = format!("renamed environment {old} to {name}"); - Self::environment_event_on(tx, id, "environment_renamed", &message, now).await?; + Self::environment_event_on(tx, id, EventKind::EnvironmentRenamed, &message, now).await?; Self::bump_generation_on( tx, &environment.environment.application_id, @@ -312,7 +313,8 @@ impl Store { Self::describe_source_on(tx, &source).await?, Self::describe_source_on(tx, previous).await?, ); - Self::environment_event_on(tx, id, "environment_source_changed", &message, now).await?; + Self::environment_event_on(tx, id, EventKind::EnvironmentSourceChanged, &message, now) + .await?; Ok(SourceWrite::Changed { deploying }) } @@ -522,7 +524,7 @@ impl Store { now, ) .await?; - Self::operation_event(&mut tx, &operation.id, "target_resolved", None, now).await?; + Self::operation_event(&mut tx, &operation.id, EventKind::TargetResolved, None, now).await?; Self::commit_environment_changes(tx, [operation.environment_id.as_str()]).await?; Ok(resolved.clone()) } @@ -549,8 +551,14 @@ impl Store { .map_err(StoreError::database)? .rows_affected(); if promoted == 1 { - Self::operation_event(&mut tx, &operation.id, "target_promoted", None, now_ms()) - .await?; + Self::operation_event( + &mut tx, + &operation.id, + EventKind::TargetPromoted, + None, + now_ms(), + ) + .await?; } Self::commit_environment_changes(tx, [environment_id]).await } diff --git a/crates/piqueld-store/src/journal.rs b/crates/piqueld-store/src/journal.rs index d1713a610..8fe16c18e 100644 --- a/crates/piqueld-store/src/journal.rs +++ b/crates/piqueld-store/src/journal.rs @@ -1,7 +1,7 @@ //! Persist intent before a runtime request and record its observed outcome afterward. use super::{Attribution, EnvironmentId, Store, StoreError, new_id, now_ms}; use piqueld_core::observability::{Diagnostic, DiagnosticCode, EventScope}; -use piqueld_core::{EventDetail, Phase}; +use piqueld_core::{EventDetail, EventKind, Phase}; use sqlx::{Sqlite, Transaction}; /// Handle to one journaled runtime request, recorded in `active_actions` until @@ -68,14 +68,14 @@ enum Step<'a> { } impl Step<'_> { /// The event's kind. - fn kind(&self) -> &'static str { + fn kind(&self) -> EventKind { match self { - Self::Started => "action_started", - Self::Requested { .. } => "action_requested", - Self::Retry { .. } => "action_retry", - Self::Progressed(_) => "action_progressed", - Self::Finished(None) => "action_succeeded", - Self::Finished(Some(_)) => "action_failed", + Self::Started => EventKind::ActionStarted, + Self::Requested { .. } => EventKind::ActionRequested, + Self::Retry { .. } => EventKind::ActionRetry, + Self::Progressed(_) => EventKind::ActionProgressed, + Self::Finished(None) => EventKind::ActionSucceeded, + Self::Finished(Some(_)) => EventKind::ActionFailed, } } } @@ -329,7 +329,7 @@ impl Store { action: &JournalAction, step: Step<'_>, ) -> Result<(), StoreError> { - let (kind, finished) = (step.kind(), matches!(step, Step::Finished(_))); + let (kind, finished) = (step.kind().as_str(), matches!(step, Step::Finished(_))); let (retry, diagnostic, message, detail) = match step { Step::Started => (None, None, None, None), Step::Requested { retry } => (Some(retry), None, None, None), @@ -413,11 +413,12 @@ impl Store { pub async fn interrupt_actions(&self, operation: Option<&str>) -> Result<(), StoreError> { let (_writer, mut tx) = self.begin_immediate().await?; let now = now_ms(); + let event_kind = EventKind::ActionOutcomeUnknown.as_str(); sqlx::query!( "INSERT INTO events(application_id,environment_id,operation_id,generation,attempt,kind,message,phase, resource,created_at_ms,scope,action_id,retry,actor_user_id,actor_credential_id,actor_operator_uid,actor_system) SELECT (SELECT application_id FROM environments WHERE id=active_actions.environment_id), - environment_id,operation_id,generation,attempt,'action_outcome_unknown', + environment_id,operation_id,generation,attempt,?3, 'Execution was interrupted before its result was committed; reconciliation will inspect current runtime state', phase,resource,?1,CASE WHEN environment_id IS NULL THEN 'daemon' ELSE 'application' END, id,retry,actor_user_id,actor_credential_id,actor_operator_uid,actor_system @@ -425,6 +426,7 @@ impl Store { WHERE ?2 IS NULL OR operation_id=?2", now, operation, + event_kind, ) .execute(&mut *tx) .await diff --git a/crates/piqueld-store/src/observability/event.rs b/crates/piqueld-store/src/observability/event.rs index 8c4b02d31..70fe878dc 100644 --- a/crates/piqueld-store/src/observability/event.rs +++ b/crates/piqueld-store/src/observability/event.rs @@ -5,7 +5,7 @@ use crate::{ now_ms, }; use piqueld_core::{ - Event, EventActor, EventDetail, Operation, + Event, EventActor, EventDetail, EventKind, Operation, api::Page, observability::{Diagnostic, EventFilter, EventScope}, sync::SystemActor, @@ -25,10 +25,11 @@ impl Store { pub async fn operation_event( tx: &mut Transaction<'_, Sqlite>, id: &str, - kind: &str, + kind: EventKind, message: Option<&str>, now: i64, ) -> Result<(), StoreError> { + let kind = kind.as_str(); let operation = Self::operation_on(tx, id).await?; let diagnostic = if let Some(code) = &operation.error_code { let attempt = i64::try_from(operation.attempt).map_err(StoreError::corrupt)?; @@ -106,11 +107,12 @@ impl Store { .map_err(StoreError::corrupt)?; let phase = coverage.phase().as_str(); let now = now_ms(); + let event_kind = EventKind::PlanRecorded.as_str(); self.write(sqlx::query!( "INSERT INTO events(application_id,environment_id,operation_id,generation,attempt,kind, phase,resource,created_at_ms,detail_json,actor_user_id,actor_credential_id, actor_operator_uid,actor_system) - SELECT e.application_id,o.environment_id,o.id,o.generation,o.attempt,'plan_recorded',?1,?2, + SELECT e.application_id,o.environment_id,o.id,o.generation,o.attempt,?6,?1,?2, ?3,?4,o.actor_user_id,o.actor_credential_id,o.actor_operator_uid,o.actor_system FROM operations o LEFT JOIN environments e ON e.id=o.environment_id WHERE o.id=?5", @@ -119,6 +121,7 @@ impl Store { now, detail, id, + event_kind, )) .await .map_err(StoreError::database)?; @@ -132,11 +135,13 @@ impl Store { /// Returns storage errors. pub async fn routed(&self, operation: &Operation) -> Result { let attempt = i64::try_from(operation.attempt).map_err(StoreError::corrupt)?; + let event_kind = EventKind::ActionStarted.as_str(); sqlx::query_scalar!( r#"SELECT EXISTS(SELECT 1 FROM events WHERE operation_id=?1 AND attempt=?2 - AND phase='routing' AND kind='action_started') AS "routed!: bool""#, + AND phase='routing' AND kind=?3) AS "routed!: bool""#, operation.id, attempt, + event_kind, ) .fetch_one(&self.pool) .await @@ -314,10 +319,11 @@ impl Store { let json = serde_json::to_string(&diagnostic).map_err(StoreError::corrupt)?; let now = now_ms(); let operator = actor.operator_uid(); + let event_kind = EventKind::Diagnostic.as_str(); self.write(sqlx::query!( "INSERT INTO events(scope,application_id,environment_id,kind,message,error_code,diagnostic_id, diagnostic_json,request_id,created_at_ms,actor_user_id,actor_credential_id,actor_operator_uid) - SELECT ?1,(SELECT application_id FROM environments WHERE id=?2),?2,'diagnostic',?3,?4,?5,?6,?7,?8,?9,?10,?11 + SELECT ?1,(SELECT application_id FROM environments WHERE id=?2),?2,?12,?3,?4,?5,?6,?7,?8,?9,?10,?11 WHERE ?1='daemon' OR EXISTS(SELECT 1 FROM environments WHERE id=?2)", @@ -332,6 +338,7 @@ impl Store { actor.user_id, actor.credential_id, operator, + event_kind, )) .await .map_err(StoreError::database)?; @@ -346,10 +353,11 @@ impl Store { pub async fn environment_event_on( tx: &mut Transaction<'_, Sqlite>, id: &str, - kind: &str, + kind: EventKind, message: &str, now: i64, ) -> Result<(), StoreError> { + let kind = kind.as_str(); sqlx::query!( "INSERT INTO events(application_id,environment_id,kind,message,created_at_ms) VALUES((SELECT application_id FROM environments WHERE id=?1),?1,?2,?3,?4)", id, @@ -374,11 +382,12 @@ impl Store { actor: crate::Attribution<'_>, application: &ApplicationId, environment: &EnvironmentId, - kind: &str, + kind: EventKind, message: &str, resource: &str, ) -> Result<(), StoreError> { let (application, environment) = (application.as_str(), environment.as_str()); + let kind = kind.as_str(); let now = now_ms(); let operator = actor.operator_uid(); self.write(sqlx::query!( @@ -407,8 +416,10 @@ impl Store { /// Returns storage errors. pub async fn record_daemon_started(&self, version: &str) -> Result<(), StoreError> { let (_writer, mut tx) = self.begin_immediate().await?; + let kind = EventKind::DaemonStarted.as_str(); let previous = sqlx::query_scalar!( - "SELECT resource FROM events WHERE kind='daemon_started' ORDER BY id DESC LIMIT 1" + "SELECT resource FROM events WHERE kind=?1 ORDER BY id DESC LIMIT 1", + kind, ) .fetch_optional(&mut *tx) .await @@ -423,10 +434,11 @@ impl Store { let now = now_ms(); sqlx::query!( "INSERT INTO events(scope,kind,message,resource,created_at_ms) - VALUES('daemon','daemon_started',?1,?2,?3)", + VALUES('daemon',?4,?1,?2,?3)", message, version, now, + kind, ) .execute(&mut *tx) .await @@ -763,7 +775,7 @@ mod tests { crate::Attribution::default(), application, &deleted, - "command_finished", + EventKind::CommandFinished, "done", "web", ) diff --git a/crates/piqueld-store/src/observability/mod.rs b/crates/piqueld-store/src/observability/mod.rs index b12abcbb1..482af1ad4 100644 --- a/crates/piqueld-store/src/observability/mod.rs +++ b/crates/piqueld-store/src/observability/mod.rs @@ -16,6 +16,7 @@ pub use notifications::RetryError; /// disabled, changed or deleted. pub const DESTINATION_CHANGED: &str = "The destination was disabled, changed or deleted"; use destinations::DestinationRow; +use piqueld_core::EventKind; use super::{Store, StoreError, now_ms}; use piqueld_core::observability::{ActionDuration, DaemonStats, DeploymentAnalytics, FailureCount}; @@ -268,15 +269,17 @@ impl Store { ) -> Result<(), StoreError> { let since = result.since_ms; let until = result.until_ms; + let event_kind = EventKind::ActionRetry.as_str(); result.action_retries = sqlx::query_scalar!( "SELECT COUNT(*) FROM events - WHERE kind='action_retry' AND (?1 IS NULL OR environment_id=?1) AND created_at_ms BETWEEN ?2 AND ?3 AND ((scope='application' AND (?4 IS NULL OR application_id IN (SELECT value FROM json_each(?4)))) OR (scope='daemon' AND ?5))", + WHERE kind=?6 AND (?1 IS NULL OR environment_id=?1) AND created_at_ms BETWEEN ?2 AND ?3 AND ((scope='application' AND (?4 IS NULL OR application_id IN (SELECT value FROM json_each(?4)))) OR (scope='daemon' AND ?5))", application, since, until, applications, daemon, + event_kind, ) .fetch_one(&mut **tx) .await diff --git a/crates/piqueld-store/src/observability/notifications.rs b/crates/piqueld-store/src/observability/notifications.rs index 6d7e0aa5b..1450bb2b8 100644 --- a/crates/piqueld-store/src/observability/notifications.rs +++ b/crates/piqueld-store/src/observability/notifications.rs @@ -2,7 +2,7 @@ use super::DestinationRow; use crate::{Paging, Store, StoreError, new_id, now_ms, seconds_ms}; use piqueld_core::{ - Event, + Event, EventKind, api::Page, observability::{ DeliveryState, Diagnostic, DiagnosticCode, EventScope, NotificationCategory, @@ -309,7 +309,8 @@ impl Store { let app = (event.scope == EventScope::Application) .then(|| event.environment_id.as_ref().map(ToString::to_string)) .flatten(); - if event.kind == "operation_succeeded" { + let known = event.known_kind(); + if known == Some(EventKind::OperationSucceeded) { for category in [ NotificationCategory::BuildFailures, NotificationCategory::DeploymentFailures, @@ -337,31 +338,30 @@ impl Store { let security = NotificationCategory::Security; return Self::enqueue(tx, event.id, security).await; } - if event.kind == "daemon_started" { + if known == Some(EventKind::DaemonStarted) { let started = NotificationCategory::DaemonStarted; return Self::enqueue(tx, event.id, started).await; } - let category = match ( - event.kind.as_str(), - event.scope, - event.error_code.as_deref(), - ) { + let category = match (known, event.scope, event.error_code.as_deref()) { ( - "operation_failed", + Some(EventKind::OperationFailed), EventScope::Application, Some("git_build_failed" | "builder_unavailable"), ) => NotificationCategory::BuildFailures, - ("operation_failed", EventScope::Application, _) => { + (Some(EventKind::OperationFailed), EventScope::Application, _) => { NotificationCategory::DeploymentFailures } - ("diagnostic" | "operation_failed", EventScope::Daemon, Some(code)) - if !matches!( - code, - "docker_unavailable" - | "swarm_manager_unavailable" - | "swarm_topology_unsupported" - | "ingress_unavailable" - ) => + ( + Some(EventKind::Diagnostic | EventKind::OperationFailed), + EventScope::Daemon, + Some(code), + ) if !matches!( + code, + "docker_unavailable" + | "swarm_manager_unavailable" + | "swarm_topology_unsupported" + | "ingress_unavailable" + ) => { NotificationCategory::DaemonFailures } @@ -597,9 +597,10 @@ impl Store { .transpose() .map_err(StoreError::corrupt)?; let error_code = failed.then_some(code.as_str()); + let event_kind = EventKind::DependencyHealthChanged.as_str(); let event = sqlx::query!( "INSERT INTO events(scope,application_id,environment_id,kind,message,error_code,diagnostic_id,diagnostic_json, - created_at_ms) VALUES(?1,(SELECT application_id FROM environments WHERE id=?2),?2,'dependency_health_changed',?3,?4,?5,?6,?7)", + created_at_ms) VALUES(?1,(SELECT application_id FROM environments WHERE id=?2),?2,?8,?3,?4,?5,?6,?7)", scope, application, summary, @@ -607,6 +608,7 @@ impl Store { diagnostic_id, json, observed, + event_kind, ) .execute(&mut **tx) .await diff --git a/crates/piqueld-store/src/operation.rs b/crates/piqueld-store/src/operation.rs index f48c6a7e7..bac48864b 100644 --- a/crates/piqueld-store/src/operation.rs +++ b/crates/piqueld-store/src/operation.rs @@ -4,6 +4,7 @@ use super::{ ApplicationState, EnvironmentId, Operation, OperationKind, OperationState, Store, StoreError, decode_name, new_id, now_ms, }; +use piqueld_core::EventKind; use piqueld_core::observability::{DeploymentFailure, DiagnosticCode}; use sqlx::{Sqlite, SqliteConnection, Transaction}; @@ -161,12 +162,12 @@ impl Store { } if from != to { let kind = match to { - OperationState::Requested => "reconciliation_requested", - OperationState::Running => "operation_started", - OperationState::Succeeded => "operation_succeeded", - OperationState::Failed => "operation_failed", - OperationState::Cancelled => "operation_cancelled", - OperationState::Superseded => "operation_superseded", + OperationState::Requested => EventKind::ReconciliationRequested, + OperationState::Running => EventKind::OperationStarted, + OperationState::Succeeded => EventKind::OperationSucceeded, + OperationState::Failed => EventKind::OperationFailed, + OperationState::Cancelled => EventKind::OperationCancelled, + OperationState::Superseded => EventKind::OperationSuperseded, }; Self::operation_event(tx, id, kind, message, now).await?; } @@ -197,7 +198,7 @@ impl Store { Self::operation_event( &mut tx, &operation.id, - "operation_failed", + EventKind::OperationFailed, Some(message), now, ) @@ -223,7 +224,14 @@ impl Store { return Err(StoreError::IllegalTransition); } // Recorded while the operation still exists; it goes with its environment. - Self::operation_event(&mut tx, &operation.id, "operation_succeeded", None, now).await?; + Self::operation_event( + &mut tx, + &operation.id, + EventKind::OperationSucceeded, + None, + now, + ) + .await?; let app_id = operation.environment_id.as_str(); sqlx::query!( "DELETE FROM notification_conditions WHERE environment_id=?1", @@ -352,7 +360,14 @@ impl Store { ApplicationState::Pending }; Self::write_status(tx, operation.environment_id.as_str(), state, now).await?; - Self::operation_event(tx, &operation.id, "reconciliation_requested", None, now).await?; + Self::operation_event( + tx, + &operation.id, + EventKind::ReconciliationRequested, + None, + now, + ) + .await?; let operation = Self::operation_on(tx, &operation.id).await?; Ok((operation, true)) } @@ -363,7 +378,7 @@ impl Store { /// Returns a storage error. pub async fn mutation_event(&self, id: &str) -> Result<(), StoreError> { let (_writer, mut tx) = self.begin_immediate().await?; - Self::operation_event(&mut tx, id, "resource_mutated", None, now_ms()).await?; + Self::operation_event(&mut tx, id, EventKind::ResourceMutated, None, now_ms()).await?; tx.commit().await.map_err(StoreError::database) } @@ -392,7 +407,8 @@ impl Store { pub async fn recover_interrupted(&self) -> Result { let now = now_ms(); let (_writer, mut tx) = self.begin_immediate().await?; - sqlx::query!("INSERT INTO events(application_id,environment_id,operation_id,generation,attempt,kind,message,error_code,phase,resource,created_at_ms) SELECT (SELECT application_id FROM environments WHERE id=o.environment_id),o.environment_id,o.id,o.generation,o.attempt,'operation_interrupted','daemon restarted during execution',o.error_code,p.phase,p.resource,?1 FROM operations o JOIN operation_progress p ON p.operation_id=o.id WHERE o.state='running'",now).execute(&mut *tx).await.map_err(StoreError::database)?; + let event_kind = EventKind::OperationInterrupted.as_str(); + sqlx::query!("INSERT INTO events(application_id,environment_id,operation_id,generation,attempt,kind,message,error_code,phase,resource,created_at_ms) SELECT (SELECT application_id FROM environments WHERE id=o.environment_id),o.environment_id,o.id,o.generation,o.attempt,?2,'daemon restarted during execution',o.error_code,p.phase,p.resource,?1 FROM operations o JOIN operation_progress p ON p.operation_id=o.id WHERE o.state='running'",now,event_kind).execute(&mut *tx).await.map_err(StoreError::database)?; let interrupted = sqlx::query_scalar!(r#"SELECT id AS "id!" FROM operations WHERE state='running'"#) .fetch_all(&mut *tx) @@ -484,7 +500,8 @@ impl Store { now: i64, ) -> Result { let app_id = app.as_str(); - sqlx::query!("INSERT INTO events(application_id,environment_id,operation_id,generation,attempt,kind,message,error_code,phase,resource,created_at_ms) SELECT (SELECT application_id FROM environments WHERE id=?2),o.environment_id,o.id,o.generation,o.attempt,'operation_superseded','superseded by newer intent',o.error_code,p.phase,p.resource,?1 FROM operations o JOIN operation_progress p ON p.operation_id=o.id WHERE o.environment_id=?2 AND o.state IN ('requested','running')",now,app_id).execute(&mut **tx).await.map_err(StoreError::database)?; + let event_kind = EventKind::OperationSuperseded.as_str(); + sqlx::query!("INSERT INTO events(application_id,environment_id,operation_id,generation,attempt,kind,message,error_code,phase,resource,created_at_ms) SELECT (SELECT application_id FROM environments WHERE id=?2),o.environment_id,o.id,o.generation,o.attempt,?3,'superseded by newer intent',o.error_code,p.phase,p.resource,?1 FROM operations o JOIN operation_progress p ON p.operation_id=o.id WHERE o.environment_id=?2 AND o.state IN ('requested','running')",now,app_id,event_kind).execute(&mut **tx).await.map_err(StoreError::database)?; let superseded=sqlx::query_scalar!(r#"UPDATE operations SET state='superseded',error_code=NULL,error_message=NULL,finished_at_ms=?1,updated_at_ms=?1 WHERE environment_id=?2 AND state IN ('requested','running') RETURNING id AS "id!""#,now,app_id) .fetch_all(&mut **tx).await.map_err(StoreError::database)?; for previous in superseded { @@ -495,9 +512,9 @@ impl Store { sqlx::query!("INSERT INTO operations(id,environment_id,generation,kind,state,created_at_ms,updated_at_ms) SELECT ?1,e.id,a.generation,?3,'requested',MAX(?4,(SELECT COALESCE(MAX(o.created_at_ms)+1,?4) FROM operations o WHERE o.environment_id=e.id)),?4 FROM environments e JOIN applications a ON a.id=e.application_id WHERE e.id=?2",id,app_id,name,now) .execute(&mut **tx).await.map_err(StoreError::database)?; let event = match kind { - OperationKind::Apply => "application_applied", - OperationKind::Refresh => "refresh_requested", - OperationKind::Delete => "deletion_requested", + OperationKind::Apply => EventKind::ApplicationApplied, + OperationKind::Refresh => EventKind::RefreshRequested, + OperationKind::Delete => EventKind::DeletionRequested, }; Self::operation_event(tx, &id, event, None, now).await?; if kind != OperationKind::Delete { diff --git a/crates/piqueld-store/src/preview/mod.rs b/crates/piqueld-store/src/preview/mod.rs index ef400a611..42598349a 100644 --- a/crates/piqueld-store/src/preview/mod.rs +++ b/crates/piqueld-store/src/preview/mod.rs @@ -7,6 +7,7 @@ use super::{ ApplicationState, Operation, ResolvedApplication, Store, StoreError, StoredApplication, StoredEnvironment, now_ms, }; +use piqueld_core::EventKind; use piqueld_core::{ ApiErrorCode, ApplicationId, EnvironmentId, GitBranch, Preview, PreviewSlot, PreviewSlug, access::Scope, @@ -117,7 +118,7 @@ impl Store { Self::check_preview_limits_on(tx, application_id, &id, limits).await?; Self::write_status(tx, &id, ApplicationState::NotDeployed, now).await?; let message = format!("created preview {slug} of branch {branch}"); - Self::environment_event_on(tx, &id, "preview_created", &message, now).await?; + Self::environment_event_on(tx, &id, EventKind::PreviewCreated, &message, now).await?; } Ok(( EnvironmentId::parse(id).map_err(StoreError::corrupt)?, diff --git a/crates/piqueld-store/src/promotion/mod.rs b/crates/piqueld-store/src/promotion/mod.rs index fbd88487d..5c5e19199 100644 --- a/crates/piqueld-store/src/promotion/mod.rs +++ b/crates/piqueld-store/src/promotion/mod.rs @@ -6,6 +6,7 @@ use super::{ ApplicationState, EnvironmentId, Operation, OperationKind, Store, StoreError, StoredEnvironment, now_ms, }; +use piqueld_core::EventKind; use piqueld_core::{ EnvironmentKind, EnvironmentName, EnvironmentSource, InstanceId, NormalizedApplication, PromotedFrom, Release, ReleaseId, ValidationErrors, @@ -535,7 +536,7 @@ impl Store { .execute(&mut **tx) .await .map_err(StoreError::database)?; - Self::operation_event(tx, &operation.id, "target_resolved", None, now).await?; + Self::operation_event(tx, &operation.id, EventKind::TargetResolved, None, now).await?; Ok(operation) } } diff --git a/crates/piqueld-store/src/repository.rs b/crates/piqueld-store/src/repository.rs index bd0b0e752..f1f13d813 100644 --- a/crates/piqueld-store/src/repository.rs +++ b/crates/piqueld-store/src/repository.rs @@ -11,6 +11,7 @@ //! records the one it fetched: a deployment of the branch `spec.manifest` //! names deploys the saved manifest while the two are the same. use super::{Operation, Store, StoreError, now_ms}; +use piqueld_core::EventKind; use piqueld_core::{ EnvironmentKind, api::{DeploymentOrigin, DiagnosticView}, @@ -156,7 +157,14 @@ impl Store { .await .map_err(StoreError::database)?; let now = now_ms(); - Self::operation_event(&mut tx, &operation.id, "manifest_fetched", commit, now).await?; + Self::operation_event( + &mut tx, + &operation.id, + EventKind::ManifestFetched, + commit, + now, + ) + .await?; if let Some(head) = branch_head { Self::record_branch_head_on(&mut tx, &operation.environment_id, head, now).await?; } @@ -254,7 +262,8 @@ impl Store { .await?; } if changed > 0 { - Self::operation_event(tx, &operation.id, "application_applied", None, now).await?; + Self::operation_event(tx, &operation.id, EventKind::ApplicationApplied, None, now) + .await?; } Ok(()) } diff --git a/crates/piqueld-store/src/restore/mod.rs b/crates/piqueld-store/src/restore/mod.rs index faf3d0764..d28b33c98 100644 --- a/crates/piqueld-store/src/restore/mod.rs +++ b/crates/piqueld-store/src/restore/mod.rs @@ -12,6 +12,7 @@ use super::{ StoredEnvironment, acceptance::Accepted, now_ms, }; use crate::Restore; +use piqueld_core::EventKind; use piqueld_core::{ NormalizedApplication, api::DeploymentOrigin, manifest::ApplicationTemplate, resource::ResolvedApplication, @@ -131,7 +132,7 @@ impl Store { Self::operation_event( &mut tx, &operation.id, - "rollback_requested", + EventKind::RollbackRequested, Some(&message), now_ms(), ) @@ -154,7 +155,7 @@ impl Store { Self::operation_event( &mut tx, &operation.id, - "rollback_unavailable", + EventKind::RollbackUnavailable, Some(reason), now_ms(), ) @@ -291,7 +292,7 @@ impl Store { .execute(&mut **tx) .await .map_err(StoreError::database)?; - Self::operation_event(tx, &operation.id, "target_resolved", None, now).await?; + Self::operation_event(tx, &operation.id, EventKind::TargetResolved, None, now).await?; Ok(operation) } } diff --git a/crates/piqueld-store/src/secret/deletion.rs b/crates/piqueld-store/src/secret/deletion.rs index db3f0e793..5e38b9a59 100644 --- a/crates/piqueld-store/src/secret/deletion.rs +++ b/crates/piqueld-store/src/secret/deletion.rs @@ -1,6 +1,7 @@ //! Reserve cleanup under the writer lock, then release it before Docker I/O. use super::{EnvironmentId, NormalizedApplication, SecretScope, SecretSource, Store, StoreError}; use crate::StoredEnvironment; +use piqueld_core::EventKind; use std::collections::{BTreeMap, BTreeSet}; /// A reserved secret deletion: its token and, per environment, the Swarm @@ -177,7 +178,7 @@ impl Store { let mut change = None; if deleted > 0 { let scope = SecretScope::Environment(application); - let event = ("secret_deleted", Self::SECRET_DELETED, name); + let event = (EventKind::SecretDeleted, Self::SECRET_DELETED, name); let by = author.actor.attribution(); Self::secret_event_on(&mut tx, scope, event, by, super::now_ms()).await?; change = Some(Self::deletion_change(name, deletion_id, "completed")); diff --git a/crates/piqueld-store/src/secret/key.rs b/crates/piqueld-store/src/secret/key.rs index 8388bf46c..6c7082d01 100644 --- a/crates/piqueld-store/src/secret/key.rs +++ b/crates/piqueld-store/src/secret/key.rs @@ -1,6 +1,7 @@ //! Authenticate the database's key before accepting any new ciphertext. use super::{Envelope, SecretCipher, SecretOwner, Store, StoreError}; use crate::secrets::KeyFailure; +use piqueld_core::EventKind; use piqueld_core::api::{CheckStatus, SecretKeyRecovery, SystemCheck, SystemCheckId}; /// What a master key makes of the stored values and webhook secrets. @@ -296,11 +297,12 @@ impl Store { let now = super::now_ms(); let by = author.actor.attribution(); let operator = by.operator_uid(); + let discarded = EventKind::SecretValuesDiscarded.as_str(); // Each affected environment's and application's history explains why // its values need replacing. - sqlx::query!("INSERT INTO events(application_id,environment_id,kind,message,created_at_ms,actor_user_id,actor_credential_id,actor_operator_uid) SELECT (SELECT application_id FROM environments WHERE id=secret_versions.environment_id),environment_id,'secret_values_discarded','Secret key recovery discarded '||COUNT(*)||' stored values; store replacements, then deploy',?1,?2,?3,?4 FROM secret_versions WHERE available=1 GROUP BY environment_id",now,by.user_id,by.credential_id,operator) + sqlx::query!("INSERT INTO events(application_id,environment_id,kind,message,created_at_ms,actor_user_id,actor_credential_id,actor_operator_uid) SELECT (SELECT application_id FROM environments WHERE id=secret_versions.environment_id),environment_id,?5,'Secret key recovery discarded '||COUNT(*)||' stored values; store replacements, then deploy',?1,?2,?3,?4 FROM secret_versions WHERE available=1 GROUP BY environment_id",now,by.user_id,by.credential_id,operator,discarded) .execute(&mut *tx).await.map_err(StoreError::database)?; - sqlx::query!("INSERT INTO events(application_id,kind,message,created_at_ms,actor_user_id,actor_credential_id,actor_operator_uid) SELECT application_id,'secret_values_discarded','Secret key recovery discarded '||COUNT(*)||' stored values; store replacements, then deploy',?1,?2,?3,?4 FROM application_secret_versions WHERE available=1 GROUP BY application_id",now,by.user_id,by.credential_id,operator) + sqlx::query!("INSERT INTO events(application_id,kind,message,created_at_ms,actor_user_id,actor_credential_id,actor_operator_uid) SELECT application_id,?5,'Secret key recovery discarded '||COUNT(*)||' stored values; store replacements, then deploy',?1,?2,?3,?4 FROM application_secret_versions WHERE available=1 GROUP BY application_id",now,by.user_id,by.credential_id,operator,discarded) .execute(&mut *tx).await.map_err(StoreError::database)?; sqlx::query!( "UPDATE secret_versions SET available=0,nonce=X'',ciphertext=X'' WHERE available=1" diff --git a/crates/piqueld-store/src/secret/mod.rs b/crates/piqueld-store/src/secret/mod.rs index fbeef3370..7f8f1dce3 100644 --- a/crates/piqueld-store/src/secret/mod.rs +++ b/crates/piqueld-store/src/secret/mod.rs @@ -15,6 +15,7 @@ use super::{ }; use crate::secrets::{Envelope, Generate, SecretCipher, SecretOwner}; use anyhow::Context; +use piqueld_core::EventKind; use piqueld_core::{ ApplicationId, api::SecretMetadata, @@ -185,7 +186,7 @@ impl Store { sqlx::query!("INSERT INTO secret_versions(environment_id,name,generation,swarm_name,nonce,ciphertext) VALUES(?1,?2,?3,?4,?5,?6)",id,name,generation,swarm_name,envelope.nonce,envelope.ciphertext).execute(&mut **tx).await.map_err(StoreError::database)?; let (scope, by) = (SecretScope::Environment(application), actor.attribution()); let message = format!("Stored secret version {generation}"); - Self::secret_event_on(tx, scope, ("secret_saved", &message, name), by, now).await?; + Self::secret_event_on(tx, scope, (EventKind::SecretSaved, &message, name), by, now).await?; Ok(SecretMetadata { name: name.into(), generation, @@ -199,11 +200,12 @@ impl Store { pub(super) async fn secret_event_on( connection: &mut SqliteConnection, scope: SecretScope<'_>, - (kind, message, name): (&str, &str, &str), + (kind, message, name): (EventKind, &str, &str), by: Attribution<'_>, now: i64, ) -> Result<(), StoreError> { let operator = by.operator_uid(); + let kind = kind.as_str(); match scope { SecretScope::Application(id) => { let id = id.as_str(); diff --git a/crates/piqueld-store/src/secret/stored/mod.rs b/crates/piqueld-store/src/secret/stored/mod.rs index 2d9a5dfb8..67256e22f 100644 --- a/crates/piqueld-store/src/secret/stored/mod.rs +++ b/crates/piqueld-store/src/secret/stored/mod.rs @@ -6,6 +6,7 @@ use super::{ deletion::SecretDeletion, now_ms, }; use crate::{Actor, Author}; +use piqueld_core::EventKind; use piqueld_core::{ ApiErrorCode, ApplicationId, EnvironmentId, ValidationError, ValidationErrors, access::Permission, @@ -227,7 +228,8 @@ impl Store { } let (scope, by) = (SecretScope::Application(application), actor.attribution()); let message = format!("Stored secret version {generation}"); - Self::secret_event_on(&mut tx, scope, ("secret_saved", &message, name), by, now).await?; + let event = (EventKind::SecretSaved, message.as_str(), name); + Self::secret_event_on(&mut tx, scope, event, by, now).await?; let secret = Self::stored_secret_on(&mut tx, application, name).await?; let target = (Some(application.as_str()), None); author @@ -267,7 +269,7 @@ impl Store { let description = Self::write_access_on(&mut tx, application, name, access).await?; let (scope, by) = (SecretScope::Application(application), actor.attribution()); let message = format!("Allowed {description} to mount the secret"); - let event = ("secret_access_changed", message.as_str(), name); + let event = (EventKind::SecretAccessChanged, message.as_str(), name); Self::secret_event_on(&mut tx, scope, event, by, now_ms()).await?; let secret = Self::stored_secret_on(&mut tx, application, name).await?; let change = format!("secret {name:?} access {description}"); @@ -529,7 +531,7 @@ impl Store { let mut change = None; if deleted > 0 { let scope = SecretScope::Application(application); - let event = ("secret_deleted", Self::SECRET_DELETED, name); + let event = (EventKind::SecretDeleted, Self::SECRET_DELETED, name); let by = author.actor.attribution(); Self::secret_event_on(&mut tx, scope, event, by, now_ms()).await?; change = Some(Self::deletion_change(name, deletion_id, "completed")); diff --git a/crates/piqueld-store/src/status.rs b/crates/piqueld-store/src/status.rs index a9c70fb76..03f5f7075 100644 --- a/crates/piqueld-store/src/status.rs +++ b/crates/piqueld-store/src/status.rs @@ -3,6 +3,7 @@ use super::{ ApplicationState, EnvironmentId, EnvironmentStatus, Store, StoreError, decode_name, now_ms, }; +use piqueld_core::EventKind; use sqlx::{Sqlite, SqliteConnection, Transaction}; impl Store { @@ -57,8 +58,14 @@ impl Store { let changed = sqlx::query!("UPDATE environment_status SET state=?1,message=?2,updated_at_ms=?3 WHERE (state!=?1 OR message IS NOT ?2) AND environment_id=(SELECT environment_id FROM operations WHERE id=?4) AND ?4=(SELECT latest.id FROM operations latest WHERE latest.environment_id=environment_status.environment_id ORDER BY latest.created_at_ms DESC,latest.id DESC LIMIT 1)",state,message,now,operation_id) .execute(&mut *tx).await.map_err(StoreError::database)?.rows_affected(); if changed == 1 { - Self::operation_event(&mut tx, operation_id, "status_changed", Some(state), now) - .await?; + Self::operation_event( + &mut tx, + operation_id, + EventKind::StatusChanged, + Some(state), + now, + ) + .await?; } let current=sqlx::query_scalar!("SELECT id FROM operations WHERE environment_id=(SELECT environment_id FROM operations WHERE id=?1) ORDER BY created_at_ms DESC,id DESC LIMIT 1",operation_id).fetch_optional(&mut *tx).await.map_err(StoreError::database)?.flatten(); tx.commit().await.map_err(StoreError::database)?; @@ -158,7 +165,8 @@ impl Store { let changed=sqlx::query!("UPDATE environment_status SET runtime_health=?1 WHERE runtime_health IS NOT ?1 AND environment_id=(SELECT environment_id FROM operations WHERE id=?2) AND ?2=(SELECT latest.id FROM operations latest WHERE latest.environment_id=environment_status.environment_id ORDER BY latest.created_at_ms DESC,latest.id DESC LIMIT 1)",health,operation_id).execute(&mut *tx).await.map_err(StoreError::database)?.rows_affected(); sqlx::query!("UPDATE environment_status SET health_observed_at_ms=?1 WHERE environment_id=(SELECT environment_id FROM operations WHERE id=?2) AND ?2=(SELECT id FROM operations WHERE environment_id=environment_status.environment_id ORDER BY created_at_ms DESC,id DESC LIMIT 1)",now,operation_id).execute(&mut *tx).await.map_err(StoreError::database)?; if changed == 1 { - sqlx::query!("INSERT INTO events(application_id,environment_id,operation_id,generation,kind,message,created_at_ms) SELECT (SELECT application_id FROM environments WHERE id=operations.environment_id),environment_id,id,generation,'health_changed',?1,?2 FROM operations WHERE id=?3",health,now,operation_id).execute(&mut *tx).await.map_err(StoreError::database)?; + let event_kind = EventKind::HealthChanged.as_str(); + sqlx::query!("INSERT INTO events(application_id,environment_id,operation_id,generation,kind,message,created_at_ms) SELECT (SELECT application_id FROM environments WHERE id=operations.environment_id),environment_id,id,generation,?4,?1,?2 FROM operations WHERE id=?3",health,now,operation_id,event_kind).execute(&mut *tx).await.map_err(StoreError::database)?; } tx.commit().await.map_err(StoreError::database) } diff --git a/crates/piqueld-store/src/stopped.rs b/crates/piqueld-store/src/stopped.rs index 0dee5b27f..a193844f6 100644 --- a/crates/piqueld-store/src/stopped.rs +++ b/crates/piqueld-store/src/stopped.rs @@ -1,6 +1,7 @@ //! Stopped environments, whose services run no replicas and whose routes //! the gateway doesn't serve, until they are started or deployed again. use super::{Store, StoreError, acceptance::Accepted}; +use piqueld_core::EventKind; use piqueld_core::{EnvironmentId, Operation}; use sqlx::{Sqlite, Transaction}; @@ -119,14 +120,14 @@ impl Store { .map_err(StoreError::database)?; let (kind, message) = if stopped { ( - "environment_stopped", + EventKind::EnvironmentStopped, format!( "environment {name} is stopped: its services scale to zero and its routes are withdrawn" ), ) } else { ( - "environment_started", + EventKind::EnvironmentStarted, format!("environment {name} is started"), ) }; diff --git a/crates/piqueld-store/src/sync.rs b/crates/piqueld-store/src/sync.rs index b0f488c1d..6dbfaed25 100644 --- a/crates/piqueld-store/src/sync.rs +++ b/crates/piqueld-store/src/sync.rs @@ -5,6 +5,7 @@ use super::acceptance::Accepted; use super::{Author, Store, StoreError, StoredEnvironment, now_ms}; use crate::secrets::{Envelope, Generate, SecretCipher, SecretOwner}; use crate::{ListedHead, MutationResponse, SyncOutcome}; +use piqueld_core::EventKind; use piqueld_core::{ ApplicationId, EnvironmentId, access::{AppPermission, Permission}, @@ -173,7 +174,14 @@ impl Store { ) .await?; let message = format!("branch {branch} moved to {head}"); - Self::operation_event(tx, &operation.id, "branch_synced", Some(&message), now).await?; + Self::operation_event( + tx, + &operation.id, + EventKind::BranchSynced, + Some(&message), + now, + ) + .await?; Self::record_synced_on(tx, id, Some(head), now).await?; Ok(SyncOutcome::Deployed(AcceptedOperation::from(&operation))) } @@ -325,7 +333,8 @@ impl Store { } else { format!("pushes no longer deploy environment {name}") }; - Self::environment_event_on(tx, row, "environment_sync_changed", &message, now).await?; + Self::environment_event_on(tx, row, EventKind::EnvironmentSyncChanged, &message, now) + .await?; Ok(true) } @@ -438,13 +447,15 @@ impl Store { .map_err(StoreError::database)?; let by = actor.attribution(); let operator = by.operator_uid(); + let event_kind = EventKind::WebhookSecretGenerated.as_str(); sqlx::query!( - "INSERT INTO events(application_id,kind,message,created_at_ms,actor_user_id,actor_credential_id,actor_operator_uid) VALUES(?1,'webhook_secret_generated','Generated a new webhook secret; the previous one no longer verifies',?2,?3,?4,?5)", + "INSERT INTO events(application_id,kind,message,created_at_ms,actor_user_id,actor_credential_id,actor_operator_uid) VALUES(?1,?6,'Generated a new webhook secret; the previous one no longer verifies',?2,?3,?4,?5)", id, now, by.user_id, by.credential_id, - operator + operator, + event_kind, ) .execute(&mut *tx) .await diff --git a/crates/piqueld-store/src/telemetry.rs b/crates/piqueld-store/src/telemetry.rs index c7488d484..358d3ab9f 100644 --- a/crates/piqueld-store/src/telemetry.rs +++ b/crates/piqueld-store/src/telemetry.rs @@ -1,6 +1,7 @@ //! Environments granted the daemon's telemetry, which their receiving //! service gets from every application. use super::{Store, StoreError, acceptance::Accepted}; +use piqueld_core::EventKind; use piqueld_core::api::DiagnosticView; use piqueld_core::{EnvironmentId, PlanDiagnostic, ResolvedApplication, ServiceName}; use sqlx::{Sqlite, Transaction}; @@ -105,8 +106,14 @@ impl Store { } else { format!("environment {name} no longer receives telemetry") }; - Self::environment_event_on(tx, row, "environment_telemetry_changed", &message, now) - .await?; + Self::environment_event_on( + tx, + row, + EventKind::EnvironmentTelemetryChanged, + &message, + now, + ) + .await?; } Ok(Self::environment_accepted(tx, id).await?.changing(changed)) } diff --git a/crates/piqueld-store/src/timeline.rs b/crates/piqueld-store/src/timeline.rs index cba1d9ee0..11cd4c186 100644 --- a/crates/piqueld-store/src/timeline.rs +++ b/crates/piqueld-store/src/timeline.rs @@ -1,5 +1,6 @@ //! What an operation's timeline expects, from its environment's history. use super::{Store, StoreError, decode_name}; +use piqueld_core::EventKind; use piqueld_core::Operation; use piqueld_core::timeline::{ExpectedStep, StepKey}; use std::collections::BTreeMap; @@ -50,14 +51,16 @@ impl Store { }; let ids = serde_json::to_string(&previous.iter().map(|row| &row.id).collect::>()) .map_err(StoreError::corrupt)?; + let event_kind = EventKind::ActionSucceeded.as_str(); let actions = sqlx::query!( r#"SELECT operation_id AS "operation_id!", attempt, phase AS "phase!", resource, duration_ms AS "duration_ms!" FROM events - WHERE operation_id IN (SELECT value FROM json_each(?1)) AND kind='action_succeeded' + WHERE operation_id IN (SELECT value FROM json_each(?1)) AND kind=?2 AND phase IS NOT NULL AND duration_ms IS NOT NULL ORDER BY id"#, ids, + event_kind, ) .fetch_all(&mut *tx) .await diff --git a/docs/dev/rust-conventions.md b/docs/dev/rust-conventions.md index f8476d10e..3ec496cd6 100644 --- a/docs/dev/rust-conventions.md +++ b/docs/dev/rust-conventions.md @@ -36,6 +36,14 @@ still reads a code it doesn't know yet; compare one with `ApiErrorCode::parse` or `==`. Operation diagnostics recorded in history have their own `DiagnosticCode`. +Other strings that cross crates are named the same way, as a `string_enum!` +in `piqueld-core`: the kind of each history event is an `EventKind`. Record +and compare one through its variant, never its string, including in SQL, where +it is bound as a parameter, unless a partial index on that kind serves the +query: SQLite only uses one for a literal. `Event.kind` stays a `String`, since history holds +kinds older daemons recorded and a client may read kinds a newer daemon adds; +compare it with `Event::known_kind` or `==`. + Production code never panics without saying why: `expect_used`, `panic`, `todo`, `unimplemented` and `dbg_macro` are denied outside tests. Return an error when the input can be wrong. An invariant the types can't express keeps From 19f7385bb5d6d1e60df0e14742ad1c67e0e16a0f Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 14:49:16 +0100 Subject: [PATCH 2/3] docs(dev): wrap the event kind convention --- docs/dev/rust-conventions.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/dev/rust-conventions.md b/docs/dev/rust-conventions.md index 3ec496cd6..6a190c1bc 100644 --- a/docs/dev/rust-conventions.md +++ b/docs/dev/rust-conventions.md @@ -38,11 +38,11 @@ their own `DiagnosticCode`. Other strings that cross crates are named the same way, as a `string_enum!` in `piqueld-core`: the kind of each history event is an `EventKind`. Record -and compare one through its variant, never its string, including in SQL, where -it is bound as a parameter, unless a partial index on that kind serves the -query: SQLite only uses one for a literal. `Event.kind` stays a `String`, since history holds -kinds older daemons recorded and a client may read kinds a newer daemon adds; -compare it with `Event::known_kind` or `==`. +and compare one through its variant, never its string. In SQL, bind it as a +parameter, unless a partial index on it serves the query: SQLite only uses one +for a literal. `Event.kind` stays a `String`, since history holds kinds older +daemons recorded and a client may read kinds a newer daemon adds; compare it +with `Event::known_kind` or `==`. Production code never panics without saying why: `expect_used`, `panic`, `todo`, `unimplemented` and `dbg_macro` are denied outside tests. Return an From 311f5c25131837de816fa095b121bd16c99f03ae Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 16:10:33 +0100 Subject: [PATCH 3/3] refactor(store): bind the denial-burst kind and check the schema's kinds The cooldown query binds `EventKind::AccessDenialBurst` like every other site: `EXPLAIN QUERY PLAN` shows SQLite still searches `security_denial_bursts` once the value is bound, so the literal it kept was never needed. Migrations can't name `EventKind`, so a store test reads the migrated schema and checks that every kind an index or view spells out (the denial-burst index, the `operation_progress` view) parses as one. `compared_as_string!` takes one type, and `EventKind` drops the serde derives nothing uses, with the test of them: the macro already rejects a duplicate string (`unreachable_patterns`). Part of PQD-161 --- crates/piqueld-core/src/event.rs | 24 ----- crates/piqueld-core/src/names.rs | 4 +- crates/piqueld-store/src/auth/security.rs | 11 +- .../piqueld-store/src/observability/event.rs | 101 ++++++++++++++++++ docs/dev/rust-conventions.md | 11 +- 5 files changed, 115 insertions(+), 36 deletions(-) diff --git a/crates/piqueld-core/src/event.rs b/crates/piqueld-core/src/event.rs index 235b92318..2db916cf4 100644 --- a/crates/piqueld-core/src/event.rs +++ b/crates/piqueld-core/src/event.rs @@ -75,7 +75,6 @@ impl Event { } string_enum! { - #[serde] /// Every kind of event the daemon records, as stored in history and sent /// as [`Event::kind`]. A kind never changes, but new ones are added. pub enum EventKind { @@ -298,26 +297,3 @@ impl std::fmt::Display for EventActor { } } } - -#[cfg(test)] -mod tests { - use super::EventKind; - use std::collections::BTreeSet; - - /// Each kind is stored and sent as its own string and read back as - /// itself, and no two share one. - #[test] - fn kinds_serialize_to_distinct_strings() { - for kind in EventKind::ALL { - let value = kind.as_str(); - assert_eq!(serde_json::to_value(kind).unwrap(), value); - assert_eq!( - serde_json::from_value::(value.into()).unwrap(), - kind - ); - assert_eq!(EventKind::parse(value), Some(kind)); - } - let values = EventKind::ALL.map(EventKind::as_str); - assert_eq!(BTreeSet::from(values).len(), values.len()); - } -} diff --git a/crates/piqueld-core/src/names.rs b/crates/piqueld-core/src/names.rs index 58d872d1b..e4815ca2b 100644 --- a/crates/piqueld-core/src/names.rs +++ b/crates/piqueld-core/src/names.rs @@ -193,7 +193,7 @@ pub(crate) use string_enum; // daemon adds or old rows hold, be built from and compared with a // `string_enum!`'s values: `event.kind == EventKind::OperationFailed`. macro_rules! compared_as_string { - ($($name:ident),+ $(,)?) => {$( + ($name:ident) => { impl From<$name> for String { fn from(value: $name) -> Self { value.as_str().to_owned() @@ -211,7 +211,7 @@ macro_rules! compared_as_string { self == value.as_str() } } - )+}; + }; } pub(crate) use compared_as_string; diff --git a/crates/piqueld-store/src/auth/security.rs b/crates/piqueld-store/src/auth/security.rs index 45b2f96d2..4af7aa236 100644 --- a/crates/piqueld-store/src/auth/security.rs +++ b/crates/piqueld-store/src/auth/security.rs @@ -184,14 +184,14 @@ impl Store { let (window, cooldown) = (now - 60_000, now - DENIAL_BURST_COOLDOWN_MS); // Runs under the writer lock on every refusal, so it stays bounded: // the cooldown only reads this address and account's recent bursts - // (`security_denial_bursts`, which needs the kind spelled out), and - // the count stops at the threshold (`audit_refusals`). The host - // operator, which has no account, is told apart from anonymous - // callers by its Unix user. + // (`security_denial_bursts`), and the count stops at the threshold + // (`audit_refusals`). The host operator, which has no account, is + // told apart from anonymous callers by its Unix user. let operator = actor.operator_uid(); + let event_kind = EventKind::AccessDenialBurst.as_str(); let burst = sqlx::query_scalar!( r#"SELECT NOT EXISTS(SELECT 1 FROM events - WHERE kind='access_denial_burst' AND resource IS ?2 AND actor_user_id IS ?3 + WHERE kind=?7 AND resource IS ?2 AND actor_user_id IS ?3 AND actor_operator_uid IS ?6 AND created_at_ms>=?5) AND (SELECT COUNT(*) FROM (SELECT 1 FROM audit_events WHERE outcome='denied' AND user_id IS ?3 AND peer IS ?2 @@ -204,6 +204,7 @@ impl Store { DENIAL_BURST, cooldown, operator, + event_kind, ) .fetch_one(&mut *db) .await diff --git a/crates/piqueld-store/src/observability/event.rs b/crates/piqueld-store/src/observability/event.rs index 70fe878dc..6e94a3e64 100644 --- a/crates/piqueld-store/src/observability/event.rs +++ b/crates/piqueld-store/src/observability/event.rs @@ -867,4 +867,105 @@ mod tests { } } } + + /// The schema can't name an `EventKind`, so each kind its indexes, + /// triggers and views spell out (`security_denial_bursts`, the + /// `operation_progress` view) must parse as one: a kind it misspells, or + /// that a variant stops writing, would leave it matching nothing. + #[tokio::test] + async fn kinds_the_schema_spells_out_are_event_kinds() { + let (_temp, store) = Store::temporary().await; + let objects: Vec<(String, String)> = + sqlx::query_as("SELECT tbl_name, sql FROM sqlite_master WHERE sql IS NOT NULL") + .fetch_all(&store.pool) + .await + .unwrap(); + let mut kinds = Vec::new(); + for (table, sql) in &objects { + kinds.extend(event_kinds_in(table, sql)); + } + assert!(!kinds.is_empty(), "the schema spells out event kinds"); + for kind in kinds { + assert!(EventKind::parse(&kind).is_some(), "{kind}"); + } + } + + /// The kinds `sql`, a schema object on `table`, compares an events row's + /// `kind` with: `kind = '…'` or `kind IN ('…', …)`, on `events` itself or + /// an alias of it, such as `failed.kind` after `FROM events failed`. + fn event_kinds_in(table: &str, sql: &str) -> Vec { + let tokens = sql_tokens(sql); + let token = |index: usize| tokens.get(index).map_or("", String::as_str); + // Bare `kind` is the events row's only in an object on `events`. + let mut rows = vec![if table == "events" { "" } else { "events" }.to_owned()]; + for (index, name) in tokens.iter().enumerate() { + let alias = token(index + 1); + let keyword = ["as", "where", "on", "set", "join", "left", "order", "limit"]; + if name.eq_ignore_ascii_case("events") + && alias.starts_with(|c: char| c.is_ascii_alphabetic()) + && !keyword.iter().any(|word| alias.eq_ignore_ascii_case(word)) + { + rows.push(alias.to_owned()); + } + } + let mut kinds = Vec::new(); + for index in 0..tokens.len() { + let qualifier = if index >= 2 && token(index - 1) == "." { + token(index - 2) + } else { + "" + }; + if token(index) != "kind" || !rows.iter().any(|row| row == qualifier) { + continue; + } + let literals = match token(index + 1).to_ascii_lowercase().as_str() { + "=" => index + 2..index + 3, + "in" => { + index + 3 + ..(index + 3..tokens.len()) + .find(|&i| token(i) == ")") + .unwrap_or(index + 3) + } + _ => continue, + }; + kinds.extend( + tokens[literals] + .iter() + .filter_map(|literal| literal.strip_prefix('\'')) + .map(|literal| literal.trim_end_matches('\'').to_owned()), + ); + } + kinds + } + + /// `sql` split into identifiers, quoted strings (quotes kept) and single + /// punctuation characters. + fn sql_tokens(sql: &str) -> Vec { + let mut tokens = Vec::new(); + let mut chars = sql.chars().peekable(); + while let Some(first) = chars.next() { + if first.is_whitespace() { + continue; + } + let mut token = first.to_string(); + if first == '\'' { + for next in chars.by_ref() { + token.push(next); + if next == '\'' { + break; + } + } + } else if first.is_ascii_alphanumeric() || first == '_' { + while let Some(&next) = chars.peek() { + if !(next.is_ascii_alphanumeric() || next == '_') { + break; + } + token.push(next); + chars.next(); + } + } + tokens.push(token); + } + tokens + } } diff --git a/docs/dev/rust-conventions.md b/docs/dev/rust-conventions.md index 6a190c1bc..dc3a89e36 100644 --- a/docs/dev/rust-conventions.md +++ b/docs/dev/rust-conventions.md @@ -38,11 +38,12 @@ their own `DiagnosticCode`. Other strings that cross crates are named the same way, as a `string_enum!` in `piqueld-core`: the kind of each history event is an `EventKind`. Record -and compare one through its variant, never its string. In SQL, bind it as a -parameter, unless a partial index on it serves the query: SQLite only uses one -for a literal. `Event.kind` stays a `String`, since history holds kinds older -daemons recorded and a client may read kinds a newer daemon adds; compare it -with `Event::known_kind` or `==`. +and compare one through its variant, never its string, and in SQL bind it as +a parameter. Migrations can't name it, so a store test checks that every kind +the schema spells out, in an index or a view, is an `EventKind`. `Event.kind` +stays a `String`, since history holds kinds older daemons recorded and a +client may read kinds a newer daemon adds; compare it with +`Event::known_kind` or `==`. Production code never panics without saying why: `expect_used`, `panic`, `todo`, `unimplemented` and `dbg_macro` are denied outside tests. Return an