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::program_schema::ProgramSchema;
9use crate::secret_resolver::default_secrets_directory;
10use crate::transport::adhoc::AdHocInputConfig;
11use crate::transport::clock::ClockConfig;
12use crate::transport::datagen::DatagenInputConfig;
13use crate::transport::delta_table::{DeltaTableReaderConfig, DeltaTableWriterConfig};
14use crate::transport::file::{FileInputConfig, FileOutputConfig};
15use crate::transport::http::HttpInputConfig;
16use crate::transport::iceberg::IcebergReaderConfig;
17use crate::transport::kafka::{KafkaInputConfig, KafkaOutputConfig};
18use crate::transport::nats::NatsInputConfig;
19use crate::transport::nexmark::NexmarkInputConfig;
20use crate::transport::postgres::{PostgresReaderConfig, PostgresWriterConfig};
21use crate::transport::pubsub::PubSubInputConfig;
22use crate::transport::redis::RedisOutputConfig;
23use crate::transport::s3::S3InputConfig;
24use crate::transport::url::UrlInputConfig;
25use core::fmt;
26use feldera_ir::{MirNode, MirNodeId};
27use serde::de::{self, MapAccess, Visitor};
28use serde::{Deserialize, Deserializer, Serialize};
29use serde_json::Value as JsonValue;
30use std::collections::HashMap;
31use std::fmt::Display;
32use std::path::Path;
33use std::str::FromStr;
34use std::time::Duration;
35use std::{borrow::Cow, cmp::max, collections::BTreeMap};
36use utoipa::ToSchema;
37use utoipa::openapi::{ObjectBuilder, OneOfBuilder, Ref, RefOr, Schema, SchemaType};
38
39const DEFAULT_MAX_PARALLEL_CONNECTOR_INIT: u64 = 10;
40
41/// Default value of `ConnectorConfig::max_queued_records`.
42pub const fn default_max_queued_records() -> u64 {
43    1_000_000
44}
45
46/// Default maximum batch size for connectors, in records.
47///
48/// If you change this then update the comment on
49/// [ConnectorConfig::max_batch_size].
50pub const fn default_max_batch_size() -> u64 {
51    10_000
52}
53
54pub const DEFAULT_CLOCK_RESOLUTION_USECS: u64 = 1_000_000;
55
56/// Program information included in the pipeline configuration.
57#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
58pub struct ProgramIr {
59    /// The MIR of the program.
60    pub mir: HashMap<MirNodeId, MirNode>,
61    /// Program schema.
62    pub program_schema: ProgramSchema,
63}
64
65/// Pipeline deployment configuration.
66/// It represents configuration entries directly provided by the user
67/// (e.g., runtime configuration) and entries derived from the schema
68/// of the compiled program (e.g., connectors). Storage configuration,
69/// if applicable, is set by the runner.
70#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq)]
71pub struct PipelineConfig {
72    /// Global controller configuration.
73    #[serde(flatten)]
74    #[schema(inline)]
75    pub global: RuntimeConfig,
76
77    /// Unique system-generated name of the pipeline (format: `pipeline-<uuid>`).
78    /// It is unique across all tenants and cannot be changed.
79    ///
80    /// The `<uuid>` is also used in the naming of various resources that back the pipeline,
81    /// and as such this name is useful to find/identify corresponding resources.
82    pub name: Option<String>,
83
84    /// Name given by the tenant to the pipeline. It is only unique within the same tenant, and can
85    /// be changed by the tenant when the pipeline is stopped.
86    ///
87    /// Given a specific tenant, it can be used to find/identify a specific pipeline of theirs.
88    pub given_name: Option<String>,
89
90    /// Configuration for persistent storage
91    ///
92    /// If `global.storage` is `Some(_)`, this field must be set to some
93    /// [`StorageConfig`].  If `global.storage` is `None``, the pipeline ignores
94    /// this field.
95    #[serde(default)]
96    pub storage_config: Option<StorageConfig>,
97
98    /// Directory containing values of secrets.
99    ///
100    /// If this is not set, a default directory is used.
101    pub secrets_dir: Option<String>,
102
103    /// Input endpoint configuration.
104    #[serde(default)]
105    pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
106
107    /// Output endpoint configuration.
108    #[serde(default)]
109    pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
110
111    /// Program information.
112    #[serde(default)]
113    pub program_ir: Option<ProgramIr>,
114}
115
116impl PipelineConfig {
117    pub fn max_parallel_connector_init(&self) -> u64 {
118        max(
119            self.global
120                .max_parallel_connector_init
121                .unwrap_or(DEFAULT_MAX_PARALLEL_CONNECTOR_INIT),
122            1,
123        )
124    }
125
126    pub fn with_storage(self, storage: Option<(StorageConfig, StorageOptions)>) -> Self {
127        let (storage_config, storage_options) = storage.unzip();
128        Self {
129            global: RuntimeConfig {
130                storage: storage_options,
131                ..self.global
132            },
133            storage_config,
134            ..self
135        }
136    }
137
138    pub fn storage(&self) -> Option<(&StorageConfig, &StorageOptions)> {
139        let storage_options = self.global.storage.as_ref();
140        let storage_config = self.storage_config.as_ref();
141        storage_config.zip(storage_options)
142    }
143
144    /// Returns `self.secrets_dir`, or the default secrets directory if it isn't
145    /// set.
146    pub fn secrets_dir(&self) -> &Path {
147        match &self.secrets_dir {
148            Some(dir) => Path::new(dir.as_str()),
149            None => default_secrets_directory(),
150        }
151    }
152
153    /// Abbreviated config that can be printed in the log on pipeline startup.
154    pub fn display_summary(&self) -> String {
155        // TODO: we may want to further abbreviate connector config.
156        let summary = serde_json::json!({
157            "name": self.name,
158            "given_name": self.given_name,
159            "global": self.global,
160            "storage_config": self.storage_config,
161            "secrets_dir": self.secrets_dir,
162            "inputs": self.inputs,
163            "outputs": self.outputs
164        });
165
166        serde_json::to_string_pretty(&summary).unwrap_or_else(|_| "{}".to_string())
167    }
168}
169
170/// A subset of fields in `PipelineConfig` that are generated by the compiler.
171/// These fields are shipped to the pipeline by the compilation server along with
172/// the program binary.
173// Note: An alternative would be to embed these fields in the program binary itself
174// as static strings. This would work well for program IR, but it would require recompiling
175// the program anytime a connector config changes, whereas today connector changes
176// do not require recompilation.
177#[derive(Default, Deserialize, Serialize, Eq, PartialEq, Debug, Clone)]
178pub struct PipelineConfigProgramInfo {
179    /// Input endpoint configuration.
180    pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
181
182    /// Output endpoint configuration.
183    #[serde(default)]
184    pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
185
186    /// Program information.
187    #[serde(default)]
188    pub program_ir: Option<ProgramIr>,
189}
190
191/// Configuration for persistent storage in a [`PipelineConfig`].
192#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
193pub struct StorageConfig {
194    /// A directory to keep pipeline state, as a path on the filesystem of the
195    /// machine or container where the pipeline will run.
196    ///
197    /// When storage is enabled, this directory stores the data for
198    /// [StorageBackendConfig::Default].
199    ///
200    /// When fault tolerance is enabled, this directory stores checkpoints and
201    /// the log.
202    pub path: String,
203
204    /// How to cache access to storage in this pipeline.
205    #[serde(default)]
206    pub cache: StorageCacheConfig,
207}
208
209impl StorageConfig {
210    pub fn path(&self) -> &Path {
211        Path::new(&self.path)
212    }
213}
214
215/// How to cache access to storage within a Feldera pipeline.
216#[derive(Copy, Clone, Default, Deserialize, Serialize, Debug, PartialEq, Eq, ToSchema)]
217#[serde(rename_all = "snake_case")]
218pub enum StorageCacheConfig {
219    /// Use the operating system's page cache as the primary storage cache.
220    ///
221    /// This is the default because it currently performs better than
222    /// `FelderaCache`.
223    #[default]
224    PageCache,
225
226    /// Use Feldera's internal cache implementation.
227    ///
228    /// This is under development. It will become the default when its
229    /// performance exceeds that of `PageCache`.
230    FelderaCache,
231}
232
233impl StorageCacheConfig {
234    #[cfg(unix)]
235    pub fn to_custom_open_flags(&self) -> i32 {
236        match self {
237            StorageCacheConfig::PageCache => (),
238            StorageCacheConfig::FelderaCache => {
239                #[cfg(target_os = "linux")]
240                return libc::O_DIRECT;
241            }
242        }
243        0
244    }
245}
246
247/// Storage configuration for a pipeline.
248#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
249#[serde(default)]
250pub struct StorageOptions {
251    /// How to connect to the underlying storage.
252    pub backend: StorageBackendConfig,
253
254    /// For a batch of data maintained as part of a persistent index during a
255    /// pipeline run, the minimum estimated number of bytes to write it to
256    /// storage.
257    ///
258    /// This is provided for debugging and fine-tuning and should ordinarily be
259    /// left unset.
260    ///
261    /// A value of 0 will write even empty batches to storage, and nonzero
262    /// values provide a threshold.  `usize::MAX` would effectively disable
263    /// storage for such batches.  The default is 10,048,576 (10 MiB).
264    pub min_storage_bytes: Option<usize>,
265
266    /// For a batch of data passed through the pipeline during a single step,
267    /// the minimum estimated number of bytes to write it to storage.
268    ///
269    /// This is provided for debugging and fine-tuning and should ordinarily be
270    /// left unset.  A value of 0 will write even empty batches to storage, and
271    /// nonzero values provide a threshold.  `usize::MAX`, the default,
272    /// effectively disables storage for such batches.  If it is set to another
273    /// value, it should ordinarily be greater than or equal to
274    /// `min_storage_bytes`.
275    pub min_step_storage_bytes: Option<usize>,
276
277    /// The form of compression to use in data batches.
278    ///
279    /// Compression has a CPU cost but it can take better advantage of limited
280    /// NVMe and network bandwidth, which means that it can increase overall
281    /// performance.
282    pub compression: StorageCompression,
283
284    /// The maximum size of the in-memory storage cache, in MiB.
285    ///
286    /// If set, the specified cache size is spread across all the foreground and
287    /// background threads. If unset, each foreground or background thread cache
288    /// is limited to 256 MiB.
289    pub cache_mib: Option<usize>,
290}
291
292/// Backend storage configuration.
293#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
294#[serde(tag = "name", content = "config", rename_all = "snake_case")]
295pub enum StorageBackendConfig {
296    /// Use the default storage configuration.
297    ///
298    /// This currently uses the local file system.
299    #[default]
300    Default,
301
302    /// Use the local file system.
303    ///
304    /// This uses ordinary system file operations.
305    File(Box<FileBackendConfig>),
306
307    /// Object storage.
308    Object(ObjectStorageConfig),
309}
310
311impl Display for StorageBackendConfig {
312    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
313        match self {
314            StorageBackendConfig::Default => write!(f, "default"),
315            StorageBackendConfig::File(_) => write!(f, "file"),
316            StorageBackendConfig::Object(_) => write!(f, "object"),
317        }
318    }
319}
320
321/// Storage compression algorithm.
322#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
323#[serde(rename_all = "snake_case")]
324pub enum StorageCompression {
325    /// Use Feldera's default compression algorithm.
326    ///
327    /// The default may change as Feldera's performance is tuned and new
328    /// algorithms are introduced.
329    #[default]
330    Default,
331
332    /// Do not compress.
333    None,
334
335    /// Use [Snappy](https://en.wikipedia.org/wiki/Snappy_(compression)) compression.
336    Snappy,
337}
338
339#[derive(Debug, Clone, Eq, PartialEq)]
340pub enum StartFromCheckpoint {
341    Latest,
342    Uuid(uuid::Uuid),
343}
344
345impl ToSchema<'_> for StartFromCheckpoint {
346    fn schema() -> (
347        &'static str,
348        utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
349    ) {
350        (
351            "StartFromCheckpoint",
352            utoipa::openapi::RefOr::T(Schema::OneOf(
353                OneOfBuilder::new()
354                    .item(
355                        ObjectBuilder::new()
356                            .schema_type(SchemaType::String)
357                            .enum_values(Some(["latest"].into_iter()))
358                            .build(),
359                    )
360                    .item(
361                        ObjectBuilder::new()
362                            .schema_type(SchemaType::String)
363                            .format(Some(utoipa::openapi::SchemaFormat::KnownFormat(
364                                utoipa::openapi::KnownFormat::Uuid,
365                            )))
366                            .build(),
367                    )
368                    .nullable(true)
369                    .build(),
370            )),
371        )
372    }
373}
374
375impl<'de> Deserialize<'de> for StartFromCheckpoint {
376    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
377    where
378        D: Deserializer<'de>,
379    {
380        struct StartFromCheckpointVisitor;
381
382        impl<'de> Visitor<'de> for StartFromCheckpointVisitor {
383            type Value = StartFromCheckpoint;
384
385            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
386                formatter.write_str("a UUID string or the string \"latest\"")
387            }
388
389            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
390            where
391                E: de::Error,
392            {
393                if value == "latest" {
394                    Ok(StartFromCheckpoint::Latest)
395                } else {
396                    uuid::Uuid::parse_str(value)
397                        .map(StartFromCheckpoint::Uuid)
398                        .map_err(|_| E::invalid_value(serde::de::Unexpected::Str(value), &self))
399                }
400            }
401        }
402
403        deserializer.deserialize_str(StartFromCheckpointVisitor)
404    }
405}
406
407impl Serialize for StartFromCheckpoint {
408    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
409    where
410        S: serde::Serializer,
411    {
412        match self {
413            StartFromCheckpoint::Latest => serializer.serialize_str("latest"),
414            StartFromCheckpoint::Uuid(uuid) => serializer.serialize_str(&uuid.to_string()),
415        }
416    }
417}
418
419#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
420pub struct SyncConfig {
421    /// The endpoint URL for the storage service.
422    ///
423    /// This is typically required for custom or local S3-compatible storage providers like MinIO.
424    /// Example: `http://localhost:9000`
425    ///
426    /// Relevant rclone config key: [`endpoint`](https://rclone.org/s3/#s3-endpoint)
427    pub endpoint: Option<String>,
428
429    /// The name of the storage bucket.
430    ///
431    /// This may include a path to a folder inside the bucket (e.g., `my-bucket/data`).
432    pub bucket: String,
433
434    /// The region that this bucket is in.
435    ///
436    /// Leave empty for Minio or the default region (`us-east-1` for AWS).
437    pub region: Option<String>,
438
439    /// The name of the cloud storage provider (e.g., `"AWS"`, `"Minio"`).
440    ///
441    /// Used for provider-specific behavior in rclone.
442    /// If omitted, defaults to `"Other"`.
443    ///
444    /// See [rclone S3 provider documentation](https://rclone.org/s3/#s3-provider)
445    pub provider: Option<String>,
446
447    /// The access key used to authenticate with the storage provider.
448    ///
449    /// If not provided, rclone will fall back to environment-based credentials, such as
450    /// `RCLONE_S3_ACCESS_KEY_ID`. In Kubernetes environments using IRSA (IAM Roles for Service Accounts),
451    /// this can be left empty to allow automatic authentication via the pod's service account.
452    pub access_key: Option<String>,
453
454    /// The secret key used together with the access key for authentication.
455    ///
456    /// If not provided, rclone will fall back to environment-based credentials, such as
457    /// `RCLONE_S3_SECRET_ACCESS_KEY`. In Kubernetes environments using IRSA (IAM Roles for Service Accounts),
458    /// this can be left empty to allow automatic authentication via the pod's service account.
459    pub secret_key: Option<String>,
460
461    /// When set, the pipeline will try fetch the specified checkpoint from the
462    /// object store.
463    ///
464    /// If `fail_if_no_checkpoint` is `true`, the pipeline will fail to initialize.
465    pub start_from_checkpoint: Option<StartFromCheckpoint>,
466
467    /// When true, the pipeline will fail to initialize if fetching the
468    /// specified checkpoint fails (missing, download error).
469    /// When false, the pipeline will start from scratch instead.
470    ///
471    /// False by default.
472    #[schema(default = std::primitive::bool::default)]
473    #[serde(default)]
474    pub fail_if_no_checkpoint: bool,
475
476    /// The number of file transfers to run in parallel.
477    /// Default: 20
478    pub transfers: Option<u8>,
479
480    /// The number of checkers to run in parallel.
481    /// Default: 20
482    pub checkers: Option<u8>,
483
484    /// Set to skip post copy check of checksums, and only check the file sizes.
485    /// This can significantly improve the throughput.
486    /// Defualt: false
487    pub ignore_checksum: Option<bool>,
488
489    /// Number of streams to use for multi-thread downloads.
490    /// Default: 10
491    pub multi_thread_streams: Option<u8>,
492
493    /// Use multi-thread download for files above this size.
494    /// Format: `[size][Suffix]` (Example: 1G, 500M)
495    /// Supported suffixes: k|M|G|T
496    /// Default: 100M
497    pub multi_thread_cutoff: Option<String>,
498
499    /// The number of chunks of the same file that are uploaded for multipart uploads.
500    /// Default: 10
501    pub upload_concurrency: Option<u8>,
502
503    /// When `true`, the pipeline starts in **standby** mode; processing doesn't
504    /// start until activation (`POST /activate`).
505    /// If this pipeline was previously activated and the storage has not been
506    /// cleared, the pipeline will auto activate, no newer checkpoints will be
507    /// fetched.
508    ///
509    /// Standby behavior depends on `start_from_checkpoint`:
510    /// - If `latest`, pipeline continuously fetches the latest available
511    ///   checkpoint until activated.
512    /// - If checkpoint UUID, pipeline fetches this checkpoint once and waits
513    ///   in standby until activated.
514    ///
515    /// Default: `false`
516    #[schema(default = std::primitive::bool::default)]
517    #[serde(default)]
518    pub standby: bool,
519
520    /// The interval (in seconds) between each attempt to fetch the latest
521    /// checkpoint from object store while in standby mode.
522    ///
523    /// Applies only when `start_from_checkpoint` is set to `latest`.
524    ///
525    /// Default: 10 seconds
526    #[schema(default = default_pull_interval)]
527    #[serde(default = "default_pull_interval")]
528    pub pull_interval: u64,
529
530    /// The interval (in seconds) between each push of checkpoints to object store.
531    ///
532    /// Default: disabled (no periodic push).
533    #[serde(default)]
534    pub push_interval: Option<u64>,
535
536    /// Extra flags to pass to `rclone`.
537    ///
538    /// WARNING: Supplying incorrect or conflicting flags can break `rclone`.
539    /// Use with caution.
540    ///
541    /// Refer to the docs to see the supported flags:
542    /// - [Global flags](https://rclone.org/flags/)
543    /// - [S3 specific flags](https://rclone.org/s3/)
544    pub flags: Option<Vec<String>>,
545
546    /// The minimum number of checkpoints to retain in object store.
547    /// No checkpoints will be deleted if the total count is below this threshold.
548    ///
549    /// Default: 10
550    #[schema(default = default_retention_min_count)]
551    #[serde(default = "default_retention_min_count")]
552    pub retention_min_count: u32,
553
554    /// The minimum age (in days) a checkpoint must reach before it becomes
555    /// eligible for deletion. All younger checkpoints will be preserved.
556    ///
557    /// Default: 30
558    #[schema(default = default_retention_min_age)]
559    #[serde(default = "default_retention_min_age")]
560    pub retention_min_age: u32,
561}
562
563fn default_pull_interval() -> u64 {
564    10
565}
566
567fn default_retention_min_count() -> u32 {
568    10
569}
570
571fn default_retention_min_age() -> u32 {
572    30
573}
574
575impl SyncConfig {
576    pub fn validate(&self) -> Result<(), String> {
577        if self.standby && self.start_from_checkpoint.is_none() {
578            return Err(r#"invalid sync config: `standby` set to `true` but `start_from_checkpoint` not set.
579Standby mode requires `start_from_checkpoint` to be set.
580Consider setting `start_from_checkpoint` to `"latest"`."#.to_owned());
581        }
582
583        Ok(())
584    }
585}
586
587#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
588pub struct ObjectStorageConfig {
589    /// URL.
590    ///
591    /// The following URL schemes are supported:
592    ///
593    /// * S3:
594    ///   - `s3://<bucket>/<path>`
595    ///   - `s3a://<bucket>/<path>`
596    ///   - `https://s3.<region>.amazonaws.com/<bucket>`
597    ///   - `https://<bucket>.s3.<region>.amazonaws.com`
598    ///   - `https://ACCOUNT_ID.r2.cloudflarestorage.com/bucket`
599    /// * Google Cloud Storage:
600    ///   - `gs://<bucket>/<path>`
601    /// * Microsoft Azure Blob Storage:
602    ///   - `abfs[s]://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
603    ///   - `abfs[s]://<file_system>@<account_name>.dfs.core.windows.net/<path>`
604    ///   - `abfs[s]://<file_system>@<account_name>.dfs.fabric.microsoft.com/<path>`
605    ///   - `az://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
606    ///   - `adl://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
607    ///   - `azure://<container>/<path>` (custom)
608    ///   - `https://<account>.dfs.core.windows.net`
609    ///   - `https://<account>.blob.core.windows.net`
610    ///   - `https://<account>.blob.core.windows.net/<container>`
611    ///   - `https://<account>.dfs.fabric.microsoft.com`
612    ///   - `https://<account>.dfs.fabric.microsoft.com/<container>`
613    ///   - `https://<account>.blob.fabric.microsoft.com`
614    ///   - `https://<account>.blob.fabric.microsoft.com/<container>`
615    ///
616    /// Settings derived from the URL will override other settings.
617    pub url: String,
618
619    /// Additional options as key-value pairs.
620    ///
621    /// The following keys are supported:
622    ///
623    /// * S3:
624    ///   - `access_key_id`: AWS Access Key.
625    ///   - `secret_access_key`: AWS Secret Access Key.
626    ///   - `region`: Region.
627    ///   - `default_region`: Default region.
628    ///   - `endpoint`: Custom endpoint for communicating with S3,
629    ///     e.g. `https://localhost:4566` for testing against a localstack
630    ///     instance.
631    ///   - `token`: Token to use for requests (passed to underlying provider).
632    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/aws/enum.AmazonS3ConfigKey.html#variants).
633    /// * Google Cloud Storage:
634    ///   - `service_account`: Path to the service account file.
635    ///   - `service_account_key`: The serialized service account key.
636    ///   - `google_application_credentials`: Application credentials path.
637    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/gcp/enum.GoogleConfigKey.html).
638    /// * Microsoft Azure Blob Storage:
639    ///   - `access_key`: Azure Access Key.
640    ///   - `container_name`: Azure Container Name.
641    ///   - `account`: Azure Account.
642    ///   - `bearer_token_authorization`: Static bearer token for authorizing requests.
643    ///   - `client_id`: Client ID for use in client secret or Kubernetes federated credential flow.
644    ///   - `client_secret`: Client secret for use in client secret flow.
645    ///   - `tenant_id`: Tenant ID for use in client secret or Kubernetes federated credential flow.
646    ///   - `endpoint`: Override the endpoint for communicating with blob storage.
647    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/azure/enum.AzureConfigKey.html#variants).
648    ///
649    /// Options set through the URL take precedence over those set with these
650    /// options.
651    #[serde(flatten)]
652    pub other_options: BTreeMap<String, String>,
653}
654
655/// Configuration for local file system access.
656#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
657#[serde(default)]
658pub struct FileBackendConfig {
659    /// Whether to use background threads for file I/O.
660    ///
661    /// Background threads should improve performance, but they can reduce
662    /// performance if too few cores are available. This is provided for
663    /// debugging and fine-tuning and should ordinarily be left unset.
664    pub async_threads: Option<bool>,
665
666    /// Per-I/O operation sleep duration, in milliseconds.
667    ///
668    /// This is for simulating slow storage devices.  Do not use this in
669    /// production.
670    pub ioop_delay: Option<u64>,
671
672    /// Configuration to synchronize checkpoints to object store.
673    pub sync: Option<SyncConfig>,
674}
675
676/// Global pipeline configuration settings. This is the publicly
677/// exposed type for users to configure pipelines.
678#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
679#[serde(default)]
680pub struct RuntimeConfig {
681    /// Number of DBSP worker threads.
682    ///
683    /// Each DBSP "foreground" worker thread is paired with a "background"
684    /// thread for LSM merging, making the total number of threads twice the
685    /// specified number.
686    ///
687    /// The typical sweet spot for the number of workers is between 4 and 16.
688    /// Each worker increases overall memory consumption for data structures
689    /// used during a step.
690    pub workers: u16,
691
692    /// Storage configuration.
693    ///
694    /// - If this is `None`, the default, the pipeline's state is kept in
695    ///   in-memory data-structures.  This is useful if the pipeline's state
696    ///   will fit in memory and if the pipeline is ephemeral and does not need
697    ///   to be recovered after a restart. The pipeline will most likely run
698    ///   faster since it does not need to access storage.
699    ///
700    /// - If set, the pipeline's state is kept on storage.  This allows the
701    ///   pipeline to work with state that will not fit into memory. It also
702    ///   allows the state to be checkpointed and recovered across restarts.
703    #[serde(deserialize_with = "deserialize_storage_options")]
704    pub storage: Option<StorageOptions>,
705
706    /// Fault tolerance configuration.
707    #[serde(deserialize_with = "deserialize_fault_tolerance")]
708    pub fault_tolerance: FtConfig,
709
710    /// Enable CPU profiler.
711    ///
712    /// The default value is `true`.
713    pub cpu_profiler: bool,
714
715    /// Enable pipeline tracing.
716    pub tracing: bool,
717
718    /// Jaeger tracing endpoint to send tracing information to.
719    pub tracing_endpoint_jaeger: String,
720
721    /// Minimal input batch size.
722    ///
723    /// The controller delays pushing input records to the circuit until at
724    /// least `min_batch_size_records` records have been received (total
725    /// across all endpoints) or `max_buffering_delay_usecs` microseconds
726    /// have passed since at least one input records has been buffered.
727    /// Defaults to 0.
728    pub min_batch_size_records: u64,
729
730    /// Maximal delay in microseconds to wait for `min_batch_size_records` to
731    /// get buffered by the controller, defaults to 0.
732    pub max_buffering_delay_usecs: u64,
733
734    /// Resource reservations and limits. This is enforced
735    /// only in Feldera Cloud.
736    pub resources: ResourceConfig,
737
738    /// Real-time clock resolution in microseconds.
739    ///
740    /// This parameter controls the execution of queries that use the `NOW()` function.  The output of such
741    /// queries depends on the real-time clock and can change over time without any external
742    /// inputs.  If the query uses `NOW()`, the pipeline will update the clock value and trigger incremental
743    /// recomputation at most each `clock_resolution_usecs` microseconds.  If the query does not use
744    /// `NOW()`, then clock value updates are suppressed and the pipeline ignores this setting.
745    ///
746    /// It is set to 1 second (1,000,000 microseconds) by default.
747    pub clock_resolution_usecs: Option<u64>,
748
749    /// Optionally, a list of CPU numbers for CPUs to which the pipeline may pin
750    /// its worker threads.  Specify at least twice as many CPU numbers as
751    /// workers.  CPUs are generally numbered starting from 0.  The pipeline
752    /// might not be able to honor CPU pinning requests.
753    ///
754    /// CPU pinning can make pipelines run faster and perform more consistently,
755    /// as long as different pipelines running on the same machine are pinned to
756    /// different CPUs.
757    pub pin_cpus: Vec<usize>,
758
759    /// Timeout in seconds for the `Provisioning` phase of the pipeline.
760    /// Setting this value will override the default of the runner.
761    pub provisioning_timeout_secs: Option<u64>,
762
763    /// The maximum number of connectors initialized in parallel during pipeline
764    /// startup.
765    ///
766    /// At startup, the pipeline must initialize all of its input and output connectors.
767    /// Depending on the number and types of connectors, this can take a long time.
768    /// To accelerate the process, multiple connectors are initialized concurrently.
769    /// This option controls the maximum number of connectors that can be initialized
770    /// in parallel.
771    ///
772    /// The default is 10.
773    pub max_parallel_connector_init: Option<u64>,
774
775    /// Specification of additional (sidecar) containers.
776    pub init_containers: Option<serde_json::Value>,
777
778    /// Deprecated: setting this true or false does not have an effect anymore.
779    pub checkpoint_during_suspend: bool,
780
781    /// Sets the number of available runtime threads for the http server.
782    ///
783    /// In most cases, this does not need to be set explicitly and
784    /// the default is sufficient. Can be increased in case the
785    /// pipeline HTTP API operations are a bottleneck.
786    ///
787    /// If not specified, the default is set to `workers`.
788    pub http_workers: Option<u64>,
789
790    /// Sets the number of available runtime threads for async IO tasks.
791    ///
792    /// This affects some networking and file I/O operations
793    /// especially adapters and ad-hoc queries.
794    ///
795    /// In most cases, this does not need to be set explicitly and
796    /// the default is sufficient. Can be increased in case
797    /// ingress, egress or ad-hoc queries are a bottleneck.
798    ///
799    /// If not specified, the default is set to `workers`.
800    pub io_workers: Option<u64>,
801
802    /// Optional settings for tweaking Feldera internals.
803    ///
804    /// The available key-value pairs change from one version of Feldera to
805    /// another, so users should not depend on particular settings being
806    /// available, or on their behavior.
807    pub dev_tweaks: BTreeMap<String, serde_json::Value>,
808
809    /// Log filtering directives.
810    ///
811    /// If set to a valid [tracing-subscriber] filter, this controls the log
812    /// messages emitted by the pipeline process.  Otherwise, or if the filter
813    /// has invalid syntax, messages at "info" severity and higher are written
814    /// to the log and all others are discarded.
815    ///
816    /// [tracing-subscriber]: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#directives
817    pub logging: Option<String>,
818}
819
820/// Accepts "true" and "false" and converts them to the new format.
821fn deserialize_storage_options<'de, D>(deserializer: D) -> Result<Option<StorageOptions>, D::Error>
822where
823    D: Deserializer<'de>,
824{
825    struct BoolOrStruct;
826
827    impl<'de> Visitor<'de> for BoolOrStruct {
828        type Value = Option<StorageOptions>;
829
830        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
831            formatter.write_str("boolean or StorageOptions")
832        }
833
834        fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
835        where
836            E: de::Error,
837        {
838            match v {
839                false => Ok(None),
840                true => Ok(Some(StorageOptions::default())),
841            }
842        }
843
844        fn visit_unit<E>(self) -> Result<Self::Value, E>
845        where
846            E: de::Error,
847        {
848            Ok(None)
849        }
850
851        fn visit_none<E>(self) -> Result<Self::Value, E>
852        where
853            E: de::Error,
854        {
855            Ok(None)
856        }
857
858        fn visit_map<M>(self, map: M) -> Result<Option<StorageOptions>, M::Error>
859        where
860            M: MapAccess<'de>,
861        {
862            Deserialize::deserialize(de::value::MapAccessDeserializer::new(map)).map(Some)
863        }
864    }
865
866    deserializer.deserialize_any(BoolOrStruct)
867}
868
869/// Accepts very old 'initial_state' and 'latest_checkpoint' as enabling fault
870/// tolerance.
871///
872/// Accepts `null` as disabling fault tolerance.
873///
874/// Otherwise, deserializes [FtConfig] in the way that one might otherwise
875/// expect.
876fn deserialize_fault_tolerance<'de, D>(deserializer: D) -> Result<FtConfig, D::Error>
877where
878    D: Deserializer<'de>,
879{
880    struct StringOrStruct;
881
882    impl<'de> Visitor<'de> for StringOrStruct {
883        type Value = FtConfig;
884
885        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
886            formatter.write_str("none or FtConfig or 'initial_state' or 'latest_checkpoint'")
887        }
888
889        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
890        where
891            E: de::Error,
892        {
893            match v {
894                "initial_state" | "latest_checkpoint" => Ok(FtConfig {
895                    model: Some(FtModel::default()),
896                    ..FtConfig::default()
897                }),
898                _ => Err(de::Error::invalid_value(de::Unexpected::Str(v), &self)),
899            }
900        }
901
902        fn visit_unit<E>(self) -> Result<Self::Value, E>
903        where
904            E: de::Error,
905        {
906            Ok(FtConfig::default())
907        }
908
909        fn visit_none<E>(self) -> Result<Self::Value, E>
910        where
911            E: de::Error,
912        {
913            Ok(FtConfig::default())
914        }
915
916        fn visit_map<M>(self, map: M) -> Result<FtConfig, M::Error>
917        where
918            M: MapAccess<'de>,
919        {
920            Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))
921        }
922    }
923
924    deserializer.deserialize_any(StringOrStruct)
925}
926
927impl Default for RuntimeConfig {
928    fn default() -> Self {
929        Self {
930            workers: 8,
931            storage: Some(StorageOptions::default()),
932            fault_tolerance: FtConfig::default(),
933            cpu_profiler: true,
934            tracing: {
935                // We discovered that the jaeger crate can use up gigabytes of RAM, so it's not harmless
936                // to keep it on by default.
937                false
938            },
939            tracing_endpoint_jaeger: "127.0.0.1:6831".to_string(),
940            min_batch_size_records: 0,
941            max_buffering_delay_usecs: 0,
942            resources: ResourceConfig::default(),
943            clock_resolution_usecs: { Some(DEFAULT_CLOCK_RESOLUTION_USECS) },
944            pin_cpus: Vec::new(),
945            provisioning_timeout_secs: None,
946            max_parallel_connector_init: None,
947            init_containers: None,
948            checkpoint_during_suspend: true,
949            io_workers: None,
950            http_workers: None,
951            dev_tweaks: BTreeMap::default(),
952            logging: None,
953        }
954    }
955}
956
957/// Fault-tolerance configuration.
958///
959/// The default [FtConfig] (via [FtConfig::default]) disables fault tolerance,
960/// which is the configuration that one gets if [RuntimeConfig] omits fault
961/// tolerance configuration.
962///
963/// The default value for [FtConfig::model] enables fault tolerance, as
964/// `Some(FtModel::default())`.  This is the configuration that one gets if
965/// [RuntimeConfig] includes a fault tolerance configuration but does not
966/// specify a particular model.
967#[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
968#[serde(rename_all = "snake_case")]
969pub struct FtConfig {
970    /// Fault tolerance model to use.
971    #[serde(with = "none_as_string")]
972    #[serde(default = "default_model")]
973    #[schema(
974        schema_with = none_as_string_schema::<FtModel>,
975    )]
976    pub model: Option<FtModel>,
977
978    /// Interval between automatic checkpoints, in seconds.
979    ///
980    /// The default is 60 seconds.  Values less than 1 or greater than 3600 will
981    /// be forced into that range.
982    #[serde(default = "default_checkpoint_interval_secs")]
983    pub checkpoint_interval_secs: Option<u64>,
984}
985
986fn default_model() -> Option<FtModel> {
987    Some(FtModel::default())
988}
989
990pub fn default_checkpoint_interval_secs() -> Option<u64> {
991    Some(60)
992}
993
994impl Default for FtConfig {
995    fn default() -> Self {
996        Self {
997            model: None,
998            checkpoint_interval_secs: default_checkpoint_interval_secs(),
999        }
1000    }
1001}
1002
1003#[cfg(test)]
1004mod test {
1005    use super::deserialize_fault_tolerance;
1006    use crate::config::{FtConfig, FtModel};
1007    use serde::{Deserialize, Serialize};
1008
1009    #[test]
1010    fn ft_config() {
1011        #[derive(Serialize, Deserialize, Default, PartialEq, Eq, Debug)]
1012        #[serde(default)]
1013        struct Wrapper {
1014            #[serde(deserialize_with = "deserialize_fault_tolerance")]
1015            config: FtConfig,
1016        }
1017
1018        // Omitting FtConfig, or specifying null, or specifying model "none", disables fault tolerance.
1019        for s in [
1020            "{}",
1021            r#"{"config": null}"#,
1022            r#"{"config": {"model": "none"}}"#,
1023        ] {
1024            let config: Wrapper = serde_json::from_str(s).unwrap();
1025            assert_eq!(
1026                config,
1027                Wrapper {
1028                    config: FtConfig {
1029                        model: None,
1030                        checkpoint_interval_secs: Some(60)
1031                    }
1032                }
1033            );
1034        }
1035
1036        // Serializing disabled FT produces explicit "none" form.
1037        let s = serde_json::to_string(&Wrapper {
1038            config: FtConfig::default(),
1039        })
1040        .unwrap();
1041        assert!(s.contains("\"none\""));
1042
1043        // `{}` for FtConfig, or `{...}` with `model` omitted, enables fault
1044        // tolerance.
1045        for s in [r#"{"config": {}}"#, r#"{"checkpoint_interval_secs": 60}"#] {
1046            assert_eq!(
1047                serde_json::from_str::<FtConfig>(s).unwrap(),
1048                FtConfig {
1049                    model: Some(FtModel::default()),
1050                    checkpoint_interval_secs: Some(60)
1051                }
1052            );
1053        }
1054
1055        // `"checkpoint_interval_secs": null` disables periodic checkpointing.
1056        assert_eq!(
1057            serde_json::from_str::<FtConfig>(r#"{"checkpoint_interval_secs": null}"#).unwrap(),
1058            FtConfig {
1059                model: Some(FtModel::default()),
1060                checkpoint_interval_secs: None
1061            }
1062        );
1063    }
1064}
1065
1066impl FtConfig {
1067    pub fn is_enabled(&self) -> bool {
1068        self.model.is_some()
1069    }
1070
1071    /// Returns the checkpoint interval, if fault tolerance is enabled, and
1072    /// otherwise `None`.
1073    pub fn checkpoint_interval(&self) -> Option<Duration> {
1074        if self.is_enabled() {
1075            self.checkpoint_interval_secs
1076                .map(|interval| Duration::from_secs(interval.clamp(1, 3600)))
1077        } else {
1078            None
1079        }
1080    }
1081}
1082
1083/// Serde implementation for de/serializing a string into `Option<T>` where
1084/// `"none"` indicates `None` and any other string indicates `Some`.
1085///
1086/// This could be extended to handle non-strings by adding more forwarding
1087/// `visit_*` methods to the Visitor implementation.  I don't see a way to write
1088/// them automatically.
1089mod none_as_string {
1090    use std::marker::PhantomData;
1091
1092    use serde::de::{Deserialize, Deserializer, IntoDeserializer, Visitor};
1093    use serde::ser::{Serialize, Serializer};
1094
1095    pub(super) fn serialize<S, T>(value: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
1096    where
1097        S: Serializer,
1098        T: Serialize,
1099    {
1100        match value.as_ref() {
1101            Some(value) => value.serialize(serializer),
1102            None => "none".serialize(serializer),
1103        }
1104    }
1105
1106    struct NoneAsString<T>(PhantomData<fn() -> T>);
1107
1108    impl<'de, T> Visitor<'de> for NoneAsString<T>
1109    where
1110        T: Deserialize<'de>,
1111    {
1112        type Value = Option<T>;
1113
1114        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
1115            formatter.write_str("string")
1116        }
1117
1118        fn visit_none<E>(self) -> Result<Self::Value, E>
1119        where
1120            E: serde::de::Error,
1121        {
1122            Ok(None)
1123        }
1124
1125        fn visit_str<E>(self, value: &str) -> Result<Option<T>, E>
1126        where
1127            E: serde::de::Error,
1128        {
1129            if &value.to_ascii_lowercase() == "none" {
1130                Ok(None)
1131            } else {
1132                Ok(Some(T::deserialize(value.into_deserializer())?))
1133            }
1134        }
1135    }
1136
1137    pub(super) fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
1138    where
1139        D: Deserializer<'de>,
1140        T: Deserialize<'de>,
1141    {
1142        deserializer.deserialize_str(NoneAsString(PhantomData))
1143    }
1144}
1145
1146/// Generates an OpenAPI schema for an `Option<T>` field serialized with `none_as_string`.
1147/// The schema is a `oneOf` with a reference to `T`'s schema and a `"none"` string enum.
1148fn none_as_string_schema<'a, T: ToSchema<'a> + Default + Serialize>() -> Schema {
1149    Schema::OneOf(
1150        OneOfBuilder::new()
1151            .item(RefOr::Ref(Ref::new(format!(
1152                "#/components/schemas/{}",
1153                T::schema().0
1154            ))))
1155            .item(
1156                ObjectBuilder::new()
1157                    .schema_type(SchemaType::String)
1158                    .enum_values(Some(vec!["none"])),
1159            )
1160            .default(Some(
1161                serde_json::to_value(T::default()).expect("Failed to serialize default value"),
1162            ))
1163            .build(),
1164    )
1165}
1166
1167/// Fault tolerance model.
1168///
1169/// The ordering is significant: we consider [Self::ExactlyOnce] to be a "higher
1170/// level" of fault tolerance than [Self::AtLeastOnce].
1171#[derive(
1172    Debug, Copy, Clone, Default, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize, ToSchema,
1173)]
1174#[serde(rename_all = "snake_case")]
1175pub enum FtModel {
1176    /// Each record is output at least once.  Crashes may duplicate output, but
1177    /// no input or output is dropped.
1178    AtLeastOnce,
1179
1180    /// Each record is output exactly once.  Crashes do not drop or duplicate
1181    /// input or output.
1182    #[default]
1183    ExactlyOnce,
1184}
1185
1186impl FtModel {
1187    pub fn option_as_str(value: Option<FtModel>) -> &'static str {
1188        value.map_or("no", |model| model.as_str())
1189    }
1190
1191    pub fn as_str(&self) -> &'static str {
1192        match self {
1193            FtModel::AtLeastOnce => "at_least_once",
1194            FtModel::ExactlyOnce => "exactly_once",
1195        }
1196    }
1197}
1198
1199pub struct FtModelUnknown;
1200
1201impl FromStr for FtModel {
1202    type Err = FtModelUnknown;
1203
1204    fn from_str(s: &str) -> Result<Self, Self::Err> {
1205        match s.to_ascii_lowercase().as_str() {
1206            "exactly_once" => Ok(Self::ExactlyOnce),
1207            "at_least_once" => Ok(Self::AtLeastOnce),
1208            _ => Err(FtModelUnknown),
1209        }
1210    }
1211}
1212
1213/// Describes an input connector configuration
1214#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1215pub struct InputEndpointConfig {
1216    /// The name of the input stream of the circuit that this endpoint is
1217    /// connected to.
1218    pub stream: Cow<'static, str>,
1219
1220    /// Connector configuration.
1221    #[serde(flatten)]
1222    pub connector_config: ConnectorConfig,
1223}
1224
1225/// Deserialize the `start_after` property of a connector configuration.
1226/// It requires a non-standard deserialization because we want to accept
1227/// either a string or an array of strings.
1228fn deserialize_start_after<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
1229where
1230    D: Deserializer<'de>,
1231{
1232    let value = Option::<JsonValue>::deserialize(deserializer)?;
1233    match value {
1234        Some(JsonValue::String(s)) => Ok(Some(vec![s])),
1235        Some(JsonValue::Array(arr)) => {
1236            let vec = arr
1237                .into_iter()
1238                .map(|item| {
1239                    item.as_str()
1240                        .map(|s| s.to_string())
1241                        .ok_or_else(|| serde::de::Error::custom("invalid 'start_after' property: expected a string, an array of strings, or null"))
1242                })
1243                .collect::<Result<Vec<String>, _>>()?;
1244            Ok(Some(vec))
1245        }
1246        Some(JsonValue::Null) | None => Ok(None),
1247        _ => Err(serde::de::Error::custom(
1248            "invalid 'start_after' property: expected a string, an array of strings, or null",
1249        )),
1250    }
1251}
1252
1253/// A data connector's configuration
1254#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1255pub struct ConnectorConfig {
1256    /// Transport endpoint configuration.
1257    pub transport: TransportConfig,
1258
1259    /// Parser configuration.
1260    pub format: Option<FormatConfig>,
1261
1262    /// Name of the index that the connector is attached to.
1263    ///
1264    /// This property is valid for output connectors only.  It is used with data
1265    /// transports and formats that expect output updates in the form of key/value
1266    /// pairs, where the key typically represents a unique id associated with the
1267    /// table or view.
1268    ///
1269    /// To support such output formats, an output connector can be attached to an
1270    /// index created using the SQL CREATE INDEX statement.  An index of a table
1271    /// or view contains the same updates as the table or view itself, indexed by
1272    /// one or more key columns.
1273    ///
1274    /// See individual connector documentation for details on how they work
1275    /// with indexes.
1276    pub index: Option<String>,
1277
1278    /// Output buffer configuration.
1279    #[serde(flatten)]
1280    pub output_buffer_config: OutputBufferConfig,
1281
1282    /// Maximum batch size, in records.
1283    ///
1284    /// This is the maximum number of records to process in one batch through
1285    /// the circuit.  The time and space cost of processing a batch is
1286    /// asymptotically superlinear in the size of the batch, but very small
1287    /// batches are less efficient due to constant factors.
1288    ///
1289    /// This should usually be less than `max_queued_records`, to give the
1290    /// connector a round-trip time to restart and refill the buffer while
1291    /// batches are being processed.
1292    ///
1293    /// Some input adapters might not honor this setting.
1294    ///
1295    /// The default is 10,000.
1296    #[serde(default = "default_max_batch_size")]
1297    pub max_batch_size: u64,
1298
1299    /// Backpressure threshold.
1300    ///
1301    /// Maximal number of records queued by the endpoint before the endpoint
1302    /// is paused by the backpressure mechanism.
1303    ///
1304    /// For input endpoints, this setting bounds the number of records that have
1305    /// been received from the input transport but haven't yet been consumed by
1306    /// the circuit since the circuit, since the circuit is still busy processing
1307    /// previous inputs.
1308    ///
1309    /// For output endpoints, this setting bounds the number of records that have
1310    /// been produced by the circuit but not yet sent via the output transport endpoint
1311    /// nor stored in the output buffer (see `enable_output_buffer`).
1312    ///
1313    /// Note that this is not a hard bound: there can be a small delay between
1314    /// the backpressure mechanism is triggered and the endpoint is paused, during
1315    /// which more data may be queued.
1316    ///
1317    /// The default is 1 million.
1318    #[serde(default = "default_max_queued_records")]
1319    pub max_queued_records: u64,
1320
1321    /// Create connector in paused state.
1322    ///
1323    /// The default is `false`.
1324    #[serde(default)]
1325    pub paused: bool,
1326
1327    /// Arbitrary user-defined text labels associated with the connector.
1328    ///
1329    /// These labels can be used in conjunction with the `start_after` property
1330    /// to control the start order of connectors.
1331    #[serde(default)]
1332    pub labels: Vec<String>,
1333
1334    /// Start the connector after all connectors with specified labels.
1335    ///
1336    /// This property is used to control the start order of connectors.
1337    /// The connector will not start until all connectors with the specified
1338    /// labels have finished processing all inputs.
1339    #[serde(deserialize_with = "deserialize_start_after")]
1340    #[serde(default)]
1341    pub start_after: Option<Vec<String>>,
1342}
1343
1344impl ConnectorConfig {
1345    /// Compare two configs modulo the `paused` field.
1346    ///
1347    /// Used to compare checkpointed and current connector configs.
1348    pub fn equal_modulo_paused(&self, other: &Self) -> bool {
1349        let mut a = self.clone();
1350        let mut b = other.clone();
1351        a.paused = false;
1352        b.paused = false;
1353        a == b
1354    }
1355}
1356
1357#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1358#[serde(default)]
1359pub struct OutputBufferConfig {
1360    /// Enable output buffering.
1361    ///
1362    /// The output buffering mechanism allows decoupling the rate at which the pipeline
1363    /// pushes changes to the output transport from the rate of input changes.
1364    ///
1365    /// By default, output updates produced by the pipeline are pushed directly to
1366    /// the output transport. Some destinations may prefer to receive updates in fewer
1367    /// bigger batches. For instance, when writing Parquet files, producing
1368    /// one bigger file every few minutes is usually better than creating
1369    /// small files every few milliseconds.
1370    ///
1371    /// To achieve such input/output decoupling, users can enable output buffering by
1372    /// setting the `enable_output_buffer` flag to `true`.  When buffering is enabled, output
1373    /// updates produced by the pipeline are consolidated in an internal buffer and are
1374    /// pushed to the output transport when one of several conditions is satisfied:
1375    ///
1376    /// * data has been accumulated in the buffer for more than `max_output_buffer_time_millis`
1377    ///   milliseconds.
1378    /// * buffer size exceeds `max_output_buffer_size_records` records.
1379    ///
1380    /// This flag is `false` by default.
1381    // TODO: on-demand output triggered via the API.
1382    pub enable_output_buffer: bool,
1383
1384    /// Maximum time in milliseconds data is kept in the output buffer.
1385    ///
1386    /// By default, data is kept in the buffer indefinitely until one of
1387    /// the other output conditions is satisfied.  When this option is
1388    /// set the buffer will be flushed at most every
1389    /// `max_output_buffer_time_millis` milliseconds.
1390    ///
1391    /// NOTE: this configuration option requires the `enable_output_buffer` flag
1392    /// to be set.
1393    pub max_output_buffer_time_millis: usize,
1394
1395    /// Maximum number of updates to be kept in the output buffer.
1396    ///
1397    /// This parameter bounds the maximal size of the buffer.
1398    /// Note that the size of the buffer is not always equal to the
1399    /// total number of updates output by the pipeline. Updates to the
1400    /// same record can overwrite or cancel previous updates.
1401    ///
1402    /// By default, the buffer can grow indefinitely until one of
1403    /// the other output conditions is satisfied.
1404    ///
1405    /// NOTE: this configuration option requires the `enable_output_buffer` flag
1406    /// to be set.
1407    pub max_output_buffer_size_records: usize,
1408}
1409
1410impl Default for OutputBufferConfig {
1411    fn default() -> Self {
1412        Self {
1413            enable_output_buffer: false,
1414            max_output_buffer_size_records: usize::MAX,
1415            max_output_buffer_time_millis: usize::MAX,
1416        }
1417    }
1418}
1419
1420impl OutputBufferConfig {
1421    pub fn validate(&self) -> Result<(), String> {
1422        if self.enable_output_buffer
1423            && self.max_output_buffer_size_records == Self::default().max_output_buffer_size_records
1424            && self.max_output_buffer_time_millis == Self::default().max_output_buffer_time_millis
1425        {
1426            return Err(
1427                "when the 'enable_output_buffer' flag is set, one of 'max_output_buffer_size_records' and 'max_output_buffer_time_millis' settings must be specified"
1428                    .to_string(),
1429            );
1430        }
1431
1432        Ok(())
1433    }
1434}
1435
1436/// Describes an output connector configuration
1437#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1438pub struct OutputEndpointConfig {
1439    /// The name of the output stream of the circuit that this endpoint is
1440    /// connected to.
1441    pub stream: Cow<'static, str>,
1442
1443    /// Connector configuration.
1444    #[serde(flatten)]
1445    pub connector_config: ConnectorConfig,
1446}
1447
1448/// Transport-specific endpoint configuration passed to
1449/// `crate::OutputTransport::new_endpoint`
1450/// and `crate::InputTransport::new_endpoint`.
1451#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1452#[serde(tag = "name", content = "config", rename_all = "snake_case")]
1453pub enum TransportConfig {
1454    FileInput(FileInputConfig),
1455    FileOutput(FileOutputConfig),
1456    NatsInput(NatsInputConfig),
1457    KafkaInput(KafkaInputConfig),
1458    KafkaOutput(KafkaOutputConfig),
1459    PubSubInput(PubSubInputConfig),
1460    UrlInput(UrlInputConfig),
1461    S3Input(S3InputConfig),
1462    DeltaTableInput(DeltaTableReaderConfig),
1463    DeltaTableOutput(DeltaTableWriterConfig),
1464    RedisOutput(RedisOutputConfig),
1465    // Prevent rust from complaining about large size difference between enum variants.
1466    IcebergInput(Box<IcebergReaderConfig>),
1467    PostgresInput(PostgresReaderConfig),
1468    PostgresOutput(PostgresWriterConfig),
1469    Datagen(DatagenInputConfig),
1470    Nexmark(NexmarkInputConfig),
1471    /// Direct HTTP input: cannot be instantiated through API
1472    HttpInput(HttpInputConfig),
1473    /// Direct HTTP output: cannot be instantiated through API
1474    HttpOutput,
1475    /// Ad hoc input: cannot be instantiated through API
1476    AdHocInput(AdHocInputConfig),
1477    ClockInput(ClockConfig),
1478}
1479
1480impl TransportConfig {
1481    pub fn name(&self) -> String {
1482        match self {
1483            TransportConfig::FileInput(_) => "file_input".to_string(),
1484            TransportConfig::FileOutput(_) => "file_output".to_string(),
1485            TransportConfig::NatsInput(_) => "nats_input".to_string(),
1486            TransportConfig::KafkaInput(_) => "kafka_input".to_string(),
1487            TransportConfig::KafkaOutput(_) => "kafka_output".to_string(),
1488            TransportConfig::PubSubInput(_) => "pub_sub_input".to_string(),
1489            TransportConfig::UrlInput(_) => "url_input".to_string(),
1490            TransportConfig::S3Input(_) => "s3_input".to_string(),
1491            TransportConfig::DeltaTableInput(_) => "delta_table_input".to_string(),
1492            TransportConfig::DeltaTableOutput(_) => "delta_table_output".to_string(),
1493            TransportConfig::IcebergInput(_) => "iceberg_input".to_string(),
1494            TransportConfig::PostgresInput(_) => "postgres_input".to_string(),
1495            TransportConfig::PostgresOutput(_) => "postgres_output".to_string(),
1496            TransportConfig::Datagen(_) => "datagen".to_string(),
1497            TransportConfig::Nexmark(_) => "nexmark".to_string(),
1498            TransportConfig::HttpInput(_) => "http_input".to_string(),
1499            TransportConfig::HttpOutput => "http_output".to_string(),
1500            TransportConfig::AdHocInput(_) => "adhoc_input".to_string(),
1501            TransportConfig::RedisOutput(_) => "redis_output".to_string(),
1502            TransportConfig::ClockInput(_) => "clock".to_string(),
1503        }
1504    }
1505
1506    /// Returns true if the connector is transient, i.e., is created and destroyed
1507    /// at runtime on demand, rather than being configured as part of the pipeline.
1508    pub fn is_transient(&self) -> bool {
1509        matches!(
1510            self,
1511            TransportConfig::AdHocInput(_)
1512                | TransportConfig::HttpInput(_)
1513                | TransportConfig::HttpOutput
1514                | TransportConfig::ClockInput(_)
1515        )
1516    }
1517}
1518
1519/// Data format specification used to parse raw data received from the
1520/// endpoint or to encode data sent to the endpoint.
1521#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, ToSchema)]
1522pub struct FormatConfig {
1523    /// Format name, e.g., "csv", "json", "bincode", etc.
1524    pub name: Cow<'static, str>,
1525
1526    /// Format-specific parser or encoder configuration.
1527    #[serde(default)]
1528    #[schema(value_type = Object)]
1529    pub config: JsonValue,
1530}
1531
1532#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
1533#[serde(default)]
1534pub struct ResourceConfig {
1535    /// The minimum number of CPU cores to reserve
1536    /// for an instance of this pipeline
1537    #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
1538    pub cpu_cores_min: Option<f64>,
1539
1540    /// The maximum number of CPU cores to reserve
1541    /// for an instance of this pipeline
1542    #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
1543    pub cpu_cores_max: Option<f64>,
1544
1545    /// The minimum memory in Megabytes to reserve
1546    /// for an instance of this pipeline
1547    pub memory_mb_min: Option<u64>,
1548
1549    /// The maximum memory in Megabytes to reserve
1550    /// for an instance of this pipeline
1551    pub memory_mb_max: Option<u64>,
1552
1553    /// The total storage in Megabytes to reserve
1554    /// for an instance of this pipeline
1555    pub storage_mb_max: Option<u64>,
1556
1557    /// Storage class to use for an instance of this pipeline.
1558    /// The class determines storage performance such as IOPS and throughput.
1559    pub storage_class: Option<String>,
1560
1561    /// Kubernetes service account name to use for an instance of this pipeline.
1562    /// The account determines permissions and access controls.
1563    pub service_account_name: Option<String>,
1564
1565    /// Kubernetes namespace to use for an instance of this pipeline.
1566    /// The namespace determines the scope of names for resources created
1567    /// for the pipeline.
1568    /// If not set, the pipeline will be deployed in the same namespace
1569    /// as the control-plane.
1570    pub namespace: Option<String>,
1571}