Skip to main content

risingwave_stream/executor/source/batch_source/
batch_posix_fs_fetch.rs

1// Copyright 2025 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::VecDeque;
16use std::io::BufRead;
17use std::path::Path;
18
19use either::Either;
20use futures::TryStreamExt;
21use futures::stream::{self, StreamExt};
22use futures_async_stream::try_stream;
23use risingwave_common::id::TableId;
24use risingwave_common::types::{JsonbVal, ScalarRef};
25use risingwave_common_rate_limit::RateLimiter;
26use risingwave_connector::parser::{ByteStreamSourceParserImpl, CommonParserConfig, ParserConfig};
27use risingwave_connector::source::filesystem::OpendalFsSplit;
28use risingwave_connector::source::filesystem::opendal_source::OpendalPosixFs;
29use risingwave_connector::source::{
30    ConnectorProperties, SourceChunkStream, SourceContext, SourceCtrlOpts, SourceMessage,
31    SourceMessageEvent, SourceMeta, SourceReaderEvent, SplitMetaData,
32};
33use risingwave_pb::common::ThrottleType;
34use thiserror_ext::AsReport;
35use tokio::fs;
36
37use crate::common::rate_limit::limited_chunk_size;
38use crate::executor::prelude::*;
39use crate::executor::source::{StreamSourceCore, get_split_offset_col_idx, prune_additional_cols};
40use crate::executor::stream_reader::StreamReaderWithPause;
41use crate::task::LocalBarrierManager;
42
43/// Maximum number of files to process in a single batch
44const BATCH_SIZE: usize = 1000;
45
46fn into_data_chunk_stream(
47    stream: impl futures::Stream<Item = risingwave_connector::error::ConnectorResult<SourceReaderEvent>>
48    + Send
49    + 'static,
50) -> impl SourceChunkStream {
51    stream
52        .try_filter_map(|event| async move {
53            Ok(match event {
54                SourceReaderEvent::DataChunk(chunk) => Some(chunk),
55                SourceReaderEvent::SplitProgress(_) => None,
56            })
57        })
58        .boxed()
59}
60
61/// Executor for fetching and processing files in batch mode for refreshable tables.
62///
63/// This executor receives file assignments from an upstream list executor,
64/// reads the files, parses their contents, and emits stream chunks.
65///
66/// Key characteristics:
67/// - Uses **ephemeral in-memory state** (no persistent state table)
68/// - State is cleared on recovery and `RefreshStart` mutations
69/// - Suitable for refreshable materialized views
70pub struct BatchPosixFsFetchExecutor<S: StateStore> {
71    actor_ctx: ActorContextRef,
72
73    /// Core component for managing external streaming source state
74    stream_source_core: Option<StreamSourceCore<S>>,
75
76    /// Upstream list executor that provides the list of files to read
77    upstream: Option<Executor>,
78
79    /// Optional rate limit in rows/s to control data ingestion speed
80    rate_limit_rps: Option<u32>,
81
82    /// Shared with the running reader, so a `Throttle` mutation applies to the file being read.
83    rate_limiter: Arc<RateLimiter>,
84
85    /// Local barrier manager for reporting load finished
86    barrier_manager: LocalBarrierManager,
87
88    /// In-memory queue of file assignments to process (`file_path`, `split_json`).
89    /// This is ephemeral and cleared on recovery and `RefreshStart` mutations.
90    file_queue: VecDeque<(String, JsonbVal)>,
91
92    /// Associated table ID for reporting load finished
93    associated_table_id: TableId,
94}
95
96/// A chunk read from a file, or `None` to mark that a file has been fully read.
97type FileData = Option<StreamChunk>;
98
99impl<S: StateStore> BatchPosixFsFetchExecutor<S> {
100    pub fn new(
101        actor_ctx: ActorContextRef,
102        stream_source_core: StreamSourceCore<S>,
103        upstream: Executor,
104        rate_limit_rps: Option<u32>,
105        barrier_manager: LocalBarrierManager,
106        associated_table_id: Option<TableId>,
107    ) -> Self {
108        assert!(associated_table_id.is_some());
109        Self {
110            actor_ctx,
111            stream_source_core: Some(stream_source_core),
112            upstream: Some(upstream),
113            rate_limit_rps,
114            rate_limiter: Arc::new(RateLimiter::new(rate_limit_rps.into())),
115            barrier_manager,
116            file_queue: VecDeque::new(),
117            associated_table_id: associated_table_id.unwrap(),
118        }
119    }
120
121    /// Pop files from the in-memory queue and create a batch reader for them.
122    /// Processes up to `BATCH_SIZE` files in parallel.
123    fn replace_with_new_batch_reader<const BIASED: bool>(
124        files_in_progress: &mut usize,
125        file_queue: &mut VecDeque<(String, JsonbVal)>,
126        stream: &mut StreamReaderWithPause<BIASED, FileData>,
127        properties: ConnectorProperties,
128        parser_config: ParserConfig,
129        source_ctx: Arc<SourceContext>,
130        rate_limiter: Arc<RateLimiter>,
131    ) -> StreamExecutorResult<()> {
132        // Pop up to BATCH_SIZE files from the queue to process
133        let mut batch = Vec::with_capacity(BATCH_SIZE);
134
135        for _ in 0..BATCH_SIZE {
136            if let Some((_file_path, split_json)) = file_queue.pop_front() {
137                let split = OpendalFsSplit::<OpendalPosixFs>::restore_from_json(split_json)?;
138                batch.push(split);
139            } else {
140                break;
141            }
142        }
143
144        if batch.is_empty() {
145            // No files to process, set stream to pending
146            stream.replace_data_stream(stream::pending().boxed());
147        } else {
148            *files_in_progress += batch.len();
149            let batch_reader = Self::build_batched_stream_reader(
150                batch,
151                properties,
152                parser_config,
153                source_ctx,
154                rate_limiter,
155            );
156            stream.replace_data_stream(batch_reader.boxed());
157        }
158
159        Ok(())
160    }
161
162    /// Build a stream reader that reads multiple files in sequence
163    #[try_stream(ok = FileData, error = StreamExecutorError)]
164    async fn build_batched_stream_reader(
165        batch: Vec<OpendalFsSplit<OpendalPosixFs>>,
166        properties: ConnectorProperties,
167        parser_config: ParserConfig,
168        source_ctx: Arc<SourceContext>,
169        rate_limiter: Arc<RateLimiter>,
170    ) {
171        let ConnectorProperties::BatchPosixFs(batch_posix_fs_properties) = properties else {
172            unreachable!()
173        };
174
175        let root_path = batch_posix_fs_properties.root.clone();
176
177        for split in batch {
178            let file_path = split.name.clone();
179            let full_path = Path::new(&root_path).join(&file_path);
180
181            // Read the entire file
182            let content = fs::read(&full_path).await.map_err(|e| {
183                StreamExecutorError::connector_error(
184                    anyhow::Error::from(e)
185                        .context(format!("failed to read file {}", full_path.display())),
186                )
187            })?;
188
189            if content.is_empty() {
190                // Empty file, skip it
191                yield None;
192                continue;
193            }
194
195            // Process the file line by line
196            for line in content.lines() {
197                let line =
198                    line.map_err(|e| StreamExecutorError::connector_error(anyhow::Error::from(e)))?;
199
200                let message = SourceMessage {
201                    key: None,
202                    payload: Some(line.as_bytes().to_vec()),
203                    offset: "0".to_owned(),
204                    split_id: split.id(),
205                    meta: SourceMeta::Empty,
206                };
207
208                // TODO(tab): avoid rebuilding ByteStreamSourceParserImpl for each file
209                // Parser is rebuilt per line because `parse_stream_with_events` consumes it.
210                let parser =
211                    ByteStreamSourceParserImpl::create(parser_config.clone(), source_ctx.clone())
212                        .await?;
213
214                let chunk_stream = into_data_chunk_stream(parser.parse_stream_with_events(
215                    Box::pin(futures::stream::once(async {
216                        Ok(SourceMessageEvent::Data(vec![message]))
217                    })),
218                ));
219
220                #[for_await]
221                for chunk in chunk_stream {
222                    let chunk = chunk?;
223                    rate_limiter.wait(chunk.rate_limit_permits()).await;
224                    yield Some(chunk);
225                }
226            }
227
228            tracing::debug!(file_path, "Processed file");
229            yield None;
230        }
231    }
232
233    #[try_stream(ok = Message, error = StreamExecutorError)]
234    async fn into_stream(mut self) {
235        let mut upstream = self.upstream.take().unwrap().execute();
236        let barrier = expect_first_barrier(&mut upstream).await?;
237        let is_pause_on_startup = barrier.is_pause_on_startup();
238        yield Message::Barrier(barrier);
239
240        let mut core = self.stream_source_core.take().unwrap();
241
242        // Build source description from the builder.
243        let source_desc_builder = core.source_desc_builder.take().unwrap();
244
245        let source_desc = source_desc_builder
246            .build()
247            .map_err(StreamExecutorError::connector_error)?;
248        let (Some(split_idx), Some(offset_idx), _) = get_split_offset_col_idx(&source_desc.columns)
249        else {
250            unreachable!("Partition and offset columns must be set.");
251        };
252
253        let properties = source_desc.source.config.clone();
254        let parser_config = ParserConfig {
255            common: CommonParserConfig {
256                rw_columns: source_desc.columns.clone(),
257            },
258            specific: source_desc.source.parser_config.clone(),
259        };
260
261        let mut files_in_progress: usize = 0;
262        let mut stream =
263            StreamReaderWithPause::<true, FileData>::new(upstream, stream::pending().boxed());
264
265        if is_pause_on_startup {
266            stream.pause_stream();
267        }
268
269        // For refreshable tables, always start fresh on recovery - no state restoration
270        // File queue is empty by default (no restoration from persistent state)
271
272        let mut list_finished = false;
273        let mut is_refreshing = false;
274        let mut file_queue = self.file_queue;
275
276        // Extract fields we'll need later
277        let actor_ctx = self.actor_ctx.clone();
278        let barrier_manager = self.barrier_manager.clone();
279        let rate_limit_rps = &mut self.rate_limit_rps;
280        let rate_limiter = self.rate_limiter.clone();
281
282        let make_source_ctx = |rate_limit_rps: Option<u32>| {
283            Arc::new(SourceContext::new(
284                actor_ctx.id,
285                core.source_id,
286                actor_ctx.fragment_id,
287                core.source_name.clone(),
288                source_desc.metrics.clone(),
289                SourceCtrlOpts {
290                    chunk_size: limited_chunk_size(rate_limit_rps),
291                    split_txn: rate_limit_rps.is_some(),
292                },
293                source_desc.source.config.clone(),
294                None,
295            ))
296        };
297        let mut source_ctx = make_source_ctx(*rate_limit_rps);
298
299        while let Some(msg) = stream.next().await {
300            match msg {
301                Err(e) => {
302                    tracing::error!(error = %e.as_report(), "Fetch Error");
303                    return Err(e);
304                }
305                Ok(msg) => match msg {
306                    // Barrier messages from upstream
307                    Either::Left(msg) => match msg {
308                        Message::Barrier(barrier) => {
309                            let need_rebuild_reader = false;
310
311                            if let Some(mutation) = barrier.mutation.as_deref() {
312                                match mutation {
313                                    Mutation::Throttle(fragment_to_apply) => {
314                                        if let Some(entry) =
315                                            fragment_to_apply.get(&actor_ctx.fragment_id)
316                                            && entry.throttle_type() == ThrottleType::Source
317                                            && entry.rate_limit != *rate_limit_rps
318                                        {
319                                            tracing::info!(
320                                                "updating rate limit from {:?} to {:?}",
321                                                *rate_limit_rps,
322                                                entry.rate_limit
323                                            );
324                                            *rate_limit_rps = entry.rate_limit;
325                                            rate_limiter.update(entry.rate_limit.into());
326                                            source_ctx = make_source_ctx(*rate_limit_rps);
327                                        }
328                                    }
329                                    Mutation::Pause => stream.pause_stream(),
330                                    Mutation::Resume => stream.resume_stream(),
331                                    Mutation::RefreshStart {
332                                        associated_source_id,
333                                        ..
334                                    } if associated_source_id.as_raw_id()
335                                        == core.source_id.as_raw_id() =>
336                                    {
337                                        tracing::info!(
338                                            ?barrier.epoch,
339                                            actor_id = %actor_ctx.id,
340                                            source_id = %core.source_id,
341                                            queue_len = file_queue.len(),
342                                            files_in_progress,
343                                            "RefreshStart: clearing state and aborting workload"
344                                        );
345
346                                        // Clear all in-memory state
347                                        file_queue.clear();
348                                        files_in_progress = 0;
349                                        list_finished = false;
350                                        is_refreshing = true;
351
352                                        // Abort current file reader
353                                        stream.replace_data_stream(stream::pending().boxed());
354                                    }
355                                    Mutation::ListFinish {
356                                        associated_source_id,
357                                    } if associated_source_id.as_raw_id()
358                                        == core.source_id.as_raw_id() =>
359                                    {
360                                        // ListFinish is for our source
361                                        tracing::info!(
362                                            ?barrier.epoch,
363                                            actor_id = %actor_ctx.id,
364                                            source_id = %core.source_id,
365                                            "received ListFinish mutation"
366                                        );
367                                        list_finished = true;
368                                    }
369                                    _ => (),
370                                }
371                            }
372
373                            let epoch = barrier.epoch;
374
375                            // Report load finished BEFORE yielding barrier when:
376                            // 1. All files have been processed (files_in_progress == 0 and file_queue is empty)
377                            // 2. ListFinish mutation has been received
378                            //
379                            // IMPORTANT: Must report BEFORE yield to ensure epoch is still in inflight_barriers.
380                            // If we yield first, the barrier worker may collect the barrier and remove the epoch
381                            // from inflight_barriers, causing the report to be ignored with a warning.
382                            if files_in_progress == 0
383                                && file_queue.is_empty()
384                                && list_finished
385                                && is_refreshing
386                                && barrier.is_checkpoint()
387                            {
388                                tracing::info!(
389                                    ?epoch,
390                                    actor_id = %actor_ctx.id,
391                                    source_id = %core.source_id,
392                                    "Reporting source load finished"
393                                );
394                                barrier_manager.report_source_load_finished(
395                                    epoch,
396                                    actor_ctx.id,
397                                    self.associated_table_id,
398                                    core.source_id,
399                                );
400                                // Reset the flag to avoid duplicate reports
401                                list_finished = false;
402                                is_refreshing = false;
403                            }
404
405                            // Propagate the barrier AFTER reporting progress.
406                            yield Message::Barrier(barrier);
407
408                            // Rebuild reader when all current files are processed
409                            if (files_in_progress == 0 || need_rebuild_reader)
410                                && *rate_limit_rps != Some(0)
411                            {
412                                Self::replace_with_new_batch_reader(
413                                    &mut files_in_progress,
414                                    &mut file_queue,
415                                    &mut stream,
416                                    properties.clone(),
417                                    parser_config.clone(),
418                                    source_ctx.clone(),
419                                    rate_limiter.clone(),
420                                )?;
421                            }
422                        }
423                        // Receiving file assignments from upstream list executor,
424                        // store into in-memory queue (no persistent state).
425                        Message::Chunk(chunk) => {
426                            for row in chunk.data_chunk().rows() {
427                                let file_name = row.datum_at(0).unwrap().into_utf8().to_owned();
428                                let split = row.datum_at(1).unwrap().into_jsonb().to_owned_scalar();
429                                file_queue.push_back((file_name, split));
430                            }
431
432                            tracing::debug!(
433                                actor_id = %actor_ctx.id,
434                                queue_len = file_queue.len(),
435                                "Added file assignments to queue"
436                            );
437                        }
438                        Message::Watermark(_) => unreachable!(),
439                    },
440                    // Data from file reader
441                    Either::Right(Some(chunk)) => {
442                        let chunk = prune_additional_cols(
443                            &chunk,
444                            &[split_idx, offset_idx],
445                            &source_desc.columns,
446                        );
447                        yield Message::Chunk(chunk);
448                    }
449                    Either::Right(None) => {
450                        files_in_progress = files_in_progress.saturating_sub(1);
451                    }
452                },
453            }
454        }
455    }
456}
457
458impl<S: StateStore> Execute for BatchPosixFsFetchExecutor<S> {
459    fn execute(self: Box<Self>) -> BoxedMessageStream {
460        self.into_stream().boxed()
461    }
462}
463
464impl<S: StateStore> Debug for BatchPosixFsFetchExecutor<S> {
465    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
466        if let Some(core) = &self.stream_source_core {
467            f.debug_struct("BatchPosixFsFetchExecutor")
468                .field("source_id", &core.source_id)
469                .field("column_ids", &core.column_ids)
470                .finish()
471        } else {
472            f.debug_struct("BatchPosixFsFetchExecutor").finish()
473        }
474    }
475}