feat: complete cmpp platform phases 0-5
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
package connection
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
type DialFunc func(context.Context) error
|
||||
|
||||
type Reconnector struct {
|
||||
MaxAttempts int
|
||||
Delay time.Duration
|
||||
Dial DialFunc
|
||||
}
|
||||
|
||||
func (r Reconnector) Connect(ctx context.Context) (int, error) {
|
||||
attempts := r.MaxAttempts
|
||||
if attempts <= 0 {
|
||||
attempts = 1
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
for attempt := 1; attempt <= attempts; attempt++ {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return attempt - 1, err
|
||||
}
|
||||
|
||||
if err := r.Dial(ctx); err != nil {
|
||||
lastErr = err
|
||||
if attempt < attempts && r.Delay > 0 {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return attempt, ctx.Err()
|
||||
case <-time.After(r.Delay):
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
return attempt, nil
|
||||
}
|
||||
|
||||
return attempts, lastErr
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package connection
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestReconnectorRetriesAfterDisconnect(t *testing.T) {
|
||||
failures := 0
|
||||
reconnector := Reconnector{
|
||||
MaxAttempts: 3,
|
||||
Dial: func(context.Context) error {
|
||||
failures++
|
||||
if failures < 2 {
|
||||
return errors.New("simulated disconnect")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
attempts, err := reconnector.Connect(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("connect after retry: %v", err)
|
||||
}
|
||||
if attempts != 2 {
|
||||
t.Fatalf("expected success on second attempt, got %d", attempts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReconnectorReturnsLastError(t *testing.T) {
|
||||
expected := errors.New("still disconnected")
|
||||
reconnector := Reconnector{
|
||||
MaxAttempts: 2,
|
||||
Dial: func(context.Context) error {
|
||||
return expected
|
||||
},
|
||||
}
|
||||
|
||||
attempts, err := reconnector.Connect(context.Background())
|
||||
if !errors.Is(err, expected) {
|
||||
t.Fatalf("expected last error, got %v", err)
|
||||
}
|
||||
if attempts != 2 {
|
||||
t.Fatalf("expected two attempts, got %d", attempts)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user