Skip to content

Commit

Permalink
Expose the underlying behavior through a ReadSeekStater interface
Browse files Browse the repository at this point in the history
  • Loading branch information
oleiade committed Aug 1, 2024
1 parent ddae9bb commit c606d95
Showing 1 changed file with 26 additions and 5 deletions.
31 changes: 26 additions & 5 deletions js/modules/k6/experimental/fs/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package fs
import (
"errors"
"fmt"
"io"
"reflect"

"github.com/grafana/sobek"
Expand Down Expand Up @@ -136,7 +137,7 @@ func (mi *ModuleInstance) openImpl(path string) (*File, error) {

file := &File{
Path: path,
Impl: file{
ReadSeekStater: &file{
path: path,
data: data,
},
Expand All @@ -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
Expand All @@ -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.
//
Expand All @@ -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
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit c606d95

Please sign in to comment.