Skip to content

Commit

Permalink
Add support for Blob (#74)
Browse files Browse the repository at this point in the history
* Add support for Blob

* Make 'Blob instanceof Blob' be true

* Split subtests into separated tests

* Error out on non-defined binaryType

* Unexport 'blob' Go struct

* Fix linter complaints

* Use 'must' helper to set obj props

* Add support for Blob.stream()

* Add some tests for Blob's public methods

* Update README.md with Blob support

* Tidy up Go module

* Fix linter complaints

* Downgrade modules upgraded by mistake

* Remove toolchain directive from go.mod

* Undo deps update

* Apply suggestions from code review

* Extend the support for Blob

* Support .send() for Blob

* Support Blob() for Blob and DataView

* Stop relying on '_ref' internal attribute

* Fix linter complaints

* Fix TestBlob/ArrayBuffer

* Make 'isBlob' work independently of 'rt.GlobalObject()'
  • Loading branch information
joanlopez authored Jul 3, 2024
1 parent 113a951 commit 75c13b2
Show file tree
Hide file tree
Showing 8 changed files with 708 additions and 55 deletions.
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ This is meant to try to implement the specification as close as possible without

1. not reporting errors
2. not allowing some ports and other security workarounds
3. supporting Blob as message

It supports additional k6 specific features such as:

Expand Down Expand Up @@ -41,7 +40,9 @@ It is implemented using the [xk6](https://k6.io/blog/extending-k6-with-xk6/) sys

## Discrepancies with the specifications

* `binaryType` is an `ArrayBuffer` by default instead of "Blob" and will throw an exception if it's tried to be changed as "Blob" is not supported by k6.
* `binaryType` does not have a default value (in contrast to the spec, [which suggests `"blob"` as default](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/binaryType)),
so in order to successfully receive binary messages a `binaryType` must be explicitly set either to `"arraybuffer"` (for `ArrayBuffer`)
or `"blob"` (for `Blob`).

## Contributing

Expand Down
12 changes: 6 additions & 6 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ go 1.20

require (
github.com/gorilla/websocket v1.5.1
github.com/grafana/sobek v0.0.0-20240606091932-2da0e9e5f3e7
github.com/grafana/sobek v0.0.0-20240607083612-4f0cd64f4e78
github.com/mstoykov/k6-taskqueue-lib v0.1.0
github.com/sirupsen/logrus v1.9.3
github.com/stretchr/testify v1.9.0
go.k6.io/k6 v0.51.1-0.20240606120708-bd114fdbd683
go.k6.io/k6 v0.51.1-0.20240612130226-3415ce6edc99
go.uber.org/goleak v1.3.0
gopkg.in/guregu/null.v3 v3.3.0
)
Expand Down Expand Up @@ -54,10 +54,10 @@ require (
go.opentelemetry.io/otel/sdk v1.24.0 // indirect
go.opentelemetry.io/otel/trace v1.24.0 // indirect
go.opentelemetry.io/proto/otlp v1.1.0 // indirect
golang.org/x/crypto v0.21.0 // indirect
golang.org/x/net v0.23.0 // indirect
golang.org/x/sys v0.18.0 // indirect
golang.org/x/text v0.14.0 // indirect
golang.org/x/crypto v0.24.0 // indirect
golang.org/x/net v0.26.0 // indirect
golang.org/x/sys v0.21.0 // indirect
golang.org/x/text v0.16.0 // indirect
golang.org/x/time v0.5.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20240227224415-6ceb2ff114de // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de // indirect
Expand Down
24 changes: 12 additions & 12 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ github.com/google/pprof v0.0.0-20230728192033-2ba5b33183c6 h1:ZgoomqkdjGbQ3+qQXC
github.com/google/pprof v0.0.0-20230728192033-2ba5b33183c6/go.mod h1:Jh3hGz2jkYak8qXPD19ryItVnUgpgeqzdkY/D0EaeuA=
github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY=
github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY=
github.com/grafana/sobek v0.0.0-20240606091932-2da0e9e5f3e7 h1:Ed0df3dkkPsjL0RKagJAv/821vrTBiB6GBk+198pxi4=
github.com/grafana/sobek v0.0.0-20240606091932-2da0e9e5f3e7/go.mod h1:6ZH0b0iOxyigeTh+/IlGoL0Hd3lVXA94xoXf0ldNgCM=
github.com/grafana/sobek v0.0.0-20240607083612-4f0cd64f4e78 h1:rVCZdB+13G+aQoGm3CBVaDGl0uxZxfjvQgEJy4IeHTA=
github.com/grafana/sobek v0.0.0-20240607083612-4f0cd64f4e78/go.mod h1:6ZH0b0iOxyigeTh+/IlGoL0Hd3lVXA94xoXf0ldNgCM=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.19.0 h1:Wqo399gCIufwto+VfwCSvsnfGpF/w5E9CNxSwbpD6No=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.19.0/go.mod h1:qmOFXW2epJhM0qSnUUYpldc7gVz2KMQwJ/QYCDIa7XU=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
Expand Down Expand Up @@ -108,8 +108,8 @@ github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.k6.io/k6 v0.51.1-0.20240606120708-bd114fdbd683 h1:ockJVj41NNWzadyC3fvlSMRXT8QYxEzo13tVvE/WBEw=
go.k6.io/k6 v0.51.1-0.20240606120708-bd114fdbd683/go.mod h1:jKW0vrZjFqum5UGRPw/38ks4bYEywYuEo8vMccp/0Nc=
go.k6.io/k6 v0.51.1-0.20240612130226-3415ce6edc99 h1:MsTh/RGrVq+zOBLVj24t+oB7KS0pWInRhmGrgv3qU4o=
go.k6.io/k6 v0.51.1-0.20240612130226-3415ce6edc99/go.mod h1:LJKmFwUODAYoxitsJ3Xk+wsyVJDpyQiLyJAVn+oGyVQ=
go.opentelemetry.io/otel v1.24.0 h1:0LAOdjNmQeSTzGBzduGe/rU4tZhMwL5rWgtp9Ku5Jfo=
go.opentelemetry.io/otel v1.24.0/go.mod h1:W7b9Ozg4nkF5tWI5zsXkaKKDjdVjpD4oAt9Qi/MArHo=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.24.0 h1:t6wl9SPayj+c7lEIFgm4ooDBZVb01IhLB4InpomhRw8=
Expand All @@ -132,8 +132,8 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA=
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
golang.org/x/crypto v0.24.0 h1:mnl8DM0o513X8fdIkmyFE/5hTYxbwYOjDS/+rK6qpRI=
golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
Expand All @@ -146,8 +146,8 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs=
golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
golang.org/x/net v0.26.0 h1:soB7SVo0PWrY4vPW/+ay0jKDNScG2X9wFeYlXIvJsOQ=
golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
Expand All @@ -171,8 +171,8 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws=
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
Expand All @@ -182,8 +182,8 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
Expand Down
192 changes: 192 additions & 0 deletions websockets/blob.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
package websockets

import (
"bytes"
"errors"
"fmt"
"strconv"
"unsafe"

"github.com/grafana/sobek"

"go.k6.io/k6/js/common"
"go.k6.io/k6/js/modules/k6/experimental/streams"
)

type blob struct {
typ string
data bytes.Buffer
}

func (b *blob) text() string {
return b.data.String()
}

func (r *WebSocketsAPI) blob(call sobek.ConstructorCall) *sobek.Object {
rt := r.vu.Runtime()

b := &blob{}
var blobParts []interface{}
if len(call.Arguments) > 0 {
if err := rt.ExportTo(call.Arguments[0], &blobParts); err != nil {
common.Throw(rt, fmt.Errorf("failed to process [blobParts]: %w", err))
}
}

if len(blobParts) > 0 {
r.fillData(b, blobParts, call)
}

if len(call.Arguments) > 1 && !sobek.IsUndefined(call.Arguments[1]) {
opts := call.Arguments[1]
if !isObject(opts) {
common.Throw(rt, errors.New("[options] must be an object"))
}

typeOpt := opts.ToObject(rt).Get("type")
if !sobek.IsUndefined(typeOpt) {
b.typ = typeOpt.String()
}
}

obj := rt.NewObject()
must(rt, obj.DefineAccessorProperty("size", rt.ToValue(func() sobek.Value {
return rt.ToValue(b.data.Len())
}), nil, sobek.FLAG_FALSE, sobek.FLAG_TRUE))
must(rt, obj.DefineAccessorProperty("type", rt.ToValue(func() sobek.Value {
return rt.ToValue(b.typ)
}), nil, sobek.FLAG_FALSE, sobek.FLAG_TRUE))

must(rt, obj.Set("arrayBuffer", func(_ sobek.FunctionCall) sobek.Value {
promise, resolve, _ := rt.NewPromise()
resolve(rt.NewArrayBuffer(b.data.Bytes()))
return rt.ToValue(promise)
}))
must(rt, obj.Set("bytes", func(_ sobek.FunctionCall) sobek.Value {
promise, resolve, reject := rt.NewPromise()
data, err := rt.New(rt.Get("Uint8Array"), rt.ToValue(b.data.Bytes()))
if err == nil {
resolve(data)
} else {
reject(fmt.Errorf("failed to create Uint8Array: %w", err))
}
return rt.ToValue(promise)
}))
must(rt, obj.Set("slice", func(call sobek.FunctionCall) sobek.Value {
return r.slice(call, b, rt)
}))
must(rt, obj.Set("text", func(_ sobek.FunctionCall) sobek.Value {
promise, resolve, _ := rt.NewPromise()
resolve(b.text())
return rt.ToValue(promise)
}))
must(rt, obj.Set("stream", func(_ sobek.FunctionCall) sobek.Value {
return rt.ToValue(streams.NewReadableStreamFromReader(r.vu, &b.data))
}))

proto := call.This.Prototype()
must(rt, proto.Set("toString", func(_ sobek.FunctionCall) sobek.Value {
return rt.ToValue("[object Blob]")
}))
must(rt, obj.SetPrototype(proto))

return obj
}

func (r *WebSocketsAPI) fillData(b *blob, blobParts []interface{}, call sobek.ConstructorCall) {
rt := r.vu.Runtime()

if len(blobParts) > 0 {
for n, part := range blobParts {
var err error
switch v := part.(type) {
case []uint8:
_, err = b.data.Write(v)
case []int8, []int16, []int32, []int64, []uint16, []uint32, []uint64, []float32, []float64:
_, err = b.data.Write(toByteSlice(v))
case sobek.ArrayBuffer:
_, err = b.data.Write(v.Bytes())
case *sobek.ArrayBuffer:
_, err = b.data.Write(v.Bytes())
case string:
_, err = b.data.WriteString(v)
case map[string]interface{}:
obj := call.Arguments[0].ToObject(rt).Get(strconv.FormatInt(int64(n), 10)).ToObject(rt)
switch {
case isDataView(obj, rt):
_, err = b.data.Write(obj.Get("buffer").Export().(sobek.ArrayBuffer).Bytes())
case isBlob(obj, r.blobConstructor):
_, err = b.data.Write(extractBytes(obj, rt))
default:
err = fmt.Errorf("unsupported type: %T", part)
}
default:
err = fmt.Errorf("unsupported type: %T", part)
}
if err != nil {
common.Throw(rt, fmt.Errorf("failed to process [blobParts]: %w", err))
}
}
}
}

func (r *WebSocketsAPI) slice(call sobek.FunctionCall, b *blob, rt *sobek.Runtime) sobek.Value {
var (
from int
to = b.data.Len()
ct = ""
)

if len(call.Arguments) > 0 {
from = int(call.Arguments[0].ToInteger())
}

if len(call.Arguments) > 1 {
to = int(call.Arguments[1].ToInteger())
if to < 0 {
to = b.data.Len() + to
}
}

if len(call.Arguments) > 2 {
ct = call.Arguments[2].String()
}

opts := rt.NewObject()
must(rt, opts.Set("type", ct))

sliced, err := rt.New(r.blobConstructor, rt.ToValue([]interface{}{b.data.Bytes()[from:to]}), opts)
must(rt, err)

return sliced
}

// toByteSlice converts a slice of numbers to a slice of bytes.
//
//nolint:gosec
func toByteSlice(data interface{}) []byte {
switch v := data.(type) {
case []int8:
return unsafe.Slice((*byte)(unsafe.Pointer(&v[0])), len(v))
case []uint16:
return unsafe.Slice((*byte)(unsafe.Pointer(&v[0])), len(v)*2)
case []int16:
return unsafe.Slice((*byte)(unsafe.Pointer(&v[0])), len(v)*2)
case []uint32:
return unsafe.Slice((*byte)(unsafe.Pointer(&v[0])), len(v)*4)
case []int32:
return unsafe.Slice((*byte)(unsafe.Pointer(&v[0])), len(v)*4)
case []uint64:
return unsafe.Slice((*byte)(unsafe.Pointer(&v[0])), len(v)*8)
case []int64:
return unsafe.Slice((*byte)(unsafe.Pointer(&v[0])), len(v)*8)
case []float32:
return unsafe.Slice((*byte)(unsafe.Pointer(&v[0])), len(v)*4)
case []float64:
return unsafe.Slice((*byte)(unsafe.Pointer(&v[0])), len(v)*8)
default:
// this should never happen
common.Throw(nil, fmt.Errorf("unsupported type: %T", data))
return nil
}
}
Loading

0 comments on commit 75c13b2

Please sign in to comment.