Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
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.
- Serializing a string-backed PHP enum as a protobuf enum throws `Exception\InvalidSchema` instead of
`\InvalidArgumentException`.
- `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.
- Malformed input makes `Serializer::deserialize()` and `Decoder::decode()` throw a subclass of the new
`Exception\MalformedMessage`: `Exception\BufferUnderflow` (now a subclass of it) for a truncated input,
`Exception\MalformedVarint` for a varint longer than 10 bytes, `Exception\UnsupportedWireType` for an unknown
wire type. They used to throw `Thesis\Varint\MalformedVarintNumber` and `\ValueError`, which escaped
`catch (ProtobufException)` when the low-level API was used.
- `Encoder::encode()` and `Decoder::decode()` no longer wrap every `\Throwable` into `EncodingError`/`DecodingError`.
Library errors are `ProtobufException`s already; anything else, such as a `\TypeError` from a property whose
PHP type does not match its protobuf type, is a bug in the schema or the code and now propagates as is.
`Decoder::decode()` still reports a class that cannot be reflected as `DecodingError`.

### Deprecated

- `Encoder\EncodingError` is not thrown any more: a `catch (EncodingError)` no longer catches anything. Catch
`ProtobufException` or one of its specific subclasses instead.

### Fixed

Expand Down
7 changes: 2 additions & 5 deletions src/Decoder/Internal/ReflectionDecoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
namespace Thesis\Protobuf\Decoder\Internal;

use Thesis\Protobuf\Decoder;
use Thesis\Protobuf\ProtobufException;
use Thesis\Protobuf\Reflection\Reflector;
use Thesis\Protobuf\Serializer;

Expand All @@ -30,10 +29,8 @@ public function decode(string $buffer, string $classType): object
),
$classType,
);
} catch (ProtobufException $e) {
throw $e;
} catch (\Throwable $e) {
throw new Decoder\DecodingError($e->getMessage(), (int) $e->getCode(), $e);
} catch (\ReflectionException $e) {
throw new Decoder\DecodingError($e->getMessage(), $e->getCode(), $e);
}
}
}
2 changes: 2 additions & 0 deletions src/Encoder/EncodingError.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,7 @@

/**
* @api
* @deprecated Not thrown any more: encoding errors are reported by the specific subclasses of ProtobufException,
* such as Exception\ValueOutOfRange. Catch ProtobufException instead. Will be removed in the next minor version.
*/
final class EncodingError extends ProtobufException {}
13 changes: 3 additions & 10 deletions src/Encoder/Internal/ReflectionEncoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
namespace Thesis\Protobuf\Encoder\Internal;

use Thesis\Protobuf\Encoder;
use Thesis\Protobuf\ProtobufException;
use Thesis\Protobuf\Reflection\Reflector;
use Thesis\Protobuf\Serializer;

Expand All @@ -22,14 +21,8 @@ public function __construct(
#[\Override]
public function encode(object $message): string
{
try {
return $this->serializer->serialize(
$this->reflector->message($message),
);
} catch (ProtobufException $e) {
throw $e;
} catch (\Throwable $e) {
throw new Encoder\EncodingError($e->getMessage(), (int) $e->getCode(), $e);
}
return $this->serializer->serialize(
$this->reflector->message($message),
);
}
}
6 changes: 3 additions & 3 deletions src/Exception/BufferUnderflow.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@

namespace Thesis\Protobuf\Exception;

use Thesis\Protobuf\ProtobufException;

/**
* The input ends before the value being read does.
*
* @api
*/
final class BufferUnderflow extends ProtobufException {}
final class BufferUnderflow extends MalformedMessage {}
15 changes: 15 additions & 0 deletions src/Exception/MalformedMessage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

declare(strict_types=1);

namespace Thesis\Protobuf\Exception;

use Thesis\Protobuf\ProtobufException;

/**
* The input is not a valid protobuf encoding. Catch this to handle any malformed input; the subclasses
* tell what exactly is wrong.
*
* @api
*/
abstract class MalformedMessage extends ProtobufException {}
12 changes: 12 additions & 0 deletions src/Exception/MalformedVarint.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

declare(strict_types=1);

namespace Thesis\Protobuf\Exception;

/**
* A varint that does not end within 10 bytes, the most a 64-bit value takes.
*
* @api
*/
final class MalformedVarint extends MalformedMessage {}
23 changes: 23 additions & 0 deletions src/Exception/UnsupportedWireType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

namespace Thesis\Protobuf\Exception;

/**
* A tag with a wire type that protobuf does not define or that is not supported.
*
* @api
*/
final class UnsupportedWireType extends MalformedMessage
{
/**
* @param int<0, 7> $wireType
*/
public function __construct(
public readonly int $wireType,
public readonly int $field,
) {
parent::__construct(\sprintf('Unsupported wire type %d for field %d.', $wireType, $field));
}
}
4 changes: 2 additions & 2 deletions src/Internal/Buffer/buffer.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
namespace Thesis\Protobuf\Internal\Buffer;

use BcMath\Number;
use Thesis\Protobuf\Exception\BufferUnderflow;
use Thesis\Protobuf\Exception\MalformedMessage;
use Thesis\Protobuf\Internal\Serde\SerdeVarint;
use Thesis\Protobuf\Internal\Wire;

Expand All @@ -23,7 +23,7 @@ function copy(ReadBuffer $src, WriteBuffer $dst): void

/**
* @internal
* @throws BufferUnderflow
* @throws MalformedMessage
*/
function slice(ReadBuffer $src): ReadBuffer
{
Expand Down
34 changes: 34 additions & 0 deletions src/Internal/IntBackedEnum.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

declare(strict_types=1);

namespace Thesis\Protobuf\Internal;

use Thesis\Protobuf\Exception\InvalidSchema;

/**
* @internal
*/
final class IntBackedEnum
{
/** @var array<string, true> */
private static array $checked = [];

/**
* Protobuf enum numbers are integers, so only an int-backed PHP enum can represent a protobuf enum.
*
* @throws InvalidSchema
*/
public static function check(string $enum): void
{
if (isset(self::$checked[$enum])) {
return;
}

if (!enum_exists($enum) || new \ReflectionEnum($enum)->getBackingType()?->getName() !== 'int') {
throw new InvalidSchema(\sprintf('"%s" must be an int-backed enum to represent a protobuf enum.', $enum));
}

self::$checked[$enum] = true;
}
}
5 changes: 2 additions & 3 deletions src/Internal/Serde/SerdeString.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,9 @@ public function serialize(WriteBuffer $buffer, mixed $value): void
#[\Override]
public function deserialize(ReadBuffer $buffer): string
{
// A varint is never negative; one above PHP_INT_MAX saturates and fails the read below.
/** @var non-negative-int $length */
$length = (int) SerdeVarint::T->deserialize($buffer)->value;
if ($length < 0) {
throw new \UnexpectedValueException("String length must be positive or equal to 0, '{$length}' given.");
}

if ($length === 0) {
return '';
Expand Down
6 changes: 2 additions & 4 deletions src/Internal/Serde/SerializeEnum.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

namespace Thesis\Protobuf\Internal\Serde;

use Thesis\Protobuf\Exception\InvalidSchema;
use Thesis\Protobuf\Internal\Buffer\WriteBuffer;

/**
Expand All @@ -18,10 +17,9 @@ enum SerializeEnum implements SerializeValue
#[\Override]
public function serialize(WriteBuffer $buffer, mixed $value): void
{
// EnumT accepts only int-backed enums.
/** @var int $case */
$case = $value->value;
if (!\is_int($case)) {
throw new InvalidSchema(\sprintf('Enum "%s" must be int-backed to be a protobuf enum.', $value::class));
}

// Enum numbers are int32: a negative one is sign-extended to 64 bits.
SerdeInt64::T->serialize($buffer, Range::int32($case, 'enum'));
Expand Down
33 changes: 25 additions & 8 deletions src/Internal/Wire/wire.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

use BcMath\Number;
use Thesis\Protobuf\Exception\BufferUnderflow;
use Thesis\Protobuf\Exception\MalformedMessage;
use Thesis\Protobuf\Exception\MalformedVarint;
use Thesis\Protobuf\Internal\Buffer\ReadBuffer;
use Thesis\Protobuf\Internal\Buffer\WriteBuffer;
use Thesis\Protobuf\Internal\Serde\SerdeVarint;
Expand All @@ -22,7 +24,7 @@
* bytes - 1 ≤ size ≤ 10 + length.
*
* @internal
* @throws BufferUnderflow
* @throws MalformedMessage
*/
function discardUnknown(ReadBuffer $buffer, Tag $tag): UnknownField
{
Expand All @@ -43,16 +45,33 @@ function discardUnknown(ReadBuffer $buffer, Tag $tag): UnknownField

/**
* @internal
* @throws BufferUnderflow
* @throws MalformedMessage
*/
function readVarint(ReadBuffer $buffer): Number
{
$number = Varint\BcMath::Codec->decodeVarintSized($buffer->peek(10));
$number = decodeVarint($buffer->peek(10));
$buffer->read($number->size);

return $number->value;
}

/**
* @internal
* @param non-empty-string $bytes up to 10 bytes from the start of a varint
* @throws MalformedMessage
*/
function decodeVarint(string $bytes): Varint\Sized
{
try {
return Varint\BcMath::Codec->decodeVarintSized($bytes);
} catch (Varint\MalformedVarintNumber) {
// No terminating byte among the bytes given: either the input ends or the varint is too long.
throw \strlen($bytes) < 10
? new BufferUnderflow('Unexpected end of input: truncated varint.')
: new MalformedVarint('Malformed varint: longer than 10 bytes.');
}
}

/**
* @internal
*/
Expand All @@ -63,18 +82,16 @@ function writeTag(WriteBuffer $buffer, Tag $tag): void

/**
* @internal
* @throws BufferUnderflow
* @throws MalformedMessage
*/
function peekTag(ReadBuffer $buffer): Tag
{
$number = Varint\BcMath::Codec->decodeVarintSized($buffer->peek(10));

return Tag::from($number->value);
return Tag::from(decodeVarint($buffer->peek(10))->value);
}

/**
* @internal
* @throws BufferUnderflow
* @throws MalformedMessage
*/
function readTag(ReadBuffer $buffer): Tag
{
Expand Down
8 changes: 7 additions & 1 deletion src/Reflection/EnumT.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@

namespace Thesis\Protobuf\Reflection;

use Thesis\Protobuf\Exception\InvalidSchema;
use Thesis\Protobuf\Internal\IntBackedEnum;

/**
* @api
* @template-covariant T of \BackedEnum
Expand All @@ -13,10 +16,13 @@
{
/**
* @param class-string<T> $enum
* @throws InvalidSchema if the class is not an int-backed enum
*/
public function __construct(
public string $enum,
) {}
) {
IntBackedEnum::check($enum);
}

#[\Override]
public function accept(Visitor $visitor): mixed
Expand Down
7 changes: 5 additions & 2 deletions src/Serializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

namespace Thesis\Protobuf;

use Thesis\Protobuf\Exception\BufferUnderflow;
use Thesis\Protobuf\Exception\MalformedMessage;
use Thesis\Protobuf\Internal\Buffer\ByteBuffer;
use Thesis\Protobuf\Internal\Serde\UnknownEnumValue;
use Thesis\Protobuf\Internal\Wire;
Expand All @@ -18,6 +18,9 @@
*/
final readonly class Serializer
{
/**
* @throws Exception\ValueOutOfRange if a value does not fit its protobuf type
*/
public function serialize(Message $message): string
{
$buffer = new ByteBuffer();
Expand All @@ -38,7 +41,7 @@ public function serialize(Message $message): string
}

/**
* @throws BufferUnderflow
* @throws MalformedMessage if the bytes are not a valid protobuf encoding
*/
public function deserialize(MessageT $type, string $bytes): Message
{
Expand Down
5 changes: 4 additions & 1 deletion src/Tag.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ final class Tag
/** @phpstan-ignore property.uninitialized */
public private(set) Number $number { get => $this->number ??= new Number($this->num << 3 | $this->type->value); }

/**
* @throws Exception\UnsupportedWireType
*/
public static function from(Number $number): self
{
$tag = (int) $number->value;
Expand All @@ -24,7 +27,7 @@ public static function from(Number $number): self

return new self(
$num,
WireType::from($type),
WireType::tryFrom($type) ?? throw new Exception\UnsupportedWireType($type, $num),
);
}

Expand Down
Loading
Loading