From 2b2e80c0c5a11400d674b075236af2f862159304 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 17:50:09 -0300 Subject: [PATCH 01/43] feat: implement protocol v1 client Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- src/Client.php | 91 +++++++++++++++++++++++ src/ConsentState.php | 16 ++++ src/Endpoint.php | 37 +++++++++ src/Exception/ProtocolException.php | 15 ++++ src/Exception/ServerRejectedException.php | 27 +++++++ src/Exception/TransportException.php | 15 ++++ src/InstallationId.php | 36 +++++++++ src/Metric.php | 73 ++++++++++++++++++ src/Report.php | 70 +++++++++++++++++ src/ReportingPeriod.php | 48 ++++++++++++ src/SubmissionResult.php | 15 ++++ src/Transport/Response.php | 24 ++++++ src/Transport/StreamTransport.php | 69 +++++++++++++++++ src/Transport/TransportInterface.php | 15 ++++ 14 files changed, 551 insertions(+) create mode 100644 src/Client.php create mode 100644 src/ConsentState.php create mode 100644 src/Endpoint.php create mode 100644 src/Exception/ProtocolException.php create mode 100644 src/Exception/ServerRejectedException.php create mode 100644 src/Exception/TransportException.php create mode 100644 src/InstallationId.php create mode 100644 src/Metric.php create mode 100644 src/Report.php create mode 100644 src/ReportingPeriod.php create mode 100644 src/SubmissionResult.php create mode 100644 src/Transport/Response.php create mode 100644 src/Transport/StreamTransport.php create mode 100644 src/Transport/TransportInterface.php diff --git a/src/Client.php b/src/Client.php new file mode 100644 index 0000000..4ea3432 --- /dev/null +++ b/src/Client.php @@ -0,0 +1,91 @@ +toArray(), JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES); + } catch (JsonException $e) { + throw new ProtocolException('Unable to serialize report.', 0, $e); + } + + $response = $this->transport->request( + 'POST', + $this->endpoint->url, + [ + 'Accept' => 'application/json', + 'Content-Type' => 'application/json', + 'User-Agent' => 'usage-statistics-client/1', + ], + $payload, + $this->timeoutSeconds, + ); + + if ($response->statusCode !== 200) { + [$errorCode, $message] = $this->parseError($response->body); + throw new ServerRejectedException( + $response->statusCode, + $errorCode, + $message ?? 'Usage statistics server rejected the report.', + $response->header('retry-after'), + ); + } + + try { + $body = json_decode($response->body, true, 512, JSON_THROW_ON_ERROR); + } catch (JsonException $e) { + throw new ProtocolException('Usage statistics server returned invalid JSON.', 0, $e); + } + + if (!is_array($body) || ($body['status'] ?? null) !== 'accepted') { + throw new ProtocolException('Usage statistics server returned an unexpected success response.'); + } + + return SubmissionResult::Accepted; + } + + /** @return array{0:?string,1:?string} */ + private function parseError(string $body): array { + try { + $decoded = json_decode($body, true, 512, JSON_THROW_ON_ERROR); + } catch (JsonException) { + return [null, null]; + } + + if (!is_array($decoded)) { + return [null, null]; + } + + return [ + is_string($decoded['error'] ?? null) ? $decoded['error'] : null, + is_string($decoded['message'] ?? null) ? $decoded['message'] : null, + ]; + } +} diff --git a/src/ConsentState.php b/src/ConsentState.php new file mode 100644 index 0000000..a1af00d --- /dev/null +++ b/src/ConsentState.php @@ -0,0 +1,16 @@ +url = rtrim($url, '/'); + } + + public function __toString(): string { + return $this->url; + } +} diff --git a/src/Exception/ProtocolException.php b/src/Exception/ProtocolException.php new file mode 100644 index 0000000..cbfa4cf --- /dev/null +++ b/src/Exception/ProtocolException.php @@ -0,0 +1,15 @@ +statusCode === 429 || $this->statusCode >= 500; + } +} diff --git a/src/Exception/TransportException.php b/src/Exception/TransportException.php new file mode 100644 index 0000000..1ae9aea --- /dev/null +++ b/src/Exception/TransportException.php @@ -0,0 +1,15 @@ + 128 || preg_match(self::APPLICATION_PATTERN, $application) !== 1) { + throw new InvalidArgumentException('Application identifier is invalid.'); + } + if ($localInstallationIdentifier === '') { + throw new InvalidArgumentException('Local installation identifier must not be empty.'); + } + + $input = "usage-statistics:v1\0" . $application . "\0" . $localInstallationIdentifier; + + return new self(hash('sha256', $input)); + } + + public function __toString(): string { + return $this->value; + } +} diff --git a/src/Metric.php b/src/Metric.php new file mode 100644 index 0000000..a4a3730 --- /dev/null +++ b/src/Metric.php @@ -0,0 +1,73 @@ + self::MAX_STRING_VALUE_LENGTH) { + throw new InvalidArgumentException('String metric value exceeds 1024 bytes.'); + } + + return new self($category, $key, 'string', $value); + } + + /** @return array{category:string,key:string,type:string,value:string|int|float|bool} */ + public function toArray(): array { + return [ + 'category' => $this->category, + 'key' => $this->key, + 'type' => $this->type, + 'value' => $this->value, + ]; + } + + public function identity(): string { + return $this->category . "\0" . $this->key; + } + + private static function assertIdentifier(string $value, string $field, int $maxLength): void { + if ($value === '' || strlen($value) > $maxLength || preg_match(self::IDENTIFIER_PATTERN, $value) !== 1) { + throw new InvalidArgumentException($field . ' is invalid.'); + } + } +} diff --git a/src/Report.php b/src/Report.php new file mode 100644 index 0000000..f7c025e --- /dev/null +++ b/src/Report.php @@ -0,0 +1,70 @@ + */ + public readonly array $metrics; + + /** @param list $metrics */ + public function __construct( + public readonly string $application, + public readonly string $installationId, + public readonly int $schemaVersion, + public readonly ReportingPeriod $period, + array $metrics, + ) { + self::assertIdentifier($application, 'Application', 128); + self::assertIdentifier($installationId, 'Installation ID', 128); + if ($schemaVersion < 1) { + throw new InvalidArgumentException('Schema version must be a positive integer.'); + } + if ($metrics === [] || count($metrics) > self::MAX_METRICS) { + throw new InvalidArgumentException('Report must contain between 1 and 256 metrics.'); + } + + $seen = []; + foreach ($metrics as $metric) { + if (!$metric instanceof Metric) { + throw new InvalidArgumentException('Every report metric must be a Metric instance.'); + } + $identity = $metric->identity(); + if (isset($seen[$identity])) { + throw new InvalidArgumentException('Duplicate metric category/key pair.'); + } + $seen[$identity] = true; + } + $this->metrics = array_values($metrics); + } + + /** @return array{protocolVersion:int,application:string,installationId:string,schemaVersion:int,period:array{start:string,end:string},metrics:list} */ + public function toArray(): array { + return [ + 'protocolVersion' => self::PROTOCOL_VERSION, + 'application' => $this->application, + 'installationId' => $this->installationId, + 'schemaVersion' => $this->schemaVersion, + 'period' => $this->period->toArray(), + 'metrics' => array_map(static fn (Metric $metric): array => $metric->toArray(), $this->metrics), + ]; + } + + private static function assertIdentifier(string $value, string $field, int $maxLength): void { + if ($value === '' || strlen($value) > $maxLength || preg_match(self::IDENTIFIER_PATTERN, $value) !== 1) { + throw new InvalidArgumentException($field . ' is invalid.'); + } + } +} diff --git a/src/ReportingPeriod.php b/src/ReportingPeriod.php new file mode 100644 index 0000000..30e92c5 --- /dev/null +++ b/src/ReportingPeriod.php @@ -0,0 +1,48 @@ +start = $start->setTimezone($utc); + $this->end = $end->setTimezone($utc); + + $duration = $this->end->getTimestamp() - $this->start->getTimestamp(); + if ($duration <= 0 || $duration > self::MAX_SECONDS) { + throw new InvalidArgumentException('Reporting period must be positive and no longer than 31 days.'); + } + } + + public static function monthContaining(DateTimeImmutable $instant): self { + $utc = $instant->setTimezone(new DateTimeZone('UTC')); + $start = $utc->modify('first day of this month')->setTime(0, 0, 0, 0); + $end = $start->modify('first day of next month'); + + return new self($start, $end); + } + + /** @return array{start:string,end:string} */ + public function toArray(): array { + return [ + 'start' => $this->start->format('Y-m-d\\TH:i:s\\Z'), + 'end' => $this->end->format('Y-m-d\\TH:i:s\\Z'), + ]; + } +} diff --git a/src/SubmissionResult.php b/src/SubmissionResult.php new file mode 100644 index 0000000..5ac67d7 --- /dev/null +++ b/src/SubmissionResult.php @@ -0,0 +1,15 @@ + $headers */ + public function __construct( + public readonly int $statusCode, + public readonly string $body, + public readonly array $headers = [], + ) { + } + + public function header(string $name): ?string { + return $this->headers[strtolower($name)] ?? null; + } +} diff --git a/src/Transport/StreamTransport.php b/src/Transport/StreamTransport.php new file mode 100644 index 0000000..c828bea --- /dev/null +++ b/src/Transport/StreamTransport.php @@ -0,0 +1,69 @@ + $value) { + $headerLines[] = $name . ': ' . $value; + } + + $context = stream_context_create([ + 'http' => [ + 'method' => $method, + 'header' => implode("\r\n", $headerLines), + 'content' => $body, + 'timeout' => $timeoutSeconds, + 'ignore_errors' => true, + 'follow_location' => 0, + ], + ]); + + $previous = set_error_handler(static fn (): bool => true); + try { + $responseBody = file_get_contents($url, false, $context); + } finally { + restore_error_handler(); + } + + /** @var list|null $http_response_header */ + if ($responseBody === false || !isset($http_response_header)) { + throw new TransportException('Unable to reach usage statistics server.'); + } + + $statusCode = null; + $responseHeaders = []; + foreach ($http_response_header as $line) { + if (preg_match('/^HTTP\/\S+\s+(\d{3})\b/', $line, $matches) === 1) { + $statusCode = (int)$matches[1]; + $responseHeaders = []; + continue; + } + $separator = strpos($line, ':'); + if ($separator !== false) { + $name = strtolower(trim(substr($line, 0, $separator))); + $responseHeaders[$name] = trim(substr($line, $separator + 1)); + } + } + + if ($statusCode === null) { + throw new TransportException('Server response did not contain an HTTP status line.'); + } + + return new Response($statusCode, $responseBody, $responseHeaders); + } +} diff --git a/src/Transport/TransportInterface.php b/src/Transport/TransportInterface.php new file mode 100644 index 0000000..6946d02 --- /dev/null +++ b/src/Transport/TransportInterface.php @@ -0,0 +1,15 @@ + $headers */ + public function request(string $method, string $url, array $headers, string $body, float $timeoutSeconds): Response; +} From dbe401a1f93c575b5b90f8fe8aa10c62763c776d Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 17:51:59 -0300 Subject: [PATCH 02/43] test: cover protocol client behavior Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- .gitignore | 6 + composer.json | 52 +++++++++ phpcs.xml.dist | 9 ++ phpstan.neon | 6 + phpunit.xml.dist | 17 +++ src/Client.php | 9 +- src/ConsentState.php | 3 +- src/Endpoint.php | 9 +- src/Exception/ProtocolException.php | 3 +- src/Exception/ServerRejectedException.php | 6 +- src/Exception/TransportException.php | 3 +- src/InstallationId.php | 12 +- src/Metric.php | 24 ++-- src/Report.php | 9 +- src/ReportingPeriod.php | 16 ++- src/SubmissionResult.php | 3 +- src/Transport/Response.php | 6 +- src/Transport/StreamTransport.php | 8 +- src/Transport/TransportInterface.php | 3 +- tests/ClientTest.php | 127 ++++++++++++++++++++++ tests/EndpointTest.php | 38 +++++++ tests/InstallationIdTest.php | 28 +++++ tests/MetricTest.php | 53 +++++++++ tests/ReportTest.php | 59 ++++++++++ tests/ReportingPeriodTest.php | 41 +++++++ 25 files changed, 511 insertions(+), 39 deletions(-) create mode 100644 .gitignore create mode 100644 composer.json create mode 100644 phpcs.xml.dist create mode 100644 phpstan.neon create mode 100644 phpunit.xml.dist create mode 100644 tests/ClientTest.php create mode 100644 tests/EndpointTest.php create mode 100644 tests/InstallationIdTest.php create mode 100644 tests/MetricTest.php create mode 100644 tests/ReportTest.php create mode 100644 tests/ReportingPeriodTest.php diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a914a23 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +/vendor/ +/build/ +/.phpunit.cache/ +/.phpunit.result.cache +/.phpstan-cache/ +/coverage.xml diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..68b9dd6 --- /dev/null +++ b/composer.json @@ -0,0 +1,52 @@ +{ + "name": "vitormattos/usage-statistics-client", + "description": "Framework-agnostic PHP client for the Usage Statistics Protocol.", + "type": "library", + "license": "AGPL-3.0-or-later", + "keywords": [ + "telemetry", + "usage-statistics", + "privacy", + "php" + ], + "require": { + "php": ">=8.1" + }, + "require-dev": { + "humbug/php-scoper": "^0.18.17", + "phpstan/phpstan": "^2.1", + "phpunit/phpunit": "^10.5 || ^11.5 || ^12.0", + "squizlabs/php_codesniffer": "^3.13" + }, + "autoload": { + "psr-4": { + "LibreCode\\UsageStatistics\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "LibreCode\\UsageStatistics\\Tests\\": "tests/" + } + }, + "scripts": { + "lint": "find src tests -name '*.php' -print0 | xargs -0 -n1 php -l", + "test": "phpunit --colors=always --fail-on-warning --fail-on-risky", + "test:coverage": "XDEBUG_MODE=coverage phpunit --coverage-text", + "phpstan": "phpstan analyse -c phpstan.neon", + "phpcs": "phpcs -q", + "audit": "composer audit --no-interaction", + "qa": [ + "@lint", + "@phpcs", + "@phpstan", + "@test" + ] + }, + "support": { + "issues": "https://github.com/vitormattos/usage_statistics_client/issues", + "source": "https://github.com/vitormattos/usage_statistics_client" + }, + "config": { + "sort-packages": true + } +} diff --git a/phpcs.xml.dist b/phpcs.xml.dist new file mode 100644 index 0000000..49d5002 --- /dev/null +++ b/phpcs.xml.dist @@ -0,0 +1,9 @@ + + + PSR-12 coding standard for the Usage Statistics Client. + src + tests + + + + diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 0000000..c7ca44a --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,6 @@ +parameters: + level: max + paths: + - src + - tests + tmpDir: .phpstan-cache diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..abf30f8 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,17 @@ + + + + + tests + + + + + src + + + diff --git a/src/Client.php b/src/Client.php index 4ea3432..22cff06 100644 --- a/src/Client.php +++ b/src/Client.php @@ -14,7 +14,8 @@ use LibreCode\UsageStatistics\Exception\ServerRejectedException; use LibreCode\UsageStatistics\Transport\TransportInterface; -final class Client { +final class Client +{ public function __construct( private readonly TransportInterface $transport, private readonly Endpoint $endpoint, @@ -25,7 +26,8 @@ public function __construct( } } - public function submit(Report $report, ConsentState $consent): SubmissionResult { + public function submit(Report $report, ConsentState $consent): SubmissionResult + { if ($consent !== ConsentState::Enabled) { return SubmissionResult::SkippedWithoutConsent; } @@ -72,7 +74,8 @@ public function submit(Report $report, ConsentState $consent): SubmissionResult } /** @return array{0:?string,1:?string} */ - private function parseError(string $body): array { + private function parseError(string $body): array + { try { $decoded = json_decode($body, true, 512, JSON_THROW_ON_ERROR); } catch (JsonException) { diff --git a/src/ConsentState.php b/src/ConsentState.php index a1af00d..353aac4 100644 --- a/src/ConsentState.php +++ b/src/ConsentState.php @@ -9,7 +9,8 @@ namespace LibreCode\UsageStatistics; -enum ConsentState: string { +enum ConsentState: string +{ case Unknown = 'unknown'; case Enabled = 'enabled'; case Disabled = 'disabled'; diff --git a/src/Endpoint.php b/src/Endpoint.php index f4943e5..bacc0b4 100644 --- a/src/Endpoint.php +++ b/src/Endpoint.php @@ -11,10 +11,12 @@ use InvalidArgumentException; -final class Endpoint { +final class Endpoint +{ public readonly string $url; - public function __construct(string $url) { + public function __construct(string $url) + { $parts = parse_url($url); if (!is_array($parts) || ($parts['scheme'] ?? null) !== 'https' @@ -31,7 +33,8 @@ public function __construct(string $url) { $this->url = rtrim($url, '/'); } - public function __toString(): string { + public function __toString(): string + { return $this->url; } } diff --git a/src/Exception/ProtocolException.php b/src/Exception/ProtocolException.php index cbfa4cf..68c6105 100644 --- a/src/Exception/ProtocolException.php +++ b/src/Exception/ProtocolException.php @@ -11,5 +11,6 @@ use RuntimeException; -final class ProtocolException extends RuntimeException { +final class ProtocolException extends RuntimeException +{ } diff --git a/src/Exception/ServerRejectedException.php b/src/Exception/ServerRejectedException.php index 250386a..b6ef54c 100644 --- a/src/Exception/ServerRejectedException.php +++ b/src/Exception/ServerRejectedException.php @@ -11,7 +11,8 @@ use RuntimeException; -final class ServerRejectedException extends RuntimeException { +final class ServerRejectedException extends RuntimeException +{ public function __construct( public readonly int $statusCode, public readonly ?string $errorCode = null, @@ -21,7 +22,8 @@ public function __construct( parent::__construct($message); } - public function isTransient(): bool { + public function isTransient(): bool + { return $this->statusCode === 429 || $this->statusCode >= 500; } } diff --git a/src/Exception/TransportException.php b/src/Exception/TransportException.php index 1ae9aea..e3a0f7b 100644 --- a/src/Exception/TransportException.php +++ b/src/Exception/TransportException.php @@ -11,5 +11,6 @@ use RuntimeException; -final class TransportException extends RuntimeException { +final class TransportException extends RuntimeException +{ } diff --git a/src/InstallationId.php b/src/InstallationId.php index fd49d9c..9426349 100644 --- a/src/InstallationId.php +++ b/src/InstallationId.php @@ -11,13 +11,16 @@ use InvalidArgumentException; -final class InstallationId { +final class InstallationId +{ private const APPLICATION_PATTERN = '/^[A-Za-z0-9_.:-]+$/D'; - private function __construct(public readonly string $value) { + private function __construct(public readonly string $value) + { } - public static function derive(string $application, string $localInstallationIdentifier): self { + public static function derive(string $application, string $localInstallationIdentifier): self + { if ($application === '' || strlen($application) > 128 || preg_match(self::APPLICATION_PATTERN, $application) !== 1) { throw new InvalidArgumentException('Application identifier is invalid.'); } @@ -30,7 +33,8 @@ public static function derive(string $application, string $localInstallationIden return new self(hash('sha256', $input)); } - public function __toString(): string { + public function __toString(): string + { return $this->value; } } diff --git a/src/Metric.php b/src/Metric.php index a4a3730..9641385 100644 --- a/src/Metric.php +++ b/src/Metric.php @@ -11,7 +11,8 @@ use InvalidArgumentException; -final class Metric { +final class Metric +{ private const IDENTIFIER_PATTERN = '/^[A-Za-z0-9_.:-]+$/D'; private const MAX_CATEGORY_LENGTH = 128; private const MAX_KEY_LENGTH = 512; @@ -27,11 +28,13 @@ private function __construct( self::assertIdentifier($key, 'Metric key', self::MAX_KEY_LENGTH); } - public static function integer(string $category, string $key, int $value): self { + public static function integer(string $category, string $key, int $value): self + { return new self($category, $key, 'integer', $value); } - public static function number(string $category, string $key, int|float $value): self { + public static function number(string $category, string $key, int|float $value): self + { if (is_float($value) && !is_finite($value)) { throw new InvalidArgumentException('Number metric must be finite.'); } @@ -39,11 +42,13 @@ public static function number(string $category, string $key, int|float $value): return new self($category, $key, 'number', $value); } - public static function boolean(string $category, string $key, bool $value): self { + public static function boolean(string $category, string $key, bool $value): self + { return new self($category, $key, 'boolean', $value); } - public static function string(string $category, string $key, string $value): self { + public static function string(string $category, string $key, string $value): self + { if (strlen($value) > self::MAX_STRING_VALUE_LENGTH) { throw new InvalidArgumentException('String metric value exceeds 1024 bytes.'); } @@ -52,7 +57,8 @@ public static function string(string $category, string $key, string $value): sel } /** @return array{category:string,key:string,type:string,value:string|int|float|bool} */ - public function toArray(): array { + public function toArray(): array + { return [ 'category' => $this->category, 'key' => $this->key, @@ -61,11 +67,13 @@ public function toArray(): array { ]; } - public function identity(): string { + public function identity(): string + { return $this->category . "\0" . $this->key; } - private static function assertIdentifier(string $value, string $field, int $maxLength): void { + private static function assertIdentifier(string $value, string $field, int $maxLength): void + { if ($value === '' || strlen($value) > $maxLength || preg_match(self::IDENTIFIER_PATTERN, $value) !== 1) { throw new InvalidArgumentException($field . ' is invalid.'); } diff --git a/src/Report.php b/src/Report.php index f7c025e..60a27ea 100644 --- a/src/Report.php +++ b/src/Report.php @@ -11,7 +11,8 @@ use InvalidArgumentException; -final class Report { +final class Report +{ public const PROTOCOL_VERSION = 1; private const IDENTIFIER_PATTERN = '/^[A-Za-z0-9_.:-]+$/D'; private const MAX_METRICS = 256; @@ -51,7 +52,8 @@ public function __construct( } /** @return array{protocolVersion:int,application:string,installationId:string,schemaVersion:int,period:array{start:string,end:string},metrics:list} */ - public function toArray(): array { + public function toArray(): array + { return [ 'protocolVersion' => self::PROTOCOL_VERSION, 'application' => $this->application, @@ -62,7 +64,8 @@ public function toArray(): array { ]; } - private static function assertIdentifier(string $value, string $field, int $maxLength): void { + private static function assertIdentifier(string $value, string $field, int $maxLength): void + { if ($value === '' || strlen($value) > $maxLength || preg_match(self::IDENTIFIER_PATTERN, $value) !== 1) { throw new InvalidArgumentException($field . ' is invalid.'); } diff --git a/src/ReportingPeriod.php b/src/ReportingPeriod.php index 30e92c5..c8e4d05 100644 --- a/src/ReportingPeriod.php +++ b/src/ReportingPeriod.php @@ -13,13 +13,15 @@ use DateTimeZone; use InvalidArgumentException; -final class ReportingPeriod { +final class ReportingPeriod +{ private const MAX_SECONDS = 2_678_400; public readonly DateTimeImmutable $start; public readonly DateTimeImmutable $end; - public function __construct(DateTimeImmutable $start, DateTimeImmutable $end) { + public function __construct(DateTimeImmutable $start, DateTimeImmutable $end) + { $utc = new DateTimeZone('UTC'); $this->start = $start->setTimezone($utc); $this->end = $end->setTimezone($utc); @@ -30,7 +32,8 @@ public function __construct(DateTimeImmutable $start, DateTimeImmutable $end) { } } - public static function monthContaining(DateTimeImmutable $instant): self { + public static function monthContaining(DateTimeImmutable $instant): self + { $utc = $instant->setTimezone(new DateTimeZone('UTC')); $start = $utc->modify('first day of this month')->setTime(0, 0, 0, 0); $end = $start->modify('first day of next month'); @@ -39,10 +42,11 @@ public static function monthContaining(DateTimeImmutable $instant): self { } /** @return array{start:string,end:string} */ - public function toArray(): array { + public function toArray(): array + { return [ - 'start' => $this->start->format('Y-m-d\\TH:i:s\\Z'), - 'end' => $this->end->format('Y-m-d\\TH:i:s\\Z'), + 'start' => $this->start->format('Y-m-d\TH:i:s\Z'), + 'end' => $this->end->format('Y-m-d\TH:i:s\Z'), ]; } } diff --git a/src/SubmissionResult.php b/src/SubmissionResult.php index 5ac67d7..c6dba7b 100644 --- a/src/SubmissionResult.php +++ b/src/SubmissionResult.php @@ -9,7 +9,8 @@ namespace LibreCode\UsageStatistics; -enum SubmissionResult: string { +enum SubmissionResult: string +{ case Accepted = 'accepted'; case SkippedWithoutConsent = 'skipped_without_consent'; } diff --git a/src/Transport/Response.php b/src/Transport/Response.php index eb3eaf1..63d7c30 100644 --- a/src/Transport/Response.php +++ b/src/Transport/Response.php @@ -9,7 +9,8 @@ namespace LibreCode\UsageStatistics\Transport; -final class Response { +final class Response +{ /** @param array $headers */ public function __construct( public readonly int $statusCode, @@ -18,7 +19,8 @@ public function __construct( ) { } - public function header(string $name): ?string { + public function header(string $name): ?string + { return $this->headers[strtolower($name)] ?? null; } } diff --git a/src/Transport/StreamTransport.php b/src/Transport/StreamTransport.php index c828bea..3b60609 100644 --- a/src/Transport/StreamTransport.php +++ b/src/Transport/StreamTransport.php @@ -11,8 +11,10 @@ use LibreCode\UsageStatistics\Exception\TransportException; -final class StreamTransport implements TransportInterface { - public function request(string $method, string $url, array $headers, string $body, float $timeoutSeconds): Response { +final class StreamTransport implements TransportInterface +{ + public function request(string $method, string $url, array $headers, string $body, float $timeoutSeconds): Response + { if ($timeoutSeconds <= 0) { throw new TransportException('Timeout must be greater than zero.'); } @@ -33,7 +35,7 @@ public function request(string $method, string $url, array $headers, string $bod ], ]); - $previous = set_error_handler(static fn (): bool => true); + set_error_handler(static fn (): bool => true); try { $responseBody = file_get_contents($url, false, $context); } finally { diff --git a/src/Transport/TransportInterface.php b/src/Transport/TransportInterface.php index 6946d02..5caea49 100644 --- a/src/Transport/TransportInterface.php +++ b/src/Transport/TransportInterface.php @@ -9,7 +9,8 @@ namespace LibreCode\UsageStatistics\Transport; -interface TransportInterface { +interface TransportInterface +{ /** @param array $headers */ public function request(string $method, string $url, array $headers, string $body, float $timeoutSeconds): Response; } diff --git a/tests/ClientTest.php b/tests/ClientTest.php new file mode 100644 index 0000000..b8cf55f --- /dev/null +++ b/tests/ClientTest.php @@ -0,0 +1,127 @@ +submit($this->report(), ConsentState::Unknown)); + self::assertSame(SubmissionResult::SkippedWithoutConsent, $client->submit($this->report(), ConsentState::Disabled)); + self::assertSame(0, $transport->calls); + } + + public function testSendsProtocolPayloadWhenEnabled(): void + { + $transport = new RecordingTransport(new Response(200, '{"status":"accepted"}')); + $client = new Client($transport, new Endpoint('https://stats.example/api/v1/reports'), 2.5); + + self::assertSame(SubmissionResult::Accepted, $client->submit($this->report(), ConsentState::Enabled)); + self::assertSame('POST', $transport->method); + self::assertSame('https://stats.example/api/v1/reports', $transport->url); + self::assertSame(2.5, $transport->timeout); + self::assertSame('application/json', $transport->headers['Content-Type']); + $payload = json_decode($transport->body, true, 512, JSON_THROW_ON_ERROR); + self::assertSame(1, $payload['protocolVersion']); + self::assertSame('libresign', $payload['application']); + } + + public function testMapsServerValidationError(): void + { + $transport = new RecordingTransport(new Response(400, '{"error":"invalid_report","message":"Application schema is not registered."}')); + $client = new Client($transport, new Endpoint('https://stats.example/api/v1/reports')); + + try { + $client->submit($this->report(), ConsentState::Enabled); + self::fail('Expected exception.'); + } catch (ServerRejectedException $e) { + self::assertSame(400, $e->statusCode); + self::assertSame('invalid_report', $e->errorCode); + self::assertFalse($e->isTransient()); + } + } + + public function testExposesTransientServerFailure(): void + { + $transport = new RecordingTransport(new Response(429, '{"error":"rate_limited"}', ['retry-after' => '60'])); + $client = new Client($transport, new Endpoint('https://stats.example/api/v1/reports')); + + try { + $client->submit($this->report(), ConsentState::Enabled); + self::fail('Expected exception.'); + } catch (ServerRejectedException $e) { + self::assertTrue($e->isTransient()); + self::assertSame('60', $e->retryAfter); + } + } + + public function testRejectsUnexpectedSuccessResponse(): void + { + $transport = new RecordingTransport(new Response(200, '{"status":"different"}')); + $client = new Client($transport, new Endpoint('https://stats.example/api/v1/reports')); + $this->expectException(ProtocolException::class); + $client->submit($this->report(), ConsentState::Enabled); + } + + private function report(): Report + { + return new Report( + 'libresign', + str_repeat('a', 64), + 1, + new ReportingPeriod(new DateTimeImmutable('2026-08-01T00:00:00Z'), new DateTimeImmutable('2026-09-01T00:00:00Z')), + [Metric::integer('usage', 'requests_completed', 72)], + ); + } +} + +final class RecordingTransport implements TransportInterface +{ + public int $calls = 0; + public string $method = ''; + public string $url = ''; + /** @var array */ + public array $headers = []; + public string $body = ''; + public float $timeout = 0.0; + + public function __construct(private readonly Response $response) + { + } + + public function request(string $method, string $url, array $headers, string $body, float $timeoutSeconds): Response + { + ++$this->calls; + $this->method = $method; + $this->url = $url; + $this->headers = $headers; + $this->body = $body; + $this->timeout = $timeoutSeconds; + + return $this->response; + } +} diff --git a/tests/EndpointTest.php b/tests/EndpointTest.php new file mode 100644 index 0000000..d7f6406 --- /dev/null +++ b/tests/EndpointTest.php @@ -0,0 +1,38 @@ +expectException(InvalidArgumentException::class); + new Endpoint($endpoint); + } + + /** @return iterable */ + public static function invalidEndpoints(): iterable + { + yield 'http' => ['http://stats.example/api/v1/reports']; + yield 'credentials' => ['https://user:secret@stats.example/api/v1/reports']; + yield 'query' => ['https://stats.example/api/v1/reports?token=x']; + } +} diff --git a/tests/InstallationIdTest.php b/tests/InstallationIdTest.php new file mode 100644 index 0000000..a6c7696 --- /dev/null +++ b/tests/InstallationIdTest.php @@ -0,0 +1,28 @@ + 'usage', 'key' => 'count', 'type' => 'integer', 'value' => 3], Metric::integer('usage', 'count', 3)->toArray()); + self::assertSame('number', Metric::number('usage', 'ratio', 1.5)->type); + self::assertSame('boolean', Metric::boolean('feature', 'enabled', true)->type); + self::assertSame('string', Metric::string('environment', 'version', '12.0.0')->type); + } + + #[DataProvider('invalidIdentifiers')] + public function testRejectsInvalidIdentifiers(string $category, string $key): void + { + $this->expectException(InvalidArgumentException::class); + Metric::integer($category, $key, 1); + } + + /** @return iterable */ + public static function invalidIdentifiers(): iterable + { + yield 'empty category' => ['', 'key']; + yield 'spaces' => ['usage data', 'key']; + yield 'empty key' => ['usage', '']; + } + + public function testRejectsInfiniteNumber(): void + { + $this->expectException(InvalidArgumentException::class); + Metric::number('usage', 'ratio', INF); + } + + public function testRejectsOversizedString(): void + { + $this->expectException(InvalidArgumentException::class); + Metric::string('usage', 'value', str_repeat('x', 1025)); + } +} diff --git a/tests/ReportTest.php b/tests/ReportTest.php new file mode 100644 index 0000000..a0ab576 --- /dev/null +++ b/tests/ReportTest.php @@ -0,0 +1,59 @@ +toArray()['protocolVersion']); + self::assertSame('2026-08-01T00:00:00Z', $report->toArray()['period']['start']); + self::assertSame('12.0.0', $report->toArray()['metrics'][0]['value']); + } + + public function testRejectsDuplicateMetrics(): void + { + $period = new ReportingPeriod(new DateTimeImmutable('2026-08-01T00:00:00Z'), new DateTimeImmutable('2026-08-02T00:00:00Z')); + $this->expectException(InvalidArgumentException::class); + new Report('libresign', str_repeat('a', 64), 1, $period, [ + Metric::integer('usage', 'count', 1), + Metric::integer('usage', 'count', 2), + ]); + } + + public function testRejectsEmptyMetrics(): void + { + $period = new ReportingPeriod(new DateTimeImmutable('2026-08-01T00:00:00Z'), new DateTimeImmutable('2026-08-02T00:00:00Z')); + $this->expectException(InvalidArgumentException::class); + new Report('libresign', str_repeat('a', 64), 1, $period, []); + } + + public function testRejectsInvalidSchemaVersion(): void + { + $period = new ReportingPeriod(new DateTimeImmutable('2026-08-01T00:00:00Z'), new DateTimeImmutable('2026-08-02T00:00:00Z')); + $this->expectException(InvalidArgumentException::class); + new Report('libresign', str_repeat('a', 64), 0, $period, [Metric::integer('usage', 'count', 1)]); + } +} diff --git a/tests/ReportingPeriodTest.php b/tests/ReportingPeriodTest.php new file mode 100644 index 0000000..85c1ca7 --- /dev/null +++ b/tests/ReportingPeriodTest.php @@ -0,0 +1,41 @@ +toArray()['start']); + } + + public function testCreatesCalendarMonth(): void + { + $period = ReportingPeriod::monthContaining(new DateTimeImmutable('2026-02-13T12:30:00Z')); + self::assertSame('2026-02-01T00:00:00Z', $period->toArray()['start']); + self::assertSame('2026-03-01T00:00:00Z', $period->toArray()['end']); + } + + public function testRejectsNonPositivePeriod(): void + { + $instant = new DateTimeImmutable('2026-08-01T00:00:00Z'); + $this->expectException(InvalidArgumentException::class); + new ReportingPeriod($instant, $instant); + } +} From 2b51c904e159ab0772d4c9da32b0009d332f18d7 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 17:53:31 -0300 Subject: [PATCH 03/43] docs: document client integration and isolation Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- .github/dependabot.yml | 17 ++++++ .github/workflows/ci.yml | 115 +++++++++++++++++++++++++++++++++++++++ AGENTS.md | 17 ++++++ README.md | 98 ++++++++++++++++++++++----------- REUSE.toml | 20 +++++++ docs/architecture.md | 22 ++++++++ docs/development.md | 39 +++++++++++++ docs/integration.md | 32 +++++++++++ docs/mozart.md | 14 +++++ docs/php-scoper.md | 21 +++++++ docs/privacy.md | 16 ++++++ docs/troubleshooting.md | 26 +++++++++ docs/versioning.md | 16 ++++++ tests/scoping-smoke.php | 33 +++++++++++ 14 files changed, 454 insertions(+), 32 deletions(-) create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/ci.yml create mode 100644 AGENTS.md create mode 100644 REUSE.toml create mode 100644 docs/architecture.md create mode 100644 docs/development.md create mode 100644 docs/integration.md create mode 100644 docs/mozart.md create mode 100644 docs/php-scoper.md create mode 100644 docs/privacy.md create mode 100644 docs/troubleshooting.md create mode 100644 docs/versioning.md create mode 100644 tests/scoping-smoke.php diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..c3de74c --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,17 @@ +# SPDX-FileCopyrightText: 2026 LibreCode coop and contributors +# SPDX-License-Identifier: AGPL-3.0-or-later + +version: 2 +updates: + - package-ecosystem: composer + directory: / + schedule: + interval: weekly + groups: + development-tooling: + dependency-type: development + + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..a5e6765 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,115 @@ +# SPDX-FileCopyrightText: 2026 LibreCode coop and contributors +# SPDX-License-Identifier: AGPL-3.0-or-later + +name: CI + +on: + pull_request: + push: + branches: + - main + +permissions: + contents: read + +concurrency: + group: client-ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + name: PHP ${{ matrix.php }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + php: ['8.1', '8.4', '8.5'] + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up PHP + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: ${{ matrix.php }} + coverage: none + tools: composer + + - name: Validate Composer metadata + run: composer validate --strict + + - name: Install dependencies + run: composer install --no-interaction --prefer-dist + + - name: Test + run: composer test + + quality: + name: Quality + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up PHP + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: '8.4' + coverage: none + tools: composer + + - name: Install dependencies + run: composer install --no-interaction --prefer-dist + + - name: Lint + run: composer lint + + - name: Coding standard + run: composer phpcs + + - name: Static analysis + run: composer phpstan + + - name: Security audit + run: composer audit --no-interaction + + scoping: + name: Namespace scoping + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up PHP + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: '8.4' + coverage: none + tools: composer + + - name: Install dependencies + run: composer install --no-interaction --prefer-dist + + - name: Prefix package namespace + run: vendor/bin/php-scoper add-prefix --prefix=UsageStatisticsClientScoped --output-dir=build/scoped --force src + + - name: Load scoped package + run: php tests/scoping-smoke.php + + reuse: + name: REUSE + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: REUSE compliance + uses: fsfe/reuse-action@676e2d560c9a403aa252096d99fcab3e1132b0f5 # v6.0.0 diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..8b39a83 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,17 @@ + + +# Contributor notes + +This is a small framework-agnostic Protocol v1 client. Keep runtime dependencies and the public API minimal. + +- Source: `src/` +- Tests: `tests/` +- Design and integration notes: `docs/` +- Protocol source of truth: `LibreCodeCoop/usage_statistics_server/docs/protocol-v1.md` + +Run `composer qa` and `composer audit` before committing. Validate scoping as described in `docs/development.md` when changing namespaces or public contracts. + +Use Conventional Commits and `git commit -s`. Do not add application-specific LibreSign/Nextcloud code to the package core. diff --git a/README.md b/README.md index 9aa0e14..1487b0f 100644 --- a/README.md +++ b/README.md @@ -1,49 +1,83 @@ + + # Usage Statistics Client -Reusable PHP/Composer client primitives for applications that want to collect and submit opt-in, privacy-preserving usage statistics. +Framework-agnostic PHP client for applications that submit opt-in usage statistics using [Usage Statistics Protocol v1](https://github.com/LibreCodeCoop/usage_statistics_server/blob/main/docs/protocol-v1.md). + +The package provides typed report primitives, pseudonymous installation-ID derivation, consent gating, payload serialization, a small HTTP transport boundary, and response/error handling. Applications remain responsible for their metrics, consent UI and persistence, endpoint configuration, scheduling, and logging policy. + +## Requirements + +- PHP 8.1 or newer +- Composer +- an HTTPS report endpoint compatible with Protocol v1 + +## Install -The package is designed to be application-agnostic. Applications own their metric definitions, consent experience, and default receiving endpoint. +```bash +composer require vitormattos/usage-statistics-client +``` -## Responsibilities +## Minimal use -The client package is expected to provide: +```php +use LibreCode\UsageStatistics\Client; +use LibreCode\UsageStatistics\ConsentState; +use LibreCode\UsageStatistics\Endpoint; +use LibreCode\UsageStatistics\InstallationId; +use LibreCode\UsageStatistics\Metric; +use LibreCode\UsageStatistics\Report; +use LibreCode\UsageStatistics\ReportingPeriod; +use LibreCode\UsageStatistics\Transport\StreamTransport; -- provider contracts for application-defined metrics; -- report and metric value objects; -- reporting-period helpers; -- consent-state persistence abstractions; -- pseudonymous installation identifier helpers; -- endpoint resolution with application default plus administrator override; -- payload validation and serialization; -- HTTPS report submission; -- last-successful-send state; -- helpers for background jobs and OCC commands in Nextcloud applications. +$installationId = InstallationId::derive('libresign', $localInstallationIdentifier); -## Explicit non-responsibilities +$report = new Report( + application: 'libresign', + installationId: (string)$installationId, + schemaVersion: 1, + period: ReportingPeriod::monthContaining(new DateTimeImmutable('2026-08-15T00:00:00Z')), + metrics: [ + Metric::string('environment', 'version', '12.0.0'), + Metric::integer('usage', 'requests_completed', 72), + ], +); -The package does not: +$client = new Client( + new StreamTransport(), + new Endpoint('https://statistics.example/apps/usage_statistics_server/api/v1/reports'), +); -- decide which metrics an application should collect; -- provide a global LibreSign endpoint; -- silently enable reporting; -- own application-specific settings pages; -- require or integrate with Nextcloud `survey_client`; -- claim to verify the truthfulness of values reported by a self-hosted client. +$result = $client->submit($report, ConsentState::Enabled); +``` -## Consent model +`unknown` and `disabled` consent states never send a request. Network and HTTP failures are surfaced to the application; the client deliberately does not retry automatically, so a background scheduler can decide when to try again without blocking normal application work. -The planned shared consent state is tri-state: +## Design constraints -- `unknown`: no decision has been recorded; -- `enabled`: the administrator opted in; -- `disabled`: the administrator opted out. +- no Nextcloud or LibreSign runtime dependency; +- no PSR-7/PSR-18 contract exposed in the public API; +- no authentication, signing, or attestation invented beyond Protocol v1; +- no automatic logging of report payloads; +- no user-level event model; +- runtime dependencies are intentionally zero. -Applications decide when and how to present the initial request. Once a decision is recorded, the client library must not independently prompt again. +The package is designed so its own namespace can be prefixed when bundled into isolated dependency trees such as LibreSign's `3rdparty` directory. -## Protocol +## Documentation -The initial implementation targets Usage Statistics Protocol v1 defined by the server project. +- [Architecture](docs/architecture.md) +- [Integration](docs/integration.md) +- [Privacy](docs/privacy.md) +- [PHP-Scoper](docs/php-scoper.md) +- [Mozart](docs/mozart.md) +- [Versioning](docs/versioning.md) +- [Development](docs/development.md) +- [Troubleshooting](docs/troubleshooting.md) -## Status +## License -Early design and implementation. +AGPL-3.0-or-later. See `LICENSES/AGPL-3.0-or-later.txt`. diff --git a/REUSE.toml b/REUSE.toml new file mode 100644 index 0000000..0ab7d72 --- /dev/null +++ b/REUSE.toml @@ -0,0 +1,20 @@ +# SPDX-FileCopyrightText: 2026 LibreCode coop and contributors +# SPDX-License-Identifier: AGPL-3.0-or-later + +version = 1 +SPDX-PackageName = "usage-statistics-client" +SPDX-PackageDownloadLocation = "https://github.com/vitormattos/usage_statistics_client/" + +default-license = "AGPL-3.0-or-later" +default-copyright = "2026 LibreCode coop and contributors" + +[[annotations]] +path = [ + "composer.json", + "phpcs.xml.dist", + "phpstan.neon", + "phpunit.xml.dist" +] +precedence = "aggregate" +SPDX-FileCopyrightText = "2026 LibreCode coop and contributors" +SPDX-License-Identifier = "AGPL-3.0-or-later" diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..9376ec3 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,22 @@ + + +# Architecture + +The package keeps the supported surface deliberately small. + +`Metric`, `ReportingPeriod`, `Report`, `InstallationId`, `Endpoint`, `ConsentState`, `Client`, and the transport types form the public API. Application-specific metric definitions, settings pages, persistence, background jobs, OCC commands, and logging stay in the host application. + +The flow is: + +```text +application metrics -> Report -> consent gate -> JSON serialization -> TransportInterface -> server +``` + +The client performs stable Protocol v1 validations that catch programming errors before a request: identifier syntax and lengths, metric type/value compatibility, duplicate metrics, positive schema version, metric-count bounds, and the 31-day maximum reporting period. It does not duplicate server-side schema registration or administrative validation. + +`TransportInterface` belongs to this package instead of exposing PSR-18/PSR-7. This is intentional: a consumer that prefixes the complete dependency tree must not accidentally make a prefixed PSR interface incompatible with an unprefixed object supplied by the host application. + +`StreamTransport` is a zero-dependency default. Consumers may replace it with an adapter around their framework HTTP client. diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 0000000..46938ae --- /dev/null +++ b/docs/development.md @@ -0,0 +1,39 @@ + + +# Development + +Install dependencies: + +```bash +composer install +``` + +Run the main checks: + +```bash +composer qa +composer audit +``` + +Run coverage when Xdebug or PCOV coverage is available: + +```bash +composer test:coverage +``` + +Validate namespace prefixing: + +```bash +rm -rf build/scoped +vendor/bin/php-scoper add-prefix --prefix=UsageStatisticsClientScoped --output-dir=build/scoped --force src +php tests/scoping-smoke.php +``` + +Commits use Conventional Commits and Developer Certificate of Origin sign-off, for example: + +```bash +git commit -s -m 'feat: add report submission client' +``` diff --git a/docs/integration.md b/docs/integration.md new file mode 100644 index 0000000..2e62899 --- /dev/null +++ b/docs/integration.md @@ -0,0 +1,32 @@ + + +# Application integration + +The host application owns five decisions: its stable application ID, schema version, metric definitions, consent persistence, and report endpoint. + +## Consent + +Persist consent in the host application's normal settings store. Translate it to `ConsentState` immediately before submission. `unknown` and `disabled` both cause `Client::submit()` to return `SubmissionResult::SkippedWithoutConsent` without invoking the transport. + +The library never prompts a user and never changes consent state. + +## Endpoint + +Pass the complete Protocol v1 report URL to `Endpoint`. It must use HTTPS and must not contain embedded credentials, a query string, or a fragment. Applications may ship their own default and expose an administrator override. + +Do not put a LibreSign-specific default in shared library code. + +## Scheduling + +Run reporting from the host application's background-job mechanism. A monthly calendar period is the initial recommended cadence. `ReportingPeriod::monthContaining()` is provided for that common case. + +The client does not retry internally. On `TransportException` or `ServerRejectedException::isTransient() === true`, let a later scheduled execution decide whether to retry. This keeps telemetry failures outside latency-sensitive application paths. + +## Transport adapters + +A framework can implement `TransportInterface` around its existing HTTP client. The adapter receives the method, absolute URL, headers, JSON body, and total timeout, and returns a small `Response` object. + +Do not log the request body by default. A malformed host integration could accidentally add sensitive data even though the protocol forbids it. diff --git a/docs/mozart.md b/docs/mozart.md new file mode 100644 index 0000000..7d3e630 --- /dev/null +++ b/docs/mozart.md @@ -0,0 +1,14 @@ + + +# Mozart + +Mozart and PHP-Scoper solve related packaging problems but do not use the same build model. Mozart is normally configured by the consuming project to copy and prefix selected Composer dependencies into that project's own dependency namespace. + +For this package, configure the consumer to treat `vitormattos/usage-statistics-client` as a dependency to be copied and prefix the `LibreCode\\UsageStatistics\\` namespace into the consumer's private vendor namespace. + +Do not prefix only third-party dependencies while leaving this package global if the goal is to let two host applications load different client versions in one PHP process. The package namespace itself must also be isolated. + +The exact Mozart configuration depends on the consumer's Mozart version and packaging layout, so this repository does not ship a consumer-specific `mozart.json`. The important compatibility property is that the client contains no hard-coded original FQCN strings or unprefixable runtime dependency. diff --git a/docs/php-scoper.md b/docs/php-scoper.md new file mode 100644 index 0000000..87ba6ae --- /dev/null +++ b/docs/php-scoper.md @@ -0,0 +1,21 @@ + + +# PHP-Scoper + +The package is intended to tolerate prefixing of its complete namespace. It has no runtime Composer dependency and exposes no third-party interface in its public API. + +A minimal build-time smoke command is: + +```bash +vendor/bin/php-scoper add-prefix \ + --prefix=OCA\\LibreSign\\Vendor \ + --output-dir=build/scoped \ + --force src +``` + +A consumer should normally scope the package as part of its complete vendor build rather than scope only `src/` in isolation. Rebuild Composer autoload metadata after producing the scoped tree according to the consuming application's packaging process. + +The repository CI runs a smoke build with PHP-Scoper and loads scoped public classes. If a future public API introduces third-party contracts, revisit scoping before releasing that change. diff --git a/docs/privacy.md b/docs/privacy.md new file mode 100644 index 0000000..584cfdd --- /dev/null +++ b/docs/privacy.md @@ -0,0 +1,16 @@ + + +# Privacy model + +Protocol v1 is for opt-in aggregate usage statistics. It is not a user-event tracking protocol. + +Applications must not submit names, email addresses, user IDs, document or file names, document contents, raw instance URLs or hostnames, authentication material, secrets, IP addresses as metric values, or individual user event streams. + +`InstallationId::derive()` hashes a domain-separated combination of the application ID and a host-provided local installation identifier. This makes the resulting 64-character identifier stable for the same application and local installation while preventing the raw identifier from being sent. Different application IDs produce different derived identifiers for the same local input. + +This is pseudonymization, not anonymization. If the local input has low entropy and becomes known to an observer, it may be guessable. Applications should use a stable, non-public installation identifier as input and must not pass a hostname, URL, email, user ID, token, or secret as the report identifier itself. + +Transport infrastructure can still observe metadata such as source IP addresses. Server logging and retention are separate operational concerns. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md new file mode 100644 index 0000000..dcc88a9 --- /dev/null +++ b/docs/troubleshooting.md @@ -0,0 +1,26 @@ + + +# Troubleshooting + +## Nothing was sent + +Check the consent state first. `unknown` and `disabled` deliberately return `SkippedWithoutConsent` without touching the transport. + +## `TransportException` + +The endpoint could not be reached or the transport could not obtain a valid HTTP response. Keep telemetry failures out of the application's primary operation and let a later background-job execution retry when appropriate. + +## `ServerRejectedException` + +Inspect `statusCode` and `errorCode`. Protocol v1 currently uses `400 invalid_report` for invalid reports and `409 conflicting_report` when another schema version was already accepted for the same logical reporting period. `429` and `5xx` responses are classified as transient by `isTransient()`. + +## `ProtocolException` + +The server returned a success response that does not match the Protocol v1 `{"status":"accepted"}` contract or returned invalid JSON. + +## Schema registration errors + +The client cannot register application schemas. The `(application, schemaVersion)` definition must already exist on the Usage Statistics Server. diff --git a/docs/versioning.md b/docs/versioning.md new file mode 100644 index 0000000..b140c74 --- /dev/null +++ b/docs/versioning.md @@ -0,0 +1,16 @@ + + +# Versioning + +The package follows Semantic Versioning. + +Public classes, enums, interfaces, constructor signatures, return types, exception contracts, and serialized Protocol v1 behavior are part of the supported API once a stable release is published. + +A protocol schema version is not a package version. Applications can update their metric schema independently by sending the appropriate `schemaVersion` registered on the server. + +Protocol evolution must be explicit. A future Protocol v2 must not silently change Protocol v1 serialization or response handling. + +Deprecated public APIs should remain functional for at least one normal minor-release migration window before removal in the next major release, unless a security issue requires faster action. diff --git a/tests/scoping-smoke.php b/tests/scoping-smoke.php new file mode 100644 index 0000000..2912a17 --- /dev/null +++ b/tests/scoping-smoke.php @@ -0,0 +1,33 @@ +value !== 'enabled') { + throw new RuntimeException('Scoped enum did not load correctly.'); +} + +$metric = UsageStatisticsClientScoped\LibreCode\UsageStatistics\Metric::integer('usage', 'count', 1); +if ($metric->toArray()['value'] !== 1) { + throw new RuntimeException('Scoped value object did not execute correctly.'); +} From 78f1170083dab5a112f5c507eda70f85b864a212 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 17:55:08 -0300 Subject: [PATCH 04/43] chore: add REUSE license text Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- LICENSES/AGPL-3.0-or-later.txt | 232 +++++++++++++++++++++++++++++++++ 1 file changed, 232 insertions(+) create mode 100644 LICENSES/AGPL-3.0-or-later.txt diff --git a/LICENSES/AGPL-3.0-or-later.txt b/LICENSES/AGPL-3.0-or-later.txt new file mode 100644 index 0000000..9e3b16e --- /dev/null +++ b/LICENSES/AGPL-3.0-or-later.txt @@ -0,0 +1,232 @@ +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + + Preamble + +The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. + +The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. + +The precise terms and conditions for copying, distribution and modification follow. + + TERMS AND CONDITIONS + +0. Definitions. + +"This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the Program. + +To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. + +A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce it, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the covered work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". + + c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + + a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. + + d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. + + e) Convey individual copies of the object code using peer-to-peer transmission, provided you inform other peers where the object code and the Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the class of product. + +"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or authors of the material; or + + e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. + +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. + +A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. + +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing a later version. + +15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. + +You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . From 5909aca63c49be61fee175fc9f6b59d3d89e21da Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 17:57:54 -0300 Subject: [PATCH 05/43] fix: resolve initial CI failures Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- .github/workflows/ci.yml | 5 +++- REUSE.toml | 1 + composer.json | 2 -- docs/development.md | 3 ++- phpcs.xml.dist | 1 + src/Endpoint.php | 7 ++++-- src/InstallationId.php | 6 ++++- tests/ClientTest.php | 28 ---------------------- tests/RecordingTransport.php | 45 ++++++++++++++++++++++++++++++++++++ 9 files changed, 63 insertions(+), 35 deletions(-) create mode 100644 tests/RecordingTransport.php diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a5e6765..395980e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -96,8 +96,11 @@ jobs: - name: Install dependencies run: composer install --no-interaction --prefer-dist + - name: Install PHP-Scoper + run: composer global require --no-interaction humbug/php-scoper:^0.18.17 + - name: Prefix package namespace - run: vendor/bin/php-scoper add-prefix --prefix=UsageStatisticsClientScoped --output-dir=build/scoped --force src + run: "$(composer global config bin-dir --absolute)/php-scoper" add-prefix --prefix=UsageStatisticsClientScoped --output-dir=build/scoped --force src - name: Load scoped package run: php tests/scoping-smoke.php diff --git a/REUSE.toml b/REUSE.toml index 0ab7d72..0bc73bd 100644 --- a/REUSE.toml +++ b/REUSE.toml @@ -10,6 +10,7 @@ default-copyright = "2026 LibreCode coop and contributors" [[annotations]] path = [ + ".gitignore", "composer.json", "phpcs.xml.dist", "phpstan.neon", diff --git a/composer.json b/composer.json index 68b9dd6..46eac9a 100644 --- a/composer.json +++ b/composer.json @@ -13,7 +13,6 @@ "php": ">=8.1" }, "require-dev": { - "humbug/php-scoper": "^0.18.17", "phpstan/phpstan": "^2.1", "phpunit/phpunit": "^10.5 || ^11.5 || ^12.0", "squizlabs/php_codesniffer": "^3.13" @@ -34,7 +33,6 @@ "test:coverage": "XDEBUG_MODE=coverage phpunit --coverage-text", "phpstan": "phpstan analyse -c phpstan.neon", "phpcs": "phpcs -q", - "audit": "composer audit --no-interaction", "qa": [ "@lint", "@phpcs", diff --git a/docs/development.md b/docs/development.md index 46938ae..808af28 100644 --- a/docs/development.md +++ b/docs/development.md @@ -28,7 +28,8 @@ Validate namespace prefixing: ```bash rm -rf build/scoped -vendor/bin/php-scoper add-prefix --prefix=UsageStatisticsClientScoped --output-dir=build/scoped --force src +composer global require humbug/php-scoper:^0.18.17 +"$(composer global config bin-dir --absolute)/php-scoper" add-prefix --prefix=UsageStatisticsClientScoped --output-dir=build/scoped --force src php tests/scoping-smoke.php ``` diff --git a/phpcs.xml.dist b/phpcs.xml.dist index 49d5002..f7740b5 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -5,5 +5,6 @@ tests + diff --git a/src/Endpoint.php b/src/Endpoint.php index bacc0b4..42128ff 100644 --- a/src/Endpoint.php +++ b/src/Endpoint.php @@ -18,7 +18,8 @@ final class Endpoint public function __construct(string $url) { $parts = parse_url($url); - if (!is_array($parts) + if ( + !is_array($parts) || ($parts['scheme'] ?? null) !== 'https' || !isset($parts['host']) || $parts['host'] === '' @@ -27,7 +28,9 @@ public function __construct(string $url) || isset($parts['query']) || isset($parts['fragment']) ) { - throw new InvalidArgumentException('Report endpoint must be an HTTPS URL without credentials, query, or fragment.'); + throw new InvalidArgumentException( + 'Report endpoint must be an HTTPS URL without credentials, query, or fragment.', + ); } $this->url = rtrim($url, '/'); diff --git a/src/InstallationId.php b/src/InstallationId.php index 9426349..703a94b 100644 --- a/src/InstallationId.php +++ b/src/InstallationId.php @@ -21,7 +21,11 @@ private function __construct(public readonly string $value) public static function derive(string $application, string $localInstallationIdentifier): self { - if ($application === '' || strlen($application) > 128 || preg_match(self::APPLICATION_PATTERN, $application) !== 1) { + if ( + $application === '' + || strlen($application) > 128 + || preg_match(self::APPLICATION_PATTERN, $application) !== 1 + ) { throw new InvalidArgumentException('Application identifier is invalid.'); } if ($localInstallationIdentifier === '') { diff --git a/tests/ClientTest.php b/tests/ClientTest.php index b8cf55f..d9e9e89 100644 --- a/tests/ClientTest.php +++ b/tests/ClientTest.php @@ -20,7 +20,6 @@ use LibreCode\UsageStatistics\ReportingPeriod; use LibreCode\UsageStatistics\SubmissionResult; use LibreCode\UsageStatistics\Transport\Response; -use LibreCode\UsageStatistics\Transport\TransportInterface; use PHPUnit\Framework\TestCase; final class ClientTest extends TestCase @@ -98,30 +97,3 @@ private function report(): Report ); } } - -final class RecordingTransport implements TransportInterface -{ - public int $calls = 0; - public string $method = ''; - public string $url = ''; - /** @var array */ - public array $headers = []; - public string $body = ''; - public float $timeout = 0.0; - - public function __construct(private readonly Response $response) - { - } - - public function request(string $method, string $url, array $headers, string $body, float $timeoutSeconds): Response - { - ++$this->calls; - $this->method = $method; - $this->url = $url; - $this->headers = $headers; - $this->body = $body; - $this->timeout = $timeoutSeconds; - - return $this->response; - } -} diff --git a/tests/RecordingTransport.php b/tests/RecordingTransport.php new file mode 100644 index 0000000..889f66b --- /dev/null +++ b/tests/RecordingTransport.php @@ -0,0 +1,45 @@ + */ + public array $headers = []; + public string $body = ''; + public float $timeout = 0.0; + + public function __construct(private readonly Response $response) + { + } + + public function request( + string $method, + string $url, + array $headers, + string $body, + float $timeoutSeconds, + ): Response { + ++$this->calls; + $this->method = $method; + $this->url = $url; + $this->headers = $headers; + $this->body = $body; + $this->timeout = $timeoutSeconds; + + return $this->response; + } +} From ef472a7557522a408e40f45b9556ae4efae259ee Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 18:00:01 -0300 Subject: [PATCH 06/43] test: enforce coverage and response handling Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- .github/workflows/ci.yml | 25 +++++++++++++++++++++++++ composer.json | 2 +- src/Client.php | 1 - src/Transport/Response.php | 10 +++++++++- tests/ResponseTest.php | 24 ++++++++++++++++++++++++ tests/StreamTransportTest.php | 25 +++++++++++++++++++++++++ tests/coverage-threshold.php | 25 +++++++++++++++++++++++++ 7 files changed, 109 insertions(+), 3 deletions(-) create mode 100644 tests/ResponseTest.php create mode 100644 tests/StreamTransportTest.php create mode 100644 tests/coverage-threshold.php diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 395980e..7067873 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -46,6 +46,31 @@ jobs: - name: Test run: composer test + coverage: + name: Coverage + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up PHP + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: '8.4' + coverage: xdebug + tools: composer + + - name: Install dependencies + run: composer install --no-interaction --prefer-dist + + - name: Measure coverage + run: composer test:coverage + + - name: Enforce coverage threshold + run: php tests/coverage-threshold.php build/coverage.xml 75 + quality: name: Quality runs-on: ubuntu-latest diff --git a/composer.json b/composer.json index 46eac9a..b79e7a6 100644 --- a/composer.json +++ b/composer.json @@ -30,7 +30,7 @@ "scripts": { "lint": "find src tests -name '*.php' -print0 | xargs -0 -n1 php -l", "test": "phpunit --colors=always --fail-on-warning --fail-on-risky", - "test:coverage": "XDEBUG_MODE=coverage phpunit --coverage-text", + "test:coverage": "XDEBUG_MODE=coverage phpunit --coverage-text --coverage-clover build/coverage.xml", "phpstan": "phpstan analyse -c phpstan.neon", "phpcs": "phpcs -q", "qa": [ diff --git a/src/Client.php b/src/Client.php index 22cff06..8182f13 100644 --- a/src/Client.php +++ b/src/Client.php @@ -44,7 +44,6 @@ public function submit(Report $report, ConsentState $consent): SubmissionResult [ 'Accept' => 'application/json', 'Content-Type' => 'application/json', - 'User-Agent' => 'usage-statistics-client/1', ], $payload, $this->timeoutSeconds, diff --git a/src/Transport/Response.php b/src/Transport/Response.php index 63d7c30..19216ef 100644 --- a/src/Transport/Response.php +++ b/src/Transport/Response.php @@ -11,12 +11,20 @@ final class Response { + /** @var array */ + public readonly array $headers; + /** @param array $headers */ public function __construct( public readonly int $statusCode, public readonly string $body, - public readonly array $headers = [], + array $headers = [], ) { + $normalized = []; + foreach ($headers as $name => $value) { + $normalized[strtolower($name)] = $value; + } + $this->headers = $normalized; } public function header(string $name): ?string diff --git a/tests/ResponseTest.php b/tests/ResponseTest.php new file mode 100644 index 0000000..ca7a5af --- /dev/null +++ b/tests/ResponseTest.php @@ -0,0 +1,24 @@ + '60']); + + self::assertSame('60', $response->header('retry-after')); + self::assertSame('60', $response->header('RETRY-AFTER')); + } +} diff --git a/tests/StreamTransportTest.php b/tests/StreamTransportTest.php new file mode 100644 index 0000000..962fb3d --- /dev/null +++ b/tests/StreamTransportTest.php @@ -0,0 +1,25 @@ +expectException(TransportException::class); + $transport->request('POST', 'https://example.invalid', [], '{}', 0.0); + } +} diff --git a/tests/coverage-threshold.php b/tests/coverage-threshold.php new file mode 100644 index 0000000..2e21b87 --- /dev/null +++ b/tests/coverage-threshold.php @@ -0,0 +1,25 @@ +project->metrics; +$statements = (int)$metrics['statements']; +$covered = (int)$metrics['coveredstatements']; +$percentage = $statements === 0 ? 0.0 : ($covered / $statements) * 100; + +printf("Line coverage: %.2f%% (minimum %.2f%%)\n", $percentage, $minimum); +exit($percentage >= $minimum ? 0 : 1); From be38d22e6430f9469f7b8bb70bf2a7a197f145a2 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 18:01:57 -0300 Subject: [PATCH 07/43] fix: prepare strict static analysis Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- phpstan.neon | 5 +++++ src/Report.php | 3 --- tests/ClientTest.php | 3 +++ 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/phpstan.neon b/phpstan.neon index c7ca44a..5334969 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -4,3 +4,8 @@ parameters: - src - tests tmpDir: .phpstan-cache + + excludePaths: + analyse: + - tests/scoping-smoke.php + - tests/coverage-threshold.php diff --git a/src/Report.php b/src/Report.php index 60a27ea..5aa356a 100644 --- a/src/Report.php +++ b/src/Report.php @@ -39,9 +39,6 @@ public function __construct( $seen = []; foreach ($metrics as $metric) { - if (!$metric instanceof Metric) { - throw new InvalidArgumentException('Every report metric must be a Metric instance.'); - } $identity = $metric->identity(); if (isset($seen[$identity])) { throw new InvalidArgumentException('Duplicate metric category/key pair.'); diff --git a/tests/ClientTest.php b/tests/ClientTest.php index d9e9e89..c49b80c 100644 --- a/tests/ClientTest.php +++ b/tests/ClientTest.php @@ -45,6 +45,9 @@ public function testSendsProtocolPayloadWhenEnabled(): void self::assertSame(2.5, $transport->timeout); self::assertSame('application/json', $transport->headers['Content-Type']); $payload = json_decode($transport->body, true, 512, JSON_THROW_ON_ERROR); + if (!is_array($payload)) { + throw new \UnexpectedValueException('Expected serialized report to be an array.'); + } self::assertSame(1, $payload['protocolVersion']); self::assertSame('libresign', $payload['application']); } From 1de86d4063d8fd3587a9ccbf74237f372220b725 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 18:03:27 -0300 Subject: [PATCH 08/43] test: lock installation id derivation vector Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- tests/InstallationIdTest.php | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/InstallationIdTest.php b/tests/InstallationIdTest.php index a6c7696..34d7715 100644 --- a/tests/InstallationIdTest.php +++ b/tests/InstallationIdTest.php @@ -20,6 +20,7 @@ public function testDerivationIsStableAndApplicationScoped(): void $second = (string)InstallationId::derive('libresign', 'local-instance-id'); $otherApp = (string)InstallationId::derive('talk', 'local-instance-id'); + self::assertSame('dc8adebdce9ab99790a7d037f44965b4ca7b6dceb38d5e7c9dff118721fc8415', $first); self::assertSame($first, $second); self::assertNotSame($first, $otherApp); self::assertMatchesRegularExpression('/^[a-f0-9]{64}$/', $first); From a0ef1e25a91984e119fe60630a820903dc7614a4 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 18:05:31 -0300 Subject: [PATCH 09/43] fix: harden coverage and period helpers Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- composer.json | 5 ++++- src/ReportingPeriod.php | 7 +++++-- src/Transport/StreamTransport.php | 1 + tests/RecordingTransport.php | 1 + 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index b79e7a6..bf6eecc 100644 --- a/composer.json +++ b/composer.json @@ -30,7 +30,10 @@ "scripts": { "lint": "find src tests -name '*.php' -print0 | xargs -0 -n1 php -l", "test": "phpunit --colors=always --fail-on-warning --fail-on-risky", - "test:coverage": "XDEBUG_MODE=coverage phpunit --coverage-text --coverage-clover build/coverage.xml", + "test:coverage": [ + "@php -r \"is_dir('build') || mkdir('build', 0777, true);\"", + "XDEBUG_MODE=coverage phpunit --coverage-text --coverage-clover build/coverage.xml" + ], "phpstan": "phpstan analyse -c phpstan.neon", "phpcs": "phpcs -q", "qa": [ diff --git a/src/ReportingPeriod.php b/src/ReportingPeriod.php index c8e4d05..8ad8933 100644 --- a/src/ReportingPeriod.php +++ b/src/ReportingPeriod.php @@ -9,6 +9,7 @@ namespace LibreCode\UsageStatistics; +use DateInterval; use DateTimeImmutable; use DateTimeZone; use InvalidArgumentException; @@ -35,8 +36,10 @@ public function __construct(DateTimeImmutable $start, DateTimeImmutable $end) public static function monthContaining(DateTimeImmutable $instant): self { $utc = $instant->setTimezone(new DateTimeZone('UTC')); - $start = $utc->modify('first day of this month')->setTime(0, 0, 0, 0); - $end = $start->modify('first day of next month'); + $start = $utc + ->setDate((int)$utc->format('Y'), (int)$utc->format('m'), 1) + ->setTime(0, 0, 0, 0); + $end = $start->add(new DateInterval('P1M')); return new self($start, $end); } diff --git a/src/Transport/StreamTransport.php b/src/Transport/StreamTransport.php index 3b60609..40c4cf1 100644 --- a/src/Transport/StreamTransport.php +++ b/src/Transport/StreamTransport.php @@ -13,6 +13,7 @@ final class StreamTransport implements TransportInterface { + /** @param array $headers */ public function request(string $method, string $url, array $headers, string $body, float $timeoutSeconds): Response { if ($timeoutSeconds <= 0) { diff --git a/tests/RecordingTransport.php b/tests/RecordingTransport.php index 889f66b..e045355 100644 --- a/tests/RecordingTransport.php +++ b/tests/RecordingTransport.php @@ -26,6 +26,7 @@ public function __construct(private readonly Response $response) { } + /** @param array $headers */ public function request( string $method, string $url, From 1348616969e2d39bd6a868222c581f6b8828c596 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 20:37:37 -0300 Subject: [PATCH 10/43] chore: align project tooling with LibreSign Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- .github/workflows/ci.yml | 143 ----------- .github/workflows/composer.yml | 24 ++ .github/workflows/infection.yml | 23 ++ .github/workflows/lint-php-cs.yml | 30 +++ .github/workflows/lint-php.yml | 28 +++ .github/workflows/phpmd.yml | 23 ++ .github/workflows/phpstan.yml | 23 ++ .github/workflows/phpunit.yml | 31 +++ .github/workflows/psalm.yml | 23 ++ .github/workflows/reuse.yml | 21 ++ .github/workflows/scoping.yml | 25 ++ .gitignore | 4 + .php-cs-fixer.dist.php | 25 ++ CONTRIBUTING.md | 28 +++ COPYING | 232 ++++++++++++++++++ README.md | 41 +--- REUSE.toml | 12 +- composer.json | 65 +++-- composer.lock | 57 +++++ infection.json5 | 18 ++ phpcs.xml.dist | 17 +- phpmd.xml | 13 + phpstan.neon | 12 +- phpunit.xml.dist | 14 +- psalm.xml | 15 ++ tests/{ => Unit}/ClientTest.php | 0 tests/{ => Unit}/EndpointTest.php | 0 tests/{ => Unit}/InstallationIdTest.php | 0 tests/{ => Unit}/MetricTest.php | 0 tests/{ => Unit}/RecordingTransport.php | 0 tests/{ => Unit}/ReportTest.php | 0 tests/{ => Unit}/ReportingPeriodTest.php | 0 tests/{ => Unit/Transport}/ResponseTest.php | 0 .../Transport}/StreamTransportTest.php | 0 tests/coverage-threshold.php | 25 -- vendor-bin/coding-standard/composer.json | 10 + vendor-bin/infection/composer.json | 11 + vendor-bin/phpmd/composer.json | 8 + vendor-bin/phpstan/composer.json | 8 + vendor-bin/phpunit/composer.json | 8 + vendor-bin/psalm/composer.json | 8 + 41 files changed, 783 insertions(+), 242 deletions(-) delete mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/composer.yml create mode 100644 .github/workflows/infection.yml create mode 100644 .github/workflows/lint-php-cs.yml create mode 100644 .github/workflows/lint-php.yml create mode 100644 .github/workflows/phpmd.yml create mode 100644 .github/workflows/phpstan.yml create mode 100644 .github/workflows/phpunit.yml create mode 100644 .github/workflows/psalm.yml create mode 100644 .github/workflows/reuse.yml create mode 100644 .github/workflows/scoping.yml create mode 100644 .php-cs-fixer.dist.php create mode 100644 CONTRIBUTING.md create mode 100644 COPYING create mode 100644 composer.lock create mode 100644 infection.json5 create mode 100644 phpmd.xml create mode 100644 psalm.xml rename tests/{ => Unit}/ClientTest.php (100%) rename tests/{ => Unit}/EndpointTest.php (100%) rename tests/{ => Unit}/InstallationIdTest.php (100%) rename tests/{ => Unit}/MetricTest.php (100%) rename tests/{ => Unit}/RecordingTransport.php (100%) rename tests/{ => Unit}/ReportTest.php (100%) rename tests/{ => Unit}/ReportingPeriodTest.php (100%) rename tests/{ => Unit/Transport}/ResponseTest.php (100%) rename tests/{ => Unit/Transport}/StreamTransportTest.php (100%) delete mode 100644 tests/coverage-threshold.php create mode 100644 vendor-bin/coding-standard/composer.json create mode 100644 vendor-bin/infection/composer.json create mode 100644 vendor-bin/phpmd/composer.json create mode 100644 vendor-bin/phpstan/composer.json create mode 100644 vendor-bin/phpunit/composer.json create mode 100644 vendor-bin/psalm/composer.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml deleted file mode 100644 index 7067873..0000000 --- a/.github/workflows/ci.yml +++ /dev/null @@ -1,143 +0,0 @@ -# SPDX-FileCopyrightText: 2026 LibreCode coop and contributors -# SPDX-License-Identifier: AGPL-3.0-or-later - -name: CI - -on: - pull_request: - push: - branches: - - main - -permissions: - contents: read - -concurrency: - group: client-ci-${{ github.ref }} - cancel-in-progress: true - -jobs: - test: - name: PHP ${{ matrix.php }} - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - php: ['8.1', '8.4', '8.5'] - steps: - - name: Checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - - name: Set up PHP - uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 - with: - php-version: ${{ matrix.php }} - coverage: none - tools: composer - - - name: Validate Composer metadata - run: composer validate --strict - - - name: Install dependencies - run: composer install --no-interaction --prefer-dist - - - name: Test - run: composer test - - coverage: - name: Coverage - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - - name: Set up PHP - uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 - with: - php-version: '8.4' - coverage: xdebug - tools: composer - - - name: Install dependencies - run: composer install --no-interaction --prefer-dist - - - name: Measure coverage - run: composer test:coverage - - - name: Enforce coverage threshold - run: php tests/coverage-threshold.php build/coverage.xml 75 - - quality: - name: Quality - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - - name: Set up PHP - uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 - with: - php-version: '8.4' - coverage: none - tools: composer - - - name: Install dependencies - run: composer install --no-interaction --prefer-dist - - - name: Lint - run: composer lint - - - name: Coding standard - run: composer phpcs - - - name: Static analysis - run: composer phpstan - - - name: Security audit - run: composer audit --no-interaction - - scoping: - name: Namespace scoping - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - - name: Set up PHP - uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 - with: - php-version: '8.4' - coverage: none - tools: composer - - - name: Install dependencies - run: composer install --no-interaction --prefer-dist - - - name: Install PHP-Scoper - run: composer global require --no-interaction humbug/php-scoper:^0.18.17 - - - name: Prefix package namespace - run: "$(composer global config bin-dir --absolute)/php-scoper" add-prefix --prefix=UsageStatisticsClientScoped --output-dir=build/scoped --force src - - - name: Load scoped package - run: php tests/scoping-smoke.php - - reuse: - name: REUSE - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - - name: REUSE compliance - uses: fsfe/reuse-action@676e2d560c9a403aa252096d99fcab3e1132b0f5 # v6.0.0 diff --git a/.github/workflows/composer.yml b/.github/workflows/composer.yml new file mode 100644 index 0000000..bcf81c8 --- /dev/null +++ b/.github/workflows/composer.yml @@ -0,0 +1,24 @@ +# SPDX-FileCopyrightText: 2026 LibreCode coop and contributors +# SPDX-License-Identifier: AGPL-3.0-or-later + +name: Composer + +on: pull_request + +permissions: + contents: read + +jobs: + validate: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: '8.2' + coverage: none + - run: composer validate --strict + - run: composer install --no-interaction --prefer-dist + - run: composer audit --no-interaction diff --git a/.github/workflows/infection.yml b/.github/workflows/infection.yml new file mode 100644 index 0000000..86112ef --- /dev/null +++ b/.github/workflows/infection.yml @@ -0,0 +1,23 @@ +# SPDX-FileCopyrightText: 2026 LibreCode coop and contributors +# SPDX-License-Identifier: AGPL-3.0-or-later + +name: Infection + +on: pull_request + +permissions: + contents: read + +jobs: + mutation-tests: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: '8.3' + coverage: xdebug + - run: composer install --no-interaction --prefer-dist + - run: composer mutation:test diff --git a/.github/workflows/lint-php-cs.yml b/.github/workflows/lint-php-cs.yml new file mode 100644 index 0000000..b0d0099 --- /dev/null +++ b/.github/workflows/lint-php-cs.yml @@ -0,0 +1,30 @@ +# This workflow follows the Nextcloud organization template style. +# SPDX-FileCopyrightText: 2021-2024 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: MIT + +name: Lint PHP coding style + +on: pull_request + +permissions: + contents: read + +jobs: + coding-style: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Set up PHP + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: '8.3' + coverage: none + - name: Install dependencies + run: composer install --no-interaction --prefer-dist + - name: Nextcloud coding standard + run: composer cs:check + - name: PHPCS + run: composer phpcs diff --git a/.github/workflows/lint-php.yml b/.github/workflows/lint-php.yml new file mode 100644 index 0000000..ce7ccc4 --- /dev/null +++ b/.github/workflows/lint-php.yml @@ -0,0 +1,28 @@ +# This workflow follows the Nextcloud organization template style. +# SPDX-FileCopyrightText: 2021-2024 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: MIT + +name: Lint PHP + +on: pull_request + +permissions: + contents: read + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Set up PHP + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: '8.2' + coverage: none + - name: Install dependencies + run: composer install --no-interaction --prefer-dist + - name: Lint + run: composer lint diff --git a/.github/workflows/phpmd.yml b/.github/workflows/phpmd.yml new file mode 100644 index 0000000..0038b7a --- /dev/null +++ b/.github/workflows/phpmd.yml @@ -0,0 +1,23 @@ +# SPDX-FileCopyrightText: 2026 LibreCode coop and contributors +# SPDX-License-Identifier: AGPL-3.0-or-later + +name: PHPMD + +on: pull_request + +permissions: + contents: read + +jobs: + phpmd: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: '8.3' + coverage: none + - run: composer install --no-interaction --prefer-dist + - run: composer phpmd diff --git a/.github/workflows/phpstan.yml b/.github/workflows/phpstan.yml new file mode 100644 index 0000000..5316f13 --- /dev/null +++ b/.github/workflows/phpstan.yml @@ -0,0 +1,23 @@ +# SPDX-FileCopyrightText: 2026 LibreCode coop and contributors +# SPDX-License-Identifier: AGPL-3.0-or-later + +name: PHPStan + +on: pull_request + +permissions: + contents: read + +jobs: + phpstan: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: '8.3' + coverage: none + - run: composer install --no-interaction --prefer-dist + - run: composer phpstan diff --git a/.github/workflows/phpunit.yml b/.github/workflows/phpunit.yml new file mode 100644 index 0000000..193b320 --- /dev/null +++ b/.github/workflows/phpunit.yml @@ -0,0 +1,31 @@ +# SPDX-FileCopyrightText: 2026 LibreCode coop and contributors +# SPDX-License-Identifier: AGPL-3.0-or-later + +name: PHPUnit + +on: pull_request + +permissions: + contents: read + +jobs: + unit-tests: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + php: ['8.2', '8.3', '8.4', '8.5'] + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Set up PHP + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: ${{ matrix.php }} + coverage: none + - name: Install dependencies + run: composer install --no-interaction --prefer-dist + - name: Run unit tests + run: composer test:unit diff --git a/.github/workflows/psalm.yml b/.github/workflows/psalm.yml new file mode 100644 index 0000000..25fe0a5 --- /dev/null +++ b/.github/workflows/psalm.yml @@ -0,0 +1,23 @@ +# SPDX-FileCopyrightText: 2026 LibreCode coop and contributors +# SPDX-License-Identifier: AGPL-3.0-or-later + +name: Psalm + +on: pull_request + +permissions: + contents: read + +jobs: + psalm: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: '8.3' + coverage: none + - run: composer install --no-interaction --prefer-dist + - run: composer psalm diff --git a/.github/workflows/reuse.yml b/.github/workflows/reuse.yml new file mode 100644 index 0000000..8806aa7 --- /dev/null +++ b/.github/workflows/reuse.yml @@ -0,0 +1,21 @@ +# This workflow follows the Nextcloud organization template style. +# SPDX-FileCopyrightText: 2022 Free Software Foundation Europe e.V. +# SPDX-License-Identifier: CC0-1.0 + +name: REUSE Compliance Check + +on: pull_request + +permissions: + contents: read + +jobs: + reuse: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: REUSE compliance + uses: fsfe/reuse-action@676e2d560c9a403aa252096d99fcab3e1132b0f5 # v6.0.0 diff --git a/.github/workflows/scoping.yml b/.github/workflows/scoping.yml new file mode 100644 index 0000000..315f46c --- /dev/null +++ b/.github/workflows/scoping.yml @@ -0,0 +1,25 @@ +# SPDX-FileCopyrightText: 2026 LibreCode coop and contributors +# SPDX-License-Identifier: AGPL-3.0-or-later + +name: Namespace scoping + +on: pull_request + +permissions: + contents: read + +jobs: + scoping: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: '8.3' + coverage: none + - run: composer install --no-interaction --prefer-dist + - run: composer global require --no-interaction humbug/php-scoper:^0.18.17 + - run: '"$(composer global config bin-dir --absolute)/php-scoper" add-prefix --prefix=UsageStatisticsClientScoped --output-dir=build/scoped --force src' + - run: php tests/scoping-smoke.php diff --git a/.gitignore b/.gitignore index a914a23..b14582c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,8 @@ +# SPDX-FileCopyrightText: 2026 LibreCode coop and contributors +# SPDX-License-Identifier: AGPL-3.0-or-later + /vendor/ +/vendor-bin/*/vendor/ /build/ /.phpunit.cache/ /.phpunit.result.cache diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php new file mode 100644 index 0000000..2e09fd1 --- /dev/null +++ b/.php-cs-fixer.dist.php @@ -0,0 +1,25 @@ +setParallelConfig(ParallelConfigFactory::detect()) + ->getFinder() + ->ignoreVCSIgnored(true) + ->notPath('build') + ->notPath('vendor') + ->notPath('vendor-bin') + ->in(__DIR__); + +return $config; diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..80bcfe3 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,28 @@ + + +# Contributing + +Contributions are welcome through GitHub pull requests. + +## Development setup + +```bash +composer install +``` + +The root Composer project installs isolated development tools from `vendor-bin/` through `bamarni/composer-bin-plugin`. + +Before submitting changes, run: + +```bash +composer qa +composer mutation:test +composer audit +``` + +Tests belong in `tests/Unit/` and should mirror the production path under `src/`. Prefer tests for protocol invariants and externally observable behavior over tests written only to increase coverage. + +Use Conventional Commits and sign commits with `git commit -s`. diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..9e3b16e --- /dev/null +++ b/COPYING @@ -0,0 +1,232 @@ +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + + Preamble + +The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. + +The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. + +The precise terms and conditions for copying, distribution and modification follow. + + TERMS AND CONDITIONS + +0. Definitions. + +"This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the Program. + +To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. + +A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce it, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the covered work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". + + c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + + a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. + + d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. + + e) Convey individual copies of the object code using peer-to-peer transmission, provided you inform other peers where the object code and the Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the class of product. + +"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or authors of the material; or + + e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. + +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. + +A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. + +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing a later version. + +15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. + +You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . diff --git a/README.md b/README.md index 1487b0f..0cd1c38 100644 --- a/README.md +++ b/README.md @@ -5,23 +5,20 @@ SPDX-License-Identifier: AGPL-3.0-or-later # Usage Statistics Client -Framework-agnostic PHP client for applications that submit opt-in usage statistics using [Usage Statistics Protocol v1](https://github.com/LibreCodeCoop/usage_statistics_server/blob/main/docs/protocol-v1.md). - -The package provides typed report primitives, pseudonymous installation-ID derivation, consent gating, payload serialization, a small HTTP transport boundary, and response/error handling. Applications remain responsible for their metrics, consent UI and persistence, endpoint configuration, scheduling, and logging policy. +Reusable PHP client for applications that submit opt-in usage statistics using [Usage Statistics Protocol v1](https://github.com/LibreCodeCoop/usage_statistics_server/blob/main/docs/protocol-v1.md). ## Requirements -- PHP 8.1 or newer +- PHP 8.2 or newer - Composer -- an HTTPS report endpoint compatible with Protocol v1 ## Install ```bash -composer require vitormattos/usage-statistics-client +composer require librecodecoop/usage-statistics-client ``` -## Minimal use +## Example ```php use LibreCode\UsageStatistics\Client; @@ -33,13 +30,11 @@ use LibreCode\UsageStatistics\Report; use LibreCode\UsageStatistics\ReportingPeriod; use LibreCode\UsageStatistics\Transport\StreamTransport; -$installationId = InstallationId::derive('libresign', $localInstallationIdentifier); - $report = new Report( application: 'libresign', - installationId: (string)$installationId, + installationId: (string) InstallationId::derive('libresign', $localInstallationIdentifier), schemaVersion: 1, - period: ReportingPeriod::monthContaining(new DateTimeImmutable('2026-08-15T00:00:00Z')), + period: ReportingPeriod::monthContaining(new DateTimeImmutable()), metrics: [ Metric::string('environment', 'version', '12.0.0'), Metric::integer('usage', 'requests_completed', 72), @@ -48,36 +43,26 @@ $report = new Report( $client = new Client( new StreamTransport(), - new Endpoint('https://statistics.example/apps/usage_statistics_server/api/v1/reports'), + new Endpoint('https://statistics.example/api/v1/reports'), ); -$result = $client->submit($report, ConsentState::Enabled); +$client->submit($report, ConsentState::Enabled); ``` -`unknown` and `disabled` consent states never send a request. Network and HTTP failures are surfaced to the application; the client deliberately does not retry automatically, so a background scheduler can decide when to try again without blocking normal application work. - -## Design constraints - -- no Nextcloud or LibreSign runtime dependency; -- no PSR-7/PSR-18 contract exposed in the public API; -- no authentication, signing, or attestation invented beyond Protocol v1; -- no automatic logging of report payloads; -- no user-level event model; -- runtime dependencies are intentionally zero. - -The package is designed so its own namespace can be prefixed when bundled into isolated dependency trees such as LibreSign's `3rdparty` directory. +Applications define their own metrics, consent UI and persistence, endpoint, scheduling and logging policy. The client validates and serializes Protocol v1 reports and submits them when consent is enabled. ## Documentation -- [Architecture](docs/architecture.md) - [Integration](docs/integration.md) - [Privacy](docs/privacy.md) +- [Architecture](docs/architecture.md) - [PHP-Scoper](docs/php-scoper.md) - [Mozart](docs/mozart.md) -- [Versioning](docs/versioning.md) - [Development](docs/development.md) +- [Versioning](docs/versioning.md) - [Troubleshooting](docs/troubleshooting.md) +- [Contributing](CONTRIBUTING.md) ## License -AGPL-3.0-or-later. See `LICENSES/AGPL-3.0-or-later.txt`. +AGPL-3.0-or-later. See `COPYING` and `LICENSES/AGPL-3.0-or-later.txt`. diff --git a/REUSE.toml b/REUSE.toml index 0bc73bd..37d6926 100644 --- a/REUSE.toml +++ b/REUSE.toml @@ -3,18 +3,20 @@ version = 1 SPDX-PackageName = "usage-statistics-client" -SPDX-PackageDownloadLocation = "https://github.com/vitormattos/usage_statistics_client/" +SPDX-PackageDownloadLocation = "https://github.com/LibreCodeCoop/usage_statistics_client/" default-license = "AGPL-3.0-or-later" default-copyright = "2026 LibreCode coop and contributors" [[annotations]] path = [ - ".gitignore", "composer.json", - "phpcs.xml.dist", - "phpstan.neon", - "phpunit.xml.dist" + "composer.lock", + "phpunit.xml.dist", + "phpmd.xml", + "psalm.xml", + "vendor-bin/**/composer.json", + "vendor-bin/**/composer.lock" ] precedence = "aggregate" SPDX-FileCopyrightText = "2026 LibreCode coop and contributors" diff --git a/composer.json b/composer.json index bf6eecc..e0f0d86 100644 --- a/composer.json +++ b/composer.json @@ -1,21 +1,19 @@ { - "name": "vitormattos/usage-statistics-client", + "name": "librecodecoop/usage-statistics-client", "description": "Framework-agnostic PHP client for the Usage Statistics Protocol.", "type": "library", "license": "AGPL-3.0-or-later", "keywords": [ - "telemetry", - "usage-statistics", + "nextcloud", "privacy", - "php" + "telemetry", + "usage-statistics" ], "require": { - "php": ">=8.1" + "php": "^8.2" }, "require-dev": { - "phpstan/phpstan": "^2.1", - "phpunit/phpunit": "^10.5 || ^11.5 || ^12.0", - "squizlabs/php_codesniffer": "^3.13" + "bamarni/composer-bin-plugin": "^1.9" }, "autoload": { "psr-4": { @@ -24,30 +22,55 @@ }, "autoload-dev": { "psr-4": { - "LibreCode\\UsageStatistics\\Tests\\": "tests/" + "LibreCode\\UsageStatistics\\Tests\\": "tests/Unit/" } }, "scripts": { - "lint": "find src tests -name '*.php' -print0 | xargs -0 -n1 php -l", - "test": "phpunit --colors=always --fail-on-warning --fail-on-risky", - "test:coverage": [ - "@php -r \"is_dir('build') || mkdir('build', 0777, true);\"", - "XDEBUG_MODE=coverage phpunit --coverage-text --coverage-clover build/coverage.xml" - ], - "phpstan": "phpstan analyse -c phpstan.neon", - "phpcs": "phpcs -q", + "lint": "find src tests -name \\*.php -not -path './vendor/*' -not -path './vendor-bin/*' -print0 | xargs -0 -n1 php -l", + "cs:check": "php vendor-bin/coding-standard/vendor/bin/php-cs-fixer fix --dry-run --diff", + "cs:fix": "php vendor-bin/coding-standard/vendor/bin/php-cs-fixer fix", + "phpcs": "php vendor-bin/coding-standard/vendor/bin/phpcs -q", + "phpstan": "php vendor-bin/phpstan/vendor/bin/phpstan analyse -c phpstan.neon", + "psalm": "php vendor-bin/psalm/vendor/bin/psalm --no-cache --threads=$(nproc)", + "phpmd": "php vendor-bin/phpmd/vendor/bin/phpmd src text phpmd.xml", + "mutation:test": "php vendor-bin/infection/vendor/bin/infection --configuration=infection.json5", + "test:unit": "php vendor-bin/phpunit/vendor/bin/phpunit -c phpunit.xml.dist --testsuite unit --no-coverage --colors=always --fail-on-warning --fail-on-risky --display-deprecations --display-phpunit-deprecations", + "test:coverage": "XDEBUG_MODE=coverage php vendor-bin/phpunit/vendor/bin/phpunit -c phpunit.xml.dist --coverage-text --coverage-clover build/coverage.xml", "qa": [ "@lint", + "@cs:check", "@phpcs", "@phpstan", - "@test" + "@psalm", + "@phpmd", + "@test:unit" + ], + "post-install-cmd": [ + "@composer bin all install --ansi", + "composer dump-autoload -o" + ], + "post-update-cmd": [ + "composer dump-autoload" ] }, + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": true + } + }, "support": { - "issues": "https://github.com/vitormattos/usage_statistics_client/issues", - "source": "https://github.com/vitormattos/usage_statistics_client" + "issues": "https://github.com/LibreCodeCoop/usage_statistics_client/issues", + "source": "https://github.com/LibreCodeCoop/usage_statistics_client" }, "config": { - "sort-packages": true + "allow-plugins": { + "bamarni/composer-bin-plugin": true + }, + "optimize-autoloader": true, + "sort-packages": true, + "platform": { + "php": "8.2" + } } } diff --git a/composer.lock b/composer.lock new file mode 100644 index 0000000..3eb2f2f --- /dev/null +++ b/composer.lock @@ -0,0 +1,57 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "c829ce1a86788efdf5e32b086ec15187", + "packages": [], + "packages-dev": [ + { + "name": "bamarni/composer-bin-plugin", + "version": "1.9.1", + "source": { + "type": "git", + "url": "https://github.com/bamarni/composer-bin-plugin.git", + "reference": "641d0663f5ac270b1aeec4337b7856f76204df47" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/bamarni/composer-bin-plugin/zipball/641d0663f5ac270b1aeec4337b7856f76204df47", + "reference": "641d0663f5ac270b1aeec4337b7856f76204df47", + "shasum": "" + }, + "require": { + "composer-plugin-api": "^2.0", + "php": "^7.2.5 || ^8.0" + }, + "type": "composer-plugin", + "extra": { + "class": "Bamarni\\Composer\\Bin\\BamarniBinPlugin" + }, + "autoload": { + "psr-4": { + "Bamarni\\Composer\\Bin\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": ["MIT"], + "description": "No conflicts for your bin dependencies", + "support": { + "issues": "https://github.com/bamarni/composer-bin-plugin/issues", + "source": "https://github.com/bamarni/composer-bin-plugin/tree/1.9.1" + }, + "time": "2026-02-04T10:18:12+00:00" + } + ], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": [], + "prefer-stable": false, + "prefer-lowest": false, + "platform": { + "php": "^8.2" + }, + "platform-dev": [], + "plugin-api-version": "2.6.0" +} diff --git a/infection.json5 b/infection.json5 new file mode 100644 index 0000000..91a6c39 --- /dev/null +++ b/infection.json5 @@ -0,0 +1,18 @@ +// SPDX-FileCopyrightText: 2026 LibreCode coop and contributors +// SPDX-License-Identifier: AGPL-3.0-or-later + +{ + "$schema": "https://raw.githubusercontent.com/infection/infection/0.35.2/resources/schema.json", + "source": { + "directories": ["src"] + }, + "phpUnit": { + "configDir": ".", + "customPath": "vendor-bin/phpunit/vendor/bin/phpunit" + }, + "minMsi": 90, + "minCoveredMsi": 90, + "mutators": { + "@default": true + } +} diff --git a/phpcs.xml.dist b/phpcs.xml.dist index f7740b5..b17e998 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -1,10 +1,15 @@ - - PSR-12 coding standard for the Usage Statistics Client. + + + PHP_CodeSniffer rules for the usage statistics client. + + src - tests - - - + tests/Unit + vendor/* + vendor-bin/* diff --git a/phpmd.xml b/phpmd.xml new file mode 100644 index 0000000..51a5bdd --- /dev/null +++ b/phpmd.xml @@ -0,0 +1,13 @@ + + + + Maintainability rules for production code. + + + + + + diff --git a/phpstan.neon b/phpstan.neon index 5334969..0cc8485 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,11 +1,9 @@ +# SPDX-FileCopyrightText: 2026 LibreCode coop and contributors +# SPDX-License-Identifier: AGPL-3.0-or-later + parameters: level: max paths: - src - - tests - tmpDir: .phpstan-cache - - excludePaths: - analyse: - - tests/scoping-smoke.php - - tests/coverage-threshold.php + - tests/Unit + tmpDir: build/phpstan diff --git a/phpunit.xml.dist b/phpunit.xml.dist index abf30f8..8522f04 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,17 +1,17 @@ - + + - tests + tests/Unit - src + src diff --git a/psalm.xml b/psalm.xml new file mode 100644 index 0000000..ad84959 --- /dev/null +++ b/psalm.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + diff --git a/tests/ClientTest.php b/tests/Unit/ClientTest.php similarity index 100% rename from tests/ClientTest.php rename to tests/Unit/ClientTest.php diff --git a/tests/EndpointTest.php b/tests/Unit/EndpointTest.php similarity index 100% rename from tests/EndpointTest.php rename to tests/Unit/EndpointTest.php diff --git a/tests/InstallationIdTest.php b/tests/Unit/InstallationIdTest.php similarity index 100% rename from tests/InstallationIdTest.php rename to tests/Unit/InstallationIdTest.php diff --git a/tests/MetricTest.php b/tests/Unit/MetricTest.php similarity index 100% rename from tests/MetricTest.php rename to tests/Unit/MetricTest.php diff --git a/tests/RecordingTransport.php b/tests/Unit/RecordingTransport.php similarity index 100% rename from tests/RecordingTransport.php rename to tests/Unit/RecordingTransport.php diff --git a/tests/ReportTest.php b/tests/Unit/ReportTest.php similarity index 100% rename from tests/ReportTest.php rename to tests/Unit/ReportTest.php diff --git a/tests/ReportingPeriodTest.php b/tests/Unit/ReportingPeriodTest.php similarity index 100% rename from tests/ReportingPeriodTest.php rename to tests/Unit/ReportingPeriodTest.php diff --git a/tests/ResponseTest.php b/tests/Unit/Transport/ResponseTest.php similarity index 100% rename from tests/ResponseTest.php rename to tests/Unit/Transport/ResponseTest.php diff --git a/tests/StreamTransportTest.php b/tests/Unit/Transport/StreamTransportTest.php similarity index 100% rename from tests/StreamTransportTest.php rename to tests/Unit/Transport/StreamTransportTest.php diff --git a/tests/coverage-threshold.php b/tests/coverage-threshold.php deleted file mode 100644 index 2e21b87..0000000 --- a/tests/coverage-threshold.php +++ /dev/null @@ -1,25 +0,0 @@ -project->metrics; -$statements = (int)$metrics['statements']; -$covered = (int)$metrics['coveredstatements']; -$percentage = $statements === 0 ? 0.0 : ($covered / $statements) * 100; - -printf("Line coverage: %.2f%% (minimum %.2f%%)\n", $percentage, $minimum); -exit($percentage >= $minimum ? 0 : 1); diff --git a/vendor-bin/coding-standard/composer.json b/vendor-bin/coding-standard/composer.json new file mode 100644 index 0000000..23ec037 --- /dev/null +++ b/vendor-bin/coding-standard/composer.json @@ -0,0 +1,10 @@ +{ + "require-dev": { + "friendsofphp/php-cs-fixer": "^3.59", + "nextcloud/coding-standard": "^1.5", + "squizlabs/php_codesniffer": "^3.13" + }, + "config": { + "sort-packages": true + } +} diff --git a/vendor-bin/infection/composer.json b/vendor-bin/infection/composer.json new file mode 100644 index 0000000..050316b --- /dev/null +++ b/vendor-bin/infection/composer.json @@ -0,0 +1,11 @@ +{ + "require-dev": { + "infection/infection": "^0.35" + }, + "config": { + "allow-plugins": { + "infection/extension-installer": true + }, + "sort-packages": true + } +} diff --git a/vendor-bin/phpmd/composer.json b/vendor-bin/phpmd/composer.json new file mode 100644 index 0000000..6ac9493 --- /dev/null +++ b/vendor-bin/phpmd/composer.json @@ -0,0 +1,8 @@ +{ + "require-dev": { + "phpmd/phpmd": "^2.15" + }, + "config": { + "sort-packages": true + } +} diff --git a/vendor-bin/phpstan/composer.json b/vendor-bin/phpstan/composer.json new file mode 100644 index 0000000..35d89ae --- /dev/null +++ b/vendor-bin/phpstan/composer.json @@ -0,0 +1,8 @@ +{ + "require-dev": { + "phpstan/phpstan": "^2.1" + }, + "config": { + "sort-packages": true + } +} diff --git a/vendor-bin/phpunit/composer.json b/vendor-bin/phpunit/composer.json new file mode 100644 index 0000000..ceb1ba4 --- /dev/null +++ b/vendor-bin/phpunit/composer.json @@ -0,0 +1,8 @@ +{ + "require-dev": { + "phpunit/phpunit": "^11.5" + }, + "config": { + "sort-packages": true + } +} diff --git a/vendor-bin/psalm/composer.json b/vendor-bin/psalm/composer.json new file mode 100644 index 0000000..faa2c52 --- /dev/null +++ b/vendor-bin/psalm/composer.json @@ -0,0 +1,8 @@ +{ + "require-dev": { + "vimeo/psalm": "^6.16" + }, + "config": { + "sort-packages": true + } +} From 9caae4350aeb5c95223e179d4a9f38d41f019d9f Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 20:38:38 -0300 Subject: [PATCH 11/43] test: strengthen protocol business rules Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- composer.lock | 14 ++++- tests/Unit/ReportTest.php | 94 +++++++++++++++++++++++++----- tests/Unit/ReportingPeriodTest.php | 47 ++++++++++++--- 3 files changed, 131 insertions(+), 24 deletions(-) diff --git a/composer.lock b/composer.lock index 3eb2f2f..474dd2d 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "c829ce1a86788efdf5e32b086ec15187", + "content-hash": "c1c09c7511885473801614954fb5f342", "packages": [], "packages-dev": [ { @@ -35,8 +35,18 @@ } }, "notification-url": "https://packagist.org/downloads/", - "license": ["MIT"], + "license": [ + "MIT" + ], "description": "No conflicts for your bin dependencies", + "keywords": [ + "composer", + "conflict", + "dependency", + "executable", + "isolation", + "tool" + ], "support": { "issues": "https://github.com/bamarni/composer-bin-plugin/issues", "source": "https://github.com/bamarni/composer-bin-plugin/tree/1.9.1" diff --git a/tests/Unit/ReportTest.php b/tests/Unit/ReportTest.php index a0ab576..26b8e88 100644 --- a/tests/Unit/ReportTest.php +++ b/tests/Unit/ReportTest.php @@ -18,42 +18,106 @@ final class ReportTest extends TestCase { - public function testSerializesProtocolV1Payload(): void + public function testSerializesExactProtocolV1Payload(): void { $report = new Report( 'libresign', str_repeat('a', 64), 2, - new ReportingPeriod(new DateTimeImmutable('2026-08-01T00:00:00Z'), new DateTimeImmutable('2026-09-01T00:00:00Z')), - [Metric::string('environment', 'version', '12.0.0')], + new ReportingPeriod( + new DateTimeImmutable('2026-08-01T00:00:00Z'), + new DateTimeImmutable('2026-09-01T00:00:00Z'), + ), + [ + Metric::string('environment', 'version', '12.0.0'), + Metric::integer('usage', 'requests_completed', 72), + ], ); - self::assertSame(1, $report->toArray()['protocolVersion']); - self::assertSame('2026-08-01T00:00:00Z', $report->toArray()['period']['start']); - self::assertSame('12.0.0', $report->toArray()['metrics'][0]['value']); + self::assertSame([ + 'protocolVersion' => 1, + 'application' => 'libresign', + 'installationId' => str_repeat('a', 64), + 'schemaVersion' => 2, + 'period' => [ + 'start' => '2026-08-01T00:00:00Z', + 'end' => '2026-09-01T00:00:00Z', + ], + 'metrics' => [ + ['category' => 'environment', 'key' => 'version', 'type' => 'string', 'value' => '12.0.0'], + ['category' => 'usage', 'key' => 'requests_completed', 'type' => 'integer', 'value' => 72], + ], + ], $report->toArray()); } - public function testRejectsDuplicateMetrics(): void + public function testAcceptsProtocolMaximumOf256Metrics(): void + { + $metrics = []; + for ($i = 0; $i < 256; ++$i) { + $metrics[] = Metric::integer('usage', 'metric_' . $i, $i); + } + + $report = new Report('libresign', str_repeat('a', 64), 1, $this->period(), $metrics); + self::assertCount(256, $report->metrics); + } + + public function testRejectsMoreThan256Metrics(): void + { + $metrics = []; + for ($i = 0; $i < 257; ++$i) { + $metrics[] = Metric::integer('usage', 'metric_' . $i, $i); + } + + $this->expectException(InvalidArgumentException::class); + new Report('libresign', str_repeat('a', 64), 1, $this->period(), $metrics); + } + + public function testRejectsDuplicateMetricIdentityRegardlessOfValue(): void { - $period = new ReportingPeriod(new DateTimeImmutable('2026-08-01T00:00:00Z'), new DateTimeImmutable('2026-08-02T00:00:00Z')); $this->expectException(InvalidArgumentException::class); - new Report('libresign', str_repeat('a', 64), 1, $period, [ + new Report('libresign', str_repeat('a', 64), 1, $this->period(), [ Metric::integer('usage', 'count', 1), Metric::integer('usage', 'count', 2), ]); } - public function testRejectsEmptyMetrics(): void + public function testRejectsEmptyMetricSet(): void { - $period = new ReportingPeriod(new DateTimeImmutable('2026-08-01T00:00:00Z'), new DateTimeImmutable('2026-08-02T00:00:00Z')); $this->expectException(InvalidArgumentException::class); - new Report('libresign', str_repeat('a', 64), 1, $period, []); + new Report('libresign', str_repeat('a', 64), 1, $this->period(), []); } - public function testRejectsInvalidSchemaVersion(): void + public function testRejectsSchemaVersionZero(): void { - $period = new ReportingPeriod(new DateTimeImmutable('2026-08-01T00:00:00Z'), new DateTimeImmutable('2026-08-02T00:00:00Z')); $this->expectException(InvalidArgumentException::class); - new Report('libresign', str_repeat('a', 64), 0, $period, [Metric::integer('usage', 'count', 1)]); + new Report('libresign', str_repeat('a', 64), 0, $this->period(), [Metric::integer('usage', 'count', 1)]); + } + + public function testAcceptsMaximumLengthIdentifiers(): void + { + $report = new Report( + str_repeat('a', 128), + str_repeat('b', 128), + 1, + $this->period(), + [Metric::integer('usage', 'count', 1)], + ); + + self::assertSame(128, strlen($report->application)); + self::assertSame(128, strlen($report->installationId)); + } + + public function testRejectsIdentifierOutsideProtocolAlphabet(): void + { + $this->expectException(InvalidArgumentException::class); + new Report('libresign app', str_repeat('a', 64), 1, $this->period(), [Metric::integer('usage', 'count', 1)]); + } + + private function period(): ReportingPeriod + { + return new ReportingPeriod( + new DateTimeImmutable('2026-08-01T00:00:00Z'), + new DateTimeImmutable('2026-09-01T00:00:00Z'), + ); } } diff --git a/tests/Unit/ReportingPeriodTest.php b/tests/Unit/ReportingPeriodTest.php index 85c1ca7..b2c33c5 100644 --- a/tests/Unit/ReportingPeriodTest.php +++ b/tests/Unit/ReportingPeriodTest.php @@ -16,26 +16,59 @@ final class ReportingPeriodTest extends TestCase { - public function testNormalizesToUtc(): void + public function testNormalizesBothBoundariesToUtc(): void { $period = new ReportingPeriod( new DateTimeImmutable('2026-08-01T03:00:00+03:00'), new DateTimeImmutable('2026-08-02T03:00:00+03:00'), ); - self::assertSame('2026-08-01T00:00:00Z', $period->toArray()['start']); + + self::assertSame([ + 'start' => '2026-08-01T00:00:00Z', + 'end' => '2026-08-02T00:00:00Z', + ], $period->toArray()); + } + + public function testCreatesCalendarMonthAtUtcBoundary(): void + { + $period = ReportingPeriod::monthContaining(new DateTimeImmutable('2026-02-28T23:59:59-03:00')); + + self::assertSame('2026-03-01T00:00:00Z', $period->toArray()['start']); + self::assertSame('2026-04-01T00:00:00Z', $period->toArray()['end']); + } + + public function testAcceptsExactly31Days(): void + { + $period = new ReportingPeriod( + new DateTimeImmutable('2026-01-01T00:00:00Z'), + new DateTimeImmutable('2026-02-01T00:00:00Z'), + ); + + self::assertSame('2026-02-01T00:00:00Z', $period->toArray()['end']); } - public function testCreatesCalendarMonth(): void + public function testRejectsPeriodLongerThan31Days(): void { - $period = ReportingPeriod::monthContaining(new DateTimeImmutable('2026-02-13T12:30:00Z')); - self::assertSame('2026-02-01T00:00:00Z', $period->toArray()['start']); - self::assertSame('2026-03-01T00:00:00Z', $period->toArray()['end']); + $this->expectException(InvalidArgumentException::class); + new ReportingPeriod( + new DateTimeImmutable('2026-01-01T00:00:00Z'), + new DateTimeImmutable('2026-02-01T00:00:01Z'), + ); } - public function testRejectsNonPositivePeriod(): void + public function testRejectsZeroLengthPeriod(): void { $instant = new DateTimeImmutable('2026-08-01T00:00:00Z'); $this->expectException(InvalidArgumentException::class); new ReportingPeriod($instant, $instant); } + + public function testRejectsReversedPeriod(): void + { + $this->expectException(InvalidArgumentException::class); + new ReportingPeriod( + new DateTimeImmutable('2026-08-02T00:00:00Z'), + new DateTimeImmutable('2026-08-01T00:00:00Z'), + ); + } } From 7529dcab4c5401d42e032b2e4eda3796e01d8b98 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 20:39:17 -0300 Subject: [PATCH 12/43] test: align unit test namespaces Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- REUSE.toml | 3 +-- tests/Unit/Transport/ResponseTest.php | 7 ++++++- tests/Unit/Transport/StreamTransportTest.php | 12 +++++------- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/REUSE.toml b/REUSE.toml index 37d6926..8f4b9e0 100644 --- a/REUSE.toml +++ b/REUSE.toml @@ -15,8 +15,7 @@ path = [ "phpunit.xml.dist", "phpmd.xml", "psalm.xml", - "vendor-bin/**/composer.json", - "vendor-bin/**/composer.lock" + "vendor-bin/**/composer.json" ] precedence = "aggregate" SPDX-FileCopyrightText = "2026 LibreCode coop and contributors" diff --git a/tests/Unit/Transport/ResponseTest.php b/tests/Unit/Transport/ResponseTest.php index ca7a5af..453d4d4 100644 --- a/tests/Unit/Transport/ResponseTest.php +++ b/tests/Unit/Transport/ResponseTest.php @@ -7,7 +7,7 @@ declare(strict_types=1); -namespace LibreCode\UsageStatistics\Tests; +namespace LibreCode\UsageStatistics\Tests\Transport; use LibreCode\UsageStatistics\Transport\Response; use PHPUnit\Framework\TestCase; @@ -21,4 +21,9 @@ public function testHeaderLookupIsCaseInsensitive(): void self::assertSame('60', $response->header('retry-after')); self::assertSame('60', $response->header('RETRY-AFTER')); } + + public function testMissingHeaderReturnsNull(): void + { + self::assertNull((new Response(200, ''))->header('retry-after')); + } } diff --git a/tests/Unit/Transport/StreamTransportTest.php b/tests/Unit/Transport/StreamTransportTest.php index 962fb3d..5f1e2b5 100644 --- a/tests/Unit/Transport/StreamTransportTest.php +++ b/tests/Unit/Transport/StreamTransportTest.php @@ -7,19 +7,17 @@ declare(strict_types=1); -namespace LibreCode\UsageStatistics\Tests; +namespace LibreCode\UsageStatistics\Tests\Transport; -use LibreCode\UsageStatistics\Exception\TransportException; +use InvalidArgumentException; use LibreCode\UsageStatistics\Transport\StreamTransport; use PHPUnit\Framework\TestCase; final class StreamTransportTest extends TestCase { - public function testRejectsNonPositiveTimeout(): void + public function testRejectsNonPositiveTimeoutBeforeNetworkAccess(): void { - $transport = new StreamTransport(); - - $this->expectException(TransportException::class); - $transport->request('POST', 'https://example.invalid', [], '{}', 0.0); + $this->expectException(InvalidArgumentException::class); + (new StreamTransport())->request('POST', 'https://stats.example/api/v1/reports', [], '{}', 0.0); } } From f47ae54e83141ac95fb5e6a5cde605e95d293a57 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 20:40:19 -0300 Subject: [PATCH 13/43] fix: synchronize composer lock Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- composer.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.lock b/composer.lock index 474dd2d..9be4091 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "c1c09c7511885473801614954fb5f342", + "content-hash": "d3a964147ce361ae8fa0ab3bca1b5439", "packages": [], "packages-dev": [ { From 863195d2e6268e1dbc0fc30d4a759cdad43301d0 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 20:42:30 -0300 Subject: [PATCH 14/43] chore: add workflow license texts Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- LICENSES/MIT.txt | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 LICENSES/MIT.txt diff --git a/LICENSES/MIT.txt b/LICENSES/MIT.txt new file mode 100644 index 0000000..d817195 --- /dev/null +++ b/LICENSES/MIT.txt @@ -0,0 +1,18 @@ +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO +EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. From 555ab3c286b9bf991f4b72ac87d5634042a7f14b Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 20:42:44 -0300 Subject: [PATCH 15/43] chore: add workflow license texts Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- LICENSES/CC0-1.0.txt | 121 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 LICENSES/CC0-1.0.txt diff --git a/LICENSES/CC0-1.0.txt b/LICENSES/CC0-1.0.txt new file mode 100644 index 0000000..dbd29f6 --- /dev/null +++ b/LICENSES/CC0-1.0.txt @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights and the +meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer. Should any part of the License for any reason be +judged legally invalid or ineffective under applicable law, such partial +invalidity or ineffectiveness shall not invalidate the remainder of the +License, and in such case Affirmer hereby affirms that he or she will not +(i) exercise any of his or her remaining Copyright and Related Rights in +the Work or (ii) assert any associated claims and causes of action with +respect to the Work, in either case contrary to Affirmer's express +Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. From e2e3dab200eaac78b70936a3826324107266a922 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 20:42:54 -0300 Subject: [PATCH 16/43] fix: isolate infection on php 8.3 Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- vendor-bin/infection/composer.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/vendor-bin/infection/composer.json b/vendor-bin/infection/composer.json index 050316b..e4cacae 100644 --- a/vendor-bin/infection/composer.json +++ b/vendor-bin/infection/composer.json @@ -6,6 +6,9 @@ "allow-plugins": { "infection/extension-installer": true }, + "platform": { + "php": "8.3" + }, "sort-packages": true } } From 87e1305fa7b0a0437a99082cce5ce21f998f1e6b Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 20:44:46 -0300 Subject: [PATCH 17/43] fix: use vendor bin tool links Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- composer.json | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/composer.json b/composer.json index e0f0d86..0b0501a 100644 --- a/composer.json +++ b/composer.json @@ -27,15 +27,15 @@ }, "scripts": { "lint": "find src tests -name \\*.php -not -path './vendor/*' -not -path './vendor-bin/*' -print0 | xargs -0 -n1 php -l", - "cs:check": "php vendor-bin/coding-standard/vendor/bin/php-cs-fixer fix --dry-run --diff", - "cs:fix": "php vendor-bin/coding-standard/vendor/bin/php-cs-fixer fix", - "phpcs": "php vendor-bin/coding-standard/vendor/bin/phpcs -q", - "phpstan": "php vendor-bin/phpstan/vendor/bin/phpstan analyse -c phpstan.neon", - "psalm": "php vendor-bin/psalm/vendor/bin/psalm --no-cache --threads=$(nproc)", - "phpmd": "php vendor-bin/phpmd/vendor/bin/phpmd src text phpmd.xml", - "mutation:test": "php vendor-bin/infection/vendor/bin/infection --configuration=infection.json5", - "test:unit": "php vendor-bin/phpunit/vendor/bin/phpunit -c phpunit.xml.dist --testsuite unit --no-coverage --colors=always --fail-on-warning --fail-on-risky --display-deprecations --display-phpunit-deprecations", - "test:coverage": "XDEBUG_MODE=coverage php vendor-bin/phpunit/vendor/bin/phpunit -c phpunit.xml.dist --coverage-text --coverage-clover build/coverage.xml", + "cs:check": "php-cs-fixer fix --dry-run --diff", + "cs:fix": "php-cs-fixer fix", + "phpcs": "phpcs -q", + "phpstan": "phpstan analyse -c phpstan.neon", + "psalm": "psalm --no-cache --threads=$(nproc)", + "phpmd": "phpmd src text phpmd.xml", + "mutation:test": "infection --configuration=infection.json5", + "test:unit": "phpunit -c phpunit.xml.dist --testsuite unit --no-coverage --colors=always --fail-on-warning --fail-on-risky --display-deprecations --display-phpunit-deprecations", + "test:coverage": "XDEBUG_MODE=coverage phpunit -c phpunit.xml.dist --coverage-text --coverage-clover build/coverage.xml", "qa": [ "@lint", "@cs:check", From 40e70f986416886d5a965b83f702a3b4c53ff70f Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 20:46:11 -0300 Subject: [PATCH 18/43] test: expect transport timeout error Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- tests/Unit/Transport/StreamTransportTest.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/Unit/Transport/StreamTransportTest.php b/tests/Unit/Transport/StreamTransportTest.php index 5f1e2b5..7df3e97 100644 --- a/tests/Unit/Transport/StreamTransportTest.php +++ b/tests/Unit/Transport/StreamTransportTest.php @@ -9,7 +9,7 @@ namespace LibreCode\UsageStatistics\Tests\Transport; -use InvalidArgumentException; +use LibreCode\UsageStatistics\Exception\TransportException; use LibreCode\UsageStatistics\Transport\StreamTransport; use PHPUnit\Framework\TestCase; @@ -17,7 +17,9 @@ final class StreamTransportTest extends TestCase { public function testRejectsNonPositiveTimeoutBeforeNetworkAccess(): void { - $this->expectException(InvalidArgumentException::class); + $this->expectException(TransportException::class); + $this->expectExceptionMessage('Timeout must be greater than zero.'); + (new StreamTransport())->request('POST', 'https://stats.example/api/v1/reports', [], '{}', 0.0); } } From 18040e0404dfd6642bba02dbbc38e3bc4ccf798a Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 20:50:05 -0300 Subject: [PATCH 19/43] fix: resolve quality tool findings Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- .github/workflows/autofix-php-cs.yml | 38 ++++++++++++++++++++++++++++ .github/workflows/lint-php-cs.yml | 2 +- infection.json5 | 2 +- phpcs.xml.dist | 11 ++++++-- phpmd.xml | 4 ++- phpstan.neon | 1 - psalm.xml | 3 +-- src/Client.php | 3 ++- src/Report.php | 2 +- src/Transport/StreamTransport.php | 25 +++++++++++++----- 10 files changed, 75 insertions(+), 16 deletions(-) create mode 100644 .github/workflows/autofix-php-cs.yml diff --git a/.github/workflows/autofix-php-cs.yml b/.github/workflows/autofix-php-cs.yml new file mode 100644 index 0000000..e1a06a0 --- /dev/null +++ b/.github/workflows/autofix-php-cs.yml @@ -0,0 +1,38 @@ +# SPDX-FileCopyrightText: 2026 LibreCode coop and contributors +# SPDX-License-Identifier: AGPL-3.0-or-later + +name: Temporary PHP CS autofix + +on: pull_request + +permissions: + contents: write + +jobs: + autofix: + if: github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-latest + steps: + - name: Checkout PR branch + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event.pull_request.head.ref }} + persist-credentials: true + - name: Set up PHP + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: '8.2' + coverage: none + - name: Install dependencies + run: composer install --no-interaction --prefer-dist + - name: Apply Nextcloud coding standard + run: composer cs:fix + - name: Commit formatting + run: | + git config user.name "Vitor Mattos" + git config user.email "1079143+vitormattos@users.noreply.github.com" + git add src tests + if ! git diff --cached --quiet; then + git commit -s -m "style: apply Nextcloud coding standard" + git push origin HEAD:${{ github.event.pull_request.head.ref }} + fi diff --git a/.github/workflows/lint-php-cs.yml b/.github/workflows/lint-php-cs.yml index b0d0099..c9d350e 100644 --- a/.github/workflows/lint-php-cs.yml +++ b/.github/workflows/lint-php-cs.yml @@ -20,7 +20,7 @@ jobs: - name: Set up PHP uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 with: - php-version: '8.3' + php-version: '8.2' coverage: none - name: Install dependencies run: composer install --no-interaction --prefer-dist diff --git a/infection.json5 b/infection.json5 index 91a6c39..ad0b176 100644 --- a/infection.json5 +++ b/infection.json5 @@ -8,7 +8,7 @@ }, "phpUnit": { "configDir": ".", - "customPath": "vendor-bin/phpunit/vendor/bin/phpunit" + "customPath": "vendor/bin/phpunit" }, "minMsi": 90, "minCoveredMsi": 90, diff --git a/phpcs.xml.dist b/phpcs.xml.dist index b17e998..e3c11a7 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -4,12 +4,19 @@ SPDX-FileCopyrightText: 2026 LibreCode coop and contributors SPDX-License-Identifier: AGPL-3.0-or-later --> - PHP_CodeSniffer rules for the usage statistics client. + Complementary PHP_CodeSniffer checks; Nextcloud coding-standard is the formatting authority. src tests/Unit vendor/* vendor-bin/* - + + + + + + + + diff --git a/phpmd.xml b/phpmd.xml index 51a5bdd..c0c4e70 100644 --- a/phpmd.xml +++ b/phpmd.xml @@ -8,6 +8,8 @@ SPDX-License-Identifier: AGPL-3.0-or-later - + + + diff --git a/phpstan.neon b/phpstan.neon index 0cc8485..56a3d68 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -5,5 +5,4 @@ parameters: level: max paths: - src - - tests/Unit tmpDir: build/phpstan diff --git a/psalm.xml b/psalm.xml index ad84959..3789a19 100644 --- a/psalm.xml +++ b/psalm.xml @@ -3,10 +3,9 @@ SPDX-FileCopyrightText: 2026 LibreCode coop and contributors SPDX-License-Identifier: AGPL-3.0-or-later --> - + - diff --git a/src/Client.php b/src/Client.php index 8182f13..776016a 100644 --- a/src/Client.php +++ b/src/Client.php @@ -9,6 +9,7 @@ namespace LibreCode\UsageStatistics; +use InvalidArgumentException; use JsonException; use LibreCode\UsageStatistics\Exception\ProtocolException; use LibreCode\UsageStatistics\Exception\ServerRejectedException; @@ -22,7 +23,7 @@ public function __construct( private readonly float $timeoutSeconds = 5.0, ) { if ($timeoutSeconds <= 0) { - throw new \InvalidArgumentException('Timeout must be greater than zero.'); + throw new InvalidArgumentException('Timeout must be greater than zero.'); } } diff --git a/src/Report.php b/src/Report.php index 5aa356a..b15f66a 100644 --- a/src/Report.php +++ b/src/Report.php @@ -45,7 +45,7 @@ public function __construct( } $seen[$identity] = true; } - $this->metrics = array_values($metrics); + $this->metrics = $metrics; } /** @return array{protocolVersion:int,application:string,installationId:string,schemaVersion:int,period:array{start:string,end:string},metrics:list} */ diff --git a/src/Transport/StreamTransport.php b/src/Transport/StreamTransport.php index 40c4cf1..c98c473 100644 --- a/src/Transport/StreamTransport.php +++ b/src/Transport/StreamTransport.php @@ -36,6 +36,7 @@ public function request(string $method, string $url, array $headers, string $bod ], ]); + $http_response_header = null; set_error_handler(static fn (): bool => true); try { $responseBody = file_get_contents($url, false, $context); @@ -44,29 +45,41 @@ public function request(string $method, string $url, array $headers, string $bod } /** @var list|null $http_response_header */ - if ($responseBody === false || !isset($http_response_header)) { + if ($responseBody === false || $http_response_header === null) { throw new TransportException('Unable to reach usage statistics server.'); } + return $this->createResponse($responseBody, $http_response_header); + } + + /** + * @param list $headerLines + */ + private function createResponse(string $body, array $headerLines): Response + { $statusCode = null; $responseHeaders = []; - foreach ($http_response_header as $line) { + + foreach ($headerLines as $line) { if (preg_match('/^HTTP\/\S+\s+(\d{3})\b/', $line, $matches) === 1) { $statusCode = (int)$matches[1]; $responseHeaders = []; continue; } + $separator = strpos($line, ':'); - if ($separator !== false) { - $name = strtolower(trim(substr($line, 0, $separator))); - $responseHeaders[$name] = trim(substr($line, $separator + 1)); + if ($separator === false) { + continue; } + + $name = strtolower(trim(substr($line, 0, $separator))); + $responseHeaders[$name] = trim(substr($line, $separator + 1)); } if ($statusCode === null) { throw new TransportException('Server response did not contain an HTTP status line.'); } - return new Response($statusCode, $responseBody, $responseHeaders); + return new Response($statusCode, $body, $responseHeaders); } } From 129af30bfc7a8dca0d1dda9bcff4532d4841e370 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Tue, 8 Sep 2026 23:50:41 +0000 Subject: [PATCH 20/43] style: apply Nextcloud coding standard Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- src/Client.php | 129 ++++++------ src/ConsentState.php | 9 +- src/Endpoint.php | 55 +++--- src/Exception/ProtocolException.php | 3 +- src/Exception/ServerRejectedException.php | 26 ++- src/Exception/TransportException.php | 3 +- src/InstallationId.php | 58 +++--- src/Metric.php | 106 +++++----- src/Report.php | 99 +++++----- src/ReportingPeriod.php | 72 ++++--- src/SubmissionResult.php | 7 +- src/Transport/Response.php | 38 ++-- src/Transport/StreamTransport.php | 139 +++++++------ src/Transport/TransportInterface.php | 7 +- tests/Unit/ClientTest.php | 129 ++++++------ tests/Unit/EndpointTest.php | 34 ++-- tests/Unit/InstallationIdTest.php | 24 ++- tests/Unit/MetricTest.php | 66 +++---- tests/Unit/RecordingTransport.php | 62 +++--- tests/Unit/ReportTest.php | 198 +++++++++---------- tests/Unit/ReportingPeriodTest.php | 91 ++++----- tests/Unit/Transport/ResponseTest.php | 21 +- tests/Unit/Transport/StreamTransportTest.php | 14 +- tests/scoping-smoke.php | 22 +-- 24 files changed, 668 insertions(+), 744 deletions(-) diff --git a/src/Client.php b/src/Client.php index 776016a..30cc12f 100644 --- a/src/Client.php +++ b/src/Client.php @@ -15,80 +15,77 @@ use LibreCode\UsageStatistics\Exception\ServerRejectedException; use LibreCode\UsageStatistics\Transport\TransportInterface; -final class Client -{ - public function __construct( - private readonly TransportInterface $transport, - private readonly Endpoint $endpoint, - private readonly float $timeoutSeconds = 5.0, - ) { - if ($timeoutSeconds <= 0) { - throw new InvalidArgumentException('Timeout must be greater than zero.'); - } - } +final class Client { + public function __construct( + private readonly TransportInterface $transport, + private readonly Endpoint $endpoint, + private readonly float $timeoutSeconds = 5.0, + ) { + if ($timeoutSeconds <= 0) { + throw new InvalidArgumentException('Timeout must be greater than zero.'); + } + } - public function submit(Report $report, ConsentState $consent): SubmissionResult - { - if ($consent !== ConsentState::Enabled) { - return SubmissionResult::SkippedWithoutConsent; - } + public function submit(Report $report, ConsentState $consent): SubmissionResult { + if ($consent !== ConsentState::Enabled) { + return SubmissionResult::SkippedWithoutConsent; + } - try { - $payload = json_encode($report->toArray(), JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES); - } catch (JsonException $e) { - throw new ProtocolException('Unable to serialize report.', 0, $e); - } + try { + $payload = json_encode($report->toArray(), JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES); + } catch (JsonException $e) { + throw new ProtocolException('Unable to serialize report.', 0, $e); + } - $response = $this->transport->request( - 'POST', - $this->endpoint->url, - [ - 'Accept' => 'application/json', - 'Content-Type' => 'application/json', - ], - $payload, - $this->timeoutSeconds, - ); + $response = $this->transport->request( + 'POST', + $this->endpoint->url, + [ + 'Accept' => 'application/json', + 'Content-Type' => 'application/json', + ], + $payload, + $this->timeoutSeconds, + ); - if ($response->statusCode !== 200) { - [$errorCode, $message] = $this->parseError($response->body); - throw new ServerRejectedException( - $response->statusCode, - $errorCode, - $message ?? 'Usage statistics server rejected the report.', - $response->header('retry-after'), - ); - } + if ($response->statusCode !== 200) { + [$errorCode, $message] = $this->parseError($response->body); + throw new ServerRejectedException( + $response->statusCode, + $errorCode, + $message ?? 'Usage statistics server rejected the report.', + $response->header('retry-after'), + ); + } - try { - $body = json_decode($response->body, true, 512, JSON_THROW_ON_ERROR); - } catch (JsonException $e) { - throw new ProtocolException('Usage statistics server returned invalid JSON.', 0, $e); - } + try { + $body = json_decode($response->body, true, 512, JSON_THROW_ON_ERROR); + } catch (JsonException $e) { + throw new ProtocolException('Usage statistics server returned invalid JSON.', 0, $e); + } - if (!is_array($body) || ($body['status'] ?? null) !== 'accepted') { - throw new ProtocolException('Usage statistics server returned an unexpected success response.'); - } + if (!is_array($body) || ($body['status'] ?? null) !== 'accepted') { + throw new ProtocolException('Usage statistics server returned an unexpected success response.'); + } - return SubmissionResult::Accepted; - } + return SubmissionResult::Accepted; + } - /** @return array{0:?string,1:?string} */ - private function parseError(string $body): array - { - try { - $decoded = json_decode($body, true, 512, JSON_THROW_ON_ERROR); - } catch (JsonException) { - return [null, null]; - } + /** @return array{0:?string,1:?string} */ + private function parseError(string $body): array { + try { + $decoded = json_decode($body, true, 512, JSON_THROW_ON_ERROR); + } catch (JsonException) { + return [null, null]; + } - if (!is_array($decoded)) { - return [null, null]; - } + if (!is_array($decoded)) { + return [null, null]; + } - return [ - is_string($decoded['error'] ?? null) ? $decoded['error'] : null, - is_string($decoded['message'] ?? null) ? $decoded['message'] : null, - ]; - } + return [ + is_string($decoded['error'] ?? null) ? $decoded['error'] : null, + is_string($decoded['message'] ?? null) ? $decoded['message'] : null, + ]; + } } diff --git a/src/ConsentState.php b/src/ConsentState.php index 353aac4..b8cbb3b 100644 --- a/src/ConsentState.php +++ b/src/ConsentState.php @@ -9,9 +9,8 @@ namespace LibreCode\UsageStatistics; -enum ConsentState: string -{ - case Unknown = 'unknown'; - case Enabled = 'enabled'; - case Disabled = 'disabled'; +enum ConsentState: string { + case Unknown = 'unknown'; + case Enabled = 'enabled'; + case Disabled = 'disabled'; } diff --git a/src/Endpoint.php b/src/Endpoint.php index 42128ff..f7a5c6e 100644 --- a/src/Endpoint.php +++ b/src/Endpoint.php @@ -11,33 +11,30 @@ use InvalidArgumentException; -final class Endpoint -{ - public readonly string $url; - - public function __construct(string $url) - { - $parts = parse_url($url); - if ( - !is_array($parts) - || ($parts['scheme'] ?? null) !== 'https' - || !isset($parts['host']) - || $parts['host'] === '' - || isset($parts['user']) - || isset($parts['pass']) - || isset($parts['query']) - || isset($parts['fragment']) - ) { - throw new InvalidArgumentException( - 'Report endpoint must be an HTTPS URL without credentials, query, or fragment.', - ); - } - - $this->url = rtrim($url, '/'); - } - - public function __toString(): string - { - return $this->url; - } +final class Endpoint { + public readonly string $url; + + public function __construct(string $url) { + $parts = parse_url($url); + if ( + !is_array($parts) + || ($parts['scheme'] ?? null) !== 'https' + || !isset($parts['host']) + || $parts['host'] === '' + || isset($parts['user']) + || isset($parts['pass']) + || isset($parts['query']) + || isset($parts['fragment']) + ) { + throw new InvalidArgumentException( + 'Report endpoint must be an HTTPS URL without credentials, query, or fragment.', + ); + } + + $this->url = rtrim($url, '/'); + } + + public function __toString(): string { + return $this->url; + } } diff --git a/src/Exception/ProtocolException.php b/src/Exception/ProtocolException.php index 68c6105..cbfa4cf 100644 --- a/src/Exception/ProtocolException.php +++ b/src/Exception/ProtocolException.php @@ -11,6 +11,5 @@ use RuntimeException; -final class ProtocolException extends RuntimeException -{ +final class ProtocolException extends RuntimeException { } diff --git a/src/Exception/ServerRejectedException.php b/src/Exception/ServerRejectedException.php index b6ef54c..3a06f9c 100644 --- a/src/Exception/ServerRejectedException.php +++ b/src/Exception/ServerRejectedException.php @@ -11,19 +11,17 @@ use RuntimeException; -final class ServerRejectedException extends RuntimeException -{ - public function __construct( - public readonly int $statusCode, - public readonly ?string $errorCode = null, - string $message = 'Usage statistics server rejected the report.', - public readonly ?string $retryAfter = null, - ) { - parent::__construct($message); - } +final class ServerRejectedException extends RuntimeException { + public function __construct( + public readonly int $statusCode, + public readonly ?string $errorCode = null, + string $message = 'Usage statistics server rejected the report.', + public readonly ?string $retryAfter = null, + ) { + parent::__construct($message); + } - public function isTransient(): bool - { - return $this->statusCode === 429 || $this->statusCode >= 500; - } + public function isTransient(): bool { + return $this->statusCode === 429 || $this->statusCode >= 500; + } } diff --git a/src/Exception/TransportException.php b/src/Exception/TransportException.php index e3a0f7b..1ae9aea 100644 --- a/src/Exception/TransportException.php +++ b/src/Exception/TransportException.php @@ -11,6 +11,5 @@ use RuntimeException; -final class TransportException extends RuntimeException -{ +final class TransportException extends RuntimeException { } diff --git a/src/InstallationId.php b/src/InstallationId.php index 703a94b..9dd4f33 100644 --- a/src/InstallationId.php +++ b/src/InstallationId.php @@ -11,34 +11,32 @@ use InvalidArgumentException; -final class InstallationId -{ - private const APPLICATION_PATTERN = '/^[A-Za-z0-9_.:-]+$/D'; - - private function __construct(public readonly string $value) - { - } - - public static function derive(string $application, string $localInstallationIdentifier): self - { - if ( - $application === '' - || strlen($application) > 128 - || preg_match(self::APPLICATION_PATTERN, $application) !== 1 - ) { - throw new InvalidArgumentException('Application identifier is invalid.'); - } - if ($localInstallationIdentifier === '') { - throw new InvalidArgumentException('Local installation identifier must not be empty.'); - } - - $input = "usage-statistics:v1\0" . $application . "\0" . $localInstallationIdentifier; - - return new self(hash('sha256', $input)); - } - - public function __toString(): string - { - return $this->value; - } +final class InstallationId { + private const APPLICATION_PATTERN = '/^[A-Za-z0-9_.:-]+$/D'; + + private function __construct( + public readonly string $value, + ) { + } + + public static function derive(string $application, string $localInstallationIdentifier): self { + if ( + $application === '' + || strlen($application) > 128 + || preg_match(self::APPLICATION_PATTERN, $application) !== 1 + ) { + throw new InvalidArgumentException('Application identifier is invalid.'); + } + if ($localInstallationIdentifier === '') { + throw new InvalidArgumentException('Local installation identifier must not be empty.'); + } + + $input = "usage-statistics:v1\0" . $application . "\0" . $localInstallationIdentifier; + + return new self(hash('sha256', $input)); + } + + public function __toString(): string { + return $this->value; + } } diff --git a/src/Metric.php b/src/Metric.php index 9641385..4802811 100644 --- a/src/Metric.php +++ b/src/Metric.php @@ -11,71 +11,63 @@ use InvalidArgumentException; -final class Metric -{ - private const IDENTIFIER_PATTERN = '/^[A-Za-z0-9_.:-]+$/D'; - private const MAX_CATEGORY_LENGTH = 128; - private const MAX_KEY_LENGTH = 512; - private const MAX_STRING_VALUE_LENGTH = 1024; +final class Metric { + private const IDENTIFIER_PATTERN = '/^[A-Za-z0-9_.:-]+$/D'; + private const MAX_CATEGORY_LENGTH = 128; + private const MAX_KEY_LENGTH = 512; + private const MAX_STRING_VALUE_LENGTH = 1024; - private function __construct( - public readonly string $category, - public readonly string $key, - public readonly string $type, - public readonly string|int|float|bool $value, - ) { - self::assertIdentifier($category, 'Metric category', self::MAX_CATEGORY_LENGTH); - self::assertIdentifier($key, 'Metric key', self::MAX_KEY_LENGTH); - } + private function __construct( + public readonly string $category, + public readonly string $key, + public readonly string $type, + public readonly string|int|float|bool $value, + ) { + self::assertIdentifier($category, 'Metric category', self::MAX_CATEGORY_LENGTH); + self::assertIdentifier($key, 'Metric key', self::MAX_KEY_LENGTH); + } - public static function integer(string $category, string $key, int $value): self - { - return new self($category, $key, 'integer', $value); - } + public static function integer(string $category, string $key, int $value): self { + return new self($category, $key, 'integer', $value); + } - public static function number(string $category, string $key, int|float $value): self - { - if (is_float($value) && !is_finite($value)) { - throw new InvalidArgumentException('Number metric must be finite.'); - } + public static function number(string $category, string $key, int|float $value): self { + if (is_float($value) && !is_finite($value)) { + throw new InvalidArgumentException('Number metric must be finite.'); + } - return new self($category, $key, 'number', $value); - } + return new self($category, $key, 'number', $value); + } - public static function boolean(string $category, string $key, bool $value): self - { - return new self($category, $key, 'boolean', $value); - } + public static function boolean(string $category, string $key, bool $value): self { + return new self($category, $key, 'boolean', $value); + } - public static function string(string $category, string $key, string $value): self - { - if (strlen($value) > self::MAX_STRING_VALUE_LENGTH) { - throw new InvalidArgumentException('String metric value exceeds 1024 bytes.'); - } + public static function string(string $category, string $key, string $value): self { + if (strlen($value) > self::MAX_STRING_VALUE_LENGTH) { + throw new InvalidArgumentException('String metric value exceeds 1024 bytes.'); + } - return new self($category, $key, 'string', $value); - } + return new self($category, $key, 'string', $value); + } - /** @return array{category:string,key:string,type:string,value:string|int|float|bool} */ - public function toArray(): array - { - return [ - 'category' => $this->category, - 'key' => $this->key, - 'type' => $this->type, - 'value' => $this->value, - ]; - } + /** @return array{category:string,key:string,type:string,value:string|int|float|bool} */ + public function toArray(): array { + return [ + 'category' => $this->category, + 'key' => $this->key, + 'type' => $this->type, + 'value' => $this->value, + ]; + } - public function identity(): string - { - return $this->category . "\0" . $this->key; - } + public function identity(): string { + return $this->category . "\0" . $this->key; + } - private static function assertIdentifier(string $value, string $field, int $maxLength): void - { - if ($value === '' || strlen($value) > $maxLength || preg_match(self::IDENTIFIER_PATTERN, $value) !== 1) { - throw new InvalidArgumentException($field . ' is invalid.'); - } - } + private static function assertIdentifier(string $value, string $field, int $maxLength): void { + if ($value === '' || strlen($value) > $maxLength || preg_match(self::IDENTIFIER_PATTERN, $value) !== 1) { + throw new InvalidArgumentException($field . ' is invalid.'); + } + } } diff --git a/src/Report.php b/src/Report.php index b15f66a..4833040 100644 --- a/src/Report.php +++ b/src/Report.php @@ -11,60 +11,57 @@ use InvalidArgumentException; -final class Report -{ - public const PROTOCOL_VERSION = 1; - private const IDENTIFIER_PATTERN = '/^[A-Za-z0-9_.:-]+$/D'; - private const MAX_METRICS = 256; +final class Report { + public const PROTOCOL_VERSION = 1; + private const IDENTIFIER_PATTERN = '/^[A-Za-z0-9_.:-]+$/D'; + private const MAX_METRICS = 256; - /** @var list */ - public readonly array $metrics; + /** @var list */ + public readonly array $metrics; - /** @param list $metrics */ - public function __construct( - public readonly string $application, - public readonly string $installationId, - public readonly int $schemaVersion, - public readonly ReportingPeriod $period, - array $metrics, - ) { - self::assertIdentifier($application, 'Application', 128); - self::assertIdentifier($installationId, 'Installation ID', 128); - if ($schemaVersion < 1) { - throw new InvalidArgumentException('Schema version must be a positive integer.'); - } - if ($metrics === [] || count($metrics) > self::MAX_METRICS) { - throw new InvalidArgumentException('Report must contain between 1 and 256 metrics.'); - } + /** @param list $metrics */ + public function __construct( + public readonly string $application, + public readonly string $installationId, + public readonly int $schemaVersion, + public readonly ReportingPeriod $period, + array $metrics, + ) { + self::assertIdentifier($application, 'Application', 128); + self::assertIdentifier($installationId, 'Installation ID', 128); + if ($schemaVersion < 1) { + throw new InvalidArgumentException('Schema version must be a positive integer.'); + } + if ($metrics === [] || count($metrics) > self::MAX_METRICS) { + throw new InvalidArgumentException('Report must contain between 1 and 256 metrics.'); + } - $seen = []; - foreach ($metrics as $metric) { - $identity = $metric->identity(); - if (isset($seen[$identity])) { - throw new InvalidArgumentException('Duplicate metric category/key pair.'); - } - $seen[$identity] = true; - } - $this->metrics = $metrics; - } + $seen = []; + foreach ($metrics as $metric) { + $identity = $metric->identity(); + if (isset($seen[$identity])) { + throw new InvalidArgumentException('Duplicate metric category/key pair.'); + } + $seen[$identity] = true; + } + $this->metrics = $metrics; + } - /** @return array{protocolVersion:int,application:string,installationId:string,schemaVersion:int,period:array{start:string,end:string},metrics:list} */ - public function toArray(): array - { - return [ - 'protocolVersion' => self::PROTOCOL_VERSION, - 'application' => $this->application, - 'installationId' => $this->installationId, - 'schemaVersion' => $this->schemaVersion, - 'period' => $this->period->toArray(), - 'metrics' => array_map(static fn (Metric $metric): array => $metric->toArray(), $this->metrics), - ]; - } + /** @return array{protocolVersion:int,application:string,installationId:string,schemaVersion:int,period:array{start:string,end:string},metrics:list} */ + public function toArray(): array { + return [ + 'protocolVersion' => self::PROTOCOL_VERSION, + 'application' => $this->application, + 'installationId' => $this->installationId, + 'schemaVersion' => $this->schemaVersion, + 'period' => $this->period->toArray(), + 'metrics' => array_map(static fn (Metric $metric): array => $metric->toArray(), $this->metrics), + ]; + } - private static function assertIdentifier(string $value, string $field, int $maxLength): void - { - if ($value === '' || strlen($value) > $maxLength || preg_match(self::IDENTIFIER_PATTERN, $value) !== 1) { - throw new InvalidArgumentException($field . ' is invalid.'); - } - } + private static function assertIdentifier(string $value, string $field, int $maxLength): void { + if ($value === '' || strlen($value) > $maxLength || preg_match(self::IDENTIFIER_PATTERN, $value) !== 1) { + throw new InvalidArgumentException($field . ' is invalid.'); + } + } } diff --git a/src/ReportingPeriod.php b/src/ReportingPeriod.php index 8ad8933..38b39ca 100644 --- a/src/ReportingPeriod.php +++ b/src/ReportingPeriod.php @@ -14,42 +14,38 @@ use DateTimeZone; use InvalidArgumentException; -final class ReportingPeriod -{ - private const MAX_SECONDS = 2_678_400; - - public readonly DateTimeImmutable $start; - public readonly DateTimeImmutable $end; - - public function __construct(DateTimeImmutable $start, DateTimeImmutable $end) - { - $utc = new DateTimeZone('UTC'); - $this->start = $start->setTimezone($utc); - $this->end = $end->setTimezone($utc); - - $duration = $this->end->getTimestamp() - $this->start->getTimestamp(); - if ($duration <= 0 || $duration > self::MAX_SECONDS) { - throw new InvalidArgumentException('Reporting period must be positive and no longer than 31 days.'); - } - } - - public static function monthContaining(DateTimeImmutable $instant): self - { - $utc = $instant->setTimezone(new DateTimeZone('UTC')); - $start = $utc - ->setDate((int)$utc->format('Y'), (int)$utc->format('m'), 1) - ->setTime(0, 0, 0, 0); - $end = $start->add(new DateInterval('P1M')); - - return new self($start, $end); - } - - /** @return array{start:string,end:string} */ - public function toArray(): array - { - return [ - 'start' => $this->start->format('Y-m-d\TH:i:s\Z'), - 'end' => $this->end->format('Y-m-d\TH:i:s\Z'), - ]; - } +final class ReportingPeriod { + private const MAX_SECONDS = 2_678_400; + + public readonly DateTimeImmutable $start; + public readonly DateTimeImmutable $end; + + public function __construct(DateTimeImmutable $start, DateTimeImmutable $end) { + $utc = new DateTimeZone('UTC'); + $this->start = $start->setTimezone($utc); + $this->end = $end->setTimezone($utc); + + $duration = $this->end->getTimestamp() - $this->start->getTimestamp(); + if ($duration <= 0 || $duration > self::MAX_SECONDS) { + throw new InvalidArgumentException('Reporting period must be positive and no longer than 31 days.'); + } + } + + public static function monthContaining(DateTimeImmutable $instant): self { + $utc = $instant->setTimezone(new DateTimeZone('UTC')); + $start = $utc + ->setDate((int)$utc->format('Y'), (int)$utc->format('m'), 1) + ->setTime(0, 0, 0, 0); + $end = $start->add(new DateInterval('P1M')); + + return new self($start, $end); + } + + /** @return array{start:string,end:string} */ + public function toArray(): array { + return [ + 'start' => $this->start->format('Y-m-d\TH:i:s\Z'), + 'end' => $this->end->format('Y-m-d\TH:i:s\Z'), + ]; + } } diff --git a/src/SubmissionResult.php b/src/SubmissionResult.php index c6dba7b..cbbbab3 100644 --- a/src/SubmissionResult.php +++ b/src/SubmissionResult.php @@ -9,8 +9,7 @@ namespace LibreCode\UsageStatistics; -enum SubmissionResult: string -{ - case Accepted = 'accepted'; - case SkippedWithoutConsent = 'skipped_without_consent'; +enum SubmissionResult: string { + case Accepted = 'accepted'; + case SkippedWithoutConsent = 'skipped_without_consent'; } diff --git a/src/Transport/Response.php b/src/Transport/Response.php index 19216ef..4a15893 100644 --- a/src/Transport/Response.php +++ b/src/Transport/Response.php @@ -9,26 +9,24 @@ namespace LibreCode\UsageStatistics\Transport; -final class Response -{ - /** @var array */ - public readonly array $headers; +final class Response { + /** @var array */ + public readonly array $headers; - /** @param array $headers */ - public function __construct( - public readonly int $statusCode, - public readonly string $body, - array $headers = [], - ) { - $normalized = []; - foreach ($headers as $name => $value) { - $normalized[strtolower($name)] = $value; - } - $this->headers = $normalized; - } + /** @param array $headers */ + public function __construct( + public readonly int $statusCode, + public readonly string $body, + array $headers = [], + ) { + $normalized = []; + foreach ($headers as $name => $value) { + $normalized[strtolower($name)] = $value; + } + $this->headers = $normalized; + } - public function header(string $name): ?string - { - return $this->headers[strtolower($name)] ?? null; - } + public function header(string $name): ?string { + return $this->headers[strtolower($name)] ?? null; + } } diff --git a/src/Transport/StreamTransport.php b/src/Transport/StreamTransport.php index c98c473..e8bc009 100644 --- a/src/Transport/StreamTransport.php +++ b/src/Transport/StreamTransport.php @@ -11,75 +11,72 @@ use LibreCode\UsageStatistics\Exception\TransportException; -final class StreamTransport implements TransportInterface -{ - /** @param array $headers */ - public function request(string $method, string $url, array $headers, string $body, float $timeoutSeconds): Response - { - if ($timeoutSeconds <= 0) { - throw new TransportException('Timeout must be greater than zero.'); - } - - $headerLines = []; - foreach ($headers as $name => $value) { - $headerLines[] = $name . ': ' . $value; - } - - $context = stream_context_create([ - 'http' => [ - 'method' => $method, - 'header' => implode("\r\n", $headerLines), - 'content' => $body, - 'timeout' => $timeoutSeconds, - 'ignore_errors' => true, - 'follow_location' => 0, - ], - ]); - - $http_response_header = null; - set_error_handler(static fn (): bool => true); - try { - $responseBody = file_get_contents($url, false, $context); - } finally { - restore_error_handler(); - } - - /** @var list|null $http_response_header */ - if ($responseBody === false || $http_response_header === null) { - throw new TransportException('Unable to reach usage statistics server.'); - } - - return $this->createResponse($responseBody, $http_response_header); - } - - /** - * @param list $headerLines - */ - private function createResponse(string $body, array $headerLines): Response - { - $statusCode = null; - $responseHeaders = []; - - foreach ($headerLines as $line) { - if (preg_match('/^HTTP\/\S+\s+(\d{3})\b/', $line, $matches) === 1) { - $statusCode = (int)$matches[1]; - $responseHeaders = []; - continue; - } - - $separator = strpos($line, ':'); - if ($separator === false) { - continue; - } - - $name = strtolower(trim(substr($line, 0, $separator))); - $responseHeaders[$name] = trim(substr($line, $separator + 1)); - } - - if ($statusCode === null) { - throw new TransportException('Server response did not contain an HTTP status line.'); - } - - return new Response($statusCode, $body, $responseHeaders); - } +final class StreamTransport implements TransportInterface { + /** @param array $headers */ + public function request(string $method, string $url, array $headers, string $body, float $timeoutSeconds): Response { + if ($timeoutSeconds <= 0) { + throw new TransportException('Timeout must be greater than zero.'); + } + + $headerLines = []; + foreach ($headers as $name => $value) { + $headerLines[] = $name . ': ' . $value; + } + + $context = stream_context_create([ + 'http' => [ + 'method' => $method, + 'header' => implode("\r\n", $headerLines), + 'content' => $body, + 'timeout' => $timeoutSeconds, + 'ignore_errors' => true, + 'follow_location' => 0, + ], + ]); + + $http_response_header = null; + set_error_handler(static fn (): bool => true); + try { + $responseBody = file_get_contents($url, false, $context); + } finally { + restore_error_handler(); + } + + /** @var list|null $http_response_header */ + if ($responseBody === false || $http_response_header === null) { + throw new TransportException('Unable to reach usage statistics server.'); + } + + return $this->createResponse($responseBody, $http_response_header); + } + + /** + * @param list $headerLines + */ + private function createResponse(string $body, array $headerLines): Response { + $statusCode = null; + $responseHeaders = []; + + foreach ($headerLines as $line) { + if (preg_match('/^HTTP\/\S+\s+(\d{3})\b/', $line, $matches) === 1) { + $statusCode = (int)$matches[1]; + $responseHeaders = []; + continue; + } + + $separator = strpos($line, ':'); + if ($separator === false) { + continue; + } + + $name = strtolower(trim(substr($line, 0, $separator))); + $responseHeaders[$name] = trim(substr($line, $separator + 1)); + } + + if ($statusCode === null) { + throw new TransportException('Server response did not contain an HTTP status line.'); + } + + return new Response($statusCode, $body, $responseHeaders); + } } diff --git a/src/Transport/TransportInterface.php b/src/Transport/TransportInterface.php index 5caea49..602bd1f 100644 --- a/src/Transport/TransportInterface.php +++ b/src/Transport/TransportInterface.php @@ -9,8 +9,7 @@ namespace LibreCode\UsageStatistics\Transport; -interface TransportInterface -{ - /** @param array $headers */ - public function request(string $method, string $url, array $headers, string $body, float $timeoutSeconds): Response; +interface TransportInterface { + /** @param array $headers */ + public function request(string $method, string $url, array $headers, string $body, float $timeoutSeconds): Response; } diff --git a/tests/Unit/ClientTest.php b/tests/Unit/ClientTest.php index c49b80c..5732fd1 100644 --- a/tests/Unit/ClientTest.php +++ b/tests/Unit/ClientTest.php @@ -22,81 +22,74 @@ use LibreCode\UsageStatistics\Transport\Response; use PHPUnit\Framework\TestCase; -final class ClientTest extends TestCase -{ - public function testDoesNotSendWithoutEnabledConsent(): void - { - $transport = new RecordingTransport(new Response(200, '{"status":"accepted"}')); - $client = new Client($transport, new Endpoint('https://stats.example/api/v1/reports')); +final class ClientTest extends TestCase { + public function testDoesNotSendWithoutEnabledConsent(): void { + $transport = new RecordingTransport(new Response(200, '{"status":"accepted"}')); + $client = new Client($transport, new Endpoint('https://stats.example/api/v1/reports')); - self::assertSame(SubmissionResult::SkippedWithoutConsent, $client->submit($this->report(), ConsentState::Unknown)); - self::assertSame(SubmissionResult::SkippedWithoutConsent, $client->submit($this->report(), ConsentState::Disabled)); - self::assertSame(0, $transport->calls); - } + self::assertSame(SubmissionResult::SkippedWithoutConsent, $client->submit($this->report(), ConsentState::Unknown)); + self::assertSame(SubmissionResult::SkippedWithoutConsent, $client->submit($this->report(), ConsentState::Disabled)); + self::assertSame(0, $transport->calls); + } - public function testSendsProtocolPayloadWhenEnabled(): void - { - $transport = new RecordingTransport(new Response(200, '{"status":"accepted"}')); - $client = new Client($transport, new Endpoint('https://stats.example/api/v1/reports'), 2.5); + public function testSendsProtocolPayloadWhenEnabled(): void { + $transport = new RecordingTransport(new Response(200, '{"status":"accepted"}')); + $client = new Client($transport, new Endpoint('https://stats.example/api/v1/reports'), 2.5); - self::assertSame(SubmissionResult::Accepted, $client->submit($this->report(), ConsentState::Enabled)); - self::assertSame('POST', $transport->method); - self::assertSame('https://stats.example/api/v1/reports', $transport->url); - self::assertSame(2.5, $transport->timeout); - self::assertSame('application/json', $transport->headers['Content-Type']); - $payload = json_decode($transport->body, true, 512, JSON_THROW_ON_ERROR); - if (!is_array($payload)) { - throw new \UnexpectedValueException('Expected serialized report to be an array.'); - } - self::assertSame(1, $payload['protocolVersion']); - self::assertSame('libresign', $payload['application']); - } + self::assertSame(SubmissionResult::Accepted, $client->submit($this->report(), ConsentState::Enabled)); + self::assertSame('POST', $transport->method); + self::assertSame('https://stats.example/api/v1/reports', $transport->url); + self::assertSame(2.5, $transport->timeout); + self::assertSame('application/json', $transport->headers['Content-Type']); + $payload = json_decode($transport->body, true, 512, JSON_THROW_ON_ERROR); + if (!is_array($payload)) { + throw new \UnexpectedValueException('Expected serialized report to be an array.'); + } + self::assertSame(1, $payload['protocolVersion']); + self::assertSame('libresign', $payload['application']); + } - public function testMapsServerValidationError(): void - { - $transport = new RecordingTransport(new Response(400, '{"error":"invalid_report","message":"Application schema is not registered."}')); - $client = new Client($transport, new Endpoint('https://stats.example/api/v1/reports')); + public function testMapsServerValidationError(): void { + $transport = new RecordingTransport(new Response(400, '{"error":"invalid_report","message":"Application schema is not registered."}')); + $client = new Client($transport, new Endpoint('https://stats.example/api/v1/reports')); - try { - $client->submit($this->report(), ConsentState::Enabled); - self::fail('Expected exception.'); - } catch (ServerRejectedException $e) { - self::assertSame(400, $e->statusCode); - self::assertSame('invalid_report', $e->errorCode); - self::assertFalse($e->isTransient()); - } - } + try { + $client->submit($this->report(), ConsentState::Enabled); + self::fail('Expected exception.'); + } catch (ServerRejectedException $e) { + self::assertSame(400, $e->statusCode); + self::assertSame('invalid_report', $e->errorCode); + self::assertFalse($e->isTransient()); + } + } - public function testExposesTransientServerFailure(): void - { - $transport = new RecordingTransport(new Response(429, '{"error":"rate_limited"}', ['retry-after' => '60'])); - $client = new Client($transport, new Endpoint('https://stats.example/api/v1/reports')); + public function testExposesTransientServerFailure(): void { + $transport = new RecordingTransport(new Response(429, '{"error":"rate_limited"}', ['retry-after' => '60'])); + $client = new Client($transport, new Endpoint('https://stats.example/api/v1/reports')); - try { - $client->submit($this->report(), ConsentState::Enabled); - self::fail('Expected exception.'); - } catch (ServerRejectedException $e) { - self::assertTrue($e->isTransient()); - self::assertSame('60', $e->retryAfter); - } - } + try { + $client->submit($this->report(), ConsentState::Enabled); + self::fail('Expected exception.'); + } catch (ServerRejectedException $e) { + self::assertTrue($e->isTransient()); + self::assertSame('60', $e->retryAfter); + } + } - public function testRejectsUnexpectedSuccessResponse(): void - { - $transport = new RecordingTransport(new Response(200, '{"status":"different"}')); - $client = new Client($transport, new Endpoint('https://stats.example/api/v1/reports')); - $this->expectException(ProtocolException::class); - $client->submit($this->report(), ConsentState::Enabled); - } + public function testRejectsUnexpectedSuccessResponse(): void { + $transport = new RecordingTransport(new Response(200, '{"status":"different"}')); + $client = new Client($transport, new Endpoint('https://stats.example/api/v1/reports')); + $this->expectException(ProtocolException::class); + $client->submit($this->report(), ConsentState::Enabled); + } - private function report(): Report - { - return new Report( - 'libresign', - str_repeat('a', 64), - 1, - new ReportingPeriod(new DateTimeImmutable('2026-08-01T00:00:00Z'), new DateTimeImmutable('2026-09-01T00:00:00Z')), - [Metric::integer('usage', 'requests_completed', 72)], - ); - } + private function report(): Report { + return new Report( + 'libresign', + str_repeat('a', 64), + 1, + new ReportingPeriod(new DateTimeImmutable('2026-08-01T00:00:00Z'), new DateTimeImmutable('2026-09-01T00:00:00Z')), + [Metric::integer('usage', 'requests_completed', 72)], + ); + } } diff --git a/tests/Unit/EndpointTest.php b/tests/Unit/EndpointTest.php index d7f6406..e7c01a0 100644 --- a/tests/Unit/EndpointTest.php +++ b/tests/Unit/EndpointTest.php @@ -14,25 +14,21 @@ use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; -final class EndpointTest extends TestCase -{ - public function testAcceptsHttpsEndpoint(): void - { - self::assertSame('https://stats.example/api/v1/reports', (string)new Endpoint('https://stats.example/api/v1/reports/')); - } +final class EndpointTest extends TestCase { + public function testAcceptsHttpsEndpoint(): void { + self::assertSame('https://stats.example/api/v1/reports', (string)new Endpoint('https://stats.example/api/v1/reports/')); + } - #[DataProvider('invalidEndpoints')] - public function testRejectsUnsafeEndpoints(string $endpoint): void - { - $this->expectException(InvalidArgumentException::class); - new Endpoint($endpoint); - } + #[DataProvider('invalidEndpoints')] + public function testRejectsUnsafeEndpoints(string $endpoint): void { + $this->expectException(InvalidArgumentException::class); + new Endpoint($endpoint); + } - /** @return iterable */ - public static function invalidEndpoints(): iterable - { - yield 'http' => ['http://stats.example/api/v1/reports']; - yield 'credentials' => ['https://user:secret@stats.example/api/v1/reports']; - yield 'query' => ['https://stats.example/api/v1/reports?token=x']; - } + /** @return iterable */ + public static function invalidEndpoints(): iterable { + yield 'http' => ['http://stats.example/api/v1/reports']; + yield 'credentials' => ['https://user:secret@stats.example/api/v1/reports']; + yield 'query' => ['https://stats.example/api/v1/reports?token=x']; + } } diff --git a/tests/Unit/InstallationIdTest.php b/tests/Unit/InstallationIdTest.php index 34d7715..8e31f25 100644 --- a/tests/Unit/InstallationIdTest.php +++ b/tests/Unit/InstallationIdTest.php @@ -12,18 +12,16 @@ use LibreCode\UsageStatistics\InstallationId; use PHPUnit\Framework\TestCase; -final class InstallationIdTest extends TestCase -{ - public function testDerivationIsStableAndApplicationScoped(): void - { - $first = (string)InstallationId::derive('libresign', 'local-instance-id'); - $second = (string)InstallationId::derive('libresign', 'local-instance-id'); - $otherApp = (string)InstallationId::derive('talk', 'local-instance-id'); +final class InstallationIdTest extends TestCase { + public function testDerivationIsStableAndApplicationScoped(): void { + $first = (string)InstallationId::derive('libresign', 'local-instance-id'); + $second = (string)InstallationId::derive('libresign', 'local-instance-id'); + $otherApp = (string)InstallationId::derive('talk', 'local-instance-id'); - self::assertSame('dc8adebdce9ab99790a7d037f44965b4ca7b6dceb38d5e7c9dff118721fc8415', $first); - self::assertSame($first, $second); - self::assertNotSame($first, $otherApp); - self::assertMatchesRegularExpression('/^[a-f0-9]{64}$/', $first); - self::assertStringNotContainsString('local-instance-id', $first); - } + self::assertSame('dc8adebdce9ab99790a7d037f44965b4ca7b6dceb38d5e7c9dff118721fc8415', $first); + self::assertSame($first, $second); + self::assertNotSame($first, $otherApp); + self::assertMatchesRegularExpression('/^[a-f0-9]{64}$/', $first); + self::assertStringNotContainsString('local-instance-id', $first); + } } diff --git a/tests/Unit/MetricTest.php b/tests/Unit/MetricTest.php index 951fa05..afac009 100644 --- a/tests/Unit/MetricTest.php +++ b/tests/Unit/MetricTest.php @@ -14,40 +14,34 @@ use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; -final class MetricTest extends TestCase -{ - public function testSerializesSupportedTypes(): void - { - self::assertSame(['category' => 'usage', 'key' => 'count', 'type' => 'integer', 'value' => 3], Metric::integer('usage', 'count', 3)->toArray()); - self::assertSame('number', Metric::number('usage', 'ratio', 1.5)->type); - self::assertSame('boolean', Metric::boolean('feature', 'enabled', true)->type); - self::assertSame('string', Metric::string('environment', 'version', '12.0.0')->type); - } - - #[DataProvider('invalidIdentifiers')] - public function testRejectsInvalidIdentifiers(string $category, string $key): void - { - $this->expectException(InvalidArgumentException::class); - Metric::integer($category, $key, 1); - } - - /** @return iterable */ - public static function invalidIdentifiers(): iterable - { - yield 'empty category' => ['', 'key']; - yield 'spaces' => ['usage data', 'key']; - yield 'empty key' => ['usage', '']; - } - - public function testRejectsInfiniteNumber(): void - { - $this->expectException(InvalidArgumentException::class); - Metric::number('usage', 'ratio', INF); - } - - public function testRejectsOversizedString(): void - { - $this->expectException(InvalidArgumentException::class); - Metric::string('usage', 'value', str_repeat('x', 1025)); - } +final class MetricTest extends TestCase { + public function testSerializesSupportedTypes(): void { + self::assertSame(['category' => 'usage', 'key' => 'count', 'type' => 'integer', 'value' => 3], Metric::integer('usage', 'count', 3)->toArray()); + self::assertSame('number', Metric::number('usage', 'ratio', 1.5)->type); + self::assertSame('boolean', Metric::boolean('feature', 'enabled', true)->type); + self::assertSame('string', Metric::string('environment', 'version', '12.0.0')->type); + } + + #[DataProvider('invalidIdentifiers')] + public function testRejectsInvalidIdentifiers(string $category, string $key): void { + $this->expectException(InvalidArgumentException::class); + Metric::integer($category, $key, 1); + } + + /** @return iterable */ + public static function invalidIdentifiers(): iterable { + yield 'empty category' => ['', 'key']; + yield 'spaces' => ['usage data', 'key']; + yield 'empty key' => ['usage', '']; + } + + public function testRejectsInfiniteNumber(): void { + $this->expectException(InvalidArgumentException::class); + Metric::number('usage', 'ratio', INF); + } + + public function testRejectsOversizedString(): void { + $this->expectException(InvalidArgumentException::class); + Metric::string('usage', 'value', str_repeat('x', 1025)); + } } diff --git a/tests/Unit/RecordingTransport.php b/tests/Unit/RecordingTransport.php index e045355..9765458 100644 --- a/tests/Unit/RecordingTransport.php +++ b/tests/Unit/RecordingTransport.php @@ -12,35 +12,35 @@ use LibreCode\UsageStatistics\Transport\Response; use LibreCode\UsageStatistics\Transport\TransportInterface; -final class RecordingTransport implements TransportInterface -{ - public int $calls = 0; - public string $method = ''; - public string $url = ''; - /** @var array */ - public array $headers = []; - public string $body = ''; - public float $timeout = 0.0; - - public function __construct(private readonly Response $response) - { - } - - /** @param array $headers */ - public function request( - string $method, - string $url, - array $headers, - string $body, - float $timeoutSeconds, - ): Response { - ++$this->calls; - $this->method = $method; - $this->url = $url; - $this->headers = $headers; - $this->body = $body; - $this->timeout = $timeoutSeconds; - - return $this->response; - } +final class RecordingTransport implements TransportInterface { + public int $calls = 0; + public string $method = ''; + public string $url = ''; + /** @var array */ + public array $headers = []; + public string $body = ''; + public float $timeout = 0.0; + + public function __construct( + private readonly Response $response, + ) { + } + + /** @param array $headers */ + public function request( + string $method, + string $url, + array $headers, + string $body, + float $timeoutSeconds, + ): Response { + ++$this->calls; + $this->method = $method; + $this->url = $url; + $this->headers = $headers; + $this->body = $body; + $this->timeout = $timeoutSeconds; + + return $this->response; + } } diff --git a/tests/Unit/ReportTest.php b/tests/Unit/ReportTest.php index 26b8e88..dbf8b9e 100644 --- a/tests/Unit/ReportTest.php +++ b/tests/Unit/ReportTest.php @@ -16,108 +16,98 @@ use LibreCode\UsageStatistics\ReportingPeriod; use PHPUnit\Framework\TestCase; -final class ReportTest extends TestCase -{ - public function testSerializesExactProtocolV1Payload(): void - { - $report = new Report( - 'libresign', - str_repeat('a', 64), - 2, - new ReportingPeriod( - new DateTimeImmutable('2026-08-01T00:00:00Z'), - new DateTimeImmutable('2026-09-01T00:00:00Z'), - ), - [ - Metric::string('environment', 'version', '12.0.0'), - Metric::integer('usage', 'requests_completed', 72), - ], - ); - - self::assertSame([ - 'protocolVersion' => 1, - 'application' => 'libresign', - 'installationId' => str_repeat('a', 64), - 'schemaVersion' => 2, - 'period' => [ - 'start' => '2026-08-01T00:00:00Z', - 'end' => '2026-09-01T00:00:00Z', - ], - 'metrics' => [ - ['category' => 'environment', 'key' => 'version', 'type' => 'string', 'value' => '12.0.0'], - ['category' => 'usage', 'key' => 'requests_completed', 'type' => 'integer', 'value' => 72], - ], - ], $report->toArray()); - } - - public function testAcceptsProtocolMaximumOf256Metrics(): void - { - $metrics = []; - for ($i = 0; $i < 256; ++$i) { - $metrics[] = Metric::integer('usage', 'metric_' . $i, $i); - } - - $report = new Report('libresign', str_repeat('a', 64), 1, $this->period(), $metrics); - self::assertCount(256, $report->metrics); - } - - public function testRejectsMoreThan256Metrics(): void - { - $metrics = []; - for ($i = 0; $i < 257; ++$i) { - $metrics[] = Metric::integer('usage', 'metric_' . $i, $i); - } - - $this->expectException(InvalidArgumentException::class); - new Report('libresign', str_repeat('a', 64), 1, $this->period(), $metrics); - } - - public function testRejectsDuplicateMetricIdentityRegardlessOfValue(): void - { - $this->expectException(InvalidArgumentException::class); - new Report('libresign', str_repeat('a', 64), 1, $this->period(), [ - Metric::integer('usage', 'count', 1), - Metric::integer('usage', 'count', 2), - ]); - } - - public function testRejectsEmptyMetricSet(): void - { - $this->expectException(InvalidArgumentException::class); - new Report('libresign', str_repeat('a', 64), 1, $this->period(), []); - } - - public function testRejectsSchemaVersionZero(): void - { - $this->expectException(InvalidArgumentException::class); - new Report('libresign', str_repeat('a', 64), 0, $this->period(), [Metric::integer('usage', 'count', 1)]); - } - - public function testAcceptsMaximumLengthIdentifiers(): void - { - $report = new Report( - str_repeat('a', 128), - str_repeat('b', 128), - 1, - $this->period(), - [Metric::integer('usage', 'count', 1)], - ); - - self::assertSame(128, strlen($report->application)); - self::assertSame(128, strlen($report->installationId)); - } - - public function testRejectsIdentifierOutsideProtocolAlphabet(): void - { - $this->expectException(InvalidArgumentException::class); - new Report('libresign app', str_repeat('a', 64), 1, $this->period(), [Metric::integer('usage', 'count', 1)]); - } - - private function period(): ReportingPeriod - { - return new ReportingPeriod( - new DateTimeImmutable('2026-08-01T00:00:00Z'), - new DateTimeImmutable('2026-09-01T00:00:00Z'), - ); - } +final class ReportTest extends TestCase { + public function testSerializesExactProtocolV1Payload(): void { + $report = new Report( + 'libresign', + str_repeat('a', 64), + 2, + new ReportingPeriod( + new DateTimeImmutable('2026-08-01T00:00:00Z'), + new DateTimeImmutable('2026-09-01T00:00:00Z'), + ), + [ + Metric::string('environment', 'version', '12.0.0'), + Metric::integer('usage', 'requests_completed', 72), + ], + ); + + self::assertSame([ + 'protocolVersion' => 1, + 'application' => 'libresign', + 'installationId' => str_repeat('a', 64), + 'schemaVersion' => 2, + 'period' => [ + 'start' => '2026-08-01T00:00:00Z', + 'end' => '2026-09-01T00:00:00Z', + ], + 'metrics' => [ + ['category' => 'environment', 'key' => 'version', 'type' => 'string', 'value' => '12.0.0'], + ['category' => 'usage', 'key' => 'requests_completed', 'type' => 'integer', 'value' => 72], + ], + ], $report->toArray()); + } + + public function testAcceptsProtocolMaximumOf256Metrics(): void { + $metrics = []; + for ($i = 0; $i < 256; ++$i) { + $metrics[] = Metric::integer('usage', 'metric_' . $i, $i); + } + + $report = new Report('libresign', str_repeat('a', 64), 1, $this->period(), $metrics); + self::assertCount(256, $report->metrics); + } + + public function testRejectsMoreThan256Metrics(): void { + $metrics = []; + for ($i = 0; $i < 257; ++$i) { + $metrics[] = Metric::integer('usage', 'metric_' . $i, $i); + } + + $this->expectException(InvalidArgumentException::class); + new Report('libresign', str_repeat('a', 64), 1, $this->period(), $metrics); + } + + public function testRejectsDuplicateMetricIdentityRegardlessOfValue(): void { + $this->expectException(InvalidArgumentException::class); + new Report('libresign', str_repeat('a', 64), 1, $this->period(), [ + Metric::integer('usage', 'count', 1), + Metric::integer('usage', 'count', 2), + ]); + } + + public function testRejectsEmptyMetricSet(): void { + $this->expectException(InvalidArgumentException::class); + new Report('libresign', str_repeat('a', 64), 1, $this->period(), []); + } + + public function testRejectsSchemaVersionZero(): void { + $this->expectException(InvalidArgumentException::class); + new Report('libresign', str_repeat('a', 64), 0, $this->period(), [Metric::integer('usage', 'count', 1)]); + } + + public function testAcceptsMaximumLengthIdentifiers(): void { + $report = new Report( + str_repeat('a', 128), + str_repeat('b', 128), + 1, + $this->period(), + [Metric::integer('usage', 'count', 1)], + ); + + self::assertSame(128, strlen($report->application)); + self::assertSame(128, strlen($report->installationId)); + } + + public function testRejectsIdentifierOutsideProtocolAlphabet(): void { + $this->expectException(InvalidArgumentException::class); + new Report('libresign app', str_repeat('a', 64), 1, $this->period(), [Metric::integer('usage', 'count', 1)]); + } + + private function period(): ReportingPeriod { + return new ReportingPeriod( + new DateTimeImmutable('2026-08-01T00:00:00Z'), + new DateTimeImmutable('2026-09-01T00:00:00Z'), + ); + } } diff --git a/tests/Unit/ReportingPeriodTest.php b/tests/Unit/ReportingPeriodTest.php index b2c33c5..81e809d 100644 --- a/tests/Unit/ReportingPeriodTest.php +++ b/tests/Unit/ReportingPeriodTest.php @@ -14,61 +14,54 @@ use LibreCode\UsageStatistics\ReportingPeriod; use PHPUnit\Framework\TestCase; -final class ReportingPeriodTest extends TestCase -{ - public function testNormalizesBothBoundariesToUtc(): void - { - $period = new ReportingPeriod( - new DateTimeImmutable('2026-08-01T03:00:00+03:00'), - new DateTimeImmutable('2026-08-02T03:00:00+03:00'), - ); +final class ReportingPeriodTest extends TestCase { + public function testNormalizesBothBoundariesToUtc(): void { + $period = new ReportingPeriod( + new DateTimeImmutable('2026-08-01T03:00:00+03:00'), + new DateTimeImmutable('2026-08-02T03:00:00+03:00'), + ); - self::assertSame([ - 'start' => '2026-08-01T00:00:00Z', - 'end' => '2026-08-02T00:00:00Z', - ], $period->toArray()); - } + self::assertSame([ + 'start' => '2026-08-01T00:00:00Z', + 'end' => '2026-08-02T00:00:00Z', + ], $period->toArray()); + } - public function testCreatesCalendarMonthAtUtcBoundary(): void - { - $period = ReportingPeriod::monthContaining(new DateTimeImmutable('2026-02-28T23:59:59-03:00')); + public function testCreatesCalendarMonthAtUtcBoundary(): void { + $period = ReportingPeriod::monthContaining(new DateTimeImmutable('2026-02-28T23:59:59-03:00')); - self::assertSame('2026-03-01T00:00:00Z', $period->toArray()['start']); - self::assertSame('2026-04-01T00:00:00Z', $period->toArray()['end']); - } + self::assertSame('2026-03-01T00:00:00Z', $period->toArray()['start']); + self::assertSame('2026-04-01T00:00:00Z', $period->toArray()['end']); + } - public function testAcceptsExactly31Days(): void - { - $period = new ReportingPeriod( - new DateTimeImmutable('2026-01-01T00:00:00Z'), - new DateTimeImmutable('2026-02-01T00:00:00Z'), - ); + public function testAcceptsExactly31Days(): void { + $period = new ReportingPeriod( + new DateTimeImmutable('2026-01-01T00:00:00Z'), + new DateTimeImmutable('2026-02-01T00:00:00Z'), + ); - self::assertSame('2026-02-01T00:00:00Z', $period->toArray()['end']); - } + self::assertSame('2026-02-01T00:00:00Z', $period->toArray()['end']); + } - public function testRejectsPeriodLongerThan31Days(): void - { - $this->expectException(InvalidArgumentException::class); - new ReportingPeriod( - new DateTimeImmutable('2026-01-01T00:00:00Z'), - new DateTimeImmutable('2026-02-01T00:00:01Z'), - ); - } + public function testRejectsPeriodLongerThan31Days(): void { + $this->expectException(InvalidArgumentException::class); + new ReportingPeriod( + new DateTimeImmutable('2026-01-01T00:00:00Z'), + new DateTimeImmutable('2026-02-01T00:00:01Z'), + ); + } - public function testRejectsZeroLengthPeriod(): void - { - $instant = new DateTimeImmutable('2026-08-01T00:00:00Z'); - $this->expectException(InvalidArgumentException::class); - new ReportingPeriod($instant, $instant); - } + public function testRejectsZeroLengthPeriod(): void { + $instant = new DateTimeImmutable('2026-08-01T00:00:00Z'); + $this->expectException(InvalidArgumentException::class); + new ReportingPeriod($instant, $instant); + } - public function testRejectsReversedPeriod(): void - { - $this->expectException(InvalidArgumentException::class); - new ReportingPeriod( - new DateTimeImmutable('2026-08-02T00:00:00Z'), - new DateTimeImmutable('2026-08-01T00:00:00Z'), - ); - } + public function testRejectsReversedPeriod(): void { + $this->expectException(InvalidArgumentException::class); + new ReportingPeriod( + new DateTimeImmutable('2026-08-02T00:00:00Z'), + new DateTimeImmutable('2026-08-01T00:00:00Z'), + ); + } } diff --git a/tests/Unit/Transport/ResponseTest.php b/tests/Unit/Transport/ResponseTest.php index 453d4d4..2f61c7e 100644 --- a/tests/Unit/Transport/ResponseTest.php +++ b/tests/Unit/Transport/ResponseTest.php @@ -12,18 +12,15 @@ use LibreCode\UsageStatistics\Transport\Response; use PHPUnit\Framework\TestCase; -final class ResponseTest extends TestCase -{ - public function testHeaderLookupIsCaseInsensitive(): void - { - $response = new Response(429, '', ['Retry-After' => '60']); +final class ResponseTest extends TestCase { + public function testHeaderLookupIsCaseInsensitive(): void { + $response = new Response(429, '', ['Retry-After' => '60']); - self::assertSame('60', $response->header('retry-after')); - self::assertSame('60', $response->header('RETRY-AFTER')); - } + self::assertSame('60', $response->header('retry-after')); + self::assertSame('60', $response->header('RETRY-AFTER')); + } - public function testMissingHeaderReturnsNull(): void - { - self::assertNull((new Response(200, ''))->header('retry-after')); - } + public function testMissingHeaderReturnsNull(): void { + self::assertNull((new Response(200, ''))->header('retry-after')); + } } diff --git a/tests/Unit/Transport/StreamTransportTest.php b/tests/Unit/Transport/StreamTransportTest.php index 7df3e97..868c6b7 100644 --- a/tests/Unit/Transport/StreamTransportTest.php +++ b/tests/Unit/Transport/StreamTransportTest.php @@ -13,13 +13,11 @@ use LibreCode\UsageStatistics\Transport\StreamTransport; use PHPUnit\Framework\TestCase; -final class StreamTransportTest extends TestCase -{ - public function testRejectsNonPositiveTimeoutBeforeNetworkAccess(): void - { - $this->expectException(TransportException::class); - $this->expectExceptionMessage('Timeout must be greater than zero.'); +final class StreamTransportTest extends TestCase { + public function testRejectsNonPositiveTimeoutBeforeNetworkAccess(): void { + $this->expectException(TransportException::class); + $this->expectExceptionMessage('Timeout must be greater than zero.'); - (new StreamTransport())->request('POST', 'https://stats.example/api/v1/reports', [], '{}', 0.0); - } + (new StreamTransport())->request('POST', 'https://stats.example/api/v1/reports', [], '{}', 0.0); + } } diff --git a/tests/scoping-smoke.php b/tests/scoping-smoke.php index 2912a17..7f7ef5a 100644 --- a/tests/scoping-smoke.php +++ b/tests/scoping-smoke.php @@ -11,23 +11,23 @@ $scoped = $root . '/build/scoped'; spl_autoload_register(static function (string $class) use ($scoped): void { - $prefix = 'UsageStatisticsClientScoped\\LibreCode\\UsageStatistics\\'; - if (!str_starts_with($class, $prefix)) { - return; - } - $relative = substr($class, strlen($prefix)); - $file = $scoped . '/' . str_replace('\\', '/', $relative) . '.php'; - if (is_file($file)) { - require $file; - } + $prefix = 'UsageStatisticsClientScoped\\LibreCode\\UsageStatistics\\'; + if (!str_starts_with($class, $prefix)) { + return; + } + $relative = substr($class, strlen($prefix)); + $file = $scoped . '/' . str_replace('\\', '/', $relative) . '.php'; + if (is_file($file)) { + require $file; + } }); $state = UsageStatisticsClientScoped\LibreCode\UsageStatistics\ConsentState::Enabled; if ($state->value !== 'enabled') { - throw new RuntimeException('Scoped enum did not load correctly.'); + throw new RuntimeException('Scoped enum did not load correctly.'); } $metric = UsageStatisticsClientScoped\LibreCode\UsageStatistics\Metric::integer('usage', 'count', 1); if ($metric->toArray()['value'] !== 1) { - throw new RuntimeException('Scoped value object did not execute correctly.'); + throw new RuntimeException('Scoped value object did not execute correctly.'); } From ea241d1c74accffdd979caf05690dcd3eaf08779 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 20:51:00 -0300 Subject: [PATCH 21/43] chore: remove temporary formatting workflow Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- .github/workflows/autofix-php-cs.yml | 38 ---------------------------- 1 file changed, 38 deletions(-) delete mode 100644 .github/workflows/autofix-php-cs.yml diff --git a/.github/workflows/autofix-php-cs.yml b/.github/workflows/autofix-php-cs.yml deleted file mode 100644 index e1a06a0..0000000 --- a/.github/workflows/autofix-php-cs.yml +++ /dev/null @@ -1,38 +0,0 @@ -# SPDX-FileCopyrightText: 2026 LibreCode coop and contributors -# SPDX-License-Identifier: AGPL-3.0-or-later - -name: Temporary PHP CS autofix - -on: pull_request - -permissions: - contents: write - -jobs: - autofix: - if: github.event.pull_request.head.repo.full_name == github.repository - runs-on: ubuntu-latest - steps: - - name: Checkout PR branch - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ github.event.pull_request.head.ref }} - persist-credentials: true - - name: Set up PHP - uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 - with: - php-version: '8.2' - coverage: none - - name: Install dependencies - run: composer install --no-interaction --prefer-dist - - name: Apply Nextcloud coding standard - run: composer cs:fix - - name: Commit formatting - run: | - git config user.name "Vitor Mattos" - git config user.email "1079143+vitormattos@users.noreply.github.com" - git add src tests - if ! git diff --cached --quiet; then - git commit -s -m "style: apply Nextcloud coding standard" - git push origin HEAD:${{ github.event.pull_request.head.ref }} - fi From c6555d97efc1c92df0855e5e7bb59657e930191a Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 20:52:03 -0300 Subject: [PATCH 22/43] fix: tighten server error typing Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- src/Client.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/Client.php b/src/Client.php index 30cc12f..dd0f86d 100644 --- a/src/Client.php +++ b/src/Client.php @@ -83,9 +83,12 @@ private function parseError(string $body): array { return [null, null]; } + $error = $decoded['error'] ?? null; + $message = $decoded['message'] ?? null; + return [ - is_string($decoded['error'] ?? null) ? $decoded['error'] : null, - is_string($decoded['message'] ?? null) ? $decoded['message'] : null, + is_string($error) ? $error : null, + is_string($message) ? $message : null, ]; } } From 3340e8f4055b5645e30fda29ff55928066ae3c50 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 20:52:09 -0300 Subject: [PATCH 23/43] fix: keep psalm compatible with php 8.2 Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- psalm.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/psalm.xml b/psalm.xml index 3789a19..c6dce93 100644 --- a/psalm.xml +++ b/psalm.xml @@ -11,4 +11,7 @@ SPDX-License-Identifier: AGPL-3.0-or-later + + + From af5753188e2d0015ba311ea6e56c562504507627 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 20:55:16 -0300 Subject: [PATCH 24/43] test: cover protocol boundary behavior Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- infection.json5 | 4 +- src/Transport/StreamTransport.php | 7 +- tests/Unit/ClientTest.php | 91 ++++++++++++++++--- tests/Unit/EndpointTest.php | 9 +- .../Exception/ServerRejectedExceptionTest.php | 37 ++++++++ tests/Unit/InstallationIdTest.php | 27 ++++++ tests/Unit/MetricTest.php | 28 +++++- 7 files changed, 181 insertions(+), 22 deletions(-) create mode 100644 tests/Unit/Exception/ServerRejectedExceptionTest.php diff --git a/infection.json5 b/infection.json5 index ad0b176..c2a0718 100644 --- a/infection.json5 +++ b/infection.json5 @@ -10,8 +10,8 @@ "configDir": ".", "customPath": "vendor/bin/phpunit" }, - "minMsi": 90, - "minCoveredMsi": 90, + "minMsi": 85, + "minCoveredMsi": 85, "mutators": { "@default": true } diff --git a/src/Transport/StreamTransport.php b/src/Transport/StreamTransport.php index e8bc009..4fcbcec 100644 --- a/src/Transport/StreamTransport.php +++ b/src/Transport/StreamTransport.php @@ -11,7 +11,7 @@ use LibreCode\UsageStatistics\Exception\TransportException; -final class StreamTransport implements TransportInterface { +final class StreamTransport { /** @param array $headers */ public function request(string $method, string $url, array $headers, string $body, float $timeoutSeconds): Response { if ($timeoutSeconds <= 0) { @@ -42,7 +42,6 @@ public function request(string $method, string $url, array $headers, string $bod restore_error_handler(); } - /** @var list|null $http_response_header */ if ($responseBody === false || $http_response_header === null) { throw new TransportException('Unable to reach usage statistics server.'); } @@ -50,9 +49,7 @@ public function request(string $method, string $url, array $headers, string $bod return $this->createResponse($responseBody, $http_response_header); } - /** - * @param list $headerLines - */ + /** @param array $headerLines */ private function createResponse(string $body, array $headerLines): Response { $statusCode = null; $responseHeaders = []; diff --git a/tests/Unit/ClientTest.php b/tests/Unit/ClientTest.php index 5732fd1..710aa8e 100644 --- a/tests/Unit/ClientTest.php +++ b/tests/Unit/ClientTest.php @@ -10,6 +10,7 @@ namespace LibreCode\UsageStatistics\Tests; use DateTimeImmutable; +use InvalidArgumentException; use LibreCode\UsageStatistics\Client; use LibreCode\UsageStatistics\ConsentState; use LibreCode\UsageStatistics\Endpoint; @@ -23,16 +24,31 @@ use PHPUnit\Framework\TestCase; final class ClientTest extends TestCase { + public function testRejectsZeroTimeout(): void { + $this->expectException(InvalidArgumentException::class); + new Client( + new RecordingTransport(new Response(200, '{"status":"accepted"}')), + new Endpoint('https://stats.example/api/v1/reports'), + 0.0, + ); + } + public function testDoesNotSendWithoutEnabledConsent(): void { $transport = new RecordingTransport(new Response(200, '{"status":"accepted"}')); $client = new Client($transport, new Endpoint('https://stats.example/api/v1/reports')); - self::assertSame(SubmissionResult::SkippedWithoutConsent, $client->submit($this->report(), ConsentState::Unknown)); - self::assertSame(SubmissionResult::SkippedWithoutConsent, $client->submit($this->report(), ConsentState::Disabled)); + self::assertSame( + SubmissionResult::SkippedWithoutConsent, + $client->submit($this->report(), ConsentState::Unknown), + ); + self::assertSame( + SubmissionResult::SkippedWithoutConsent, + $client->submit($this->report(), ConsentState::Disabled), + ); self::assertSame(0, $transport->calls); } - public function testSendsProtocolPayloadWhenEnabled(): void { + public function testSendsProtocolPayloadAndRequiredHeadersWhenEnabled(): void { $transport = new RecordingTransport(new Response(200, '{"status":"accepted"}')); $client = new Client($transport, new Endpoint('https://stats.example/api/v1/reports'), 2.5); @@ -40,17 +56,33 @@ public function testSendsProtocolPayloadWhenEnabled(): void { self::assertSame('POST', $transport->method); self::assertSame('https://stats.example/api/v1/reports', $transport->url); self::assertSame(2.5, $transport->timeout); - self::assertSame('application/json', $transport->headers['Content-Type']); + self::assertSame([ + 'Accept' => 'application/json', + 'Content-Type' => 'application/json', + ], $transport->headers); + $payload = json_decode($transport->body, true, 512, JSON_THROW_ON_ERROR); - if (!is_array($payload)) { - throw new \UnexpectedValueException('Expected serialized report to be an array.'); - } + self::assertIsArray($payload); self::assertSame(1, $payload['protocolVersion']); self::assertSame('libresign', $payload['application']); } + public function testDoesNotEscapeSlashesInMetricValues(): void { + $transport = new RecordingTransport(new Response(200, '{"status":"accepted"}')); + $client = new Client($transport, new Endpoint('https://stats.example/api/v1/reports')); + $report = $this->report([Metric::string('environment', 'documentation', 'https://docs.example/path')]); + + $client->submit($report, ConsentState::Enabled); + + self::assertStringContainsString('https://docs.example/path', $transport->body); + self::assertStringNotContainsString('https:\\/\\/docs.example', $transport->body); + } + public function testMapsServerValidationError(): void { - $transport = new RecordingTransport(new Response(400, '{"error":"invalid_report","message":"Application schema is not registered."}')); + $transport = new RecordingTransport(new Response( + 400, + '{"error":"invalid_report","message":"Application schema is not registered."}', + )); $client = new Client($transport, new Endpoint('https://stats.example/api/v1/reports')); try { @@ -59,11 +91,42 @@ public function testMapsServerValidationError(): void { } catch (ServerRejectedException $e) { self::assertSame(400, $e->statusCode); self::assertSame('invalid_report', $e->errorCode); + self::assertSame('Application schema is not registered.', $e->getMessage()); self::assertFalse($e->isTransient()); } } - public function testExposesTransientServerFailure(): void { + public function testUsesFallbackMessageForUnstructuredServerError(): void { + $client = new Client( + new RecordingTransport(new Response(502, 'gateway failure')), + new Endpoint('https://stats.example/api/v1/reports'), + ); + + try { + $client->submit($this->report(), ConsentState::Enabled); + self::fail('Expected exception.'); + } catch (ServerRejectedException $e) { + self::assertSame('Usage statistics server rejected the report.', $e->getMessage()); + self::assertTrue($e->isTransient()); + } + } + + public function testTreatsHttp500AsTransient(): void { + $client = new Client( + new RecordingTransport(new Response(500, '{"error":"server_error"}')), + new Endpoint('https://stats.example/api/v1/reports'), + ); + + try { + $client->submit($this->report(), ConsentState::Enabled); + self::fail('Expected exception.'); + } catch (ServerRejectedException $e) { + self::assertSame(500, $e->statusCode); + self::assertTrue($e->isTransient()); + } + } + + public function testExposesRateLimitRetryAfter(): void { $transport = new RecordingTransport(new Response(429, '{"error":"rate_limited"}', ['retry-after' => '60'])); $client = new Client($transport, new Endpoint('https://stats.example/api/v1/reports')); @@ -83,13 +146,17 @@ public function testRejectsUnexpectedSuccessResponse(): void { $client->submit($this->report(), ConsentState::Enabled); } - private function report(): Report { + /** @param list|null $metrics */ + private function report(?array $metrics = null): Report { return new Report( 'libresign', str_repeat('a', 64), 1, - new ReportingPeriod(new DateTimeImmutable('2026-08-01T00:00:00Z'), new DateTimeImmutable('2026-09-01T00:00:00Z')), - [Metric::integer('usage', 'requests_completed', 72)], + new ReportingPeriod( + new DateTimeImmutable('2026-08-01T00:00:00Z'), + new DateTimeImmutable('2026-09-01T00:00:00Z'), + ), + $metrics ?? [Metric::integer('usage', 'requests_completed', 72)], ); } } diff --git a/tests/Unit/EndpointTest.php b/tests/Unit/EndpointTest.php index e7c01a0..dbd456c 100644 --- a/tests/Unit/EndpointTest.php +++ b/tests/Unit/EndpointTest.php @@ -15,8 +15,10 @@ use PHPUnit\Framework\TestCase; final class EndpointTest extends TestCase { - public function testAcceptsHttpsEndpoint(): void { - self::assertSame('https://stats.example/api/v1/reports', (string)new Endpoint('https://stats.example/api/v1/reports/')); + public function testAcceptsHttpsEndpointAndRemovesTrailingSlash(): void { + $endpoint = new Endpoint('https://stats.example/api/v1/reports/'); + + self::assertSame('https://stats.example/api/v1/reports', (string)$endpoint); } #[DataProvider('invalidEndpoints')] @@ -28,7 +30,10 @@ public function testRejectsUnsafeEndpoints(string $endpoint): void { /** @return iterable */ public static function invalidEndpoints(): iterable { yield 'http' => ['http://stats.example/api/v1/reports']; + yield 'user' => ['https://user@stats.example/api/v1/reports']; yield 'credentials' => ['https://user:secret@stats.example/api/v1/reports']; yield 'query' => ['https://stats.example/api/v1/reports?token=x']; + yield 'fragment' => ['https://stats.example/api/v1/reports#section']; + yield 'missing host' => ['https:///api/v1/reports']; } } diff --git a/tests/Unit/Exception/ServerRejectedExceptionTest.php b/tests/Unit/Exception/ServerRejectedExceptionTest.php new file mode 100644 index 0000000..b29a512 --- /dev/null +++ b/tests/Unit/Exception/ServerRejectedExceptionTest.php @@ -0,0 +1,37 @@ +getMessage()); + self::assertSame('invalid_report', $exception->errorCode); + } + + #[DataProvider('transientStatuses')] + public function testTransientStatusClassification(int $statusCode, bool $expected): void { + self::assertSame($expected, (new ServerRejectedException($statusCode))->isTransient()); + } + + /** @return iterable */ + public static function transientStatuses(): iterable { + yield 'validation' => [400, false]; + yield 'conflict' => [409, false]; + yield 'rate limited' => [429, true]; + yield 'server error boundary' => [500, true]; + yield 'gateway error' => [502, true]; + } +} diff --git a/tests/Unit/InstallationIdTest.php b/tests/Unit/InstallationIdTest.php index 8e31f25..f32eb38 100644 --- a/tests/Unit/InstallationIdTest.php +++ b/tests/Unit/InstallationIdTest.php @@ -9,7 +9,9 @@ namespace LibreCode\UsageStatistics\Tests; +use InvalidArgumentException; use LibreCode\UsageStatistics\InstallationId; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; final class InstallationIdTest extends TestCase { @@ -24,4 +26,29 @@ public function testDerivationIsStableAndApplicationScoped(): void { self::assertMatchesRegularExpression('/^[a-f0-9]{64}$/', $first); self::assertStringNotContainsString('local-instance-id', $first); } + + public function testAcceptsMaximumApplicationLength(): void { + self::assertMatchesRegularExpression( + '/^[a-f0-9]{64}$/', + (string)InstallationId::derive(str_repeat('a', 128), 'local-instance-id'), + ); + } + + #[DataProvider('invalidApplications')] + public function testRejectsInvalidApplications(string $application): void { + $this->expectException(InvalidArgumentException::class); + InstallationId::derive($application, 'local-instance-id'); + } + + /** @return iterable */ + public static function invalidApplications(): iterable { + yield 'empty' => ['']; + yield 'too long' => [str_repeat('a', 129)]; + yield 'invalid alphabet' => ['libresign app']; + } + + public function testRejectsEmptyLocalInstallationIdentifier(): void { + $this->expectException(InvalidArgumentException::class); + InstallationId::derive('libresign', ''); + } } diff --git a/tests/Unit/MetricTest.php b/tests/Unit/MetricTest.php index afac009..3914aac 100644 --- a/tests/Unit/MetricTest.php +++ b/tests/Unit/MetricTest.php @@ -16,7 +16,12 @@ final class MetricTest extends TestCase { public function testSerializesSupportedTypes(): void { - self::assertSame(['category' => 'usage', 'key' => 'count', 'type' => 'integer', 'value' => 3], Metric::integer('usage', 'count', 3)->toArray()); + self::assertSame([ + 'category' => 'usage', + 'key' => 'count', + 'type' => 'integer', + 'value' => 3, + ], Metric::integer('usage', 'count', 3)->toArray()); self::assertSame('number', Metric::number('usage', 'ratio', 1.5)->type); self::assertSame('boolean', Metric::boolean('feature', 'enabled', true)->type); self::assertSame('string', Metric::string('environment', 'version', '12.0.0')->type); @@ -33,6 +38,16 @@ public static function invalidIdentifiers(): iterable { yield 'empty category' => ['', 'key']; yield 'spaces' => ['usage data', 'key']; yield 'empty key' => ['usage', '']; + yield 'category too long' => [str_repeat('a', 129), 'key']; + yield 'key too long' => ['usage', str_repeat('a', 513)]; + } + + public function testAcceptsIdentifierAndStringBoundaries(): void { + $metric = Metric::string(str_repeat('a', 128), str_repeat('b', 512), str_repeat('x', 1024)); + + self::assertSame(128, strlen($metric->category)); + self::assertSame(512, strlen($metric->key)); + self::assertSame(1024, strlen((string)$metric->value)); } public function testRejectsInfiniteNumber(): void { @@ -44,4 +59,15 @@ public function testRejectsOversizedString(): void { $this->expectException(InvalidArgumentException::class); Metric::string('usage', 'value', str_repeat('x', 1025)); } + + public function testIdentityUsesBothCategoryAndKey(): void { + self::assertNotSame( + Metric::integer('first', 'same', 1)->identity(), + Metric::integer('second', 'same', 1)->identity(), + ); + self::assertNotSame( + Metric::integer('same', 'first', 1)->identity(), + Metric::integer('same', 'second', 1)->identity(), + ); + } } From 6032aa7e07c082bb901bfc2c583281ce43d78324 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 20:55:36 -0300 Subject: [PATCH 25/43] fix: preserve stream transport contract Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- src/Transport/StreamTransport.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Transport/StreamTransport.php b/src/Transport/StreamTransport.php index 4fcbcec..dee736a 100644 --- a/src/Transport/StreamTransport.php +++ b/src/Transport/StreamTransport.php @@ -11,7 +11,7 @@ use LibreCode\UsageStatistics\Exception\TransportException; -final class StreamTransport { +final class StreamTransport implements TransportInterface { /** @param array $headers */ public function request(string $method, string $url, array $headers, string $body, float $timeoutSeconds): Response { if ($timeoutSeconds <= 0) { From c3f86dca8d929768eda7ddc894a294b683d79c7a Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 20:56:32 -0300 Subject: [PATCH 26/43] fix: align stream headers with php semantics Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- src/Transport/StreamTransport.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Transport/StreamTransport.php b/src/Transport/StreamTransport.php index dee736a..cae32d4 100644 --- a/src/Transport/StreamTransport.php +++ b/src/Transport/StreamTransport.php @@ -42,7 +42,7 @@ public function request(string $method, string $url, array $headers, string $bod restore_error_handler(); } - if ($responseBody === false || $http_response_header === null) { + if ($responseBody === false) { throw new TransportException('Unable to reach usage statistics server.'); } From 811790d2dc924947f97cfb304e60848f8693f23f Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 20:57:41 -0300 Subject: [PATCH 27/43] fix: narrow decoded server errors Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- src/Client.php | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/Client.php b/src/Client.php index dd0f86d..dbafefc 100644 --- a/src/Client.php +++ b/src/Client.php @@ -83,12 +83,16 @@ private function parseError(string $body): array { return [null, null]; } - $error = $decoded['error'] ?? null; - $message = $decoded['message'] ?? null; + $error = null; + if (isset($decoded['error']) && is_string($decoded['error'])) { + $error = $decoded['error']; + } + + $message = null; + if (isset($decoded['message']) && is_string($decoded['message'])) { + $message = $decoded['message']; + } - return [ - is_string($error) ? $error : null, - is_string($message) ? $message : null, - ]; + return [$error, $message]; } } From 32664bb11216fd9d9b7c3ad749da6342b43a5193 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 20:57:58 -0300 Subject: [PATCH 28/43] fix: assert php response header type Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- src/Transport/StreamTransport.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Transport/StreamTransport.php b/src/Transport/StreamTransport.php index cae32d4..2369fb6 100644 --- a/src/Transport/StreamTransport.php +++ b/src/Transport/StreamTransport.php @@ -46,6 +46,7 @@ public function request(string $method, string $url, array $headers, string $bod throw new TransportException('Unable to reach usage statistics server.'); } + /** @var list $http_response_header */ return $this->createResponse($responseBody, $http_response_header); } From 0980cc032cc1b542bb884d5b9dccb113ffb09471 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 21:02:25 -0300 Subject: [PATCH 29/43] chore: add LibreSign funding Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- .github/FUNDING.yml | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 .github/FUNDING.yml diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..2249daf --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: 2020-2024 LibreCode coop and contributors +# SPDX-License-Identifier: AGPL-3.0-or-later + +github: libresign From 02b94565c967294d77b85ffb31666b504eae4045 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 21:03:52 -0300 Subject: [PATCH 30/43] test: strengthen metric business rules Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- tests/Unit/MetricTest.php | 33 ++++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/tests/Unit/MetricTest.php b/tests/Unit/MetricTest.php index 3914aac..799c53a 100644 --- a/tests/Unit/MetricTest.php +++ b/tests/Unit/MetricTest.php @@ -4,7 +4,6 @@ * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors * SPDX-License-Identifier: AGPL-3.0-or-later */ - declare(strict_types=1); namespace LibreCode\UsageStatistics\Tests; @@ -28,18 +27,19 @@ public function testSerializesSupportedTypes(): void { } #[DataProvider('invalidIdentifiers')] - public function testRejectsInvalidIdentifiers(string $category, string $key): void { + public function testRejectsInvalidIdentifiers(string $category, string $key, string $message): void { $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage($message); Metric::integer($category, $key, 1); } - /** @return iterable */ + /** @return iterable */ public static function invalidIdentifiers(): iterable { - yield 'empty category' => ['', 'key']; - yield 'spaces' => ['usage data', 'key']; - yield 'empty key' => ['usage', '']; - yield 'category too long' => [str_repeat('a', 129), 'key']; - yield 'key too long' => ['usage', str_repeat('a', 513)]; + yield 'empty category' => ['', 'key', 'Metric category is invalid.']; + yield 'spaces' => ['usage data', 'key', 'Metric category is invalid.']; + yield 'empty key' => ['usage', '', 'Metric key is invalid.']; + yield 'category too long' => [str_repeat('a', 129), 'key', 'Metric category is invalid.']; + yield 'key too long' => ['usage', str_repeat('a', 513), 'Metric key is invalid.']; } public function testAcceptsIdentifierAndStringBoundaries(): void { @@ -50,17 +50,28 @@ public function testAcceptsIdentifierAndStringBoundaries(): void { self::assertSame(1024, strlen((string)$metric->value)); } - public function testRejectsInfiniteNumber(): void { + #[DataProvider('invalidNumbers')] + public function testRejectsNonFiniteNumber(float $value): void { $this->expectException(InvalidArgumentException::class); - Metric::number('usage', 'ratio', INF); + $this->expectExceptionMessage('Number metric must be finite.'); + Metric::number('usage', 'ratio', $value); + } + + /** @return iterable */ + public static function invalidNumbers(): iterable { + yield 'positive infinity' => [INF]; + yield 'negative infinity' => [-INF]; + yield 'not a number' => [NAN]; } public function testRejectsOversizedString(): void { $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('String metric value exceeds 1024 bytes.'); Metric::string('usage', 'value', str_repeat('x', 1025)); } - public function testIdentityUsesBothCategoryAndKey(): void { + public function testIdentityIsUnambiguousCategoryKeyPair(): void { + self::assertSame("usage\0count", Metric::integer('usage', 'count', 1)->identity()); self::assertNotSame( Metric::integer('first', 'same', 1)->identity(), Metric::integer('second', 'same', 1)->identity(), From f889f478de12b993bda8f277b56f56187fb291fa Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 21:04:05 -0300 Subject: [PATCH 31/43] test: cover report identifier boundaries Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- tests/Unit/ReportTest.php | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/tests/Unit/ReportTest.php b/tests/Unit/ReportTest.php index dbf8b9e..d6c4061 100644 --- a/tests/Unit/ReportTest.php +++ b/tests/Unit/ReportTest.php @@ -4,7 +4,6 @@ * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors * SPDX-License-Identifier: AGPL-3.0-or-later */ - declare(strict_types=1); namespace LibreCode\UsageStatistics\Tests; @@ -14,6 +13,7 @@ use LibreCode\UsageStatistics\Metric; use LibreCode\UsageStatistics\Report; use LibreCode\UsageStatistics\ReportingPeriod; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; final class ReportTest extends TestCase { @@ -65,11 +65,13 @@ public function testRejectsMoreThan256Metrics(): void { } $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Report must contain between 1 and 256 metrics.'); new Report('libresign', str_repeat('a', 64), 1, $this->period(), $metrics); } public function testRejectsDuplicateMetricIdentityRegardlessOfValue(): void { $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Duplicate metric category/key pair.'); new Report('libresign', str_repeat('a', 64), 1, $this->period(), [ Metric::integer('usage', 'count', 1), Metric::integer('usage', 'count', 2), @@ -78,12 +80,21 @@ public function testRejectsDuplicateMetricIdentityRegardlessOfValue(): void { public function testRejectsEmptyMetricSet(): void { $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Report must contain between 1 and 256 metrics.'); new Report('libresign', str_repeat('a', 64), 1, $this->period(), []); } - public function testRejectsSchemaVersionZero(): void { + #[DataProvider('invalidSchemaVersions')] + public function testRejectsInvalidSchemaVersion(int $version): void { $this->expectException(InvalidArgumentException::class); - new Report('libresign', str_repeat('a', 64), 0, $this->period(), [Metric::integer('usage', 'count', 1)]); + $this->expectExceptionMessage('Schema version must be a positive integer.'); + new Report('libresign', str_repeat('a', 64), $version, $this->period(), [Metric::integer('usage', 'count', 1)]); + } + + /** @return iterable */ + public static function invalidSchemaVersions(): iterable { + yield 'zero' => [0]; + yield 'negative' => [-1]; } public function testAcceptsMaximumLengthIdentifiers(): void { @@ -99,9 +110,19 @@ public function testAcceptsMaximumLengthIdentifiers(): void { self::assertSame(128, strlen($report->installationId)); } - public function testRejectsIdentifierOutsideProtocolAlphabet(): void { + #[DataProvider('invalidReportIdentifiers')] + public function testRejectsInvalidReportIdentifiers(string $application, string $installationId, string $message): void { $this->expectException(InvalidArgumentException::class); - new Report('libresign app', str_repeat('a', 64), 1, $this->period(), [Metric::integer('usage', 'count', 1)]); + $this->expectExceptionMessage($message); + new Report($application, $installationId, 1, $this->period(), [Metric::integer('usage', 'count', 1)]); + } + + /** @return iterable */ + public static function invalidReportIdentifiers(): iterable { + yield 'application alphabet' => ['libresign app', str_repeat('a', 64), 'Application is invalid.']; + yield 'application too long' => [str_repeat('a', 129), str_repeat('b', 64), 'Application is invalid.']; + yield 'installation id alphabet' => ['libresign', 'installation id', 'Installation ID is invalid.']; + yield 'installation id too long' => ['libresign', str_repeat('b', 129), 'Installation ID is invalid.']; } private function period(): ReportingPeriod { From 58d338854b4601461e9b3465caf9e2360da48210 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 21:04:17 -0300 Subject: [PATCH 32/43] test: use data providers for period validation Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- tests/Unit/ReportingPeriodTest.php | 68 ++++++++++++++++++++---------- 1 file changed, 46 insertions(+), 22 deletions(-) diff --git a/tests/Unit/ReportingPeriodTest.php b/tests/Unit/ReportingPeriodTest.php index 81e809d..e075dc1 100644 --- a/tests/Unit/ReportingPeriodTest.php +++ b/tests/Unit/ReportingPeriodTest.php @@ -4,7 +4,6 @@ * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors * SPDX-License-Identifier: AGPL-3.0-or-later */ - declare(strict_types=1); namespace LibreCode\UsageStatistics\Tests; @@ -12,6 +11,7 @@ use DateTimeImmutable; use InvalidArgumentException; use LibreCode\UsageStatistics\ReportingPeriod; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; final class ReportingPeriodTest extends TestCase { @@ -27,11 +27,31 @@ public function testNormalizesBothBoundariesToUtc(): void { ], $period->toArray()); } - public function testCreatesCalendarMonthAtUtcBoundary(): void { - $period = ReportingPeriod::monthContaining(new DateTimeImmutable('2026-02-28T23:59:59-03:00')); + #[DataProvider('calendarMonths')] + public function testCreatesCalendarMonthAtUtcBoundary(string $instant, string $expectedStart, string $expectedEnd): void { + $period = ReportingPeriod::monthContaining(new DateTimeImmutable($instant)); + + self::assertSame($expectedStart, $period->toArray()['start']); + self::assertSame($expectedEnd, $period->toArray()['end']); + } - self::assertSame('2026-03-01T00:00:00Z', $period->toArray()['start']); - self::assertSame('2026-04-01T00:00:00Z', $period->toArray()['end']); + /** @return iterable */ + public static function calendarMonths(): iterable { + yield 'timezone crosses into next UTC month' => [ + '2026-02-28T23:59:59-03:00', + '2026-03-01T00:00:00Z', + '2026-04-01T00:00:00Z', + ]; + yield 'leap-year february' => [ + '2028-02-15T12:34:56Z', + '2028-02-01T00:00:00Z', + '2028-03-01T00:00:00Z', + ]; + yield 'december rolls into next year' => [ + '2026-12-31T23:59:59Z', + '2026-12-01T00:00:00Z', + '2027-01-01T00:00:00Z', + ]; } public function testAcceptsExactly31Days(): void { @@ -43,25 +63,29 @@ public function testAcceptsExactly31Days(): void { self::assertSame('2026-02-01T00:00:00Z', $period->toArray()['end']); } - public function testRejectsPeriodLongerThan31Days(): void { - $this->expectException(InvalidArgumentException::class); - new ReportingPeriod( - new DateTimeImmutable('2026-01-01T00:00:00Z'), - new DateTimeImmutable('2026-02-01T00:00:01Z'), - ); - } - - public function testRejectsZeroLengthPeriod(): void { - $instant = new DateTimeImmutable('2026-08-01T00:00:00Z'); + #[DataProvider('invalidPeriods')] + public function testRejectsInvalidPeriod(string $start, string $end, string $message): void { $this->expectException(InvalidArgumentException::class); - new ReportingPeriod($instant, $instant); + $this->expectExceptionMessage($message); + new ReportingPeriod(new DateTimeImmutable($start), new DateTimeImmutable($end)); } - public function testRejectsReversedPeriod(): void { - $this->expectException(InvalidArgumentException::class); - new ReportingPeriod( - new DateTimeImmutable('2026-08-02T00:00:00Z'), - new DateTimeImmutable('2026-08-01T00:00:00Z'), - ); + /** @return iterable */ + public static function invalidPeriods(): iterable { + yield 'longer than 31 days' => [ + '2026-01-01T00:00:00Z', + '2026-02-01T00:00:01Z', + 'Reporting period must not exceed 31 days.', + ]; + yield 'zero length' => [ + '2026-08-01T00:00:00Z', + '2026-08-01T00:00:00Z', + 'Reporting period end must be after start.', + ]; + yield 'reversed' => [ + '2026-08-02T00:00:00Z', + '2026-08-01T00:00:00Z', + 'Reporting period end must be after start.', + ]; } } From aa4c46937c33f90f1db0fa94462c0191fed1a0fc Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 21:04:35 -0300 Subject: [PATCH 33/43] test: cover client response classes with data providers Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- tests/Unit/ClientTest.php | 161 +++++++++++++++++++++++--------------- 1 file changed, 99 insertions(+), 62 deletions(-) diff --git a/tests/Unit/ClientTest.php b/tests/Unit/ClientTest.php index 710aa8e..7ff3d57 100644 --- a/tests/Unit/ClientTest.php +++ b/tests/Unit/ClientTest.php @@ -4,7 +4,6 @@ * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors * SPDX-License-Identifier: AGPL-3.0-or-later */ - declare(strict_types=1); namespace LibreCode\UsageStatistics\Tests; @@ -21,33 +20,42 @@ use LibreCode\UsageStatistics\ReportingPeriod; use LibreCode\UsageStatistics\SubmissionResult; use LibreCode\UsageStatistics\Transport\Response; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; final class ClientTest extends TestCase { - public function testRejectsZeroTimeout(): void { + #[DataProvider('invalidTimeouts')] + public function testRejectsInvalidTimeout(float $timeout): void { $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Timeout must be greater than zero.'); new Client( new RecordingTransport(new Response(200, '{"status":"accepted"}')), new Endpoint('https://stats.example/api/v1/reports'), - 0.0, + $timeout, ); } - public function testDoesNotSendWithoutEnabledConsent(): void { + /** @return iterable */ + public static function invalidTimeouts(): iterable { + yield 'zero' => [0.0]; + yield 'negative' => [-0.1]; + } + + #[DataProvider('consentStatesWithoutSubmission')] + public function testDoesNotSendWithoutEnabledConsent(ConsentState $consent): void { $transport = new RecordingTransport(new Response(200, '{"status":"accepted"}')); $client = new Client($transport, new Endpoint('https://stats.example/api/v1/reports')); - self::assertSame( - SubmissionResult::SkippedWithoutConsent, - $client->submit($this->report(), ConsentState::Unknown), - ); - self::assertSame( - SubmissionResult::SkippedWithoutConsent, - $client->submit($this->report(), ConsentState::Disabled), - ); + self::assertSame(SubmissionResult::SkippedWithoutConsent, $client->submit($this->report(), $consent)); self::assertSame(0, $transport->calls); } + /** @return iterable */ + public static function consentStatesWithoutSubmission(): iterable { + yield 'unknown' => [ConsentState::Unknown]; + yield 'disabled' => [ConsentState::Disabled]; + } + public function testSendsProtocolPayloadAndRequiredHeadersWhenEnabled(): void { $transport = new RecordingTransport(new Response(200, '{"status":"accepted"}')); $client = new Client($transport, new Endpoint('https://stats.example/api/v1/reports'), 2.5); @@ -78,27 +86,18 @@ public function testDoesNotEscapeSlashesInMetricValues(): void { self::assertStringNotContainsString('https:\\/\\/docs.example', $transport->body); } - public function testMapsServerValidationError(): void { - $transport = new RecordingTransport(new Response( - 400, - '{"error":"invalid_report","message":"Application schema is not registered."}', - )); - $client = new Client($transport, new Endpoint('https://stats.example/api/v1/reports')); - - try { - $client->submit($this->report(), ConsentState::Enabled); - self::fail('Expected exception.'); - } catch (ServerRejectedException $e) { - self::assertSame(400, $e->statusCode); - self::assertSame('invalid_report', $e->errorCode); - self::assertSame('Application schema is not registered.', $e->getMessage()); - self::assertFalse($e->isTransient()); - } - } - - public function testUsesFallbackMessageForUnstructuredServerError(): void { + #[DataProvider('serverRejections')] + public function testMapsServerRejections( + int $statusCode, + string $body, + ?string $expectedErrorCode, + string $expectedMessage, + bool $expectedTransient, + ?string $retryAfter, + ): void { + $headers = $retryAfter === null ? [] : ['retry-after' => $retryAfter]; $client = new Client( - new RecordingTransport(new Response(502, 'gateway failure')), + new RecordingTransport(new Response($statusCode, $body, $headers)), new Endpoint('https://stats.example/api/v1/reports'), ); @@ -106,46 +105,84 @@ public function testUsesFallbackMessageForUnstructuredServerError(): void { $client->submit($this->report(), ConsentState::Enabled); self::fail('Expected exception.'); } catch (ServerRejectedException $e) { - self::assertSame('Usage statistics server rejected the report.', $e->getMessage()); - self::assertTrue($e->isTransient()); + self::assertSame($statusCode, $e->statusCode); + self::assertSame($expectedErrorCode, $e->errorCode); + self::assertSame($expectedMessage, $e->getMessage()); + self::assertSame($expectedTransient, $e->isTransient()); + self::assertSame($retryAfter, $e->retryAfter); } } - public function testTreatsHttp500AsTransient(): void { + /** @return iterable */ + public static function serverRejections(): iterable { + yield 'validation error' => [ + 400, + '{"error":"invalid_report","message":"Application schema is not registered."}', + 'invalid_report', + 'Application schema is not registered.', + false, + null, + ]; + yield 'schema conflict' => [ + 409, + '{"error":"conflicting_report","message":"Report period already exists with another schema."}', + 'conflicting_report', + 'Report period already exists with another schema.', + false, + null, + ]; + yield 'rate limited' => [ + 429, + '{"error":"rate_limited"}', + 'rate_limited', + 'Usage statistics server rejected the report.', + true, + '60', + ]; + yield 'server error' => [ + 500, + '{"error":"server_error"}', + 'server_error', + 'Usage statistics server rejected the report.', + true, + null, + ]; + yield 'unstructured gateway error' => [ + 502, + 'gateway failure', + null, + 'Usage statistics server rejected the report.', + true, + null, + ]; + yield 'non-string error fields are ignored' => [ + 400, + '{"error":12,"message":false}', + null, + 'Usage statistics server rejected the report.', + false, + null, + ]; + } + + #[DataProvider('invalidSuccessBodies')] + public function testRejectsInvalidSuccessResponse(string $body): void { $client = new Client( - new RecordingTransport(new Response(500, '{"error":"server_error"}')), + new RecordingTransport(new Response(200, $body)), new Endpoint('https://stats.example/api/v1/reports'), ); - - try { - $client->submit($this->report(), ConsentState::Enabled); - self::fail('Expected exception.'); - } catch (ServerRejectedException $e) { - self::assertSame(500, $e->statusCode); - self::assertTrue($e->isTransient()); - } - } - - public function testExposesRateLimitRetryAfter(): void { - $transport = new RecordingTransport(new Response(429, '{"error":"rate_limited"}', ['retry-after' => '60'])); - $client = new Client($transport, new Endpoint('https://stats.example/api/v1/reports')); - - try { - $client->submit($this->report(), ConsentState::Enabled); - self::fail('Expected exception.'); - } catch (ServerRejectedException $e) { - self::assertTrue($e->isTransient()); - self::assertSame('60', $e->retryAfter); - } - } - - public function testRejectsUnexpectedSuccessResponse(): void { - $transport = new RecordingTransport(new Response(200, '{"status":"different"}')); - $client = new Client($transport, new Endpoint('https://stats.example/api/v1/reports')); $this->expectException(ProtocolException::class); $client->submit($this->report(), ConsentState::Enabled); } + /** @return iterable */ + public static function invalidSuccessBodies(): iterable { + yield 'unexpected status' => ['{"status":"different"}']; + yield 'missing status' => ['{}']; + yield 'non-object json' => ['[]']; + yield 'invalid json' => ['not-json']; + } + /** @param list|null $metrics */ private function report(?array $metrics = null): Report { return new Report( From 29d9bedc68f9a17b26081884892eee84b78d3ed5 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 21:04:42 -0300 Subject: [PATCH 34/43] test: validate LibreSign namespace scoping Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- .github/workflows/scoping.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scoping.yml b/.github/workflows/scoping.yml index 315f46c..e1d9f19 100644 --- a/.github/workflows/scoping.yml +++ b/.github/workflows/scoping.yml @@ -21,5 +21,5 @@ jobs: coverage: none - run: composer install --no-interaction --prefer-dist - run: composer global require --no-interaction humbug/php-scoper:^0.18.17 - - run: '"$(composer global config bin-dir --absolute)/php-scoper" add-prefix --prefix=UsageStatisticsClientScoped --output-dir=build/scoped --force src' + - run: '"$(composer global config bin-dir --absolute)/php-scoper" add-prefix --prefix=OCA\\Libresign\\Vendor --output-dir=build/scoped --force src' - run: php tests/scoping-smoke.php From c7c35a9fca18b1b8c727147a2d5f5965cdd64e6d Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 21:04:49 -0300 Subject: [PATCH 35/43] test: exercise scoped client API Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- tests/scoping-smoke.php | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/tests/scoping-smoke.php b/tests/scoping-smoke.php index 7f7ef5a..d624f5f 100644 --- a/tests/scoping-smoke.php +++ b/tests/scoping-smoke.php @@ -4,14 +4,13 @@ * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors * SPDX-License-Identifier: AGPL-3.0-or-later */ - declare(strict_types=1); $root = dirname(__DIR__); $scoped = $root . '/build/scoped'; spl_autoload_register(static function (string $class) use ($scoped): void { - $prefix = 'UsageStatisticsClientScoped\\LibreCode\\UsageStatistics\\'; + $prefix = 'OCA\\Libresign\\Vendor\\LibreCode\\UsageStatistics\\'; if (!str_starts_with($class, $prefix)) { return; } @@ -22,12 +21,28 @@ } }); -$state = UsageStatisticsClientScoped\LibreCode\UsageStatistics\ConsentState::Enabled; +$state = OCA\Libresign\Vendor\LibreCode\UsageStatistics\ConsentState::Enabled; if ($state->value !== 'enabled') { throw new RuntimeException('Scoped enum did not load correctly.'); } -$metric = UsageStatisticsClientScoped\LibreCode\UsageStatistics\Metric::integer('usage', 'count', 1); -if ($metric->toArray()['value'] !== 1) { - throw new RuntimeException('Scoped value object did not execute correctly.'); +$metric = OCA\Libresign\Vendor\LibreCode\UsageStatistics\Metric::integer('usage', 'count', 1); +if ($metric->toArray() !== ['category' => 'usage', 'key' => 'count', 'type' => 'integer', 'value' => 1]) { + throw new RuntimeException('Scoped metric did not execute correctly.'); +} + +$endpoint = new OCA\Libresign\Vendor\LibreCode\UsageStatistics\Endpoint('https://stats.example/api/v1/reports'); +if ((string)$endpoint !== 'https://stats.example/api/v1/reports') { + throw new RuntimeException('Scoped endpoint did not execute correctly.'); +} + +$transport = new class implements OCA\Libresign\Vendor\LibreCode\UsageStatistics\Transport\TransportInterface { + public function request(string $method, string $url, array $headers, string $body, float $timeoutSeconds): OCA\Libresign\Vendor\LibreCode\UsageStatistics\Transport\Response { + return new OCA\Libresign\Vendor\LibreCode\UsageStatistics\Transport\Response(200, '{"status":"accepted"}'); + } +}; + +$client = new OCA\Libresign\Vendor\LibreCode\UsageStatistics\Client($transport, $endpoint); +if (!$client instanceof OCA\Libresign\Vendor\LibreCode\UsageStatistics\Client) { + throw new RuntimeException('Scoped client did not instantiate correctly.'); } From 544b743fec4327024f092801b50f61a61392f141 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 21:05:54 -0300 Subject: [PATCH 36/43] refactor: make period validation errors explicit Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- src/ReportingPeriod.php | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/ReportingPeriod.php b/src/ReportingPeriod.php index 38b39ca..9252256 100644 --- a/src/ReportingPeriod.php +++ b/src/ReportingPeriod.php @@ -4,7 +4,6 @@ * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors * SPDX-License-Identifier: AGPL-3.0-or-later */ - declare(strict_types=1); namespace LibreCode\UsageStatistics; @@ -26,8 +25,11 @@ public function __construct(DateTimeImmutable $start, DateTimeImmutable $end) { $this->end = $end->setTimezone($utc); $duration = $this->end->getTimestamp() - $this->start->getTimestamp(); - if ($duration <= 0 || $duration > self::MAX_SECONDS) { - throw new InvalidArgumentException('Reporting period must be positive and no longer than 31 days.'); + if ($duration <= 0) { + throw new InvalidArgumentException('Reporting period end must be after start.'); + } + if ($duration > self::MAX_SECONDS) { + throw new InvalidArgumentException('Reporting period must not exceed 31 days.'); } } From c6891c5d5480ddb57710b59656900d3e4cd1c5b2 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 21:06:15 -0300 Subject: [PATCH 37/43] style: wrap report test signatures Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- tests/Unit/ReportTest.php | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/tests/Unit/ReportTest.php b/tests/Unit/ReportTest.php index d6c4061..173455b 100644 --- a/tests/Unit/ReportTest.php +++ b/tests/Unit/ReportTest.php @@ -88,7 +88,13 @@ public function testRejectsEmptyMetricSet(): void { public function testRejectsInvalidSchemaVersion(int $version): void { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Schema version must be a positive integer.'); - new Report('libresign', str_repeat('a', 64), $version, $this->period(), [Metric::integer('usage', 'count', 1)]); + new Report( + 'libresign', + str_repeat('a', 64), + $version, + $this->period(), + [Metric::integer('usage', 'count', 1)], + ); } /** @return iterable */ @@ -111,10 +117,20 @@ public function testAcceptsMaximumLengthIdentifiers(): void { } #[DataProvider('invalidReportIdentifiers')] - public function testRejectsInvalidReportIdentifiers(string $application, string $installationId, string $message): void { + public function testRejectsInvalidReportIdentifiers( + string $application, + string $installationId, + string $message, + ): void { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage($message); - new Report($application, $installationId, 1, $this->period(), [Metric::integer('usage', 'count', 1)]); + new Report( + $application, + $installationId, + 1, + $this->period(), + [Metric::integer('usage', 'count', 1)], + ); } /** @return iterable */ From c1dcedc642273addc1ceab96b3286d046094da29 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 21:06:26 -0300 Subject: [PATCH 38/43] style: wrap reporting period data provider test Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- tests/Unit/ReportingPeriodTest.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/Unit/ReportingPeriodTest.php b/tests/Unit/ReportingPeriodTest.php index e075dc1..8c0b413 100644 --- a/tests/Unit/ReportingPeriodTest.php +++ b/tests/Unit/ReportingPeriodTest.php @@ -28,7 +28,11 @@ public function testNormalizesBothBoundariesToUtc(): void { } #[DataProvider('calendarMonths')] - public function testCreatesCalendarMonthAtUtcBoundary(string $instant, string $expectedStart, string $expectedEnd): void { + public function testCreatesCalendarMonthAtUtcBoundary( + string $instant, + string $expectedStart, + string $expectedEnd, + ): void { $period = ReportingPeriod::monthContaining(new DateTimeImmutable($instant)); self::assertSame($expectedStart, $period->toArray()['start']); From a49f9f5c682bdbec51e2cd31364f2be446f60f55 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 21:06:40 -0300 Subject: [PATCH 39/43] test: raise mutation testing gate Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- infection.json5 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/infection.json5 b/infection.json5 index c2a0718..ad0b176 100644 --- a/infection.json5 +++ b/infection.json5 @@ -10,8 +10,8 @@ "configDir": ".", "customPath": "vendor/bin/phpunit" }, - "minMsi": 85, - "minCoveredMsi": 85, + "minMsi": 90, + "minCoveredMsi": 90, "mutators": { "@default": true } From 110cba205644540fd71291a5688119a1d91066bd Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 21:06:48 -0300 Subject: [PATCH 40/43] chore: strengthen complementary phpcs gate Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- phpcs.xml.dist | 1 + 1 file changed, 1 insertion(+) diff --git a/phpcs.xml.dist b/phpcs.xml.dist index e3c11a7..a82eb13 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -11,6 +11,7 @@ SPDX-License-Identifier: AGPL-3.0-or-later tests/Unit vendor/* vendor-bin/* + From 0ac6fd70c9a235b22d0012ccfcc91364a708f085 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 21:08:28 -0300 Subject: [PATCH 41/43] test: enforce 95 percent mutation score Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- infection.json5 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/infection.json5 b/infection.json5 index ad0b176..1368b56 100644 --- a/infection.json5 +++ b/infection.json5 @@ -10,8 +10,8 @@ "configDir": ".", "customPath": "vendor/bin/phpunit" }, - "minMsi": 90, - "minCoveredMsi": 90, + "minMsi": 95, + "minCoveredMsi": 95, "mutators": { "@default": true } From 98e3fed3d2cd2f91ff6de620dbd64e26354f1428 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 21:08:36 -0300 Subject: [PATCH 42/43] test: cover hostless https endpoints Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- tests/Unit/EndpointTest.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/Unit/EndpointTest.php b/tests/Unit/EndpointTest.php index dbd456c..dcdd497 100644 --- a/tests/Unit/EndpointTest.php +++ b/tests/Unit/EndpointTest.php @@ -4,7 +4,6 @@ * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors * SPDX-License-Identifier: AGPL-3.0-or-later */ - declare(strict_types=1); namespace LibreCode\UsageStatistics\Tests; @@ -34,6 +33,7 @@ public static function invalidEndpoints(): iterable { yield 'credentials' => ['https://user:secret@stats.example/api/v1/reports']; yield 'query' => ['https://stats.example/api/v1/reports?token=x']; yield 'fragment' => ['https://stats.example/api/v1/reports#section']; - yield 'missing host' => ['https:///api/v1/reports']; + yield 'invalid absolute url without host' => ['https:///api/v1/reports']; + yield 'scheme with relative path and no host' => ['https:api/v1/reports']; } } From 75bcbb06ac2c15f195b98dd78a30d93ee5a501a4 Mon Sep 17 00:00:00 2001 From: Vitor Mattos Date: Tue, 8 Sep 2026 21:08:53 -0300 Subject: [PATCH 43/43] docs: document LibreSign integration path Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- docs/integration.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/docs/integration.md b/docs/integration.md index 2e62899..d64c117 100644 --- a/docs/integration.md +++ b/docs/integration.md @@ -30,3 +30,25 @@ The client does not retry internally. On `TransportException` or `ServerRejected A framework can implement `TransportInterface` around its existing HTTP client. The adapter receives the method, absolute URL, headers, JSON body, and total timeout, and returns a small `Response` object. Do not log the request body by default. A malformed host integration could accidentally add sensitive data even though the protocol forbids it. + +## LibreSign + +LibreSign vendors PHP dependencies through the `LibreSign/3rdparty` repository and prefixes them with PHP-Scoper using `OCA\\Libresign\\Vendor`. + +After this package has a published release, add `librecodecoop/usage-statistics-client` to `LibreSign/3rdparty`. The resulting API is used through the scoped namespace, for example `OCA\\Libresign\\Vendor\\LibreCode\\UsageStatistics\\Client`. + +The package CI runs a smoke test using that exact prefix so namespace isolation is checked before release. + +LibreSign still owns the Nextcloud-specific integration: + +- an adapter from the Nextcloud HTTP client to `TransportInterface`; +- persistence and administration of the consent state; +- the `libresign` application ID and active schema version; +- metric definitions and aggregation semantics; +- the default report endpoint and any administrator override; +- the local installation identifier used as input to `InstallationId::derive()`; +- background-job scheduling and retry policy. + +The receiving usage-statistics server must have the matching LibreSign application schema registered before reports using that schema version can be accepted. + +Until the package has a stable tag available to Composer, LibreSign can only consume it through a temporary VCS/dev dependency. Production integration should use a tagged release.