8.9 KiB
CLAUDE.md - DeepDrftContent.Services
Guidance for working in the DeepDrftContent.Services project (the binary-content domain logic).
See the root CLAUDE.md for full architecture overview. This file covers what is specific to this project.
One-line purpose
Binary-content domain logic. The FileDatabase implementation in full (Models, Services, Utils, Abstractions, Constants), WAV stream-with-offset, audio processing, and the content-side track service. Consumed by DeepDrftContent (the host) and DeepDrftCli (the admin CLI).
Layout
DeepDrftContent.Services/
├── FileDatabase/ # The subsystem (port of TypeScript system)
│ ├── Abstractions/ # Interfaces
│ ├── Models/ # Data models, DTOs, enums
│ ├── Services/ # FileDatabase, MediaVault, IndexSystem, IndexWatcher
│ └── Utils/ # StructuralMap, StructuralSet, FileUtils
├── Audio/
│ └── WavOffsetService.cs # Byte offset → valid WAV stream
├── Processors/
│ └── AudioProcessor.cs # WAV file parsing, metadata extraction
├── Constants/
│ └── VaultConstants.cs # Vault name definitions
├── TrackService.cs # Content-side orchestrator
└── DeepDrftContent.Services.csproj
FileDatabase model (high-level)
See FileDatabase/README.md for the long-form design discussion — it's a port of a TypeScript system and has deep rationale. This section covers the essentials for an agent walking in cold.
Core structure
- FileDatabase: Root object. Created via
FileDatabase.FromAsync(rootPath). Holds a collection ofMediaVaultinstances and anIndexWatcher. ImplementsIDisposable. Singleton in the host. - MediaVault: A subdirectory under the FileDatabase root. Each vault has its own JSON
indexfile listing entries and per-entry metadata. Typed viaMediaVaultTypeenum (Media | Image | Audio).- Concrete implementations:
ImageVault(for images),AudioVault(for audio). Do not useImageDirectoryVault(that's stale docs) — the type isImageVault.
- Concrete implementations:
- Entry filenames:
{sanitized-key}{extension}, where sanitisation isRegex.Replace(entryKey, @"[^a-zA-Z0-9]", "-"). So entry id"my-song"with extension.wav→ filenamemy-song.wav.
Binary hierarchy
FileBinary (base: byte buffer)
└── MediaBinary (+ Extension: string, MIME type inferred via MimeTypeExtensions)
├── AudioBinary (+ Duration: double, Bitrate: int)
└── ImageBinary (+ AspectRatio: double)
Each has a matching *Dto variant for base64 JSON transport (e.g., AudioBinaryDto with buffer encoded as base64).
Index lifecycle
- DirectoryIndex: Root index file (at
{rootPath}/index). Tracks which vaults exist. - VaultIndex: Per-vault index (at
{vaultPath}/index). RecordsMediaVaultTypeand lists all entries in that vault. - Both are JSON files. Created/loaded via
IndexFactoryService. - When a file is written externally (e.g., the CLI calls
FileDatabase.RegisterResourceAsyncdirectly), the IndexWatcher detects the write to the vault'sindexfile and triggersMediaVault.ReloadIndexAsync, so a long-running web host stays consistent without restart.
Error-handling philosophy (load-bearing)
Public Load* / Register* operations swallow exceptions and return null / false to match the TypeScript original.
public async Task<T?> LoadResourceAsync<T>(string vaultId, string entryId) where T : FileBinary
{
try { /* load and deserialize */ }
catch { return null; } // Swallow, return null
}
public async Task<bool> RegisterResourceAsync(string vaultId, string entryId, FileBinary media)
{
try { /* store and update index */ }
catch { return false; } // Swallow, return false
}
Callers must check return values. Do not change this without a deliberate design pass — it's embedded in all FileDatabase tests and client code.
WAV offset service
WavOffsetService.CreateOffsetStream(buffer, byteOffset):
- Parses the WAV header from the buffer.
- Block-aligns the byte offset to the nearest block boundary (required for clean audio — misalignment causes clicks).
- Synthesises a new 44-byte WAV header sized for the remaining data (from offset to EOF).
- Returns a
MemoryStreamcontaining[new header][data from offset].
Used by the content API to serve seek-beyond-buffer requests. The player asks for a new stream at the byte offset it wants to seek to; the server returns a valid WAV that starts there.
Block alignment is critical. Do not bypass it. The WAV fmt chunk tells you the block size; use it.
Audio processor
AudioProcessor.ProcessWavFileAsync(filePath):
- Validates the RIFF/WAVE/PCM structure.
- Parses the fmt and data chunks.
- Extracts duration (sample count / sample rate) and bitrate (file size / duration).
- Returns
AudioBinarywith all metadata. - Fallback: If parsing fails, logs a warning and returns defaults (180s / 1411 kbps / 44.1 kHz / 16-bit stereo).
PCM-only today. Other formats (mp3, flac, aac, ogg, m4a) are listed in MimeTypeExtensions but not implemented. The processor validates RIFF/WAVE/PCM format — anything else is rejected.
Image processor
ImageProcessor.ProcessImageAsync(buffer, mimeType):
- Accepts raw image bytes and MIME type (e.g.,
image/png,image/jpeg). - Parses PNG or JPEG headers to extract image dimensions.
- Computes aspect ratio (width / height). Defaults to 1.0 if parsing fails or format is unsupported.
- Returns
ImageBinarywith MIME type and aspect ratio metadata. - No disk I/O: operates on
byte[]only — no file reading required.
Content-side TrackService (orchestrator)
AddTrackFromWavAsync(filePath)
- Reads a WAV file from disk.
- Calls
AudioProcessor.ProcessWavFileAsync→AudioBinary. - Generates a GUID entry key (via
Guid.NewGuid().ToString()). - Ensures the
tracksvault exists (creates if missing). - Calls
FileDatabase.RegisterResourceAsync("tracks", entryKey, audioBinary). - Returns a populated
TrackEntity(withId = 0since it's not yet in SQL).
Note: The caller (CLI or web) is responsible for then saving this entity to SQL via DeepDrftWeb.Services.TrackService.Create. If the vault write succeeds and SQL write fails, audio is orphaned (no compensating rollback).
GetAudioBinaryAsync(entryKey)
Reads audio from the tracks vault via FileDatabase.LoadResourceAsync<AudioBinary>("tracks", entryKey). Returns null if not found or read fails.
InitializeTracksVaultAsync()
Safety call to ensure the tracks vault exists (creates if missing). Called on host startup.
Vault constants
VaultConstants.Tracks = "tracks" and VaultConstants.Images = "images" — the vault names in production use. New vault names go here when adding new vault types.
Service registration
In DeepDrftContent/Startup.ConfigureDomainServices() and DeepDrftCli/Program.cs:
services.AddSingleton<WavOffsetService>();
services.AddSingleton<FileDatabase>(/* from FileDatabase.FromAsync */);
services.AddScoped<AudioProcessor>();
services.AddScoped<TrackService>(); // DeepDrftContent.Services.TrackService
Development commands
# Build
dotnet build DeepDrftContent.Services
# Run tests (FileDatabase tests cover vault/index/factory/utilities thoroughly)
dotnet test DeepDrftTests/
# Run CLI (which consumes this service)
dotnet run --project DeepDrftCli -- add myfile.wav "Track Name" "Artist"
Important patterns
- Async/await: All FileDatabase operations are async. No sync methods.
- Type safety: Generic
LoadResourceAsync<T>ensures callers know what they're loading. - Vault lifecycle: Vaults are created on first boot, then reused. The
FileDatabasesingleton holds them in memory with liveIndexWatcheres. - Entry sanitisation: Keys are sanitised client-side (in the CLI and web host) and by
MediaVault(defensive). Always sanitise before registering — it's the only way to ensure safe filenames. - Metadata hierarchy: Use the appropriate media type (
AudioBinary,ImageBinary) so downstream code can rely on the metadata. Don't store an audio file as a genericMediaBinary— useAudioBinarywith duration/bitrate.
What does NOT live here
- HTTP controllers or middleware — that's
DeepDrftContent. - SQL database code — that's
DeepDrftWeb.Services. - Blazor components or UI logic — that's
DeepDrftWeb.Client. - Configuration files (
appsettings.json,filedatabase.json) — those are in the host project.
When working with this project, focus on the FileDatabase subsystem (the most complex piece of the codebase), audio processing, and the orchestration logic that bridges binary and SQL databases. The tests (in DeepDrftTests/) are the load-bearing documentation of FileDatabase behaviour — consult them when FileDatabase semantics are unclear.