PatersonProjects commented on code in PR #936:
URL: https://github.com/apache/burr/pull/936#discussion_r4212484693


##########
burr/integrations/persisters/b_aerospike.py:
##########
@@ -0,0 +1,1014 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+
+import hashlib
+import json
+import random
+import sys
+import threading
+import time
+from collections import OrderedDict
+from datetime import datetime, timezone
+from typing import Any, Optional
+
+from burr.core import persistence, state
+from burr.integrations import base
+
+if sys.version_info < (3, 10):
+    raise ImportError(
+        "The Aerospike persister requires Python 3.10 or newer. "
+        "Install Burr with the 'aerospike' extra on a supported Python 
version."
+    )
+
+try:
+    import aerospike
+    import aerospike_helpers.expressions as expr
+    from aerospike_helpers.operations import map_operations as map_ops
+    from aerospike_helpers.operations import operations as aero_ops
+except ImportError as e:
+    base.require_plugin(e, "aerospike")
+
+_CODE_VERSION = 1
+_SYSTEM = "burr-as"
+
+# Aerospike bin names are capped at 15 characters.
+_PART_BIN = "partition"
+_PREFIX_BIN = "key_prefix"
+_APP_BIN = "app_id"
+_APPS_BIN = "app_ids"
+_TAIL_BIN = "tail_page"
+_MEMBERSHIP_BIN = "member_confirm"
+_SEQ_BIN = "sequence_id"
+_POS_BIN = "position"
+_STATE_BIN = "state"
+_STATUS_BIN = "status"
+_CREATED_BIN = "created_at"
+
+_MAX_WRITE_ATTEMPTS = 3
+_MAX_TAIL_HINTS = 128
+_MEMBERSHIP_BATCH_SIZE = 1000
+_RECORD_NOT_FOUND_CODE = 2
+_RETRYABLE_CODES = {9, -10, 7, 14}  # Timeout, Connection, ClusterChange, 
KEY_BUSY
+
+
+class AerospikePersistenceError(Exception):
+    """Base class for Aerospike persister errors."""
+
+
+class AerospikePersistenceConsistencyError(AerospikePersistenceError):
+    """Raised when stored data violates the persister's invariants."""
+
+
+class AerospikePersistenceSerializationError(AerospikePersistenceError, 
ValueError):
+    """Raised when state cannot be serialized to strict JSON."""
+
+
+class AerospikePersistenceUncertainOutcomeError(AerospikePersistenceError):
+    """Raised when a write retry budget is exhausted without a definitive 
result."""
+
+
+class AerospikeBasePersister(persistence.BaseStatePersister):
+    """Synchronous Aerospike-backed implementation of Burr's 
``BaseStatePersister``.
+
+    The persister stores one immutable history record per ``(partition_key,
+    app_id, sequence_id)`` and a small mutable head record per 
``(partition_key,
+    app_id)`` that points to the latest sequence. Application IDs within a
+    partition are listed through one materialized membership record per
+    logical partition.
+
+    This optional integration requires Python 3.10+ and the official Aerospike
+    Python client. Burr core remains compatible with Python 3.9+.
+    """
+
+    @classmethod
+    def from_config(cls, config: dict) -> "AerospikeBasePersister":
+        """Create a persister from a configuration dictionary."""
+        return cls.from_values(**config)
+
+    @classmethod
+    def from_values(
+        cls,
+        hosts: Optional[list] = None,
+        client_config: Optional[dict] = None,
+        namespace: str = "test",
+        history_set: str = "burr_state",
+        head_set: str = "burr_head",
+        membership_set: str = "burr_apps",
+        key_prefix: Optional[str] = "",
+        serde_kwargs: Optional[dict] = None,
+    ) -> "AerospikeBasePersister":
+        """Create a persister from seed hosts and client configuration.
+
+        :param hosts: Aerospike seed hosts as ``[(host, port), ...]``.
+        :param client_config: Additional official client configuration options.
+        :param namespace: Aerospike namespace.
+        :param history_set: Set for immutable checkpoint records.
+        :param head_set: Set for mutable latest-sequence heads.
+        :param membership_set: Set for per-partition application membership.
+        :param key_prefix: Optional logical prefix for key isolation.
+        :param serde_kwargs: Kwargs for Burr ``State`` serialization.
+        """
+        if hosts is None:
+            hosts = [("127.0.0.1", 3000)]
+        aerospike_config = {"hosts": hosts}
+        if client_config:
+            aerospike_config.update(client_config)
+
+        client = aerospike.client(aerospike_config)
+
+        return cls(
+            client,
+            namespace=namespace,
+            history_set=history_set,
+            head_set=head_set,
+            membership_set=membership_set,
+            key_prefix=key_prefix if key_prefix is not None else "",
+            serde_kwargs=serde_kwargs,
+            _client_config=aerospike_config,
+            _owned=True,
+        )
+
+    def __init__(
+        self,
+        client,
+        *,
+        namespace: str = "test",
+        history_set: str = "burr_state",
+        head_set: str = "burr_head",
+        membership_set: str = "burr_apps",
+        key_prefix: Optional[str] = "",
+        serde_kwargs: Optional[dict] = None,
+        _client_config: Optional[dict] = None,
+        _owned: bool = False,
+    ):
+        """Initialize the persister with an Aerospike client.
+
+        Direct construction accepts an already-connected caller-owned client.
+        Use :meth:`from_values` or :meth:`from_config` for persister-owned
+        clients.
+        """
+        self._client = client
+        self._owned = _owned
+        self.namespace = namespace
+        self.history_set = history_set
+        self.head_set = head_set
+        self.membership_set = membership_set
+        self.key_prefix = key_prefix if key_prefix is not None else ""
+        self.serde_kwargs = serde_kwargs or {}
+        self._client_config = _client_config
+        self._initialized = False
+        self._closed = False
+        self._tail_hints = OrderedDict()
+        self._tail_hints_lock = threading.Lock()
+
+    def __enter__(self):
+        return self
+
+    def __exit__(self, exc_type, exc_value, traceback):
+        self.cleanup()
+        return False
+
+    def is_async(self) -> bool:
+        return False
+
+    def cleanup(self):
+        """Close the persister-owned client, if any."""
+        if self._owned and not self._closed and self._client is not None:
+            self._client.close()
+            self._closed = True
+
+    def __getstate__(self) -> dict:
+        if not self._owned:
+            raise TypeError(
+                "An AerospikeBasePersister constructed with an injected client 
cannot be pickled"
+            )
+        if self._client_config is None:
+            raise TypeError(
+                "Cannot pickle an AerospikeBasePersister without reconnectable 
client configuration"
+            )
+        state = self.__dict__.copy()
+        del state["_client"]
+        del state["_tail_hints"]
+        del state["_tail_hints_lock"]
+        state["_initialized"] = False
+        state["_closed"] = False
+        return state
+
+    def __setstate__(self, state: dict):
+        client_config = state.get("_client_config")
+        if client_config is None:
+            raise TypeError(
+                "Cannot unpickle an AerospikeBasePersister without client 
configuration"
+            )
+        self.__dict__.update(state)
+        try:
+            self._client = aerospike.client(client_config)
+        except Exception as e:
+            raise AerospikePersistenceError(
+                f"Failed to reconnect Aerospike client from configuration: {e}"
+            ) from e
+        self._owned = True
+        self._initialized = False
+        self._closed = False
+        self._tail_hints = OrderedDict()
+        self._tail_hints_lock = threading.Lock()
+
+    def set_serde_kwargs(self, serde_kwargs: dict):
+        self.serde_kwargs = serde_kwargs
+
+    def initialize(self):
+        """Mark the dynamically provisioned persister ready for use."""
+        self._initialized = True
+
+    def is_initialized(self) -> bool:
+        return self._initialized
+
+    def save(
+        self,
+        partition_key: Optional[str],
+        app_id: str,
+        sequence_id: int,
+        position: str,
+        state: state.State,
+        status: str,
+        **kwargs,
+    ):
+        self._validate_sequence_id(sequence_id)
+
+        try:
+            state_json = json.dumps(state.serialize(**self.serde_kwargs), 
allow_nan=False)
+        except (TypeError, ValueError) as e:
+            raise AerospikePersistenceSerializationError(
+                f"State is not JSON-serializable: {e}"
+            ) from e
+        created_at = 
datetime.now(timezone.utc).isoformat(timespec="microseconds")
+
+        key_prefix = self.key_prefix
+        partition_canonical = self._canonical_partition(partition_key)
+        key_prefix_canonical = self._canonical_key_prefix()
+        membership_key = self._key(
+            self.membership_set,
+            self._derive_membership_key(key_prefix, partition_key),
+        )
+
+        history_key = self._key(
+            self.history_set,
+            self._derive_history_key(key_prefix, partition_key, app_id, 
sequence_id),
+        )
+        head_key = self._key(
+            self.head_set,
+            self._derive_head_key(key_prefix, partition_key, app_id),
+        )
+
+        history_bins = {
+            _PART_BIN: partition_canonical,
+            _PREFIX_BIN: key_prefix_canonical,
+            _APP_BIN: app_id,
+            _SEQ_BIN: sequence_id,
+            _POS_BIN: position,
+            _STATE_BIN: state_json,
+            _STATUS_BIN: status,
+            _CREATED_BIN: created_at,
+        }
+
+        # History must exist before the head can be advanced.
+        self._write_history(history_key, history_bins)
+
+        head_bins = {
+            _PART_BIN: partition_canonical,
+            _PREFIX_BIN: key_prefix_canonical,
+            _APP_BIN: app_id,
+            _SEQ_BIN: sequence_id,
+        }
+        _, membership_registered = self._advance_head(head_key, head_bins)
+        if membership_registered is not True:
+            self._register_membership(membership_key, partition_key, app_id)
+            self._confirm_membership(
+                head_key,
+                partition_canonical,
+                key_prefix_canonical,
+                app_id,
+            )
+
+    def load(
+        self,
+        partition_key: Optional[str],
+        app_id: Optional[str],
+        sequence_id: Optional[int] = None,
+        **kwargs,
+    ) -> Optional[persistence.PersistedStateData]:
+        if app_id is None:
+            raise ValueError("app_id is required for load")
+        if sequence_id is not None:
+            self._validate_sequence_id(sequence_id)
+
+        if sequence_id is None:
+            return self._load_latest(partition_key, app_id)
+
+        # Exact-sequence load.
+        key_prefix = self.key_prefix
+        partition_canonical = self._canonical_partition(partition_key)
+        key_prefix_canonical = self._canonical_key_prefix()
+        history_key = self._key(
+            self.history_set,
+            self._derive_history_key(key_prefix, partition_key, app_id, 
sequence_id),
+        )
+        history_record = self._read_history(history_key)
+        if history_record is None:
+            return None
+        self._validate_history_identity(
+            history_record, partition_canonical, key_prefix_canonical, app_id, 
sequence_id
+        )
+        return self._build_persisted_data(history_record, partition_key, 
app_id, sequence_id)
+
+    def _load_latest(
+        self,
+        partition_key: Optional[str],
+        app_id: str,
+    ) -> Optional[persistence.PersistedStateData]:
+        """Load the latest state for an application by reading the head, then 
the referenced history."""
+        key_prefix = self.key_prefix
+        partition_canonical = self._canonical_partition(partition_key)
+        key_prefix_canonical = self._canonical_key_prefix()
+        head_key = self._key(
+            self.head_set,
+            self._derive_head_key(key_prefix, partition_key, app_id),
+        )
+        head_record = self._read_head(head_key)
+        if head_record is None:
+            return None
+        stored_seq, _ = self._validate_head_identity(
+            head_record,
+            partition_canonical,
+            key_prefix_canonical,
+            app_id,
+        )
+        history_key = self._key(
+            self.history_set,
+            self._derive_history_key(key_prefix, partition_key, app_id, 
stored_seq),
+        )
+        history_record = self._read_history(history_key)
+        if history_record is None:
+            raise AerospikePersistenceConsistencyError(
+                f"Head for app_id={app_id} references missing history sequence 
{stored_seq}"
+            )
+        self._validate_history_identity(
+            history_record, partition_canonical, key_prefix_canonical, app_id, 
stored_seq
+        )
+        return self._build_persisted_data(history_record, partition_key, 
app_id, stored_seq)
+
+    def list_app_ids(self, partition_key: Optional[str], **kwargs) -> 
list[str]:
+        membership_key = self._membership_page_key(partition_key, 0)
+        root = self._read_membership_root(membership_key)
+        if root is None:
+            return []
+        app_ids, tail_page = root
+        if tail_page == 0:
+            return list(app_ids)
+        combined = set(app_ids)
+        for first_page in range(1, tail_page + 1, _MEMBERSHIP_BATCH_SIZE):
+            keys = [
+                self._membership_page_key(partition_key, page)
+                for page in range(
+                    first_page,
+                    min(first_page + _MEMBERSHIP_BATCH_SIZE, tail_page + 1),
+                )
+            ]
+            try:
+                results = self._client.batch_read(
+                    keys,
+                    bins=[_APPS_BIN],
+                    policy={"replica": aerospike.POLICY_REPLICA_MASTER},
+                )
+            except aerospike.exception.AerospikeError as e:
+                raise AerospikePersistenceError(f"Membership batch read 
failed: {e}") from e
+            membership_pages = results.batch_records
+            if len(membership_pages) != len(keys):
+                raise AerospikePersistenceConsistencyError("Membership batch 
read was incomplete")
+            for membership_page in membership_pages:
+                if membership_page.result == _RECORD_NOT_FOUND_CODE:
+                    continue
+                if membership_page.result != 0:
+                    raise AerospikePersistenceError(
+                        f"Membership batch entry failed with result code 
{membership_page.result}"
+                    )
+                if membership_page.record is None:
+                    raise AerospikePersistenceConsistencyError(
+                        "Successful membership batch entry lacks a record"
+                    )
+                
combined.update(self._validate_membership_map(membership_page.record[2]))
+        return list(combined)
+
+    def _canonical_json(self, value: Any) -> str:
+        """Deterministic JSON encoding used for canonical identities and state 
snapshots."""
+        return json.dumps(
+            value,
+            sort_keys=True,
+            separators=(",", ":"),
+            ensure_ascii=False,
+            allow_nan=False,
+        )
+
+    def _identity_history(
+        self, key_prefix: Optional[str], partition_key: Optional[str], app_id: 
str, sequence_id: int
+    ) -> list:
+        return [
+            _SYSTEM,
+            _CODE_VERSION,
+            "history",
+            key_prefix,
+            partition_key,
+            app_id,
+            sequence_id,
+        ]
+
+    def _identity_head(
+        self, key_prefix: Optional[str], partition_key: Optional[str], app_id: 
str
+    ) -> list:
+        return [
+            _SYSTEM,
+            _CODE_VERSION,
+            "head",
+            key_prefix,
+            partition_key,
+            app_id,
+        ]
+
+    def _identity_membership(self, key_prefix: Optional[str], partition_key: 
Optional[str]) -> list:
+        return [
+            _SYSTEM,
+            _CODE_VERSION,
+            "membership",
+            key_prefix,
+            partition_key,
+        ]
+
+    def _identity_membership_page(
+        self, key_prefix: Optional[str], partition_key: Optional[str], page: 
int
+    ) -> list:
+        return [
+            _SYSTEM,
+            _CODE_VERSION,
+            "membership-page",
+            key_prefix,
+            partition_key,
+            page,
+        ]

Review Comment:
   Have added _normalize_partition_key at line 537, which is called at 
save/load/list_app_ids entry points. Strengthened the type checking here to 
match. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to