Skip to main content

feldera_types/
config.rs

1//! Controller configuration.
2//!
3//! This module defines the controller configuration structure.  The leaves of
4//! this structure are individual transport-specific and data-format-specific
5//! endpoint configs.  We represent these configs as opaque JSON values, so
6//! that the entire configuration tree can be deserialized from a JSON file.
7
8use crate::postprocess::PostprocessorConfig;
9use crate::preprocess::PreprocessorConfig;
10use crate::secret_resolver::default_secrets_directory;
11use crate::transport::adhoc::AdHocInputConfig;
12use crate::transport::clock::{ClockConfig, ClockTimezoneOffset};
13use crate::transport::datagen::DatagenInputConfig;
14use crate::transport::delta_table::{DeltaTableReaderConfig, DeltaTableWriterConfig};
15use crate::transport::dynamodb::DynamoDBWriterConfig;
16use crate::transport::file::{FileInputConfig, FileOutputConfig};
17use crate::transport::http::{HttpInputConfig, HttpOutputConfig};
18use crate::transport::iceberg::IcebergReaderConfig;
19use crate::transport::kafka::{KafkaInputConfig, KafkaOutputConfig};
20use crate::transport::nats::NatsInputConfig;
21use crate::transport::nexmark::NexmarkInputConfig;
22use crate::transport::postgres::{
23    PostgresCdcReaderConfig, PostgresReaderConfig, PostgresWriterConfig,
24};
25use crate::transport::pubsub::PubSubInputConfig;
26use crate::transport::redis::RedisOutputConfig;
27use crate::transport::s3::S3InputConfig;
28use crate::transport::url::UrlInputConfig;
29use core::fmt;
30use feldera_ir::{MirNode, MirNodeId};
31use serde::de::{self, MapAccess, Visitor};
32use serde::{Deserialize, Deserializer, Serialize};
33use serde_json::Value as JsonValue;
34use std::collections::HashMap;
35use std::fmt::Display;
36use std::path::Path;
37use std::str::FromStr;
38use std::time::Duration;
39use std::{borrow::Cow, cmp::max, collections::BTreeMap};
40use utoipa::ToSchema;
41use utoipa::openapi::{ObjectBuilder, OneOfBuilder, Ref, RefOr, Schema, SchemaType};
42
43pub mod dev_tweaks;
44pub use dev_tweaks::DevTweaks;
45
46const DEFAULT_MAX_PARALLEL_CONNECTOR_INIT: u64 = 10;
47
48/// Default maximum number of updates to be kept in the output buffer.
49const DEFAULT_MAX_OUTPUT_BUFFER_SIZE_RECORDS: usize = 10_000_000;
50
51/// Default value of `ConnectorConfig::max_queued_records`.
52pub const fn default_max_queued_records() -> u64 {
53    1_000_000
54}
55
56pub const DEFAULT_MAX_WORKER_BATCH_SIZE: u64 = 10_000;
57
58pub const DEFAULT_CLOCK_RESOLUTION_USECS: u64 = 1_000_000;
59
60/// Program information included in the pipeline configuration.
61#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
62pub struct ProgramIr {
63    /// The MIR of the program.
64    pub mir: HashMap<MirNodeId, MirNode>,
65    /// Program schema.
66    pub program_schema: serde_json::Value,
67}
68
69/// Identity of a pipeline, used to record and check ownership of an S3
70/// checkpoint bucket.
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
72pub struct PipelineIdentity {
73    /// System-generated name of the pipeline (format `pipeline-<uuid>`).
74    pub name: String,
75    /// Name given to the pipeline by the tenant.
76    pub given_name: Option<String>,
77}
78
79impl Display for PipelineIdentity {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        match &self.given_name {
82            Some(given_name) => write!(f, "{given_name} (id: {})", self.name),
83            None => write!(f, "{}", self.name),
84        }
85    }
86}
87
88/// Pipeline deployment configuration.
89/// It represents configuration entries directly provided by the user
90/// (e.g., runtime configuration) and entries derived from the schema
91/// of the compiled program (e.g., connectors). Storage configuration,
92/// if applicable, is set by the runner.
93#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq)]
94pub struct PipelineConfig {
95    /// Global controller configuration.
96    #[serde(flatten)]
97    #[schema(inline)]
98    pub global: RuntimeConfig,
99
100    /// Configuration for multihost pipelines.
101    ///
102    /// The presence of this field indicates that the pipeline is running in
103    /// multihost mode.  In the pod with ordinal 0, this triggers starting the
104    /// coordinator process.  In all pods, this tells the pipeline process to
105    /// await a connection from the coordinator instead of initializing the
106    /// pipeline immediately.
107    pub multihost: Option<MultihostConfig>,
108
109    /// Unique system-generated name of the pipeline (format: `pipeline-<uuid>`).
110    /// It is unique across all tenants and cannot be changed.
111    ///
112    /// The `<uuid>` is also used in the naming of various resources that back the pipeline,
113    /// and as such this name is useful to find/identify corresponding resources.
114    pub name: Option<String>,
115
116    /// Name given by the tenant to the pipeline. It is only unique within the same tenant, and can
117    /// be changed by the tenant when the pipeline is stopped.
118    ///
119    /// Given a specific tenant, it can be used to find/identify a specific pipeline of theirs.
120    pub given_name: Option<String>,
121
122    /// Configuration for persistent storage
123    ///
124    /// If `global.storage` is `Some(_)`, this field must be set to some
125    /// [`StorageConfig`].  If `global.storage` is `None``, the pipeline ignores
126    /// this field.
127    #[serde(default)]
128    pub storage_config: Option<StorageConfig>,
129
130    /// Directory containing values of secrets.
131    ///
132    /// If this is not set, a default directory is used.
133    pub secrets_dir: Option<String>,
134
135    /// Input endpoint configuration.
136    #[serde(default)]
137    pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
138
139    /// Output endpoint configuration.
140    #[serde(default)]
141    pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
142
143    /// Program information.
144    #[serde(default)]
145    pub program_ir: Option<ProgramIr>,
146}
147
148impl PipelineConfig {
149    pub fn max_parallel_connector_init(&self) -> u64 {
150        max(
151            self.global
152                .max_parallel_connector_init
153                .unwrap_or(DEFAULT_MAX_PARALLEL_CONNECTOR_INIT),
154            1,
155        )
156    }
157
158    /// Extract the compiler-generated subset of the configuration (connectors
159    /// and program IR) used to compute pipeline diffs.
160    pub fn program_info_subset(&self) -> PipelineConfigProgramInfo {
161        PipelineConfigProgramInfo {
162            inputs: self.inputs.clone(),
163            outputs: self.outputs.clone(),
164            program_ir: self.program_ir.clone(),
165        }
166    }
167
168    pub fn with_storage(self, storage: Option<(StorageConfig, StorageOptions)>) -> Self {
169        let (storage_config, storage_options) = storage.unzip();
170        Self {
171            global: RuntimeConfig {
172                storage: storage_options,
173                ..self.global
174            },
175            storage_config,
176            ..self
177        }
178    }
179
180    pub fn storage(&self) -> Option<(&StorageConfig, &StorageOptions)> {
181        let storage_options = self.global.storage.as_ref();
182        let storage_config = self.storage_config.as_ref();
183        storage_config.zip(storage_options)
184    }
185
186    /// Returns this pipeline's [`PipelineIdentity`], used to identify the
187    /// pipeline that owns an S3 checkpoint bucket.
188    ///
189    /// Returns `None` when the pipeline has no system-generated [`name`](Self::name).
190    pub fn pipeline_identity(&self) -> Option<PipelineIdentity> {
191        self.name.as_ref().map(|name| PipelineIdentity {
192            name: name.clone(),
193            given_name: self.given_name.clone(),
194        })
195    }
196
197    /// Returns `self.secrets_dir`, or the default secrets directory if it isn't
198    /// set.
199    pub fn secrets_dir(&self) -> &Path {
200        match &self.secrets_dir {
201            Some(dir) => Path::new(dir.as_str()),
202            None => default_secrets_directory(),
203        }
204    }
205
206    /// Abbreviated config that can be printed in the log on pipeline startup.
207    pub fn display_summary(&self) -> String {
208        // TODO: we may want to further abbreviate connector config.
209        let summary = serde_json::json!({
210            "name": self.name,
211            "given_name": self.given_name,
212            "global": self.global,
213            "storage_config": self.storage_config,
214            "secrets_dir": self.secrets_dir,
215            "inputs": self.inputs,
216            "outputs": self.outputs
217        });
218
219        serde_json::to_string_pretty(&summary).unwrap_or_else(|_| "{}".to_string())
220    }
221}
222
223/// A subset of fields in `PipelineConfig` that are generated by the compiler.
224/// These fields are shipped to the pipeline by the compilation server along with
225/// the program binary.
226// Note: An alternative would be to embed these fields in the program binary itself
227// as static strings. This would work well for program IR, but it would require recompiling
228// the program anytime a connector config changes, whereas today connector changes
229// do not require recompilation.
230#[derive(Default, Deserialize, Serialize, Eq, PartialEq, Debug, Clone)]
231pub struct PipelineConfigProgramInfo {
232    /// Input endpoint configuration.
233    pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
234
235    /// Output endpoint configuration.
236    #[serde(default)]
237    pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
238
239    /// Program information.
240    #[serde(default)]
241    pub program_ir: Option<ProgramIr>,
242}
243
244/// Configuration for a multihost Feldera pipeline.
245///
246/// This configuration is primarily for the coordinator.
247#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
248pub struct MultihostConfig {
249    /// Number of hosts to launch.
250    ///
251    /// For the configuration to be truly multihost, this should be at least 2.
252    /// A value of 1 still runs the multihost coordinator but it only
253    /// coordinates a single host.
254    pub hosts: usize,
255}
256
257impl Default for MultihostConfig {
258    fn default() -> Self {
259        Self { hosts: 1 }
260    }
261}
262
263/// Configuration for persistent storage in a [`PipelineConfig`].
264#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
265pub struct StorageConfig {
266    /// A directory to keep pipeline state, as a path on the filesystem of the
267    /// machine or container where the pipeline will run.
268    ///
269    /// When storage is enabled, this directory stores the data for
270    /// [StorageBackendConfig::Default].
271    ///
272    /// When fault tolerance is enabled, this directory stores checkpoints and
273    /// the log.
274    pub path: String,
275
276    /// How to cache access to storage in this pipeline.
277    #[serde(default)]
278    pub cache: StorageCacheConfig,
279}
280
281impl StorageConfig {
282    pub fn path(&self) -> &Path {
283        Path::new(&self.path)
284    }
285}
286
287/// How to cache access to storage within a Feldera pipeline.
288#[derive(Copy, Clone, Default, Deserialize, Serialize, Debug, PartialEq, Eq, ToSchema)]
289#[serde(rename_all = "snake_case")]
290pub enum StorageCacheConfig {
291    /// Use the operating system's page cache as the primary storage cache.
292    ///
293    /// This is the default because it currently performs better than
294    /// `FelderaCache`.
295    #[default]
296    PageCache,
297
298    /// Use Feldera's internal cache implementation.
299    ///
300    /// This is under development. It will become the default when its
301    /// performance exceeds that of `PageCache`.
302    FelderaCache,
303}
304
305impl StorageCacheConfig {
306    #[cfg(unix)]
307    pub fn to_custom_open_flags(&self) -> i32 {
308        match self {
309            StorageCacheConfig::PageCache => (),
310            StorageCacheConfig::FelderaCache => {
311                #[cfg(target_os = "linux")]
312                return libc::O_DIRECT;
313            }
314        }
315        0
316    }
317}
318
319/// Storage configuration for a pipeline.
320#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
321#[serde(default)]
322pub struct StorageOptions {
323    /// How to connect to the underlying storage.
324    pub backend: StorageBackendConfig,
325
326    /// For a batch of data maintained as part of a persistent index during a
327    /// pipeline run, the minimum estimated number of bytes to write it to
328    /// storage.
329    ///
330    /// This is provided for debugging and fine-tuning and should ordinarily be
331    /// left unset.
332    ///
333    /// A value of 0 will write even empty batches to storage, and nonzero
334    /// values provide a threshold.  `usize::MAX` would effectively disable
335    /// storage for such batches.  The default is 10,048,576 (10 MiB).
336    pub min_storage_bytes: Option<usize>,
337
338    /// For a batch of data passed through the pipeline during a single step,
339    /// the minimum estimated number of bytes to write it to storage.
340    ///
341    /// This is provided for debugging and fine-tuning and should ordinarily be
342    /// left unset.  A value of 0 will write even empty batches to storage, and
343    /// nonzero values provide a threshold.  `usize::MAX`, the default,
344    /// effectively disables storage for such batches.  If it is set to another
345    /// value, it should ordinarily be greater than or equal to
346    /// `min_storage_bytes`.
347    pub min_step_storage_bytes: Option<usize>,
348
349    /// The form of compression to use in data batches.
350    ///
351    /// Compression has a CPU cost but it can take better advantage of limited
352    /// NVMe and network bandwidth, which means that it can increase overall
353    /// performance.
354    pub compression: StorageCompression,
355
356    /// The maximum size of the in-memory storage cache, in MiB.
357    ///
358    /// If set, the specified cache size is spread across all the foreground and
359    /// background threads. If unset, each foreground or background thread cache
360    /// is limited to 256 MiB.
361    pub cache_mib: Option<usize>,
362}
363
364/// Backend storage configuration.
365#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
366#[serde(tag = "name", content = "config", rename_all = "snake_case")]
367pub enum StorageBackendConfig {
368    /// Use the default storage configuration.
369    ///
370    /// This currently uses the local file system.
371    #[default]
372    Default,
373
374    /// Use the local file system.
375    ///
376    /// This uses ordinary system file operations.
377    File(Box<FileBackendConfig>),
378
379    /// Object storage.
380    Object(ObjectStorageConfig),
381}
382
383impl Display for StorageBackendConfig {
384    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
385        match self {
386            StorageBackendConfig::Default => write!(f, "default"),
387            StorageBackendConfig::File(_) => write!(f, "file"),
388            StorageBackendConfig::Object(_) => write!(f, "object"),
389        }
390    }
391}
392
393/// Storage compression algorithm.
394#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
395#[serde(rename_all = "snake_case")]
396pub enum StorageCompression {
397    /// Use Feldera's default compression algorithm.
398    ///
399    /// The default may change as Feldera's performance is tuned and new
400    /// algorithms are introduced.
401    #[default]
402    Default,
403
404    /// Do not compress.
405    None,
406
407    /// Use [Snappy](https://en.wikipedia.org/wiki/Snappy_(compression)) compression.
408    Snappy,
409}
410
411#[derive(Debug, Clone, Eq, PartialEq)]
412pub enum StartFromCheckpoint {
413    Latest,
414    Uuid(uuid::Uuid),
415}
416
417impl ToSchema<'_> for StartFromCheckpoint {
418    fn schema() -> (
419        &'static str,
420        utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
421    ) {
422        (
423            "StartFromCheckpoint",
424            utoipa::openapi::RefOr::T(Schema::OneOf(
425                OneOfBuilder::new()
426                    .item(
427                        ObjectBuilder::new()
428                            .schema_type(SchemaType::String)
429                            .enum_values(Some(["latest"].into_iter()))
430                            .build(),
431                    )
432                    .item(
433                        ObjectBuilder::new()
434                            .schema_type(SchemaType::String)
435                            .format(Some(utoipa::openapi::SchemaFormat::KnownFormat(
436                                utoipa::openapi::KnownFormat::Uuid,
437                            )))
438                            .build(),
439                    )
440                    .nullable(true)
441                    .build(),
442            )),
443        )
444    }
445}
446
447impl<'de> Deserialize<'de> for StartFromCheckpoint {
448    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
449    where
450        D: Deserializer<'de>,
451    {
452        struct StartFromCheckpointVisitor;
453
454        impl<'de> Visitor<'de> for StartFromCheckpointVisitor {
455            type Value = StartFromCheckpoint;
456
457            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
458                formatter.write_str("a UUID string or the string \"latest\"")
459            }
460
461            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
462            where
463                E: de::Error,
464            {
465                if value == "latest" {
466                    Ok(StartFromCheckpoint::Latest)
467                } else {
468                    uuid::Uuid::parse_str(value)
469                        .map(StartFromCheckpoint::Uuid)
470                        .map_err(|_| E::invalid_value(serde::de::Unexpected::Str(value), &self))
471                }
472            }
473        }
474
475        deserializer.deserialize_str(StartFromCheckpointVisitor)
476    }
477}
478
479impl Serialize for StartFromCheckpoint {
480    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
481    where
482        S: serde::Serializer,
483    {
484        match self {
485            StartFromCheckpoint::Latest => serializer.serialize_str("latest"),
486            StartFromCheckpoint::Uuid(uuid) => serializer.serialize_str(&uuid.to_string()),
487        }
488    }
489}
490
491#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
492pub struct SyncConfig {
493    /// The endpoint URL for the storage service.
494    ///
495    /// This is typically required for custom or local S3-compatible storage providers like MinIO.
496    /// Example: `http://localhost:9000`
497    ///
498    /// Relevant rclone config key: [`endpoint`](https://rclone.org/s3/#s3-endpoint)
499    pub endpoint: Option<String>,
500
501    /// The name of the storage bucket.
502    ///
503    /// This may include a path to a folder inside the bucket (e.g., `my-bucket/data`).
504    pub bucket: String,
505
506    /// The region that this bucket is in.
507    ///
508    /// Leave empty for Minio or the default region (`us-east-1` for AWS).
509    pub region: Option<String>,
510
511    /// The name of the cloud storage provider (e.g., `"AWS"`, `"Minio"`).
512    ///
513    /// Used for provider-specific behavior in rclone.
514    /// If omitted, defaults to `"Other"`.
515    ///
516    /// See [rclone S3 provider documentation](https://rclone.org/s3/#s3-provider)
517    pub provider: Option<String>,
518
519    /// The access key used to authenticate with the storage provider.
520    ///
521    /// If not provided, rclone will fall back to environment-based credentials, such as
522    /// `RCLONE_S3_ACCESS_KEY_ID`. In Kubernetes environments using IRSA (IAM Roles for Service Accounts),
523    /// this can be left empty to allow automatic authentication via the pod's service account.
524    pub access_key: Option<String>,
525
526    /// The secret key used together with the access key for authentication.
527    ///
528    /// If not provided, rclone will fall back to environment-based credentials, such as
529    /// `RCLONE_S3_SECRET_ACCESS_KEY`. In Kubernetes environments using IRSA (IAM Roles for Service Accounts),
530    /// this can be left empty to allow automatic authentication via the pod's service account.
531    pub secret_key: Option<String>,
532
533    /// When set, the pipeline will try fetch the specified checkpoint from the
534    /// object store.
535    ///
536    /// If `fail_if_no_checkpoint` is `true`, the pipeline will fail to initialize.
537    pub start_from_checkpoint: Option<StartFromCheckpoint>,
538
539    /// When true, the pipeline will fail to initialize if fetching the
540    /// specified checkpoint fails (missing, download error).
541    /// When false, the pipeline will start from scratch instead.
542    ///
543    /// False by default.
544    #[schema(default = std::primitive::bool::default)]
545    #[serde(default)]
546    pub fail_if_no_checkpoint: bool,
547
548    /// The number of file transfers to run in parallel.
549    /// Default: 20
550    pub transfers: Option<u8>,
551
552    /// The number of checkers to run in parallel.
553    /// Default: 20
554    pub checkers: Option<u8>,
555
556    /// Set to skip post copy check of checksums, and only check the file sizes.
557    /// This can significantly improve the throughput.
558    /// Defualt: false
559    pub ignore_checksum: Option<bool>,
560
561    /// Number of streams to use for multi-thread downloads.
562    /// Default: 10
563    pub multi_thread_streams: Option<u8>,
564
565    /// Use multi-thread download for files above this size.
566    /// Format: `[size][Suffix]` (Example: 1G, 500M)
567    /// Supported suffixes: k|M|G|T
568    /// Default: 100M
569    pub multi_thread_cutoff: Option<String>,
570
571    /// When true, checkpoint downloads use the maximum resources available on
572    /// the host: `transfers` and `checkers` are scaled to the number of CPUs,
573    /// and the download buffer is allowed to grow up to most of the available
574    /// memory. This maximizes download throughput at the cost of higher CPU and
575    /// memory usage during a pull.
576    ///
577    /// When false, downloads use the values configured via `transfers`,
578    /// `checkers`, and the rclone defaults instead.
579    ///
580    /// Default: true
581    #[schema(default = default_optimize_download_resources)]
582    #[serde(default = "default_optimize_download_resources")]
583    pub optimize_download_resources: bool,
584
585    /// The number of chunks of the same file that are uploaded for multipart uploads.
586    /// Default: 10
587    pub upload_concurrency: Option<u8>,
588
589    /// **Deprecated.** Use `initial=standby` when starting the pipeline instead.
590    #[deprecated(note = "Use `initial=standby` when starting the pipeline instead.")]
591    #[schema(default = std::primitive::bool::default)]
592    #[serde(default)]
593    pub standby: bool,
594
595    /// The interval (in seconds) between each attempt to fetch the latest
596    /// checkpoint from object store while in standby mode.
597    ///
598    /// Applies only when `start_from_checkpoint` is set to `latest`.
599    ///
600    /// Default: 10 seconds
601    #[schema(default = default_pull_interval)]
602    #[serde(default = "default_pull_interval")]
603    pub pull_interval: u64,
604
605    /// The interval (in seconds) between each push of checkpoints to object store.
606    ///
607    /// Default: disabled (no periodic push).
608    #[serde(default)]
609    pub push_interval: Option<u64>,
610
611    /// Extra flags to pass to `rclone`.
612    ///
613    /// WARNING: Supplying incorrect or conflicting flags can break `rclone`.
614    /// Use with caution.
615    ///
616    /// Refer to the docs to see the supported flags:
617    /// - [Global flags](https://rclone.org/flags/)
618    /// - [S3 specific flags](https://rclone.org/s3/)
619    pub flags: Option<Vec<String>>,
620
621    /// The minimum number of checkpoints to retain in object store.
622    /// No checkpoints will be deleted if the total count is below this threshold.
623    ///
624    /// Default: 10
625    #[schema(default = default_retention_min_count)]
626    #[serde(default = "default_retention_min_count")]
627    pub retention_min_count: u32,
628
629    /// The minimum age (in days) a checkpoint must reach before it becomes
630    /// eligible for deletion. All younger checkpoints will be preserved.
631    ///
632    /// Default: 30
633    #[schema(default = default_retention_min_age)]
634    #[serde(default = "default_retention_min_age")]
635    pub retention_min_age: u32,
636
637    /// A read-only bucket used as a fallback checkpoint source.
638    ///
639    /// When the pipeline has no local checkpoint and `bucket` contains no
640    /// checkpoint either, it will attempt to fetch the checkpoint from this
641    /// location instead.  All connection settings (`endpoint`, `region`,
642    /// `provider`, `access_key`, `secret_key`) are shared with `bucket`.
643    ///
644    /// The pipeline **never writes** to `read_bucket`.
645    ///
646    /// Must point to a different location than `bucket`.
647    #[serde(default)]
648    pub read_bucket: Option<String>,
649
650    /// Take ownership of `bucket` when the pipeline starts, even if another
651    /// pipeline owns it.
652    ///
653    /// A pipeline records its ownership of `bucket` in an `owner.json` file
654    /// at the root of `bucket`, and a push fails without writing anything if
655    /// that file names a different pipeline.  When this is `true`, the
656    /// pipeline takes ownership as it starts (a standby pipeline, when it is
657    /// activated): it logs a warning naming the previous and new owners and
658    /// overwrites `owner.json`.  The previous owner's later pushes to
659    /// `bucket` then fail.
660    ///
661    /// This only applies at startup.  If another pipeline takes ownership of
662    /// `bucket` while this pipeline is running, this pipeline's pushes fail.
663    ///
664    /// Ownership changes before the pipeline opens its checkpoint, so it
665    /// sticks even if the pipeline then fails to start: the previous owner's
666    /// pushes keep failing.  To give `bucket` back, start the previous owner
667    /// with `take_bucket_ownership` set.
668    ///
669    /// Use this to hand a checkpoint location over to a pipeline that
670    /// replaces another one, e.g., after deleting and recreating a pipeline.
671    /// Stop the previous owner first, and set this on only one of the
672    /// pipelines that share a `bucket`.
673    ///
674    /// Default: false
675    #[schema(default = std::primitive::bool::default)]
676    #[serde(default)]
677    pub take_bucket_ownership: bool,
678}
679
680fn default_pull_interval() -> u64 {
681    10
682}
683
684fn default_retention_min_count() -> u32 {
685    10
686}
687
688fn default_retention_min_age() -> u32 {
689    30
690}
691
692fn default_optimize_download_resources() -> bool {
693    true
694}
695
696impl SyncConfig {
697    pub fn validate(&self) -> Result<(), String> {
698        #[allow(deprecated)]
699        if self.standby {
700            return Err(
701                "The `standby` config field has been deprecated. Use `initial=standby` when starting the pipeline instead.".to_owned()
702            );
703        }
704
705        if let Some(ref rb) = self.read_bucket
706            && rb == &self.bucket
707        {
708            return Err(
709                "invalid sync config: `read_bucket` and `bucket` must point to different locations"
710                    .to_owned(),
711            );
712        }
713
714        Ok(())
715    }
716}
717
718/// Configuration for supplying a custom pipeline StatefulSet template via a Kubernetes ConfigMap.
719///
720/// Operators can provide a custom StatefulSet YAML that the Kubernetes runner will use when
721/// creating pipeline StatefulSets for a pipeline. The custom template must be stored as the
722/// value of a key in a ConfigMap in the same namespace as the pipeline; set `name` to the
723/// ConfigMap name and `key` to the entry that contains the template.
724///
725/// Recommendations and requirements:
726/// - **Start from the default template and modify it as needed.** The default template is present
727///   in ConfigMap named as `<release-name>-pipeline-template`, with key `pipelineTemplate` in the release
728///   namespace and should be used as a reference.
729/// - The template must contain a valid Kubernetes `StatefulSet` manifest in YAML form. The
730///   runner substitutes variables in the template before parsing; therefore the final YAML
731///   must be syntactically valid.
732/// - The runner performs simple string substitution for the following placeholders. Please ensure these
733///   placeholders are placed at appropriate location for their semantics:
734///   - `{id}`: pipeline Kubernetes name (used for object names and labels)
735///   - `{namespace}`: Kubernetes namespace where the pipeline runs
736///   - `{pipeline_executor_image}`: container image used to run the pipeline executor
737///   - `{binary_ref}`: program binary reference passed as an argument
738///   - `{program_info_ref}`: program info reference passed as an argument
739///   - `{pipeline_storage_path}`: mount path for persistent pipeline storage
740///   - `{storage_class_name}`: storage class name to use for PVCs (if applicable)
741///   - `{deployment_id}`: UUID identifying the deployment instance
742///   - `{deployment_initial}`: initial desired runtime status (e.g., `provisioning`)
743///   - `{bootstrap_policy}`: bootstrap policy value when applicable
744#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
745pub struct PipelineTemplateConfig {
746    /// Name of the ConfigMap containing the pipeline template.
747    pub name: String,
748    /// Key in the ConfigMap containing the pipeline template.
749    ///
750    /// If not set, defaults to `pipelineTemplate`.
751    #[schema(default = default_pipeline_template_key)]
752    #[serde(default = "default_pipeline_template_key")]
753    pub key: String,
754}
755
756fn default_pipeline_template_key() -> String {
757    "pipelineTemplate".to_string()
758}
759
760#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
761pub struct ObjectStorageConfig {
762    /// URL.
763    ///
764    /// The following URL schemes are supported:
765    ///
766    /// * S3:
767    ///   - `s3://<bucket>/<path>`
768    ///   - `s3a://<bucket>/<path>`
769    ///   - `https://s3.<region>.amazonaws.com/<bucket>`
770    ///   - `https://<bucket>.s3.<region>.amazonaws.com`
771    ///   - `https://ACCOUNT_ID.r2.cloudflarestorage.com/bucket`
772    /// * Google Cloud Storage:
773    ///   - `gs://<bucket>/<path>`
774    /// * Microsoft Azure Blob Storage:
775    ///   - `abfs[s]://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
776    ///   - `abfs[s]://<file_system>@<account_name>.dfs.core.windows.net/<path>`
777    ///   - `abfs[s]://<file_system>@<account_name>.dfs.fabric.microsoft.com/<path>`
778    ///   - `az://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
779    ///   - `adl://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
780    ///   - `azure://<container>/<path>` (custom)
781    ///   - `https://<account>.dfs.core.windows.net`
782    ///   - `https://<account>.blob.core.windows.net`
783    ///   - `https://<account>.blob.core.windows.net/<container>`
784    ///   - `https://<account>.dfs.fabric.microsoft.com`
785    ///   - `https://<account>.dfs.fabric.microsoft.com/<container>`
786    ///   - `https://<account>.blob.fabric.microsoft.com`
787    ///   - `https://<account>.blob.fabric.microsoft.com/<container>`
788    ///
789    /// Settings derived from the URL will override other settings.
790    pub url: String,
791
792    /// Additional options as key-value pairs.
793    ///
794    /// The following keys are supported:
795    ///
796    /// * S3:
797    ///   - `access_key_id`: AWS Access Key.
798    ///   - `secret_access_key`: AWS Secret Access Key.
799    ///   - `region`: Region.
800    ///   - `default_region`: Default region.
801    ///   - `endpoint`: Custom endpoint for communicating with S3,
802    ///     e.g. `https://localhost:4566` for testing against a localstack
803    ///     instance.
804    ///   - `token`: Token to use for requests (passed to underlying provider).
805    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/aws/enum.AmazonS3ConfigKey.html#variants).
806    /// * Google Cloud Storage:
807    ///   - `service_account`: Path to the service account file.
808    ///   - `service_account_key`: The serialized service account key.
809    ///   - `google_application_credentials`: Application credentials path.
810    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/gcp/enum.GoogleConfigKey.html).
811    /// * Microsoft Azure Blob Storage:
812    ///   - `access_key`: Azure Access Key.
813    ///   - `container_name`: Azure Container Name.
814    ///   - `account`: Azure Account.
815    ///   - `bearer_token_authorization`: Static bearer token for authorizing requests.
816    ///   - `client_id`: Client ID for use in client secret or Kubernetes federated credential flow.
817    ///   - `client_secret`: Client secret for use in client secret flow.
818    ///   - `tenant_id`: Tenant ID for use in client secret or Kubernetes federated credential flow.
819    ///   - `endpoint`: Override the endpoint for communicating with blob storage.
820    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/azure/enum.AzureConfigKey.html#variants).
821    ///
822    /// Options set through the URL take precedence over those set with these
823    /// options.
824    #[serde(flatten)]
825    pub other_options: BTreeMap<String, String>,
826}
827
828/// Configuration for local file system access.
829#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
830#[serde(default)]
831pub struct FileBackendConfig {
832    /// Whether to use background threads for file I/O.
833    ///
834    /// Background threads should improve performance, but they can reduce
835    /// performance if too few cores are available. This is provided for
836    /// debugging and fine-tuning and should ordinarily be left unset.
837    pub async_threads: Option<bool>,
838
839    /// Per-I/O operation sleep duration, in milliseconds.
840    ///
841    /// This is for simulating slow storage devices.  Do not use this in
842    /// production.
843    pub ioop_delay: Option<u64>,
844
845    /// Configuration to synchronize checkpoints to object store.
846    pub sync: Option<SyncConfig>,
847}
848
849/// Global pipeline configuration settings. This is the publicly
850/// exposed type for users to configure pipelines.
851#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
852#[serde(default)]
853pub struct RuntimeConfig {
854    /// Number of DBSP worker threads.
855    ///
856    /// Each DBSP "foreground" worker thread is paired with a "background"
857    /// thread for LSM merging, making the total number of threads twice the
858    /// specified number.
859    ///
860    /// The typical sweet spot for the number of workers is between 4 and 16.
861    /// Each worker increases overall memory consumption for data structures
862    /// used during a step.
863    pub workers: u16,
864
865    /// The maximum amount of memory, in Megabytes, that the pipeline is allowed to use
866    /// on each host.
867    ///
868    /// Setting this property activates memory pressure monitoring and backpressure
869    /// mechanisms. The pipeline will track the amount of remaining memory and
870    /// report the memory pressure level via the `memory_pressure` metric.
871    ///
872    /// As the memory pressure increases, the system will apply increasing backpressure
873    /// to push state cached in memory to storage, preventing the pipeline from running
874    /// out of memory at the cost of some performance degradation.
875    ///
876    /// It is strongly recommended to set this property to prevent the pipeline from
877    /// running out of memory. The setting should not exceed the memory limit of the pipeline
878    /// instance.
879    ///
880    /// When `max_rss_mb` is not specified but `resources.memory_mb_max` is set, the
881    /// latter is used as the effective memory cap for the pipeline.
882    ///
883    /// See [documentation on the pipeline's memory usage](https://docs.feldera.com/operations/memory)
884    /// for more details.
885    pub max_rss_mb: Option<u64>,
886
887    /// DataFusion memory pool size, in MB, shared by the ad-hoc query
888    /// engine and the Delta Lake / Iceberg connectors.
889    ///
890    /// Carved out of `max_rss_mb` (falling back to
891    /// `resources.memory_mb_max`); the remainder goes to the DBSP circuit,
892    /// so the two do not double-book RAM.
893    ///
894    /// Unset: defaults to 5% of the effective budget, capped at 2 GB.
895    /// Pipelines that don't run heavy ad-hoc / Delta / Iceberg workloads
896    /// can leave this unset.
897    ///
898    /// Sort/aggregate-heavy ad-hoc queries (especially at high `workers`
899    /// counts) should set this explicitly. An under-sized pool surfaces as
900    /// `ResourcesExhausted` on the failing query — the pipeline keeps
901    /// running and only that query fails.
902    ///
903    /// No pool limit applied if no overall budget is configured.
904    ///
905    /// See [documentation on the pipeline's memory usage](https://docs.feldera.com/operations/memory)
906    /// for more details.
907    pub datafusion_memory_mb: Option<u64>,
908
909    /// Number of DBSP hosts.
910    ///
911    /// The worker threads are evenly divided among the hosts.  For single-host
912    /// deployments, this should be 1 (the default).
913    ///
914    /// Multihost pipelines are an enterprise-only preview feature.
915    pub hosts: usize,
916
917    /// Storage configuration.
918    ///
919    /// - If this is `None`, the default, the pipeline's state is kept in
920    ///   in-memory data-structures.  This is useful if the pipeline's state
921    ///   will fit in memory and if the pipeline is ephemeral and does not need
922    ///   to be recovered after a restart. The pipeline will most likely run
923    ///   faster since it does not need to access storage.
924    ///
925    /// - If set, the pipeline's state is kept on storage.  This allows the
926    ///   pipeline to work with state that will not fit into memory. It also
927    ///   allows the state to be checkpointed and recovered across restarts.
928    #[serde(deserialize_with = "deserialize_storage_options")]
929    pub storage: Option<StorageOptions>,
930
931    /// Fault tolerance configuration.
932    #[serde(deserialize_with = "deserialize_fault_tolerance")]
933    pub fault_tolerance: FtConfig,
934
935    /// Enable CPU profiler.
936    ///
937    /// The default value is `true`.
938    pub cpu_profiler: bool,
939
940    /// Enable pipeline tracing.
941    pub tracing: bool,
942
943    /// Jaeger tracing endpoint to send tracing information to.
944    pub tracing_endpoint_jaeger: String,
945
946    /// Minimal input batch size.
947    ///
948    /// The controller delays pushing input records to the circuit until at
949    /// least `min_batch_size_records` records have been received (total
950    /// across all endpoints) or `max_buffering_delay_usecs` microseconds
951    /// have passed since at least one input records has been buffered.
952    /// Defaults to 0.
953    pub min_batch_size_records: u64,
954
955    /// Maximal delay in microseconds to wait for `min_batch_size_records` to
956    /// get buffered by the controller, defaults to 0.
957    pub max_buffering_delay_usecs: u64,
958
959    /// Resource reservations and limits. This is enforced
960    /// only in Feldera Cloud.
961    pub resources: ResourceConfig,
962
963    /// Real-time clock resolution in microseconds.
964    ///
965    /// This parameter controls the execution of queries that use the `NOW()` function.  The output of such
966    /// queries depends on the real-time clock and can change over time without any external
967    /// inputs.  If the query uses `NOW()`, the pipeline will update the clock value and trigger incremental
968    /// recomputation at most each `clock_resolution_usecs` microseconds.  If the query does not use
969    /// `NOW()`, then clock value updates are suppressed and the pipeline ignores this setting.
970    ///
971    /// It is set to 1 second (1,000,000 microseconds) by default.
972    pub clock_resolution_usecs: Option<u64>,
973
974    /// Fixed timezone offset for the SQL `NOW()` clock.
975    ///
976    /// An ISO-8601 UTC offset, for example `"+05:30"` or `"-08:00"`, that the
977    /// clock connector adds to every `NOW()` value it emits, so `NOW()`
978    /// returns local time in that fixed timezone instead of UTC.
979    ///
980    /// The offset is baked into the pipeline's checkpointed state and cannot
981    /// be changed when the pipeline resumes from a checkpoint: the value from
982    /// the checkpoint stays in effect, and a differing new value is ignored
983    /// with a warning in the pipeline log.
984    #[schema(value_type = Option<String>, example = "+05:30")]
985    pub clock_timezone_offset: Option<ClockTimezoneOffset>,
986
987    /// Optionally, a list of CPU numbers for CPUs to which the pipeline may pin
988    /// its worker threads.  Specify at least twice as many CPU numbers as
989    /// workers.  CPUs are generally numbered starting from 0.  The pipeline
990    /// might not be able to honor CPU pinning requests.
991    ///
992    /// CPU pinning can make pipelines run faster and perform more consistently,
993    /// as long as different pipelines running on the same machine are pinned to
994    /// different CPUs.
995    pub pin_cpus: Vec<usize>,
996
997    /// Timeout in seconds for the `Provisioning` phase of the pipeline.
998    /// Setting this value will override the default of the runner.
999    pub provisioning_timeout_secs: Option<u64>,
1000
1001    /// The maximum number of connectors initialized in parallel during pipeline
1002    /// startup.
1003    ///
1004    /// At startup, the pipeline must initialize all of its input and output connectors.
1005    /// Depending on the number and types of connectors, this can take a long time.
1006    /// To accelerate the process, multiple connectors are initialized concurrently.
1007    /// This option controls the maximum number of connectors that can be initialized
1008    /// in parallel.
1009    ///
1010    /// The default is 10.
1011    pub max_parallel_connector_init: Option<u64>,
1012
1013    /// Specification of additional (sidecar) containers.
1014    pub init_containers: Option<serde_json::Value>,
1015
1016    /// Deprecated: setting this true or false does not have an effect anymore.
1017    pub checkpoint_during_suspend: bool,
1018
1019    /// Sets the number of available runtime threads for the http server.
1020    ///
1021    /// In most cases, this does not need to be set explicitly and
1022    /// the default is sufficient. Can be increased in case the
1023    /// pipeline HTTP API operations are a bottleneck.
1024    ///
1025    /// If not specified, the default is set to `workers`.
1026    pub http_workers: Option<u64>,
1027
1028    /// Sets the number of available runtime threads for async IO tasks.
1029    ///
1030    /// This affects some networking and file I/O operations
1031    /// especially adapters and ad-hoc queries.
1032    ///
1033    /// In most cases, this does not need to be set explicitly and
1034    /// the default is sufficient. Can be increased in case
1035    /// ingress, egress or ad-hoc queries are a bottleneck.
1036    ///
1037    /// If not specified, the default is set to `workers`.
1038    pub io_workers: Option<u64>,
1039
1040    /// Environment variables for the pipeline process.
1041    ///
1042    /// These are key-value pairs injected into the pipeline process environment.
1043    /// Some variable names are reserved by the platform and cannot be overridden
1044    /// (for example `RUST_LOG`, and variables in the `FELDERA_`,
1045    /// `KUBERNETES_`, and `TOKIO_` namespaces).
1046    #[serde(default)]
1047    pub env: BTreeMap<String, String>,
1048
1049    /// Optional settings for tweaking Feldera internals.
1050    pub dev_tweaks: DevTweaks,
1051
1052    /// Log filtering directives.
1053    ///
1054    /// If set to a valid [tracing-subscriber] filter, this controls the log
1055    /// messages emitted by the pipeline process.  Otherwise, or if the filter
1056    /// has invalid syntax, messages at "info" severity and higher are written
1057    /// to the log and all others are discarded.
1058    ///
1059    /// [tracing-subscriber]: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#directives
1060    pub logging: Option<String>,
1061
1062    /// ConfigMap containing a custom pipeline template (Enterprise only).
1063    ///
1064    /// This feature is only available in Feldera Enterprise. If set, the Kubernetes runner
1065    /// will read the template from the specified ConfigMap and use it instead of the default
1066    /// StatefulSet template for the configured pipeline.
1067    ///
1068    /// check [`PipelineTemplateConfig`] documentation for details.
1069    pub pipeline_template_configmap: Option<PipelineTemplateConfig>,
1070}
1071
1072/// Accepts "true" and "false" and converts them to the new format.
1073fn deserialize_storage_options<'de, D>(deserializer: D) -> Result<Option<StorageOptions>, D::Error>
1074where
1075    D: Deserializer<'de>,
1076{
1077    struct BoolOrStruct;
1078
1079    impl<'de> Visitor<'de> for BoolOrStruct {
1080        type Value = Option<StorageOptions>;
1081
1082        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1083            formatter.write_str("boolean or StorageOptions")
1084        }
1085
1086        fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
1087        where
1088            E: de::Error,
1089        {
1090            match v {
1091                false => Ok(None),
1092                true => Ok(Some(StorageOptions::default())),
1093            }
1094        }
1095
1096        fn visit_unit<E>(self) -> Result<Self::Value, E>
1097        where
1098            E: de::Error,
1099        {
1100            Ok(None)
1101        }
1102
1103        fn visit_none<E>(self) -> Result<Self::Value, E>
1104        where
1105            E: de::Error,
1106        {
1107            Ok(None)
1108        }
1109
1110        fn visit_map<M>(self, map: M) -> Result<Option<StorageOptions>, M::Error>
1111        where
1112            M: MapAccess<'de>,
1113        {
1114            Deserialize::deserialize(de::value::MapAccessDeserializer::new(map)).map(Some)
1115        }
1116    }
1117
1118    deserializer.deserialize_any(BoolOrStruct)
1119}
1120
1121/// Accepts very old 'initial_state' and 'latest_checkpoint' as enabling fault
1122/// tolerance.
1123///
1124/// Accepts `null` as disabling fault tolerance.
1125///
1126/// Otherwise, deserializes [FtConfig] in the way that one might otherwise
1127/// expect.
1128fn deserialize_fault_tolerance<'de, D>(deserializer: D) -> Result<FtConfig, D::Error>
1129where
1130    D: Deserializer<'de>,
1131{
1132    struct StringOrStruct;
1133
1134    impl<'de> Visitor<'de> for StringOrStruct {
1135        type Value = FtConfig;
1136
1137        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1138            formatter.write_str("none or FtConfig or 'initial_state' or 'latest_checkpoint'")
1139        }
1140
1141        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1142        where
1143            E: de::Error,
1144        {
1145            match v {
1146                "initial_state" | "latest_checkpoint" => Ok(FtConfig {
1147                    model: Some(FtModel::default()),
1148                    ..FtConfig::default()
1149                }),
1150                _ => Err(de::Error::invalid_value(de::Unexpected::Str(v), &self)),
1151            }
1152        }
1153
1154        fn visit_unit<E>(self) -> Result<Self::Value, E>
1155        where
1156            E: de::Error,
1157        {
1158            Ok(FtConfig::default())
1159        }
1160
1161        fn visit_none<E>(self) -> Result<Self::Value, E>
1162        where
1163            E: de::Error,
1164        {
1165            Ok(FtConfig::default())
1166        }
1167
1168        fn visit_map<M>(self, map: M) -> Result<FtConfig, M::Error>
1169        where
1170            M: MapAccess<'de>,
1171        {
1172            Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))
1173        }
1174    }
1175
1176    deserializer.deserialize_any(StringOrStruct)
1177}
1178
1179impl Default for RuntimeConfig {
1180    fn default() -> Self {
1181        Self {
1182            workers: 8,
1183            max_rss_mb: None,
1184            datafusion_memory_mb: None,
1185            hosts: 1,
1186            storage: Some(StorageOptions::default()),
1187            fault_tolerance: FtConfig::default(),
1188            cpu_profiler: true,
1189            tracing: {
1190                // We discovered that the jaeger crate can use up gigabytes of RAM, so it's not harmless
1191                // to keep it on by default.
1192                false
1193            },
1194            tracing_endpoint_jaeger: "127.0.0.1:6831".to_string(),
1195            min_batch_size_records: 0,
1196            max_buffering_delay_usecs: 0,
1197            resources: ResourceConfig::default(),
1198            clock_resolution_usecs: { Some(DEFAULT_CLOCK_RESOLUTION_USECS) },
1199            clock_timezone_offset: None,
1200            pin_cpus: Vec::new(),
1201            provisioning_timeout_secs: None,
1202            max_parallel_connector_init: None,
1203            init_containers: None,
1204            checkpoint_during_suspend: true,
1205            io_workers: None,
1206            http_workers: None,
1207            env: BTreeMap::default(),
1208            dev_tweaks: DevTweaks::default(),
1209            logging: None,
1210            pipeline_template_configmap: None,
1211        }
1212    }
1213}
1214
1215/// Upper bound on the default DataFusion pool size, in MB.
1216///
1217/// Spill-to-disk handles overflow; reserving more starves the circuit.
1218pub const DEFAULT_DATAFUSION_MEMORY_MB_CEILING: u64 = 2048;
1219
1220/// Default DataFusion pool size as a percentage of the pipeline's
1221/// effective memory budget. The remainder is left for the DBSP circuit.
1222pub const DEFAULT_DATAFUSION_MEMORY_PERCENT: u64 = 5;
1223
1224impl RuntimeConfig {
1225    /// Pipeline's effective memory budget in MB: `max_rss_mb`, falling back
1226    /// to `resources.memory_mb_max` (the k8s pod limit).
1227    pub fn effective_memory_mb(&self) -> Option<u64> {
1228        self.max_rss_mb.or(self.resources.memory_mb_max)
1229    }
1230
1231    /// Resolved DataFusion pool size in MB: explicit `datafusion_memory_mb`
1232    /// if set, else 5% of the effective budget capped at
1233    /// `DEFAULT_DATAFUSION_MEMORY_MB_CEILING`. `None` if no budget is
1234    /// configured.
1235    pub fn resolved_datafusion_memory_mb(&self) -> Option<u64> {
1236        if let Some(explicit) = self.datafusion_memory_mb {
1237            return Some(explicit);
1238        }
1239        let effective = self.effective_memory_mb()?;
1240        let fraction = effective * DEFAULT_DATAFUSION_MEMORY_PERCENT / 100;
1241        Some(fraction.min(DEFAULT_DATAFUSION_MEMORY_MB_CEILING))
1242    }
1243}
1244
1245/// Fault-tolerance configuration.
1246///
1247/// The default [FtConfig] (via [FtConfig::default]) disables fault tolerance,
1248/// which is the configuration that one gets if [RuntimeConfig] omits fault
1249/// tolerance configuration.
1250///
1251/// The default value for [FtConfig::model] enables fault tolerance, as
1252/// `Some(FtModel::default())`.  This is the configuration that one gets if
1253/// [RuntimeConfig] includes a fault tolerance configuration but does not
1254/// specify a particular model.
1255#[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1256#[serde(rename_all = "snake_case")]
1257pub struct FtConfig {
1258    /// Fault tolerance model to use.
1259    #[serde(with = "none_as_string")]
1260    #[serde(default = "default_model")]
1261    #[schema(
1262        schema_with = none_as_string_schema::<FtModel>,
1263    )]
1264    pub model: Option<FtModel>,
1265
1266    /// Interval between automatic checkpoints, in seconds.
1267    ///
1268    /// The default is 60 seconds.  Values less than 1 or greater than 3600 will
1269    /// be forced into that range.
1270    #[serde(default = "default_checkpoint_interval_secs")]
1271    pub checkpoint_interval_secs: Option<u64>,
1272}
1273
1274fn default_model() -> Option<FtModel> {
1275    Some(FtModel::default())
1276}
1277
1278pub fn default_checkpoint_interval_secs() -> Option<u64> {
1279    Some(60)
1280}
1281
1282impl Default for FtConfig {
1283    fn default() -> Self {
1284        Self {
1285            model: None,
1286            checkpoint_interval_secs: default_checkpoint_interval_secs(),
1287        }
1288    }
1289}
1290
1291#[cfg(test)]
1292mod test {
1293    use super::deserialize_fault_tolerance;
1294    use crate::config::{
1295        ConnectorConfig, DEFAULT_DATAFUSION_MEMORY_MB_CEILING, FtConfig, FtModel, PipelineConfig,
1296        ResourceConfig, RuntimeConfig, TransportConfig,
1297    };
1298    use serde::{Deserialize, Serialize};
1299    use serde_json::json;
1300
1301    /// A configuration written by an older version of Feldera carries no
1302    /// `soft_delete` field, and a connector that does not use soft deletes
1303    /// serializes exactly as it did before the field existed.  This keeps
1304    /// configurations readable and writable across versions.
1305    #[test]
1306    fn soft_delete_is_backward_compatible() {
1307        let config: ConnectorConfig = serde_json::from_value(json!({
1308            "transport": {"name": "empty_input"}
1309        }))
1310        .unwrap();
1311        assert!(!config.soft_delete);
1312
1313        let serialized = serde_json::to_value(&config).unwrap();
1314        assert_eq!(serialized.get("soft_delete"), None);
1315
1316        let config: ConnectorConfig = serde_json::from_value(json!({
1317            "transport": {"name": "empty_input"},
1318            "soft_delete": true
1319        }))
1320        .unwrap();
1321        assert!(config.soft_delete);
1322        assert_eq!(
1323            serde_json::to_value(&config).unwrap().get("soft_delete"),
1324            Some(&json!(true))
1325        );
1326    }
1327
1328    /// Soft deletes change how input is interpreted, so flipping the flag must
1329    /// count as a connector change even where flow-control settings do not.
1330    #[test]
1331    fn soft_delete_invalidates_checkpointed_connector_state() {
1332        let config = ConnectorConfig::new(TransportConfig::EmptyInput, None);
1333        let mut soft_delete = config.clone();
1334        soft_delete.soft_delete = true;
1335
1336        assert!(config.equal_for_input_checkpoint_replay(&config));
1337        assert!(!config.equal_for_input_checkpoint_replay(&soft_delete));
1338    }
1339
1340    fn config_with_name(name: Option<&str>) -> PipelineConfig {
1341        PipelineConfig {
1342            global: RuntimeConfig::default(),
1343            multihost: None,
1344            name: name.map(str::to_string),
1345            given_name: None,
1346            storage_config: None,
1347            secrets_dir: None,
1348            inputs: Default::default(),
1349            outputs: Default::default(),
1350            program_ir: None,
1351        }
1352    }
1353
1354    #[test]
1355    fn pipeline_identity_uses_system_and_given_names() {
1356        let mut config = config_with_name(Some("pipeline-018f6f57-4e15-7438-91af-3fd21ff2a8d3"));
1357        config.given_name = Some("my-pipeline".to_string());
1358
1359        let metadata = config.pipeline_identity().unwrap();
1360        assert_eq!(
1361            metadata.name,
1362            "pipeline-018f6f57-4e15-7438-91af-3fd21ff2a8d3"
1363        );
1364        assert_eq!(metadata.given_name.as_deref(), Some("my-pipeline"));
1365    }
1366
1367    #[test]
1368    fn pipeline_identity_is_none_without_system_name() {
1369        assert_eq!(config_with_name(None).pipeline_identity(), None);
1370    }
1371
1372    #[test]
1373    fn resolved_datafusion_memory_explicit_passes_through() {
1374        let config = RuntimeConfig {
1375            max_rss_mb: Some(8_000),
1376            datafusion_memory_mb: Some(1_500),
1377            ..Default::default()
1378        };
1379        assert_eq!(config.resolved_datafusion_memory_mb(), Some(1_500));
1380    }
1381
1382    #[test]
1383    fn resolved_datafusion_memory_unconfigured_returns_none() {
1384        let config = RuntimeConfig::default();
1385        assert!(config.max_rss_mb.is_none());
1386        assert!(config.resources.memory_mb_max.is_none());
1387        assert_eq!(config.resolved_datafusion_memory_mb(), None);
1388    }
1389
1390    #[test]
1391    fn resolved_datafusion_memory_small_budget_scales_down() {
1392        // Small pipelines must provision cleanly; the default just shrinks.
1393        let config = RuntimeConfig {
1394            max_rss_mb: Some(256),
1395            ..Default::default()
1396        };
1397        assert_eq!(config.resolved_datafusion_memory_mb(), Some(12));
1398
1399        let config = RuntimeConfig {
1400            max_rss_mb: Some(512),
1401            ..Default::default()
1402        };
1403        assert_eq!(config.resolved_datafusion_memory_mb(), Some(25));
1404    }
1405
1406    #[test]
1407    fn resolved_datafusion_memory_clamps_to_ceiling_for_large_budgets() {
1408        // 5% of 64 GB = 3.2 GB, above the 2 GB ceiling.
1409        let config = RuntimeConfig {
1410            max_rss_mb: Some(64_000),
1411            ..Default::default()
1412        };
1413        assert_eq!(
1414            config.resolved_datafusion_memory_mb(),
1415            Some(DEFAULT_DATAFUSION_MEMORY_MB_CEILING),
1416        );
1417    }
1418
1419    #[test]
1420    fn resolved_datafusion_memory_midrange_uses_five_percent() {
1421        // 5% of 16 GB = 800 MB, inside the clamp range.
1422        let config = RuntimeConfig {
1423            max_rss_mb: Some(16_000),
1424            ..Default::default()
1425        };
1426        assert_eq!(config.resolved_datafusion_memory_mb(), Some(800));
1427    }
1428
1429    #[test]
1430    fn resolved_datafusion_memory_falls_back_to_resources() {
1431        // No max_rss_mb, but resources.memory_mb_max is set.
1432        let config = RuntimeConfig {
1433            max_rss_mb: None,
1434            resources: ResourceConfig {
1435                memory_mb_max: Some(16_000),
1436                ..Default::default()
1437            },
1438            ..Default::default()
1439        };
1440        assert_eq!(config.resolved_datafusion_memory_mb(), Some(800));
1441    }
1442
1443    #[test]
1444    fn ft_config() {
1445        #[derive(Serialize, Deserialize, Default, PartialEq, Eq, Debug)]
1446        #[serde(default)]
1447        struct Wrapper {
1448            #[serde(deserialize_with = "deserialize_fault_tolerance")]
1449            config: FtConfig,
1450        }
1451
1452        // Omitting FtConfig, or specifying null, or specifying model "none", disables fault tolerance.
1453        for s in [
1454            "{}",
1455            r#"{"config": null}"#,
1456            r#"{"config": {"model": "none"}}"#,
1457        ] {
1458            let config: Wrapper = serde_json::from_str(s).unwrap();
1459            assert_eq!(
1460                config,
1461                Wrapper {
1462                    config: FtConfig {
1463                        model: None,
1464                        checkpoint_interval_secs: Some(60)
1465                    }
1466                }
1467            );
1468        }
1469
1470        // Serializing disabled FT produces explicit "none" form.
1471        let s = serde_json::to_string(&Wrapper {
1472            config: FtConfig::default(),
1473        })
1474        .unwrap();
1475        assert!(s.contains("\"none\""));
1476
1477        // `{}` for FtConfig, or `{...}` with `model` omitted, enables fault
1478        // tolerance.
1479        for s in [r#"{"config": {}}"#, r#"{"checkpoint_interval_secs": 60}"#] {
1480            assert_eq!(
1481                serde_json::from_str::<FtConfig>(s).unwrap(),
1482                FtConfig {
1483                    model: Some(FtModel::default()),
1484                    checkpoint_interval_secs: Some(60)
1485                }
1486            );
1487        }
1488
1489        // `"checkpoint_interval_secs": null` disables periodic checkpointing.
1490        assert_eq!(
1491            serde_json::from_str::<FtConfig>(r#"{"checkpoint_interval_secs": null}"#).unwrap(),
1492            FtConfig {
1493                model: Some(FtModel::default()),
1494                checkpoint_interval_secs: None
1495            }
1496        );
1497    }
1498}
1499
1500impl FtConfig {
1501    pub fn is_enabled(&self) -> bool {
1502        self.model.is_some()
1503    }
1504
1505    /// Returns the checkpoint interval, if fault tolerance is enabled, and
1506    /// otherwise `None`.
1507    pub fn checkpoint_interval(&self) -> Option<Duration> {
1508        if self.is_enabled() {
1509            self.checkpoint_interval_secs
1510                .map(|interval| Duration::from_secs(interval.clamp(1, 3600)))
1511        } else {
1512            None
1513        }
1514    }
1515}
1516
1517/// Serde implementation for de/serializing a string into `Option<T>` where
1518/// `"none"` indicates `None` and any other string indicates `Some`.
1519///
1520/// This could be extended to handle non-strings by adding more forwarding
1521/// `visit_*` methods to the Visitor implementation.  I don't see a way to write
1522/// them automatically.
1523mod none_as_string {
1524    use std::marker::PhantomData;
1525
1526    use serde::de::{Deserialize, Deserializer, IntoDeserializer, Visitor};
1527    use serde::ser::{Serialize, Serializer};
1528
1529    pub(super) fn serialize<S, T>(value: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
1530    where
1531        S: Serializer,
1532        T: Serialize,
1533    {
1534        match value.as_ref() {
1535            Some(value) => value.serialize(serializer),
1536            None => "none".serialize(serializer),
1537        }
1538    }
1539
1540    struct NoneAsString<T>(PhantomData<fn() -> T>);
1541
1542    impl<'de, T> Visitor<'de> for NoneAsString<T>
1543    where
1544        T: Deserialize<'de>,
1545    {
1546        type Value = Option<T>;
1547
1548        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
1549            formatter.write_str("string")
1550        }
1551
1552        fn visit_none<E>(self) -> Result<Self::Value, E>
1553        where
1554            E: serde::de::Error,
1555        {
1556            Ok(None)
1557        }
1558
1559        fn visit_str<E>(self, value: &str) -> Result<Option<T>, E>
1560        where
1561            E: serde::de::Error,
1562        {
1563            if &value.to_ascii_lowercase() == "none" {
1564                Ok(None)
1565            } else {
1566                Ok(Some(T::deserialize(value.into_deserializer())?))
1567            }
1568        }
1569    }
1570
1571    pub(super) fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
1572    where
1573        D: Deserializer<'de>,
1574        T: Deserialize<'de>,
1575    {
1576        deserializer.deserialize_str(NoneAsString(PhantomData))
1577    }
1578}
1579
1580/// Generates an OpenAPI schema for an `Option<T>` field serialized with `none_as_string`.
1581/// The schema is a `oneOf` with a reference to `T`'s schema and a `"none"` string enum.
1582fn none_as_string_schema<'a, T: ToSchema<'a> + Default + Serialize>() -> Schema {
1583    Schema::OneOf(
1584        OneOfBuilder::new()
1585            .item(RefOr::Ref(Ref::new(format!(
1586                "#/components/schemas/{}",
1587                T::schema().0
1588            ))))
1589            .item(
1590                ObjectBuilder::new()
1591                    .schema_type(SchemaType::String)
1592                    .enum_values(Some(vec!["none"])),
1593            )
1594            .default(Some(
1595                serde_json::to_value(T::default()).expect("Failed to serialize default value"),
1596            ))
1597            .build(),
1598    )
1599}
1600
1601/// Fault tolerance model.
1602///
1603/// The ordering is significant: we consider [Self::ExactlyOnce] to be a "higher
1604/// level" of fault tolerance than [Self::AtLeastOnce].
1605#[derive(
1606    Debug, Copy, Clone, Default, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize, ToSchema,
1607)]
1608#[serde(rename_all = "snake_case")]
1609pub enum FtModel {
1610    /// Each record is output at least once.  Crashes may duplicate output, but
1611    /// no input or output is dropped.
1612    AtLeastOnce,
1613
1614    /// Each record is output exactly once.  Crashes do not drop or duplicate
1615    /// input or output.
1616    #[default]
1617    ExactlyOnce,
1618}
1619
1620impl FtModel {
1621    pub fn option_as_str(value: Option<FtModel>) -> &'static str {
1622        value.map_or("no", |model| model.as_str())
1623    }
1624
1625    pub fn as_str(&self) -> &'static str {
1626        match self {
1627            FtModel::AtLeastOnce => "at_least_once",
1628            FtModel::ExactlyOnce => "exactly_once",
1629        }
1630    }
1631}
1632
1633pub struct FtModelUnknown;
1634
1635impl FromStr for FtModel {
1636    type Err = FtModelUnknown;
1637
1638    fn from_str(s: &str) -> Result<Self, Self::Err> {
1639        match s.to_ascii_lowercase().as_str() {
1640            "exactly_once" => Ok(Self::ExactlyOnce),
1641            "at_least_once" => Ok(Self::AtLeastOnce),
1642            _ => Err(FtModelUnknown),
1643        }
1644    }
1645}
1646
1647/// Describes an input connector configuration
1648#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1649pub struct InputEndpointConfig {
1650    /// The name of the input stream of the circuit that this endpoint is
1651    /// connected to.
1652    pub stream: Cow<'static, str>,
1653
1654    /// Connector configuration.
1655    #[serde(flatten)]
1656    pub connector_config: ConnectorConfig,
1657}
1658
1659impl InputEndpointConfig {
1660    pub fn new(stream: impl Into<Cow<'static, str>>, connector_config: ConnectorConfig) -> Self {
1661        Self {
1662            stream: stream.into(),
1663            connector_config,
1664        }
1665    }
1666}
1667
1668/// Deserialize the `start_after` property of a connector configuration.
1669/// It requires a non-standard deserialization because we want to accept
1670/// either a string or an array of strings.
1671fn deserialize_start_after<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
1672where
1673    D: Deserializer<'de>,
1674{
1675    let value = Option::<JsonValue>::deserialize(deserializer)?;
1676    match value {
1677        Some(JsonValue::String(s)) => Ok(Some(vec![s])),
1678        Some(JsonValue::Array(arr)) => {
1679            let vec = arr
1680                .into_iter()
1681                .map(|item| {
1682                    item.as_str()
1683                        .map(|s| s.to_string())
1684                        .ok_or_else(|| serde::de::Error::custom("invalid 'start_after' property: expected a string, an array of strings, or null"))
1685                })
1686                .collect::<Result<Vec<String>, _>>()?;
1687            Ok(Some(vec))
1688        }
1689        Some(JsonValue::Null) | None => Ok(None),
1690        _ => Err(serde::de::Error::custom(
1691            "invalid 'start_after' property: expected a string, an array of strings, or null",
1692        )),
1693    }
1694}
1695
1696#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1697pub struct ConnectorConfig {
1698    /// Send a full snapshot of a materialized view when the connector first
1699    /// starts. Valid for output connectors only.
1700    ///
1701    /// When `true`, the pipeline emits the current contents of the view as the
1702    /// initial batch the first time the connector runs. The view must be
1703    /// materialized (declared with `CREATE MATERIALIZED VIEW`).
1704    ///
1705    /// The snapshot is sent exactly once per connector lifetime: it does not
1706    /// fire again when the pipeline resumes from a checkpoint. Modifying the
1707    /// connector configuration or invoking the reset API triggers a fresh
1708    /// snapshot when the connector supports reset (e.g., Delta Lake in
1709    /// `truncate` mode and Postgres).
1710    #[serde(default)]
1711    pub send_snapshot: bool,
1712
1713    /// Ingest deletions as insertions, recording the original polarity in the
1714    /// `is_delete` metadata attribute. Valid for input connectors only.
1715    ///
1716    /// When `true`, a delete received by the connector is pushed to the table
1717    /// as an insertion of the same record, and the connector attaches the
1718    /// `is_delete` metadata attribute set to `true` to it. Insertions carry no
1719    /// `is_delete` attribute, so a column declared as
1720    /// `DEFAULT CAST(CONNECTOR_METADATA()['is_delete'] AS BOOLEAN)` is `NULL`
1721    /// for them. The table then contains the entire history of the input
1722    /// stream instead of tracking its current contents.
1723    ///
1724    /// Only tables without a primary key support this mode, since deletions in
1725    /// a table with a primary key delete a key rather than a record.
1726    ///
1727    /// Versions of Feldera that predate this option ignore it and apply
1728    /// deletions as regular deletions.
1729    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1730    pub soft_delete: bool,
1731
1732    /// Transport endpoint configuration.
1733    pub transport: TransportConfig,
1734
1735    /// Optional preprocessor configuration
1736    #[serde(skip_serializing_if = "Option::is_none")]
1737    pub preprocessor: Option<Vec<PreprocessorConfig>>,
1738
1739    /// Parser configuration.
1740    pub format: Option<FormatConfig>,
1741
1742    /// Optional postprocessor configuration
1743    #[serde(skip_serializing_if = "Option::is_none")]
1744    pub postprocessor: Option<Vec<PostprocessorConfig>>,
1745
1746    /// Name of the index that the connector is attached to.
1747    ///
1748    /// This property is valid for output connectors only.  It is used with data
1749    /// transports and formats that expect output updates in the form of key/value
1750    /// pairs, where the key typically represents a unique id associated with the
1751    /// table or view.
1752    ///
1753    /// To support such output formats, an output connector can be attached to an
1754    /// index created using the SQL CREATE INDEX statement.  An index of a table
1755    /// or view contains the same updates as the table or view itself, indexed by
1756    /// one or more key columns.
1757    ///
1758    /// See individual connector documentation for details on how they work
1759    /// with indexes.
1760    pub index: Option<String>,
1761
1762    /// Output buffer configuration.
1763    #[serde(flatten)]
1764    pub output_buffer_config: OutputBufferConfig,
1765
1766    /// Maximum number of records from this connector to process in a single batch.
1767    ///
1768    /// When set, this caps how many records are taken from the connector’s input
1769    /// buffer and pushed through the circuit at once.
1770    ///
1771    /// This is typically configured lower than `max_queued_records` to allow the
1772    /// connector time to restart and refill its buffer while a batch is being
1773    /// processed.
1774    ///
1775    /// Not all input adapters honor this limit.
1776    ///
1777    /// If this is not set, the batch size is derived from `max_worker_batch_size`.
1778    #[serde(skip_serializing_if = "Option::is_none")]
1779    pub max_batch_size: Option<u64>,
1780
1781    /// Maximum number of records processed per batch, per worker thread.
1782    ///
1783    /// When `max_batch_size` is not set, this setting is used to cap
1784    /// the number of records that can be taken from the connector’s input
1785    /// buffer and pushed through the circuit at once.  The effective batch size is computed as:
1786    /// `max_worker_batch_size × workers`.
1787    ///
1788    /// This provides an alternative to `max_batch_size` that automatically adjusts batch
1789    /// size as the number of worker threads changes to maintain constant amount of
1790    /// work per worker per batch.
1791    ///
1792    /// Defaults to 10,000 records per worker.
1793    #[serde(skip_serializing_if = "Option::is_none")]
1794    pub max_worker_batch_size: Option<u64>,
1795
1796    /// Backpressure threshold, in records.
1797    ///
1798    /// Maximal number of records queued by the endpoint before the endpoint
1799    /// is paused by the backpressure mechanism.
1800    ///
1801    /// For input endpoints, this setting bounds the number of records that have
1802    /// been received from the input transport but haven't yet been consumed by
1803    /// the circuit, since the circuit is still busy processing previous inputs.
1804    ///
1805    /// For output endpoints, this setting bounds the number of records that have
1806    /// been produced by the circuit but not yet sent via the output transport endpoint
1807    /// nor stored in the output buffer (see `enable_output_buffer`).
1808    ///
1809    /// Note that this is not a hard bound: there can be a small delay between
1810    /// the backpressure mechanism is triggered and the endpoint is paused, during
1811    /// which more data may be queued.
1812    ///
1813    /// The default is 1 million.
1814    #[serde(default = "default_max_queued_records")]
1815    pub max_queued_records: u64,
1816
1817    /// Backpressure threshold, in bytes.
1818    ///
1819    /// Maximal number of bytes queued by the endpoint before the endpoint
1820    /// is paused by the backpressure mechanism.
1821    ///
1822    /// For input endpoints, this setting bounds the number of bytes that have
1823    /// been received from the input transport but haven't yet been consumed by
1824    /// the circuit since the circuit, since the circuit is still busy processing
1825    /// previous inputs.
1826    ///
1827    /// This setting is not yet implemented for output endpoints.
1828    ///
1829    /// Note that this is not a hard bound: there can be a small delay between
1830    /// the backpressure mechanism is triggered and the endpoint is paused, during
1831    /// which more data may be queued.
1832    ///
1833    /// When this is unspecified, it defaults to `1000 * max_queued_records`.
1834    #[serde(skip_serializing_if = "Option::is_none")]
1835    pub max_queued_bytes: Option<u64>,
1836
1837    /// Create connector in paused state.
1838    ///
1839    /// The default is `false`.
1840    #[serde(default)]
1841    pub paused: bool,
1842
1843    /// Arbitrary user-defined text labels associated with the connector.
1844    ///
1845    /// These labels can be used in conjunction with the `start_after` property
1846    /// to control the start order of connectors.
1847    #[serde(default)]
1848    pub labels: Vec<String>,
1849
1850    /// Start the connector after all connectors with specified labels.
1851    ///
1852    /// This property is used to control the start order of connectors.
1853    /// The connector will not start until all connectors with the specified
1854    /// labels have finished processing all inputs.
1855    #[serde(deserialize_with = "deserialize_start_after")]
1856    #[serde(default)]
1857    pub start_after: Option<Vec<String>>,
1858}
1859
1860impl ConnectorConfig {
1861    pub fn new(transport: TransportConfig, format: Option<FormatConfig>) -> Self {
1862        Self {
1863            send_snapshot: false,
1864            soft_delete: false,
1865            transport,
1866            preprocessor: None,
1867            format,
1868            postprocessor: None,
1869            index: None,
1870            output_buffer_config: Default::default(),
1871            max_batch_size: None,
1872            max_worker_batch_size: None,
1873            max_queued_records: default_max_queued_records(),
1874            max_queued_bytes: None,
1875            paused: false,
1876            labels: Vec::new(),
1877            start_after: None,
1878        }
1879    }
1880
1881    pub fn with_max_batch_size(mut self, max_batch_size: Option<u64>) -> Self {
1882        self.max_batch_size = max_batch_size;
1883        self
1884    }
1885
1886    pub fn with_max_queued_records(mut self, max_queued_records: u64) -> Self {
1887        self.max_queued_records = max_queued_records;
1888        self
1889    }
1890
1891    /// Compare two configs modulo the `paused` field.
1892    ///
1893    /// Used to compare checkpointed and current connector configs.
1894    pub fn equal_modulo_paused(&self, other: &Self) -> bool {
1895        let mut a = self.clone();
1896        let mut b = other.clone();
1897        a.paused = false;
1898        b.paused = false;
1899        a == b
1900    }
1901
1902    /// Compare two input connector configs modulo fields that only affect
1903    /// runtime flow control and do not invalidate checkpointed connector state.
1904    pub fn equal_for_input_checkpoint_replay(&self, other: &Self) -> bool {
1905        let mut a = self.clone();
1906        let mut b = other.clone();
1907        a.normalize_for_input_checkpoint_replay();
1908        b.normalize_for_input_checkpoint_replay();
1909        a == b
1910    }
1911
1912    fn normalize_for_input_checkpoint_replay(&mut self) {
1913        self.paused = false;
1914        self.max_batch_size = None;
1915        self.max_worker_batch_size = None;
1916        self.max_queued_records = default_max_queued_records();
1917        self.max_queued_bytes = None;
1918    }
1919
1920    /// Adopt input connector settings that are safe to change while replaying
1921    /// checkpointed connector state.
1922    pub fn apply_input_checkpoint_replay_config_from(&mut self, other: &Self) {
1923        self.max_batch_size = other.max_batch_size;
1924        self.max_worker_batch_size = other.max_worker_batch_size;
1925        self.max_queued_records = other.max_queued_records;
1926        self.max_queued_bytes = other.max_queued_bytes;
1927    }
1928
1929    /// Returns `max_queued_records` or, if it is not set, the default.
1930    pub fn max_queued_records(&self) -> u64 {
1931        self.max_queued_records
1932    }
1933
1934    /// Returns `max_queued_bytes` or, if it is not set, the default based on
1935    /// `max_queued_records`.
1936    pub fn max_queued_bytes(&self) -> u64 {
1937        self.max_queued_bytes
1938            .unwrap_or_else(|| self.max_queued_records().saturating_mul(1000))
1939    }
1940}
1941
1942#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1943#[serde(default)]
1944pub struct OutputBufferConfig {
1945    /// Enable output buffering.
1946    ///
1947    /// The output buffering mechanism allows decoupling the rate at which the pipeline
1948    /// pushes changes to the output transport from the rate of input changes.
1949    ///
1950    /// By default, output updates produced by the pipeline are pushed directly to
1951    /// the output transport. Some destinations may prefer to receive updates in fewer
1952    /// bigger batches. For instance, when writing Parquet files, producing
1953    /// one bigger file every few minutes is usually better than creating
1954    /// small files every few milliseconds.
1955    ///
1956    /// To achieve such input/output decoupling, users can enable output buffering by
1957    /// setting the `enable_output_buffer` flag to `true`.  When buffering is enabled, output
1958    /// updates produced by the pipeline are consolidated in an internal buffer and are
1959    /// pushed to the output transport when one of several conditions is satisfied:
1960    ///
1961    /// * data has been accumulated in the buffer for more than `max_output_buffer_time_millis`
1962    ///   milliseconds.
1963    /// * buffer size exceeds `max_output_buffer_size_records` records.
1964    ///
1965    /// This flag is `false` by default.
1966    // TODO: on-demand output triggered via the API.
1967    pub enable_output_buffer: bool,
1968
1969    /// Maximum time in milliseconds data is kept in the output buffer.
1970    ///
1971    /// By default, data is kept in the buffer indefinitely until one of
1972    /// the other output conditions is satisfied.  When this option is
1973    /// set the buffer will be flushed at most every
1974    /// `max_output_buffer_time_millis` milliseconds.
1975    ///
1976    /// NOTE: this configuration option requires the `enable_output_buffer` flag
1977    /// to be set.
1978    pub max_output_buffer_time_millis: usize,
1979
1980    /// Maximum number of updates to be kept in the output buffer.
1981    ///
1982    /// This parameter bounds the maximal size of the buffer.
1983    /// Note that the size of the buffer is not always equal to the
1984    /// total number of updates output by the pipeline. Updates to the
1985    /// same record can overwrite or cancel previous updates.
1986    ///
1987    /// The default is 10,000,000.
1988    ///
1989    /// NOTE: this configuration option requires the `enable_output_buffer` flag
1990    /// to be set.
1991    pub max_output_buffer_size_records: usize,
1992}
1993
1994impl Default for OutputBufferConfig {
1995    fn default() -> Self {
1996        Self {
1997            enable_output_buffer: false,
1998            max_output_buffer_size_records: DEFAULT_MAX_OUTPUT_BUFFER_SIZE_RECORDS,
1999            max_output_buffer_time_millis: usize::MAX,
2000        }
2001    }
2002}
2003
2004/// Describes an output connector configuration
2005#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
2006pub struct OutputEndpointConfig {
2007    /// The name of the output stream of the circuit that this endpoint is
2008    /// connected to.
2009    pub stream: Cow<'static, str>,
2010
2011    /// Connector configuration.
2012    #[serde(flatten)]
2013    pub connector_config: ConnectorConfig,
2014}
2015
2016impl OutputEndpointConfig {
2017    pub fn new(stream: impl Into<Cow<'static, str>>, connector_config: ConnectorConfig) -> Self {
2018        Self {
2019            stream: stream.into(),
2020            connector_config,
2021        }
2022    }
2023}
2024
2025/// Transport-specific endpoint configuration passed to
2026/// `crate::OutputTransport::new_endpoint`
2027/// and `crate::InputTransport::new_endpoint`.
2028#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
2029#[serde(tag = "name", content = "config", rename_all = "snake_case")]
2030pub enum TransportConfig {
2031    FileInput(FileInputConfig),
2032    FileOutput(FileOutputConfig),
2033    NatsInput(NatsInputConfig),
2034    KafkaInput(KafkaInputConfig),
2035    KafkaOutput(KafkaOutputConfig),
2036    PubSubInput(PubSubInputConfig),
2037    UrlInput(UrlInputConfig),
2038    S3Input(S3InputConfig),
2039    DeltaTableInput(DeltaTableReaderConfig),
2040    DeltaTableOutput(DeltaTableWriterConfig),
2041    // Snake case would rename "DynamoDBOutput" to `dynamo_db_output`.
2042    // However, DynamoDB is a single word, so override the tag to `dynamodb_output`.
2043    #[serde(rename = "dynamodb_output")]
2044    DynamoDBOutput(DynamoDBWriterConfig),
2045    RedisOutput(RedisOutputConfig),
2046    // Prevent rust from complaining about large size difference between enum variants.
2047    IcebergInput(Box<IcebergReaderConfig>),
2048    PostgresInput(PostgresReaderConfig),
2049    PostgresCdcInput(PostgresCdcReaderConfig),
2050    PostgresOutput(PostgresWriterConfig),
2051    Datagen(DatagenInputConfig),
2052    Nexmark(NexmarkInputConfig),
2053    /// Direct HTTP input: cannot be instantiated through API
2054    HttpInput(HttpInputConfig),
2055    /// Direct HTTP output: cannot be instantiated through API
2056    HttpOutput(HttpOutputConfig),
2057    /// Ad hoc input: cannot be instantiated through API
2058    AdHocInput(AdHocInputConfig),
2059    ClockInput(ClockConfig),
2060    /// Output connector that discards all data.
2061    NullOutput,
2062    /// Input connector that produces no data.
2063    EmptyInput,
2064}
2065
2066impl TransportConfig {
2067    pub fn name(&self) -> String {
2068        match self {
2069            TransportConfig::FileInput(_) => "file_input".to_string(),
2070            TransportConfig::FileOutput(_) => "file_output".to_string(),
2071            TransportConfig::NatsInput(_) => "nats_input".to_string(),
2072            TransportConfig::KafkaInput(_) => "kafka_input".to_string(),
2073            TransportConfig::KafkaOutput(_) => "kafka_output".to_string(),
2074            TransportConfig::PubSubInput(_) => "pub_sub_input".to_string(),
2075            TransportConfig::UrlInput(_) => "url_input".to_string(),
2076            TransportConfig::S3Input(_) => "s3_input".to_string(),
2077            TransportConfig::DeltaTableInput(_) => "delta_table_input".to_string(),
2078            TransportConfig::DeltaTableOutput(_) => "delta_table_output".to_string(),
2079            TransportConfig::DynamoDBOutput(_) => "dynamodb_output".to_string(),
2080            TransportConfig::IcebergInput(_) => "iceberg_input".to_string(),
2081            TransportConfig::PostgresInput(_) => "postgres_input".to_string(),
2082            TransportConfig::PostgresCdcInput(_) => "postgres_cdc_input".to_string(),
2083            TransportConfig::PostgresOutput(_) => "postgres_output".to_string(),
2084            TransportConfig::Datagen(_) => "datagen".to_string(),
2085            TransportConfig::Nexmark(_) => "nexmark".to_string(),
2086            TransportConfig::HttpInput(_) => "http_input".to_string(),
2087            TransportConfig::HttpOutput(_) => "http_output".to_string(),
2088            TransportConfig::AdHocInput(_) => "adhoc_input".to_string(),
2089            TransportConfig::RedisOutput(_) => "redis_output".to_string(),
2090            TransportConfig::ClockInput(_) => "clock".to_string(),
2091            TransportConfig::NullOutput => "null_output".to_string(),
2092            TransportConfig::EmptyInput => "empty_input".to_string(),
2093        }
2094    }
2095
2096    /// Returns true if the connector is transient, i.e., is created and destroyed
2097    /// at runtime on demand, rather than being configured as part of the pipeline.
2098    pub fn is_transient(&self) -> bool {
2099        matches!(
2100            self,
2101            TransportConfig::AdHocInput(_)
2102                | TransportConfig::HttpInput(_)
2103                | TransportConfig::HttpOutput(_)
2104                | TransportConfig::ClockInput(_)
2105        )
2106    }
2107
2108    pub fn is_http_input(&self) -> bool {
2109        matches!(self, TransportConfig::HttpInput(_))
2110    }
2111}
2112
2113/// Data format specification used to parse raw data received from the
2114/// endpoint or to encode data sent to the endpoint.
2115#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, ToSchema)]
2116pub struct FormatConfig {
2117    /// Format name, e.g., "csv", "json", "bincode", etc.
2118    pub name: Cow<'static, str>,
2119
2120    /// Format-specific parser or encoder configuration.
2121    #[serde(default)]
2122    #[schema(value_type = Object)]
2123    pub config: JsonValue,
2124}
2125
2126#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
2127#[serde(default)]
2128pub struct ResourceConfig {
2129    /// The minimum number of CPU cores to reserve
2130    /// for an instance of this pipeline
2131    #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
2132    pub cpu_cores_min: Option<f64>,
2133
2134    /// The maximum number of CPU cores to reserve
2135    /// for an instance of this pipeline
2136    #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
2137    pub cpu_cores_max: Option<f64>,
2138
2139    /// The minimum memory in Megabytes to reserve
2140    /// for an instance of this pipeline
2141    pub memory_mb_min: Option<u64>,
2142
2143    /// The maximum memory in Megabytes to reserve
2144    /// for an instance of this pipeline
2145    pub memory_mb_max: Option<u64>,
2146
2147    /// The total storage in Megabytes to reserve
2148    /// for an instance of this pipeline
2149    pub storage_mb_max: Option<u64>,
2150
2151    /// Storage class to use for an instance of this pipeline.
2152    /// The class determines storage performance such as IOPS and throughput.
2153    pub storage_class: Option<String>,
2154
2155    /// Kubernetes service account name to use for an instance of this pipeline.
2156    /// The account determines permissions and access controls.
2157    pub service_account_name: Option<String>,
2158
2159    /// Kubernetes namespace to use for an instance of this pipeline.
2160    /// The namespace determines the scope of names for resources created
2161    /// for the pipeline.
2162    /// If not set, the pipeline will be deployed in the same namespace
2163    /// as the control-plane.
2164    // The type of this field should not be backward incompatibly changed, and its location in the
2165    // runtime configuration JSON (`runtime_config.resources.namespace`) should not be changed.
2166    pub namespace: Option<String>,
2167}
2168
2169#[cfg(test)]
2170mod sync_config_tests {
2171    use super::SyncConfig;
2172
2173    #[test]
2174    fn take_bucket_ownership_defaults_to_false() {
2175        let sync: SyncConfig = serde_json::from_str(r#"{"bucket": "ckpts/a"}"#).unwrap();
2176        assert!(!sync.take_bucket_ownership);
2177
2178        let sync: SyncConfig =
2179            serde_json::from_str(r#"{"bucket": "ckpts/a", "take_bucket_ownership": true}"#)
2180                .unwrap();
2181        assert!(sync.take_bucket_ownership);
2182    }
2183}