forked from drborges/rivers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
77 lines (65 loc) · 1.3 KB
/
context.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
package rivers
import (
"errors"
"fmt"
"github.com/drborges/rivers/stream"
"runtime/debug"
"time"
)
var DebugEnabled = false
type context struct {
requests chan error
success chan struct{}
failure chan struct{}
deadline time.Duration
err error
}
func NewContext() stream.Context {
return &context{
requests: make(chan error, 1),
success: make(chan struct{}),
failure: make(chan struct{}),
deadline: time.Hour,
}
}
func (context *context) Err() error {
return context.err
}
func (context *context) Deadline() time.Duration {
return context.deadline
}
func (context *context) SetDeadline(duration time.Duration) {
context.deadline = duration
}
func (context *context) Failure() <-chan struct{} {
return context.failure
}
func (context *context) Done() <-chan struct{} {
return context.success
}
func (context *context) Close(err error) {
context.requests <- err
ch := context.success
if err != nil {
ch = context.failure
}
select {
case <-ch:
return
default:
close(ch)
context.err = <-context.requests
}
}
func (context *context) Recover() {
if r := recover(); r != nil {
if DebugEnabled && r != stream.Done {
debug.PrintStack()
}
err := errors.New(fmt.Sprintf("Recovered from %v", r))
if e, ok := r.(error); ok {
err = e
}
context.Close(err)
}
}