forked from berty/berty
-
Notifications
You must be signed in to change notification settings - Fork 3
/
driver_lifecycle.go
87 lines (68 loc) · 1.7 KB
/
driver_lifecycle.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
84
85
86
87
package bertybridge
import (
"context"
"sync"
"time"
"go.uber.org/zap"
)
const (
AppStateUnknown int = iota
AppStateActive
AppStateInactive
AppStateBackground
)
type LifeCycleDriver interface {
GetCurrentState() int
RegisterHandler(handler LifeCycleHandler)
}
type LifeCycleHandler interface {
HandleState(appstate int)
HandleTask() LifeCycleBackgroundTask
WillTerminate()
}
type LifeCycleBackgroundTask interface {
Execute() (success bool)
Cancel()
}
var _ LifeCycleBackgroundTask = (*backgroundTask)(nil)
type backgroundTask struct {
task func(context.Context) error
logger *zap.Logger
finishOnce sync.Once
finish chan struct{}
ctx context.Context
cancel context.CancelFunc
}
func newBackgroundTask(logger *zap.Logger, task func(context.Context) error) LifeCycleBackgroundTask {
ctx, cancel := context.WithCancel(context.Background())
return &backgroundTask{
finish: make(chan struct{}),
logger: logger,
task: task,
ctx: ctx,
cancel: cancel,
}
}
// Execute should be only called once
func (bt *backgroundTask) Execute() bool {
defer bt.finishOnce.Do(func() { close(bt.finish) })
if err := bt.task(bt.ctx); err != nil {
bt.logger.Error("background task failed", zap.Error(err))
return false
}
return true
}
// Cancel background task
func (bt *backgroundTask) Cancel() {
bt.cancel()
// wait until task is done or expire
select {
case <-time.After(time.Second * 5):
case <-bt.finish:
}
}
// noop driver
// var _ LifeCycleDriver = (*noopLifeCycleDriver)(nil)
// type noopLifeCycleDriver struct{}
// func (*noopLifeCycleDriver) GetCurrentState() int { return AppStateUnknown }
// func (*noopLifeCycleDriver) RegisterHandler(_ LifeCycleHandler) {}