Skip to content

Commit c67d45b

Browse files
committed
Provide an option to specify base context for RPC connection
Signed-off-by: Dzmitry Mikhalapau <dzmitry.mikhalapau@gmail.com>
1 parent 46ccd63 commit c67d45b

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

‎rpc/rpc.go‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -88,10 +88,11 @@ type Conn struct {
8888
bootstrap capnp.Client
8989
er errReporter
9090
abortTimeout time.Duration
91+
baseContext func() context.Context
9192

9293
// bgctx is a Context that is canceled when shutdown starts. Note
93-
// that it's parent is context.Background(), so we can rely on this
94-
// being the *only* time it will be canceled.
94+
// that if baseContext is not provided. it's parent is context.Background(),
95+
// so we can rely on this being the *only* time it will be canceled.
9596
bgctx context.Context
9697

9798
// tasks block shutdown.
@@ -202,6 +203,11 @@ type Options struct {
202203
// by Dial or Accept on the Network itself; application code should not
203204
// set this.
204205
Network Network
206+
207+
// BaseContext is an optional funcation that returns a base context
208+
// for any incoming connection. If ommitted, the context.Background()
209+
// will be used instead.
210+
BaseContext func() context.Context
205211
}
206212

207213
// Logger is used for logging by the RPC system. Each method logs
@@ -231,8 +237,9 @@ type Logger interface {
231237
// requests from the transport.
232238
func NewConn(t Transport, opts *Options) *Conn {
233239
c := &Conn{
234-
transport: t,
235-
closed: make(chan struct{}),
240+
transport: t,
241+
baseContext: context.Background,
242+
closed: make(chan struct{}),
236243
}
237244

238245
sender := spsc.New[asyncSend]()
@@ -248,6 +255,10 @@ func NewConn(t Transport, opts *Options) *Conn {
248255
c.abortTimeout = opts.AbortTimeout
249256
c.network = opts.Network
250257
c.remotePeerID = opts.RemotePeerID
258+
259+
if opts.BaseContext != nil {
260+
c.baseContext = opts.BaseContext
261+
}
251262
}
252263
if c.abortTimeout == 0 {
253264
c.abortTimeout = 100 * time.Millisecond
@@ -261,7 +272,7 @@ func NewConn(t Transport, opts *Options) *Conn {
261272
func (c *Conn) startBackgroundTasks() {
262273
// We use an errgroup to link the lifetime of background tasks
263274
// to each other.
264-
ctx, cancel := context.WithCancel(context.Background())
275+
ctx, cancel := context.WithCancel(c.baseContext())
265276
g, ctx := errgroup.WithContext(ctx)
266277

267278
c.bgctx = ctx

0 commit comments

Comments
 (0)