Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/simple_plugin/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ require (
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect
github.com/spf13/cobra v1.10.2 // indirect
github.com/spf13/pflag v1.0.9 // indirect
github.com/stoewer/go-strcase v1.3.1 // indirect
github.com/stretchr/testify v1.12.1 // indirect
github.com/thoas/go-funk v0.9.3 // indirect
github.com/zeebo/xxh3 v1.1.0 // indirect
Expand Down
7 changes: 7 additions & 0 deletions examples/simple_plugin/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ github.com/cloudquery/plugin-sdk/v2 v2.7.0 h1:hRXsdEiaOxJtsn/wZMFQC9/jPfU1MeMK3K
github.com/cloudquery/plugin-sdk/v2 v2.7.0/go.mod h1:pAX6ojIW99b/Vg4CkhnsGkRIzNaVEceYMR+Bdit73ug=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=
Expand Down Expand Up @@ -148,8 +149,13 @@ github.com/spkg/bom v0.0.0-20160624110644-59b7046e48ad/go.mod h1:qLr4V1qq6nMqFKk
github.com/stoewer/go-strcase v1.3.1 h1:iS0MdW+kVTxgMoE1LAZyMiYJFKlOzLooE4MxjirtkAs=
github.com/stoewer/go-strcase v1.3.1/go.mod h1:fAH5hQ5pehh+j3nZfvwdk2RgEgQjAoM8wodgtPmh1xo=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/thoas/go-funk v0.9.3 h1:7+nAEx3kn5ZJcnDm2Bh23N2yOtweO14bi//dvRtgLpw=
Expand Down Expand Up @@ -232,5 +238,6 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EV
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
55 changes: 55 additions & 0 deletions internal/batch/negative_bytes_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package batch

import (
"testing"

"github.com/apache/arrow-go/v18/arrow"
"github.com/apache/arrow-go/v18/arrow/array"
"github.com/apache/arrow-go/v18/arrow/memory"
"github.com/apache/arrow-go/v18/arrow/util"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func boolRecord(t *testing.T, rows int) arrow.RecordBatch {
t.Helper()

sc := arrow.NewSchema([]arrow.Field{{Name: "b", Type: arrow.FixedWidthTypes.Boolean}}, nil)
builder := array.NewRecordBuilder(memory.DefaultAllocator, sc)
defer builder.Release()

for range rows {
builder.Field(0).(*array.BooleanBuilder).Append(true)
}
return builder.NewRecordBatch()
}

func TestSlicedRecordBytesNeverNegative(t *testing.T) {
const rows = 20000
record := boolRecord(t, rows)
t.Logf("real size: %d bytes for %d rows", util.TotalRecordSize(record), record.NumRows())

limit := CappedAt(18000, 0)
limit.bytes.current = 4000

add, toFlush, rest := SliceRecord(record, limit)

require.NotNil(t, add)
assert.GreaterOrEqual(t, add.Bytes, int64(0), "add.Bytes must not be negative")
if rest != nil {
t.Logf("rest: %d rows, %d bytes", rest.NumRows(), rest.Bytes)
assert.GreaterOrEqual(t, rest.Bytes, int64(0), "rest.Bytes must not be negative")
}

var total int64
if add != nil {
total += add.NumRows()
}
for _, r := range toFlush {
total += r.NumRows()
}
if rest != nil {
total += rest.NumRows()
}
assert.Equal(t, int64(rows), total, "no rows may be lost")
}
26 changes: 23 additions & 3 deletions internal/batch/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ func (s *SlicedRecord) getAdd(limit *Cap) *SlicedRecord {
bytesPerRow: s.bytesPerRow,
}
s.RecordBatch = s.NewSlice(rows, s.NumRows())
s.Bytes -= res.Bytes
s.Bytes = max(s.Bytes-res.Bytes, 0)
return &res
}

Expand All @@ -84,7 +84,10 @@ func (s *SlicedRecord) getToFlush(limit *Cap) []arrow.RecordBatch {
case rows == 0:
// not even a single row fits
// we still need to process this, so slice by single row
return s.slice()
res := s.slice()
s.RecordBatch = nil
s.Bytes = 0
return res
case rows < 0:
// as s.Record != nil we know that the limits are there in place & the s.Record.NumRows() > 0
panic("should never be here")
Expand Down Expand Up @@ -129,7 +132,7 @@ func newSlicedRecord(r arrow.RecordBatch) *SlicedRecord {
RecordBatch: r,
Bytes: util.TotalRecordSize(r),
}
res.bytesPerRow = res.Bytes / r.NumRows()
res.bytesPerRow = max(res.Bytes/r.NumRows(), 1)
return &res
}

Expand All @@ -143,3 +146,20 @@ func SliceRecord(r arrow.RecordBatch, limit *Cap) (add *SlicedRecord, flush []ar
l := *limit // copy value
return newSlicedRecord(r).split(&l)
}

func SplitRecord(r arrow.RecordBatch, limit *Cap) []arrow.RecordBatch {
if r.NumRows() == 0 {
return []arrow.RecordBatch{r}
}

add, toFlush, rest := SliceRecord(r, limit)
records := make([]arrow.RecordBatch, 0, len(toFlush)+2)
if add != nil {
records = append(records, add.RecordBatch)
}
records = append(records, toFlush...)
if rest != nil {
records = append(records, rest.RecordBatch)
}
return records
}
78 changes: 78 additions & 0 deletions internal/batch/split_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package batch

import (
"testing"
"time"

"github.com/apache/arrow-go/v18/arrow"
"github.com/apache/arrow-go/v18/arrow/util"
"github.com/cloudquery/plugin-sdk/v4/schema"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func testRecord(t *testing.T, rows int) arrow.RecordBatch {
t.Helper()

table := schema.TestTable("test_table", schema.TestSourceOptions{})
return schema.NewTestDataGenerator(0).Generate(table, schema.GenTestDataOptions{
MaxRows: rows,
SourceName: "test",
SyncTime: time.Now(),
})
}

func totalRows(records []arrow.RecordBatch) int64 {
var rows int64
for _, record := range records {
rows += record.NumRows()
}
return rows
}

func TestSplitRecord(t *testing.T) {
const rows = 20
record := testRecord(t, rows)
bytesPerRow := util.TotalRecordSize(record) / record.NumRows()

t.Run("no limit", func(t *testing.T) {
records := SplitRecord(record, CappedAt(0, 0))
require.Len(t, records, 1)
assert.Equal(t, int64(rows), records[0].NumRows())
})

t.Run("limit above record size", func(t *testing.T) {
records := SplitRecord(record, CappedAt(0, 2*rows))
require.Len(t, records, 1)
assert.Equal(t, int64(rows), records[0].NumRows())
})

t.Run("rows limit", func(t *testing.T) {
records := SplitRecord(record, CappedAt(0, 6))
assert.Equal(t, int64(rows), totalRows(records))
for _, r := range records {
assert.LessOrEqual(t, r.NumRows(), int64(6))
}
})

t.Run("bytes limit", func(t *testing.T) {
records := SplitRecord(record, CappedAt(5*bytesPerRow, 0))
assert.Equal(t, int64(rows), totalRows(records))
for _, r := range records {
assert.LessOrEqual(t, r.NumRows(), int64(5))
}
})

t.Run("no single row fits", func(t *testing.T) {
records := SplitRecord(record, CappedAt(1, 0))
assert.Len(t, records, int(record.NumRows()), "each row gets a record of its own")
assert.Equal(t, record.NumRows(), totalRows(records))
})

t.Run("empty record", func(t *testing.T) {
empty := testRecord(t, 0)
records := SplitRecord(empty, CappedAt(1, 1))
require.Len(t, records, 1)
assert.Equal(t, int64(0), records[0].NumRows())
})
}
85 changes: 73 additions & 12 deletions internal/servers/plugin/v3/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (

"github.com/apache/arrow-go/v18/arrow"
pb "github.com/cloudquery/plugin-pb-go/pb/plugin/v3"
"github.com/cloudquery/plugin-sdk/v4/internal/batch"
"github.com/cloudquery/plugin-sdk/v4/message"
"github.com/cloudquery/plugin-sdk/v4/plugin"
"github.com/cloudquery/plugin-sdk/v4/schema"
Expand All @@ -28,6 +29,15 @@ type Server struct {
Plugin *plugin.Plugin
Logger zerolog.Logger
Directory string

MaxMsgSize int
}

func (s *Server) maxMsgSize() int {
if s.MaxMsgSize > 0 {
return s.MaxMsgSize
}
return MaxMsgSize
}

func (s *Server) GetTables(ctx context.Context, req *pb.GetTables_Request) (*pb.GetTables_Response, error) {
Expand Down Expand Up @@ -215,15 +225,10 @@ func (s *Server) Sync(req *pb.Sync_Request, stream pb.Plugin_SyncServer) error {
}

case *message.SyncInsert:
recordBytes, err := pb.RecordToBytes(m.Record)
if err != nil {
return status.Errorf(codes.Internal, "failed to encode record: %v", err)
}
pbMsg.Message = &pb.Sync_Response_Insert{
Insert: &pb.Sync_MessageInsert{
Record: recordBytes,
},
if err := s.sendInsert(stream, m.Record); err != nil {
return err
}
continue
case *message.SyncDeleteRecord:
whereClause := make([]*pb.PredicatesGroup, len(m.WhereClause))
for j, predicateGroup := range m.WhereClause {
Expand Down Expand Up @@ -273,10 +278,8 @@ func (s *Server) Sync(req *pb.Sync_Request, stream pb.Plugin_SyncServer) error {
return status.Errorf(codes.Internal, "unknown message type: %T", msg)
}

size := proto.Size(pbMsg)
if size > MaxMsgSize {
s.Logger.Error().Int("bytes", size).Msg("Message exceeds max size")
continue
if size := proto.Size(pbMsg); size > s.maxMsgSize() {
return status.Errorf(codes.Internal, "message of type %T exceeds max message size: %d bytes > %d bytes", msg, size, s.maxMsgSize())
}
if err := stream.Send(pbMsg); err != nil {
return status.Errorf(codes.Internal, "failed to send message: %v", err)
Expand All @@ -290,6 +293,64 @@ func (s *Server) Sync(req *pb.Sync_Request, stream pb.Plugin_SyncServer) error {
return syncErr
}

func (s *Server) sendInsert(stream pb.Plugin_SyncServer, record arrow.RecordBatch) error {
maxMsgSize := s.maxMsgSize()
pending := []arrow.RecordBatch{record}
for len(pending) > 0 {
current := pending[0]
pending = pending[1:]

recordBytes, err := pb.RecordToBytes(current)
if err != nil {
return status.Errorf(codes.Internal, "failed to encode record for table %q: %v", recordTableName(current), err)
}
pbMsg := &pb.Sync_Response{
Message: &pb.Sync_Response_Insert{
Insert: &pb.Sync_MessageInsert{
Record: recordBytes,
},
},
}

size := proto.Size(pbMsg)
if size <= maxMsgSize {
if err := stream.Send(pbMsg); err != nil {
return status.Errorf(codes.Internal, "failed to send message: %v", err)
}
continue
}

tableName := recordTableName(current)
if current.NumRows() <= 1 {
return status.Errorf(codes.Internal, "table %q: single row exceeds max message size: %d bytes > %d bytes", tableName, size, maxMsgSize)
}

rowsPerMessage := maxRowsPerMessage(size, current.NumRows(), maxMsgSize)
s.Logger.Warn().
Str("table", tableName).
Int("bytes", size).
Int64("rows", current.NumRows()).
Int64("rows_per_message", rowsPerMessage).
Msg("Message exceeds max size, splitting into smaller messages")
pending = append(batch.SplitRecord(current, batch.CappedAt(0, rowsPerMessage)), pending...)
}

return nil
}

func maxRowsPerMessage(size int, rows int64, maxMsgSize int) int64 {
perMessage := rows * int64(maxMsgSize) * 9 / (int64(size) * 10)
if perMessage >= rows {
perMessage = rows / 2
}
return max(perMessage, 1)
}

func recordTableName(record arrow.RecordBatch) string {
name, _ := record.Schema().Metadata().GetValue(schema.MetadataTableName)
return name
}

func (s *Server) Write(stream pb.Plugin_WriteServer) error {
msgs := make(chan message.WriteMessage)
ctx := stream.Context()
Expand Down
Loading
Loading