Skip to content

Commit b6a7af9

Browse files
docs: Fix API references and add missing documentation
1 parent d11bb7e commit b6a7af9

8 files changed

Lines changed: 261 additions & 66 deletions

File tree

README.md

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -31,19 +31,20 @@ composer require fyennyi/async-cache-php
3131

3232
### Basic Setup
3333

34-
The easiest way to create a manager is using the `AsyncCacheBuilder`.
34+
The easiest way to create a manager is using the fluent configuration API.
3535

3636
```php
37-
use Fyennyi\AsyncCache\AsyncCacheBuilder;
38-
use Fyennyi\AsyncCache\Storage\ReactCacheAdapter;
37+
use Fyennyi\AsyncCache\AsyncCacheManager;
3938
use React\Cache\ArrayCache;
4039

4140
// 1. Setup Cache (using ReactPHP ArrayCache as an example)
42-
$cacheAdapter = new ReactCacheAdapter(new ArrayCache());
41+
$cache = new ArrayCache();
4342

44-
// 2. Create the Manager using the Builder
45-
$manager = AsyncCacheBuilder::create($cacheAdapter)
46-
->build();
43+
// 2. Create the Manager using fluent configuration
44+
$manager = new AsyncCacheManager(
45+
AsyncCacheManager::configure($cache)
46+
->build()
47+
);
4748
```
4849

4950
### Wrapping an Async Operation
@@ -91,6 +92,8 @@ new CacheOptions(
9192
serve_stale_if_limited: true, // Return stale data if rate limited
9293
tags: ['geo', 'kyiv'], // Cache tags (if adapter supports them)
9394
compression: false, // Enable data compression
95+
compression_threshold: 1024, // Minimum size in bytes to trigger compression
96+
fail_safe: true, // Catch cache exceptions and treat as misses
9497
x_fetch_beta: 1.0 // Beta coefficient for X-Fetch (0 to disable)
9598
);
9699
```

docs/advanced/events.md

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,34 @@ Async Cache PHP dispatches PSR-14 events to help you monitor and debug cache beh
66

77
All events reside in the `Fyennyi\AsyncCache\Event` namespace.
88

9-
| Event Class |
10-
| :--- |
9+
| Event Class | Description |
10+
| :--- | :--- |
1111
| `CacheHitEvent` | Dispatched when a valid item is found in the cache. Contains the value. |
1212
| `CacheMissEvent` | Dispatched when the item is missing and the factory is about to be called. |
13-
| `CacheStatusEvent` | Telemetry event containing timing info, status (`Hit`, `Miss`, `Stale`, `XFetch`), and tags. |
13+
| `CacheStatusEvent` | Telemetry event containing timing info, status, and tags. |
1414
| `RateLimitExceededEvent` | Dispatched when the rate limiter blocks a request. |
1515

16+
## Cache Status Values
17+
18+
The `CacheStatusEvent` contains a `status` property with one of the following values from `Fyennyi\AsyncCache\Enum\CacheStatus`:
19+
20+
| Status | Description |
21+
| :--- | :--- |
22+
| `Hit` | Data was found in cache and is fresh. |
23+
| `Miss` | Data was not found, factory will be called. |
24+
| `Stale` | Data was found but expired, stale data returned (Background strategy). |
25+
| `XFetch` | X-Fetch algorithm triggered early recomputation. |
26+
| `RateLimited` | Request was blocked by rate limiter. |
27+
| `Bypass` | Cache was bypassed (ForceRefresh strategy). |
28+
1629
## Setting Up an Event Dispatcher
1730

1831
You can pass any PSR-14 compliant Event Dispatcher (like Symfony's) to the builder.
1932

2033
```php
2134
use Symfony\Component\EventDispatcher\EventDispatcher;
22-
use Fyennyi\AsyncCache\AsyncCacheBuilder;
35+
use Fyennyi\AsyncCache\AsyncCacheManager;
36+
use Fyennyi\AsyncCache\Event\CacheHitEvent;
2337

2438
$dispatcher = new EventDispatcher();
2539

@@ -28,14 +42,19 @@ $dispatcher->addListener(CacheHitEvent::class, function ($event) {
2842
echo "Cache Hit for key: " . $event->key . "\n";
2943
});
3044

31-
$manager = AsyncCacheBuilder::create($adapter)
32-
->withEventDispatcher($dispatcher)
33-
->build();
45+
$manager = new AsyncCacheManager(
46+
AsyncCacheManager::configure($cache)
47+
->withEventDispatcher($dispatcher)
48+
->build()
49+
);
3450
```
3551

3652
## Telemetry Logging
3753

3854
The `CacheStatusEvent` is particularly useful for logging metrics (e.g., to Prometheus or DataDog). It provides:
39-
- **Duration**: How long the lookup took.
40-
- **Status**: Why the result was returned (Hit, Miss, Stale fallback, etc.).
41-
- **Tags**: Categories associated with the key.
55+
56+
- **`key`**: The cache key identifier.
57+
- **`status`**: Why the result was returned (Hit, Miss, Stale, XFetch, Bypass).
58+
- **`latency`**: How long the lookup took in seconds.
59+
- **`tags`**: Categories associated with the key.
60+
- **`timestamp`**: When the event occurred.

docs/advanced/middleware.md

Lines changed: 121 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,38 +4,45 @@ The logic of Async Cache PHP is built on a **Middleware Pipeline**. Every reques
44

55
## Default Pipeline
66

7-
When you create a manager using `AsyncCacheBuilder`, the following middleware stack is assembled (in order):
7+
When you create a manager using `AsyncCacheManager::configure()`, the following middleware stack is assembled (in order):
88

99
1. **`CoalesceMiddleware`**: Prevents duplicate requests for the same key happening at the same time. If 10 requests come in for `key_A`, only one factory is executed, and the result is shared.
1010
2. **`StaleOnErrorMiddleware`**: If the factory fails (throws an exception), this middleware tries to return stale data from the cache instead of propagating the error.
1111
3. **`CacheLookupMiddleware`**: Checks if the item is in the cache. Handles `CacheStrategy` logic (Strict vs Background) and X-Fetch calculations.
12-
4. **`AsyncLockMiddleware`**: Acquires a lock before calling the factory to ensure only one process generates the data (Cache Stampede protection via locking).
13-
5. **`SourceFetchMiddleware`**: The final handler. It executes the user's factory function and saves the result to the storage.
12+
4. **`TagValidationMiddleware`**: Validates cache tags and handles tag-based invalidation.
13+
5. **`AsyncLockMiddleware`**: Acquires a lock before calling the factory to ensure only one process generates the data (Cache Stampede protection via locking).
14+
6. **`SourceFetchMiddleware`**: The final handler. It executes the user's factory function and saves the result to the storage.
15+
16+
## Additional Middleware
17+
18+
The library also provides optional middleware that can be added to the pipeline:
19+
20+
- **`CircuitBreakerMiddleware`**: Implements the circuit breaker pattern to prevent cascading failures when external services are down.
21+
- **`RetryMiddleware`**: Automatically retries failed operations with configurable backoff strategies.
1422

1523
## Custom Middleware
1624

17-
You can inject your own middleware into the pipeline using the `AsyncCacheBuilder`.
25+
You can inject your own middleware into the pipeline using the configuration builder.
1826

1927
### 1. Implement `MiddlewareInterface`
2028

2129
```php
2230
use Fyennyi\AsyncCache\Middleware\MiddlewareInterface;
2331
use Fyennyi\AsyncCache\Core\CacheContext;
24-
use Fyennyi\AsyncCache\Core\Future;
32+
use React\Promise\PromiseInterface;
2533

2634
class MyCustomMiddleware implements MiddlewareInterface
2735
{
28-
public function handle(CacheContext $context, callable $next): Future
36+
public function handle(CacheContext $context, callable $next): PromiseInterface
2937
{
3038
// Pre-processing
3139
echo "Processing key: " . $context->key . "\n";
3240

3341
// Call next middleware
34-
$future = $next($context);
35-
36-
// Post-processing (using Future callbacks)
37-
return $future->onResolve(function ($value) {
42+
return $next($context)->then(function ($value) {
43+
// Post-processing
3844
echo "Finished!\n";
45+
return $value;
3946
});
4047
}
4148
}
@@ -44,11 +51,110 @@ class MyCustomMiddleware implements MiddlewareInterface
4451
### 2. Register with Builder
4552

4653
```php
47-
$manager = AsyncCacheBuilder::create($adapter)
48-
->withMiddleware(new MyCustomMiddleware())
49-
->build();
54+
$manager = new AsyncCacheManager(
55+
AsyncCacheManager::configure($cache)
56+
->withMiddleware(new MyCustomMiddleware())
57+
->build()
58+
);
59+
```
60+
61+
cat > /home/serhii/alerts-in-ua-php/async-cache-php/docs/reference.md << 'EOF'
62+
# API Reference
63+
64+
## `AsyncCacheManager`
65+
66+
The main class for caching operations. Create using fluent configuration.
67+
68+
### Static Methods
69+
70+
#### `configure(PsrCacheInterface|ReactCacheInterface|AsyncCacheAdapterInterface $cache_adapter): AsyncCacheConfigBuilder`
71+
Creates a configuration builder for fluent setup.
72+
73+
```php
74+
$manager = new AsyncCacheManager(
75+
AsyncCacheManager::configure($cache)
76+
->withLogger($logger)
77+
->withRateLimiter($limiter)
78+
->withEventDispatcher($dispatcher)
79+
->build()
80+
);
5081
```
5182

52-
!!! warning
53-
Custom middleware is appended to the **end** of the stack by default (before `SourceFetchMiddleware` but after others). If you need precise control over the order, you might need to construct the `AsyncCacheManager` manually, passing the full array of middleware.
83+
### Instance Methods
84+
85+
#### `wrap(string $key, callable $promise_factory, CacheOptions $options): PromiseInterface`
86+
Wraps an operation with caching logic. Returns a ReactPHP Promise.
87+
88+
#### `increment(string $key, int $step = 1, ?CacheOptions $options = null): PromiseInterface`
89+
Atomically increments a cached value.
90+
91+
#### `decrement(string $key, int $step = 1, ?CacheOptions $options = null): PromiseInterface`
92+
Atomically decrements a cached value.
93+
94+
#### `invalidateTags(array $tags): PromiseInterface`
95+
Invalidates items by tags.
96+
97+
#### `clear(): PromiseInterface`
98+
Clears the entire cache storage.
5499

100+
#### `delete(string $key): PromiseInterface`
101+
Deletes a specific item from the cache.
102+
103+
## `AsyncCacheConfigBuilder`
104+
105+
Fluent builder for configuring the manager.
106+
107+
### `withRateLimiter(LimiterInterface $rate_limiter): self`
108+
Configures a Symfony Rate Limiter.
109+
110+
### `withLogger(LoggerInterface $logger): self`
111+
Sets a PSR-3 logger.
112+
113+
### `withLockFactory(LockFactory $lock_factory): self`
114+
Sets a custom Symfony Lock factory.
115+
116+
### `withMiddleware(MiddlewareInterface $middleware): self`
117+
Adds custom middleware to the pipeline.
118+
119+
### `withEventDispatcher(EventDispatcherInterface $dispatcher): self`
120+
Sets a PSR-14 event dispatcher.
121+
122+
### `withSerializer(SerializerInterface $serializer): self`
123+
Sets a custom serializer.
124+
125+
### `withClock(ClockInterface $clock): self`
126+
Sets a PSR-20 clock implementation.
127+
128+
### `build(): AsyncCacheConfig`
129+
Finalizes and returns the configuration.
130+
131+
## `CacheOptions`
132+
133+
| Property | Type | Default | Description |
134+
| :--- | :--- | :--- | :--- |
135+
| `ttl` | `?int` | `3600` | Logical expiration in seconds. |
136+
| `strategy` | `CacheStrategy` | `Strict` | Caching strategy (Strict, Background, ForceRefresh). |
137+
| `stale_grace_period` | `int` | `86400` | Physical storage TTL in seconds. |
138+
| `rate_limit_key` | `?string` | `null` | Key for rate limiting logic. |
139+
| `serve_stale_if_limited`| `bool` | `true` | Return stale data on rate limit hits. |
140+
| `tags` | `array` | `[]` | Tags for invalidation. |
141+
| `x_fetch_beta` | `float` | `1.0` | X-Fetch algorithm coefficient. |
142+
| `compression` | `bool` | `false` | Enable Zlib compression. |
143+
| `compression_threshold` | `int` | `1024` | Minimum data size in bytes to trigger compression. |
144+
| `fail_safe` | `bool` | `true` | Catch cache adapter exceptions and treat as misses. |
145+
146+
## `CacheOptionsBuilder`
147+
148+
Fluent builder for `CacheOptions`.
149+
150+
```php
151+
$options = CacheOptionsBuilder::create()
152+
->withTtl(300)
153+
->withStrategy(CacheStrategy::Background)
154+
->withStaleGracePeriod(3600)
155+
->withCompression(true, 2048)
156+
->withTags(['users', 'api'])
157+
->build();
158+
```
159+
EOF! warning
160+
Custom middleware is prepended to the stack (runs before default middleware). If you need precise control over the order, you might need to construct the `AsyncCacheManager` manually, passing the full array of middleware.

docs/advanced/serialization.md

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,14 @@ Use `withSerializer` on the builder.
1919
### Using JSON
2020

2121
```php
22+
use Fyennyi\AsyncCache\AsyncCacheManager;
2223
use Fyennyi\AsyncCache\Serializer\JsonSerializer;
2324

24-
$manager = AsyncCacheBuilder::create($adapter)
25-
->withSerializer(new JsonSerializer())
26-
->build();
25+
$manager = new AsyncCacheManager(
26+
AsyncCacheManager::configure($cache)
27+
->withSerializer(new JsonSerializer())
28+
->build()
29+
);
2730
```
2831

2932
### Using Encryption
@@ -39,9 +42,11 @@ $serializer = new EncryptingSerializer(
3942
$key
4043
);
4144

42-
$manager = AsyncCacheBuilder::create($adapter)
43-
->withSerializer($serializer)
44-
->build();
45+
$manager = new AsyncCacheManager(
46+
AsyncCacheManager::configure($cache)
47+
->withSerializer($serializer)
48+
->build()
49+
);
4550
```
4651

4752
## Compression

0 commit comments

Comments
 (0)