Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,7 @@ resharper_braces_for_for = required

resharper_return_value_of_pure_method_is_not_used_highlighting = error

resharper_member_hides_interface_member_with_default_implementation_highlighting = error

resharper_misleading_body_like_statement_highlighting = error

Expand Down
63 changes: 63 additions & 0 deletions claude.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

Replicant is a .NET NuGet library providing disk-based HTTP response caching for HttpClient. It implements RFC 7234 HTTP caching semantics including Expires, Cache-Control (max-age, no-store, no-cache), Last-Modified, and ETag headers.

**Two usage patterns:**
- **HttpCache**: Direct API for caching HTTP responses (string, bytes, stream, file)
- **CachingHandler**: DelegatingHandler for transparent HttpClient pipeline integration

## Build Commands

```bash
# Build
dotnet build src --configuration Release

# Test
dotnet test src --configuration Release

# Build and test
dotnet build src --configuration Release && dotnet test src --configuration Release --no-build --no-restore
```

## Architecture

### Key Files
- `src/Replicant/HttpCache.cs` - Core caching class (split across partial files: HttpCache_*.cs)
- `src/Replicant/CachingHandler.cs` - DelegatingHandler for pipeline integration
- `src/Replicant/Timestamp.cs` - Cache entry metadata encoded in filename format: `{uriHash}_{date}_{etag}`
- `src/Replicant/FilePair.cs` - Manages paired content (.bin) + metadata (.json) files
- `src/Replicant/MetaData.cs` - JSON-serialized response headers for cache revalidation
- `src/Replicant/Extensions.cs` - HTTP header parsing helpers (GetExpiry, IsNoCache, etc.)

### Design Patterns
- **Partial classes**: HttpCache split across 10 files by concern (AddItem, Bytes, Cleanup, Dispose, File, Lines, Response, Stream, String)
- **Filename-based state**: Timestamp struct encodes expiry/ETag in filename, avoids separate metadata lookups
- **FilePair atomic operations**: Content and metadata managed together for consistency
- **Thread-safe purging**: Timer-based cleanup with atomic file moves for locked files

### Target Frameworks
- Library: `net48;net7.0;net8.0;net9.0;net10.0` (net48 Windows only)
- Tests: `net10.0`

## Testing

Tests use NUnit with Verify for snapshot testing. Code snippets in readme.md are auto-extracted from test files and verified on each push.

```bash
# Run all tests
dotnet test src

# Run a single test
dotnet test src --filter "FullyQualifiedName~TestMethodName"
```

## Code Style

- EditorConfig enforced with `TreatWarningsAsErrors=true` and `EnforceCodeStyleInBuild=true`
- LangVersion is `preview`
- Uses `CharSpan` alias for `System.ReadOnlySpan<System.Char>`
- Warnings CS1591, NU1608, NU1109 suppressed globally
73 changes: 73 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,79 @@ using var response = await httpCache.ResponseAsync("https://httpbin.org/status/2
<!-- endSnippet -->


### Using with HttpClient Pipeline (DelegatingHandler)

`CachingHandler` is a `DelegatingHandler` that provides transparent HTTP response caching. It can be used with `HttpClient` and `HttpClientFactory` to add caching to the request pipeline.


#### Basic Usage

<!-- snippet: DelegatingHandlerBasic -->
<a id='snippet-DelegatingHandlerBasic'></a>
```cs
var handler = new CachingHandler();
var httpClient = new HttpClient(handler);
var response = await httpClient.GetAsync("https://httpbin.org/json");
```
<sup><a href='/src/Tests/CachingHandlerTests.cs#L294-L300' title='Snippet source file'>snippet source</a> | <a href='#snippet-DelegatingHandlerBasic' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

The default cache directory is `{Temp}/Replicant`.


#### HttpClientFactory Integration

<!-- snippet: DelegatingHandlerWithFactory -->
<a id='snippet-DelegatingHandlerWithFactory'></a>
```cs
var services = new ServiceCollection();
services.AddHttpClient("cached")
.ConfigurePrimaryHttpMessageHandler(() => new CachingHandler());

using var provider = services.BuildServiceProvider();
var factory = provider.GetRequiredService<IHttpClientFactory>();
var client = factory.CreateClient("cached");
```
<sup><a href='/src/Tests/CachingHandlerTests.cs#L210-L220' title='Snippet source file'>snippet source</a> | <a href='#snippet-DelegatingHandlerWithFactory' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->


#### Stale-If-Error Support

Return stale cached responses when the origin server is unavailable:

<!-- snippet: DelegatingHandlerStaleIfError -->
<a id='snippet-DelegatingHandlerStaleIfError'></a>
```cs
var handler = new CachingHandler { StaleIfError = true };
```
<sup><a href='/src/Tests/CachingHandlerTests.cs#L308-L312' title='Snippet source file'>snippet source</a> | <a href='#snippet-DelegatingHandlerStaleIfError' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->


#### Cache Status Monitoring

The cache status is reported via the `X-Replicant-Cache-Status` response header:

<!-- snippet: DelegatingHandlerCacheStatus -->
<a id='snippet-DelegatingHandlerCacheStatus'></a>
```cs
status = response.Headers
.GetValues(CachingHandler.CacheStatusHeaderName)
.First();
```
<sup><a href='/src/Tests/CachingHandlerTests.cs#L328-L334' title='Snippet source file'>snippet source</a> | <a href='#snippet-DelegatingHandlerCacheStatus' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

Possible values:

* `hit` - Response returned from cache without revalidation
* `miss` - Response fetched from origin and stored in cache
* `revalidate` - Cached response revalidated with origin (304 Not Modified)
* `no-store` - Response not cached due to Cache-Control directives
* `stale` - Stale response returned due to network error (stale-if-error)


## Influences / Alternatives

* [Tavis.HttpCache](https://github.com/tavis-software/Tavis.HttpCache)
Expand Down
13 changes: 13 additions & 0 deletions src/Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,18 @@
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="Argon" Version="0.33.5" />
<<<<<<< HEAD
<PackageVersion Include="MarkdownSnippets.MsBuild" Version="28.0.0" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.3" />
<PackageVersion Include="Microsoft.Extensions.Http" Version="10.0.3" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.0.1" />
<PackageVersion Include="Polyfill" Version="9.9.0" />
<PackageVersion Include="ProjectDefaults" Version="1.0.172" />
<PackageVersion Include="System.Net.Http" Version="4.3.4" />
<PackageVersion Include="System.Text.Json" Version="10.0.3" />
<PackageVersion Include="Verify.DiffPlex" Version="3.1.2" />
<PackageVersion Include="Verify.NUnit" Version="31.13.0" />
=======
<PackageVersion Include="MarkdownSnippets.MsBuild" Version="28.0.1" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.5" />
<PackageVersion Include="Microsoft.Extensions.Http" Version="10.0.5" />
Expand All @@ -15,6 +27,7 @@
<PackageVersion Include="System.Text.Json" Version="10.0.5" />
<PackageVersion Include="Verify.DiffPlex" Version="3.1.2" />
<PackageVersion Include="Verify.NUnit" Version="31.13.2" />
>>>>>>> main
<PackageVersion Include="Verify.Http" Version="7.5.1" />
<PackageVersion Include="NUnit" Version="4.5.1" />
<PackageVersion Include="NUnit3TestAdapter" Version="6.1.0" />
Expand Down
Loading
Loading