-
Notifications
You must be signed in to change notification settings - Fork 1
/
worker.go
59 lines (51 loc) · 1.33 KB
/
worker.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
package observability
import (
"context"
"github.com/hephbuild/heph/worker2"
)
type createSpanFunc[S any] func(job worker2.Dep) (context.Context, S)
type workerStageStore[S any] struct {
span S
hasSpan bool
createSpanFunc createSpanFunc[S]
}
func (s *workerStageStore[S]) createSpan(job worker2.Dep) (context.Context, S) {
ctx, span := s.createSpanFunc(job)
s.span = span
s.hasSpan = true
return ctx, span
}
func WorkerStageFactory[S SpanError](f createSpanFunc[S]) worker2.Hook {
ss := &workerStageStore[S]{createSpanFunc: f}
return worker2.StageHook{
OnScheduled: func(job worker2.Dep) context.Context {
ctx, span := ss.createSpan(job)
span.SetScheduledTime(job.GetScheduledAt())
return ctx
},
OnQueued: func(job worker2.Dep) context.Context {
ss.span.SetQueuedTime(job.GetQueuedAt())
return nil
},
OnStart: func(job worker2.Dep) context.Context {
var ctx context.Context
if !ss.hasSpan {
ctx, _ = ss.createSpan(job)
}
ss.span.SetStartTime(job.GetStartedAt())
return ctx
},
OnEnd: func(job worker2.Dep) context.Context {
if err := job.GetErr(); err != nil {
state := StateFailed
if job.GetState() == worker2.ExecStateSkipped {
state = StateSkipped
}
ss.span.EndErrorState(err, state)
} else {
ss.span.End()
}
return nil
},
}.Hook()
}