forked from stellar/go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.go
211 lines (183 loc) · 5.05 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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package actions
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"net/http"
"sync"
"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/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
appCtx context.Context
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, appCtx context.Context, sseUpdateFrequency time.Duration) {
base.W = w
base.R = r
base.sseUpdateFrequency = sseUpdateFrequency
base.appCtx = appCtx
}
// 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.(JSONer)
if !ok {
goto NotAcceptable
}
err := action.JSON()
if err != nil {
problem.Render(ctx, base.W, err)
return
}
case render.MimeEventStream:
switch action.(type) {
case EventStreamer, SingleObjectStreamer:
default:
goto NotAcceptable
}
stream := sse.NewStream(ctx, base.W)
var oldHash [32]byte
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 {
stream.Err(errors.Wrap(err, "RateLimiter error"))
return
}
if limited {
stream.Err(sse.ErrRateLimited)
return
}
}
switch ac := action.(type) {
case EventStreamer:
err := ac.SSE(stream)
if err != nil {
stream.Err(err)
return
}
case SingleObjectStreamer:
newEvent, err := ac.LoadEvent()
if err != nil {
stream.Err(err)
return
}
resource, err := json.Marshal(newEvent.Data)
if err != nil {
stream.Err(errors.Wrap(err, "unable to marshal next action resource"))
return
}
nextHash := sha256.Sum256(resource)
if bytes.Equal(nextHash[:], oldHash[:]) {
break
}
oldHash = nextHash
stream.SetLimit(10)
stream.Send(newEvent)
}
// 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)
var closedLock sync.Mutex
var closed bool
go func() {
for {
time.Sleep(base.sseUpdateFrequency)
closedLock.Lock()
tmpClosed := closed
closedLock.Unlock()
if tmpClosed {
return
}
currentLedgerState := ledger.CurrentState()
if currentLedgerState.HistoryLatest >= lastLedgerState.HistoryLatest+1 {
newLedgers <- true
return
}
}
}()
select {
case <-newLedgers:
continue
case <-ctx.Done():
closedLock.Lock()
closed = true
closedLock.Unlock()
case <-base.appCtx.Done():
}
stream.Done()
return
}
case render.MimeRaw:
action, ok := action.(RawDataResponder)
if !ok {
goto NotAcceptable
}
err := action.Raw()
if err != nil {
problem.Render(ctx, base.W, err)
return
}
default:
goto NotAcceptable
}
return
NotAcceptable:
problem.Render(ctx, base.W, hProblem.NotAcceptable)
}
// 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
}