use crate::duration::ConfigDuration;
use crate::postprocess::PostprocessorConfig;
use crate::preprocess::PreprocessorConfig;
use crate::secret_resolver::default_secrets_directory;
use crate::size::{ConfigSize, LegacySizeUnit};
use crate::transport::adhoc::AdHocInputConfig;
use crate::transport::clock::{ClockConfig, ClockTimezoneOffset};
use crate::transport::datagen::DatagenInputConfig;
use crate::transport::delta_table::{DeltaTableReaderConfig, DeltaTableWriterConfig};
use crate::transport::dynamodb::DynamoDBWriterConfig;
use crate::transport::file::{FileInputConfig, FileOutputConfig};
use crate::transport::http::{HttpInputConfig, HttpOutputConfig};
use crate::transport::iceberg::IcebergReaderConfig;
use crate::transport::kafka::{KafkaInputConfig, KafkaOutputConfig};
use crate::transport::nats::{NatsInputConfig, NatsOutputConfig};
use crate::transport::nexmark::NexmarkInputConfig;
use crate::transport::postgres::{
PostgresCdcReaderConfig, PostgresReaderConfig, PostgresWriterConfig,
};
use crate::transport::pubsub::PubSubInputConfig;
use crate::transport::redis::RedisOutputConfig;
use crate::transport::s2::{S2InputConfig, S2OutputConfig};
use crate::transport::s3::S3InputConfig;
use crate::transport::url::UrlInputConfig;
use crate::{duration::LegacyUnit, duration_setting, nullable_duration_setting, size_setting};
use core::fmt;
use feldera_ir::{MirNode, MirNodeId};
use serde::de::{self, MapAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use std::fmt::Display;
use std::path::Path;
use std::str::FromStr;
use std::time::Duration;
use std::{borrow::Cow, cmp::max, collections::BTreeMap};
use utoipa::ToSchema;
use utoipa::openapi::{ObjectBuilder, OneOfBuilder, Ref, RefOr, Schema, SchemaType};
pub mod dev_tweaks;
pub use dev_tweaks::DevTweaks;
const DEFAULT_MAX_PARALLEL_CONNECTOR_INIT: u64 = 10;
const DEFAULT_MAX_OUTPUT_BUFFER_SIZE_RECORDS: usize = 10_000_000;
pub const fn default_max_queued_records() -> u64 {
1_000_000
}
pub const DEFAULT_MAX_WORKER_BATCH_SIZE: u64 = 10_000;
pub const DEFAULT_CLOCK_RESOLUTION: ConfigDuration = ConfigDuration::from_secs(1);
pub const DEFAULT_CHECKPOINT_INTERVAL: ConfigDuration = ConfigDuration::from_secs(60);
pub const DEFAULT_PULL_INTERVAL: ConfigDuration = ConfigDuration::from_secs(10);
pub const DEFAULT_RETENTION_MIN_AGE: ConfigDuration = ConfigDuration::from_days(30);
fn default_clock_resolution() -> String {
DEFAULT_CLOCK_RESOLUTION.to_string()
}
fn default_checkpoint_interval() -> String {
DEFAULT_CHECKPOINT_INTERVAL.to_string()
}
fn default_pull_interval() -> String {
DEFAULT_PULL_INTERVAL.to_string()
}
fn default_retention_min_age() -> String {
DEFAULT_RETENTION_MIN_AGE.to_string()
}
duration_setting!(
duration_standby_pull_interval,
"standby_pull_interval",
LegacyUnit::Secs
);
duration_setting!(
duration_checkpoint_push_interval,
"checkpoint_push_interval",
LegacyUnit::Secs
);
duration_setting!(duration_min_retention, "min_retention", LegacyUnit::Days);
duration_setting!(duration_ioop_latency, "ioop_latency", LegacyUnit::Millis);
duration_setting!(
duration_max_buffering_delay,
"max_buffering_delay",
LegacyUnit::Micros
);
duration_setting!(
duration_clock_resolution,
"clock_resolution",
LegacyUnit::Micros
);
duration_setting!(
duration_provisioning_timeout,
"provisioning_timeout",
LegacyUnit::Secs
);
nullable_duration_setting!(
duration_checkpoint_interval,
"checkpoint_interval",
LegacyUnit::Secs
);
duration_setting!(
duration_max_output_buffer_time,
"max_output_buffer_time",
LegacyUnit::Millis
);
size_setting!(size_max_rss, "max_rss", LegacySizeUnit::Megabytes);
size_setting!(
size_datafusion_memory,
"datafusion_memory",
LegacySizeUnit::Megabytes
);
size_setting!(size_cache_size, "cache_size", LegacySizeUnit::Mebibytes);
size_setting!(size_min_spill_size, "min_spill_size", LegacySizeUnit::Bytes);
size_setting!(
size_min_step_spill_size,
"min_step_spill_size",
LegacySizeUnit::Bytes
);
size_setting!(size_memory_min, "memory_min", LegacySizeUnit::Megabytes);
size_setting!(size_memory_max, "memory_max", LegacySizeUnit::Megabytes);
size_setting!(size_storage_min, "storage_min", LegacySizeUnit::Megabytes);
size_setting!(size_storage_max, "storage_max", LegacySizeUnit::Megabytes);
size_setting!(
size_scale_threshold_available,
"scale_threshold_available",
LegacySizeUnit::Megabytes
);
size_setting!(
size_max_queued_size,
"max_queued_size",
LegacySizeUnit::Bytes
);
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
pub struct ProgramIr {
pub mir: HashMap<MirNodeId, MirNode>,
pub program_schema: serde_json::Value,
#[serde(default)]
pub circuit_ir: Option<serde_json::Value>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PipelineIdentity {
pub name: String,
pub given_name: Option<String>,
}
impl Display for PipelineIdentity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.given_name {
Some(given_name) => write!(f, "{given_name} (id: {})", self.name),
None => write!(f, "{}", self.name),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq)]
pub struct PipelineConfig {
#[serde(flatten)]
#[schema(inline)]
pub global: RuntimeConfig,
pub multihost: Option<MultihostConfig>,
pub name: Option<String>,
pub given_name: Option<String>,
#[serde(default)]
pub storage_config: Option<StorageConfig>,
pub secrets_dir: Option<String>,
#[serde(default)]
pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
#[serde(default)]
pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
#[serde(default)]
pub program_ir: Option<ProgramIr>,
}
impl PipelineConfig {
pub fn max_parallel_connector_init(&self) -> u64 {
max(
self.global
.max_parallel_connector_init
.unwrap_or(DEFAULT_MAX_PARALLEL_CONNECTOR_INIT),
1,
)
}
pub fn program_info_subset(&self) -> PipelineConfigProgramInfo {
PipelineConfigProgramInfo {
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
program_ir: self.program_ir.clone(),
}
}
pub fn with_storage(self, storage: Option<(StorageConfig, StorageOptions)>) -> Self {
let (storage_config, storage_options) = storage.unzip();
Self {
global: RuntimeConfig {
storage: storage_options,
..self.global
},
storage_config,
..self
}
}
pub fn storage(&self) -> Option<(&StorageConfig, &StorageOptions)> {
let storage_options = self.global.storage.as_ref();
let storage_config = self.storage_config.as_ref();
storage_config.zip(storage_options)
}
pub fn pipeline_identity(&self) -> Option<PipelineIdentity> {
self.name.as_ref().map(|name| PipelineIdentity {
name: name.clone(),
given_name: self.given_name.clone(),
})
}
pub fn secrets_dir(&self) -> &Path {
match &self.secrets_dir {
Some(dir) => Path::new(dir.as_str()),
None => default_secrets_directory(),
}
}
pub fn display_summary(&self) -> String {
let summary = serde_json::json!({
"name": self.name,
"given_name": self.given_name,
"global": self.global,
"storage_config": self.storage_config,
"secrets_dir": self.secrets_dir,
"inputs": self.inputs,
"outputs": self.outputs
});
serde_json::to_string_pretty(&summary).unwrap_or_else(|_| "{}".to_string())
}
}
#[derive(Default, Deserialize, Serialize, Eq, PartialEq, Debug, Clone)]
pub struct PipelineConfigProgramInfo {
pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
#[serde(default)]
pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
#[serde(default)]
pub program_ir: Option<ProgramIr>,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct MultihostConfig {
pub hosts: usize,
}
impl Default for MultihostConfig {
fn default() -> Self {
Self { hosts: 1 }
}
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct StorageConfig {
pub path: String,
#[serde(default)]
pub cache: StorageCacheConfig,
}
impl StorageConfig {
pub fn path(&self) -> &Path {
Path::new(&self.path)
}
}
#[derive(Copy, Clone, Default, Deserialize, Serialize, Debug, PartialEq, Eq, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum StorageCacheConfig {
#[default]
PageCache,
FelderaCache,
}
impl StorageCacheConfig {
#[cfg(unix)]
pub fn to_custom_open_flags(&self) -> i32 {
match self {
StorageCacheConfig::PageCache => (),
StorageCacheConfig::FelderaCache => {
#[cfg(target_os = "linux")]
return libc::O_DIRECT;
}
}
0
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(default)]
pub struct StorageOptions {
pub backend: StorageBackendConfig,
#[serde(
alias = "min_storage_bytes",
deserialize_with = "size_min_spill_size",
skip_serializing_if = "Option::is_none"
)]
#[schema(value_type = Option<String>)]
pub min_spill_size: Option<ConfigSize>,
#[serde(
alias = "min_step_storage_bytes",
deserialize_with = "size_min_step_spill_size",
skip_serializing_if = "Option::is_none"
)]
#[schema(value_type = Option<String>)]
pub min_step_spill_size: Option<ConfigSize>,
pub compression: StorageCompression,
pub compression_level: Option<i32>,
#[serde(
alias = "cache_mib",
deserialize_with = "size_cache_size",
skip_serializing_if = "Option::is_none"
)]
#[schema(value_type = Option<String>)]
pub cache_size: Option<ConfigSize>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
pub bloom_false_positive_rate: Option<f64>,
}
impl Eq for StorageOptions {}
#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(tag = "name", content = "config", rename_all = "snake_case")]
pub enum StorageBackendConfig {
#[default]
Default,
File(Box<FileBackendConfig>),
Object(ObjectStorageConfig),
}
impl Display for StorageBackendConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
StorageBackendConfig::Default => write!(f, "default"),
StorageBackendConfig::File(_) => write!(f, "file"),
StorageBackendConfig::Object(_) => write!(f, "object"),
}
}
}
#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum StorageCompression {
#[default]
Default,
None,
Snappy,
Lz4,
Zstd,
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum StartFromCheckpoint {
Latest,
Uuid(uuid::Uuid),
}
impl ToSchema<'_> for StartFromCheckpoint {
fn schema() -> (
&'static str,
utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
) {
(
"StartFromCheckpoint",
utoipa::openapi::RefOr::T(Schema::OneOf(
OneOfBuilder::new()
.item(
ObjectBuilder::new()
.schema_type(SchemaType::String)
.enum_values(Some(["latest"].into_iter()))
.build(),
)
.item(
ObjectBuilder::new()
.schema_type(SchemaType::String)
.format(Some(utoipa::openapi::SchemaFormat::KnownFormat(
utoipa::openapi::KnownFormat::Uuid,
)))
.build(),
)
.nullable(true)
.build(),
)),
)
}
}
impl<'de> Deserialize<'de> for StartFromCheckpoint {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct StartFromCheckpointVisitor;
impl<'de> Visitor<'de> for StartFromCheckpointVisitor {
type Value = StartFromCheckpoint;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a UUID string or the string \"latest\"")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
if value == "latest" {
Ok(StartFromCheckpoint::Latest)
} else {
uuid::Uuid::parse_str(value)
.map(StartFromCheckpoint::Uuid)
.map_err(|_| E::invalid_value(serde::de::Unexpected::Str(value), &self))
}
}
}
deserializer.deserialize_str(StartFromCheckpointVisitor)
}
}
impl Serialize for StartFromCheckpoint {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
StartFromCheckpoint::Latest => serializer.serialize_str("latest"),
StartFromCheckpoint::Uuid(uuid) => serializer.serialize_str(&uuid.to_string()),
}
}
}
#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct SyncConfig {
pub endpoint: Option<String>,
pub bucket: String,
pub region: Option<String>,
pub provider: Option<String>,
pub access_key: Option<String>,
pub secret_key: Option<String>,
pub start_from_checkpoint: Option<StartFromCheckpoint>,
#[schema(default = std::primitive::bool::default)]
#[serde(default)]
pub fail_if_no_checkpoint: bool,
pub transfers: Option<u8>,
pub checkers: Option<u8>,
pub ignore_checksum: Option<bool>,
pub multi_thread_streams: Option<u8>,
pub multi_thread_cutoff: Option<String>,
#[schema(default = default_optimize_download_resources)]
#[serde(default = "default_optimize_download_resources")]
pub optimize_download_resources: bool,
pub upload_concurrency: Option<u8>,
#[deprecated(note = "Use `initial=standby` when starting the pipeline instead.")]
#[schema(default = std::primitive::bool::default)]
#[serde(default)]
pub standby: bool,
#[serde(
default,
alias = "pull_interval",
deserialize_with = "duration_standby_pull_interval",
skip_serializing_if = "Option::is_none"
)]
#[schema(value_type = Option<String>, default = default_pull_interval)]
pub standby_pull_interval: Option<ConfigDuration>,
#[serde(
default,
alias = "push_interval",
deserialize_with = "duration_checkpoint_push_interval",
skip_serializing_if = "Option::is_none"
)]
#[schema(value_type = Option<String>)]
pub checkpoint_push_interval: Option<ConfigDuration>,
pub flags: Option<Vec<String>>,
#[schema(default = default_retention_min_count)]
#[serde(default = "default_retention_min_count")]
pub retention_min_count: u32,
#[serde(
default,
alias = "retention_min_age",
deserialize_with = "duration_min_retention",
skip_serializing_if = "Option::is_none"
)]
#[schema(value_type = Option<String>, default = default_retention_min_age)]
pub min_retention: Option<ConfigDuration>,
#[serde(default)]
pub read_bucket: Option<String>,
#[schema(default = std::primitive::bool::default)]
#[serde(default)]
pub take_bucket_ownership: bool,
}
fn default_retention_min_count() -> u32 {
10
}
fn default_optimize_download_resources() -> bool {
true
}
impl SyncConfig {
pub fn standby_pull_interval(&self) -> ConfigDuration {
self.standby_pull_interval.unwrap_or(DEFAULT_PULL_INTERVAL)
}
pub fn checkpoint_push_interval(&self) -> Option<ConfigDuration> {
self.checkpoint_push_interval
}
pub fn min_retention(&self) -> ConfigDuration {
self.min_retention.unwrap_or(DEFAULT_RETENTION_MIN_AGE)
}
pub fn validate(&self) -> Result<(), String> {
#[allow(deprecated)]
if self.standby {
return Err(
"The `standby` config field has been deprecated. Use `initial=standby` when starting the pipeline instead.".to_owned()
);
}
if let Some(ref rb) = self.read_bucket {
if rb == &self.bucket {
return Err(
"invalid sync config: `read_bucket` and `bucket` must point to different locations"
.to_owned(),
);
}
if is_gcs_bucket(rb) != is_gcs_bucket(&self.bucket) {
return Err(format!(
"invalid sync config: `bucket` ('{}') and `read_bucket` ('{}') must use the same object store; prefix both with `gs://` for Google Cloud Storage or neither for S3",
self.bucket, rb
));
}
}
Ok(())
}
}
fn is_gcs_bucket(bucket: &str) -> bool {
bucket.starts_with("gs://")
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
pub struct PipelineTemplateConfig {
pub name: String,
#[schema(default = default_pipeline_template_key)]
#[serde(default = "default_pipeline_template_key")]
pub key: String,
}
fn default_pipeline_template_key() -> String {
"pipelineTemplate".to_string()
}
#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct ObjectStorageConfig {
pub url: String,
#[serde(flatten)]
pub other_options: BTreeMap<String, String>,
}
#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(default)]
pub struct FileBackendConfig {
pub async_threads: Option<bool>,
#[serde(
default,
alias = "ioop_delay",
deserialize_with = "duration_ioop_latency",
skip_serializing_if = "Option::is_none"
)]
#[schema(value_type = Option<String>)]
pub ioop_latency: Option<ConfigDuration>,
pub sync: Option<SyncConfig>,
pub sync_mode: Option<StorageSyncMode>,
}
#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum StorageSyncMode {
#[default]
Auto,
Syncfs,
PerFile,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(default)]
pub struct RuntimeConfig {
pub workers: u16,
#[serde(
default,
alias = "max_rss_mb",
deserialize_with = "size_max_rss",
skip_serializing_if = "Option::is_none"
)]
#[schema(value_type = Option<String>)]
pub max_rss: Option<ConfigSize>,
#[serde(
default,
alias = "datafusion_memory_mb",
deserialize_with = "size_datafusion_memory",
skip_serializing_if = "Option::is_none"
)]
#[schema(value_type = Option<String>)]
pub datafusion_memory: Option<ConfigSize>,
pub hosts: usize,
#[serde(deserialize_with = "deserialize_storage_options")]
pub storage: Option<StorageOptions>,
#[serde(deserialize_with = "deserialize_fault_tolerance")]
pub fault_tolerance: FtConfig,
pub cpu_profiler: bool,
pub tracing: bool,
pub tracing_endpoint_jaeger: String,
pub min_batch_size_records: u64,
#[serde(
default,
alias = "max_buffering_delay_usecs",
deserialize_with = "duration_max_buffering_delay",
skip_serializing_if = "Option::is_none"
)]
#[schema(value_type = Option<String>)]
pub max_buffering_delay: Option<ConfigDuration>,
pub resources: ResourceConfig,
#[serde(
default,
alias = "clock_resolution_usecs",
deserialize_with = "duration_clock_resolution",
skip_serializing_if = "Option::is_none"
)]
#[schema(value_type = Option<String>, default = default_clock_resolution)]
pub clock_resolution: Option<ConfigDuration>,
#[schema(value_type = Option<String>, example = "+05:30")]
pub clock_timezone_offset: Option<ClockTimezoneOffset>,
pub pin_cpus: Vec<usize>,
#[serde(
default,
alias = "provisioning_timeout_secs",
deserialize_with = "duration_provisioning_timeout",
skip_serializing_if = "Option::is_none"
)]
#[schema(value_type = Option<String>)]
pub provisioning_timeout: Option<ConfigDuration>,
pub max_parallel_connector_init: Option<u64>,
pub init_containers: Option<serde_json::Value>,
pub checkpoint_during_suspend: bool,
pub http_workers: Option<u64>,
pub io_workers: Option<u64>,
#[serde(default)]
pub env: BTreeMap<String, String>,
pub dev_tweaks: DevTweaks,
pub logging: Option<String>,
pub pipeline_template_configmap: Option<PipelineTemplateConfig>,
}
fn deserialize_storage_options<'de, D>(deserializer: D) -> Result<Option<StorageOptions>, D::Error>
where
D: Deserializer<'de>,
{
struct BoolOrStruct;
impl<'de> Visitor<'de> for BoolOrStruct {
type Value = Option<StorageOptions>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("boolean or StorageOptions")
}
fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
where
E: de::Error,
{
match v {
false => Ok(None),
true => Ok(Some(StorageOptions::default())),
}
}
fn visit_unit<E>(self) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(None)
}
fn visit_none<E>(self) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(None)
}
fn visit_map<M>(self, map: M) -> Result<Option<StorageOptions>, M::Error>
where
M: MapAccess<'de>,
{
Deserialize::deserialize(de::value::MapAccessDeserializer::new(map)).map(Some)
}
}
deserializer.deserialize_any(BoolOrStruct)
}
fn deserialize_fault_tolerance<'de, D>(deserializer: D) -> Result<FtConfig, D::Error>
where
D: Deserializer<'de>,
{
struct StringOrStruct;
impl<'de> Visitor<'de> for StringOrStruct {
type Value = FtConfig;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("none or FtConfig or 'initial_state' or 'latest_checkpoint'")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
match v {
"initial_state" | "latest_checkpoint" => Ok(FtConfig {
model: Some(FtModel::default()),
..FtConfig::default()
}),
_ => Err(de::Error::invalid_value(de::Unexpected::Str(v), &self)),
}
}
fn visit_unit<E>(self) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(FtConfig::default())
}
fn visit_none<E>(self) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(FtConfig::default())
}
fn visit_map<M>(self, map: M) -> Result<FtConfig, M::Error>
where
M: MapAccess<'de>,
{
Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))
}
}
deserializer.deserialize_any(StringOrStruct)
}
impl Default for RuntimeConfig {
fn default() -> Self {
Self {
workers: 8,
max_rss: None,
datafusion_memory: None,
hosts: 1,
storage: Some(StorageOptions::default()),
fault_tolerance: FtConfig::default(),
cpu_profiler: true,
tracing: {
false
},
tracing_endpoint_jaeger: "127.0.0.1:6831".to_string(),
min_batch_size_records: 0,
max_buffering_delay: None,
resources: ResourceConfig::default(),
clock_resolution: None,
clock_timezone_offset: None,
pin_cpus: Vec::new(),
provisioning_timeout: None,
max_parallel_connector_init: None,
init_containers: None,
checkpoint_during_suspend: true,
io_workers: None,
http_workers: None,
env: BTreeMap::default(),
dev_tweaks: DevTweaks::default(),
logging: None,
pipeline_template_configmap: None,
}
}
}
pub const DEFAULT_DATAFUSION_MEMORY_CEILING: ConfigSize = ConfigSize::from_mb(2048);
pub const DEFAULT_DATAFUSION_MEMORY_PERCENT: u64 = 5;
impl RuntimeConfig {
pub fn max_buffering_delay(&self) -> ConfigDuration {
self.max_buffering_delay.unwrap_or(ConfigDuration::ZERO)
}
pub fn clock_resolution(&self) -> ConfigDuration {
self.clock_resolution.unwrap_or(DEFAULT_CLOCK_RESOLUTION)
}
pub fn effective_memory(&self) -> Option<ConfigSize> {
self.max_rss.or(self.resources.memory_max)
}
pub fn resolved_datafusion_memory(&self) -> Option<ConfigSize> {
if let Some(explicit) = self.datafusion_memory {
return Some(explicit);
}
let effective = self.effective_memory()?.as_bytes();
let fraction = u128::from(effective) * u128::from(DEFAULT_DATAFUSION_MEMORY_PERCENT) / 100;
let fraction = u64::try_from(fraction).unwrap_or(u64::MAX);
Some(ConfigSize::from_bytes(fraction).min(DEFAULT_DATAFUSION_MEMORY_CEILING))
}
}
#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub struct FtConfig {
#[serde(with = "none_as_string")]
#[serde(default = "default_model")]
#[schema(
schema_with = none_as_string_schema::<FtModel>,
)]
pub model: Option<FtModel>,
#[serde(
default,
alias = "checkpoint_interval_secs",
deserialize_with = "duration_checkpoint_interval",
skip_serializing_if = "Option::is_none"
)]
#[schema(value_type = Option<String>, default = default_checkpoint_interval)]
pub checkpoint_interval: Option<Option<ConfigDuration>>,
}
fn default_model() -> Option<FtModel> {
Some(FtModel::default())
}
pub fn to_legacy_duration_spelling(config: &mut serde_json::Value) {
use crate::duration::LegacyUnit;
use serde_json::{Map, Value};
struct Rule {
new: &'static str,
old: &'static str,
unit: LegacyUnit,
max: u64,
null_allowed: bool,
}
const fn rule(
new: &'static str,
old: &'static str,
unit: LegacyUnit,
max: u64,
null_allowed: bool,
) -> Rule {
Rule {
new,
old,
unit,
max,
null_allowed,
}
}
const U32: u64 = u32::MAX as u64;
const U64: u64 = u64::MAX;
use LegacyUnit::{Days, Micros, Millis, Secs};
fn apply(object: &mut Map<String, Value>, rules: &[Rule]) {
for rule in rules {
let Some(value) = object.remove(rule.new) else {
continue;
};
let legacy = match &value {
Value::String(text) => match text.parse::<ConfigDuration>() {
Ok(duration) => {
let nanos = std::time::Duration::from(duration).as_nanos();
let unit_nanos = u128::from(rule.unit.nanos());
let whole = nanos.div_ceil(unit_nanos);
Value::from(u64::try_from(whole).unwrap_or(U64).min(rule.max))
}
Err(_) => {
object.insert(rule.new.to_string(), value);
continue;
}
},
Value::Null if !rule.null_allowed => continue,
other => other.clone(),
};
object.insert(rule.old.to_string(), legacy);
}
}
fn child<'a>(
object: &'a mut Map<String, Value>,
key: &str,
) -> Option<&'a mut Map<String, Value>> {
object.get_mut(key).and_then(Value::as_object_mut)
}
fn max_expiry(consumer: &mut Map<String, Value>) {
let Some(Value::String(text)) = consumer.get("max_expiry") else {
return;
};
let Ok(duration) = text.parse::<ConfigDuration>() else {
return;
};
let duration = std::time::Duration::from(duration);
consumer.remove("max_expiry");
consumer.insert(
"max_expires".to_string(),
serde_json::json!({"secs": duration.as_secs(), "nanos": duration.subsec_nanos()}),
);
}
fn nats_connection(transport: &mut Map<String, Value>) {
if let Some(connection) = child(transport, "connection_config") {
apply(
connection,
&[
rule(
"connection_timeout",
"connection_timeout_secs",
Secs,
U64,
false,
),
rule("request_timeout", "request_timeout_secs", Secs, U64, false),
],
);
}
}
fn connector(endpoint: &mut Map<String, Value>) {
apply(
endpoint,
&[rule(
"max_output_buffer_time",
"max_output_buffer_time_millis",
Millis,
U64,
false,
)],
);
let name = endpoint
.get("transport")
.and_then(|transport| transport.get("name"))
.and_then(Value::as_str)
.map(str::to_string);
if let Some(transport) = child(endpoint, "transport").and_then(|t| child(t, "config")) {
match name.as_deref() {
Some("url_input") => apply(
transport,
&[rule("pause_linger", "pause_timeout", Secs, U32, false)],
),
Some("kafka_input") => apply(
transport,
&[rule(
"group_join_timeout",
"group_join_timeout_secs",
Secs,
U32,
false,
)],
),
Some("kafka_output") => apply(
transport,
&[rule(
"initialization_timeout",
"initialization_timeout_secs",
Secs,
U32,
false,
)],
),
Some("clock_input") => apply(
transport,
&[rule(
"clock_resolution",
"clock_resolution_usecs",
Micros,
U64,
false,
)],
),
Some("pub_sub_input") => apply(
transport,
&[
rule("timeout", "timeout_seconds", Secs, U32, true),
rule(
"connect_timeout",
"connect_timeout_seconds",
Secs,
U32,
true,
),
],
),
Some("nats_input") => {
apply(
transport,
&[
rule(
"inactivity_timeout",
"inactivity_timeout_secs",
Secs,
U64,
false,
),
rule("retry_interval", "retry_interval_secs", Secs, U64, false),
],
);
nats_connection(transport);
if let Some(consumer) = child(transport, "consumer_config") {
max_expiry(consumer);
}
}
Some("nats_output") => {
apply(
transport,
&[rule(
"publish_timeout",
"publish_timeout_secs",
Secs,
U64,
false,
)],
);
nats_connection(transport);
}
_ => {}
}
}
let is_avro = endpoint
.get("format")
.and_then(|format| format.get("name"))
.and_then(Value::as_str)
== Some("avro");
if is_avro && let Some(format) = child(endpoint, "format").and_then(|f| child(f, "config"))
{
apply(
format,
&[rule(
"registry_timeout",
"registry_timeout_secs",
Secs,
U64,
true,
)],
);
}
}
let Some(global) = config.as_object_mut() else {
return;
};
apply(
global,
&[
rule(
"clock_resolution",
"clock_resolution_usecs",
Micros,
U64,
true,
),
rule(
"max_buffering_delay",
"max_buffering_delay_usecs",
Micros,
U64,
false,
),
rule(
"provisioning_timeout",
"provisioning_timeout_secs",
Secs,
U64,
true,
),
],
);
if let Some(ft) = child(global, "fault_tolerance") {
apply(
ft,
&[rule(
"checkpoint_interval",
"checkpoint_interval_secs",
Secs,
U64,
true,
)],
);
}
let backend = child(global, "storage")
.and_then(|storage| child(storage, "backend"))
.filter(|backend| backend.get("name").and_then(Value::as_str) == Some("file"))
.and_then(|backend| child(backend, "config"));
if let Some(file) = backend {
apply(
file,
&[rule("ioop_latency", "ioop_delay", Millis, U64, true)],
);
if let Some(sync) = child(file, "sync") {
apply(
sync,
&[
rule("standby_pull_interval", "pull_interval", Secs, U64, false),
rule("checkpoint_push_interval", "push_interval", Secs, U64, true),
rule("min_retention", "retention_min_age", Days, U32, false),
],
);
}
}
for endpoints in ["inputs", "outputs"] {
if let Some(endpoints) = child(global, endpoints) {
for endpoint in endpoints.values_mut().filter_map(Value::as_object_mut) {
connector(endpoint);
}
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LegacySpelling {
pub durations: bool,
pub sizes: bool,
}
impl LegacySpelling {
pub const NONE: LegacySpelling = LegacySpelling {
durations: false,
sizes: false,
};
pub fn any(self) -> bool {
self.durations || self.sizes
}
pub fn apply(self, config: &mut serde_json::Value) {
if self.durations {
to_legacy_duration_spelling(config);
}
if self.sizes {
to_legacy_size_spelling(config);
}
}
}
pub fn to_legacy_size_spelling(config: &mut serde_json::Value) {
use crate::size::LegacySizeUnit::{self, Bytes, Mebibytes, Megabytes};
use serde_json::{Map, Value};
struct Rule {
new: &'static str,
old: &'static str,
unit: LegacySizeUnit,
}
const fn rule(new: &'static str, old: &'static str, unit: LegacySizeUnit) -> Rule {
Rule { new, old, unit }
}
fn apply(object: &mut Map<String, Value>, rules: &[Rule]) {
for rule in rules {
let Some(value) = object.remove(rule.new) else {
continue;
};
let legacy = match &value {
Value::String(text) => match text.parse::<ConfigSize>() {
Ok(size) => Value::from(size.as_bytes().div_ceil(rule.unit.bytes())),
Err(_) => {
object.insert(rule.new.to_string(), value);
continue;
}
},
Value::Null => continue,
other => other.clone(),
};
object.insert(rule.old.to_string(), legacy);
}
}
fn child<'a>(
object: &'a mut Map<String, Value>,
key: &str,
) -> Option<&'a mut Map<String, Value>> {
object.get_mut(key).and_then(Value::as_object_mut)
}
fn connector(endpoint: &mut Map<String, Value>) {
apply(
endpoint,
&[rule("max_queued_size", "max_queued_bytes", Bytes)],
);
let name = endpoint
.get("transport")
.and_then(|transport| transport.get("name"))
.and_then(Value::as_str)
.map(str::to_string);
if let Some(transport) = child(endpoint, "transport").and_then(|t| child(t, "config")) {
match name.as_deref() {
Some("file_input") => apply(
transport,
&[rule("buffer_size", "buffer_size_bytes", Bytes)],
),
Some("dynamodb_output" | "postgres_output") => apply(
transport,
&[rule("max_buffer_size", "max_buffer_size_bytes", Bytes)],
),
Some("postgres_cdc_input") => {
if let Some(batch) = child(transport, "batch") {
apply(batch, &[rule("max_size", "max_bytes", Bytes)]);
}
}
_ => {}
}
}
}
let Some(global) = config.as_object_mut() else {
return;
};
apply(
global,
&[
rule("max_rss", "max_rss_mb", Megabytes),
rule("datafusion_memory", "datafusion_memory_mb", Megabytes),
],
);
if let Some(storage) = child(global, "storage") {
apply(
storage,
&[
rule("cache_size", "cache_mib", Mebibytes),
rule("min_spill_size", "min_storage_bytes", Bytes),
rule("min_step_spill_size", "min_step_storage_bytes", Bytes),
],
);
}
if let Some(resources) = child(global, "resources") {
apply(
resources,
&[
rule("memory_min", "memory_mb_min", Megabytes),
rule("memory_max", "memory_mb_max", Megabytes),
rule("storage_min", "storage_mb_min", Megabytes),
rule("storage_max", "storage_mb_max", Megabytes),
],
);
if let Some(storage) = child(resources, "autoscaling").and_then(|a| child(a, "storage")) {
apply(
storage,
&[rule(
"scale_threshold_available",
"scale_threshold_available_mb",
Megabytes,
)],
);
}
}
if let Some(tweaks) = child(global, "dev_tweaks") {
apply(
tweaks,
&[
rule("storage_max", "storage_mb_max", Mebibytes),
rule(
"fbuf_slab_size_per_class",
"fbuf_slab_bytes_per_class",
Bytes,
),
rule(
"lazy_input_map_key_block_size",
"lazy_input_map_key_block_bytes",
Bytes,
),
rule(
"exchange_channel_capacity",
"exchange_channel_capacity_bytes",
Bytes,
),
],
);
}
for endpoints in ["inputs", "outputs"] {
if let Some(endpoints) = child(global, endpoints) {
for endpoint in endpoints.values_mut().filter_map(Value::as_object_mut) {
connector(endpoint);
}
}
}
}
#[cfg(test)]
mod test {
use super::deserialize_fault_tolerance;
use crate::config::{
ConnectorConfig, DEFAULT_CLOCK_RESOLUTION, DEFAULT_DATAFUSION_MEMORY_CEILING,
DEFAULT_PULL_INTERVAL, DEFAULT_RETENTION_MIN_AGE, FileBackendConfig, FtConfig, FtModel,
OutputBufferConfig, PipelineConfig, ResourceConfig, RuntimeConfig, StorageBackendConfig,
StorageOptions, SyncConfig, TransportConfig,
};
use crate::duration::ConfigDuration;
use crate::size::ConfigSize;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::time::Duration;
fn assert_reloads<T>(value: serde_json::Value)
where
T: Serialize + for<'de> Deserialize<'de>,
{
let first: T = serde_json::from_value(value.clone())
.unwrap_or_else(|e| panic!("{value} does not load: {e}"));
let written = serde_json::to_value(&first).unwrap();
let second: T = serde_json::from_value(written.clone()).unwrap_or_else(|e| {
panic!("{value} is written as {written}, which does not load: {e}")
});
assert_eq!(serde_json::to_value(&second).unwrap(), written, "{value}");
}
#[test]
fn size_settings_reload_from_what_is_written() {
use crate::transport::dynamodb::DynamoDBWriterConfig;
use crate::transport::file::FileInputConfig;
use crate::transport::postgres::{PostgresCdcBatchConfig, PostgresWriterConfig};
for number in [0u64, 1, 1_100, u64::MAX] {
assert_reloads::<RuntimeConfig>(json!({
"max_rss_mb": number,
"datafusion_memory_mb": number,
"storage": {"cache_mib": number, "min_storage_bytes": number},
"resources": {"memory_mb_min": number, "storage_mb_max": number},
"dev_tweaks": {"storage_mb_max": number},
}));
}
let max = format!("{}B", u64::MAX);
for size in ["0B", "1B", "999B", "1.1Gi", "1.1G", "16G", "8Gi", &max] {
assert_reloads::<RuntimeConfig>(json!({
"max_rss": size,
"datafusion_memory": size,
"storage": {
"cache_size": size,
"min_spill_size": size,
"min_step_spill_size": size,
},
"resources": {
"memory_min": size,
"memory_max": size,
"storage_min": size,
"storage_max": size,
"autoscaling": {"storage": {"scale_threshold_available": size}},
},
"dev_tweaks": {
"storage_max": size,
"fbuf_slab_size_per_class": size,
"exchange_channel_capacity": size,
},
}));
assert_reloads::<ConnectorConfig>(json!({
"transport": {
"name": "file_input",
"config": {"path": "input.csv", "buffer_size": size},
},
"max_queued_size": size,
}));
assert_reloads::<FileInputConfig>(json!({"path": "input.csv", "buffer_size": size}));
assert_reloads::<PostgresCdcBatchConfig>(json!({"max_size": size}));
assert_reloads::<PostgresWriterConfig>(json!({
"uri": "postgres://localhost/db",
"table": "t",
"max_buffer_size": size,
}));
assert_reloads::<DynamoDBWriterConfig>(json!({
"table": "t",
"region": "us-east-1",
"max_buffer_size": size,
}));
}
}
#[test]
fn soft_delete_is_backward_compatible() {
let config: ConnectorConfig = serde_json::from_value(json!({
"transport": {"name": "empty_input"}
}))
.unwrap();
assert!(!config.soft_delete);
let serialized = serde_json::to_value(&config).unwrap();
assert_eq!(serialized.get("soft_delete"), None);
let config: ConnectorConfig = serde_json::from_value(json!({
"transport": {"name": "empty_input"},
"soft_delete": true
}))
.unwrap();
assert!(config.soft_delete);
assert_eq!(
serde_json::to_value(&config).unwrap().get("soft_delete"),
Some(&json!(true))
);
}
#[test]
fn soft_delete_invalidates_checkpointed_connector_state() {
let config = ConnectorConfig::new(TransportConfig::EmptyInput, None);
let mut soft_delete = config.clone();
soft_delete.soft_delete = true;
assert!(config.equal_for_input_checkpoint_replay(&config));
assert!(!config.equal_for_input_checkpoint_replay(&soft_delete));
}
fn config_with_name(name: Option<&str>) -> PipelineConfig {
PipelineConfig {
global: RuntimeConfig::default(),
multihost: None,
name: name.map(str::to_string),
given_name: None,
storage_config: None,
secrets_dir: None,
inputs: Default::default(),
outputs: Default::default(),
program_ir: None,
}
}
#[test]
fn pipeline_identity_uses_system_and_given_names() {
let mut config = config_with_name(Some("pipeline-018f6f57-4e15-7438-91af-3fd21ff2a8d3"));
config.given_name = Some("my-pipeline".to_string());
let metadata = config.pipeline_identity().unwrap();
assert_eq!(
metadata.name,
"pipeline-018f6f57-4e15-7438-91af-3fd21ff2a8d3"
);
assert_eq!(metadata.given_name.as_deref(), Some("my-pipeline"));
}
#[test]
fn pipeline_identity_is_none_without_system_name() {
assert_eq!(config_with_name(None).pipeline_identity(), None);
}
#[test]
fn resolved_datafusion_memory_explicit_passes_through() {
let config = RuntimeConfig {
max_rss: Some(ConfigSize::from_mb(8_000)),
datafusion_memory: Some(ConfigSize::from_mb(1_500)),
..Default::default()
};
assert_eq!(
config.resolved_datafusion_memory(),
Some(ConfigSize::from_mb(1_500))
);
}
#[test]
fn resolved_datafusion_memory_unconfigured_returns_none() {
let config = RuntimeConfig::default();
assert!(config.max_rss.is_none());
assert!(config.resources.memory_max.is_none());
assert_eq!(config.resolved_datafusion_memory(), None);
}
#[test]
fn resolved_datafusion_memory_small_budget_scales_down() {
let config = RuntimeConfig {
max_rss: Some(ConfigSize::from_mb(256)),
..Default::default()
};
assert_eq!(
config.resolved_datafusion_memory(),
Some(ConfigSize::from_bytes(12_800_000))
);
let config = RuntimeConfig {
max_rss: Some(ConfigSize::from_mb(512)),
..Default::default()
};
assert_eq!(
config.resolved_datafusion_memory(),
Some(ConfigSize::from_bytes(25_600_000))
);
}
#[test]
fn resolved_datafusion_memory_clamps_to_ceiling_for_large_budgets() {
let config = RuntimeConfig {
max_rss: Some(ConfigSize::from_mb(64_000)),
..Default::default()
};
assert_eq!(
config.resolved_datafusion_memory(),
Some(DEFAULT_DATAFUSION_MEMORY_CEILING),
);
}
#[test]
fn resolved_datafusion_memory_midrange_uses_five_percent() {
let config = RuntimeConfig {
max_rss: Some(ConfigSize::from_mb(16_000)),
..Default::default()
};
assert_eq!(
config.resolved_datafusion_memory(),
Some(ConfigSize::from_mb(800))
);
}
#[test]
fn resolved_datafusion_memory_falls_back_to_resources() {
let config = RuntimeConfig {
max_rss: None,
resources: ResourceConfig {
memory_max: Some(ConfigSize::from_mb(16_000)),
..Default::default()
},
..Default::default()
};
assert_eq!(
config.resolved_datafusion_memory(),
Some(ConfigSize::from_mb(800))
);
}
#[test]
fn ft_config() {
#[derive(Serialize, Deserialize, Default, PartialEq, Eq, Debug)]
#[serde(default)]
struct Wrapper {
#[serde(deserialize_with = "deserialize_fault_tolerance")]
config: FtConfig,
}
for s in [
"{}",
r#"{"config": null}"#,
r#"{"config": {"model": "none"}}"#,
] {
let config: Wrapper = serde_json::from_str(s).unwrap();
assert_eq!(config.config.model, None);
assert_eq!(config.config.checkpoint_interval(), None);
}
let s = serde_json::to_string(&Wrapper {
config: FtConfig::default(),
})
.unwrap();
assert!(s.contains("\"none\""));
for s in [
r#"{}"#,
r#"{"checkpoint_interval": "60s"}"#,
r#"{"checkpoint_interval_secs": 60}"#,
] {
let config = serde_json::from_str::<FtConfig>(s).unwrap();
assert_eq!(config.model, Some(FtModel::default()), "parsing {s}");
assert_eq!(
config.checkpoint_interval(),
Some(Duration::from_secs(60)),
"parsing {s}"
);
}
for s in [
r#"{"checkpoint_interval": null}"#,
r#"{"checkpoint_interval_secs": null}"#,
] {
let config = serde_json::from_str::<FtConfig>(s).unwrap();
assert_eq!(config.model, Some(FtModel::default()), "parsing {s}");
assert_eq!(config.checkpoint_interval(), None, "parsing {s}");
}
let error = serde_json::from_str::<FtConfig>(
r#"{"checkpoint_interval": "5m", "checkpoint_interval_secs": 10}"#,
)
.unwrap_err()
.to_string();
assert!(error.contains("duplicate field"), "{error}");
for (json, expected_secs) in [
(r#"{"checkpoint_interval": "1ms"}"#, 1),
(r#"{"checkpoint_interval": "10h"}"#, 3600),
] {
assert_eq!(
serde_json::from_str::<FtConfig>(json)
.unwrap()
.checkpoint_interval(),
Some(Duration::from_secs(expected_secs)),
"parsing {json}"
);
}
}
#[test]
fn legacy_duration_spelling_uses_the_older_keys() {
let mut config = serde_json::json!({
"workers": 2,
"clock_resolution": "250ms",
"max_buffering_delay": "3ms",
"provisioning_timeout": "15m",
"fault_tolerance": {"model": "at_least_once", "checkpoint_interval": "20s"},
"storage": {"backend": {"name": "file", "config": {
"ioop_latency": "5ms",
"sync": {"bucket": "b", "standby_pull_interval": "10s",
"checkpoint_push_interval": "1h", "min_retention": "30d"}}}},
});
super::to_legacy_duration_spelling(&mut config);
assert_eq!(
config,
serde_json::json!({
"workers": 2,
"clock_resolution_usecs": 250_000,
"max_buffering_delay_usecs": 3_000,
"provisioning_timeout_secs": 900,
"fault_tolerance": {"model": "at_least_once", "checkpoint_interval_secs": 20},
"storage": {"backend": {"name": "file", "config": {
"ioop_delay": 5,
"sync": {"bucket": "b", "pull_interval": 10,
"push_interval": 3_600, "retention_min_age": 30}}}},
})
);
}
fn pipeline_with_every_duration_connector() -> serde_json::Value {
serde_json::json!({
"name": "p",
"clock_resolution": "250ms",
"inputs": {
"t.kafka": {"stream": "t", "transport": {"name": "kafka_input", "config": {
"topic": "t", "group_join_timeout": "30s"}}},
"t.url": {"stream": "t", "transport": {"name": "url_input", "config": {
"path": "http://x", "pause_linger": "7s"}}},
"t.nats": {"stream": "t", "transport": {"name": "nats_input", "config": {
"connection_config": {"server_url": "nats://x",
"connection_timeout": "5s", "request_timeout": "6s"},
"stream_name": "s",
"consumer_config": {"deliver_policy": "All", "max_expiry": "45.5s"},
"inactivity_timeout": "90s", "retry_interval": "3s"}}},
"t.pubsub": {"stream": "t", "transport": {"name": "pub_sub_input", "config": {
"subscription": "s", "timeout": "20s", "connect_timeout": "4s"}}},
},
"outputs": {
"v.kafka": {"stream": "v",
"transport": {"name": "kafka_output", "config": {
"topic": "v", "initialization_timeout": "40s"}},
"format": {"name": "avro", "config": {"registry_urls": ["http://r"],
"registry_timeout": "8s"}},
"enable_output_buffer": true,
"max_output_buffer_time": "500ms"},
"v.nats": {"stream": "v", "transport": {"name": "nats_output", "config": {
"connection_config": {"server_url": "nats://x",
"connection_timeout": "5s", "request_timeout": "6s"},
"subject": "s", "publish_timeout": "9s"}}},
},
})
}
#[test]
fn legacy_duration_spelling_rewrites_every_connector() {
let mut config = pipeline_with_every_duration_connector();
super::to_legacy_duration_spelling(&mut config);
let i = &config["inputs"];
assert_eq!(
i["t.kafka"]["transport"]["config"]["group_join_timeout_secs"],
30
);
assert_eq!(i["t.url"]["transport"]["config"]["pause_timeout"], 7);
let nats = &i["t.nats"]["transport"]["config"];
assert_eq!(nats["connection_config"]["connection_timeout_secs"], 5);
assert_eq!(nats["connection_config"]["request_timeout_secs"], 6);
assert_eq!(nats["inactivity_timeout_secs"], 90);
assert_eq!(nats["retry_interval_secs"], 3);
assert_eq!(
nats["consumer_config"]["max_expires"],
serde_json::json!({"secs": 45, "nanos": 500_000_000})
);
let pubsub = &i["t.pubsub"]["transport"]["config"];
assert_eq!(pubsub["timeout_seconds"], 20);
assert_eq!(pubsub["connect_timeout_seconds"], 4);
let out = &config["outputs"]["v.kafka"];
assert_eq!(
out["transport"]["config"]["initialization_timeout_secs"],
40
);
assert_eq!(out["format"]["config"]["registry_timeout_secs"], 8);
assert_eq!(out["max_output_buffer_time_millis"], 500);
let nats = &config["outputs"]["v.nats"]["transport"]["config"];
assert_eq!(nats["connection_config"]["connection_timeout_secs"], 5);
assert_eq!(nats["connection_config"]["request_timeout_secs"], 6);
assert_eq!(nats["publish_timeout_secs"], 9);
let text = config.to_string();
for new in [
"\"group_join_timeout\"",
"\"pause_linger\"",
"\"connection_timeout\"",
"\"request_timeout\"",
"\"inactivity_timeout\"",
"\"retry_interval\"",
"\"max_expiry\"",
"\"timeout\"",
"\"connect_timeout\"",
"\"initialization_timeout\"",
"\"registry_timeout\"",
"\"max_output_buffer_time\"",
"\"publish_timeout\"",
"\"clock_resolution\"",
] {
assert!(!text.contains(new), "{new} survived in {text}");
}
}
#[test]
fn legacy_duration_spelling_round_trips_connectors() {
let original: PipelineConfig =
serde_json::from_value(pipeline_with_every_duration_connector()).unwrap();
let mut value = serde_json::to_value(&original).unwrap();
super::to_legacy_duration_spelling(&mut value);
let mut reread: PipelineConfig = serde_json::from_value(value).unwrap();
let registry = |config: &PipelineConfig| {
let format = config.outputs["v.kafka"]
.connector_config
.format
.clone()
.unwrap();
serde_json::from_value::<crate::format::avro::AvroEncoderConfig>(format.config)
.unwrap()
.registry_config
.registry_timeout
};
assert_eq!(registry(&reread), registry(&original));
let mut original = original;
for config in [&mut reread, &mut original] {
config
.outputs
.get_mut("v.kafka")
.unwrap()
.connector_config
.format = None;
}
assert_eq!(reread, original);
}
#[test]
fn legacy_duration_spelling_caps_and_keeps_bare_numbers() {
let mut config = serde_json::json!({
"inputs": {
"t.kafka": {"transport": {"name": "kafka_input", "config": {
"group_join_timeout": "100000000000s"}}},
"t.url": {"transport": {"name": "url_input", "config": {"pause_linger": 9}}},
},
"storage": {"backend": {"name": "file", "config": {
"sync": {"min_retention": "100000000000d"}}}},
});
super::to_legacy_duration_spelling(&mut config);
let i = &config["inputs"];
assert_eq!(
i["t.kafka"]["transport"]["config"]["group_join_timeout_secs"],
u64::from(u32::MAX)
);
assert_eq!(i["t.url"]["transport"]["config"]["pause_timeout"], 9);
assert_eq!(
config["storage"]["backend"]["config"]["sync"]["retention_min_age"],
u64::from(u32::MAX)
);
}
#[test]
fn legacy_duration_spelling_round_trips() {
let original: RuntimeConfig = serde_json::from_value(serde_json::json!({
"clock_resolution": "250ms",
"max_buffering_delay": "3ms",
"provisioning_timeout": "15m",
"fault_tolerance": {"model": "at_least_once", "checkpoint_interval": "20s"},
}))
.unwrap();
let mut value = serde_json::to_value(&original).unwrap();
super::to_legacy_duration_spelling(&mut value);
let reread: RuntimeConfig = serde_json::from_value(value).unwrap();
assert_eq!(reread.clock_resolution(), original.clock_resolution());
assert_eq!(reread.max_buffering_delay(), original.max_buffering_delay());
assert_eq!(reread.provisioning_timeout, original.provisioning_timeout);
assert_eq!(
reread.fault_tolerance.checkpoint_interval(),
original.fault_tolerance.checkpoint_interval()
);
}
#[test]
fn legacy_duration_spelling_edge_cases() {
let mut config = serde_json::json!({
"max_buffering_delay": null,
"provisioning_timeout": "1.5s",
"fault_tolerance": {"checkpoint_interval": null},
"clock_resolution": "10sec",
"storage": {"backend": {"name": "file", "config": {
"ioop_latency": "400us",
"sync": {"bucket": "b", "min_retention": "11h", "standby_pull_interval": "400ms"}}}},
});
super::to_legacy_duration_spelling(&mut config);
assert_eq!(
config,
serde_json::json!({
"provisioning_timeout_secs": 2,
"fault_tolerance": {"checkpoint_interval_secs": null},
"clock_resolution": "10sec",
"storage": {"backend": {"name": "file", "config": {
"ioop_delay": 1,
"sync": {"bucket": "b", "retention_min_age": 1, "pull_interval": 1}}}},
})
);
let mut zero = serde_json::json!({"provisioning_timeout": "0"});
super::to_legacy_duration_spelling(&mut zero);
assert_eq!(zero, serde_json::json!({"provisioning_timeout_secs": 0}));
let legacy = serde_json::json!({"clock_resolution_usecs": 5, "workers": 1});
let mut again = legacy.clone();
super::to_legacy_duration_spelling(&mut again);
assert_eq!(again, legacy);
}
#[test]
fn legacy_size_spelling_uses_the_older_keys() {
let mut config = serde_json::json!({
"workers": 2,
"max_rss": "16G",
"datafusion_memory": "1.5G",
"storage": {"cache_size": "4Gi", "min_spill_size": "10Mi", "min_step_spill_size": "0"},
"resources": {
"memory_min": "4G", "memory_max": "16Gi",
"storage_min": "100G", "storage_max": "400Gi",
"autoscaling": {"storage": {"scale_threshold_available": "10G", "scale_factor": 2.0}}
},
"dev_tweaks": {
"storage_max": "1Gi", "fbuf_slab_size_per_class": "16Mi",
"lazy_input_map_key_block_size": "32Ki", "exchange_channel_capacity": "10M"
},
"inputs": {
"t.file": {"stream": "t", "max_queued_size": "1Mi",
"transport": {"name": "file_input", "config": {"path": "x", "buffer_size": "64Ki"}}},
"t.cdc": {"stream": "t",
"transport": {"name": "postgres_cdc_input", "config": {"batch": {"max_size": "32Mi"}}}},
},
"outputs": {
"v.ddb": {"stream": "v",
"transport": {"name": "dynamodb_output", "config": {"max_buffer_size": "1Mi"}}},
"v.pg": {"stream": "v",
"transport": {"name": "postgres_output", "config": {"max_buffer_size": "2Mi"}}},
},
});
super::to_legacy_size_spelling(&mut config);
assert_eq!(
config,
serde_json::json!({
"workers": 2,
"max_rss_mb": 16_000,
"datafusion_memory_mb": 1_500,
"storage": {"cache_mib": 4096, "min_storage_bytes": 10 * 1024 * 1024, "min_step_storage_bytes": 0},
"resources": {
"memory_mb_min": 4_000, "memory_mb_max": 17_180,
"storage_mb_min": 100_000, "storage_mb_max": 429_497,
"autoscaling": {"storage": {"scale_threshold_available_mb": 10_000, "scale_factor": 2.0}}
},
"dev_tweaks": {
"storage_mb_max": 1024, "fbuf_slab_bytes_per_class": 16 * 1024 * 1024,
"lazy_input_map_key_block_bytes": 32 * 1024, "exchange_channel_capacity_bytes": 10_000_000
},
"inputs": {
"t.file": {"stream": "t", "max_queued_bytes": 1024 * 1024,
"transport": {"name": "file_input", "config": {"path": "x", "buffer_size_bytes": 64 * 1024}}},
"t.cdc": {"stream": "t",
"transport": {"name": "postgres_cdc_input", "config": {"batch": {"max_bytes": 32 * 1024 * 1024}}}},
},
"outputs": {
"v.ddb": {"stream": "v",
"transport": {"name": "dynamodb_output", "config": {"max_buffer_size_bytes": 1024 * 1024}}},
"v.pg": {"stream": "v",
"transport": {"name": "postgres_output", "config": {"max_buffer_size_bytes": 2 * 1024 * 1024}}},
},
})
);
}
#[test]
fn legacy_size_spelling_round_trips() {
let config: PipelineConfig = serde_json::from_value(serde_json::json!({
"name": "p",
"max_rss": "16G",
"datafusion_memory": "1G",
"storage": {"cache_size": "4Gi", "min_spill_size": "10Mi"},
"resources": {"memory_max": "16G", "storage_max": "400G"},
"dev_tweaks": {"lazy_input_map_key_block_size": "32Ki"},
"inputs": {"t.file": {"stream": "t", "max_queued_size": "1Mi",
"transport": {"name": "file_input", "config": {"path": "x", "buffer_size": "64Ki"}}}},
"outputs": {},
}))
.unwrap();
let mut value = serde_json::to_value(&config).unwrap();
super::to_legacy_size_spelling(&mut value);
assert_eq!(value["max_rss_mb"], serde_json::json!(16_000));
assert_eq!(
value["inputs"]["t.file"]["max_queued_bytes"],
serde_json::json!(1024 * 1024)
);
let reread: PipelineConfig = serde_json::from_value(value).unwrap();
assert_eq!(reread, config);
}
#[test]
fn legacy_spelling_applies_each_rename_separately() {
let current = serde_json::json!({"clock_resolution": "1s", "max_rss": "16G"});
let mut both = current.clone();
super::LegacySpelling {
durations: true,
sizes: true,
}
.apply(&mut both);
assert_eq!(
both,
serde_json::json!({"clock_resolution_usecs": 1_000_000, "max_rss_mb": 16_000})
);
let mut sizes_only = current.clone();
super::LegacySpelling {
durations: false,
sizes: true,
}
.apply(&mut sizes_only);
assert_eq!(
sizes_only,
serde_json::json!({"clock_resolution": "1s", "max_rss_mb": 16_000})
);
let mut none = current.clone();
super::LegacySpelling::NONE.apply(&mut none);
assert_eq!(none, current);
assert!(!super::LegacySpelling::NONE.any());
}
#[test]
fn legacy_size_spelling_edge_cases() {
let mut config = serde_json::json!({
"max_rss": "lots",
"resources": {"memory_max": null, "memory_min": 4000}
});
super::to_legacy_size_spelling(&mut config);
assert_eq!(
config,
serde_json::json!({"max_rss": "lots", "resources": {"memory_mb_min": 4000}})
);
let mut small = serde_json::json!({"max_rss": "1"});
super::to_legacy_size_spelling(&mut small);
assert_eq!(small, serde_json::json!({"max_rss_mb": 1}));
let legacy = serde_json::json!({"max_rss_mb": 5, "workers": 1});
let mut again = legacy.clone();
super::to_legacy_size_spelling(&mut again);
assert_eq!(again, legacy);
}
#[test]
fn a_stored_default_matches_an_omitted_one() {
let stored: ConnectorConfig = serde_json::from_value(serde_json::json!({
"transport": {
"name": "url_input",
"config": {"path": "http://example.com/x", "pause_timeout": 60},
}
}))
.unwrap();
let fresh: ConnectorConfig = serde_json::from_value(serde_json::json!({
"transport": {
"name": "url_input",
"config": {"path": "http://example.com/x"},
}
}))
.unwrap();
assert_ne!(stored, fresh);
assert!(stored.equal_for_input_checkpoint_replay(&fresh));
let changed: ConnectorConfig = serde_json::from_value(serde_json::json!({
"transport": {
"name": "url_input",
"config": {"path": "http://example.com/x", "pause_linger": "90s"},
}
}))
.unwrap();
assert!(!stored.equal_for_input_checkpoint_replay(&changed));
}
#[test]
fn an_avro_registry_timeout_compares_equal_across_the_rename() {
let connector = |registry: serde_json::Value| -> ConnectorConfig {
let mut format = serde_json::json!({"registry_urls": ["http://registry:8081"]});
format
.as_object_mut()
.unwrap()
.extend(registry.as_object().unwrap().clone());
serde_json::from_value(serde_json::json!({
"transport": {
"name": "url_input",
"config": {"path": "http://example.com/x"},
},
"format": {"name": "avro", "config": format},
}))
.unwrap()
};
let stored = connector(serde_json::json!({"registry_timeout_secs": 10}));
let current = connector(serde_json::json!({"registry_timeout": "10s"}));
let spelled_out = connector(serde_json::json!({"registry_timeout": "10000ms"}));
let changed = connector(serde_json::json!({"registry_timeout": "11s"}));
let unset = connector(serde_json::json!({}));
assert!(stored.equal_modulo_paused(¤t));
assert!(stored.equal_for_input_checkpoint_replay(¤t));
assert!(current.equal_modulo_paused(&spelled_out));
assert!(!stored.equal_modulo_paused(&changed));
assert!(!stored.equal_modulo_paused(&unset));
let json: ConnectorConfig = serde_json::from_value(serde_json::json!({
"transport": {"name": "url_input", "config": {"path": "http://example.com/x"}},
"format": {"name": "json", "config": {"registry_timeout_secs": 10}},
}))
.unwrap();
assert!(!json.equal_modulo_paused(&stored));
}
#[test]
fn the_largest_legacy_defaults_still_load() {
let buffer: OutputBufferConfig = serde_json::from_value(serde_json::json!({
"enable_output_buffer": false,
"max_output_buffer_time_millis": u64::MAX,
"max_output_buffer_size_records": 10_000_000u64,
}))
.unwrap();
assert_eq!(
buffer.max_output_buffer_time,
Some(ConfigDuration::from_millis(u64::MAX))
);
let sync: SyncConfig =
serde_json::from_str(r#"{"bucket": "b", "retention_min_age": 4000000000}"#).unwrap();
assert_eq!(
sync.min_retention(),
ConfigDuration::from_days(4_000_000_000)
);
}
#[test]
fn a_legacy_number_past_u64_seconds_saturates() {
let sync: SyncConfig =
serde_json::from_str(r#"{"bucket": "b", "retention_min_age": 18446744073709551615}"#)
.unwrap();
assert_eq!(
sync.min_retention(),
ConfigDuration::from(std::time::Duration::MAX)
);
}
#[test]
fn spelled_out_defaults_match_for_kafka_input_and_nats() {
fn connector(value: serde_json::Value) -> ConnectorConfig {
serde_json::from_value(value).unwrap()
}
fn secs(duration: ConfigDuration) -> u64 {
std::time::Duration::from(duration).as_secs()
}
let fresh_kafka = connector(serde_json::json!({
"transport": {"name": "kafka_input", "config": {"topic": "t"}}}));
let TransportConfig::KafkaInput(kafka) = &fresh_kafka.transport else {
unreachable!()
};
let stored_kafka = connector(serde_json::json!({
"transport": {"name": "kafka_input", "config": {
"topic": "t",
"group_join_timeout_secs": secs(kafka.group_join_timeout())}}}));
assert_ne!(stored_kafka, fresh_kafka);
assert!(stored_kafka.equal_for_input_checkpoint_replay(&fresh_kafka));
let base = serde_json::json!({
"connection_config": {"server_url": "nats://x"},
"stream_name": "s",
"consumer_config": {"deliver_policy": "All"}});
let fresh_nats = connector(serde_json::json!({
"transport": {"name": "nats_input", "config": base.clone()}}));
let TransportConfig::NatsInput(nats) = &fresh_nats.transport else {
unreachable!()
};
let mut spelled_out = base;
spelled_out["inactivity_timeout_secs"] = secs(nats.inactivity_timeout()).into();
spelled_out["retry_interval_secs"] = secs(nats.retry_interval()).into();
spelled_out["connection_config"]["connection_timeout_secs"] =
secs(nats.connection_config.connection_timeout()).into();
spelled_out["connection_config"]["request_timeout_secs"] =
secs(nats.connection_config.request_timeout()).into();
let stored_nats = connector(serde_json::json!({
"transport": {"name": "nats_input", "config": spelled_out}}));
assert_ne!(stored_nats, fresh_nats);
assert!(stored_nats.equal_for_input_checkpoint_replay(&fresh_nats));
}
#[test]
fn superseded_keys_are_normalised_by_a_round_trip() {
let stored = serde_json::json!({
"workers": 4,
"clock_resolution_usecs": 100_000,
"max_buffering_delay_usecs": 0,
"provisioning_timeout_secs": 300,
});
let config: RuntimeConfig = serde_json::from_value(stored).unwrap();
let written = serde_json::to_value(&config).unwrap();
assert_eq!(written["clock_resolution"], "100ms");
assert_eq!(written["max_buffering_delay"], "0s");
assert_eq!(written["provisioning_timeout"], "5m");
for superseded in [
"clock_resolution_usecs",
"max_buffering_delay_usecs",
"provisioning_timeout_secs",
] {
assert!(
written.get(superseded).is_none(),
"`{superseded}` survived the round trip: {written}"
);
}
let reparsed: RuntimeConfig = serde_json::from_value(written.clone()).unwrap();
assert_eq!(serde_json::to_value(&reparsed).unwrap(), written);
}
#[test]
fn ioop_latency_accepts_both_spellings() {
for (json, expected) in [
(r#"{"name": "file", "config": {}}"#, None),
(
r#"{"name": "file", "config": {"ioop_latency": "5ms"}}"#,
Some(ConfigDuration::from_millis(5)),
),
(
r#"{"name": "file", "config": {"ioop_delay": 5}}"#,
Some(ConfigDuration::from_millis(5)),
),
(
r#"{"name": "file", "config": {"ioop_latency": "1s"}}"#,
Some(ConfigDuration::from_secs(1)),
),
] {
let backend: StorageBackendConfig = serde_json::from_str(json).unwrap();
let StorageBackendConfig::File(file) = backend else {
panic!("expected the file backend, parsing {json}");
};
assert_eq!(file.ioop_latency, expected, "parsing {json}");
}
}
#[test]
fn clock_resolution_falls_back_to_the_deprecated_field() {
for (json, expected) in [
(r#"{}"#, DEFAULT_CLOCK_RESOLUTION),
(
r#"{"clock_resolution": "100ms"}"#,
ConfigDuration::from_millis(100),
),
(
r#"{"clock_resolution_usecs": 100000}"#,
ConfigDuration::from_millis(100),
),
(r#"{"clock_resolution": null}"#, DEFAULT_CLOCK_RESOLUTION),
(
r#"{"clock_resolution_usecs": null}"#,
DEFAULT_CLOCK_RESOLUTION,
),
] {
assert_eq!(
serde_json::from_str::<RuntimeConfig>(json)
.unwrap()
.clock_resolution(),
expected,
"parsing {json}"
);
}
}
#[test]
fn deprecated_duration_fields_still_work() {
let runtime: RuntimeConfig = serde_json::from_str(
r#"{"max_buffering_delay_usecs": 5000, "provisioning_timeout_secs": 1200}"#,
)
.unwrap();
assert_eq!(
runtime.max_buffering_delay(),
ConfigDuration::from_millis(5)
);
assert_eq!(
runtime.provisioning_timeout,
Some(ConfigDuration::from_secs(1200))
);
let sync: SyncConfig = serde_json::from_str(
r#"{"bucket": "b", "pull_interval": 30, "push_interval": 300, "retention_min_age": 7}"#,
)
.unwrap();
assert_eq!(sync.standby_pull_interval(), ConfigDuration::from_secs(30));
assert_eq!(
sync.checkpoint_push_interval(),
Some(ConfigDuration::from_secs(300))
);
assert_eq!(sync.min_retention(), ConfigDuration::from_days(7));
let storage: FileBackendConfig = serde_json::from_str(r#"{"ioop_delay": 5}"#).unwrap();
assert_eq!(storage.ioop_latency, Some(ConfigDuration::from_millis(5)));
let buffer: OutputBufferConfig =
serde_json::from_str(r#"{"max_output_buffer_time_millis": 250}"#).unwrap();
assert_eq!(
buffer.max_output_buffer_time(),
ConfigDuration::from_millis(250)
);
}
#[test]
fn duration_fields_default_when_unset() {
let sync: SyncConfig = serde_json::from_str(r#"{"bucket": "b"}"#).unwrap();
assert_eq!(sync.standby_pull_interval(), DEFAULT_PULL_INTERVAL);
assert_eq!(sync.checkpoint_push_interval(), None);
assert_eq!(sync.min_retention(), DEFAULT_RETENTION_MIN_AGE);
let runtime = RuntimeConfig::default();
assert_eq!(runtime.max_buffering_delay(), ConfigDuration::ZERO);
assert_eq!(runtime.clock_resolution(), DEFAULT_CLOCK_RESOLUTION);
assert_eq!(runtime.provisioning_timeout, None);
}
#[test]
fn storage_options_f64_roundtrip_through_pipeline_config() {
let pc = PipelineConfig {
global: RuntimeConfig {
storage: Some(StorageOptions {
bloom_false_positive_rate: Some(0.01),
..Default::default()
}),
..Default::default()
},
multihost: None,
name: Some("test-pipeline".into()),
given_name: None,
storage_config: None,
secrets_dir: None,
inputs: Default::default(),
outputs: Default::default(),
program_ir: None,
};
let json = serde_json::to_string_pretty(&pc).unwrap();
let pc2: PipelineConfig = serde_json::from_str(&json).expect(
"JSON string round-trip of PipelineConfig with f64 StorageOptions must succeed",
);
assert_eq!(
pc2.global.storage.unwrap().bloom_false_positive_rate,
Some(0.01)
);
let value = serde_json::to_value(&pc).unwrap();
let pc3: PipelineConfig = serde_json::from_value(value)
.expect("Value round-trip of PipelineConfig with f64 StorageOptions must succeed");
assert_eq!(
pc3.global.storage.unwrap().bloom_false_positive_rate,
Some(0.01)
);
}
}
impl FtConfig {
pub fn is_enabled(&self) -> bool {
self.model.is_some()
}
pub fn checkpoint_interval(&self) -> Option<Duration> {
if !self.is_enabled() {
return None;
}
let interval = self
.checkpoint_interval
.unwrap_or(Some(DEFAULT_CHECKPOINT_INTERVAL))?;
Some(Duration::from(interval).clamp(Duration::from_secs(1), Duration::from_secs(3600)))
}
}
mod none_as_string {
use std::marker::PhantomData;
use serde::de::{Deserialize, Deserializer, IntoDeserializer, Visitor};
use serde::ser::{Serialize, Serializer};
pub(super) fn serialize<S, T>(value: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
T: Serialize,
{
match value.as_ref() {
Some(value) => value.serialize(serializer),
None => "none".serialize(serializer),
}
}
struct NoneAsString<T>(PhantomData<fn() -> T>);
impl<'de, T> Visitor<'de> for NoneAsString<T>
where
T: Deserialize<'de>,
{
type Value = Option<T>;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("string")
}
fn visit_none<E>(self) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(None)
}
fn visit_str<E>(self, value: &str) -> Result<Option<T>, E>
where
E: serde::de::Error,
{
if &value.to_ascii_lowercase() == "none" {
Ok(None)
} else {
Ok(Some(T::deserialize(value.into_deserializer())?))
}
}
}
pub(super) fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de>,
{
deserializer.deserialize_str(NoneAsString(PhantomData))
}
}
fn none_as_string_schema<'a, T: ToSchema<'a> + Default + Serialize>() -> Schema {
Schema::OneOf(
OneOfBuilder::new()
.item(RefOr::Ref(Ref::new(format!(
"#/components/schemas/{}",
T::schema().0
))))
.item(
ObjectBuilder::new()
.schema_type(SchemaType::String)
.enum_values(Some(vec!["none"])),
)
.default(Some(
serde_json::to_value(T::default()).expect("Failed to serialize default value"),
))
.build(),
)
}
#[derive(
Debug, Copy, Clone, Default, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize, ToSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum FtModel {
AtLeastOnce,
#[default]
ExactlyOnce,
}
impl FtModel {
pub fn option_as_str(value: Option<FtModel>) -> &'static str {
value.map_or("no", |model| model.as_str())
}
pub fn as_str(&self) -> &'static str {
match self {
FtModel::AtLeastOnce => "at_least_once",
FtModel::ExactlyOnce => "exactly_once",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FtModelUnknown;
impl std::fmt::Display for FtModelUnknown {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("expected `exactly_once` or `at_least_once`")
}
}
impl std::error::Error for FtModelUnknown {}
impl FromStr for FtModel {
type Err = FtModelUnknown;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"exactly_once" => Ok(Self::ExactlyOnce),
"at_least_once" => Ok(Self::AtLeastOnce),
_ => Err(FtModelUnknown),
}
}
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct InputEndpointConfig {
pub stream: Cow<'static, str>,
#[serde(flatten)]
pub connector_config: ConnectorConfig,
}
impl InputEndpointConfig {
pub fn new(stream: impl Into<Cow<'static, str>>, connector_config: ConnectorConfig) -> Self {
Self {
stream: stream.into(),
connector_config,
}
}
}
fn deserialize_start_after<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
where
D: Deserializer<'de>,
{
let value = Option::<JsonValue>::deserialize(deserializer)?;
match value {
Some(JsonValue::String(s)) => Ok(Some(vec![s])),
Some(JsonValue::Array(arr)) => {
let vec = arr
.into_iter()
.map(|item| {
item.as_str()
.map(|s| s.to_string())
.ok_or_else(|| serde::de::Error::custom("invalid 'start_after' property: expected a string, an array of strings, or null"))
})
.collect::<Result<Vec<String>, _>>()?;
Ok(Some(vec))
}
Some(JsonValue::Null) | None => Ok(None),
_ => Err(serde::de::Error::custom(
"invalid 'start_after' property: expected a string, an array of strings, or null",
)),
}
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct ConnectorConfig {
#[serde(default)]
pub send_snapshot: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub soft_delete: bool,
pub transport: TransportConfig,
#[serde(skip_serializing_if = "Option::is_none")]
pub preprocessor: Option<Vec<PreprocessorConfig>>,
pub format: Option<FormatConfig>,
#[serde(skip_serializing_if = "Option::is_none")]
pub postprocessor: Option<Vec<PostprocessorConfig>>,
pub index: Option<String>,
#[serde(flatten)]
pub output_buffer_config: OutputBufferConfig,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_batch_size: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_worker_batch_size: Option<u64>,
#[serde(default = "default_max_queued_records")]
pub max_queued_records: u64,
#[serde(
default,
alias = "max_queued_bytes",
deserialize_with = "size_max_queued_size",
skip_serializing_if = "Option::is_none"
)]
#[schema(value_type = Option<String>)]
pub max_queued_size: Option<ConfigSize>,
#[serde(default)]
pub paused: bool,
#[serde(default)]
pub labels: Vec<String>,
#[serde(deserialize_with = "deserialize_start_after")]
#[serde(default)]
pub start_after: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub distributed: bool,
}
impl ConnectorConfig {
pub fn new(transport: TransportConfig, format: Option<FormatConfig>) -> Self {
Self {
send_snapshot: false,
soft_delete: false,
transport,
preprocessor: None,
format,
postprocessor: None,
index: None,
output_buffer_config: Default::default(),
max_batch_size: None,
max_worker_batch_size: None,
max_queued_records: default_max_queued_records(),
max_queued_size: None,
paused: false,
labels: Vec::new(),
start_after: None,
distributed: false,
}
}
pub fn with_max_batch_size(mut self, max_batch_size: Option<u64>) -> Self {
self.max_batch_size = max_batch_size;
self
}
pub fn with_max_queued_records(mut self, max_queued_records: u64) -> Self {
self.max_queued_records = max_queued_records;
self
}
pub fn equal_modulo_paused(&self, other: &Self) -> bool {
let mut a = self.clone();
let mut b = other.clone();
a.paused = false;
b.paused = false;
a.normalize_durations();
b.normalize_durations();
a == b
}
fn normalize_durations(&mut self) {
self.transport.normalize_durations();
self.output_buffer_config.max_output_buffer_time =
Some(self.output_buffer_config.max_output_buffer_time());
if let Some(format) = &mut self.format {
format.normalize_durations();
}
}
pub fn equal_for_input_checkpoint_replay(&self, other: &Self) -> bool {
let mut a = self.clone();
let mut b = other.clone();
a.normalize_for_input_checkpoint_replay();
b.normalize_for_input_checkpoint_replay();
a == b
}
fn normalize_for_input_checkpoint_replay(&mut self) {
self.paused = false;
self.max_batch_size = None;
self.max_worker_batch_size = None;
self.max_queued_records = default_max_queued_records();
self.max_queued_size = None;
self.normalize_durations();
}
pub fn apply_input_checkpoint_replay_config_from(&mut self, other: &Self) {
self.max_batch_size = other.max_batch_size;
self.max_worker_batch_size = other.max_worker_batch_size;
self.max_queued_records = other.max_queued_records;
self.max_queued_size = other.max_queued_size;
}
pub fn max_queued_records(&self) -> u64 {
self.max_queued_records
}
pub fn max_queued_bytes(&self) -> u64 {
self.max_queued_size
.map(ConfigSize::as_bytes)
.unwrap_or_else(|| self.max_queued_records().saturating_mul(1000))
}
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(default)]
pub struct OutputBufferConfig {
pub enable_output_buffer: bool,
#[serde(
default,
alias = "max_output_buffer_time_millis",
deserialize_with = "duration_max_output_buffer_time",
skip_serializing_if = "Option::is_none"
)]
#[schema(value_type = Option<String>)]
pub max_output_buffer_time: Option<ConfigDuration>,
pub max_output_buffer_size_records: usize,
}
impl OutputBufferConfig {
pub fn max_output_buffer_time(&self) -> ConfigDuration {
self.max_output_buffer_time
.unwrap_or(ConfigDuration::from_millis(u64::MAX))
}
}
impl Default for OutputBufferConfig {
fn default() -> Self {
Self {
enable_output_buffer: false,
max_output_buffer_size_records: DEFAULT_MAX_OUTPUT_BUFFER_SIZE_RECORDS,
max_output_buffer_time: None,
}
}
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct OutputEndpointConfig {
pub stream: Cow<'static, str>,
#[serde(flatten)]
pub connector_config: ConnectorConfig,
}
impl OutputEndpointConfig {
pub fn new(stream: impl Into<Cow<'static, str>>, connector_config: ConnectorConfig) -> Self {
Self {
stream: stream.into(),
connector_config,
}
}
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(tag = "name", content = "config", rename_all = "snake_case")]
pub enum TransportConfig {
FileInput(FileInputConfig),
FileOutput(FileOutputConfig),
NatsInput(Box<NatsInputConfig>),
NatsOutput(NatsOutputConfig),
KafkaInput(KafkaInputConfig),
KafkaOutput(KafkaOutputConfig),
PubSubInput(PubSubInputConfig),
UrlInput(UrlInputConfig),
S3Input(S3InputConfig),
DeltaTableInput(DeltaTableReaderConfig),
DeltaTableOutput(DeltaTableWriterConfig),
#[serde(rename = "dynamodb_output")]
DynamoDBOutput(DynamoDBWriterConfig),
RedisOutput(RedisOutputConfig),
IcebergInput(Box<IcebergReaderConfig>),
PostgresInput(PostgresReaderConfig),
PostgresCdcInput(PostgresCdcReaderConfig),
PostgresOutput(PostgresWriterConfig),
Datagen(DatagenInputConfig),
Nexmark(NexmarkInputConfig),
HttpInput(HttpInputConfig),
HttpOutput(HttpOutputConfig),
AdHocInput(AdHocInputConfig),
ClockInput(ClockConfig),
S2Input(S2InputConfig),
S2Output(S2OutputConfig),
NullOutput,
EmptyInput,
}
impl TransportConfig {
pub fn normalize_durations(&mut self) {
match self {
TransportConfig::UrlInput(config) => {
config.pause_linger = Some(config.pause_linger());
}
TransportConfig::KafkaInput(config) => {
config.group_join_timeout = Some(config.group_join_timeout());
}
TransportConfig::KafkaOutput(config) => {
config.initialization_timeout = Some(config.initialization_timeout());
}
TransportConfig::NatsInput(config) => {
config.connection_config.connection_timeout =
Some(config.connection_config.connection_timeout());
config.connection_config.request_timeout =
Some(config.connection_config.request_timeout());
config.inactivity_timeout = Some(config.inactivity_timeout());
config.retry_interval = Some(config.retry_interval());
}
TransportConfig::NatsOutput(config) => {
config.connection_config.connection_timeout =
Some(config.connection_config.connection_timeout());
config.connection_config.request_timeout =
Some(config.connection_config.request_timeout());
config.publish_timeout = Some(config.publish_timeout());
}
_ => {}
}
}
pub fn name(&self) -> String {
match self {
TransportConfig::FileInput(_) => "file_input".to_string(),
TransportConfig::FileOutput(_) => "file_output".to_string(),
TransportConfig::NatsInput(_) => "nats_input".to_string(),
TransportConfig::NatsOutput(_) => "nats_output".to_string(),
TransportConfig::KafkaInput(_) => "kafka_input".to_string(),
TransportConfig::KafkaOutput(_) => "kafka_output".to_string(),
TransportConfig::PubSubInput(_) => "pub_sub_input".to_string(),
TransportConfig::UrlInput(_) => "url_input".to_string(),
TransportConfig::S3Input(_) => "s3_input".to_string(),
TransportConfig::DeltaTableInput(_) => "delta_table_input".to_string(),
TransportConfig::DeltaTableOutput(_) => "delta_table_output".to_string(),
TransportConfig::DynamoDBOutput(_) => "dynamodb_output".to_string(),
TransportConfig::IcebergInput(_) => "iceberg_input".to_string(),
TransportConfig::PostgresInput(_) => "postgres_input".to_string(),
TransportConfig::PostgresCdcInput(_) => "postgres_cdc_input".to_string(),
TransportConfig::PostgresOutput(_) => "postgres_output".to_string(),
TransportConfig::Datagen(_) => "datagen".to_string(),
TransportConfig::Nexmark(_) => "nexmark".to_string(),
TransportConfig::HttpInput(_) => "http_input".to_string(),
TransportConfig::HttpOutput(_) => "http_output".to_string(),
TransportConfig::AdHocInput(_) => "adhoc_input".to_string(),
TransportConfig::RedisOutput(_) => "redis_output".to_string(),
TransportConfig::ClockInput(_) => "clock".to_string(),
TransportConfig::S2Input(_) => "s2_input".to_string(),
TransportConfig::S2Output(_) => "s2_output".to_string(),
TransportConfig::NullOutput => "null_output".to_string(),
TransportConfig::EmptyInput => "empty_input".to_string(),
}
}
pub fn is_transient(&self) -> bool {
matches!(
self,
TransportConfig::AdHocInput(_)
| TransportConfig::HttpInput(_)
| TransportConfig::HttpOutput(_)
| TransportConfig::ClockInput(_)
)
}
pub fn is_http_input(&self) -> bool {
matches!(self, TransportConfig::HttpInput(_))
}
pub fn supports_distribution(&self) -> bool {
matches!(
self,
TransportConfig::KafkaInput(_)
| TransportConfig::DeltaTableInput(_)
| TransportConfig::IcebergInput(_)
)
}
pub fn needs_input_choice(&self) -> bool {
matches!(
self,
TransportConfig::DeltaTableInput(_) | TransportConfig::IcebergInput(_)
)
}
pub fn frontier_merge(&self) -> crate::adapter_stats::FrontierMerge {
use crate::adapter_stats::FrontierMerge;
match self {
TransportConfig::KafkaInput(_) => FrontierMerge::Partitioned,
TransportConfig::DeltaTableInput(_) | TransportConfig::IcebergInput(_) => {
FrontierMerge::Shared
}
_ => FrontierMerge::Opaque,
}
}
}
#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, ToSchema)]
pub struct FormatConfig {
pub name: Cow<'static, str>,
#[serde(default)]
#[schema(value_type = Object)]
pub config: JsonValue,
}
impl FormatConfig {
pub fn normalize_durations(&mut self) {
if self.name != "avro" {
return;
}
let has_timeout = self.config.as_object().is_some_and(|object| {
object.contains_key("registry_timeout") || object.contains_key("registry_timeout_secs")
});
if !has_timeout {
return;
}
let Ok(registry) = serde_json::from_value::<crate::format::avro::AvroSchemaRegistryConfig>(
self.config.clone(),
) else {
return;
};
let object = self.config.as_object_mut().unwrap();
object.remove("registry_timeout_secs");
match registry.registry_timeout {
Some(timeout) => object.insert(
"registry_timeout".to_string(),
JsonValue::String(timeout.to_string()),
),
None => object.remove("registry_timeout"),
};
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
#[serde(default)]
pub struct ResourceConfig {
#[serde(deserialize_with = "crate::serde_via_value::deserialize")]
pub cpu_cores_min: Option<f64>,
#[serde(deserialize_with = "crate::serde_via_value::deserialize")]
pub cpu_cores_max: Option<f64>,
#[serde(
alias = "memory_mb_min",
deserialize_with = "size_memory_min",
skip_serializing_if = "Option::is_none"
)]
#[schema(value_type = Option<String>)]
pub memory_min: Option<ConfigSize>,
#[serde(
alias = "memory_mb_max",
deserialize_with = "size_memory_max",
skip_serializing_if = "Option::is_none"
)]
#[schema(value_type = Option<String>)]
pub memory_max: Option<ConfigSize>,
#[serde(
alias = "storage_mb_min",
deserialize_with = "size_storage_min",
skip_serializing_if = "Option::is_none"
)]
#[schema(value_type = Option<String>)]
pub storage_min: Option<ConfigSize>,
#[serde(
alias = "storage_mb_max",
deserialize_with = "size_storage_max",
skip_serializing_if = "Option::is_none"
)]
#[schema(value_type = Option<String>)]
pub storage_max: Option<ConfigSize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub autoscaling: Option<AutoscalingConfig>,
pub storage_class: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub volume_attributes_class: Option<String>,
pub service_account_name: Option<String>,
pub namespace: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
#[serde(default)]
pub struct AutoscalingConfig {
#[serde(skip_serializing_if = "Option::is_none")]
pub storage: Option<StorageAutoscalingConfig>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
#[serde(default)]
pub struct StorageAutoscalingConfig {
#[serde(
deserialize_with = "crate::serde_via_value::deserialize",
skip_serializing_if = "Option::is_none"
)]
pub scale_threshold: Option<f64>,
#[serde(
alias = "scale_threshold_available_mb",
deserialize_with = "size_scale_threshold_available",
skip_serializing_if = "Option::is_none"
)]
#[schema(value_type = Option<String>)]
pub scale_threshold_available: Option<ConfigSize>,
#[serde(
deserialize_with = "crate::serde_via_value::deserialize",
skip_serializing_if = "Option::is_none"
)]
pub scale_factor: Option<f64>,
}
#[cfg(test)]
mod resource_config_tests {
use super::{AutoscalingConfig, ResourceConfig, StorageAutoscalingConfig};
use crate::size::ConfigSize;
use serde_json::json;
#[test]
fn storage_autoscaling_round_trips_through_json() {
let input = json!({
"storage_min": "1G",
"storage_max": "8G",
"autoscaling": {
"storage": {
"scale_threshold": 0.8,
"scale_threshold_available": "10G",
"scale_factor": 2.0
}
}
});
let config: ResourceConfig = serde_json::from_value(input).unwrap();
assert_eq!(config.storage_min, Some(ConfigSize::from_mb(1000)));
assert_eq!(config.storage_max, Some(ConfigSize::from_mb(8000)));
assert_eq!(
config.autoscaling,
Some(AutoscalingConfig {
storage: Some(StorageAutoscalingConfig {
scale_threshold: Some(0.8),
scale_threshold_available: Some(ConfigSize::from_mb(10000)),
scale_factor: Some(2.0),
}),
})
);
let output = serde_json::to_value(&config).unwrap();
assert_eq!(output["storage_min"], json!("1G"));
assert_eq!(
output["autoscaling"]["storage"]["scale_threshold"],
json!(0.8)
);
assert_eq!(
output["autoscaling"]["storage"]["scale_threshold_available"],
json!("10G")
);
assert_eq!(output["autoscaling"]["storage"]["scale_factor"], json!(2.0));
}
#[test]
fn autoscaling_fields_default_to_none() {
let config: ResourceConfig = serde_json::from_value(json!({})).unwrap();
assert_eq!(config.storage_min, None);
assert_eq!(config.autoscaling, None);
let output = serde_json::to_value(&config).unwrap();
assert!(output.get("storage_min").is_none());
assert!(output.get("autoscaling").is_none());
assert!(output.get("storage_max").is_none());
let input = json!({ "autoscaling": { "storage": { "scale_threshold": 0.9 } } });
let config: ResourceConfig = serde_json::from_value(input.clone()).unwrap();
let output = serde_json::to_value(&config).unwrap();
assert_eq!(output["autoscaling"], input["autoscaling"]);
let config: ResourceConfig = serde_json::from_value(json!({ "autoscaling": {} })).unwrap();
assert_eq!(config.autoscaling, Some(AutoscalingConfig::default()));
}
#[test]
fn autoscaling_rejects_non_numeric_values() {
let input = json!({ "autoscaling": { "storage": { "scale_threshold": "high" } } });
assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
let input = json!({ "autoscaling": { "storage": { "scale_threshold_available_mb": -1 } } });
assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
let input = json!({ "storage_mb_min": -1 });
assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
}
}
#[cfg(test)]
mod sync_config_tests {
use super::SyncConfig;
fn config(bucket: &str, read_bucket: Option<&str>) -> SyncConfig {
SyncConfig {
bucket: bucket.to_owned(),
read_bucket: read_bucket.map(str::to_owned),
..Default::default()
}
}
#[test]
fn read_bucket_must_differ_from_bucket() {
let err = config("ckpts/a", Some("ckpts/a")).validate().unwrap_err();
assert!(err.contains("different locations"), "{err}");
}
#[test]
fn read_bucket_must_use_the_same_object_store() {
let err = config("gs://ckpts/a", Some("ckpts/b"))
.validate()
.unwrap_err();
assert!(err.contains("same object store"), "{err}");
let err = config("ckpts/a", Some("gs://ckpts/b"))
.validate()
.unwrap_err();
assert!(err.contains("same object store"), "{err}");
}
#[test]
fn matching_object_stores_are_accepted() {
config("gs://ckpts/a", Some("gs://ckpts/b"))
.validate()
.unwrap();
config("ckpts/a", Some("s3://ckpts/b")).validate().unwrap();
config("gs://ckpts/a", None).validate().unwrap();
}
#[test]
fn take_bucket_ownership_defaults_to_false() {
let sync: SyncConfig = serde_json::from_str(r#"{"bucket": "ckpts/a"}"#).unwrap();
assert!(!sync.take_bucket_ownership);
let sync: SyncConfig =
serde_json::from_str(r#"{"bucket": "ckpts/a", "take_bucket_ownership": true}"#)
.unwrap();
assert!(sync.take_bucket_ownership);
}
}