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