-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
79 lines (66 loc) · 1.76 KB
/
session.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
package ana
import "time"
type SessionCtx[P any, R any] interface {
Success(*TrackedOperation[P, R])
Fail(*TrackedOperation[P, R])
}
// TODO: Add some tests at session_test.go
type Session[P any, R any, C SessionCtx[P, R]] struct {
Context C
operation Operation[P, R, C]
startedAt time.Time
result *R
err error
closed bool
}
func NewSession[P any, R any, C SessionCtx[P, R]](operation Operation[P, R, C], context C) *Session[P, R, C] {
return &Session[P, R, C]{
Context: context,
operation: operation,
closed: false,
}
}
func (session *Session[P, R, C]) call() {
defer session.recover()
session.startedAt = time.Now()
session.result, session.err = session.operation.Call(session.Context)
}
func (session *Session[P, R, C]) recover() {
if recovery := recover(); recovery != nil {
session.err = newPanicError(recovery)
}
}
func (session *Session[P, R, C]) trackedOperation() *TrackedOperation[P, R] {
timeout := time.Time{}
expiration := time.Time{}
if session.operation.Timeout() != time.Duration(0) {
timeout = session.operation.ReferenceTime().Add(session.operation.Timeout())
}
if session.operation.Expiration() != time.Duration(0) {
expiration = session.operation.ReferenceTime().Add(session.operation.Expiration())
}
return NewTrackedOperation(
Running,
session.operation.Key(),
session.operation.Target(),
session.operation.Payload(),
session.operation.ReferenceTime(),
session.startedAt,
timeout,
expiration,
session.result,
session.err,
)
}
func (session *Session[P, R, C]) close() {
if session.closed {
return
}
if session.err == nil {
session.Context.Success(session.trackedOperation())
session.closed = true
return
}
session.Context.Fail(session.trackedOperation())
session.closed = true
}