-
Notifications
You must be signed in to change notification settings - Fork 47
/
computation.go
326 lines (292 loc) · 9.41 KB
/
computation.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package signalflow
import (
"context"
"fmt"
"sync"
"time"
"github.com/signalfx/golib/v3/pointer"
"github.com/signalfx/signalfx-go/idtool"
"github.com/signalfx/signalfx-go/signalflow/messages"
)
// Computation is a single running SignalFlow job
type Computation struct {
ctx context.Context
cancel context.CancelFunc
channel *Channel
client *Client
dataCh chan *messages.DataMessage
// An intermediate channel for data messages where they can be buffered if
// nothing is currently pulling data messages.
dataChBuffer chan *messages.DataMessage
expirationCh chan *messages.ExpiredTSIDMessage
expirationChBuffer chan *messages.ExpiredTSIDMessage
updateSignal updateSignal
lastError error
resolutionMS *int
lagMS *int
maxDelayMS *int
tsidMetadata map[idtool.ID]*messages.MetadataProperties
handle string
// The timeout to wait for metadata when a metadata access function is
// called. This will default to what is set on the client, but can be
// overridden by changing this field directly.
MetadataTimeout time.Duration
}
func newComputation(ctx context.Context, channel *Channel, client *Client) *Computation {
newCtx, cancel := context.WithCancel(ctx)
comp := &Computation{
ctx: newCtx,
cancel: cancel,
channel: channel,
client: client,
dataCh: make(chan *messages.DataMessage),
dataChBuffer: make(chan *messages.DataMessage),
expirationCh: make(chan *messages.ExpiredTSIDMessage),
expirationChBuffer: make(chan *messages.ExpiredTSIDMessage),
tsidMetadata: make(map[idtool.ID]*messages.MetadataProperties),
updateSignal: updateSignal{},
MetadataTimeout: client.defaultMetadataTimeout,
}
go comp.bufferDataMessages()
go comp.bufferExpirationMessages()
go comp.watchMessages()
return comp
}
// Channel returns the underlying Channel instance used by this computation.
func (c *Computation) Channel() *Channel {
return c.channel
}
// Handle of the computation
func (c *Computation) Handle() string {
if err := c.waitForMetadata(func() bool { return c.handle != "" }); err != nil {
return ""
}
return c.handle
}
// Waits for the given cond func to return true, or until the metadata timeout
// duration has passed.
func (c *Computation) waitForMetadata(cond func() bool) error {
c.updateSignal.Lock()
defer c.updateSignal.Unlock()
remaining := c.MetadataTimeout
for !cond() {
if err := c.updateSignal.WaitWithTimeout(c.ctx, &remaining); err != nil {
return err
}
}
return nil
}
// Resolution of the job. This will wait for a short while for the resolution
// message to come on the websocket, but will return 0 after a timeout if it
// does not come.
func (c *Computation) Resolution() time.Duration {
if err := c.waitForMetadata(func() bool { return c.resolutionMS != nil }); err != nil {
return 0
}
return time.Duration(*c.resolutionMS) * time.Millisecond
}
// Lag detected for the job. This will wait for a short while for the lag
// message to come on the websocket, but will return 0 after a timeout if it
// does not come.
func (c *Computation) Lag() time.Duration {
if err := c.waitForMetadata(func() bool { return c.lagMS != nil }); err != nil {
return 0
}
return time.Duration(*c.lagMS) * time.Millisecond
}
// MaxDelay detected of the job. This will wait for a short while for the max
// delay message to come on the websocket, but will return 0 after a timeout if
// it does not come.
func (c *Computation) MaxDelay() time.Duration {
if err := c.waitForMetadata(func() bool { return c.maxDelayMS != nil }); err != nil {
return 0
}
return time.Duration(*c.maxDelayMS) * time.Millisecond
}
// TSIDMetadata for a particular tsid. This will wait for a short while for
// the tsid metadata message to come on the websocket, but will return nil
// after a timeout if it does not come.
func (c *Computation) TSIDMetadata(tsid idtool.ID) *messages.MetadataProperties {
if err := c.waitForMetadata(func() bool { return c.tsidMetadata[tsid] != nil }); err != nil {
return nil
}
return c.tsidMetadata[tsid]
}
// Done passes through the computation context's Done channel for use in select
// statements to know when the computation is finished or an error occurred.
func (c *Computation) Done() <-chan struct{} {
return c.ctx.Done()
}
// Err returns the last fatal error that caused the computation to stop, if
// any. Will be nil if the computation stopped in an expected manner.
func (c *Computation) Err() error {
return c.lastError
}
func (c *Computation) watchMessages() {
for {
select {
case <-c.ctx.Done():
close(c.dataCh)
return
case m, ok := <-c.channel.Messages():
if !ok {
c.cancel()
continue
}
c.processMessage(m)
}
}
}
func (c *Computation) processMessage(m messages.Message) {
defer c.updateSignal.SignalAll()
switch v := m.(type) {
case *messages.JobStartControlMessage:
c.handle = v.Handle
case *messages.BaseControlMessage:
switch v.Type() {
case messages.ChannelAbortEvent, messages.EndOfChannelEvent:
c.cancel()
}
case *messages.DataMessage:
c.dataChBuffer <- v
case *messages.ExpiredTSIDMessage:
delete(c.tsidMetadata, idtool.IDFromString(v.TSID))
c.expirationChBuffer <- v
case *messages.InfoMessage:
switch v.MessageBlock.Code {
case messages.JobRunningResolution:
c.resolutionMS = pointer.Int(v.MessageBlock.Contents.(messages.JobRunningResolutionContents).ResolutionMS())
case messages.JobDetectedLag:
c.lagMS = pointer.Int(v.MessageBlock.Contents.(messages.JobDetectedLagContents).LagMS())
case messages.JobInitialMaxDelay:
c.maxDelayMS = pointer.Int(v.MessageBlock.Contents.(messages.JobInitialMaxDelayContents).MaxDelayMS())
}
case *messages.ErrorMessage:
c.lastError = fmt.Errorf("error executing SignalFlow: %v", v.RawData())
c.cancel()
case *messages.MetadataMessage:
c.tsidMetadata[v.TSID] = &v.Properties
}
}
// Buffer up data messages indefinitely until another goroutine reads them off of
// c.messages, which is an unbuffered channel.
func (c *Computation) bufferDataMessages() {
buffer := make([]*messages.DataMessage, 0)
var nextMessage *messages.DataMessage
for {
if len(buffer) > 0 {
if nextMessage == nil {
nextMessage, buffer = buffer[0], buffer[1:]
}
select {
case <-c.ctx.Done():
return
case c.dataCh <- nextMessage:
nextMessage = nil
case msg := <-c.dataChBuffer:
buffer = append(buffer, msg)
}
} else {
buffer = append(buffer, <-c.dataChBuffer)
}
}
}
// Buffer up expiration messages indefinitely until another goroutine reads
// them off of c.expirationCh, which is an unbuffered channel.
func (c *Computation) bufferExpirationMessages() {
buffer := make([]*messages.ExpiredTSIDMessage, 0)
var nextMessage *messages.ExpiredTSIDMessage
for {
if len(buffer) > 0 {
if nextMessage == nil {
nextMessage, buffer = buffer[0], buffer[1:]
}
select {
case <-c.ctx.Done():
return
case c.expirationCh <- nextMessage:
nextMessage = nil
case msg := <-c.expirationChBuffer:
buffer = append(buffer, msg)
}
} else {
buffer = append(buffer, <-c.expirationChBuffer)
}
}
}
// Data returns the channel on which data messages come.
func (c *Computation) Data() <-chan *messages.DataMessage {
return c.dataCh
}
// Expirations returns a channel that will be sent messages about expired
// TSIDs, i.e. time series that are no longer valid for this computation.
func (c *Computation) Expirations() <-chan *messages.ExpiredTSIDMessage {
return c.expirationCh
}
// IsFinished returns true if the computation is done and no more data should
// be expected from it.
func (c *Computation) IsFinished() bool {
// The context will have a non-nil err if it was cancelled.
return c.ctx.Err() != nil
}
// Stop the computation on the backend.
func (c *Computation) Stop() error {
return c.StopWithReason("")
}
// StopWithReason stops the computation with a given reason. This reason will
// be reflected in the control message that signals the end of the job/channel.
func (c *Computation) StopWithReason(reason string) error {
return c.client.Stop(&StopRequest{
Reason: reason,
Handle: c.handle,
})
}
// Simple struct that allows one goroutine to signal a bunch of other
// goroutines that are waiting on a condition, with a timeout. It is basically
// similar to sync.Cond except the lock in internal (but accessible) and you
// can set a timeout.
type updateSignal struct {
sync.Mutex
s chan struct{}
}
// WaitWithTimeout waits for the given duration, remaining, for the signal to
// be triggered. It is assumed that the caller holds u.Mutex upon calling.
// When this function returns, that mutex will be relocked, but will have been
// unlocked for some time while waiting. The remaining arg will be updated in
// place to contain the remaining time when the function returned.
func (u *updateSignal) WaitWithTimeout(ctx context.Context, remaining *time.Duration) error {
start := time.Now()
if u.s == nil {
u.reset()
}
sig := u.s
u.Unlock()
defer func() {
newRemaining := *remaining - time.Since(start)
if newRemaining > 0 {
*remaining = newRemaining
} else {
*remaining = 0
}
}()
defer u.Lock()
ctxTimeout, cancel := context.WithTimeout(ctx, *remaining)
defer cancel()
select {
case <-ctxTimeout.Done():
return ctxTimeout.Err()
case <-sig:
return nil
}
}
func (u *updateSignal) reset() {
u.s = make(chan struct{})
}
func (u *updateSignal) SignalAll() {
u.Lock()
if u.s != nil {
close(u.s)
u.reset()
}
u.Unlock()
}