forked from temporalio/samples-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
propagator.go
83 lines (69 loc) · 2.45 KB
/
propagator.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package encryption
import (
"context"
"go.temporal.io/sdk/converter"
"go.temporal.io/sdk/workflow"
)
type (
// contextKey is an unexported type used as key for items stored in the
// Context object
contextKey struct{}
// propagator implements the custom context propagator
propagator struct{}
// CryptConfig is a struct holding values
CryptContext struct {
KeyID string `json:"keyId"`
}
)
// PropagateKey is the key used to store the value in the Context object
var PropagateKey = contextKey{}
// propagationKey is the key used by the propagator to pass values through the
// Temporal server headers
const propagationKey = "encryption"
// NewContextPropagator returns a context propagator that propagates a set of
// string key-value pairs across a workflow
func NewContextPropagator() workflow.ContextPropagator {
return &propagator{}
}
// Inject injects values from context into headers for propagation
func (s *propagator) Inject(ctx context.Context, writer workflow.HeaderWriter) error {
value := ctx.Value(PropagateKey)
payload, err := converter.GetDefaultDataConverter().ToPayload(value)
if err != nil {
return err
}
writer.Set(propagationKey, payload)
return nil
}
// InjectFromWorkflow injects values from context into headers for propagation
func (s *propagator) InjectFromWorkflow(ctx workflow.Context, writer workflow.HeaderWriter) error {
value := ctx.Value(PropagateKey)
payload, err := converter.GetDefaultDataConverter().ToPayload(value)
if err != nil {
return err
}
writer.Set(propagationKey, payload)
return nil
}
// Extract extracts values from headers and puts them into context
func (s *propagator) Extract(ctx context.Context, reader workflow.HeaderReader) (context.Context, error) {
if value, ok := reader.Get(propagationKey); ok {
var cryptContext CryptContext
if err := converter.GetDefaultDataConverter().FromPayload(value, &cryptContext); err != nil {
return ctx, nil
}
ctx = context.WithValue(ctx, PropagateKey, cryptContext)
}
return ctx, nil
}
// ExtractToWorkflow extracts values from headers and puts them into context
func (s *propagator) ExtractToWorkflow(ctx workflow.Context, reader workflow.HeaderReader) (workflow.Context, error) {
if value, ok := reader.Get(propagationKey); ok {
var cryptContext CryptContext
if err := converter.GetDefaultDataConverter().FromPayload(value, &cryptContext); err != nil {
return ctx, nil
}
ctx = workflow.WithValue(ctx, PropagateKey, cryptContext)
}
return ctx, nil
}