-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbus.go
952 lines (788 loc) · 17.8 KB
/
bus.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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
package bus
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"iter"
"strconv"
"strings"
"time"
)
var (
Version = "dev"
GitCommit = ""
)
//
// Event
//
type Event struct {
Id string `json:"id"`
TraceId string `json:"trace_id,omitempty"`
Subject string `json:"subject"`
ResponseSubject string `json:"response_subject,omitempty"`
Payload json.RawMessage `json:"payload"`
CreatedAt time.Time `json:"created_at"`
Index int64 `json:"index"`
// for internal use
consumerId string
acker Acker
putter Putter
// Internal state for serialization
writeState int // Tracks which field we're writing
tc trackCopy
}
// NOTE: I had to implement Read method to enhance the performance of the code
// with the current implementation I gained around 50x performance improvement
func (e *Event) Read(p []byte) (n int, err error) {
for len(p) > 0 {
switch e.writeState {
case 0:
{
n1 := e.tc.Copy(p, []byte(`{`), 0)
n += n1
p = p[n1:]
if n1 < 1 {
return n, nil
}
e.writeState = 1
}
case 1: // Write "id" field
{
field := []byte(`"id":"`)
n1 := e.tc.Copy(p, field, 1)
n += n1
p = p[n1:]
if n1 < len(field) {
return n, nil
}
e.writeState = 2
}
case 2: // Write Id value
{
if len(e.Id) == 0 {
e.writeState = 3
continue
}
n1 := e.tc.Copy(p, []byte(e.Id), 2)
n += n1
p = p[n1:]
if n1 < len(e.Id) {
return n, nil
}
e.writeState = 3
}
case 3: // close "id" field
{
n1 := e.tc.Copy(p, []byte(`"`), 3)
n += n1
p = p[n1:]
if n1 < 1 {
return n, nil
}
e.writeState = 4
}
case 4: // Write "trace_id" field
{
if len(e.TraceId) == 0 {
e.writeState = 7 // skip trace_id field
continue
}
field := []byte(`,"trace_id":"`)
n1 := e.tc.Copy(p, field, 4)
n += n1
p = p[n1:]
if n1 < len(field) {
return n, nil
}
e.writeState = 5
}
case 5: // Write TraceId value
{
n1 := e.tc.Copy(p, []byte(e.TraceId), 5)
n += n1
p = p[n1:]
if n1 < len(e.TraceId) {
return n, nil
}
e.writeState = 6
}
case 6: // close "trace_id" field
{
n1 := e.tc.Copy(p, []byte(`"`), 6)
n += n1
p = p[n1:]
if n1 < 1 {
return n, nil
}
e.writeState = 7
}
case 7: // Write "subject" field
{
field := []byte(`,"subject":"`)
n1 := e.tc.Copy(p, field, 7)
n += n1
p = p[n1:]
if n1 < len(field) {
return n, nil
}
e.writeState = 8
}
case 8: // Write Subject value
{
n1 := e.tc.Copy(p, []byte(e.Subject), 8)
n += n1
p = p[n1:]
if n1 < len(e.Subject) {
return n, nil
}
e.writeState = 9
}
case 9: // close "subject" field
{
n1 := e.tc.Copy(p, []byte(`"`), 9)
n += n1
p = p[n1:]
if n1 < 1 {
return n, nil
}
e.writeState = 10
}
case 10: // Write "response_subject" field
{
if len(e.ResponseSubject) == 0 {
e.writeState = 13 // skip response_subject field
continue
}
field := []byte(`,"response_subject":"`)
n1 := e.tc.Copy(p, field, 10)
n += n1
p = p[n1:]
if n1 < len(field) {
return n, nil
}
e.writeState = 11
}
case 11: // Write ResponseSubject value
{
n1 := e.tc.Copy(p, []byte(e.ResponseSubject), 11)
n += n1
p = p[n1:]
if n1 < len(e.ResponseSubject) {
return n, nil
}
e.writeState = 12
}
case 12: // close "response_subject" field
{
n1 := e.tc.Copy(p, []byte(`"`), 12)
n += n1
p = p[n1:]
if n1 < 1 {
return n, nil
}
e.writeState = 13
}
case 13: // Write "created_at" field
{
field := []byte(`,"created_at":"`)
n1 := e.tc.Copy(p, field, 13)
n += n1
p = p[n1:]
if n1 < len(field) {
return n, nil
}
e.writeState = 14
}
case 14: // Write CreatedAt value
{
createdAt := e.CreatedAt.Format(time.RFC3339)
n1 := e.tc.Copy(p, []byte(createdAt), 14)
n += n1
p = p[n1:]
if n1 < len(createdAt) {
return n, nil
}
e.writeState = 15
}
case 15: // close "created_at" field
{
n1 := e.tc.Copy(p, []byte(`"`), 15)
n += n1
p = p[n1:]
if n1 < 1 {
return n, nil
}
e.writeState = 16
}
case 16: // Write "payload" field
{
if len(e.Payload) == 0 {
e.writeState = 18 // skip payload field
continue
}
field := []byte(`,"payload":`)
n1 := e.tc.Copy(p, field, 16)
n += n1
p = p[n1:]
if n1 < len(field) {
return n, nil
}
e.writeState = 17
}
case 17: // Write Payload value
{
n1 := e.tc.Copy(p, e.Payload, 17)
n += n1
p = p[n1:]
if n1 < len(e.Payload) {
return n, nil
}
e.writeState = 18
}
case 18: // Write Index
{
if e.Index == 0 {
e.writeState = 20 // skip index field
continue
}
field := []byte(`,"index":`)
n1 := e.tc.Copy(p, field, 18)
n += n1
p = p[n1:]
if n1 < len(field) {
return n, nil
}
e.writeState = 19
}
case 19: // Write Index value
{
index := strconv.FormatInt(e.Index, 10)
n1 := e.tc.Copy(p, []byte(index), 19)
n += n1
p = p[n1:]
if n1 < len(index) {
return n, nil
}
e.writeState = 20
}
case 20: // close
{
n1 := e.tc.Copy(p, []byte(`}`), 18)
n += n1
p = p[n1:]
if n1 < 1 {
return n, nil
}
e.writeState = 21
}
default:
return n, io.EOF
}
}
return n, nil
}
func (e *Event) Write(b []byte) (int, error) {
if len(b) == 0 {
return 0, errors.New("empty input")
}
// Skip leading whitespace
pos := 0
for pos < len(b) && (b[pos] == ' ' || b[pos] == '\n' || b[pos] == '\t' || b[pos] == '\r') {
pos++
}
// Expect opening brace
if pos >= len(b) || b[pos] != '{' {
return 0, errors.New("expected opening brace")
}
pos++
for pos < len(b) {
// Skip whitespace
for pos < len(b) && (b[pos] == ' ' || b[pos] == '\n' || b[pos] == '\t' || b[pos] == '\r') {
pos++
}
if pos >= len(b) {
return 0, errors.New("unexpected end of input")
}
// Check for closing brace
if b[pos] == '}' {
pos++
break
}
// Expect quote for field name
if b[pos] != '"' {
return 0, errors.New("expected quote before field name")
}
pos++
// Read field name
fieldStart := pos
for pos < len(b) && b[pos] != '"' {
pos++
}
if pos >= len(b) {
return 0, errors.New("unterminated field name")
}
fieldName := string(b[fieldStart:pos])
pos++ // Skip closing quote
// Skip whitespace and colon
for pos < len(b) && (b[pos] == ' ' || b[pos] == '\n' || b[pos] == '\t' || b[pos] == '\r') {
pos++
}
if pos >= len(b) || b[pos] != ':' {
return 0, errors.New("expected colon after field name")
}
pos++
// Skip whitespace before value
for pos < len(b) && (b[pos] == ' ' || b[pos] == '\n' || b[pos] == '\t' || b[pos] == '\r') {
pos++
}
// Parse value based on field name
switch fieldName {
case "id":
val, newPos, err := parseString(b[pos:])
if err != nil {
return 0, err
}
e.Id = val
pos += newPos
case "trace_id":
val, newPos, err := parseString(b[pos:])
if err != nil {
return 0, err
}
e.TraceId = val
pos += newPos
case "subject":
val, newPos, err := parseString(b[pos:])
if err != nil {
return 0, err
}
e.Subject = val
pos += newPos
case "response_subject":
val, newPos, err := parseString(b[pos:])
if err != nil {
return 0, err
}
e.ResponseSubject = val
pos += newPos
case "created_at":
val, newPos, err := parseString(b[pos:])
if err != nil {
return 0, err
}
// Parse ISO 8601 timestamp
t, err := time.Parse(time.RFC3339, val)
if err != nil {
return 0, errors.New("invalid timestamp format")
}
e.CreatedAt = t
pos += newPos
case "payload":
if b[pos] == 'n' && pos+3 < len(b) && string(b[pos:pos+4]) == "null" {
e.Payload = nil
pos += 4
} else {
// Find the end of the JSON value (could be object, array, string, number, etc.)
depth := 0
dataStart := pos
inString := false
for pos < len(b) {
if !inString {
if b[pos] == '{' || b[pos] == '[' {
depth++
} else if b[pos] == '}' || b[pos] == ']' {
depth--
if depth < 0 {
break
}
} else if b[pos] == '"' {
inString = true
} else if b[pos] == ',' && depth == 0 {
break
}
} else {
if b[pos] == '\\' {
pos++
} else if b[pos] == '"' {
inString = false
}
}
pos++
}
e.Payload = json.RawMessage(b[dataStart:pos])
}
case "index":
val, newPos, err := parseNumber(b[pos:])
if err != nil {
return 0, err
}
index, err := strconv.ParseInt(val, 10, 64)
if err != nil {
return 0, err
}
e.Index = index
pos += newPos
}
// Skip whitespace
for pos < len(b) && (b[pos] == ' ' || b[pos] == '\n' || b[pos] == '\t' || b[pos] == '\r') {
pos++
}
// Check for comma or closing brace
if pos >= len(b) {
return 0, errors.New("unexpected end of input")
}
if b[pos] == ',' {
pos++
} else if b[pos] != '}' {
return 0, errors.New("expected comma or closing brace")
}
}
return pos, nil
}
// Helper function to parse a JSON number
func parseNumber(b []byte) (string, int, error) {
if len(b) == 0 {
return "", 0, errors.New("expected number")
}
pos := 0
if b[pos] == '-' {
pos++
}
if pos >= len(b) || (b[pos] < '0' || b[pos] > '9') {
return "", 0, errors.New("expected number")
}
for pos < len(b) && b[pos] >= '0' && b[pos] <= '9' {
pos++
}
if pos < len(b) && b[pos] == '.' {
pos++
for pos < len(b) && b[pos] >= '0' && b[pos] <= '9' {
pos++
}
}
if pos < len(b) && (b[pos] == 'e' || b[pos] == 'E') {
pos++
if pos < len(b) && (b[pos] == '+' || b[pos] == '-') {
pos++
}
if pos >= len(b) || (b[pos] < '0' || b[pos] > '9') {
return "", 0, errors.New("expected number")
}
for pos < len(b) && b[pos] >= '0' && b[pos] <= '9' {
pos++
}
}
return string(b[:pos]), pos, nil
}
// Helper function to parse a JSON string
func parseString(b []byte) (string, int, error) {
if len(b) == 0 || b[0] != '"' {
return "", 0, errors.New("expected string")
}
pos := 1
var result bytes.Buffer
for pos < len(b) {
if b[pos] == '\\' {
if pos+1 >= len(b) {
return "", 0, errors.New("incomplete escape sequence")
}
pos++
switch b[pos] {
case '"', '\\', '/':
result.WriteByte(b[pos])
case 'b':
result.WriteByte('\b')
case 'f':
result.WriteByte('\f')
case 'n':
result.WriteByte('\n')
case 'r':
result.WriteByte('\r')
case 't':
result.WriteByte('\t')
default:
return "", 0, errors.New("invalid escape sequence")
}
} else if b[pos] == '"' {
return result.String(), pos + 1, nil
} else {
result.WriteByte(b[pos])
}
pos++
}
return "", 0, errors.New("unterminated string")
}
func (e *Event) validate() error {
// subject is required
if e.Subject == "" {
return errors.New("subject is required")
}
// subject must be in a form of "a.b.c"
if strings.Contains(e.Subject, "*") || strings.Contains(e.Subject, ">") {
return errors.New("subject should not have * or >")
}
// simple validation for response subject
if e.ResponseSubject != "" {
if strings.Contains(e.ResponseSubject, "*") || strings.Contains(e.ResponseSubject, ">") {
return errors.New("response subject should not have * or >")
}
}
return nil
}
func (e *Event) Ack(ctx context.Context, opts ...AckOpt) error {
if err := e.acker.Ack(ctx, e.consumerId, e.Id); err != nil {
return fmt.Errorf("failed to ack event: %w", err)
}
if e.ResponseSubject == "" {
return nil
}
var putOpts = []PutOpt{
WithSubject(e.ResponseSubject),
}
for _, opt := range opts {
if o, ok := opt.(PutOpt); ok {
putOpts = append(putOpts, o)
}
}
if err := e.putter.Put(ctx, putOpts...).Error(); err != nil {
return fmt.Errorf("failed to send response: %w", err)
}
return nil
}
const (
AckManual = "manual" // client should ack the event
AckNone = "none" // no need to ack and server push the event to the client as fast as possible
)
const (
StartOldest = "oldest"
StartNewest = "newest"
)
const (
DefaultAck = AckNone
DefaultStart = StartNewest
DefaultRedelivery = 5 * time.Second
)
//
// Putter
//
type Response struct {
err error
Id string
Index int64
CreatedAt time.Time
Payload json.RawMessage
}
func (s *Response) String() string {
var sb strings.Builder
sb.WriteString("id: ")
sb.WriteString(s.Id)
if s.Index != -1 {
sb.WriteString(", index: ")
sb.WriteString(fmt.Sprintf("%d", s.Index))
}
sb.WriteString(", created_at: ")
sb.WriteString(s.CreatedAt.Format(time.RFC3339Nano))
return sb.String()
}
func (r *Response) Error() error {
if r.err != nil {
return r.err
}
if len(r.Payload) == 0 || r.Payload[0] == '{' || r.Payload[0] == '[' {
return nil
}
return fmt.Errorf("%s", r.Payload)
}
type putOpt struct {
event Event
confirmCount int
}
type PutOpt interface {
configurePut(*putOpt) error
}
type PutOptFunc func(*putOpt) error
func (f PutOptFunc) configurePut(p *putOpt) error {
return f(p)
}
type Putter interface {
Put(ctx context.Context, opts ...PutOpt) *Response
}
//
// Getter
//
type getOpt struct {
subject string
ackStrategy string
redelivery time.Duration
start string
metaFn func(map[string]string)
}
// GetOpt is an interface that can be used to configure the Get operation
type GetOpt interface {
configureGet(*getOpt) error
}
type GetOptFunc func(*getOpt) error
func (f GetOptFunc) configureGet(g *getOpt) error {
return f(g)
}
// Getter is an interface that can be used to get events from the bus
type Getter interface {
Get(ctx context.Context, opts ...GetOpt) iter.Seq2[*Event, error]
}
//
// Acker
//
type ackOpt struct {
payload json.RawMessage
}
// AckOpt is an interface that can be used to configure the Ack operation
type AckOpt interface {
configureAck(*ackOpt) error
}
// Acker is an interface that can be used to acknowledge the event
type Acker interface {
Ack(ctx context.Context, consumerId string, eventId string) error
}
//
// Options
// options are utility functions which can be used to configure the Putter and Getter
// Subject
type subjectOpt string
var _ PutOpt = (*subjectOpt)(nil)
var _ GetOpt = (*subjectOpt)(nil)
func (s subjectOpt) configurePut(p *putOpt) error {
if p.event.Subject != "" {
return errors.New("subject already set")
}
p.event.Subject = string(s)
// should not have * or >
if strings.Contains(string(s), "*") || strings.Contains(string(s), ">") {
return errors.New("subject should not have * or >")
}
return nil
}
func (s subjectOpt) configureGet(g *getOpt) error {
if g.subject != "" {
return errors.New("subject already set")
}
// should not starts with * or >
if strings.HasPrefix(string(s), "*") || strings.HasPrefix(string(s), ">") {
return errors.New("subject should not starts with * or >")
}
// should not have anything after >
if strings.Contains(string(s), ">") && !strings.HasSuffix(string(s), ">") {
return errors.New("subject should not have anything after >")
}
g.subject = string(s)
return nil
}
// WithSubject sets the subject of the event and consumer
func WithSubject(subject string) subjectOpt {
return subjectOpt(subject)
}
func WithStartFrom(start string) GetOpt {
return GetOptFunc(func(g *getOpt) error {
if start != StartOldest && start != StartNewest && !strings.HasPrefix(start, "e_") {
return errors.New("invalid start from")
}
g.start = start
return nil
})
}
func WithDelivery(duration time.Duration) GetOpt {
return GetOptFunc(func(g *getOpt) error {
if duration < 0 {
return errors.New("delivery duration should be greater than 0")
}
g.redelivery = duration
return nil
})
}
func WithAckStrategy(strategy string) GetOpt {
return GetOptFunc(func(g *getOpt) error {
if strategy != AckManual && strategy != AckNone {
return errors.New("invalid ack strategy")
}
g.ackStrategy = strategy
return nil
})
}
func WithExtractMeta(fn func(map[string]string)) GetOpt {
return GetOptFunc(func(g *getOpt) error {
if g.metaFn != nil {
return errors.New("meta function already set")
}
g.metaFn = fn
return nil
})
}
func WithConfirm(n int) PutOpt {
return PutOptFunc(func(p *putOpt) error {
if n < 0 {
return errors.New("confirm count should be greater than 0")
}
if p.event.ResponseSubject != "" {
return errors.New("response subject already set")
}
p.confirmCount = n
p.event.ResponseSubject = newInboxSubject()
return nil
})
}
func WithRequestReply() PutOpt {
return PutOptFunc(func(p *putOpt) error {
if p.confirmCount != 0 {
return errors.New("confirm count already set")
}
p.event.ResponseSubject = newInboxSubject()
return nil
})
}
// Payload
type dataOpt struct{ value any }
func (d *dataOpt) configurePut(p *putOpt) error {
if p.event.Payload != nil {
return errors.New("event's payload already set")
}
// how to encode error value ?? {error: "error message"} or simple string?????
data, err := json.Marshal(d.value)
if err != nil {
return err
}
p.event.Payload = json.RawMessage(data)
return nil
}
func (d *dataOpt) configureAck(a *ackOpt) error {
if a.payload != nil {
return errors.New("payload already set")
}
data, err := json.Marshal(d.value)
if err != nil {
return err
}
a.payload = json.RawMessage(data)
return nil
}
func WithData(data any) *dataOpt {
return &dataOpt{data}
}
//
// Trace Id
//
type traceIdOpt struct {
value string
}
var _ PutOpt = (*traceIdOpt)(nil)
func (o *traceIdOpt) configurePut(opt *putOpt) error {
if opt.event.TraceId != "" {
return fmt.Errorf("trace id option already set to %s", opt.event.TraceId)
}
opt.event.TraceId = o.value
return nil
}
func WithTraceId(traceId string) *traceIdOpt {
return &traceIdOpt{traceId}
}