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