From 3391a10c71e675df605ee6ed64dd1ec86da45caf Mon Sep 17 00:00:00 2001 From: Oleg Jukovec Date: Sun, 25 Dec 2022 12:13:41 +0300 Subject: [PATCH] api: use msgpack/v5 instead of msgpack.v2 We found several critical bugs in the library msgpack.v2. It was decided to update the library to msgpack/v5. Closes #211 Closes #236 --- .github/workflows/testing.yml | 38 --------- CHANGELOG.md | 2 + README.md | 10 +-- box_error.go | 30 ++++--- box_error_test.go | 19 ++--- client_tools.go | 32 ++++---- connection.go | 14 ++-- crud/count.go | 6 +- crud/delete.go | 4 +- crud/error.go | 10 ++- crud/get.go | 6 +- crud/insert.go | 6 +- crud/insert_many.go | 6 +- crud/len.go | 4 +- crud/max.go | 4 +- crud/min.go | 4 +- crud/msgpack.go | 29 ------- crud/msgpack_helper_test.go | 10 --- crud/msgpack_v5.go | 29 ------- crud/msgpack_v5_helper_test.go | 10 --- crud/object.go | 17 ++++ crud/options.go | 19 +++-- crud/replace.go | 6 +- crud/replace_many.go | 6 +- crud/request_test.go | 25 ++++-- crud/result.go | 16 +++- crud/select.go | 6 +- crud/stats.go | 4 +- crud/storage_info.go | 8 +- crud/truncate.go | 4 +- crud/update.go | 4 +- crud/upsert.go | 6 +- crud/upsert_many.go | 6 +- datetime/datetime.go | 6 ++ datetime/datetime_test.go | 32 ++++---- datetime/interval.go | 35 ++++++-- datetime/msgpack.go | 28 ------- datetime/msgpack_helper_test.go | 26 ------ datetime/msgpack_v5.go | 42 ---------- datetime/msgpack_v5_helper_test.go | 28 ------- decimal/decimal.go | 5 ++ decimal/decimal_test.go | 60 +++++++------- decimal/msgpack.go | 12 --- decimal/msgpack_helper_test.go | 26 ------ decimal/msgpack_v5.go | 12 --- decimal/msgpack_v5_helper_test.go | 28 ------- dial.go | 6 +- example_custom_unpacking_test.go | 8 +- export_test.go | 41 +++++----- go.mod | 3 - go.sum | 19 ----- msgpack.go | 54 ------------- msgpack_helper_test.go | 29 ------- msgpack_v5.go | 58 ------------- msgpack_v5_helper_test.go | 32 -------- pool/connection_pool_test.go | 4 +- pool/msgpack_helper_test.go | 10 --- pool/msgpack_v5_helper_test.go | 10 --- prepared.go | 32 ++++---- protocol.go | 12 +-- queue/example_msgpack_test.go | 6 +- queue/msgpack.go | 10 --- queue/msgpack_helper_test.go | 11 --- queue/msgpack_v5.go | 10 --- queue/msgpack_v5_helper_test.go | 11 --- queue/queue.go | 8 +- queue/queue_test.go | 6 +- queue/task.go | 4 +- request.go | 126 +++++++++++++++-------------- request_test.go | 74 +++++++++-------- response.go | 22 +++-- schema.go | 31 ++++++- settings/msgpack.go | 10 --- settings/msgpack_helper_test.go | 22 ----- settings/msgpack_v5.go | 10 --- settings/msgpack_v5_helper_test.go | 25 ------ settings/request.go | 6 +- settings/request_test.go | 4 +- settings/tarantool_test.go | 2 +- stream.go | 26 +++--- tarantool_test.go | 11 +-- test_helpers/main.go | 2 +- test_helpers/msgpack.go | 10 --- test_helpers/msgpack_v5.go | 10 --- test_helpers/request_mock.go | 4 +- test_helpers/utils.go | 15 ---- uuid/msgpack.go | 19 ----- uuid/msgpack_helper_test.go | 10 --- uuid/msgpack_v5.go | 27 ------- uuid/msgpack_v5_helper_test.go | 10 --- uuid/uuid.go | 20 ++++- uuid/uuid_test.go | 4 +- watch.go | 18 +++-- 93 files changed, 555 insertions(+), 1087 deletions(-) delete mode 100644 crud/msgpack.go delete mode 100644 crud/msgpack_helper_test.go delete mode 100644 crud/msgpack_v5.go delete mode 100644 crud/msgpack_v5_helper_test.go create mode 100644 crud/object.go delete mode 100644 datetime/msgpack.go delete mode 100644 datetime/msgpack_helper_test.go delete mode 100644 datetime/msgpack_v5.go delete mode 100644 datetime/msgpack_v5_helper_test.go delete mode 100644 decimal/msgpack.go delete mode 100644 decimal/msgpack_helper_test.go delete mode 100644 decimal/msgpack_v5.go delete mode 100644 decimal/msgpack_v5_helper_test.go delete mode 100644 msgpack.go delete mode 100644 msgpack_helper_test.go delete mode 100644 msgpack_v5.go delete mode 100644 msgpack_v5_helper_test.go delete mode 100644 pool/msgpack_helper_test.go delete mode 100644 pool/msgpack_v5_helper_test.go delete mode 100644 queue/msgpack.go delete mode 100644 queue/msgpack_helper_test.go delete mode 100644 queue/msgpack_v5.go delete mode 100644 queue/msgpack_v5_helper_test.go delete mode 100644 settings/msgpack.go delete mode 100644 settings/msgpack_helper_test.go delete mode 100644 settings/msgpack_v5.go delete mode 100644 settings/msgpack_v5_helper_test.go delete mode 100644 test_helpers/msgpack.go delete mode 100644 test_helpers/msgpack_v5.go delete mode 100644 uuid/msgpack.go delete mode 100644 uuid/msgpack_helper_test.go delete mode 100644 uuid/msgpack_v5.go delete mode 100644 uuid/msgpack_v5_helper_test.go diff --git a/.github/workflows/testing.yml b/.github/workflows/testing.yml index 7d90fa892..68f283b95 100644 --- a/.github/workflows/testing.yml +++ b/.github/workflows/testing.yml @@ -104,16 +104,6 @@ jobs: make test TAGS="go_tarantool_call_17" make testrace TAGS="go_tarantool_call_17" - - name: Run regression tests with msgpack.v5 - run: | - make test TAGS="go_tarantool_msgpack_v5" - make testrace TAGS="go_tarantool_msgpack_v5" - - - name: Run regression tests with msgpack.v5 and call_17 - run: | - make test TAGS="go_tarantool_msgpack_v5,go_tarantool_call_17" - make testrace TAGS="go_tarantool_msgpack_v5,go_tarantool_call_17" - - name: Run fuzzing tests if: ${{ matrix.fuzzing }} run: make fuzzing TAGS="go_tarantool_decimal_fuzzing" @@ -207,22 +197,6 @@ jobs: env: TEST_TNT_SSL: ${{matrix.ssl}} - - name: Run regression tests with msgpack.v5 - run: | - source tarantool-enterprise/env.sh - make test TAGS="go_tarantool_msgpack_v5" - make testrace TAGS="go_tarantool_msgpack_v5" - env: - TEST_TNT_SSL: ${{matrix.ssl}} - - - name: Run regression tests with msgpack.v5 and call_17 - run: | - source tarantool-enterprise/env.sh - make test TAGS="go_tarantool_msgpack_v5,go_tarantool_call_17" - make testrace TAGS="go_tarantool_msgpack_v5,go_tarantool_call_17" - env: - TEST_TNT_SSL: ${{matrix.ssl}} - - name: Run fuzzing tests if: ${{ matrix.fuzzing }} run: make fuzzing TAGS="go_tarantool_decimal_fuzzing" @@ -395,18 +369,6 @@ jobs: make test TAGS="go_tarantool_call_17" make testrace TAGS="go_tarantool_call_17" - - name: Run regression tests with msgpack.v5 - run: | - cd "${SRCDIR}" - make test TAGS="go_tarantool_msgpack_v5" - make testrace TAGS="go_tarantool_msgpack_v5" - - - name: Run regression tests with msgpack.v5 and call_17 - run: | - cd "${SRCDIR}" - make test TAGS="go_tarantool_msgpack_v5,go_tarantool_call_17" - make testrace TAGS="go_tarantool_msgpack_v5,go_tarantool_call_17" - - name: Run fuzzing tests if: ${{ matrix.fuzzing }} run: | diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e21632c1..7f9d1b99a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,10 +13,12 @@ Versioning](http://semver.org/spec/v2.0.0.html) except to the first release. ### Changed - connection_pool renamed to pool (#239) +- Use msgpack/v5 instead of msgpack.v2 (#236) ### Removed - multi subpackage (#240) +- msgpack.v2 support (#236) ### Fixed diff --git a/README.md b/README.md index 8151f71e2..ea941d964 100644 --- a/README.md +++ b/README.md @@ -72,15 +72,7 @@ This allows us to introduce new features without losing backward compatibility. go_tarantool_call_17 ``` **Note:** In future releases, `Call17` may be used as default `Call` behavior. -3. To replace usage of `msgpack.v2` with `msgpack.v5`, you can use the build - tag: - ``` - go_tarantool_msgpack_v5 - ``` - **Note:** In future releases, `msgpack.v5` may be used by default. We recommend - to read [msgpack.v5 migration notes](#msgpackv5-migration) and try to - use msgpack.v5 before the changes. -4. To run fuzz tests with decimals, you can use the build tag: +3. To run fuzz tests with decimals, you can use the build tag: ``` go_tarantool_decimal_fuzzing ``` diff --git a/box_error.go b/box_error.go index ab8981b0b..3d76a942c 100644 --- a/box_error.go +++ b/box_error.go @@ -3,6 +3,8 @@ package tarantool import ( "bytes" "fmt" + + "github.com/vmihailenco/msgpack/v5" ) const errorExtID = 3 @@ -69,7 +71,7 @@ func (e *BoxError) Depth() int { return depth } -func decodeBoxError(d *decoder) (*BoxError, error) { +func decodeBoxError(d *msgpack.Decoder) (*BoxError, error) { var l, larr, l1, l2 int var errorStack []BoxError var err error @@ -169,7 +171,7 @@ func decodeBoxError(d *decoder) (*BoxError, error) { return &errorStack[0], nil } -func encodeBoxError(enc *encoder, boxError *BoxError) error { +func encodeBoxError(enc *msgpack.Encoder, boxError *BoxError) error { if boxError == nil { return fmt.Errorf("msgpack: unexpected nil BoxError on encode") } @@ -177,7 +179,7 @@ func encodeBoxError(enc *encoder, boxError *BoxError) error { if err := enc.EncodeMapLen(1); err != nil { return err } - if err := encodeUint(enc, keyErrorStack); err != nil { + if err := enc.EncodeUint(keyErrorStack); err != nil { return err } @@ -199,42 +201,42 @@ func encodeBoxError(enc *encoder, boxError *BoxError) error { } } - if err := encodeUint(enc, keyErrorType); err != nil { + if err := enc.EncodeUint(keyErrorType); err != nil { return err } if err := enc.EncodeString(boxError.Type); err != nil { return err } - if err := encodeUint(enc, keyErrorFile); err != nil { + if err := enc.EncodeUint(keyErrorFile); err != nil { return err } if err := enc.EncodeString(boxError.File); err != nil { return err } - if err := encodeUint(enc, keyErrorLine); err != nil { + if err := enc.EncodeUint(keyErrorLine); err != nil { return err } if err := enc.EncodeUint64(boxError.Line); err != nil { return err } - if err := encodeUint(enc, keyErrorMessage); err != nil { + if err := enc.EncodeUint(keyErrorMessage); err != nil { return err } if err := enc.EncodeString(boxError.Msg); err != nil { return err } - if err := encodeUint(enc, keyErrorErrno); err != nil { + if err := enc.EncodeUint(keyErrorErrno); err != nil { return err } if err := enc.EncodeUint64(boxError.Errno); err != nil { return err } - if err := encodeUint(enc, keyErrorErrcode); err != nil { + if err := enc.EncodeUint(keyErrorErrcode); err != nil { return err } if err := enc.EncodeUint64(boxError.Code); err != nil { @@ -242,7 +244,7 @@ func encodeBoxError(enc *encoder, boxError *BoxError) error { } if fieldsLen > 0 { - if err := encodeUint(enc, keyErrorFields); err != nil { + if err := enc.EncodeUint(keyErrorFields); err != nil { return err } @@ -276,7 +278,7 @@ func (e *BoxError) UnmarshalMsgpack(b []byte) error { } buf := bytes.NewBuffer(b) - dec := newDecoder(buf) + dec := msgpack.NewDecoder(buf) if val, err := decodeBoxError(dec); err != nil { return err @@ -290,10 +292,14 @@ func (e *BoxError) UnmarshalMsgpack(b []byte) error { func (e *BoxError) MarshalMsgpack() ([]byte, error) { var buf bytes.Buffer - enc := newEncoder(&buf) + enc := msgpack.NewEncoder(&buf) if err := encodeBoxError(enc, e); err != nil { return nil, err } return buf.Bytes(), nil } + +func init() { + msgpack.RegisterExt(errorExtID, (*BoxError)(nil)) +} diff --git a/box_error_test.go b/box_error_test.go index 4c38d359c..d8ff5b11f 100644 --- a/box_error_test.go +++ b/box_error_test.go @@ -6,6 +6,8 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/vmihailenco/msgpack/v5" + . "github.com/tarantool/go-tarantool/v2" "github.com/tarantool/go-tarantool/v2/test_helpers" ) @@ -217,7 +219,7 @@ type TupleBoxError struct { val BoxError } -func (t *TupleBoxError) EncodeMsgpack(e *encoder) error { +func (t *TupleBoxError) EncodeMsgpack(e *msgpack.Encoder) error { if err := e.EncodeArrayLen(2); err != nil { return err } @@ -229,7 +231,7 @@ func (t *TupleBoxError) EncodeMsgpack(e *encoder) error { return e.Encode(&t.val) } -func (t *TupleBoxError) DecodeMsgpack(d *decoder) error { +func (t *TupleBoxError) DecodeMsgpack(d *msgpack.Decoder) error { var err error var l int if l, err = d.DecodeArrayLen(); err != nil { @@ -278,11 +280,11 @@ var tupleCases = map[string]struct { func TestErrorTypeMPEncodeDecode(t *testing.T) { for name, testcase := range tupleCases { t.Run(name, func(t *testing.T) { - buf, err := marshal(&testcase.tuple) + buf, err := msgpack.Marshal(&testcase.tuple) require.Nil(t, err) var res TupleBoxError - err = unmarshal(buf, &res) + err = msgpack.Unmarshal(buf, &res) require.Nil(t, err) require.Equal(t, testcase.tuple, res) @@ -302,9 +304,9 @@ func TestErrorTypeEval(t *testing.T) { require.Nil(t, err) require.NotNil(t, resp.Data) require.Equal(t, len(resp.Data), 1) - actual, ok := toBoxError(resp.Data[0]) + actual, ok := resp.Data[0].(*BoxError) require.Truef(t, ok, "Response data has valid type") - require.Equal(t, testcase.tuple.val, actual) + require.Equal(t, testcase.tuple.val, *actual) }) } } @@ -440,14 +442,13 @@ func TestErrorTypeSelect(t *testing.T) { tpl, ok := resp.Data[0].([]interface{}) require.Truef(t, ok, "Tuple has valid type") require.Equal(t, testcase.tuple.pk, tpl[0]) - var actual BoxError - actual, ok = toBoxError(tpl[1]) + actual, ok := tpl[1].(*BoxError) require.Truef(t, ok, "BoxError tuple field has valid type") // In fact, CheckEqualBoxErrors does not check than File and Line // of connector BoxError are equal to the Tarantool ones // since they may differ between different Tarantool versions // and editions. - test_helpers.CheckEqualBoxErrors(t, testcase.tuple.val, actual) + test_helpers.CheckEqualBoxErrors(t, testcase.tuple.val, *actual) }) } } diff --git a/client_tools.go b/client_tools.go index 9c439ec21..159f3d0ce 100644 --- a/client_tools.go +++ b/client_tools.go @@ -1,14 +1,18 @@ package tarantool +import ( + "github.com/vmihailenco/msgpack/v5" +) + // IntKey is utility type for passing integer key to Select*, Update*, // Delete* and GetTyped. It serializes to array with single integer element. type IntKey struct { I int } -func (k IntKey) EncodeMsgpack(enc *encoder) error { +func (k IntKey) EncodeMsgpack(enc *msgpack.Encoder) error { enc.EncodeArrayLen(1) - encodeInt(enc, int64(k.I)) + enc.EncodeInt(int64(k.I)) return nil } @@ -19,9 +23,9 @@ type UintKey struct { I uint } -func (k UintKey) EncodeMsgpack(enc *encoder) error { +func (k UintKey) EncodeMsgpack(enc *msgpack.Encoder) error { enc.EncodeArrayLen(1) - encodeUint(enc, uint64(k.I)) + enc.EncodeUint(uint64(k.I)) return nil } @@ -31,7 +35,7 @@ type StringKey struct { S string } -func (k StringKey) EncodeMsgpack(enc *encoder) error { +func (k StringKey) EncodeMsgpack(enc *msgpack.Encoder) error { enc.EncodeArrayLen(1) enc.EncodeString(k.S) return nil @@ -43,10 +47,10 @@ type IntIntKey struct { I1, I2 int } -func (k IntIntKey) EncodeMsgpack(enc *encoder) error { +func (k IntIntKey) EncodeMsgpack(enc *msgpack.Encoder) error { enc.EncodeArrayLen(2) - encodeInt(enc, int64(k.I1)) - encodeInt(enc, int64(k.I2)) + enc.EncodeInt(int64(k.I1)) + enc.EncodeInt(int64(k.I2)) return nil } @@ -57,10 +61,10 @@ type Op struct { Arg interface{} } -func (o Op) EncodeMsgpack(enc *encoder) error { +func (o Op) EncodeMsgpack(enc *msgpack.Encoder) error { enc.EncodeArrayLen(3) enc.EncodeString(o.Op) - encodeInt(enc, int64(o.Field)) + enc.EncodeInt(int64(o.Field)) return enc.Encode(o.Arg) } @@ -145,12 +149,12 @@ type OpSplice struct { Replace string } -func (o OpSplice) EncodeMsgpack(enc *encoder) error { +func (o OpSplice) EncodeMsgpack(enc *msgpack.Encoder) error { enc.EncodeArrayLen(5) enc.EncodeString(o.Op) - encodeInt(enc, int64(o.Field)) - encodeInt(enc, int64(o.Pos)) - encodeInt(enc, int64(o.Len)) + enc.EncodeInt(int64(o.Field)) + enc.EncodeInt(int64(o.Pos)) + enc.EncodeInt(int64(o.Len)) enc.EncodeString(o.Replace) return nil } diff --git a/connection.go b/connection.go index 055941e78..a79657072 100644 --- a/connection.go +++ b/connection.go @@ -14,6 +14,8 @@ import ( "sync" "sync/atomic" "time" + + "github.com/vmihailenco/msgpack/v5" ) const requestsMap = 128 @@ -164,7 +166,7 @@ type Connection struct { rlimit chan struct{} opts Opts state uint32 - dec *decoder + dec *msgpack.Decoder lenbuf [PacketLengthBytes]byte lastStreamId uint64 @@ -230,7 +232,7 @@ type connShard struct { requestsWithCtx [requestsMap]futureList bufmut sync.Mutex buf smallWBuf - enc *encoder + enc *msgpack.Encoder } // Opts is a way to configure Connection @@ -364,7 +366,7 @@ func Connect(addr string, opts Opts) (conn *Connection, err error) { Greeting: &Greeting{}, control: make(chan struct{}), opts: opts.Clone(), - dec: newDecoder(&smallBuf{}), + dec: msgpack.NewDecoder(&smallBuf{}), } maxprocs := uint32(runtime.GOMAXPROCS(-1)) if conn.opts.Concurrency == 0 || conn.opts.Concurrency > maxprocs*128 { @@ -579,7 +581,7 @@ func (conn *Connection) dial() (err error) { return } -func pack(h *smallWBuf, enc *encoder, reqid uint32, +func pack(h *smallWBuf, enc *msgpack.Encoder, reqid uint32, req Request, streamId uint64, res SchemaResolver) (err error) { const uint32Code = 0xce const uint64Code = 0xcf @@ -798,7 +800,7 @@ func (conn *Connection) writer(w writeFlusher, c Conn) { func readWatchEvent(reader io.Reader) (connWatchEvent, error) { keyExist := false event := connWatchEvent{} - d := newDecoder(reader) + d := msgpack.NewDecoder(reader) l, err := d.DecodeMapLen() if err != nil { @@ -1048,7 +1050,7 @@ func (conn *Connection) putFuture(fut *Future, req Request, streamId uint64) { firstWritten := shard.buf.Len() == 0 if shard.buf.Cap() == 0 { shard.buf.b = make([]byte, 0, 128) - shard.enc = newEncoder(&shard.buf) + shard.enc = msgpack.NewEncoder(&shard.buf) } blen := shard.buf.Len() reqid := fut.requestId diff --git a/crud/count.go b/crud/count.go index aede8f800..dc89f916e 100644 --- a/crud/count.go +++ b/crud/count.go @@ -3,6 +3,8 @@ package crud import ( "context" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" ) @@ -39,7 +41,7 @@ type CountOpts struct { } // EncodeMsgpack provides custom msgpack encoder. -func (opts CountOpts) EncodeMsgpack(enc *encoder) error { +func (opts CountOpts) EncodeMsgpack(enc *msgpack.Encoder) error { const optsCnt = 9 names := [optsCnt]string{timeoutOptName, vshardRouterOptName, @@ -101,7 +103,7 @@ func (req CountRequest) Opts(opts CountOpts) CountRequest { } // Body fills an encoder with the call request body. -func (req CountRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req CountRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { args := countArgs{Space: req.space, Conditions: req.conditions, Opts: req.opts} req.impl = req.impl.Args(args) return req.impl.Body(res, enc) diff --git a/crud/delete.go b/crud/delete.go index cd6e59382..f37da7ac5 100644 --- a/crud/delete.go +++ b/crud/delete.go @@ -3,6 +3,8 @@ package crud import ( "context" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" ) @@ -48,7 +50,7 @@ func (req DeleteRequest) Opts(opts DeleteOpts) DeleteRequest { } // Body fills an encoder with the call request body. -func (req DeleteRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req DeleteRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { if req.key == nil { req.key = []interface{}{} } diff --git a/crud/error.go b/crud/error.go index 12d416cfd..d7c36a333 100644 --- a/crud/error.go +++ b/crud/error.go @@ -1,6 +1,10 @@ package crud -import "strings" +import ( + "strings" + + "github.com/vmihailenco/msgpack/v5" +) // Error describes CRUD error object. type Error struct { @@ -20,7 +24,7 @@ type Error struct { } // DecodeMsgpack provides custom msgpack decoder. -func (e *Error) DecodeMsgpack(d *decoder) error { +func (e *Error) DecodeMsgpack(d *msgpack.Decoder) error { l, err := d.DecodeMapLen() if err != nil { return err @@ -76,7 +80,7 @@ type ErrorMany struct { } // DecodeMsgpack provides custom msgpack decoder. -func (e *ErrorMany) DecodeMsgpack(d *decoder) error { +func (e *ErrorMany) DecodeMsgpack(d *msgpack.Decoder) error { l, err := d.DecodeArrayLen() if err != nil { return err diff --git a/crud/get.go b/crud/get.go index f63bfda9f..e1855f35c 100644 --- a/crud/get.go +++ b/crud/get.go @@ -3,6 +3,8 @@ package crud import ( "context" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" ) @@ -30,7 +32,7 @@ type GetOpts struct { } // EncodeMsgpack provides custom msgpack encoder. -func (opts GetOpts) EncodeMsgpack(enc *encoder) error { +func (opts GetOpts) EncodeMsgpack(enc *msgpack.Encoder) error { const optsCnt = 7 names := [optsCnt]string{timeoutOptName, vshardRouterOptName, @@ -87,7 +89,7 @@ func (req GetRequest) Opts(opts GetOpts) GetRequest { } // Body fills an encoder with the call request body. -func (req GetRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req GetRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { if req.key == nil { req.key = []interface{}{} } diff --git a/crud/insert.go b/crud/insert.go index 2f09613a7..c696d201f 100644 --- a/crud/insert.go +++ b/crud/insert.go @@ -3,6 +3,8 @@ package crud import ( "context" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" ) @@ -48,7 +50,7 @@ func (req InsertRequest) Opts(opts InsertOpts) InsertRequest { } // Body fills an encoder with the call request body. -func (req InsertRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req InsertRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { if req.tuple == nil { req.tuple = []interface{}{} } @@ -106,7 +108,7 @@ func (req InsertObjectRequest) Opts(opts InsertObjectOpts) InsertObjectRequest { } // Body fills an encoder with the call request body. -func (req InsertObjectRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req InsertObjectRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { if req.object == nil { req.object = MapObject{} } diff --git a/crud/insert_many.go b/crud/insert_many.go index a3c3aead3..602e210d5 100644 --- a/crud/insert_many.go +++ b/crud/insert_many.go @@ -3,6 +3,8 @@ package crud import ( "context" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" ) @@ -48,7 +50,7 @@ func (req InsertManyRequest) Opts(opts InsertManyOpts) InsertManyRequest { } // Body fills an encoder with the call request body. -func (req InsertManyRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req InsertManyRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { if req.tuples == nil { req.tuples = []Tuple{} } @@ -106,7 +108,7 @@ func (req InsertObjectManyRequest) Opts(opts InsertObjectManyOpts) InsertObjectM } // Body fills an encoder with the call request body. -func (req InsertObjectManyRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req InsertObjectManyRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { if req.objects == nil { req.objects = []Object{} } diff --git a/crud/len.go b/crud/len.go index dc8a4cb10..5fef700d7 100644 --- a/crud/len.go +++ b/crud/len.go @@ -3,6 +3,8 @@ package crud import ( "context" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" ) @@ -42,7 +44,7 @@ func (req LenRequest) Opts(opts LenOpts) LenRequest { } // Body fills an encoder with the call request body. -func (req LenRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req LenRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { args := lenArgs{Space: req.space, Opts: req.opts} req.impl = req.impl.Args(args) return req.impl.Body(res, enc) diff --git a/crud/max.go b/crud/max.go index 7464b0480..727a17ac5 100644 --- a/crud/max.go +++ b/crud/max.go @@ -3,6 +3,8 @@ package crud import ( "context" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" ) @@ -48,7 +50,7 @@ func (req MaxRequest) Opts(opts MaxOpts) MaxRequest { } // Body fills an encoder with the call request body. -func (req MaxRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req MaxRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { args := maxArgs{Space: req.space, Index: req.index, Opts: req.opts} req.impl = req.impl.Args(args) return req.impl.Body(res, enc) diff --git a/crud/min.go b/crud/min.go index f186d303e..ab3bcfe07 100644 --- a/crud/min.go +++ b/crud/min.go @@ -3,6 +3,8 @@ package crud import ( "context" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" ) @@ -48,7 +50,7 @@ func (req MinRequest) Opts(opts MinOpts) MinRequest { } // Body fills an encoder with the call request body. -func (req MinRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req MinRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { args := minArgs{Space: req.space, Index: req.index, Opts: req.opts} req.impl = req.impl.Args(args) return req.impl.Body(res, enc) diff --git a/crud/msgpack.go b/crud/msgpack.go deleted file mode 100644 index b9696b15e..000000000 --- a/crud/msgpack.go +++ /dev/null @@ -1,29 +0,0 @@ -//go:build !go_tarantool_msgpack_v5 -// +build !go_tarantool_msgpack_v5 - -package crud - -import ( - "gopkg.in/vmihailenco/msgpack.v2" - msgpcode "gopkg.in/vmihailenco/msgpack.v2/codes" -) - -type encoder = msgpack.Encoder -type decoder = msgpack.Decoder - -// Object is an interface to describe object for CRUD methods. -type Object interface { - EncodeMsgpack(enc *encoder) -} - -// MapObject is a type to describe object as a map. -type MapObject map[string]interface{} - -func (o MapObject) EncodeMsgpack(enc *encoder) { - enc.Encode(o) -} - -func msgpackIsArray(code byte) bool { - return code == msgpcode.Array16 || code == msgpcode.Array32 || - msgpcode.IsFixedArray(code) -} diff --git a/crud/msgpack_helper_test.go b/crud/msgpack_helper_test.go deleted file mode 100644 index 7d3998fc6..000000000 --- a/crud/msgpack_helper_test.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build !go_tarantool_msgpack_v5 -// +build !go_tarantool_msgpack_v5 - -package crud_test - -import ( - "gopkg.in/vmihailenco/msgpack.v2" -) - -var newEncoder = msgpack.NewEncoder diff --git a/crud/msgpack_v5.go b/crud/msgpack_v5.go deleted file mode 100644 index 393e359c3..000000000 --- a/crud/msgpack_v5.go +++ /dev/null @@ -1,29 +0,0 @@ -//go:build go_tarantool_msgpack_v5 -// +build go_tarantool_msgpack_v5 - -package crud - -import ( - "github.com/vmihailenco/msgpack/v5" - "github.com/vmihailenco/msgpack/v5/msgpcode" -) - -type encoder = msgpack.Encoder -type decoder = msgpack.Decoder - -// Object is an interface to describe object for CRUD methods. -type Object interface { - EncodeMsgpack(enc *encoder) -} - -// MapObject is a type to describe object as a map. -type MapObject map[string]interface{} - -func (o MapObject) EncodeMsgpack(enc *encoder) { - enc.Encode(o) -} - -func msgpackIsArray(code byte) bool { - return code == msgpcode.Array16 || code == msgpcode.Array32 || - msgpcode.IsFixedArray(code) -} diff --git a/crud/msgpack_v5_helper_test.go b/crud/msgpack_v5_helper_test.go deleted file mode 100644 index f3700bebc..000000000 --- a/crud/msgpack_v5_helper_test.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build go_tarantool_msgpack_v5 -// +build go_tarantool_msgpack_v5 - -package crud_test - -import ( - "github.com/vmihailenco/msgpack/v5" -) - -var newEncoder = msgpack.NewEncoder diff --git a/crud/object.go b/crud/object.go new file mode 100644 index 000000000..3f266a7ee --- /dev/null +++ b/crud/object.go @@ -0,0 +1,17 @@ +package crud + +import ( + "github.com/vmihailenco/msgpack/v5" +) + +// Object is an interface to describe object for CRUD methods. +type Object interface { + EncodeMsgpack(enc *msgpack.Encoder) +} + +// MapObject is a type to describe object as a map. +type MapObject map[string]interface{} + +func (o MapObject) EncodeMsgpack(enc *msgpack.Encoder) { + enc.Encode(o) +} diff --git a/crud/options.go b/crud/options.go index 9bec34754..c073b7222 100644 --- a/crud/options.go +++ b/crud/options.go @@ -1,5 +1,9 @@ package crud +import ( + "github.com/vmihailenco/msgpack/v5" +) + const ( timeoutOptName = "timeout" vshardRouterOptName = "vshard_router" @@ -121,7 +125,7 @@ type BaseOpts struct { } // EncodeMsgpack provides custom msgpack encoder. -func (opts BaseOpts) EncodeMsgpack(enc *encoder) error { +func (opts BaseOpts) EncodeMsgpack(enc *msgpack.Encoder) error { const optsCnt = 2 names := [optsCnt]string{timeoutOptName, vshardRouterOptName} @@ -148,7 +152,7 @@ type SimpleOperationOpts struct { } // EncodeMsgpack provides custom msgpack encoder. -func (opts SimpleOperationOpts) EncodeMsgpack(enc *encoder) error { +func (opts SimpleOperationOpts) EncodeMsgpack(enc *msgpack.Encoder) error { const optsCnt = 4 names := [optsCnt]string{timeoutOptName, vshardRouterOptName, @@ -182,7 +186,7 @@ type SimpleOperationObjectOpts struct { } // EncodeMsgpack provides custom msgpack encoder. -func (opts SimpleOperationObjectOpts) EncodeMsgpack(enc *encoder) error { +func (opts SimpleOperationObjectOpts) EncodeMsgpack(enc *msgpack.Encoder) error { const optsCnt = 5 names := [optsCnt]string{timeoutOptName, vshardRouterOptName, @@ -218,7 +222,7 @@ type OperationManyOpts struct { } // EncodeMsgpack provides custom msgpack encoder. -func (opts OperationManyOpts) EncodeMsgpack(enc *encoder) error { +func (opts OperationManyOpts) EncodeMsgpack(enc *msgpack.Encoder) error { const optsCnt = 5 names := [optsCnt]string{timeoutOptName, vshardRouterOptName, @@ -258,7 +262,7 @@ type OperationObjectManyOpts struct { } // EncodeMsgpack provides custom msgpack encoder. -func (opts OperationObjectManyOpts) EncodeMsgpack(enc *encoder) error { +func (opts OperationObjectManyOpts) EncodeMsgpack(enc *msgpack.Encoder) error { const optsCnt = 6 names := [optsCnt]string{timeoutOptName, vshardRouterOptName, @@ -289,7 +293,7 @@ type BorderOpts struct { } // EncodeMsgpack provides custom msgpack encoder. -func (opts BorderOpts) EncodeMsgpack(enc *encoder) error { +func (opts BorderOpts) EncodeMsgpack(enc *msgpack.Encoder) error { const optsCnt = 3 names := [optsCnt]string{timeoutOptName, vshardRouterOptName, fieldsOptName} @@ -302,7 +306,8 @@ func (opts BorderOpts) EncodeMsgpack(enc *encoder) error { return encodeOptions(enc, names[:], values[:], exists[:]) } -func encodeOptions(enc *encoder, names []string, values []interface{}, exists []bool) error { +func encodeOptions(enc *msgpack.Encoder, + names []string, values []interface{}, exists []bool) error { mapLen := 0 for _, exist := range exists { diff --git a/crud/replace.go b/crud/replace.go index 87a60930a..8231c9aa5 100644 --- a/crud/replace.go +++ b/crud/replace.go @@ -3,6 +3,8 @@ package crud import ( "context" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" ) @@ -48,7 +50,7 @@ func (req ReplaceRequest) Opts(opts ReplaceOpts) ReplaceRequest { } // Body fills an encoder with the call request body. -func (req ReplaceRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req ReplaceRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { if req.tuple == nil { req.tuple = []interface{}{} } @@ -106,7 +108,7 @@ func (req ReplaceObjectRequest) Opts(opts ReplaceObjectOpts) ReplaceObjectReques } // Body fills an encoder with the call request body. -func (req ReplaceObjectRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req ReplaceObjectRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { if req.object == nil { req.object = MapObject{} } diff --git a/crud/replace_many.go b/crud/replace_many.go index 7216a67c2..77c947718 100644 --- a/crud/replace_many.go +++ b/crud/replace_many.go @@ -3,6 +3,8 @@ package crud import ( "context" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" ) @@ -48,7 +50,7 @@ func (req ReplaceManyRequest) Opts(opts ReplaceManyOpts) ReplaceManyRequest { } // Body fills an encoder with the call request body. -func (req ReplaceManyRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req ReplaceManyRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { if req.tuples == nil { req.tuples = []Tuple{} } @@ -106,7 +108,7 @@ func (req ReplaceObjectManyRequest) Opts(opts ReplaceObjectManyOpts) ReplaceObje } // Body fills an encoder with the call request body. -func (req ReplaceObjectManyRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req ReplaceObjectManyRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { if req.objects == nil { req.objects = []Object{} } diff --git a/crud/request_test.go b/crud/request_test.go index 3e4f171a7..5a81e0d1e 100644 --- a/crud/request_test.go +++ b/crud/request_test.go @@ -4,11 +4,13 @@ import ( "bytes" "context" "errors" + "fmt" "testing" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" "github.com/tarantool/go-tarantool/v2/crud" - "github.com/tarantool/go-tarantool/v2/test_helpers" ) const invalidSpaceMsg = "invalid space" @@ -91,15 +93,28 @@ func (*ValidSchemeResolver) ResolveSpaceIndex(s, i interface{}) (spaceNo, indexN var resolver ValidSchemeResolver +func extractRequestBody(req tarantool.Request, + resolver tarantool.SchemaResolver) ([]byte, error) { + var reqBuf bytes.Buffer + reqEnc := msgpack.NewEncoder(&reqBuf) + + err := req.Body(resolver, reqEnc) + if err != nil { + return nil, fmt.Errorf("An unexpected Response.Body() error: %q", err.Error()) + } + + return reqBuf.Bytes(), nil +} + func assertBodyEqual(t testing.TB, reference tarantool.Request, req tarantool.Request) { t.Helper() - reqBody, err := test_helpers.ExtractRequestBody(req, &resolver, newEncoder) + reqBody, err := extractRequestBody(req, &resolver) if err != nil { t.Fatalf("An unexpected Response.Body() error: %q", err.Error()) } - refBody, err := test_helpers.ExtractRequestBody(reference, &resolver, newEncoder) + refBody, err := extractRequestBody(reference, &resolver) if err != nil { t.Fatalf("An unexpected Response.Body() error: %q", err.Error()) } @@ -112,7 +127,7 @@ func assertBodyEqual(t testing.TB, reference tarantool.Request, req tarantool.Re func BenchmarkLenRequest(b *testing.B) { buf := bytes.Buffer{} buf.Grow(512 * 1024 * 1024) // Avoid allocs in test. - enc := newEncoder(&buf) + enc := msgpack.NewEncoder(&buf) b.ResetTimer() @@ -131,7 +146,7 @@ func BenchmarkLenRequest(b *testing.B) { func BenchmarkSelectRequest(b *testing.B) { buf := bytes.Buffer{} buf.Grow(512 * 1024 * 1024) // Avoid allocs in test. - enc := newEncoder(&buf) + enc := msgpack.NewEncoder(&buf) b.ResetTimer() diff --git a/crud/result.go b/crud/result.go index 5ee556a5f..100ec2a95 100644 --- a/crud/result.go +++ b/crud/result.go @@ -3,6 +3,9 @@ package crud import ( "fmt" "reflect" + + "github.com/vmihailenco/msgpack/v5" + "github.com/vmihailenco/msgpack/v5/msgpcode" ) // FieldFormat contains field definition: {name='...',type='...'[,is_nullable=...]}. @@ -13,7 +16,7 @@ type FieldFormat struct { } // DecodeMsgpack provides custom msgpack decoder. -func (format *FieldFormat) DecodeMsgpack(d *decoder) error { +func (format *FieldFormat) DecodeMsgpack(d *msgpack.Decoder) error { l, err := d.DecodeMapLen() if err != nil { return err @@ -60,8 +63,13 @@ func MakeResult(rowType reflect.Type) Result { } } +func msgpackIsArray(code byte) bool { + return code == msgpcode.Array16 || code == msgpcode.Array32 || + msgpcode.IsFixedArray(code) +} + // DecodeMsgpack provides custom msgpack decoder. -func (r *Result) DecodeMsgpack(d *decoder) error { +func (r *Result) DecodeMsgpack(d *msgpack.Decoder) error { arrLen, err := d.DecodeArrayLen() if err != nil { return err @@ -162,7 +170,7 @@ type NumberResult struct { } // DecodeMsgpack provides custom msgpack decoder. -func (r *NumberResult) DecodeMsgpack(d *decoder) error { +func (r *NumberResult) DecodeMsgpack(d *msgpack.Decoder) error { arrLen, err := d.DecodeArrayLen() if err != nil { return err @@ -201,7 +209,7 @@ type BoolResult struct { } // DecodeMsgpack provides custom msgpack decoder. -func (r *BoolResult) DecodeMsgpack(d *decoder) error { +func (r *BoolResult) DecodeMsgpack(d *msgpack.Decoder) error { arrLen, err := d.DecodeArrayLen() if err != nil { return err diff --git a/crud/select.go b/crud/select.go index cce17ccf4..bdd0e9d42 100644 --- a/crud/select.go +++ b/crud/select.go @@ -3,6 +3,8 @@ package crud import ( "context" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" ) @@ -42,7 +44,7 @@ type SelectOpts struct { } // EncodeMsgpack provides custom msgpack encoder. -func (opts SelectOpts) EncodeMsgpack(enc *encoder) error { +func (opts SelectOpts) EncodeMsgpack(enc *msgpack.Encoder) error { const optsCnt = 12 names := [optsCnt]string{timeoutOptName, vshardRouterOptName, @@ -108,7 +110,7 @@ func (req SelectRequest) Opts(opts SelectOpts) SelectRequest { } // Body fills an encoder with the call request body. -func (req SelectRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req SelectRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { args := selectArgs{Space: req.space, Conditions: req.conditions, Opts: req.opts} req.impl = req.impl.Args(args) return req.impl.Body(res, enc) diff --git a/crud/stats.go b/crud/stats.go index d29c0eb70..47737f33a 100644 --- a/crud/stats.go +++ b/crud/stats.go @@ -3,6 +3,8 @@ package crud import ( "context" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" ) @@ -28,7 +30,7 @@ func (req StatsRequest) Space(space string) StatsRequest { } // Body fills an encoder with the call request body. -func (req StatsRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req StatsRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { if value, ok := req.space.Get(); ok { req.impl = req.impl.Args([]interface{}{value}) } else { diff --git a/crud/storage_info.go b/crud/storage_info.go index 146e0a22e..e2d67aadb 100644 --- a/crud/storage_info.go +++ b/crud/storage_info.go @@ -3,6 +3,8 @@ package crud import ( "context" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" ) @@ -14,7 +16,7 @@ type StatusTable struct { } // DecodeMsgpack provides custom msgpack decoder. -func (statusTable *StatusTable) DecodeMsgpack(d *decoder) error { +func (statusTable *StatusTable) DecodeMsgpack(d *msgpack.Decoder) error { l, err := d.DecodeMapLen() if err != nil { return err @@ -54,7 +56,7 @@ type StorageInfoResult struct { } // DecodeMsgpack provides custom msgpack decoder. -func (r *StorageInfoResult) DecodeMsgpack(d *decoder) error { +func (r *StorageInfoResult) DecodeMsgpack(d *msgpack.Decoder) error { _, err := d.DecodeArrayLen() if err != nil { return err @@ -116,7 +118,7 @@ func (req StorageInfoRequest) Opts(opts StorageInfoOpts) StorageInfoRequest { } // Body fills an encoder with the call request body. -func (req StorageInfoRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req StorageInfoRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { args := storageInfoArgs{Opts: req.opts} req.impl = req.impl.Args(args) return req.impl.Body(res, enc) diff --git a/crud/truncate.go b/crud/truncate.go index 5ad1d785e..9f80063d1 100644 --- a/crud/truncate.go +++ b/crud/truncate.go @@ -3,6 +3,8 @@ package crud import ( "context" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" ) @@ -42,7 +44,7 @@ func (req TruncateRequest) Opts(opts TruncateOpts) TruncateRequest { } // Body fills an encoder with the call request body. -func (req TruncateRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req TruncateRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { args := truncateArgs{Space: req.space, Opts: req.opts} req.impl = req.impl.Args(args) return req.impl.Body(res, enc) diff --git a/crud/update.go b/crud/update.go index a2b9a5572..41ebd2c09 100644 --- a/crud/update.go +++ b/crud/update.go @@ -3,6 +3,8 @@ package crud import ( "context" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" ) @@ -58,7 +60,7 @@ func (req UpdateRequest) Opts(opts UpdateOpts) UpdateRequest { } // Body fills an encoder with the call request body. -func (req UpdateRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req UpdateRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { if req.key == nil { req.key = []interface{}{} } diff --git a/crud/upsert.go b/crud/upsert.go index 8fc9efa69..e44523d45 100644 --- a/crud/upsert.go +++ b/crud/upsert.go @@ -3,6 +3,8 @@ package crud import ( "context" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" ) @@ -58,7 +60,7 @@ func (req UpsertRequest) Opts(opts UpsertOpts) UpsertRequest { } // Body fills an encoder with the call request body. -func (req UpsertRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req UpsertRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { if req.tuple == nil { req.tuple = []interface{}{} } @@ -127,7 +129,7 @@ func (req UpsertObjectRequest) Opts(opts UpsertObjectOpts) UpsertObjectRequest { } // Body fills an encoder with the call request body. -func (req UpsertObjectRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req UpsertObjectRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { if req.object == nil { req.object = MapObject{} } diff --git a/crud/upsert_many.go b/crud/upsert_many.go index 884a574ed..c7a54ba05 100644 --- a/crud/upsert_many.go +++ b/crud/upsert_many.go @@ -3,6 +3,8 @@ package crud import ( "context" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" ) @@ -57,7 +59,7 @@ func (req UpsertManyRequest) Opts(opts UpsertManyOpts) UpsertManyRequest { } // Body fills an encoder with the call request body. -func (req UpsertManyRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req UpsertManyRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { args := upsertManyArgs{Space: req.space, TuplesOperationsData: req.tuplesOperationsData, Opts: req.opts} req.impl = req.impl.Args(args) @@ -123,7 +125,7 @@ func (req UpsertObjectManyRequest) Opts(opts UpsertObjectManyOpts) UpsertObjectM } // Body fills an encoder with the call request body. -func (req UpsertObjectManyRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req UpsertObjectManyRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { args := upsertObjectManyArgs{Space: req.space, ObjectsOperationsData: req.objectsOperationsData, Opts: req.opts} req.impl = req.impl.Args(args) diff --git a/datetime/datetime.go b/datetime/datetime.go index 105d2cca5..09e86ce46 100644 --- a/datetime/datetime.go +++ b/datetime/datetime.go @@ -13,6 +13,8 @@ import ( "encoding/binary" "fmt" "time" + + "github.com/vmihailenco/msgpack/v5" ) // Datetime MessagePack serialization schema is an MP_EXT extension, which @@ -319,3 +321,7 @@ func (tm *Datetime) UnmarshalMsgpack(b []byte) error { } return err } + +func init() { + msgpack.RegisterExt(datetime_extId, (*Datetime)(nil)) +} diff --git a/datetime/datetime_test.go b/datetime/datetime_test.go index 7c24fa922..a47126049 100644 --- a/datetime/datetime_test.go +++ b/datetime/datetime_test.go @@ -9,6 +9,8 @@ import ( "testing" "time" + "github.com/vmihailenco/msgpack/v5" + . "github.com/tarantool/go-tarantool/v2" . "github.com/tarantool/go-tarantool/v2/datetime" "github.com/tarantool/go-tarantool/v2/test_helpers" @@ -431,7 +433,7 @@ func assertDatetimeIsEqual(t *testing.T, tuples []interface{}, tm time.Time) { if len(tpl) != 2 { t.Fatalf("Unexpected return value body (tuple len = %d)", len(tpl)) } - if val, ok := toDatetime(tpl[dtIndex]); !ok || !val.ToTime().Equal(tm) { + if val, ok := tpl[dtIndex].(*Datetime); !ok || !val.ToTime().Equal(tm) { t.Fatalf("Unexpected tuple %d field %v, expected %v", dtIndex, val, @@ -546,7 +548,7 @@ func TestCustomTimezone(t *testing.T) { assertDatetimeIsEqual(t, resp.Data, tm) tpl := resp.Data[0].([]interface{}) - if respDt, ok := toDatetime(tpl[0]); ok { + if respDt, ok := tpl[0].(*Datetime); ok { zone := respDt.ToTime().Location().String() _, offset := respDt.ToTime().Zone() if zone != customZone { @@ -776,7 +778,7 @@ type Tuple1 struct { Datetime Datetime } -func (t *Tuple1) EncodeMsgpack(e *encoder) error { +func (t *Tuple1) EncodeMsgpack(e *msgpack.Encoder) error { if err := e.EncodeArrayLen(2); err != nil { return err } @@ -786,7 +788,7 @@ func (t *Tuple1) EncodeMsgpack(e *encoder) error { return nil } -func (t *Tuple1) DecodeMsgpack(d *decoder) error { +func (t *Tuple1) DecodeMsgpack(d *msgpack.Decoder) error { var err error var l int if l, err = d.DecodeArrayLen(); err != nil { @@ -802,7 +804,7 @@ func (t *Tuple1) DecodeMsgpack(d *decoder) error { return nil } -func (ev *Event) EncodeMsgpack(e *encoder) error { +func (ev *Event) EncodeMsgpack(e *msgpack.Encoder) error { if err := e.EncodeArrayLen(2); err != nil { return err } @@ -815,7 +817,7 @@ func (ev *Event) EncodeMsgpack(e *encoder) error { return nil } -func (ev *Event) DecodeMsgpack(d *decoder) error { +func (ev *Event) DecodeMsgpack(d *msgpack.Decoder) error { var err error var l int if l, err = d.DecodeArrayLen(); err != nil { @@ -831,14 +833,16 @@ func (ev *Event) DecodeMsgpack(d *decoder) error { if err != nil { return err } - var ok bool - if ev.Datetime, ok = toDatetime(res); !ok { + + if dt, ok := res.(*Datetime); !ok { return fmt.Errorf("Datetime doesn't match") + } else { + ev.Datetime = *dt } return nil } -func (c *Tuple2) EncodeMsgpack(e *encoder) error { +func (c *Tuple2) EncodeMsgpack(e *msgpack.Encoder) error { if err := e.EncodeArrayLen(3); err != nil { return err } @@ -852,7 +856,7 @@ func (c *Tuple2) EncodeMsgpack(e *encoder) error { return nil } -func (c *Tuple2) DecodeMsgpack(d *decoder) error { +func (c *Tuple2) DecodeMsgpack(d *msgpack.Decoder) error { var err error var l int if l, err = d.DecodeArrayLen(); err != nil { @@ -938,7 +942,7 @@ func TestCustomEncodeDecodeTuple1(t *testing.T) { } for i, tv := range []time.Time{tm1, tm2} { - dt, ok := toDatetime(events[i].([]interface{})[1]) + dt, ok := events[i].([]interface{})[1].(*Datetime) if !ok || !dt.ToTime().Equal(tv) { t.Fatalf("%v != %v", dt.ToTime(), tv) } @@ -1011,7 +1015,7 @@ func TestCustomEncodeDecodeTuple5(t *testing.T) { if tpl, ok := resp.Data[0].([]interface{}); !ok { t.Errorf("Unexpected body of Select") } else { - if val, ok := toDatetime(tpl[0]); !ok || !val.ToTime().Equal(tm) { + if val, ok := tpl[0].(*Datetime); !ok || !val.ToTime().Equal(tm) { t.Fatalf("Unexpected body of Select") } } @@ -1043,7 +1047,7 @@ func TestMPEncode(t *testing.T) { if err != nil { t.Fatalf("Unable to create Datetime from %s: %s", tm, err) } - buf, err := marshal(dt) + buf, err := msgpack.Marshal(dt) if err != nil { t.Fatalf("Marshalling failed: %s", err.Error()) } @@ -1076,7 +1080,7 @@ func TestMPDecode(t *testing.T) { } buf, _ := hex.DecodeString(testcase.mpBuf) var v Datetime - err = unmarshal(buf, &v) + err = msgpack.Unmarshal(buf, &v) if err != nil { t.Fatalf("Unmarshalling failed: %s", err.Error()) } diff --git a/datetime/interval.go b/datetime/interval.go index eee6b2d97..ef378e405 100644 --- a/datetime/interval.go +++ b/datetime/interval.go @@ -1,8 +1,11 @@ package datetime import ( + "bytes" "fmt" "reflect" + + "github.com/vmihailenco/msgpack/v5" ) const interval_extId = 6 @@ -63,22 +66,22 @@ func (ival Interval) Sub(sub Interval) Interval { return ival } -func encodeIntervalValue(e *encoder, typ uint64, value int64) (err error) { +func encodeIntervalValue(e *msgpack.Encoder, typ uint64, value int64) (err error) { if value == 0 { return } - err = encodeUint(e, typ) + err = e.EncodeUint(typ) if err == nil { if value > 0 { - err = encodeUint(e, uint64(value)) + err = e.EncodeUint(uint64(value)) } else if value < 0 { - err = encodeInt(e, int64(value)) + err = e.EncodeInt(int64(value)) } } return } -func encodeInterval(e *encoder, v reflect.Value) (err error) { +func encodeInterval(e *msgpack.Encoder, v reflect.Value) (err error) { val := v.Interface().(Interval) var fieldNum uint64 @@ -89,7 +92,7 @@ func encodeInterval(e *encoder, v reflect.Value) (err error) { fieldNum++ } } - if err = encodeUint(e, fieldNum); err != nil { + if err = e.EncodeUint(fieldNum); err != nil { return } @@ -123,7 +126,7 @@ func encodeInterval(e *encoder, v reflect.Value) (err error) { return nil } -func decodeInterval(d *decoder, v reflect.Value) (err error) { +func decodeInterval(d *msgpack.Decoder, v reflect.Value) (err error) { var fieldNum uint if fieldNum, err = d.DecodeUint(); err != nil { return @@ -177,3 +180,21 @@ func decodeInterval(d *decoder, v reflect.Value) (err error) { v.Set(reflect.ValueOf(val)) return nil } + +func init() { + msgpack.RegisterExtEncoder(interval_extId, Interval{}, + func(e *msgpack.Encoder, v reflect.Value) (ret []byte, err error) { + var b bytes.Buffer + + enc := msgpack.NewEncoder(&b) + if err = encodeInterval(enc, v); err == nil { + ret = b.Bytes() + } + + return + }) + msgpack.RegisterExtDecoder(interval_extId, Interval{}, + func(d *msgpack.Decoder, v reflect.Value, extLen int) error { + return decodeInterval(d, v) + }) +} diff --git a/datetime/msgpack.go b/datetime/msgpack.go deleted file mode 100644 index b5bc0d7c5..000000000 --- a/datetime/msgpack.go +++ /dev/null @@ -1,28 +0,0 @@ -//go:build !go_tarantool_msgpack_v5 -// +build !go_tarantool_msgpack_v5 - -package datetime - -import ( - "reflect" - - "gopkg.in/vmihailenco/msgpack.v2" -) - -type encoder = msgpack.Encoder -type decoder = msgpack.Decoder - -func encodeUint(e *encoder, v uint64) error { - return e.EncodeUint(uint(v)) -} - -func encodeInt(e *encoder, v int64) error { - return e.EncodeInt(int(v)) -} - -func init() { - msgpack.RegisterExt(datetime_extId, &Datetime{}) - - msgpack.Register(reflect.TypeOf((*Interval)(nil)).Elem(), encodeInterval, decodeInterval) - msgpack.RegisterExt(interval_extId, (*Interval)(nil)) -} diff --git a/datetime/msgpack_helper_test.go b/datetime/msgpack_helper_test.go deleted file mode 100644 index 12be0bce4..000000000 --- a/datetime/msgpack_helper_test.go +++ /dev/null @@ -1,26 +0,0 @@ -//go:build !go_tarantool_msgpack_v5 -// +build !go_tarantool_msgpack_v5 - -package datetime_test - -import ( - . "github.com/tarantool/go-tarantool/v2/datetime" - - "gopkg.in/vmihailenco/msgpack.v2" -) - -type encoder = msgpack.Encoder -type decoder = msgpack.Decoder - -func toDatetime(i interface{}) (dt Datetime, ok bool) { - dt, ok = i.(Datetime) - return -} - -func marshal(v interface{}) ([]byte, error) { - return msgpack.Marshal(v) -} - -func unmarshal(data []byte, v interface{}) error { - return msgpack.Unmarshal(data, v) -} diff --git a/datetime/msgpack_v5.go b/datetime/msgpack_v5.go deleted file mode 100644 index 69285576e..000000000 --- a/datetime/msgpack_v5.go +++ /dev/null @@ -1,42 +0,0 @@ -//go:build go_tarantool_msgpack_v5 -// +build go_tarantool_msgpack_v5 - -package datetime - -import ( - "bytes" - "reflect" - - "github.com/vmihailenco/msgpack/v5" -) - -type encoder = msgpack.Encoder -type decoder = msgpack.Decoder - -func encodeUint(e *encoder, v uint64) error { - return e.EncodeUint(v) -} - -func encodeInt(e *encoder, v int64) error { - return e.EncodeInt(v) -} - -func init() { - msgpack.RegisterExt(datetime_extId, (*Datetime)(nil)) - - msgpack.RegisterExtEncoder(interval_extId, Interval{}, - func(e *msgpack.Encoder, v reflect.Value) (ret []byte, err error) { - var b bytes.Buffer - - enc := msgpack.NewEncoder(&b) - if err = encodeInterval(enc, v); err == nil { - ret = b.Bytes() - } - - return - }) - msgpack.RegisterExtDecoder(interval_extId, Interval{}, - func(d *msgpack.Decoder, v reflect.Value, extLen int) error { - return decodeInterval(d, v) - }) -} diff --git a/datetime/msgpack_v5_helper_test.go b/datetime/msgpack_v5_helper_test.go deleted file mode 100644 index 3ee42f0bd..000000000 --- a/datetime/msgpack_v5_helper_test.go +++ /dev/null @@ -1,28 +0,0 @@ -//go:build go_tarantool_msgpack_v5 -// +build go_tarantool_msgpack_v5 - -package datetime_test - -import ( - . "github.com/tarantool/go-tarantool/v2/datetime" - "github.com/vmihailenco/msgpack/v5" -) - -type encoder = msgpack.Encoder -type decoder = msgpack.Decoder - -func toDatetime(i interface{}) (dt Datetime, ok bool) { - var ptr *Datetime - if ptr, ok = i.(*Datetime); ok { - dt = *ptr - } - return -} - -func marshal(v interface{}) ([]byte, error) { - return msgpack.Marshal(v) -} - -func unmarshal(data []byte, v interface{}) error { - return msgpack.Unmarshal(data, v) -} diff --git a/decimal/decimal.go b/decimal/decimal.go index cda08c12e..6cca53404 100644 --- a/decimal/decimal.go +++ b/decimal/decimal.go @@ -19,6 +19,7 @@ import ( "fmt" "github.com/shopspring/decimal" + "github.com/vmihailenco/msgpack/v5" ) // Decimal numbers have 38 digits of precision, that is, the total @@ -98,3 +99,7 @@ func (decNum *Decimal) UnmarshalMsgpack(b []byte) error { return nil } + +func init() { + msgpack.RegisterExt(decimalExtID, (*Decimal)(nil)) +} diff --git a/decimal/decimal_test.go b/decimal/decimal_test.go index c1b8b60f7..372a06fce 100644 --- a/decimal/decimal_test.go +++ b/decimal/decimal_test.go @@ -10,6 +10,8 @@ import ( "time" "github.com/shopspring/decimal" + "github.com/vmihailenco/msgpack/v5" + . "github.com/tarantool/go-tarantool/v2" . "github.com/tarantool/go-tarantool/v2/decimal" "github.com/tarantool/go-tarantool/v2/test_helpers" @@ -39,14 +41,14 @@ type TupleDecimal struct { number Decimal } -func (t *TupleDecimal) EncodeMsgpack(e *encoder) error { +func (t *TupleDecimal) EncodeMsgpack(e *msgpack.Encoder) error { if err := e.EncodeArrayLen(1); err != nil { return err } return e.EncodeValue(reflect.ValueOf(&t.number)) } -func (t *TupleDecimal) DecodeMsgpack(d *decoder) error { +func (t *TupleDecimal) DecodeMsgpack(d *msgpack.Decoder) error { var err error var l int if l, err = d.DecodeArrayLen(); err != nil { @@ -60,9 +62,11 @@ func (t *TupleDecimal) DecodeMsgpack(d *decoder) error { if err != nil { return err } - var ok bool - if t.number, ok = toDecimal(res); !ok { + + if dec, ok := res.(*Decimal); !ok { return fmt.Errorf("decimal doesn't match") + } else { + t.number = *dec } return nil } @@ -145,11 +149,11 @@ func TestMPEncodeDecode(t *testing.T) { } var buf []byte tuple := TupleDecimal{number: *decNum} - if buf, err = marshal(&tuple); err != nil { - t.Fatalf("Failed to encode decimal number '%s' to a MessagePack buffer: %s", testcase.numString, err) + if buf, err = msgpack.Marshal(&tuple); err != nil { + t.Fatalf("Failed to msgpack.Encoder decimal number '%s' to a MessagePack buffer: %s", testcase.numString, err) } var v TupleDecimal - if err = unmarshal(buf, &v); err != nil { + if err = msgpack.Unmarshal(buf, &v); err != nil { t.Fatalf("Failed to decode MessagePack buffer '%x' to a decimal number: %s", buf, err) } if !decNum.Equal(v.number.Decimal) { @@ -248,12 +252,12 @@ func TestEncodeMaxNumber(t *testing.T) { referenceErrMsg := "msgpack: decimal number is bigger than maximum supported number (10^38 - 1)" decNum := decimal.New(1, DecimalPrecision) // // 10^DecimalPrecision tuple := TupleDecimal{number: *NewDecimal(decNum)} - _, err := marshal(&tuple) + _, err := msgpack.Marshal(&tuple) if err == nil { - t.Fatalf("It is possible to encode a number unsupported by Tarantool") + t.Fatalf("It is possible to msgpack.Encoder a number unsupported by Tarantool") } if err.Error() != referenceErrMsg { - t.Fatalf("Incorrect error message on attempt to encode number unsupported by Tarantool") + t.Fatalf("Incorrect error message on attempt to msgpack.Encoder number unsupported by Tarantool") } } @@ -262,14 +266,14 @@ func TestEncodeMinNumber(t *testing.T) { two := decimal.NewFromInt(2) decNum := decimal.New(1, DecimalPrecision).Neg().Sub(two) // -10^DecimalPrecision - 2 tuple := TupleDecimal{number: *NewDecimal(decNum)} - _, err := marshal(&tuple) + _, err := msgpack.Marshal(&tuple) if err == nil { - t.Fatalf("It is possible to encode a number unsupported by Tarantool") + t.Fatalf("It is possible to msgpack.Encoder a number unsupported by Tarantool") } if err.Error() != referenceErrMsg { fmt.Println("Actual message: ", err.Error()) fmt.Println("Expected message: ", referenceErrMsg) - t.Fatalf("Incorrect error message on attempt to encode number unsupported by Tarantool") + t.Fatalf("Incorrect error message on attempt to msgpack.Encoder number unsupported by Tarantool") } } @@ -281,10 +285,10 @@ func benchmarkMPEncodeDecode(b *testing.B, src decimal.Decimal, dst interface{}) var err error for i := 0; i < b.N; i++ { tuple := TupleDecimal{number: *NewDecimal(src)} - if buf, err = marshal(&tuple); err != nil { + if buf, err = msgpack.Marshal(&tuple); err != nil { b.Fatal(err) } - if err = unmarshal(buf, &v); err != nil { + if err = msgpack.Unmarshal(buf, &v); err != nil { b.Fatal(err) } } @@ -311,7 +315,7 @@ func BenchmarkMPEncodeDecimal(b *testing.B) { } b.ResetTimer() for i := 0; i < b.N; i++ { - marshal(decNum) + msgpack.Marshal(decNum) } }) } @@ -325,13 +329,13 @@ func BenchmarkMPDecodeDecimal(b *testing.B) { b.Fatal(err) } var buf []byte - if buf, err = marshal(decNum); err != nil { + if buf, err = msgpack.Marshal(decNum); err != nil { b.Fatal(err) } b.ResetTimer() var v TupleDecimal for i := 0; i < b.N; i++ { - unmarshal(buf, &v) + msgpack.Unmarshal(buf, &v) } }) @@ -349,7 +353,7 @@ func tupleValueIsDecimal(t *testing.T, tuples []interface{}, number decimal.Deci if len(tpl) != 1 { t.Fatalf("Unexpected return value body (tuple len)") } - if val, ok := toDecimal(tpl[0]); !ok || !val.Equal(number) { + if val, ok := tpl[0].(*Decimal); !ok || !val.Equal(number) { t.Fatalf("Unexpected return value body (tuple 0 field)") } } @@ -370,13 +374,13 @@ func TestEncodeStringToBCD(t *testing.T) { t.Run(testcase.numString, func(t *testing.T) { buf, err := EncodeStringToBCD(testcase.numString) if err != nil { - t.Fatalf("Failed to encode decimal '%s' to BCD: %s", testcase.numString, err) + t.Fatalf("Failed to msgpack.Encoder decimal '%s' to BCD: %s", testcase.numString, err) } b, _ := hex.DecodeString(testcase.mpBuf) bcdBuf := trimMPHeader(b, testcase.fixExt) if reflect.DeepEqual(buf, bcdBuf) != true { - t.Fatalf("Failed to encode decimal '%s' to BCD: expected '%x', actual '%x'", testcase.numString, bcdBuf, buf) + t.Fatalf("Failed to msgpack.Encoder decimal '%s' to BCD: expected '%x', actual '%x'", testcase.numString, bcdBuf, buf) } }) } @@ -396,11 +400,11 @@ func TestDecodeStringFromBCD(t *testing.T) { decActual, err := decimal.NewFromString(s) if err != nil { - t.Fatalf("Failed to encode string ('%s') to decimal", s) + t.Fatalf("Failed to msgpack.Encoder string ('%s') to decimal", s) } decExpected, err := decimal.NewFromString(testcase.numString) if err != nil { - t.Fatalf("Failed to encode string ('%s') to decimal", testcase.numString) + t.Fatalf("Failed to msgpack.Encoder string ('%s') to decimal", testcase.numString) } if !decExpected.Equal(decActual) { t.Fatalf("Decoded decimal from BCD ('%x') is incorrect: expected '%s', actual '%s'", bcdBuf, testcase.numString, s) @@ -418,13 +422,13 @@ func TestMPEncode(t *testing.T) { if err != nil { t.Fatalf("NewDecimalFromString() failed: %s", err.Error()) } - buf, err := marshal(dec) + buf, err := msgpack.Marshal(dec) if err != nil { t.Fatalf("Marshalling failed: %s", err.Error()) } refBuf, _ := hex.DecodeString(testcase.mpBuf) if reflect.DeepEqual(buf, refBuf) != true { - t.Fatalf("Failed to encode decimal '%s', actual %x, expected %x", + t.Fatalf("Failed to msgpack.Encoder decimal '%s', actual %x, expected %x", testcase.numString, buf, refBuf) @@ -443,11 +447,11 @@ func TestMPDecode(t *testing.T) { t.Fatalf("hex.DecodeString() failed: %s", err) } var v interface{} - err = unmarshal(mpBuf, &v) + err = msgpack.Unmarshal(mpBuf, &v) if err != nil { - t.Fatalf("Unmarshalling failed: %s", err.Error()) + t.Fatalf("Unmsgpack.Marshalling failed: %s", err.Error()) } - decActual, ok := toDecimal(v) + decActual, ok := v.(*Decimal) if !ok { t.Fatalf("Unable to convert to Decimal") } diff --git a/decimal/msgpack.go b/decimal/msgpack.go deleted file mode 100644 index 5a455ae59..000000000 --- a/decimal/msgpack.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build !go_tarantool_msgpack_v5 -// +build !go_tarantool_msgpack_v5 - -package decimal - -import ( - "gopkg.in/vmihailenco/msgpack.v2" -) - -func init() { - msgpack.RegisterExt(decimalExtID, &Decimal{}) -} diff --git a/decimal/msgpack_helper_test.go b/decimal/msgpack_helper_test.go deleted file mode 100644 index b58ea9731..000000000 --- a/decimal/msgpack_helper_test.go +++ /dev/null @@ -1,26 +0,0 @@ -//go:build !go_tarantool_msgpack_v5 -// +build !go_tarantool_msgpack_v5 - -package decimal_test - -import ( - . "github.com/tarantool/go-tarantool/v2/decimal" - - "gopkg.in/vmihailenco/msgpack.v2" -) - -type encoder = msgpack.Encoder -type decoder = msgpack.Decoder - -func toDecimal(i interface{}) (dec Decimal, ok bool) { - dec, ok = i.(Decimal) - return -} - -func marshal(v interface{}) ([]byte, error) { - return msgpack.Marshal(v) -} - -func unmarshal(data []byte, v interface{}) error { - return msgpack.Unmarshal(data, v) -} diff --git a/decimal/msgpack_v5.go b/decimal/msgpack_v5.go deleted file mode 100644 index 59fa713d0..000000000 --- a/decimal/msgpack_v5.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build go_tarantool_msgpack_v5 -// +build go_tarantool_msgpack_v5 - -package decimal - -import ( - "github.com/vmihailenco/msgpack/v5" -) - -func init() { - msgpack.RegisterExt(decimalExtID, (*Decimal)(nil)) -} diff --git a/decimal/msgpack_v5_helper_test.go b/decimal/msgpack_v5_helper_test.go deleted file mode 100644 index e253bb0bc..000000000 --- a/decimal/msgpack_v5_helper_test.go +++ /dev/null @@ -1,28 +0,0 @@ -//go:build go_tarantool_msgpack_v5 -// +build go_tarantool_msgpack_v5 - -package decimal_test - -import ( - . "github.com/tarantool/go-tarantool/v2/decimal" - "github.com/vmihailenco/msgpack/v5" -) - -type encoder = msgpack.Encoder -type decoder = msgpack.Decoder - -func toDecimal(i interface{}) (dec Decimal, ok bool) { - var ptr *Decimal - if ptr, ok = i.(*Decimal); ok { - dec = *ptr - } - return -} - -func marshal(v interface{}) ([]byte, error) { - return msgpack.Marshal(v) -} - -func unmarshal(data []byte, v interface{}) error { - return msgpack.Unmarshal(data, v) -} diff --git a/dial.go b/dial.go index abed85e1b..3baf25986 100644 --- a/dial.go +++ b/dial.go @@ -9,6 +9,8 @@ import ( "net" "strings" "time" + + "github.com/vmihailenco/msgpack/v5" ) const ( @@ -350,7 +352,7 @@ func authenticate(c Conn, opts DialOpts, salt string) error { // writeRequest writes a request to the writer. func writeRequest(w writeFlusher, req Request) error { var packet smallWBuf - err := pack(&packet, newEncoder(&packet), 0, req, ignoreStreamId, nil) + err := pack(&packet, msgpack.NewEncoder(&packet), 0, req, ignoreStreamId, nil) if err != nil { return fmt.Errorf("pack error: %w", err) @@ -374,7 +376,7 @@ func readResponse(r io.Reader) (Response, error) { } resp := Response{buf: smallBuf{b: respBytes}} - err = resp.decodeHeader(newDecoder(&smallBuf{})) + err = resp.decodeHeader(msgpack.NewDecoder(&smallBuf{})) if err != nil { return resp, fmt.Errorf("decode response header error: %w", err) } diff --git a/example_custom_unpacking_test.go b/example_custom_unpacking_test.go index 6fe8eff83..5bac7ae62 100644 --- a/example_custom_unpacking_test.go +++ b/example_custom_unpacking_test.go @@ -5,6 +5,8 @@ import ( "log" "time" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" ) @@ -23,11 +25,11 @@ type Tuple3 struct { Members []Member } -func (c *Tuple2) EncodeMsgpack(e *encoder) error { +func (c *Tuple2) EncodeMsgpack(e *msgpack.Encoder) error { if err := e.EncodeArrayLen(3); err != nil { return err } - if err := encodeUint(e, uint64(c.Cid)); err != nil { + if err := e.EncodeUint(uint64(c.Cid)); err != nil { return err } if err := e.EncodeString(c.Orig); err != nil { @@ -37,7 +39,7 @@ func (c *Tuple2) EncodeMsgpack(e *encoder) error { return nil } -func (c *Tuple2) DecodeMsgpack(d *decoder) error { +func (c *Tuple2) DecodeMsgpack(d *msgpack.Decoder) error { var err error var l int if l, err = d.DecodeArrayLen(); err != nil { diff --git a/export_test.go b/export_test.go index 71886bb20..879d345ac 100644 --- a/export_test.go +++ b/export_test.go @@ -1,9 +1,10 @@ package tarantool import ( - "io" "net" "time" + + "github.com/vmihailenco/msgpack/v5" ) func SslDialTimeout(network, address string, timeout time.Duration, @@ -17,107 +18,103 @@ func SslCreateContext(opts SslOpts) (ctx interface{}, err error) { // RefImplPingBody is reference implementation for filling of a ping // request's body. -func RefImplPingBody(enc *encoder) error { +func RefImplPingBody(enc *msgpack.Encoder) error { return fillPing(enc) } // RefImplSelectBody is reference implementation for filling of a select // request's body. -func RefImplSelectBody(enc *encoder, space, index, offset, limit, iterator uint32, +func RefImplSelectBody(enc *msgpack.Encoder, space, index, offset, limit, iterator uint32, key, after interface{}, fetchPos bool) error { return fillSelect(enc, space, index, offset, limit, iterator, key, after, fetchPos) } // RefImplInsertBody is reference implementation for filling of an insert // request's body. -func RefImplInsertBody(enc *encoder, space uint32, tuple interface{}) error { +func RefImplInsertBody(enc *msgpack.Encoder, space uint32, tuple interface{}) error { return fillInsert(enc, space, tuple) } // RefImplReplaceBody is reference implementation for filling of a replace // request's body. -func RefImplReplaceBody(enc *encoder, space uint32, tuple interface{}) error { +func RefImplReplaceBody(enc *msgpack.Encoder, space uint32, tuple interface{}) error { return fillInsert(enc, space, tuple) } // RefImplDeleteBody is reference implementation for filling of a delete // request's body. -func RefImplDeleteBody(enc *encoder, space, index uint32, key interface{}) error { +func RefImplDeleteBody(enc *msgpack.Encoder, space, index uint32, key interface{}) error { return fillDelete(enc, space, index, key) } // RefImplUpdateBody is reference implementation for filling of an update // request's body. -func RefImplUpdateBody(enc *encoder, space, index uint32, key, ops interface{}) error { +func RefImplUpdateBody(enc *msgpack.Encoder, space, index uint32, key, ops interface{}) error { return fillUpdate(enc, space, index, key, ops) } // RefImplUpsertBody is reference implementation for filling of an upsert // request's body. -func RefImplUpsertBody(enc *encoder, space uint32, tuple, ops interface{}) error { +func RefImplUpsertBody(enc *msgpack.Encoder, space uint32, tuple, ops interface{}) error { return fillUpsert(enc, space, tuple, ops) } // RefImplCallBody is reference implementation for filling of a call or call17 // request's body. -func RefImplCallBody(enc *encoder, function string, args interface{}) error { +func RefImplCallBody(enc *msgpack.Encoder, function string, args interface{}) error { return fillCall(enc, function, args) } // RefImplEvalBody is reference implementation for filling of an eval // request's body. -func RefImplEvalBody(enc *encoder, expr string, args interface{}) error { +func RefImplEvalBody(enc *msgpack.Encoder, expr string, args interface{}) error { return fillEval(enc, expr, args) } // RefImplExecuteBody is reference implementation for filling of an execute // request's body. -func RefImplExecuteBody(enc *encoder, expr string, args interface{}) error { +func RefImplExecuteBody(enc *msgpack.Encoder, expr string, args interface{}) error { return fillExecute(enc, expr, args) } // RefImplPrepareBody is reference implementation for filling of an prepare // request's body. -func RefImplPrepareBody(enc *encoder, expr string) error { +func RefImplPrepareBody(enc *msgpack.Encoder, expr string) error { return fillPrepare(enc, expr) } // RefImplUnprepareBody is reference implementation for filling of an execute prepared // request's body. -func RefImplExecutePreparedBody(enc *encoder, stmt Prepared, args interface{}) error { +func RefImplExecutePreparedBody(enc *msgpack.Encoder, stmt Prepared, args interface{}) error { return fillExecutePrepared(enc, stmt, args) } // RefImplUnprepareBody is reference implementation for filling of an unprepare // request's body. -func RefImplUnprepareBody(enc *encoder, stmt Prepared) error { +func RefImplUnprepareBody(enc *msgpack.Encoder, stmt Prepared) error { return fillUnprepare(enc, stmt) } // RefImplBeginBody is reference implementation for filling of an begin // request's body. -func RefImplBeginBody(enc *encoder, txnIsolation TxnIsolationLevel, timeout time.Duration) error { +func RefImplBeginBody(enc *msgpack.Encoder, txnIsolation TxnIsolationLevel, timeout time.Duration) error { return fillBegin(enc, txnIsolation, timeout) } // RefImplCommitBody is reference implementation for filling of an commit // request's body. -func RefImplCommitBody(enc *encoder) error { +func RefImplCommitBody(enc *msgpack.Encoder) error { return fillCommit(enc) } // RefImplRollbackBody is reference implementation for filling of an rollback // request's body. -func RefImplRollbackBody(enc *encoder) error { +func RefImplRollbackBody(enc *msgpack.Encoder) error { return fillRollback(enc) } // RefImplIdBody is reference implementation for filling of an id // request's body. -func RefImplIdBody(enc *encoder, protocolInfo ProtocolInfo) error { +func RefImplIdBody(enc *msgpack.Encoder, protocolInfo ProtocolInfo) error { return fillId(enc, protocolInfo) } - -func NewEncoder(w io.Writer) *encoder { - return newEncoder(w) -} diff --git a/go.mod b/go.mod index e93a083e5..9e179e327 100644 --- a/go.mod +++ b/go.mod @@ -9,9 +9,6 @@ require ( github.com/stretchr/testify v1.7.1 github.com/tarantool/go-openssl v0.0.8-0.20230307065445-720eeb389195 github.com/vmihailenco/msgpack/v5 v5.3.5 - golang.org/x/net v0.0.0-20201021035429-f5854403a974 // indirect golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4 // indirect - google.golang.org/appengine v1.6.7 // indirect gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect - gopkg.in/vmihailenco/msgpack.v2 v2.9.2 ) diff --git a/go.sum b/go.sum index 733f1f96e..95fc38125 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,5 @@ github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg= -github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= @@ -27,28 +25,11 @@ github.com/vmihailenco/msgpack/v5 v5.3.5 h1:5gO0H1iULLWGhs2H5tbAHIZTV8/cYafcFOr9 github.com/vmihailenco/msgpack/v5 v5.3.5/go.mod h1:7xyJ9e+0+9SaZT0Wt1RGleJXzli6Q/V5KbhBonMG9jc= github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= -golang.org/x/net v0.0.0-20201021035429-f5854403a974 h1:IX6qOQeG5uLjB/hjjwjedwfjND0hgjPMMyO1RoIXQNI= -golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4 h1:myAQVi0cGEoqQVR5POX+8RR2mrocKqNN1hmeMqhX27k= golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= -google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/vmihailenco/msgpack.v2 v2.9.2 h1:gjPqo9orRVlSAH/065qw3MsFCDpH7fa1KpiizXyllY4= -gopkg.in/vmihailenco/msgpack.v2 v2.9.2/go.mod h1:/3Dn1Npt9+MYyLpYYXjInO/5jvMLamn+AEGwNEOatn8= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/msgpack.go b/msgpack.go deleted file mode 100644 index 9977e9399..000000000 --- a/msgpack.go +++ /dev/null @@ -1,54 +0,0 @@ -//go:build !go_tarantool_msgpack_v5 -// +build !go_tarantool_msgpack_v5 - -package tarantool - -import ( - "io" - - "gopkg.in/vmihailenco/msgpack.v2" - msgpcode "gopkg.in/vmihailenco/msgpack.v2/codes" -) - -type encoder = msgpack.Encoder -type decoder = msgpack.Decoder - -func newEncoder(w io.Writer) *encoder { - return msgpack.NewEncoder(w) -} - -func newDecoder(r io.Reader) *decoder { - return msgpack.NewDecoder(r) -} - -func encodeUint(e *encoder, v uint64) error { - return e.EncodeUint(uint(v)) -} - -func encodeInt(e *encoder, v int64) error { - return e.EncodeInt(int(v)) -} - -func msgpackIsUint(code byte) bool { - return code == msgpcode.Uint8 || code == msgpcode.Uint16 || - code == msgpcode.Uint32 || code == msgpcode.Uint64 || - msgpcode.IsFixedNum(code) -} - -func msgpackIsMap(code byte) bool { - return code == msgpcode.Map16 || code == msgpcode.Map32 || msgpcode.IsFixedMap(code) -} - -func msgpackIsArray(code byte) bool { - return code == msgpcode.Array16 || code == msgpcode.Array32 || - msgpcode.IsFixedArray(code) -} - -func msgpackIsString(code byte) bool { - return msgpcode.IsFixedString(code) || code == msgpcode.Str8 || - code == msgpcode.Str16 || code == msgpcode.Str32 -} - -func init() { - msgpack.RegisterExt(errorExtID, &BoxError{}) -} diff --git a/msgpack_helper_test.go b/msgpack_helper_test.go deleted file mode 100644 index 5b618bdd1..000000000 --- a/msgpack_helper_test.go +++ /dev/null @@ -1,29 +0,0 @@ -//go:build !go_tarantool_msgpack_v5 -// +build !go_tarantool_msgpack_v5 - -package tarantool_test - -import ( - "github.com/tarantool/go-tarantool/v2" - "gopkg.in/vmihailenco/msgpack.v2" -) - -type encoder = msgpack.Encoder -type decoder = msgpack.Decoder - -func encodeUint(e *encoder, v uint64) error { - return e.EncodeUint(uint(v)) -} - -func toBoxError(i interface{}) (v tarantool.BoxError, ok bool) { - v, ok = i.(tarantool.BoxError) - return -} - -func marshal(v interface{}) ([]byte, error) { - return msgpack.Marshal(v) -} - -func unmarshal(data []byte, v interface{}) error { - return msgpack.Unmarshal(data, v) -} diff --git a/msgpack_v5.go b/msgpack_v5.go deleted file mode 100644 index e8cd9aa29..000000000 --- a/msgpack_v5.go +++ /dev/null @@ -1,58 +0,0 @@ -//go:build go_tarantool_msgpack_v5 -// +build go_tarantool_msgpack_v5 - -package tarantool - -import ( - "io" - - "github.com/vmihailenco/msgpack/v5" - "github.com/vmihailenco/msgpack/v5/msgpcode" -) - -type encoder = msgpack.Encoder -type decoder = msgpack.Decoder - -func newEncoder(w io.Writer) *encoder { - return msgpack.NewEncoder(w) -} - -func newDecoder(r io.Reader) *decoder { - dec := msgpack.NewDecoder(r) - dec.SetMapDecoder(func(dec *msgpack.Decoder) (interface{}, error) { - return dec.DecodeUntypedMap() - }) - return dec -} - -func encodeUint(e *encoder, v uint64) error { - return e.EncodeUint(v) -} - -func encodeInt(e *encoder, v int64) error { - return e.EncodeInt(v) -} - -func msgpackIsUint(code byte) bool { - return code == msgpcode.Uint8 || code == msgpcode.Uint16 || - code == msgpcode.Uint32 || code == msgpcode.Uint64 || - msgpcode.IsFixedNum(code) -} - -func msgpackIsMap(code byte) bool { - return code == msgpcode.Map16 || code == msgpcode.Map32 || msgpcode.IsFixedMap(code) -} - -func msgpackIsArray(code byte) bool { - return code == msgpcode.Array16 || code == msgpcode.Array32 || - msgpcode.IsFixedArray(code) -} - -func msgpackIsString(code byte) bool { - return msgpcode.IsFixedString(code) || code == msgpcode.Str8 || - code == msgpcode.Str16 || code == msgpcode.Str32 -} - -func init() { - msgpack.RegisterExt(errorExtID, (*BoxError)(nil)) -} diff --git a/msgpack_v5_helper_test.go b/msgpack_v5_helper_test.go deleted file mode 100644 index ba1d72908..000000000 --- a/msgpack_v5_helper_test.go +++ /dev/null @@ -1,32 +0,0 @@ -//go:build go_tarantool_msgpack_v5 -// +build go_tarantool_msgpack_v5 - -package tarantool_test - -import ( - "github.com/tarantool/go-tarantool/v2" - "github.com/vmihailenco/msgpack/v5" -) - -type encoder = msgpack.Encoder -type decoder = msgpack.Decoder - -func encodeUint(e *encoder, v uint64) error { - return e.EncodeUint(v) -} - -func toBoxError(i interface{}) (v tarantool.BoxError, ok bool) { - var ptr *tarantool.BoxError - if ptr, ok = i.(*tarantool.BoxError); ok { - v = *ptr - } - return -} - -func marshal(v interface{}) ([]byte, error) { - return msgpack.Marshal(v) -} - -func unmarshal(data []byte, v interface{}) error { - return msgpack.Unmarshal(data, v) -} diff --git a/pool/connection_pool_test.go b/pool/connection_pool_test.go index f96afd2f3..645644081 100644 --- a/pool/connection_pool_test.go +++ b/pool/connection_pool_test.go @@ -13,6 +13,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" "github.com/tarantool/go-tarantool/v2/pool" "github.com/tarantool/go-tarantool/v2/test_helpers" @@ -1049,7 +1051,7 @@ type Member struct { val string } -func (m *Member) DecodeMsgpack(d *decoder) error { +func (m *Member) DecodeMsgpack(d *msgpack.Decoder) error { var err error var l int if l, err = d.DecodeArrayLen(); err != nil { diff --git a/pool/msgpack_helper_test.go b/pool/msgpack_helper_test.go deleted file mode 100644 index f54df2038..000000000 --- a/pool/msgpack_helper_test.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build !go_tarantool_msgpack_v5 -// +build !go_tarantool_msgpack_v5 - -package pool_test - -import ( - "gopkg.in/vmihailenco/msgpack.v2" -) - -type decoder = msgpack.Decoder diff --git a/pool/msgpack_v5_helper_test.go b/pool/msgpack_v5_helper_test.go deleted file mode 100644 index a507ffa64..000000000 --- a/pool/msgpack_v5_helper_test.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build go_tarantool_msgpack_v5 -// +build go_tarantool_msgpack_v5 - -package pool_test - -import ( - "github.com/vmihailenco/msgpack/v5" -) - -type decoder = msgpack.Decoder diff --git a/prepared.go b/prepared.go index 9019a81f3..4e3f494ee 100644 --- a/prepared.go +++ b/prepared.go @@ -3,6 +3,8 @@ package tarantool import ( "context" "fmt" + + "github.com/vmihailenco/msgpack/v5" ) // PreparedID is a type for Prepared Statement ID @@ -18,23 +20,23 @@ type Prepared struct { Conn *Connection } -func fillPrepare(enc *encoder, expr string) error { +func fillPrepare(enc *msgpack.Encoder, expr string) error { enc.EncodeMapLen(1) - encodeUint(enc, KeySQLText) + enc.EncodeUint(KeySQLText) return enc.EncodeString(expr) } -func fillUnprepare(enc *encoder, stmt Prepared) error { +func fillUnprepare(enc *msgpack.Encoder, stmt Prepared) error { enc.EncodeMapLen(1) - encodeUint(enc, KeyStmtID) - return encodeUint(enc, uint64(stmt.StatementID)) + enc.EncodeUint(KeyStmtID) + return enc.EncodeUint(uint64(stmt.StatementID)) } -func fillExecutePrepared(enc *encoder, stmt Prepared, args interface{}) error { +func fillExecutePrepared(enc *msgpack.Encoder, stmt Prepared, args interface{}) error { enc.EncodeMapLen(2) - encodeUint(enc, KeyStmtID) - encodeUint(enc, uint64(stmt.StatementID)) - encodeUint(enc, KeySQLBind) + enc.EncodeUint(KeyStmtID) + enc.EncodeUint(uint64(stmt.StatementID)) + enc.EncodeUint(KeySQLBind) return encodeSQLBind(enc, args) } @@ -72,8 +74,8 @@ func NewPrepareRequest(expr string) *PrepareRequest { return req } -// Body fills an encoder with the execute request body. -func (req *PrepareRequest) Body(res SchemaResolver, enc *encoder) error { +// Body fills an msgpack.Encoder with the execute request body. +func (req *PrepareRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error { return fillPrepare(enc, req.expr) } @@ -108,8 +110,8 @@ func (req *UnprepareRequest) Conn() *Connection { return req.stmt.Conn } -// Body fills an encoder with the execute request body. -func (req *UnprepareRequest) Body(res SchemaResolver, enc *encoder) error { +// Body fills an msgpack.Encoder with the execute request body. +func (req *UnprepareRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error { return fillUnprepare(enc, *req.stmt) } @@ -153,8 +155,8 @@ func (req *ExecutePreparedRequest) Args(args interface{}) *ExecutePreparedReques return req } -// Body fills an encoder with the execute request body. -func (req *ExecutePreparedRequest) Body(res SchemaResolver, enc *encoder) error { +// Body fills an msgpack.Encoder with the execute request body. +func (req *ExecutePreparedRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error { return fillExecutePrepared(enc, *req.stmt, req.args) } diff --git a/protocol.go b/protocol.go index ae8dce306..6ddfd8d48 100644 --- a/protocol.go +++ b/protocol.go @@ -3,6 +3,8 @@ package tarantool import ( "context" "fmt" + + "github.com/vmihailenco/msgpack/v5" ) // ProtocolVersion type stores Tarantool protocol version. @@ -101,15 +103,15 @@ type IdRequest struct { protocolInfo ProtocolInfo } -func fillId(enc *encoder, protocolInfo ProtocolInfo) error { +func fillId(enc *msgpack.Encoder, protocolInfo ProtocolInfo) error { enc.EncodeMapLen(2) - encodeUint(enc, KeyVersion) + enc.EncodeUint(KeyVersion) if err := enc.Encode(protocolInfo.Version); err != nil { return err } - encodeUint(enc, KeyFeatures) + enc.EncodeUint(KeyFeatures) t := len(protocolInfo.Features) if err := enc.EncodeArrayLen(t); err != nil { @@ -133,8 +135,8 @@ func NewIdRequest(protocolInfo ProtocolInfo) *IdRequest { return req } -// Body fills an encoder with the id request body. -func (req *IdRequest) Body(res SchemaResolver, enc *encoder) error { +// Body fills an msgpack.Encoder with the id request body. +func (req *IdRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error { return fillId(enc, req.protocolInfo) } diff --git a/queue/example_msgpack_test.go b/queue/example_msgpack_test.go index 71e5cf814..ff37c1879 100644 --- a/queue/example_msgpack_test.go +++ b/queue/example_msgpack_test.go @@ -13,6 +13,8 @@ import ( "log" "time" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" "github.com/tarantool/go-tarantool/v2/queue" ) @@ -21,7 +23,7 @@ type dummyData struct { Dummy bool } -func (c *dummyData) DecodeMsgpack(d *decoder) error { +func (c *dummyData) DecodeMsgpack(d *msgpack.Decoder) error { var err error if c.Dummy, err = d.DecodeBool(); err != nil { return err @@ -29,7 +31,7 @@ func (c *dummyData) DecodeMsgpack(d *decoder) error { return nil } -func (c *dummyData) EncodeMsgpack(e *encoder) error { +func (c *dummyData) EncodeMsgpack(e *msgpack.Encoder) error { return e.EncodeBool(c.Dummy) } diff --git a/queue/msgpack.go b/queue/msgpack.go deleted file mode 100644 index d9e0b58db..000000000 --- a/queue/msgpack.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build !go_tarantool_msgpack_v5 -// +build !go_tarantool_msgpack_v5 - -package queue - -import ( - "gopkg.in/vmihailenco/msgpack.v2" -) - -type decoder = msgpack.Decoder diff --git a/queue/msgpack_helper_test.go b/queue/msgpack_helper_test.go deleted file mode 100644 index 49b61240c..000000000 --- a/queue/msgpack_helper_test.go +++ /dev/null @@ -1,11 +0,0 @@ -//go:build !go_tarantool_msgpack_v5 -// +build !go_tarantool_msgpack_v5 - -package queue_test - -import ( - "gopkg.in/vmihailenco/msgpack.v2" -) - -type encoder = msgpack.Encoder -type decoder = msgpack.Decoder diff --git a/queue/msgpack_v5.go b/queue/msgpack_v5.go deleted file mode 100644 index b5037caaf..000000000 --- a/queue/msgpack_v5.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build go_tarantool_msgpack_v5 -// +build go_tarantool_msgpack_v5 - -package queue - -import ( - "github.com/vmihailenco/msgpack/v5" -) - -type decoder = msgpack.Decoder diff --git a/queue/msgpack_v5_helper_test.go b/queue/msgpack_v5_helper_test.go deleted file mode 100644 index ea2991f34..000000000 --- a/queue/msgpack_v5_helper_test.go +++ /dev/null @@ -1,11 +0,0 @@ -//go:build go_tarantool_msgpack_v5 -// +build go_tarantool_msgpack_v5 - -package queue_test - -import ( - "github.com/vmihailenco/msgpack/v5" -) - -type encoder = msgpack.Encoder -type decoder = msgpack.Decoder diff --git a/queue/queue.go b/queue/queue.go index 5dfc147f3..2407bad03 100644 --- a/queue/queue.go +++ b/queue/queue.go @@ -13,6 +13,8 @@ import ( "time" "github.com/google/uuid" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" ) @@ -371,7 +373,7 @@ type kickResult struct { id uint64 } -func (r *kickResult) DecodeMsgpack(d *decoder) (err error) { +func (r *kickResult) DecodeMsgpack(d *msgpack.Decoder) (err error) { var l int if l, err = d.DecodeArrayLen(); err != nil { return err @@ -453,7 +455,7 @@ type queueData struct { result interface{} } -func (qd *queueData) DecodeMsgpack(d *decoder) error { +func (qd *queueData) DecodeMsgpack(d *msgpack.Decoder) error { var err error var l int if l, err = d.DecodeArrayLen(); err != nil { @@ -472,7 +474,7 @@ func (qd *queueData) DecodeMsgpack(d *decoder) error { } if qd.task.Data() == nil { - // It may happen if the decoder has a code.Nil value inside. As a + // It may happen if the msgpack.Decoder has a code.Nil value inside. As a // result, the task will not be decoded. qd.task = nil } diff --git a/queue/queue_test.go b/queue/queue_test.go index 11f4a65a9..313032f49 100644 --- a/queue/queue_test.go +++ b/queue/queue_test.go @@ -8,6 +8,8 @@ import ( "testing" "time" + "github.com/vmihailenco/msgpack/v5" + . "github.com/tarantool/go-tarantool/v2" "github.com/tarantool/go-tarantool/v2/queue" "github.com/tarantool/go-tarantool/v2/test_helpers" @@ -300,7 +302,7 @@ type customData struct { customField string } -func (c *customData) DecodeMsgpack(d *decoder) error { +func (c *customData) DecodeMsgpack(d *msgpack.Decoder) error { var err error var l int if l, err = d.DecodeArrayLen(); err != nil { @@ -315,7 +317,7 @@ func (c *customData) DecodeMsgpack(d *decoder) error { return nil } -func (c *customData) EncodeMsgpack(e *encoder) error { +func (c *customData) EncodeMsgpack(e *msgpack.Encoder) error { if err := e.EncodeArrayLen(1); err != nil { return err } diff --git a/queue/task.go b/queue/task.go index c1b0aad98..db970884e 100644 --- a/queue/task.go +++ b/queue/task.go @@ -3,6 +3,8 @@ package queue import ( "fmt" "time" + + "github.com/vmihailenco/msgpack/v5" ) // Task represents a task from Tarantool queue's tube. @@ -13,7 +15,7 @@ type Task struct { q *queue } -func (t *Task) DecodeMsgpack(d *decoder) error { +func (t *Task) DecodeMsgpack(d *msgpack.Decoder) error { var err error var l int if l, err = d.DecodeArrayLen(); err != nil { diff --git a/request.go b/request.go index 7c79c5863..5388c0e1a 100644 --- a/request.go +++ b/request.go @@ -7,63 +7,65 @@ import ( "reflect" "strings" "sync" + + "github.com/vmihailenco/msgpack/v5" ) -func fillSearch(enc *encoder, spaceNo, indexNo uint32, key interface{}) error { - if err := encodeUint(enc, KeySpaceNo); err != nil { +func fillSearch(enc *msgpack.Encoder, spaceNo, indexNo uint32, key interface{}) error { + if err := enc.EncodeUint(KeySpaceNo); err != nil { return err } - if err := encodeUint(enc, uint64(spaceNo)); err != nil { + if err := enc.EncodeUint(uint64(spaceNo)); err != nil { return err } - if err := encodeUint(enc, KeyIndexNo); err != nil { + if err := enc.EncodeUint(KeyIndexNo); err != nil { return err } - if err := encodeUint(enc, uint64(indexNo)); err != nil { + if err := enc.EncodeUint(uint64(indexNo)); err != nil { return err } - if err := encodeUint(enc, KeyKey); err != nil { + if err := enc.EncodeUint(KeyKey); err != nil { return err } return enc.Encode(key) } -func fillIterator(enc *encoder, offset, limit, iterator uint32) error { - if err := encodeUint(enc, KeyIterator); err != nil { +func fillIterator(enc *msgpack.Encoder, offset, limit, iterator uint32) error { + if err := enc.EncodeUint(KeyIterator); err != nil { return err } - if err := encodeUint(enc, uint64(iterator)); err != nil { + if err := enc.EncodeUint(uint64(iterator)); err != nil { return err } - if err := encodeUint(enc, KeyOffset); err != nil { + if err := enc.EncodeUint(KeyOffset); err != nil { return err } - if err := encodeUint(enc, uint64(offset)); err != nil { + if err := enc.EncodeUint(uint64(offset)); err != nil { return err } - if err := encodeUint(enc, KeyLimit); err != nil { + if err := enc.EncodeUint(KeyLimit); err != nil { return err } - return encodeUint(enc, uint64(limit)) + return enc.EncodeUint(uint64(limit)) } -func fillInsert(enc *encoder, spaceNo uint32, tuple interface{}) error { +func fillInsert(enc *msgpack.Encoder, spaceNo uint32, tuple interface{}) error { if err := enc.EncodeMapLen(2); err != nil { return err } - if err := encodeUint(enc, KeySpaceNo); err != nil { + if err := enc.EncodeUint(KeySpaceNo); err != nil { return err } - if err := encodeUint(enc, uint64(spaceNo)); err != nil { + if err := enc.EncodeUint(uint64(spaceNo)); err != nil { return err } - if err := encodeUint(enc, KeyTuple); err != nil { + if err := enc.EncodeUint(KeyTuple); err != nil { return err } return enc.Encode(tuple) } -func fillSelect(enc *encoder, spaceNo, indexNo, offset, limit, iterator uint32, +func fillSelect(enc *msgpack.Encoder, spaceNo, indexNo, offset, limit, iterator uint32, key, after interface{}, fetchPos bool) error { mapLen := 6 if fetchPos { @@ -82,7 +84,7 @@ func fillSelect(enc *encoder, spaceNo, indexNo, offset, limit, iterator uint32, return err } if fetchPos { - if err := encodeUint(enc, KeyFetchPos); err != nil { + if err := enc.EncodeUint(KeyFetchPos); err != nil { return err } if err := enc.EncodeBool(fetchPos); err != nil { @@ -91,14 +93,14 @@ func fillSelect(enc *encoder, spaceNo, indexNo, offset, limit, iterator uint32, } if after != nil { if pos, ok := after.([]byte); ok { - if err := encodeUint(enc, KeyAfterPos); err != nil { + if err := enc.EncodeUint(KeyAfterPos); err != nil { return err } if err := enc.EncodeString(string(pos)); err != nil { return err } } else { - if err := encodeUint(enc, KeyAfterTuple); err != nil { + if err := enc.EncodeUint(KeyAfterTuple); err != nil { return err } if err := enc.Encode(after); err != nil { @@ -109,57 +111,57 @@ func fillSelect(enc *encoder, spaceNo, indexNo, offset, limit, iterator uint32, return nil } -func fillUpdate(enc *encoder, spaceNo, indexNo uint32, key, ops interface{}) error { +func fillUpdate(enc *msgpack.Encoder, spaceNo, indexNo uint32, key, ops interface{}) error { enc.EncodeMapLen(4) if err := fillSearch(enc, spaceNo, indexNo, key); err != nil { return err } - encodeUint(enc, KeyTuple) + enc.EncodeUint(KeyTuple) return enc.Encode(ops) } -func fillUpsert(enc *encoder, spaceNo uint32, tuple, ops interface{}) error { +func fillUpsert(enc *msgpack.Encoder, spaceNo uint32, tuple, ops interface{}) error { enc.EncodeMapLen(3) - encodeUint(enc, KeySpaceNo) - encodeUint(enc, uint64(spaceNo)) - encodeUint(enc, KeyTuple) + enc.EncodeUint(KeySpaceNo) + enc.EncodeUint(uint64(spaceNo)) + enc.EncodeUint(KeyTuple) if err := enc.Encode(tuple); err != nil { return err } - encodeUint(enc, KeyDefTuple) + enc.EncodeUint(KeyDefTuple) return enc.Encode(ops) } -func fillDelete(enc *encoder, spaceNo, indexNo uint32, key interface{}) error { +func fillDelete(enc *msgpack.Encoder, spaceNo, indexNo uint32, key interface{}) error { enc.EncodeMapLen(3) return fillSearch(enc, spaceNo, indexNo, key) } -func fillCall(enc *encoder, functionName string, args interface{}) error { +func fillCall(enc *msgpack.Encoder, functionName string, args interface{}) error { enc.EncodeMapLen(2) - encodeUint(enc, KeyFunctionName) + enc.EncodeUint(KeyFunctionName) enc.EncodeString(functionName) - encodeUint(enc, KeyTuple) + enc.EncodeUint(KeyTuple) return enc.Encode(args) } -func fillEval(enc *encoder, expr string, args interface{}) error { +func fillEval(enc *msgpack.Encoder, expr string, args interface{}) error { enc.EncodeMapLen(2) - encodeUint(enc, KeyExpression) + enc.EncodeUint(KeyExpression) enc.EncodeString(expr) - encodeUint(enc, KeyTuple) + enc.EncodeUint(KeyTuple) return enc.Encode(args) } -func fillExecute(enc *encoder, expr string, args interface{}) error { +func fillExecute(enc *msgpack.Encoder, expr string, args interface{}) error { enc.EncodeMapLen(2) - encodeUint(enc, KeySQLText) + enc.EncodeUint(KeySQLText) enc.EncodeString(expr) - encodeUint(enc, KeySQLBind) + enc.EncodeUint(KeySQLBind) return encodeSQLBind(enc, args) } -func fillPing(enc *encoder) error { +func fillPing(enc *msgpack.Encoder) error { return enc.EncodeMapLen(0) } @@ -264,7 +266,7 @@ type single struct { found bool } -func (s *single) DecodeMsgpack(d *decoder) error { +func (s *single) DecodeMsgpack(d *msgpack.Decoder) error { var err error var len int if len, err = d.DecodeArrayLen(); err != nil { @@ -471,7 +473,7 @@ type KeyValueBind struct { // to avoid extra allocations in heap by calling strings.ToLower() var lowerCaseNames sync.Map -func encodeSQLBind(enc *encoder, from interface{}) error { +func encodeSQLBind(enc *msgpack.Encoder, from interface{}) error { // internal function for encoding single map in msgpack encodeKeyInterface := func(key string, val interface{}) error { if err := enc.EncodeMapLen(1); err != nil { @@ -603,8 +605,8 @@ func encodeSQLBind(enc *encoder, from interface{}) error { type Request interface { // Code returns a IPROTO code for the request. Code() int32 - // Body fills an encoder with a request body. - Body(resolver SchemaResolver, enc *encoder) error + // Body fills an msgpack.Encoder with a request body. + Body(resolver SchemaResolver, enc *msgpack.Encoder) error // Ctx returns a context of the request. Ctx() context.Context // Async returns true if the request does not expect response. @@ -705,7 +707,7 @@ func (req authRequest) Ctx() context.Context { } // Body fills an encoder with the auth request body. -func (req authRequest) Body(res SchemaResolver, enc *encoder) error { +func (req authRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error { return enc.Encode(map[uint32]interface{}{ KeyUserName: req.user, KeyTuple: []interface{}{req.auth.String(), req.pass}, @@ -725,8 +727,8 @@ func NewPingRequest() *PingRequest { return req } -// Body fills an encoder with the ping request body. -func (req *PingRequest) Body(res SchemaResolver, enc *encoder) error { +// Body fills an msgpack.Encoder with the ping request body. +func (req *PingRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error { return fillPing(enc) } @@ -828,7 +830,7 @@ func (req *SelectRequest) After(after interface{}) *SelectRequest { } // Body fills an encoder with the select request body. -func (req *SelectRequest) Body(res SchemaResolver, enc *encoder) error { +func (req *SelectRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error { spaceNo, indexNo, err := res.ResolveSpaceIndex(req.space, req.index) if err != nil { return err @@ -872,8 +874,8 @@ func (req *InsertRequest) Tuple(tuple interface{}) *InsertRequest { return req } -// Body fills an encoder with the insert request body. -func (req *InsertRequest) Body(res SchemaResolver, enc *encoder) error { +// Body fills an msgpack.Encoder with the insert request body. +func (req *InsertRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error { spaceNo, _, err := res.ResolveSpaceIndex(req.space, nil) if err != nil { return err @@ -916,8 +918,8 @@ func (req *ReplaceRequest) Tuple(tuple interface{}) *ReplaceRequest { return req } -// Body fills an encoder with the replace request body. -func (req *ReplaceRequest) Body(res SchemaResolver, enc *encoder) error { +// Body fills an msgpack.Encoder with the replace request body. +func (req *ReplaceRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error { spaceNo, _, err := res.ResolveSpaceIndex(req.space, nil) if err != nil { return err @@ -967,8 +969,8 @@ func (req *DeleteRequest) Key(key interface{}) *DeleteRequest { return req } -// Body fills an encoder with the delete request body. -func (req *DeleteRequest) Body(res SchemaResolver, enc *encoder) error { +// Body fills an msgpack.Encoder with the delete request body. +func (req *DeleteRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error { spaceNo, indexNo, err := res.ResolveSpaceIndex(req.space, req.index) if err != nil { return err @@ -1029,8 +1031,8 @@ func (req *UpdateRequest) Operations(ops *Operations) *UpdateRequest { return req } -// Body fills an encoder with the update request body. -func (req *UpdateRequest) Body(res SchemaResolver, enc *encoder) error { +// Body fills an msgpack.Encoder with the update request body. +func (req *UpdateRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error { spaceNo, indexNo, err := res.ResolveSpaceIndex(req.space, req.index) if err != nil { return err @@ -1084,8 +1086,8 @@ func (req *UpsertRequest) Operations(ops *Operations) *UpsertRequest { return req } -// Body fills an encoder with the upsert request body. -func (req *UpsertRequest) Body(res SchemaResolver, enc *encoder) error { +// Body fills an msgpack.Encoder with the upsert request body. +func (req *UpsertRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error { spaceNo, _, err := res.ResolveSpaceIndex(req.space, nil) if err != nil { return err @@ -1131,7 +1133,7 @@ func (req *CallRequest) Args(args interface{}) *CallRequest { } // Body fills an encoder with the call request body. -func (req *CallRequest) Body(res SchemaResolver, enc *encoder) error { +func (req *CallRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error { args := req.args if args == nil { args = []interface{}{} @@ -1191,8 +1193,8 @@ func (req *EvalRequest) Args(args interface{}) *EvalRequest { return req } -// Body fills an encoder with the eval request body. -func (req *EvalRequest) Body(res SchemaResolver, enc *encoder) error { +// Body fills an msgpack.Encoder with the eval request body. +func (req *EvalRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error { return fillEval(enc, req.expr, req.args) } @@ -1231,8 +1233,8 @@ func (req *ExecuteRequest) Args(args interface{}) *ExecuteRequest { return req } -// Body fills an encoder with the execute request body. -func (req *ExecuteRequest) Body(res SchemaResolver, enc *encoder) error { +// Body fills an msgpack.Encoder with the execute request body. +func (req *ExecuteRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error { return fillExecute(enc, req.expr, req.args) } diff --git a/request_test.go b/request_test.go index 3458f397b..d3f15c179 100644 --- a/request_test.go +++ b/request_test.go @@ -8,9 +8,9 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/vmihailenco/msgpack/v5" . "github.com/tarantool/go-tarantool/v2" - "github.com/tarantool/go-tarantool/v2/test_helpers" ) const invalidSpaceMsg = "invalid space" @@ -68,7 +68,7 @@ func assertBodyCall(t testing.TB, requests []Request, errorMsg string) { const errBegin = "An unexpected Request.Body() " for _, req := range requests { var reqBuf bytes.Buffer - enc := NewEncoder(&reqBuf) + enc := msgpack.NewEncoder(&reqBuf) err := req.Body(&resolver, enc) if err != nil && errorMsg != "" && err.Error() != errorMsg { @@ -86,11 +86,15 @@ func assertBodyCall(t testing.TB, requests []Request, errorMsg string) { func assertBodyEqual(t testing.TB, reference []byte, req Request) { t.Helper() - reqBody, err := test_helpers.ExtractRequestBody(req, &resolver, NewEncoder) + var reqBuf bytes.Buffer + reqEnc := msgpack.NewEncoder(&reqBuf) + + err := req.Body(&resolver, reqEnc) if err != nil { t.Fatalf("An unexpected Response.Body() error: %q", err.Error()) } + reqBody := reqBuf.Bytes() if !bytes.Equal(reqBody, reference) { t.Errorf("Encoded request %v != reference %v", reqBody, reference) } @@ -301,7 +305,7 @@ func TestRequestsCtx_setter(t *testing.T) { func TestPingRequestDefaultValues(t *testing.T) { var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplPingBody(refEnc) if err != nil { t.Errorf("An unexpected RefImplPingBody() error: %q", err.Error()) @@ -315,7 +319,7 @@ func TestPingRequestDefaultValues(t *testing.T) { func TestSelectRequestDefaultValues(t *testing.T) { var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplSelectBody(refEnc, validSpace, defaultIndex, 0, 0xFFFFFFFF, IterAll, []interface{}{}, nil, false) if err != nil { @@ -331,7 +335,7 @@ func TestSelectRequestDefaultIteratorEqIfKey(t *testing.T) { var refBuf bytes.Buffer key := []interface{}{uint(18)} - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplSelectBody(refEnc, validSpace, defaultIndex, 0, 0xFFFFFFFF, IterEq, key, nil, false) if err != nil { @@ -349,7 +353,7 @@ func TestSelectRequestIteratorNotChangedIfKey(t *testing.T) { key := []interface{}{uint(678)} const iter = IterGe - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplSelectBody(refEnc, validSpace, defaultIndex, 0, 0xFFFFFFFF, iter, key, nil, false) if err != nil { @@ -372,7 +376,7 @@ func TestSelectRequestSetters(t *testing.T) { afterKey := []interface{}{uint(13)} var refBufAfterBytes, refBufAfterKey bytes.Buffer - refEncAfterBytes := NewEncoder(&refBufAfterBytes) + refEncAfterBytes := msgpack.NewEncoder(&refBufAfterBytes) err := RefImplSelectBody(refEncAfterBytes, validSpace, validIndex, offset, limit, iter, key, afterBytes, true) if err != nil { @@ -380,7 +384,7 @@ func TestSelectRequestSetters(t *testing.T) { return } - refEncAfterKey := NewEncoder(&refBufAfterKey) + refEncAfterKey := msgpack.NewEncoder(&refBufAfterKey) err = RefImplSelectBody(refEncAfterKey, validSpace, validIndex, offset, limit, iter, key, afterKey, true) if err != nil { @@ -412,7 +416,7 @@ func TestSelectRequestSetters(t *testing.T) { func TestInsertRequestDefaultValues(t *testing.T) { var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplInsertBody(refEnc, validSpace, []interface{}{}) if err != nil { t.Errorf("An unexpected RefImplInsertBody() error: %q", err.Error()) @@ -427,7 +431,7 @@ func TestInsertRequestSetters(t *testing.T) { tuple := []interface{}{uint(24)} var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplInsertBody(refEnc, validSpace, tuple) if err != nil { t.Errorf("An unexpected RefImplInsertBody() error: %q", err.Error()) @@ -442,7 +446,7 @@ func TestInsertRequestSetters(t *testing.T) { func TestReplaceRequestDefaultValues(t *testing.T) { var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplReplaceBody(refEnc, validSpace, []interface{}{}) if err != nil { t.Errorf("An unexpected RefImplReplaceBody() error: %q", err.Error()) @@ -457,7 +461,7 @@ func TestReplaceRequestSetters(t *testing.T) { tuple := []interface{}{uint(99)} var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplReplaceBody(refEnc, validSpace, tuple) if err != nil { t.Errorf("An unexpected RefImplReplaceBody() error: %q", err.Error()) @@ -472,7 +476,7 @@ func TestReplaceRequestSetters(t *testing.T) { func TestDeleteRequestDefaultValues(t *testing.T) { var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplDeleteBody(refEnc, validSpace, defaultIndex, []interface{}{}) if err != nil { t.Errorf("An unexpected RefImplDeleteBody() error: %q", err.Error()) @@ -487,7 +491,7 @@ func TestDeleteRequestSetters(t *testing.T) { key := []interface{}{uint(923)} var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplDeleteBody(refEnc, validSpace, validIndex, key) if err != nil { t.Errorf("An unexpected RefImplDeleteBody() error: %q", err.Error()) @@ -503,7 +507,7 @@ func TestDeleteRequestSetters(t *testing.T) { func TestUpdateRequestDefaultValues(t *testing.T) { var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplUpdateBody(refEnc, validSpace, defaultIndex, []interface{}{}, []Op{}) if err != nil { t.Errorf("An unexpected RefImplUpdateBody() error: %q", err.Error()) @@ -519,7 +523,7 @@ func TestUpdateRequestSetters(t *testing.T) { refOps, reqOps := getTestOps() var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplUpdateBody(refEnc, validSpace, validIndex, key, refOps) if err != nil { t.Errorf("An unexpected RefImplUpdateBody() error: %q", err.Error()) @@ -536,7 +540,7 @@ func TestUpdateRequestSetters(t *testing.T) { func TestUpsertRequestDefaultValues(t *testing.T) { var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplUpsertBody(refEnc, validSpace, []interface{}{}, []Op{}) if err != nil { t.Errorf("An unexpected RefImplUpsertBody() error: %q", err.Error()) @@ -552,7 +556,7 @@ func TestUpsertRequestSetters(t *testing.T) { refOps, reqOps := getTestOps() var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplUpsertBody(refEnc, validSpace, tuple, refOps) if err != nil { t.Errorf("An unexpected RefImplUpsertBody() error: %q", err.Error()) @@ -568,7 +572,7 @@ func TestUpsertRequestSetters(t *testing.T) { func TestCallRequestsDefaultValues(t *testing.T) { var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplCallBody(refEnc, validExpr, []interface{}{}) if err != nil { t.Errorf("An unexpected RefImplCallBody() error: %q", err.Error()) @@ -587,7 +591,7 @@ func TestCallRequestsSetters(t *testing.T) { args := []interface{}{uint(34)} var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplCallBody(refEnc, validExpr, args) if err != nil { t.Errorf("An unexpected RefImplCallBody() error: %q", err.Error()) @@ -608,7 +612,7 @@ func TestCallRequestsSetters(t *testing.T) { func TestEvalRequestDefaultValues(t *testing.T) { var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplEvalBody(refEnc, validExpr, []interface{}{}) if err != nil { t.Errorf("An unexpected RefImplEvalBody() error: %q", err.Error()) @@ -623,7 +627,7 @@ func TestEvalRequestSetters(t *testing.T) { args := []interface{}{uint(34), int(12)} var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplEvalBody(refEnc, validExpr, args) if err != nil { t.Errorf("An unexpected RefImplEvalBody() error: %q", err.Error()) @@ -638,7 +642,7 @@ func TestEvalRequestSetters(t *testing.T) { func TestExecuteRequestDefaultValues(t *testing.T) { var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplExecuteBody(refEnc, validExpr, []interface{}{}) if err != nil { t.Errorf("An unexpected RefImplExecuteBody() error: %q", err.Error()) @@ -653,7 +657,7 @@ func TestExecuteRequestSetters(t *testing.T) { args := []interface{}{uint(11)} var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplExecuteBody(refEnc, validExpr, args) if err != nil { t.Errorf("An unexpected RefImplExecuteBody() error: %q", err.Error()) @@ -668,7 +672,7 @@ func TestExecuteRequestSetters(t *testing.T) { func TestPrepareRequestDefaultValues(t *testing.T) { var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplPrepareBody(refEnc, validExpr) if err != nil { t.Errorf("An unexpected RefImplPrepareBody() error: %q", err.Error()) @@ -682,7 +686,7 @@ func TestPrepareRequestDefaultValues(t *testing.T) { func TestUnprepareRequestDefaultValues(t *testing.T) { var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplUnprepareBody(refEnc, *validStmt) if err != nil { t.Errorf("An unexpected RefImplUnprepareBody() error: %q", err.Error()) @@ -698,7 +702,7 @@ func TestExecutePreparedRequestSetters(t *testing.T) { args := []interface{}{uint(11)} var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplExecutePreparedBody(refEnc, *validStmt, args) if err != nil { t.Errorf("An unexpected RefImplExecutePreparedBody() error: %q", err.Error()) @@ -714,7 +718,7 @@ func TestExecutePreparedRequestSetters(t *testing.T) { func TestExecutePreparedRequestDefaultValues(t *testing.T) { var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplExecutePreparedBody(refEnc, *validStmt, []interface{}{}) if err != nil { t.Errorf("An unexpected RefImplExecutePreparedBody() error: %q", err.Error()) @@ -729,7 +733,7 @@ func TestExecutePreparedRequestDefaultValues(t *testing.T) { func TestBeginRequestDefaultValues(t *testing.T) { var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplBeginBody(refEnc, defaultIsolationLevel, defaultTimeout) if err != nil { t.Errorf("An unexpected RefImplBeginBody() error: %q", err.Error()) @@ -743,7 +747,7 @@ func TestBeginRequestDefaultValues(t *testing.T) { func TestBeginRequestSetters(t *testing.T) { var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplBeginBody(refEnc, ReadConfirmedLevel, validTimeout) if err != nil { t.Errorf("An unexpected RefImplBeginBody() error: %q", err.Error()) @@ -757,7 +761,7 @@ func TestBeginRequestSetters(t *testing.T) { func TestCommitRequestDefaultValues(t *testing.T) { var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplCommitBody(refEnc) if err != nil { t.Errorf("An unexpected RefImplCommitBody() error: %q", err.Error()) @@ -771,7 +775,7 @@ func TestCommitRequestDefaultValues(t *testing.T) { func TestRollbackRequestDefaultValues(t *testing.T) { var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) err := RefImplRollbackBody(refEnc) if err != nil { t.Errorf("An unexpected RefImplRollbackBody() error: %q", err.Error()) @@ -785,7 +789,7 @@ func TestRollbackRequestDefaultValues(t *testing.T) { func TestBroadcastRequestDefaultValues(t *testing.T) { var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) expectedArgs := []interface{}{validKey} err := RefImplCallBody(refEnc, "box.broadcast", expectedArgs) if err != nil { @@ -801,7 +805,7 @@ func TestBroadcastRequestSetters(t *testing.T) { value := []interface{}{uint(34), int(12)} var refBuf bytes.Buffer - refEnc := NewEncoder(&refBuf) + refEnc := msgpack.NewEncoder(&refBuf) expectedArgs := []interface{}{validKey, value} err := RefImplCallBody(refEnc, "box.broadcast", expectedArgs) if err != nil { diff --git a/response.go b/response.go index e5486b0a4..b07e8690f 100644 --- a/response.go +++ b/response.go @@ -2,6 +2,8 @@ package tarantool import ( "fmt" + + "github.com/vmihailenco/msgpack/v5" ) type Response struct { @@ -32,7 +34,7 @@ type SQLInfo struct { InfoAutoincrementIds []uint64 } -func (meta *ColumnMetaData) DecodeMsgpack(d *decoder) error { +func (meta *ColumnMetaData) DecodeMsgpack(d *msgpack.Decoder) error { var err error var l int if l, err = d.DecodeMapLen(); err != nil { @@ -70,7 +72,7 @@ func (meta *ColumnMetaData) DecodeMsgpack(d *decoder) error { return nil } -func (info *SQLInfo) DecodeMsgpack(d *decoder) error { +func (info *SQLInfo) DecodeMsgpack(d *msgpack.Decoder) error { var err error var l int if l, err = d.DecodeMapLen(); err != nil { @@ -100,7 +102,7 @@ func (info *SQLInfo) DecodeMsgpack(d *decoder) error { return nil } -func (resp *Response) smallInt(d *decoder) (i int, err error) { +func (resp *Response) smallInt(d *msgpack.Decoder) (i int, err error) { b, err := resp.buf.ReadByte() if err != nil { return @@ -112,7 +114,7 @@ func (resp *Response) smallInt(d *decoder) (i int, err error) { return d.DecodeInt() } -func (resp *Response) decodeHeader(d *decoder) (err error) { +func (resp *Response) decodeHeader(d *msgpack.Decoder) (err error) { var l int d.Reset(&resp.buf) if l, err = d.DecodeMapLen(); err != nil { @@ -156,7 +158,10 @@ func (resp *Response) decodeBody() (err error) { var feature ProtocolFeature var errorExtendedInfo *BoxError = nil - d := newDecoder(&resp.buf) + d := msgpack.NewDecoder(&resp.buf) + d.SetMapDecoder(func(dec *msgpack.Decoder) (interface{}, error) { + return dec.DecodeUntypedMap() + }) if l, err = d.DecodeMapLen(); err != nil { return err @@ -277,7 +282,12 @@ func (resp *Response) decodeBodyTyped(res interface{}) (err error) { var errorExtendedInfo *BoxError = nil var l int - d := newDecoder(&resp.buf) + + d := msgpack.NewDecoder(&resp.buf) + d.SetMapDecoder(func(dec *msgpack.Decoder) (interface{}, error) { + return dec.DecodeUntypedMap() + }) + if l, err = d.DecodeMapLen(); err != nil { return err } diff --git a/schema.go b/schema.go index 87c788fe0..9e9f0ac17 100644 --- a/schema.go +++ b/schema.go @@ -3,6 +3,9 @@ package tarantool import ( "errors" "fmt" + + "github.com/vmihailenco/msgpack/v5" + "github.com/vmihailenco/msgpack/v5/msgpcode" ) // nolint: varcheck,deadcode @@ -16,6 +19,26 @@ const ( vspaceSpFormatFieldNum = 7 ) +func msgpackIsUint(code byte) bool { + return code == msgpcode.Uint8 || code == msgpcode.Uint16 || + code == msgpcode.Uint32 || code == msgpcode.Uint64 || + msgpcode.IsFixedNum(code) +} + +func msgpackIsMap(code byte) bool { + return code == msgpcode.Map16 || code == msgpcode.Map32 || msgpcode.IsFixedMap(code) +} + +func msgpackIsArray(code byte) bool { + return code == msgpcode.Array16 || code == msgpcode.Array32 || + msgpcode.IsFixedArray(code) +} + +func msgpackIsString(code byte) bool { + return msgpcode.IsFixedString(code) || code == msgpcode.Str8 || + code == msgpcode.Str16 || code == msgpcode.Str32 +} + // SchemaResolver is an interface for resolving schema details. type SchemaResolver interface { // ResolveSpaceIndex returns resolved space and index numbers or an @@ -49,7 +72,7 @@ type Space struct { IndexesById map[uint32]*Index } -func (space *Space) DecodeMsgpack(d *decoder) error { +func (space *Space) DecodeMsgpack(d *msgpack.Decoder) error { arrayLen, err := d.DecodeArrayLen() if err != nil { return err @@ -134,7 +157,7 @@ type Field struct { Type string } -func (field *Field) DecodeMsgpack(d *decoder) error { +func (field *Field) DecodeMsgpack(d *msgpack.Decoder) error { l, err := d.DecodeMapLen() if err != nil { return err @@ -172,7 +195,7 @@ type Index struct { Fields []*IndexField } -func (index *Index) DecodeMsgpack(d *decoder) error { +func (index *Index) DecodeMsgpack(d *msgpack.Decoder) error { _, err := d.DecodeArrayLen() if err != nil { return err @@ -248,7 +271,7 @@ type IndexField struct { Type string } -func (indexField *IndexField) DecodeMsgpack(d *decoder) error { +func (indexField *IndexField) DecodeMsgpack(d *msgpack.Decoder) error { code, err := d.PeekCode() if err != nil { return err diff --git a/settings/msgpack.go b/settings/msgpack.go deleted file mode 100644 index 295620aba..000000000 --- a/settings/msgpack.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build !go_tarantool_msgpack_v5 -// +build !go_tarantool_msgpack_v5 - -package settings - -import ( - "gopkg.in/vmihailenco/msgpack.v2" -) - -type encoder = msgpack.Encoder diff --git a/settings/msgpack_helper_test.go b/settings/msgpack_helper_test.go deleted file mode 100644 index efc3285e4..000000000 --- a/settings/msgpack_helper_test.go +++ /dev/null @@ -1,22 +0,0 @@ -//go:build !go_tarantool_msgpack_v5 -// +build !go_tarantool_msgpack_v5 - -package settings_test - -import ( - "io" - - "github.com/tarantool/go-tarantool/v2" - "gopkg.in/vmihailenco/msgpack.v2" -) - -type encoder = msgpack.Encoder - -func NewEncoder(w io.Writer) *encoder { - return msgpack.NewEncoder(w) -} - -func toBoxError(i interface{}) (v tarantool.BoxError, ok bool) { - v, ok = i.(tarantool.BoxError) - return -} diff --git a/settings/msgpack_v5.go b/settings/msgpack_v5.go deleted file mode 100644 index 288418ec6..000000000 --- a/settings/msgpack_v5.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build go_tarantool_msgpack_v5 -// +build go_tarantool_msgpack_v5 - -package settings - -import ( - "github.com/vmihailenco/msgpack/v5" -) - -type encoder = msgpack.Encoder diff --git a/settings/msgpack_v5_helper_test.go b/settings/msgpack_v5_helper_test.go deleted file mode 100644 index e58651f61..000000000 --- a/settings/msgpack_v5_helper_test.go +++ /dev/null @@ -1,25 +0,0 @@ -//go:build go_tarantool_msgpack_v5 -// +build go_tarantool_msgpack_v5 - -package settings_test - -import ( - "io" - - "github.com/tarantool/go-tarantool/v2" - "github.com/vmihailenco/msgpack/v5" -) - -type encoder = msgpack.Encoder - -func NewEncoder(w io.Writer) *encoder { - return msgpack.NewEncoder(w) -} - -func toBoxError(i interface{}) (v tarantool.BoxError, ok bool) { - var ptr *tarantool.BoxError - if ptr, ok = i.(*tarantool.BoxError); ok { - v = *ptr - } - return -} diff --git a/settings/request.go b/settings/request.go index fa4e1eadd..df6dcd0ac 100644 --- a/settings/request.go +++ b/settings/request.go @@ -60,6 +60,8 @@ package settings import ( "context" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" ) @@ -89,7 +91,7 @@ func (req *SetRequest) Code() int32 { } // Body fills an encoder with set session settings request body. -func (req *SetRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req *SetRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { return req.impl.Body(res, enc) } @@ -129,7 +131,7 @@ func (req *GetRequest) Code() int32 { } // Body fills an encoder with get session settings request body. -func (req *GetRequest) Body(res tarantool.SchemaResolver, enc *encoder) error { +func (req *GetRequest) Body(res tarantool.SchemaResolver, enc *msgpack.Encoder) error { return req.impl.Body(res, enc) } diff --git a/settings/request_test.go b/settings/request_test.go index 662a7002e..7623a6cac 100644 --- a/settings/request_test.go +++ b/settings/request_test.go @@ -6,6 +6,8 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" . "github.com/tarantool/go-tarantool/v2/settings" ) @@ -68,7 +70,7 @@ func TestRequestsAPI(t *testing.T) { require.Equal(t, test.code, test.req.Code()) var reqBuf bytes.Buffer - enc := NewEncoder(&reqBuf) + enc := msgpack.NewEncoder(&reqBuf) require.Nilf(t, test.req.Body(&resolver, enc), "No errors on fill") } } diff --git a/settings/tarantool_test.go b/settings/tarantool_test.go index dc6a79825..aeec28cc0 100644 --- a/settings/tarantool_test.go +++ b/settings/tarantool_test.go @@ -89,7 +89,7 @@ func TestErrorMarshalingEnabledSetting(t *testing.T) { resp, err = conn.Eval("return box.error.new(box.error.UNKNOWN)", []interface{}{}) require.Nil(t, err) require.NotNil(t, resp) - _, ok := toBoxError(resp.Data[0]) + _, ok := resp.Data[0].(*tarantool.BoxError) require.True(t, ok) } diff --git a/stream.go b/stream.go index 3a03ec68f..5e1220dff 100644 --- a/stream.go +++ b/stream.go @@ -4,6 +4,8 @@ import ( "context" "fmt" "time" + + "github.com/vmihailenco/msgpack/v5" ) type TxnIsolationLevel uint @@ -27,7 +29,7 @@ type Stream struct { Conn *Connection } -func fillBegin(enc *encoder, txnIsolation TxnIsolationLevel, timeout time.Duration) error { +func fillBegin(enc *msgpack.Encoder, txnIsolation TxnIsolationLevel, timeout time.Duration) error { hasTimeout := timeout > 0 hasIsolationLevel := txnIsolation != DefaultIsolationLevel mapLen := 0 @@ -44,7 +46,7 @@ func fillBegin(enc *encoder, txnIsolation TxnIsolationLevel, timeout time.Durati } if hasTimeout { - err = encodeUint(enc, KeyTimeout) + err = enc.EncodeUint(KeyTimeout) if err != nil { return err } @@ -56,12 +58,12 @@ func fillBegin(enc *encoder, txnIsolation TxnIsolationLevel, timeout time.Durati } if hasIsolationLevel { - err = encodeUint(enc, KeyTxnIsolation) + err = enc.EncodeUint(KeyTxnIsolation) if err != nil { return err } - err = encodeUint(enc, uint64(txnIsolation)) + err = enc.EncodeUint(uint64(txnIsolation)) if err != nil { return err } @@ -70,11 +72,11 @@ func fillBegin(enc *encoder, txnIsolation TxnIsolationLevel, timeout time.Durati return err } -func fillCommit(enc *encoder) error { +func fillCommit(enc *msgpack.Encoder) error { return enc.EncodeMapLen(0) } -func fillRollback(enc *encoder) error { +func fillRollback(enc *msgpack.Encoder) error { return enc.EncodeMapLen(0) } @@ -108,8 +110,8 @@ func (req *BeginRequest) Timeout(timeout time.Duration) *BeginRequest { return req } -// Body fills an encoder with the begin request body. -func (req *BeginRequest) Body(res SchemaResolver, enc *encoder) error { +// Body fills an msgpack.Encoder with the begin request body. +func (req *BeginRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error { return fillBegin(enc, req.txnIsolation, req.timeout) } @@ -138,8 +140,8 @@ func NewCommitRequest() *CommitRequest { return req } -// Body fills an encoder with the commit request body. -func (req *CommitRequest) Body(res SchemaResolver, enc *encoder) error { +// Body fills an msgpack.Encoder with the commit request body. +func (req *CommitRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error { return fillCommit(enc) } @@ -168,8 +170,8 @@ func NewRollbackRequest() *RollbackRequest { return req } -// Body fills an encoder with the rollback request body. -func (req *RollbackRequest) Body(res SchemaResolver, enc *encoder) error { +// Body fills an msgpack.Encoder with the rollback request body. +func (req *RollbackRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error { return fillRollback(enc) } diff --git a/tarantool_test.go b/tarantool_test.go index 9c315b358..c663fa190 100644 --- a/tarantool_test.go +++ b/tarantool_test.go @@ -15,9 +15,10 @@ import ( "testing" "time" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/vmihailenco/msgpack/v5" - "github.com/stretchr/testify/assert" . "github.com/tarantool/go-tarantool/v2" "github.com/tarantool/go-tarantool/v2/test_helpers" ) @@ -38,20 +39,20 @@ type Member struct { Val uint } -func (m *Member) EncodeMsgpack(e *encoder) error { +func (m *Member) EncodeMsgpack(e *msgpack.Encoder) error { if err := e.EncodeArrayLen(2); err != nil { return err } if err := e.EncodeString(m.Name); err != nil { return err } - if err := encodeUint(e, uint64(m.Val)); err != nil { + if err := e.EncodeUint(uint64(m.Val)); err != nil { return err } return nil } -func (m *Member) DecodeMsgpack(d *decoder) error { +func (m *Member) DecodeMsgpack(d *msgpack.Decoder) error { var err error var l int if l, err = d.DecodeArrayLen(); err != nil { @@ -2652,7 +2653,7 @@ func (req *waitCtxRequest) Code() int32 { return NewPingRequest().Code() } -func (req *waitCtxRequest) Body(res SchemaResolver, enc *encoder) error { +func (req *waitCtxRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error { req.wg.Wait() return NewPingRequest().Body(res, enc) } diff --git a/test_helpers/main.go b/test_helpers/main.go index c6c03b00d..c234d4c02 100644 --- a/test_helpers/main.go +++ b/test_helpers/main.go @@ -373,7 +373,7 @@ func copyFile(srcFile, dstFile string) error { return nil } -// msgpack.v2 and msgpack.v5 return different uint types in responses. The +// msgpack.v5 decodes different uint types depending on value. The // function helps to unify a result. func ConvertUint64(v interface{}) (result uint64, err error) { switch v := v.(type) { diff --git a/test_helpers/msgpack.go b/test_helpers/msgpack.go deleted file mode 100644 index 1ea712b38..000000000 --- a/test_helpers/msgpack.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build !go_tarantool_msgpack_v5 -// +build !go_tarantool_msgpack_v5 - -package test_helpers - -import ( - "gopkg.in/vmihailenco/msgpack.v2" -) - -type encoder = msgpack.Encoder diff --git a/test_helpers/msgpack_v5.go b/test_helpers/msgpack_v5.go deleted file mode 100644 index 37f85ef31..000000000 --- a/test_helpers/msgpack_v5.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build go_tarantool_msgpack_v5 -// +build go_tarantool_msgpack_v5 - -package test_helpers - -import ( - "github.com/vmihailenco/msgpack/v5" -) - -type encoder = msgpack.Encoder diff --git a/test_helpers/request_mock.go b/test_helpers/request_mock.go index d668c8f52..0eaa11739 100644 --- a/test_helpers/request_mock.go +++ b/test_helpers/request_mock.go @@ -3,6 +3,8 @@ package test_helpers import ( "context" + "github.com/vmihailenco/msgpack/v5" + "github.com/tarantool/go-tarantool/v2" ) @@ -21,7 +23,7 @@ func (sr *StrangerRequest) Async() bool { return false } -func (sr *StrangerRequest) Body(resolver tarantool.SchemaResolver, enc *encoder) error { +func (sr *StrangerRequest) Body(resolver tarantool.SchemaResolver, enc *msgpack.Encoder) error { return nil } diff --git a/test_helpers/utils.go b/test_helpers/utils.go index cf17971f5..3771a5f9e 100644 --- a/test_helpers/utils.go +++ b/test_helpers/utils.go @@ -1,9 +1,7 @@ package test_helpers import ( - "bytes" "fmt" - "io" "testing" "time" @@ -230,16 +228,3 @@ func CheckEqualBoxErrors(t *testing.T, expected tarantool.BoxError, actual taran } } } - -func ExtractRequestBody(req tarantool.Request, resolver tarantool.SchemaResolver, - newEncFunc func(w io.Writer) *encoder) ([]byte, error) { - var reqBuf bytes.Buffer - reqEnc := newEncFunc(&reqBuf) - - err := req.Body(resolver, reqEnc) - if err != nil { - return nil, fmt.Errorf("An unexpected Response.Body() error: %q", err.Error()) - } - - return reqBuf.Bytes(), nil -} diff --git a/uuid/msgpack.go b/uuid/msgpack.go deleted file mode 100644 index 62504e5f9..000000000 --- a/uuid/msgpack.go +++ /dev/null @@ -1,19 +0,0 @@ -//go:build !go_tarantool_msgpack_v5 -// +build !go_tarantool_msgpack_v5 - -package uuid - -import ( - "reflect" - - "github.com/google/uuid" - "gopkg.in/vmihailenco/msgpack.v2" -) - -type encoder = msgpack.Encoder -type decoder = msgpack.Decoder - -func init() { - msgpack.Register(reflect.TypeOf((*uuid.UUID)(nil)).Elem(), encodeUUID, decodeUUID) - msgpack.RegisterExt(UUID_extId, (*uuid.UUID)(nil)) -} diff --git a/uuid/msgpack_helper_test.go b/uuid/msgpack_helper_test.go deleted file mode 100644 index d5a1cb70e..000000000 --- a/uuid/msgpack_helper_test.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build !go_tarantool_msgpack_v5 -// +build !go_tarantool_msgpack_v5 - -package uuid_test - -import ( - "gopkg.in/vmihailenco/msgpack.v2" -) - -type decoder = msgpack.Decoder diff --git a/uuid/msgpack_v5.go b/uuid/msgpack_v5.go deleted file mode 100644 index 951c437dd..000000000 --- a/uuid/msgpack_v5.go +++ /dev/null @@ -1,27 +0,0 @@ -//go:build go_tarantool_msgpack_v5 -// +build go_tarantool_msgpack_v5 - -package uuid - -import ( - "reflect" - - "github.com/google/uuid" - "github.com/vmihailenco/msgpack/v5" -) - -type encoder = msgpack.Encoder -type decoder = msgpack.Decoder - -func init() { - msgpack.Register(reflect.TypeOf((*uuid.UUID)(nil)).Elem(), encodeUUID, decodeUUID) - msgpack.RegisterExtEncoder(UUID_extId, uuid.UUID{}, - func(e *msgpack.Encoder, v reflect.Value) ([]byte, error) { - uuid := v.Interface().(uuid.UUID) - return uuid.MarshalBinary() - }) - msgpack.RegisterExtDecoder(UUID_extId, uuid.UUID{}, - func(d *msgpack.Decoder, v reflect.Value, extLen int) error { - return decodeUUID(d, v) - }) -} diff --git a/uuid/msgpack_v5_helper_test.go b/uuid/msgpack_v5_helper_test.go deleted file mode 100644 index c2356ef1a..000000000 --- a/uuid/msgpack_v5_helper_test.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build go_tarantool_msgpack_v5 -// +build go_tarantool_msgpack_v5 - -package uuid_test - -import ( - "github.com/vmihailenco/msgpack/v5" -) - -type decoder = msgpack.Decoder diff --git a/uuid/uuid.go b/uuid/uuid.go index a72785c0e..262335646 100644 --- a/uuid/uuid.go +++ b/uuid/uuid.go @@ -18,12 +18,13 @@ import ( "reflect" "github.com/google/uuid" + "github.com/vmihailenco/msgpack/v5" ) // UUID external type. const UUID_extId = 2 -func encodeUUID(e *encoder, v reflect.Value) error { +func encodeUUID(e *msgpack.Encoder, v reflect.Value) error { id := v.Interface().(uuid.UUID) bytes, err := id.MarshalBinary() @@ -33,13 +34,13 @@ func encodeUUID(e *encoder, v reflect.Value) error { _, err = e.Writer().Write(bytes) if err != nil { - return fmt.Errorf("msgpack: can't write bytes to encoder writer: %w", err) + return fmt.Errorf("msgpack: can't write bytes to msgpack.Encoder writer: %w", err) } return nil } -func decodeUUID(d *decoder, v reflect.Value) error { +func decodeUUID(d *msgpack.Decoder, v reflect.Value) error { var bytesCount int = 16 bytes := make([]byte, bytesCount) @@ -59,3 +60,16 @@ func decodeUUID(d *decoder, v reflect.Value) error { v.Set(reflect.ValueOf(id)) return nil } + +func init() { + msgpack.Register(reflect.TypeOf((*uuid.UUID)(nil)).Elem(), encodeUUID, decodeUUID) + msgpack.RegisterExtEncoder(UUID_extId, uuid.UUID{}, + func(e *msgpack.Encoder, v reflect.Value) ([]byte, error) { + uuid := v.Interface().(uuid.UUID) + return uuid.MarshalBinary() + }) + msgpack.RegisterExtDecoder(UUID_extId, uuid.UUID{}, + func(d *msgpack.Decoder, v reflect.Value, extLen int) error { + return decodeUUID(d, v) + }) +} diff --git a/uuid/uuid_test.go b/uuid/uuid_test.go index a000f99cc..f09caf03d 100644 --- a/uuid/uuid_test.go +++ b/uuid/uuid_test.go @@ -8,6 +8,8 @@ import ( "time" "github.com/google/uuid" + "github.com/vmihailenco/msgpack/v5" + . "github.com/tarantool/go-tarantool/v2" "github.com/tarantool/go-tarantool/v2/test_helpers" _ "github.com/tarantool/go-tarantool/v2/uuid" @@ -32,7 +34,7 @@ type TupleUUID struct { id uuid.UUID } -func (t *TupleUUID) DecodeMsgpack(d *decoder) error { +func (t *TupleUUID) DecodeMsgpack(d *msgpack.Decoder) error { var err error var l int if l, err = d.DecodeArrayLen(); err != nil { diff --git a/watch.go b/watch.go index 61631657c..bf045de4b 100644 --- a/watch.go +++ b/watch.go @@ -2,6 +2,8 @@ package tarantool import ( "context" + + "github.com/vmihailenco/msgpack/v5" ) // BroadcastRequest helps to send broadcast messages. See: @@ -37,8 +39,8 @@ func (req *BroadcastRequest) Code() int32 { return req.call.Code() } -// Body fills an encoder with the broadcast request body. -func (req *BroadcastRequest) Body(res SchemaResolver, enc *encoder) error { +// Body fills an msgpack.Encoder with the broadcast request body. +func (req *BroadcastRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error { return req.call.Body(res, enc) } @@ -70,12 +72,12 @@ func newWatchRequest(key string) *watchRequest { return req } -// Body fills an encoder with the watch request body. -func (req *watchRequest) Body(res SchemaResolver, enc *encoder) error { +// Body fills an msgpack.Encoder with the watch request body. +func (req *watchRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error { if err := enc.EncodeMapLen(1); err != nil { return err } - if err := encodeUint(enc, KeyEvent); err != nil { + if err := enc.EncodeUint(KeyEvent); err != nil { return err } return enc.EncodeString(req.key) @@ -104,12 +106,12 @@ func newUnwatchRequest(key string) *unwatchRequest { return req } -// Body fills an encoder with the unwatch request body. -func (req *unwatchRequest) Body(res SchemaResolver, enc *encoder) error { +// Body fills an msgpack.Encoder with the unwatch request body. +func (req *unwatchRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error { if err := enc.EncodeMapLen(1); err != nil { return err } - if err := encodeUint(enc, KeyEvent); err != nil { + if err := enc.EncodeUint(KeyEvent); err != nil { return err } return enc.EncodeString(req.key)