forked from stellar/go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.go
187 lines (158 loc) · 4.72 KB
/
base.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
package actions
import (
"database/sql"
"net/http"
"time"
horizonContext "github.com/stellar/go/services/horizon/internal/context"
"github.com/stellar/go/services/horizon/internal/ledger"
"github.com/stellar/go/services/horizon/internal/render"
hProblem "github.com/stellar/go/services/horizon/internal/render/problem"
"github.com/stellar/go/services/horizon/internal/render/sse"
"github.com/stellar/go/support/errors"
"github.com/stellar/go/support/log"
"github.com/stellar/go/support/render/problem"
)
// Base is a helper struct you can use as part of a custom action via
// composition.
//
// TODO: example usage
type Base struct {
W http.ResponseWriter
R *http.Request
Err error
sseUpdateFrequency time.Duration
isSetup bool
}
// Prepare established the common attributes that get used in nearly every
// action. "Child" actions may override this method to extend action, but it
// is advised you also call this implementation to maintain behavior.
func (base *Base) Prepare(w http.ResponseWriter, r *http.Request, sseUpdateFrequency time.Duration) {
base.W = w
base.R = r
base.sseUpdateFrequency = sseUpdateFrequency
}
// Execute trigger content negotiation and the actual execution of one of the
// action's handlers.
func (base *Base) Execute(action interface{}) {
ctx := base.R.Context()
contentType := render.Negotiate(base.R)
switch contentType {
case render.MimeHal, render.MimeJSON:
action, ok := action.(JSON)
if !ok {
goto NotAcceptable
}
action.JSON()
if base.Err != nil {
problem.Render(ctx, base.W, base.Err)
return
}
case render.MimeEventStream:
action, ok := action.(SSE)
if !ok {
goto NotAcceptable
}
stream := sse.NewStream(ctx, base.W)
for {
lastLedgerState := ledger.CurrentState()
// Rate limit the request if it's a call to stream since it queries the DB every second. See
// https://github.com/stellar/go/issues/715 for more details.
app := base.R.Context().Value(&horizonContext.AppContextKey)
rateLimiter := app.(RateLimiterProvider).GetRateLimiter()
if rateLimiter != nil {
limited, _, err := rateLimiter.RateLimiter.RateLimit(rateLimiter.VaryBy.Key(base.R), 1)
if err != nil {
log.Ctx(ctx).Error(errors.Wrap(err, "RateLimiter error"))
stream.Err(errors.New("Unexpected stream error"))
return
}
if limited {
stream.Err(errors.New("rate limit exceeded"))
return
}
}
action.SSE(stream)
if base.Err != nil {
// In the case that we haven't yet sent an event, is also means we
// haven't sent the preamble, meaning we should simply return the normal HTTP
// error.
if stream.SentCount() == 0 {
problem.Render(ctx, base.W, base.Err)
return
}
if errors.Cause(base.Err) == sql.ErrNoRows {
base.Err = errors.New("Object not found")
} else {
log.Ctx(ctx).Error(base.Err)
base.Err = errors.New("Unexpected stream error")
}
// Send errors through the stream and then close the stream.
stream.Err(base.Err)
}
// Manually send the preamble in case there are no data events in SSE to trigger a stream.Send call.
// This method is called every iteration of the loop, but is protected by a sync.Once variable so it's
// only executed once.
stream.Init()
if stream.IsDone() {
return
}
// Make sure this is buffered channel of size 1. Otherwise, the go routine below
// will never return if `newLedgers` channel is not read. From Effective Go:
// > If the channel is unbuffered, the sender blocks until the receiver has received the value.
newLedgers := make(chan bool, 1)
go func() {
for {
time.Sleep(base.sseUpdateFrequency)
currentLedgerState := ledger.CurrentState()
if currentLedgerState.HistoryLatest >= lastLedgerState.HistoryLatest+1 {
newLedgers <- true
return
}
}
}()
select {
case <-ctx.Done():
stream.Done()
return
case <-newLedgers:
continue
}
}
case render.MimeRaw:
action, ok := action.(Raw)
if !ok {
goto NotAcceptable
}
action.Raw()
if base.Err != nil {
problem.Render(ctx, base.W, base.Err)
return
}
default:
goto NotAcceptable
}
return
NotAcceptable:
problem.Render(ctx, base.W, hProblem.NotAcceptable)
return
}
// Do executes the provided func iff there is no current error for the action.
// Provides a nicer way to invoke a set of steps that each may set `action.Err`
// during execution
func (base *Base) Do(fns ...func()) {
for _, fn := range fns {
if base.Err != nil {
return
}
fn()
}
}
// Setup runs the provided funcs if and only if no call to Setup() has been
// made previously on this action.
func (base *Base) Setup(fns ...func()) {
if base.isSetup {
return
}
base.Do(fns...)
base.isSetup = true
}