Source code for confluent_kafka.common.uuid

# Copyright 2025 Confluent Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""``Uuid``: Java's ``org.apache.kafka.common.Uuid``.

Java's ``long`` fields are signed, so ``most_significant_bits()`` /
``least_significant_bits()`` are signed 64-bit values and the ordering
(``Comparable<Uuid>``) is signed. ``__str__`` and ``from_string`` use the
URL-safe base64 form, decoded with ``java.util.Base64``'s rules and messages.
"""

from __future__ import annotations

import base64
import uuid as _uuid
from collections.abc import Sequence
from typing import ClassVar

from confluent_kafka.illegal_argument_error import IllegalArgumentError

__all__ = ["Uuid"]

_INT64_MAX = 2**63 - 1
_UINT64_MASK = (1 << 64) - 1
_URL_ALPHABET = {c: i for i, c in enumerate(
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_")}


def _to_signed64(value: int) -> int:
    """The low 64 bits of ``value`` as a signed 64-bit integer (Java's ``long``)."""
    value &= _UINT64_MASK
    return value - (1 << 64) if value > _INT64_MAX else value


def _base64_url_decode(text: str) -> bytes:
    """``Base64.getUrlDecoder().decode(String)``, with the JDK's messages."""
    # decode(String) reads the ISO-8859-1 bytes; an unmappable char is '?'.
    src = [ord(c) if ord(c) < 256 else ord("?") for c in text]
    out = bytearray()
    bits = 0
    shiftto = 18
    sp = 0
    while sp < len(src):
        b = src[sp]
        sp += 1
        if b == ord("="):
            if (shiftto == 6 and (sp == len(src) or src[(sp := sp + 1) - 1] != ord("="))) \
                    or shiftto == 18:
                raise IllegalArgumentError(message="Input byte array has wrong 4-byte ending unit")
            break
        value = _URL_ALPHABET.get(chr(b))
        if value is None:
            signed = b - 256 if b > 127 else b
            raise IllegalArgumentError(message="Illegal base64 character " + format(signed, "x"))
        bits |= value << shiftto
        shiftto -= 6
        if shiftto < 0:
            out += bytes(((bits >> 16) & 0xFF, (bits >> 8) & 0xFF, bits & 0xFF))
            shiftto = 18
            bits = 0
    if shiftto == 6:
        out.append((bits >> 16) & 0xFF)
    elif shiftto == 0:
        out += bytes(((bits >> 16) & 0xFF, (bits >> 8) & 0xFF))
    elif shiftto == 12:
        raise IllegalArgumentError(message="Last unit does not have enough valid bits")
    if sp < len(src):
        raise IllegalArgumentError(
            message="Input byte array has incorrect ending byte at " + str(sp))
    return bytes(out)


[docs] class Uuid: """This class defines an immutable universally unique identifier (UUID). It represents a 128-bit value. More specifically, the random UUIDs generated by this class are variant 2 (Leach-Salz) version 4 UUIDs. This is the same type of UUID as the ones generated by ``java.util.UUID``. The ``__str__`` method prints using the base64 string encoding. Likewise, the ``from_string`` method expects a base64 string encoding. Java: ``org.apache.kafka.common.Uuid``. """ #: A reserved UUID. Will never be returned by the ``random_uuid`` method. ONE_UUID: ClassVar[Uuid] #: A UUID for the metadata topic in KRaft mode. Will never be returned by #: the ``random_uuid`` method. METADATA_TOPIC_ID: ClassVar[Uuid] #: A UUID that represents a null or empty UUID. Will never be returned by #: the ``random_uuid`` method. ZERO_UUID: ClassVar[Uuid] #: The set of reserved UUIDs that will never be returned by the #: ``random_uuid`` method. RESERVED: ClassVar[frozenset[Uuid]] __slots__ = ("_most_significant_bits", "_least_significant_bits") def __init__(self, *, most_sig_bits: int, least_sig_bits: int) -> None: """Constructs a 128-bit type 4 UUID where the first long represents the most significant 64 bits and the second long represents the least significant 64 bits.""" self._most_significant_bits = _to_signed64(most_sig_bits) self._least_significant_bits = _to_signed64(least_sig_bits) @staticmethod def _unsafe_random_uuid() -> Uuid: j = _uuid.uuid4().int return Uuid(most_sig_bits=j >> 64, least_sig_bits=j & _UINT64_MASK)
[docs] @staticmethod def random_uuid() -> Uuid: """Static factory to retrieve a type 4 (pseudo randomly generated) UUID. This will not generate a UUID equal to 0, 1, or one whose string representation contains a dash ("-").""" candidate = Uuid._unsafe_random_uuid() while candidate in Uuid.RESERVED or "-" in str(candidate): candidate = Uuid._unsafe_random_uuid() return candidate
[docs] def most_significant_bits(self) -> int: """Returns the most significant bits of the UUID's 128 value.""" return self._most_significant_bits
[docs] def least_significant_bits(self) -> int: """Returns the least significant bits of the UUID's 128 value.""" return self._least_significant_bits
def __eq__(self, other: object) -> bool: """True iff ``other`` is another ``Uuid`` represented by the same two long values.""" if type(other) is not type(self): return NotImplemented assert isinstance(other, Uuid) return (self._most_significant_bits == other._most_significant_bits and self._least_significant_bits == other._least_significant_bits) def __hash__(self) -> int: """Java's ``hashCode()``: ``(int) (xor >> 32) ^ (int) xor``.""" xor = self._most_significant_bits ^ self._least_significant_bits high = _to_signed64(xor >> 32) & 0xFFFFFFFF low = xor & 0xFFFFFFFF result = high ^ low return result - (1 << 32) if result > 0x7FFFFFFF else result def __str__(self) -> str: """A base64 string encoding of the UUID.""" return base64.urlsafe_b64encode(self._bytes()).rstrip(b"=").decode("ascii")
[docs] @staticmethod def from_string(*, str: str) -> Uuid: # noqa: A002 - Java's parameter name """Creates a UUID based on a base64 string encoding used in the ``__str__`` method. (``str`` is Java's parameter name; it shadows the builtin only inside this method, whose body does not call ``str()``.) A ``None`` raises ``TypeError``, as Java's ``str.length()``.""" if str is None: raise TypeError("str must not be None") if len(str) > 24: raise IllegalArgumentError( message="Input string with prefix `" + str[:24] + "` is too long to be decoded as a base64 UUID") raw = _base64_url_decode(str) if len(raw) != 16: raise IllegalArgumentError( message="Input string `" + str + "` decoded as " + repr(len(raw)) + " bytes, which is not equal to the expected 16 bytes " + "of a base64-encoded UUID") return Uuid(most_sig_bits=int.from_bytes(raw[:8], "big", signed=True), least_sig_bits=int.from_bytes(raw[8:], "big", signed=True))
def _bytes(self) -> bytes: return ((self._most_significant_bits & _UINT64_MASK).to_bytes(8, "big") + (self._least_significant_bits & _UINT64_MASK).to_bytes(8, "big")) def _compare(self, other: Uuid) -> int: if self._most_significant_bits > other._most_significant_bits: return 1 if self._most_significant_bits < other._most_significant_bits: return -1 if self._least_significant_bits > other._least_significant_bits: return 1 if self._least_significant_bits < other._least_significant_bits: return -1 return 0 def __lt__(self, other: Uuid) -> bool: return self._compare(other) < 0 def __le__(self, other: Uuid) -> bool: return self._compare(other) <= 0 def __gt__(self, other: Uuid) -> bool: return self._compare(other) > 0 def __ge__(self, other: Uuid) -> bool: return self._compare(other) >= 0
[docs] @staticmethod def to_array(*, list: Sequence[Uuid] | None) -> tuple[Uuid, ...] | None: # noqa: A002 """Convert a list of Uuid to an array of Uuid (``None`` for ``None``).""" return None if list is None else tuple(list)
[docs] @staticmethod def to_list(*, array: tuple[Uuid, ...] | None) -> list[Uuid] | None: """Convert an array of Uuids to a list of Uuid (``None`` for ``None``).""" return None if array is None else [*array]
Uuid.ONE_UUID = Uuid(most_sig_bits=0, least_sig_bits=1) Uuid.METADATA_TOPIC_ID = Uuid.ONE_UUID Uuid.ZERO_UUID = Uuid(most_sig_bits=0, least_sig_bits=0) Uuid.RESERVED = frozenset({Uuid.ZERO_UUID, Uuid.ONE_UUID})