Debian Codegraph @

ami/request.go

raw symbols SCIP
1 package ami
2
3 import (
4 "context"
5 "time"
6
7 "github.com/pkg/errors"
8 )
9
10 const attrActionID = "ActionID"
11
12 type requestOptions struct {
13 Timeout time.Duration
14 OnComplete func(ctx context.Context, msg *Message, err error)
15 }
16 type RequestOption func(o *requestOptions) error
17
18 func RequestTimeout(d time.Duration) RequestOption {
19 return func(o *requestOptions) error {
20 o.Timeout = d
21 return nil
22 }
23 }
24
25 // RequestResponseCallback will case Conn.Request run async, will not timeout
26 func RequestResponseCallback(cb func(ctx context.Context, msg *Message, err error)) RequestOption {
27 return func(o *requestOptions) error {
28 o.OnComplete = cb
29 return nil
30 }
31 }
32
33 func (c *Conn) Request(r interface{}, opts ...RequestOption) (resp *Message, err error) {
34 var msg *Message
35 msg, err = ConvertToMessage(r)
36 if err != nil {
37 return nil, err
38 }
39 if msg.Type != MessageTypeAction {
40 return nil, errors.Errorf("can only request action: %v", msg.Type)
41 }
42
43 async := &asyncMsg{
44 id: c.nextID(),
45 msg: msg,
46 result: make(chan *asyncMsg, 1),
47 ctx: context.Background(),
48 }
49 o := requestOptions{
50 Timeout: time.Second * 30,
51 }
52 for _, opt := range opts {
53 if err = opt(&o); err != nil {
54 return
55 }
56 }
57
58 onComplete := o.OnComplete
59 if onComplete != nil {
60 async.cb = func(v *asyncMsg) {
61 onComplete(v.ctx, v.resp, v.err)
62 }
63 }
64
65 msg.SetAttr(attrActionID, async.id)
66
67 if async.cb == nil {
68 var cancel context.CancelFunc
69 // todo allowed custom timeout
70 async.ctx, cancel = context.WithTimeout(async.ctx, o.Timeout)
71 defer cancel()
72 }
73
74 // enqueue
75 c.pending <- async
76
77 if async.cb != nil {
78 return nil, errors.New("No response yet")
79 }
80
81 select {
82 case <-async.ctx.Done():
83 return nil, async.ctx.Err()
84 case <-async.result:
85 err = async.err
86 if err == nil && async.resp != nil {
87 err = async.resp.Error()
88 }
89 return async.resp, err
90 }
91 }