|
| 1 | +# syncutil Package |
| 2 | + |
| 3 | +The `syncutil` package provides thread-safe synchronization utilities for concurrent operations. |
| 4 | + |
| 5 | +## Overview |
| 6 | + |
| 7 | +This package provides generic types for common concurrency patterns with zero-allocation caching. It is designed for situations where an expensive or fallible operation should be executed at most once, with subsequent callers receiving the cached result. |
| 8 | + |
| 9 | +## Public API |
| 10 | + |
| 11 | +### Types |
| 12 | + |
| 13 | +| Symbol | Kind | Description | |
| 14 | +|--------|------|-------------| |
| 15 | +| `OnceLoader[T]` | struct | Caches the result of an expensive, fallible one-shot fetch; safe for concurrent use | |
| 16 | + |
| 17 | +### Methods on `OnceLoader[T]` |
| 18 | + |
| 19 | +| Method | Signature | Description | |
| 20 | +|--------|-----------|-------------| |
| 21 | +| `Get` | `func (o *OnceLoader[T]) Get(loader func() (T, error)) (T, error)` | Returns the cached result, invoking `loader` exactly once | |
| 22 | +| `Reset` | `func (o *OnceLoader[T]) Reset()` | Clears the cached result and error so that the next `Get` call re-invokes `loader` | |
| 23 | + |
| 24 | +## Usage Examples |
| 25 | + |
| 26 | +```go |
| 27 | +import "github.com/github/gh-aw/pkg/syncutil" |
| 28 | + |
| 29 | +var cache syncutil.OnceLoader[string] |
| 30 | + |
| 31 | +// loader is called only once; subsequent calls return the cached value |
| 32 | +value, err := cache.Get(func() (string, error) { |
| 33 | + return expensiveOperation() |
| 34 | +}) |
| 35 | + |
| 36 | +// Reset allows re-fetching the value on the next Get call |
| 37 | +cache.Reset() |
| 38 | +``` |
| 39 | + |
| 40 | +**Typical usage as a package-level cache**: |
| 41 | + |
| 42 | +```go |
| 43 | +var currentRepoSlugCache syncutil.OnceLoader[string] |
| 44 | + |
| 45 | +func getCurrentRepoSlug() (string, error) { |
| 46 | + return currentRepoSlugCache.Get(func() (string, error) { |
| 47 | + return fetchRepoSlugFromGitHub() |
| 48 | + }) |
| 49 | +} |
| 50 | +``` |
| 51 | + |
| 52 | +## Design Notes |
| 53 | + |
| 54 | +- The internal mutex ensures that `loader` is invoked at most once, even when multiple goroutines call `Get` concurrently. |
| 55 | +- If `loader` returns an error, the error is cached alongside the zero value of `T`; subsequent calls return the same error without re-invoking `loader`. |
| 56 | +- `Reset` acquires the same mutex, making it safe to call concurrently with `Get`. |
| 57 | +- The zero value of `OnceLoader[T]` is ready to use; no constructor is needed. |
| 58 | + |
| 59 | +## Dependencies |
| 60 | + |
| 61 | +This package has no internal or external dependencies beyond the Go standard library (`sync`). |
| 62 | + |
| 63 | +--- |
| 64 | + |
| 65 | +*This specification is automatically maintained by the [spec-extractor](../../.github/workflows/spec-extractor.md) workflow.* |
0 commit comments