Skip to main content

wasmtime_wasi/p3/filesystem/
host.rs

1use crate::filesystem::sys;
2use crate::filesystem::{Descriptor, Dir, File, WasiFilesystem, WasiFilesystemCtxView};
3use crate::p3::bindings::clocks::system_clock;
4use crate::p3::bindings::filesystem::types::{
5    self, Advice, DescriptorFlags, DescriptorStat, DescriptorType, DirectoryEntry, ErrorCode,
6    Filesize, MetadataHashValue, NewTimestamp, OpenFlags, PathFlags,
7};
8use crate::p3::filesystem::{FilesystemError, FilesystemResult, preopens};
9use crate::p3::{DEFAULT_BUFFER_CAPACITY, FallibleIteratorProducer};
10use bytes::BytesMut;
11use core::pin::Pin;
12use core::task::{Context, Poll, ready};
13use core::{iter, mem};
14use std::io;
15use std::sync::Arc;
16use std::time::SystemTime;
17use tokio::sync::{mpsc, oneshot};
18use tokio::task::{JoinHandle, spawn_blocking};
19use wasmtime::StoreContextMut;
20use wasmtime::component::{
21    Access, Accessor, Destination, FutureReader, Resource, ResourceTable, Source, StreamConsumer,
22    StreamProducer, StreamReader, StreamResult,
23};
24use wasmtime::error::Context as _;
25
26fn get_descriptor<'a>(
27    table: &'a ResourceTable,
28    fd: &'a Resource<Descriptor>,
29) -> FilesystemResult<&'a Descriptor> {
30    table
31        .get(fd)
32        .context("failed to get descriptor resource from table")
33        .map_err(FilesystemError::trap)
34}
35
36fn get_file<'a>(
37    table: &'a ResourceTable,
38    fd: &'a Resource<Descriptor>,
39) -> FilesystemResult<&'a File> {
40    let file = get_descriptor(table, fd).map(Descriptor::file)??;
41    Ok(file)
42}
43
44fn get_dir<'a>(
45    table: &'a ResourceTable,
46    fd: &'a Resource<Descriptor>,
47) -> FilesystemResult<&'a Dir> {
48    let dir = get_descriptor(table, fd).map(Descriptor::dir)??;
49    Ok(dir)
50}
51
52trait AccessorExt {
53    fn get_descriptor(&self, fd: &Resource<Descriptor>) -> FilesystemResult<Descriptor>;
54    fn get_file(&self, fd: &Resource<Descriptor>) -> FilesystemResult<File>;
55    fn get_dir(&self, fd: &Resource<Descriptor>) -> FilesystemResult<Dir>;
56    fn get_dir_pair(
57        &self,
58        a: &Resource<Descriptor>,
59        b: &Resource<Descriptor>,
60    ) -> FilesystemResult<(Dir, Dir)>;
61}
62
63impl<T> AccessorExt for Accessor<T, WasiFilesystem> {
64    fn get_descriptor(&self, fd: &Resource<Descriptor>) -> FilesystemResult<Descriptor> {
65        self.with(|mut store| {
66            let fd = get_descriptor(store.get().table, fd)?;
67            Ok(fd.clone())
68        })
69    }
70
71    fn get_file(&self, fd: &Resource<Descriptor>) -> FilesystemResult<File> {
72        self.with(|mut store| {
73            let file = get_file(store.get().table, fd)?;
74            Ok(file.clone())
75        })
76    }
77
78    fn get_dir(&self, fd: &Resource<Descriptor>) -> FilesystemResult<Dir> {
79        self.with(|mut store| {
80            let dir = get_dir(store.get().table, fd)?;
81            Ok(dir.clone())
82        })
83    }
84
85    fn get_dir_pair(
86        &self,
87        a: &Resource<Descriptor>,
88        b: &Resource<Descriptor>,
89    ) -> FilesystemResult<(Dir, Dir)> {
90        self.with(|mut store| {
91            let table = store.get().table;
92            let a = get_dir(table, a)?;
93            let b = get_dir(table, b)?;
94            Ok((a.clone(), b.clone()))
95        })
96    }
97}
98
99fn systemtime_from(t: system_clock::Instant) -> Result<std::time::SystemTime, ErrorCode> {
100    if let Ok(seconds) = t.seconds.try_into() {
101        std::time::SystemTime::UNIX_EPOCH
102            .checked_add(core::time::Duration::new(seconds, t.nanoseconds))
103            .ok_or(ErrorCode::Overflow)
104    } else {
105        std::time::SystemTime::UNIX_EPOCH
106            .checked_sub(core::time::Duration::new(
107                t.seconds.unsigned_abs(),
108                t.nanoseconds,
109            ))
110            .ok_or(ErrorCode::Overflow)
111    }
112}
113
114fn systemtimespec_from(t: NewTimestamp) -> Result<Option<SystemTime>, ErrorCode> {
115    match t {
116        NewTimestamp::NoChange => Ok(None),
117        NewTimestamp::Now => Ok(Some(SystemTime::now())),
118        NewTimestamp::Timestamp(st) => Ok(Some(systemtime_from(st)?)),
119    }
120}
121
122struct ReadStreamProducer {
123    file: File,
124    offset: u64,
125    result: Option<oneshot::Sender<Result<(), ErrorCode>>>,
126    task: Option<JoinHandle<std::io::Result<BytesMut>>>,
127}
128
129impl Drop for ReadStreamProducer {
130    fn drop(&mut self) {
131        self.close(Ok(()))
132    }
133}
134
135impl ReadStreamProducer {
136    fn close(&mut self, res: Result<(), ErrorCode>) {
137        if let Some(tx) = self.result.take() {
138            _ = tx.send(res);
139        }
140    }
141
142    /// Update the internal `offset` field after reading `amt` bytes from the file.
143    fn complete_read(&mut self, amt: usize) -> StreamResult {
144        let Ok(amt) = amt.try_into() else {
145            self.close(Err(ErrorCode::Overflow));
146            return StreamResult::Dropped;
147        };
148        let Some(amt) = self.offset.checked_add(amt) else {
149            self.close(Err(ErrorCode::Overflow));
150            return StreamResult::Dropped;
151        };
152        self.offset = amt;
153        StreamResult::Completed
154    }
155}
156
157impl<D> StreamProducer<D> for ReadStreamProducer {
158    type Item = u8;
159    type Buffer = BytesMut;
160
161    fn poll_produce<'a>(
162        mut self: Pin<&mut Self>,
163        cx: &mut Context<'_>,
164        store: StoreContextMut<'a, D>,
165        mut dst: Destination<'a, Self::Item, Self::Buffer>,
166        finish: bool,
167    ) -> Poll<wasmtime::Result<StreamResult>> {
168        if let Some(file) = self.file.as_blocking_file() {
169            // Once a blocking file, always a blocking file, so assert as such.
170            assert!(self.task.is_none());
171            let mut dst = dst.as_direct(store, DEFAULT_BUFFER_CAPACITY);
172            let buf = dst.remaining();
173            if buf.is_empty() {
174                return Poll::Ready(Ok(StreamResult::Completed));
175            }
176            return match sys::read_at_cursor_unspecified(file, buf, self.offset) {
177                Ok(0) => {
178                    self.close(Ok(()));
179                    Poll::Ready(Ok(StreamResult::Dropped))
180                }
181                Ok(n) => {
182                    dst.mark_written(n);
183                    Poll::Ready(Ok(self.complete_read(n)))
184                }
185                Err(err) => {
186                    self.close(Err(err.into()));
187                    Poll::Ready(Ok(StreamResult::Dropped))
188                }
189            };
190        }
191
192        // Lazily spawn a read task if one hasn't already been spawned yet.
193        let me = &mut *self;
194        let task = me.task.get_or_insert_with(|| {
195            let mut buf = dst.take_buffer();
196            buf.resize(DEFAULT_BUFFER_CAPACITY, 0);
197            let file = Arc::clone(me.file.as_file());
198            let offset = me.offset;
199            spawn_blocking(move || {
200                sys::read_at_cursor_unspecified(&file, &mut buf, offset).map(|n| {
201                    buf.truncate(n);
202                    buf
203                })
204            })
205        });
206
207        // Await the completion of the read task. Note that this is not a
208        // cancellable await point because we can't cancel the other task, so
209        // the `finish` parameter is ignored.
210        let result = match Pin::new(&mut *task).poll(cx) {
211            // If cancellation is requested, then flag that to Tokio. Note that
212            // this still waits for the actual completion of the spawned task,
213            // which won't actually happen if it's already executing.
214            Poll::Pending if finish => {
215                task.abort();
216                ready!(Pin::new(task).poll(cx))
217            }
218            other => ready!(other),
219        };
220        self.task = None;
221        match result {
222            Ok(Ok(buf)) if buf.is_empty() => {
223                self.close(Ok(()));
224                Poll::Ready(Ok(StreamResult::Dropped))
225            }
226            Ok(Ok(buf)) => {
227                let n = buf.len();
228                dst.set_buffer(buf);
229                Poll::Ready(Ok(self.complete_read(n)))
230            }
231            Ok(Err(err)) => {
232                self.close(Err(err.into()));
233                Poll::Ready(Ok(StreamResult::Dropped))
234            }
235            Err(err) => {
236                if err.is_cancelled() {
237                    return Poll::Ready(Ok(StreamResult::Cancelled));
238                }
239                panic!("I/O task should not panic: {err}")
240            }
241        }
242    }
243}
244
245fn map_dir_entry(
246    entry: std::io::Result<cap_primitives::fs::DirEntry>,
247) -> Result<Option<DirectoryEntry>, ErrorCode> {
248    match entry {
249        Ok(entry) => {
250            let meta = entry.metadata()?;
251            let Ok(name) = entry.file_name().into_string() else {
252                return Err(ErrorCode::IllegalByteSequence);
253            };
254            Ok(Some(DirectoryEntry {
255                type_: meta.file_type().into(),
256                name,
257            }))
258        }
259        Err(err) => {
260            // On windows, filter out files like `C:\DumpStack.log.tmp` which we
261            // can't get full metadata for.
262            #[cfg(windows)]
263            {
264                use windows_sys::Win32::Foundation::{
265                    ERROR_ACCESS_DENIED, ERROR_SHARING_VIOLATION,
266                };
267                if err.raw_os_error() == Some(ERROR_SHARING_VIOLATION as i32)
268                    || err.raw_os_error() == Some(ERROR_ACCESS_DENIED as i32)
269                {
270                    return Ok(None);
271                }
272            }
273            Err(err.into())
274        }
275    }
276}
277
278struct ReadDirStream {
279    rx: mpsc::Receiver<DirectoryEntry>,
280    task: JoinHandle<Result<(), ErrorCode>>,
281    result: Option<oneshot::Sender<Result<(), ErrorCode>>>,
282}
283
284impl ReadDirStream {
285    fn new(
286        dir: Arc<std::fs::File>,
287        result: oneshot::Sender<Result<(), ErrorCode>>,
288    ) -> ReadDirStream {
289        let (tx, rx) = mpsc::channel(1);
290        ReadDirStream {
291            task: spawn_blocking(move || {
292                let entries = cap_primitives::fs::read_base_dir(&dir)?;
293                for entry in entries {
294                    if let Some(entry) = map_dir_entry(entry)? {
295                        if let Err(_) = tx.blocking_send(entry) {
296                            break;
297                        }
298                    }
299                }
300                Ok(())
301            }),
302            rx,
303            result: Some(result),
304        }
305    }
306
307    fn close(&mut self, res: Result<(), ErrorCode>) {
308        self.rx.close();
309        self.task.abort();
310        let _ = self.result.take().unwrap().send(res);
311    }
312}
313
314impl<D> StreamProducer<D> for ReadDirStream {
315    type Item = DirectoryEntry;
316    type Buffer = Option<DirectoryEntry>;
317
318    fn poll_produce<'a>(
319        mut self: Pin<&mut Self>,
320        cx: &mut Context<'_>,
321        mut store: StoreContextMut<'a, D>,
322        mut dst: Destination<'a, Self::Item, Self::Buffer>,
323        finish: bool,
324    ) -> Poll<wasmtime::Result<StreamResult>> {
325        // If this is a 0-length read then `mpsc::Receiver` does not expose an
326        // API to wait for an item to be available without taking it out of the
327        // channel. In lieu of that just say that we're complete and ready for a
328        // read.
329        if dst.remaining(&mut store) == Some(0) {
330            return Poll::Ready(Ok(StreamResult::Completed));
331        }
332
333        match self.rx.poll_recv(cx) {
334            // If an item is on the channel then send that along and say that
335            // the read is now complete with one item being yielded.
336            Poll::Ready(Some(item)) => {
337                dst.set_buffer(Some(item));
338                Poll::Ready(Ok(StreamResult::Completed))
339            }
340
341            // If there's nothing left on the channel then that means that an
342            // error occurred or the iterator is done. In both cases an
343            // un-cancellable wait for the spawned task is entered and we await
344            // its completion. Upon completion there our own stream is closed
345            // with the result (sending an error code on our oneshot) and then
346            // the stream is reported as dropped.
347            Poll::Ready(None) => {
348                let result = ready!(Pin::new(&mut self.task).poll(cx))
349                    .expect("spawned task should not panic");
350                self.close(result);
351                Poll::Ready(Ok(StreamResult::Dropped))
352            }
353
354            // If an item isn't ready yet then cancel this outstanding request
355            // if `finish` is set, otherwise propagate the `Pending` status.
356            Poll::Pending if finish => Poll::Ready(Ok(StreamResult::Cancelled)),
357            Poll::Pending => Poll::Pending,
358        }
359    }
360}
361
362impl Drop for ReadDirStream {
363    fn drop(&mut self) {
364        if self.result.is_some() {
365            self.close(Ok(()));
366        }
367    }
368}
369
370struct WriteStreamConsumer {
371    file: File,
372    location: WriteLocation,
373    result: Option<oneshot::Sender<Result<(), ErrorCode>>>,
374    buffer: BytesMut,
375    task: Option<JoinHandle<std::io::Result<(BytesMut, usize)>>>,
376}
377
378#[derive(Copy, Clone)]
379enum WriteLocation {
380    End,
381    Offset(u64),
382}
383
384impl WriteStreamConsumer {
385    fn new_at(file: File, offset: u64, result: oneshot::Sender<Result<(), ErrorCode>>) -> Self {
386        Self {
387            file,
388            location: WriteLocation::Offset(offset),
389            result: Some(result),
390            buffer: BytesMut::default(),
391            task: None,
392        }
393    }
394
395    fn new_append(file: File, result: oneshot::Sender<Result<(), ErrorCode>>) -> Self {
396        Self {
397            file,
398            location: WriteLocation::End,
399            result: Some(result),
400            buffer: BytesMut::default(),
401            task: None,
402        }
403    }
404
405    fn close(&mut self, res: Result<(), ErrorCode>) {
406        _ = self.result.take().unwrap().send(res);
407    }
408
409    /// Update the internal `offset` field after writing `amt` bytes from the file.
410    fn complete_write(&mut self, amt: usize) -> StreamResult {
411        match &mut self.location {
412            WriteLocation::End => StreamResult::Completed,
413            WriteLocation::Offset(offset) => {
414                let Ok(amt) = amt.try_into() else {
415                    self.close(Err(ErrorCode::Overflow));
416                    return StreamResult::Dropped;
417                };
418                let Some(amt) = offset.checked_add(amt) else {
419                    self.close(Err(ErrorCode::Overflow));
420                    return StreamResult::Dropped;
421                };
422                *offset = amt;
423                StreamResult::Completed
424            }
425        }
426    }
427}
428
429impl WriteLocation {
430    fn write(&self, file: &std::fs::File, bytes: &[u8]) -> io::Result<usize> {
431        match *self {
432            WriteLocation::End => sys::append_cursor_unspecified(file, bytes),
433            WriteLocation::Offset(at) => sys::write_at_cursor_unspecified(file, bytes, at),
434        }
435    }
436}
437
438impl<D> StreamConsumer<D> for WriteStreamConsumer {
439    type Item = u8;
440
441    fn poll_consume(
442        mut self: Pin<&mut Self>,
443        cx: &mut Context<'_>,
444        store: StoreContextMut<D>,
445        src: Source<Self::Item>,
446        finish: bool,
447    ) -> Poll<wasmtime::Result<StreamResult>> {
448        let mut src = src.as_direct(store);
449        if let Some(file) = self.file.as_blocking_file() {
450            // Once a blocking file, always a blocking file, so assert as such.
451            assert!(self.task.is_none());
452            return match self.location.write(file, src.remaining()) {
453                Ok(n) => {
454                    src.mark_read(n);
455                    Poll::Ready(Ok(self.complete_write(n)))
456                }
457                Err(err) => {
458                    self.close(Err(err.into()));
459                    Poll::Ready(Ok(StreamResult::Dropped))
460                }
461            };
462        }
463        let me = &mut *self;
464        let task = me.task.get_or_insert_with(|| {
465            debug_assert!(me.buffer.is_empty());
466            me.buffer.extend_from_slice(src.remaining());
467            let buf = mem::take(&mut me.buffer);
468            let file = Arc::clone(me.file.as_file());
469            let location = me.location;
470            spawn_blocking(move || location.write(&file, &buf).map(|n| (buf, n)))
471        });
472        let result = match Pin::new(&mut *task).poll(cx) {
473            // If cancellation is requested, then flag that to Tokio. Note that
474            // this still waits for the actual completion of the spawned task,
475            // which won't actually happen if it's already executing.
476            Poll::Pending if finish => {
477                task.abort();
478                ready!(Pin::new(task).poll(cx))
479            }
480            other => ready!(other),
481        };
482        self.task = None;
483        match result {
484            Ok(Ok((buf, n))) => {
485                src.mark_read(n);
486                self.buffer = buf;
487                self.buffer.clear();
488                Poll::Ready(Ok(self.complete_write(n)))
489            }
490            Ok(Err(err)) => {
491                self.close(Err(err.into()));
492                Poll::Ready(Ok(StreamResult::Dropped))
493            }
494            Err(err) => {
495                if err.is_cancelled() {
496                    return Poll::Ready(Ok(StreamResult::Cancelled));
497                }
498                panic!("I/O task should not panic: {err}")
499            }
500        }
501    }
502}
503
504impl Drop for WriteStreamConsumer {
505    fn drop(&mut self) {
506        if self.result.is_some() {
507            self.close(Ok(()))
508        }
509    }
510}
511
512impl types::Host for WasiFilesystemCtxView<'_> {
513    fn convert_error_code(&mut self, error: FilesystemError) -> wasmtime::Result<ErrorCode> {
514        error.downcast()
515    }
516}
517
518impl<U> types::HostDescriptorWithStore<U> for WasiFilesystem {
519    fn read_via_stream(
520        mut store: Access<U, Self>,
521        fd: Resource<Descriptor>,
522        offset: Filesize,
523    ) -> wasmtime::Result<(StreamReader<u8>, FutureReader<Result<(), ErrorCode>>)> {
524        let file = match get_descriptor(store.get().table, &fd)? {
525            Descriptor::File(file) => file.clone(),
526            Descriptor::Dir(_) => {
527                return Ok((
528                    StreamReader::new(&mut store, iter::empty())?,
529                    FutureReader::new(&mut store, async move {
530                        wasmtime::error::Ok(Err(ErrorCode::IsDirectory))
531                    })?,
532                ));
533            }
534        };
535        let (result_tx, result_rx) = oneshot::channel();
536        Ok((
537            StreamReader::new(
538                &mut store,
539                ReadStreamProducer {
540                    file,
541                    offset,
542                    result: Some(result_tx),
543                    task: None,
544                },
545            )?,
546            FutureReader::new(&mut store, result_rx)?,
547        ))
548    }
549
550    fn write_via_stream(
551        mut store: Access<'_, U, Self>,
552        fd: Resource<Descriptor>,
553        mut data: StreamReader<u8>,
554        offset: Filesize,
555    ) -> wasmtime::Result<FutureReader<Result<(), ErrorCode>>> {
556        let (result_tx, result_rx) = oneshot::channel();
557        match get_file(store.get().table, &fd).and_then(|file| {
558            if file.perms.write_not_permitted() {
559                Err(ErrorCode::NotPermitted.into())
560            } else {
561                Ok(file.clone())
562            }
563        }) {
564            Ok(file) => {
565                data.pipe(
566                    &mut store,
567                    WriteStreamConsumer::new_at(file, offset, result_tx),
568                )?;
569            }
570            Err(err) => {
571                data.close(&mut store)?;
572                let _ = result_tx.send(Err(err.downcast().unwrap_or(ErrorCode::Io)));
573            }
574        }
575        FutureReader::new(&mut store, result_rx)
576    }
577
578    fn append_via_stream(
579        mut store: Access<'_, U, Self>,
580        fd: Resource<Descriptor>,
581        mut data: StreamReader<u8>,
582    ) -> wasmtime::Result<FutureReader<Result<(), ErrorCode>>> {
583        let (result_tx, result_rx) = oneshot::channel();
584        match get_file(store.get().table, &fd).and_then(|file| {
585            if file.perms.write_not_permitted() {
586                Err(ErrorCode::NotPermitted.into())
587            } else {
588                Ok(file.clone())
589            }
590        }) {
591            Ok(file) => {
592                data.pipe(&mut store, WriteStreamConsumer::new_append(file, result_tx))?;
593            }
594            Err(err) => {
595                data.close(&mut store)?;
596                let _ = result_tx.send(Err(err.downcast().unwrap_or(ErrorCode::Io)));
597            }
598        }
599        FutureReader::new(&mut store, result_rx)
600    }
601
602    async fn advise(
603        store: &Accessor<U, Self>,
604        fd: Resource<Descriptor>,
605        offset: Filesize,
606        length: Filesize,
607        advice: Advice,
608    ) -> FilesystemResult<()> {
609        let file = store.get_file(&fd)?;
610        file.advise(offset, length, advice.into()).await?;
611        Ok(())
612    }
613
614    async fn sync_data(
615        store: &Accessor<U, Self>,
616        fd: Resource<Descriptor>,
617    ) -> FilesystemResult<()> {
618        let fd = store.get_descriptor(&fd)?;
619        fd.sync_data().await?;
620        Ok(())
621    }
622
623    async fn get_flags(
624        store: &Accessor<U, Self>,
625        fd: Resource<Descriptor>,
626    ) -> FilesystemResult<DescriptorFlags> {
627        let fd = store.get_descriptor(&fd)?;
628        let flags = fd.get_flags().await?;
629        Ok(flags.into())
630    }
631
632    async fn get_type(
633        store: &Accessor<U, Self>,
634        fd: Resource<Descriptor>,
635    ) -> FilesystemResult<DescriptorType> {
636        let fd = store.get_descriptor(&fd)?;
637        let ty = fd.get_type().await?;
638        Ok(ty.into())
639    }
640
641    async fn set_size(
642        store: &Accessor<U, Self>,
643        fd: Resource<Descriptor>,
644        size: Filesize,
645    ) -> FilesystemResult<()> {
646        let file = store.get_file(&fd)?;
647        file.set_size(size).await?;
648        Ok(())
649    }
650
651    async fn set_times(
652        store: &Accessor<U, Self>,
653        fd: Resource<Descriptor>,
654        data_access_timestamp: NewTimestamp,
655        data_modification_timestamp: NewTimestamp,
656    ) -> FilesystemResult<()> {
657        let fd = store.get_descriptor(&fd)?;
658        let atim = systemtimespec_from(data_access_timestamp)?;
659        let mtim = systemtimespec_from(data_modification_timestamp)?;
660        fd.set_times(atim, mtim).await?;
661        Ok(())
662    }
663
664    fn read_directory(
665        mut store: Access<'_, U, Self>,
666        fd: Resource<Descriptor>,
667    ) -> wasmtime::Result<(
668        StreamReader<DirectoryEntry>,
669        FutureReader<Result<(), ErrorCode>>,
670    )> {
671        let (result_tx, result_rx) = oneshot::channel();
672        let stream = match get_dir(store.get().table, &fd) {
673            Ok(dir) => {
674                let allow_blocking_current_thread = dir.allow_blocking_current_thread;
675                let dir = Arc::clone(dir.as_dir());
676                if allow_blocking_current_thread {
677                    match cap_primitives::fs::read_base_dir(&dir) {
678                        Ok(readdir) => StreamReader::new(
679                            &mut store,
680                            FallibleIteratorProducer::new(
681                                readdir.filter_map(|e| map_dir_entry(e).transpose()),
682                                result_tx,
683                            ),
684                        )?,
685                        Err(e) => {
686                            let _ = result_tx.send(Err(e.into()));
687                            StreamReader::new(&mut store, iter::empty())?
688                        }
689                    }
690                } else {
691                    StreamReader::new(&mut store, ReadDirStream::new(dir, result_tx))?
692                }
693            }
694            Err(err) => {
695                let _ = result_tx.send(Err(err.downcast().unwrap_or(ErrorCode::Io)));
696                StreamReader::new(&mut store, iter::empty())?
697            }
698        };
699        Ok((stream, FutureReader::new(&mut store, result_rx)?))
700    }
701
702    async fn sync(store: &Accessor<U, Self>, fd: Resource<Descriptor>) -> FilesystemResult<()> {
703        let fd = store.get_descriptor(&fd)?;
704        fd.sync().await?;
705        Ok(())
706    }
707
708    async fn create_directory_at(
709        store: &Accessor<U, Self>,
710        fd: Resource<Descriptor>,
711        path: String,
712    ) -> FilesystemResult<()> {
713        let dir = store.get_dir(&fd)?;
714        dir.create_directory_at(path).await?;
715        Ok(())
716    }
717
718    async fn stat(
719        store: &Accessor<U, Self>,
720        fd: Resource<Descriptor>,
721    ) -> FilesystemResult<DescriptorStat> {
722        let fd = store.get_descriptor(&fd)?;
723        let stat = fd.stat().await?;
724        Ok(stat.into())
725    }
726
727    async fn stat_at(
728        store: &Accessor<U, Self>,
729        fd: Resource<Descriptor>,
730        path_flags: PathFlags,
731        path: String,
732    ) -> FilesystemResult<DescriptorStat> {
733        let dir = store.get_dir(&fd)?;
734        let stat = dir.stat_at(path_flags.into(), path).await?;
735        Ok(stat.into())
736    }
737
738    async fn set_times_at(
739        store: &Accessor<U, Self>,
740        fd: Resource<Descriptor>,
741        path_flags: PathFlags,
742        path: String,
743        data_access_timestamp: NewTimestamp,
744        data_modification_timestamp: NewTimestamp,
745    ) -> FilesystemResult<()> {
746        let dir = store.get_dir(&fd)?;
747        let atim = systemtimespec_from(data_access_timestamp)?;
748        let mtim = systemtimespec_from(data_modification_timestamp)?;
749        dir.set_times_at(path_flags.into(), path, atim, mtim)
750            .await?;
751        Ok(())
752    }
753
754    async fn link_at(
755        store: &Accessor<U, Self>,
756        fd: Resource<Descriptor>,
757        old_path_flags: PathFlags,
758        old_path: String,
759        new_fd: Resource<Descriptor>,
760        new_path: String,
761    ) -> FilesystemResult<()> {
762        let (old_dir, new_dir) = store.get_dir_pair(&fd, &new_fd)?;
763        old_dir
764            .link_at(old_path_flags.into(), old_path, &new_dir, new_path)
765            .await?;
766        Ok(())
767    }
768
769    async fn open_at(
770        store: &Accessor<U, Self>,
771        fd: Resource<Descriptor>,
772        path_flags: PathFlags,
773        path: String,
774        open_flags: OpenFlags,
775        flags: DescriptorFlags,
776    ) -> FilesystemResult<Resource<Descriptor>> {
777        let (allow_blocking_current_thread, dir) = store.with(|mut store| {
778            let store = store.get();
779            let dir = get_dir(&store.table, &fd)?;
780            FilesystemResult::Ok((store.ctx.allow_blocking_current_thread, dir.clone()))
781        })?;
782        let fd = dir
783            .open_at(
784                path_flags.into(),
785                path,
786                open_flags.into(),
787                flags.into(),
788                allow_blocking_current_thread,
789            )
790            .await?;
791        let fd = store.with(|mut store| store.get().table.push(fd))?;
792        Ok(fd)
793    }
794
795    async fn readlink_at(
796        store: &Accessor<U, Self>,
797        fd: Resource<Descriptor>,
798        path: String,
799    ) -> FilesystemResult<String> {
800        let dir = store.get_dir(&fd)?;
801        let path = dir.readlink_at(path).await?;
802        Ok(path)
803    }
804
805    async fn remove_directory_at(
806        store: &Accessor<U, Self>,
807        fd: Resource<Descriptor>,
808        path: String,
809    ) -> FilesystemResult<()> {
810        let dir = store.get_dir(&fd)?;
811        dir.remove_directory_at(path).await?;
812        Ok(())
813    }
814
815    async fn rename_at(
816        store: &Accessor<U, Self>,
817        fd: Resource<Descriptor>,
818        old_path: String,
819        new_fd: Resource<Descriptor>,
820        new_path: String,
821    ) -> FilesystemResult<()> {
822        let (old_dir, new_dir) = store.get_dir_pair(&fd, &new_fd)?;
823        old_dir.rename_at(old_path, &new_dir, new_path).await?;
824        Ok(())
825    }
826
827    async fn symlink_at(
828        store: &Accessor<U, Self>,
829        fd: Resource<Descriptor>,
830        old_path: String,
831        new_path: String,
832    ) -> FilesystemResult<()> {
833        let dir = store.get_dir(&fd)?;
834        dir.symlink_at(old_path, new_path).await?;
835        Ok(())
836    }
837
838    async fn unlink_file_at(
839        store: &Accessor<U, Self>,
840        fd: Resource<Descriptor>,
841        path: String,
842    ) -> FilesystemResult<()> {
843        let dir = store.get_dir(&fd)?;
844        dir.unlink_file_at(path).await?;
845        Ok(())
846    }
847
848    async fn is_same_object(
849        store: &Accessor<U, Self>,
850        fd: Resource<Descriptor>,
851        other: Resource<Descriptor>,
852    ) -> wasmtime::Result<bool> {
853        let (fd, other) = store.with(|mut store| {
854            let table = store.get().table;
855            let fd = get_descriptor(table, &fd)?.clone();
856            let other = get_descriptor(table, &other)?.clone();
857            wasmtime::error::Ok((fd, other))
858        })?;
859        fd.is_same_object(&other).await
860    }
861
862    async fn metadata_hash(
863        store: &Accessor<U, Self>,
864        fd: Resource<Descriptor>,
865    ) -> FilesystemResult<MetadataHashValue> {
866        let fd = store.get_descriptor(&fd)?;
867        let meta = fd.metadata_hash().await?;
868        Ok(meta.into())
869    }
870
871    async fn metadata_hash_at(
872        store: &Accessor<U, Self>,
873        fd: Resource<Descriptor>,
874        path_flags: PathFlags,
875        path: String,
876    ) -> FilesystemResult<MetadataHashValue> {
877        let dir = store.get_dir(&fd)?;
878        let meta = dir.metadata_hash_at(path_flags.into(), path).await?;
879        Ok(meta.into())
880    }
881}
882
883impl types::HostDescriptor for WasiFilesystemCtxView<'_> {
884    fn drop(&mut self, fd: Resource<Descriptor>) -> wasmtime::Result<()> {
885        self.table
886            .delete(fd)
887            .context("failed to delete descriptor resource from table")?;
888        Ok(())
889    }
890}
891
892impl preopens::Host for WasiFilesystemCtxView<'_> {
893    fn get_directories(&mut self) -> wasmtime::Result<Vec<(Resource<Descriptor>, String)>> {
894        self.get_directories()
895    }
896}