Files
mtusi2026lab6/src/messenger/messaging/infrastructure/cursor.py
T
ArtyomandClaude Opus 5.5 5ae3d77152 Carry over the lab 5 solution
Bring the application, own tests, Dockerfile, toolchain, compose stack,
HAProxy, k6, RustFS and RabbitMQ configuration, migrations, hooks,
scenario scripts and the CI job from the lab 5 solution commit 64d5c67,
keep the lab 5 Makefile targets on top of the unchanged skeleton
targets, and append the lab 5 solution variables to the skeleton
.env.example. The package and the application follow the contract
version 1.6.0, and the image, the throwaway test containers and the
broker vhost description are tagged lab6 so they do not collide with a
lab 5 stand on the same host.

This is the starting point of the lab 6 cycle: lint, own tests and the
offline skeleton check pass before any lab 6 change.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-29 03:51:58 +03:00

60 lines
2.2 KiB
Python

import hmac
from base64 import urlsafe_b64decode, urlsafe_b64encode
from datetime import UTC, datetime, timedelta
from hashlib import sha256
from messenger.messaging.domain.errors import InvalidPageRequest
from messenger.messaging.domain.keys import HistoryKey
VERSION = "1"
SIGNATURE_BYTES = 12
EPOCH = datetime(1970, 1, 1, tzinfo=UTC)
PARTS = 4
def _encode_part(value: bytes) -> str:
return urlsafe_b64encode(value).decode("ascii").rstrip("=")
def _decode_part(value: str) -> bytes:
padding = "=" * (-len(value) % 4)
try:
return urlsafe_b64decode(value + padding)
except (ValueError, TypeError) as error:
raise InvalidPageRequest("параметр cursor повреждён") from error
class SignedCursorCodec:
__slots__ = ("_secret",)
def __init__(self, secret: bytes) -> None:
self._secret = secret
def encode(self, scope: str, key: HistoryKey) -> str:
moment, identifier = key
micros = (moment - EPOCH) // timedelta(microseconds=1)
body = f"{VERSION}.{micros}.{identifier:032x}"
return f"{body}.{_encode_part(self._sign(scope, body))}"
def decode(self, scope: str, raw: str) -> HistoryKey:
parts = raw.split(".")
if len(parts) != PARTS or parts[0] != VERSION:
raise InvalidPageRequest("параметр cursor не распознан")
body = ".".join(parts[:3])
if not hmac.compare_digest(self._sign(scope, body), _decode_part(parts[3])):
raise InvalidPageRequest("параметр cursor недействителен для этого запроса")
try:
micros = int(parts[1])
identifier = int(parts[2], 16)
except ValueError as error:
raise InvalidPageRequest("параметр cursor повреждён") from error
try:
moment = EPOCH + timedelta(microseconds=micros)
except (OverflowError, ValueError) as error:
raise InvalidPageRequest("параметр cursor повреждён") from error
return (moment, identifier)
def _sign(self, scope: str, body: str) -> bytes:
payload = f"{scope}|{body}".encode()
return hmac.new(self._secret, payload, sha256).digest()[:SIGNATURE_BYTES]