JackieTien97 commented on code in PR #179:
URL: https://github.com/apache/iotdb-client-go/pull/179#discussion_r4625003981


##########
client/protocol.go:
##########
@@ -113,127 +113,236 @@ const (
 )
 
 // TSStatusCode
+// The names and values follow the current Java TSStatusCode definition. Legacy

Review Comment:
   The PR description already calls this out as an intentional API change. Two 
observations that may still be useful:
   
   - The change covers the whole v2 status-code table, not just subscription. 
Against `main`, this file adds 205 constants, of which 31 relate to 
subscription, topics or consumers; the rest include stream, LBAC policy/label, 
TOTP and IoTConsensusV2 codes. It also removes 3 constants and renumbers 4.
   - Six old values now belong to different names: 1000 
(`DatanodeAlreadyRegistered` → `AddConfignodeError`), 1001 (`NoEnoughDatanode` 
→ `RemoveConfignodeError`), 1002 (`AddConfignodeError` → `RejectNodeStart`), 
1003 (`RemoveConfignodeError` → `NoEnoughDatanode`), 1007 
(`RegisterRemovedDatanode` → `CanNotConnectDatanode`) and 1008 
(`CanNotConnectDatanode` → `TransferLeaderError`). The renumbering corrects the 
mapping, but callers that compare against these names change behavior without a 
compile error, so the release notes should list these values explicitly.
   
   Consider landing the status-code alignment as its own PR, together with the 
new Tablet decoding API. That lets it be reviewed and released independently of 
subscription, and it unblocks the `subscription/go.mod` bump described in the 
comment on that file.



##########
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:
   **Downstream users cannot build this module as released.** This `require` 
pins `github.com/apache/iotdb-client-go/v2` to `a25f68a`, the current `main` 
before this PR. Inside the repository, `replace 
github.com/apache/iotdb-client-go/v2 => ..` hides that, but `replace` only 
applies in the main module. A user who runs `go get 
github.com/apache/iotdb-client-go/subscription@latest` (README L35) therefore 
gets v2 at `a25f68a`.
   
   I checked this with a separate module that replaces only `subscription` with 
a local checkout, so v2 is resolved from the module proxy the way it would be 
for a user:
   - At `a53f30e`, the build fails with `undefined: 
client.SubscriptionPollError`, `client.SubscriptionHandshakeError` and the 
other subscription status constants this PR adds to `client/protocol.go`.
   - At `aeaa5d4`, `internal/record` also fails on the new `Tablet` methods 
(`GetTargetName`, `GetTimestampAt`, `ColumnCount`, `ColumnName`, 
`ColumnDataType`, `ColumnCategory`). `client.DecodeTablet` and 
`client.NewDecodedTablet` are also new in this PR, so they are missing from 
that version as well.
   
   A user can work around this by upgrading v2 separately, but `go get` of the 
subscription module alone produces a build that fails. Since the module now 
depends on unreleased v2 APIs, it needs a two-step release: merge the v2 
changes first, then bump this `require` to a v2 version that contains them 
before the subscription module is tagged or announced. One way to do that is to 
move the v2 changes (status codes and the Tablet decoding API) into a separate 
PR that lands first. This PR can then require the merged commit.



##########
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:
   `go vet` reports `stdmethods` here: `method ReadByte() int8 should have 
signature ReadByte() (byte, error)`. The same check fires twice in 
`subscription/internal/wire/codec.go`, for `WriteByte(int8)` at L42 and 
`ReadByte() int8` at L205. `go vet ./client/` is clean on `main`, so this would 
be the first vet warning in the main module. CI doesn't run `go vet`, so 
nothing fails today. Renaming the methods to `ReadInt8`/`WriteInt8` fixes all 
three.



##########
subscription/consumer/provider.go:
##########
@@ -0,0 +1,498 @@
+/*
+ * 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 consumer
+
+import (
+       "github.com/apache/iotdb-client-go/subscription"
+       "github.com/apache/iotdb-client-go/subscription/payload"
+       "github.com/apache/iotdb-client-go/subscription/internal/protocol"
+       "github.com/apache/iotdb-client-go/subscription/internal/rpcsession"
+       "github.com/apache/iotdb-client-go/subscription/internal/wire"
+
+       "context"
+       "errors"
+       "strconv"
+       "strings"
+       "sync/atomic"
+
+       "github.com/apache/thrift/lib/go/thrift"
+
+       "github.com/apache/iotdb-client-go/v2/client"
+       "github.com/apache/iotdb-client-go/v2/common"
+       "github.com/apache/iotdb-client-go/v2/rpc"
+)
+
+const (
+       subscriptionFrameReserve = 1024
+       // Oversized-entry status is returned by servers that enforce 
subscription
+       // materialization limits. Keep the compatibility value local to the 
consumer.
+       subscriptionOversizedEntryStatus int32 = 1920

Review Comment:
   Re-tested at `aeaa5d4` with the same fake-server probe. When the server 
answers POLL with 1920, `Poll` now returns no messages and a nil error. The 
next `Poll` re-handshakes on a new connection (handshakes 1 → 2) and keeps 
polling without errors. In the code, `commitNode` still retries on 1920. This 
matches Java. Thanks for the fix.



##########
subscription/consumer/push_consumer.go:
##########
@@ -0,0 +1,455 @@
+/*
+ * 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 consumer
+
+import (
+       "github.com/apache/iotdb-client-go/subscription"
+       "github.com/apache/iotdb-client-go/subscription/payload"
+       "github.com/apache/iotdb-client-go/subscription/internal/protocol"
+       "github.com/apache/iotdb-client-go/subscription/internal/record"
+       "github.com/apache/iotdb-client-go/subscription/internal/identifier"
+
+       "context"
+       "errors"
+       "fmt"
+       "sync"
+       "time"
+)
+
+// NewSubscriptionPushConsumer copies and validates config without connecting.
+// Handler is required. Open starts sequential background delivery with the
+// configured acknowledgment strategy; its context limits opening only.
+// Close cancels delivery and closes connections without waiting for an active
+// Handler. Its message remains valid until that Handler returns.
+func NewSubscriptionPushConsumer(config SubscriptionPushConsumerConfig) 
(SubscriptionPushConsumer, error) {
+       resolved, err := normalizeSubscriptionPushConsumerConfig(config)
+       if err != nil {
+               return nil, err
+       }
+       autoCommit := false
+       consumer, err := 
newSubscriptionPullConsumer(SubscriptionPullConsumerConfig{
+               Consumer: resolved.Consumer,
+               AutoCommit: &autoCommit,
+               AutoCommitInterval: 
DefaultSubscriptionPullConsumerConfig().AutoCommitInterval,
+       })
+       if err != nil {
+               return nil, err
+       }
+       return &subscriptionPushConsumer{
+               config: resolved,
+               consumer: consumer,
+               operations: make(chan struct{}, 1),
+               generations: make(map[string]uint64),
+               errors: make(chan error, 1),
+       }, nil
+}
+
+type subscriptionPushConsumer struct {
+       config SubscriptionPushConsumerConfig
+       consumer *subscriptionPullConsumer
+       operations chan struct{}
+       mu sync.Mutex
+       generations map[string]uint64
+       started bool
+       closed bool
+       terminal error
+       deliveryCancel context.CancelFunc
+       callbackTopic string
+       callbackCancel context.CancelFunc
+       errors chan error
+       errorsClosed sync.Once
+}
+
+type subscriptionPushDelivery struct {
+       message payload.SubscriptionMessage
+       generation uint64
+}
+
+func (c *subscriptionPushConsumer) Open(ctx context.Context) error {
+       if ctx == nil {
+               return errors.New("subscription: context must not be nil")
+       }
+       if err := ctx.Err(); err != nil {
+               return err
+       }
+       c.mu.Lock()
+       err := c.deliveryStateLocked()
+       c.mu.Unlock()
+       if err != nil {
+               return err
+       }
+       if err := c.consumer.Open(ctx); err != nil {
+               return err
+       }
+       c.mu.Lock()
+       if err := c.deliveryStateLocked(); err != nil {
+               c.mu.Unlock()
+               return err
+       }
+       if c.started {
+               c.mu.Unlock()
+               return nil
+       }
+       c.consumer.mu.RLock()
+       lifeCtx := c.consumer.lifeCtx
+       c.consumer.mu.RUnlock()
+       deliveryCtx, cancel := context.WithCancel(lifeCtx)
+       c.deliveryCancel = cancel
+       c.started = true
+       c.mu.Unlock()
+       go c.runDelivery(deliveryCtx)
+       return nil
+}
+
+func (c *subscriptionPushConsumer) Close() error {
+       c.mu.Lock()
+       if c.closed {
+               c.mu.Unlock()
+               return nil
+       }
+       c.closed = true
+       if c.deliveryCancel != nil {
+               c.deliveryCancel()
+       }
+       started := c.started
+       c.mu.Unlock()
+       // The loop is not a core worker: a Handler may close its own consumer.
+       // It retains ownership of its messages until the Handler has returned.
+       err := c.consumer.Close()
+       if !started {
+               c.closeErrors()
+       }
+       return err
+}
+
+func (c *subscriptionPushConsumer) Errors() <-chan error {
+       return c.errors
+}
+
+func (c *subscriptionPushConsumer) Info() SubscriptionConsumerInfo {
+       return c.consumer.Info()
+}
+
+func (c *subscriptionPushConsumer) LatestWatermark() (int64, bool) {
+       return c.consumer.LatestWatermark()
+}
+
+func (c *subscriptionPushConsumer) AllConsumed() bool {
+       return c.consumer.AllConsumed()
+}
+
+func (c *subscriptionPushConsumer) Subscribe(ctx context.Context, topics 
...string) error {
+       return c.consumer.Subscribe(ctx, topics...)
+}
+
+func (c *subscriptionPushConsumer) Unsubscribe(ctx context.Context, topics 
...string) error {
+       return c.consumer.Unsubscribe(ctx, topics...)
+}
+
+func (c *subscriptionPushConsumer) Positions(topic string) 
(payload.TopicProgress, error) {
+       return c.consumer.Positions(topic)
+}
+
+func (c *subscriptionPushConsumer) CommittedPositions(topic string) 
(payload.TopicProgress, error) {
+       return c.consumer.CommittedPositions(topic)
+}
+
+func (c *subscriptionPushConsumer) SeekToBeginning(ctx context.Context, topic 
string) error {
+       return c.seek(ctx, topic, protocol.SeekBeginning, nil)
+}
+
+func (c *subscriptionPushConsumer) SeekToEnd(ctx context.Context, topic 
string) error {
+       return c.seek(ctx, topic, protocol.SeekEnd, nil)
+}
+
+func (c *subscriptionPushConsumer) Seek(ctx context.Context, topic string, 
progress payload.TopicProgress) error {
+       return c.seek(ctx, topic, protocol.SeekProgress, progress)
+}
+
+func (c *subscriptionPushConsumer) SeekAfter(ctx context.Context, topic 
string, progress payload.TopicProgress) error {
+       return c.seek(ctx, topic, protocol.SeekAfterProgress, progress)
+}
+
+func (c *subscriptionPushConsumer) seek(ctx context.Context, topic string, 
kind int16, progress payload.TopicProgress) error {
+       name, err := identifier.Parse(topic)
+       if err != nil {
+               return err
+       }
+       if err := c.acquireOperations(ctx); err != nil {
+               return err
+       }
+       defer c.releaseOperations()
+       if err := c.consumer.checkOpen(); err != nil {
+               return err
+       }
+       if err := ctx.Err(); err != nil {
+               return err
+       }
+       c.mu.Lock()
+       if c.closed {
+               c.mu.Unlock()
+               return subscription.ErrClosed
+       }
+       // Even a failed multi-provider seek can change server state. Never 
confirm
+       // or start another callback for an older delivery of the affected 
topic.
+       c.generations[name]++
+       var cancelCallback context.CancelFunc
+       if c.callbackTopic == name {
+               cancelCallback = c.callbackCancel
+       }
+       c.mu.Unlock()
+       // Keep a callback's context usable for a seek invoked from that 
callback.
+       // Cancel the obsolete delivery after the request completes instead.
+       if cancelCallback != nil {
+               defer cancelCallback()
+       }
+       return c.consumer.seekProgress(ctx, topic, kind, progress)
+}
+
+func (c *subscriptionPushConsumer) acquireOperations(ctx context.Context) 
error {
+       if ctx == nil {
+               return errors.New("subscription: context must not be nil")
+       }
+       if err := ctx.Err(); err != nil {
+               return err
+       }
+       select {
+       case c.operations <- struct{}{}:
+               return nil
+       case <-ctx.Done():
+               return ctx.Err()
+       }
+}
+
+func (c *subscriptionPushConsumer) releaseOperations() {
+       <-c.operations
+}
+
+func (c *subscriptionPushConsumer) deliveryStateLocked() error {
+       if c.closed {
+               return subscription.ErrClosed
+       }
+       return c.terminal
+}
+
+func (c *subscriptionPushConsumer) pollDeliveries(ctx context.Context) 
([]subscriptionPushDelivery, error) {
+       if err := c.acquireOperations(ctx); err != nil {
+               return nil, err
+       }
+       defer c.releaseOperations()
+       c.mu.Lock()
+       err := c.deliveryStateLocked()
+       c.mu.Unlock()
+       if err != nil {
+               return nil, err
+       }
+       messages, err := c.consumer.Poll(ctx, c.config.PollTimeout)
+       if err != nil {
+               return nil, err
+       }
+       c.mu.Lock()
+       defer c.mu.Unlock()
+       if err := c.deliveryStateLocked(); err != nil {
+               for _, message := range messages {
+                       message.Release()
+               }
+               return nil, err
+       }
+       deliveries := make([]subscriptionPushDelivery, 0, len(messages))
+       for _, message := range messages {
+               deliveries = append(deliveries, subscriptionPushDelivery{
+                       message: message,
+                       generation: 
c.generations[record.ReadCommitContext(message).Topic],
+               })
+       }
+       return deliveries, nil
+}
+
+func (c *subscriptionPushConsumer) runDelivery(ctx context.Context) {
+       var terminal error
+       defer func() { c.finishDelivery(terminal) }()
+       for {
+               if err := ctx.Err(); err != nil {
+                       terminal = c.terminalDeliveryError(err)
+                       return
+               }
+               deliveries, err := c.pollDeliveries(ctx)
+               if err == nil {
+                       err = c.deliver(ctx, deliveries)
+               }
+               if err != nil {
+                       terminal = c.terminalDeliveryError(err)
+                       if terminal != nil || ctx.Err() != nil {
+                               return
+                       }
+               }
+               // Wait after the entire round, including callbacks and 
acknowledgment.
+               // A slow round therefore never overlaps the next round.
+               timer := time.NewTimer(c.config.PollInterval)
+               select {
+               case <-ctx.Done():
+                       timer.Stop()
+                       terminal = c.terminalDeliveryError(ctx.Err())
+                       return
+               case <-timer.C:
+               }
+       }
+}
+
+func (c *subscriptionPushConsumer) deliver(ctx context.Context, deliveries 
[]subscriptionPushDelivery) error {
+       defer func() {
+               for _, delivery := range deliveries {
+                       delivery.message.Release()
+               }
+       }()
+       if c.config.AckStrategy == AckBeforeConsume {
+               if err := c.commitDeliveries(ctx, deliveries, false); err != 
nil {
+                       return err
+               }
+       }
+       var succeeded, failed []subscriptionPushDelivery
+       for _, delivery := range deliveries {
+               if err := ctx.Err(); err != nil {
+                       return err
+               }
+               callbackCtx, finish, current := c.beginCallback(ctx, delivery)
+               if !current {
+                       continue
+               }
+               err := c.invokeHandler(callbackCtx, delivery.message)
+               finish()
+               delivery.message.Release()
+               if err == nil {
+                       succeeded = append(succeeded, delivery)
+               } else {
+                       failed = append(failed, delivery)
+               }
+       }
+       if c.config.AckStrategy == AckBeforeConsume {
+               return nil
+       }
+       // Java confirms successful callbacks before nacking failures. An ACK 
error
+       // leaves the failed group unconfirmed for server-side recovery.
+       if err := c.commitDeliveries(ctx, succeeded, false); err != nil {
+               return err
+       }
+       return c.commitDeliveries(ctx, failed, true)
+}
+
+func (c *subscriptionPushConsumer) beginCallback(ctx context.Context, delivery 
subscriptionPushDelivery) (context.Context, func(), bool) {
+       topic := record.ReadCommitContext(delivery.message).Topic
+       c.mu.Lock()
+       defer c.mu.Unlock()
+       if c.deliveryStateLocked() != nil || ctx.Err() != nil || 
c.generations[topic] != delivery.generation {
+               return nil, nil, false
+       }
+       callbackCtx, cancel := context.WithCancel(ctx)
+       c.callbackTopic = topic
+       c.callbackCancel = cancel
+       return callbackCtx, func() {
+               cancel()
+               c.mu.Lock()
+               c.callbackTopic = ""
+               c.callbackCancel = nil
+               c.mu.Unlock()
+       }, true
+}
+
+func (c *subscriptionPushConsumer) invokeHandler(ctx context.Context, message 
payload.SubscriptionMessage) (err error) {
+       defer func() {
+               if failure := recover(); failure != nil {
+                       err = fmt.Errorf("subscription: push handler panicked: 
%v", failure)
+               }
+       }()
+       return c.config.Handler(ctx, message)
+}
+
+func (c *subscriptionPushConsumer) commitDeliveries(ctx context.Context, 
deliveries []subscriptionPushDelivery, nack bool) error {
+       if len(deliveries) == 0 {
+               return nil
+       }
+       if err := c.acquireOperations(ctx); err != nil {
+               return err
+       }
+       defer c.releaseOperations()
+       c.mu.Lock()
+       if err := c.deliveryStateLocked(); err != nil {
+               c.mu.Unlock()
+               return err
+       }
+       messages := make([]payload.SubscriptionMessage, 0, len(deliveries))
+       for _, delivery := range deliveries {
+               if 
c.generations[record.ReadCommitContext(delivery.message).Topic] == 
delivery.generation {
+                       messages = append(messages, delivery.message)
+               }
+       }
+       c.mu.Unlock()
+       if len(messages) == 0 {
+               return nil
+       }
+       commitCtx, cancel := context.WithTimeout(ctx, 
c.config.Consumer.Connection.ConnectTimeout)
+       defer cancel()
+       operationCtx, finish, err := c.consumer.linkContext(commitCtx)
+       if err != nil {
+               return err
+       }
+       defer finish()
+       contexts, err := c.consumer.messageCommitContexts(messages)
+       if err != nil {
+               return err
+       }
+       return c.consumer.commitContexts(operationCtx, contexts, nack)
+}
+
+func (c *subscriptionPushConsumer) terminalDeliveryError(failure error) error {
+       c.mu.Lock()
+       closed := c.closed
+       c.mu.Unlock()
+       if closed {
+               return nil
+       }
+       if err := c.consumer.checkOpen(); err != nil {
+               return err
+       }
+       if flowFatalPollError(failure) || flowCriticalPollError(failure) {

Review Comment:
   Re-tested at `aeaa5d4`. With the first POLL answered by 1909 and later ones 
answered normally, `Errors()` reports nothing and the delivery loop keeps 
polling: 31 POLLs after 3 s, 52 two seconds later. The README (L485) and the 
`Errors()` doc comment now describe this behavior, which matches Java's 
`AutoPollWorker`. 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 `aeaa5d4`: `go test -cover ./...` under `subscription/` reports 
11.3% overall: `consumer` 0.1%, `internal/protocol` 28.8% (the Tablet decoding 
tests moved to `client`), and `processor` 79.6%. The 1920 and Push fixes came 
without regression tests, and the Apache e2e job still skips every 
`TestSubscription*` case.
   
   The fake server I used for the probes is about 150 lines: an 
`rpc.IClientRPCService` implementation that answers `PipeSubscribe`, served 
with `thrift.NewTSimpleServer4`. As a test fixture in `consumer`, it would give 
both fixes regression tests and make the error, redirect-ACK and recovery 
branches cheap to cover.



-- 
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]

Reply via email to