authentik.root.db.router

 1from random import choice
 2
 3from django.conf import settings
 4from django.db import DEFAULT_DB_ALIAS, connections
 5
 6from authentik.lib.config import DIRECT_DB_ALIAS
 7
 8
 9class FailoverRouter:
10    """Primary/read-replica routing, with the ``direct`` alias (if configured)
11    excluded from replica selection, migrations, and automatic ORM routing.
12    The ``direct`` alias is opened explicitly via
13    ``connections.create_connection(DIRECT_DB_ALIAS)`` by code that needs a
14    stable PG backend (LISTEN/NOTIFY, advisory locks).
15    """
16
17    def __init__(self) -> None:
18        super().__init__()
19        self.database_aliases = set(settings.DATABASES.keys())
20        self.read_replica_aliases = list(
21            self.database_aliases - {DEFAULT_DB_ALIAS, DIRECT_DB_ALIAS}
22        )
23        self.replica_enabled = len(self.read_replica_aliases) > 0
24
25    def db_for_read(self, model, **hints):
26        if not self.replica_enabled:
27            return DEFAULT_DB_ALIAS
28        # Stay on primary for the entire transaction to maintain consistency.
29        # Reading from a replica mid-transaction would give a different snapshot,
30        # breaking transactional semantics (not just read-your-writes, but the
31        # entire consistent point-in-time view that a transaction provides).
32        if connections[DEFAULT_DB_ALIAS].in_atomic_block:
33            return DEFAULT_DB_ALIAS
34        # Read an instance's related objects (a prefetch, a related object, refresh_from_db)
35        # from the database the instance came from. Replicas lag by different amounts, so another
36        # one may not have the related rows yet, and an instance that was saved should see its
37        # own writes.
38        instance = hints.get("instance")
39        if instance is not None and (
40            instance._state.db == DEFAULT_DB_ALIAS
41            or instance._state.db in self.read_replica_aliases
42        ):
43            return instance._state.db
44        return choice(self.read_replica_aliases)  # nosec
45
46    def db_for_write(self, model, **hints):
47        return DEFAULT_DB_ALIAS
48
49    def allow_relation(self, obj1, obj2, **hints):
50        """Relations between objects are allowed if both objects are
51        in the primary/replica pool."""
52        if obj1._state.db in self.database_aliases and obj2._state.db in self.database_aliases:
53            return True
54        return None
55
56    def allow_migrate(self, db, app_label, model_name=None, **hints):
57        """Block migrations against the ``direct`` alias. It points at the same
58        underlying database as ``default``; migrations must run via ``default``
59        to avoid duplicate work and to avoid taking the migration advisory lock
60        against a transaction pooler that can't hold it."""
61        if db == DIRECT_DB_ALIAS:
62            return False
63        return None
class FailoverRouter:
10class FailoverRouter:
11    """Primary/read-replica routing, with the ``direct`` alias (if configured)
12    excluded from replica selection, migrations, and automatic ORM routing.
13    The ``direct`` alias is opened explicitly via
14    ``connections.create_connection(DIRECT_DB_ALIAS)`` by code that needs a
15    stable PG backend (LISTEN/NOTIFY, advisory locks).
16    """
17
18    def __init__(self) -> None:
19        super().__init__()
20        self.database_aliases = set(settings.DATABASES.keys())
21        self.read_replica_aliases = list(
22            self.database_aliases - {DEFAULT_DB_ALIAS, DIRECT_DB_ALIAS}
23        )
24        self.replica_enabled = len(self.read_replica_aliases) > 0
25
26    def db_for_read(self, model, **hints):
27        if not self.replica_enabled:
28            return DEFAULT_DB_ALIAS
29        # Stay on primary for the entire transaction to maintain consistency.
30        # Reading from a replica mid-transaction would give a different snapshot,
31        # breaking transactional semantics (not just read-your-writes, but the
32        # entire consistent point-in-time view that a transaction provides).
33        if connections[DEFAULT_DB_ALIAS].in_atomic_block:
34            return DEFAULT_DB_ALIAS
35        # Read an instance's related objects (a prefetch, a related object, refresh_from_db)
36        # from the database the instance came from. Replicas lag by different amounts, so another
37        # one may not have the related rows yet, and an instance that was saved should see its
38        # own writes.
39        instance = hints.get("instance")
40        if instance is not None and (
41            instance._state.db == DEFAULT_DB_ALIAS
42            or instance._state.db in self.read_replica_aliases
43        ):
44            return instance._state.db
45        return choice(self.read_replica_aliases)  # nosec
46
47    def db_for_write(self, model, **hints):
48        return DEFAULT_DB_ALIAS
49
50    def allow_relation(self, obj1, obj2, **hints):
51        """Relations between objects are allowed if both objects are
52        in the primary/replica pool."""
53        if obj1._state.db in self.database_aliases and obj2._state.db in self.database_aliases:
54            return True
55        return None
56
57    def allow_migrate(self, db, app_label, model_name=None, **hints):
58        """Block migrations against the ``direct`` alias. It points at the same
59        underlying database as ``default``; migrations must run via ``default``
60        to avoid duplicate work and to avoid taking the migration advisory lock
61        against a transaction pooler that can't hold it."""
62        if db == DIRECT_DB_ALIAS:
63            return False
64        return None

Primary/read-replica routing, with the direct alias (if configured) excluded from replica selection, migrations, and automatic ORM routing. The direct alias is opened explicitly via connections.create_connection(DIRECT_DB_ALIAS) by code that needs a stable PG backend (LISTEN/NOTIFY, advisory locks).

database_aliases
read_replica_aliases
replica_enabled
def db_for_read(self, model, **hints):
26    def db_for_read(self, model, **hints):
27        if not self.replica_enabled:
28            return DEFAULT_DB_ALIAS
29        # Stay on primary for the entire transaction to maintain consistency.
30        # Reading from a replica mid-transaction would give a different snapshot,
31        # breaking transactional semantics (not just read-your-writes, but the
32        # entire consistent point-in-time view that a transaction provides).
33        if connections[DEFAULT_DB_ALIAS].in_atomic_block:
34            return DEFAULT_DB_ALIAS
35        # Read an instance's related objects (a prefetch, a related object, refresh_from_db)
36        # from the database the instance came from. Replicas lag by different amounts, so another
37        # one may not have the related rows yet, and an instance that was saved should see its
38        # own writes.
39        instance = hints.get("instance")
40        if instance is not None and (
41            instance._state.db == DEFAULT_DB_ALIAS
42            or instance._state.db in self.read_replica_aliases
43        ):
44            return instance._state.db
45        return choice(self.read_replica_aliases)  # nosec
def db_for_write(self, model, **hints):
47    def db_for_write(self, model, **hints):
48        return DEFAULT_DB_ALIAS
def allow_relation(self, obj1, obj2, **hints):
50    def allow_relation(self, obj1, obj2, **hints):
51        """Relations between objects are allowed if both objects are
52        in the primary/replica pool."""
53        if obj1._state.db in self.database_aliases and obj2._state.db in self.database_aliases:
54            return True
55        return None

Relations between objects are allowed if both objects are in the primary/replica pool.

def allow_migrate(self, db, app_label, model_name=None, **hints):
57    def allow_migrate(self, db, app_label, model_name=None, **hints):
58        """Block migrations against the ``direct`` alias. It points at the same
59        underlying database as ``default``; migrations must run via ``default``
60        to avoid duplicate work and to avoid taking the migration advisory lock
61        against a transaction pooler that can't hold it."""
62        if db == DIRECT_DB_ALIAS:
63            return False
64        return None

Block migrations against the direct alias. It points at the same underlying database as default; migrations must run via default to avoid duplicate work and to avoid taking the migration advisory lock against a transaction pooler that can't hold it.