use std::fmt;
use std::str::FromStr;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::did::DidNostr;
use crate::encoding;
use crate::grant::OfferedGrant;
use crate::id::{OperationId, ParseIdError, Sha256Digest, UnixTime};
use crate::manifest::{ContainerPath, ImageId, Manifest, ParseNameError, WorkspaceMode};
use crate::members::Enforcement;
macro_rules! hex16_id {
($(#[$doc:meta])* $name:ident) => {
$(#[$doc])*
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct $name([u8; 16]);
impl $name {
pub const fn from_bytes(bytes: [u8; 16]) -> Self {
Self(bytes)
}
pub const fn as_bytes(&self) -> &[u8; 16] {
&self.0
}
pub fn to_hex(&self) -> String {
hex::encode(self.0)
}
}
impl From<[u8; 16]> for $name {
fn from(bytes: [u8; 16]) -> Self {
Self(bytes)
}
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.to_hex())
}
}
impl fmt::Debug for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, concat!(stringify!($name), "({})"), self.to_hex())
}
}
impl FromStr for $name {
type Err = ParseIdError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
encoding::decode_lower_hex::<16>(text)
.map(Self)
.ok_or(ParseIdError::InvalidHex { expected: 32 })
}
}
impl Serialize for $name {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.to_hex())
}
}
impl<'de> Deserialize<'de> for $name {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let text = String::deserialize(deserializer)?;
text.parse().map_err(serde::de::Error::custom)
}
}
};
}
hex16_id!(
ApplicationId
);
hex16_id!(
InstallationId
);
hex16_id!(
JobId
);
macro_rules! named_enum {
($(#[$doc:meta])* $name:ident { $($(#[$vdoc:meta])* $variant:ident => $text:literal,)+ }) => {
$(#[$doc])*
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum $name {
$($(#[$vdoc])* $variant,)+
}
impl $name {
pub const ALL: &'static [Self] = &[$(Self::$variant,)+];
pub fn as_str(self) -> &'static str {
match self {
$(Self::$variant => $text,)+
}
}
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for $name {
type Err = ParseNameError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
Self::ALL
.iter()
.copied()
.find(|value| value.as_str() == text)
.ok_or(ParseNameError)
}
}
impl Serialize for $name {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for $name {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let text = String::deserialize(deserializer)?;
text.parse().map_err(|_| {
serde::de::Error::custom(concat!("not a known ", stringify!($name)))
})
}
}
};
}
named_enum!(
ApplicationState {
Approved => "approved",
Withdrawn => "withdrawn",
Disabled => "disabled",
}
);
impl ApplicationState {
pub fn is_terminal(self) -> bool {
matches!(self, Self::Disabled)
}
}
named_enum!(
InstallationState {
PendingConsent => "pending_consent",
Active => "active",
Withdrawn => "withdrawn",
Removed => "removed",
}
);
impl InstallationState {
pub fn is_terminal(self) -> bool {
matches!(self, Self::Withdrawn | Self::Removed)
}
}
named_enum!(
GrantState {
Offered => "offered",
Consented => "consented",
Withdrawn => "withdrawn",
CleanupReported => "cleanup_reported",
}
);
named_enum!(
JobState {
Pending => "pending",
Running => "running",
Succeeded => "succeeded",
Failed => "failed",
Cancelled => "cancelled",
Conflict => "conflict",
Skipped => "skipped",
}
);
impl JobState {
pub fn is_terminal(self) -> bool {
!matches!(self, Self::Pending | Self::Running)
}
}
named_enum!(
LeaseState {
Claimed => "claimed",
Started => "started",
Ended => "ended",
Revoked => "revoked",
Expired => "expired",
}
);
impl LeaseState {
pub fn is_current(self) -> bool {
matches!(self, Self::Claimed | Self::Started)
}
}
named_enum!(
KeyReason {
Suspension => "suspension",
Application => "application",
Withdrawal => "withdrawal",
Restore => "restore",
}
);
named_enum!(
KeyStatus {
Enabled => "enabled",
Disabled => "disabled",
Destroyed => "destroyed",
}
);
named_enum!(
KeysPart {
Disabling => "disabling",
Disabled => "disabled",
}
);
named_enum!(
WorkPart {
Stopping => "stopping",
Stopped => "stopped",
}
);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct EnforcementParts {
pub authorisation: Enforcement,
pub keys: KeysPart,
pub work: WorkPart,
}
impl EnforcementParts {
pub fn is_complete(&self) -> bool {
self.authorisation == Enforcement::Enforced
&& self.keys == KeysPart::Disabled
&& self.work == WorkPart::Stopped
}
}
named_enum!(
JobOutcome {
Created => "created",
Existing => "existing",
Conflict => "conflict",
InsufficientStorage => "insufficient_storage",
NotGranted => "not_granted",
LimitsNotApplied => "limits_not_applied",
LimitAboveCeiling => "limit_above_ceiling",
}
);
impl JobOutcome {
pub fn is_reportable(self) -> bool {
!matches!(self, Self::LimitsNotApplied | Self::LimitAboveCeiling)
}
}
named_enum!(
WorkspaceSlotState {
Free => "free",
Reserved => "reserved",
Assigned => "assigned",
WipePending => "wipe_pending",
Quarantined => "quarantined",
}
);
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct WorkspaceView {
pub slot: String,
pub state: WorkspaceSlotState,
pub usable_bytes: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct WorkspaceGrant {
pub slot: String,
pub usable_bytes: u64,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct JobCounts {
pub pending: u64,
pub running: u64,
pub succeeded: u64,
pub failed: u64,
pub cancelled: u64,
pub conflict: u64,
pub skipped: u64,
}
impl JobCounts {
fn slot(&mut self, state: JobState) -> &mut u64 {
match state {
JobState::Pending => &mut self.pending,
JobState::Running => &mut self.running,
JobState::Succeeded => &mut self.succeeded,
JobState::Failed => &mut self.failed,
JobState::Cancelled => &mut self.cancelled,
JobState::Conflict => &mut self.conflict,
JobState::Skipped => &mut self.skipped,
}
}
pub fn add(&mut self, state: JobState, count: u64) {
let slot = self.slot(state);
*slot = slot.saturating_add(count);
}
pub fn get(&self, state: JobState) -> u64 {
let mut copy = *self;
*copy.slot(state)
}
pub fn total(&self) -> u64 {
JobState::ALL
.iter()
.fold(0u64, |sum, state| sum.saturating_add(self.get(*state)))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ApproveApplicationRequest {
pub operation_id: OperationId,
pub manifest: serde_json::Value,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ApproveApplicationResponse {
pub application: ApplicationId,
pub state: ApplicationState,
pub image_id: ImageId,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ApplicationActionRequest {
pub operation_id: OperationId,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ApplicationStateResponse {
pub state: ApplicationState,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ApplicationView {
pub application: ApplicationId,
pub state: ApplicationState,
pub manifest: Manifest,
pub image_id: ImageId,
pub approved_at: UnixTime,
pub installations: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ApplicationList {
pub applications: Vec<ApplicationView>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CatalogueEntry {
pub application: ApplicationId,
pub manifest: Manifest,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Catalogue {
pub applications: Vec<CatalogueEntry>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CreateInstallationRequest {
pub operation_id: OperationId,
pub application: ApplicationId,
pub schedule_secs: u64,
#[serde(default)]
pub workspace: WorkspaceMode,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CreateInstallationResponse {
pub installation: InstallationId,
pub app_did: DidNostr,
pub grant: OfferedGrant,
pub state: InstallationState,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ConsentRequest {
pub operation_id: OperationId,
pub grant_sha256: Sha256Digest,
pub read_back: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ConsentResponse {
pub state: InstallationState,
pub workspace: Option<WorkspaceGrant>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RunRequest {
pub operation_id: OperationId,
pub period: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RunResponse {
pub job: JobId,
pub state: JobState,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct InstallationActionRequest {
pub operation_id: OperationId,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct WithdrawResponse {
pub state: InstallationState,
pub authorisation: Enforcement,
pub cleanup_pending: Vec<ContainerPath>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CleanupRequest {
pub operation_id: OperationId,
pub containers: Vec<ContainerPath>,
pub read_back: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CleanupResponse {
pub grant: GrantState,
pub cleanup_pending: Vec<ContainerPath>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ResumeInstallationResponse {
pub keys: KeyStatus,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct InstallationView {
pub installation: InstallationId,
pub application: ApplicationId,
pub owner: DidNostr,
pub state: InstallationState,
pub generation: u64,
pub schedule_secs: u64,
pub workspace: WorkspaceMode,
pub app_did: Option<DidNostr>,
pub created_at: UnixTime,
pub activated_at: Option<UnixTime>,
pub withdrawn_at: Option<UnixTime>,
pub key_reasons: Vec<KeyReason>,
pub grant: GrantState,
pub cleanup_pending: Vec<ContainerPath>,
pub enforcement: Option<EnforcementParts>,
pub jobs: JobCounts,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct InstallationList {
pub installations: Vec<InstallationView>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct JobView {
pub job: JobId,
pub period: u64,
pub state: JobState,
pub attempts: u32,
pub created_at: UnixTime,
pub next_eligible_at: Option<UnixTime>,
pub outcome: Option<JobOutcome>,
pub resource: Option<String>,
pub sha256: Option<Sha256Digest>,
pub length: Option<u64>,
pub exit_code: Option<i64>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct JobList {
pub installation: InstallationId,
pub jobs: Vec<JobView>,
}