forked from riverqueue/river
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
48 lines (42 loc) · 1.74 KB
/
context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package river
import (
"context"
"errors"
"github.com/riverqueue/river/internal/rivercommon"
)
var errClientNotInContext = errors.New("river: client not found in context, can only be used in a Worker")
func withClient[TTx any](ctx context.Context, client *Client[TTx]) context.Context {
return context.WithValue(ctx, rivercommon.ContextKeyClient{}, client)
}
// ClientFromContext returns the Client from the context. This function can
// only be used within a Worker's Work() method because that is the only place
// River sets the Client on the context.
//
// It panics if the context does not contain a Client, which will never happen
// from the context provided to a Worker's Work() method.
//
// When testing JobArgs.Work implementations, it might be useful to use
// rivertest.WorkContext to initialize a context that has an available client.
func ClientFromContext[TTx any](ctx context.Context) *Client[TTx] {
client, err := ClientFromContextSafely[TTx](ctx)
if err != nil {
panic(err)
}
return client
}
// ClientFromContext returns the Client from the context. This function can
// only be used within a Worker's Work() method because that is the only place
// River sets the Client on the context.
//
// It returns an error if the context does not contain a Client, which will
// never happen from the context provided to a Worker's Work() method.
//
// When testing JobArgs.Work implementations, it might be useful to use
// rivertest.WorkContext to initialize a context that has an available client.
func ClientFromContextSafely[TTx any](ctx context.Context) (*Client[TTx], error) {
client, exists := ctx.Value(rivercommon.ContextKeyClient{}).(*Client[TTx])
if !exists || client == nil {
return nil, errClientNotInContext
}
return client, nil
}