diff --git a/CHANGELOG.md b/CHANGELOG.md index d1b92a7..45a8f3d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,7 +14,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Serializing a value that its protobuf type cannot represent now throws `Exception\ValueOutOfRange` instead of wrapping it or writing a broken varint: `int32`/`sint32`/`sfixed32`/enum outside [-2^31, 2^31-1] (e.g. `int32Of(2 ** 31)` used to wrap to a negative number), `uint32`/`fixed32` outside [0, 2^32-1], and - `uint64`/`fixed64` that are negative, above 2^64-1 or fractional. + `uint64`/`fixed64` that are negative, above 2^64-1 or fractional. The exception names the field numbers that + lead to the value (`$fields`, e.g. `field 3.1`) and, when encoding an object, the class properties + (`$properties`, e.g. `Order::$items → Item::$quantity`). - `enumT()`, `enumOf()`, `Type\EnumT` and `Reflection\EnumT` accept only int-backed PHP enums and throw `Exception\InvalidSchema` for any other class when the type is declared. A string-backed enum used to fail with `\InvalidArgumentException` only when a value was serialized. diff --git a/src/Encoder/Internal/ReflectionEncoder.php b/src/Encoder/Internal/ReflectionEncoder.php index 63d0023..2a15d42 100644 --- a/src/Encoder/Internal/ReflectionEncoder.php +++ b/src/Encoder/Internal/ReflectionEncoder.php @@ -5,6 +5,7 @@ namespace Thesis\Protobuf\Encoder\Internal; use Thesis\Protobuf\Encoder; +use Thesis\Protobuf\Exception\ValueOutOfRange; use Thesis\Protobuf\Reflection\Reflector; use Thesis\Protobuf\Serializer; @@ -21,8 +22,12 @@ public function __construct( #[\Override] public function encode(object $message): string { - return $this->serializer->serialize( - $this->reflector->message($message), - ); + try { + return $this->serializer->serialize( + $this->reflector->message($message), + ); + } catch (ValueOutOfRange $e) { + throw $e->withProperties($this->reflector->propertyPath($message::class, $e->fields)); + } } } diff --git a/src/Exception/ValueOutOfRange.php b/src/Exception/ValueOutOfRange.php index dc0163e..c1bc94f 100644 --- a/src/Exception/ValueOutOfRange.php +++ b/src/Exception/ValueOutOfRange.php @@ -15,6 +15,22 @@ */ final class ValueOutOfRange extends ProtobufException { + /** + * Numbers of the fields that lead to the value, from the outermost message. A map entry adds 1 for its key + * or 2 for its value; a repeated field adds nothing for the element index. Empty when the value was + * serialized outside of a message. + * + * @var list + */ + public private(set) array $fields = []; + + /** + * The same path as "Class::$property" names when the message was encoded from an object. + * + * @var list + */ + public private(set) array $properties = []; + /** * @param non-empty-string $type protobuf type name, e.g. "int32" * @param non-empty-string $range the values the type accepts, e.g. "[0, 4294967295]" @@ -22,8 +38,47 @@ final class ValueOutOfRange extends ProtobufException public function __construct( public readonly string $type, public readonly int|Number $value, - string $range, + private readonly string $range, ) { - parent::__construct(\sprintf('Value %s is out of range for %s: expected an integer in %s.', $value, $type, $range)); + parent::__construct($this->describe()); + } + + /** + * @internal + * @param positive-int $num the field containing the location known so far + */ + public function inField(int $num): self + { + array_unshift($this->fields, $num); + $this->message = $this->describe(); + + return $this; + } + + /** + * @internal + * @param list $properties + */ + public function withProperties(array $properties): self + { + $this->properties = $properties; + $this->message = $this->describe(); + + return $this; + } + + private function describe(): string + { + $location = ''; + + if ($this->fields !== []) { + $location .= ' in field ' . implode('.', $this->fields); + } + + if ($this->properties !== []) { + $location .= ' (' . implode(' → ', $this->properties) . ')'; + } + + return \sprintf('Value %s is out of range for %s%s: expected an integer in %s.', $this->value, $this->type, $location, $this->range); } } diff --git a/src/Internal/Serde/SerializeMessage.php b/src/Internal/Serde/SerializeMessage.php index 02577ef..05baf11 100644 --- a/src/Internal/Serde/SerializeMessage.php +++ b/src/Internal/Serde/SerializeMessage.php @@ -4,6 +4,7 @@ namespace Thesis\Protobuf\Internal\Serde; +use Thesis\Protobuf\Exception\ValueOutOfRange; use Thesis\Protobuf\FieldDescriptor; use Thesis\Protobuf\Internal\Buffer; use Thesis\Protobuf\Internal\Buffer\ByteBuffer; @@ -35,8 +36,11 @@ public function serialize(WriteBuffer $buffer, mixed $value): void $type->accept(DetermineWireType::Visitor), ); - $serializer = $type->accept(new TypeSerializerVisitor($tag)); - $serializer->serialize($tmp, $field->value->value); + try { + $type->accept(new TypeSerializerVisitor($tag))->serialize($tmp, $field->value->value); + } catch (ValueOutOfRange $e) { + throw $e->inField($field->num); + } } Buffer\copy($tmp, $buffer); diff --git a/src/Reflection/Reflector.php b/src/Reflection/Reflector.php index 0711541..523ef53 100644 --- a/src/Reflection/Reflector.php +++ b/src/Reflection/Reflector.php @@ -185,6 +185,82 @@ public function map(Message $message, string $class): object return $object; } + /** + * Translates a path of field numbers (see Exception\ValueOutOfRange::$fields) into "Class::$property" + * names, starting from the class of the encoded object. Stops where the path leaves the known classes. + * + * @internal + * @param class-string $class + * @param list $fields + * @return list + */ + public function propertyPath(string $class, array $fields): array + { + $path = []; + $i = 0; + + while (($num = $fields[$i] ?? null) !== null) { + $field = null; + + foreach ($this->classReflector->reflect($class)->properties as $property) { + $name = $property->reflection->getName(); + + if ($property->attributes->has(Field::class)) { + if ($property->attributes->get(Field::class)->num === $num) { + $field = $property->attributes->get(Field::class); + + break; + } + } elseif ($property->attributes->has(OneOf::class)) { + foreach ($property->attributes->get(OneOf::class)->variants as $variant) { + if (isset($this->type($variant)->fields[$num])) { + // The variant's own properties carry the field: look it up there. + $path[] = "{$class}::\${$name}"; + $class = $variant; + + continue 3; + } + } + } + } + + if ($field === null) { + break; + } + + $segment = "{$class}::\${$name}"; + ++$i; + + $type = $field->type; + + while ($type instanceof ListT) { + $type = $type->element; + } + + if ($type instanceof MapT) { + $entry = $fields[$i++] ?? null; + + if ($entry === 1) { + $segment .= '[key]'; + $type = $type->keyT; + } elseif ($entry === 2) { + $segment .= '[value]'; + $type = $type->valueT; + } + } + + $path[] = $segment; + + if (!$type instanceof ObjectT) { + break; + } + + $class = $type->class; + } + + return $path; + } + /** * @param ?\Closure(Field, mixed): bool $presence */ diff --git a/src/Serializer.php b/src/Serializer.php index f0042ed..b86de16 100644 --- a/src/Serializer.php +++ b/src/Serializer.php @@ -28,13 +28,17 @@ public function serialize(Message $message): string foreach ($message->fields as $field) { $type = $field->value->type; - $type - ->accept( - new TypeSerializerVisitor( - new Tag($field->num, $type->accept(DetermineWireType::Visitor)), - ), - ) - ->serialize($buffer, $field->value->value); + try { + $type + ->accept( + new TypeSerializerVisitor( + new Tag($field->num, $type->accept(DetermineWireType::Visitor)), + ), + ) + ->serialize($buffer, $field->value->value); + } catch (Exception\ValueOutOfRange $e) { + throw $e->inField($field->num); + } } return $buffer->flush(); diff --git a/tests/ValueOutOfRangeLocationTest.php b/tests/ValueOutOfRangeLocationTest.php new file mode 100644 index 0000000..7876dc8 --- /dev/null +++ b/tests/ValueOutOfRangeLocationTest.php @@ -0,0 +1,135 @@ + $fields + */ + #[DataProvider('provideSerializerNamesTheFieldCases')] + public function testSerializerNamesTheField(Message $message, array $fields, string $location): void + { + try { + new Serializer()->serialize($message); + self::fail('Serialization must fail.'); + } catch (ValueOutOfRange $e) { + self::assertSame($fields, $e->fields); + self::assertSame([], $e->properties); + self::assertStringContainsString("for uint32 in field {$location}: expected", $e->getMessage()); + } + } + + /** + * @return iterable, string}> + */ + public static function provideSerializerNamesTheFieldCases(): iterable + { + yield 'top-level field' => [message(fieldOf(3, uint32Of(-5))), [3], '3']; + yield 'nested message' => [message(fieldOf(3, messageOf(fieldOf(1, uint32Of(-5))))), [3, 1], '3.1']; + yield 'list element' => [message(fieldOf(4, listOf(uint32T, [1, -5]))), [4], '4']; + yield 'map key' => [message(fieldOf(5, mapOf(uint32T, stringT, Map::fromArray([-5 => 'a'])))), [5, 1], '5.1']; + yield 'map value' => [message(fieldOf(5, mapOf(stringT, uint32T, Map::fromArray(['a' => -5])))), [5, 2], '5.2']; + } + + /** + * @param list $fields + * @param list $properties + */ + #[DataProvider('provideEncoderNamesTheClassAndPropertyCases')] + public function testEncoderNamesTheClassAndProperty(object $message, array $fields, array $properties): void + { + try { + Encoder\Builder::buildDefault()->encode($message); + self::fail('Encoding must fail.'); + } catch (ValueOutOfRange $e) { + self::assertSame($fields, $e->fields); + self::assertSame($properties, $e->properties); + self::assertStringContainsString(\sprintf('(%s)', implode(' → ', $properties)), $e->getMessage()); + } + } + + /** + * @return iterable, list}> + */ + public static function provideEncoderNamesTheClassAndPropertyCases(): iterable + { + $outer = LocationTestOuter::class; + $inner = LocationTestInner::class; + + yield 'scalar' => [new LocationTestInner(-5), [1], ["{$inner}::\$id"]]; + yield 'nested object' => [new LocationTestOuter(inner: new LocationTestInner(-5)), [3, 1], ["{$outer}::\$inner", "{$inner}::\$id"]]; + yield 'list of objects' => [ + new LocationTestOuter(items: [new LocationTestInner(1), new LocationTestInner(-5)]), + [4, 1], + ["{$outer}::\$items", "{$inner}::\$id"], + ]; + yield 'map value object' => [ + new LocationTestOuter(byName: Map::fromArray(['a' => new LocationTestInner(-5)])), + [5, 2, 1], + ["{$outer}::\$byName[value]", "{$inner}::\$id"], + ]; + yield 'map key' => [ + new LocationTestOuter(byId: Map::fromArray([-5 => 'a'])), + [6, 1], + ["{$outer}::\$byId[key]"], + ]; + yield 'oneof variant' => [ + new LocationTestOuter(choice: new LocationTestVariant(-5)), + [7], + ["{$outer}::\$choice", LocationTestVariant::class . '::$count'], + ]; + } +} + +final readonly class LocationTestInner +{ + public function __construct( + #[Reflection\Field(1, Reflection\Uint32T::T)] + public int $id = 0, + ) {} +} + +final readonly class LocationTestVariant +{ + public function __construct( + #[Reflection\Field(7, Reflection\Uint32T::T)] + public int $count = 0, + ) {} +} + +final readonly class LocationTestOuter +{ + /** + * @param list $items + * @param Map $byName + * @param Map $byId + */ + public function __construct( + #[Reflection\Field(3, new Reflection\ObjectT(LocationTestInner::class))] + public ?LocationTestInner $inner = null, + #[Reflection\Field(4, new Reflection\ListT(new Reflection\ObjectT(LocationTestInner::class)))] + public array $items = [], + #[Reflection\Field(5, new Reflection\MapT(Reflection\StringT::T, new Reflection\ObjectT(LocationTestInner::class)))] + public Map $byName = new Map(), + #[Reflection\Field(6, new Reflection\MapT(Reflection\Uint32T::T, Reflection\StringT::T))] + public Map $byId = new Map(), + #[Reflection\OneOf([LocationTestVariant::class])] + public ?LocationTestVariant $choice = null, + ) {} +}