Repository navigation
Conversation
- Encrypt per-key values with AES-256-GCM and PBKDF2-SHA256; committed secrets_enc[.client][.env].txt files stay diff-friendly. - Load encrypted files above plaintext secrets, below .env, process env and CLI arguments; resolve per-client keys and fail fast when a file exists without one. - Add a built-in .env loader, SecretEncryptionOptions, and the LoadDotEnv/DotEnvFileName options. - Add build-sh/do-secrets.sh (encrypt/decrypt/check) on top of a .NET 10 file-based app, plus an encrypted demo in Configuration.Web. - Rename SecretStore/Stories to Stores and bump Sa.Configuration to 0.17.0.
…ey aliases Adds a shared ConfigurationKey (src/Sa/Classes, linked into the packages that compile it) that treats a double underscore as the configuration separator, mirroring AddEnvironmentVariables(), so sa__pg__host and sa:pg:host address the same setting. - Sa.Configuration: CLI Arguments and its provider store keys in canonical `:` form and answer both spellings on lookup. - Sa.Configuration.PostgreSql: new opt-in DoubleUnderscoreAsSeparator (default false, so keys with `__` are stored verbatim) normalizes DB keys and the requested key. - Sa.Configuration (secrets layer): new KeyAliasOptions applies explicit canonical-path → flat-spelling aliases over the merged configuration of every provider at the post-secrets stage; exposed on SecretOptions and wired through AddSaPostSecretProcessing. - Sa.csproj: exclude the new ConfigurationKey.cs from the base package's glob since it references Microsoft.Extensions.Configuration. Tests: new KeyAliasesTests, Arguments/ArgumentsConfigurationProvider alias cases, and PostgreSql separator cases. Solution builds clean; Sa.ConfigurationTests 122/122 and Sa.Configuration.PostgreSqlTests 35/35 pass.
…ucture Restyles and rewrites the EN and RU readmes of Sa.Configuration and Sa.Configuration.PostgreSql for readability: - feature lists and section prose rewritten in plainer, sentence-level language - headings and tables reworded; added `---` separators between sections - "Key aliases" section restructured into problem / how-to / resolution / details / cheat-sheet - secret priority order table re-ordered highest-to-lowest with a plain one-line summary No code changes. Also fixes a copy-paste bug in the English Sa.Configuration.PostgreSql readme, which linked to the Russian Sa.Configuration readme (Readme-ru.md#алиасы-ключей) instead of its own (Readme.md#key-aliases).
…ccounting; bump 0.16.1 Review follow-up on the work queue. Registration - AddSaWorkQueue kept the factory of the first call, so a bare registration followed by a configuring one dropped the processor and callbacks while the settings still merged; the only symptom was "No processor" at resolve, pointing at the call that had already supplied one. The factory now reads a WorkQueueBuilderState singleton, so the configuring call is honored. Shutdown - Shutdown/ShutdownAsync are idempotent in result, not just in effect: a caller that finds the shutdown already running waits for it instead of returning while readers are still unwinding and the buffer is undrained. Re-entrant calls made by the shutdown itself (a status callback) return immediately via an async-local depth guard, so they cannot wait on themselves. - DisposeAsync reuses ShutdownAsync, and Dispose no longer disposes the shutdown token source: _shutdownCts.Token throws ObjectDisposedException once the source is, which let a concurrent ConcurrencyLimit change throw out of a setter documented to do nothing, and left the readers it registered unlaunched. - StartReaders launches whatever it registered in a finally: a reader that is registered but never launched never completes its published task, and a shutdown waiting for the pool would wait out the whole timeout on it. Slot accounting - CancelAndTrackReaders skips readers that RemoveReader already reaped. Such a reader (a StopReader fault) still reports IsLive, and releasing its slot a second time could eat a limit re-armed since the snapshot was taken. Options - WithMaxConcurrency rejects a negative value instead of folding it into the CPU count, matching the constructor's own guard. Docs - ForceCancelReadersAsync keeps the buffer only on the timeout path; a successful wait drains it like the sync variant (was documented otherwise). - PoolState names NoReaders, not Stopped, as the one fault state. - TryEnqueue documents that its items carry no token and cannot be aborted. - Shutdown methods document that a concurrent caller waits for the running one. Tests - New: configuring call after a bare one, concurrent shutdown callers, and WithMaxConcurrency sign/boundary. - WaitForIdleAsync_WhilePaused_SaysWhyItReturned was racy: a pause cancels an item the reader has dequeued but not yet started, so the pending count could be 1 instead of 2 (reproduced on the unmodified library, 1483/1500 under load). It now waits for the processor to enter the item and releases it before dispose, which also removes a 30 s shutdown-timeout wait. - Drop the two Task.Delay(100)s in the force-cancel recovery test; the async force-cancel already awaited the readers. Build - Commit src/.nuget/fallback/.gitkeep: Directory.Build.props points NuGet's RestoreFallbackFolders at it, and a fresh clone failed the restore (NU1301) because the gitignored directory did not exist.
…mp 0.17.0 Review follow-up on the scheduler. Observable behavior changes: - The default schedule's IJobErrorHandler is now registered through a factory with GetService, like the keyed one. Registered by implementation type it required both ILogger<> and IHostApplicationLifetime; in a container without a Generic Host resolution threw and JobController's catch silently aborted the job, bypassing the global handler and the configured action. - The global error handler receives the original exception; the JobException wrapper, with its ContextSnapshot, stays on IJobContext.LastError. - A slot that faults outside the iteration loop (job constructor, custom IJobTiming) logs and runs the normal teardown instead of leaving IsStarted true over a dead slot; the DI scope opened for the failed job is disposed. - ConcurrencyLimit is applied by pausing/resuming the pre-allocated slots; the reader pool stays at MaxConcurrency. Lowering the limit used to hard-cancel readers and destroy those slots for good — raising it again restored nothing until Stop+Start. - The retry budget resets after a handler consumes an error, so the next failure gets its retries again. - Start bounds its wait-for-idle by the shutdown timeout (Restart could hang); the stopping CTS is cancelled outside the lock. - Restart returns the number of jobs actually restarted, and the docs say so. - An explicit ThenCloseApplication() survives a merge with a later registration. - A duplicate explicit jobId across job types throws an ArgumentException that names both types instead of ToDictionary's "same key" noise; a rejected second configuring AddSaSchedule call rolls back what it registered. - ContextSnapshot.FailedIterations includes the failure being reported; the immediate first iteration pushes its context snapshot. - ScheduleHost.StopAsync honours the host shutdown token. - Readme/Readme-ru corrected (jobId parameter, concurrency model, error handler order, StopAllJobs scope); CRON.md translated to EN and its stale signature fixed; ScheduleOptions/JobOptions/validator XML docs translated. Tests: 254 in Sa.ScheduleTests (was 232), all green; Sa.Outbox.Tests 126/126. Every new regression test was checked against the pre-fix code (mutation run).
…eardown Second review pass follow-up. - IJobRunner.Run now reports why the loop ended (Finished / Stopped / Faulted) instead of a bool. A loop-level fault (a throwing custom IJobTiming, a failed job construction) still tears the slot down and is logged, but it no longer counts as a natural completion: a RunOnce job keeps its single run and can be started again once the cause is fixed. Faults still abort all slots of the job. - A cancelled caller token (for example the host's startup token, which the stop token is linked to) now moves the scheduler to the stopped state instead of leaving IsStarted true over dead slots. - Comments corrected: Stop deliberately cancels the source under its lock to close the race with Dispose (Cancel after Dispose throws ObjectDisposedException), while Start/AbortJob cancel outside. - Readme/Readme-ru: new "Failures outside a run" section — a fault stops the whole job (all slots) and does not consume a RunOnce run. Tests: 256 in Sa.ScheduleTests (was 254), all green over repeated runs; Sa.Outbox.Tests 126/126. Both new tests were checked against the pre-fix code (mutation run).
…guard - The work queue is created paused and raised to MaxConcurrency on the first Start(), so resolving a scheduler that is never started no longer allocates the whole reader pool. The pool is still pinned at MaxConcurrency afterwards and the effective limit remains the pause gate, so the slot behaviour is unchanged. - Scheduler.Restart isolates per-job failures: a job whose Stop/Start throws is logged (new SchedulerLog, event 701) and counted as "not restarted" instead of failing the whole Restart and leaving the other jobs half-restarted. Caller cancellation is still propagated. - A duplicate explicit jobId on a different job type now throws inside AddSaSchedule instead of surfacing at scheduler resolution: ScheduleBuilder records (id, type) markers per schedule and rejects the conflict immediately, naming the id and both types. The settings-level check stays as a safety net; the same id on the same type still accumulates, and different schedules may reuse an id. - Readme/Readme-ru updated (early id check, restart isolation). Tests: 261 in Sa.ScheduleTests (was 256), all green over repeated runs; Sa.Outbox.Tests 126/126. Each new test was checked against the pre-fix code (mutation run).
… cron doc fixes
- ScheduleOptionsValidator now builds CronTiming.Strict instead of the lenient
ctor, so an unsatisfiable Cron option ("0 0 31 4 *", "0 0 30 2 *", "31W 2")
fails as an OptionsValidationException instead of passing validation and then
silently aborting the job loop on the first null GetNextOccurrence.
- New CronDaySpecialsTests (47) pins the L / L-n / LW / dW / dL features that
had no tests at all: the occurrence table from CRON.md, month-length-specific
L-n offsets, LW skipping months that end on a weekend, the W rollover rules
(Saturday 1st -> Monday 3rd, Sunday last day -> Friday), OR semantics between
a day special and day-of-week, the strict accept/reject matrix, lenient null
results, and CronParseException Field/Token diagnostics.
- CronFieldParserTests covers the specials at the field level (L-0 folding,
7L -> 0L, plain value + special in one list).
- ScheduleOptionsConfigurationTests covers the strict config path and keeps
"0 0 29 2 *" accepted (leap years are inside the 28-year horizon).
- CRON.md / CRON-ru.md: fix the 4-field "9-17/2 * * *" example, document the
L-n limit (0-30, L-0 == L), the deliberate LW difference from Quartz and the
L + dW list rejection, add a "not supported" section (? / # / names / macros
/ seconds / lowercase specials), and sync the RU timezone, wildcard and
GetNextOccurrence signature text with the EN version.
- README links pointed at the pre-move src/Sa.Schedule/CRON.md path; the
Readme/Readme-ru config table now mentions the strict cron check.
- Correct the misleading "Quartz forbids mixing W with L" comment (LW is the
supported combination; only a separate dW element is rejected) and drop the
stale "(.NET 8-10)" remark in CronTiming.
…one source for field limits; bump 0.17.1 - GetNextOccurrence now returns null instead of throwing when the input is too close to the end of the representable range: the +1 minute start and the 28-year horizon are constructed as DateTimeOffset values, so from year 9971 on they could overflow (previously "9990-01-01" threw ArgumentOutOfRangeException). Year 9970 still searches, including with a negative offset. The method also gets a real XML doc in place of a no-op <inheritdoc/> (CronTiming implements no interface), and CRON.md / CRON-ru.md mention the rule in the search-horizon bullet. - New internal CronLimits is the single source of truth for the five field bounds: CronFieldParser validates against it and CronTiming sizes every lookup table from it, so the hand-written 60/24/32/13/7 table sizes and the separate MaxLastDayOffset can no longer drift apart. PopulateFlags now fails loudly on an out-of-range index instead of silently dropping the value (unreachable while the bounds are shared, but no longer able to hide a future mismatch). - Tests: two facts pin the end-of-range behaviour (null near 9999, and a leap-day search in the last searchable year with a -12:00 offset). The existing 20k-expression fuzz reference was re-run against both the standard and the day-special grammars after the refactor: 0 mismatches. Suite: 314 -> 316, all green. - Version 0.17.1 (the validator behaviour change from the previous commit is user-visible, so a patch bump).
…mp 0.18.0
CronTiming.Every was an exact alias of the constructor, and the name read like an
interval ("Every 15 minutes") rather than "the timing for this expression". Renamed to
CronTiming.For, which pairs with CronTiming.Strict: For is the lenient factory (malformed
syntax throws, an expression that can never fire just returns null), Strict additionally
validates the calendar. The XML doc now says so explicitly, and the alias no longer
pretends to be an interval API.
Breaking for anyone using CronTiming.Every — acceptable at 0.x, hence the 0.18.0 bump.
CRON.md / CRON-ru.md usage snippets and the "lenient factories" sentence updated.
Suite still 316/316 green.
…cted by field count)
- Format detection: 5 fields keep the existing "minute hour dom month dow"; 6 fields mean
"second minute hour dom month dow". The rule is purely positional; a 7th field (year) is
rejected with a message naming both supported shapes, so a Quartz-with-year expression
cannot be misread silently.
- One search path for both formats: CronTiming gains _secondFlags/_nextSecond/_firstSecond,
Matches checks the second, and Advance has a second level before minute/hour/day. A 5-field
expression simply has "second 0" as its only valid second, so its behaviour is unchanged —
the 20k-expression fuzz reference (standard + day specials) still reports 0 mismatches.
GetNextOccurrence now steps AddSeconds(1) and truncates to the second; for 5 fields that
lands on the next minute exactly as before.
- CronLimits gains the 0-59 second range; CronFieldKind.Second is the new first member and
field positions are parsed with a running index instead of (int)enum casts.
- Strict/config: the calendar check is shared, so "0 0 0 31 4 *" is rejected while
"0 0 0 29 2 *" is accepted; the options validator message now says "5- or 6-field".
- Tests: new CronSecondsTests (29 cases: detection, seconds lists/steps/ranges, minute/hour/
day/year rollovers, exclusive sub-second behaviour, 5-field minute precision, strict and
malformed cases, raw-text preservation), a parser-level seconds test, and a config test
proving the overlay detects the 6-field form. CronTimingTests' invalid list now uses 7
fields ("* * * * * *" is a valid every-second expression). Suite: 345 -> 347, green.
Six-field differential fuzz (1500 random expressions vs a brute-force minute+second
reference): 0 mismatches.
- Docs: EN/RU get a "Seconds (6-field expressions)" section with examples, a precision
section explaining the resolution, missed-firing and Task.Delay caveats plus the
"prefer EveryTime for a plain N-second cadence" recommendation; field tables, format and
"not supported" bullets updated; Readme/Readme-ru mention the optional seconds field.
- Version stays 0.17.0 for the dev line (the 0.17.1/0.18.0 bumps from the previous commits
are reverted).
Adds an "expression → from → next" table to the Seconds section of CRON.md and CRON-ru.md, mirroring the day-specials table: plain next second, sub-second input, step/list/range seconds, the exclusive instant, weekday skipping, second→year rollover and a day special combined with seconds. Every row was generated from the built Sa.Schedule and matches the implementation.
…cope lazily, document the cost 1. JobDelay.Wait now takes the scheduler's TimeProvider and uses Task.Delay(delay, timeProvider, cancellationToken) for both call sites (the initial delay in WaitToRun and the occurrence wait in CanExecute), including the chunked path for delays above int.MaxValue ms. The promise is now consistent: the occurrence search reads timeProvider.GetUtcNow(), so a custom clock (a fake provider in tests, a simulated host clock) drives the waits as well instead of the wall clock. Covered by JobDelayTests with a ManualTimeProvider: the timer is created on the provider, the wait does not complete until it fires, and cancellation / non-positive delays behave as before. A hand-rolled allocation-free waiter (reusable ITimer + SemaphoreSlim) was deliberately not added: it would shave a few hundred bytes per iteration off the ~0.3-1 KB that Task.Delay allocates, at the price of hand-managed timer/semaphore races in the hot path of the scheduler. Not a good trade for a 1 Hz ceiling. 2. JobController no longer opens the run's DI scope in Start(): EnsureExecutor does it on the first Execute() and every later iteration of the run reuses it. A slot started for a job firing hours from now (a nightly cron) therefore stops pinning scoped services - a DbContext, a connection - for the entire wait, which is what the pause-gate comment in JobRunner already aimed at. Failures that happen before the first execution (a throwing custom timing, a failed pause gate) still apply the configured error policy: the handler is resolved in a short-lived scope for the duration of the handling. Tests: Start() without execution opens no scope; the first Execute() opens exactly one and Shutdown disposes it; ExecutionFailed before any execution still invokes the handler. 3. CRON.md / CRON-ru.md get a "Cost per firing" section: what one iteration does, the measured order of magnitude (~0.1 ms CPU, a few hundred bytes with a no-op job), the 1 Hz-per-slot cap of a cron expression, ConcurrencyLimit multiplying the executions, EveryTime being able to go below a second, and the "one job that loops beats N jobs on the same cadence" recommendation. Suite: 347 -> 352, green; Sa.Schedule Release build has no warnings.
src/nuget.config maps the `local.nupkgs` source to ./nupkgs, and NuGet fails restore with NU1301 when that path does not exist — a clean clone could not even restore the samples. The folder is tracked through a placeholder, while its contents stay local. `nupkgs/` had to become `nupkgs/*` + `!nupkgs/.gitkeep`: git does not descend into an ignored directory, so a plain negation for a file inside `nupkgs/` would never match. Package files (.nupkg, .snupkg, hashes, nested folders) remain ignored, so `git add src/nupkgs` stages nothing but the placeholder.
…shot; bump 0.17.0 1. OutboxMessagePublisher handed the bulk writer `payloads[..len]` — the requested batch length — instead of the number of items actually written. A collection whose Count over-reports thus pushed default structs into the writer, and through ArrayPool (Return had no clearArray) also the previous batch's payloads. The slice now follows `count`, the loop stops when the enumerator under-yields, the rented array is returned with clearArray: true, and cancellation is checked between batches. Covered by OutboxMessagePublisherTests, which feeds a collection that advertises two items and yields one. 2. Apply ran the caller's transform under the manager's Lock, which is not reentrant: a transform that called Get/IsPaused/Pause/Apply deadlocked against itself. The transform now runs outside the lock and the result is swapped in only if the snapshot it transformed is still current; otherwise it is retried (bounded at 64 attempts, so pathological contention fails loudly instead of hanging). The contract is documented on IOutboxConsumerManager.Apply. Covered by an Apply test whose transform reads the manager. 3. Listener notification enumerated the live List<Action<...>> outside the lock, so Subscribe/Dispose during a callback either threw InvalidOperationException or silently skipped the remaining listeners (the exception was swallowed by the per-listener catch). The list is now snapshotted under the lock. Listener faults go through ILogger instead of Debug.WriteLine, which is compiled out of Release — the one signal a bad subscriber produced was invisible in production.
… floor; bump 0.17.0 1. OutboxTaskLoader read `COUNT(*)` (bigint) with GetInt32. On Npgsql 10 that throws InvalidCastException, and LoadNewTasks swallowed it as "empty queue": no task was ever created from the message table while the cycle looked idle, so adaptive back-off also stepped up. Read int64, drop the dead IsDBNull check (COUNT never returns NULL) and do not touch max_seq, which is NULL when nothing was inserted. LoadNewTasks no longer masks a failure that survived PgRetryStrategy as an empty queue either: it logs and rethrows. Note the consequences for the job error policy: with the default RetryCountOnError = 0 and ThenCloseApplication the host now closes on a persistent load failure instead of silently stopping delivery. 2. OutboxTypeCache.Reset returned Task.FromResult(() => _cache.Reset()) — a Task<Action> whose body nobody invoked — so the in-process map never picked up a type inserted after startup and every miss paid a semaphore plus another INSERT ... ON CONFLICT DO NOTHING. Reset now actually drops the snapshot, a faulted load is dropped instead of being replayed forever, and the load uses the token of the caller that started it (volatile LoadScope: a bare CancellationToken field could be read torn). 3. GetCode used 0 as the "unknown type" sentinel, although 0 is a legal Murmur3 value; it now returns long?, and a stored hash of 0 is found while a missing type is null. 4. OutboxTypeResolver could not tell whether its INSERT won: ON CONFLICT DO NOTHING leaves another type's row in place, and the colliding code was returned as if it were ours — the consumer would then deserialize the other type's payload. The stored name is verified after the insert and a mismatch throws. The hash input stays Type.Name (changing it would split the cursor from rows already stored). 5. The resolved consumption floor is derived by tenant-filtered queries but was cached per consumer group, so the first tenant's boundary was reused for every other tenant. PgOutboxConsumeSettings keys it by (group, tenant) in a ConcurrentDictionary; the floor is resolved concurrently for all tenants of a group (default MaxConcurrency 48), so the raw floor dictionaries are concurrent as well. 6. OutboxTenantDetector and the loader's retry callback ignored the CancellationToken handed to them and used the outer one. Tests: OutboxTypeCacheTests (reset, hash 0, retry after a faulted load, collision), PgOutboxConsumeSettingsFloorTests, and two PostgreSQL tests that read COUNT(*) as long instead of int.
opencode.jsonc is machine-local: it wires MCP servers and points at the DSN in .secrets/postgres-uri, so neither belongs in the repository. Both are ignored now; opencode.json is covered as well for the JSON variant.
The bundled Linux FFmpeg was built with --disable-shared --enable-static for libav*, but the codecs stayed linked to the host: readelf -d listed libmp3lame.so.0, libopus.so.0 and libvorbis*.so as NEEDED. On a machine without those packages the binary did not start at all — exit 127, "error while loading shared libraries" — so every Linux consumer had to install four system packages, which contradicted the "bundled static binaries" promise that the readme (and the Windows payload) already made. build-linux.sh now passes --pkg-config-flags=--static and -static, mirroring build-windows.sh, and fails the build if a codec library leaks back into the dynamic dependencies. The linux-x64 payload is rebuilt from the same FFmpeg 7.1.5 configuration: readelf -d reports no dynamic section, ldd reports "not a dynamic executable", and the binary runs in an empty namespace as well as on a musl rootfs (Alpine) — linux-musl-x64 reduces to linux-x64, so that payload applies there too. GetVersion/GetFormats/GetCodecs now execute with throwOnError, so a bundle that cannot start raises ProcessExecutionResultException carrying the exit code and the ffmpeg stderr tail. Before, they returned an empty string and the caller failed later with an unrelated exception (the sample died on ver.AsSpan(0, 21)). Samples/FFMpeg.Console: print the first version line instead of assuming 21 characters, resolve data/ from AppContext.BaseDirectory (the documented "dotnet run --project Samples/FFMpeg.Console" from src/ used to die with FileNotFoundException on src/data/input.mp3), and reference the project again rather than a PackageReference the empty local Sa.* feed cannot satisfy — the packaged path stays covered by do-package-check.sh in CI. Readmes now describe the payload as it is: fully static, no system libraries needed, no Alpine caveat, plus the "no fallback from a broken bundle" warning.
The linux-x64 payload no longer depends on system shared libraries, and GetVersion/GetFormats/GetCodecs now surface ffmpeg failures instead of returning an empty string, so this is a new minor.
`minio/minio` no longer answers anonymous pulls on Docker Hub and `quay.io/minio/minio` rejects them too, so the fixture could not start on a clean machine. Switch the container to `chrislusf/seaweedfs:4.50`. The SeaweedFS `mini` command runs master, volume, filer and the S3 gateway in one process, which is what a per-test-class container needs, but three details differ from MinIO: - the S3 gateway listens on 8333, not 9000; - credentials come from AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY, and with no config file present they become an admin identity, so requests must be signed; - `-s3.autoCreateBucket=false` keeps writes to a missing bucket failing with NoSuchBucket, so `ThrowIfBucketNotExists` still throws instead of the bucket being created on the fly. The gateway answers anonymous requests with 403, so readiness waits on the internal TCP port rather than an HTTP probe. Replace the `Testcontainers.Minio` package with plain `Testcontainers` 4.15.0; `MinioBuilder`/`MinioContainer` are gone, the container is a ContainerBuilder.
…containers
Every integration test class boots its own container, but each image is pulled
once and then reused from the local daemon — after that the suites need no
registry at all. Two scripts make that state explicit and reproducible on a
machine that cannot reach Docker Hub:
- `do-docker-images.sh {status|pull|save|load}` — the image list lives in
tasks.sh (DOCKER_TEST_IMAGES) and mirrors the fixture defaults; `save`/`load`
moves the tars to an isolated machine through dist/docker-images.
- `do-docker-bypass.sh {status|on|off}` — when a VPN owns the default route,
pulls crawl through the tunnel. `on` adds host routes for the registry, its
auth endpoint and the blob CDN to the tunnel's policy-routing table, pointing
at the physical gateway, so only those hosts bypass the tunnel. Routes are by
IP, hence `on` → `pull` → `off` in one go.
Both files are executable and documented in build-sh/readme.md; AGENTS.md now
describes the SeaweedFS image and the offline/warm-up workflow.
…names, identifier budget; bump 0.17.0
`PgPartBy.FromPartName` resolved every stored strategy to `Day`. The `part_by` column
holds `PgPartBy.Name` ("Day"/"Month"/"Year"), but the lookup went through
`Part.TryFromName`, whose registry holds the single entry "root": every value missed
and fell back to `Day`. A month- or year-partitioned table was then checked against a
one-day range by `PartCache.InCache`, so its partition looked missing on every write and
the whole partition DDL plus a cache flush ran each time. Resolve by `Name`.
The cache snapshot had the same hole from the other side: it kept partitions whose range
starts within `CachedFromDate` (one day by default), while the partition being written to
may have started on the 1st of the month or on 1 January. The window is now widened to
at least one full partition period of the table, and `EnsureCache` reports by outcome
(it returns when the partition exists) instead of re-reading the snapshot — which could
only ever say whether the *window* covers the date.
DDL paths that cannot take parameters, hardened:
- partition names read back from the cache table (`DROP TABLE`, `DETACH PARTITION`,
`SET SCHEMA`) are parsed into their component identifiers and quoted again, so a
corrupt row can only ever become a quoted identifier — never an extra statement;
- a partition value containing `SqlPartSeparator` is rejected: ("a__b", "c") and
("a", "b__c") composed the same table name with different bounds, and the second
`CREATE TABLE IF NOT EXISTS` silently no-opped while its rows landed in the first;
- a literal containing a backslash switches to the `E'…'` form with the backslash
doubled, so it cannot swallow its closing quote under any `standard_conforming_strings`;
- the range annotation is flattened, so a newline in a field name cannot end the `--`
comment and leave the rest of the name as live SQL;
- `Find` removes only the quotes that enclose each part instead of every quote in the
string, and a schema name that arrives quoted no longer opens a second schema group.
Smaller items: `StrToDate` returns null for an out-of-range calendar value instead of
throwing; `WithFillFactor` rejects values outside PostgreSQL's 10–100 instead of clamping
them silently; `WithPartSeparator` / `WithPartTablePostfix` reject control characters and
`ArchiveSchemaName` is held to the 63-byte limit; `EnsureParts` drops its `Task<bool>`
(the bool was false whenever the partition was merely outside the cache window, which
read as a failure); and the 63-byte error now names the fixed part of the name and what
is left for the values.
Tests: a Day/Month/Year lifecycle matrix (ensure, idempotency, migrate, write, drop,
archive), a smoke suite that executes the generated DDL for hostile values and for
table/schema names carrying a quote, and a round-trip property test for the
`part_values` encoding.
…budget, test settings; bump 0.17.1
`EscapeIdentifier` escaped a double quote inside a quoted identifier as two apostrophes
(`''`) instead of doubling it (`""`). Inside `"…"` an apostrophe is plain text, so the
emitted `"a''b"` was a valid but *different* identifier: every object was created under a
name the caller never configured. The two places that embed a table name in a constraint
(`pk_…` for `__type$` and `__offset$`) were also interpolated inside quotes with no
escaping at all, which the new `QuoteDerivedIdentifier` fixes.
A leaf name is `table__{tenant}__{key}__{date}`, and PostgreSQL truncates identifiers at
63 bytes. Nothing checked that arithmetic, so a consumer group id or a message part name
that was too long failed at the first DDL — for the delivery log that means the first
*failed* delivery, long after startup. `PgOutboxPartitionNames` now owns the budget (the
day suffix is rendered by `PgPartBy`, the separator is pinned to the partitional default
by a test), the registered consumer groups are validated at startup through
`IOutboxConsumerManager.GetAllConsumerGroupIds()`, and the exact check with the real
tenant runs in `OutboxPartRepository` before the DDL.
Also: `UseTestSettings()` set `ForwardDays = 0` and `ExecutionInterval = TimeSpan.Zero`,
both of which the partitional schedule validators reject at host start — the methods
could never work; `FillFactor` accepted 1–100 while PostgreSQL accepts 10–100;
`WithTaskTableName` fills the one gap in the fluent setters; and table/schema names are
validated once from the container factory, before any SQL template is built. The settings
are documented as "configure before the container is built", since `SqlOutboxBuilder`
composes every template from them in its constructor while `NpgsqlOutboxReader` reads
them live.
…runs; bump 0.17.1 The stop token is linked to the caller's token, so cancelling it (the host's startup token, a scoped request) ends the job without `Stop()`. The scheduler learned about that only from a running slot: `RunJob`'s `Stopped` branch calls `AbortJob` when the token is cancelled. That is not enough, because `SaWorkQueue.ExecuteItemAsync` checks the producer token *before* invoking the processor and reports the item as `Aborted` when it is already cancelled — so a token cancelled after `Start()` returned but before a reader picked the slot up drops the item, no processor runs, and `IsStarted` stays true over a dead job forever. `JobSchedulerTests.CallerTokenCancelledLater_...` failed on exactly that race, intermittently, depending on which side of it the thread pool landed. `Start` now registers an observation on its own stop token, so the state follows the caller's token whatever the slots are doing. The callback only flips `_started`: it deliberately does not call `AbortJob`, whose `ForceCancelReadersAsync` would turn `Stop()`'s graceful drain (bounded by the shutdown timeout) into a hard cancel — and `Stop()` cancels that same token. It ignores a superseded start (a new `Start` cancels the previous source before arming its own) and records `_jobEndedDuringStart` while a start is still in flight. Added `CallerTokenCancelledBeforeTheSlotRuns_MarksTheJobStopped`, which repeats the start-then-cancel race until the item is dropped before the processor runs; it fails on the previous code and passes now.
…s*.pub
The encrypted layer used `secrets_enc*.txt`, an infix plus a `.txt` extension that
advertised nothing about the file's safety: it read like a plaintext secrets file that
happened to be encrypted. The committed file is ciphertext, so it now carries that in its
name instead of in its body.
Lookup order and priorities are unchanged; only the four names changed:
secrets_enc.txt -> secrets.pub
secrets_enc.{env}.txt -> secrets.{env}.pub
secrets_enc.{client}.txt -> secrets.{client}.pub
secrets_enc.{client}.{env}.txt -> secrets.{client}.{env}.pub
This is a hard replace: the old names are not probed any more, so an existing deployment
that still ships `secrets_enc*.txt` silently loses the encrypted layer until the files are
renamed. `Secrets.EncryptedFileName` keeps its name and changes value to `secrets.pub`;
`EncryptedFileSecretStore` is untouched because it takes a path.
`do-secrets.sh check` now globs `secrets*.pub`, the committed sample moved to
`secrets.lsr.Development.pub` (same ciphertext, verified to decrypt), and both READMEs
plus the store docs follow. One line in each README notes that `.pub` marks a safe-to-commit
file rather than a public key, since the extension usually means the opposite.
Tests: existing cases moved to the new names, plus `CreateDefault_ReadsEnvironmentOnlyEncryptedFile`
(`secrets.{env}.pub` with a null client was previously not covered at all) and an assertion
pinning `EncryptedFileName`. `Sa.ConfigurationTests`: 124 passed.
…rt counts; bump 0.17.1 The docs declared the range partition column as `timestamptz` while every generated `FOR VALUES` bound is a Unix-second integer, so the documented configuration failed in PostgreSQL with "specified value cannot be cast to type timestamp with time zone". The column is `bigint` throughout now. Guards, so that mistake - and its neighbours - fail at Build() instead of inside a background migration job: - Build() rejects a list column that no field declares, a list column listed twice, and a `timestamp`/`timestamptz`/`date`/`time` range column. - CreateSql throws ArgumentException when the number of part values does not match the declared list depth (it used to emit an incomplete tree under a comment, whose deepest level had no range leaf, and every later INSERT failed). - MigrateSql skips a list-partitioned table that resolved no values instead of emitting that incomplete tree. Other fixes in the package: - PartMigrationService no longer disposes the deadline CancellationTokenSource twice. - PartCleanupScheduleSettings only validates ArchiveSchemaName in Archive mode. - PartRepository drops IDisposable: the semaphore is deliberately never disposed, and disposing it broke runs still queued on it. - GetDefaultSchema no longer swallows every exception: only "no data source" and "connection string is still empty" fall back to the default schema, so a malformed configuration surfaces at build time instead of at the first migration. Enabled by the new PgDataSourceResolver.TryResolve. - AddSaPartitional validates its arguments and names its parameter `asBackgroundJob` (public surface). - Dead internal API removed (CreatePartSql, SelectPartsQualifiedTablesSql, GetPartsSql); SqlFieldName is quote-aware and gained ExtractType/HasColumn. - XML docs and Readme/Guide/ApiReference aligned with the code: EnsureParts returns Task, ArchivePartsToDate documented, CleanupMode/Archive described, WaitMigration waits asynchronously, and the generated-DDL example regenerated.
…after shutdown; bump 0.16.2 Review follow-up on the work queue. Force cancel - ForceCancelReaders and ForceCancelReadersAsync drained the buffer on every call, so a paused queue (ConcurrencyLimit = 0) — or one whose readers were already unwinding — threw away work nobody had cancelled: the accepted items were reported as Faulted and lost, although the caller only asked to stop the pool. CancelAndTrackReaders now reports how many readers it actually stopped, counted in the same critical section that takes the decision (which is what makes the call idempotent), and the drain runs only when that count is non-zero. The async variant no longer drains "because there was nobody to wait for" either: with nothing cancelled there is nothing to discard, and a re-armed pool still has the work to do. The channel is untouched by force-cancel in both cases — it stays open so the queue keeps accepting, exactly as before. Slot accounting - RemoveReader treated the readers a shutdown dismisses as lost slots, so every shutdown ended with ConcurrencyLimit reading 0 while the contract — and the reason the setter is a no-op once stopped — says the getter keeps reporting the limit the queue was stopped at. A stopped queue is not a lost slot: its readers did not die, they were cancelled. Shutdown cause - _shutdownError is a volatile field again, read directly by ShutdownError, and written through Interlocked.CompareExchange so two simultaneous faults keep the first cause. Passing a volatile field by ref is the case CS0420 documents as legitimate for an interlocked API; the warning is suppressed locally, on that one call. Options - Undefined enum values were read as their default arm: (SaEnqueueStrategy)99 behaved as Skip, an unknown ReaderCancelMode as Hard, an unknown ReaderCancellationOrder as Lifo. A typo in appsettings looked deliberate. The constructor and SaWorkQueueSettingsValidator now reject them with Enum.IsDefined, which is AOT-safe. EnqueueMany - A null sequence surfaced as a NullReferenceException from inside the loop; ArgumentNullException.ThrowIfNull reports the argument and the XML docs list the exception. Tests: the paused-queue cases for both force-cancel variants (verified to fail with the gate removed), the limit after shutdown and dispose, the enum validation in the constructor and through configuration, and the force-cancel gate itself. Readmes and the ISaWorkQueue remarks describe the new drain rule.
…p 0.17.0 Repeated AddSaConfiguration calls used to install independent post-secret passes. Each pass copied the whole merged configuration into its own provider, so the last pass shadowed every alias derived by an earlier one, secrets were read once per call, and Reload() never dropped a key that had disappeared. - state in builder.Properties: aliases accumulate, one pass, one CLI source; a canonical key declared twice is won by the last call, as are SecretOptions and CanonicalValueWins - transform pipeline (ISaConfigurationTransform / ISaConfigurationView) with built-ins for placeholders and aliases; custom transforms run after them - the pass now stores only derived keys, in canonical `:` spelling with a case-insensitive lookup, and replaces its data on every Load() - FinalizeSaConfiguration() moves the pass after every registered source - secrets are created lazily on the first build instead of at registration - AddSaPostSecretProcessing(ISecretService, KeyAliasOptions?) stays additive - docs: multisetup, finalize, custom transforms, Reload; PG ordering fixed - tests: ConfigurationMultisetupTests (13 cases)
…numerate ReadAsync, DeleteFileAsync and EnumerateFilesAsync resolved their paths textually, so a link planted inside the root redirected them outside it. - ReadAsync and DeleteFileAsync run the component check that WriteAsync and CopyFileAsync already had: a directory link (`root/up_cache -> /var/www`) made File.Delete unlink a file outside the root, and a read handed out its content. The check runs before the file is opened, so nothing escapes even for the duration of the call - EnumerateFilesAsync sets AttributesToSkip = ReparsePoint, exactly like the volume scan and the cleanup walk: a recursive walk no longer reports paths from the link's tree, and a link cycle cannot hang it - docs: the symlink rule now covers every operation (create, write, copy, read, delete, enumerate), plus an error-table row for it - tests: SymlinkProtectionTests — a delete through a link leaves the target intact, a read through a link never invokes the callback, and a recursive enumeration ignores the linked tree
…gn validation and docs - MaxFoldersPerPass is enforced by the instance now (candidates.Take(budget)), not just by the built-in strategy: a custom strategy registered with UseCleanupStrategy<T>() could return an unbounded list and make one pass delete the whole expired tree. ICleanupStrategy documents that the instance truncates, so "oldest first" is what leaves the freshest folders for the next pass - FreeSpaceCheckInterval: zero is accepted while the check is off (MinFreeSpace = 0) — the same "not used" convention the cleanup knobs already follow — while a negative value stays an error either way - the FolderPrefix check in AgeBasedCleanupStrategy compares with PathGuard.PathComparison (case-insensitive on Windows) instead of always Ordinal, so a folder spelled with a different case is no longer treated as foreign and silently skipped - docs: read-only instances reject DeleteFileAsync too and CleanupExpiredAsync is a no-op returning 0 (the old wording listed cleanup as rejected and omitted delete); MaxFoldersPerPass and the interval rule updated in ITempFolder, the options type and both readmes - tests: a custom strategy over the budget is truncated by the instance; the interval theory covers (negative, 0) x (check off, check on), plus a Windows-only prefix-case case that skips elsewhere
…files atomically
Volume tracking
- the pre-cleanup measurement moved above the CleanupEnabled early return: with
CleanupEnabled = false, TrackVolume = true and the default VolumeScanInterval
of 0 the scan was its only trigger, so turning the cleanup off silently
switched the whole feature (and OnVolumeExceeded) off
- the scan is skipped up front when CleanupGate reports activity or a pass in
flight — the pass below cannot start in that state anyway, so the tree walk
would be wasted; a measurement itself is reporting only
- VolumeScanner serialises its walks with a SemaphoreSlim: the pre-cleanup scan
and the independent interval loop no longer fight over the cache, where a
stale walk could overwrite a fresher measurement
- Invalidate drops the loose-file entry for paths directly in the root: an
overwrite moves no directory stamp at all, so the cached total stayed frozen;
WriteCoreAsync now invalidates on every successful write, not only deletes
WriteAsync / CopyFileAsync
- the copy is staged in a sibling `.sa-{guidv7:N}.tmp` file in the target's own
directory and renamed into place with File.Move(overwrite: OverwriteFiles).
A reader no longer observes a truncated target, and a failed or cancelled
copy leaves an existing file exactly as it was — the old
FileMode.Create had already destroyed it before the first byte was copied.
The staging file is always created with CreateNew (its name is unique), so
the overwrite policy is enforced by the rename alone
- a failed copy removes the staged partial, as before, but never the target
- docs: turning the cleanup off no longer claims to stop volume tracking; the
cache-invalidation rule covers writes; WriteAsync row and the error table
describe the staged write
- tests: cleanup disabled still measures; overwriting a root-level file updates
the measured total; the preallocation test now inspects the staged file and
checks nothing is left behind; a failing source leaves the existing file
intact
…lver cache; bump 0.17.0 - CleanupGate released the interrupt CancellationTokenSource without disposing it: every cleanup pass leaked one source with its registrations. ReleasePass now takes it under the lock, clears it and disposes it after leaving the lock — a waiting activity may still hold the snapshot, and Cancel tolerates a disposed source - FilePathResolver: the per-file cache is bounded at 65 536 entries and dropped wholesale on overflow, instead of growing with every distinct database path a long-running process sees; an exception thrown by a Resolved handler is swallowed, so a subscriber cannot break a lookup that already succeeded; the ToRelative containment test uses the platform comparison (case-insensitive on Windows) instead of always Ordinal - docs: both resolver readmes describe the bound and the handler guarantee - version 0.16.1 -> 0.17.0: WriteAsync/CopyFileAsync now stage and rename, a failed copy no longer truncates an existing file, and paths through a symlink are rejected for reads, deletes and enumeration
… IDs, keyed registration
The provider sits between a caller-supplied File ID and the disk, so the path
boundary is where the fixes are concentrated.
- CanProcess: the containment check now requires a separator (or the end of the
path) after {root}/{basket}, so a sibling basket that merely shares the name
prefix (`share` vs `share2`) is no longer claimed, and the comparison follows
the platform's casing rules like PathGuard does. An ID the OS cannot resolve
(NUL character, unsupported form, over-long path) reads as "not mine"
instead of throwing — the hybrid chain probes every storage with this
predicate before any failover handling. The path is now resolved once: the
second GetFullPath over an already absolute Combine result was pure overhead.
- File IDs always use '/': the sanitizer emits the platform separator for
nested names, which leaked a backslash into the ID on Windows and made the
same file map to different IDs per OS.
- PathSanitizer: reserved Windows device names (CON, PRN, AUX, NUL, CONIN$,
CONOUT$, COM0-COM9, LPT0-LPT9 — matched on the stem before the first dot, so
`NUL.txt` counts) and segments with a trailing dot are rejected on every
platform: Windows resolves the former to a device (the upload would write
nowhere) and strips the latter (`report.txt.` would alias `report.txt`), so
two File IDs would fight over one file. The fast path mirrors the complex one
(trim, invalid-char replacement) and routes these names to it, so none of
them can slip through unchanged; the dead SanitizeSimplePath identity is gone.
- DeleteAsync also swallows UnauthorizedAccessException — the temp folder
retries it and rethrows it, so the documented "returns false" contract now
holds on both exception types.
- GetMetadataAsync reports the configured basket rather than the one re-parsed
out of the ID (matching the Postgres provider).
- registration: the storage is registered keyed by its name (with the previous
unkeyed registration kept as an alias of the same instance), the named
options instance is named after the registration instead of an internal
sequence, and the test-only FileSystemStorageRegistration marker is removed —
the duplicate-name guard is anchored on the keyed IFileStorage. The now
unused InternalsVisibleTo entries are dropped.
- docs (en/ru): nested File IDs, the real layout for nested names, the
RootPath rule, the two read-only switches, portable (device-safe) names, and
a corrected error table.
- tests: path ownership (sibling baskets, foreign schemes, NUL IDs), portable
nested IDs, read-only upload/delete/download, sanitizer fast-path parity and
the rejected device/trailing-dot names, keyed resolution and the
options-instance name.
- Bump to 0.17.0. Remove the outdated planning notes under docs/.
…e non-seekable uploads, read metadata from the table
The data path carried two silent defects, and the read contract disagreed with the
other providers, so the fixes are concentrated there.
- DownloadAsync: the reader callback was passed to IPgDataSource.ExecuteReader,
whose parameter is a synchronous Action — an `async` lambda there compiles to
`async void`. The method returned before the consumer finished, a failure inside
its callback was unobservable, and the reader/connection could be disposed while
it was still reading. The connection is opened directly now, so the whole read is
awaited while the reader is open; the consumer's callback stays outside the
catch that maps a missing table to "not found".
- UploadAsync: a non-seekable stream was buffered and handed over at its end.
Npgsql writes a Stream parameter from the current position, so the row was stored
with an empty `data` while `size` recorded the real length. The buffer is rewound,
and the whole buffering block sits in the try so the buffer returns to the
manager when the read fails.
- GetMetadataAsync answered for any parsable file ID without touching the database,
so a deleted or never-uploaded file looked present and won the hybrid chain. The
row is read now and `null` means "not here". A table that does not exist yet (no
upload, no migration schedule) also answers not-found instead of raising 42P01,
the same way the partition cache treats those codes.
- UploadAsync rejects a FileName longer than the column or containing a NUL byte
with a named argument error instead of a bare PostgreSQL 22001/22021, and the new
MaxUploadSizeBytes option (0 = no limit) bounds a buffered upload: the check runs
before the partition DDL for a seekable stream and while buffering a non-seekable
one.
- Schema auto-detection from the connection's Search Path is normalised (unquoted
entries fold to lower case, quoted ones lose their quotes) and validated as a bare
identifier, falling back to "public". A quoted or mixed-case entry used to produce
SQL that does not parse, or a schema PostgreSQL never resolves to.
- Smaller corrections: `created_at` is matched by equality and the no-op upsert of
the partition key is gone; the qualified name and the four statements are built
once; CanProcess is the prefix check alone (the prefix already carries the basket,
so the second parse was dead); UploadedAt is the upload instant rather than the UTC
midnight of the day; a null file ID is rejected instead of reading as "not found";
the unnamed-options guard in the table registry also covers the empty name that
IValidateOptions reports for the default instance. Copy() is `this with { }`, and
CopyTo is guarded by a record-equality test, so a property added later cannot be
silently dropped by the explicit-instance overloads.
Tests: a non-seekable upload, an asynchronous download consumer, missing
file/table/schema reads, the read-only guards, the size limit on both stream kinds,
CanProcess negatives, the retention/forward-days wiring into the schedules, and
PartByRange reaching the DDL (monthly leaves, no daily ones). The partition-tree
comment records why the basket list level stays: PostgreSQL cannot infer a narrower
ON CONFLICT target from the existing wider primary key, so removing it would reject
writes on every table created before the change.
…rden the reader, add the float DSP path; bump 0.17.0 Sample conversion - The 24-bit writer scaled to 16-bit amplitude (int.MaxValue / 65536), so every 24-bit output was 48 dB too quiet; use the full 8_388_607 range. - Clamp (and NaN -> 0) in every PCM writer. Converting an out-of-range double to an integral type is unspecified in C#, so an overloaded float WAV turned into silence instead of clipping. - Convert8BitToDouble divided integers (value / byte.MaxValue): every 8-bit sample except 255 read as -1.0. - Add float converters plus AsyncWavReader.ReadFloatSamplesAsync / AudioFloatPacket for DSP paths that would otherwise pay a byte -> double -> float round-trip. Reader and header - Resolve DataSize from the file length for streamed WAVs (data size 0xFFFFFFFF): GetDuration() no longer reports a fake ~13.5 h and Echo no longer sizes buffers from 1_073_741_823 frames. - GetHeaderAsync parses without the caller's token, so a cancelled first call no longer poisons the cached header task; the token now only cancels the wait. - Validate block align against channels x bits/8 and reject unsupported (format, bits) pairs at parse time instead of deep inside a converter. - Truncated headers throw InvalidDataException instead of ArgumentOutOfRangeException; fmt chunks smaller than 16 bytes are rejected; skip length is verified. - AsyncWavReader.Create(Stream) leaves the caller's stream open (LeaveOpen) and owns only what it opens itself; Dispose/DisposeAsync are idempotent. - Passing a malformed pipe reader is reported as ArgumentNullException. Echo - Estimate cross-talk in one pass (per-frame sums of l^2, r^2 and l*r), dropping the extra full read; in-memory and streaming estimates now agree byte for byte. - Aggressive mode refuses recordings that do not fit in memory instead of renting gigabytes. Output path and arguments are validated before touching the file system. - CrossFeedSeparator is a static class; TimeRangeExpander renamed to TimeRangeExtensions and thresholdMillesecods to thresholdMilliseconds. Tests and docs - Rewrite the Echo suite on synthetic audio with a known cross-talk model: the five pcm_s16le.wav tests were skipped and only asserted the output header. Assert the actual suppression (>= 40 dB, measured ~75 dB), frame counts and normalization. - Add header, converter, reader lifecycle, buffer-reuse and float-path suites. - Delete the unused AsyncWavWriter and the assembly-wide xUnit1004 suppression. - Fix the readmes: Create(stream) instead of a non-existent constructor, the real Auto threshold, buffer-reuse semantics, and the new float API. Fix the sample's path.
…-path allocations
Per-item work:
- WorkItem is a struct: removes the one 32-byte object every Enqueue allocated.
- ExecuteItemAsync is inlined into the reader loop, so an asynchronous item keeps
one boxed state machine instead of two.
- An item whose producer token is already cancelled is reported Aborted without
building a linked CTS first.
- Reader.Work exists only in Soft mode; Hard mode already owns the item through
the loop token.
- LaunchReader no longer allocates a Task continuation: the loop completes its
own Reader.Completion from finally.
- SingleReader is promised to the channel when MaxConcurrency is 1.
Shutdown/drain:
- Status names are formatted only when a logger exists.
- A drain allocates no exception per dropped item when there is no status
callback, and returns the pending count in one critical section.
Producer cancellation:
- New SaProducerCancellationMode { Observe, Detached } and
WithProducerCancellation / SaWorkQueueSettings.ProducerCancellation.
- Detached keeps the producer token for the WriteAsync wait only; an accepted
item runs to a terminal status. An already-cancelled token rejects the offer,
EnqueueMany stops between items, and queue shutdown/force-cancel still cancels.
Benchmarks:
- New dependency-free harness (src/Benchmarks) measuring time and process-wide
allocated bytes, including multi-producer and detached-token scenarios.
Enqueue on the synchronous path drops from 32.2 to ~0.2 B/op and detached
ref+token from ~140 to ~0.6 B/op.
Tests: 188/188; adds producer-cancellation coverage and the undefined-enum guard.
…nd readers NpgsqlDataReader.GetOrdinal scans the statement's field list by name. The task queue reader already captured its ordinals once per result set (M3), but the payload reader did not: every delivered message paid a GetOrdinal for msg_payload, on the main delivery path. - MsgReader/TypeReader now expose an Ordinals record and Capture, matching TaskQueueReader; GetMgsPayload/GetTenantId/GetTypeId/GetTypeName take it in. - StartDeliveryCommand captures both halves of the joined row on the first row. - SelectMsgTypeCommand captures its ordinals the same way. - SelectTenantCommand reads the single projected column by index (always 0), and drops its now-unused NpgsqlOutboxReader dependency.
…che identities Publish path: - OutboxBulkWriter dedupes (day, tenant, part) in a dictionary before calling EnsureMsgParts. SelectWhere allocated an N-element array and EnsureParts filled an N-entry HashSet even when all N messages shared one part, which is the normal publish shape. - PgOutboxDatabaseGuard caches the parsed (host, port, database) identity per connection string. It is checked on every transactional publish, and rebuilding it parsed the connection string each time. Delivery path: - ReturnDelivery keys delivery parts by (day, tenant, part) and copies the OutboxPartInfo only on the first occurrence instead of once per message; error days reuse the same day value. The sets are no longer pre-sized to the whole batch. - EnsureErrorParts no longer runs Select(StartOfDay).Distinct() over a set that the caller already keyed by day. Polling: - OutboxTaskLoader caches advisory-lock keys per (consumer group, tenant), removing a ToString()-based hash walk from every poll. - DeliveryJobInterceptor uses the ordinal StartsWith overload.
AddParam<TProvider, T> used CreateParameter() and assigned (object)value, so every long/int bound by a bulk statement boxed. The Outbox finish statement binds eight parameters per delivered message, and a 1024-row batch therefore produced thousands of boxes per round trip. Value types now become NpgsqlParameter<T>, which carries the value in a typed field. A null reference keeps the untyped parameter with DBNull, exactly as before, because a null has no type to infer. Pinned by DbCommandExtensionsTests: the runtime parameter types and the round trip through PostgreSQL for long, int, string and a null text.
…napshot Every publish, poll and lock renewal calls the type resolver to turn a payload type name into its Murmur3 code. Once the map was loaded, the old path still ran two async wrappers (GetStorage -> Observe) plus the resolver's async Task, so a cache hit allocated a few tasks and state-machine plumbing per call. - OutboxTypeCache publishes the immutable Storage in a volatile _ready field after a successful SelectAll. Reset clears it before invalidating ResetLazy, so a lookup cannot answer from the snapshot that is being dropped. - TryGetCode / TryGetTypeName resolve synchronously from that snapshot without starting a load. - IOutboxTypeResolver now returns ValueTask<long>/ValueTask<string>; the resolver returns a completed ValueTask on a hit and only falls back to the async insert/retry path on a miss. Both interfaces are internal. Pinned by GetHashCode_CachedType_DoesNotReloadTheTable: a second lookup of a known type performs no additional SELECT.
…dless tenant CTS
Publish:
- OutboxMessagePublisher now builds one immutable OutboxPartInfo per publish
call and shares it across the batch. Every message of a publish has the same
tenant, part and timestamp, so the old code allocated one record per message
for no reason.
- PublishSingle is implemented on the publisher: one pooled OutboxMessage slot
written straight to the bulk writer, instead of the [message] collection plus
the batch/enumerator machinery in Send. The interface's default single-message
overloads now route to this method, and PgOutboxPublishExtensions.PublishSingle
uses it for the transaction path.
Delivery:
- ProcessTenantWithTimeout creates a linked CancellationTokenSource only when
PerTenantTimeout is positive. Zero (the default) no longer allocates a source
and a registration per tenant per iteration.
- FilterFactory builds the transaction id with string.Create/TryFormat, avoiding
the intermediate Guid.ToString("N") string per tenant per iteration.
Tests: Publish_Batch_SharesOnePartInfo and
PublishSingle_ThroughTheInterface_UsesTheSingleMessagePath.
…ed delivery contexts OutboxPartInfo is now a readonly record struct. It is part of every published and delivered message, and the PostgreSQL provider used to create two of them per delivered message; as a value type those allocations disappear. Providers only read its fields, so value semantics are enough. Publish path: - New OutboxMessageBatch<TMessage>/OutboxMessageBatchItem<TMessage>: one shared part for the batch plus payload/payload-id pairs, with no OutboxMessage<T> wrapper object per message. - IOutboxBulkWriter gained batch overloads. Their default implementation materializes the old OutboxMessage<T> shape, so an existing provider keeps working until it overrides them; the PostgreSQL provider overrides both the context-less and the transaction overload and writes rows directly. - OutboxMessagePublisher builds batches from a pooled item array; PublishSingle uses the same path with one slot. Delivery path: - IOutboxContextFactory gained Return<T> (default no-op). The built-in factory pools OutboxContext<T> per closed generic (capped at 256), clears it on return and resets it on rent, so a finished delivery no longer leaves payload, delivery-info and exception references behind. - DeliveryTenant returns contexts only after ReturnDelivery has persisted the statuses; if that call throws, the contexts are left to the GC. - IConsumer.Consume now documents the ownership contract: contexts and the messages memory must not be retained past the call. Versions: Sa.Outbox and Sa.Outbox.PostgreSql bumped to 0.18.0. Tests: batch-overload routing, legacy batch adapter, and context reuse/reset.
…sk per EnsureParts Table resolution: - SqlBuilder now builds a name index once: full names plus the bare name of a table in the default schema. Find used to interpolate "schema.table" on every unqualified lookup (one string allocation per EnsureParts) and then fall back to a linear scan of all builders. A quoted name still takes the unquote path. Part cache: - InCache resolves the builder once and scans the snapshot with a plain loop, so the capturing lambda and the SequenceEqual enumerator no longer allocate per call. SnapshotFloor and the loader take the resolved builder instead of doing another lookup. - AwaitLoad returns the completed snapshot directly. Task.WaitAsync allocated a task even for an already-finished load; a cancelled caller still goes through WaitAsync, preserving the token contract. Cleanup/migration: - PartCleanupService iterates the table collection instead of projecting FullName through LINQ; PartMigrationService fills the dates array in a loop. Version 0.17.2. Tests: 270/270.
…k on running iterations - JobContext.JobName resolved the GUID fallback on every access: the property is read by every snapshot, error line and log call. It is now formatted once when the context is created. - WaitIfPaused took the pause lock on every running iteration just to observe that the slot is not paused. A volatile fast path returns before the lock; a Pause() that lands just after the check still takes effect on the next iteration, which is the same guarantee the locked check gave. Version 0.17.2. Tests: 353/353.
Command churn: - PgDataSource now keeps a small pool of NpgsqlCommand objects (capped at 64) for the paths where the caller cannot mutate the command: the parameter overloads of ExecuteNonQuery/ExecuteScalarTyped/ExecuteReader, both ExecuteReaderList overloads, and ExecuteReaderFirst. Rent sets the text and connection, return clears parameters/text/connection/transaction; the pool is drained on Dispose/DisposeAsync. - The initCommand overloads stay unpooled on purpose: the caller's mutator can change CommandTimeout/CommandType/result-type flags, which must not leak into the next renter. Closures: - The parameter overloads of ExecuteNonQuery/ExecuteReader and both ExecuteReaderList overloads no longer route through an Action<NpgsqlCommand> closure just to run FillParams. ExecuteReaderList also reads rows directly instead of invoking ExecuteReader's per-row callback (which allocated a closure over the list and the reader delegate). - ExecuteReaderFirst builds its per-T reader delegate once per closed T instead of repeating Nullable.GetUnderlyingType/IsEnum/GetTypeCode on every query. Version 0.16.1. Tests: Data 75, Outbox.PostgreSql 166, Partitional 270, Configuration.PostgreSql 35.
OutboxTaskDeliveryInfo and OutboxDeliveryMessage<T> were record classes created for every delivered message by the PostgreSQL provider, so two allocations per message existed solely to carry values into OutboxContext. Both are now readonly record structs; OutboxContext stores the delivery message by value and the pooled context is reset/copied without changing its ownership contract. This follows OutboxPartInfo, which became a struct in the previous contract change. Sa.Outbox and Sa.Outbox.PostgreSql are bumped to 0.19.0. Tests: Sa.Outbox 136/136, Sa.Outbox.PostgreSql 166/166.
- OutboxBulkWriterDefaultTests uses async tests and awaits the ValueTask instead of blocking on GetAwaiter().GetResult() (xUnit1031). - DeliveryGroupConfigurationKeyTests uses Assert.Single(collection, predicate) instead of filtering with Where first (xUnit2031). - PartitionGranularityTests now asserts the granularity-specific range leaf in the two theories that declared the parameter but never read it (xUnit1026). Solution build is warning-free; Outbox 136, Outbox.PostgreSql 166 and Partitional.PostgreSql 270 tests pass.
The ownership note said not to retain contexts but did not show what a consumer should do instead. Add an example that copies message.Payload into its own collection inside Consume and acknowledges the message, plus the deep-copy variant for mutable payloads or custom serializers that may reuse buffers.
OutboxMessage<T> was the last per-message class on the delivery path: the PostgreSQL reader constructs one for every row, and OutboxDeliveryMessage<T> (a struct) then carried it by reference. The new Sa.Outbox.Benchmarks harness measures the envelope without a database: publish/batch, publish/single, and delivery/context for reference and value payloads, with fake writer/metadata. Baseline with OutboxMessage<T> as a class: delivery/context/ref == 64 B/op, ~2.3-2.5M ops/s. As a readonly record struct: 0 B/op, ~2.3M ops/s — the allocation disappears and the copy cost is inside the run-to-run noise. Kept the struct. Sa.Outbox and Sa.Outbox.PostgreSql are bumped to 0.20.0 (breaking: record class -> struct). Tests: Sa.Outbox 136/136, Sa.Outbox.PostgreSql 166/166; solution build clean.
…rge structs The metadata payload-id accessor was stored as Func<object, string>. Publishing a value-type TMessage passed it through object, boxing the whole payload on every message. The new large-payload benchmark exposed it: a 512-byte struct payload cost 536 B/op on publish/batch/large-struct (one boxed payload per message) and ran at ~1.6M ops/s. OutboxMessageMetadata now keeps the caller's typed delegate and exposes a generic GetPayloadId<TMessage>; the IOutboxPublishable fallback is resolved once per closed TMessage. Value payloads that do not implement the interface no longer box. After the fix publish/batch/large-struct is 0 B/op and ~4M ops/s. The benchmark also measures delivery/context for a 512-byte value payload: 0 B/op, ~2.3M ops/s. Tests: Sa.Outbox 136/136, Sa.Outbox.PostgreSql 166/166; solution build clean.
- AddMetadata<T> and AddMetadata<T>() no longer require T : class, in both IOutboxMessageMetadataBuilder and IOutboxBuilder. A struct can now register a typed getter or derive metadata from IOutboxPublishable; the generic call is constrained, so GetPayloadId/PartName do not box for a struct. - The tenant-deriving Publish/PublishSingle overloads on IOutboxMessagePublisher no longer require TMessage : class, so a struct that implements IOutboxPublishable can use the same API as a class. Benchmark: - publish/batch/struct-publishable has 0 B/op and ~14M ops/s; publish/batch/struct-publishable/tenant is 24.6 B/op, which is the ToLookup/group-array cost of tenant grouping, not payload boxing. Tests: a struct payload registers metadata and publishes through the explicit tenant, tenant-derived and single-message overloads. Sa.Outbox and Sa.Outbox.PostgreSql are bumped to 0.21.0.
Set the same 0.17.0 Version in every src/*.csproj so the packages ship as one version line. Solution build is clean (0 warnings, 0 errors).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
No description provided.