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