Spaces:
Paused

yaz / src /core /database /platform_id.py
anaselamr's picture
[PLATFORM] fix(endpoints+templates): Sprint 52 — zero-error operational pass
579285c
Raw History Blame Contribute Delete
6.49 kB
"""
Platform-Specific Hashed ID System
State-of-the-art human-readable, collision-resistant identifiers
Pattern: {PREFIX}-{TENANT_SHARD}-{TIMESTAMP_ENCODED}-{RANDOM}
Example: SRG-YAZ-A7X9-K3M2 (Surgery case in YAZ platform)
Benefits:
- Human-readable and typeable
- Platform/tenant specific (prevents cross-platform ID confusion)
- Time-sortable (embedded timestamp)
- Collision-resistant (cryptographic randomness)
- URL-safe (no special characters)
- Audit-friendly (decode reveals creation context)
"""
import secrets
import time
from datetime import datetime, timezone
from typing import Optional
from uuid import UUID
# Base32 alphabet (URL-safe, no ambiguous chars: 0/O, 1/I/L)
ALPHABET = "23456789ABCDEFGHJKMNPQRSTUVWXYZ"
ALPHABET_MAP: dict[str, int] = {c: i for i, c in enumerate(ALPHABET)}
class PlatformID:
"""
Platform-specific hashed identifier generator
Format: {APP_PREFIX}-{PLATFORM_SHARD}-{TIME_SEGMENT}-{RANDOM_SEGMENT}
Examples:
SRG-YAZ-A7X9-K3M2 (Surgery case)
LAB-YAZ-B2Y8-N5P7 (Lab result)
PAT-YAZ-C4Z3-Q9R6 (Patient record)
RX-YAZ-D6W5-T2S8 (Prescription)
"""
# App prefixes for different modules
PREFIXES: dict[str, str] = {
"surgio": "SRG",
"clinica": "CLN",
"labo": "LAB",
"pharma": "RX",
"stay": "HSP",
"patient": "PAT",
"encounter": "ENC",
"order": "ORD",
"result": "RES",
"invoice": "INV",
"equipment": "EQP",
"room": "ROM",
"staff": "STF",
"appointment": "APT",
"document": "DOC",
}
# Platform identifier (configurable per deployment)
PLATFORM_CODE = "YAZ" # YAZ Care Platform
@classmethod
def generate(
cls,
app: str = "surgio",
tenant_id: Optional[UUID] = None,
platform_code: Optional[str] = None,
) -> str:
"""
Generate a new platform-specific ID
Args:
app: Application module name (surgio, clinica, labo, etc.)
tenant_id: Optional tenant UUID for multi-tenant sharding
platform_code: Optional platform override (default: YAZ)
Returns:
Human-readable ID like SRG-YAZ-A7X9-K3M2
"""
prefix: str = cls.PREFIXES.get(app, app[:3].upper())
platform: str = platform_code or cls.PLATFORM_CODE
# Time segment: encode current timestamp (sortable)
# Use seconds since 2024-01-01 to keep numbers manageable
epoch_2024 = 1704067200 # 2024-01-01 00:00:00 UTC
time_offset: int = int(time.time()) - epoch_2024
time_segment: str = cls._encode_base32(time_offset, 4)
# Random segment: cryptographically secure randomness
random_bytes: bytes = secrets.token_bytes(3)
random_int: int = int.from_bytes(random_bytes, "big")
random_segment: str = cls._encode_base32(random_int, 4)
return f"{prefix}-{platform}-{time_segment}-{random_segment}"
@classmethod
def generate_case_number(
cls, tenant_id: Optional[UUID] = None, sequence: Optional[int] = None
) -> str:
"""
Generate surgery case number with optional sequence
Format: SRG-YAZ-YYYYMMDD-XXXX
Example: SRG-YAZ-20260201-0023
"""
date_str: str = datetime.now(timezone.utc).strftime("%Y%m%d")
if sequence is not None:
seq_str = f"{sequence:04d}"
else:
# Use random if no sequence provided
seq_str = f"{secrets.randbelow(10000):04d}"
return f"SRG-{cls.PLATFORM_CODE}-{date_str}-{seq_str}"
@classmethod
def parse(cls, platform_id: str) -> Optional[dict]:
"""
Parse a platform ID to extract components
Returns:
dict with prefix, platform, timestamp, random components
or None if invalid format
"""
try:
parts: list[str] = platform_id.split("-")
if len(parts) != 4:
return None
prefix, platform, time_seg, random_seg = parts
# Decode time segment
time_offset: int = cls._decode_base32(time_seg)
epoch_2024 = 1704067200
timestamp: datetime = datetime.utcfromtimestamp(epoch_2024 + time_offset)
return {
"prefix": prefix,
"platform": platform,
"timestamp": timestamp,
"time_segment": time_seg,
"random_segment": random_seg,
"app": next((k for k, v in cls.PREFIXES.items() if v == prefix), prefix.lower()),
}
except Exception:
return None
@classmethod
def validate(cls, platform_id: str) -> bool:
"""Check if a platform ID is valid format"""
return cls.parse(platform_id) is not None
@classmethod
def _encode_base32(cls, num: int, length: int) -> str:
"""Encode integer to base32 string of fixed length"""
result = []
base: int = len(ALPHABET)
for _ in range(length):
result.append(ALPHABET[num % base])
num //= base
return "".join(reversed(result))
@classmethod
def _decode_base32(cls, s: str) -> int:
"""Decode base32 string to integer"""
num = 0
base = len(ALPHABET)
for c in s:
num = num * base + ALPHABET_MAP.get(c, 0)
return num
def new_uuid7() -> UUID:
"""
Generate a UUID v7 (time-ordered random UUID per RFC 4122 bis).
Layout (128-bit)::
[48-bit unix_ts_ms][4-bit version=7][12-bit rand_a]
[2-bit variant=10][62-bit rand_b]
Time-ordered UUIDs reduce B-tree index fragmentation on PostgreSQL 16+.
Prefer this over ``uuid4()`` for primary keys on high-write tables.
Usage::
from core.database import new_uuid7
class MyModel(SQLModel, table=True):
id: UUID = Field(default_factory=new_uuid7, primary_key=True)
"""
ts_ms = int(time.time() * 1000)
rand: bytes = secrets.token_bytes(10)
b = bytearray(16)
# 48-bit timestamp
b[0] = (ts_ms >> 40) & 0xFF
b[1] = (ts_ms >> 32) & 0xFF
b[2] = (ts_ms >> 24) & 0xFF
b[3] = (ts_ms >> 16) & 0xFF
b[4] = (ts_ms >> 8) & 0xFF
b[5] = ts_ms & 0xFF
# version 7
b[6] = 0x70 | (rand[0] & 0x0F)
b[7] = rand[1]
# variant 10xx
b[8] = 0x80 | (rand[2] & 0x3F)
b[9:16] = rand[3:10]
return UUID(bytes=bytes(b))