From c606d95c085ec7dc0c3ed7315a72892646ae8f64 Mon Sep 17 00:00:00 2001 From: oleiade Date: Thu, 23 May 2024 11:38:13 +0200 Subject: [PATCH] Expose the underlying behavior through a ReadSeekStater interface --- js/modules/k6/experimental/fs/module.go | 31 +++++++++++++++++++++---- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/js/modules/k6/experimental/fs/module.go b/js/modules/k6/experimental/fs/module.go index c78fdce3c9b..994c3e8083d 100644 --- a/js/modules/k6/experimental/fs/module.go +++ b/js/modules/k6/experimental/fs/module.go @@ -7,6 +7,7 @@ package fs import ( "errors" "fmt" + "io" "reflect" "github.com/grafana/sobek" @@ -136,7 +137,7 @@ func (mi *ModuleInstance) openImpl(path string) (*File, error) { file := &File{ Path: path, - Impl: file{ + ReadSeekStater: &file{ path: path, data: data, }, @@ -147,6 +148,26 @@ func (mi *ModuleInstance) openImpl(path string) (*File, error) { return file, nil } +// Stater is an interface that provides information about a file. +// +// Although in the context of this module we have a single implementation +// of this interface, it is defined to allow exposing the `file`'s behavior +// to other module through the `ReadSeekStater` interface without having to +// leak our internal abstraction. +type Stater interface { + // Stat returns a FileInfo describing the named file. + Stat() *FileInfo +} + +// ReadSeekStater is an interface that combines the io.ReadSeeker and Stater +// interfaces and ensure that structs implementing it have the necessary +// methods to interact with files. +type ReadSeekStater interface { + io.Reader + io.Seeker + Stater +} + // File represents a file and exposes methods to interact with it. // // It is a wrapper around the [file] struct, which is meant to be directly @@ -162,7 +183,7 @@ type File struct { // implementation details, but keep it public so that we can access it // from other modules that would want to leverage its implementation of // io.Reader and io.Seeker. - Impl file `js:"-"` + ReadSeekStater ReadSeekStater `js:"-"` // vu holds a reference to the VU this file is associated with. // @@ -182,7 +203,7 @@ func (f *File) Stat() *sobek.Promise { promise, resolve, _ := promises.New(f.vu) go func() { - resolve(f.Impl.stat()) + resolve(f.ReadSeekStater.Stat()) }() return promise @@ -227,7 +248,7 @@ func (f *File) Read(into sobek.Value) *sobek.Promise { // occurs on the main thread, during the promise's resolution. callback := f.vu.RegisterCallback() go func() { - n, readErr := f.Impl.Read(buffer) + n, readErr := f.ReadSeekStater.Read(buffer) callback(func() error { _ = copy(intoBytes[0:n], buffer) @@ -290,7 +311,7 @@ func (f *File) Seek(offset sobek.Value, whence sobek.Value) *sobek.Promise { callback := f.vu.RegisterCallback() go func() { - newOffset, err := f.Impl.Seek(intOffset, seekMode) + newOffset, err := f.ReadSeekStater.Seek(intOffset, seekMode) callback(func() error { if err != nil { reject(err)