From 950f12c60bf24174e614eaf7e200d5bc40422b9d Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 09:49:47 +0600 Subject: [PATCH 01/26] build: require Runwire 4.0.1 for runtime integration QA --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index a394f6f..0fab27e 100644 --- a/composer.json +++ b/composer.json @@ -37,7 +37,7 @@ }, "require-dev": { "infocyph/phpforge": "dev-main@dev", - "infocyph/runwire": "^3.0", + "infocyph/runwire": "^4.0.1", "psr/clock": "^1.0", "psr/simple-cache": "^3.0" }, From 910563db229ba608216fde8f147f71ef8facccb3 Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 09:52:38 +0600 Subject: [PATCH 02/26] fix: resolve generator and runtime analysis contracts --- src/CUID2.php | 2 +- src/Runtime/GenerationContext.php | 4 ++-- src/Runtime/RunwireBinding.php | 2 +- src/Sequence/FilesystemSequenceProvider.php | 2 +- src/Snowflake.php | 5 ++--- src/Sonyflake.php | 5 ++--- src/Support/BaseEncoder.php | 2 +- src/TBSL.php | 2 +- src/ULID.php | 4 ++-- src/XID.php | 2 +- 10 files changed, 14 insertions(+), 16 deletions(-) diff --git a/src/CUID2.php b/src/CUID2.php index aaf450b..8e6c4e6 100644 --- a/src/CUID2.php +++ b/src/CUID2.php @@ -32,7 +32,7 @@ public static function generate(int $length = 24): string ); self::ensureProcessState(); - $time = (string) (int) floor(microtime(true) * 1000); + $time = (string) (int) floor(microtime(true) * 1000.0); $counter = (string) self::$counter; if (self::$counter === PHP_INT_MAX) { self::$counter = random_int(0, self::INITIAL_COUNTER_MAX); diff --git a/src/Runtime/GenerationContext.php b/src/Runtime/GenerationContext.php index 4b23912..16f24ff 100644 --- a/src/Runtime/GenerationContext.php +++ b/src/Runtime/GenerationContext.php @@ -31,7 +31,7 @@ public function nowMicroseconds(): int $this->assertActive(); if ($this->clock === null) { - return (int) floor(microtime(true) * 1_000_000); + return (int) floor(microtime(true) * 1_000_000.0); } $now = $this->clock->now(); @@ -40,7 +40,7 @@ public function nowMicroseconds(): int throw new InvalidArgumentException('Generation clock must fit in non-negative integer microseconds'); } - return ($seconds * 1_000_000) + (int) $now->format('u'); + return ($seconds * 1_000_000.0) + (int) $now->format('u'); } public function nowMilliseconds(): int diff --git a/src/Runtime/RunwireBinding.php b/src/Runtime/RunwireBinding.php index 810eb9d..99fc396 100644 --- a/src/Runtime/RunwireBinding.php +++ b/src/Runtime/RunwireBinding.php @@ -75,7 +75,7 @@ public function sleep(float $seconds): void if ($this->scope !== null) { $this->scope->sleep($seconds); } else { - usleep((int) ceil($seconds * 1_000_000)); + usleep((int) ceil($seconds * 1_000_000.0)); } $this->assertActive(); diff --git a/src/Sequence/FilesystemSequenceProvider.php b/src/Sequence/FilesystemSequenceProvider.php index 741c711..af605c2 100644 --- a/src/Sequence/FilesystemSequenceProvider.php +++ b/src/Sequence/FilesystemSequenceProvider.php @@ -35,7 +35,7 @@ public function __construct( private readonly int $reservationSize = 1, private readonly ?GenerationContext $runtime = null, ) { - $this->baseDirectory = $baseDirectory ?: sys_get_temp_dir(); + $this->baseDirectory = $baseDirectory === null || $baseDirectory === '' || $baseDirectory === '0' ? sys_get_temp_dir() : $baseDirectory; if ($namespace !== '' && preg_match('/^[A-Za-z0-9_-]+$/D', $namespace) !== 1) { throw new InvalidArgumentException('Sequence namespace may contain only letters, numbers, underscores, and hyphens'); diff --git a/src/Snowflake.php b/src/Snowflake.php index b9c8005..ba71d6d 100644 --- a/src/Snowflake.php +++ b/src/Snowflake.php @@ -374,7 +374,7 @@ private static function nextSequenceAtValidTimestamp( private static function nowMilliseconds(?GenerationContext $runtime): int { - return $runtime?->nowMilliseconds() ?? (int) floor(microtime(true) * 1000); + return $runtime?->nowMilliseconds() ?? (int) floor(microtime(true) * 1000.0); } /** @@ -386,8 +386,7 @@ private static function providerState( ): \ArrayObject { self::$lastStateByProvider ??= new \WeakMap(); - /** @var \ArrayObject|null $state */ - $state = self::$lastStateByProvider[$provider] ?? null; + $state = self::$lastStateByProvider[$provider] ?? null; if ($state === null) { /** @var \ArrayObject $state */ $state = new \ArrayObject(); diff --git a/src/Sonyflake.php b/src/Sonyflake.php index e4f5f2a..9845843 100644 --- a/src/Sonyflake.php +++ b/src/Sonyflake.php @@ -369,7 +369,7 @@ private static function getStartTimeStamp(SonyflakeFormat $format): int private static function nowMilliseconds(?GenerationContext $runtime): int { - return $runtime?->nowMilliseconds() ?? (int) floor(microtime(true) * 1000); + return $runtime?->nowMilliseconds() ?? (int) floor(microtime(true) * 1000.0); } private static function packId( @@ -402,8 +402,7 @@ private static function providerState( ): \ArrayObject { self::$lastWallTimeByProvider ??= new \WeakMap(); - /** @var \ArrayObject|null $state */ - $state = self::$lastWallTimeByProvider[$provider] ?? null; + $state = self::$lastWallTimeByProvider[$provider] ?? null; if ($state === null) { /** @var \ArrayObject $state */ $state = new \ArrayObject(); diff --git a/src/Support/BaseEncoder.php b/src/Support/BaseEncoder.php index 384839b..1a5017f 100644 --- a/src/Support/BaseEncoder.php +++ b/src/Support/BaseEncoder.php @@ -102,7 +102,7 @@ private static function assertByteLength(int $byteLength): void private static function decodeRadix(string $encoded, int $base, int $bytesLength): string { $alphabet = self::alphabet($base); - $maximumLength = (int) ceil(($bytesLength * 8) / log($base, 2)); + $maximumLength = (int) ceil((float) ($bytesLength * 8) / log($base, 2)); if (strlen($encoded) > $maximumLength) { throw new InvalidArgumentException('Encoded value exceeds target byte length'); } diff --git a/src/TBSL.php b/src/TBSL.php index 45ecde4..de604e4 100644 --- a/src/TBSL.php +++ b/src/TBSL.php @@ -218,7 +218,7 @@ private static function generateInternal( private static function nowMicroseconds(?GenerationContext $runtime): int { - return $runtime?->nowMicroseconds() ?? (int) floor(microtime(true) * 1_000_000); + return $runtime?->nowMicroseconds() ?? (int) floor(microtime(true) * 1_000_000.0); } /** diff --git a/src/ULID.php b/src/ULID.php index a5f027a..c04d03a 100644 --- a/src/ULID.php +++ b/src/ULID.php @@ -82,7 +82,7 @@ public static function generate( ): string { self::resetAfterFork(); $time = $dateTime === null - ? (int) floor(microtime(true) * 1000) + ? (int) floor(microtime(true) * 1000.0) : (int) $dateTime->format('Uv'); self::assertTimestamp($time); @@ -329,7 +329,7 @@ private static function waitForNextMillisecond(int $lastTimestamp): int throw new ULIDException('Timed out waiting for the next ULID timestamp'); } usleep(1000); - $next = (int) floor(microtime(true) * 1000); + $next = (int) floor(microtime(true) * 1000.0); } while ($next <= $lastTimestamp); return $next; diff --git a/src/XID.php b/src/XID.php index f57d313..0b6d879 100644 --- a/src/XID.php +++ b/src/XID.php @@ -157,7 +157,7 @@ private static function ensureProcessState(): void private static function machine(): string { - return self::$machine ??= substr(hash('sha256', gethostname() ?: 'localhost', true), 0, 3); + return self::$machine ??= substr(hash('sha256', (($host = gethostname()) === false || $host === '' || $host === '0' ? 'localhost' : $host), true), 0, 3); } private static function pidBytes(): string From 95a41236536d8dd89dafc9e8f03715dc94e0290f Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 09:52:57 +0600 Subject: [PATCH 03/26] fix: document ID factory and configuration failure contracts --- src/NanoID.php | 3 --- src/Randflake.php | 3 +-- src/Runtime/GenerationContext.php | 2 +- 3 files changed, 2 insertions(+), 6 deletions(-) diff --git a/src/NanoID.php b/src/NanoID.php index 82be887..382a229 100644 --- a/src/NanoID.php +++ b/src/NanoID.php @@ -23,9 +23,6 @@ public static function generate(int $length = 21): string } $byteLength = intdiv(($length * 3) + 3, 4); - if ($byteLength < 1) { - throw new \LogicException('Unable to calculate NanoID entropy length'); - } return substr( rtrim(strtr(base64_encode(random_bytes($byteLength)), '+/', '-_'), '='), diff --git a/src/Randflake.php b/src/Randflake.php index c3587bf..a74f7cf 100644 --- a/src/Randflake.php +++ b/src/Randflake.php @@ -591,8 +591,7 @@ private static function providerState( ): \ArrayObject { self::$lastTimestampByProvider ??= new \WeakMap(); - /** @var \ArrayObject|null $state */ - $state = self::$lastTimestampByProvider[$provider] ?? null; + $state = self::$lastTimestampByProvider[$provider] ?? null; if ($state === null) { /** @var \ArrayObject $state */ $state = new \ArrayObject(); diff --git a/src/Runtime/GenerationContext.php b/src/Runtime/GenerationContext.php index 16f24ff..c6a6cdf 100644 --- a/src/Runtime/GenerationContext.php +++ b/src/Runtime/GenerationContext.php @@ -40,7 +40,7 @@ public function nowMicroseconds(): int throw new InvalidArgumentException('Generation clock must fit in non-negative integer microseconds'); } - return ($seconds * 1_000_000.0) + (int) $now->format('u'); + return ($seconds * 1_000_000) + (int) $now->format('u'); } public function nowMilliseconds(): int From 05ede265d76430ce8baa2f242f167e366b6b769c Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 09:53:13 +0600 Subject: [PATCH 04/26] fix: resolve sequence and binary codec analyzer contracts --- src/Support/TypeIdCodec.php | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/Support/TypeIdCodec.php b/src/Support/TypeIdCodec.php index 9c6e943..5786165 100644 --- a/src/Support/TypeIdCodec.php +++ b/src/Support/TypeIdCodec.php @@ -34,10 +34,6 @@ public static function decode(string $suffix): string } } - if (count($bytes) > 16) { - throw new InvalidArgumentException('TypeID suffix exceeds 128 bits'); - } - $decoded = ''; foreach ($bytes as $byte) { $decoded .= chr($byte); From acc1415464c247a1eb0a4b4b35130beaa33a4849 Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 09:53:33 +0600 Subject: [PATCH 05/26] fix: complete UUID, TypeID and value-object contracts --- src/UUID.php | 19 +++++-------------- src/Value/UlidValue.php | 1 + 2 files changed, 6 insertions(+), 14 deletions(-) diff --git a/src/UUID.php b/src/UUID.php index 0af8702..569d219 100644 --- a/src/UUID.php +++ b/src/UUID.php @@ -129,15 +129,6 @@ public static function getNode(): string */ public static function guid(bool $trim = true): string { - if (function_exists('com_create_guid')) { - $data = com_create_guid(); - if (!is_string($data)) { - throw new UUIDException('Failed to generate GUID'); - } - - return $trim ? trim($data, '{}') : $data; - } - $data = random_bytes(16); $data[6] = chr(ord($data[6]) & 0x0f | 0x40); $data[8] = chr(ord($data[8]) & 0x3f | 0x80); @@ -445,7 +436,7 @@ public static function v6(?string $node = null): string public static function v7(?DateTimeInterface $dateTime = null): string { $unixTsMs = $dateTime === null - ? (int) floor(microtime(true) * 1000) + ? (int) floor(microtime(true) * 1000.0) : (int) $dateTime->format('Uv'); if ($unixTsMs < 0 || $unixTsMs > self::MAX_V7_TIMESTAMP) { throw new UUIDException('UUID v7 timestamp must fit in an unsigned 48-bit integer'); @@ -509,9 +500,9 @@ private static function canonicalFromHex(string $hex): string private static function getTime(array $uuid, int $version): DateTimeInterface { $timestamp = match ($version) { - 1 => substr((string) $uuid[2], -3) . $uuid[1] . $uuid[0], - 2 => substr((string) $uuid[2], -3) . $uuid[1] . '00000000', - 6 => $uuid[0] . $uuid[1] . substr((string) $uuid[2], -3), + 1 => substr($uuid[2], -3) . $uuid[1] . $uuid[0], + 2 => substr($uuid[2], -3) . $uuid[1] . '00000000', + 6 => $uuid[0] . $uuid[1] . substr($uuid[2], -3), 7 => $uuid[0] . $uuid[1], default => throw new UUIDException('Invalid version (applicable: 1, 2, 6, 7)'), }; @@ -705,7 +696,7 @@ private static function nextV7Timestamp(int $lastTimestamp): int throw new UUIDException('Timed out waiting for the next UUID v7 timestamp'); } usleep(1000); - $next = (int) floor(microtime(true) * 1000); + $next = (int) floor(microtime(true) * 1000.0); } while ($next <= $lastTimestamp); if ($next > self::MAX_V7_TIMESTAMP) { diff --git a/src/Value/UlidValue.php b/src/Value/UlidValue.php index eec3257..5725f10 100644 --- a/src/Value/UlidValue.php +++ b/src/Value/UlidValue.php @@ -7,6 +7,7 @@ use Infocyph\UID\Contracts\IdValueInterface; use Infocyph\UID\ULID; +/** @api */ final readonly class UlidValue implements IdValueInterface { private string $value; From d8ff6c1a46143eb864cc28b2c43dd1764e7cfb30 Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 09:54:00 +0600 Subject: [PATCH 06/26] fix: preserve exception API, repair benchmark contracts and expand acceptance matrix --- .github/workflows/release-acceptance.yml | 2 +- benchmarks/BaseCodecBench.php | 13 +++++++++++ benchmarks/HotspotBench.php | 29 +++++++++--------------- benchmarks/SequenceProviderBench.php | 4 ++++ composer.json | 1 + src/Exceptions/RandflakeException.php | 1 + src/Exceptions/SnowflakeException.php | 1 + src/Exceptions/SonyflakeException.php | 1 + src/Exceptions/ULIDException.php | 1 + src/Exceptions/UUIDException.php | 1 + 10 files changed, 35 insertions(+), 19 deletions(-) diff --git a/.github/workflows/release-acceptance.yml b/.github/workflows/release-acceptance.yml index f4f1239..e4a2ea7 100644 --- a/.github/workflows/release-acceptance.yml +++ b/.github/workflows/release-acceptance.yml @@ -28,7 +28,7 @@ jobs: strategy: fail-fast: false matrix: - php: ["8.4", "8.5"] + php: ["8.4", "8.5", "8.6"] steps: - name: Checkout exact candidate uses: actions/checkout@v7 diff --git a/benchmarks/BaseCodecBench.php b/benchmarks/BaseCodecBench.php index f424983..9f3a925 100644 --- a/benchmarks/BaseCodecBench.php +++ b/benchmarks/BaseCodecBench.php @@ -10,6 +10,10 @@ use Infocyph\UID\Support\TypeIdCodec; use PhpBench\Attributes as Bench; +/** + * PHPBench discovers this entry point by reflection. + * @api + */ final class BaseCodecBench { /** @var array */ @@ -41,42 +45,49 @@ public function __construct() $this->typeIdEncoded = TypeIdCodec::encode($this->samples[16]); } + /** @param array{length:int} $params */ #[Bench\Revs(1000), Bench\Iterations(5), Bench\ParamProviders('provideLengths')] public function benchBase16(array $params): void { BaseEncoder::encodeBytes($this->sample($params), 16); } + /** @param array{length:int} $params */ #[Bench\Revs(1000), Bench\Iterations(5), Bench\ParamProviders('provideLengths')] public function benchBase32(array $params): void { BaseEncoder::encodeBytes($this->sample($params), 32); } + /** @param array{length:int} $params */ #[Bench\Revs(1000), Bench\Iterations(5), Bench\ParamProviders('provideLengths')] public function benchBase36(array $params): void { BaseEncoder::encodeBytes($this->sample($params), 36); } + /** @param array{length:int} $params */ #[Bench\Revs(1000), Bench\Iterations(5), Bench\ParamProviders('provideLengths')] public function benchBase58(array $params): void { BaseEncoder::encodeBytes($this->sample($params), 58); } + /** @param array{length:int} $params */ #[Bench\Revs(1000), Bench\Iterations(5), Bench\ParamProviders('provideLengths')] public function benchBase62(array $params): void { BaseEncoder::encodeBytes($this->sample($params), 62); } + /** @param array{length:int} $params */ #[Bench\Revs(1000), Bench\Iterations(5), Bench\ParamProviders('provideLengths')] public function benchDecimal(array $params): void { BaseEncoder::encodeBytes($this->sample($params), 10); } + /** @param array{base:int,length:int} $params */ #[Bench\Revs(250), Bench\Iterations(5), Bench\ParamProviders('provideBaseLengthPairs')] public function benchDecode(array $params): void { @@ -87,12 +98,14 @@ public function benchDecode(array $params): void ); } + /** @param array{length:int} $params */ #[Bench\Revs(500), Bench\Iterations(5), Bench\ParamProviders('provideLengths')] public function benchNumericFromBytes(array $params): void { NumericIdCodec::decimalFromBytes($this->sample($params), $params['length']); } + /** @param array{length:int} $params */ #[Bench\Revs(500), Bench\Iterations(5), Bench\ParamProviders('provideLengths')] public function benchNumericToBytes(array $params): void { diff --git a/benchmarks/HotspotBench.php b/benchmarks/HotspotBench.php index a5a601d..b75488f 100644 --- a/benchmarks/HotspotBench.php +++ b/benchmarks/HotspotBench.php @@ -5,6 +5,8 @@ namespace Infocyph\UID\Benchmarks; use Closure; +use ReflectionMethod; +use ReflectionProperty; use Infocyph\UID\Configuration\RandflakeConfig; use Infocyph\UID\Configuration\SnowflakeConfig; use Infocyph\UID\Configuration\SonyflakeConfig; @@ -27,6 +29,10 @@ use Infocyph\UID\XID; use PhpBench\Attributes as Bench; +/** + * PHPBench discovers this entry point by reflection. + * @api + */ final class HotspotBench { private Closure $cuidFingerprint; @@ -48,24 +54,11 @@ public function __construct() require_once __DIR__ . '/BenchBootstrap.php'; BenchBootstrap::load(); - $fingerprint = Closure::bind( - static fn(): string => CUID2::fingerprint(), - null, - CUID2::class, - ); - $resetFingerprint = Closure::bind( - static function (): void { - CUID2::$fingerprint = null; - }, - null, - CUID2::class, - ); - if (!$fingerprint instanceof Closure || !$resetFingerprint instanceof Closure) { - throw new \LogicException('Unable to bind CUID2 benchmark helpers'); - } - - $this->cuidFingerprint = $fingerprint; - $this->resetCuidFingerprint = $resetFingerprint; + $this->cuidFingerprint = (new ReflectionMethod(CUID2::class, 'fingerprint'))->getClosure(); + $property = new ReflectionProperty(CUID2::class, 'fingerprint'); + $this->resetCuidFingerprint = static function () use ($property): void { + $property->setValue(null, null); + }; ($this->cuidFingerprint)(); $provider = new FilesystemSequenceProvider(namespace: 'phpbench'); diff --git a/benchmarks/SequenceProviderBench.php b/benchmarks/SequenceProviderBench.php index 3aabcb7..d57bb48 100644 --- a/benchmarks/SequenceProviderBench.php +++ b/benchmarks/SequenceProviderBench.php @@ -12,6 +12,10 @@ use Infocyph\UID\Snowflake; use PhpBench\Attributes as Bench; +/** + * PHPBench discovers this entry point by reflection. + * @api + */ final class SequenceProviderBench { private RandflakeConfig $randflakeFilesystem; diff --git a/composer.json b/composer.json index 0fab27e..7aefbf1 100644 --- a/composer.json +++ b/composer.json @@ -45,6 +45,7 @@ "abmmhasan/uuid": "self.version" }, "suggest": { + "ext-pcntl": "Required for the development fork and concurrent sequence tests.", "infocyph/runwire": "Enables request-aware cooperative waits for coordinated generators.", "psr/clock": "Enables injectable wall-clock sampling for coordinated generators.", "psr/simple-cache": "Required for the optional PSR-16 sequence provider." diff --git a/src/Exceptions/RandflakeException.php b/src/Exceptions/RandflakeException.php index 0937601..a04aaf4 100644 --- a/src/Exceptions/RandflakeException.php +++ b/src/Exceptions/RandflakeException.php @@ -4,4 +4,5 @@ namespace Infocyph\UID\Exceptions; +/** @api */ class RandflakeException extends UIDException {} diff --git a/src/Exceptions/SnowflakeException.php b/src/Exceptions/SnowflakeException.php index 8e0d8f9..d710158 100644 --- a/src/Exceptions/SnowflakeException.php +++ b/src/Exceptions/SnowflakeException.php @@ -4,4 +4,5 @@ namespace Infocyph\UID\Exceptions; +/** @api */ class SnowflakeException extends UIDException {} diff --git a/src/Exceptions/SonyflakeException.php b/src/Exceptions/SonyflakeException.php index 262421f..c02cba2 100644 --- a/src/Exceptions/SonyflakeException.php +++ b/src/Exceptions/SonyflakeException.php @@ -4,4 +4,5 @@ namespace Infocyph\UID\Exceptions; +/** @api */ class SonyflakeException extends UIDException {} diff --git a/src/Exceptions/ULIDException.php b/src/Exceptions/ULIDException.php index 91cc59d..5707726 100644 --- a/src/Exceptions/ULIDException.php +++ b/src/Exceptions/ULIDException.php @@ -4,4 +4,5 @@ namespace Infocyph\UID\Exceptions; +/** @api */ class ULIDException extends UIDException {} diff --git a/src/Exceptions/UUIDException.php b/src/Exceptions/UUIDException.php index 27b3239..9989fb1 100644 --- a/src/Exceptions/UUIDException.php +++ b/src/Exceptions/UUIDException.php @@ -4,4 +4,5 @@ namespace Infocyph\UID\Exceptions; +/** @api */ class UUIDException extends UIDException {} From d527f11007d49917fe1ecdb07e9a98e912b85f20 Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 09:54:30 +0600 Subject: [PATCH 07/26] test: validate fixture boundaries and remove dynamic smoke include --- tests/AdditionalIdsTest.php | 12 +++---- tests/BaseEncoderTest.php | 9 ++++- tests/FilesystemSequenceV5Test.php | 28 +++++++++++---- tests/IdFactoryTest.php | 44 +++++++++++++----------- tests/RandflakeTest.php | 2 +- tests/RandflakeUpstreamPrimitiveTest.php | 6 +++- tests/RuntimeIntegrationTest.php | 10 +++++- tests/SequenceSafetyTest.php | 19 ++++------ tests/V5CompatibilityTest.php | 6 ++-- tests/smoke.php | 10 ++++-- 10 files changed, 91 insertions(+), 55 deletions(-) diff --git a/tests/AdditionalIdsTest.php b/tests/AdditionalIdsTest.php index 2ca4680..4702a98 100644 --- a/tests/AdditionalIdsTest.php +++ b/tests/AdditionalIdsTest.php @@ -15,13 +15,13 @@ expect(KSUID::isValid($id))->toBeTrue() ->and($id)->toHaveLength(27) - ->and($parsed['time'])->not()->toBeNull(); + ->and($parsed['time']->getTimestamp())->toBeGreaterThan(0); }); test('KSUID matches the reference text and binary vector', function () { $bytes = hex2bin('0669f7efb5a1cd34b5f99d1154fb6853345c9735'); - expect($bytes)->toBeString() - ->and(KSUID::fromBytes($bytes))->toBe('0ujtsYcgvSTl8PAuAdqWYSMnLOv') + $bytes !== false || throw new RuntimeException('Invalid reference vector'); + expect(KSUID::fromBytes($bytes))->toBe('0ujtsYcgvSTl8PAuAdqWYSMnLOv') ->and(KSUID::toBytes('0ujtsYcgvSTl8PAuAdqWYSMnLOv'))->toBe($bytes); }); @@ -31,13 +31,13 @@ expect(XID::isValid($id))->toBeTrue() ->and($id)->toHaveLength(20) - ->and($parsed['time'])->not()->toBeNull(); + ->and($parsed['time']->getTimestamp())->toBeGreaterThan(0); }); test('XID matches the upstream text and binary vector', function () { $bytes = hex2bin('4d88e15b60f486e428412dc9'); - expect($bytes)->toBeString() - ->and(XID::fromBytes($bytes))->toBe('9m4e2mr0ui3e8a215n4g') + $bytes !== false || throw new RuntimeException('Invalid reference vector'); + expect(XID::fromBytes($bytes))->toBe('9m4e2mr0ui3e8a215n4g') ->and(XID::toBytes('9m4e2mr0ui3e8a215n4g'))->toBe($bytes); }); diff --git a/tests/BaseEncoderTest.php b/tests/BaseEncoderTest.php index 8104c67..2b08447 100644 --- a/tests/BaseEncoderTest.php +++ b/tests/BaseEncoderTest.php @@ -6,10 +6,17 @@ test('radix encoding matches independent integer vectors across word and carry boundaries', function (): void { // Generated with Python int.from_bytes/divmod, independently of the PHP codec. - $vectors = json_decode(file_get_contents(__DIR__ . '/Fixtures/radix-vectors.json'), true, 512, JSON_THROW_ON_ERROR); + $json = file_get_contents(__DIR__ . '/Fixtures/radix-vectors.json'); + $json !== false || throw new RuntimeException('Unable to read radix vectors'); + $vectors = json_decode($json, true, 512, JSON_THROW_ON_ERROR); + is_array($vectors) || throw new RuntimeException('Invalid radix vectors'); foreach ($vectors as $vector) { + if (!is_array($vector) || !is_string($vector['hex'] ?? null) || !is_int($vector['base'] ?? null) || !is_string($vector['sha256'] ?? null)) { + throw new RuntimeException('Invalid radix vector'); + } $bytes = hex2bin($vector['hex']); + $bytes !== false || throw new RuntimeException('Invalid radix vector bytes'); $encoded = BaseEncoder::encodeBytes($bytes, $vector['base']); expect(hash('sha256', $encoded))->toBe($vector['sha256']) diff --git a/tests/FilesystemSequenceV5Test.php b/tests/FilesystemSequenceV5Test.php index e8dc94d..a7cb95c 100644 --- a/tests/FilesystemSequenceV5Test.php +++ b/tests/FilesystemSequenceV5Test.php @@ -35,7 +35,8 @@ ->and((new FilesystemSequenceProvider($directory, 'billing', reservationSize: 4)) ->next('snowflake', 7, 100))->toBe(5); } finally { - foreach (glob($directory . DIRECTORY_SEPARATOR . '*') ?: [] as $file) { + $files = glob($directory . DIRECTORY_SEPARATOR . '*'); + foreach ($files === false ? [] : $files as $file) { unlink($file); } rmdir($directory); @@ -96,14 +97,20 @@ foreach ($children as $pid => $output) { pcntl_waitpid($pid, $status); $json = file_get_contents($output); - expect($json)->toBeString(); - $allocations = [...$allocations, ...json_decode($json, true, 512, JSON_THROW_ON_ERROR)]; + $json !== false || throw new RuntimeException('Unable to read child output'); + $values = json_decode($json, true, 512, JSON_THROW_ON_ERROR); + is_array($values) || throw new RuntimeException('Invalid child output'); + foreach ($values as $value) { + is_int($value) || throw new RuntimeException('Invalid child value'); + $allocations[] = $value; + } } expect($allocations)->toHaveCount(400) ->and(array_unique($allocations))->toHaveCount(400); } finally { - foreach (glob($directory . DIRECTORY_SEPARATOR . '*') ?: [] as $file) { + $files = glob($directory . DIRECTORY_SEPARATOR . '*'); + foreach ($files === false ? [] : $files as $file) { unlink($file); } rmdir($directory); @@ -138,6 +145,7 @@ sequenceProvider: $provider, )), 'tbsl' => TBSL::generateWithConfig(new TBSLConfig(sequenceProvider: $provider)), + default => throw new InvalidArgumentException('Unknown coordinated generator'), }; } @@ -153,14 +161,20 @@ foreach ($children as $pid => $output) { pcntl_waitpid($pid, $status); $json = file_get_contents($output); - expect($json)->toBeString(); - $ids = [...$ids, ...json_decode($json, true, 512, JSON_THROW_ON_ERROR)]; + $json !== false || throw new RuntimeException('Unable to read child output'); + $values = json_decode($json, true, 512, JSON_THROW_ON_ERROR); + is_array($values) || throw new RuntimeException('Invalid child output'); + foreach ($values as $value) { + is_string($value) || throw new RuntimeException('Invalid child value'); + $ids[] = $value; + } } expect($ids)->toHaveCount(400) ->and(array_unique($ids))->toHaveCount(400); } finally { - foreach (glob($directory . DIRECTORY_SEPARATOR . '*') ?: [] as $file) { + $files = glob($directory . DIRECTORY_SEPARATOR . '*'); + foreach ($files === false ? [] : $files as $file) { unlink($file); } rmdir($directory); diff --git a/tests/IdFactoryTest.php b/tests/IdFactoryTest.php index 8f10924..efbb014 100644 --- a/tests/IdFactoryTest.php +++ b/tests/IdFactoryTest.php @@ -11,6 +11,7 @@ use Infocyph\UID\Id; use Infocyph\UID\RandomId; use Infocyph\UID\Value\UuidValue; +use Infocyph\UID\Value\UlidValue; test('Id factory basic methods', function () { $ksuid = Id::ksuid(); @@ -38,30 +39,33 @@ secret: 'super-secret-key', )); - expect($ksuid)->toBeString()->toHaveLength(27) - ->and($xid)->toBeString()->toHaveLength(20) + expect($ksuid)->toHaveLength(27) + ->and($xid)->toHaveLength(20) ->and($typeId)->toStartWith('user_')->toHaveLength(31) ->and($objectId)->toHaveLength(24) - ->and($uuid1)->toBeString()->toHaveLength(36) - ->and($uuid2)->toBeString()->toHaveLength(36) - ->and($uuid3)->toBeString()->toHaveLength(36) - ->and($uuid4)->toBeString()->toHaveLength(36) - ->and($uuid5)->toBeString()->toHaveLength(36) - ->and($uuid6)->toBeString()->toHaveLength(36) - ->and($uuid)->toBeString()->toHaveLength(36) - ->and($uuid8)->toBeString()->toHaveLength(36) - ->and($ulid)->toBeString()->toHaveLength(26) - ->and((string)$snowflake)->toBeString()->not()->toBeEmpty() - ->and((string)$sonyflake)->toBeString()->not()->toBeEmpty() - ->and((string)$tbsl)->toBeString()->toHaveLength(20) - ->and((string)$randflake)->toBeString()->not()->toBeEmpty(); + ->and($uuid1)->toHaveLength(36) + ->and($uuid2)->toHaveLength(36) + ->and($uuid3)->toHaveLength(36) + ->and($uuid4)->toHaveLength(36) + ->and($uuid5)->toHaveLength(36) + ->and($uuid6)->toHaveLength(36) + ->and($uuid)->toHaveLength(36) + ->and($uuid8)->toHaveLength(36) + ->and($ulid)->toHaveLength(26) + ->and($snowflake)->not()->toBeEmpty() + ->and($sonyflake)->not()->toBeEmpty() + ->and($tbsl)->toHaveLength(20) + ->and($randflake)->not()->toBeEmpty(); }); test('value objects remain available from their owning type', function () { $uuidValue = new UuidValue(Id::uuid7()); - expect($uuidValue)->toBeInstanceOf(UuidValue::class) - ->and($uuidValue->toString())->toHaveLength(36) + expect($uuidValue->toString())->toHaveLength(36) ->and($uuidValue->getVersion())->toBe(7); + $ulid = Id::ulid(); + $ulidValue = new UlidValue($ulid); + expect($ulidValue->toString())->toBe($ulid) + ->and($ulidValue->isSortable())->toBeTrue(); }); test('Id factory random strategy', function () { @@ -88,10 +92,10 @@ secret: 'super-secret-key', )); - expect($snowflake)->toBeString() - ->and($sonyflake)->toBeString() + expect($snowflake)->not()->toBeEmpty() + ->and($sonyflake)->not()->toBeEmpty() ->and($tbsl)->toHaveLength(20) - ->and($randflake)->toBeString(); + ->and($randflake)->not()->toBeEmpty(); }); diff --git a/tests/RandflakeTest.php b/tests/RandflakeTest.php index b6e781f..74e3bd8 100644 --- a/tests/RandflakeTest.php +++ b/tests/RandflakeTest.php @@ -97,7 +97,7 @@ ), ); - expect($stringId)->toBeString()->toMatch('/^\d+$/'); + expect($stringId)->toMatch('/^\d+$/'); }); test('Randflake namespaced helper delegates to the generator', function () { diff --git a/tests/RandflakeUpstreamPrimitiveTest.php b/tests/RandflakeUpstreamPrimitiveTest.php index 15bfeb0..bb554c1 100644 --- a/tests/RandflakeUpstreamPrimitiveTest.php +++ b/tests/RandflakeUpstreamPrimitiveTest.php @@ -19,8 +19,12 @@ }); test('SPARX64 encryption round trips fixed blocks', function (): void { - $cipher = new Sparx64(hex2bin('000102030405060708090a0b0c0d0e0f')); + $key = hex2bin('000102030405060708090a0b0c0d0e0f'); $plain = hex2bin('0011223344556677'); + if ($key === false || $plain === false) { + throw new RuntimeException('Invalid SPARX64 vector'); + } + $cipher = new Sparx64($key); $encrypted = $cipher->encrypt($plain); expect($encrypted)->not()->toBe($plain) diff --git a/tests/RuntimeIntegrationTest.php b/tests/RuntimeIntegrationTest.php index 7cb92e4..33e53af 100644 --- a/tests/RuntimeIntegrationTest.php +++ b/tests/RuntimeIntegrationTest.php @@ -23,6 +23,7 @@ { public function __construct(private DateTimeImmutable $time) {} + #[\Override] public function now(): DateTimeImmutable { return $this->time; @@ -31,6 +32,7 @@ public function now(): DateTimeImmutable final class OverflowUidSequenceProvider implements SequenceProviderInterface { + #[\Override] public function next(string $type, int $machineId, int $timestamp): int { unset($type, $machineId, $timestamp); @@ -152,6 +154,10 @@ static function (string $type, int $machineId, int $timestamp) use (&$allocation }); +/** + * @throws \Infocyph\UID\Exceptions\SnowflakeException + * @throws \Infocyph\UID\Exceptions\FileLockException + */ function forwardUidSnowflake(SnowflakeConfig $config): string { return Snowflake::generateWithConfig($config); @@ -166,7 +172,7 @@ function forwardUidSnowflake(SnowflakeConfig $config): string runtime: new GenerationContext(runwire: $binding), ); - expect(forwardUidSnowflake($config))->toBeString() + expect(Snowflake::isValid(forwardUidSnowflake($config)))->toBeTrue() ->and($config->runtime?->runwire)->toBe($binding) ->and($binding->runtime)->toBe($host) ->and($binding->request)->toBe($request); @@ -201,6 +207,7 @@ function (CoroutineScope $scope) use (&$capturedScope): void { $path = $directory . '/uid-snowflake-0.seq'; file_put_contents($path, '1700000000000,7'); $held = fopen($path, 'r+b'); + $held !== false || throw new RuntimeException('Unable to open lock fixture'); expect(flock($held, LOCK_EX))->toBeTrue(); $host = RuntimeContext::fromCapabilities(new RuntimeCapabilities( driver: RuntimeDriver::NATIVE, @@ -259,6 +266,7 @@ function (CoroutineScope $scope) use (&$capturedScope): void { $path = $directory . '/uid-test-1.seq'; file_put_contents($path, '100,1'); $held = fopen($path, 'r+b'); + $held !== false || throw new RuntimeException('Unable to open lock fixture'); expect(flock($held, LOCK_EX))->toBeTrue(); $host = RuntimeContext::fromCapabilities(new RuntimeCapabilities( driver: RuntimeDriver::NATIVE, diff --git a/tests/SequenceSafetyTest.php b/tests/SequenceSafetyTest.php index 9d09376..d4d5a66 100644 --- a/tests/SequenceSafetyTest.php +++ b/tests/SequenceSafetyTest.php @@ -15,17 +15,11 @@ file_put_contents($path, '100,1'); file_put_contents($target, 'unchanged'); $handle = fopen($path, 'r+b'); - $before = null; - $verify = Closure::bind( - static function () use ($path, $handle, &$before) { - return FileLock::verifyHandle($path, $handle, $before, 'replaced lock', function_exists('posix_geteuid') ? posix_geteuid() : null); - }, - null, - FileLock::class, - ); - expect($verify)->toBeInstanceOf(Closure::class); + $handle !== false || throw new RuntimeException('Unable to open lock fixture'); + $verify = new ReflectionMethod(FileLock::class, 'verifyHandle'); // Prime PHP's path cache after loading the verifier and assertion machinery. $before = lstat($path); + $before !== false || throw new RuntimeException('Unable to stat lock fixture'); $pid = pcntl_fork(); if ($pid < 0) { throw new RuntimeException('Unable to fork pathname replacement fixture'); @@ -40,7 +34,7 @@ static function () use ($path, $handle, &$before) { try { $failure = null; try { - $verify(); + $verify->invoke(null, $path, $handle, $before, 'replaced lock', function_exists('posix_geteuid') ? posix_geteuid() : null); } catch (Throwable $exception) { $failure = $exception; } @@ -59,8 +53,6 @@ static function () use ($path, $handle, &$before) { test('filesystem sequence rejects symlink state without touching its target', function (): void { if (PHP_OS_FAMILY === 'Windows') { - expect(true)->toBeTrue(); - return; } @@ -103,7 +95,8 @@ static function () use ($path, $handle, &$before) { symlink($directory . '/first', $alias); $provider = new FilesystemSequenceProvider($alias); expect(realpath($path))->toBe($first); - lstat($path); + $metadata = lstat($path); + $metadata !== false || throw new RuntimeException('Unable to stat parent fixture'); $pid = pcntl_fork(); if ($pid < 0) { diff --git a/tests/V5CompatibilityTest.php b/tests/V5CompatibilityTest.php index 80c354c..dbb6c90 100644 --- a/tests/V5CompatibilityTest.php +++ b/tests/V5CompatibilityTest.php @@ -62,7 +62,9 @@ }); test('ObjectID matches unsigned timestamp boundary vectors', function (string $hex, string $expected) { - $id = ObjectID::fromBytes(hex2bin($hex . str_repeat('00', 8)) ?: ''); + $bytes = hex2bin($hex . str_repeat('00', 8)); + $bytes !== false || throw new RuntimeException('Invalid ObjectID fixture'); + $id = ObjectID::fromBytes($bytes); expect(ObjectID::parse($id)['time']->format('Y-m-d H:i:s'))->toBe($expected) ->and(ObjectID::toBytes($id))->toBe(hex2bin($hex . str_repeat('00', 8))); @@ -218,7 +220,7 @@ $names = array_map( static fn(ReflectionParameter $parameter): string => $parameter->getName(), - $constructor?->getParameters() ?? [], + $constructor->getParameters(), ); expect(array_slice($names, 0, count($expectedPrefix)))->toBe($expectedPrefix); } diff --git a/tests/smoke.php b/tests/smoke.php index cad384e..970bb45 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -26,9 +26,12 @@ use Infocyph\UID\UUID; use Infocyph\UID\XID; -require ($argv[1] ?? dirname(__DIR__)) . '/vendor/autoload.php'; +require dirname(__DIR__) . '/vendor/autoload.php'; -/** @param array> $seen */ +/** + * @param array> $seen + * @throws RuntimeException + */ function uidSmokeId(string $algorithm, string $id, bool $valid, array &$seen): void { if (!$valid || isset($seen[$algorithm][$id])) { @@ -134,7 +137,8 @@ function uidSmokeId(string $algorithm, string $id, bool $valid, array &$seen): v } printf("Passed %d generator variants in one 100-cycle smoke pass.\n", count($seen)); } finally { - foreach (glob($directory . '/*') ?: [] as $path) { + $paths = glob($directory . '/*'); + foreach ($paths === false ? [] : $paths as $path) { unlink($path); } rmdir($directory); From e69e78097a2dd999fba8ae0c8a21ba2e574872e6 Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 09:55:01 +0600 Subject: [PATCH 08/26] test: complete typed UUID, ULID and coordinated sequence fixtures --- tests/PersistentDomainLimitTest.php | 1 + tests/RandflakeUpstreamFormatTest.php | 1 + tests/ReleaseBoundaryTest.php | 6 ++- tests/SequenceDomainLimitTest.php | 13 +++++- tests/SequenceProviderTest.php | 25 ++++++++--- tests/ShortIdTest.php | 3 +- tests/SnowflakeTest.php | 6 ++- tests/SonyflakeTest.php | 2 +- tests/ULIDTest.php | 7 ++- tests/UUIDTest.php | 63 ++++++++++++++------------- 10 files changed, 78 insertions(+), 49 deletions(-) diff --git a/tests/PersistentDomainLimitTest.php b/tests/PersistentDomainLimitTest.php index b6db78a..e2fe906 100644 --- a/tests/PersistentDomainLimitTest.php +++ b/tests/PersistentDomainLimitTest.php @@ -17,6 +17,7 @@ final readonly class PersistentDomainClock implements ClockInterface { + #[\Override] public function now(): DateTimeImmutable { return new DateTimeImmutable('@1800000000.123456'); diff --git a/tests/RandflakeUpstreamFormatTest.php b/tests/RandflakeUpstreamFormatTest.php index 029c038..d045733 100644 --- a/tests/RandflakeUpstreamFormatTest.php +++ b/tests/RandflakeUpstreamFormatTest.php @@ -11,6 +11,7 @@ final readonly class RandflakeVectorClock implements ClockInterface { + #[\Override] public function now(): DateTimeImmutable { return new DateTimeImmutable('@1730000001'); diff --git a/tests/ReleaseBoundaryTest.php b/tests/ReleaseBoundaryTest.php index 93ade46..4e413ed 100644 --- a/tests/ReleaseBoundaryTest.php +++ b/tests/ReleaseBoundaryTest.php @@ -24,6 +24,7 @@ { public function __construct(private DateTimeImmutable $time) {} + #[\Override] public function now(): DateTimeImmutable { return $this->time; @@ -99,7 +100,7 @@ public function now(): DateTimeImmutable test('generation rejects out-of-domain clocks and keeps large wait budgets integer safe', function (): void { $negative = new GenerationContext(clock: new ReleaseBoundaryClock(new DateTimeImmutable('1969-12-31T23:59:59.500000Z'))); expect(fn(): int => $negative->nowMicroseconds())->toThrow(InvalidArgumentException::class) - ->and((new GenerationContext(waitTimeoutMicros: PHP_INT_MAX))->waitDeadlineNanoseconds())->toBeInt(); + ->and((new GenerationContext(waitTimeoutMicros: PHP_INT_MAX))->waitDeadlineNanoseconds())->toBeGreaterThan(hrtime(true)); }); test('upstream Randflake lease conversion fails with a domain error at integer exhaustion', function (): void { @@ -120,6 +121,7 @@ function (string $type, int $machineId, int $timestamp) use (&$nested, &$config, unset($type, $machineId, $timestamp); if (!$nested) { $nested = true; + $config !== null || throw new LogicException('Missing reentrant configuration'); $nestedId = \Infocyph\UID\Randflake::generateWithConfig($config); } @@ -151,7 +153,7 @@ function (string $type, int $machineId, int $timestamp) use (&$nested, &$config, [\Infocyph\UID\UUID::class, 'nextV7Timestamp', \Infocyph\UID\Exceptions\UUIDException::class], ] as [$class, $method, $exception]) { $wait = new ReflectionMethod($class, $method); - expect(fn(): int => $wait->invoke(null, 281_474_976_710_655))->toThrow($exception, 'exhausted'); + expect(fn(): mixed => $wait->invoke(null, 281_474_976_710_655))->toThrow($exception, 'exhausted'); } }); diff --git a/tests/SequenceDomainLimitTest.php b/tests/SequenceDomainLimitTest.php index b9f5994..f73bead 100644 --- a/tests/SequenceDomainLimitTest.php +++ b/tests/SequenceDomainLimitTest.php @@ -12,11 +12,13 @@ final class DomainLimitCache implements CacheInterface /** @var array */ private array $values = []; + #[\Override] public function get(string $key, mixed $default = null): mixed { return $this->values[$key] ?? $default; } + #[\Override] public function set(string $key, mixed $value, null|int|DateInterval $ttl = null): bool { unset($ttl); @@ -25,6 +27,7 @@ public function set(string $key, mixed $value, null|int|DateInterval $ttl = null return true; } + #[\Override] public function delete(string $key): bool { unset($this->values[$key]); @@ -32,6 +35,7 @@ public function delete(string $key): bool return true; } + #[\Override] public function clear(): bool { $this->values = []; @@ -39,6 +43,7 @@ public function clear(): bool return true; } + #[\Override] public function getMultiple(iterable $keys, mixed $default = null): iterable { foreach ($keys as $key) { @@ -46,24 +51,28 @@ public function getMultiple(iterable $keys, mixed $default = null): iterable } } + /** @param iterable $values */ + #[\Override] public function setMultiple(iterable $values, null|int|DateInterval $ttl = null): bool { foreach ($values as $key => $value) { - $this->set((string) $key, $value, $ttl); + $this->set($key), $value, $ttl); } return true; } + #[\Override] public function deleteMultiple(iterable $keys): bool { foreach ($keys as $key) { - $this->delete((string) $key); + $this->delete($key)); } return true; } + #[\Override] public function has(string $key): bool { return array_key_exists($key, $this->values); diff --git a/tests/SequenceProviderTest.php b/tests/SequenceProviderTest.php index d286dff..1a3175a 100644 --- a/tests/SequenceProviderTest.php +++ b/tests/SequenceProviderTest.php @@ -20,6 +20,7 @@ final class SequenceTestCache implements CacheInterface /** @var array */ private array $store = []; + #[\Override] public function clear(): bool { $this->store = []; @@ -27,6 +28,7 @@ public function clear(): bool return true; } + #[\Override] public function delete(string $key): bool { unset($this->store[$key]); @@ -34,15 +36,17 @@ public function delete(string $key): bool return true; } + #[\Override] public function deleteMultiple(iterable $keys): bool { foreach ($keys as $key) { - $this->delete((string) $key); + $this->delete($key)); } return true; } + #[\Override] public function get(string $key, mixed $default = null): mixed { ($this->beforeRead ?? static function (): void {})(); @@ -50,6 +54,7 @@ public function get(string $key, mixed $default = null): mixed return $this->store[$key] ?? $default; } + #[\Override] public function getMultiple(iterable $keys, mixed $default = null): iterable { $values = []; @@ -60,6 +65,7 @@ public function getMultiple(iterable $keys, mixed $default = null): iterable return $values; } + #[\Override] public function has(string $key): bool { return isset($this->store[$key]); @@ -70,6 +76,7 @@ public function seed(string $key, mixed $value): void $this->store[$key] = $value; } + #[\Override] public function set(string $key, mixed $value, null|int|DateInterval $ttl = null): bool { $this->lastTtl = $ttl; @@ -82,10 +89,12 @@ public function set(string $key, mixed $value, null|int|DateInterval $ttl = null return true; } + /** @param iterable $values */ + #[\Override] public function setMultiple(iterable $values, null|int|DateInterval $ttl = null): bool { foreach ($values as $key => $value) { - if (!$this->set((string) $key, $value, $ttl)) { + if (!$this->set($key), $value, $ttl)) { return false; } } @@ -101,14 +110,16 @@ public function setMultiple(iterable $values, null|int|DateInterval $ttl = null) runwire: new \Infocyph\UID\Runtime\RunwireBinding($host, $request), ); $cache = new SequenceTestCache(); - $cancel = static fn() => $request->cancel(\Infocyph\Runwire\Runtime\Enum\CancellationReason::HOST_CANCELLED); + $cancel = static fn(): bool => $request->cancel(\Infocyph\Runwire\Runtime\Enum\CancellationReason::HOST_CANCELLED); $synchronizer = static function (string $key, callable $allocate) use ($cancel, $phase): int { unset($key); if ($phase === 'synchronizer') { $cancel(); } - return $allocate(); + $result = $allocate(); + is_int($result) || throw new LogicException('Invalid allocation result'); + return $result; }; $provider = new PsrSimpleCacheSequenceProvider($cache, synchronizer: $synchronizer, runtime: $runtime); @@ -128,6 +139,8 @@ final class FutureOnceSequenceProvider implements SequenceProviderInterface { public int $calls = 0; + /** @throws \Infocyph\UID\Exceptions\SequenceTimestampException */ + #[\Override] public function next(string $type, int $machineId, int $timestamp): int { unset($type, $machineId); @@ -206,7 +219,9 @@ public function next(string $type, int $machineId, int $timestamp): int expect($key)->toContain('uid.seq.'); $synchronizerCalls++; - return $criticalSection(); + $result = $criticalSection(); + is_int($result) || throw new LogicException('Invalid allocation result'); + return $result; }; Snowflake::setSequenceProvider(new PsrSimpleCacheSequenceProvider($cache, synchronizer: $synchronizer)); diff --git a/tests/ShortIdTest.php b/tests/ShortIdTest.php index 02420b3..9516ffa 100644 --- a/tests/ShortIdTest.php +++ b/tests/ShortIdTest.php @@ -11,7 +11,6 @@ test('CUID2', function () { $string = CUID2::generate(); expect($string) - ->toBeString() ->not()->toBeEmpty() ->toHaveLength(24) ->toMatch('/^[a-z][0-9a-z]+$/'); @@ -24,7 +23,7 @@ test('nanoId', function () { $string = NanoID::generate(); - expect($string)->toBeString()->not()->toBeEmpty()->toHaveLength(21); + expect($string)->not()->toBeEmpty()->toHaveLength(21); }); test('namespaced helper functions for NanoID and CUID2', function () { diff --git a/tests/SnowflakeTest.php b/tests/SnowflakeTest.php index 1396212..a9a0923 100644 --- a/tests/SnowflakeTest.php +++ b/tests/SnowflakeTest.php @@ -50,7 +50,9 @@ $id1 = Snowflake::generate(); for ($i = 0; $i <= $maxSeq; $i++) { - $id1 = Snowflake::generate(); + $next = Snowflake::generate(); + expect((int) $next)->toBeGreaterThan((int) $id1); + $id1 = $next; } $id2 = Snowflake::generate(); @@ -137,7 +139,7 @@ test('Snowflake config rejects invalid epochs and resolver output', function () { $invalidResolver = new SnowflakeConfig(nodeResolver: fn (): string => 'invalid'); - $futureEpoch = ((int) floor(microtime(true) * 1000)) + 60_000; + $futureEpoch = ((int) floor(microtime(true) * 1000.0)) + 60_000; expect(fn () => Snowflake::generateWithConfig(new SnowflakeConfig(customEpoch: $futureEpoch))) ->toThrow(\Infocyph\UID\Exceptions\SnowflakeException::class) diff --git a/tests/SonyflakeTest.php b/tests/SonyflakeTest.php index 6b6a6ee..cf89c78 100644 --- a/tests/SonyflakeTest.php +++ b/tests/SonyflakeTest.php @@ -109,7 +109,7 @@ test('Sonyflake config rejects invalid epochs and resolver output', function () { $invalidResolver = new SonyflakeConfig(machineIdResolver: fn (): string => '1'); - $futureEpoch = ((int) floor(microtime(true) * 1000)) + 60_000; + $futureEpoch = ((int) floor(microtime(true) * 1000.0)) + 60_000; expect(fn () => Sonyflake::generateWithConfig(new SonyflakeConfig(customEpoch: $futureEpoch))) ->toThrow(\Infocyph\UID\Exceptions\SonyflakeException::class) diff --git a/tests/ULIDTest.php b/tests/ULIDTest.php index 0e24e01..3aa22c8 100644 --- a/tests/ULIDTest.php +++ b/tests/ULIDTest.php @@ -10,14 +10,13 @@ $startedAt = time() - 1; $ulid = ULID::generate(); $finishedAt = time() + 1; - expect($ulid)->toBeString() - ->and(ULID::isValid($ulid))->toBeTrue() + expect(ULID::isValid($ulid))->toBeTrue() ->and(ULID::getTime($ulid)->getTimestamp())->toBeBetween($startedAt, $finishedAt); }); test('Monotonic overflow on fixed timestamp throws ULIDException', function () { $dateTime = DateTimeImmutable::createFromFormat('U.u', '1700000000.123000'); - expect($dateTime)->not()->toBeFalse(); + $dateTime !== false || throw new RuntimeException('Invalid fixed timestamp'); $class = new ReflectionClass(ULID::class); $lastGenTime = $class->getProperty('lastGenTime'); @@ -46,7 +45,7 @@ test('ULID random mode does not depend on monotonic state', function () { $fixed = DateTimeImmutable::createFromFormat('U.u', '1700000000.123000'); - expect($fixed)->not()->toBeFalse(); + $fixed !== false || throw new RuntimeException('Invalid fixed timestamp'); $id1 = ULID::generate($fixed, UlidGenerationMode::RANDOM); $id2 = ULID::generate($fixed, UlidGenerationMode::RANDOM); diff --git a/tests/UUIDTest.php b/tests/UUIDTest.php index 6b02831..a94cd39 100644 --- a/tests/UUIDTest.php +++ b/tests/UUIDTest.php @@ -11,12 +11,12 @@ $startedAt = time() - 1; $uid = UUID::v1(); $finishedAt = time() + 1; - expect($uid)->toBeString(); + expect(UUID::isValid($uid))->toBeTrue(); $parsed = UUID::parse($uid); expect($parsed['version'])->toBe(1) ->and($parsed['time'])->not()->toBeNull() - ->and($parsed['node'])->toBeString()->not()->toBeNull() - ->and($parsed['time']->getTimestamp())->toBeBetween($startedAt, $finishedAt); + ->and($parsed['node'])->toBeString() + ->and($parsed['time']?->getTimestamp())->toBeBetween($startedAt, $finishedAt); }); test('UUID v2 encodes local identity and coordinated node fields', function (int $domain, int $identifier, int $sequence): void { @@ -28,8 +28,8 @@ ->and(substr($uuid, 0, 8))->toBe(sprintf('%08x', $identifier)) ->and(substr($uuid, 19, 4))->toBe(sprintf('%02x%02x', 0x80 | $sequence, $domain)) ->and($parsed['version'])->toBe(2) - ->and($parsed['local_domain'])->toBe($domain) - ->and($parsed['local_identifier'])->toBe($identifier) + ->and(($parsed['local_domain'] ?? null))->toBe($domain) + ->and(($parsed['local_identifier'] ?? null))->toBe($identifier) ->and($parsed['node'])->toBe('abcdef123456') ->and($parsed['time']?->getTimestamp())->toBeBetween($startedAt - 430, time()) ->and(UUID::fromBytes(UUID::toBytes($uuid)))->toBe($uuid) @@ -41,8 +41,8 @@ $parsed = UUID::parse($uuid); $value = new \Infocyph\UID\Value\UuidValue($uuid); - expect($parsed['local_identifier'])->toBe(501) - ->and($parsed['local_domain'])->toBe(0) + expect(($parsed['local_identifier'] ?? null))->toBe(501) + ->and(($parsed['local_domain'] ?? null))->toBe(0) ->and($parsed['time']?->format('Y-m-d H:i:s.u'))->toBe('2020-03-05 04:30:10.619596') ->and($value->getTimestamp()?->format('Y-m-d H:i:s.u'))->toBe('2020-03-05 04:30:10.619596') ->and($value->getVersion())->toBe(2) @@ -55,16 +55,17 @@ for ($index = 0; $index < 100; ++$index) { $uuid = $generate(1001); $parsed = UUID::parse($uuid); - expect($parsed['local_identifier'])->toBe(1001) - ->and($parsed['local_domain'])->toBe(0) - ->and(hexdec(substr($parsed['node'], 0, 2)) & 1)->toBe(1); + expect(($parsed['local_identifier'] ?? null))->toBe(1001) + ->and(($parsed['local_domain'] ?? null))->toBe(0) + ->and(hexdec(substr($parsed['node'] ?? '', 0, 2)) & 1)->toBe(1); $ids[] = $uuid; } } expect(array_unique($ids))->toHaveCount(300); }); -test('UUID v2 rejects invalid fields and uncoordinated fixed nodes', function (array $arguments): void { +test('UUID v2 rejects invalid fields and uncoordinated fixed nodes', /** @param array{0:int,1?:int,2?:string|null,3?:int} $arguments */ +function (array $arguments): void { expect(fn(): string => UUID::v2(...$arguments))->toThrow(\Infocyph\UID\Exceptions\UUIDException::class); })->with([ [[-1]], @@ -83,41 +84,41 @@ test('UUID v3', function () use ($ns) { $uid = UUID::v3($ns, 'my-string'); - expect($uid)->toBeString(); + expect(UUID::isValid($uid))->toBeTrue(); $parsed = UUID::parse($uid); expect($parsed['version'])->toBe(3) ->and($parsed['time'])->toBeNull() - ->and($parsed['node'])->toBeString()->not()->toBeNull(); + ->and($parsed['node'])->toBeString(); }); test('UUID v4', function () { $uid = UUID::v4(); - expect($uid)->toBeString(); + expect(UUID::isValid($uid))->toBeTrue(); $parsed = UUID::parse($uid); expect($parsed['version'])->toBe(4) ->and($parsed['time'])->toBeNull() - ->and($parsed['node'])->toBeString()->not()->toBeNull(); + ->and($parsed['node'])->toBeString(); }); test('UUID v5', function () use ($ns) { $uid = UUID::v5($ns, 'my-string'); - expect($uid)->toBeString(); + expect(UUID::isValid($uid))->toBeTrue(); $parsed = UUID::parse($uid); expect($parsed['version'])->toBe(5) ->and($parsed['time'])->toBeNull() - ->and($parsed['node'])->toBeString()->not()->toBeNull(); + ->and($parsed['node'])->toBeString(); }); test('UUID v6', function () { $startedAt = time() - 1; $uid = UUID::v6(); $finishedAt = time() + 1; - expect($uid)->toBeString(); + expect(UUID::isValid($uid))->toBeTrue(); $parsed = UUID::parse($uid); expect($parsed['version'])->toBe(6) ->and($parsed['time'])->not()->toBeNull() - ->and($parsed['node'])->toBeString()->not()->toBeNull() - ->and($parsed['time']->getTimestamp())->toBeBetween($startedAt, $finishedAt); + ->and($parsed['node'])->toBeString() + ->and($parsed['time']?->getTimestamp())->toBeBetween($startedAt, $finishedAt); }); test('UUID time parsing preserves fractional timestamps across the Unix epoch', function (int $version, int $offset, string $expected): void { @@ -143,23 +144,23 @@ $startedAt = time() - 1; $uid = UUID::v7(); $finishedAt = time() + 1; - expect($uid)->toBeString(); + expect(UUID::isValid($uid))->toBeTrue(); $parsed = UUID::parse($uid); expect($parsed['version'])->toBe(7) ->and($parsed['time'])->not()->toBeNull() ->and($parsed['node'])->toBeNull() - ->and($parsed['tail'])->toBeString()->not()->toBeNull() - ->and($parsed['time']->getTimestamp())->toBeBetween($startedAt, $finishedAt); + ->and($parsed['tail'])->toBeString() + ->and($parsed['time']?->getTimestamp())->toBeBetween($startedAt, $finishedAt); }); test('UUID v8', function () { $uid = UUID::v8(); - expect($uid)->toBeString(); + expect(UUID::isValid($uid))->toBeTrue(); $parsed = UUID::parse($uid); expect($parsed['version'])->toBe(8) ->and($parsed['time'])->toBeNull() ->and($parsed['node'])->toBeNull() - ->and($parsed['tail'])->toBeString()->not()->toBeNull(); + ->and($parsed['tail'])->toBeString(); }); test('UUID node must be exactly 12 hex characters when provided', function () { @@ -191,27 +192,27 @@ expect(hexdec(substr($node, 0, 2)) & 0x01)->toBe(0x01) ->and($parsedNode)->toBeString() - ->and(hexdec(substr($parsedNode, 0, 2)) & 0x01)->toBe(0x01); + ->and(hexdec(substr($parsedNode ?? '', 0, 2)) & 0x01)->toBe(0x01); }); test('GUID', function () { $uid = UUID::guid(); - expect($uid)->toBeString(); + expect(UUID::isValid($uid))->toBeTrue(); $parsed = UUID::parse($uid); expect($parsed['version'])->toBe(4) ->and($parsed['time'])->toBeNull() - ->and($parsed['node'])->toBeString()->not()->toBeNull(); + ->and($parsed['node'])->toBeString(); }); test('UUID v7 does not move timestamp forward for monotonicity', function () { $fixedTime = DateTimeImmutable::createFromFormat('U.u', '1700000000.123000'); - expect($fixedTime)->not()->toBeFalse(); + $fixedTime !== false || throw new RuntimeException('Invalid fixed timestamp'); $uid1 = UUID::v7($fixedTime); $uid2 = UUID::v7($fixedTime); - $time1 = (int)UUID::parse($uid1)['time']->format('Uv'); - $time2 = (int)UUID::parse($uid2)['time']->format('Uv'); + $time1 = (int) (UUID::parse($uid1)['time']?->format('Uv') ?? '-1'); + $time2 = (int) (UUID::parse($uid2)['time']?->format('Uv') ?? '-1'); $expected = (int)$fixedTime->format('Uv'); expect($time1)->toBe($expected) From f50e61f79ac4c34f75c402c2ea1b61f4e6c8c1f6 Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 09:55:51 +0600 Subject: [PATCH 09/26] docs: declare generator and configuration exception contracts --- src/CUID2.php | 1 + src/Configuration/RandflakeConfig.php | 3 ++ src/Configuration/ResolvesMachineId.php | 3 ++ src/Configuration/SnowflakeConfig.php | 1 + src/DeterministicId.php | 1 + src/Id.php | 48 +++++++++++++++++++++++++ src/NanoID.php | 1 + src/ObjectID.php | 10 ++++++ src/OpaqueId.php | 1 + 9 files changed, 69 insertions(+) diff --git a/src/CUID2.php b/src/CUID2.php index 8e6c4e6..f57a173 100644 --- a/src/CUID2.php +++ b/src/CUID2.php @@ -67,6 +67,7 @@ public static function isValid(string $id, ?int $length = null): bool * Parses CUID2 information. * * @return array{length: int} + * @throws \InvalidArgumentException */ public static function parse(string $id, ?int $length = null): array { diff --git a/src/Configuration/RandflakeConfig.php b/src/Configuration/RandflakeConfig.php index 5148c58..29b02e8 100644 --- a/src/Configuration/RandflakeConfig.php +++ b/src/Configuration/RandflakeConfig.php @@ -23,6 +23,9 @@ public function __construct( public ?int $leaseEndExclusive = null, ) {} + /** + * @throws \Infocyph\UID\Exceptions\RandflakeException + */ public function resolveLeaseEndExclusive(): int { if ($this->leaseEndExclusive !== null) { diff --git a/src/Configuration/ResolvesMachineId.php b/src/Configuration/ResolvesMachineId.php index 94badf0..1e246c4 100644 --- a/src/Configuration/ResolvesMachineId.php +++ b/src/Configuration/ResolvesMachineId.php @@ -10,6 +10,9 @@ trait ResolvesMachineId { private readonly ?Closure $machineIdResolver; + /** + * @throws \UnexpectedValueException + */ public function resolveMachineId(): int { if ($this->machineIdResolver === null) { diff --git a/src/Configuration/SnowflakeConfig.php b/src/Configuration/SnowflakeConfig.php index 21e5740..ab0044c 100644 --- a/src/Configuration/SnowflakeConfig.php +++ b/src/Configuration/SnowflakeConfig.php @@ -37,6 +37,7 @@ public function __construct( /** * @return array{0:int, 1:int} + * @throws \UnexpectedValueException */ public function resolveNode(): array { diff --git a/src/DeterministicId.php b/src/DeterministicId.php index 2f489bd..dfeea0b 100644 --- a/src/DeterministicId.php +++ b/src/DeterministicId.php @@ -16,6 +16,7 @@ final class DeterministicId /** * Generates a deterministic opaque ID from payload. + * @throws \InvalidArgumentException */ public static function fromPayload(string $payload, int $length = 24, string $namespace = 'default'): string { diff --git a/src/Id.php b/src/Id.php index 4ca6b51..38b45f9 100644 --- a/src/Id.php +++ b/src/Id.php @@ -16,6 +16,10 @@ final class Id { + /** + * @throws \InvalidArgumentException + * @throws \Exception + */ public static function cuid2(int $length = 24): string { return CUID2::generate($length); @@ -26,11 +30,17 @@ public static function deterministic(string $payload, int $length = 24, string $ return DeterministicId::fromPayload($payload, $length, $namespace); } + /** + * @throws \Exception + */ public static function ksuid(?DateTimeInterface $dateTime = null): string { return KSUID::generate($dateTime); } + /** + * @throws \Exception + */ public static function nanoId(int $length = 21): string { return NanoID::generate($length); @@ -41,6 +51,10 @@ public static function objectId(?DateTimeInterface $dateTime = null): string return ObjectID::generate($dateTime); } + /** + * @throws \Infocyph\UID\Exceptions\RandflakeException + * @throws \Infocyph\UID\Exceptions\FileLockException + */ public static function randflake(RandflakeConfig $config): string { return Randflake::generateWithConfig($config); @@ -92,6 +106,9 @@ public static function typeId(string $type = ''): string return TypeID::generate($type); } + /** + * @throws \Exception + */ public static function ulid( ?DateTimeInterface $dateTime = null, UlidGenerationMode $mode = UlidGenerationMode::MONOTONIC, @@ -99,16 +116,26 @@ public static function ulid( return ULID::generate($dateTime, $mode); } + /** + * @throws \Exception + */ public static function uuid(?DateTimeInterface $dateTime = null): string { return UUID::v7($dateTime); } + /** + * @throws \Exception + */ public static function uuid1(?string $node = null): string { return UUID::v1($node); } + /** + * @throws \Infocyph\UID\Exceptions\UUIDException + * @throws \Exception + */ public static function uuid2( int $localIdentifier, int $localDomain = UUID::DCE_DOMAIN_PERSON, @@ -118,36 +145,57 @@ public static function uuid2( return UUID::v2($localIdentifier, $localDomain, $node, $clockSequence); } + /** + * @throws \Infocyph\UID\Exceptions\UUIDException + */ public static function uuid3(string $namespace, string $string): string { return UUID::v3($namespace, $string); } + /** + * @throws \Exception + */ public static function uuid4(): string { return UUID::v4(); } + /** + * @throws \Infocyph\UID\Exceptions\UUIDException + */ public static function uuid5(string $namespace, string $string): string { return UUID::v5($namespace, $string); } + /** + * @throws \Exception + */ public static function uuid6(?string $node = null): string { return UUID::v6($node); } + /** + * @throws \Exception + */ public static function uuid7(?DateTimeInterface $dateTime = null): string { return UUID::v7($dateTime); } + /** + * @throws \Exception + */ public static function uuid8(?string $node = null): string { return UUID::v8($node); } + /** + * @throws \Exception + */ public static function xid(): string { return XID::generate(); diff --git a/src/NanoID.php b/src/NanoID.php index 382a229..16dcdc3 100644 --- a/src/NanoID.php +++ b/src/NanoID.php @@ -47,6 +47,7 @@ public static function isValid(string $id, ?int $length = null): bool * Parses NanoID information. * * @return array{length: int, alphabet: string} + * @throws \InvalidArgumentException */ public static function parse(string $id, ?int $length = null): array { diff --git a/src/ObjectID.php b/src/ObjectID.php index 7f17de0..eb44b09 100644 --- a/src/ObjectID.php +++ b/src/ObjectID.php @@ -17,6 +17,9 @@ final class ObjectID private static ?int $sourcePid = null; + /** + * @throws \Infocyph\UID\Exceptions\ObjectIDException + */ public static function fromBytes(string $bytes): string { if (strlen($bytes) !== 12) { @@ -26,6 +29,9 @@ public static function fromBytes(string $bytes): string return bin2hex($bytes); } + /** + * @throws \Infocyph\UID\Exceptions\ObjectIDException + */ public static function generate(?DateTimeInterface $dateTime = null): string { self::ensureProcessState(); @@ -47,6 +53,7 @@ public static function isValid(string $id): bool /** * @return array{time:DateTimeImmutable, process_random:string, counter:int} + * @throws \Exception */ public static function parse(string $id): array { @@ -60,6 +67,9 @@ public static function parse(string $id): array ]; } + /** + * @throws \Infocyph\UID\Exceptions\ObjectIDException + */ public static function toBytes(string $id): string { if (!self::isValid($id)) { diff --git a/src/OpaqueId.php b/src/OpaqueId.php index f5262c2..476275f 100644 --- a/src/OpaqueId.php +++ b/src/OpaqueId.php @@ -11,6 +11,7 @@ final class OpaqueId { /** * Encodes an integer in a hashid-style opaque token. + * @throws \InvalidArgumentException */ public static function fromInt(int $value, string $salt = ''): string { From 564b8fa380c05ddcc21379d585d6420c2580a10b Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 09:56:10 +0600 Subject: [PATCH 10/26] docs: declare runtime and coordinated allocation failure contracts --- src/Randflake.php | 9 +++++++++ src/Runtime/GenerationContext.php | 6 ++++++ src/Runtime/RunwireBinding.php | 10 ++++++++++ src/Sequence/CallbackSequenceProvider.php | 1 + src/Sequence/FilesystemSequenceProvider.php | 16 ++++++++++++++++ src/Sequence/InMemorySequenceProvider.php | 5 +++++ .../PsrSimpleCacheSequenceProvider.php | 19 +++++++++++++++++++ src/Snowflake.php | 7 +++++++ src/Sonyflake.php | 19 +++++++++++++++++++ 9 files changed, 92 insertions(+) diff --git a/src/Randflake.php b/src/Randflake.php index a74f7cf..4f10e50 100644 --- a/src/Randflake.php +++ b/src/Randflake.php @@ -359,6 +359,7 @@ public static function toBytes( /** * @return array{0:int,1:int} + * @throws \Infocyph\UID\Exceptions\RandflakeException */ private static function allocateSequence( SequenceProviderInterface $provider, @@ -389,6 +390,9 @@ private static function allocateSequence( } } + /** + * @throws \Infocyph\UID\Exceptions\RandflakeException + */ private static function assertGenerationTime( int $now, int $leaseStart, @@ -515,6 +519,7 @@ private static function leaseContains( /** * @param array{timestamp:int,sequence:int}|null $last + * @throws \Infocyph\UID\Exceptions\RandflakeException */ private static function normalizeAllocation(int $allocation, ?array $last, int $now): int { @@ -554,6 +559,7 @@ private static function packPayload(int $timestamp, int $nodeId, int $sequence): /** * Small secret-key permutation over 64-bit blocks to protect payload fields. + * @throws \Infocyph\UID\Exceptions\RandflakeException */ private static function permute(string $block, string $secret, bool $decrypt): string { @@ -584,6 +590,7 @@ private static function permute(string $block, string $secret, bool $decrypt): s /** * @return \ArrayObject + * @throws \Infocyph\UID\Exceptions\RandflakeException */ private static function providerState( SequenceProviderInterface $provider, @@ -625,6 +632,7 @@ private static function roundFunction(int $value, int $key): int /** * @return array + * @throws \Infocyph\UID\Exceptions\RandflakeException */ private static function roundKeys(string $secret): array { @@ -683,6 +691,7 @@ private static function unpackedInt(array|false $parts, string $key): int /** * @return array{0:int,1:int,2:int} + * @throws \Infocyph\UID\Exceptions\RandflakeException */ private static function unpackPayload(string $payload): array { diff --git a/src/Runtime/GenerationContext.php b/src/Runtime/GenerationContext.php index c6a6cdf..9a95bfb 100644 --- a/src/Runtime/GenerationContext.php +++ b/src/Runtime/GenerationContext.php @@ -11,6 +11,9 @@ { private const int DEFAULT_WAIT_TIMEOUT_MICROS = 1_000_000; + /** + * @throws \InvalidArgumentException + */ public function __construct( public ?ClockInterface $clock = null, public ?RunwireBinding $runwire = null, @@ -26,6 +29,9 @@ public function assertActive(): void $this->runwire?->assertActive(); } + /** + * @throws \InvalidArgumentException + */ public function nowMicroseconds(): int { $this->assertActive(); diff --git a/src/Runtime/RunwireBinding.php b/src/Runtime/RunwireBinding.php index 99fc396..9c27f0d 100644 --- a/src/Runtime/RunwireBinding.php +++ b/src/Runtime/RunwireBinding.php @@ -23,6 +23,11 @@ public function __construct( $this->assertActive(); } + /** + * @throws \LogicException + * @throws \Infocyph\Runwire\Exception\CancelledException + * @throws \Throwable + */ public function assertActive(): void { $pid = getmypid(); @@ -68,6 +73,11 @@ public function deadlineNanoseconds(): ?int return min($requestDeadline, $scopeDeadline); } + /** + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable + */ public function sleep(float $seconds): void { $this->assertActive(); diff --git a/src/Sequence/CallbackSequenceProvider.php b/src/Sequence/CallbackSequenceProvider.php index e4ed13d..9cd3e21 100644 --- a/src/Sequence/CallbackSequenceProvider.php +++ b/src/Sequence/CallbackSequenceProvider.php @@ -22,6 +22,7 @@ public function __construct(callable $callback) /** * @throws FileLockException */ + #[\Override] public function next(string $type, int $machineId, int $timestamp): int { $value = ($this->callback)($type, $machineId, $timestamp); diff --git a/src/Sequence/FilesystemSequenceProvider.php b/src/Sequence/FilesystemSequenceProvider.php index af605c2..7353b71 100644 --- a/src/Sequence/FilesystemSequenceProvider.php +++ b/src/Sequence/FilesystemSequenceProvider.php @@ -28,6 +28,9 @@ final class FilesystemSequenceProvider implements SequenceProviderInterface private ?int $sourcePid = null; + /** + * @throws \InvalidArgumentException + */ public function __construct( ?string $baseDirectory = null, private readonly string $namespace = '', @@ -50,6 +53,11 @@ public function __construct( } } + /** + * @throws \Infocyph\UID\Exceptions\FileLockException + * @throws \Infocyph\UID\Exceptions\SequenceTimestampException + */ + #[\Override] public function next(string $type, int $machineId, int $timestamp, ?GenerationContext $runtime = null): int { $this->runtime?->assertActive(); @@ -104,6 +112,7 @@ public function next(string $type, int $machineId, int $timestamp, ?GenerationCo /** * @param resource $handle * @return array{0:int,1:int,2:int} + * @throws \Infocyph\UID\Exceptions\FileLockException */ private function readState($handle): array { @@ -148,6 +157,9 @@ private function resetAfterFork(): void $this->reservations = []; } + /** + * @throws \InvalidArgumentException + */ private function sequenceFileLocation(string $type, int $machineId): string { $cacheKey = $type . ':' . $machineId; @@ -167,6 +179,9 @@ private function sequenceFileLocation(string $type, int $machineId): string return $this->pathCache[$cacheKey] = $this->baseDirectory . DIRECTORY_SEPARATOR . $name; } + /** + * @throws \Infocyph\UID\Exceptions\FileLockException + */ private function storeReservation( string $fileLocation, int $timestamp, @@ -207,6 +222,7 @@ private function takeReservedAllocation(string $fileLocation, int $timestamp): ? /** * @param resource $handle + * @throws \Infocyph\UID\Exceptions\FileLockException */ private function writeState($handle, string $state, int $oldLength): void { diff --git a/src/Sequence/InMemorySequenceProvider.php b/src/Sequence/InMemorySequenceProvider.php index 26b6009..2ce5147 100644 --- a/src/Sequence/InMemorySequenceProvider.php +++ b/src/Sequence/InMemorySequenceProvider.php @@ -16,6 +16,11 @@ final class InMemorySequenceProvider implements SequenceProviderInterface */ private array $state = []; + /** + * @throws \Infocyph\UID\Exceptions\FileLockException + * @throws \Infocyph\UID\Exceptions\SequenceTimestampException + */ + #[\Override] public function next(string $type, int $machineId, int $timestamp): int { $key = $this->key($type, $machineId); diff --git a/src/Sequence/PsrSimpleCacheSequenceProvider.php b/src/Sequence/PsrSimpleCacheSequenceProvider.php index 918e6ec..451bb7a 100644 --- a/src/Sequence/PsrSimpleCacheSequenceProvider.php +++ b/src/Sequence/PsrSimpleCacheSequenceProvider.php @@ -24,6 +24,7 @@ final class PsrSimpleCacheSequenceProvider implements SequenceProviderInterface /** * @param callable(string, callable():int):mixed|null $synchronizer + * @throws \InvalidArgumentException */ public function __construct( private readonly CacheInterface $cache, @@ -50,6 +51,7 @@ public function __construct( /** * @throws FileLockException */ + #[\Override] public function next(string $type, int $machineId, int $timestamp, ?GenerationContext $runtime = null): int { $this->runtime?->assertActive(); @@ -77,6 +79,7 @@ public function next(string $type, int $machineId, int $timestamp, ?GenerationCo /** * @param array{timestamp:int,sequence:int}|null $state * @param array{timestamp:int,sequence:int}|null $observed + * @throws \Infocyph\UID\Exceptions\FileLockException */ private static function assertNotRegressed(?array $state, ?array $observed, string $key): void { @@ -93,6 +96,8 @@ private static function assertNotRegressed(?array $state, ?array $observed, stri /** * @param array{timestamp:int,sequence:int}|null $state + * @throws \Infocyph\UID\Exceptions\SequenceTimestampException + * @throws \Infocyph\UID\Exceptions\FileLockException */ private static function nextSequence(?array $state, int $timestamp, string $key): int { @@ -133,6 +138,9 @@ private function acquireLock(string $key, ?GenerationContext $runtime) ); } + /** + * @throws \InvalidArgumentException + */ private function key(string $type, int $machineId): string { if (preg_match('/^[A-Za-z0-9_.]+$/D', $type) !== 1) { @@ -147,6 +155,10 @@ private function key(string $type, int $machineId): string return $key; } + /** + * @throws \Psr\SimpleCache\InvalidArgumentException + * @throws \Infocyph\UID\Exceptions\FileLockException + */ private function nextFromCacheState(string $key, int $timestamp, ?GenerationContext $runtime): int { $runtime?->assertActive(); @@ -169,6 +181,9 @@ private function nextFromCacheState(string $key, int $timestamp, ?GenerationCont return $sequence; } + /** + * @throws \Infocyph\UID\Exceptions\FileLockException + */ private function nextSafely(string $key, int $timestamp, ?GenerationContext $runtime): int { try { @@ -182,6 +197,9 @@ private function nextSafely(string $key, int $timestamp, ?GenerationContext $run } } + /** + * @throws \Infocyph\UID\Exceptions\FileLockException + */ private function nextSynchronized(Closure $synchronizer, string $key, int $timestamp, ?GenerationContext $runtime): int { try { @@ -206,6 +224,7 @@ private function nextSynchronized(Closure $synchronizer, string $key, int $times /** * @return array{timestamp:int,sequence:int}|null + * @throws \Infocyph\UID\Exceptions\FileLockException */ private function normalizeState(mixed $state, string $key): ?array { diff --git a/src/Snowflake.php b/src/Snowflake.php index ba71d6d..ea07af0 100644 --- a/src/Snowflake.php +++ b/src/Snowflake.php @@ -176,6 +176,9 @@ public static function toBytes(string $id): string return self::encodeNumericBytes($id); } + /** + * @throws \Infocyph\UID\Exceptions\SnowflakeException + */ private static function assertDecodedId(string $id): string { if (!self::isValid($id)) { @@ -379,6 +382,7 @@ private static function nowMilliseconds(?GenerationContext $runtime): int /** * @return \ArrayObject + * @throws \Infocyph\UID\Exceptions\SnowflakeException */ private static function providerState( SequenceProviderInterface $provider, @@ -418,6 +422,9 @@ private static function timestampParts(int $timestamp): array ]; } + /** + * @throws \Infocyph\UID\Exceptions\SnowflakeException + */ private static function waitUntil(int $timestamp, ?GenerationContext $runtime): int { $deadline = $runtime?->waitDeadlineNanoseconds() diff --git a/src/Sonyflake.php b/src/Sonyflake.php index 9845843..aeba87b 100644 --- a/src/Sonyflake.php +++ b/src/Sonyflake.php @@ -186,6 +186,7 @@ public static function toBytes(string $id): string /** * @return array{0:int,1:int} + * @throws \Infocyph\UID\Exceptions\SonyflakeException */ private static function allocateSequence( SequenceProviderInterface $provider, @@ -228,6 +229,9 @@ private static function allocateSequence( } } + /** + * @throws \Infocyph\UID\Exceptions\SonyflakeException + */ private static function assertDecodedId(string $id): string { if (!self::isValid($id)) { @@ -237,6 +241,9 @@ private static function assertDecodedId(string $id): string return $id; } + /** + * @throws \Infocyph\UID\Exceptions\SonyflakeException + */ private static function assertMachineId(int $machineId): void { $maximum = -1 ^ (-1 << self::MACHINE_BITS); @@ -260,6 +267,7 @@ private static function decodeNumeric(callable $operation, ?string $customMessag /** * Calculates the elapsed time in 10ms units. + * @throws \Infocyph\UID\Exceptions\SonyflakeException */ private static function elapsedTime(int $currentTime, int $startTimestamp): int { @@ -292,6 +300,7 @@ private static function ensureEffectiveRuntime(int $elapsedTime): void /** * @return array{seconds:string,fraction:string,sequence:int,machine_id:int} + * @throws \Infocyph\UID\Exceptions\SonyflakeException */ private static function extractParts( string $id, @@ -395,6 +404,7 @@ private static function packId( /** * @return \ArrayObject + * @throws \Infocyph\UID\Exceptions\SonyflakeException */ private static function providerState( SequenceProviderInterface $provider, @@ -421,6 +431,9 @@ private static function resolveSequenceProvider(?SequenceProviderInterface $prov return $provider ?? self::$sequenceProvider ??= new FilesystemSequenceProvider(); } + /** + * @throws \Infocyph\UID\Exceptions\SonyflakeException + */ private static function resolveWallTime( int $currentTime, int $lastWallTime, @@ -437,6 +450,9 @@ private static function resolveWallTime( return self::waitUntilWallTime($lastWallTime, $runtime); } + /** + * @throws \Infocyph\UID\Exceptions\SonyflakeException + */ private static function waitUntilElapsed( int $elapsedTime, int $startTimestamp, @@ -460,6 +476,9 @@ private static function waitUntilElapsed( return $next; } + /** + * @throws \Infocyph\UID\Exceptions\SonyflakeException + */ private static function waitUntilWallTime(int $lastTime, ?GenerationContext $runtime): int { $deadline = $runtime?->waitDeadlineNanoseconds() From 2df8c512ce6f07d24d19ae514876a6f19611497a Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 09:56:30 +0600 Subject: [PATCH 11/26] docs: declare binary codec and locking failure contracts --- src/Support/BaseEncoder.php | 9 +++++++++ src/Support/BinaryUnpack.php | 2 ++ src/Support/DecimalBytes.php | 10 ++++++++++ src/Support/FileLock.php | 2 ++ src/Support/GetSequence.php | 1 + src/Support/RandomSampler.php | 6 ++++++ src/Support/Sparx64.php | 8 +++++++- src/Support/TypeIdCodec.php | 7 +++++++ src/TBSL.php | 9 +++++++++ 9 files changed, 53 insertions(+), 1 deletion(-) diff --git a/src/Support/BaseEncoder.php b/src/Support/BaseEncoder.php index 1a5017f..cb222d1 100644 --- a/src/Support/BaseEncoder.php +++ b/src/Support/BaseEncoder.php @@ -28,6 +28,9 @@ final class BaseEncoder 62 => [916_132_832, 5], ]; + /** + * @throws \InvalidArgumentException + */ public static function decodeToBytes(string $encoded, int $base, int $bytesLength): string { if ($encoded === '') { @@ -92,6 +95,9 @@ private static function alphabet(int $base): string return self::ALPHABETS[$base] ?? throw new InvalidArgumentException('Unsupported base: ' . $base); } + /** + * @throws \InvalidArgumentException + */ private static function assertByteLength(int $byteLength): void { if ($byteLength < 1 || $byteLength > self::MAX_BYTE_LENGTH) { @@ -99,6 +105,9 @@ private static function assertByteLength(int $byteLength): void } } + /** + * @throws \InvalidArgumentException + */ private static function decodeRadix(string $encoded, int $base, int $bytesLength): string { $alphabet = self::alphabet($base); diff --git a/src/Support/BinaryUnpack.php b/src/Support/BinaryUnpack.php index d2e3650..c173832 100644 --- a/src/Support/BinaryUnpack.php +++ b/src/Support/BinaryUnpack.php @@ -8,6 +8,7 @@ final class BinaryUnpack { /** * @return list + * @throws \LogicException */ public static function bytes(string $bytes): array { @@ -44,6 +45,7 @@ public static function u32(string $bytes, string $error): int /** * @return list + * @throws \LogicException */ public static function words(string $bytes): array { diff --git a/src/Support/DecimalBytes.php b/src/Support/DecimalBytes.php index f2e76c4..3e267bf 100644 --- a/src/Support/DecimalBytes.php +++ b/src/Support/DecimalBytes.php @@ -24,6 +24,9 @@ public static function fromBytes(string $bytes): string return BaseEncoder::encodeBytes($bytes, 10); } + /** + * @throws \InvalidArgumentException + */ public static function fromLittleEndianSigned64(string $bytes): string { if (strlen($bytes) !== 8) { @@ -74,6 +77,9 @@ public static function toFixedBytes(string $decimal, int $byteLength): string return BaseEncoder::decodeToBytes(UnsignedDecimal::normalize($decimal), 10, $byteLength); } + /** + * @throws \InvalidArgumentException + */ public static function toLittleEndianSigned64(string $value): string { if (!self::isSigned64($value)) { @@ -91,6 +97,10 @@ public static function toLittleEndianSigned64(string $value): string return strrev(self::toFixedBytes($unsigned, 8)); } + /** + * @throws \InvalidArgumentException + * @throws \LogicException + */ private static function subtract(string $left, string $right): string { if (UnsignedDecimal::compare($left, $right) < 0) { diff --git a/src/Support/FileLock.php b/src/Support/FileLock.php index ad61687..9c41a0b 100644 --- a/src/Support/FileLock.php +++ b/src/Support/FileLock.php @@ -15,6 +15,7 @@ final class FileLock /** * @return resource * @throws FileLockException + * @throws \Throwable */ public static function acquire( string $path, @@ -151,6 +152,7 @@ static function (int $severity, string $message, string $file, int $line): never * @param resource $handle * @param array|null $before * @return resource + * @throws \Throwable */ private static function verifyHandle(string $path, $handle, ?array $before, string $errorMessage, ?int $ownerId) { diff --git a/src/Support/GetSequence.php b/src/Support/GetSequence.php index e94b37b..9db4622 100644 --- a/src/Support/GetSequence.php +++ b/src/Support/GetSequence.php @@ -96,6 +96,7 @@ public static function useSimpleCacheSequenceProvider( * @param int $dateTime The current time. * @param int $machineId The machine ID. * @param string $type The type identifier. + * @throws \Infocyph\UID\Exceptions\FileLockException */ private static function sequence( int $dateTime, diff --git a/src/Support/RandomSampler.php b/src/Support/RandomSampler.php index a058c5f..4b8ec2b 100644 --- a/src/Support/RandomSampler.php +++ b/src/Support/RandomSampler.php @@ -8,6 +8,9 @@ final class RandomSampler { + /** + * @throws \InvalidArgumentException + */ public static function assertAlphabet(string $alphabet): void { $length = strlen($alphabet); @@ -45,6 +48,9 @@ public static function containsOnly(string $value, string $alphabet): bool return true; } + /** + * @throws \InvalidArgumentException + */ public static function generate(int $length, string $alphabet): string { self::assertAlphabet($alphabet); diff --git a/src/Support/Sparx64.php b/src/Support/Sparx64.php index 78f6705..2f637fe 100644 --- a/src/Support/Sparx64.php +++ b/src/Support/Sparx64.php @@ -17,6 +17,9 @@ final class Sparx64 /** @var array> */ private array $subkeys; + /** + * @throws \InvalidArgumentException + */ public function __construct(#[\SensitiveParameter] string $key) { if (strlen($key) !== 16) { @@ -148,7 +151,10 @@ private static function roundInverse(int &$left, int &$right): void $left = self::rotateLeft16(($left - $right) & 0xffff, 7); } - /** @return array */ + /** + * @return array + * @throws \InvalidArgumentException + */ private static function unpackBlock(string $block): array { if (strlen($block) !== 8) { diff --git a/src/Support/TypeIdCodec.php b/src/Support/TypeIdCodec.php index 5786165..4a17345 100644 --- a/src/Support/TypeIdCodec.php +++ b/src/Support/TypeIdCodec.php @@ -10,6 +10,9 @@ final class TypeIdCodec { private const string ALPHABET = '0123456789abcdefghjkmnpqrstvwxyz'; + /** + * @throws \InvalidArgumentException + */ public static function decode(string $suffix): string { if (strlen($suffix) !== 26 || $suffix[0] > '7') { @@ -42,6 +45,10 @@ public static function decode(string $suffix): string return str_repeat("\0", 16 - strlen($decoded)) . $decoded; } + /** + * @throws \InvalidArgumentException + * @throws \LogicException + */ public static function encode(string $bytes): string { if (strlen($bytes) !== 16) { diff --git a/src/TBSL.php b/src/TBSL.php index de604e4..a54f87c 100644 --- a/src/TBSL.php +++ b/src/TBSL.php @@ -76,6 +76,9 @@ public static function generateRandom(int $machineId = 0): string return self::generate($machineId, false); } + /** + * @throws \Exception + */ public static function generateWithConfig(TBSLConfig $config): string { return self::generateInternal( @@ -158,6 +161,9 @@ private static function assertMachineId(int $machineId): void } } + /** + * @throws \Infocyph\UID\Exceptions\UIDException + */ private static function assertTimestamp(int $timestamp, int $machineId): void { if ($timestamp < 0 || $timestamp > intdiv(0x0fffffffffffffff - $machineId, 100)) { @@ -271,6 +277,9 @@ private static function resolveTail( } while (true); } + /** + * @throws \Infocyph\UID\Exceptions\UIDException + */ private static function waitUntilNextTimeSequence(int $last, ?GenerationContext $runtime): int { $deadline = $runtime?->waitDeadlineNanoseconds() From e73d2a33d76a206b5ae235333679aa89f82253a0 Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 09:56:50 +0600 Subject: [PATCH 12/26] docs: complete UUID and value-object inheritance contracts --- src/TypeID.php | 14 ++++++++++++++ src/ULID.php | 6 ++++++ src/UUID.php | 1 + src/Value/AbstractParsedIdValue.php | 7 +++++++ src/Value/SnowflakeValue.php | 5 +++++ src/Value/SonyflakeValue.php | 5 +++++ src/Value/TbslValue.php | 5 +++++ src/Value/UlidValue.php | 13 +++++++++++++ src/Value/UuidValue.php | 10 ++++++++++ 9 files changed, 66 insertions(+) diff --git a/src/TypeID.php b/src/TypeID.php index c41ae0c..a0f3521 100644 --- a/src/TypeID.php +++ b/src/TypeID.php @@ -10,6 +10,9 @@ final class TypeID { + /** + * @throws \Infocyph\UID\Exceptions\TypeIDException + */ public static function fromUuid(string $type, string $uuid): string { self::assertPrefix($type); @@ -23,6 +26,9 @@ public static function fromUuid(string $type, string $uuid): string return $type === '' ? $suffix : $type . '_' . $suffix; } + /** + * @throws \Exception + */ public static function generate(string $type = ''): string { return self::fromUuid($type, UUID::v7()); @@ -41,6 +47,7 @@ public static function isValid(string $typeId): bool /** * @return array{type:string, uuid:string, time:?DateTimeImmutable} + * @throws \Infocyph\UID\Exceptions\UUIDException */ public static function parse(string $typeId): array { @@ -56,6 +63,9 @@ public static function parse(string $typeId): array ]; } + /** + * @throws \Infocyph\UID\Exceptions\UUIDException + */ public static function toUuid(string $typeId): string { [, $suffix] = self::split($typeId); @@ -63,6 +73,9 @@ public static function toUuid(string $typeId): string return UUID::fromBytes(TypeIdCodec::decode($suffix)); } + /** + * @throws \Infocyph\UID\Exceptions\TypeIDException + */ private static function assertPrefix(string $type): void { $length = strlen($type); @@ -73,6 +86,7 @@ private static function assertPrefix(string $type): void /** * @return array{0:string,1:string} + * @throws \Infocyph\UID\Exceptions\TypeIDException */ private static function split(string $typeId): array { diff --git a/src/ULID.php b/src/ULID.php index c04d03a..bdcfe68 100644 --- a/src/ULID.php +++ b/src/ULID.php @@ -213,6 +213,9 @@ public static function toBytes(string $ulid): string return $bytes; } + /** + * @throws \Infocyph\UID\Exceptions\ULIDException + */ private static function assertTimestamp(int $timestamp): void { if ($timestamp < 0 || $timestamp > self::MAX_TIMESTAMP) { @@ -318,6 +321,9 @@ private static function resetRandomState(): void } } + /** + * @throws \Infocyph\UID\Exceptions\ULIDException + */ private static function waitForNextMillisecond(int $lastTimestamp): int { if ($lastTimestamp >= self::MAX_TIMESTAMP) { diff --git a/src/UUID.php b/src/UUID.php index 569d219..40a3a0b 100644 --- a/src/UUID.php +++ b/src/UUID.php @@ -684,6 +684,7 @@ private static function nextV7DefaultState(int $unixTsMs, bool $isExplicitTimest /** * Waits until the system clock moves to the next millisecond. + * @throws \Infocyph\UID\Exceptions\UUIDException */ private static function nextV7Timestamp(int $lastTimestamp): int { diff --git a/src/Value/AbstractParsedIdValue.php b/src/Value/AbstractParsedIdValue.php index 0f22796..03531f7 100644 --- a/src/Value/AbstractParsedIdValue.php +++ b/src/Value/AbstractParsedIdValue.php @@ -17,6 +17,9 @@ private string $value; + /** + * @throws \InvalidArgumentException + */ public function __construct(string $value) { $validator = $this->validator(); @@ -44,6 +47,7 @@ abstract protected function parser(): callable; */ abstract protected function validator(): callable; + #[\Override] public function compare(IdValueInterface|string $other): int { $otherValue = $other instanceof IdValueInterface ? $other->toString() : $other; @@ -51,16 +55,19 @@ public function compare(IdValueInterface|string $other): int return IdComparator::compare($this->value, $otherValue); } + #[\Override] public function getVersion(): ?int { return null; } + #[\Override] public function isSortable(): bool { return true; } + #[\Override] public function toString(): string { return $this->value; diff --git a/src/Value/SnowflakeValue.php b/src/Value/SnowflakeValue.php index fd53e09..33b0394 100644 --- a/src/Value/SnowflakeValue.php +++ b/src/Value/SnowflakeValue.php @@ -22,11 +22,13 @@ public function getDatacenterId(): int return $this->parsed['datacenter_id']; } + #[\Override] public function getMachineId(): string { return $this->parsed['datacenter_id'] . ':' . $this->parsed['worker_id']; } + #[\Override] public function getTimestamp(): DateTimeImmutable { return $this->parsed['time']; @@ -37,11 +39,13 @@ public function getWorkerId(): int return $this->parsed['worker_id']; } + #[\Override] protected function invalidMessage(): string { return 'Invalid Snowflake ID string'; } + #[\Override] protected function parser(): callable { return $this->customEpoch === null @@ -49,6 +53,7 @@ protected function parser(): callable : fn(string $id): array => Snowflake::parseWithEpoch($id, $this->customEpoch); } + #[\Override] protected function validator(): callable { return Snowflake::isValid(...); diff --git a/src/Value/SonyflakeValue.php b/src/Value/SonyflakeValue.php index ab8c43e..eea09e2 100644 --- a/src/Value/SonyflakeValue.php +++ b/src/Value/SonyflakeValue.php @@ -26,21 +26,25 @@ public function getFormat(): SonyflakeFormat return $this->format; } + #[\Override] public function getMachineId(): int { return $this->parsed['machine_id']; } + #[\Override] public function getTimestamp(): DateTimeImmutable { return $this->parsed['time']; } + #[\Override] protected function invalidMessage(): string { return 'Invalid Sonyflake ID string'; } + #[\Override] protected function parser(): callable { return $this->customEpoch === null @@ -48,6 +52,7 @@ protected function parser(): callable : fn(string $id): array => Sonyflake::parseWithEpoch($id, $this->customEpoch, $this->format); } + #[\Override] protected function validator(): callable { return Sonyflake::isValid(...); diff --git a/src/Value/TbslValue.php b/src/Value/TbslValue.php index 9844b5e..8236207 100644 --- a/src/Value/TbslValue.php +++ b/src/Value/TbslValue.php @@ -12,26 +12,31 @@ */ final readonly class TbslValue extends AbstractParsedIdValue { + #[\Override] public function getMachineId(): int { return $this->parsed['machineId']; } + #[\Override] public function getTimestamp(): DateTimeImmutable { return $this->parsed['time']; } + #[\Override] protected function invalidMessage(): string { return 'Invalid TBSL string'; } + #[\Override] protected function parser(): callable { return TBSL::parse(...); } + #[\Override] protected function validator(): callable { return TBSL::isValid(...); diff --git a/src/Value/UlidValue.php b/src/Value/UlidValue.php index 5725f10..86e033e 100644 --- a/src/Value/UlidValue.php +++ b/src/Value/UlidValue.php @@ -12,6 +12,9 @@ { private string $value; + /** + * @throws \InvalidArgumentException + */ public function __construct(string $value) { ULID::isValid($value) || throw new \InvalidArgumentException('Invalid ULID string'); @@ -23,6 +26,7 @@ public function __toString(): string return $this->toString(); } + #[\Override] public function compare(IdValueInterface|string $other): int { $otherValue = $other instanceof IdValueInterface ? $other->toString() : $other; @@ -30,26 +34,35 @@ public function compare(IdValueInterface|string $other): int return strcmp($this->value, $otherValue); } + #[\Override] public function getMachineId(): int|string|null { return null; } + /** + * @throws \Infocyph\UID\Exceptions\ULIDException + * @throws \Exception + */ + #[\Override] public function getTimestamp(): \DateTimeImmutable { return ULID::getTime($this->value); } + #[\Override] public function getVersion(): ?int { return null; } + #[\Override] public function isSortable(): bool { return true; } + #[\Override] public function toString(): string { return $this->value; diff --git a/src/Value/UuidValue.php b/src/Value/UuidValue.php index 9e8e588..04b2e0b 100644 --- a/src/Value/UuidValue.php +++ b/src/Value/UuidValue.php @@ -19,6 +19,10 @@ private string $value; + /** + * @throws \Infocyph\UID\Exceptions\UUIDException + * @throws \Exception + */ public function __construct(string $value) { $this->value = UUID::normalize($value); @@ -30,6 +34,7 @@ public function __toString(): string return $this->toString(); } + #[\Override] public function compare(IdValueInterface|string $other): int { $otherValue = $other instanceof IdValueInterface ? $other->toString() : UUID::normalize($other); @@ -37,11 +42,13 @@ public function compare(IdValueInterface|string $other): int return strcmp($this->value, $otherValue); } + #[\Override] public function getMachineId(): ?string { return $this->parsed['node']; } + #[\Override] public function getTimestamp(): ?DateTimeImmutable { $time = $this->parsed['time']; @@ -60,16 +67,19 @@ public function getTimestamp(): ?DateTimeImmutable } } + #[\Override] public function getVersion(): ?int { return $this->parsed['version']; } + #[\Override] public function isSortable(): bool { return in_array($this->getVersion(), [6, 7], true); } + #[\Override] public function toString(): string { return $this->value; From 34fae2e68acf2dded1dac927c7ce40681e3d63c9 Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 09:57:09 +0600 Subject: [PATCH 13/26] docs: complete helper and benchmark failure contracts --- benchmarks/BaseCodecBench.php | 10 ++++-- benchmarks/HotspotBench.php | 48 ++++++++++++++++++++++++++++ benchmarks/SequenceProviderBench.php | 16 ++++++++++ src/XID.php | 3 ++ src/functions.php | 45 ++++++++++++++++++++++++++ 5 files changed, 120 insertions(+), 2 deletions(-) diff --git a/benchmarks/BaseCodecBench.php b/benchmarks/BaseCodecBench.php index 9f3a925..a267e38 100644 --- a/benchmarks/BaseCodecBench.php +++ b/benchmarks/BaseCodecBench.php @@ -98,14 +98,20 @@ public function benchDecode(array $params): void ); } - /** @param array{length:int} $params */ + /** + * @param array{length:int} $params + * @throws \InvalidArgumentException + */ #[Bench\Revs(500), Bench\Iterations(5), Bench\ParamProviders('provideLengths')] public function benchNumericFromBytes(array $params): void { NumericIdCodec::decimalFromBytes($this->sample($params), $params['length']); } - /** @param array{length:int} $params */ + /** + * @param array{length:int} $params + * @throws \InvalidArgumentException + */ #[Bench\Revs(500), Bench\Iterations(5), Bench\ParamProviders('provideLengths')] public function benchNumericToBytes(array $params): void { diff --git a/benchmarks/HotspotBench.php b/benchmarks/HotspotBench.php index b75488f..7ae9dfe 100644 --- a/benchmarks/HotspotBench.php +++ b/benchmarks/HotspotBench.php @@ -70,12 +70,20 @@ public function __construct() $this->opaque = OpaqueId::fromInt(123456, 'bench'); } + /** + * @throws \InvalidArgumentException + * @throws \Exception + */ #[Bench\Revs(1000), Bench\Iterations(5)] public function benchCuid2(): void { CUID2::generate(); } + /** + * @throws \InvalidArgumentException + * @throws \Exception + */ #[Bench\Revs(100), Bench\Iterations(5)] public function benchCuid2ColdGenerate(): void { @@ -102,12 +110,18 @@ public function benchDeterministicId(): void DeterministicId::fromPayload('payload', 24, 'bench'); } + /** + * @throws \Exception + */ #[Bench\Revs(1000), Bench\Iterations(5)] public function benchKsuid(): void { KSUID::generate(); } + /** + * @throws \Exception + */ #[Bench\Revs(1000), Bench\Iterations(5)] public function benchNanoId(): void { @@ -120,6 +134,9 @@ public function benchObjectId(): void ObjectID::generate(); } + /** + * @throws \Exception + */ #[Bench\Revs(1000), Bench\Iterations(5)] public function benchOpaqueIdDecode(): void { @@ -132,6 +149,10 @@ public function benchOpaqueIdEncode(): void OpaqueId::fromInt(123456, 'bench'); } + /** + * @throws \Infocyph\UID\Exceptions\RandflakeException + * @throws \Infocyph\UID\Exceptions\FileLockException + */ #[Bench\Revs(250), Bench\Iterations(5)] public function benchRandflakeFilesystem(): void { @@ -156,12 +177,20 @@ public function benchRandomIdDefault61(): void RandomId::generate(); } + /** + * @throws \Infocyph\UID\Exceptions\SnowflakeException + * @throws \Infocyph\UID\Exceptions\FileLockException + */ #[Bench\Revs(250), Bench\Iterations(5)] public function benchSnowflakeFilesystem(): void { Snowflake::generateWithConfig($this->snowflakeConfig); } + /** + * @throws \Infocyph\UID\Exceptions\SonyflakeException + * @throws \Infocyph\UID\Exceptions\FileLockException + */ #[Bench\Revs(250), Bench\Iterations(5)] public function benchSonyflakeFilesystem(): void { @@ -180,36 +209,55 @@ public function benchTypeId(): void TypeID::generate('user'); } + /** + * @throws \Exception + */ #[Bench\Revs(1000), Bench\Iterations(5)] public function benchUlidMonotonic(): void { ULID::generateMonotonic(); } + /** + * @throws \Exception + */ #[Bench\Revs(1000), Bench\Iterations(5)] public function benchUlidRandom(): void { ULID::generateRandom(); } + /** + * @throws \Infocyph\UID\Exceptions\UUIDException + * @throws \Exception + */ #[Bench\Revs(1000), Bench\Iterations(5)] public function benchUuidV2(): void { UUID::v2(1001); } + /** + * @throws \Exception + */ #[Bench\Revs(1000), Bench\Iterations(5)] public function benchUuidV4(): void { UUID::v4(); } + /** + * @throws \Exception + */ #[Bench\Revs(1000), Bench\Iterations(5)] public function benchUuidV7(): void { UUID::v7(); } + /** + * @throws \Exception + */ #[Bench\Revs(1000), Bench\Iterations(5)] public function benchXid(): void { diff --git a/benchmarks/SequenceProviderBench.php b/benchmarks/SequenceProviderBench.php index d57bb48..56a4483 100644 --- a/benchmarks/SequenceProviderBench.php +++ b/benchmarks/SequenceProviderBench.php @@ -40,24 +40,40 @@ public function __construct() $this->randflakeInMemory = new RandflakeConfig(1, $leaseStart, $leaseEnd, $secret, $memory); } + /** + * @throws \Infocyph\UID\Exceptions\RandflakeException + * @throws \Infocyph\UID\Exceptions\FileLockException + */ #[Bench\Revs(500), Bench\Iterations(5)] public function benchRandflakeFilesystem(): void { Randflake::generateWithConfig($this->randflakeFilesystem); } + /** + * @throws \Infocyph\UID\Exceptions\RandflakeException + * @throws \Infocyph\UID\Exceptions\FileLockException + */ #[Bench\Revs(500), Bench\Iterations(5)] public function benchRandflakeInMemory(): void { Randflake::generateWithConfig($this->randflakeInMemory); } + /** + * @throws \Infocyph\UID\Exceptions\SnowflakeException + * @throws \Infocyph\UID\Exceptions\FileLockException + */ #[Bench\Revs(500), Bench\Iterations(5)] public function benchSnowflakeFilesystem(): void { Snowflake::generateWithConfig($this->snowflakeFilesystem); } + /** + * @throws \Infocyph\UID\Exceptions\SnowflakeException + * @throws \Infocyph\UID\Exceptions\FileLockException + */ #[Bench\Revs(500), Bench\Iterations(5)] public function benchSnowflakeInMemory(): void { diff --git a/src/XID.php b/src/XID.php index 0b6d879..bd1be3f 100644 --- a/src/XID.php +++ b/src/XID.php @@ -97,6 +97,9 @@ private static function counterBytes(): string return substr(pack('N', self::$counter), 1, 3); } + /** + * @throws \LogicException + */ private static function decodeText(string $xid): string { $buffer = 0; diff --git a/src/functions.php b/src/functions.php index f753dbc..abc69f0 100644 --- a/src/functions.php +++ b/src/functions.php @@ -11,16 +11,26 @@ use Infocyph\UID\Configuration\TBSLConfig; use Infocyph\UID\Enums\UlidGenerationMode; +/** + * @throws \InvalidArgumentException + * @throws \Exception + */ function cuid2(int $length = 24): string { return CUID2::generate($length); } +/** + * @throws \Exception + */ function ksuid(?DateTimeInterface $dateTime = null): string { return KSUID::generate($dateTime); } +/** + * @throws \Exception + */ function nano_id(int $length = 21): string { return NanoID::generate($length); @@ -31,6 +41,10 @@ function object_id(?DateTimeInterface $dateTime = null): string return ObjectID::generate($dateTime); } +/** + * @throws \Infocyph\UID\Exceptions\RandflakeException + * @throws \Infocyph\UID\Exceptions\FileLockException + */ function randflake(RandflakeConfig $config): string { return Randflake::generateWithConfig($config); @@ -61,6 +75,9 @@ function type_id(string $type = ''): string return TypeID::generate($type); } +/** + * @throws \Exception + */ function ulid( ?DateTimeInterface $dateTime = null, UlidGenerationMode $mode = UlidGenerationMode::MONOTONIC, @@ -68,11 +85,18 @@ function ulid( return ULID::generate($dateTime, $mode); } +/** + * @throws \Exception + */ function uuid1(?string $node = null): string { return UUID::v1($node); } +/** + * @throws \Infocyph\UID\Exceptions\UUIDException + * @throws \Exception + */ function uuid2( int $localIdentifier, int $localDomain = UUID::DCE_DOMAIN_PERSON, @@ -82,36 +106,57 @@ function uuid2( return UUID::v2($localIdentifier, $localDomain, $node, $clockSequence); } +/** + * @throws \Infocyph\UID\Exceptions\UUIDException + */ function uuid3(string $namespace, string $string): string { return UUID::v3($namespace, $string); } +/** + * @throws \Exception + */ function uuid4(): string { return UUID::v4(); } +/** + * @throws \Infocyph\UID\Exceptions\UUIDException + */ function uuid5(string $namespace, string $string): string { return UUID::v5($namespace, $string); } +/** + * @throws \Exception + */ function uuid6(?string $node = null): string { return UUID::v6($node); } +/** + * @throws \Exception + */ function uuid7(?DateTimeInterface $dateTime = null): string { return UUID::v7($dateTime); } +/** + * @throws \Exception + */ function uuid8(?string $node = null): string { return UUID::v8($node); } +/** + * @throws \Exception + */ function xid(): string { return XID::generate(); From 93e7bbd554a7a2d2e06ac9b51dfa452fcc2cc72a Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 09:57:36 +0600 Subject: [PATCH 14/26] docs: update Runwire integration and PHP 8.6 acceptance guidance --- README.md | 4 ++-- docs/compatibility.rst | 2 +- docs/framework-integration.rst | 6 +++--- docs/installation.rst | 2 +- docs/uuid.rst | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index c63b669..d4fbc1f 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ All-in-one unique ID toolkit for PHP. - Binary conversion and base encoders (`10`, `16`, `32`, `36`, `58`, `62`) - Pluggable sequence providers (filesystem, memory, PSR-16 cache, callback) - Explicit legacy/upstream Sonyflake and Randflake compatibility modes -- Optional PSR-20 clocks and Runwire 3.0 cooperative wait integration +- Optional PSR-20 clocks and Runwire 4.0.1 cooperative wait integration ## Requirements @@ -101,7 +101,7 @@ UID is protected by [PHPForge](https://github.com/infocyph/PHPForge), an automat tests, static and taint analysis, dependency auditing, architecture checks, and release readiness. Automated controls reduce risk but do not replace responsible disclosure or manual review. -Release acceptance also runs `php tests/smoke.php` with a production-only install on PHP 8.4 and 8.5. +Release acceptance also runs `php tests/smoke.php` with a production-only install on PHP 8.4, 8.5, and 8.6. One 100-cycle pass covers every generator and supported format, checking valid output, sample uniqueness, and relevant round trips. Long HTTP benchmarks and soak runs are not release gates. diff --git a/docs/compatibility.rst b/docs/compatibility.rst index c180324..91a44f4 100644 --- a/docs/compatibility.rst +++ b/docs/compatibility.rst @@ -69,6 +69,6 @@ Runtime Requirements - PHP 8.4 or newer on a 64-bit runtime. - The ctype extension is required. -- Runwire 3.0 and PSR-20 clocks are optional passed-instance integrations. +- Runwire 4.0.1 and PSR-20 clocks are optional passed-instance integrations. - No BCMath dependency. - PSR-16 is optional and needed only for the PSR simple-cache sequence provider. diff --git a/docs/framework-integration.rst b/docs/framework-integration.rst index f200221..a1d8abd 100644 --- a/docs/framework-integration.rst +++ b/docs/framework-integration.rst @@ -22,7 +22,7 @@ application domain that owns their node/machine ID, epoch, sequence provider and runtime policy. SnowflakeConfig, SonyflakeConfig, RandflakeConfig and TBSLConfig may receive a GenerationContext without changing the ordinary synchronous APIs. -Runwire 3.0 Integration +Runwire 4.0.1 Integration -------------------------- Runwire support is optional. UID never discovers a runtime globally and never @@ -58,8 +58,8 @@ operation. Construct bindings after worker creation/fork and do not retain a request binding in static provider selectors or worker-wide mutable state. The binding validates the process, request/runtime identity, request completion, active coroutine -capability, cancellation and deadlines using Runwire 3.0 public APIs. UID's -development fixture targets ``infocyph/runwire ^3.0``. +capability, cancellation and deadlines using Runwire 4.0.1 public APIs. UID's +development fixture targets ``infocyph/runwire ^4.0.1``. A CoroutineScope does not expose public request identity. Therefore the host boundary that owns both objects is responsible for pairing the correct scope with diff --git a/docs/installation.rst b/docs/installation.rst index 496f452..572567d 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -30,7 +30,7 @@ only the integration used by the application: .. code-block:: bash - composer require infocyph/runwire:^3.0 + composer require infocyph/runwire:^4.0.1 composer require psr/clock:^1.0 composer require psr/simple-cache:^3.0 diff --git a/docs/uuid.rst b/docs/uuid.rst index c6757e9..30aad17 100644 --- a/docs/uuid.rst +++ b/docs/uuid.rst @@ -142,7 +142,7 @@ Supported bases: ``10``, ``16``, ``32``, ``36``, ``58``, ``62``. GUID Helper ----------- -``UUID::guid(bool $trim = true)`` generates GUID-format text. +``UUID::guid(bool $trim = true)`` generates GUID-format text using the PHP CSPRNG on every platform. Exception Type -------------- From e202eafc71603bb94fe58aa2dacbee88b442a7a7 Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 09:58:56 +0600 Subject: [PATCH 15/26] fix: correct fixture syntax and PER formatting after hosted QA --- benchmarks/HotspotBench.php | 4 ++-- src/Randflake.php | 2 +- src/Snowflake.php | 2 +- src/Sonyflake.php | 2 +- tests/SequenceDomainLimitTest.php | 4 ++-- tests/SequenceProviderTest.php | 4 ++-- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/benchmarks/HotspotBench.php b/benchmarks/HotspotBench.php index 7ae9dfe..402bffc 100644 --- a/benchmarks/HotspotBench.php +++ b/benchmarks/HotspotBench.php @@ -5,8 +5,6 @@ namespace Infocyph\UID\Benchmarks; use Closure; -use ReflectionMethod; -use ReflectionProperty; use Infocyph\UID\Configuration\RandflakeConfig; use Infocyph\UID\Configuration\SnowflakeConfig; use Infocyph\UID\Configuration\SonyflakeConfig; @@ -28,6 +26,8 @@ use Infocyph\UID\UUID; use Infocyph\UID\XID; use PhpBench\Attributes as Bench; +use ReflectionMethod; +use ReflectionProperty; /** * PHPBench discovers this entry point by reflection. diff --git a/src/Randflake.php b/src/Randflake.php index 4f10e50..8309c85 100644 --- a/src/Randflake.php +++ b/src/Randflake.php @@ -598,7 +598,7 @@ private static function providerState( ): \ArrayObject { self::$lastTimestampByProvider ??= new \WeakMap(); - $state = self::$lastTimestampByProvider[$provider] ?? null; + $state = self::$lastTimestampByProvider[$provider] ?? null; if ($state === null) { /** @var \ArrayObject $state */ $state = new \ArrayObject(); diff --git a/src/Snowflake.php b/src/Snowflake.php index ea07af0..b7c9afc 100644 --- a/src/Snowflake.php +++ b/src/Snowflake.php @@ -390,7 +390,7 @@ private static function providerState( ): \ArrayObject { self::$lastStateByProvider ??= new \WeakMap(); - $state = self::$lastStateByProvider[$provider] ?? null; + $state = self::$lastStateByProvider[$provider] ?? null; if ($state === null) { /** @var \ArrayObject $state */ $state = new \ArrayObject(); diff --git a/src/Sonyflake.php b/src/Sonyflake.php index aeba87b..18c9d18 100644 --- a/src/Sonyflake.php +++ b/src/Sonyflake.php @@ -412,7 +412,7 @@ private static function providerState( ): \ArrayObject { self::$lastWallTimeByProvider ??= new \WeakMap(); - $state = self::$lastWallTimeByProvider[$provider] ?? null; + $state = self::$lastWallTimeByProvider[$provider] ?? null; if ($state === null) { /** @var \ArrayObject $state */ $state = new \ArrayObject(); diff --git a/tests/SequenceDomainLimitTest.php b/tests/SequenceDomainLimitTest.php index f73bead..3c63d2a 100644 --- a/tests/SequenceDomainLimitTest.php +++ b/tests/SequenceDomainLimitTest.php @@ -56,7 +56,7 @@ public function getMultiple(iterable $keys, mixed $default = null): iterable public function setMultiple(iterable $values, null|int|DateInterval $ttl = null): bool { foreach ($values as $key => $value) { - $this->set($key), $value, $ttl); + $this->set($key, $value, $ttl); } return true; @@ -66,7 +66,7 @@ public function setMultiple(iterable $values, null|int|DateInterval $ttl = null) public function deleteMultiple(iterable $keys): bool { foreach ($keys as $key) { - $this->delete($key)); + $this->delete($key); } return true; diff --git a/tests/SequenceProviderTest.php b/tests/SequenceProviderTest.php index 1a3175a..4b53e9c 100644 --- a/tests/SequenceProviderTest.php +++ b/tests/SequenceProviderTest.php @@ -40,7 +40,7 @@ public function delete(string $key): bool public function deleteMultiple(iterable $keys): bool { foreach ($keys as $key) { - $this->delete($key)); + $this->delete($key); } return true; @@ -94,7 +94,7 @@ public function set(string $key, mixed $value, null|int|DateInterval $ttl = null public function setMultiple(iterable $values, null|int|DateInterval $ttl = null): bool { foreach ($values as $key => $value) { - if (!$this->set($key), $value, $ttl)) { + if (!$this->set($key, $value, $ttl)) { return false; } } From 1d692fff4f7e66748d8042b1bc7c86c83128fd30 Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 09:59:36 +0600 Subject: [PATCH 16/26] fix: propagate newly exposed runtime and generator exception contracts --- benchmarks/BaseCodecBench.php | 12 +++++++++++- benchmarks/HotspotBench.php | 15 +++++++++++++++ src/Id.php | 9 +++++++++ src/NanoID.php | 2 +- src/Randflake.php | 8 ++++++++ src/RandomId.php | 3 +++ src/Runtime/GenerationContext.php | 11 +++++++++++ src/Runtime/RunwireBinding.php | 10 ++++++++++ src/Sequence/FilesystemSequenceProvider.php | 2 ++ 9 files changed, 70 insertions(+), 2 deletions(-) diff --git a/benchmarks/BaseCodecBench.php b/benchmarks/BaseCodecBench.php index a267e38..41793d9 100644 --- a/benchmarks/BaseCodecBench.php +++ b/benchmarks/BaseCodecBench.php @@ -87,7 +87,10 @@ public function benchDecimal(array $params): void BaseEncoder::encodeBytes($this->sample($params), 10); } - /** @param array{base:int,length:int} $params */ + /** + * @param array{base:int,length:int} $params + * @throws \InvalidArgumentException + */ #[Bench\Revs(250), Bench\Iterations(5), Bench\ParamProviders('provideBaseLengthPairs')] public function benchDecode(array $params): void { @@ -118,12 +121,19 @@ public function benchNumericToBytes(array $params): void DecimalBytes::toFixedBytes($this->decimal[$params['length']], $params['length']); } + /** + * @throws \InvalidArgumentException + */ #[Bench\Revs(1000), Bench\Iterations(5)] public function benchTypeIdDecode(): void { TypeIdCodec::decode($this->typeIdEncoded); } + /** + * @throws \InvalidArgumentException + * @throws \LogicException + */ #[Bench\Revs(1000), Bench\Iterations(5)] public function benchTypeIdEncode(): void { diff --git a/benchmarks/HotspotBench.php b/benchmarks/HotspotBench.php index 402bffc..9ed1144 100644 --- a/benchmarks/HotspotBench.php +++ b/benchmarks/HotspotBench.php @@ -104,6 +104,9 @@ public function benchCuid2FingerprintWarm(): void ($this->cuidFingerprint)(); } + /** + * @throws \InvalidArgumentException + */ #[Bench\Revs(1000), Bench\Iterations(5)] public function benchDeterministicId(): void { @@ -128,6 +131,9 @@ public function benchNanoId(): void NanoID::generate(); } + /** + * @throws \Infocyph\UID\Exceptions\ObjectIDException + */ #[Bench\Revs(1000), Bench\Iterations(5)] public function benchObjectId(): void { @@ -143,6 +149,9 @@ public function benchOpaqueIdDecode(): void OpaqueId::toInt($this->opaque, 'bench'); } + /** + * @throws \InvalidArgumentException + */ #[Bench\Revs(1000), Bench\Iterations(5)] public function benchOpaqueIdEncode(): void { @@ -197,12 +206,18 @@ public function benchSonyflakeFilesystem(): void Sonyflake::generateWithConfig($this->sonyflakeConfig); } + /** + * @throws \Exception + */ #[Bench\Revs(250), Bench\Iterations(5)] public function benchTbslFilesystem(): void { TBSL::generateWithConfig($this->tbslConfig); } + /** + * @throws \Exception + */ #[Bench\Revs(1000), Bench\Iterations(5)] public function benchTypeId(): void { diff --git a/src/Id.php b/src/Id.php index 38b45f9..848739c 100644 --- a/src/Id.php +++ b/src/Id.php @@ -25,6 +25,9 @@ public static function cuid2(int $length = 24): string return CUID2::generate($length); } + /** + * @throws \InvalidArgumentException + */ public static function deterministic(string $payload, int $length = 24, string $namespace = 'default'): string { return DeterministicId::fromPayload($payload, $length, $namespace); @@ -46,6 +49,9 @@ public static function nanoId(int $length = 21): string return NanoID::generate($length); } + /** + * @throws \Infocyph\UID\Exceptions\ObjectIDException + */ public static function objectId(?DateTimeInterface $dateTime = null): string { return ObjectID::generate($dateTime); @@ -101,6 +107,9 @@ public static function tbsl(?TBSLConfig $config = null): string return $config === null ? TBSL::generate() : TBSL::generateWithConfig($config); } + /** + * @throws \Exception + */ public static function typeId(string $type = ''): string { return TypeID::generate($type); diff --git a/src/NanoID.php b/src/NanoID.php index 16dcdc3..2b7d056 100644 --- a/src/NanoID.php +++ b/src/NanoID.php @@ -25,7 +25,7 @@ public static function generate(int $length = 21): string $byteLength = intdiv(($length * 3) + 3, 4); return substr( - rtrim(strtr(base64_encode(random_bytes($byteLength)), '+/', '-_'), '='), + rtrim(strtr(base64_encode(random_bytes(max(1, $byteLength))), '+/', '-_'), '='), 0, $length, ); diff --git a/src/Randflake.php b/src/Randflake.php index 8309c85..ce662dd 100644 --- a/src/Randflake.php +++ b/src/Randflake.php @@ -360,6 +360,7 @@ public static function toBytes( /** * @return array{0:int,1:int} * @throws \Infocyph\UID\Exceptions\RandflakeException + * @throws \Infocyph\UID\Exceptions\FileLockException */ private static function allocateSequence( SequenceProviderInterface $provider, @@ -409,6 +410,10 @@ private static function assertGenerationTime( } } + /** + * @throws \InvalidArgumentException + * @throws \Infocyph\UID\Exceptions\RandflakeException + */ private static function encodeGeneratedPayload( int $timestamp, int $nodeId, @@ -655,6 +660,9 @@ private static function roundKeys(string $secret): array return self::$roundKeyCache[$fingerprint] = $keys; } + /** + * @throws \InvalidArgumentException + */ private static function sparx( #[\SensitiveParameter] string $secret, diff --git a/src/RandomId.php b/src/RandomId.php index afe0dc9..d5668e2 100644 --- a/src/RandomId.php +++ b/src/RandomId.php @@ -10,6 +10,9 @@ final class RandomId { public const string DEFAULT_ALPHABET = 'abcdefghijklmnopqrstuvwxyz123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + /** + * @throws \InvalidArgumentException + */ public static function generate(int $length = 21, string $alphabet = self::DEFAULT_ALPHABET): string { return RandomSampler::generate($length, $alphabet); diff --git a/src/Runtime/GenerationContext.php b/src/Runtime/GenerationContext.php index 9a95bfb..d2daa60 100644 --- a/src/Runtime/GenerationContext.php +++ b/src/Runtime/GenerationContext.php @@ -49,16 +49,27 @@ public function nowMicroseconds(): int return ($seconds * 1_000_000) + (int) $now->format('u'); } + /** + * @throws \InvalidArgumentException + */ public function nowMilliseconds(): int { return intdiv($this->nowMicroseconds(), 1_000); } + /** + * @throws \InvalidArgumentException + */ public function nowSeconds(): int { return intdiv($this->nowMicroseconds(), 1_000_000); } + /** + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable + */ public function sleepMicroseconds(int $microseconds): void { $this->assertActive(); diff --git a/src/Runtime/RunwireBinding.php b/src/Runtime/RunwireBinding.php index 9c27f0d..9f8946a 100644 --- a/src/Runtime/RunwireBinding.php +++ b/src/Runtime/RunwireBinding.php @@ -15,6 +15,11 @@ final class RunwireBinding { private static ?TaskLocal $scopeProbe = null; + /** + * @throws \LogicException + * @throws \Infocyph\Runwire\Exception\CancelledException + * @throws \Throwable + */ public function __construct( public readonly RuntimeContext $runtime, public readonly ?RequestContext $request = null, @@ -57,6 +62,11 @@ public function assertActive(): void } } + /** + * @throws \LogicException + * @throws \Infocyph\Runwire\Exception\CancelledException + * @throws \Throwable + */ public function deadlineNanoseconds(): ?int { $this->assertActive(); diff --git a/src/Sequence/FilesystemSequenceProvider.php b/src/Sequence/FilesystemSequenceProvider.php index 7353b71..1d57b55 100644 --- a/src/Sequence/FilesystemSequenceProvider.php +++ b/src/Sequence/FilesystemSequenceProvider.php @@ -56,6 +56,8 @@ public function __construct( /** * @throws \Infocyph\UID\Exceptions\FileLockException * @throws \Infocyph\UID\Exceptions\SequenceTimestampException + * @throws \InvalidArgumentException + * @throws \Throwable */ #[\Override] public function next(string $type, int $machineId, int $timestamp, ?GenerationContext $runtime = null): int From 1d9377b476026e775a159e03fe12a3b509b209aa Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 09:59:55 +0600 Subject: [PATCH 17/26] fix: propagate codec and sequence provider exception contracts --- src/Sequence/PsrSimpleCacheSequenceProvider.php | 2 ++ src/Snowflake.php | 7 +++++++ src/Sonyflake.php | 2 ++ src/Support/BaseEncoder.php | 4 ++++ src/Support/DecimalBytes.php | 1 + src/Support/FileLock.php | 1 + src/Support/GetSequence.php | 2 ++ src/Support/RandomSampler.php | 6 ++++++ src/Support/Sparx64.php | 6 ++++++ src/TypeID.php | 4 ++++ 10 files changed, 35 insertions(+) diff --git a/src/Sequence/PsrSimpleCacheSequenceProvider.php b/src/Sequence/PsrSimpleCacheSequenceProvider.php index 451bb7a..6eca152 100644 --- a/src/Sequence/PsrSimpleCacheSequenceProvider.php +++ b/src/Sequence/PsrSimpleCacheSequenceProvider.php @@ -50,6 +50,7 @@ public function __construct( /** * @throws FileLockException + * @throws \InvalidArgumentException */ #[\Override] public function next(string $type, int $machineId, int $timestamp, ?GenerationContext $runtime = null): int @@ -124,6 +125,7 @@ private static function nextSequence(?array $state, int $timestamp, string $key) /** * @return resource * @throws FileLockException + * @throws \Throwable */ private function acquireLock(string $key, ?GenerationContext $runtime) { diff --git a/src/Snowflake.php b/src/Snowflake.php index b7c9afc..13f537e 100644 --- a/src/Snowflake.php +++ b/src/Snowflake.php @@ -82,6 +82,7 @@ public static function generate(int $datacenter = 0, int $workerId = 0): string * Generates Snowflake using configuration object. * * @throws SnowflakeException|FileLockException + * @throws \UnexpectedValueException */ public static function generateWithConfig(SnowflakeConfig $config): string { @@ -221,6 +222,9 @@ private static function assertTimestampRange(int $currentTime, int $startTimesta } } + /** + * @throws \Infocyph\UID\Exceptions\SnowflakeException + */ private static function decodeNumericBase(string $encoded, int $base): string { $id = NumericConversion::decimalFromBase( @@ -233,6 +237,9 @@ private static function decodeNumericBase(string $encoded, int $base): string return self::assertDecodedId($id); } + /** + * @throws \Infocyph\UID\Exceptions\SnowflakeException + */ private static function decodeNumericBytes(string $bytes): string { $id = NumericConversion::decimalFromBytes( diff --git a/src/Sonyflake.php b/src/Sonyflake.php index 18c9d18..b29699b 100644 --- a/src/Sonyflake.php +++ b/src/Sonyflake.php @@ -92,6 +92,7 @@ public static function generate(int $machineId = 0): string * Generates Sonyflake using configuration object. * * @throws SonyflakeException|FileLockException + * @throws \UnexpectedValueException */ public static function generateWithConfig(SonyflakeConfig $config): string { @@ -187,6 +188,7 @@ public static function toBytes(string $id): string /** * @return array{0:int,1:int} * @throws \Infocyph\UID\Exceptions\SonyflakeException + * @throws \Infocyph\UID\Exceptions\FileLockException */ private static function allocateSequence( SequenceProviderInterface $provider, diff --git a/src/Support/BaseEncoder.php b/src/Support/BaseEncoder.php index cb222d1..14a7102 100644 --- a/src/Support/BaseEncoder.php +++ b/src/Support/BaseEncoder.php @@ -54,6 +54,10 @@ public static function decodeToBytes(string $encoded, int $base, int $bytesLengt return self::decodeRadix($encoded, $base, $bytesLength); } + /** + * @throws \InvalidArgumentException + * @throws \LogicException + */ public static function encodeBytes(string $bytes, int $base): string { self::assertByteLength(strlen($bytes)); diff --git a/src/Support/DecimalBytes.php b/src/Support/DecimalBytes.php index 3e267bf..30679e8 100644 --- a/src/Support/DecimalBytes.php +++ b/src/Support/DecimalBytes.php @@ -26,6 +26,7 @@ public static function fromBytes(string $bytes): string /** * @throws \InvalidArgumentException + * @throws \LogicException */ public static function fromLittleEndianSigned64(string $bytes): string { diff --git a/src/Support/FileLock.php b/src/Support/FileLock.php index 9c41a0b..d80123f 100644 --- a/src/Support/FileLock.php +++ b/src/Support/FileLock.php @@ -96,6 +96,7 @@ private static function lockDeadline(?int $timeoutMicros, ?GenerationContext $ru /** * @return resource * @throws FileLockException + * @throws \Throwable */ private static function openVerified(string $path, string $errorMessage) { diff --git a/src/Support/GetSequence.php b/src/Support/GetSequence.php index 9db4622..ef19262 100644 --- a/src/Support/GetSequence.php +++ b/src/Support/GetSequence.php @@ -34,6 +34,7 @@ public static function setSequenceProvider(SequenceProviderInterface $provider): /** * Use the default filesystem-backed sequence provider. + * @throws \InvalidArgumentException */ public static function useFilesystemSequenceProvider( ?string $baseDirectory = null, @@ -71,6 +72,7 @@ public static function useSequenceCallback(callable $callback): void /** * Use PSR-16 simple cache-backed sequence provider. + * @throws \InvalidArgumentException */ public static function useSimpleCacheSequenceProvider( CacheInterface $cache, diff --git a/src/Support/RandomSampler.php b/src/Support/RandomSampler.php index 4b8ec2b..f3b32c9 100644 --- a/src/Support/RandomSampler.php +++ b/src/Support/RandomSampler.php @@ -29,6 +29,9 @@ public static function assertAlphabet(string $alphabet): void } } + /** + * @throws \InvalidArgumentException + */ public static function containsOnly(string $value, string $alphabet): bool { self::assertAlphabet($alphabet); @@ -77,6 +80,9 @@ public static function generate(int $length, string $alphabet): string return $result; } + /** + * @throws \InvalidArgumentException + */ public static function mapBytes(string $bytes, string $alphabet): string { self::assertAlphabet($alphabet); diff --git a/src/Support/Sparx64.php b/src/Support/Sparx64.php index 2f637fe..5f11200 100644 --- a/src/Support/Sparx64.php +++ b/src/Support/Sparx64.php @@ -38,6 +38,9 @@ public function __construct(#[\SensitiveParameter] string $key) } } + /** + * @throws \InvalidArgumentException + */ public function decrypt(string $block): string { $state = self::unpackBlock($block); @@ -61,6 +64,9 @@ public function decrypt(string $block): string return self::packBlock($state); } + /** + * @throws \InvalidArgumentException + */ public function encrypt(string $block): string { $state = self::unpackBlock($block); diff --git a/src/TypeID.php b/src/TypeID.php index a0f3521..c9be2c4 100644 --- a/src/TypeID.php +++ b/src/TypeID.php @@ -48,6 +48,8 @@ public static function isValid(string $typeId): bool /** * @return array{type:string, uuid:string, time:?DateTimeImmutable} * @throws \Infocyph\UID\Exceptions\UUIDException + * @throws \Infocyph\UID\Exceptions\TypeIDException + * @throws \InvalidArgumentException */ public static function parse(string $typeId): array { @@ -65,6 +67,8 @@ public static function parse(string $typeId): array /** * @throws \Infocyph\UID\Exceptions\UUIDException + * @throws \Infocyph\UID\Exceptions\TypeIDException + * @throws \InvalidArgumentException */ public static function toUuid(string $typeId): string { From e4e875fe91b5d3ce2ada510db86748158f907d2d Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 10:00:16 +0600 Subject: [PATCH 18/26] fix: resolve remaining recorded test and value object findings --- src/Value/SnowflakeValue.php | 3 +++ src/Value/SonyflakeValue.php | 3 +++ src/functions.php | 6 ++++++ tests/FilesystemSequenceV5Test.php | 12 ++++++------ tests/ReleaseBoundaryTest.php | 11 ++++++----- tests/SequenceDomainLimitTest.php | 3 ++- tests/SequenceProviderTest.php | 3 ++- tests/SequenceSafetyTest.php | 4 +--- tests/UUIDTest.php | 4 ++-- 9 files changed, 31 insertions(+), 18 deletions(-) diff --git a/src/Value/SnowflakeValue.php b/src/Value/SnowflakeValue.php index 33b0394..ea3703c 100644 --- a/src/Value/SnowflakeValue.php +++ b/src/Value/SnowflakeValue.php @@ -12,6 +12,9 @@ */ final readonly class SnowflakeValue extends AbstractParsedIdValue { + /** + * @throws \InvalidArgumentException + */ public function __construct(string $value, private ?int $customEpoch = null) { parent::__construct($value); diff --git a/src/Value/SonyflakeValue.php b/src/Value/SonyflakeValue.php index eea09e2..eb1eb07 100644 --- a/src/Value/SonyflakeValue.php +++ b/src/Value/SonyflakeValue.php @@ -13,6 +13,9 @@ */ final readonly class SonyflakeValue extends AbstractParsedIdValue { + /** + * @throws \InvalidArgumentException + */ public function __construct( string $value, private ?int $customEpoch = null, diff --git a/src/functions.php b/src/functions.php index abc69f0..6288843 100644 --- a/src/functions.php +++ b/src/functions.php @@ -36,6 +36,9 @@ function nano_id(int $length = 21): string return NanoID::generate($length); } +/** + * @throws \Infocyph\UID\Exceptions\ObjectIDException + */ function object_id(?DateTimeInterface $dateTime = null): string { return ObjectID::generate($dateTime); @@ -70,6 +73,9 @@ function tbsl(?TBSLConfig $config = null): string return $config === null ? TBSL::generate() : TBSL::generateWithConfig($config); } +/** + * @throws \Exception + */ function type_id(string $type = ''): string { return TypeID::generate($type); diff --git a/tests/FilesystemSequenceV5Test.php b/tests/FilesystemSequenceV5Test.php index a7cb95c..d831cb2 100644 --- a/tests/FilesystemSequenceV5Test.php +++ b/tests/FilesystemSequenceV5Test.php @@ -100,9 +100,9 @@ $json !== false || throw new RuntimeException('Unable to read child output'); $values = json_decode($json, true, 512, JSON_THROW_ON_ERROR); is_array($values) || throw new RuntimeException('Invalid child output'); - foreach ($values as $value) { - is_int($value) || throw new RuntimeException('Invalid child value'); - $allocations[] = $value; + foreach (array_keys($values) as $index) { + is_int($values[$index]) || throw new RuntimeException('Invalid child value'); + $allocations[] = $values[$index]; } } @@ -164,9 +164,9 @@ $json !== false || throw new RuntimeException('Unable to read child output'); $values = json_decode($json, true, 512, JSON_THROW_ON_ERROR); is_array($values) || throw new RuntimeException('Invalid child output'); - foreach ($values as $value) { - is_string($value) || throw new RuntimeException('Invalid child value'); - $ids[] = $value; + foreach (array_keys($values) as $index) { + is_string($values[$index]) || throw new RuntimeException('Invalid child value'); + $ids[] = $values[$index]; } } diff --git a/tests/ReleaseBoundaryTest.php b/tests/ReleaseBoundaryTest.php index 4e413ed..1fbb3f1 100644 --- a/tests/ReleaseBoundaryTest.php +++ b/tests/ReleaseBoundaryTest.php @@ -114,21 +114,22 @@ public function now(): DateTimeImmutable test('Randflake rechecks live domain state after reentrant provider work', function (\Infocyph\UID\Enums\RandflakeFormat $format): void { $nested = false; - $config = null; + $fixture = new class { + public \Infocyph\UID\Configuration\RandflakeConfig $config; + }; $nestedId = null; $provider = new \Infocyph\UID\Sequence\CallbackSequenceProvider( - function (string $type, int $machineId, int $timestamp) use (&$nested, &$config, &$nestedId): int { + function (string $type, int $machineId, int $timestamp) use (&$nested, $fixture, &$nestedId): int { unset($type, $machineId, $timestamp); if (!$nested) { $nested = true; - $config !== null || throw new LogicException('Missing reentrant configuration'); - $nestedId = \Infocyph\UID\Randflake::generateWithConfig($config); + $nestedId = \Infocyph\UID\Randflake::generateWithConfig($fixture->config); } return 1; }, ); - $config = new \Infocyph\UID\Configuration\RandflakeConfig( + $config = $fixture->config = new \Infocyph\UID\Configuration\RandflakeConfig( 0, 1_730_000_000, 1_730_000_005, '0123456789abcdef', sequenceProvider: $provider, runtime: new GenerationContext(clock: new ReleaseBoundaryClock(new DateTimeImmutable('@1730000001'))), diff --git a/tests/SequenceDomainLimitTest.php b/tests/SequenceDomainLimitTest.php index 3c63d2a..1d107e1 100644 --- a/tests/SequenceDomainLimitTest.php +++ b/tests/SequenceDomainLimitTest.php @@ -51,11 +51,12 @@ public function getMultiple(iterable $keys, mixed $default = null): iterable } } - /** @param iterable $values */ + /** @param iterable $values */ #[\Override] public function setMultiple(iterable $values, null|int|DateInterval $ttl = null): bool { foreach ($values as $key => $value) { + is_string($key) || throw new InvalidArgumentException('Cache key must be a string'); $this->set($key, $value, $ttl); } diff --git a/tests/SequenceProviderTest.php b/tests/SequenceProviderTest.php index 4b53e9c..9f89fe8 100644 --- a/tests/SequenceProviderTest.php +++ b/tests/SequenceProviderTest.php @@ -89,11 +89,12 @@ public function set(string $key, mixed $value, null|int|DateInterval $ttl = null return true; } - /** @param iterable $values */ + /** @param iterable $values */ #[\Override] public function setMultiple(iterable $values, null|int|DateInterval $ttl = null): bool { foreach ($values as $key => $value) { + is_string($key) || throw new InvalidArgumentException('Cache key must be a string'); if (!$this->set($key, $value, $ttl)) { return false; } diff --git a/tests/SequenceSafetyTest.php b/tests/SequenceSafetyTest.php index d4d5a66..1341684 100644 --- a/tests/SequenceSafetyTest.php +++ b/tests/SequenceSafetyTest.php @@ -41,9 +41,7 @@ expect($failure)->toBeInstanceOf(FileLockException::class) ->and(file_get_contents($target))->toBe('unchanged'); } finally { - if (is_resource($handle)) { - fclose($handle); - } + fclose($handle); unlink($path); unlink($path . '.original'); unlink($target); diff --git a/tests/UUIDTest.php b/tests/UUIDTest.php index a94cd39..773678c 100644 --- a/tests/UUIDTest.php +++ b/tests/UUIDTest.php @@ -189,10 +189,10 @@ function (array $arguments): void { $node = UUID::getNode(); $uuid = UUID::v1(); $parsedNode = UUID::parse($uuid)['node']; + $parsedNode !== null || throw new RuntimeException('UUID v1 node missing'); expect(hexdec(substr($node, 0, 2)) & 0x01)->toBe(0x01) - ->and($parsedNode)->toBeString() - ->and(hexdec(substr($parsedNode ?? '', 0, 2)) & 0x01)->toBe(0x01); + ->and(hexdec(substr($parsedNode, 0, 2)) & 0x01)->toBe(0x01); }); test('GUID', function () { From 546d23582fba0683ff3c91c643027d25b6bba54e Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 10:02:05 +0600 Subject: [PATCH 19/26] Fix QA resource ownership and remaining test type contracts --- tests/ReleaseBoundaryTest.php | 5 +++-- tests/RuntimeIntegrationTest.php | 1 + tests/SequenceDomainLimitTest.php | 5 ++++- tests/SequenceProviderTest.php | 5 ++++- tests/SequenceSafetyTest.php | 4 +++- tests/UUIDTest.php | 25 ++++++++++++------------- tests/V5CompatibilityTest.php | 3 +-- 7 files changed, 28 insertions(+), 20 deletions(-) diff --git a/tests/ReleaseBoundaryTest.php b/tests/ReleaseBoundaryTest.php index 1fbb3f1..ec436fc 100644 --- a/tests/ReleaseBoundaryTest.php +++ b/tests/ReleaseBoundaryTest.php @@ -115,7 +115,7 @@ public function now(): DateTimeImmutable test('Randflake rechecks live domain state after reentrant provider work', function (\Infocyph\UID\Enums\RandflakeFormat $format): void { $nested = false; $fixture = new class { - public \Infocyph\UID\Configuration\RandflakeConfig $config; + public ?\Infocyph\UID\Configuration\RandflakeConfig $config = null; }; $nestedId = null; $provider = new \Infocyph\UID\Sequence\CallbackSequenceProvider( @@ -123,7 +123,8 @@ function (string $type, int $machineId, int $timestamp) use (&$nested, $fixture, unset($type, $machineId, $timestamp); if (!$nested) { $nested = true; - $nestedId = \Infocyph\UID\Randflake::generateWithConfig($fixture->config); + $config = $fixture->config ?? throw new LogicException('Missing reentrant configuration'); + $nestedId = \Infocyph\UID\Randflake::generateWithConfig($config); } return 1; diff --git a/tests/RuntimeIntegrationTest.php b/tests/RuntimeIntegrationTest.php index 33e53af..dc7d87b 100644 --- a/tests/RuntimeIntegrationTest.php +++ b/tests/RuntimeIntegrationTest.php @@ -155,6 +155,7 @@ static function (string $type, int $machineId, int $timestamp) use (&$allocation /** + * @throws \UnexpectedValueException * @throws \Infocyph\UID\Exceptions\SnowflakeException * @throws \Infocyph\UID\Exceptions\FileLockException */ diff --git a/tests/SequenceDomainLimitTest.php b/tests/SequenceDomainLimitTest.php index 1d107e1..36a272a 100644 --- a/tests/SequenceDomainLimitTest.php +++ b/tests/SequenceDomainLimitTest.php @@ -51,7 +51,10 @@ public function getMultiple(iterable $keys, mixed $default = null): iterable } } - /** @param iterable $values */ + /** + * @param iterable $values + * @throws InvalidArgumentException + */ #[\Override] public function setMultiple(iterable $values, null|int|DateInterval $ttl = null): bool { diff --git a/tests/SequenceProviderTest.php b/tests/SequenceProviderTest.php index 9f89fe8..7631d66 100644 --- a/tests/SequenceProviderTest.php +++ b/tests/SequenceProviderTest.php @@ -89,7 +89,10 @@ public function set(string $key, mixed $value, null|int|DateInterval $ttl = null return true; } - /** @param iterable $values */ + /** + * @param iterable $values + * @throws InvalidArgumentException + */ #[\Override] public function setMultiple(iterable $values, null|int|DateInterval $ttl = null): bool { diff --git a/tests/SequenceSafetyTest.php b/tests/SequenceSafetyTest.php index 1341684..f0628e3 100644 --- a/tests/SequenceSafetyTest.php +++ b/tests/SequenceSafetyTest.php @@ -41,7 +41,9 @@ expect($failure)->toBeInstanceOf(FileLockException::class) ->and(file_get_contents($target))->toBe('unchanged'); } finally { - fclose($handle); + if (get_resource_type($handle) === 'stream') { + fclose($handle); + } unlink($path); unlink($path . '.original'); unlink($target); diff --git a/tests/UUIDTest.php b/tests/UUIDTest.php index 773678c..af95083 100644 --- a/tests/UUIDTest.php +++ b/tests/UUIDTest.php @@ -64,20 +64,19 @@ expect(array_unique($ids))->toHaveCount(300); }); -test('UUID v2 rejects invalid fields and uncoordinated fixed nodes', /** @param array{0:int,1?:int,2?:string|null,3?:int} $arguments */ -function (array $arguments): void { - expect(fn(): string => UUID::v2(...$arguments))->toThrow(\Infocyph\UID\Exceptions\UUIDException::class); +test('UUID v2 rejects invalid fields and uncoordinated fixed nodes', function (int $identifier, int $domain = 0, ?string $node = null, ?int $sequence = null): void { + expect(fn(): string => UUID::v2($identifier, $domain, $node, $sequence))->toThrow(\Infocyph\UID\Exceptions\UUIDException::class); })->with([ - [[-1]], - [[0x100000000]], - [[1, -1]], - [[1, 3]], - [[1, 256]], - [[1, 0, null, -1]], - [[1, 0, null, 64]], - [[1, 0, 'abcdef123456']], - [[1, 0, "abcdef123456\n", 0]], - [[1, 0, 'invalid-node', 0]], + [-1], + [0x100000000], + [1, -1], + [1, 3], + [1, 256], + [1, 0, null, -1], + [1, 0, null, 64], + [1, 0, 'abcdef123456'], + [1, 0, "abcdef123456\n", 0], + [1, 0, 'invalid-node', 0], ]); $ns = UUID::v4(); diff --git a/tests/V5CompatibilityTest.php b/tests/V5CompatibilityTest.php index dbb6c90..ebca07d 100644 --- a/tests/V5CompatibilityTest.php +++ b/tests/V5CompatibilityTest.php @@ -215,8 +215,7 @@ ]; foreach ($contracts as $class => $expectedPrefix) { - $constructor = (new ReflectionClass($class))->getConstructor(); - expect($constructor)->not->toBeNull(); + $constructor = new ReflectionMethod($class, '__construct'); $names = array_map( static fn(ReflectionParameter $parameter): string => $parameter->getName(), From 45821bc696c2d01a33a197f5880b36a870a83977 Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 10:02:23 +0600 Subject: [PATCH 20/26] Propagate codec and identifier exception contracts --- benchmarks/BaseCodecBench.php | 36 +++++++++++++++---- benchmarks/HotspotBench.php | 11 ++++++ benchmarks/SequenceProviderBench.php | 2 ++ src/Id.php | 9 +++++ src/OpaqueId.php | 1 + src/Randflake.php | 9 +++++ src/RandomId.php | 3 ++ .../PsrSimpleCacheSequenceProvider.php | 1 + 8 files changed, 66 insertions(+), 6 deletions(-) diff --git a/benchmarks/BaseCodecBench.php b/benchmarks/BaseCodecBench.php index 41793d9..ab02175 100644 --- a/benchmarks/BaseCodecBench.php +++ b/benchmarks/BaseCodecBench.php @@ -45,42 +45,66 @@ public function __construct() $this->typeIdEncoded = TypeIdCodec::encode($this->samples[16]); } - /** @param array{length:int} $params */ + /** + * @param array{length:int} $params + * @throws \InvalidArgumentException + * @throws \LogicException + */ #[Bench\Revs(1000), Bench\Iterations(5), Bench\ParamProviders('provideLengths')] public function benchBase16(array $params): void { BaseEncoder::encodeBytes($this->sample($params), 16); } - /** @param array{length:int} $params */ + /** + * @param array{length:int} $params + * @throws \InvalidArgumentException + * @throws \LogicException + */ #[Bench\Revs(1000), Bench\Iterations(5), Bench\ParamProviders('provideLengths')] public function benchBase32(array $params): void { BaseEncoder::encodeBytes($this->sample($params), 32); } - /** @param array{length:int} $params */ + /** + * @param array{length:int} $params + * @throws \InvalidArgumentException + * @throws \LogicException + */ #[Bench\Revs(1000), Bench\Iterations(5), Bench\ParamProviders('provideLengths')] public function benchBase36(array $params): void { BaseEncoder::encodeBytes($this->sample($params), 36); } - /** @param array{length:int} $params */ + /** + * @param array{length:int} $params + * @throws \InvalidArgumentException + * @throws \LogicException + */ #[Bench\Revs(1000), Bench\Iterations(5), Bench\ParamProviders('provideLengths')] public function benchBase58(array $params): void { BaseEncoder::encodeBytes($this->sample($params), 58); } - /** @param array{length:int} $params */ + /** + * @param array{length:int} $params + * @throws \InvalidArgumentException + * @throws \LogicException + */ #[Bench\Revs(1000), Bench\Iterations(5), Bench\ParamProviders('provideLengths')] public function benchBase62(array $params): void { BaseEncoder::encodeBytes($this->sample($params), 62); } - /** @param array{length:int} $params */ + /** + * @param array{length:int} $params + * @throws \InvalidArgumentException + * @throws \LogicException + */ #[Bench\Revs(1000), Bench\Iterations(5), Bench\ParamProviders('provideLengths')] public function benchDecimal(array $params): void { diff --git a/benchmarks/HotspotBench.php b/benchmarks/HotspotBench.php index 9ed1144..f850e83 100644 --- a/benchmarks/HotspotBench.php +++ b/benchmarks/HotspotBench.php @@ -168,18 +168,27 @@ public function benchRandflakeFilesystem(): void Randflake::generateWithConfig($this->randflakeConfig); } + /** + * @throws \InvalidArgumentException + */ #[Bench\Revs(1000), Bench\Iterations(5)] public function benchRandomId62(): void { RandomId::generate(21, '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'); } + /** + * @throws \InvalidArgumentException + */ #[Bench\Revs(1000), Bench\Iterations(5)] public function benchRandomId64(): void { RandomId::generate(21, '_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'); } + /** + * @throws \InvalidArgumentException + */ #[Bench\Revs(1000), Bench\Iterations(5)] public function benchRandomIdDefault61(): void { @@ -189,6 +198,7 @@ public function benchRandomIdDefault61(): void /** * @throws \Infocyph\UID\Exceptions\SnowflakeException * @throws \Infocyph\UID\Exceptions\FileLockException + * @throws \UnexpectedValueException */ #[Bench\Revs(250), Bench\Iterations(5)] public function benchSnowflakeFilesystem(): void @@ -199,6 +209,7 @@ public function benchSnowflakeFilesystem(): void /** * @throws \Infocyph\UID\Exceptions\SonyflakeException * @throws \Infocyph\UID\Exceptions\FileLockException + * @throws \UnexpectedValueException */ #[Bench\Revs(250), Bench\Iterations(5)] public function benchSonyflakeFilesystem(): void diff --git a/benchmarks/SequenceProviderBench.php b/benchmarks/SequenceProviderBench.php index 56a4483..2528066 100644 --- a/benchmarks/SequenceProviderBench.php +++ b/benchmarks/SequenceProviderBench.php @@ -63,6 +63,7 @@ public function benchRandflakeInMemory(): void /** * @throws \Infocyph\UID\Exceptions\SnowflakeException * @throws \Infocyph\UID\Exceptions\FileLockException + * @throws \UnexpectedValueException */ #[Bench\Revs(500), Bench\Iterations(5)] public function benchSnowflakeFilesystem(): void @@ -73,6 +74,7 @@ public function benchSnowflakeFilesystem(): void /** * @throws \Infocyph\UID\Exceptions\SnowflakeException * @throws \Infocyph\UID\Exceptions\FileLockException + * @throws \UnexpectedValueException */ #[Bench\Revs(500), Bench\Iterations(5)] public function benchSnowflakeInMemory(): void diff --git a/src/Id.php b/src/Id.php index 848739c..0b4a849 100644 --- a/src/Id.php +++ b/src/Id.php @@ -66,6 +66,9 @@ public static function randflake(RandflakeConfig $config): string return Randflake::generateWithConfig($config); } + /** + * @throws \InvalidArgumentException + */ public static function random( int $length = 21, string $alphabet = RandomId::DEFAULT_ALPHABET, @@ -78,6 +81,9 @@ public static function snowflake(?SnowflakeConfig $config = null): string return $config === null ? Snowflake::generate() : Snowflake::generateWithConfig($config); } + /** + * @throws \InvalidArgumentException + */ public static function snowflakeValue(?SnowflakeConfig $config = null): SnowflakeValue { return new SnowflakeValue(self::snowflake($config), $config?->resolveCustomEpochMs()); @@ -88,6 +94,9 @@ public static function sonyflake(?SonyflakeConfig $config = null): string return $config === null ? Sonyflake::generate() : Sonyflake::generateWithConfig($config); } + /** + * @throws \InvalidArgumentException + */ public static function sonyflakeValue(?SonyflakeConfig $config = null): SonyflakeValue { $format = SonyflakeFormat::UID; diff --git a/src/OpaqueId.php b/src/OpaqueId.php index 476275f..cc0725e 100644 --- a/src/OpaqueId.php +++ b/src/OpaqueId.php @@ -12,6 +12,7 @@ final class OpaqueId /** * Encodes an integer in a hashid-style opaque token. * @throws \InvalidArgumentException + * @throws \LogicException */ public static function fromInt(int $value, string $salt = ''): string { diff --git a/src/Randflake.php b/src/Randflake.php index ce662dd..72b741d 100644 --- a/src/Randflake.php +++ b/src/Randflake.php @@ -54,6 +54,7 @@ final class Randflake /** * @throws RandflakeException + * @throws \LogicException */ public static function decodeString( string $id, @@ -95,6 +96,8 @@ static function (string $message, \InvalidArgumentException $exception): Randfla /** * @throws RandflakeException + * @throws \InvalidArgumentException + * @throws \LogicException */ public static function encodeString( string $id, @@ -114,6 +117,7 @@ public static function encodeString( /** * @throws RandflakeException + * @throws \LogicException */ public static function fromBase( string $encoded, @@ -144,6 +148,7 @@ public static function fromBase( /** * @throws RandflakeException + * @throws \LogicException */ public static function fromBytes( string $bytes, @@ -314,6 +319,8 @@ public static function parseString( /** * @throws RandflakeException + * @throws \InvalidArgumentException + * @throws \LogicException */ public static function toBase( string $id, @@ -413,6 +420,7 @@ private static function assertGenerationTime( /** * @throws \InvalidArgumentException * @throws \Infocyph\UID\Exceptions\RandflakeException + * @throws \LogicException */ private static function encodeGeneratedPayload( int $timestamp, @@ -434,6 +442,7 @@ private static function encodeGeneratedPayload( /** * @throws RandflakeException|FileLockException + * @throws \InvalidArgumentException */ private static function generateInternal( int $nodeId, diff --git a/src/RandomId.php b/src/RandomId.php index d5668e2..e0407ab 100644 --- a/src/RandomId.php +++ b/src/RandomId.php @@ -18,6 +18,9 @@ public static function generate(int $length = 21, string $alphabet = self::DEFAU return RandomSampler::generate($length, $alphabet); } + /** + * @throws \InvalidArgumentException + */ public static function isValid( string $id, ?int $length = null, diff --git a/src/Sequence/PsrSimpleCacheSequenceProvider.php b/src/Sequence/PsrSimpleCacheSequenceProvider.php index 6eca152..2ccc8f8 100644 --- a/src/Sequence/PsrSimpleCacheSequenceProvider.php +++ b/src/Sequence/PsrSimpleCacheSequenceProvider.php @@ -51,6 +51,7 @@ public function __construct( /** * @throws FileLockException * @throws \InvalidArgumentException + * @throws \Throwable */ #[\Override] public function next(string $type, int $machineId, int $timestamp, ?GenerationContext $runtime = null): int From 4846ee9dae03f24ea7275166403ac9626e7ce567 Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 10:02:40 +0600 Subject: [PATCH 21/26] Complete remaining sequence and UUID exception declarations --- src/Snowflake.php | 5 +++++ src/Sonyflake.php | 8 ++++++++ src/Support/DecimalBytes.php | 4 ++++ src/Support/GetSequence.php | 2 ++ src/TBSL.php | 3 +++ src/ULID.php | 2 ++ src/UUID.php | 1 + src/functions.php | 3 +++ 8 files changed, 28 insertions(+) diff --git a/src/Snowflake.php b/src/Snowflake.php index 13f537e..e262179 100644 --- a/src/Snowflake.php +++ b/src/Snowflake.php @@ -161,6 +161,8 @@ public static function parseWithEpoch(string $id, int $startTimestamp): array * Encodes Snowflake bytes into one of bases: 16, 32, 36, 58, 62. * * @throws SnowflakeException + * @throws \InvalidArgumentException + * @throws \LogicException */ public static function toBase(string $id, int $base): string { @@ -431,6 +433,9 @@ private static function timestampParts(int $timestamp): array /** * @throws \Infocyph\UID\Exceptions\SnowflakeException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable */ private static function waitUntil(int $timestamp, ?GenerationContext $runtime): int { diff --git a/src/Sonyflake.php b/src/Sonyflake.php index b29699b..8c7fce2 100644 --- a/src/Sonyflake.php +++ b/src/Sonyflake.php @@ -161,6 +161,8 @@ public static function parseWithEpoch( * Encodes Sonyflake bytes into one of bases: 16, 32, 36, 58, 62. * * @throws SonyflakeException + * @throws \InvalidArgumentException + * @throws \LogicException */ public static function toBase(string $id, int $base): string { @@ -454,6 +456,9 @@ private static function resolveWallTime( /** * @throws \Infocyph\UID\Exceptions\SonyflakeException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable */ private static function waitUntilElapsed( int $elapsedTime, @@ -480,6 +485,9 @@ private static function waitUntilElapsed( /** * @throws \Infocyph\UID\Exceptions\SonyflakeException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable */ private static function waitUntilWallTime(int $lastTime, ?GenerationContext $runtime): int { diff --git a/src/Support/DecimalBytes.php b/src/Support/DecimalBytes.php index 30679e8..b41f468 100644 --- a/src/Support/DecimalBytes.php +++ b/src/Support/DecimalBytes.php @@ -19,6 +19,10 @@ final class DecimalBytes private const string TWO_TO_64 = '18446744073709551616'; + /** + * @throws \InvalidArgumentException + * @throws \LogicException + */ public static function fromBytes(string $bytes): string { return BaseEncoder::encodeBytes($bytes, 10); diff --git a/src/Support/GetSequence.php b/src/Support/GetSequence.php index ef19262..f5f210d 100644 --- a/src/Support/GetSequence.php +++ b/src/Support/GetSequence.php @@ -99,6 +99,8 @@ public static function useSimpleCacheSequenceProvider( * @param int $machineId The machine ID. * @param string $type The type identifier. * @throws \Infocyph\UID\Exceptions\FileLockException + * @throws \InvalidArgumentException + * @throws \Throwable */ private static function sequence( int $dateTime, diff --git a/src/TBSL.php b/src/TBSL.php index a54f87c..1b700ab 100644 --- a/src/TBSL.php +++ b/src/TBSL.php @@ -279,6 +279,9 @@ private static function resolveTail( /** * @throws \Infocyph\UID\Exceptions\UIDException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable */ private static function waitUntilNextTimeSequence(int $last, ?GenerationContext $runtime): int { diff --git a/src/ULID.php b/src/ULID.php index bdcfe68..1cb182f 100644 --- a/src/ULID.php +++ b/src/ULID.php @@ -178,6 +178,8 @@ public static function isValid(string $ulid): bool * Encodes ULID bytes into one of bases: 16, 32, 36, 58, 62. * * @throws ULIDException + * @throws \InvalidArgumentException + * @throws \LogicException */ public static function toBase(string $ulid, int $base): string { diff --git a/src/UUID.php b/src/UUID.php index 40a3a0b..54c355e 100644 --- a/src/UUID.php +++ b/src/UUID.php @@ -262,6 +262,7 @@ public static function parse(string $uuid): array * Encodes UUID bytes into one of bases: 16, 32, 36, 58, 62. * * @throws UUIDException + * @throws \LogicException */ public static function toBase(string $uuid, int $base): string { diff --git a/src/functions.php b/src/functions.php index 6288843..01f97d6 100644 --- a/src/functions.php +++ b/src/functions.php @@ -53,6 +53,9 @@ function randflake(RandflakeConfig $config): string return Randflake::generateWithConfig($config); } +/** + * @throws \InvalidArgumentException + */ function random_id(int $length = 21, string $alphabet = RandomId::DEFAULT_ALPHABET): string { return RandomId::generate($length, $alphabet); From cd99e722c48885af0f36df95bc32e78d8cf8fc36 Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 10:04:11 +0600 Subject: [PATCH 22/26] Document remaining transitive identifier and cache exceptions --- benchmarks/HotspotBench.php | 1 + src/Randflake.php | 8 ++++++++ src/Snowflake.php | 6 ++++++ src/Sonyflake.php | 6 ++++++ src/Support/NumericIdCodec.php | 1 + src/TBSL.php | 2 ++ tests/SequenceDomainLimitTest.php | 1 + tests/SequenceProviderTest.php | 1 + 8 files changed, 26 insertions(+) diff --git a/benchmarks/HotspotBench.php b/benchmarks/HotspotBench.php index f850e83..10678b2 100644 --- a/benchmarks/HotspotBench.php +++ b/benchmarks/HotspotBench.php @@ -151,6 +151,7 @@ public function benchOpaqueIdDecode(): void /** * @throws \InvalidArgumentException + * @throws \LogicException */ #[Bench\Revs(1000), Bench\Iterations(5)] public function benchOpaqueIdEncode(): void diff --git a/src/Randflake.php b/src/Randflake.php index 72b741d..dc7d8df 100644 --- a/src/Randflake.php +++ b/src/Randflake.php @@ -172,6 +172,7 @@ public static function fromBytes( /** * @throws RandflakeException|FileLockException + * @throws \InvalidArgumentException */ public static function generate( int $nodeId, @@ -194,6 +195,8 @@ public static function generate( /** * @throws RandflakeException|FileLockException + * @throws \InvalidArgumentException + * @throws \LogicException */ public static function generateString( int $nodeId, @@ -207,6 +210,7 @@ public static function generateString( /** * @throws RandflakeException|FileLockException + * @throws \InvalidArgumentException */ public static function generateWithConfig(RandflakeConfig $config): string { @@ -254,6 +258,7 @@ public static function inspect( /** * @return array{timestamp: int, node_id: int, sequence: int} * @throws RandflakeException + * @throws \LogicException */ public static function inspectString( string $id, @@ -368,6 +373,8 @@ public static function toBytes( * @return array{0:int,1:int} * @throws \Infocyph\UID\Exceptions\RandflakeException * @throws \Infocyph\UID\Exceptions\FileLockException + * @throws \InvalidArgumentException + * @throws \Throwable */ private static function allocateSequence( SequenceProviderInterface $provider, @@ -443,6 +450,7 @@ private static function encodeGeneratedPayload( /** * @throws RandflakeException|FileLockException * @throws \InvalidArgumentException + * @throws \LogicException */ private static function generateInternal( int $nodeId, diff --git a/src/Snowflake.php b/src/Snowflake.php index e262179..d39c5f6 100644 --- a/src/Snowflake.php +++ b/src/Snowflake.php @@ -268,6 +268,9 @@ private static function encodeNumericBytes(string $id): string /** * @throws SnowflakeException|FileLockException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable */ private static function generateInternal( int $datacenter, @@ -342,6 +345,9 @@ private static function generateInternal( /** * @return array{0:int, 1:int} * @throws FileLockException|SnowflakeException + * @throws \InvalidArgumentException + * @throws \Throwable + * @throws \LogicException */ private static function nextSequenceAtValidTimestamp( int $currentTime, diff --git a/src/Sonyflake.php b/src/Sonyflake.php index 8c7fce2..feb56c6 100644 --- a/src/Sonyflake.php +++ b/src/Sonyflake.php @@ -191,6 +191,9 @@ public static function toBytes(string $id): string * @return array{0:int,1:int} * @throws \Infocyph\UID\Exceptions\SonyflakeException * @throws \Infocyph\UID\Exceptions\FileLockException + * @throws \InvalidArgumentException + * @throws \Throwable + * @throws \LogicException */ private static function allocateSequence( SequenceProviderInterface $provider, @@ -437,6 +440,9 @@ private static function resolveSequenceProvider(?SequenceProviderInterface $prov /** * @throws \Infocyph\UID\Exceptions\SonyflakeException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable */ private static function resolveWallTime( int $currentTime, diff --git a/src/Support/NumericIdCodec.php b/src/Support/NumericIdCodec.php index 07fcfce..ba04cac 100644 --- a/src/Support/NumericIdCodec.php +++ b/src/Support/NumericIdCodec.php @@ -31,6 +31,7 @@ public static function decimalFromBase(string $encoded, int $base, int $byteLeng /** * @throws \InvalidArgumentException + * @throws \LogicException */ public static function decimalFromBytes(string $bytes, int $byteLength): string { diff --git a/src/TBSL.php b/src/TBSL.php index 1b700ab..f211a25 100644 --- a/src/TBSL.php +++ b/src/TBSL.php @@ -173,6 +173,7 @@ private static function assertTimestamp(int $timestamp, int $machineId): void /** * @throws Exception + * @throws \Throwable */ private static function generateInternal( int $machineId, @@ -235,6 +236,7 @@ private static function nowMicroseconds(?GenerationContext $runtime): int * @param int $timeSequence The timestamp sequence. * @return array{0:int, 1:string} * @throws Exception + * @throws \Throwable */ private static function resolveTail( int $machineId, diff --git a/tests/SequenceDomainLimitTest.php b/tests/SequenceDomainLimitTest.php index 36a272a..43f6fa9 100644 --- a/tests/SequenceDomainLimitTest.php +++ b/tests/SequenceDomainLimitTest.php @@ -54,6 +54,7 @@ public function getMultiple(iterable $keys, mixed $default = null): iterable /** * @param iterable $values * @throws InvalidArgumentException + * @throws \Psr\SimpleCache\InvalidArgumentException */ #[\Override] public function setMultiple(iterable $values, null|int|DateInterval $ttl = null): bool diff --git a/tests/SequenceProviderTest.php b/tests/SequenceProviderTest.php index 7631d66..147363d 100644 --- a/tests/SequenceProviderTest.php +++ b/tests/SequenceProviderTest.php @@ -92,6 +92,7 @@ public function set(string $key, mixed $value, null|int|DateInterval $ttl = null /** * @param iterable $values * @throws InvalidArgumentException + * @throws \Psr\SimpleCache\InvalidArgumentException */ #[\Override] public function setMultiple(iterable $values, null|int|DateInterval $ttl = null): bool From 875593ff377ef5a885bc436f6952370a835c89cb Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 10:08:14 +0600 Subject: [PATCH 23/26] fix: complete coordinated generator and codec exception contracts --- benchmarks/BaseCodecBench.php | 1 + benchmarks/HotspotBench.php | 10 +++++++++ benchmarks/SequenceProviderBench.php | 12 ++++++++++ src/Id.php | 33 ++++++++++++++++++++++++++++ src/Randflake.php | 6 +++++ src/Snowflake.php | 10 +++++++++ src/Sonyflake.php | 11 ++++++++++ src/Support/NumericConversion.php | 2 ++ src/Support/NumericIdCodec.php | 1 + src/TBSL.php | 3 +++ src/functions.php | 23 +++++++++++++++++++ 11 files changed, 112 insertions(+) diff --git a/benchmarks/BaseCodecBench.php b/benchmarks/BaseCodecBench.php index ab02175..5537c1e 100644 --- a/benchmarks/BaseCodecBench.php +++ b/benchmarks/BaseCodecBench.php @@ -128,6 +128,7 @@ public function benchDecode(array $params): void /** * @param array{length:int} $params * @throws \InvalidArgumentException + * @throws \LogicException */ #[Bench\Revs(500), Bench\Iterations(5), Bench\ParamProviders('provideLengths')] public function benchNumericFromBytes(array $params): void diff --git a/benchmarks/HotspotBench.php b/benchmarks/HotspotBench.php index 10678b2..9ccb7eb 100644 --- a/benchmarks/HotspotBench.php +++ b/benchmarks/HotspotBench.php @@ -162,6 +162,9 @@ public function benchOpaqueIdEncode(): void /** * @throws \Infocyph\UID\Exceptions\RandflakeException * @throws \Infocyph\UID\Exceptions\FileLockException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable */ #[Bench\Revs(250), Bench\Iterations(5)] public function benchRandflakeFilesystem(): void @@ -200,6 +203,9 @@ public function benchRandomIdDefault61(): void * @throws \Infocyph\UID\Exceptions\SnowflakeException * @throws \Infocyph\UID\Exceptions\FileLockException * @throws \UnexpectedValueException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable */ #[Bench\Revs(250), Bench\Iterations(5)] public function benchSnowflakeFilesystem(): void @@ -211,6 +217,9 @@ public function benchSnowflakeFilesystem(): void * @throws \Infocyph\UID\Exceptions\SonyflakeException * @throws \Infocyph\UID\Exceptions\FileLockException * @throws \UnexpectedValueException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable */ #[Bench\Revs(250), Bench\Iterations(5)] public function benchSonyflakeFilesystem(): void @@ -220,6 +229,7 @@ public function benchSonyflakeFilesystem(): void /** * @throws \Exception + * @throws \Throwable */ #[Bench\Revs(250), Bench\Iterations(5)] public function benchTbslFilesystem(): void diff --git a/benchmarks/SequenceProviderBench.php b/benchmarks/SequenceProviderBench.php index 2528066..d650b97 100644 --- a/benchmarks/SequenceProviderBench.php +++ b/benchmarks/SequenceProviderBench.php @@ -43,6 +43,9 @@ public function __construct() /** * @throws \Infocyph\UID\Exceptions\RandflakeException * @throws \Infocyph\UID\Exceptions\FileLockException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable */ #[Bench\Revs(500), Bench\Iterations(5)] public function benchRandflakeFilesystem(): void @@ -53,6 +56,9 @@ public function benchRandflakeFilesystem(): void /** * @throws \Infocyph\UID\Exceptions\RandflakeException * @throws \Infocyph\UID\Exceptions\FileLockException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable */ #[Bench\Revs(500), Bench\Iterations(5)] public function benchRandflakeInMemory(): void @@ -64,6 +70,9 @@ public function benchRandflakeInMemory(): void * @throws \Infocyph\UID\Exceptions\SnowflakeException * @throws \Infocyph\UID\Exceptions\FileLockException * @throws \UnexpectedValueException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable */ #[Bench\Revs(500), Bench\Iterations(5)] public function benchSnowflakeFilesystem(): void @@ -75,6 +84,9 @@ public function benchSnowflakeFilesystem(): void * @throws \Infocyph\UID\Exceptions\SnowflakeException * @throws \Infocyph\UID\Exceptions\FileLockException * @throws \UnexpectedValueException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable */ #[Bench\Revs(500), Bench\Iterations(5)] public function benchSnowflakeInMemory(): void diff --git a/src/Id.php b/src/Id.php index 0b4a849..f50724f 100644 --- a/src/Id.php +++ b/src/Id.php @@ -60,6 +60,9 @@ public static function objectId(?DateTimeInterface $dateTime = null): string /** * @throws \Infocyph\UID\Exceptions\RandflakeException * @throws \Infocyph\UID\Exceptions\FileLockException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable */ public static function randflake(RandflakeConfig $config): string { @@ -76,6 +79,14 @@ public static function random( return RandomId::generate($length, $alphabet); } + /** + * @throws \Infocyph\UID\Exceptions\SnowflakeException + * @throws \Infocyph\UID\Exceptions\FileLockException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable + * @throws \UnexpectedValueException + */ public static function snowflake(?SnowflakeConfig $config = null): string { return $config === null ? Snowflake::generate() : Snowflake::generateWithConfig($config); @@ -83,12 +94,25 @@ public static function snowflake(?SnowflakeConfig $config = null): string /** * @throws \InvalidArgumentException + * @throws \Infocyph\UID\Exceptions\SnowflakeException + * @throws \Infocyph\UID\Exceptions\FileLockException + * @throws \LogicException + * @throws \Throwable + * @throws \UnexpectedValueException */ public static function snowflakeValue(?SnowflakeConfig $config = null): SnowflakeValue { return new SnowflakeValue(self::snowflake($config), $config?->resolveCustomEpochMs()); } + /** + * @throws \Infocyph\UID\Exceptions\SonyflakeException + * @throws \Infocyph\UID\Exceptions\FileLockException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable + * @throws \UnexpectedValueException + */ public static function sonyflake(?SonyflakeConfig $config = null): string { return $config === null ? Sonyflake::generate() : Sonyflake::generateWithConfig($config); @@ -96,6 +120,11 @@ public static function sonyflake(?SonyflakeConfig $config = null): string /** * @throws \InvalidArgumentException + * @throws \Infocyph\UID\Exceptions\SonyflakeException + * @throws \Infocyph\UID\Exceptions\FileLockException + * @throws \LogicException + * @throws \Throwable + * @throws \UnexpectedValueException */ public static function sonyflakeValue(?SonyflakeConfig $config = null): SonyflakeValue { @@ -111,6 +140,10 @@ public static function sonyflakeValue(?SonyflakeConfig $config = null): Sonyflak ); } + /** + * @throws \Exception + * @throws \Throwable + */ public static function tbsl(?TBSLConfig $config = null): string { return $config === null ? TBSL::generate() : TBSL::generateWithConfig($config); diff --git a/src/Randflake.php b/src/Randflake.php index dc7d8df..ace2177 100644 --- a/src/Randflake.php +++ b/src/Randflake.php @@ -173,6 +173,8 @@ public static function fromBytes( /** * @throws RandflakeException|FileLockException * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable */ public static function generate( int $nodeId, @@ -197,6 +199,7 @@ public static function generate( * @throws RandflakeException|FileLockException * @throws \InvalidArgumentException * @throws \LogicException + * @throws \Throwable */ public static function generateString( int $nodeId, @@ -211,6 +214,8 @@ public static function generateString( /** * @throws RandflakeException|FileLockException * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable */ public static function generateWithConfig(RandflakeConfig $config): string { @@ -451,6 +456,7 @@ private static function encodeGeneratedPayload( * @throws RandflakeException|FileLockException * @throws \InvalidArgumentException * @throws \LogicException + * @throws \Throwable */ private static function generateInternal( int $nodeId, diff --git a/src/Snowflake.php b/src/Snowflake.php index d39c5f6..8004e59 100644 --- a/src/Snowflake.php +++ b/src/Snowflake.php @@ -44,6 +44,7 @@ final class Snowflake * Decodes one of bases: 16, 32, 36, 58, 62 into Snowflake decimal. * * @throws SnowflakeException + * @throws \LogicException */ public static function fromBase(string $encoded, int $base): string { @@ -54,6 +55,7 @@ public static function fromBase(string $encoded, int $base): string * Converts 8-byte Snowflake binary data to decimal string. * * @throws SnowflakeException + * @throws \LogicException */ public static function fromBytes(string $bytes): string { @@ -67,6 +69,9 @@ public static function fromBytes(string $bytes): string * @param int $workerId The ID of the worker (default: 0) * @return string The generated snowflake ID * @throws SnowflakeException|FileLockException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable */ public static function generate(int $datacenter = 0, int $workerId = 0): string { @@ -83,6 +88,9 @@ public static function generate(int $datacenter = 0, int $workerId = 0): string * * @throws SnowflakeException|FileLockException * @throws \UnexpectedValueException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable */ public static function generateWithConfig(SnowflakeConfig $config): string { @@ -226,6 +234,7 @@ private static function assertTimestampRange(int $currentTime, int $startTimesta /** * @throws \Infocyph\UID\Exceptions\SnowflakeException + * @throws \LogicException */ private static function decodeNumericBase(string $encoded, int $base): string { @@ -241,6 +250,7 @@ private static function decodeNumericBase(string $encoded, int $base): string /** * @throws \Infocyph\UID\Exceptions\SnowflakeException + * @throws \LogicException */ private static function decodeNumericBytes(string $bytes): string { diff --git a/src/Sonyflake.php b/src/Sonyflake.php index feb56c6..e4934de 100644 --- a/src/Sonyflake.php +++ b/src/Sonyflake.php @@ -45,6 +45,7 @@ final class Sonyflake * Decodes one of bases: 16, 32, 36, 58, 62 into Sonyflake decimal. * * @throws SonyflakeException + * @throws \LogicException */ public static function fromBase(string $encoded, int $base): string { @@ -60,6 +61,7 @@ public static function fromBase(string $encoded, int $base): string * Converts 8-byte Sonyflake binary data to decimal string. * * @throws SonyflakeException + * @throws \LogicException */ public static function fromBytes(string $bytes): string { @@ -77,6 +79,9 @@ public static function fromBytes(string $bytes): string * @param int $machineId The machine identifier. Must be between 0 and the maximum machine ID. * @return string The generated unique identifier. * @throws SonyflakeException|FileLockException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable */ public static function generate(int $machineId = 0): string { @@ -93,6 +98,9 @@ public static function generate(int $machineId = 0): string * * @throws SonyflakeException|FileLockException * @throws \UnexpectedValueException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable */ public static function generateWithConfig(SonyflakeConfig $config): string { @@ -335,6 +343,9 @@ private static function extractParts( /** * @throws SonyflakeException|FileLockException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable */ private static function generateInternal( int $machineId, diff --git a/src/Support/NumericConversion.php b/src/Support/NumericConversion.php index 91ade22..f15ec14 100644 --- a/src/Support/NumericConversion.php +++ b/src/Support/NumericConversion.php @@ -34,6 +34,7 @@ public static function bytesFromDecimal( /** * @template T of \Throwable * @param callable(string, \InvalidArgumentException):T $exceptionFactory + * @throws \LogicException */ public static function decimalFromBase( string $encoded, @@ -51,6 +52,7 @@ public static function decimalFromBase( /** * @template T of \Throwable * @param callable(string, \InvalidArgumentException):T $exceptionFactory + * @throws \LogicException */ public static function decimalFromBytes( string $bytes, diff --git a/src/Support/NumericIdCodec.php b/src/Support/NumericIdCodec.php index ba04cac..6f798b8 100644 --- a/src/Support/NumericIdCodec.php +++ b/src/Support/NumericIdCodec.php @@ -23,6 +23,7 @@ public static function bytesFromDecimal( /** * @throws \InvalidArgumentException + * @throws \LogicException */ public static function decimalFromBase(string $encoded, int $base, int $byteLength): string { diff --git a/src/TBSL.php b/src/TBSL.php index f211a25..2f28d99 100644 --- a/src/TBSL.php +++ b/src/TBSL.php @@ -56,6 +56,7 @@ public static function fromBytes(string $bytes): string * @param bool $sequenced Whether to use sequencing. * @return string The generated unique identifier. * @throws Exception + * @throws \Throwable */ public static function generate(int $machineId = 0, bool $sequenced = true): string { @@ -70,6 +71,7 @@ public static function generate(int $machineId = 0, bool $sequenced = true): str * Generates TBSL using configuration object. * * @throws Exception + * @throws \Throwable */ public static function generateRandom(int $machineId = 0): string { @@ -78,6 +80,7 @@ public static function generateRandom(int $machineId = 0): string /** * @throws \Exception + * @throws \Throwable */ public static function generateWithConfig(TBSLConfig $config): string { diff --git a/src/functions.php b/src/functions.php index 01f97d6..abb0e35 100644 --- a/src/functions.php +++ b/src/functions.php @@ -47,6 +47,9 @@ function object_id(?DateTimeInterface $dateTime = null): string /** * @throws \Infocyph\UID\Exceptions\RandflakeException * @throws \Infocyph\UID\Exceptions\FileLockException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable */ function randflake(RandflakeConfig $config): string { @@ -61,16 +64,36 @@ function random_id(int $length = 21, string $alphabet = RandomId::DEFAULT_ALPHAB return RandomId::generate($length, $alphabet); } +/** + * @throws \Infocyph\UID\Exceptions\SnowflakeException + * @throws \Infocyph\UID\Exceptions\FileLockException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable + * @throws \UnexpectedValueException + */ function snowflake(?SnowflakeConfig $config = null): string { return $config === null ? Snowflake::generate() : Snowflake::generateWithConfig($config); } +/** + * @throws \Infocyph\UID\Exceptions\SonyflakeException + * @throws \Infocyph\UID\Exceptions\FileLockException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable + * @throws \UnexpectedValueException + */ function sonyflake(?SonyflakeConfig $config = null): string { return $config === null ? Sonyflake::generate() : Sonyflake::generateWithConfig($config); } +/** + * @throws \Exception + * @throws \Throwable + */ function tbsl(?TBSLConfig $config = null): string { return $config === null ? TBSL::generate() : TBSL::generateWithConfig($config); From 53db407d01d223e52444a16abb926266d3fa5d2b Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 10:09:18 +0600 Subject: [PATCH 24/26] fix: reject negative timestamps before cache sequence allocation --- docs/sequence-providers.rst | 3 +++ .../PsrSimpleCacheSequenceProvider.php | 4 +++ tests/SequenceProviderTest.php | 25 +++++++++++++++++++ 3 files changed, 32 insertions(+) diff --git a/docs/sequence-providers.rst b/docs/sequence-providers.rst index 309cfda..8aebd6c 100644 --- a/docs/sequence-providers.rst +++ b/docs/sequence-providers.rst @@ -47,6 +47,9 @@ enough for sequence allocation. For a shared ID domain: - coordinate all hosts with an application-supplied distributed synchronizer; - keep machine/node ownership stable across writers. +The PSR-16 provider rejects negative timestamps before accessing the cache, so +invalid input cannot persist malformed sequence state. + UID writes sequence state without an explicit TTL. PSR-16 implementations may apply their configured default lifetime when null/default TTL is used, so the backend must be configured accordingly. UID fails closed when state that this diff --git a/src/Sequence/PsrSimpleCacheSequenceProvider.php b/src/Sequence/PsrSimpleCacheSequenceProvider.php index 2ccc8f8..56b6b7a 100644 --- a/src/Sequence/PsrSimpleCacheSequenceProvider.php +++ b/src/Sequence/PsrSimpleCacheSequenceProvider.php @@ -59,6 +59,10 @@ public function next(string $type, int $machineId, int $timestamp, ?GenerationCo $this->runtime?->assertActive(); $runtime ??= $this->runtime; $runtime?->assertActive(); + if ($timestamp < 0) { + throw new InvalidArgumentException('Sequence timestamp must not be negative'); + } + $key = $this->key($type, $machineId); if (!isset($this->observedState[$key]) && count($this->observedState) >= self::MAX_OBSERVED_DOMAINS) { throw new FileLockException('Observed PSR-16 sequence domain limit exceeded'); diff --git a/tests/SequenceProviderTest.php b/tests/SequenceProviderTest.php index 147363d..f67605a 100644 --- a/tests/SequenceProviderTest.php +++ b/tests/SequenceProviderTest.php @@ -238,6 +238,31 @@ public function next(string $type, int $machineId, int $timestamp): int ->and($synchronizerCalls)->toBe(2); }); +test('psr-16 sequence provider rejects negative timestamps before accessing storage', function (bool $synchronized): void { + $cache = new SequenceTestCache(); + $synchronizer = $synchronized + ? static function (string $key, callable $allocate): int { + unset($key); + $result = $allocate(); + is_int($result) || throw new LogicException('Invalid allocation result'); + + return $result; + } + : null; + $provider = new PsrSimpleCacheSequenceProvider($cache, synchronizer: $synchronizer); + $cache->beforeRead = static function (): void { + throw new LogicException('Invalid timestamp must not access storage'); + }; + + expect(fn(): int => $provider->next('audit', 1, -1)) + ->toThrow(InvalidArgumentException::class, 'Sequence timestamp must not be negative') + ->and($cache->has('uid.seq.audit.1'))->toBeFalse(); + + $cache->beforeRead = null; + expect($provider->next('audit', 1, 0))->toBe(1) + ->and($provider->next('audit', 1, 0))->toBe(2); +})->with([false, true]); + test('psr-16 sequence provider fails safely when state cannot be persisted', function () { $cache = new SequenceTestCache(); $cache->failWrites = true; From ca8b56f0082b7ef15041a64fc6e04192f8b2384e Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 10:10:13 +0600 Subject: [PATCH 25/26] fix: unify numeric conversion and finish analyzer fixture contracts --- src/Sonyflake.php | 42 ++++++++++++-------------------- tests/RuntimeIntegrationTest.php | 3 +++ tests/V5CompatibilityTest.php | 4 +++ 3 files changed, 23 insertions(+), 26 deletions(-) diff --git a/src/Sonyflake.php b/src/Sonyflake.php index e4934de..9b9e61b 100644 --- a/src/Sonyflake.php +++ b/src/Sonyflake.php @@ -17,7 +17,7 @@ use Infocyph\UID\Sequence\SequenceProviderInterface; use Infocyph\UID\Support\BaseEncoder; use Infocyph\UID\Support\GetSequence; -use Infocyph\UID\Support\NumericIdCodec; +use Infocyph\UID\Support\NumericConversion; use Infocyph\UID\Support\UnsignedDecimal; final class Sonyflake @@ -49,9 +49,11 @@ final class Sonyflake */ public static function fromBase(string $encoded, int $base): string { - $id = self::decodeNumeric( - fn(): string => NumericIdCodec::decimalFromBase($encoded, $base, 8), - null, + $id = NumericConversion::decimalFromBase( + $encoded, + $base, + 8, + static fn(string $message, \InvalidArgumentException $exception): SonyflakeException => new SonyflakeException($message, 0, $exception), ); return self::assertDecodedId($id); @@ -65,9 +67,11 @@ public static function fromBase(string $encoded, int $base): string */ public static function fromBytes(string $bytes): string { - $id = self::decodeNumeric( - fn(): string => NumericIdCodec::decimalFromBytes($bytes, 8), + $id = NumericConversion::decimalFromBytes( + $bytes, + 8, 'Sonyflake binary data must be exactly 8 bytes', + static fn(string $message, \InvalidArgumentException $exception): SonyflakeException => new SonyflakeException($message, 0, $exception), ); return self::assertDecodedId($id); @@ -184,14 +188,13 @@ public static function toBase(string $id, int $base): string */ public static function toBytes(string $id): string { - return self::decodeNumeric( - fn(): string => NumericIdCodec::bytesFromDecimal( - $id, - 8, - self::isValid(...), - 'Invalid Sonyflake ID string', - ), + return NumericConversion::bytesFromDecimal( + $id, + 8, + self::isValid(...), + 'Invalid Sonyflake ID string', 'Unable to convert Sonyflake ID to bytes', + static fn(string $message, \InvalidArgumentException $exception): SonyflakeException => new SonyflakeException($message, 0, $exception), ); } @@ -267,19 +270,6 @@ private static function assertMachineId(int $machineId): void } } - /** - * @param callable():string $operation - * @throws SonyflakeException - */ - private static function decodeNumeric(callable $operation, ?string $customMessage): string - { - try { - return $operation(); - } catch (\InvalidArgumentException $exception) { - throw new SonyflakeException($customMessage ?? $exception->getMessage(), 0, $exception); - } - } - /** * Calculates the elapsed time in 10ms units. * @throws \Infocyph\UID\Exceptions\SonyflakeException diff --git a/tests/RuntimeIntegrationTest.php b/tests/RuntimeIntegrationTest.php index dc7d87b..adf6aa2 100644 --- a/tests/RuntimeIntegrationTest.php +++ b/tests/RuntimeIntegrationTest.php @@ -158,6 +158,9 @@ static function (string $type, int $machineId, int $timestamp) use (&$allocation * @throws \UnexpectedValueException * @throws \Infocyph\UID\Exceptions\SnowflakeException * @throws \Infocyph\UID\Exceptions\FileLockException + * @throws \InvalidArgumentException + * @throws \LogicException + * @throws \Throwable */ function forwardUidSnowflake(SnowflakeConfig $config): string { diff --git a/tests/V5CompatibilityTest.php b/tests/V5CompatibilityTest.php index ebca07d..357a0cd 100644 --- a/tests/V5CompatibilityTest.php +++ b/tests/V5CompatibilityTest.php @@ -85,6 +85,10 @@ }); test('random sampler maps every accepted byte uniformly', function (int $size) { + if ($size < 2 || $size > 256) { + throw new InvalidArgumentException('Alphabet fixture size must be between 2 and 256'); + } + $alphabet = ''; for ($index = 0; $index < $size; ++$index) { $alphabet .= chr($index); From 512aa7fbb9a9996af4f5d3552fbe98db6bf3ccbb Mon Sep 17 00:00:00 2001 From: "A. B. M. Mahmudul Hasan" Date: Fri, 27 Nov 2026 10:44:42 +0600 Subject: [PATCH 26/26] :sparkles: feat(config): share generation retry deadlines and normalize date epochs - Share a single monotonic wait deadline across ID generator retries :zap: - Normalize date-time epochs to integer milliseconds with bounds validation :art: - Add comprehensive test coverage for custom epochs and retry budgets :white_check_mark: - Update framework integration and generator documentation :memo: --- docs/framework-integration.rst | 5 + docs/snowflake.rst | 5 + docs/sonyflake.rst | 5 + src/Configuration/ResolvesCustomEpoch.php | 26 ++++- src/Configuration/SnowflakeConfig.php | 1 + src/Configuration/SonyflakeConfig.php | 1 + src/Snowflake.php | 24 ++-- src/Sonyflake.php | 39 ++++--- src/TBSL.php | 26 +++-- tests/ReleaseBoundaryTest.php | 54 +++++++++ tests/RuntimeIntegrationTest.php | 133 ++++++++++++++++++++++ 11 files changed, 277 insertions(+), 42 deletions(-) diff --git a/docs/framework-integration.rst b/docs/framework-integration.rst index a1d8abd..9596c33 100644 --- a/docs/framework-integration.rst +++ b/docs/framework-integration.rst @@ -85,3 +85,8 @@ PSR-20 Clock Injection controllable wall clock. Monotonic wait accounting remains based on hrtime() and Runwire deadlines, so a frozen test clock cannot create an infinite lock or rollover wait. Explicit timestamp APIs continue to work without a clock object. + +Snowflake, Sonyflake and TBSL share one monotonic wait deadline across the retries +of a generation call. Clock advancement, repeated sequence exhaustion and clock +rollback do not renew that budget. A later generation call gets a fresh budget; +an earlier host deadline or cancellation remains terminal. diff --git a/docs/snowflake.rst b/docs/snowflake.rst index 2112d4d..3ad43a7 100644 --- a/docs/snowflake.rst +++ b/docs/snowflake.rst @@ -83,6 +83,11 @@ Parsing supports negative epoch milliseconds, including fractional seconds befor 1970. An epoch plus encoded offset that exceeds PHP's integer range throws ``SnowflakeException``. +Date-time epochs are normalized to integer milliseconds, including fractions +before 1970. For example, ``1969-12-31T23:59:59.500000Z`` is ``-500`` milliseconds. +A date-time outside PHP's integer millisecond range throws ``InvalidArgumentException`` +when constructing the configuration. + Binary and Alternate Bases -------------------------- diff --git a/docs/sonyflake.rst b/docs/sonyflake.rst index d152c1c..adbf3cb 100644 --- a/docs/sonyflake.rst +++ b/docs/sonyflake.rst @@ -85,6 +85,11 @@ Parsing supports negative epoch milliseconds, including fractional seconds befor 1970. An epoch plus encoded offset that exceeds PHP's integer range throws ``SonyflakeException``. +Date-time epochs are normalized to integer milliseconds, including fractions +before 1970. For example, ``1969-12-31T23:59:59.500000Z`` is ``-500`` milliseconds. +A date-time outside PHP's integer millisecond range throws ``InvalidArgumentException`` +when constructing the configuration. + Binary and Alternate Bases -------------------------- diff --git a/src/Configuration/ResolvesCustomEpoch.php b/src/Configuration/ResolvesCustomEpoch.php index add2a8d..76e86fa 100644 --- a/src/Configuration/ResolvesCustomEpoch.php +++ b/src/Configuration/ResolvesCustomEpoch.php @@ -13,14 +13,30 @@ public function resolveCustomEpochMs(): ?int return $this->customEpoch; } + /** + * @throws \InvalidArgumentException + */ private static function normalizeEpoch(DateTimeInterface|int|null $customEpoch): ?int { - if ($customEpoch === null) { - return null; + if (!$customEpoch instanceof DateTimeInterface) { + return $customEpoch; } - return $customEpoch instanceof DateTimeInterface - ? (int) $customEpoch->format('Uv') - : $customEpoch; + $seconds = $customEpoch->getTimestamp(); + $fraction = (int) $customEpoch->format('v'); + $minimumSeconds = intdiv(PHP_INT_MIN, 1_000) - 1; + $maximumSeconds = intdiv(PHP_INT_MAX, 1_000); + if ( + $seconds < $minimumSeconds || $seconds > $maximumSeconds + || ($seconds === $minimumSeconds && $fraction < 1_000 + (PHP_INT_MIN % 1_000)) + || ($seconds === $maximumSeconds && $fraction > PHP_INT_MAX % 1_000) + ) { + throw new \InvalidArgumentException('Custom epoch must fit in integer milliseconds'); + } + + // Add the negative fraction from the next second to avoid underflow at PHP_INT_MIN. + return $seconds < 0 + ? (($seconds + 1) * 1_000) - (1_000 - $fraction) + : ($seconds * 1_000) + $fraction; } } diff --git a/src/Configuration/SnowflakeConfig.php b/src/Configuration/SnowflakeConfig.php index ab0044c..298180e 100644 --- a/src/Configuration/SnowflakeConfig.php +++ b/src/Configuration/SnowflakeConfig.php @@ -21,6 +21,7 @@ /** * @param callable():mixed|null $nodeResolver * @param DateTimeInterface|int|null $customEpoch Epoch in milliseconds or a date-time value. + * @throws \InvalidArgumentException */ public function __construct( public int $datacenterId = 0, diff --git a/src/Configuration/SonyflakeConfig.php b/src/Configuration/SonyflakeConfig.php index f494ffe..ee0530a 100644 --- a/src/Configuration/SonyflakeConfig.php +++ b/src/Configuration/SonyflakeConfig.php @@ -19,6 +19,7 @@ /** * @param callable():mixed|null $machineIdResolver + * @throws \InvalidArgumentException */ public function __construct( public int $machineId = 0, diff --git a/src/Snowflake.php b/src/Snowflake.php index 8004e59..f66798d 100644 --- a/src/Snowflake.php +++ b/src/Snowflake.php @@ -301,6 +301,8 @@ private static function generateInternal( ? 'snowflake' : 'snowflake_' . $startTimestamp; + $deadline = $runtime?->waitDeadlineNanoseconds() + ?? hrtime(true) + (self::WAIT_TIMEOUT_MICROS * 1_000); $currentTime = self::nowMilliseconds($runtime); self::assertTimestampRange($currentTime, $startTimestamp); @@ -314,6 +316,7 @@ private static function generateInternal( $resolvedSequenceProvider, $sequenceType, $runtime, + $deadline, ); $lastState = $providerState[$stateKey] ?? null; @@ -328,7 +331,7 @@ private static function generateInternal( $currentTime < $lastState['timestamp'] || ($currentTime === $lastState['timestamp'] && $sequence <= $lastState['sequence']) ) { - $currentTime = self::waitUntil($lastState['timestamp'] + 1, $runtime); + $currentTime = self::waitUntil($lastState['timestamp'] + 1, $runtime, $deadline); self::assertTimestampRange($currentTime, $startTimestamp); continue; @@ -368,6 +371,7 @@ private static function nextSequenceAtValidTimestamp( SequenceProviderInterface $sequenceProvider, string $sequenceType, ?GenerationContext $runtime, + int $deadline, ): array { while (true) { try { @@ -381,7 +385,7 @@ private static function nextSequenceAtValidTimestamp( ); } - $currentTime = self::waitUntil($exception->lastTimestamp, $runtime); + $currentTime = self::waitUntil($exception->lastTimestamp, $runtime, $deadline); self::assertTimestampRange($currentTime, $startTimestamp); continue; @@ -395,7 +399,7 @@ private static function nextSequenceAtValidTimestamp( return [$currentTime, $allocation - 1]; } - $currentTime = self::waitUntil($currentTime + 1, $runtime); + $currentTime = self::waitUntil($currentTime + 1, $runtime, $deadline); self::assertTimestampRange($currentTime, $startTimestamp); } } @@ -453,23 +457,23 @@ private static function timestampParts(int $timestamp): array * @throws \LogicException * @throws \Throwable */ - private static function waitUntil(int $timestamp, ?GenerationContext $runtime): int + private static function waitUntil(int $timestamp, ?GenerationContext $runtime, int $deadline): int { - $deadline = $runtime?->waitDeadlineNanoseconds() - ?? hrtime(true) + (self::WAIT_TIMEOUT_MICROS * 1_000); - - while (($now = self::nowMilliseconds($runtime)) < $timestamp) { + while (true) { + $now = self::nowMilliseconds($runtime); if (hrtime(true) >= $deadline) { throw new SnowflakeException('Timed out waiting for a valid Snowflake timestamp'); } + if ($now >= $timestamp) { + return $now; + } + if ($runtime !== null) { $runtime->sleepMicroseconds(1_000); } else { usleep(1_000); } } - - return $now; } } diff --git a/src/Sonyflake.php b/src/Sonyflake.php index 9b9e61b..619d052 100644 --- a/src/Sonyflake.php +++ b/src/Sonyflake.php @@ -214,6 +214,7 @@ private static function allocateSequence( ClockBackwardPolicy $policy, ?GenerationContext $runtime, SonyflakeFormat $format, + int $deadline, ): array { $sequenceType = $format === SonyflakeFormat::UID ? 'sonyflake_' . $startTimestamp @@ -231,7 +232,7 @@ private static function allocateSequence( ); } - $elapsedTime = self::waitUntilElapsed($exception->lastTimestamp, $startTimestamp, $runtime); + $elapsedTime = self::waitUntilElapsed($exception->lastTimestamp, $startTimestamp, $runtime, $deadline); continue; } @@ -243,7 +244,7 @@ private static function allocateSequence( return [$elapsedTime, $allocation - 1]; } - $elapsedTime = self::waitUntilElapsed($elapsedTime, $startTimestamp, $runtime); + $elapsedTime = self::waitUntilElapsed($elapsedTime, $startTimestamp, $runtime, $deadline); } } @@ -350,11 +351,14 @@ private static function generateInternal( $provider = self::resolveSequenceProvider($sequenceProvider); $domainKey = $format->value . ':' . $startTimestamp . ':' . $machineId; $providerState = self::providerState($provider, $domainKey); + $deadline = $runtime?->waitDeadlineNanoseconds() + ?? hrtime(true) + (self::WAIT_TIMEOUT_MICROS * 1_000); $currentTime = self::resolveWallTime( self::nowMilliseconds($runtime), $providerState[$domainKey] ?? 0, $clockBackwardPolicy, $runtime, + $deadline, ); $elapsedTime = self::elapsedTime($currentTime, $startTimestamp); self::ensureEffectiveRuntime($elapsedTime); @@ -367,6 +371,7 @@ private static function generateInternal( $clockBackwardPolicy, $runtime, $format, + $deadline, ); $providerState[$domainKey] = max($currentTime, $startTimestamp + ($elapsedTime * 10)); self::ensureEffectiveRuntime($elapsedTime); @@ -450,6 +455,7 @@ private static function resolveWallTime( int $lastWallTime, ClockBackwardPolicy $policy, ?GenerationContext $runtime, + int $deadline, ): int { if ($currentTime >= $lastWallTime) { return $currentTime; @@ -458,7 +464,7 @@ private static function resolveWallTime( throw new SonyflakeException('Clock moved backwards while generating Sonyflake ID'); } - return self::waitUntilWallTime($lastWallTime, $runtime); + return self::waitUntilWallTime($lastWallTime, $runtime, $deadline); } /** @@ -471,23 +477,24 @@ private static function waitUntilElapsed( int $elapsedTime, int $startTimestamp, ?GenerationContext $runtime, + int $deadline, ): int { - $deadline = $runtime?->waitDeadlineNanoseconds() - ?? hrtime(true) + (self::WAIT_TIMEOUT_MICROS * 1_000); - - while (($next = self::elapsedTime(self::nowMilliseconds($runtime), $startTimestamp)) <= $elapsedTime) { + while (true) { + $next = self::elapsedTime(self::nowMilliseconds($runtime), $startTimestamp); if (hrtime(true) >= $deadline) { throw new SonyflakeException('Timed out waiting for the next Sonyflake timestamp'); } + if ($next > $elapsedTime) { + return $next; + } + if ($runtime !== null) { $runtime->sleepMicroseconds(1_000); } else { usleep(1_000); } } - - return $next; } /** @@ -496,23 +503,23 @@ private static function waitUntilElapsed( * @throws \LogicException * @throws \Throwable */ - private static function waitUntilWallTime(int $lastTime, ?GenerationContext $runtime): int + private static function waitUntilWallTime(int $lastTime, ?GenerationContext $runtime, int $deadline): int { - $deadline = $runtime?->waitDeadlineNanoseconds() - ?? hrtime(true) + (self::WAIT_TIMEOUT_MICROS * 1_000); - - while (($currentTime = self::nowMilliseconds($runtime)) < $lastTime) { + while (true) { + $currentTime = self::nowMilliseconds($runtime); if (hrtime(true) >= $deadline) { throw new SonyflakeException('Timed out waiting for the Sonyflake clock to recover'); } + if ($currentTime >= $lastTime) { + return $currentTime; + } + if ($runtime !== null) { $runtime->sleepMicroseconds(1_000); } else { usleep(1_000); } } - - return $currentTime; } } diff --git a/src/TBSL.php b/src/TBSL.php index 2f28d99..10d0818 100644 --- a/src/TBSL.php +++ b/src/TBSL.php @@ -192,6 +192,8 @@ private static function generateInternal( /** @var \ArrayObject $state */ $state = self::$lastTimeByProvider[$sequenceProvider] ??= new \ArrayObject(); $lastTime = $state[$machineId] ?? 0; + $deadline = $runtime?->waitDeadlineNanoseconds() + ?? hrtime(true) + (self::WAIT_TIMEOUT_MICROS * 1_000); $timeSequence = self::nowMicroseconds($runtime); if ($timeSequence < $lastTime) { @@ -199,7 +201,7 @@ private static function generateInternal( throw new UIDException('Clock moved backwards while generating TBSL ID'); } - $timeSequence = self::waitUntilNextTimeSequence($lastTime, $runtime); + $timeSequence = self::waitUntilNextTimeSequence($lastTime, $runtime, $deadline); } self::assertTimestamp($timeSequence, $machineId); [$timeSequence, $tail] = self::resolveTail( @@ -209,6 +211,7 @@ private static function generateInternal( $clockBackwardPolicy, $sequenceProvider, $runtime, + $deadline, ); self::assertTimestamp($timeSequence, $machineId); $state[$machineId] = max($state[$machineId] ?? 0, $timeSequence); @@ -247,7 +250,8 @@ private static function resolveTail( int $timeSequence, ClockBackwardPolicy $clockBackwardPolicy, SequenceProviderInterface $sequenceProvider, - ?GenerationContext $runtime = null, + ?GenerationContext $runtime, + int $deadline, ): array { if (!$enableSequence) { return [$timeSequence, substr(bin2hex(random_bytes(3)), 0, 5)]; @@ -265,7 +269,7 @@ private static function resolveTail( ); } - $timeSequence = self::waitUntilNextTimeSequence($exception->lastTimestamp, $runtime); + $timeSequence = self::waitUntilNextTimeSequence($exception->lastTimestamp, $runtime, $deadline); continue; } @@ -278,7 +282,7 @@ private static function resolveTail( return [$timeSequence, str_pad(dechex($sequence - 1), 5, '0', STR_PAD_LEFT)]; } - $timeSequence = self::waitUntilNextTimeSequence($timeSequence, $runtime); + $timeSequence = self::waitUntilNextTimeSequence($timeSequence, $runtime, $deadline); } while (true); } @@ -288,23 +292,23 @@ private static function resolveTail( * @throws \LogicException * @throws \Throwable */ - private static function waitUntilNextTimeSequence(int $last, ?GenerationContext $runtime): int + private static function waitUntilNextTimeSequence(int $last, ?GenerationContext $runtime, int $deadline): int { - $deadline = $runtime?->waitDeadlineNanoseconds() - ?? hrtime(true) + (self::WAIT_TIMEOUT_MICROS * 1_000); - - while (($candidate = self::nowMicroseconds($runtime)) <= $last) { + while (true) { + $candidate = self::nowMicroseconds($runtime); if (hrtime(true) >= $deadline) { throw new UIDException('Timed out waiting for the next TBSL timestamp'); } + if ($candidate > $last) { + return $candidate; + } + if ($runtime !== null) { $runtime->sleepMicroseconds(100); } else { usleep(100); } } - - return $candidate; } } diff --git a/tests/ReleaseBoundaryTest.php b/tests/ReleaseBoundaryTest.php index ec436fc..45ada5c 100644 --- a/tests/ReleaseBoundaryTest.php +++ b/tests/ReleaseBoundaryTest.php @@ -206,3 +206,57 @@ function (string $type, int $machineId, int $timestamp) use (&$nested, $fixture, ->toThrow(SonyflakeException::class); } }); + +test('date epochs preserve fractional milliseconds on both sides of Unix zero', function (string $date, int $milliseconds, bool $mutable): void { + $epoch = $mutable ? new DateTime($date) : new DateTimeImmutable($date); + $snowflake = new \Infocyph\UID\Configuration\SnowflakeConfig(customEpoch: $epoch); + $sonyflake = new SonyflakeConfig(customEpoch: $epoch); + + expect($snowflake->customEpoch)->toBe($milliseconds) + ->and($sonyflake->customEpoch)->toBe($milliseconds); +})->with([ + ['1969-12-31T23:59:59.500000Z', -500], + ['1969-12-31T23:59:58.500000Z', -1_500], + ['1969-12-31T23:59:59.999999Z', -1], + ['1969-12-31T23:59:59Z', -1_000], + ['1970-01-01T05:29:59.500000+05:30', -500], + ['1970-01-01T00:00:00Z', 0], + ['1970-01-01T00:00:00.001000Z', 1], + ['1970-01-01T00:00:01.500000Z', 1_500], + ['@9223372036854775.807', PHP_INT_MAX], + ['@-9223372036854775.808', PHP_INT_MIN], +])->with([false, true]); + +test('date epochs outside integer milliseconds fail instead of saturating', function (string $date): void { + $epoch = new DateTimeImmutable($date); + expect(fn(): \Infocyph\UID\Configuration\SnowflakeConfig => new \Infocyph\UID\Configuration\SnowflakeConfig(customEpoch: $epoch)) + ->toThrow(InvalidArgumentException::class) + ->and(fn(): SonyflakeConfig => new SonyflakeConfig(customEpoch: $epoch)) + ->toThrow(InvalidArgumentException::class); +})->with([ + '@9223372036854775.808', + '@-9223372036854775.809', + '@9223372036854776', + '@-9223372036854776.001', +]); + +test('equivalent date and integer epochs generate identical IDs', function (string $family): void { + $runtime = new GenerationContext(clock: new ReleaseBoundaryClock(new DateTimeImmutable('@1700000000'))); + $format = $family === 'sonyflake-upstream' ? SonyflakeFormat::UPSTREAM : SonyflakeFormat::UID; + $ids = []; + foreach ([new DateTimeImmutable('1969-12-31T23:59:59.500000Z'), -500] as $epoch) { + $provider = new InMemorySequenceProvider(); + $ids[] = match ($family) { + 'snowflake' => \Infocyph\UID\Snowflake::generateWithConfig(new \Infocyph\UID\Configuration\SnowflakeConfig( + customEpoch: $epoch, sequenceProvider: $provider, runtime: $runtime, + )), + 'sonyflake', 'sonyflake-upstream' => Sonyflake::generateWithConfig(new SonyflakeConfig( + customEpoch: $epoch, sequenceProvider: $provider, runtime: $runtime, + format: $format, + )), + default => throw new LogicException('Unknown generator family'), + }; + } + + expect($ids[0])->toBe($ids[1]); +})->with(['snowflake', 'sonyflake', 'sonyflake-upstream']); diff --git a/tests/RuntimeIntegrationTest.php b/tests/RuntimeIntegrationTest.php index adf6aa2..6f3aa94 100644 --- a/tests/RuntimeIntegrationTest.php +++ b/tests/RuntimeIntegrationTest.php @@ -309,3 +309,136 @@ function (CoroutineScope $scope) use (&$capturedScope): void { rmdir($directory); } }); + +final class AdvancingUidClock implements ClockInterface +{ + private DateTimeImmutable $time; + + public function __construct() + { + $this->time = new DateTimeImmutable('@1700000000'); + } + + #[\Override] + public function now(): DateTimeImmutable + { + $this->time = $this->time->modify('+20 milliseconds'); + + return $this->time; + } +} + +test('advancing clocks cannot renew exhausted generation retry budgets', function (string $family, bool $rollback): void { + $fixture = new class { + public int $attempts = 0; + + public bool $failing = true; + }; + $runtime = new GenerationContext(clock: new AdvancingUidClock(), waitTimeoutMicros: 3_000); + $provider = new \Infocyph\UID\Sequence\CallbackSequenceProvider( + static function (string $type, int $machineId, int $timestamp) use ($fixture, $family, $rollback): int { + unset($type, $machineId); + if (++$fixture->attempts > 20) { + throw new RuntimeException('Retry probe exceeded its safety limit'); + } + if (!$fixture->failing) { + return 1; + } + + usleep(1_000); + if ($rollback) { + throw new \Infocyph\UID\Exceptions\SequenceTimestampException($timestamp + 1, $timestamp); + } + + return match ($family) { + 'snowflake' => 4_097, + 'sonyflake', 'sonyflake-upstream' => 257, + 'tbsl' => 0x100001, + default => throw new LogicException('Unknown generator family'), + }; + }, + ); + $format = $family === 'sonyflake-upstream' ? \Infocyph\UID\Enums\SonyflakeFormat::UPSTREAM : \Infocyph\UID\Enums\SonyflakeFormat::UID; + $generate = static fn(): string => match ($family) { + 'snowflake' => Snowflake::generateWithConfig(new SnowflakeConfig(sequenceProvider: $provider, runtime: $runtime)), + 'sonyflake', 'sonyflake-upstream' => \Infocyph\UID\Sonyflake::generateWithConfig(new \Infocyph\UID\Configuration\SonyflakeConfig( + sequenceProvider: $provider, + runtime: $runtime, + format: $format, + )), + 'tbsl' => \Infocyph\UID\TBSL::generateWithConfig(new \Infocyph\UID\Configuration\TBSLConfig(sequenceProvider: $provider, runtime: $runtime)), + default => throw new LogicException('Unknown generator family'), + }; + + expect($generate)->toThrow(\Infocyph\UID\Exceptions\UIDException::class, 'Timed out') + ->and($fixture->attempts)->toBeGreaterThan(0)->toBeLessThan(20); + + $fixture->failing = false; + $fixture->attempts = 0; + expect($generate())->not()->toBeEmpty() + ->and($fixture->attempts)->toBe(1); +})->with(['snowflake', 'sonyflake', 'sonyflake-upstream', 'tbsl'])->with([false, true]); + +test('Snowflake monotonic retries share the outer generation deadline', function (): void { + $fixture = new class { + public ?SnowflakeConfig $config = null; + + public bool $nested = false; + + public int $attempts = 0; + }; + $provider = new \Infocyph\UID\Sequence\CallbackSequenceProvider( + static function (string $type, int $machineId, int $timestamp) use ($fixture): int { + unset($type, $machineId, $timestamp); + if (++$fixture->attempts > 20) { + throw new RuntimeException('Retry probe exceeded its safety limit'); + } + if (!$fixture->nested) { + $config = $fixture->config ?? throw new LogicException('Missing test configuration'); + $fixture->nested = true; + try { + usleep(1_000); + Snowflake::generateWithConfig($config); + } finally { + $fixture->nested = false; + } + } + + return 1; + }, + ); + $fixture->config = new SnowflakeConfig( + sequenceProvider: $provider, + runtime: new GenerationContext(clock: new AdvancingUidClock(), waitTimeoutMicros: 3_000), + ); + expect(fn(): string => Snowflake::generateWithConfig($fixture->config ?? throw new LogicException('Missing test configuration'))) + ->toThrow(SnowflakeException::class, 'Timed out') + ->and($fixture->attempts)->toBeGreaterThan(1)->toBeLessThan(20); +}); + +test('host request deadlines remain terminal during generation retries', function (): void { + $host = RuntimeContext::standalone(); + $request = RequestContext::create($host, new \Infocyph\Runwire\Runtime\RequestExecutionPolicy(maxExecutionSeconds: 0.005)); + $attempts = 0; + $provider = new \Infocyph\UID\Sequence\CallbackSequenceProvider( + static function (string $type, int $machineId, int $timestamp) use (&$attempts): int { + unset($type, $machineId, $timestamp); + if (++$attempts > 20) { + throw new RuntimeException('Retry probe exceeded its safety limit'); + } + usleep(1_000); + + return 4_097; + }, + ); + + expect(fn(): string => Snowflake::generateWithConfig(new SnowflakeConfig( + sequenceProvider: $provider, + runtime: new GenerationContext( + clock: new AdvancingUidClock(), + runwire: new RunwireBinding($host, $request), + waitTimeoutMicros: 1_000_000, + ), + )))->toThrow(CancelledException::class) + ->and($request->completed())->toBeFalse(); +});