Skip to main content

ddaerospike

pypi downloads versions codecov license

Aerospike helpers: typed records, filters and a set manager on top of aerospike-native

Installation

Install the library using pip:

pip install ddaerospike

Development

The project runs entirely in Docker. Requires Docker and Fabric on the host:

fab build      # build the dev image
fab tests      # run pytest
fab linters    # run ruff (with --fix), ty and complexipy
fab shell      # IPython inside the container
fab bash       # bash inside the container

This project was generated from dd-lib-stub; run copier update to pull in template updates.

aerospike-native

The library sits on aerospike-native, the official Rust-core asyncio client. Two of its properties shape how the manager is wired: a client completes its futures on the event loop it was created in, so the factory behind client_factory keeps one client per process and loop; and on import it installs uvloop as the global event loop policy (AEROSPIKE_NO_UVLOOP=1 opts out), which importing ddaerospike therefore does too.

Errors come out as the client raises them: RecordNotFound, RecordExistsError and the other mapped errors subclass aerospike_native.exceptions.AerospikeError, a server code without a mapping arrives as aerospike_native.ServerError, which does not. "Any Aerospike error" is except (AerospikeError, ServerError).

AerospikeDsn

A settings field for a cluster: aerospike://host[:port][,host[:port]]/<namespace>, validated as a URL like pydantic's PostgresDsn. The hosts are the seeds the client learns the rest of the cluster from (a missing port is 3000), the path names the namespace and is required.

from pydantic_settings import BaseSettings

from ddaerospike.dsn import AerospikeDsn


class Settings(BaseSettings):
    AEROSPIKE_URL: AerospikeDsn  # AEROSPIKE_URL=aerospike://aerospike-0,aerospike-1/application


settings = Settings()
settings.AEROSPIKE_URL.seeds      # 'aerospike-0:3000,aerospike-1:3000', what `new_client` takes
settings.AEROSPIKE_URL.namespace  # 'application'

AerospikeData

A record of a set, every field a bin. Scalars and plain containers are simple bins; a BaseModel / RootModel field is a composite bin stored as a map or list. Datetimes are declared as AerospikeTimestamp: stored as integer microseconds since the epoch (UTC), read back as an aware datetime, and compared the same way by the filters; a bare datetime or date field is rejected at class definition, as is a bin name over 15 characters. Subclasses map to and from the domain through to_entity / from_entity.

from pydantic import BaseModel

from ddaerospike.data import AerospikeData, AerospikeTimestamp


class Address(BaseModel):
    city: str
    zip_code: str | None = None


class ProfileData(AerospikeData[Profile]):
    name: str
    age: int | None = None
    created_at: AerospikeTimestamp
    address: Address | None = None  # a composite bin

    def to_entity(self, **kwargs) -> Profile:
        return Profile(name=self.name, age=self.age, created_at=self.created_at)

    @classmethod
    def from_entity(cls, entity: Profile) -> 'ProfileData':
        return cls(name=entity.name, age=entity.age, created_at=entity.created_at)

AerospikeManager

ORM-like access to one set, typed by its AerospikeData model: get, get_map, get_list, find_one, put and delete. It is a Django-style manager, not a dddesign repository: a context repository owns one and maps records to entities. The client is obtained for every call from client_factory, a ConnectionManagerFactory from ddutils called with alias, the way a ddsql adapter runs a query inside factory(alias=...): the factory owns which cluster the alias means, the scope the client lives in (one per process and event loop, the client completes its futures on the loop it was created in), its lazy creation and its close on shutdown.

import asyncio
import os
from enum import Enum
from functools import partial

from aerospike_native import Client, ClientPolicy, new_client
from ddutils.connections import ConnectionManagerFactory
from ddutils.scoped_registry import ScopedRegistry

from ddaerospike.dsn import AerospikeDsn
from ddaerospike.manager import AerospikeManager


class AerospikeConnectionAlias(str, Enum):
    """The cluster to talk to; the alias resolves to its DSN, everything else derives from that."""

    PRIMARY = 'primary'

    @property
    def url(self) -> AerospikeDsn:
        return {AerospikeConnectionAlias.PRIMARY: settings.AEROSPIKE_URL}[self]

    @property
    def namespace(self) -> str:
        return self.url.namespace


async def create_client(alias: AerospikeConnectionAlias) -> Client:
    policy = ClientPolicy()
    policy.timeout = 5_000
    return await new_client(policy, alias.url.seeds)


def client_scope() -> tuple[int, asyncio.AbstractEventLoop]:
    return os.getpid(), asyncio.get_running_loop()


client_registries = {
    alias: ScopedRegistry[Client](
        create_func=partial(create_client, alias), scope_func=client_scope, destructor_method_name='close'
    )
    for alias in AerospikeConnectionAlias
}
aerospike_client_factory = ConnectionManagerFactory(client_registries, default=AerospikeConnectionAlias.PRIMARY)


class ProfileManager(AerospikeManager[ProfileData]):
    client_factory = aerospike_client_factory
    namespace = AerospikeConnectionAlias.PRIMARY.namespace
    set_name = 'profile'
    ttl_seconds = 30 * 24 * 60 * 60  # set by every write; None leaves the record's TTL alone
    # alias = AerospikeConnectionAlias.PRIMARY  # None picks the factory's default


profile_manager = ProfileManager()

await profile_manager.put(profile.id, ProfileData.from_entity(profile))
data = await profile_manager.get(profile.id)                       # ProfileData | None
await profile_manager.get_map([1, 2, 3])                           # {'1': ProfileData, ...}
await profile_manager.put(profile.id, data, if_absent=True)        # False when the record exists
await profile_manager.delete(profile.id)

await aerospike_client_factory.close()                             # on shutdown

A bin set to None is removed from the record by the write; inside a composite bin the None values are left out. The read_policy_fields, batch_policy_fields, query_policy_fields and write_policy_fields class attributes (typed dicts from ddaerospike.policies) override the defaults: short timeouts, retries on reads only, send_key on writes so queries can return the primary key. get_map holds what the batch read; a key it could not answer (a timeout, a node away) is left out like a missing one. get_list passes limit to the server as max_records and stops reading at exactly limit.

Filters

AerospikeFilterCollection(Model) holds the conditions of one query on a set, bound to its record model: at most one secondary-index filter (a query runs on one index: equality on int / str, a range on int) and any number of filter expressions, ANDed and evaluated on every record the index or the whole set yields. add_filter checks the bin against the model and the value against the bin's scalar (an int widens to a float bin); values are normalized the way the server compares them (enums to their value, UUIDs to strings, datetimes to AerospikeTimestamp microseconds, Decimal to float), and every operator checks the type it accepts. A composite bin only takes is_null / is_not_null, which take no value.

from ddaerospike.filters import AerospikeFilterCollection, AerospikeFilterOperator

filters = (
    AerospikeFilterCollection(ProfileData)
    .add_filter('name', AerospikeFilterOperator.EQUAL, 'john', use_index=True)   # needs an index on `name`
    .add_filter('age', AerospikeFilterOperator.BETWEEN, [18, 65])
    .add_filter('address', AerospikeFilterOperator.IS_NOT_NULL)
)

items = await profile_manager.get_list(filters, limit=100)   # [AerospikeDataWithPK(pk='1', data=ProfileData(...)), ...]
first = await profile_manager.find_one(filters)

AerospikeFeatureFlagStorage

The Aerospike backend of ddutils feature flags: one set, a flag per record (FeatureFlagData: enabled, proportion, payload bins, the flag name is the primary key), through an AerospikeManager[FeatureFlagData] the application wires. Client and server errors raise FeatureFlagStorageError, so FeatureFlags keeps serving the last known values; a record that does not validate is read as the defaults.

from ddaerospike.feature_flags import AerospikeFeatureFlagStorage, FeatureFlagData
from ddaerospike.manager import AerospikeManager
from ddutils.feature_flags import FeatureFlags


class FeatureFlagManager(AerospikeManager[FeatureFlagData]):
    client_factory = aerospike_client_factory
    namespace = settings.AEROSPIKE_URL.namespace
    set_name = 'feature_flag'


feature_flags = FeatureFlags(AerospikeFeatureFlagStorage(FeatureFlagManager()))

if await feature_flags.is_enabled('new_checkout'):            # proportion 1.0: on or off for everyone
    ...
if await feature_flags.is_enabled('new_ranking', user_id):  # on for `proportion` of the users
    ...

Metadata

Release files for ddaerospike 0.0.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ddaerospike 0.0.2
File Size Uploaded Provenance Actions
ddaerospike-0.0.2.tar.gz 16.4 kB With provenance Details for ddaerospike-0.0.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ddaerospike 0.0.2
File Interpreter ABI Platform Actions
ddaerospike-0.0.2-py3-none-any.whl Python 3 none any Details for ddaerospike-0.0.2-py3-none-any.whl

Total release size: 36.4 kB

Release files / ddaerospike-0.0.2.tar.gz

Download URL ddaerospike-0.0.2.tar.gz
Size 16.4 kB
Tags Source
SHA-256 checksum
How to use checksums
56efd42a8c08cc785ca4680f21a5be65fa5df0b873e423454da2a6d991552d5f
BLAKE2b-256 checksum
How to use checksums
1fba7158fa91cc1fc4a05f13db4918f8d33c8bfc20f1747e09bafcab763ebfb9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 18, 2026.

Transparency log

Release files / ddaerospike-0.0.2-py3-none-any.whl

Download URL ddaerospike-0.0.2-py3-none-any.whl
Size 20.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ceadbd71e97aaecc960793ab69c8d69146c6c5925caa3cd40f6e5b21b33e9b01
BLAKE2b-256 checksum
How to use checksums
33fa0ed508ea77b29d6a0fbbbf0db8a58762bb98b9f3248e1edd795f407f4fd1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 18, 2026.

Transparency log

Security for ddaerospike 0.0.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for ddaerospike-0.0.2.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 18, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page