scopedb_client/append_writer.rs
1// Copyright 2024 ScopeDB, Inc.
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::future::Future;
16use std::future::poll_fn;
17use std::ops::Range;
18use std::pin::Pin;
19use std::task::Poll;
20use std::time::Duration;
21
22use serde::Serialize;
23
24use crate::AppendDeliveryOutcome;
25use crate::AppendFailurePolicy;
26use crate::AppendOutcome;
27use crate::AppendRowsResult;
28use crate::Error;
29use crate::ErrorOperation;
30use crate::Table;
31use crate::append::AppendOptions;
32use crate::append::append_batch;
33use crate::append::encode_record;
34
35/// Builder for an [`AppendWriter`].
36///
37/// Defaults match [`AppendStreamBuilder`](crate::AppendStreamBuilder): 4 MiB target batches, up to
38/// 200,000 rows per batch, 4 concurrent batches, [`AppendFailurePolicy::Stop`],
39/// and up to 8 retries of validated HTTP 429 admission refusals.
40#[derive(Debug, Clone)]
41pub struct AppendWriterBuilder {
42 table: Table,
43 options: AppendOptions,
44 failure_policy: AppendFailurePolicy,
45}
46
47impl AppendWriterBuilder {
48 /// Sets the target uncompressed NDJSON batch size (default 4 MiB, maximum 8 MiB).
49 ///
50 /// A single row larger than this target is sent in its own batch up to the
51 /// 8 MiB protocol limit.
52 pub fn target_batch_bytes(mut self, bytes: usize) -> Self {
53 self.options.batch_bytes = bytes;
54 self
55 }
56
57 /// Sets the maximum rows per HTTP batch (default and maximum 200,000).
58 pub fn max_batch_rows(mut self, rows: usize) -> Self {
59 self.options.max_batch_rows = rows;
60 self
61 }
62
63 /// Sets the maximum in-flight batches per [`AppendWriter::write`] call (default 4). Use `1` for
64 /// sequential submission.
65 pub fn max_concurrent_batches(mut self, batches: usize) -> Self {
66 self.options.max_in_flight_requests = batches;
67 self
68 }
69
70 /// Sets the maximum retry attempts after an initial batch failure (default 8).
71 pub fn max_retries(mut self, retries: usize) -> Self {
72 self.options.retry.max_retries = retries;
73 self
74 }
75
76 /// Enables retrying transient [`AppendOutcome::Ambiguous`] responses (default `false`).
77 ///
78 /// Retrying an ambiguous outcome can insert duplicate rows. Client timeouts
79 /// are never replayed automatically.
80 pub fn retry_ambiguous(mut self, enabled: bool) -> Self {
81 self.options.retry.retry_ambiguous = enabled;
82 self
83 }
84
85 /// Sets the initial retry backoff delay (default 100 ms).
86 pub fn initial_backoff(mut self, delay: Duration) -> Self {
87 self.options.retry.initial_backoff = delay;
88 self
89 }
90
91 /// Sets the maximum retry delay, capping exponential backoff and `Retry-After` headers (default
92 /// 5 s).
93 pub fn max_backoff(mut self, delay: Duration) -> Self {
94 self.options.retry.max_backoff = delay;
95 self
96 }
97
98 /// Overrides the client's [`ClientBuilder::write_timeout`](crate::ClientBuilder::write_timeout)
99 /// with a positive per-attempt timeout.
100 pub fn attempt_timeout(mut self, timeout: Duration) -> Self {
101 self.options.attempt_timeout = Some(timeout);
102 self
103 }
104
105 /// Sets whether a batch failure stops scheduling subsequent batches (default
106 /// [`AppendFailurePolicy::Stop`]).
107 pub fn failure_policy(mut self, policy: AppendFailurePolicy) -> Self {
108 self.failure_policy = policy;
109 self
110 }
111
112 /// Validates the configuration and returns a reusable [`AppendWriter`].
113 pub fn build(self) -> Result<AppendWriter, Error> {
114 self.options
115 .validate()
116 .map_err(|error| error.with_operation(ErrorOperation::BuildAppendWriter))?;
117 self.table
118 .validate_append()
119 .map_err(|error| error.with_operation(ErrorOperation::BuildAppendWriter))?;
120 Ok(AppendWriter {
121 table: self.table,
122 options: self.options,
123 failure_policy: self.failure_policy,
124 })
125 }
126
127 pub(crate) fn new(table: Table) -> Self {
128 Self {
129 table,
130 options: AppendOptions::default(),
131 failure_policy: AppendFailurePolicy::Stop,
132 }
133 }
134}
135
136/// Reusable batch writer for finite slices of rows.
137///
138/// Each [`write`](Self::write) call batches and settles its input slice independently.
139/// Clones share the underlying HTTP connection pool.
140#[derive(Debug, Clone)]
141pub struct AppendWriter {
142 table: Table,
143 options: AppendOptions,
144 failure_policy: AppendFailurePolicy,
145}
146
147/// Settlement report for one [`AppendWriter::write`] call.
148///
149/// [`batches`](Self::batches) are ordered by their [`AppendRequestResult::input_range`]
150/// and cover a contiguous prefix of the input slice; [`unsubmitted`](Self::unsubmitted)
151/// covers the remaining suffix.
152#[derive(Debug, Clone)]
153#[must_use]
154pub struct AppendWriteReport {
155 input_rows: usize,
156 batches: Vec<AppendRequestResult>,
157 unsubmitted: Range<usize>,
158}
159
160impl AppendWriteReport {
161 /// Returns the total number of rows in the input slice.
162 pub fn input_rows(&self) -> usize {
163 self.input_rows
164 }
165
166 /// Returns the scheduled batches in input order.
167 pub fn batches(&self) -> &[AppendRequestResult] {
168 &self.batches
169 }
170
171 /// Returns the input index range that was never sent and is known not to have committed.
172 pub fn unsubmitted(&self) -> Range<usize> {
173 self.unsubmitted.clone()
174 }
175
176 /// Returns the number of input rows in batches acknowledged as committed.
177 pub fn committed_rows(&self) -> usize {
178 self.batches
179 .iter()
180 .filter(|batch| batch.result.is_ok())
181 .map(|batch| batch.input_range.len())
182 .sum()
183 }
184
185 /// Returns the aggregate [`AppendDeliveryOutcome`] for this write call.
186 ///
187 /// [`AppendDeliveryOutcome::Partial`] may include batches with
188 /// [`AppendOutcome::Ambiguous`]; inspect [`batches`](Self::batches) before replaying
189 /// failed ranges.
190 pub fn outcome(&self) -> AppendDeliveryOutcome {
191 if self.unsubmitted.is_empty() && self.batches.iter().all(|batch| batch.result.is_ok()) {
192 AppendDeliveryOutcome::Succeeded
193 } else if self.committed_rows() > 0 {
194 AppendDeliveryOutcome::Partial
195 } else if self.batches.iter().any(|batch| {
196 batch.result.as_ref().is_err_and(|error| {
197 error
198 .append_details()
199 .is_some_and(|details| details.status == AppendOutcome::Ambiguous)
200 })
201 }) {
202 AppendDeliveryOutcome::Ambiguous
203 } else {
204 AppendDeliveryOutcome::Failed
205 }
206 }
207}
208
209/// Outcome of one batch within an [`AppendWriteReport`], including any retry attempts.
210#[derive(Debug, Clone)]
211pub struct AppendRequestResult {
212 input_range: Range<usize>,
213 result: Result<AppendRowsResult, Error>,
214 retries: usize,
215}
216
217impl AppendRequestResult {
218 /// Returns the input slice range covered by this batch.
219 pub fn input_range(&self) -> Range<usize> {
220 self.input_range.clone()
221 }
222
223 /// Returns the final outcome of the batch.
224 pub fn result(&self) -> &Result<AppendRowsResult, Error> {
225 &self.result
226 }
227
228 /// Returns the number of retry attempts made for this batch.
229 pub fn retries(&self) -> usize {
230 self.retries
231 }
232
233 /// Maps a zero-based [`AppendRowError::row_index`](crate::AppendRowError::row_index) from this
234 /// batch to its index in the original input slice. Returns `None` for indexes outside this
235 /// batch.
236 pub fn input_index(&self, row_index: u64) -> Option<usize> {
237 let index = self
238 .input_range
239 .start
240 .checked_add(usize::try_from(row_index).ok()?)?;
241 self.input_range.contains(&index).then_some(index)
242 }
243}
244
245type PendingBatch = Pin<Box<dyn Future<Output = AppendRequestResult> + Send>>;
246
247// Poll requests in the caller's task so cancellation drops the requests and
248// their retry loops together, without detached workers or another executor.
249async fn next_batch(pending: &mut Vec<PendingBatch>) -> AppendRequestResult {
250 poll_fn(|cx| {
251 for index in 0..pending.len() {
252 if let Poll::Ready(result) = pending[index].as_mut().poll(cx) {
253 drop(pending.swap_remove(index));
254 return Poll::Ready(result);
255 }
256 }
257 Poll::Pending
258 })
259 .await
260}
261
262impl AppendWriter {
263 /// Batches and writes `rows`, returning `Ok` when every row is committed.
264 ///
265 /// ```no_run
266 /// # async fn example(client: scopedb_client::Client) -> Result<(), scopedb_client::Error> {
267 /// let writer = client.table("events").append_writer().build()?;
268 /// let rows = [serde_json::json!({"id": 1}), serde_json::json!({"id": 2})];
269 /// let report = writer.write(&rows).await?;
270 /// assert_eq!(report.committed_rows(), rows.len());
271 /// # Ok(())
272 /// # }
273 /// ```
274 ///
275 /// If any row fails local encoding or any batch fails after retries, returns
276 /// [`Error`] with [`Error::append_write_report`] recording every scheduled
277 /// batch and the [`AppendWriteReport::unsubmitted`] suffix. Local encoding
278 /// errors also set [`Error::append_input_index`], stop input processing under
279 /// either failure policy, and leave the partially built batch unsubmitted.
280 ///
281 /// Under [`AppendFailurePolicy::Stop`], no new batches are scheduled after
282 /// a batch failure is observed, while in-flight batches are settled before returning.
283 /// Under [`AppendFailurePolicy::Continue`], remaining batches are still
284 /// attempted before returning the error. Dropping this future stops
285 /// scheduling and retrying, though requests already sent may still commit.
286 pub async fn write<T: Serialize>(&self, rows: &[T]) -> Result<AppendWriteReport, Error> {
287 let mut report = AppendWriteReport {
288 input_rows: rows.len(),
289 batches: Vec::new(),
290 unsubmitted: 0..rows.len(),
291 };
292 let mut pending: Vec<PendingBatch> = Vec::new();
293 let mut cursor = 0;
294 let mut submitted = 0;
295 let mut lookahead = None;
296 let mut local_failure = None;
297 let mut stopped = false;
298
299 loop {
300 while !stopped
301 && cursor < rows.len()
302 && pending.len() < self.options.max_in_flight_requests
303 {
304 let start = cursor;
305 let mut payload = String::new();
306 let mut count = 0;
307 while cursor < rows.len() {
308 let encoded = match lookahead
309 .take()
310 .map(Ok)
311 .unwrap_or_else(|| encode_record(&rows[cursor]))
312 {
313 Ok(encoded) => encoded,
314 Err(error) => {
315 local_failure = Some((cursor, Error::from(error)));
316 stopped = true;
317 break;
318 }
319 };
320 if self
321 .options
322 .would_overflow(payload.len(), count, encoded.len())
323 {
324 lookahead = Some(encoded);
325 break;
326 }
327 if count > 0 {
328 payload.push('\n');
329 }
330 payload.push_str(&encoded);
331 count += 1;
332 cursor += 1;
333 if self.options.is_full(payload.len(), count) {
334 break;
335 }
336 }
337 if stopped {
338 break;
339 }
340 let input_range = start..cursor;
341 let table = self.table.clone();
342 let options = self.options.clone();
343 pending.push(Box::pin(async move {
344 let (result, retries) = append_batch(table, options, payload).await;
345 AppendRequestResult {
346 input_range,
347 result,
348 retries,
349 }
350 }));
351 submitted = cursor;
352 }
353 if pending.is_empty() {
354 break;
355 }
356 let result = next_batch(&mut pending).await;
357 if result.result.is_err() && self.failure_policy == AppendFailurePolicy::Stop {
358 stopped = true;
359 }
360 report.batches.push(result);
361 }
362 report.batches.sort_by_key(|batch| batch.input_range.start);
363 report.unsubmitted = submitted..rows.len();
364 if let Some((index, cause)) = local_failure {
365 return Err(cause.with_append_write(report, Some(index)));
366 }
367 // Prefer an ambiguous failure as the headline error; every other failure
368 // remains available in the report for selective reconciliation.
369 let cause = report
370 .batches
371 .iter()
372 .filter_map(|batch| batch.result.as_ref().err())
373 .find(|error| {
374 error
375 .append_details()
376 .is_some_and(|details| details.status == AppendOutcome::Ambiguous)
377 })
378 .or_else(|| {
379 report
380 .batches
381 .iter()
382 .find_map(|batch| batch.result.as_ref().err())
383 })
384 .cloned();
385 match cause {
386 Some(cause) => Err(cause.with_append_write(report, None)),
387 None => Ok(report),
388 }
389 }
390}