Skip to content

Commit

Permalink
fix: fix send context when using Dispatch()
Browse files Browse the repository at this point in the history
  • Loading branch information
bounoable committed Jun 22, 2020
1 parent e3f8036 commit 5280165
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
27 changes: 24 additions & 3 deletions office.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ type Transport interface {
}

type dispatchJob struct {
values context.Context
letter letter.Letter
transport string
}
Expand Down Expand Up @@ -213,7 +214,10 @@ func (o *Office) Send(ctx context.Context, let letter.Letter) error {
// Available options:
// DispatchWith(): Set the name of the transport to use.
func (o *Office) Dispatch(ctx context.Context, let letter.Letter, opts ...DispatchOption) error {
job := dispatchJob{letter: let}
job := dispatchJob{
values: ctx,
letter: let,
}
for _, opt := range opts {
opt(&job)
}
Expand Down Expand Up @@ -273,15 +277,32 @@ func (o *Office) run(ctx context.Context, wg *sync.WaitGroup) {
case <-ctx.Done():
return
case job := <-o.queue:
dispatchCtx := &dispatchContext{
Context: ctx,
values: job.values,
}

if job.transport == "" {
o.Send(ctx, job.letter)
o.Send(dispatchCtx, job.letter)
} else {
o.SendWith(ctx, job.transport, job.letter)
o.SendWith(dispatchCtx, job.transport, job.letter)
}
}
}
}

type dispatchContext struct {
context.Context
values context.Context
}

func (ctx *dispatchContext) Value(key interface{}) interface{} {
if val := ctx.Context.Value(key); val != nil {
return val
}
return ctx.values.Value(key)
}

func (o *Office) log(v ...interface{}) {
if o.cfg.Logger == nil {
return
Expand Down
6 changes: 3 additions & 3 deletions office_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -483,9 +483,9 @@ func TestOffice_Run(t *testing.T) {

let1, let2, let3 := letter.Write(), letter.Write(), letter.Write()

trans.EXPECT().Send(ctx, let1)
trans.EXPECT().Send(ctx, let2)
trans.EXPECT().Send(ctx, let3)
trans.EXPECT().Send(gomock.Any(), let1).Return(nil)
trans.EXPECT().Send(gomock.Any(), let2).Return(nil)
trans.EXPECT().Send(gomock.Any(), let3).Return(nil)

assert.Nil(t, off.Dispatch(context.Background(), let1))
assert.Nil(t, off.Dispatch(context.Background(), let2))
Expand Down

0 comments on commit 5280165

Please sign in to comment.