-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepomix-output.xml
More file actions
4906 lines (4140 loc) · 140 KB
/
repomix-output.xml
File metadata and controls
4906 lines (4140 loc) · 140 KB
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
This file is a merged representation of the entire codebase, combined into a single document by Repomix.
<file_summary>
This section contains a summary of this file.
<purpose>
This file contains a packed representation of the entire repository's contents.
It is designed to be easily consumable by AI systems for analysis, code review,
or other automated processes.
</purpose>
<file_format>
The content is organized as follows:
1. This summary section
2. Repository information
3. Directory structure
4. Repository files (if enabled)
5. Multiple file entries, each consisting of:
- File path as an attribute
- Full contents of the file
</file_format>
<usage_guidelines>
- This file should be treated as read-only. Any changes should be made to the
original repository files, not this packed version.
- When processing this file, use the file path to distinguish
between different files in the repository.
- Be aware that this file may contain sensitive information. Handle it with
the same level of security as you would the original repository.
</usage_guidelines>
<notes>
- Some files may have been excluded based on .gitignore rules and Repomix's configuration
- Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files
- Files matching patterns in .gitignore are excluded
- Files matching default ignore patterns are excluded
- Files are sorted by Git change count (files with more changes are at the bottom)
</notes>
</file_summary>
<directory_structure>
.github/
workflows/
ci.yml
cmd/
api/
static/
index.html
handlers_test.go
handlers.go
main.go
worker/
dlq_consumer/
main.go
worker_main/
main.go
worker_test.go
docker/
Dockerfile.api
Dockerfile.worker
internal/
config/
config.go
events/
ring.go
integration/
queue_test.go
jobs/
handlers/
email.go
resize_image.go
handler.go
job.go
queue/
config.go
queue.go
rabbitmq.go
worker/
grpc_server_test.go
grpc_server.go
registry_test.go
registry.go
proto/
workerpb/
worker_grpc.pb.go
worker.pb.go
worker.proto
.env.example
.gitignore
docker-compose.yml
go.mod
README.md
</directory_structure>
<files>
This section contains the contents of the repository's files.
<file path=".github/workflows/ci.yml">
name: CI
on:
push:
branches: ["**"]
pull_request:
branches: ["**"]
jobs:
# ---------------------------------------------------------------------------
# Unit tests — fast, no external dependencies, runs on every push/PR
# ---------------------------------------------------------------------------
unit:
name: Unit Tests
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: "1.24"
cache: true
- name: Download dependencies
run: go mod download
- name: Vet
run: go vet ./...
- name: Unit tests
run: go test -race -count=1 -timeout=60s ./...
# ---------------------------------------------------------------------------
# Integration tests — spins up a real RabbitMQ via testcontainers-go
# Requires Docker (available on ubuntu-latest GitHub-hosted runners)
# ---------------------------------------------------------------------------
integration:
name: Integration Tests
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: "1.24"
cache: true
- name: Download dependencies
run: go mod download
- name: Integration tests
run: go test -race -count=1 -timeout=120s -tags integration ./internal/integration/...
</file>
<file path="docker/Dockerfile.worker">
FROM golang:1.24-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN go build -o worker ./cmd/worker/worker_main/main.go
FROM alpine:3.19
WORKDIR /app
COPY --from=builder /app/worker .
EXPOSE 9001
CMD ["./worker"]
</file>
<file path="internal/events/ring.go">
package events
import (
"sync"
"time"
)
// Kind classifies an event for the dashboard.
type Kind string
const (
KindDirect Kind = "direct"
KindQueued Kind = "queued"
KindError Kind = "error"
KindInfo Kind = "info"
)
// Event is a single activity record.
type Event struct {
Time time.Time `json:"time"`
JobID string `json:"job_id"`
JobType string `json:"job_type"`
Kind Kind `json:"kind"`
WorkerID string `json:"worker_id,omitempty"`
Message string `json:"message"`
}
// Ring is a fixed-capacity thread-safe ring buffer of Events.
// Oldest entries are overwritten when the buffer is full.
type Ring struct {
mu sync.Mutex
buf []Event
cap int
head int // index of next write
count int // number of valid entries
}
// NewRing returns a Ring with the given capacity.
func NewRing(capacity int) *Ring {
return &Ring{
buf: make([]Event, capacity),
cap: capacity,
}
}
// Push adds an event to the ring, overwriting the oldest entry if full.
func (r *Ring) Push(e Event) {
r.mu.Lock()
defer r.mu.Unlock()
if e.Time.IsZero() {
e.Time = time.Now()
}
r.buf[r.head] = e
r.head = (r.head + 1) % r.cap
if r.count < r.cap {
r.count++
}
}
// Snapshot returns all events in chronological order (oldest first).
func (r *Ring) Snapshot() []Event {
r.mu.Lock()
defer r.mu.Unlock()
out := make([]Event, r.count)
if r.count == 0 {
return out
}
// If buffer is not yet full, entries start at index 0.
// If full, the oldest entry is at r.head.
start := 0
if r.count == r.cap {
start = r.head
}
for i := 0; i < r.count; i++ {
out[i] = r.buf[(start+i)%r.cap]
}
return out
}
</file>
<file path="internal/integration/queue_test.go">
//go:build integration
package integration_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
amqp "github.com/rabbitmq/amqp091-go"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
"jobqueue/internal/jobs"
"jobqueue/internal/queue"
)
// startRabbitMQ spins up a RabbitMQ container and returns the AMQP URL.
// The container is automatically terminated when the test ends.
func startRabbitMQ(t *testing.T) string {
t.Helper()
ctx := context.Background()
container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: testcontainers.ContainerRequest{
Image: "rabbitmq:3.13-alpine",
ExposedPorts: []string{"5672/tcp"},
Env: map[string]string{
"RABBITMQ_DEFAULT_USER": "guest",
"RABBITMQ_DEFAULT_PASS": "guest",
},
WaitingFor: wait.ForLog("Server startup complete").
WithStartupTimeout(60 * time.Second),
},
Started: true,
})
if err != nil {
t.Fatalf("failed to start RabbitMQ container: %v", err)
}
t.Cleanup(func() {
if err := testcontainers.TerminateContainer(container); err != nil {
t.Logf("failed to terminate RabbitMQ container: %v", err)
}
})
host, err := container.Host(ctx)
if err != nil {
t.Fatalf("failed to get container host: %v", err)
}
port, err := container.MappedPort(ctx, "5672")
if err != nil {
t.Fatalf("failed to get mapped port: %v", err)
}
return fmt.Sprintf("amqp://guest:guest@%s:%s/", host, port.Port())
}
// ---------------------------------------------------------------------------
// Test: POST /jobs with no workers → published to RabbitMQ → consumer acks
// ---------------------------------------------------------------------------
func TestIntegration_JobQueuedAndConsumed(t *testing.T) {
amqpURL := startRabbitMQ(t)
// Connect using our real RabbitMQ implementation.
rmq, err := queue.NewRabbitMQ(&queue.Config{
URL: amqpURL,
QueueName: "jobs",
})
if err != nil {
t.Fatalf("failed to connect to RabbitMQ: %v", err)
}
defer rmq.Close()
// Use the real jobsHandler with an empty worker registry so every job
// falls through to the queue path.
reg := emptyRegistry{}
handler := jobsHandlerFunc(reg, rmq)
// Submit a job via the HTTP handler.
body := `{"type":"email","payload":{"to":"test@example.com","subject":"Integration test"}}`
req := httptest.NewRequest(http.MethodPost, "/jobs", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
handler(rr, req)
if rr.Code != http.StatusAccepted {
t.Fatalf("expected 202, got %d — body: %s", rr.Code, rr.Body.String())
}
var resp map[string]interface{}
if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
t.Fatalf("failed to decode response: %v", err)
}
if resp["routed"] != "queue" {
t.Errorf("expected routed=queue, got %v", resp["routed"])
}
// Now consume the message and verify it is a valid job.
consumed := make(chan jobs.Job, 1)
go func() {
msgs, err := rmq.Channel().Consume("jobs", "", false, false, false, false, nil)
if err != nil {
t.Logf("consume error: %v", err)
return
}
for msg := range msgs {
var j jobs.Job
if err := json.Unmarshal(msg.Body, &j); err != nil {
t.Logf("unmarshal error: %v", err)
_ = msg.Nack(false, false)
continue
}
_ = msg.Ack(false)
consumed <- j
return
}
}()
select {
case j := <-consumed:
if j.Type != "email" {
t.Errorf("expected job type 'email', got %q", j.Type)
}
if j.ID == "" {
t.Error("expected non-empty job ID")
}
if j.Attempts != 0 {
t.Errorf("expected attempts=0, got %d", j.Attempts)
}
case <-time.After(15 * time.Second):
t.Fatal("timed out waiting for job to be consumed")
}
}
// ---------------------------------------------------------------------------
// Test: job published directly → consumer retries on failure → DLQ after 3
// ---------------------------------------------------------------------------
func TestIntegration_JobRetriesAndReachesDLQ(t *testing.T) {
amqpURL := startRabbitMQ(t)
rmq, err := queue.NewRabbitMQ(&queue.Config{
URL: amqpURL,
QueueName: "jobs",
})
if err != nil {
t.Fatalf("failed to connect to RabbitMQ: %v", err)
}
defer rmq.Close()
// Publish a job with an unknown type so the handler always fails.
job := jobs.Job{ID: "integ-1", Type: "unknown-type", Attempts: 0}
data, _ := json.Marshal(job)
if err := rmq.Publish(data); err != nil {
t.Fatalf("failed to publish job: %v", err)
}
// Consume and simulate the retry loop manually, mirroring handleMessage logic.
msgs, err := rmq.Channel().Consume("jobs", "", false, false, false, false, nil)
if err != nil {
t.Fatalf("failed to consume: %v", err)
}
attempts := 0
timeout := time.After(20 * time.Second)
for {
select {
case msg, ok := <-msgs:
if !ok {
t.Fatal("channel closed unexpectedly")
}
var j jobs.Job
if err := json.Unmarshal(msg.Body, &j); err != nil {
t.Fatalf("unmarshal failed: %v", err)
}
attempts++
if j.Attempts < 2 {
// Re-publish with incremented attempt counter (mirrors handleMessage).
j.Attempts++
redata, _ := json.Marshal(j)
_ = msg.Ack(false)
if err := rmq.Publish(redata); err != nil {
t.Fatalf("re-publish failed: %v", err)
}
} else {
// Third attempt — Nack to DLQ.
_ = msg.Nack(false, false)
// Verify the message lands on the DLQ.
dlqMsgs, err := rmq.Channel().Consume("jobs.dlq", "", true, false, false, false, nil)
if err != nil {
t.Fatalf("failed to consume DLQ: %v", err)
}
select {
case dlqMsg := <-dlqMsgs:
var dead jobs.Job
if err := json.Unmarshal(dlqMsg.Body, &dead); err != nil {
t.Fatalf("failed to unmarshal DLQ message: %v", err)
}
if dead.ID != "integ-1" {
t.Errorf("expected DLQ job id integ-1, got %q", dead.ID)
}
if attempts != 3 {
t.Errorf("expected 3 attempts before DLQ, got %d", attempts)
}
return
case <-time.After(10 * time.Second):
t.Fatal("timed out waiting for DLQ message")
}
}
case <-timeout:
t.Fatalf("timed out after %d attempts", attempts)
}
}
}
// ---------------------------------------------------------------------------
// Minimal stubs — satisfy the queue.Queue interface for the handler call
// ---------------------------------------------------------------------------
// emptyRegistry satisfies enough of worker.Registry's interface for the handler.
// Since we want the queue path, PickWorker always returns "".
type emptyRegistry struct{}
func (emptyRegistry) PickWorker() string { return "" }
func (emptyRegistry) DispatchJob(workerID, jobID, jobType string, payload interface{}) error {
return nil
}
// jobsHandlerFunc is a minimal re-implementation of the POST /jobs logic
// so the integration test doesn't import cmd/api (which has a main package).
func jobsHandlerFunc(reg emptyRegistry, rmq queue.Queue) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var body struct {
Type string `json:"type"`
Payload interface{} `json:"payload"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
j := jobs.Job{
ID: generateID(),
Type: body.Type,
Payload: body.Payload,
Attempts: 0,
}
data, _ := json.Marshal(j)
if err := rmq.Publish(data); err != nil {
http.Error(w, "failed to queue job", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted)
json.NewEncoder(w).Encode(map[string]interface{}{
"job": j,
"routed": "queue",
})
}
}
func generateID() string {
return fmt.Sprintf("test-%d", time.Now().UnixNano())
}
// ---------------------------------------------------------------------------
// Test: raw AMQP publish → consume → message body is valid JSON job
// ---------------------------------------------------------------------------
func TestIntegration_RawPublishAndConsume(t *testing.T) {
amqpURL := startRabbitMQ(t)
conn, err := amqp.Dial(amqpURL)
if err != nil {
t.Fatalf("failed to connect: %v", err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
t.Fatalf("failed to open channel: %v", err)
}
defer ch.Close()
q, err := ch.QueueDeclare("raw-test", false, true, false, false, nil)
if err != nil {
t.Fatalf("failed to declare queue: %v", err)
}
job := jobs.Job{ID: "raw-1", Type: "email", Attempts: 0}
body, _ := json.Marshal(job)
if err := ch.Publish("", q.Name, false, false, amqp.Publishing{
ContentType: "application/json",
Body: body,
}); err != nil {
t.Fatalf("failed to publish: %v", err)
}
msgs, err := ch.Consume(q.Name, "", true, false, false, false, nil)
if err != nil {
t.Fatalf("failed to consume: %v", err)
}
select {
case msg := <-msgs:
var received jobs.Job
if err := json.Unmarshal(msg.Body, &received); err != nil {
t.Fatalf("failed to unmarshal: %v", err)
}
if received.ID != "raw-1" {
t.Errorf("expected ID raw-1, got %q", received.ID)
}
case <-time.After(10 * time.Second):
t.Fatal("timed out waiting for message")
}
}
</file>
<file path="internal/jobs/handlers/email.go">
package handlers
import (
"context"
"encoding/json"
"fmt"
"log"
"jobqueue/internal/jobs"
)
// EmailHandler processes jobs of type "email".
// Replace the log statements with a real mail client (e.g. SendGrid, SES)
// when you are ready to send actual emails.
type EmailHandler struct{}
type emailPayload struct {
To string `json:"to"`
Subject string `json:"subject"`
Body string `json:"body"`
}
func (h *EmailHandler) Handle(ctx context.Context, job jobs.Job) error {
raw, err := json.Marshal(job.Payload)
if err != nil {
return fmt.Errorf("email handler: failed to decode payload: %w", err)
}
var p emailPayload
if err := json.Unmarshal(raw, &p); err != nil {
return fmt.Errorf("email handler: invalid payload shape: %w", err)
}
if p.To == "" {
return fmt.Errorf("email handler: missing required field 'to'")
}
// TODO: replace with real mail-client call.
log.Printf("[email] job=%s to=%s subject=%q — sent (simulated)", job.ID, p.To, p.Subject)
return nil
}
</file>
<file path="internal/jobs/handlers/resize_image.go">
package handlers
import (
"context"
"encoding/json"
"fmt"
"log"
"jobqueue/internal/jobs"
)
// ResizeImageHandler processes jobs of type "resize-image".
// Replace the log statement with a real image-processing call
// (e.g. imaging, vips, or an external service) when ready.
type ResizeImageHandler struct{}
type resizeImagePayload struct {
URL string `json:"url"`
Width int `json:"width"`
Height int `json:"height"`
}
func (h *ResizeImageHandler) Handle(ctx context.Context, job jobs.Job) error {
raw, err := json.Marshal(job.Payload)
if err != nil {
return fmt.Errorf("resize-image handler: failed to encode payload: %w", err)
}
var p resizeImagePayload
if err := json.Unmarshal(raw, &p); err != nil {
return fmt.Errorf("resize-image handler: invalid payload shape: %w", err)
}
if p.URL == "" {
return fmt.Errorf("resize-image handler: missing required field 'url'")
}
// TODO: replace with real image-processing call.
log.Printf("[resize-image] job=%s url=%s size=%dx%d — resized (simulated)", job.ID, p.URL, p.Width, p.Height)
return nil
}
</file>
<file path="internal/jobs/handler.go">
package jobs
import (
"context"
"errors"
"fmt"
)
// ErrUnknownJobType is returned when no handler is registered for a job type.
var ErrUnknownJobType = errors.New("unknown job type")
// Handler processes a single job. Returning a non-nil error signals failure
// and causes the worker to retry or send the job to the DLQ.
type Handler interface {
Handle(ctx context.Context, job Job) error
}
// HandlerFunc is a convenience type that lets a plain function satisfy Handler.
type HandlerFunc func(ctx context.Context, job Job) error
func (f HandlerFunc) Handle(ctx context.Context, job Job) error {
return f(ctx, job)
}
// HandlerRegistry maps job types to their Handler implementations.
// Register all handlers on startup; the worker looks up by job.Type at runtime.
type HandlerRegistry struct {
handlers map[string]Handler
}
// NewHandlerRegistry returns an empty HandlerRegistry.
func NewHandlerRegistry() *HandlerRegistry {
return &HandlerRegistry{handlers: make(map[string]Handler)}
}
// Register associates a job type string with a Handler.
// Panics on duplicate registration to catch wiring mistakes at startup.
func (r *HandlerRegistry) Register(jobType string, h Handler) {
if _, exists := r.handlers[jobType]; exists {
panic(fmt.Sprintf("jobs: handler already registered for type %q", jobType))
}
r.handlers[jobType] = h
}
// Dispatch looks up the handler for job.Type and calls it.
// Returns ErrUnknownJobType if no handler is registered.
func (r *HandlerRegistry) Dispatch(ctx context.Context, job Job) error {
h, ok := r.handlers[job.Type]
if !ok {
return fmt.Errorf("%w: %q", ErrUnknownJobType, job.Type)
}
return h.Handle(ctx, job)
}
</file>
<file path="internal/queue/config.go">
package queue
type Config struct {
URL string
QueueName string
}
</file>
<file path="internal/queue/queue.go">
package queue
type Queue interface {
Publish(body []byte) error
Close() error
}
</file>
<file path="internal/worker/grpc_server_test.go">
package worker
import (
"context"
"testing"
"jobqueue/proto/workerpb"
)
// ---------------------------------------------------------------------------
// splitWorkerID
// ---------------------------------------------------------------------------
func TestSplitWorkerID_WithAt(t *testing.T) {
id, addr := splitWorkerID("abc-123@localhost:9001")
if id != "abc-123" {
t.Errorf("expected id abc-123, got %q", id)
}
if addr != "localhost:9001" {
t.Errorf("expected addr localhost:9001, got %q", addr)
}
}
func TestSplitWorkerID_WithoutAt(t *testing.T) {
id, addr := splitWorkerID("abc-123")
if id != "abc-123" {
t.Errorf("expected id abc-123, got %q", id)
}
if addr != "" {
t.Errorf("expected empty addr, got %q", addr)
}
}
func TestSplitWorkerID_MultipleAtSigns(t *testing.T) {
// Only the first @ is the separator; the address itself may contain @.
id, addr := splitWorkerID("abc@host@9001")
if id != "abc" {
t.Errorf("expected id abc, got %q", id)
}
if addr != "host@9001" {
t.Errorf("expected addr host@9001, got %q", addr)
}
}
// ---------------------------------------------------------------------------
// GRPCServer.Register
// ---------------------------------------------------------------------------
func TestGRPCServer_Register_StoresWorker(t *testing.T) {
reg := NewRegistry()
srv := NewGRPCServer(reg)
resp, err := srv.Register(context.Background(), &workerpb.RegisterRequest{
WorkerId: "worker-1@localhost:9001",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if resp.Status != "ok" {
t.Errorf("expected status ok, got %q", resp.Status)
}
snapshot := reg.List()
info, ok := snapshot["worker-1"]
if !ok {
t.Fatal("expected worker-1 in registry after Register")
}
if info.Address != "localhost:9001" {
t.Errorf("expected address localhost:9001, got %q", info.Address)
}
}
func TestGRPCServer_Register_WithoutAddress(t *testing.T) {
reg := NewRegistry()
srv := NewGRPCServer(reg)
resp, err := srv.Register(context.Background(), &workerpb.RegisterRequest{
WorkerId: "worker-1", // no @ separator
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if resp.Status != "ok" {
t.Errorf("expected status ok, got %q", resp.Status)
}
snapshot := reg.List()
info, ok := snapshot["worker-1"]
if !ok {
t.Fatal("expected worker-1 in registry")
}
if info.Address != "" {
t.Errorf("expected empty address, got %q", info.Address)
}
}
// ---------------------------------------------------------------------------
// GRPCServer.Heartbeat
// ---------------------------------------------------------------------------
func TestGRPCServer_Heartbeat_UpdatesLoad(t *testing.T) {
reg := NewRegistry()
srv := NewGRPCServer(reg)
// Register first so there is a worker to heartbeat.
reg.Register("worker-1", "localhost:9001")
resp, err := srv.Heartbeat(context.Background(), &workerpb.HeartbeatRequest{
WorkerId: "worker-1",
Load: 7,
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if resp.Status != "alive" {
t.Errorf("expected status alive, got %q", resp.Status)
}
snapshot := reg.List()
if snapshot["worker-1"].Load != 7 {
t.Errorf("expected load 7, got %d", snapshot["worker-1"].Load)
}
}
// ---------------------------------------------------------------------------
// GRPCServer.ListWorkers
// ---------------------------------------------------------------------------
func TestGRPCServer_ListWorkers_ReturnsAllWorkers(t *testing.T) {
reg := NewRegistry()
srv := NewGRPCServer(reg)
reg.Register("w1", "localhost:9001")
reg.Register("w2", "localhost:9002")
resp, err := srv.ListWorkers(context.Background(), &workerpb.Empty{})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(resp.Workers) != 2 {
t.Errorf("expected 2 workers, got %d", len(resp.Workers))
}
}
func TestGRPCServer_ListWorkers_EmptyRegistry(t *testing.T) {
reg := NewRegistry()
srv := NewGRPCServer(reg)
resp, err := srv.ListWorkers(context.Background(), &workerpb.Empty{})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(resp.Workers) != 0 {
t.Errorf("expected 0 workers, got %d", len(resp.Workers))
}
}
func TestGRPCServer_ListWorkers_ContainsCorrectFields(t *testing.T) {
reg := NewRegistry()
srv := NewGRPCServer(reg)
reg.Register("w1", "localhost:9001")
reg.UpdateLoad("w1", 3)
resp, err := srv.ListWorkers(context.Background(), &workerpb.Empty{})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(resp.Workers) != 1 {
t.Fatalf("expected 1 worker, got %d", len(resp.Workers))
}
w := resp.Workers[0]
if w.WorkerId != "w1" {
t.Errorf("expected worker_id w1, got %q", w.WorkerId)
}
if w.Load != 3 {
t.Errorf("expected load 3, got %d", w.Load)
}
if w.LastSeenUnix == 0 {
t.Error("expected non-zero last_seen_unix")
}
}
</file>
<file path="internal/worker/registry_test.go">
package worker
import (
"net/http"
"net/http/httptest"
"testing"
"time"
)
// ---------------------------------------------------------------------------
// Register
// ---------------------------------------------------------------------------
func TestRegister_StoresWorker(t *testing.T) {
r := NewRegistry()
r.Register("worker-1", "localhost:9001")
snapshot := r.List()
info, ok := snapshot["worker-1"]
if !ok {
t.Fatal("expected worker-1 to be in registry")
}
if info.Address != "localhost:9001" {
t.Errorf("expected address localhost:9001, got %s", info.Address)
}
if info.Load != 0 {
t.Errorf("expected initial load 0, got %d", info.Load)
}
}
func TestRegister_OverwritesExistingWorker(t *testing.T) {
r := NewRegistry()
r.Register("worker-1", "localhost:9001")
r.Register("worker-1", "localhost:9002") // re-register with new address
snapshot := r.List()
if snapshot["worker-1"].Address != "localhost:9002" {
t.Errorf("expected updated address localhost:9002, got %s", snapshot["worker-1"].Address)
}
}
// ---------------------------------------------------------------------------
// UpdateLoad
// ---------------------------------------------------------------------------
func TestUpdateLoad_UpdatesKnownWorker(t *testing.T) {
r := NewRegistry()
r.Register("worker-1", "localhost:9001")
r.UpdateLoad("worker-1", 5)
snapshot := r.List()
if snapshot["worker-1"].Load != 5 {
t.Errorf("expected load 5, got %d", snapshot["worker-1"].Load)
}
}
func TestUpdateLoad_RefreshesLastSeen(t *testing.T) {
r := NewRegistry()
r.Register("worker-1", "localhost:9001")
before := r.List()["worker-1"].LastSeen
time.Sleep(5 * time.Millisecond)