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