Adding a Custom Provider
Kirak uses a unified, modular provider architecture across all backend-driven modules: Payments, Storage, Notifications, Scheduler, and Vector.
While Kirak launches with an extensive initial set of built-in providers across each module, this is just the beginning. The provider architecture is designed as an open, continuously expanding ecosystem where the core team, enterprise developers, and community contributors can rapidly build, publish, and integrate new providers without touching Kirak’s core codebase.
This guide explains how Kirak’s provider lifecycle works and provides a step-by-step walkthrough for building, registering, and distributing custom providers.
Architectural Resolution Pipeline
Section titled “Architectural Resolution Pipeline”Kirak separates provider types (the underlying driver code) from instances (configured uses of that driver):
flowchart TD CALL["Operation Request<br/>(e.g. upload_image, charge)"] --> INSTANCE_NAME{"Instance Specified?<br/>payload.provider or default_provider"} INSTANCE_NAME --> RESOLVE_INST["Lookup in kirak.json<br/>module.providers[instance_name]"]
RESOLVE_INST --> CACHE{"Instance Object<br/>Already Cached in ProviderSet?"} CACHE -->|Yes| EXECUTE["Execute Provider Method"] CACHE -->|No| REGISTRY{"Lookup Provider Type in<br/>ProviderRegistry"}
REGISTRY -->|1. In-App Registration| CLASS_FOUND["Resolve Class"] REGISTRY -->|2. Built-in Catalog Specs| CLASS_FOUND REGISTRY -->|3. Setuptools Entry Points| CLASS_FOUND
CLASS_FOUND --> SECRETS["Inject Secrets from Environment<br/>PREFIX_INSTANCE_FIELD, e.g. KIRAK_STORAGE_MEDIA_SECRET_KEY"] SECRETS --> INIT["Instantiate Class<br/>Provider(config, module)"] INIT --> VERIFY["Run self._require() Guard"] VERIFY --> STORE_CACHE["Cache in ProviderSet"] STORE_CACHE --> EXECUTE- Type: The underlying implementation class (
aws_s3,stripe,sendgrid). Declared viaTYPE_NAME. - Instance: A named configuration in
kirak.json(e.g.s3_avatars,stripe_uk). Multiple instances can share the same provider type with different credentials. - Default Provider: Declared via
default_providerinkirak.json. Invoked whenever an operation does not explicitly designate a provider. - Lazy Loading: Provider code is only imported upon first invocation. Missing third-party SDKs never crash applications that do not use that provider.
Choose Your Integration Path
Section titled “Choose Your Integration Path”| Integration Path | Implementation Location | Discovery Mechanism | Use Case |
|---|---|---|---|
| 1. Single Application | Inside project repo (src/providers.py by default) |
Call register_provider in on_kirak_ready callback |
Custom proprietary backends or rapid prototyping |
| 2. Pip Package (Plugin) | Distributed via PyPI / Wheel | Declare setuptools entry points in pyproject.toml |
Open-source extensions or shared internal team libraries |
| 3. Kirak Core Contribution | Inside the kirak repository |
Add to kirak.catalog.specs and module provider package |
Contributing standard cloud or payment integrations |
Module Provider Registry Reference
Section titled “Module Provider Registry Reference”| Module | Base Class | Registration Function | Setuptools Entry Point Group | Environment Secret Prefix |
|---|---|---|---|---|
| Storage | StorageProvider |
kirak.storage.register_provider(type, cls) |
kirak.storage_providers |
KIRAK_STORAGE_<INSTANCE>_ |
| Payments | PaymentProvider |
kirak.payments.register_provider(type, cls) |
kirak.payment_providers |
KIRAK_PAYMENT_<INSTANCE>_ |
| Notifications (Email) | EmailProvider |
kirak.notifications.register_provider("email", type, cls) |
kirak.notifications_email_providers |
KIRAK_NOTIFICATION_EMAIL_<INSTANCE>_ |
| Notifications (SMS) | SMSProvider |
kirak.notifications.register_provider("sms", type, cls) |
kirak.notifications_sms_providers |
KIRAK_NOTIFICATION_SMS_<INSTANCE>_ |
| Notifications (Push) | PushProvider |
kirak.notifications.register_provider("push", type, cls) |
kirak.notifications_push_providers |
KIRAK_NOTIFICATION_PUSH_<INSTANCE>_ |
| Notifications (Chat/IM) | IMProvider |
kirak.notifications.register_provider("im", type, cls) |
kirak.notifications_im_providers |
KIRAK_NOTIFICATION_IM_<INSTANCE>_ |
| Notifications (Webhook) | WebhookProvider |
kirak.notifications.register_provider("webhook", type, cls) |
kirak.notifications_webhook_providers |
KIRAK_NOTIFICATION_WEBHOOK_<INSTANCE>_ |
| Scheduler | QueueBackend |
kirak.scheduler.register_provider(type, cls) |
kirak.scheduler_providers |
KIRAK_SCHEDULER_<INSTANCE>_ |
| Vector (Store) | VectorStoreProvider |
kirak.vector.register_provider("store", type, cls) |
kirak.vector_store_providers |
KIRAK_VECTOR_STORE_<INSTANCE>_ |
| Vector (Embedding) | EmbeddingProvider |
kirak.vector.register_provider("embedding", type, cls) |
kirak.vector_embedding_providers |
KIRAK_VECTOR_EMBEDDING_<INSTANCE>_ |
Provider Implementation Contract
Section titled “Provider Implementation Contract”Every custom provider class must inherit from the module’s abstract base class and adhere to the following contract:
from kirak.storage.providers.base import StorageProviderfrom kirak.core.exceptions import KirakException, ConfigurationErrorfrom typing import Any, Dict, Optional
class CustomStorageProvider(StorageProvider): # The identifier matching the "type" key in kirak.json TYPE_NAME: str = "custom_s3"
# Fields that MUST be read from environment variables (never in kirak.json) SECRET_FIELDS: tuple = ("secret_key",)
# Human-readable service label used in logs and check() outputs CHECK_LABEL: str = "Custom S3 Compatible Storage"
def __init__(self, config: Dict[str, Any], storage: Any = None): super().__init__(config, storage) # Fail fast if required configuration is missing self._require("endpoint_url", "bucket", "access_key", "secret_key")
async def upload(self, path: str, content: bytes, content_type: Optional[str] = None) -> Dict[str, Any]: """Upload raw bytes to destination path.""" ...
async def download(self, path: str) -> bytes: """Download file content as raw bytes.""" ...
async def delete(self, path: str) -> bool: """Delete file at path.""" ...
async def exists(self, path: str) -> bool: """Check if file exists.""" ...
async def get_url(self, path: str, expires: Optional[int] = None) -> str: """Return public URL or generate time-limited signed URL.""" ...
async def check(self) -> Dict[str, Any]: """Health check probe invoked by kirak check or monitoring.""" ...Core Requirements
Section titled “Core Requirements”TYPE_NAME: Lowercase alphanumeric string with underscores (^[a-z][a-z0-9_]*$). Matches the"type"field inkirak.json.SECRET_FIELDS: Tuple of configuration keys that hold secrets. Kirak automatically reads these from.envusing the uppercase format: $$\text{KIRAK__ _ }$$ If a developer attempts to write a secret field directly into kirak.json, Kirak’s manifest validator halts startup.self._require(*fields): Validates that required parameters are non-empty; raisesConfigurationErrorif missing.self.instance_name: Provides the instance name declared underkirak.json -> providers -> <instance_name>.- Structured Error Handling: Raise
KirakException(error="CODE", message="...", status_code=...)rather than returning error dictionaries or raising raw SDK exceptions.
Step-by-Step Tutorial: Building a Cloudflare R2 Provider
Section titled “Step-by-Step Tutorial: Building a Cloudflare R2 Provider”Below is a complete implementation of a Cloudflare R2 storage provider using boto3.
1. Write the Provider Class (providers/cloudflare_r2.py)
Section titled “1. Write the Provider Class (providers/cloudflare_r2.py)”import iofrom typing import Any, Dict, Optionalfrom kirak.storage.providers.base import StorageProviderfrom kirak.core.exceptions import KirakException, ConfigurationError
class CloudflareR2Provider(StorageProvider): TYPE_NAME = "cloudflare_r2" SECRET_FIELDS = ("secret_access_key",) CHECK_LABEL = "Cloudflare R2 Object Storage"
def __init__(self, config: Dict[str, Any], storage: Any = None): super().__init__(config, storage) self._require("account_id", "bucket", "access_key_id", "secret_access_key") self._client = None
def _get_client(self): if self._client is None: import boto3 from botocore.config import Config
endpoint_url = f"https://{self.config['account_id']}.r2.cloudflarestorage.com" self._client = boto3.client( "s3", endpoint_url=endpoint_url, aws_access_key_id=self.config["access_key_id"], aws_secret_access_key=self.config["secret_access_key"], config=Config(signature_version="s3v4"), region_name="auto", ) return self._client
async def upload(self, path: str, content: bytes, content_type: Optional[str] = None) -> Dict[str, Any]: client = self._get_client() extra_args = {} if content_type: extra_args["ContentType"] = content_type
try: client.upload_fileobj(io.BytesIO(content), self.config["bucket"], path, ExtraArgs=extra_args) return {"path": path, "size": len(content)} except Exception as exc: raise KirakException("STORAGE_UPLOAD_ERROR", f"Failed to upload to R2: {exc}", status_code=500)
async def download(self, path: str) -> bytes: client = self._get_client() buffer = io.BytesIO() try: client.download_fileobj(self.config["bucket"], path, buffer) return buffer.getvalue() except Exception as exc: raise KirakException("STORAGE_DOWNLOAD_ERROR", f"File not found or failed to read: {exc}", status_code=404)
async def delete(self, path: str) -> bool: client = self._get_client() try: client.delete_object(Bucket=self.config["bucket"], Key=path) return True except Exception: return False
async def exists(self, path: str) -> bool: client = self._get_client() try: client.head_object(Bucket=self.config["bucket"], Key=path) return True except Exception: return False
async def get_url(self, path: str, expires: Optional[int] = None) -> str: client = self._get_client() ttl = expires or self._signed_url_ttl() return client.generate_presigned_url( "get_object", Params={"Bucket": self.config["bucket"], "Key": path}, ExpiresIn=ttl, )
async def check(self) -> Dict[str, Any]: client = self._get_client() try: client.head_bucket(Bucket=self.config["bucket"]) return {"healthy": True, "message": "Connected successfully to R2 bucket"} except Exception as exc: return {"healthy": False, "message": str(exc)}2. Register the Provider
Section titled “2. Register the Provider”Option A: In One Application (src/)
Section titled “Option A: In One Application (src/)”Register the provider class from the on_kirak_ready callback. In a project made by kirak new, that is
register() in src/__init__.py, which main.py passes to create_kirak_app:
from src import hooksfrom src.providers import CloudflareR2Provider
def register(kirak): hooks.register(kirak) # Register under the TYPE_NAME kirak.storage.register_provider("cloudflare_r2", CloudflareR2Provider)Option B: Standalone Python Package (pyproject.toml)
Section titled “Option B: Standalone Python Package (pyproject.toml)”If publishing a reusable package (e.g. kirak-cloudflare-r2), declare the provider under setuptools entry points:
[project]name = "kirak-cloudflare-r2"version = "0.1.0"dependencies = [ "kirak>=1.0.0", "boto3>=1.34.0",]
[project.entry-points."kirak.storage_providers"]cloudflare_r2 = "kirak_cloudflare_r2:CloudflareR2Provider"Once installed via pip install kirak-cloudflare-r2, Kirak automatically detects and registers the provider.
3. Configure kirak.json and .env
Section titled “3. Configure kirak.json and .env”In kirak.json:
{ "storage": { "default_provider": "r2_assets", "providers": { "r2_assets": { "type": "cloudflare_r2", "account_id": "a1b2c3d4e5f6a7b8c9d0", "bucket": "my-production-bucket", "access_key_id": "9876543210abcdef" } } }}In .env:
KIRAK_STORAGE_R2_ASSETS_SECRET_ACCESS_KEY=your_cloudflare_r2_secret_key_hereTesting the Provider Class
Section titled “Testing the Provider Class”kirak.core.providers has a static conformance check for provider classes. It does not create an
instance or import the provider’s SDK, so it runs in any test environment:
| Function | Returns |
|---|---|
provider_problems(cls, base_class) |
A list of problems as strings; an empty list means the class conforms |
assert_provider_conforms(cls, base_class) |
Nothing; raises AssertionError listing every problem |
It checks that the class subclasses base_class, implements every abstract method, has a valid
TYPE_NAME, has SECRET_FIELDS as a tuple of non-empty strings that use no reserved config key,
has a constructor that accepts (config, module=None), and, when it has an EVENT_MAP, that the
map is a dict of strings to strings.
from kirak.core.providers import assert_provider_conformsfrom kirak.storage.providers.base import StorageProvider
from src.providers import CloudflareR2Provider
def test_r2_provider_conforms(): assert_provider_conforms(CloudflareR2Provider, StorageProvider)register_provider itself checks only the base class. A class that fails the other checks is
accepted there and fails later, when Kirak builds the instance or calls it, so run this check in
the provider’s tests.
Verifying Provider Health
Section titled “Verifying Provider Health”Verify that the custom provider is recognized, properly configured, and reachable:
# Verify environment variableskirak env
# Validate configurationkirak validate
# Check provider connectivitykirak providers storage cloudflare_r2