forked from Graphmasters/occamy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_test.go
1217 lines (979 loc) · 38.3 KB
/
server_test.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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package occamy_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"runtime/debug"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/Graphmasters/occamy"
)
/*
Many tests in this file overlap in what they are testing. This is because the
server is stateful and testing one particular method usually requires other
calls to ensure the server is in the desired state.
The tests have been written so the tests should fail if the occamy package
has been incorrectly implemented and panic if the test itself has been
incorrectly implemented.
*/
const (
ShortDuration = 10 * time.Millisecond
)
// TestServer_ExpandTasks tests that the expand method can be called without error.
func TestServer_ExpandTasks(t *testing.T) {
server, monitors := NewServer(nil)
server.ExpandTasks()
assertErrorIsNil(t, monitors.Error.nextError(), "error after expand")
assertResourceMonitorStatusMatch(t, monitors.Resource, DefaultResources, 0, 0, 0, "resources after expand")
testServerShutdownSuccess(t, server, monitors, DefaultResources)
}
// TestServer_ExpandTasks_expandableExternalTask tests that calling ExpandTasks while
// there is an "external" task will be added to a slot and after a second call
// of ExpandTasks will use all available resources.
func TestServer_ExpandTasks_expandableExternalTask(t *testing.T) {
controller := NewTaskController()
handler := NewStandardHandler(controller)
server, monitors := NewServer(handler.Handle)
mf := NewMessageFactory()
msg := mf.NewSimpleTaskMessage(true)
server.HandleControlMsg(msg)
assertResourceMonitorStatusMatch(t, monitors.Resource, DefaultResources, 0, 0, 0, "resources after request message in control handler")
time.Sleep(ShortDuration)
server.ExpandTasks()
assertErrorIsNil(t, monitors.Error.nextError(), "error after expand")
assertResourceMonitorStatusMatch(t, monitors.Resource, DefaultResources-1, 0, 0, 1, "resources after expand")
server.ExpandTasks()
assertErrorIsNil(t, monitors.Error.nextError(), "error after second expand")
assertResourceMonitorStatusMatch(t, monitors.Resource, 0, 0, 0, DefaultResources, "resources after second expand")
testServerShutdownSuccess(t, server, monitors, DefaultResources)
}
// TestServer_Expand_expandableExternalTask tests that calling ExpandTasks while
// there is a protected expandable task will use all available resources.
func TestServer_ExpandTasks_expandableProtectedTask(t *testing.T) {
controller := NewTaskController()
handler := NewStandardHandler(controller)
server, monitors := NewServer(handler.Handle)
mf := NewMessageFactory()
msg := mf.NewSimpleTaskMessage(true)
testHandleRequestMessageSuccess(t, server, monitors, msg, "")
server.ExpandTasks()
assertErrorIsNil(t, monitors.Error.nextError(), "error after expand")
assertResourceMonitorStatusMatch(t, monitors.Resource, 0, 1, DefaultResources-1, 0, "resources after expand")
testServerShutdownSuccess(t, server, monitors, DefaultResources)
}
// TestServer_ExpandTasks_expansionBuffer tests that the ExpandTasks method will respect
// the expansion buffer.
func TestServer_ExpandTasks_expansionBuffer(t *testing.T) {
controller := NewTaskController()
handler := NewStandardHandler(controller)
monitors := NewMonitors(DefaultResources)
server := occamy.NewServer(occamy.ServerConfig{
Slots: DefaultResources,
ExpansionSlotBuffer: 2,
ExpansionPeriod: 0,
KillTimeout: 100 * time.Millisecond,
HeaderKeyTaskID: HeaderKeyTaskID,
Handler: handler.Handle,
Monitors: occamy.Monitors{
Error: monitors.Error,
Latency: monitors.Latency,
Resource: monitors.Resource,
},
})
mf := NewMessageFactory()
msg := mf.NewSimpleTaskMessage(true)
testHandleRequestMessageSuccess(t, server, monitors, msg, "")
server.ExpandTasks()
assertErrorIsNil(t, monitors.Error.nextError(), "error after expand")
assertResourceMonitorStatusMatch(t, monitors.Resource, 2, 1, DefaultResources-3, 0, "resources after expand")
testServerShutdownSuccess(t, server, monitors, DefaultResources)
}
// TestServer_ExpandTasks_unexpandableProtectedTask tests that ExpandTasks will do nothing
// when there is a task that can not be expanded.
func TestServer_ExpandTasks_unexpandableProtectedTask(t *testing.T) {
controller := NewTaskController()
handler := NewStandardHandler(controller)
server, monitors := NewServer(handler.Handle)
mf := NewMessageFactory()
msg := mf.NewSimpleTaskMessage(false)
testHandleRequestMessageSuccess(t, server, monitors, msg, "")
server.ExpandTasks()
assertErrorIsNil(t, monitors.Error.nextError(), "error after expand")
assertResourceMonitorStatusMatch(t, monitors.Resource, DefaultResources-1, 1, 0, 0, "resources after expand")
testServerShutdownSuccess(t, server, monitors, DefaultResources)
}
// TestServer_HandleControlMsg tests that a control message can be handled.
func TestServer_HandleControlMsg(t *testing.T) {
server, monitors := NewServer(nil)
mf := NewMessageFactory()
msg := mf.NewCancelMessage("non-existent")
server.HandleControlMsg(msg)
assertErrorIsNil(t, monitors.Error.nextError(), "unexpected error after control message")
testServerShutdownSuccess(t, server, monitors, DefaultResources)
}
// TestServer_HandleControlMsg_cancelMultipleTasksWithSameID tests that if
// multiple task with the same ID are running the cancel message will be handled
// by all of them. This checks that the control message goes to multiple tasks
// with matching task IDs.
func TestServer_HandleControlMsg_cancelMultipleTasksWithSameID(t *testing.T) {
controller := NewTaskController()
handler := NewStandardHandler(controller)
server, monitors := NewServer(handler.Handle)
mf := NewMessageFactory()
msg := mf.NewSimpleTaskMessage(false)
testHandleRequestMessageSuccess(t, server, monitors, msg, "handling single message")
testHandleRequestMessageSuccess(t, server, monitors, msg, "handling single message")
cancel := mf.NewCancelMessage(msg.id)
server.HandleControlMsg(cancel)
time.Sleep(ShortDuration)
assertErrorIsNil(t, monitors.Error.nextError(), "unexpected error after control message")
assertResourceMonitorStatusMatch(t, monitors.Resource, DefaultResources, 0, 0, 0, "resources after server shutdown")
panicIfBoolIsFalse(controller.isStopped(msg.id), "task was should have been cancelled via a message not using the controller")
testServerShutdownSuccess(t, server, monitors, DefaultResources)
}
// TestServer_HandleControlMsg_cancelTask tests that if a task is running it can
// be cancelled via a control message.
func TestServer_HandleControlMsg_cancelTask(t *testing.T) {
controller := NewTaskController()
handler := NewStandardHandler(controller)
server, monitors := NewServer(handler.Handle)
mf := NewMessageFactory()
msg := mf.NewSimpleTaskMessage(false)
testHandleRequestMessageSuccess(t, server, monitors, msg, "handling single message")
cancel := mf.NewCancelMessage(msg.id)
server.HandleControlMsg(cancel)
time.Sleep(ShortDuration)
assertErrorIsNil(t, monitors.Error.nextError(), "unexpected error after control message")
assertResourceMonitorStatusMatch(t, monitors.Resource, DefaultResources, 0, 0, 0, "resources after server shutdown")
panicIfBoolIsFalse(controller.isStopped(msg.id), "task was should have been cancelled via a message not using the controller")
testServerShutdownSuccess(t, server, monitors, DefaultResources)
}
// TestServer_HandleControlMsg_cancelTaskOneOfMultipleTasks tests that a that if
// multiple tasks are running one of them can be cancelled. This checks that
// the control message is only handled by the task with the task with the
// matching task ID.
func TestServer_HandleControlMsg_cancelTaskOneOfMultipleTasks(t *testing.T) {
controller := NewTaskController()
handler := NewStandardHandler(controller)
server, monitors := NewServer(handler.Handle)
mf := NewMessageFactory()
msgs := mf.NewSimpleTaskMessages(4, false)
testHandleRequestMessagesSuccess(t, server, monitors, msgs, "handling single message")
cancel := mf.NewCancelMessage(msgs[2].id)
server.HandleControlMsg(cancel)
time.Sleep(ShortDuration)
assertErrorIsNil(t, monitors.Error.nextError(), "unexpected error after control message")
assertResourceMonitorStatusMatch(t, monitors.Resource, DefaultResources-3, 3, 0, 0, "resources after server shutdown")
assertMessageStatus(t, MessageStatusOpen, msgs[0], "message for running task")
assertMessageStatus(t, MessageStatusOpen, msgs[1], "message for running task")
assertMessageStatus(t, MessageStatusAcked, msgs[2], "message for cancelled task")
assertMessageStatus(t, MessageStatusOpen, msgs[3], "message for running task")
panicIfBoolIsFalse(controller.isStopped(msgs[2].id), "task was should have been cancelled via a message not using the controller")
testServerShutdownSuccess(t, server, monitors, DefaultResources)
}
// TestServer_HandleControlMsg_requestMessage tests if a request message can
// be handled as a control message without leading to an error.
func TestServer_HandleControlMsg_requestMessage(t *testing.T) {
controller := NewTaskController()
handler := NewStandardHandler(controller)
server, monitors := NewServer(handler.Handle)
mf := NewMessageFactory()
msg := mf.NewSimpleTaskMessage(false)
server.HandleControlMsg(msg)
assertErrorIsNil(t, monitors.Error.nextError(), "unexpected error after request message handled as a control message")
testServerShutdownSuccess(t, server, monitors, DefaultResources)
}
// TestServer_HandleRequestMsg tests that a message can be handled.
func TestServer_HandleRequestMsg(t *testing.T) {
controller := NewTaskController()
handler := NewStandardHandler(controller)
server, monitors := NewServer(handler.Handle)
mf := NewMessageFactory()
msg := mf.NewSimpleTaskMessage(false)
testHandleRequestMessageSuccess(t, server, monitors, msg, "handling single message")
testServerShutdownSuccess(t, server, monitors, DefaultResources)
}
// TestServer_HandleRequestMsg_messageAck tests that a messages can be handled
// and be an "acked"/"acknowledged".
func TestServer_HandleRequestMsg_messageAck(t *testing.T) {
controller := NewTaskController()
handler := NewStandardHandler(controller)
server, monitors := NewServer(handler.Handle)
mf := NewMessageFactory()
msg := mf.NewSimpleTaskMessage(false)
testHandleRequestMessageSuccess(t, server, monitors, msg, "handling single message")
controller.stop(msg.id, nil)
time.Sleep(ShortDuration)
assertErrorIsNil(t, monitors.Error.nextError(), "error after the task stopped")
assertResourceMonitorStatusMatch(t, monitors.Resource, DefaultResources, 0, 0, 0, "resources after server shutdown")
assertMessageStatus(t, MessageStatusAcked, msg, "message ack test")
testServerShutdownSuccess(t, server, monitors, DefaultResources)
}
// TestServer_HandleRequestMsg_messageRequeue tests that a messages can be
// handled and be "requeued".
func TestServer_HandleRequestMsg_messageRequeue(t *testing.T) {
controller := NewTaskController()
handler := NewStandardHandler(controller)
server, monitors := NewServer(handler.Handle)
mf := NewMessageFactory()
msg := mf.NewSimpleTaskMessage(false)
testHandleRequestMessageSuccess(t, server, monitors, msg, "handling single message")
testServerShutdownSuccess(t, server, monitors, DefaultResources)
assertMessageStatus(t, MessageStatusRequeued, msg, "message requeue test") // The message gets requeued after shutdown.
}
// TestServer_HandleRequestMsg_messageReject tests that a messages can be
// handled and be "rejected".
func TestServer_HandleRequestMsg_messageReject(t *testing.T) {
controller := NewTaskController()
handler := NewStandardHandler(controller)
server, monitors := NewServer(handler.Handle)
mf := NewMessageFactory()
msg := mf.NewSimpleTaskMessage(false)
testHandleRequestMessageSuccess(t, server, monitors, msg, "handling single message")
err := fmt.Errorf("error for TestServer_HandleRequestMsg_messageReject")
controller.stop(msg.id, err)
time.Sleep(ShortDuration)
assertErrorEqual(t, err, monitors.Error.nextError(), "no error after the task stopped")
assertResourceMonitorStatusMatch(t, monitors.Resource, DefaultResources, 0, 0, 0, "resources after server shutdown")
assertMessageStatus(t, MessageStatusRejected, msg, "message reject test")
testServerShutdownSuccess(t, server, monitors, DefaultResources)
}
// TestServer_HandleRequestMsg_multipleMessage tests that the server can
// successfully handle multiple messages.
func TestServer_HandleRequestMsg_multipleMessage(t *testing.T) {
controller := NewTaskController()
handler := NewStandardHandler(controller)
server, monitors := NewServer(handler.Handle)
mf := NewMessageFactory()
msgs := mf.NewSimpleTaskMessages(6, true)
testHandleRequestMessagesSuccess(t, server, monitors, msgs, "handling multiple messages")
controller.stop(msgs[0].id, nil)
controller.stop(msgs[1].id, nil)
time.Sleep(ShortDuration)
assertErrorIsNil(t, monitors.Error.nextError(), "errors after stopping tasks")
assertResourceMonitorStatusMatch(t, monitors.Resource, DefaultResources-4, 4, 0, 0, "resources after stopping tasks")
controller.stop(msgs[2].id, occamy.NewErrorf(occamy.ErrKindInvalidTask, "stopping msg 2"))
controller.stop(msgs[3].id, occamy.NewErrorf(occamy.ErrKindInvalidTask, "stopping msg 3"))
time.Sleep(ShortDuration)
assertErrorMonitorErrorCount(t, monitors.Error, 2, "check errors after tasks throwing errors")
assertErrorIsOccamyError(t, occamy.ErrKindInvalidTask, monitors.Error.nextError(), "checking error after tasks throwing error (1)")
assertErrorIsOccamyError(t, occamy.ErrKindInvalidTask, monitors.Error.nextError(), "checking error after tasks throwing error (2)")
assertResourceMonitorStatusMatch(t, monitors.Resource, DefaultResources-2, 2, 0, 0, "resources after stopping tasks")
testServerShutdownSuccess(t, server, monitors, DefaultResources)
}
// TestServer_HandleRequestMsg_overloadServer tests that the server will
// requeue messages if it is overloaded.
func TestServer_HandleRequestMsg_overloadServer(t *testing.T) {
controller := NewTaskController()
handler := NewStandardHandler(controller)
server, monitors := NewServer(handler.Handle)
mf := NewMessageFactory()
msgs := mf.NewSimpleTaskMessages(DefaultResources+1, true)
handleRequestMessages(server, msgs)
assertErrorIsNotNil(t, monitors.Error.nextError(), "handling more requests than possible should trigger error")
assertResourceMonitorStatusMatch(t, monitors.Resource, 0, DefaultResources, 0, 0, "resources after overloading")
assertMessageStatus(t, MessageStatusRequeued, msgs[DefaultResources], "overloaded server")
testServerShutdownSuccess(t, server, monitors, DefaultResources)
}
// TestServer_HandleRequestMsg_overloadServer tests that the server will
// requeue messages if it is overloaded. The overloading is done twice.
func TestServer_HandleRequestMsg_overloadServerTwice(t *testing.T) {
controller := NewTaskController()
handler := NewStandardHandler(controller)
server, monitors := NewServer(handler.Handle)
mf := NewMessageFactory()
msgs := mf.NewSimpleTaskMessages(DefaultResources+1, true)
handleRequestMessages(server, msgs)
assertErrorMonitorErrorCount(t, monitors.Error, 1, "handling more requests than possible should trigger error")
assertErrorIsNotNil(t, monitors.Error.nextError(), "handling more requests than possible should trigger error")
assertResourceMonitorStatusMatch(t, monitors.Resource, 0, DefaultResources, 0, 0, "resources after overloading")
for _, msg := range msgs[:4] {
controller.stop(msg.id, nil)
}
time.Sleep(ShortDuration)
assertResourceMonitorStatusMatch(t, monitors.Resource, 4, DefaultResources-4, 0, 0, "resources after stopping some task")
handleRequestMessages(server, mf.NewSimpleTaskMessages(5, true))
assertErrorMonitorErrorCount(t, monitors.Error, 1, "handling more requests than possible should trigger error (second attempt)")
assertErrorIsNotNil(t, monitors.Error.nextError(), "handling more requests than possible should trigger error (second attempt)")
assertResourceMonitorStatusMatch(t, monitors.Resource, 0, DefaultResources, 0, 0, "resources after overloading (second attempt)")
testServerShutdownSuccess(t, server, monitors, DefaultResources)
}
// TestServer_HandleRequestMsg_postExpansionExternal tests that unprotected
// external tasks can be overwritten by incoming request messages.
func TestServer_HandleRequestMsg_postExpansionExternal(t *testing.T) {
controller := NewTaskController()
handler := NewStandardHandler(controller)
server, monitors := NewServer(handler.Handle)
mf := NewMessageFactory()
msgA := mf.NewSimpleTaskMessage(true)
server.HandleControlMsg(msgA)
time.Sleep(ShortDuration)
server.ExpandTasks()
server.ExpandTasks()
assertResourceMonitorStatusMatch(t, monitors.Resource, 0, 0, 0, DefaultResources, "resources after expansion")
msgB := mf.NewSimpleTaskMessage(true)
testHandleRequestMessageSuccess(t, server, monitors, msgB, "handling single message")
assertResourceMonitorStatusMatch(t, monitors.Resource, 0, 1, 0, DefaultResources-1, "resources after expand")
testServerShutdownSuccess(t, server, monitors, DefaultResources)
}
// TestServer_HandleRequestMsg_postExpansionExternal tests that unprotected
// internal tasks can be overwritten by incoming request messages.
func TestServer_HandleRequestMsg_postExpansionInternal(t *testing.T) {
controller := NewTaskController()
handler := NewStandardHandler(controller)
server, monitors := NewServer(handler.Handle)
mf := NewMessageFactory()
msgA := mf.NewSimpleTaskMessage(true)
testHandleRequestMessageSuccess(t, server, monitors, msgA, "handling single message")
server.ExpandTasks()
assertResourceMonitorStatusMatch(t, monitors.Resource, 0, 1, DefaultResources-1, 0, "resources after expand")
msgB := mf.NewSimpleTaskMessage(true)
testHandleRequestMessageSuccess(t, server, monitors, msgB, "handling single message")
assertResourceMonitorStatusMatch(t, monitors.Resource, 0, 2, DefaultResources-2, 0, "resources after expand")
testServerShutdownSuccess(t, server, monitors, DefaultResources)
}
// TestServer_HandleRequestMsg_postExpansionWithExpansionBuffer tests that
// messages are correctly handled after expansion when there is an expansion
// buffer.
func TestServer_HandleRequestMsg_postExpansionWithExpansionBuffer(t *testing.T) {
controller := NewTaskController()
handler := NewStandardHandler(controller)
monitors := NewMonitors(DefaultResources)
server := occamy.NewServer(occamy.ServerConfig{
Slots: DefaultResources,
ExpansionSlotBuffer: 2,
ExpansionPeriod: 0,
KillTimeout: 100 * time.Millisecond,
HeaderKeyTaskID: HeaderKeyTaskID,
Handler: handler.Handle,
Monitors: occamy.Monitors{
Error: monitors.Error,
Latency: monitors.Latency,
Resource: monitors.Resource,
},
})
mf := NewMessageFactory()
msgA := mf.NewSimpleTaskMessage(true)
testHandleRequestMessageSuccess(t, server, monitors, msgA, "handling single message")
server.ExpandTasks()
assertResourceMonitorStatusMatch(t, monitors.Resource, 2, 1, DefaultResources-3, 0, "resources after expansion")
msgB := mf.NewSimpleTaskMessage(true)
testHandleRequestMessageSuccess(t, server, monitors, msgB, "handling single message")
assertResourceMonitorStatusMatch(t, monitors.Resource, 1, 2, DefaultResources-3, 0, "resources after another message")
msgs := mf.NewSimpleTaskMessages(2, true)
testHandleRequestMessagesSuccess(t, server, monitors, msgs, "")
assertResourceMonitorStatusMatch(t, monitors.Resource, 0, 4, DefaultResources-4, 0, "resources after more messages")
testServerShutdownSuccess(t, server, monitors, DefaultResources)
}
// TestServer_Shutdown tests that the shutdown can be successfully called and
// yield no errors.
func TestServer_Shutdown(t *testing.T) {
server, monitors := NewServer(nil)
testServerShutdownSuccess(t, server, monitors, DefaultResources)
}
// TestServer_Shutdown_idempotent tests that shutdown can be successfully called
// multiple times.
func TestServer_Shutdown_idempotent(t *testing.T) {
server, monitors := NewServer(nil)
testServerShutdownSuccess(t, server, monitors, DefaultResources)
testServerShutdownSuccess(t, server, monitors, DefaultResources)
testServerShutdownSuccess(t, server, monitors, DefaultResources)
}
// TestServer_Shutdown_idempotent_withTasks tests that shutdown can be
// successfully called multiple times when the server contains tasks.
func TestServer_Shutdown_idempotent_withTasks(t *testing.T) {
controller := NewTaskController()
handler := NewStandardHandler(controller)
server, monitors := NewServer(handler.Handle)
mf := NewMessageFactory()
messages := mf.NewSimpleTaskMessages(4, false)
testHandleRequestMessagesSuccess(t, server, monitors, messages, "handling multiple tasks")
testServerShutdownSuccess(t, server, monitors, DefaultResources)
testServerShutdownSuccess(t, server, monitors, DefaultResources)
testServerShutdownSuccess(t, server, monitors, DefaultResources)
}
// TestServer_Shutdown_withTasks tests that shutdown empties all slots without
// any errors when the server contains tasks.
func TestServer_Shutdown_withTasks(t *testing.T) {
controller := NewTaskController()
handler := NewStandardHandler(controller)
server, monitors := NewServer(handler.Handle)
mf := NewMessageFactory()
messages := mf.NewSimpleTaskMessages(4, false)
testHandleRequestMessagesSuccess(t, server, monitors, messages, "handling multiple tasks")
testServerShutdownSuccess(t, server, monitors, DefaultResources)
}
// TestServer_Shutdown_withUnstoppableTask tests that shutdown will record
// errors when the server contains unstoppable tasks.
func TestServer_Shutdown_withUnstoppableTask(t *testing.T) {
controller := NewTaskController()
handler := NewStandardHandler(controller)
server, monitors := NewServer(handler.Handle)
mf := NewMessageFactory()
msg := mf.NewUnstoppableTaskMessage(false)
testHandleRequestMessageSuccess(t, server, monitors, msg, "handling multiple tasks")
shutdownServer(server)
assertErrorIsOccamyError(t, occamy.ErrKindTaskNotKilled, monitors.Error.nextError(), "no error after shutdown")
assertResourceMonitorStatusMatch(t, monitors.Resource, DefaultResources-1, 1, 0, 0, "resources after server shutdown")
}
// region Asserts
func assertErrorEqual(t *testing.T, expected, actual error, comment string) {
if errors.Is(actual, expected) {
return
}
t.Log(string(debug.Stack()))
t.Logf("%s: actual error (%v) did not match expected (%v)", comment, actual, expected)
t.FailNow()
}
func assertErrorIsNil(t *testing.T, err error, comment string) {
if err == nil {
return
}
t.Logf("%s: error was not nil: %v", comment, err)
t.FailNow()
}
func assertErrorIsOccamyError(t *testing.T, expectedKind occamy.ErrKind, err error, comment string) {
if err == nil {
t.Logf("%s: error was nil", comment)
t.FailNow()
}
kind, ok := occamy.ExtractErrorKind(err)
if !ok {
t.Log(string(debug.Stack()))
t.Logf("%s: error could not have its error kind extracted: %v", comment, err)
t.FailNow()
}
if expectedKind != kind {
t.Log(string(debug.Stack()))
t.Logf("%s: error had kind %v that did not match expected kind %s", comment, kind, expectedKind)
t.FailNow()
}
}
func assertErrorIsNotNil(t *testing.T, err error, comment string) {
if err != nil {
return
}
t.Logf("%s: error was nil", comment)
t.FailNow()
}
func assertErrorMonitorErrorCount(t *testing.T, em *ErrorMonitor, expected int, comment string) {
if len(em.errors) == expected {
return
}
t.Logf("%s: error monitor contains %d errors which does not match the expected amount of %d", comment, len(em.errors), expected)
t.Log(string(debug.Stack()))
t.FailNow()
}
func assertIntsEqual(t *testing.T, expected, actual int, comment string) {
if expected == actual {
return
}
t.Logf("%s: actual value (%d) does not match expected value %d", comment, actual, expected)
t.Log(string(debug.Stack()))
t.FailNow()
}
func assertMessageStatus(t *testing.T, expected string, message *Message, comment string) {
if message.status == expected {
return
}
t.Logf("%s: message has status %s does not match expected status %s", comment, message.status, expected)
t.FailNow()
}
func assertResourceMonitorStatusMatch(t *testing.T, rm *ResourceMonitor, empty, protected, unprotectedInternal, unprotectedExternal int, comment string) {
assertIntsEqual(t, empty, rm.statuses[occamy.SlotStatusEmpty], fmt.Sprintf("%s: mismatch in empty slots", comment))
assertIntsEqual(t, protected, rm.statuses[occamy.SlotStatusProtected], fmt.Sprintf("%s: mismatch in protected slots", comment))
assertIntsEqual(t, unprotectedInternal, rm.statuses[occamy.SlotStatusUnprotectedInternal], fmt.Sprintf("%s: mismatch in unprotected internal slots", comment))
assertIntsEqual(t, unprotectedExternal, rm.statuses[occamy.SlotStatusUnprotectedExternal], fmt.Sprintf("%s: mismatch in unprotected external slots", comment))
}
// endregion
// region Comment Helpers
func joinComments(primary, secondary string) string {
switch {
case primary == "":
return secondary
case secondary == "":
return primary
default:
return fmt.Sprintf("%s: %s", primary, secondary)
}
}
// endregion
// region Handler - Standard
type StandardHandler struct {
controller *TaskController
}
func NewStandardHandler(controller *TaskController) *StandardHandler {
return &StandardHandler{controller: controller}
}
func (sh *StandardHandler) Handle(header occamy.Headers, body []byte) (occamy.Task, error) {
data := &MessageDataRequest{}
if err := json.Unmarshal(body, data); err != nil {
return nil, occamy.NewErrorf(occamy.ErrKindInvalidBody, "failed to unmarshal as json: %w", err)
}
switch data.TaskGroup {
case TaskGroupSimple:
return NewSimpleTask(data.ID, data.Expandable, sh.controller), nil
case TaskGroupUnstoppable:
return NewUnstoppableTask(data.ID, data.Expandable), nil
default:
return nil, occamy.NewErrorf(occamy.ErrKindInvalidBody, "unknown task group: %s", data.TaskGroup)
}
}
// endregion Handler
// region Header Keys
const (
HeaderKeyTaskID = "task_id"
)
// endregion
// region Message
type Message struct {
id string
headers occamy.Headers
body []byte
mutex *sync.Mutex
status string
}
func (m *Message) Body() []byte {
return m.body
}
func (m *Message) Headers() occamy.Headers {
return m.headers
}
func (m *Message) Ack() error {
m.setStatus(MessageStatusAcked)
return nil
}
func (m *Message) Reject(requeue bool) error {
if requeue {
m.setStatus(MessageStatusRequeued)
return nil
}
m.setStatus(MessageStatusRejected)
return nil
}
func (m *Message) setStatus(status string) {
m.mutex.Lock()
m.status = status
m.mutex.Unlock()
}
// endregion
// region Message Data - Request
type MessageDataRequest struct {
ID string
Expandable bool
TaskGroup string
}
// endregion
// region Message Data - Control
type MessageDataControl struct {
ID string
Cancel bool
}
// endregion
// region Message Factory
type MessageFactory struct {
count int32
}
func NewMessageFactory() *MessageFactory {
return &MessageFactory{
count: 0,
}
}
func (mf *MessageFactory) NewCancelMessage(id string) *Message {
return mf.convertControlToMessage(MessageDataControl{
ID: id,
Cancel: true,
})
}
func (mf *MessageFactory) NewSimpleTaskMessage(expandable bool) *Message {
return mf.convertRequestToMessage(MessageDataRequest{
ID: fmt.Sprintf("simple_%s", mf.nextIDSuffix()),
Expandable: expandable,
TaskGroup: TaskGroupSimple,
})
}
func (mf *MessageFactory) NewSimpleTaskMessages(n int, expandable bool) []*Message {
messages := make([]*Message, n)
for i := range messages {
messages[i] = mf.NewSimpleTaskMessage(expandable)
}
return messages
}
func (mf *MessageFactory) NewUnstoppableTaskMessage(expandable bool) *Message {
return mf.convertRequestToMessage(MessageDataRequest{
ID: fmt.Sprintf("unstoppable_%s", mf.nextIDSuffix()),
Expandable: expandable,
TaskGroup: TaskGroupUnstoppable,
})
}
func (mf *MessageFactory) convertControlToMessage(data MessageDataControl) *Message {
headers := make(occamy.Headers)
headers[HeaderKeyTaskID] = data.ID
body, err := json.Marshal(data)
if err != nil {
panic(fmt.Sprintf("unable to continue test as message data could not be marshaled into the body of a message: %v", err))
}
return &Message{
id: data.ID,
headers: headers,
body: body,
status: MessageStatusOpen,
mutex: &sync.Mutex{},
}
}
func (mf *MessageFactory) convertRequestToMessage(data MessageDataRequest) *Message {
headers := make(occamy.Headers)
body, err := json.Marshal(data)
if err != nil {
panic(fmt.Sprintf("unable to continue test as message data could not be marshaled into the body of a message: %v", err))
}
return &Message{
id: data.ID,
headers: headers,
body: body,
status: MessageStatusOpen,
mutex: &sync.Mutex{},
}
}
func (mf *MessageFactory) nextIDSuffix() string {
value := atomic.AddInt32(&mf.count, 1)
id := fmt.Sprintf("%03d", value)
return id
}
// endregion
// region Message Status
const (
MessageStatusOpen = "open"
MessageStatusAcked = "acked"
MessageStatusRejected = "rejected"
MessageStatusRequeued = "requeued"
)
// endregion
// region Panic
// panicIfBoolIsFalse will panic if the value is false.
//
// This method should only be used when checking an internal mechanism of the
// test is as expected. The panic indicates that it is the test itself that has
// not been correctly implemented.
func panicIfBoolIsFalse(value bool, comment string) {
if !value {
return
}
panic(fmt.Sprintf("%s: boolean was true when expected to be false", comment))
}
// panicIfErrorMonitorContainsErrors will panic if error monitor contains errors.
//
// This method should only be used when checking an internal mechanism of the
// test is as expected. The panic indicates that it is the test itself that has
// not been correctly implemented.
func panicIfErrorMonitorContainsErrors(monitors Monitors, comment string) {
if len(monitors.Error.errors) > 0 {
panic(fmt.Sprintf("%s: error monitor contained errors", comment))
}
}
// endregion
// region Task Controller
type TaskController struct {
errors map[string]error
stopChs map[string]chan struct{}
stopOnces map[string]*sync.Once
mutex *sync.Mutex
}
func NewTaskController() *TaskController {
return &TaskController{
errors: map[string]error{},
stopChs: map[string]chan struct{}{},
stopOnces: map[string]*sync.Once{},
mutex: &sync.Mutex{},
}
}
func (tc *TaskController) error(id string) error {
tc.mutex.Lock()
err := tc.errors[id]
tc.mutex.Unlock()
return err
}
func (tc *TaskController) isStopped(id string) bool {
tc.mutex.Lock()
_, stopped := tc.errors[id]
tc.mutex.Unlock()
return stopped
}
func (tc *TaskController) register(id string) {
tc.mutex.Lock()
if _, ok := tc.stopChs[id]; !ok {
tc.stopChs[id] = make(chan struct{})
tc.stopOnces[id] = &sync.Once{}
}
tc.mutex.Unlock()
}
func (tc *TaskController) stop(id string, err error) {
// The task is always registered before stopping to ensure that the channel
// can always be closed.
tc.register(id)
tc.mutex.Lock()
tc.stopOnces[id].Do(func() {
tc.errors[id] = err
close(tc.stopChs[id])
})
tc.mutex.Unlock()
}
func (tc *TaskController) stopCh(id string) <-chan struct{} {
tc.mutex.Lock()
ch := tc.stopChs[id]
tc.mutex.Unlock()
return ch
}
// endregion
// region Task - Simple
const TaskGroupSimple = "simple"
type SimpleTask struct {
id string
expandable bool
controller *TaskController
stopCh chan struct{}
stopOnce *sync.Once
}
func NewSimpleTask(id string, expandable bool, controller *TaskController) *SimpleTask {
controller.register(id)
return &SimpleTask{
id: id,
expandable: expandable,
controller: controller,
stopCh: make(chan struct{}),
stopOnce: &sync.Once{},
}
}
func (task *SimpleTask) Do(ctx context.Context) error {
select {
case <-task.stopCh:
return nil
case <-task.controller.stopCh(task.id):
return task.controller.error(task.id)
case <-ctx.Done():
return occamy.NewError(occamy.ErrKindTaskInterrupted, ctx.Err())
}
}
func (task *SimpleTask) Details() occamy.TaskDetails {
return occamy.TaskDetails{
Deadline: time.Now().Add(1000000 * time.Hour),
ID: task.id,
Group: TaskGroupUnstoppable,
}
}
func (task *SimpleTask) Expand(n int) []occamy.Task {
if !task.expandable {
return nil
}
tasks := make([]occamy.Task, n)
for i := range tasks {
tasks[i] = NewSimpleTask(task.assistantID(), task.expandable, task.controller)
}
return tasks
}
func (task *SimpleTask) Handle(_ context.Context, _ occamy.Headers, body []byte) error {
message := &MessageDataControl{}
if err := json.Unmarshal(body, message); err != nil {
return err
}
if message.ID != task.id {
return fmt.Errorf("control message sent to wrong task")
}
if message.Cancel {
task.stop()
}
return nil
}
func (task *SimpleTask) assistantID() string {
return fmt.Sprintf("%s_assistant", task.id)
}
func (task *SimpleTask) stop() {
task.stopOnce.Do(func() {
close(task.stopCh)
})
}
// endregion
// region Task - Unstoppable
const TaskGroupUnstoppable = "unstoppable"
type UnstoppableTask struct {
id string
expandable bool
}