Files
mtusi2026lab5/src/messenger/messaging/infrastructure/cursor.py
T
ArtyomandClaude Opus 5.5 540fcb35ba Carry over the lab 4 solution
Bring the application, own tests, Dockerfile, toolchain, compose stack,
HAProxy, k6 and RustFS configuration, migrations, hooks, evidence and
scenario scripts and the CI job from the lab 4 solution commit d2744bc,
merge the lab 4 Makefile targets into the lab 5 skeleton Makefile
without touching its targets, and append the lab 4 solution variables
to the skeleton .env.example. The package and the application follow
the contract version 1.5.0, and the image and the throwaway test
containers are tagged lab5 so they do not collide with a lab 4 stand on
the same host.

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

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-29 00:34:03 +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]