-
Notifications
You must be signed in to change notification settings - Fork 69
/
eph.go
469 lines (391 loc) · 13.3 KB
/
eph.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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
// Package eph provides functionality for balancing load of Event Hub receivers through scheduling receivers across
// processes and machines.
package eph
// MIT License
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE
import (
"context"
"errors"
"fmt"
"os"
"os/signal"
"sync"
"time"
"github.com/Azure/azure-amqp-common-go/v3/auth"
"github.com/Azure/azure-amqp-common-go/v3/conn"
"github.com/Azure/azure-amqp-common-go/v3/sas"
"github.com/Azure/azure-amqp-common-go/v3/uuid"
"github.com/Azure/azure-event-hubs-go/v3"
"github.com/Azure/azure-event-hubs-go/v3/persist"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/devigned/tab"
)
const (
banner = `
______ __ __ __ __
/ ____/ _____ ____ / /_/ / / /_ __/ /_ _____
/ __/ | | / / _ \/ __ \/ __/ /_/ / / / / __ \/ ___/
/ /___ | |/ / __/ / / / /_/ __ / /_/ / /_/ (__ )
/_____/ |___/\___/_/ /_/\__/_/ /_/\__,_/_.___/____/
`
exitPrompt = "=> processing events, ctrl+c to exit"
)
type (
// EventProcessorHost provides functionality for coordinating and balancing load across multiple Event Hub partitions
EventProcessorHost struct {
namespace string
hubName string
name string
consumerGroup string
tokenProvider auth.TokenProvider
client *eventhub.Hub
leaser Leaser
checkpointer Checkpointer
scheduler *scheduler
handlers map[string]eventhub.Handler
hostMu sync.Mutex
handlersMu sync.Mutex
partitionIDs []string
noBanner bool
webSocketConnection bool
env *azure.Environment
}
// EventProcessorHostOption provides configuration options for an EventProcessorHost
EventProcessorHostOption func(host *EventProcessorHost) error
// Receiver provides the ability to handle Event Hub events
Receiver interface {
Receive(ctx context.Context, handler eventhub.Handler) (close func() error, err error)
}
checkpointPersister struct {
checkpointer Checkpointer
}
// HandlerID is a UUID in string format that identifies a registered handler
HandlerID string
)
// WithNoBanner will configure an EventProcessorHost to not output the banner upon start
func WithNoBanner() EventProcessorHostOption {
return func(host *EventProcessorHost) error {
host.noBanner = true
return nil
}
}
// WithConsumerGroup will configure an EventProcessorHost to a specific consumer group
func WithConsumerGroup(consumerGroup string) EventProcessorHostOption {
return func(host *EventProcessorHost) error {
host.consumerGroup = consumerGroup
return nil
}
}
// WithEnvironment will configure an EventProcessorHost to use the specified Azure Environment
func WithEnvironment(env azure.Environment) EventProcessorHostOption {
return func(host *EventProcessorHost) error {
host.env = &env
return nil
}
}
// WithWebSocketConnection will configure an EventProcessorHost to use websockets
func WithWebSocketConnection() EventProcessorHostOption {
return func(host *EventProcessorHost) error {
host.webSocketConnection = true
return nil
}
}
// NewFromConnectionString builds a new Event Processor Host from an Event Hub connection string which can be found in
// the Azure portal
func NewFromConnectionString(ctx context.Context, connStr string, leaser Leaser, checkpointer Checkpointer, opts ...EventProcessorHostOption) (*EventProcessorHost, error) {
span, ctx := startConsumerSpanFromContext(ctx, "eph.NewFromConnectionString")
defer span.End()
hostName, err := uuid.NewV4()
if err != nil {
tab.For(ctx).Error(err)
return nil, err
}
parsed, err := conn.ParsedConnectionFromStr(connStr)
if err != nil {
tab.For(ctx).Error(err)
return nil, err
}
tokenProvider, err := sas.NewTokenProvider(sas.TokenProviderWithKey(parsed.KeyName, parsed.Key))
if err != nil {
tab.For(ctx).Error(err)
return nil, err
}
host := &EventProcessorHost{
namespace: parsed.Namespace,
name: hostName.String(),
hubName: parsed.HubName,
tokenProvider: tokenProvider,
handlers: make(map[string]eventhub.Handler),
leaser: leaser,
checkpointer: checkpointer,
noBanner: false,
}
for _, opt := range opts {
err := opt(host)
if err != nil {
return nil, err
}
}
persister := checkpointPersister{checkpointer: checkpointer}
hubOpts := []eventhub.HubOption{eventhub.HubWithOffsetPersistence(persister)}
if host.env != nil {
hubOpts = append(hubOpts, eventhub.HubWithEnvironment(*host.env))
}
if host.webSocketConnection {
hubOpts = append(hubOpts, eventhub.HubWithWebSocketConnection())
}
client, err := eventhub.NewHubFromConnectionString(connStr, hubOpts...)
if err != nil {
tab.For(ctx).Error(err)
return nil, err
}
runtimeInfo, err := client.GetRuntimeInformation(ctx)
if err != nil {
tab.For(ctx).Error(err)
return nil, err
}
host.client = client
host.partitionIDs = runtimeInfo.PartitionIDs
return host, nil
}
// New constructs a new instance of an EventHostProcessor
func New(ctx context.Context, namespace, hubName string, tokenProvider auth.TokenProvider, leaser Leaser, checkpointer Checkpointer, opts ...EventProcessorHostOption) (*EventProcessorHost, error) {
span, ctx := startConsumerSpanFromContext(ctx, "eph.New")
defer span.End()
hostName, err := uuid.NewV4()
if err != nil {
return nil, err
}
host := &EventProcessorHost{
namespace: namespace,
name: hostName.String(),
hubName: hubName,
tokenProvider: tokenProvider,
handlers: make(map[string]eventhub.Handler),
leaser: leaser,
checkpointer: checkpointer,
noBanner: false,
}
for _, opt := range opts {
err := opt(host)
if err != nil {
return nil, err
}
}
persister := checkpointPersister{checkpointer: checkpointer}
hubOpts := []eventhub.HubOption{eventhub.HubWithOffsetPersistence(persister)}
if host.env != nil {
hubOpts = append(hubOpts, eventhub.HubWithEnvironment(*host.env))
}
if host.webSocketConnection {
hubOpts = append(hubOpts, eventhub.HubWithWebSocketConnection())
}
client, err := eventhub.NewHub(namespace, hubName, tokenProvider, hubOpts...)
if err != nil {
return nil, err
}
runtimeInfo, err := client.GetRuntimeInformation(ctx)
if err != nil {
return nil, err
}
host.client = client
host.partitionIDs = runtimeInfo.PartitionIDs
return host, nil
}
// RegisteredHandlerIDs will return the registered event handler IDs
func (h *EventProcessorHost) RegisteredHandlerIDs() []HandlerID {
h.handlersMu.Lock()
defer h.handlersMu.Unlock()
ids := make([]HandlerID, len(h.handlers))
count := 0
for key := range h.handlers {
ids[count] = HandlerID(key)
count++
}
return ids
}
// RegisterHandler will register an event handler which will receive events after Start or StartNonBlocking is called
func (h *EventProcessorHost) RegisterHandler(ctx context.Context, handler eventhub.Handler) (HandlerID, error) {
span, _ := startConsumerSpanFromContext(ctx, "eph.EventProcessorHost.RegisterHandler")
defer span.End()
h.handlersMu.Lock()
defer h.handlersMu.Unlock()
id, err := uuid.NewV4()
if err != nil {
return "", err
}
h.handlers[id.String()] = handler
return HandlerID(id.String()), nil
}
// UnregisterHandler will remove an event handler from receiving events, and will close the EventProcessorHost if it is
// the last handler registered.
func (h *EventProcessorHost) UnregisterHandler(ctx context.Context, id HandlerID) {
span, ctx := startConsumerSpanFromContext(ctx, "eph.EventProcessorHost.UnregisterHandler")
defer span.End()
h.handlersMu.Lock()
defer h.handlersMu.Unlock()
delete(h.handlers, string(id))
if len(h.handlers) == 0 {
if err := h.Close(ctx); err != nil {
tab.For(ctx).Error(err)
}
}
}
// Start begins processing of messages for registered handlers on the EventHostProcessor. The call is blocking.
func (h *EventProcessorHost) Start(ctx context.Context) error {
span, ctx := startConsumerSpanFromContext(ctx, "eph.EventProcessorHost.Start")
defer span.End()
if !h.noBanner {
fmt.Print(banner)
fmt.Println(exitPrompt)
}
if len(h.handlers) == 0 {
return errors.New("no handlers have been registered; call RegisterHandler to setup an event handler")
}
if err := h.setup(ctx); err != nil {
return err
}
go func() {
span := tab.FromContext(ctx)
ctx := tab.NewContext(context.Background(), span)
h.scheduler.Run(ctx)
}()
// Wait for a signal to quit:
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, os.Interrupt)
<-signalChan
return h.Close(ctx)
}
// StartNonBlocking begins processing of messages for registered handlers
func (h *EventProcessorHost) StartNonBlocking(ctx context.Context) error {
span, ctx := startConsumerSpanFromContext(ctx, "eph.EventProcessorHost.StartNonBlocking")
defer span.End()
if !h.noBanner {
fmt.Print(banner)
}
if err := h.setup(ctx); err != nil {
return err
}
go func() {
span := tab.FromContext(ctx)
ctx := tab.NewContext(context.Background(), span)
h.scheduler.Run(ctx)
}()
return nil
}
// GetName returns the name of the EventProcessorHost
func (h *EventProcessorHost) GetName() string {
return h.name
}
// GetPartitionIDs fetches the partition IDs for the Event Hub
func (h *EventProcessorHost) GetPartitionIDs() []string {
return h.partitionIDs
}
// PartitionIDsBeingProcessed returns the partition IDs currently receiving messages
func (h *EventProcessorHost) PartitionIDsBeingProcessed() []string {
return h.scheduler.getPartitionIDsBeingProcessed()
}
// Close stops the EventHostProcessor from processing messages
func (h *EventProcessorHost) Close(ctx context.Context) error {
if !h.noBanner {
fmt.Println("shutting down...")
}
if h.scheduler != nil {
if err := h.scheduler.Stop(ctx); err != nil {
if h.client != nil {
_ = h.client.Close(ctx)
}
return err
}
}
if h.leaser != nil {
_ = h.leaser.Close()
}
if h.checkpointer != nil {
_ = h.checkpointer.Close()
}
return h.client.Close(ctx)
}
func (h *EventProcessorHost) setup(ctx context.Context) error {
h.hostMu.Lock()
defer h.hostMu.Unlock()
span, ctx := startConsumerSpanFromContext(ctx, "eph.EventProcessorHost.setup")
defer span.End()
if h.scheduler == nil {
h.leaser.SetEventHostProcessor(h)
h.checkpointer.SetEventHostProcessor(h)
if err := h.leaser.EnsureStore(ctx); err != nil {
return err
}
if err := h.checkpointer.EnsureStore(ctx); err != nil {
return err
}
scheduler := newScheduler(h)
for _, partitionID := range h.partitionIDs {
h.leaser.EnsureLease(ctx, partitionID)
h.checkpointer.EnsureCheckpoint(ctx, partitionID)
}
h.scheduler = scheduler
}
return nil
}
func (h *EventProcessorHost) compositeHandlers() eventhub.Handler {
return func(ctx context.Context, event *eventhub.Event) error {
span, ctx := startConsumerSpanFromContext(ctx, "eph.EventProcessorHost.compositeHandlers")
defer span.End()
h.handlersMu.Lock()
defer h.handlersMu.Unlock()
// we accept that this will contain any of the possible len(h.handlers) errors
// as it will be used to later decide of delivery is considered a failure
// and NOT further inspected
var lastError error
wg := &sync.WaitGroup{}
for _, handler := range h.handlers {
wg.Add(1)
go func(boundHandler eventhub.Handler) {
defer wg.Done() // consider if panics should be cought here, too. Currently would crash process
if err := boundHandler(ctx, event); err != nil {
lastError = err
tab.For(ctx).Error(err)
}
}(handler)
}
wg.Wait()
return lastError
}
}
func (c checkpointPersister) Write(namespace, name, consumerGroup, partitionID string, checkpoint persist.Checkpoint) error {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
return c.checkpointer.UpdateCheckpoint(ctx, partitionID, checkpoint)
}
func (c checkpointPersister) Read(namespace, name, consumerGroup, partitionID string) (persist.Checkpoint, error) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
return c.checkpointer.EnsureCheckpoint(ctx, partitionID)
}
func startConsumerSpanFromContext(ctx context.Context, operationName string) (tab.Spanner, context.Context) {
ctx, span := tab.StartSpan(ctx, operationName)
eventhub.ApplyComponentInfo(span)
span.AddAttributes(tab.StringAttribute("span.kind", "consumer"))
return span, ctx
}