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