chore: initialize containerized Go learning workbook (2026 DevOps/SRE)
This commit is contained in:
commit
84be3e5d77
64 files changed
+1382
No files matched your search
@@ -0,0 +1,9 @@
|
||||
# 02 — `context.Context` i Odporność (Retry + Anulowanie)
|
||||
|
||||
## Zadania (`resilience.go`)
|
||||
1. `RetryWithContext(ctx context.Context, attempts int, delay time.Duration, fn func(context.Context) error) error` — ponawiaj `fn(ctx)` do `attempts` razy, czekając `delay` (z przerwaniem przez `ctx.Done()` w `select`).
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=./exercises/02-engineering-2026/02-context-and-resilience
|
||||
```
|
||||
@@ -0,0 +1,15 @@
|
||||
package resilience
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
func RetryWithContext(
|
||||
ctx context.Context,
|
||||
attempts int,
|
||||
delay time.Duration,
|
||||
fn func(context.Context) error,
|
||||
) error {
|
||||
panic("TODO: ponawiaj fn(ctx) do attempts razy, respektując ctx.Done() podczas czekania delay")
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package resilience
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRetrySucceedsOnThirdAttempt(t *testing.T) {
|
||||
calls := 0
|
||||
err := RetryWithContext(context.Background(), 3, time.Millisecond, func(ctx context.Context) error {
|
||||
calls++
|
||||
if calls < 3 {
|
||||
return errors.New("transient")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil || calls != 3 {
|
||||
t.Fatalf("got err=%v calls=%d, want nil and 3", err, calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryStopsOnContextCancel(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Millisecond)
|
||||
defer cancel()
|
||||
err := RetryWithContext(ctx, 10, 50*time.Millisecond, func(ctx context.Context) error {
|
||||
return errors.New("always fails")
|
||||
})
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("expected context.DeadlineExceeded, got %v", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user