Update cancel context usage

This commit is contained in:
世界
2023-04-10 13:00:57 +08:00
parent f7f9a7ae20
commit bb63429079
5 changed files with 23 additions and 12 deletions

View File

@@ -101,10 +101,10 @@ func (c *Client) DialContext(ctx context.Context) (net.Conn, error) {
return nil, err
}
client := NewGunServiceClient(clientConn).(GunServiceCustomNameClient)
ctx, cancel := context.WithCancel(ctx)
ctx, cancel := common.ContextWithCancelCause(ctx)
stream, err := client.TunCustomName(ctx, c.serviceName)
if err != nil {
cancel()
cancel(err)
return nil, err
}
return NewGRPCConn(stream, cancel), nil

View File

@@ -1,12 +1,12 @@
package v2raygrpc
import (
"context"
"net"
"os"
"time"
"github.com/sagernet/sing-box/common/baderror"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/rw"
)
@@ -14,11 +14,11 @@ var _ net.Conn = (*GRPCConn)(nil)
type GRPCConn struct {
GunService
cancel context.CancelFunc
cancel common.ContextCancelCauseFunc
cache []byte
}
func NewGRPCConn(service GunService, cancel context.CancelFunc) *GRPCConn {
func NewGRPCConn(service GunService, cancel common.ContextCancelCauseFunc) *GRPCConn {
if client, isClient := service.(GunService_TunClient); isClient {
service = &clientConnWrapper{client}
}
@@ -37,6 +37,7 @@ func (c *GRPCConn) Read(b []byte) (n int, err error) {
hunk, err := c.Recv()
err = baderror.WrapGRPC(err)
if err != nil {
c.cancel(err)
return
}
n = copy(b, hunk.Data)
@@ -49,13 +50,14 @@ func (c *GRPCConn) Read(b []byte) (n int, err error) {
func (c *GRPCConn) Write(b []byte) (n int, err error) {
err = baderror.WrapGRPC(c.Send(&Hunk{Data: b}))
if err != nil {
c.cancel(err)
return
}
return len(b), nil
}
func (c *GRPCConn) Close() error {
c.cancel()
c.cancel(net.ErrClosed)
return nil
}

View File

@@ -10,6 +10,7 @@ import (
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/common/tls"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing/common"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
@@ -45,7 +46,7 @@ func NewServer(ctx context.Context, options option.V2RayGRPCOptions, tlsConfig t
}
func (s *Server) Tun(server GunService_TunServer) error {
ctx, cancel := context.WithCancel(s.ctx)
ctx, cancel := common.ContextWithCancelCause(s.ctx)
conn := NewGRPCConn(server, cancel)
var metadata M.Metadata
if remotePeer, loaded := peer.FromContext(server.Context()); loaded {