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::transport::adhoc::AdHocInputConfig;
9use crate::transport::datagen::DatagenInputConfig;
10use crate::transport::delta_table::{DeltaTableReaderConfig, DeltaTableWriterConfig};
11use crate::transport::file::{FileInputConfig, FileOutputConfig};
12use crate::transport::http::HttpInputConfig;
13use crate::transport::iceberg::IcebergReaderConfig;
14use crate::transport::kafka::{KafkaInputConfig, KafkaOutputConfig};
15use crate::transport::nexmark::NexmarkInputConfig;
16use crate::transport::postgres::PostgresReaderConfig;
17use crate::transport::pubsub::PubSubInputConfig;
18use crate::transport::redis::RedisOutputConfig;
19use crate::transport::s3::S3InputConfig;
20use crate::transport::url::UrlInputConfig;
21use core::fmt;
22use serde::de::{self, MapAccess, Visitor};
23use serde::{Deserialize, Deserializer, Serialize};
24use serde_json::Value as JsonValue;
25use serde_yaml::Value as YamlValue;
26use std::fmt::Display;
27use std::path::Path;
28use std::{borrow::Cow, cmp::max, collections::BTreeMap};
29use utoipa::ToSchema;
30
31const DEFAULT_MAX_PARALLEL_CONNECTOR_INIT: u64 = 10;
32
33/// Default value of `ConnectorConfig::max_queued_records`.
34pub const fn default_max_queued_records() -> u64 {
35    1_000_000
36}
37
38/// Default maximum batch size for connectors, in records.
39///
40/// If you change this then update the comment on
41/// [ConnectorConfig::max_batch_size].
42pub const fn default_max_batch_size() -> u64 {
43    10_000
44}
45
46/// Pipeline deployment configuration.
47/// It represents configuration entries directly provided by the user
48/// (e.g., runtime configuration) and entries derived from the schema
49/// of the compiled program (e.g., connectors). Storage configuration,
50/// if applicable, is set by the runner.
51#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
52pub struct PipelineConfig {
53    /// Global controller configuration.
54    #[serde(flatten)]
55    #[schema(inline)]
56    pub global: RuntimeConfig,
57
58    /// Pipeline name.
59    pub name: Option<String>,
60
61    /// Configuration for persistent storage
62    ///
63    /// If `global.storage` is `true`, this field must be set to some
64    /// [`StorageConfig`].  If `global.storage` is `false`, the pipeline ignores
65    /// this field.
66    #[serde(default)]
67    pub storage_config: Option<StorageConfig>,
68
69    /// Input endpoint configuration.
70    pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
71
72    /// Output endpoint configuration.
73    #[serde(default)]
74    pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
75}
76
77impl PipelineConfig {
78    pub fn max_parallel_connector_init(&self) -> u64 {
79        max(
80            self.global
81                .max_parallel_connector_init
82                .unwrap_or(DEFAULT_MAX_PARALLEL_CONNECTOR_INIT),
83            1,
84        )
85    }
86
87    pub fn with_storage(self, storage: Option<(StorageConfig, StorageOptions)>) -> Self {
88        let (storage_config, storage_options) = storage.unzip();
89        Self {
90            global: RuntimeConfig {
91                storage: storage_options,
92                ..self.global
93            },
94            storage_config,
95            ..self
96        }
97    }
98}
99
100/// Configuration for persistent storage in a [`PipelineConfig`].
101#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
102pub struct StorageConfig {
103    /// A directory to keep pipeline state, as a path on the filesystem of the
104    /// machine or container where the pipeline will run.
105    ///
106    /// When storage is enabled, this directory stores the data for
107    /// [StorageBackendConfig::Default].
108    ///
109    /// When fault tolerance is enabled, this directory stores checkpoints and
110    /// the log.
111    pub path: String,
112
113    /// How to cache access to storage in this pipeline.
114    #[serde(default)]
115    pub cache: StorageCacheConfig,
116}
117
118impl StorageConfig {
119    pub fn path(&self) -> &Path {
120        Path::new(&self.path)
121    }
122}
123
124/// How to cache access to storage within a Feldera pipeline.
125#[derive(Copy, Clone, Default, Deserialize, Serialize, Debug, PartialEq, Eq, ToSchema)]
126#[serde(rename_all = "snake_case")]
127pub enum StorageCacheConfig {
128    /// Use the operating system's page cache as the primary storage cache.
129    ///
130    /// This is the default because it currently performs better than
131    /// `FelderaCache`.
132    #[default]
133    PageCache,
134
135    /// Use Feldera's internal cache implementation.
136    ///
137    /// This is under development. It will become the default when its
138    /// performance exceeds that of `PageCache`.
139    FelderaCache,
140}
141
142impl StorageCacheConfig {
143    #[cfg(unix)]
144    pub fn to_custom_open_flags(&self) -> i32 {
145        match self {
146            StorageCacheConfig::PageCache => (),
147            StorageCacheConfig::FelderaCache => {
148                #[cfg(target_os = "linux")]
149                return libc::O_DIRECT;
150            }
151        }
152        0
153    }
154}
155
156/// Storage configuration for a pipeline.
157#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
158#[serde(default)]
159pub struct StorageOptions {
160    /// How to connect to the underlying storage.
161    pub backend: StorageBackendConfig,
162
163    /// The minimum estimated number of bytes in a batch of data to write it to
164    /// storage.  This is provided for debugging and fine-tuning and should
165    /// ordinarily be left unset.
166    ///
167    /// A value of 0 will write even empty batches to storage, and nonzero
168    /// values provide a threshold.  `usize::MAX` would effectively disable
169    /// storage.
170    ///
171    /// The default is 1,048,576 (1 MiB).
172    pub min_storage_bytes: Option<usize>,
173
174    /// The form of compression to use in data batches.
175    ///
176    /// Compression has a CPU cost but it can take better advantage of limited
177    /// NVMe and network bandwidth, which means that it can increase overall
178    /// performance.
179    pub compression: StorageCompression,
180
181    /// The maximum size of the in-memory storage cache, in MiB.
182    ///
183    /// If set, the specified cache size is spread across all the foreground and
184    /// background threads. If unset, each foreground or background thread cache
185    /// is limited to 256 MiB.
186    pub cache_mib: Option<usize>,
187}
188
189/// Backend storage configuration.
190#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
191#[serde(tag = "name", content = "config", rename_all = "snake_case")]
192pub enum StorageBackendConfig {
193    /// Use the default storage configuration.
194    ///
195    /// This currently uses the local file system.
196    #[default]
197    Default,
198
199    /// Object storage.
200    Object(ObjectStorageConfig),
201}
202
203impl Display for StorageBackendConfig {
204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205        match self {
206            StorageBackendConfig::Default => write!(f, "default"),
207            StorageBackendConfig::Object(_) => write!(f, "object"),
208        }
209    }
210}
211
212/// Storage compression algorithm.
213#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
214#[serde(rename_all = "snake_case")]
215pub enum StorageCompression {
216    /// Use Feldera's default compression algorithm.
217    ///
218    /// The default may change as Feldera's performance is tuned and new
219    /// algorithms are introduced.
220    #[default]
221    Default,
222
223    /// Do not compress.
224    None,
225
226    /// Use [Snappy](https://en.wikipedia.org/wiki/Snappy_(compression)) compression.
227    Snappy,
228}
229
230#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
231pub struct ObjectStorageConfig {
232    /// URL.
233    ///
234    /// The following URL schemes are supported:
235    ///
236    /// * S3:
237    ///   - `s3://<bucket>/<path>`
238    ///   - `s3a://<bucket>/<path>`
239    ///   - `https://s3.<region>.amazonaws.com/<bucket>`
240    ///   - `https://<bucket>.s3.<region>.amazonaws.com`
241    ///   - `https://ACCOUNT_ID.r2.cloudflarestorage.com/bucket`
242    /// * Google Cloud Storage:
243    ///   - `gs://<bucket>/<path>`
244    /// * Microsoft Azure Blob Storage:
245    ///   - `abfs[s]://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
246    ///   - `abfs[s]://<file_system>@<account_name>.dfs.core.windows.net/<path>`
247    ///   - `abfs[s]://<file_system>@<account_name>.dfs.fabric.microsoft.com/<path>`
248    ///   - `az://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
249    ///   - `adl://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
250    ///   - `azure://<container>/<path>` (custom)
251    ///   - `https://<account>.dfs.core.windows.net`
252    ///   - `https://<account>.blob.core.windows.net`
253    ///   - `https://<account>.blob.core.windows.net/<container>`
254    ///   - `https://<account>.dfs.fabric.microsoft.com`
255    ///   - `https://<account>.dfs.fabric.microsoft.com/<container>`
256    ///   - `https://<account>.blob.fabric.microsoft.com`
257    ///   - `https://<account>.blob.fabric.microsoft.com/<container>`
258    ///
259    /// Settings derived from the URL will override other settings.
260    pub url: String,
261
262    /// Additional options as key-value pairs.
263    ///
264    /// The following keys are supported:
265    ///
266    /// * S3:
267    ///   - `access_key_id`: AWS Access Key.
268    ///   - `secret_access_key`: AWS Secret Access Key.
269    ///   - `region`: Region.
270    ///   - `default_region`: Default region.
271    ///   - `endpoint`: Custom endpoint for communicating with S3,
272    ///     e.g. `https://localhost:4566` for testing against a localstack
273    ///     instance.
274    ///   - `token`: Token to use for requests (passed to underlying provider).
275    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/aws/enum.AmazonS3ConfigKey.html#variants).
276    /// * Google Cloud Storage:
277    ///   - `service_account`: Path to the service account file.
278    ///   - `service_account_key`: The serialized service account key.
279    ///   - `google_application_credentials`: Application credentials path.
280    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/gcp/enum.GoogleConfigKey.html).
281    /// * Microsoft Azure Blob Storage:
282    ///   - `access_key`: Azure Access Key.
283    ///   - `container_name`: Azure Container Name.
284    ///   - `account`: Azure Account.
285    ///   - `bearer_token_authorization`: Static bearer token for authorizing requests.
286    ///   - `client_id`: Client ID for use in client secret or Kubernetes federated credential flow.
287    ///   - `client_secret`: Client secret for use in client secret flow.
288    ///   - `tenant_id`: Tenant ID for use in client secret or Kubernetes federated credential flow.
289    ///   - `endpoint`: Override the endpoint for communicating with blob storage.
290    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/azure/enum.AzureConfigKey.html#variants).
291    ///
292    /// Options set through the URL take precedence over those set with these
293    /// options.
294    #[serde(flatten)]
295    pub other_options: BTreeMap<String, String>,
296}
297
298/// Global pipeline configuration settings. This is the publicly
299/// exposed type for users to configure pipelines.
300#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
301#[serde(default)]
302pub struct RuntimeConfig {
303    /// Number of DBSP worker threads.
304    ///
305    /// Each DBSP "foreground" worker thread is paired with a "background"
306    /// thread for LSM merging, making the total number of threads twice the
307    /// specified number.
308    pub workers: u16,
309
310    /// Storage configuration.
311    ///
312    /// - If this is `None`, the default, the pipeline's state is kept in
313    ///   in-memory data-structures.  This is useful if the pipeline's state
314    ///   will fit in memory and if the pipeline is ephemeral and does not need
315    ///   to be recovered after a restart. The pipeline will most likely run
316    ///   faster since it does not need to access storage.
317    ///
318    /// - If set, the pipeline's state is kept on storage.  This allows the
319    ///   pipeline to work with state that will not fit into memory. It also
320    ///   allows the state to be checkpointed and recovered across restarts.
321    #[serde(deserialize_with = "deserialize_storage_options")]
322    pub storage: Option<StorageOptions>,
323
324    /// Configures fault tolerance with the specified start up behavior. Fault
325    /// tolerance is disabled if this or `storage` is `None`.
326    #[serde(deserialize_with = "deserialize_fault_tolerance")]
327    pub fault_tolerance: Option<FtConfig>,
328
329    /// Enable CPU profiler.
330    ///
331    /// The default value is `true`.
332    pub cpu_profiler: bool,
333
334    /// Enable pipeline tracing.
335    pub tracing: bool,
336
337    /// Jaeger tracing endpoint to send tracing information to.
338    pub tracing_endpoint_jaeger: String,
339
340    /// Minimal input batch size.
341    ///
342    /// The controller delays pushing input records to the circuit until at
343    /// least `min_batch_size_records` records have been received (total
344    /// across all endpoints) or `max_buffering_delay_usecs` microseconds
345    /// have passed since at least one input records has been buffered.
346    /// Defaults to 0.
347    pub min_batch_size_records: u64,
348
349    /// Maximal delay in microseconds to wait for `min_batch_size_records` to
350    /// get buffered by the controller, defaults to 0.
351    pub max_buffering_delay_usecs: u64,
352
353    /// Resource reservations and limits. This is enforced
354    /// only in Feldera Cloud.
355    pub resources: ResourceConfig,
356
357    /// Real-time clock resolution in microseconds.
358    ///
359    /// This parameter controls the execution of queries that use the `NOW()` function.  The output of such
360    /// queries depends on the real-time clock and can change over time without any external
361    /// inputs.  The pipeline will update the clock value and trigger incremental recomputation
362    /// at most each `clock_resolution_usecs` microseconds.
363    ///
364    /// It is set to 100 milliseconds (100,000 microseconds) by default.
365    ///
366    /// Set to `null` to disable periodic clock updates.
367    pub clock_resolution_usecs: Option<u64>,
368
369    /// Optionally, a list of CPU numbers for CPUs to which the pipeline may pin
370    /// its worker threads.  Specify at least twice as many CPU numbers as
371    /// workers.  CPUs are generally numbered starting from 0.  The pipeline
372    /// might not be able to honor CPU pinning requests.
373    ///
374    /// CPU pinning can make pipelines run faster and perform more consistently,
375    /// as long as different pipelines running on the same machine are pinned to
376    /// different CPUs.
377    pub pin_cpus: Vec<usize>,
378
379    /// Timeout in seconds for the `Provisioning` phase of the pipeline.
380    /// Setting this value will override the default of the runner.
381    pub provisioning_timeout_secs: Option<u64>,
382
383    /// The maximum number of connectors initialized in parallel during pipeline
384    /// startup.
385    ///
386    /// At startup, the pipeline must initialize all of its input and output connectors.
387    /// Depending on the number and types of connectors, this can take a long time.
388    /// To accelerate the process, multiple connectors are initialized concurrently.
389    /// This option controls the maximum number of connectors that can be intitialized
390    /// in parallel.
391    ///
392    /// The default is 10.
393    pub max_parallel_connector_init: Option<u64>,
394}
395
396/// Accepts "true" and "false" and converts them to the new format.
397fn deserialize_storage_options<'de, D>(deserializer: D) -> Result<Option<StorageOptions>, D::Error>
398where
399    D: Deserializer<'de>,
400{
401    struct BoolOrStruct;
402
403    impl<'de> Visitor<'de> for BoolOrStruct {
404        type Value = Option<StorageOptions>;
405
406        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
407            formatter.write_str("boolean or StorageOptions")
408        }
409
410        fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
411        where
412            E: de::Error,
413        {
414            match v {
415                false => Ok(None),
416                true => Ok(Some(StorageOptions::default())),
417            }
418        }
419
420        fn visit_unit<E>(self) -> Result<Self::Value, E>
421        where
422            E: de::Error,
423        {
424            Ok(None)
425        }
426
427        fn visit_none<E>(self) -> Result<Self::Value, E>
428        where
429            E: de::Error,
430        {
431            Ok(None)
432        }
433
434        fn visit_map<M>(self, map: M) -> Result<Option<StorageOptions>, M::Error>
435        where
436            M: MapAccess<'de>,
437        {
438            Deserialize::deserialize(de::value::MapAccessDeserializer::new(map)).map(Some)
439        }
440    }
441
442    deserializer.deserialize_any(BoolOrStruct)
443}
444
445/// Accepts old 'initial_state' and 'latest_checkpoint' and converts them to the
446/// new format.
447fn deserialize_fault_tolerance<'de, D>(deserializer: D) -> Result<Option<FtConfig>, D::Error>
448where
449    D: Deserializer<'de>,
450{
451    struct StringOrStruct;
452
453    impl<'de> Visitor<'de> for StringOrStruct {
454        type Value = Option<FtConfig>;
455
456        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
457            formatter.write_str("none or FtConfig or 'initial_state' or 'latest_checkpoint'")
458        }
459
460        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
461        where
462            E: de::Error,
463        {
464            match v {
465                "initial_state" | "latest_checkpoint" => Ok(Some(FtConfig::default())),
466                _ => Err(de::Error::invalid_value(de::Unexpected::Str(v), &self)),
467            }
468        }
469
470        fn visit_unit<E>(self) -> Result<Self::Value, E>
471        where
472            E: de::Error,
473        {
474            Ok(None)
475        }
476
477        fn visit_none<E>(self) -> Result<Self::Value, E>
478        where
479            E: de::Error,
480        {
481            Ok(None)
482        }
483
484        fn visit_map<M>(self, map: M) -> Result<Option<FtConfig>, M::Error>
485        where
486            M: MapAccess<'de>,
487        {
488            Deserialize::deserialize(de::value::MapAccessDeserializer::new(map)).map(Some)
489        }
490    }
491
492    deserializer.deserialize_any(StringOrStruct)
493}
494
495impl Default for RuntimeConfig {
496    fn default() -> Self {
497        Self {
498            workers: 8,
499            storage: None,
500            fault_tolerance: None,
501            cpu_profiler: true,
502            tracing: {
503                // We discovered that the jaeger crate can use up gigabytes of RAM, so it's not harmless
504                // to keep it on by default.
505                false
506            },
507            tracing_endpoint_jaeger: "127.0.0.1:6831".to_string(),
508            min_batch_size_records: 0,
509            max_buffering_delay_usecs: 0,
510            resources: ResourceConfig::default(),
511            clock_resolution_usecs: {
512                // Every 100 ms.
513                Some(100_000)
514            },
515            pin_cpus: Vec::new(),
516            provisioning_timeout_secs: None,
517            max_parallel_connector_init: None,
518        }
519    }
520}
521
522/// Fault-tolerance configuration for runtime startup.
523#[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
524#[serde(default)]
525#[serde(rename_all = "snake_case")]
526pub struct FtConfig {
527    /// Interval between automatic checkpoints, in seconds.
528    ///
529    /// The default is 60 seconds.  A value of 0 disables automatic
530    /// checkpointing.
531    pub checkpoint_interval_secs: u64,
532}
533
534impl Default for FtConfig {
535    fn default() -> Self {
536        Self {
537            checkpoint_interval_secs: 60,
538        }
539    }
540}
541
542/// Describes an input connector configuration
543#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
544pub struct InputEndpointConfig {
545    /// The name of the input stream of the circuit that this endpoint is
546    /// connected to.
547    pub stream: Cow<'static, str>,
548
549    /// Connector configuration.
550    #[serde(flatten)]
551    pub connector_config: ConnectorConfig,
552}
553
554/// Deserialize the `start_after` property of a connector configuration.
555/// It requires a non-standard deserialization because we want to accept
556/// either a string or an array of strings.
557fn deserialize_start_after<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
558where
559    D: Deserializer<'de>,
560{
561    let value = Option::<JsonValue>::deserialize(deserializer)?;
562    match value {
563        Some(JsonValue::String(s)) => Ok(Some(vec![s])),
564        Some(JsonValue::Array(arr)) => {
565            let vec = arr
566                .into_iter()
567                .map(|item| {
568                    item.as_str()
569                        .map(|s| s.to_string())
570                        .ok_or_else(|| serde::de::Error::custom("invalid 'start_after' property: expected a string, an array of strings, or null"))
571                })
572                .collect::<Result<Vec<String>, _>>()?;
573            Ok(Some(vec))
574        }
575        Some(JsonValue::Null) | None => Ok(None),
576        _ => Err(serde::de::Error::custom(
577            "invalid 'start_after' property: expected a string, an array of strings, or null",
578        )),
579    }
580}
581
582/// A data connector's configuration
583#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
584pub struct ConnectorConfig {
585    /// Transport endpoint configuration.
586    pub transport: TransportConfig,
587
588    /// Parser configuration.
589    pub format: Option<FormatConfig>,
590
591    /// Name of the index that the connector is attached to.
592    ///
593    /// This property is valid for output connectors only.  It is used with data
594    /// transports and formats that expect output updates in the form of key/value
595    /// pairs, where the key typically represents a unique id associated with the
596    /// table or view.
597    ///
598    /// To support such output formats, an output connector can be attached to an
599    /// index created using the SQL CREATE INDEX statement.  An index of a table
600    /// or view contains the same updates as the table or view itself, indexed by
601    /// one or more key columns.
602    ///
603    /// See individual connector documentation for details on how they work
604    /// with indexes.
605    pub index: Option<String>,
606
607    /// Output buffer configuration.
608    #[serde(flatten)]
609    pub output_buffer_config: OutputBufferConfig,
610
611    /// Maximum batch size, in records.
612    ///
613    /// This is the maximum number of records to process in one batch through
614    /// the circuit.  The time and space cost of processing a batch is
615    /// asymptotically superlinear in the size of the batch, but very small
616    /// batches are less efficient due to constant factors.
617    ///
618    /// This should usually be less than `max_queued_records`, to give the
619    /// connector a round-trip time to restart and refill the buffer while
620    /// batches are being processed.
621    ///
622    /// Some input adapters might not honor this setting.
623    ///
624    /// The default is 10,000.
625    #[serde(default = "default_max_batch_size")]
626    pub max_batch_size: u64,
627
628    /// Backpressure threshold.
629    ///
630    /// Maximal number of records queued by the endpoint before the endpoint
631    /// is paused by the backpressure mechanism.
632    ///
633    /// For input endpoints, this setting bounds the number of records that have
634    /// been received from the input transport but haven't yet been consumed by
635    /// the circuit since the circuit, since the circuit is still busy processing
636    /// previous inputs.
637    ///
638    /// For output endpoints, this setting bounds the number of records that have
639    /// been produced by the circuit but not yet sent via the output transport endpoint
640    /// nor stored in the output buffer (see `enable_output_buffer`).
641    ///
642    /// Note that this is not a hard bound: there can be a small delay between
643    /// the backpressure mechanism is triggered and the endpoint is paused, during
644    /// which more data may be queued.
645    ///
646    /// The default is 1 million.
647    #[serde(default = "default_max_queued_records")]
648    pub max_queued_records: u64,
649
650    /// Create connector in paused state.
651    ///
652    /// The default is `false`.
653    #[serde(default)]
654    pub paused: bool,
655
656    /// Arbitrary user-defined text labels associated with the connector.
657    ///
658    /// These labels can be used in conjunction with the `start_after` property
659    /// to control the start order of connectors.
660    #[serde(default)]
661    pub labels: Vec<String>,
662
663    /// Start the connector after all connectors with specified labels.
664    ///
665    /// This property is used to control the start order of connectors.
666    /// The connector will not start until all connectors with the specified
667    /// labels have finished processing all inputs.
668    #[serde(deserialize_with = "deserialize_start_after")]
669    #[serde(default)]
670    pub start_after: Option<Vec<String>>,
671}
672
673#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
674#[serde(default)]
675pub struct OutputBufferConfig {
676    /// Enable output buffering.
677    ///
678    /// The output buffering mechanism allows decoupling the rate at which the pipeline
679    /// pushes changes to the output transport from the rate of input changes.
680    ///
681    /// By default, output updates produced by the pipeline are pushed directly to
682    /// the output transport. Some destinations may prefer to receive updates in fewer
683    /// bigger batches. For instance, when writing Parquet files, producing
684    /// one bigger file every few minutes is usually better than creating
685    /// small files every few milliseconds.
686    ///
687    /// To achieve such input/output decoupling, users can enable output buffering by
688    /// setting the `enable_output_buffer` flag to `true`.  When buffering is enabled, output
689    /// updates produced by the pipeline are consolidated in an internal buffer and are
690    /// pushed to the output transport when one of several conditions is satisfied:
691    ///
692    /// * data has been accumulated in the buffer for more than `max_output_buffer_time_millis`
693    ///   milliseconds.
694    /// * buffer size exceeds `max_output_buffer_size_records` records.
695    ///
696    /// This flag is `false` by default.
697    // TODO: on-demand output triggered via the API.
698    pub enable_output_buffer: bool,
699
700    /// Maximum time in milliseconds data is kept in the output buffer.
701    ///
702    /// By default, data is kept in the buffer indefinitely until one of
703    /// the other output conditions is satisfied.  When this option is
704    /// set the buffer will be flushed at most every
705    /// `max_output_buffer_time_millis` milliseconds.
706    ///
707    /// NOTE: this configuration option requires the `enable_output_buffer` flag
708    /// to be set.
709    pub max_output_buffer_time_millis: usize,
710
711    /// Maximum number of updates to be kept in the output buffer.
712    ///
713    /// This parameter bounds the maximal size of the buffer.
714    /// Note that the size of the buffer is not always equal to the
715    /// total number of updates output by the pipeline. Updates to the
716    /// same record can overwrite or cancel previous updates.
717    ///
718    /// By default, the buffer can grow indefinitely until one of
719    /// the other output conditions is satisfied.
720    ///
721    /// NOTE: this configuration option requires the `enable_output_buffer` flag
722    /// to be set.
723    pub max_output_buffer_size_records: usize,
724}
725
726impl Default for OutputBufferConfig {
727    fn default() -> Self {
728        Self {
729            enable_output_buffer: false,
730            max_output_buffer_size_records: usize::MAX,
731            max_output_buffer_time_millis: usize::MAX,
732        }
733    }
734}
735
736impl OutputBufferConfig {
737    pub fn validate(&self) -> Result<(), String> {
738        if self.enable_output_buffer
739            && self.max_output_buffer_size_records == Self::default().max_output_buffer_size_records
740            && self.max_output_buffer_time_millis == Self::default().max_output_buffer_time_millis
741        {
742            return Err(
743                "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"
744                    .to_string(),
745            );
746        }
747
748        Ok(())
749    }
750}
751
752/// Describes an output connector configuration
753#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
754pub struct OutputEndpointConfig {
755    /// The name of the output stream of the circuit that this endpoint is
756    /// connected to.
757    pub stream: Cow<'static, str>,
758
759    /// Connector configuration.
760    #[serde(flatten)]
761    pub connector_config: ConnectorConfig,
762}
763
764/// Transport-specific endpoint configuration passed to
765/// `crate::OutputTransport::new_endpoint`
766/// and `crate::InputTransport::new_endpoint`.
767#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
768#[serde(tag = "name", content = "config", rename_all = "snake_case")]
769pub enum TransportConfig {
770    FileInput(FileInputConfig),
771    FileOutput(FileOutputConfig),
772    KafkaInput(KafkaInputConfig),
773    KafkaOutput(KafkaOutputConfig),
774    PubSubInput(PubSubInputConfig),
775    UrlInput(UrlInputConfig),
776    S3Input(S3InputConfig),
777    DeltaTableInput(DeltaTableReaderConfig),
778    DeltaTableOutput(DeltaTableWriterConfig),
779    RedisOutput(RedisOutputConfig),
780    // Prevent rust from complaining about large size difference between enum variants.
781    IcebergInput(Box<IcebergReaderConfig>),
782    PostgresInput(PostgresReaderConfig),
783    Datagen(DatagenInputConfig),
784    Nexmark(NexmarkInputConfig),
785    /// Direct HTTP input: cannot be instantiated through API
786    HttpInput(HttpInputConfig),
787    /// Direct HTTP output: cannot be instantiated through API
788    HttpOutput,
789    /// Ad hoc input: cannot be instantiated through API
790    AdHocInput(AdHocInputConfig),
791}
792
793impl TransportConfig {
794    pub fn name(&self) -> String {
795        match self {
796            TransportConfig::FileInput(_) => "file_input".to_string(),
797            TransportConfig::FileOutput(_) => "file_output".to_string(),
798            TransportConfig::KafkaInput(_) => "kafka_input".to_string(),
799            TransportConfig::KafkaOutput(_) => "kafka_output".to_string(),
800            TransportConfig::PubSubInput(_) => "pub_sub_input".to_string(),
801            TransportConfig::UrlInput(_) => "url_input".to_string(),
802            TransportConfig::S3Input(_) => "s3_input".to_string(),
803            TransportConfig::DeltaTableInput(_) => "delta_table_input".to_string(),
804            TransportConfig::DeltaTableOutput(_) => "delta_table_output".to_string(),
805            TransportConfig::IcebergInput(_) => "iceberg_input".to_string(),
806            TransportConfig::PostgresInput(_) => "postgres_input".to_string(),
807            TransportConfig::Datagen(_) => "datagen".to_string(),
808            TransportConfig::Nexmark(_) => "nexmark".to_string(),
809            TransportConfig::HttpInput(_) => "http_input".to_string(),
810            TransportConfig::HttpOutput => "http_output".to_string(),
811            TransportConfig::AdHocInput(_) => "adhoc_input".to_string(),
812            TransportConfig::RedisOutput(_) => "redis_output".to_string(),
813        }
814    }
815}
816
817/// Data format specification used to parse raw data received from the
818/// endpoint or to encode data sent to the endpoint.
819#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, ToSchema)]
820pub struct FormatConfig {
821    /// Format name, e.g., "csv", "json", "bincode", etc.
822    pub name: Cow<'static, str>,
823
824    /// Format-specific parser or encoder configuration.
825    #[serde(default)]
826    #[schema(value_type = Object)]
827    pub config: YamlValue,
828}
829
830#[derive(Debug, Clone, Eq, PartialEq, Default, Serialize, Deserialize, ToSchema)]
831#[serde(default)]
832pub struct ResourceConfig {
833    /// The minimum number of CPU cores to reserve
834    /// for an instance of this pipeline
835    pub cpu_cores_min: Option<u64>,
836
837    /// The maximum number of CPU cores to reserve
838    /// for an instance of this pipeline
839    pub cpu_cores_max: Option<u64>,
840
841    /// The minimum memory in Megabytes to reserve
842    /// for an instance of this pipeline
843    pub memory_mb_min: Option<u64>,
844
845    /// The maximum memory in Megabytes to reserve
846    /// for an instance of this pipeline
847    pub memory_mb_max: Option<u64>,
848
849    /// The total storage in Megabytes to reserve
850    /// for an instance of this pipeline
851    pub storage_mb_max: Option<u64>,
852
853    /// Storage class to use for an instance of this pipeline.
854    /// The class determines storage performance such as IOPS and throughput.
855    pub storage_class: Option<String>,
856}