Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Services/SerialNumberAllocator.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Services/SerialNumberAllocator.cs ---- using redb.Core; using SerialNumbers.Domain.Entities; namespace SerialNumbers.Core.Services; /// /// Serial numbers and the quota ledger, as plain SQL through redb.Context. Inside the request /// route's .Transacted() block it runs on the transaction's connection, so the numbers, the /// ledger row and the redb objects of the request commit or roll back together. /// /// Parameters are written $1, $2...: redb maps them to the provider's own syntax. /// /// public static class SerialNumberAllocator { /// /// The size of the block each serial number is drawn from: one chance in 10 000 to guess a /// number, as the verification service of a medicines agency expects. /// public const int BlockSize = 10_000; /// /// Quantity already allocated for the GTIN this year. The range lock (UPDLOCK, HOLDLOCK) holds /// until the transaction ends, so two requests for one product cannot both pass the quota check. /// public static async Task AllocatedThisYearAsync(IRedbService redb, string gtin, int year, CancellationToken ct) => await redb.Context.ExecuteScalarAsync( """ SELECT COALESCE(SUM(CAST(quantity AS bigint)), 0) FROM dbo.serial_allocations WITH (UPDLOCK, HOLDLOCK) WHERE gtin = $1 AND allocation_year = $2 """, [gtin, year], ct); /// /// Reserves one block per serial number, writes the ledger row and one row per serial number, /// and returns the id of the allocation. /// /// The numbers are not consecutive: the i-th number is a random value from its own block /// ((first + i) * 10000 + 1 .. (first + i + 1) * 10000), taken from /// CRYPT_GEN_RANDOM, the cryptographic generator of SQL Server. Blocks never overlap, so /// two numbers cannot collide, and the whole set is written by one statement however large it is. /// /// public static async Task AllocateAsync( IRedbService redb, SerialNumberRequest request, long requestObjectId, int year, CancellationToken ct) { var firstBlock = await redb.Context.ExecuteScalarAsync( """ IF NOT EXISTS (SELECT 1 FROM dbo.serial_blocks WITH (UPDLOCK, HOLDLOCK) WHERE gtin = $1) INSERT INTO dbo.serial_blocks (gtin, next_block) VALUES ($1, 0); UPDATE dbo.serial_blocks SET next_block = next_block + $2 OUTPUT deleted.next_block WHERE gtin = $1; """, [request.Gtin, request.Quantity], ct); var allocationId = await redb.Context.ExecuteScalarAsync( """ INSERT INTO dbo.serial_allocations (gtin, partner_code, request_id, request_object_id, first_block, quantity, allocation_year) OUTPUT inserted.id VALUES ($1, $2, $3, $4, $5, $6, $7); """, [request.Gtin, request.PartnerCode, request.RequestId, requestObjectId, firstBlock, request.Quantity, year], ct); // CRYPT_GEN_RANDOM(4) is evaluated per row; as bigint it is 0 .. 2^32 - 1, and modulo 10 000 // it is an offset inside the block. await redb.Context.ExecuteAsync( """ INSERT INTO dbo.serial_numbers (gtin, serial_value, allocation_id) SELECT $1, (CAST($3 AS bigint) + s.value) * $5 + 1 + CAST(CRYPT_GEN_RANDOM(4) AS bigint) % $5, $2 FROM GENERATE_SERIES(CAST(0 AS bigint), CAST($4 AS bigint) - 1) AS s; """, [request.Gtin, allocationId, firstBlock, request.Quantity, BlockSize], ct); return allocationId; } /// The serial numbers of an allocation, in block order. public static Task> SerialNumbersOfAsync(IRedbService redb, long allocationId, CancellationToken ct) => redb.Context.QueryScalarListAsync( "SELECT serial_value FROM dbo.serial_numbers WHERE allocation_id = $1 ORDER BY serial_value", [allocationId], ct); }