use serde::{Deserialize, Serialize};
use wist_contracts::API_VERSION_V1;
pub const API_VERSION: &str = API_VERSION_V1;
pub const POLL_WORK_KIND: &str = "poll_harvest_work";
pub const ACK_WORK_KIND: &str = "ack_harvest_work";
pub const REPORT_WORK_RESULT_KIND: &str = "report_harvest_work_result";
pub const ENROLL_KIND: &str = "submit_harvest_enrollment";
pub const RENEW_CERTIFICATE_KIND: &str = "renew_harvest_certificate";
pub const FAMILY_INVENTORY: &str = "inventory";
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HarvestSpec {
pub credential_ref: String,
pub vendor: String,
#[serde(default)]
pub assets: Vec<String>,
#[serde(default)]
pub regions: HarvestRegions,
pub cadence: HarvestCadence,
#[serde(default)]
pub rate: Option<HarvestRate>,
}
impl HarvestSpec {
pub fn is_scheduled(&self) -> bool {
!self.cadence.is_on_demand()
}
pub fn collects_nothing(&self) -> bool {
self.assets.is_empty()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum HarvestRegions {
Auto(String),
List(Vec<String>),
}
impl Default for HarvestRegions {
fn default() -> Self {
Self::Auto("auto".to_string())
}
}
impl HarvestRegions {
pub fn is_auto(&self) -> bool {
matches!(self, Self::Auto(value) if value == "auto")
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HarvestCadence {
pub mode: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub at: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub jitter_seconds: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub seconds: Option<u64>,
}
pub const CADENCE_DAILY: &str = "daily";
pub const CADENCE_INTERVAL: &str = "interval";
pub const CADENCE_ON_DEMAND: &str = "on_demand";
impl HarvestCadence {
pub fn daily(at: impl Into<String>, jitter_seconds: u64) -> Self {
Self {
mode: CADENCE_DAILY.to_string(),
at: Some(at.into()),
jitter_seconds: Some(jitter_seconds),
seconds: None,
}
}
pub fn interval(seconds: u64) -> Self {
Self {
mode: CADENCE_INTERVAL.to_string(),
at: None,
jitter_seconds: None,
seconds: Some(seconds),
}
}
pub fn on_demand() -> Self {
Self {
mode: CADENCE_ON_DEMAND.to_string(),
at: None,
jitter_seconds: None,
seconds: None,
}
}
pub fn is_on_demand(&self) -> bool {
self.mode == CADENCE_ON_DEMAND
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HarvestRate {
pub qps: f64,
#[serde(default)]
pub burst: f64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StandingHarvestWork {
pub work_id: String,
pub family: String,
pub spec: HarvestSpec,
#[serde(default)]
pub catalog_version: i64,
#[serde(default)]
pub proposal_id: Option<String>,
pub plan_version: i64,
pub effective_from: String,
pub status: String,
pub updated_by: String,
pub updated_at: String,
}
impl StandingHarvestWork {
pub fn is_active(&self) -> bool {
self.status == STATUS_ACTIVE
}
}
pub const STATUS_ACTIVE: &str = "active";
pub const STATUS_PAUSED: &str = "paused";
pub const STATUS_REVOKED: &str = "revoked";
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OneShotHarvestWork {
pub work_id: String,
pub action: String,
pub spec: OneShotHarvestSpec,
pub scheduled_at: String,
pub deadline_at: String,
pub timeout_seconds: i64,
pub interruptible: bool,
pub status: String,
#[serde(default)]
pub attempt: i64,
pub issued_by: String,
pub issued_at: String,
}
impl OneShotHarvestWork {
pub fn is_outstanding(&self) -> bool {
!ONE_SHOT_TERMINAL_STATUSES.contains(&self.status.as_str())
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OneShotHarvestSpec {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub assets: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub regions: Option<HarvestRegions>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fresh: Option<bool>,
}
pub const ONE_SHOT_WORK_STATUSES: &[&str] = &[
"dispatched",
"accepted",
"running",
"succeeded",
"failed",
"timed_out",
"canceled",
"expired",
];
pub const ONE_SHOT_TERMINAL_STATUSES: &[&str] =
&["succeeded", "failed", "timed_out", "canceled", "expired"];
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HarvestWorkGrant {
pub worker_id: String,
pub source_code: String,
pub standing: Option<StandingHarvestWork>,
#[serde(default)]
pub one_shot: Vec<OneShotHarvestWork>,
pub sequence: i64,
pub granted_at: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PollHarvestWork {
pub api_version: String,
pub kind: String,
pub worker_id: String,
pub instance_id: String,
pub last_seen_sequence: i64,
pub wait_ms: i64,
pub requested_at: String,
}
impl PollHarvestWork {
pub fn new(
worker_id: impl Into<String>,
instance_id: impl Into<String>,
last_seen_sequence: i64,
requested_at: impl Into<String>,
) -> Self {
Self {
api_version: API_VERSION.to_string(),
kind: POLL_WORK_KIND.to_string(),
worker_id: worker_id.into(),
instance_id: instance_id.into(),
last_seen_sequence,
wait_ms: 0,
requested_at: requested_at.into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AckHarvestWork {
pub api_version: String,
pub kind: String,
pub worker_id: String,
pub instance_id: String,
pub work_id: String,
pub plan_version: i64,
pub acknowledged_at: String,
}
impl AckHarvestWork {
pub fn new(
worker_id: impl Into<String>,
instance_id: impl Into<String>,
work_id: impl Into<String>,
plan_version: i64,
acknowledged_at: impl Into<String>,
) -> Self {
Self {
api_version: API_VERSION.to_string(),
kind: ACK_WORK_KIND.to_string(),
worker_id: worker_id.into(),
instance_id: instance_id.into(),
work_id: work_id.into(),
plan_version,
acknowledged_at: acknowledged_at.into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HarvestWorkAccepted {
pub work_id: String,
pub status: String,
pub accepted_at: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ReportHarvestResult {
pub api_version: String,
pub kind: String,
pub worker_id: String,
pub instance_id: String,
pub work_id: String,
pub status: String,
#[serde(default)]
pub detail: String,
pub reported_at: String,
}
impl ReportHarvestResult {
pub fn new(
worker_id: impl Into<String>,
instance_id: impl Into<String>,
work_id: impl Into<String>,
status: impl Into<String>,
detail: impl Into<String>,
reported_at: impl Into<String>,
) -> Self {
Self {
api_version: API_VERSION.to_string(),
kind: REPORT_WORK_RESULT_KIND.to_string(),
worker_id: worker_id.into(),
instance_id: instance_id.into(),
work_id: work_id.into(),
status: status.into(),
detail: detail.into(),
reported_at: reported_at.into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HarvestResultAccepted {
pub work_id: String,
pub status: String,
pub accepted_at: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HarvestEnrollmentRequest {
pub api_version: String,
pub kind: String,
pub ticket: String,
pub worker_id: String,
pub source_code: String,
pub instance_id: String,
pub certificate_signing_request: String,
pub requested_at: String,
}
impl HarvestEnrollmentRequest {
pub fn new(
ticket: impl Into<String>,
worker_id: impl Into<String>,
source_code: impl Into<String>,
instance_id: impl Into<String>,
certificate_signing_request: impl Into<String>,
requested_at: impl Into<String>,
) -> Self {
Self {
api_version: API_VERSION.to_string(),
kind: ENROLL_KIND.to_string(),
ticket: ticket.into(),
worker_id: worker_id.into(),
source_code: source_code.into(),
instance_id: instance_id.into(),
certificate_signing_request: certificate_signing_request.into(),
requested_at: requested_at.into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HarvestEnrollmentEnvelope {
pub result: HarvestEnrollmentOutcome,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HarvestEnrollmentOutcome {
pub status: HarvestEnrollmentStatus,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason_code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub worker_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub instance_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub certificate_pem: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ca_certificate_pem: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub not_after: Option<String>,
}
impl HarvestEnrollmentOutcome {
pub fn rejected(reason_code: impl Into<String>) -> Self {
Self {
status: HarvestEnrollmentStatus::Rejected,
reason_code: Some(reason_code.into()),
worker_id: None,
instance_id: None,
certificate_pem: None,
ca_certificate_pem: None,
not_after: None,
}
}
pub fn accepted(
worker_id: impl Into<String>,
instance_id: impl Into<String>,
certificate_pem: impl Into<String>,
ca_certificate_pem: impl Into<String>,
not_after: impl Into<String>,
) -> Self {
Self {
status: HarvestEnrollmentStatus::Accepted,
reason_code: None,
worker_id: Some(worker_id.into()),
instance_id: Some(instance_id.into()),
certificate_pem: Some(certificate_pem.into()),
ca_certificate_pem: Some(ca_certificate_pem.into()),
not_after: Some(not_after.into()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum HarvestEnrollmentStatus {
#[serde(rename = "accepted")]
Accepted,
#[serde(rename = "rejected")]
Rejected,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HarvestCertificateRenewal {
pub api_version: String,
pub kind: String,
pub worker_id: String,
pub instance_id: String,
pub certificate_signing_request: String,
pub requested_at: String,
}
impl HarvestCertificateRenewal {
pub fn new(
worker_id: impl Into<String>,
instance_id: impl Into<String>,
certificate_signing_request: impl Into<String>,
requested_at: impl Into<String>,
) -> Self {
Self {
api_version: API_VERSION.to_string(),
kind: RENEW_CERTIFICATE_KIND.to_string(),
worker_id: worker_id.into(),
instance_id: instance_id.into(),
certificate_signing_request: certificate_signing_request.into(),
requested_at: requested_at.into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HarvestCertificateRenewed {
pub certificate_pem: String,
pub ca_certificate_pem: String,
pub not_after: String,
}
#[cfg(test)]
mod tests {
use super::*;
fn spec() -> HarvestSpec {
HarvestSpec {
credential_ref: "tcloud:prod".to_string(),
vendor: "TENCENT_CLOUD".to_string(),
assets: vec!["vpc".to_string(), "subnet".to_string()],
regions: HarvestRegions::Auto("auto".to_string()),
cadence: HarvestCadence::daily("00:30", 300),
rate: Some(HarvestRate {
qps: 5.0,
burst: 5.0,
}),
}
}
#[test]
fn grant_round_trips_with_serde() {
let grant = HarvestWorkGrant {
worker_id: "harvest:tencent-cloud-prod".to_string(),
source_code: "tencent-cloud-prod".to_string(),
standing: Some(StandingHarvestWork {
work_id: "hsw:harvest:tencent-cloud-prod:inventory".to_string(),
family: FAMILY_INVENTORY.to_string(),
spec: spec(),
catalog_version: 0,
proposal_id: None,
plan_version: 3,
effective_from: "2026-11-14T00:00:00Z".to_string(),
status: STATUS_ACTIVE.to_string(),
updated_by: "admin".to_string(),
updated_at: "2026-11-14T08:00:00Z".to_string(),
}),
one_shot: vec![],
sequence: 13,
granted_at: "2026-11-14T08:30:05Z".to_string(),
};
let json = serde_json::to_string(&grant).expect("serialize");
let decoded: HarvestWorkGrant = serde_json::from_str(&json).expect("deserialize");
assert_eq!(decoded, grant);
}
#[test]
fn on_demand_cadence_is_not_scheduled() {
let mut value = spec();
value.cadence = HarvestCadence::on_demand();
assert!(!value.is_scheduled());
assert!(spec().is_scheduled());
}
#[test]
fn cadence_encodes_mode_and_rejects_unknown_fields() {
let daily = serde_json::to_value(HarvestCadence::daily("00:30", 300)).unwrap();
assert_eq!(daily["mode"], "daily");
assert_eq!(daily["at"], "00:30");
let interval = serde_json::to_value(HarvestCadence::interval(3600)).unwrap();
assert_eq!(interval["mode"], "interval");
let on_demand = serde_json::to_value(HarvestCadence::on_demand()).unwrap();
assert_eq!(on_demand["mode"], "on_demand");
let extra = r#"{"mode":"on_demand","oops":1}"#;
assert!(serde_json::from_str::<HarvestCadence>(extra).is_err());
}
#[test]
fn regions_accept_auto_and_lists() {
let auto: HarvestRegions = serde_json::from_str("\"auto\"").unwrap();
assert!(auto.is_auto());
let list: HarvestRegions = serde_json::from_str(r#"["ap-guangzhou"]"#).unwrap();
assert_eq!(list, HarvestRegions::List(vec!["ap-guangzhou".to_string()]));
}
#[test]
fn grant_rejects_unknown_fields() {
let json = r#"{"worker_id":"w","source_code":"s","standing":null,"one_shot":[],
"sequence":1,"granted_at":"t","extra":1}"#;
assert!(serde_json::from_str::<HarvestWorkGrant>(json).is_err());
}
#[test]
fn spec_rejects_unknown_fields() {
let json = r#"{"credential_ref":"c","vendor":"TENCENT_CLOUD","assets":[],
"cadence":{"mode":"on_demand"},"extra":1}"#;
assert!(serde_json::from_str::<HarvestSpec>(json).is_err());
}
#[test]
fn one_shot_outstanding_uses_terminal_statuses() {
let work = OneShotHarvestWork {
work_id: "w".to_string(),
action: "inventory.run".to_string(),
spec: OneShotHarvestSpec::default(),
scheduled_at: "t".to_string(),
deadline_at: "t".to_string(),
timeout_seconds: 60,
interruptible: true,
status: "running".to_string(),
attempt: 0,
issued_by: "admin".to_string(),
issued_at: "t".to_string(),
};
assert!(work.is_outstanding());
let mut done = work.clone();
done.status = "succeeded".to_string();
assert!(!done.is_outstanding());
}
#[test]
fn poll_and_ack_builders_use_v1_kinds() {
let poll = PollHarvestWork::new("w", "i", 0, "t");
assert_eq!(poll.api_version, "v1");
assert_eq!(poll.kind, POLL_WORK_KIND);
let ack = AckHarvestWork::new("w", "i", "work", 1, "t");
assert_eq!(ack.kind, ACK_WORK_KIND);
}
#[test]
fn renewal_builder_uses_the_renewal_kind() {
let renewal = HarvestCertificateRenewal::new("w", "i", "csr", "t");
assert_eq!(renewal.api_version, "v1");
assert_eq!(renewal.kind, RENEW_CERTIFICATE_KIND);
assert_eq!(renewal.certificate_signing_request, "csr");
}
}