Backend Plugin System
The Netherframe backend plugin system allows external packages to register backend implementations without nf.core having any knowledge of specific providers. This enables a truly extensible architecture where cloud provider packages can be developed and maintained independently.
Overview
The plugin system consists of several key components:
- Backend Registry (
BackendRegistry) - Central registry for backend implementations - Backend Factory (
create_backend) - Factory function for creating backend instances - Decorators - Convenient decorators for registering backends
- Auto-discovery - Automatic discovery of backend packages
Architecture
Backend Types
The system supports three types of backend registrations:
- Backend Constructs - Configuration classes that inherit from
Backend - State Backends - Storage classes that inherit from
StateBackend - Backend Factories - Factory functions that create
StateBackendinstances
For Terraform backend constructs, see docs/architecture/backend-construct-guide.md
for literal-only config requirements and dependency tracking tips.
Registry API
from nf.backends.aws import S3Backend
from nf.core.backends.backend_registry import BackendRegistry
def s3_factory_func(config: dict) -> S3Backend:
return S3Backend(bucket=config["bucket"], hybrid_mode=True)
# Register a backend construct class
BackendRegistry.register_backend_construct("s3", S3Backend, "nf.backends.aws")
# Register a state backend class
BackendRegistry.register_state_backend("s3", S3Backend, "nf.backends.aws")
# Register a factory function
BackendRegistry.register_backend_factory("s3", s3_factory_func, "nf.backends.aws")
Decorators
For convenience, decorators are provided:
from nf.backends.aws import S3Backend
from nf.core.backends.backend_registry import backend_construct, state_backend
@backend_construct("s3-copy")
@state_backend("s3-copy")
class S3CopyBackend(S3Backend):
"""A backend that is both a configuration construct and a state implementation."""
Creating a Backend Package
To create a new backend package (e.g., for Google Cloud Storage):
1. Package Structure
netherframe.backends.gcp/
├── pyproject.toml
├── netherframe/
│ └── backends/
│ └── gcp/
│ ├── __init__.py
│ ├── gcs_backend.py
│ └── gcs_state.py
2. Implement Backend Classes
# gcs_backend.py
from nf.core import App, Stack
from nf.core.backends.backend_registry import BackendRegistry, backend_construct
from nf.core.constructs import Backend
@backend_construct("gcs")
class GCSBackend(Backend):
def __init__(self, *, nf_scope, nf_id, bucket, prefix, **kwargs):
super().__init__(nf_scope=nf_scope, nf_id=nf_id, bucket=bucket, prefix=prefix, **kwargs)
@property
def backend_type(self) -> str:
return "gcs"
def to_hcl(self) -> dict:
return {
"bucket": self.bucket,
"prefix": self.prefix,
}
# The decorator registered it, so the registry creates it by type
stack = Stack(nf_scope=App(nf_id="app"), nf_id="main")
backend = BackendRegistry.create_backend_construct("gcs", nf_scope=stack, nf_id="backend", bucket="state", prefix="prod")
assert backend.to_hcl() == {"bucket": "state", "prefix": "prod"}
# gcs_state.py
from typing import Any
from nf.core.backends.backend_registry import BackendRegistry, state_backend
from nf.core.backends.state_backend import StateBackend
from nf.core.backends.state_models import State
@state_backend("gcs")
class GCSStateBackend(StateBackend):
def __init__(self, bucket, prefix, **kwargs):
self.bucket = bucket
self.prefix = prefix
self._state = State() # stands in for the object in GCS
def get_backend_type(self) -> str:
return "gcs"
def get_config(self) -> dict[str, Any]:
return {"bucket": self.bucket, "prefix": self.prefix}
def load(self) -> State:
# Load state from GCS
return self._state
def save(self, state: State) -> None:
# Save state to GCS
self._state = state
def lock(self, info: dict[str, Any]) -> bool:
# Take a lock in GCS; False when another run holds it
return True
def unlock(self) -> None:
# Release the lock
pass
backend = BackendRegistry.create_state_backend("gcs", {"bucket": "state", "prefix": "prod"})
assert backend.get_backend_type() == "gcs"
A state backend implements load, save, lock, unlock, get_backend_type and get_config;
registration fails when one is missing. StateBackend has more optional methods (conditional
writes, checkpoints, run status), documented on the class.
3. Register on Import
# __init__.py
from .gcs_backend import GCSBackend
from .gcs_state import GCSStateBackend
# Registration happens automatically via decorators
# Or you can register explicitly:
from nf.core.backends.backend_registry import BackendRegistry
BackendRegistry.register_backend_construct("gcs", GCSBackend, "nf.backends.gcp")
BackendRegistry.register_state_backend("gcs", GCSStateBackend, "nf.backends.gcp")
4. Entry Points (Optional)
For more control, use Python entry points in pyproject.toml:
[project.entry-points."netherframe.backends"]
gcs = "nf.backends.gcp:register_backends"
Using Backends
Factory Function
The recommended way to create backends:
from nf.core import App, Stack
from nf.core.backends.backend_registry import BackendRegistry
stack = Stack(nf_scope=App(nf_id="app"), nf_id="main")
backend = BackendRegistry.create_backend_construct("s3", nf_scope=stack, nf_id="backend", bucket="my-state-bucket", key="terraform.tfstate")
Direct Import
If the package is installed, you can import directly:
from nf.backends.aws import S3Backend
from nf.core import App, Stack
stack = Stack(nf_scope=App(nf_id="app"), nf_id="main")
backend = S3Backend(nf_scope=stack, nf_id="backend", bucket="my-state-bucket", key="terraform.tfstate")
Checking Availability
from nf.core.backends.backend_registry import BackendRegistry
# Check if a specific backend is available
if BackendRegistry.is_backend_available("s3"):
# Create S3 backend
pass
# List all available backends
backends = BackendRegistry.list_registered_backends()
for backend_type, info in backends.items():
print(f"{backend_type}: {info}")
Auto-Discovery
The system automatically attempts to discover backends when requested:
- First checks if the backend is already registered
- If not found, tries to import common package patterns:
netherframe.backends.{backend_type}nf_backends_{backend_type}andnetherframe_backends_{backend_type}- Provider-specific mappings (e.g., "s3" → "netherframe.backends.aws")
State Engine Integration
The state engine automatically uses the registry:
from nf.core.backends.state_engine import BackendType, S3BackendConfig, StateEngine
# This will use BackendRegistry.create_state_backend internally
# (it reads and writes only when the engine loads or saves state)
engine = StateEngine(
BackendType.S3,
S3BackendConfig(
bucket="my-state-bucket",
key="terraform.tfstate",
region="us-east-1",
),
)
Example: AWS S3 Backend
Here's how the AWS backend package uses the plugin system:
# netherframe.backends.aws/netherframe/backends/aws/__init__.py
from typing import Any
from netherframe.backends.aws.s3 import S3Backend
from netherframe.backends.aws.s3_backend_bootstrap import S3BackendBootstrapper
from netherframe.core.backends.backend_bootstrap import BackendBootstrapManager
from netherframe.core.backends.backend_registry import BackendRegistry
def _s3_backend_factory(config: dict[str, Any]) -> S3Backend:
"""Factory function for creating S3Backend instances."""
return S3Backend(
bucket=config["bucket"],
key=config.get("key", "terraform.tfstate"),
region=config.get("region"),
dynamodb_table=config.get("dynamodb_table"),
encrypt=config.get("encrypt", True),
hybrid_mode=True,
)
def register_backends() -> None:
"""Register all components (the package calls this on import and as an entry point)."""
BackendBootstrapManager.register_bootstrapper("s3", S3BackendBootstrapper)
BackendRegistry.register_backend_construct("s3", S3Backend, "netherframe.backends.aws")
BackendRegistry.register_state_backend("s3", S3Backend, "netherframe.backends.aws")
# Optional: factory function
BackendRegistry.register_backend_factory("s3", _s3_backend_factory, "netherframe.backends.aws")
Benefits
- Decoupling - nf.core has no dependencies on specific cloud providers
- Extensibility - New backends can be added without modifying core
- Flexibility - Multiple implementations can exist for the same backend type
- Discovery - Backends are discovered automatically when packages are installed
- Type Safety - Full type checking and IDE support preserved
Migration Guide
If you have existing code using hardcoded backends:
from nf.core import App, Stack
stack = Stack(nf_scope=App(nf_id="app"), nf_id="main")
# Old way (requires nf.core to know about S3Backend)
from nf.backends.aws import S3Backend
backend = S3Backend(nf_scope=stack, nf_id="backend", bucket="my-state-bucket")
# New way (provider-agnostic)
from nf.core.backends.backend_registry import BackendRegistry
backend = BackendRegistry.create_backend_construct("s3", nf_scope=stack, nf_id="backend", bucket="my-state-bucket")
The old way still works if the package is installed, but the registry approach is more flexible and doesn't require compile-time knowledge of specific backend types.