1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
//! Chunked writer for efficient sequential writing.
use super::buffer::{ChunkDescriptor, ChunkedBuffer};
use super::chunked::{ChunkStrategy, ChunkedIO, FileChunkedIO};
use crate::error::{Result, StreamingError};
use bytes::Bytes;
use std::path::Path;
use std::sync::Arc;
use tokio::sync::Semaphore;
use tracing::{debug, info, warn};
/// A writer that processes data in chunks.
pub struct ChunkedWriter {
/// The underlying chunked I/O
io: Box<dyn ChunkedIO>,
/// Chunk buffer (retained for future buffered-write support)
#[allow(dead_code)]
buffer: ChunkedBuffer,
/// Current chunk index (equals the number of chunks written so far)
current_index: usize,
/// Total size written
bytes_written: u64,
/// Write semaphore
write_semaphore: Arc<Semaphore>,
/// Chunk strategy (retained for future adaptive-size support)
#[allow(dead_code)]
strategy: ChunkStrategy,
/// Optional pre-declared total chunk count.
///
/// When set, [`finalize`] checks that exactly this many chunks were written
/// and returns [`StreamingError::IncompleteFinalize`] on mismatch.
preset_total_chunks: Option<usize>,
}
impl ChunkedWriter {
/// Create a new chunked writer to a file.
pub async fn from_file<P: AsRef<Path>>(
path: P,
strategy: ChunkStrategy,
buffer_size: usize,
max_concurrent_writes: usize,
) -> Result<Self> {
let mut io = FileChunkedIO::new(path, strategy).await?;
io.open_write().await?;
let chunk_size = strategy.chunk_size_for_index(0, 0);
let buffer = ChunkedBuffer::new(chunk_size, buffer_size);
info!("Created chunked writer with chunk size {}", chunk_size);
Ok(Self {
io: Box::new(io),
buffer,
current_index: 0,
bytes_written: 0,
write_semaphore: Arc::new(Semaphore::new(max_concurrent_writes)),
strategy,
preset_total_chunks: None,
})
}
/// Declare the expected total number of chunks up front.
///
/// When `finalize` is called it verifies that exactly `n` chunks were
/// written. A mismatch returns [`StreamingError::IncompleteFinalize`].
pub fn set_total_chunks(mut self, n: usize) -> Self {
self.preset_total_chunks = Some(n);
self
}
/// Write a chunk of data.
pub async fn write_chunk(&mut self, data: Bytes) -> Result<()> {
let _permit = self
.write_semaphore
.acquire()
.await
.map_err(|e| StreamingError::Other(e.to_string()))?;
let offset = self.bytes_written;
let length = data.len();
// `total_chunks` in the descriptor is set to 0 here because we may not
// know the final count yet; `finalize` will write a footer or patch the
// header with the real value.
let descriptor = ChunkDescriptor::new(
offset,
length,
self.current_index,
0, // Updated when finalized (see finalize())
);
self.io.write_chunk(&descriptor, data).await?;
self.current_index += 1;
self.bytes_written += length as u64;
debug!(
"Wrote chunk {} ({} bytes), total: {} bytes",
descriptor.index, length, self.bytes_written
);
Ok(())
}
/// Write multiple chunks sequentially.
pub async fn write_chunks(&mut self, chunks: Vec<Bytes>) -> Result<()> {
for chunk in chunks {
self.write_chunk(chunk).await?;
}
Ok(())
}
/// Flush all pending writes.
pub async fn flush(&mut self) -> Result<()> {
self.io.flush().await?;
info!(
"Flushed {} bytes in {} chunks",
self.bytes_written, self.current_index
);
Ok(())
}
/// Finalize the writer, validate chunk counts, and close the stream.
///
/// If [`set_total_chunks`] was called previously and the actual number of
/// chunks written does not match the preset value,
/// [`StreamingError::IncompleteFinalize`] is returned *before* the
/// underlying I/O is closed so callers can inspect the partial output.
///
/// After a successful finalize a footer descriptor containing the real
/// `total_chunks` value is appended so readers can discover the count
/// without having to re-scan the file.
///
/// [`set_total_chunks`]: ChunkedWriter::set_total_chunks
pub async fn finalize(mut self) -> Result<()> {
self.flush().await?;
let total_chunks = self.current_index;
// Validate against the preset (if any)
if let Some(expected) = self.preset_total_chunks
&& total_chunks != expected
{
warn!(
"Finalize mismatch: expected {} chunks, wrote {}",
expected, total_chunks
);
return Err(StreamingError::IncompleteFinalize {
expected,
actual: total_chunks,
});
}
// Write a footer: a small sentinel chunk whose ChunkDescriptor carries
// the definitive `total_chunks` value. This allows readers that cannot
// seek (e.g. network streams) to discover the count at the end.
//
// The footer payload is a little-endian u64 encoding of `total_chunks`
// preceded by the magic bytes `b"CHNK"` (4 bytes) so it is identifiable.
let mut footer = Vec::with_capacity(12);
footer.extend_from_slice(b"CHNK");
footer.extend_from_slice(&(total_chunks as u64).to_le_bytes());
let footer_descriptor = ChunkDescriptor::new(
self.bytes_written,
footer.len(),
total_chunks, // footer index = total_chunks (one past the last data chunk)
total_chunks + 1, // total including the footer itself
);
self.io
.write_chunk(&footer_descriptor, Bytes::from(footer))
.await?;
self.io.flush().await?;
info!(
"Finalized chunked writer: {} data chunks, {} total bytes",
total_chunks, self.bytes_written
);
Ok(())
}
/// Get the number of chunks written so far.
pub fn chunks_written(&self) -> usize {
self.current_index
}
/// Get the total bytes written so far.
pub fn bytes_written(&self) -> u64 {
self.bytes_written
}
}
#[cfg(test)]
#[allow(clippy::panic)]
mod tests {
use super::*;
use std::env;
#[tokio::test]
async fn test_chunked_writer() {
let temp_dir = env::temp_dir();
let test_path = temp_dir.join("test_chunked_write.dat");
let result =
ChunkedWriter::from_file(&test_path, ChunkStrategy::FixedSize(1024), 10240, 4).await;
if let Ok(mut writer) = result {
let data = Bytes::from(vec![42u8; 1024]);
writer.write_chunk(data).await.ok();
writer.finalize().await.ok();
}
// Clean up
tokio::fs::remove_file(&test_path).await.ok();
}
/// Verify that `finalize` writes the footer and reports the correct total.
#[tokio::test]
async fn test_chunked_writer_finalize_patches_total_chunks() {
let temp_dir = env::temp_dir();
let test_path = temp_dir.join("test_cw_finalize_total.dat");
// Clean up before test to avoid stale state
tokio::fs::remove_file(&test_path).await.ok();
let mut writer =
ChunkedWriter::from_file(&test_path, ChunkStrategy::FixedSize(512), 10240, 2)
.await
.expect("writer should be created successfully");
for i in 0u8..5 {
let data = Bytes::from(vec![i; 512]);
writer
.write_chunk(data)
.await
.expect("write_chunk should succeed");
}
assert_eq!(writer.chunks_written(), 5);
writer.finalize().await.expect("finalize should succeed");
// The footer should have been written; verify the file is larger than 5 * 512
let meta = tokio::fs::metadata(&test_path)
.await
.expect("file metadata should be readable");
assert!(meta.len() > 5 * 512, "footer was not written");
tokio::fs::remove_file(&test_path).await.ok();
}
/// When `set_total_chunks` matches the actual count, `finalize` succeeds.
#[tokio::test]
async fn test_chunked_writer_with_preset_chunks_matches_on_finalize() {
let temp_dir = env::temp_dir();
let test_path = temp_dir.join("test_cw_preset_match.dat");
tokio::fs::remove_file(&test_path).await.ok();
let mut writer =
ChunkedWriter::from_file(&test_path, ChunkStrategy::FixedSize(256), 10240, 2)
.await
.expect("writer should be created successfully");
// Pre-declare 3 chunks
writer = writer.set_total_chunks(3);
for i in 0u8..3 {
writer
.write_chunk(Bytes::from(vec![i; 256]))
.await
.expect("write_chunk should succeed");
}
writer
.finalize()
.await
.expect("finalize should succeed when preset matches actual");
tokio::fs::remove_file(&test_path).await.ok();
}
/// When `set_total_chunks` does NOT match the actual count, `finalize` errors.
#[tokio::test]
async fn test_chunked_writer_preset_mismatch_returns_error() {
let temp_dir = env::temp_dir();
let test_path = temp_dir.join("test_cw_preset_mismatch.dat");
tokio::fs::remove_file(&test_path).await.ok();
let mut writer =
ChunkedWriter::from_file(&test_path, ChunkStrategy::FixedSize(256), 10240, 2)
.await
.expect("writer should be created successfully");
// Pre-declare 5 chunks but only write 3
writer = writer.set_total_chunks(5);
for i in 0u8..3 {
writer
.write_chunk(Bytes::from(vec![i; 256]))
.await
.expect("write_chunk should succeed");
}
let result = writer.finalize().await;
match result {
Err(StreamingError::IncompleteFinalize { expected, actual }) => {
assert_eq!(expected, 5, "expected preset value");
assert_eq!(actual, 3, "actual written count");
}
other => panic!("expected IncompleteFinalize, got {:?}", other),
}
tokio::fs::remove_file(&test_path).await.ok();
}
}