JackieTien97 commented on code in PR #179: URL: https://github.com/apache/iotdb-client-go/pull/179#discussion_r4637297223
########## test/e2e/subscription_tree_test.go: ########## @@ -0,0 +1,1023 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package e2e + +import ( + "context" + "errors" + "fmt" + "reflect" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/apache/iotdb-client-go/v2/subscription" + subconsumer "github.com/apache/iotdb-client-go/v2/subscription/consumer" + subpayload "github.com/apache/iotdb-client-go/v2/subscription/payload" + subsession "github.com/apache/iotdb-client-go/v2/subscription/session" + "github.com/apache/iotdb-client-go/v2/client" +) + +func subscriptionE2EContext(t *testing.T) context.Context { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), subscriptionE2ETestTimeout) + t.Cleanup(cancel) + return ctx +} + +var subscriptionE2ESequence atomic.Uint64 + +func subscriptionE2EName(prefix string) string { + return fmt.Sprintf("%s_%d_%d", prefix, time.Now().UnixNano(), subscriptionE2ESequence.Add(1)) +} + +func subscriptionE2EManager(t *testing.T, connection subscription.ConnectionConfig, dialect subscription.Dialect) subsession.SubscriptionSession { + t.Helper() + config := subsession.DefaultSubscriptionSessionConfig() + config.Connection, config.Dialect = connection, dialect + manager, err := subsession.NewSubscriptionSession(config) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := manager.Close(); err != nil { + t.Errorf("close subscription manager: %v", err) + } + }) + ctx, cancel := context.WithTimeout(context.Background(), subscriptionE2EOpenTimeout) + defer cancel() + if err := manager.Open(ctx); err != nil { + t.Fatal(err) + } + return manager +} + +func subscriptionE2ETopic(t *testing.T, ctx context.Context, manager subsession.SubscriptionSession, name string, attributes map[string]string) { + t.Helper() + if err := manager.CreateTopic(ctx, name, subsession.CreateTopicOptions{Attributes: attributes}); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + cleanupCtx, cancel := context.WithTimeout(context.Background(), subscriptionE2ECleanupTimeout) + defer cancel() + for { + err := manager.DropTopic(cleanupCtx, name, subsession.DropOptions{IfExists: true}) + if err == nil { + return + } + select { + case <-cleanupCtx.Done(): + t.Errorf("drop topic %s: %v", name, err) Review Comment: **Cleanup flake: the drop loop can give up before the server releases the consumer.** In the full E2E run at `43ee497`, `TestSubscriptionTableColumnFilterNoMatchReturnsNothing` failed only in this cleanup. For the whole `subscriptionE2ECleanupTimeout` (10 s), `DropTopic` returned `the topic is subscribed by some consumers`. Five reruns of the case passed. The DataNode log, the code and a fake-server probe point to this sequence: - The last quiet `Poll` reached its deadline before the idle server answered. `flowRemainingMilliseconds` (`pull_flow.go`) sends the client's remaining poll time as the server-side poll timeout, so the answer can arrive just after the deadline. `transport.Connection.Call` then aborts the connection. At that moment the DataNode logged only `remove consumer config ... when handling exit`. - The cleanup `Close()` ran next. `subscriptionProvider.close` returns nil without sending CLOSE when the connection is already closed. By then `Close()` has stopped the background workers, including `runEndpointSync`, which handles reconnects, so nothing reconnects to send it. - The DataNode kept the subscription until its inactivity check closed the consumer (`inactive for 14269 ms, exceeding timeout 10000 ms`), about 4 s after this loop had given up. The probe reproduces this deterministically. When the fake server holds POLL past the client deadline, a `Close()` right after `Poll` returns nil and the server never receives CLOSE. When the server answers at once, or when `Close()` comes a second later after recovery has reconnected, CLOSE arrives. Closing a Push consumer while a POLL is in flight also skips CLOSE. From reading the Java SDK, its `close()` also skips CLOSE when an RPC is still in flight, because `prepareClose()` force-closes those connections. The server's inactivity timeout is therefore the fallback in both clients. I did not run the Java client for this case. The simplest fix is in this loop: give it more time than the server-side cleanup needs, for example 30 s. That cleanup takes the consumer's `connection-timeout-ms` (10 s in these tests) plus the checker's delay, 14.3 s in this run. Optionally, `flowRemainingMilliseconds` could leave a small margin so an idle server usually answers before the client deadline. That would also avoid the reconnect and handshake that follow an aborted poll. ########## subscription/go.mod: ########## @@ -0,0 +1,10 @@ +module github.com/apache/iotdb-client-go/subscription + +go 1.25 + +require ( + github.com/apache/iotdb-client-go/v2 v2.0.0-20260914074454-a25f68aa9681 Review Comment: Fixed in `b0eab1a`. The nested `go.mod` files under `subscription/`, `example/` and `test/e2e/` are gone. The subscription packages are now `github.com/apache/iotdb-client-go/v2/subscription/...` in the root module and share its version. A separate module that imports `v2/subscription/consumer` from the `43ee497` checkout builds and runs. The README now says `go get github.com/apache/iotdb-client-go/v2@latest`. The root `go.mod` already declares `go 1.25` on `main`, so the move doesn't raise the minimum Go version. Thanks. ########## test/e2e/config_test.go: ########## @@ -0,0 +1,158 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package e2e + +import ( + "os" + "strings" + "testing" + "time" + + "github.com/apache/iotdb-client-go/subscription" + subsession "github.com/apache/iotdb-client-go/subscription/session" + "github.com/apache/iotdb-client-go/v2/client" +) + +const ( + e2eDefaultNodeURLs = "iotdb:6668,iotdb:6667,iotdb:6669" + e2eDefaultTableHost = "iotdb" + e2eDefaultTablePort = "6667" + e2eDefaultUsername = "root" + e2eDefaultPassword = "root" +) + +var ( + e2eNodeURLs = e2eDefaultValue("IOTDB_E2E_NODE_URLS", "", e2eDefaultNodeURLs) + e2eUsername = e2eDefaultValue("IOTDB_E2E_USERNAME", "IOTDB_USERNAME", e2eDefaultUsername) + e2ePassword = e2eValueOrFallback("IOTDB_E2E_PASSWORD", "IOTDB_PASSWORD", e2eDefaultPassword) +) + +// Subscription cases are discovered by the normal go test run but require an +// explicit environment opt-in. Endpoint and credential defaults come from the +// shared E2E configuration. +const ( + subscriptionE2EDefaultEnabled = false Review Comment: Status at `43ee497`: `subscription/consumer/provider_retry_test.go` adds `TestPollRetriesReplacedConnection` and `TestPushContinuesAfterCriticalPollError`, both against an in-process fake server. The 1920 and Push fixes now have regression tests. Thanks for adding them. `go test -cover ./subscription/...` now reports 21.0% overall, up from 11.3%: `consumer` is at 17.8% (was 0.1%), `internal/protocol` at 28.8%, and `processor` at 79.6%. The Apache e2e job at this head still reports all 24 `TestSubscription*` cases as `--- SKIP`, so the server-backed cases run only when `IOTDB_SUBSCRIPTION_E2E=1` is set. ########## client/tablet_decode.go: ########## @@ -0,0 +1,333 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package client + +import ( + "encoding/binary" + "fmt" + "io" + "math" + "time" +) + +// DecodeTablet decodes one serialized Tablet from the beginning of data. The +// returned byte count identifies the end of the Tablet so callers can decode +// multiple Tablets from one payload. Trailing bytes are not validated here. +func DecodeTablet(data []byte) (*Tablet, int, error) { + reader := &tabletDecoder{data: data} + tablet, err := decodeTablet(reader) + if err != nil { + return nil, 0, err + } + return tablet, len(data) - reader.Remaining(), nil +} + +func decodeTablet(reader *tabletDecoder) (*Tablet, error) { + target := reader.ReadString() + rowCount := reader.ReadInt32() + if reader.Err() != nil { + return nil, reader.Err() + } + if rowCount < 0 { + return nil, fmt.Errorf("tablet: invalid row count %d", rowCount) + } + rows := int(rowCount) + + var schemas []*MeasurementSchema + var categories []ColumnCategory + if reader.ReadBool() { + columnCount := reader.ReadCount(1) + for index := int32(0); index < columnCount && reader.Err() == nil; index++ { + hasSchema := reader.ReadBool() + if reader.Err() != nil { + return nil, reader.Err() + } + if !hasSchema { + return nil, fmt.Errorf("tablet: null schema at column %d is not supported", index) + } + schema := &MeasurementSchema{Measurement: reader.ReadString(), DataType: TSDataType(reader.ReadByte())} + // Encoding and compression describe the source representation; the + // serialized Tablet already contains uncompressed typed arrays. + reader.ReadByte() + reader.ReadByte() + properties := reader.ReadCount(8) + for property := int32(0); property < properties && reader.Err() == nil; property++ { + reader.ReadString() + reader.ReadString() + } + category := reader.ReadByte() + if reader.Err() != nil { + break + } + switch category { + case 0: + categories = append(categories, TAG) + case 1: + categories = append(categories, FIELD) + case 2: + categories = append(categories, ATTRIBUTE) + default: + return nil, fmt.Errorf("tablet: unsupported column category %d", category) + } + if _, err := tabletValueSize(schema.DataType); err != nil { + return nil, err + } + schemas = append(schemas, schema) + } + } + if reader.Err() != nil { + return nil, reader.Err() + } + + timestamps := make([]int64, rows) + if reader.ReadBool() { + if err := requireTabletValues(reader, rows, 8); err != nil { + return nil, err + } + for row := range timestamps { + timestamps[row] = reader.ReadInt64() + } + } + + nullBitmaps := make([][]byte, len(schemas)) + if reader.ReadBool() { + for column := range schemas { + if !reader.ReadBool() { + continue + } + size := reader.ReadInt32() + length := reader.ReadCount(1) + if reader.Err() != nil { + break + } + if size < rowCount || int64(length) < (int64(rowCount)+7)/8 { + return nil, fmt.Errorf("tablet: bitmap cannot represent %d rows", rowCount) + } + nullBitmaps[column] = append([]byte(nil), reader.Take(int(length))...) + } + } + if reader.Err() != nil { + return nil, reader.Err() + } + + values := make([]interface{}, len(schemas)) + if reader.ReadBool() { + for column, schema := range schemas { + if !reader.ReadBool() { + continue + } + decoded, err := decodeTabletColumn(reader, schema.DataType, rows) + if err != nil { + return nil, err + } + values[column] = decoded + } + } + if reader.Err() != nil { + return nil, reader.Err() + } + return NewDecodedTablet(target, schemas, categories, rows, timestamps, values, nullBitmaps), nil +} + +func tabletValueSize(dataType TSDataType) (int, error) { + switch dataType { + case BOOLEAN, TEXT, STRING, BLOB, OBJECT: + return 1, nil + case INT32, FLOAT, DATE: + return 4, nil + case INT64, DOUBLE, TIMESTAMP: + return 8, nil + default: + return 0, fmt.Errorf("tablet: unsupported data type %d", dataType) + } +} + +func requireTabletValues(reader *tabletDecoder, count, size int) error { + if reader.Err() != nil { + return reader.Err() + } + if count > reader.Remaining()/size { + reader.SetError(fmt.Errorf("tablet: array of %d entries exceeds remaining payload: %w", count, io.ErrUnexpectedEOF)) + return reader.Err() + } + return nil +} + +func decodeTabletColumn(reader *tabletDecoder, dataType TSDataType, rows int) (interface{}, error) { + size, err := tabletValueSize(dataType) + if err != nil { + return nil, err + } + if err := requireTabletValues(reader, rows, size); err != nil { + return nil, err + } + switch dataType { + case BOOLEAN: + values := make([]bool, rows) + for row := range values { + values[row] = reader.ReadBool() + } + return values, reader.Err() + case INT32: + values := make([]int32, rows) + for row := range values { + values[row] = reader.ReadInt32() + } + return values, reader.Err() + case INT64, TIMESTAMP: + values := make([]int64, rows) + for row := range values { + values[row] = reader.ReadInt64() + } + return values, reader.Err() + case FLOAT: + values := make([]float32, rows) + for row := range values { + values[row] = math.Float32frombits(uint32(reader.ReadInt32())) + } + return values, reader.Err() + case DOUBLE: + values := make([]float64, rows) + for row := range values { + values[row] = math.Float64frombits(uint64(reader.ReadInt64())) + } + return values, reader.Err() + case DATE: + values := make([]int32, rows) + for row := range values { + date := reader.ReadInt32() + if reader.Err() != nil { + return nil, reader.Err() + } + year, month, day := int(date/10000), time.Month((date/100)%100), int(date%100) + value := time.Date(year, month, day, 0, 0, 0, 0, time.UTC) + if value.Year() != year || value.Month() != month || value.Day() != day { + return nil, fmt.Errorf("tablet: invalid DATE value %d", date) + } + values[row] = date + } + return values, reader.Err() + case TEXT, STRING, BLOB, OBJECT: + values := make([][]byte, rows) + for row := range values { + if reader.ReadBool() { + length := reader.ReadCount(1) + values[row] = append([]byte{}, reader.Take(int(length))...) + } else { + values[row] = []byte{} + } + } + return values, reader.Err() + default: + return nil, fmt.Errorf("tablet: unsupported data type %d", dataType) + } +} + +type tabletDecoder struct { + data []byte + offset int + err error +} + +func (d *tabletDecoder) Remaining() int { + if d.err != nil || d.offset < 0 || d.offset > len(d.data) { + return 0 + } + return len(d.data) - d.offset +} + +func (d *tabletDecoder) Take(count int) []byte { + if d.err != nil { + return nil + } + if count < 0 || d.offset < 0 || d.offset > len(d.data) || count > len(d.data)-d.offset { + d.err = io.ErrUnexpectedEOF + return nil + } + value := d.data[d.offset : d.offset+count] + d.offset += count + return value +} + +func (d *tabletDecoder) ReadByte() int8 { Review Comment: Fixed in `69fdf9a`. The methods are now `ReadInt8`/`WriteInt8` in both `client/tablet_decode.go` and `subscription/internal/wire/codec.go`, and `go vet ./...` is clean for the whole module at `43ee497`. Thanks. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
