allsource-core 0.30.0

High-performance event store core built in Rust
Documentation
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! Offline, exact-stream erasure of local durable event files. Core writers,
//! replicas and backup jobs must be stopped before calling these operations.
//! Each replacement is atomic; interrupted multi-file work must be retried and
//! verified across every retained copy before restarting consumers.

use super::{
    archive_repack::{archive_directory_guard, archive_mutation_guard},
    erasure_redaction::{EventRedaction, redact_batch},
    wal::{WALConfig, WALEntry},
};
use crate::error::{AllSourceError, Result};
use arrow::{
    array::{Array, BooleanArray, StringArray},
    compute::filter_record_batch,
};
use parquet::{
    arrow::{ArrowWriter, arrow_reader::ParquetRecordBatchReaderBuilder},
    basic::Compression,
    file::properties::WriterProperties,
};
use serde::Serialize;
use sha2::{Digest, Sha256};
use std::{
    collections::{HashMap, HashSet},
    fs::{self, File, Metadata, OpenOptions},
    io::{BufRead, BufReader, Read, Seek, SeekFrom, Write},
    path::{Component, Path},
    time::Instant,
};

pub(super) const MAX_FILE_BYTES: u64 = 64 * 1024 * 1024;
/// Default location of the system store under the storage directory; its
/// audit records are outside tenant erasure scope and are reported, not read.
pub(super) const SYSTEM_DIR: &str = "__system";
const MAX_DECODED_BYTES: usize = 128 * 1024 * 1024;
const MAX_WAL_LINE_BYTES: u64 = 16 * 1024 * 1024;

/// Rotation runs after the append that reaches `max_file_size`, so a sealed
/// segment exceeds it by at most one line.
pub(super) fn wal_file_limit() -> u64 {
    WALConfig::default().max_file_size as u64 + MAX_WAL_LINE_BYTES
}

pub struct ErasureScope {
    pub(super) tenant: String,
    pub(super) entities: HashSet<String>,
    pub(super) redactions: HashMap<uuid::Uuid, EventRedaction>,
    pub(super) seen_redactions: std::sync::Mutex<HashSet<uuid::Uuid>>,
}

impl ErasureScope {
    pub fn new(tenant: String, entities: Vec<String>) -> Result<Self> {
        Self::with_redactions(tenant, entities, Vec::new())
    }

    pub fn with_redactions(
        tenant: String,
        entities: Vec<String>,
        redactions: Vec<EventRedaction>,
    ) -> Result<Self> {
        if tenant.is_empty()
            || tenant.len() > 256
            || tenant == SYSTEM_DIR
            || !tenant
                .bytes()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_'))
            || (entities.is_empty() && redactions.is_empty())
            || entities.len() > 10_000
            || redactions.len() > 10_000
            || entities.iter().any(|id| id.is_empty() || id.len() > 1024)
        {
            return Err(failure(
                "an exact tenant and nonempty, bounded entity list are required",
            ));
        }
        let mut by_event = HashMap::new();
        for redaction in redactions {
            redaction.validate()?;
            if entities.contains(&redaction.entity_id)
                || by_event.insert(redaction.event_id, redaction).is_some()
            {
                return Err(failure("duplicate redaction or overlap with erased entity"));
            }
        }
        Ok(Self {
            tenant,
            entities: entities.into_iter().collect(),
            redactions: by_event,
            seen_redactions: std::sync::Mutex::new(HashSet::new()),
        })
    }

    pub(super) fn matches(&self, tenant: &str, entity: &str) -> bool {
        tenant == self.tenant && self.entities.contains(entity)
    }

    pub(super) fn redact(&self, event: &mut crate::domain::entities::Event) -> Result<bool> {
        if event.tenant_id_str() != self.tenant {
            return Ok(false);
        }
        let entity = event.entity_id_str().to_owned();
        self.redactions
            .get(&event.id)
            .map_or(Ok(false), |redaction| {
                self.seen_redactions
                    .lock()
                    .map_err(|_| failure("redaction inventory lock failed"))?
                    .insert(event.id);
                redaction.replace(&entity, &mut event.payload, &mut event.metadata)
            })
    }
}

#[derive(Debug, Default, PartialEq, Eq, Serialize)]
pub struct ErasureReport {
    pub examined: u64,
    pub removed: u64,
    pub redacted: u64,
}

pub(super) fn failure(message: &str) -> AllSourceError {
    AllSourceError::StorageError(format!("Local event erasure: {message}"))
}

pub(super) fn io_error(error: impl std::fmt::Display) -> AllSourceError {
    failure(&error.to_string())
}

pub(super) fn check_deadline(deadline: Instant) -> Result<()> {
    if Instant::now() >= deadline {
        return Err(failure("deadline exceeded"));
    }
    Ok(())
}

pub(super) fn regular_file(path: &Path) -> Result<Metadata> {
    regular_file_within(path, MAX_FILE_BYTES)
}

pub(super) fn regular_file_within(path: &Path, limit: u64) -> Result<Metadata> {
    let meta = fs::symlink_metadata(path).map_err(io_error)?;
    if !meta.is_file() || meta.len() > limit {
        return Err(failure(
            "source must be a regular file within the byte limit",
        ));
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        if meta.nlink() != 1 {
            return Err(failure(
                "hard-linked sources require separate copy inventory",
            ));
        }
    }
    Ok(meta)
}

/// A dangling symlink at the lock path must not create its target.
pub(super) fn open_lock_file(path: &Path) -> Result<File> {
    match fs::symlink_metadata(path) {
        Ok(_) => {
            regular_file(path)?;
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
        Err(e) => return Err(io_error(e)),
    }
    let mut options = OpenOptions::new();
    options.read(true).write(true).create(true).truncate(false);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }
    options.open(path).map_err(io_error)
}

fn unchanged(before: &Metadata, after: &Metadata) -> bool {
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        if before.ino() != after.ino() || before.dev() != after.dev() {
            return false;
        }
    }
    before.len() == after.len() && before.modified().ok() == after.modified().ok()
}

pub(super) fn digest(file: &mut File, deadline: Instant) -> Result<Vec<u8>> {
    file.seek(SeekFrom::Start(0)).map_err(io_error)?;
    let mut hash = Sha256::new();
    let mut buffer = [0u8; 16 * 1024];
    loop {
        check_deadline(deadline)?;
        let count = file.read(&mut buffer).map_err(io_error)?;
        if count == 0 {
            break;
        }
        hash.update(&buffer[..count]);
    }
    file.seek(SeekFrom::Start(0)).map_err(io_error)?;
    Ok(hash.finalize().to_vec())
}

pub(super) fn rewrite(
    path: &Path,
    limit: u64,
    deadline: Instant,
    transform: impl FnOnce(&mut File, &mut File) -> Result<ErasureReport>,
) -> Result<ErasureReport> {
    check_deadline(deadline)?;
    let _mutation = archive_mutation_guard(Some(deadline))
        .ok_or_else(|| failure("maintenance lock deadline exceeded"))?;
    let parent = path
        .parent()
        .ok_or_else(|| failure("source parent missing"))?;
    if parent.canonicalize().map_err(io_error)? != parent {
        return Err(failure(
            "use canonical absolute paths without symlink ancestors",
        ));
    }
    let _directory = archive_directory_guard(parent)?;
    let before = regular_file_within(path, limit)?;
    let mut source = File::open(path).map_err(io_error)?;
    if !unchanged(&before, &source.metadata().map_err(io_error)?) {
        return Err(failure("source changed before opening"));
    }
    let original_hash = digest(&mut source, deadline)?;
    let temporary = parent.join(format!(".erasure-{}.pending", uuid::Uuid::new_v4()));
    let mut options = OpenOptions::new();
    options.write(true).create_new(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }
    let mut output = options.open(&temporary).map_err(io_error)?;
    let result = (|| {
        let report = transform(&mut source, &mut output)?;
        check_deadline(deadline)?;
        if report.removed == 0 && report.redacted == 0 {
            return Ok(report);
        }
        output.sync_all().map_err(io_error)?;
        let current = regular_file_within(path, limit)?;
        if !unchanged(&before, &current) || digest(&mut source, deadline)? != original_hash {
            return Err(failure("source changed during maintenance"));
        }
        fs::rename(&temporary, path).map_err(io_error)?;
        File::open(parent)
            .and_then(|directory| directory.sync_all())
            .map_err(io_error)?;
        Ok(report)
    })();
    drop(output);
    match fs::remove_file(&temporary) {
        Ok(()) => {}
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
        Err(error) => return Err(io_error(error)),
    }
    result
}

/// Erase exact tenant/entity matches; retain original sequence numbers and bytes
/// for all other WAL entries. Any unreadable or invalid entry rejects the rewrite.
pub fn erase_wal_segment(
    path: &Path,
    scope: &ErasureScope,
    deadline: Instant,
) -> Result<ErasureReport> {
    rewrite(path, wal_file_limit(), deadline, |source, output| {
        let (report, sequence) = scan_wal(source, output, scope, deadline)?;
        if report.removed > 0 {
            super::wal_sequence::preserve_floor(
                path.parent().ok_or_else(|| failure("WAL parent missing"))?,
                sequence,
            )?;
        }
        Ok(report)
    })
}

pub(super) fn scan_wal(
    source: &mut File,
    output: &mut dyn Write,
    scope: &ErasureScope,
    deadline: Instant,
) -> Result<(ErasureReport, u64)> {
    let mut report = ErasureReport::default();
    let mut sequence = 0;
    for line in BufReader::new(source).lines() {
        check_deadline(deadline)?;
        let line = line.map_err(io_error)?;
        if line.trim().is_empty() {
            continue;
        }
        let mut entry: WALEntry = serde_json::from_str(&line)?;
        if !entry.verify() {
            return Err(failure("invalid WAL checksum"));
        }
        sequence = sequence.max(entry.sequence);
        report.examined += 1;
        if scope.matches(entry.event.tenant_id_str(), entry.event.entity_id_str()) {
            report.removed += 1;
        } else if scope.redact(&mut entry.event)? {
            report.redacted += 1;
            serde_json::to_writer(&mut *output, &entry)?;
            writeln!(output).map_err(io_error)?;
        } else {
            writeln!(output, "{line}").map_err(io_error)?;
        }
    }
    Ok((report, sequence))
}

/// Rewrite one partitioned event archive or compaction snapshot. Tenant identity
/// comes from the storage layout; row filtering preserves every existing column.
pub fn erase_parquet_file(
    root: &Path,
    path: &Path,
    scope: &ErasureScope,
    deadline: Instant,
) -> Result<ErasureReport> {
    if root.canonicalize().map_err(io_error)? != root {
        return Err(failure("storage root must be canonical"));
    }
    let relative = path
        .strip_prefix(root)
        .map_err(|_| failure("archive outside storage root"))?;
    let parts = relative.components().collect::<Vec<_>>();
    if parts.len() != 3
        || parts
            .iter()
            .any(|part| !matches!(part, Component::Normal(_)))
    {
        return Err(failure("partitioned tenant/month/file layout required"));
    }
    let tenant = parts[0]
        .as_os_str()
        .to_str()
        .ok_or_else(|| failure("invalid tenant path"))?;
    if tenant != scope.tenant {
        return Err(failure("archive belongs to a different tenant"));
    }
    if !path
        .file_name()
        .and_then(|name| name.to_str())
        .is_some_and(|name| name.ends_with(".parquet") || name.contains(".parquet."))
    {
        return Err(failure("expected a Parquet archive"));
    }
    rewrite(path, MAX_FILE_BYTES, deadline, |source, output| {
        scan_parquet(source, Some(output), scope, deadline)
    })
}

pub(super) fn scan_parquet(
    source: &mut File,
    output: Option<&mut File>,
    scope: &ErasureScope,
    deadline: Instant,
) -> Result<ErasureReport> {
    let reader = ParquetRecordBatchReaderBuilder::try_new(source.try_clone().map_err(io_error)?)?;
    let declared = reader
        .metadata()
        .row_groups()
        .iter()
        .try_fold(0u64, |sum, group| {
            let bytes = u64::try_from(group.total_byte_size())
                .map_err(|_| failure("invalid row-group size"))?;
            sum.checked_add(bytes)
                .ok_or_else(|| failure("row-group size overflow"))
        })?;
    if declared > MAX_DECODED_BYTES as u64 {
        return Err(failure("archive exceeds decoded byte limit"));
    }
    // The source codec is what the store wrote, so the rewrite keeps it.
    let codec = reader
        .metadata()
        .row_groups()
        .first()
        .and_then(|group| group.columns().first())
        .map_or(
            Compression::SNAPPY,
            parquet::file::metadata::ColumnChunkMetaData::compression,
        );
    let mut writer = output
        .map(|output| {
            let properties = WriterProperties::builder().set_compression(codec).build();
            ArrowWriter::try_new(output, reader.schema().clone(), Some(properties))
        })
        .transpose()?;
    let mut report = ErasureReport::default();
    for batch in reader.with_batch_size(64).build()? {
        check_deadline(deadline)?;
        let batch = batch?;
        if batch.get_array_memory_size() > MAX_DECODED_BYTES {
            return Err(failure("batch exceeds decoded byte limit"));
        }
        let ids = batch
            .column_by_name("entity_id")
            .and_then(|column| column.as_any().downcast_ref::<StringArray>())
            .ok_or_else(|| failure("invalid entity_id column"))?;
        if ids.null_count() > 0 {
            return Err(failure("null entity identity"));
        }
        let keep = BooleanArray::from(
            ids.iter()
                .map(|id| !scope.entities.contains(id.unwrap_or_default()))
                .collect::<Vec<_>>(),
        );
        let filtered = filter_record_batch(&batch, &keep)?;
        report.examined += batch.num_rows() as u64;
        report.removed += (batch.num_rows() - filtered.num_rows()) as u64;
        let (filtered, redacted) = redact_batch(filtered, scope)?;
        report.redacted += redacted;
        if let Some(writer) = writer.as_mut() {
            writer.write(&filtered)?;
        }
    }
    if let Some(writer) = writer {
        writer.close()?;
    }
    Ok(report)
}