|
| 1 | +# ctxcache |
| 2 | + |
| 3 | +[English](README.md) | [中文](README_CN.md) |
| 4 | + |
| 5 | +## Introduction |
| 6 | + |
| 7 | +`ctxcache` is a strongly-typed, context-scoped cache package designed for request-scoped data. |
| 8 | + |
| 9 | +`ctxcache` attaches a concurrency-safe, write-once key-value store to `context.Context`, allowing values to be |
| 10 | +implicitly propagated across call boundaries without polluting function signatures. |
| 11 | + |
| 12 | +## Features |
| 13 | + |
| 14 | +- **Strong Type Safety**: Uses generics combining string names and Go type parameters as key identifiers, ensuring type |
| 15 | + safety and preventing collisions between values of different types—even if they share the same string identifier |
| 16 | +- **Concurrency Safe**: Internally uses mutex-protected maps, supporting concurrent access |
| 17 | +- **Write-Once Semantics**: Each key can be assigned exactly once, then read multiple times until the cache is cleared |
| 18 | +- **Context Lifecycle**: Cache lifecycle is explicitly controlled by the cancel function returned from `Init` |
| 19 | +- **Request Scope Isolation**: Cache is attached to context, naturally supporting request-level data isolation |
| 20 | + |
| 21 | +## Main Functions |
| 22 | + |
| 23 | +### Initialize Cache |
| 24 | + |
| 25 | +Use the `Init` function to attach a cache to a context: |
| 26 | + |
| 27 | +```go |
| 28 | +ctx, cancel := ctxcache.Init(ctx) |
| 29 | +defer cancel() // Clean up cache at request boundary |
| 30 | +``` |
| 31 | + |
| 32 | +`Init` is idempotent: repeated calls with the same context return the original context and a no-op cancel function. |
| 33 | + |
| 34 | +### Set Values |
| 35 | + |
| 36 | +Use the `Set` function to assign a value to a key: |
| 37 | + |
| 38 | +```go |
| 39 | +err := ctxcache.Set(ctx, "user", userInfo) |
| 40 | +if err != nil { |
| 41 | +// handle error |
| 42 | +} |
| 43 | +``` |
| 44 | + |
| 45 | +Each key can only be set once. Repeated attempts return an `ErrKeyAlreadySet` error. |
| 46 | + |
| 47 | +### Get Values |
| 48 | + |
| 49 | +Use the `Get` function to retrieve a value: |
| 50 | + |
| 51 | +```go |
| 52 | +value, err := ctxcache.Get[UserType](ctx, "user") |
| 53 | +if err != nil { |
| 54 | +// handle error |
| 55 | +} |
| 56 | +``` |
| 57 | + |
| 58 | +`Get` is a generic function that requires specifying a type parameter to ensure type safety. |
| 59 | + |
| 60 | +### Clear Cache |
| 61 | + |
| 62 | +Calling the cancel function returned by `Init` clears all cached values: |
| 63 | + |
| 64 | +```go |
| 65 | +cancel() // Clear cache and make it permanently unusable |
| 66 | +``` |
| 67 | + |
| 68 | +Once cleared, subsequent `Get` or `Set` operations will return `ErrCacheAlreadyCleared` error. |
| 69 | + |
| 70 | +## Error Types |
| 71 | + |
| 72 | +The package defines the following error types: |
| 73 | + |
| 74 | +- `ErrCacheNotInitialized`: Cache is not initialized |
| 75 | +- `ErrCacheAlreadyCleared`: Cache has already been cleared |
| 76 | +- `ErrKeyNotSet`: Key is not set |
| 77 | +- `ErrKeyAlreadySet`: Key is already set |
| 78 | + |
| 79 | +## Typical Use Cases |
| 80 | + |
| 81 | +1. **HTTP Middleware**: Initialize cache at request entry point and clean up at exit |
| 82 | +2. **Authenticated User Info**: Store authenticated user objects |
| 83 | +3. **Permission Data**: Pass user permission lists |
| 84 | +4. **Trace Metadata**: Carry trace context information |
| 85 | +5. **Computed Intermediates**: Share computed intermediate values across call chains |
| 86 | + |
| 87 | +## Example Usage |
| 88 | + |
| 89 | +```go |
| 90 | +package main |
| 91 | + |
| 92 | +import ( |
| 93 | + "context" |
| 94 | + "fmt" |
| 95 | + "github.com/go-spring/stdlib/ctxcache" |
| 96 | +) |
| 97 | + |
| 98 | +type User struct { |
| 99 | + ID int |
| 100 | + Name string |
| 101 | +} |
| 102 | + |
| 103 | +func main() { |
| 104 | + ctx := context.Background() |
| 105 | + |
| 106 | + // Initialize cache |
| 107 | + ctx, cancel := ctxcache.Init(ctx) |
| 108 | + defer cancel() |
| 109 | + |
| 110 | + // Set user info |
| 111 | + user := User{ID: 1, Name: "Alice"} |
| 112 | + if err := ctxcache.Set(ctx, "user", user); err != nil { |
| 113 | + panic(err) |
| 114 | + } |
| 115 | + |
| 116 | + // Get user info in downstream code |
| 117 | + retrievedUser, err := ctxcache.Get[User](ctx, "user") |
| 118 | + if err != nil { |
| 119 | + panic(err) |
| 120 | + } |
| 121 | + |
| 122 | + fmt.Printf("User: %+v\n", retrievedUser) |
| 123 | +} |
| 124 | +``` |
| 125 | + |
| 126 | +## Notes |
| 127 | + |
| 128 | +- `ctxcache` is not a general-purpose cache. It is designed for structured, short-lived, in-process context data |
| 129 | +- Each key can only be assigned once. This is intentional design to ensure data immutability |
| 130 | +- The cancel function should be called at request boundaries to ensure request-scoped data is properly cleaned up |
| 131 | +- Once cleared, the cache becomes permanently unusable and should not be used again |
0 commit comments