Skip to content

Commit

Permalink
fix: improve gRPC error handling and cancellation logic
Browse files Browse the repository at this point in the history
- Add error handling for gRPC stream cancellation
- Introduce status code checks for better error management
- Refactor block fetching logic to include cancellation checks
- Clean up redundant error handling code in the FetchBlockInfo function

Signed-off-by: Sean Zheng <[email protected]>
  • Loading branch information
blackhorseya committed Oct 4, 2024
1 parent 60a31d6 commit 7b4da21
Showing 1 changed file with 15 additions and 8 deletions.
23 changes: 15 additions & 8 deletions app/domain/block/block_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ import (
"github.com/xssnick/tonutils-go/ton"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
)

Expand Down Expand Up @@ -134,15 +136,24 @@ func (i *impl) FoundNewBlock(stream grpc.BidiStreamingServer[model.Block, model.

for {
newBlock, err := stream.Recv()
if errors.Is(err, io.EOF) || errors.Is(err, context.Canceled) {
break
st, ok := status.FromError(err)
if ok && st.Code() == codes.Canceled {
ctx.Info("found new block canceled")
return nil
}
if errors.Is(err, io.EOF) {
return nil
}
if err != nil {
ctx.Error("failed to receive new block", zap.Error(err))
continue
}

err = i.FetchBlockInfo(ctx, newBlock)
if errors.Is(err, context.Canceled) {
ctx.Info("found new block canceled")
return nil
}
if err != nil {
ctx.Error("failed to fetch block info", zap.Error(err))
continue
Expand All @@ -160,8 +171,6 @@ func (i *impl) FoundNewBlock(stream grpc.BidiStreamingServer[model.Block, model.
continue
}
}

return nil
}

// FetchBlockInfo is used to fetch block info
Expand All @@ -174,17 +183,15 @@ func (i *impl) FetchBlockInfo(c context.Context, block *model.Block) (err error)

// 查找區塊
blockID, err := api.LookupBlock(ctx, block.Workchain, block.Shard, block.SeqNo)
if err != nil {
if err != nil && !errors.Is(err, context.Canceled) {
ctx.Error("failed to lookup block", zap.Error(err), zap.Any("block", block))
span.RecordError(err)
return err
}

// 獲取區塊資訊
blockData, err := api.GetBlockData(ctx, blockID)
if err != nil {
if err != nil && !errors.Is(err, context.Canceled) {
ctx.Error("failed to get block data", zap.Error(err))
span.RecordError(err)
return err
}

Expand Down

0 comments on commit 7b4da21

Please sign in to comment.