use std::fmt;
use std::future::Future;
use std::num::NonZeroUsize;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use serde::de::DeserializeOwned;
use tokio_util::sync::CancellationToken;
use crate::client_hub::ClientHub;
use crate::config::{ConfigError, ConfigProvider, gear_config_or_default, gear_config_required};
use toolkit_gts::local::DeclarationMerge;
pub use toolkit_gts::local::DeclarationSource;
pub struct GtsPublicationInputs<'a> {
gear: &'a str,
config: &'a dyn ConfigProvider,
}
impl<'a> GtsPublicationInputs<'a> {
#[must_use]
pub fn new(gear: &'a str, config: &'a dyn ConfigProvider) -> Self {
Self { gear, config }
}
pub fn config<T: DeserializeOwned>(&self) -> Result<T, ConfigError> {
gear_config_required(self.config, self.gear)
}
pub fn config_or_default<T: DeserializeOwned + Default>(&self) -> Result<T, ConfigError> {
gear_config_or_default(self.config, self.gear)
}
pub fn config_expanded_or_default<T>(&self) -> Result<T, ConfigError>
where
T: DeserializeOwned + Default + crate::var_expand::ExpandVars,
{
let mut cfg: T = self.config_or_default()?;
cfg.expand_vars().map_err(|e| ConfigError::VarExpand {
gear: self.gear.to_owned(),
cause: e,
})?;
Ok(cfg)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct GtsManifest {
publisher_name: String,
publisher_version: String,
documents: Vec<(gts::GtsId, serde_json::Value)>,
}
impl GtsManifest {
pub fn build(
publisher_name: impl Into<String>,
publisher_version: impl Into<String>,
sources: impl IntoIterator<Item = DeclarationSource>,
) -> anyhow::Result<Self> {
Ok(Self {
publisher_name: publisher_name.into(),
publisher_version: publisher_version.into(),
documents: toolkit_gts::local::merge_declarations(sources)?,
})
}
#[must_use]
pub fn publisher_name(&self) -> &str {
&self.publisher_name
}
#[must_use]
pub fn publisher_version(&self) -> &str {
&self.publisher_version
}
#[must_use]
pub fn documents(&self) -> &[(gts::GtsId, serde_json::Value)] {
&self.documents
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.documents.is_empty()
}
}
pub fn check_ownership<'a>(
manifests: impl IntoIterator<Item = &'a GtsManifest>,
) -> anyhow::Result<()> {
let mut owners: std::collections::BTreeMap<&str, Vec<&str>> = std::collections::BTreeMap::new();
for manifest in manifests {
for (id, _) in manifest.documents() {
owners
.entry(id.id())
.or_default()
.push(manifest.publisher_name());
}
}
let conflicts: Vec<String> = owners
.into_iter()
.filter(|(_, publishers)| publishers.len() > 1)
.map(|(id, mut publishers)| {
publishers.sort_unstable();
format!("{id} is published by {}", publishers.join(" and "))
})
.collect();
if conflicts.is_empty() {
Ok(())
} else {
anyhow::bail!(
"GTS ids with more than one publisher:\n- {}",
conflicts.join("\n- ")
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GtsPublicationOptions {
timeout: Option<Duration>,
retry_backoff: Duration,
retry_backoff_max: Duration,
batch_size: NonZeroUsize,
}
impl Default for GtsPublicationOptions {
fn default() -> Self {
Self {
timeout: None,
retry_backoff: Duration::from_secs(1),
retry_backoff_max: Duration::from_secs(30),
batch_size: NonZeroUsize::new(100).unwrap_or(NonZeroUsize::MIN),
}
}
}
pub const MAX_PUBLICATION_BUDGET: Duration = Duration::from_mins(10);
pub(crate) fn check_publication_budget(what: &str, budget: Duration) -> anyhow::Result<()> {
anyhow::ensure!(
budget <= MAX_PUBLICATION_BUDGET,
"{what}: {budget:?} is too large to be a publication budget (at most {MAX_PUBLICATION_BUDGET:?})"
);
Ok(())
}
pub fn parse_publication_budget(what: &str, text: &str) -> anyhow::Result<Duration> {
let budget = positive_duration(what, &serde_json::Value::String(text.to_owned()))?;
check_publication_budget(what, budget)?;
Ok(budget)
}
impl GtsPublicationOptions {
const FIELDS: &str = "timeout, retry_backoff, retry_backoff_max, batch_size";
pub fn from_config(gear: &str, config: &dyn ConfigProvider) -> anyhow::Result<Self> {
let path = format!(
"gears.{gear}.config.{}",
crate::config::GTS_PUBLICATION_CONFIG_KEY
);
let Some(section) = config
.get_gear_config(gear)
.and_then(|gear| gear.get("config"))
.and_then(|config| config.get(crate::config::GTS_PUBLICATION_CONFIG_KEY))
else {
return Ok(Self::default());
};
let serde_json::Value::Object(fields) = section else {
anyhow::bail!(
"{path}: expected a mapping of {}, got {section}",
Self::FIELDS
);
};
let mut options = Self::default();
for (key, value) in fields {
let field = format!("{path}.{key}");
match key.as_str() {
"timeout" => options.timeout = Some(positive_duration(&field, value)?),
"retry_backoff" => options.retry_backoff = positive_duration(&field, value)?,
"retry_backoff_max" => {
options.retry_backoff_max = positive_duration(&field, value)?;
}
"batch_size" => {
options.batch_size = value
.as_u64()
.and_then(|n| usize::try_from(n).ok())
.and_then(NonZeroUsize::new)
.ok_or_else(|| {
anyhow::anyhow!("{field}: expected a positive integer, got {value}")
})?;
}
_ => anyhow::bail!("{field}: unknown field; expected one of {}", Self::FIELDS),
}
}
if options.retry_backoff_max < options.retry_backoff {
anyhow::bail!(
"{path}: retry_backoff_max ({:?}) is less than retry_backoff ({:?})",
options.retry_backoff_max,
options.retry_backoff
);
}
if let Some(timeout) = options.timeout {
check_publication_budget(&format!("{path}.timeout"), timeout)?;
}
Ok(options)
}
#[must_use]
pub fn timeout(&self) -> Option<Duration> {
self.timeout
}
#[must_use]
pub fn retry_backoff(&self) -> Duration {
self.retry_backoff
}
#[must_use]
pub fn retry_backoff_max(&self) -> Duration {
self.retry_backoff_max
}
#[must_use]
pub fn batch_size(&self) -> NonZeroUsize {
self.batch_size
}
}
fn positive_duration(field: &str, value: &serde_json::Value) -> anyhow::Result<Duration> {
let duration = toolkit_utils::humantime_serde::deserialize(value)
.map_err(|e| anyhow::anyhow!("{field}: {e}, such as \"30s\""))?;
if duration.is_zero() {
anyhow::bail!("{field}: must be greater than zero");
}
Ok(duration)
}
pub struct GtsPublicationRequest {
manifest: Arc<GtsManifest>,
cancel: CancellationToken,
progress: Arc<dyn Fn(&str) + Send + Sync>,
deadline: Option<tokio::time::Instant>,
options: GtsPublicationOptions,
}
impl GtsPublicationRequest {
#[must_use]
pub fn new(
manifest: Arc<GtsManifest>,
cancel: CancellationToken,
progress: Arc<dyn Fn(&str) + Send + Sync>,
) -> Self {
Self {
manifest,
cancel,
progress,
deadline: None,
options: GtsPublicationOptions::default(),
}
}
#[must_use]
pub fn with_deadline(mut self, deadline: Option<tokio::time::Instant>) -> Self {
self.deadline = deadline;
self
}
#[must_use]
pub fn with_options(mut self, options: GtsPublicationOptions) -> Self {
self.options = options;
self
}
#[must_use]
pub fn gts_manifest(&self) -> &GtsManifest {
&self.manifest
}
#[must_use]
pub fn cancel(&self) -> &CancellationToken {
&self.cancel
}
#[must_use]
pub fn deadline(&self) -> Option<tokio::time::Instant> {
self.deadline
}
#[must_use]
pub fn options(&self) -> GtsPublicationOptions {
self.options
}
pub fn report_pending(&self, detail: &str) {
(self.progress)(detail);
}
}
type GtsPublishFuture = Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send>>;
#[derive(Clone)]
pub struct GtsPublicationBackend(
Arc<dyn Fn(GtsPublicationRequest) -> GtsPublishFuture + Send + Sync>,
);
impl GtsPublicationBackend {
pub fn new<F, Fut>(publish: F) -> Self
where
F: Fn(GtsPublicationRequest) -> Fut + Send + Sync + 'static,
Fut: Future<Output = anyhow::Result<()>> + Send + 'static,
{
Self(Arc::new(move |request| Box::pin(publish(request))))
}
pub async fn publish(&self, request: GtsPublicationRequest) -> anyhow::Result<()> {
if let Some(deadline) = request.deadline() {
check_publication_budget(
"the publication deadline",
deadline.saturating_duration_since(tokio::time::Instant::now()),
)?;
}
(self.0)(request).await
}
}
impl fmt::Debug for GtsPublicationBackend {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("GtsPublicationBackend")
}
}
pub type GtsEntitiesFn =
fn(&GtsPublicationInputs<'_>) -> anyhow::Result<Vec<(gts::GtsId, serde_json::Value)>>;
pub struct GtsPublicationDescriptor {
pub gear: &'static str,
pub publisher_version: &'static str,
pub declarations: fn() -> Vec<DeclarationSource>,
pub entities: Option<GtsEntitiesFn>,
pub backend: fn(&ClientHub) -> anyhow::Result<GtsPublicationBackend>,
pub provider: &'static str,
pub wire: crate::discovery::WireFn,
}
impl GtsPublicationDescriptor {
pub fn build_gts_manifest(&self, config: &dyn ConfigProvider) -> anyhow::Result<GtsManifest> {
let mut merge = DeclarationMerge::default();
let declarations = std::panic::catch_unwind(self.declarations).map_err(|payload| {
let detail = payload
.downcast_ref::<String>()
.map(String::as_str)
.or_else(|| payload.downcast_ref::<&str>().copied())
.unwrap_or("collector panicked without a text diagnostic");
anyhow::anyhow!("{}: GTS declarations: {detail}", self.gear)
})?;
for source in declarations {
merge.add_source(source);
}
if let Some(entities) = self.entities {
let inputs = GtsPublicationInputs::new(self.gear, config);
merge.add_documents("entities", entities(&inputs)?);
}
Ok(GtsManifest {
publisher_name: self.gear.to_owned(),
publisher_version: self.publisher_version.to_owned(),
documents: merge.finish()?,
})
}
}
impl fmt::Debug for GtsPublicationDescriptor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("GtsPublicationDescriptor")
.field("gear", &self.gear)
.field("publisher_version", &self.publisher_version)
.finish_non_exhaustive()
}
}
pub struct GtsPublicationRegistration(pub &'static GtsPublicationDescriptor);
inventory::collect!(GtsPublicationRegistration);
#[must_use]
pub fn linked_descriptors() -> Vec<&'static GtsPublicationDescriptor> {
let mut out: Vec<_> = inventory::iter::<GtsPublicationRegistration>
.into_iter()
.map(|r| r.0)
.collect();
out.sort_by_key(|d| d.gear);
out
}
pub trait GtsPublicationCapability: Send + Sync {
fn descriptor(&self) -> &'static GtsPublicationDescriptor;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("the GTS publication budget ran out before admission")]
pub struct GtsPublicationExpired;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum GtsPublicationError {
#[error("{gear}: GTS manifest: {source:#}")]
GtsManifest {
gear: &'static str,
source: anyhow::Error,
},
#[error("{gear}: GTS publication options: {source:#}")]
Options {
gear: &'static str,
source: anyhow::Error,
},
#[error("{gear}: GTS publisher: {source:#}")]
Backend {
gear: &'static str,
source: anyhow::Error,
},
#[error("{gear}: GTS publication refused: {source:#}")]
Refused {
gear: &'static str,
source: anyhow::Error,
},
#[error("{gear}: GTS publication not admitted in time: {source:#}")]
Expired {
gear: &'static str,
source: anyhow::Error,
},
#[error("{gear}: GTS publication cancelled")]
Cancelled { gear: &'static str },
}
pub struct PreparedGtsPublication {
gear: &'static str,
manifest: Arc<GtsManifest>,
backend: Option<GtsPublicationBackend>,
deadline: Option<tokio::time::Instant>,
options: GtsPublicationOptions,
}
impl PreparedGtsPublication {
pub fn prepare(
descriptor: &'static GtsPublicationDescriptor,
config: &dyn ConfigProvider,
hub: &ClientHub,
) -> Result<Self, GtsPublicationError> {
let gear = descriptor.gear;
let manifest = descriptor
.build_gts_manifest(config)
.map_err(|source| GtsPublicationError::GtsManifest { gear, source })?;
let options = GtsPublicationOptions::from_config(gear, config)
.map_err(|source| GtsPublicationError::Options { gear, source })?;
Self::bind(descriptor, Arc::new(manifest), options, hub)
}
pub fn bind(
descriptor: &'static GtsPublicationDescriptor,
manifest: Arc<GtsManifest>,
options: GtsPublicationOptions,
hub: &ClientHub,
) -> Result<Self, GtsPublicationError> {
let gear = descriptor.gear;
let backend = if manifest.is_empty() {
None
} else {
Some(
(descriptor.backend)(hub)
.map_err(|source| GtsPublicationError::Backend { gear, source })?,
)
};
Ok(Self {
gear,
manifest,
backend,
deadline: None,
options,
})
}
#[must_use]
pub fn with_deadline(mut self, deadline: tokio::time::Instant) -> Self {
self.deadline = Some(deadline);
self
}
#[must_use]
pub fn gear(&self) -> &'static str {
self.gear
}
#[must_use]
pub fn gts_manifest(&self) -> &GtsManifest {
&self.manifest
}
#[must_use]
pub fn options(&self) -> GtsPublicationOptions {
self.options
}
#[must_use]
pub fn shared_gts_manifest(&self) -> Arc<GtsManifest> {
Arc::clone(&self.manifest)
}
pub async fn publish(
&self,
cancel: &CancellationToken,
progress: Arc<dyn Fn(&str) + Send + Sync>,
) -> Result<(), GtsPublicationError> {
let gear = self.gear;
if cancel.is_cancelled() {
return Err(GtsPublicationError::Cancelled { gear });
}
let Some(backend) = &self.backend else {
return Ok(());
};
let request =
GtsPublicationRequest::new(Arc::clone(&self.manifest), cancel.clone(), progress)
.with_deadline(self.deadline)
.with_options(self.options);
let result = tokio::select! {
biased;
() = cancel.cancelled() => return Err(GtsPublicationError::Cancelled { gear }),
result = backend.publish(request) => result,
};
match result {
Ok(()) => Ok(()),
Err(_) if cancel.is_cancelled() => Err(GtsPublicationError::Cancelled { gear }),
Err(source) if source.downcast_ref::<GtsPublicationExpired>().is_some() => {
Err(GtsPublicationError::Expired { gear, source })
}
Err(source) => Err(GtsPublicationError::Refused { gear, source }),
}
}
}
pub type GtsPublicationProgress = Arc<dyn Fn(&'static str, &str) + Send + Sync>;
pub async fn publish_all(
prepared: &[PreparedGtsPublication],
cancel: &CancellationToken,
progress: GtsPublicationProgress,
stop_on_refusal: bool,
) -> Vec<(&'static str, Result<(), GtsPublicationError>)> {
use futures_util::StreamExt as _;
let stop = cancel.child_token();
let mut running: futures_util::stream::FuturesUnordered<_> = prepared
.iter()
.enumerate()
.map(|(index, publication)| {
let stop = stop.clone();
let gear = publication.gear();
let progress = Arc::clone(&progress);
async move {
let report: Arc<dyn Fn(&str) + Send + Sync> =
Arc::new(move |detail: &str| progress(gear, detail));
(index, publication.publish(&stop, report).await)
}
})
.collect();
let mut results: Vec<Option<Result<(), GtsPublicationError>>> =
prepared.iter().map(|_| None).collect();
while let Some((index, result)) = running.next().await {
if stop_on_refusal
&& matches!(
result,
Err(GtsPublicationError::Refused { .. } | GtsPublicationError::Expired { .. })
)
{
stop.cancel();
}
results[index] = Some(result);
}
prepared
.iter()
.zip(results)
.map(|(publication, result)| {
let gear = publication.gear();
(
gear,
result.unwrap_or(Err(GtsPublicationError::Cancelled { gear })),
)
})
.collect()
}
#[path = "gts_publication_deployment.rs"]
pub mod deployment;
#[cfg(test)]
#[path = "gts_publication_tests.rs"]
mod gts_publication_tests;