Skip to main content

risingwave_connector/sink/file_sink/
fs.rs

1// Copyright 2024 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::{BTreeMap, HashMap};
16
17use anyhow::anyhow;
18use opendal::Operator;
19use opendal::layers::{LoggingLayer, RetryLayer};
20use opendal::services::Fs;
21use serde::Deserialize;
22use serde_with::serde_as;
23use with_options::WithOptions;
24
25use super::opendal_sink::BatchingStrategy;
26use crate::sink::file_sink::opendal_sink::{FileSink, OpendalSinkBackend};
27use crate::sink::{Result, SINK_TYPE_APPEND_ONLY, SINK_TYPE_OPTION, SINK_TYPE_UPSERT, SinkError};
28use crate::source::UnknownFields;
29
30#[derive(Deserialize, Debug, Clone, WithOptions)]
31pub struct FsCommon {
32    /// The directory where the sink file is located.
33    #[serde(rename = "fs.path")]
34    pub path: String,
35}
36
37#[serde_as]
38#[derive(Clone, Debug, Deserialize, WithOptions)]
39pub struct FsConfig {
40    #[serde(flatten)]
41    pub common: FsCommon,
42    #[serde(flatten)]
43    pub batching_strategy: BatchingStrategy,
44
45    pub r#type: String, // accept "append-only"
46
47    #[serde(flatten)]
48    pub unknown_fields: HashMap<String, String>,
49}
50
51impl UnknownFields for FsConfig {
52    fn unknown_fields(&self) -> HashMap<String, String> {
53        self.unknown_fields.clone()
54    }
55}
56
57crate::impl_sink_unknown_fields!(FsConfig);
58
59pub const FS_SINK: &str = "fs";
60
61impl<S: OpendalSinkBackend> FileSink<S> {
62    pub fn new_fs_sink(config: FsConfig) -> Result<Operator> {
63        // Create fs builder.
64        let builder = Fs::default().root(&config.common.path);
65        let operator: Operator = Operator::new(builder)?
66            .layer(LoggingLayer::default())
67            .layer(RetryLayer::default())
68            .finish();
69        Ok(operator)
70    }
71}
72
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub struct FsSink;
75
76impl OpendalSinkBackend for FsSink {
77    type Properties = FsConfig;
78
79    const SINK_NAME: &'static str = FS_SINK;
80
81    fn from_btreemap(btree_map: BTreeMap<String, String>) -> Result<Self::Properties> {
82        let config = serde_json::from_value::<FsConfig>(serde_json::to_value(btree_map).unwrap())
83            .map_err(|e| SinkError::Config(anyhow!(e)))?;
84        if config.r#type != SINK_TYPE_APPEND_ONLY && config.r#type != SINK_TYPE_UPSERT {
85            return Err(SinkError::Config(anyhow!(
86                "`{}` must be {}, or {}",
87                SINK_TYPE_OPTION,
88                SINK_TYPE_APPEND_ONLY,
89                SINK_TYPE_UPSERT
90            )));
91        }
92        Ok(config)
93    }
94
95    fn new_operator(properties: FsConfig) -> Result<Operator> {
96        FileSink::<FsSink>::new_fs_sink(properties)
97    }
98
99    fn get_path(properties: Self::Properties) -> String {
100        properties.common.path
101    }
102
103    fn get_engine_type() -> super::opendal_sink::EngineType {
104        super::opendal_sink::EngineType::Fs
105    }
106
107    fn get_batching_strategy(properties: Self::Properties) -> BatchingStrategy {
108        BatchingStrategy {
109            max_row_count: properties.batching_strategy.max_row_count,
110            rollover_seconds: properties.batching_strategy.rollover_seconds,
111            path_partition_prefix: properties.batching_strategy.path_partition_prefix,
112        }
113    }
114}