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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions apps/piqueld/src/api/service/exec.rs
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -89,7 +90,7 @@ impl ExecSession {
/// including a disconnected client.
pub async fn run(self, io: ExecIo) -> Result<i64, ApplicationError> {
self.record(
"command_started",
EventKind::CommandStarted,
&format!("{} started a command in task {}", self.who, self.exec.task),
)
.await?;
Expand All @@ -103,15 +104,15 @@ 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?)
}

/// 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
Expand Down
56 changes: 27 additions & 29 deletions apps/piqueld/src/telemetry/journal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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
Expand All @@ -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<SpanData> {
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();
Expand All @@ -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)),
}
Expand All @@ -129,9 +127,9 @@ impl Journal {
/// The span of a finished action, and its build metrics.
fn action(&self, event: &Event, context: EventContext<'_>) -> Option<SpanData> {
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);
Expand Down Expand Up @@ -203,15 +201,15 @@ 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(),
};
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);
Expand Down
22 changes: 2 additions & 20 deletions crates/piqueld-core/src/api/error_code.rs
Original file line number Diff line number Diff line change
@@ -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]
Expand Down Expand Up @@ -578,25 +578,7 @@ string_enum! {
}
}

impl From<ApiErrorCode> 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<ApiErrorCode> 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<ApiErrorCode> for str {
fn eq(&self, code: &ApiErrorCode) -> bool {
self == code.as_str()
}
}
compared_as_string!(ApiErrorCode);

#[cfg(test)]
mod tests {
Expand Down
155 changes: 155 additions & 0 deletions crates/piqueld-core/src/event.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -20,6 +21,10 @@ pub struct Event {
/// Execution attempt for attempt-related events.
pub attempt: Option<u64>,
/// 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<String>,
Expand Down Expand Up @@ -61,6 +66,156 @@ 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> {
EventKind::parse(&self.kind)
}
}

string_enum! {
/// 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)]
Expand Down
2 changes: 1 addition & 1 deletion crates/piqueld-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
26 changes: 26 additions & 0 deletions crates/piqueld-core/src/names.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading