iroh_blobs/store/
fs.rs

1//! # File based blob store.
2//!
3//! A file based blob store needs a writeable directory to work with.
4//!
5//! General design:
6//!
7//! The file store consists of two actors.
8//!
9//! # The main actor
10//!
11//! The purpose of the main actor is to handle user commands and own a map of
12//! handles for hashes that are currently being worked on.
13//!
14//! It also owns tasks for ongoing import and export operations, as well as the
15//! database actor.
16//!
17//! Handling a command almost always involves either forwarding it to the
18//! database actor or creating a hash context and spawning a task.
19//!
20//! # The database actor
21//!
22//! The database actor is responsible for storing metadata about each hash,
23//! as well as inlined data and outboard data for small files.
24//!
25//! In addition to the metadata, the database actor also stores tags.
26//!
27//! # Tasks
28//!
29//! Tasks do not return a result. They are responsible for sending an error
30//! to the requester if possible. Otherwise, just dropping the sender will
31//! also fail the receiver, but without a descriptive error message.
32//!
33//! Tasks are usually implemented as an impl fn that does return a result,
34//! and a wrapper (named `..._task`) that just forwards the error, if any.
35//!
36//! That way you can use `?` syntax in the task implementation. The impl fns
37//! are also easier to test.
38//!
39//! # Context
40//!
41//! The main actor holds a TaskContext that is needed for almost all tasks,
42//! such as the config and a way to interact with the database.
43//!
44//! For tasks that are specific to a hash, a HashContext combines the task
45//! context with a slot from the table of the main actor that can be used
46//! to obtain an unique handle for the hash.
47//!
48//! # Runtime
49//!
50//! The fs store owns and manages its own tokio runtime. Dropping the store
51//! will clean up the database and shut down the runtime. However, some parts
52//! of the persistent state won't make it to disk, so operations involving large
53//! partial blobs will have a large initial delay on the next startup.
54//!
55//! It is also not guaranteed that all write operations will make it to disk.
56//! The on-disk store will be in a consistent state, but might miss some writes
57//! in the last seconds before shutdown.
58//!
59//! To avoid this, you can use the [`crate::api::Store::shutdown`] method to
60//! cleanly shut down the store and save ephemeral state to disk.
61//!
62//! Note that if you use the store inside a [`iroh::protocol::Router`] and shut
63//! down the router using [`iroh::protocol::Router::shutdown`], the store will be
64//! safely shut down as well. Any store refs you are holding will be inoperable
65//! after this.
66use std::{
67    fmt::{self, Debug},
68    fs,
69    future::Future,
70    io::Write,
71    num::NonZeroU64,
72    ops::Deref,
73    path::{Path, PathBuf},
74    sync::{
75        atomic::{AtomicU64, Ordering},
76        Arc,
77    },
78};
79
80use bao_tree::{
81    blake3,
82    io::{
83        mixed::{traverse_ranges_validated, EncodedItem, ReadBytesAt},
84        outboard::PreOrderOutboard,
85        sync::ReadAt,
86        BaoContentItem, Leaf,
87    },
88    BaoTree, ChunkNum, ChunkRanges,
89};
90use bytes::Bytes;
91use delete_set::{BaoFilePart, ProtectHandle};
92use entity_manager::{EntityManagerState, SpawnArg};
93use entry_state::{DataLocation, OutboardLocation};
94use import::{ImportEntry, ImportSource};
95use irpc::{channel::mpsc, RpcMessage};
96use meta::list_blobs;
97use n0_error::{Result, StdResultExt};
98use n0_future::{future::yield_now, io};
99use nested_enum_utils::enum_conversions;
100use range_collections::range_set::RangeSetRange;
101use tokio::task::{JoinError, JoinSet};
102use tracing::{error, instrument, trace};
103
104use crate::{
105    api::{
106        proto::{
107            self, bitfield::is_validated, BatchMsg, BatchResponse, Bitfield, Command,
108            CreateTempTagMsg, ExportBaoMsg, ExportBaoRequest, ExportPathMsg, ExportPathRequest,
109            ExportRangesItem, ExportRangesMsg, ExportRangesRequest, HashSpecific, ImportBaoMsg,
110            ImportBaoRequest, ObserveMsg, Scope,
111        },
112        ApiClient,
113    },
114    protocol::ChunkRangesExt,
115    store::{
116        fs::{
117            bao_file::{
118                BaoFileStorage, BaoFileStorageSubscriber, CompleteStorage, DataReader,
119                OutboardReader,
120            },
121            util::entity_manager::{self, ActiveEntityState},
122        },
123        gc::run_gc,
124        util::{BaoTreeSender, FixedSize, MemOrFile, ValueOrPoisioned},
125        IROH_BLOCK_SIZE,
126    },
127    util::{
128        channel::oneshot,
129        temp_tag::{TagDrop, TempTag, TempTagScope, TempTags},
130    },
131    Hash,
132};
133mod bao_file;
134use bao_file::BaoFileHandle;
135mod delete_set;
136mod entry_state;
137mod import;
138mod meta;
139pub mod options;
140pub(crate) mod util;
141use entry_state::EntryState;
142use import::{import_byte_stream, import_bytes, import_path, ImportEntryMsg};
143use options::Options;
144use tracing::Instrument;
145
146use crate::{
147    api::{
148        self,
149        blobs::{AddProgressItem, ExportMode, ExportProgressItem},
150        Store,
151    },
152    HashAndFormat,
153};
154
155/// Maximum number of external paths we track per blob.
156const MAX_EXTERNAL_PATHS: usize = 8;
157
158/// Create a 16 byte unique ID.
159fn new_uuid() -> [u8; 16] {
160    use rand::RngCore;
161    let mut rng = rand::rng();
162    let mut bytes = [0u8; 16];
163    rng.fill_bytes(&mut bytes);
164    bytes
165}
166
167/// Create temp file name based on a 16 byte UUID.
168fn temp_name() -> String {
169    format!("{}.temp", hex::encode(new_uuid()))
170}
171
172#[derive(Debug)]
173#[enum_conversions()]
174pub(crate) enum InternalCommand {
175    Dump(meta::Dump),
176    FinishImport(ImportEntryMsg),
177    ClearScope(ClearScope),
178}
179
180#[derive(Debug)]
181pub(crate) struct ClearScope {
182    pub scope: Scope,
183}
184
185impl InternalCommand {
186    pub fn parent_span(&self) -> tracing::Span {
187        match self {
188            Self::Dump(_) => tracing::Span::current(),
189            Self::ClearScope(_) => tracing::Span::current(),
190            Self::FinishImport(cmd) => cmd
191                .parent_span_opt()
192                .cloned()
193                .unwrap_or_else(tracing::Span::current),
194        }
195    }
196}
197
198/// Context needed by most tasks
199#[derive(Debug)]
200struct TaskContext {
201    // Store options such as paths and inline thresholds, in an Arc to cheaply share with tasks.
202    pub options: Arc<Options>,
203    // Metadata database, basically a mpsc sender with some extra functionality.
204    pub db: meta::Db,
205    // Handle to send internal commands
206    pub internal_cmd_tx: tokio::sync::mpsc::Sender<InternalCommand>,
207    /// Handle to protect files from deletion.
208    pub protect: ProtectHandle,
209}
210
211impl TaskContext {
212    pub async fn clear_scope(&self, scope: Scope) {
213        self.internal_cmd_tx
214            .send(ClearScope { scope }.into())
215            .await
216            .ok();
217    }
218}
219
220#[derive(Debug)]
221struct EmParams;
222
223impl entity_manager::Params for EmParams {
224    type EntityId = Hash;
225
226    type GlobalState = Arc<TaskContext>;
227
228    type EntityState = BaoFileHandle;
229
230    async fn on_shutdown(
231        state: entity_manager::ActiveEntityState<Self>,
232        cause: entity_manager::ShutdownCause,
233    ) {
234        trace!("persist {:?} due to {cause:?}", state.id);
235        state.persist().await;
236    }
237}
238
239#[derive(Debug)]
240struct Actor {
241    // Context that can be cheaply shared with tasks.
242    context: Arc<TaskContext>,
243    // Receiver for incoming user commands.
244    cmd_rx: tokio::sync::mpsc::Receiver<Command>,
245    // Receiver for incoming file store specific commands.
246    fs_cmd_rx: tokio::sync::mpsc::Receiver<InternalCommand>,
247    // Tasks for import and export operations.
248    tasks: JoinSet<()>,
249    // Entity manager that handles concurrency for entities.
250    handles: EntityManagerState<EmParams>,
251    // temp tags
252    temp_tags: TempTags,
253    // waiters for idle state.
254    idle_waiters: Vec<irpc::channel::oneshot::Sender<()>>,
255    // our private tokio runtime. It has to live somewhere.
256    _rt: RtWrapper,
257}
258
259type HashContext = ActiveEntityState<EmParams>;
260
261impl SyncEntityApi for HashContext {
262    /// Load the state from the database.
263    ///
264    /// If the state is Initial, this will start the load.
265    /// If it is Loading, it will wait until loading is done.
266    /// If it is any other state, it will be a noop.
267    async fn load(&self) {
268        enum Action {
269            Load,
270            Wait,
271            None,
272        }
273        let mut action = Action::None;
274        self.state.send_if_modified(|guard| match guard.deref() {
275            BaoFileStorage::Initial => {
276                *guard = BaoFileStorage::Loading;
277                action = Action::Load;
278                true
279            }
280            BaoFileStorage::Loading => {
281                action = Action::Wait;
282                false
283            }
284            _ => false,
285        });
286        match action {
287            Action::Load => {
288                let state = if self.id == Hash::EMPTY {
289                    BaoFileStorage::Complete(CompleteStorage {
290                        data: MemOrFile::Mem(Bytes::new()),
291                        outboard: MemOrFile::empty(),
292                    })
293                } else {
294                    // we must assign a new state even in the error case, otherwise
295                    // tasks waiting for loading would stall!
296                    match self.global.db.get(self.id).await {
297                        Ok(state) => match BaoFileStorage::open(state, self).await {
298                            Ok(handle) => handle,
299                            Err(_) => BaoFileStorage::Poisoned,
300                        },
301                        Err(_) => BaoFileStorage::Poisoned,
302                    }
303                };
304                self.state.send_replace(state);
305            }
306            Action::Wait => {
307                // we are in state loading already, so we just need to wait for the
308                // other task to complete loading.
309                while matches!(self.state.borrow().deref(), BaoFileStorage::Loading) {
310                    self.state.0.subscribe().changed().await.ok();
311                }
312            }
313            Action::None => {}
314        }
315    }
316
317    /// Write a batch and notify the db
318    async fn write_batch(&self, batch: &[BaoContentItem], bitfield: &Bitfield) -> io::Result<()> {
319        trace!("write_batch bitfield={:?} batch={}", bitfield, batch.len());
320        let mut res = Ok(None);
321        self.state.send_if_modified(|state| {
322            let Ok((state1, update)) = state.take().write_batch(batch, bitfield, self) else {
323                res = Err(io::Error::other("write batch failed"));
324                return false;
325            };
326            res = Ok(update);
327            *state = state1;
328            true
329        });
330        if let Some(update) = res? {
331            self.global.db.update(self.id, update).await?;
332        }
333        Ok(())
334    }
335
336    /// An AsyncSliceReader for the data file.
337    ///
338    /// Caution: this is a reader for the unvalidated data file. Reading this
339    /// can produce data that does not match the hash.
340    #[allow(refining_impl_trait_internal)]
341    fn data_reader(&self) -> DataReader {
342        DataReader(self.state.clone())
343    }
344
345    /// An AsyncSliceReader for the outboard file.
346    ///
347    /// The outboard file is used to validate the data file. It is not guaranteed
348    /// to be complete.
349    #[allow(refining_impl_trait_internal)]
350    fn outboard_reader(&self) -> OutboardReader {
351        OutboardReader(self.state.clone())
352    }
353
354    /// The most precise known total size of the data file.
355    fn current_size(&self) -> io::Result<u64> {
356        match self.state.borrow().deref() {
357            BaoFileStorage::Complete(mem) => Ok(mem.size()),
358            BaoFileStorage::PartialMem(mem) => Ok(mem.current_size()),
359            BaoFileStorage::Partial(file) => file.current_size(),
360            BaoFileStorage::Poisoned => Err(io::Error::other("poisoned storage")),
361            BaoFileStorage::Initial => Err(io::Error::other("initial")),
362            BaoFileStorage::Loading => Err(io::Error::other("loading")),
363            BaoFileStorage::NonExisting => Err(io::ErrorKind::NotFound.into()),
364        }
365    }
366
367    /// The most precise known total size of the data file.
368    fn bitfield(&self) -> io::Result<Bitfield> {
369        match self.state.borrow().deref() {
370            BaoFileStorage::Complete(mem) => Ok(mem.bitfield()),
371            BaoFileStorage::PartialMem(mem) => Ok(mem.bitfield().clone()),
372            BaoFileStorage::Partial(file) => Ok(file.bitfield().clone()),
373            BaoFileStorage::Poisoned => Err(io::Error::other("poisoned storage")),
374            BaoFileStorage::Initial => Err(io::Error::other("initial")),
375            BaoFileStorage::Loading => Err(io::Error::other("loading")),
376            BaoFileStorage::NonExisting => Err(io::ErrorKind::NotFound.into()),
377        }
378    }
379}
380
381impl HashContext {
382    /// The outboard for the file.
383    pub fn outboard(&self) -> io::Result<PreOrderOutboard<OutboardReader>> {
384        let tree = BaoTree::new(self.current_size()?, IROH_BLOCK_SIZE);
385        let outboard = self.outboard_reader();
386        Ok(PreOrderOutboard {
387            root: blake3::Hash::from(self.id),
388            tree,
389            data: outboard,
390        })
391    }
392
393    fn db(&self) -> &meta::Db {
394        &self.global.db
395    }
396
397    pub fn options(&self) -> &Arc<Options> {
398        &self.global.options
399    }
400
401    pub fn protect(&self, parts: impl IntoIterator<Item = BaoFilePart>) {
402        self.global.protect.protect(self.id, parts);
403    }
404
405    /// Update the entry state in the database, and wait for completion.
406    pub async fn update_await(&self, state: EntryState<Bytes>) -> io::Result<()> {
407        self.db().update_await(self.id, state).await?;
408        Ok(())
409    }
410
411    pub async fn get_entry_state(&self) -> io::Result<Option<EntryState<Bytes>>> {
412        let hash = self.id;
413        if hash == Hash::EMPTY {
414            return Ok(Some(EntryState::Complete {
415                data_location: DataLocation::Inline(Bytes::new()),
416                outboard_location: OutboardLocation::NotNeeded,
417            }));
418        };
419        self.db().get(hash).await
420    }
421
422    /// Update the entry state in the database, and wait for completion.
423    pub async fn set(&self, state: EntryState<Bytes>) -> io::Result<()> {
424        self.db().set(self.id, state).await
425    }
426}
427
428impl Actor {
429    fn db(&self) -> &meta::Db {
430        &self.context.db
431    }
432
433    fn context(&self) -> Arc<TaskContext> {
434        self.context.clone()
435    }
436
437    fn spawn(&mut self, fut: impl Future<Output = ()> + Send + 'static) {
438        let span = tracing::Span::current();
439        self.tasks.spawn(fut.instrument(span));
440    }
441
442    fn log_task_result(res: Result<(), JoinError>) {
443        match res {
444            Ok(_) => {}
445            Err(e) => {
446                error!("task failed: {e}");
447            }
448        }
449    }
450
451    async fn create_temp_tag(&mut self, cmd: CreateTempTagMsg) {
452        let CreateTempTagMsg { tx, inner, .. } = cmd;
453        let mut tt = self.temp_tags.create(inner.scope, inner.value);
454        if tx.is_rpc() {
455            tt.leak();
456        }
457        tx.send(tt).await.ok();
458    }
459
460    async fn handle_command(&mut self, cmd: Command) {
461        let span = cmd.parent_span();
462        let _entered = span.enter();
463        match cmd {
464            Command::SyncDb(cmd) => {
465                trace!("{cmd:?}");
466                self.db().send(cmd.into()).await.ok();
467            }
468            Command::WaitIdle(cmd) => {
469                trace!("{cmd:?}");
470                if self.tasks.is_empty() {
471                    // we are currently idle
472                    cmd.tx.send(()).await.ok();
473                } else {
474                    // wait for idle state
475                    self.idle_waiters.push(cmd.tx);
476                }
477            }
478            Command::Shutdown(cmd) => {
479                trace!("{cmd:?}");
480                self.db().send(cmd.into()).await.ok();
481            }
482            Command::CreateTag(cmd) => {
483                trace!("{cmd:?}");
484                self.db().send(cmd.into()).await.ok();
485            }
486            Command::SetTag(cmd) => {
487                trace!("{cmd:?}");
488                self.db().send(cmd.into()).await.ok();
489            }
490            Command::ListTags(cmd) => {
491                trace!("{cmd:?}");
492                self.db().send(cmd.into()).await.ok();
493            }
494            Command::DeleteTags(cmd) => {
495                trace!("{cmd:?}");
496                self.db().send(cmd.into()).await.ok();
497            }
498            Command::RenameTag(cmd) => {
499                trace!("{cmd:?}");
500                self.db().send(cmd.into()).await.ok();
501            }
502            Command::ClearProtected(cmd) => {
503                trace!("{cmd:?}");
504                self.db().send(cmd.into()).await.ok();
505            }
506            Command::BlobStatus(cmd) => {
507                trace!("{cmd:?}");
508                self.db().send(cmd.into()).await.ok();
509            }
510            Command::DeleteBlobs(cmd) => {
511                trace!("{cmd:?}");
512                self.db().send(cmd.into()).await.ok();
513            }
514            Command::ListBlobs(cmd) => {
515                trace!("{cmd:?}");
516                if let Ok(snapshot) = self.db().snapshot(cmd.span.clone()).await {
517                    self.spawn(list_blobs(snapshot, cmd));
518                }
519            }
520            Command::Batch(cmd) => {
521                trace!("{cmd:?}");
522                let (id, scope) = self.temp_tags.create_scope();
523                self.spawn(handle_batch(cmd, id, scope, self.context()));
524            }
525            Command::CreateTempTag(cmd) => {
526                trace!("{cmd:?}");
527                self.create_temp_tag(cmd).await;
528            }
529            Command::ListTempTags(cmd) => {
530                trace!("{cmd:?}");
531                let tts = self.temp_tags.list();
532                cmd.tx.send(tts).await.ok();
533            }
534            Command::ImportBytes(cmd) => {
535                trace!("{cmd:?}");
536                self.spawn(import_bytes(cmd, self.context()));
537            }
538            Command::ImportByteStream(cmd) => {
539                trace!("{cmd:?}");
540                self.spawn(import_byte_stream(cmd, self.context()));
541            }
542            Command::ImportPath(cmd) => {
543                trace!("{cmd:?}");
544                self.spawn(import_path(cmd, self.context()));
545            }
546            Command::ExportPath(cmd) => {
547                trace!("{cmd:?}");
548                cmd.spawn(&mut self.handles, &mut self.tasks).await;
549            }
550            Command::ExportBao(cmd) => {
551                trace!("{cmd:?}");
552                cmd.spawn(&mut self.handles, &mut self.tasks).await;
553            }
554            Command::ExportRanges(cmd) => {
555                trace!("{cmd:?}");
556                cmd.spawn(&mut self.handles, &mut self.tasks).await;
557            }
558            Command::ImportBao(cmd) => {
559                trace!("{cmd:?}");
560                cmd.spawn(&mut self.handles, &mut self.tasks).await;
561            }
562            Command::Observe(cmd) => {
563                trace!("{cmd:?}");
564                cmd.spawn(&mut self.handles, &mut self.tasks).await;
565            }
566        }
567    }
568
569    async fn handle_fs_command(&mut self, cmd: InternalCommand) {
570        let span = cmd.parent_span();
571        let _entered = span.enter();
572        match cmd {
573            InternalCommand::Dump(cmd) => {
574                trace!("{cmd:?}");
575                self.db().send(cmd.into()).await.ok();
576            }
577            InternalCommand::ClearScope(cmd) => {
578                trace!("{cmd:?}");
579                self.temp_tags.end_scope(cmd.scope);
580            }
581            InternalCommand::FinishImport(cmd) => {
582                trace!("{cmd:?}");
583                if cmd.hash == Hash::EMPTY {
584                    cmd.tx
585                        .send(AddProgressItem::Done(TempTag::leaking_empty(cmd.format)))
586                        .await
587                        .ok();
588                } else {
589                    let tt = self.temp_tags.create(
590                        cmd.scope,
591                        HashAndFormat {
592                            hash: cmd.hash,
593                            format: cmd.format,
594                        },
595                    );
596                    (tt, cmd).spawn(&mut self.handles, &mut self.tasks).await;
597                }
598            }
599        }
600    }
601
602    async fn run(mut self) {
603        loop {
604            tokio::select! {
605                task = self.handles.tick() => {
606                    if let Some(task) = task {
607                        self.spawn(task);
608                    }
609                }
610                cmd = self.cmd_rx.recv() => {
611                    let Some(cmd) = cmd else {
612                        break;
613                    };
614                    self.handle_command(cmd).await;
615                }
616                Some(cmd) = self.fs_cmd_rx.recv() => {
617                    self.handle_fs_command(cmd).await;
618                }
619                Some(res) = self.tasks.join_next(), if !self.tasks.is_empty() => {
620                    Self::log_task_result(res);
621                    if self.tasks.is_empty() {
622                        for tx in self.idle_waiters.drain(..) {
623                            tx.send(()).await.ok();
624                        }
625                    }
626                }
627            }
628        }
629        self.handles.shutdown().await;
630        while let Some(res) = self.tasks.join_next().await {
631            Self::log_task_result(res);
632        }
633    }
634
635    async fn new(
636        db_path: PathBuf,
637        rt: RtWrapper,
638        cmd_rx: tokio::sync::mpsc::Receiver<Command>,
639        fs_commands_rx: tokio::sync::mpsc::Receiver<InternalCommand>,
640        fs_commands_tx: tokio::sync::mpsc::Sender<InternalCommand>,
641        options: Arc<Options>,
642    ) -> Result<Self> {
643        trace!(
644            "creating data directory: {}",
645            options.path.data_path.display()
646        );
647        fs::create_dir_all(&options.path.data_path)?;
648        trace!(
649            "creating temp directory: {}",
650            options.path.temp_path.display()
651        );
652        fs::create_dir_all(&options.path.temp_path)?;
653        trace!(
654            "creating parent directory for db file{}",
655            db_path.parent().unwrap().display()
656        );
657        fs::create_dir_all(db_path.parent().unwrap())?;
658        let (db_send, db_recv) = tokio::sync::mpsc::channel(100);
659        let (protect, ds) = delete_set::pair(Arc::new(options.path.clone()));
660        let db_actor = meta::Actor::new(db_path, db_recv, ds, options.batch.clone())?;
661        let slot_context = Arc::new(TaskContext {
662            options: options.clone(),
663            db: meta::Db::new(db_send),
664            internal_cmd_tx: fs_commands_tx,
665            protect,
666        });
667        rt.spawn(db_actor.run());
668        Ok(Self {
669            context: slot_context.clone(),
670            cmd_rx,
671            fs_cmd_rx: fs_commands_rx,
672            tasks: JoinSet::new(),
673            handles: EntityManagerState::new(slot_context, 1024, 32, 32, 2),
674            temp_tags: Default::default(),
675            idle_waiters: Vec::new(),
676            _rt: rt,
677        })
678    }
679}
680
681trait HashSpecificCommand: HashSpecific + Send + 'static {
682    /// Handle the command on success by spawning a task into the per-hash context.
683    fn handle(self, ctx: HashContext) -> impl Future<Output = ()> + Send + 'static;
684
685    /// Opportunity to send an error if spawning fails due to the task being busy (inbox full)
686    /// or dead (e.g. panic in one of the running tasks).
687    fn on_error(self, arg: SpawnArg<EmParams>) -> impl Future<Output = ()> + Send + 'static;
688
689    async fn spawn(
690        self,
691        manager: &mut entity_manager::EntityManagerState<EmParams>,
692        tasks: &mut JoinSet<()>,
693    ) where
694        Self: Sized,
695    {
696        let span = tracing::Span::current();
697        let task = manager
698            .spawn(self.hash(), |arg| {
699                async move {
700                    match arg {
701                        SpawnArg::Active(state) => {
702                            self.handle(state).await;
703                        }
704                        SpawnArg::Busy => {
705                            self.on_error(arg).await;
706                        }
707                        SpawnArg::Dead => {
708                            self.on_error(arg).await;
709                        }
710                    }
711                }
712                .instrument(span)
713            })
714            .await;
715        if let Some(task) = task {
716            tasks.spawn(task);
717        }
718    }
719}
720
721impl HashSpecificCommand for ObserveMsg {
722    async fn handle(self, ctx: HashContext) {
723        ctx.observe(self).await
724    }
725    async fn on_error(self, _arg: SpawnArg<EmParams>) {}
726}
727impl HashSpecificCommand for ExportPathMsg {
728    async fn handle(self, ctx: HashContext) {
729        ctx.export_path(self).await
730    }
731    async fn on_error(self, arg: SpawnArg<EmParams>) {
732        let err = match arg {
733            SpawnArg::Busy => io::ErrorKind::ResourceBusy.into(),
734            SpawnArg::Dead => err_entity_dead(),
735            _ => unreachable!(),
736        };
737        self.tx
738            .send(ExportProgressItem::Error(api::Error::from(err)))
739            .await
740            .ok();
741    }
742}
743impl HashSpecificCommand for ExportBaoMsg {
744    async fn handle(self, ctx: HashContext) {
745        ctx.export_bao(self).await
746    }
747    async fn on_error(self, arg: SpawnArg<EmParams>) {
748        let err = match arg {
749            SpawnArg::Busy => io::ErrorKind::ResourceBusy.into(),
750            SpawnArg::Dead => err_entity_dead(),
751            _ => unreachable!(),
752        };
753        self.tx
754            .send(EncodedItem::Error(bao_tree::io::EncodeError::Io(err)))
755            .await
756            .ok();
757    }
758}
759impl HashSpecificCommand for ExportRangesMsg {
760    async fn handle(self, ctx: HashContext) {
761        ctx.export_ranges(self).await
762    }
763    async fn on_error(self, arg: SpawnArg<EmParams>) {
764        let err = match arg {
765            SpawnArg::Busy => io::ErrorKind::ResourceBusy.into(),
766            SpawnArg::Dead => err_entity_dead(),
767            _ => unreachable!(),
768        };
769        self.tx
770            .send(ExportRangesItem::Error(api::Error::from(err)))
771            .await
772            .ok();
773    }
774}
775impl HashSpecificCommand for ImportBaoMsg {
776    async fn handle(self, ctx: HashContext) {
777        ctx.import_bao(self).await
778    }
779    async fn on_error(self, arg: SpawnArg<EmParams>) {
780        let err = match arg {
781            SpawnArg::Busy => io::ErrorKind::ResourceBusy.into(),
782            SpawnArg::Dead => err_entity_dead(),
783            _ => unreachable!(),
784        };
785        self.tx.send(Err(api::Error::from(err))).await.ok();
786    }
787}
788impl HashSpecific for (TempTag, ImportEntryMsg) {
789    fn hash(&self) -> Hash {
790        self.1.hash()
791    }
792}
793impl HashSpecificCommand for (TempTag, ImportEntryMsg) {
794    async fn handle(self, ctx: HashContext) {
795        let (tt, cmd) = self;
796        ctx.finish_import(cmd, tt).await
797    }
798    async fn on_error(self, arg: SpawnArg<EmParams>) {
799        let err = match arg {
800            SpawnArg::Busy => io::ErrorKind::ResourceBusy.into(),
801            SpawnArg::Dead => err_entity_dead(),
802            _ => unreachable!(),
803        };
804        self.1.tx.send(AddProgressItem::Error(err)).await.ok();
805    }
806}
807
808fn err_entity_dead() -> io::Error {
809    io::Error::other("entity is dead")
810}
811
812struct RtWrapper(Option<tokio::runtime::Runtime>);
813
814impl From<tokio::runtime::Runtime> for RtWrapper {
815    fn from(rt: tokio::runtime::Runtime) -> Self {
816        Self(Some(rt))
817    }
818}
819
820impl fmt::Debug for RtWrapper {
821    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
822        ValueOrPoisioned(self.0.as_ref()).fmt(f)
823    }
824}
825
826impl Deref for RtWrapper {
827    type Target = tokio::runtime::Runtime;
828
829    fn deref(&self) -> &Self::Target {
830        self.0.as_ref().unwrap()
831    }
832}
833
834impl Drop for RtWrapper {
835    fn drop(&mut self) {
836        if let Some(rt) = self.0.take() {
837            trace!("dropping tokio runtime");
838            tokio::task::block_in_place(|| {
839                drop(rt);
840            });
841            trace!("dropped tokio runtime");
842        }
843    }
844}
845
846async fn handle_batch(cmd: BatchMsg, id: Scope, scope: Arc<TempTagScope>, ctx: Arc<TaskContext>) {
847    if let Err(cause) = handle_batch_impl(cmd, id, &scope).await {
848        error!("batch failed: {cause}");
849    }
850    ctx.clear_scope(id).await;
851}
852
853async fn handle_batch_impl(cmd: BatchMsg, id: Scope, scope: &Arc<TempTagScope>) -> api::Result<()> {
854    let BatchMsg { tx, mut rx, .. } = cmd;
855    trace!("created scope {}", id);
856    tx.send(id).await?;
857    while let Some(msg) = rx.recv().await? {
858        match msg {
859            BatchResponse::Drop(msg) => scope.on_drop(&msg),
860            BatchResponse::Ping => {}
861        }
862    }
863    Ok(())
864}
865
866/// The minimal API you need to implement for an entity for a store to work.
867trait EntityApi {
868    /// Import from a stream of n0 bao encoded data.
869    async fn import_bao(&self, cmd: ImportBaoMsg);
870    /// Finish an import from a local file or memory.
871    async fn finish_import(&self, cmd: ImportEntryMsg, tt: TempTag);
872    /// Observe the bitfield of the entry.
873    async fn observe(&self, cmd: ObserveMsg);
874    /// Export byte ranges of the entry as data
875    async fn export_ranges(&self, cmd: ExportRangesMsg);
876    /// Export chunk ranges of the entry as a n0 bao encoded stream.
877    async fn export_bao(&self, cmd: ExportBaoMsg);
878    /// Export the entry to a local file.
879    async fn export_path(&self, cmd: ExportPathMsg);
880    /// Persist the entry at the end of its lifecycle.
881    async fn persist(&self);
882}
883
884/// A more opinionated API that can be used as a helper to save implementation
885/// effort when implementing the EntityApi trait.
886trait SyncEntityApi: EntityApi {
887    /// Load the entry state from the database. This must make sure that it is
888    /// not run concurrently, so if load is called multiple times, all but one
889    /// must wait. You can use a tokio::sync::OnceCell or similar to achieve this.
890    async fn load(&self);
891
892    /// Get a synchronous reader for the data file.
893    fn data_reader(&self) -> impl ReadBytesAt;
894
895    /// Get a synchronous reader for the outboard file.
896    fn outboard_reader(&self) -> impl ReadAt;
897
898    /// Get the best known size of the data file.
899    fn current_size(&self) -> io::Result<u64>;
900
901    /// Get the bitfield of the entry.
902    fn bitfield(&self) -> io::Result<Bitfield>;
903
904    /// Write a batch of content items to the entry.
905    async fn write_batch(&self, batch: &[BaoContentItem], bitfield: &Bitfield) -> io::Result<()>;
906}
907
908/// The high level entry point per entry.
909impl EntityApi for HashContext {
910    #[instrument(skip_all, fields(hash = %cmd.hash_short()))]
911    async fn import_bao(&self, cmd: ImportBaoMsg) {
912        trace!("{cmd:?}");
913        self.load().await;
914        let ImportBaoMsg {
915            inner: ImportBaoRequest { size, .. },
916            rx,
917            tx,
918            ..
919        } = cmd;
920        let res = import_bao_impl(self, size, rx).await;
921        trace!("{res:?}");
922        tx.send(res).await.ok();
923    }
924
925    #[instrument(skip_all, fields(hash = %cmd.hash_short()))]
926    async fn observe(&self, cmd: ObserveMsg) {
927        trace!("{cmd:?}");
928        self.load().await;
929        BaoFileStorageSubscriber::new(self.state.subscribe())
930            .forward(cmd.tx)
931            .await
932            .ok();
933    }
934
935    #[instrument(skip_all, fields(hash = %cmd.hash_short()))]
936    async fn export_ranges(&self, mut cmd: ExportRangesMsg) {
937        trace!("{cmd:?}");
938        self.load().await;
939        if let Err(cause) = export_ranges_impl(self, cmd.inner, &mut cmd.tx).await {
940            cmd.tx
941                .send(ExportRangesItem::Error(cause.into()))
942                .await
943                .ok();
944        }
945    }
946
947    #[instrument(skip_all, fields(hash = %cmd.hash_short()))]
948    async fn export_bao(&self, mut cmd: ExportBaoMsg) {
949        trace!("{cmd:?}");
950        self.load().await;
951        if let Err(cause) = export_bao_impl(self, cmd.inner, &mut cmd.tx).await {
952            // if the entry is in state NonExisting, this will be an io error with
953            // kind NotFound. So we must not wrap this somehow but pass it on directly.
954            cmd.tx
955                .send(bao_tree::io::EncodeError::Io(cause).into())
956                .await
957                .ok();
958        }
959    }
960
961    #[instrument(skip_all, fields(hash = %cmd.hash_short()))]
962    async fn export_path(&self, cmd: ExportPathMsg) {
963        trace!("{cmd:?}");
964        self.load().await;
965        let ExportPathMsg { inner, mut tx, .. } = cmd;
966        if let Err(cause) = export_path_impl(self, inner, &mut tx).await {
967            tx.send(cause.into()).await.ok();
968        }
969    }
970
971    #[instrument(skip_all, fields(hash = %cmd.hash_short()))]
972    async fn finish_import(&self, cmd: ImportEntryMsg, mut tt: TempTag) {
973        trace!("{cmd:?}");
974        self.load().await;
975        let res = match finish_import_impl(self, cmd.inner).await {
976            Ok(()) => {
977                // for a remote call, we can't have the on_drop callback, so we have to leak the temp tag
978                // it will be cleaned up when either the process exits or scope ends
979                if cmd.tx.is_rpc() {
980                    trace!("leaking temp tag {}", tt.hash_and_format());
981                    tt.leak();
982                }
983                AddProgressItem::Done(tt)
984            }
985            Err(cause) => AddProgressItem::Error(cause),
986        };
987        cmd.tx.send(res).await.ok();
988    }
989
990    #[instrument(skip_all, fields(hash = %self.id.fmt_short()))]
991    async fn persist(&self) {
992        self.state.send_if_modified(|guard| {
993            let hash = &self.id;
994            let BaoFileStorage::Partial(fs) = guard.take() else {
995                return false;
996            };
997            let path = self.global.options.path.bitfield_path(hash);
998            trace!("writing bitfield for hash {} to {}", hash, path.display());
999            if let Err(cause) = fs.sync_all(&path) {
1000                error!(
1001                    "failed to write bitfield for {} at {}: {:?}",
1002                    hash,
1003                    path.display(),
1004                    cause
1005                );
1006            }
1007            false
1008        });
1009    }
1010}
1011
1012async fn finish_import_impl(ctx: &HashContext, import_data: ImportEntry) -> io::Result<()> {
1013    if ctx.id == Hash::EMPTY {
1014        return Ok(()); // nothing to do for the empty hash
1015    }
1016    let ImportEntry {
1017        source,
1018        hash,
1019        outboard,
1020        ..
1021    } = import_data;
1022    let options = ctx.options();
1023    match &source {
1024        ImportSource::Memory(data) => {
1025            debug_assert!(options.is_inlined_data(data.len() as u64));
1026        }
1027        ImportSource::External(_, _, size) => {
1028            debug_assert!(!options.is_inlined_data(*size));
1029        }
1030        ImportSource::TempFile(_, _, size) => {
1031            debug_assert!(!options.is_inlined_data(*size));
1032        }
1033    }
1034    ctx.load().await;
1035    let handle = &ctx.state;
1036    // if I do have an existing handle, I have to possibly deal with observers.
1037    // if I don't have an existing handle, there are 2 cases:
1038    //   the entry exists in the db, but we don't have a handle
1039    //   the entry does not exist at all.
1040    // convert the import source to a data location and drop the open files
1041    ctx.protect([BaoFilePart::Data, BaoFilePart::Outboard]);
1042    let data_location = match source {
1043        ImportSource::Memory(data) => DataLocation::Inline(data),
1044        ImportSource::External(path, _file, size) => DataLocation::External(vec![path], size),
1045        ImportSource::TempFile(path, _file, size) => {
1046            // this will always work on any unix, but on windows there might be an issue if the target file is open!
1047            // possibly open with FILE_SHARE_DELETE on windows?
1048            let target = ctx.options().path.data_path(&hash);
1049            trace!(
1050                "moving temp file to owned data location: {} -> {}",
1051                path.display(),
1052                target.display()
1053            );
1054            if let Err(cause) = fs::rename(&path, &target) {
1055                error!(
1056                    "failed to move temp file {} to owned data location {}: {cause}",
1057                    path.display(),
1058                    target.display()
1059                );
1060            }
1061            DataLocation::Owned(size)
1062        }
1063    };
1064    let outboard_location = match outboard {
1065        MemOrFile::Mem(bytes) if bytes.is_empty() => OutboardLocation::NotNeeded,
1066        MemOrFile::Mem(bytes) => OutboardLocation::Inline(bytes),
1067        MemOrFile::File(path) => {
1068            // the same caveat as above applies here
1069            let target = ctx.options().path.outboard_path(&hash);
1070            trace!(
1071                "moving temp file to owned outboard location: {} -> {}",
1072                path.display(),
1073                target.display()
1074            );
1075            if let Err(cause) = fs::rename(&path, &target) {
1076                error!(
1077                    "failed to move temp file {} to owned outboard location {}: {cause}",
1078                    path.display(),
1079                    target.display()
1080                );
1081            }
1082            OutboardLocation::Owned
1083        }
1084    };
1085    let data = match &data_location {
1086        DataLocation::Inline(data) => MemOrFile::Mem(data.clone()),
1087        DataLocation::Owned(size) => {
1088            let path = ctx.options().path.data_path(&hash);
1089            let file = fs::File::open(&path)?;
1090            MemOrFile::File(FixedSize::new(file, *size))
1091        }
1092        DataLocation::External(paths, size) => {
1093            let Some(path) = paths.iter().next() else {
1094                return Err(io::Error::other("no external data path"));
1095            };
1096            let file = fs::File::open(path)?;
1097            MemOrFile::File(FixedSize::new(file, *size))
1098        }
1099    };
1100    let outboard = match &outboard_location {
1101        OutboardLocation::NotNeeded => MemOrFile::empty(),
1102        OutboardLocation::Inline(data) => MemOrFile::Mem(data.clone()),
1103        OutboardLocation::Owned => {
1104            let path = ctx.options().path.outboard_path(&hash);
1105            let file = fs::File::open(&path)?;
1106            MemOrFile::File(file)
1107        }
1108    };
1109    handle.complete(data, outboard);
1110    let state = EntryState::Complete {
1111        data_location,
1112        outboard_location,
1113    };
1114    ctx.update_await(state).await?;
1115    Ok(())
1116}
1117
1118fn chunk_range(leaf: &Leaf) -> ChunkRanges {
1119    let start = ChunkNum::chunks(leaf.offset);
1120    let end = ChunkNum::chunks(leaf.offset + leaf.data.len() as u64);
1121    (start..end).into()
1122}
1123
1124async fn import_bao_impl(
1125    ctx: &HashContext,
1126    size: NonZeroU64,
1127    mut rx: mpsc::Receiver<BaoContentItem>,
1128) -> api::Result<()> {
1129    trace!("importing bao: {} {} bytes", ctx.id.fmt_short(), size);
1130    let mut batch = Vec::<BaoContentItem>::new();
1131    let mut ranges = ChunkRanges::empty();
1132    while let Some(item) = rx.recv().await? {
1133        // if the batch is not empty, the last item is a leaf and the current item is a parent, write the batch
1134        if !batch.is_empty() && batch[batch.len() - 1].is_leaf() && item.is_parent() {
1135            let bitfield = Bitfield::new_unchecked(ranges, size.into());
1136            ctx.write_batch(&batch, &bitfield).await?;
1137            batch.clear();
1138            ranges = ChunkRanges::empty();
1139        }
1140        if let BaoContentItem::Leaf(leaf) = &item {
1141            let leaf_range = chunk_range(leaf);
1142            if is_validated(size, &leaf_range) && size.get() != leaf.offset + leaf.data.len() as u64
1143            {
1144                return Err(api::Error::io(io::ErrorKind::InvalidData, "invalid size"));
1145            }
1146            ranges |= leaf_range;
1147        }
1148        batch.push(item);
1149    }
1150    if !batch.is_empty() {
1151        let bitfield = Bitfield::new_unchecked(ranges, size.into());
1152        ctx.write_batch(&batch, &bitfield).await?;
1153    }
1154    Ok(())
1155}
1156
1157async fn export_ranges_impl(
1158    ctx: &HashContext,
1159    cmd: ExportRangesRequest,
1160    tx: &mut mpsc::Sender<ExportRangesItem>,
1161) -> io::Result<()> {
1162    let ExportRangesRequest { ranges, hash } = cmd;
1163    trace!(
1164        "exporting ranges: {hash} {ranges:?} size={}",
1165        ctx.current_size()?
1166    );
1167    let bitfield = ctx.bitfield()?;
1168    let data = ctx.data_reader();
1169    let size = bitfield.size();
1170    for range in ranges.iter() {
1171        let range = match range {
1172            RangeSetRange::Range(range) => size.min(*range.start)..size.min(*range.end),
1173            RangeSetRange::RangeFrom(range) => size.min(*range.start)..size,
1174        };
1175        let requested = ChunkRanges::bytes(range.start..range.end);
1176        if !bitfield.ranges.is_superset(&requested) {
1177            return Err(io::Error::other(format!(
1178                "missing range: {requested:?}, present: {bitfield:?}",
1179            )));
1180        }
1181        let bs = 1024;
1182        let mut offset = range.start;
1183        loop {
1184            let end: u64 = (offset + bs).min(range.end);
1185            let size = (end - offset) as usize;
1186            let res = data.read_bytes_at(offset, size);
1187            tx.send(ExportRangesItem::Data(Leaf { offset, data: res? }))
1188                .await?;
1189            offset = end;
1190            if offset >= range.end {
1191                break;
1192            }
1193        }
1194    }
1195    Ok(())
1196}
1197
1198async fn export_bao_impl(
1199    ctx: &HashContext,
1200    cmd: ExportBaoRequest,
1201    tx: &mut mpsc::Sender<EncodedItem>,
1202) -> io::Result<()> {
1203    let ExportBaoRequest { ranges, hash, .. } = cmd;
1204    let outboard = ctx.outboard()?;
1205    let size = outboard.tree.size();
1206    if size == 0 && cmd.hash != Hash::EMPTY {
1207        // we have no data whatsoever, so we stop here
1208        return Ok(());
1209    }
1210    trace!("exporting bao: {hash} {ranges:?} size={size}",);
1211    let data = ctx.data_reader();
1212    let tx = BaoTreeSender::new(tx);
1213    traverse_ranges_validated(data, outboard, &ranges, tx).await?;
1214    Ok(())
1215}
1216
1217async fn export_path_impl(
1218    ctx: &HashContext,
1219    cmd: ExportPathRequest,
1220    tx: &mut mpsc::Sender<ExportProgressItem>,
1221) -> api::Result<()> {
1222    let ExportPathRequest { mode, target, .. } = cmd;
1223    if !target.is_absolute() {
1224        return Err(api::Error::io(
1225            io::ErrorKind::InvalidInput,
1226            "path is not absolute",
1227        ));
1228    }
1229    if let Some(parent) = target.parent() {
1230        fs::create_dir_all(parent)?;
1231    }
1232    let state = ctx.get_entry_state().await?;
1233    let (data_location, outboard_location) = match state {
1234        Some(EntryState::Complete {
1235            data_location,
1236            outboard_location,
1237        }) => (data_location, outboard_location),
1238        Some(EntryState::Partial { .. }) => {
1239            return Err(api::Error::io(
1240                io::ErrorKind::InvalidInput,
1241                "cannot export partial entry",
1242            ));
1243        }
1244        None => {
1245            return Err(api::Error::io(io::ErrorKind::NotFound, "no entry found"));
1246        }
1247    };
1248    trace!("exporting {} to {}", cmd.hash.to_hex(), target.display());
1249    let (data, mut external) = match data_location {
1250        DataLocation::Inline(data) => (MemOrFile::Mem(data), vec![]),
1251        DataLocation::Owned(size) => (
1252            MemOrFile::File((ctx.options().path.data_path(&cmd.hash), size)),
1253            vec![],
1254        ),
1255        DataLocation::External(paths, size) => (
1256            MemOrFile::File((
1257                paths.first().cloned().ok_or_else(|| {
1258                    io::Error::new(io::ErrorKind::NotFound, "no external data path")
1259                })?,
1260                size,
1261            )),
1262            paths,
1263        ),
1264    };
1265    let size = match &data {
1266        MemOrFile::Mem(data) => data.len() as u64,
1267        MemOrFile::File((_, size)) => *size,
1268    };
1269    tx.send(ExportProgressItem::Size(size)).await?;
1270    match data {
1271        MemOrFile::Mem(data) => {
1272            let mut target = fs::File::create(&target)?;
1273            target.write_all(&data)?;
1274        }
1275        MemOrFile::File((source_path, size)) => match mode {
1276            ExportMode::Copy => {
1277                let res = reflink_or_copy_with_progress(&source_path, &target, size, tx).await?;
1278                trace!(
1279                    "exported {} to {}, {res:?}",
1280                    source_path.display(),
1281                    target.display()
1282                );
1283            }
1284            ExportMode::TryReference => {
1285                if !external.is_empty() {
1286                    // the file already exists externally, so we need to copy it.
1287                    // if the OS supports reflink, we might as well use that.
1288                    let res =
1289                        reflink_or_copy_with_progress(&source_path, &target, size, tx).await?;
1290                    trace!(
1291                        "exported {} also to {}, {res:?}",
1292                        source_path.display(),
1293                        target.display()
1294                    );
1295                    external.push(target);
1296                    external.sort();
1297                    external.dedup();
1298                    external.truncate(MAX_EXTERNAL_PATHS);
1299                } else {
1300                    // the file was previously owned, so we can just move it.
1301                    // if that fails with ERR_CROSS, we fall back to copy.
1302                    match std::fs::rename(&source_path, &target) {
1303                        Ok(()) => {}
1304                        Err(cause) => {
1305                            const ERR_CROSS: i32 = 18;
1306                            if cause.raw_os_error() == Some(ERR_CROSS) {
1307                                reflink_or_copy_with_progress(&source_path, &target, size, tx)
1308                                    .await?;
1309                            } else {
1310                                return Err(cause.into());
1311                            }
1312                        }
1313                    }
1314                    external.push(target);
1315                };
1316                // setting the new entry state will also take care of deleting the owned data file!
1317                ctx.set(EntryState::Complete {
1318                    data_location: DataLocation::External(external, size),
1319                    outboard_location,
1320                })
1321                .await?;
1322            }
1323        },
1324    }
1325    tx.send(ExportProgressItem::Done).await?;
1326    Ok(())
1327}
1328
1329trait CopyProgress: RpcMessage {
1330    fn from_offset(offset: u64) -> Self;
1331}
1332
1333impl CopyProgress for ExportProgressItem {
1334    fn from_offset(offset: u64) -> Self {
1335        ExportProgressItem::CopyProgress(offset)
1336    }
1337}
1338
1339impl CopyProgress for AddProgressItem {
1340    fn from_offset(offset: u64) -> Self {
1341        AddProgressItem::CopyProgress(offset)
1342    }
1343}
1344
1345#[derive(Debug)]
1346enum CopyResult {
1347    Reflinked,
1348    Copied,
1349}
1350
1351async fn reflink_or_copy_with_progress(
1352    from: impl AsRef<Path>,
1353    to: impl AsRef<Path>,
1354    size: u64,
1355    tx: &mut mpsc::Sender<impl CopyProgress>,
1356) -> io::Result<CopyResult> {
1357    let from = from.as_ref();
1358    let to = to.as_ref();
1359    if reflink_copy::reflink(from, to).is_ok() {
1360        return Ok(CopyResult::Reflinked);
1361    }
1362    let source = fs::File::open(from)?;
1363    let mut target = fs::File::create(to)?;
1364    copy_with_progress(source, size, &mut target, tx).await?;
1365    Ok(CopyResult::Copied)
1366}
1367
1368async fn copy_with_progress<T: CopyProgress>(
1369    file: impl ReadAt,
1370    size: u64,
1371    target: &mut impl Write,
1372    tx: &mut mpsc::Sender<T>,
1373) -> io::Result<()> {
1374    let mut offset = 0;
1375    let mut buf = vec![0u8; 1024 * 1024];
1376    while offset < size {
1377        let remaining = buf.len().min((size - offset) as usize);
1378        let buf: &mut [u8] = &mut buf[..remaining];
1379        file.read_exact_at(offset, buf)?;
1380        target.write_all(buf)?;
1381        tx.try_send(T::from_offset(offset)).await?;
1382        yield_now().await;
1383        offset += buf.len() as u64;
1384    }
1385    Ok(())
1386}
1387
1388impl FsStore {
1389    /// Load or create a new store.
1390    pub async fn load(root: impl AsRef<Path>) -> Result<Self> {
1391        let path = root.as_ref();
1392        let db_path = path.join("blobs.db");
1393        let options = Options::new(path);
1394        Self::load_with_opts(db_path, options).await
1395    }
1396
1397    /// Load or create a new store with custom options, returning an additional sender for file store specific commands.
1398    pub async fn load_with_opts(db_path: PathBuf, options: Options) -> Result<FsStore> {
1399        static THREAD_NR: AtomicU64 = AtomicU64::new(0);
1400        let rt = tokio::runtime::Builder::new_multi_thread()
1401            .thread_name_fn(|| {
1402                format!(
1403                    "iroh-blob-store-{}",
1404                    THREAD_NR.fetch_add(1, Ordering::Relaxed)
1405                )
1406            })
1407            .enable_time()
1408            .build()?;
1409        let handle = rt.handle().clone();
1410        let (commands_tx, commands_rx) = tokio::sync::mpsc::channel(100);
1411        let (fs_commands_tx, fs_commands_rx) = tokio::sync::mpsc::channel(100);
1412        let gc_config = options.gc.clone();
1413        let actor = handle
1414            .spawn(Actor::new(
1415                db_path,
1416                rt.into(),
1417                commands_rx,
1418                fs_commands_rx,
1419                fs_commands_tx.clone(),
1420                Arc::new(options),
1421            ))
1422            .await
1423            .anyerr()??;
1424        handle.spawn(actor.run());
1425        let store = FsStore::new(commands_tx.into(), fs_commands_tx);
1426        if let Some(config) = gc_config {
1427            handle.spawn(run_gc(store.deref().clone(), config));
1428        }
1429        Ok(store)
1430    }
1431}
1432
1433/// A file based store.
1434///
1435/// A store can be created using [`load`](FsStore::load) or [`load_with_opts`](FsStore::load_with_opts).
1436/// Load will use the default options and create the required directories, while load_with_opts allows
1437/// you to customize the options and the location of the database. Both variants will create the database
1438/// if it does not exist, and load an existing database if one is found at the configured location.
1439///
1440/// In addition to implementing the [`Store`](`crate::api::Store`) API via [`Deref`](`std::ops::Deref`),
1441/// there are a few additional methods that are specific to file based stores, such as [`dump`](FsStore::dump).
1442#[derive(Debug, Clone)]
1443pub struct FsStore {
1444    sender: ApiClient,
1445    db: tokio::sync::mpsc::Sender<InternalCommand>,
1446}
1447
1448impl From<FsStore> for Store {
1449    fn from(value: FsStore) -> Self {
1450        Store::from_sender(value.sender)
1451    }
1452}
1453
1454impl Deref for FsStore {
1455    type Target = Store;
1456
1457    fn deref(&self) -> &Self::Target {
1458        Store::ref_from_sender(&self.sender)
1459    }
1460}
1461
1462impl AsRef<Store> for FsStore {
1463    fn as_ref(&self) -> &Store {
1464        self.deref()
1465    }
1466}
1467
1468impl FsStore {
1469    fn new(
1470        sender: irpc::LocalSender<proto::Request>,
1471        db: tokio::sync::mpsc::Sender<InternalCommand>,
1472    ) -> Self {
1473        Self {
1474            sender: sender.into(),
1475            db,
1476        }
1477    }
1478
1479    pub async fn dump(&self) -> Result<()> {
1480        let (tx, rx) = oneshot::channel();
1481        self.db
1482            .send(
1483                meta::Dump {
1484                    tx,
1485                    span: tracing::Span::current(),
1486                }
1487                .into(),
1488            )
1489            .await
1490            .anyerr()?;
1491        rx.await.anyerr()??;
1492        Ok(())
1493    }
1494}
1495
1496#[cfg(test)]
1497pub mod tests {
1498    use core::panic;
1499    use std::collections::{HashMap, HashSet};
1500
1501    use bao_tree::{io::round_up_to_chunks_groups, ChunkRanges};
1502    use n0_future::{stream, Stream, StreamExt};
1503    use testresult::TestResult;
1504    use walkdir::WalkDir;
1505
1506    use super::*;
1507    use crate::{
1508        api::blobs::Bitfield,
1509        store::{
1510            util::{read_checksummed, tests::create_n0_bao, SliceInfoExt, Tag},
1511            IROH_BLOCK_SIZE,
1512        },
1513    };
1514
1515    /// Interesting sizes for testing.
1516    pub const INTERESTING_SIZES: [usize; 8] = [
1517        0,               // annoying corner case - always present, handled by the api
1518        1,               // less than 1 chunk, data inline, outboard not needed
1519        1024,            // exactly 1 chunk, data inline, outboard not needed
1520        1024 * 16 - 1,   // less than 1 chunk group, data inline, outboard not needed
1521        1024 * 16,       // exactly 1 chunk group, data inline, outboard not needed
1522        1024 * 16 + 1,   // data file, outboard inline (just 1 hash pair)
1523        1024 * 1024,     // data file, outboard inline (many hash pairs)
1524        1024 * 1024 * 8, // data file, outboard file
1525    ];
1526
1527    pub fn round_up_request(size: u64, ranges: &ChunkRanges) -> ChunkRanges {
1528        let last_chunk = ChunkNum::chunks(size);
1529        let data_range = ChunkRanges::from(..last_chunk);
1530        let ranges = if !data_range.intersects(ranges) && !ranges.is_empty() {
1531            if last_chunk == 0 {
1532                ChunkRanges::all()
1533            } else {
1534                ChunkRanges::from(last_chunk - 1..)
1535            }
1536        } else {
1537            ranges.clone()
1538        };
1539        round_up_to_chunks_groups(ranges, IROH_BLOCK_SIZE)
1540    }
1541
1542    fn create_n0_bao_full(
1543        data: &[u8],
1544        ranges: &ChunkRanges,
1545    ) -> n0_error::Result<(Hash, ChunkRanges, Vec<u8>)> {
1546        let ranges = round_up_request(data.len() as u64, ranges);
1547        let (hash, encoded) = create_n0_bao(data, &ranges)?;
1548        Ok((hash, ranges, encoded))
1549    }
1550
1551    #[tokio::test]
1552    // #[traced_test]
1553    async fn test_observe() -> TestResult<()> {
1554        tracing_subscriber::fmt::try_init().ok();
1555        let testdir = tempfile::tempdir()?;
1556        let db_dir = testdir.path().join("db");
1557        let options = Options::new(&db_dir);
1558        let store = FsStore::load_with_opts(db_dir.join("blobs.db"), options).await?;
1559        let sizes = INTERESTING_SIZES;
1560        for size in sizes {
1561            let data = test_data(size);
1562            let ranges = ChunkRanges::all();
1563            let (hash, bao) = create_n0_bao(&data, &ranges)?;
1564            let obs = store.observe(hash);
1565            let task = n0_future::task::spawn(async move {
1566                obs.await_completion().await?;
1567                api::Result::Ok(())
1568            });
1569            store.import_bao_bytes(hash, ranges, bao).await?;
1570            task.await??;
1571        }
1572        Ok(())
1573    }
1574
1575    /// Generate test data for size n.
1576    ///
1577    /// We don't really care about the content, since we assume blake3 works.
1578    /// The only thing it should not be is all zeros, since that is what you
1579    /// will get for a gap.
1580    pub fn test_data(n: usize) -> Bytes {
1581        let mut res = Vec::with_capacity(n);
1582        // Using uppercase A-Z (65-90), 26 possible characters
1583        for i in 0..n {
1584            // Change character every 1024 bytes
1585            let block_num = i / 1024;
1586            // Map to uppercase A-Z range (65-90)
1587            let ascii_val = 65 + (block_num % 26) as u8;
1588            res.push(ascii_val);
1589        }
1590        Bytes::from(res)
1591    }
1592
1593    // import data via import_bytes, check that we can observe it and that it is complete
1594    #[tokio::test]
1595    async fn test_import_byte_stream() -> TestResult<()> {
1596        tracing_subscriber::fmt::try_init().ok();
1597        let testdir = tempfile::tempdir()?;
1598        let db_dir = testdir.path().join("db");
1599        let store = FsStore::load(db_dir).await?;
1600        for size in INTERESTING_SIZES {
1601            let expected = test_data(size);
1602            let expected_hash = Hash::new(&expected);
1603            let stream = bytes_to_stream(expected.clone(), 1023);
1604            let obs = store.observe(expected_hash);
1605            let tt = store.add_stream(stream).await.temp_tag().await?;
1606            assert_eq!(expected_hash, tt.hash());
1607            // we must at some point see completion, otherwise the test will hang
1608            obs.await_completion().await?;
1609            let actual = store.get_bytes(expected_hash).await?;
1610            // check that the data is there
1611            assert_eq!(&expected, &actual);
1612        }
1613        Ok(())
1614    }
1615
1616    // import data via import_bytes, check that we can observe it and that it is complete
1617    #[tokio::test]
1618    async fn test_import_bytes_simple() -> TestResult<()> {
1619        tracing_subscriber::fmt::try_init().ok();
1620        let testdir = tempfile::tempdir()?;
1621        let db_dir = testdir.path().join("db");
1622        let store = FsStore::load(&db_dir).await?;
1623        let sizes = INTERESTING_SIZES;
1624        trace!("{}", Options::new(&db_dir).is_inlined_data(16385));
1625        for size in sizes {
1626            let expected = test_data(size);
1627            let expected_hash = Hash::new(&expected);
1628            let obs = store.observe(expected_hash);
1629            let tt = store.add_bytes(expected.clone()).await?;
1630            assert_eq!(expected_hash, tt.hash);
1631            // we must at some point see completion, otherwise the test will hang
1632            obs.await_completion().await?;
1633            let actual = store.get_bytes(expected_hash).await?;
1634            // check that the data is there
1635            assert_eq!(&expected, &actual);
1636        }
1637        store.shutdown().await?;
1638        dump_dir_full(db_dir)?;
1639        Ok(())
1640    }
1641
1642    // import data via import_bytes, check that we can observe it and that it is complete
1643    #[tokio::test]
1644    #[ignore = "flaky. I need a reliable way to keep the handle alive"]
1645    async fn test_roundtrip_bytes_small() -> TestResult<()> {
1646        tracing_subscriber::fmt::try_init().ok();
1647        let testdir = tempfile::tempdir()?;
1648        let db_dir = testdir.path().join("db");
1649        let store = FsStore::load(db_dir).await?;
1650        for size in INTERESTING_SIZES
1651            .into_iter()
1652            .filter(|x| *x != 0 && *x <= IROH_BLOCK_SIZE.bytes())
1653        {
1654            let expected = test_data(size);
1655            let expected_hash = Hash::new(&expected);
1656            let obs = store.observe(expected_hash);
1657            let tt = store.add_bytes(expected.clone()).await?;
1658            assert_eq!(expected_hash, tt.hash);
1659            let actual = store.get_bytes(expected_hash).await?;
1660            // check that the data is there
1661            assert_eq!(&expected, &actual);
1662            assert_eq!(
1663                &expected.addr(),
1664                &actual.addr(),
1665                "address mismatch for size {size}"
1666            );
1667            // we must at some point see completion, otherwise the test will hang
1668            // keep the handle alive by observing until the end, otherwise the handle
1669            // will change and the bytes won't be the same instance anymore
1670            obs.await_completion().await?;
1671        }
1672        store.shutdown().await?;
1673        Ok(())
1674    }
1675
1676    // import data via import_bytes, check that we can observe it and that it is complete
1677    #[tokio::test]
1678    async fn test_import_path() -> TestResult<()> {
1679        tracing_subscriber::fmt::try_init().ok();
1680        let testdir = tempfile::tempdir()?;
1681        let db_dir = testdir.path().join("db");
1682        let store = FsStore::load(db_dir).await?;
1683        for size in INTERESTING_SIZES {
1684            let expected = test_data(size);
1685            let expected_hash = Hash::new(&expected);
1686            let path = testdir.path().join(format!("in-{size}"));
1687            fs::write(&path, &expected)?;
1688            let obs = store.observe(expected_hash);
1689            let tt = store.add_path(&path).await?;
1690            assert_eq!(expected_hash, tt.hash);
1691            // we must at some point see completion, otherwise the test will hang
1692            obs.await_completion().await?;
1693            let actual = store.get_bytes(expected_hash).await?;
1694            // check that the data is there
1695            assert_eq!(&expected, &actual, "size={size}");
1696        }
1697        dump_dir_full(testdir.path())?;
1698        Ok(())
1699    }
1700
1701    // import data via import_bytes, check that we can observe it and that it is complete
1702    #[tokio::test]
1703    async fn test_export_path() -> TestResult<()> {
1704        tracing_subscriber::fmt::try_init().ok();
1705        let testdir = tempfile::tempdir()?;
1706        let db_dir = testdir.path().join("db");
1707        let store = FsStore::load(db_dir).await?;
1708        for size in INTERESTING_SIZES {
1709            let expected = test_data(size);
1710            let expected_hash = Hash::new(&expected);
1711            let tt = store.add_bytes(expected.clone()).await?;
1712            assert_eq!(expected_hash, tt.hash);
1713            let out_path = testdir.path().join(format!("out-{size}"));
1714            store.export(expected_hash, &out_path).await?;
1715            let actual = fs::read(&out_path)?;
1716            assert_eq!(expected, actual);
1717        }
1718        Ok(())
1719    }
1720
1721    #[tokio::test]
1722    async fn test_import_bao_ranges() -> TestResult<()> {
1723        tracing_subscriber::fmt::try_init().ok();
1724        let testdir = tempfile::tempdir()?;
1725        let db_dir = testdir.path().join("db");
1726        {
1727            let store = FsStore::load(&db_dir).await?;
1728            let data = test_data(100000);
1729            let ranges = ChunkRanges::chunks(16..32);
1730            let (hash, bao) = create_n0_bao(&data, &ranges)?;
1731            store
1732                .import_bao_bytes(hash, ranges.clone(), bao.clone())
1733                .await?;
1734            let bitfield = store.observe(hash).await?;
1735            assert_eq!(bitfield.ranges, ranges);
1736            assert_eq!(bitfield.size(), data.len() as u64);
1737            let export = store.export_bao(hash, ranges).bao_to_vec().await?;
1738            assert_eq!(export, bao);
1739        }
1740        Ok(())
1741    }
1742
1743    #[tokio::test]
1744    async fn test_import_bao_minimal() -> TestResult<()> {
1745        tracing_subscriber::fmt::try_init().ok();
1746        let testdir = tempfile::tempdir()?;
1747        let sizes = [1];
1748        let db_dir = testdir.path().join("db");
1749        {
1750            let store = FsStore::load(&db_dir).await?;
1751            for size in sizes {
1752                let data = vec![0u8; size];
1753                let (hash, encoded) = create_n0_bao(&data, &ChunkRanges::all())?;
1754                let data = Bytes::from(encoded);
1755                store
1756                    .import_bao_bytes(hash, ChunkRanges::all(), data)
1757                    .await?;
1758            }
1759            store.shutdown().await?;
1760        }
1761        Ok(())
1762    }
1763
1764    #[tokio::test]
1765    async fn test_import_bao_simple() -> TestResult<()> {
1766        tracing_subscriber::fmt::try_init().ok();
1767        let testdir = tempfile::tempdir()?;
1768        let sizes = [1048576];
1769        let db_dir = testdir.path().join("db");
1770        {
1771            let store = FsStore::load(&db_dir).await?;
1772            for size in sizes {
1773                let data = vec![0u8; size];
1774                let (hash, encoded) = create_n0_bao(&data, &ChunkRanges::all())?;
1775                let data = Bytes::from(encoded);
1776                trace!("importing size={}", size);
1777                store
1778                    .import_bao_bytes(hash, ChunkRanges::all(), data)
1779                    .await?;
1780            }
1781            store.shutdown().await?;
1782        }
1783        Ok(())
1784    }
1785
1786    #[tokio::test]
1787    async fn test_import_bao_persistence_full() -> TestResult<()> {
1788        tracing_subscriber::fmt::try_init().ok();
1789        let testdir = tempfile::tempdir()?;
1790        let sizes = INTERESTING_SIZES;
1791        let db_dir = testdir.path().join("db");
1792        {
1793            let store = FsStore::load(&db_dir).await?;
1794            for size in sizes {
1795                let data = vec![0u8; size];
1796                let (hash, encoded) = create_n0_bao(&data, &ChunkRanges::all())?;
1797                let data = Bytes::from(encoded);
1798                store
1799                    .import_bao_bytes(hash, ChunkRanges::all(), data)
1800                    .await?;
1801            }
1802            store.shutdown().await?;
1803        }
1804        {
1805            let store = FsStore::load(&db_dir).await?;
1806            for size in sizes {
1807                let expected = vec![0u8; size];
1808                let hash = Hash::new(&expected);
1809                let actual = store
1810                    .export_bao(hash, ChunkRanges::all())
1811                    .data_to_vec()
1812                    .await?;
1813                assert_eq!(&expected, &actual);
1814            }
1815            store.shutdown().await?;
1816        }
1817        Ok(())
1818    }
1819
1820    #[tokio::test]
1821    async fn test_import_bao_persistence_just_size() -> TestResult<()> {
1822        tracing_subscriber::fmt::try_init().ok();
1823        let testdir = tempfile::tempdir()?;
1824        let sizes = INTERESTING_SIZES;
1825        let db_dir = testdir.path().join("db");
1826        let just_size = ChunkRanges::last_chunk();
1827        {
1828            let store = FsStore::load(&db_dir).await?;
1829            for size in sizes {
1830                let data = test_data(size);
1831                let (hash, ranges, encoded) = create_n0_bao_full(&data, &just_size)?;
1832                let data = Bytes::from(encoded);
1833                if let Err(cause) = store.import_bao_bytes(hash, ranges, data).await {
1834                    panic!("failed to import size={size}: {cause}");
1835                }
1836            }
1837            store.dump().await?;
1838            store.shutdown().await?;
1839        }
1840        {
1841            let store = FsStore::load(&db_dir).await?;
1842            store.dump().await?;
1843            for size in sizes {
1844                let data = test_data(size);
1845                let (hash, ranges, expected) = create_n0_bao_full(&data, &just_size)?;
1846                let actual = match store.export_bao(hash, ranges).bao_to_vec().await {
1847                    Ok(actual) => actual,
1848                    Err(cause) => panic!("failed to export size={size}: {cause}"),
1849                };
1850                assert_eq!(&expected, &actual);
1851            }
1852            store.shutdown().await?;
1853        }
1854        dump_dir_full(testdir.path())?;
1855        Ok(())
1856    }
1857
1858    #[tokio::test]
1859    async fn test_import_bao_persistence_two_stages() -> TestResult<()> {
1860        tracing_subscriber::fmt::try_init().ok();
1861        let testdir = tempfile::tempdir()?;
1862        let sizes = INTERESTING_SIZES;
1863        let db_dir = testdir.path().join("db");
1864        let just_size = ChunkRanges::last_chunk();
1865        // stage 1, import just the last full chunk group to get a validated size
1866        {
1867            let store = FsStore::load(&db_dir).await?;
1868            for size in sizes {
1869                let data = test_data(size);
1870                let (hash, ranges, encoded) = create_n0_bao_full(&data, &just_size)?;
1871                let data = Bytes::from(encoded);
1872                if let Err(cause) = store.import_bao_bytes(hash, ranges, data).await {
1873                    panic!("failed to import size={size}: {cause}");
1874                }
1875            }
1876            store.dump().await?;
1877            store.shutdown().await?;
1878        }
1879        dump_dir_full(testdir.path())?;
1880        // stage 2, import the rest
1881        {
1882            let store = FsStore::load(&db_dir).await?;
1883            for size in sizes {
1884                let remaining = ChunkRanges::all() - round_up_request(size as u64, &just_size);
1885                if remaining.is_empty() {
1886                    continue;
1887                }
1888                let data = test_data(size);
1889                let (hash, ranges, encoded) = create_n0_bao_full(&data, &remaining)?;
1890                let data = Bytes::from(encoded);
1891                if let Err(cause) = store.import_bao_bytes(hash, ranges, data).await {
1892                    panic!("failed to import size={size}: {cause}");
1893                }
1894            }
1895            store.dump().await?;
1896            store.shutdown().await?;
1897        }
1898        // check if the data is complete
1899        {
1900            let store = FsStore::load(&db_dir).await?;
1901            store.dump().await?;
1902            for size in sizes {
1903                let data = test_data(size);
1904                let (hash, ranges, expected) = create_n0_bao_full(&data, &ChunkRanges::all())?;
1905                let actual = match store.export_bao(hash, ranges).bao_to_vec().await {
1906                    Ok(actual) => actual,
1907                    Err(cause) => panic!("failed to export size={size}: {cause}"),
1908                };
1909                assert_eq!(&expected, &actual);
1910            }
1911            store.dump().await?;
1912            store.shutdown().await?;
1913        }
1914        dump_dir_full(testdir.path())?;
1915        Ok(())
1916    }
1917
1918    fn just_size() -> ChunkRanges {
1919        ChunkRanges::last_chunk()
1920    }
1921
1922    #[tokio::test]
1923    async fn test_import_bao_persistence_observe() -> TestResult<()> {
1924        tracing_subscriber::fmt::try_init().ok();
1925        let testdir = tempfile::tempdir()?;
1926        let sizes = INTERESTING_SIZES;
1927        let db_dir = testdir.path().join("db");
1928        let just_size = just_size();
1929        // stage 1, import just the last full chunk group to get a validated size
1930        {
1931            let store = FsStore::load(&db_dir).await?;
1932            for size in sizes {
1933                let data = test_data(size);
1934                let (hash, ranges, encoded) = create_n0_bao_full(&data, &just_size)?;
1935                let data = Bytes::from(encoded);
1936                if let Err(cause) = store.import_bao_bytes(hash, ranges, data).await {
1937                    panic!("failed to import size={size}: {cause}");
1938                }
1939            }
1940            store.dump().await?;
1941            store.shutdown().await?;
1942        }
1943        dump_dir_full(testdir.path())?;
1944        // stage 2, import the rest
1945        {
1946            let store = FsStore::load(&db_dir).await?;
1947            for size in sizes {
1948                let expected_ranges = round_up_request(size as u64, &just_size);
1949                let data = test_data(size);
1950                let hash = Hash::new(&data);
1951                let bitfield = store.observe(hash).await?;
1952                assert_eq!(bitfield.ranges, expected_ranges);
1953            }
1954            store.dump().await?;
1955            store.shutdown().await?;
1956        }
1957        Ok(())
1958    }
1959
1960    #[tokio::test]
1961    async fn test_import_bao_persistence_recover() -> TestResult<()> {
1962        tracing_subscriber::fmt::try_init().ok();
1963        let testdir = tempfile::tempdir()?;
1964        let sizes = INTERESTING_SIZES;
1965        let db_dir = testdir.path().join("db");
1966        let options = Options::new(&db_dir);
1967        let just_size = just_size();
1968        // stage 1, import just the last full chunk group to get a validated size
1969        {
1970            let store = FsStore::load_with_opts(db_dir.join("blobs.db"), options.clone()).await?;
1971            for size in sizes {
1972                let data = test_data(size);
1973                let (hash, ranges, encoded) = create_n0_bao_full(&data, &just_size)?;
1974                let data = Bytes::from(encoded);
1975                if let Err(cause) = store.import_bao_bytes(hash, ranges, data).await {
1976                    panic!("failed to import size={size}: {cause}");
1977                }
1978            }
1979            store.dump().await?;
1980            store.shutdown().await?;
1981        }
1982        delete_rec(testdir.path(), "bitfield")?;
1983        dump_dir_full(testdir.path())?;
1984        // stage 2, import the rest
1985        {
1986            let store = FsStore::load_with_opts(db_dir.join("blobs.db"), options.clone()).await?;
1987            for size in sizes {
1988                let expected_ranges = round_up_request(size as u64, &just_size);
1989                let data = test_data(size);
1990                let hash = Hash::new(&data);
1991                let bitfield = store.observe(hash).await?;
1992                assert_eq!(bitfield.ranges, expected_ranges, "size={size}");
1993            }
1994            store.dump().await?;
1995            store.shutdown().await?;
1996        }
1997        Ok(())
1998    }
1999
2000    #[tokio::test]
2001    async fn test_import_bytes_persistence_full() -> TestResult<()> {
2002        tracing_subscriber::fmt::try_init().ok();
2003        let testdir = tempfile::tempdir()?;
2004        let sizes = INTERESTING_SIZES;
2005        let db_dir = testdir.path().join("db");
2006        {
2007            let store = FsStore::load(&db_dir).await?;
2008            let mut tts = Vec::new();
2009            for size in sizes {
2010                let data = test_data(size);
2011                let data = data;
2012                tts.push(store.add_bytes(data.clone()).await?);
2013            }
2014            store.dump().await?;
2015            store.shutdown().await?;
2016        }
2017        {
2018            let store = FsStore::load(&db_dir).await?;
2019            store.dump().await?;
2020            for size in sizes {
2021                let expected = test_data(size);
2022                let hash = Hash::new(&expected);
2023                let Ok(actual) = store
2024                    .export_bao(hash, ChunkRanges::all())
2025                    .data_to_vec()
2026                    .await
2027                else {
2028                    panic!("failed to export size={size}");
2029                };
2030                assert_eq!(&expected, &actual, "size={size}");
2031            }
2032            store.shutdown().await?;
2033        }
2034        Ok(())
2035    }
2036
2037    async fn test_batch(store: &Store) -> TestResult<()> {
2038        let batch = store.blobs().batch().await?;
2039        let tt1 = batch.temp_tag(Hash::new("foo")).await?;
2040        let tt2 = batch.add_slice("boo").await?;
2041        let tts = store
2042            .tags()
2043            .list_temp_tags()
2044            .await?
2045            .collect::<HashSet<_>>()
2046            .await;
2047        assert!(tts.contains(&tt1.hash_and_format()));
2048        assert!(tts.contains(&tt2.hash_and_format()));
2049        drop(batch);
2050        store.sync_db().await?;
2051        store.wait_idle().await?;
2052        let tts = store
2053            .tags()
2054            .list_temp_tags()
2055            .await?
2056            .collect::<HashSet<_>>()
2057            .await;
2058        // temp tag went out of scope, so it does not work anymore
2059        assert!(!tts.contains(&tt1.hash_and_format()));
2060        assert!(!tts.contains(&tt2.hash_and_format()));
2061        drop(tt1);
2062        drop(tt2);
2063        Ok(())
2064    }
2065
2066    #[tokio::test]
2067    async fn test_batch_fs() -> TestResult<()> {
2068        tracing_subscriber::fmt::try_init().ok();
2069        let testdir = tempfile::tempdir()?;
2070        let db_dir = testdir.path().join("db");
2071        let store = FsStore::load(db_dir).await?;
2072        test_batch(&store).await
2073    }
2074
2075    #[tokio::test]
2076    async fn smoke() -> TestResult<()> {
2077        tracing_subscriber::fmt::try_init().ok();
2078        let testdir = tempfile::tempdir()?;
2079        let db_dir = testdir.path().join("db");
2080        let store = FsStore::load(db_dir).await?;
2081        let haf = HashAndFormat::raw(Hash::from([0u8; 32]));
2082        store.tags().set(Tag::from("test"), haf).await?;
2083        store.tags().set(Tag::from("boo"), haf).await?;
2084        store.tags().set(Tag::from("bar"), haf).await?;
2085        let sizes = INTERESTING_SIZES;
2086        let mut hashes = Vec::new();
2087        let mut data_by_hash = HashMap::new();
2088        let mut bao_by_hash = HashMap::new();
2089        for size in sizes {
2090            let data = vec![0u8; size];
2091            let data = Bytes::from(data);
2092            let tt = store.add_bytes(data.clone()).temp_tag().await?;
2093            data_by_hash.insert(tt.hash(), data);
2094            hashes.push(tt);
2095        }
2096        store.sync_db().await?;
2097        for tt in &hashes {
2098            let hash = tt.hash();
2099            let path = testdir.path().join(format!("{hash}.txt"));
2100            store.export(hash, path).await?;
2101        }
2102        for tt in &hashes {
2103            let hash = tt.hash();
2104            let data = store
2105                .export_bao(hash, ChunkRanges::all())
2106                .data_to_vec()
2107                .await
2108                .unwrap();
2109            assert_eq!(data, data_by_hash[&hash].to_vec());
2110            let bao = store
2111                .export_bao(hash, ChunkRanges::all())
2112                .bao_to_vec()
2113                .await
2114                .unwrap();
2115            bao_by_hash.insert(hash, bao);
2116        }
2117        store.dump().await?;
2118
2119        for size in sizes {
2120            let data = test_data(size);
2121            let ranges = ChunkRanges::all();
2122            let (hash, bao) = create_n0_bao(&data, &ranges)?;
2123            store.import_bao_bytes(hash, ranges, bao).await?;
2124        }
2125
2126        for (_hash, _bao_tree) in bao_by_hash {
2127            // let mut reader = Cursor::new(bao_tree);
2128            // let size = reader.read_u64_le().await?;
2129            // let tree = BaoTree::new(size, IROH_BLOCK_SIZE);
2130            // let ranges = ChunkRanges::all();
2131            // let mut decoder = DecodeResponseIter::new(hash, tree, reader, &ranges);
2132            // while let Some(item) = decoder.next() {
2133            //     let item = item?;
2134            // }
2135            // store.import_bao_bytes(hash, ChunkRanges::all(), bao_tree.into()).await?;
2136        }
2137        Ok(())
2138    }
2139
2140    pub fn delete_rec(root_dir: impl AsRef<Path>, extension: &str) -> Result<(), std::io::Error> {
2141        // Remove leading dot if present, so we have just the extension
2142        let ext = extension.trim_start_matches('.').to_lowercase();
2143
2144        for entry in WalkDir::new(root_dir).into_iter().filter_map(|e| e.ok()) {
2145            let path = entry.path();
2146
2147            if path.is_file() {
2148                if let Some(file_ext) = path.extension() {
2149                    if file_ext.to_string_lossy().to_lowercase() == ext {
2150                        fs::remove_file(path)?;
2151                    }
2152                }
2153            }
2154        }
2155
2156        Ok(())
2157    }
2158
2159    pub fn dump_dir(path: impl AsRef<Path>) -> io::Result<()> {
2160        let mut entries: Vec<_> = WalkDir::new(&path)
2161            .into_iter()
2162            .filter_map(Result::ok) // Skip errors
2163            .collect();
2164
2165        // Sort by path (name at each depth)
2166        entries.sort_by(|a, b| a.path().cmp(b.path()));
2167
2168        for entry in entries {
2169            let depth = entry.depth();
2170            let indent = "  ".repeat(depth); // Two spaces per level
2171            let name = entry.file_name().to_string_lossy();
2172            let size = entry.metadata()?.len(); // Size in bytes
2173
2174            if entry.file_type().is_file() {
2175                println!("{indent}{name} ({size} bytes)");
2176            } else if entry.file_type().is_dir() {
2177                println!("{indent}{name}/");
2178            }
2179        }
2180        Ok(())
2181    }
2182
2183    pub fn dump_dir_full(path: impl AsRef<Path>) -> io::Result<()> {
2184        let mut entries: Vec<_> = WalkDir::new(&path)
2185            .into_iter()
2186            .filter_map(Result::ok) // Skip errors
2187            .collect();
2188
2189        // Sort by path (name at each depth)
2190        entries.sort_by(|a, b| a.path().cmp(b.path()));
2191
2192        for entry in entries {
2193            let depth = entry.depth();
2194            let indent = "  ".repeat(depth);
2195            let name = entry.file_name().to_string_lossy();
2196
2197            if entry.file_type().is_dir() {
2198                println!("{indent}{name}/");
2199            } else if entry.file_type().is_file() {
2200                let size = entry.metadata()?.len();
2201                println!("{indent}{name} ({size} bytes)");
2202
2203                // Dump depending on file type
2204                let path = entry.path();
2205                if name.ends_with(".data") {
2206                    print!("{indent}  ");
2207                    dump_file(path, 1024 * 16)?;
2208                } else if name.ends_with(".obao4") {
2209                    print!("{indent}  ");
2210                    dump_file(path, 64)?;
2211                } else if name.ends_with(".sizes4") {
2212                    print!("{indent}  ");
2213                    dump_file(path, 8)?;
2214                } else if name.ends_with(".bitfield") {
2215                    match read_checksummed::<Bitfield>(path) {
2216                        Ok(bitfield) => {
2217                            println!("{indent}  bitfield: {bitfield:?}");
2218                        }
2219                        Err(cause) => {
2220                            println!("{indent}  bitfield: error: {cause}");
2221                        }
2222                    }
2223                } else {
2224                    continue; // Skip content dump for other files
2225                };
2226            }
2227        }
2228        Ok(())
2229    }
2230
2231    pub fn dump_file<P: AsRef<Path>>(path: P, chunk_size: u64) -> io::Result<()> {
2232        let bits = file_bits(path, chunk_size)?;
2233        println!("{}", print_bitfield_ansi(bits));
2234        Ok(())
2235    }
2236
2237    pub fn file_bits(path: impl AsRef<Path>, chunk_size: u64) -> io::Result<Vec<bool>> {
2238        let file = fs::File::open(&path)?;
2239        let file_size = file.metadata()?.len();
2240        let mut buffer = vec![0u8; chunk_size as usize];
2241        let mut bits = Vec::new();
2242
2243        let mut offset = 0u64;
2244        while offset < file_size {
2245            let remaining = file_size - offset;
2246            let current_chunk_size = chunk_size.min(remaining);
2247
2248            let chunk = &mut buffer[..current_chunk_size as usize];
2249            file.read_exact_at(offset, chunk)?;
2250
2251            let has_non_zero = chunk.iter().any(|&byte| byte != 0);
2252            bits.push(has_non_zero);
2253
2254            offset += current_chunk_size;
2255        }
2256
2257        Ok(bits)
2258    }
2259
2260    #[allow(dead_code)]
2261    fn print_bitfield(bits: impl IntoIterator<Item = bool>) -> String {
2262        bits.into_iter()
2263            .map(|bit| if bit { '#' } else { '_' })
2264            .collect()
2265    }
2266
2267    fn print_bitfield_ansi(bits: impl IntoIterator<Item = bool>) -> String {
2268        let mut result = String::new();
2269        let mut iter = bits.into_iter();
2270
2271        while let Some(b1) = iter.next() {
2272            let b2 = iter.next();
2273
2274            // ANSI color codes
2275            let white_fg = "\x1b[97m"; // bright white foreground
2276            let reset = "\x1b[0m"; // reset all attributes
2277            let gray_bg = "\x1b[100m"; // bright black (gray) background
2278            let black_bg = "\x1b[40m"; // black background
2279
2280            let colored_char = match (b1, b2) {
2281                (true, Some(true)) => format!("{}{}{}", white_fg, '█', reset), // 11 - solid white on default background
2282                (true, Some(false)) => format!("{}{}{}{}", gray_bg, white_fg, '▌', reset), // 10 - left half white on gray background
2283                (false, Some(true)) => format!("{}{}{}{}", gray_bg, white_fg, '▐', reset), // 01 - right half white on gray background
2284                (false, Some(false)) => format!("{}{}{}{}", gray_bg, white_fg, ' ', reset), // 00 - space with gray background
2285                (true, None) => format!("{}{}{}{}", black_bg, white_fg, '▌', reset), // 1 (pad 0) - left half white on black background
2286                (false, None) => format!("{}{}{}{}", black_bg, white_fg, ' ', reset), // 0 (pad 0) - space with black background
2287            };
2288
2289            result.push_str(&colored_char);
2290        }
2291
2292        // Ensure we end with a reset code to prevent color bleeding
2293        result.push_str("\x1b[0m");
2294        result
2295    }
2296
2297    fn bytes_to_stream(
2298        bytes: Bytes,
2299        chunk_size: usize,
2300    ) -> impl Stream<Item = io::Result<Bytes>> + 'static {
2301        assert!(chunk_size > 0, "Chunk size must be greater than 0");
2302        stream::unfold((bytes, 0), move |(bytes, offset)| async move {
2303            if offset >= bytes.len() {
2304                None
2305            } else {
2306                let chunk_len = chunk_size.min(bytes.len() - offset);
2307                let chunk = bytes.slice(offset..offset + chunk_len);
2308                Some((Ok(chunk), (bytes, offset + chunk_len)))
2309            }
2310        })
2311    }
2312}