-
Notifications
You must be signed in to change notification settings - Fork 0
/
manager.go
54 lines (40 loc) · 1.4 KB
/
manager.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
package ana
import "time"
type Manager[P any, R any, C SessionCtx[P, R]] struct {
repository IdempotencyRepository[P, R, C]
}
func New[P any, R any, C SessionCtx[P, R]](repository IdempotencyRepository[P, R, C]) *Manager[P, R, C] {
return &Manager[P, R, C]{repository: repository}
}
func (manager *Manager[P, R, C]) Call(operation Operation[P, R, C]) (*R, error) {
if manager.isExpiredOperation(operation) {
return nil, newExpirationError(operation.Target(), operation.Key())
}
trackedOperation := manager.repository.FetchOrStart(operation)
if trackedOperation != nil {
if trackedOperation.isFinished() {
return trackedOperation.Result, nil
}
if trackedOperation.isExpired() {
return nil, newExpirationError(trackedOperation.Target, trackedOperation.Key)
}
if trackedOperation.stillRunning() {
return nil, newStillRunningError(trackedOperation.Target, trackedOperation.Key)
}
}
return manager.callOperation(operation)
}
func (manager *Manager[P, R, C]) callOperation(operation Operation[P, R, C]) (*R, error) {
session := manager.repository.NewSession(operation)
defer session.close()
session.call()
return session.result, session.err
}
func (manager *Manager[P, R, C]) isExpiredOperation(operation Operation[P, R, C]) bool {
if operation.Expiration() == time.Duration(0) {
return false
}
return time.Now().After(
operation.ReferenceTime().Add(operation.Expiration()),
)
}