Skip to content

mongrator.state

mongrator.state

Migration state storage: Protocol definitions and sync/async implementations.

The tracking collection stores one document per applied migration::

{
    "_id": "20260408_143022_add_users_email_index",
    "applied_at": ISODate("2026-04-08T14:30:22Z"),
    "checksum": "e3b0c44298fc1c149afb...",
    "direction": "up",
    "duration_ms": 42
}

StateStore

Bases: Protocol

Synchronous migration state store.

Source code in src/mongrator/state.py
31
32
33
34
35
36
37
38
39
40
41
@runtime_checkable
class StateStore(Protocol):
    """Synchronous migration state store."""

    def get_applied(self) -> set[MigrationId]: ...

    def record_applied(self, record: MigrationRecord) -> None: ...

    def remove_record(self, migration_id: MigrationId) -> None: ...

    def get_record(self, migration_id: MigrationId) -> MigrationRecord | None: ...

AsyncStateStore

Bases: Protocol

Asynchronous migration state store.

Source code in src/mongrator/state.py
44
45
46
47
48
49
50
51
52
53
54
@runtime_checkable
class AsyncStateStore(Protocol):
    """Asynchronous migration state store."""

    async def get_applied(self) -> set[MigrationId]: ...

    async def record_applied(self, record: MigrationRecord) -> None: ...

    async def remove_record(self, migration_id: MigrationId) -> None: ...

    async def get_record(self, migration_id: MigrationId) -> MigrationRecord | None: ...

SyncStateStore

StateStore backed by a synchronous pymongo collection.

Source code in src/mongrator/state.py
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
class SyncStateStore:
    """StateStore backed by a synchronous pymongo collection."""

    def __init__(self, collection: "Collection") -> None:  # type: ignore[type-arg]
        self._col = collection

    def get_applied(self) -> set[MigrationId]:
        return {doc["_id"] for doc in self._col.find({"direction": "up"}, {"_id": 1})}

    def record_applied(self, record: MigrationRecord) -> None:
        self._col.replace_one({"_id": record["_id"]}, record, upsert=True)

    def remove_record(self, migration_id: MigrationId) -> None:
        self._col.delete_one({"_id": migration_id})

    def get_record(self, migration_id: MigrationId) -> MigrationRecord | None:
        return self._col.find_one({"_id": migration_id})  # type: ignore[return-value]

AsyncMongoStateStore

AsyncStateStore backed by a pymongo AsyncCollection.

Source code in src/mongrator/state.py
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
class AsyncMongoStateStore:
    """AsyncStateStore backed by a pymongo AsyncCollection."""

    def __init__(self, collection: "AsyncCollection") -> None:  # type: ignore[type-arg]
        self._col = collection

    async def get_applied(self) -> set[MigrationId]:
        cursor = self._col.find({"direction": "up"}, {"_id": 1})
        return {doc["_id"] async for doc in cursor}

    async def record_applied(self, record: MigrationRecord) -> None:
        await self._col.replace_one({"_id": record["_id"]}, record, upsert=True)

    async def remove_record(self, migration_id: MigrationId) -> None:
        await self._col.delete_one({"_id": migration_id})

    async def get_record(self, migration_id: MigrationId) -> MigrationRecord | None:
        return await self._col.find_one({"_id": migration_id})  # type: ignore[return-value]

SyncMigrationLock

Advisory lock using a document in the tracking collection.

Prevents concurrent migration runs. The lock expires automatically after a TTL to handle crashes or abandoned processes.

Source code in src/mongrator/state.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
class SyncMigrationLock:
    """Advisory lock using a document in the tracking collection.

    Prevents concurrent migration runs. The lock expires automatically
    after a TTL to handle crashes or abandoned processes.
    """

    def __init__(self, collection: "Collection") -> None:  # type: ignore[type-arg]
        self._col = collection

    def acquire(self) -> None:
        """Acquire the lock or raise MigrationLockError."""
        now = datetime.now(tz=UTC)
        try:
            result = self._col.find_one_and_update(
                {
                    "_id": _LOCK_ID,
                    "$or": [{"locked": False}, {"expires_at": {"$lt": now}}],
                },
                {
                    "$set": {
                        "locked": True,
                        "locked_by": f"{os.getpid()}@{platform.node()}",
                        "locked_at": now,
                        "expires_at": now + _LOCK_TTL,
                    },
                },
                upsert=True,
                return_document=True,
            )
        except DuplicateKeyError:
            raise MigrationLockError from None
        if result is None:
            raise MigrationLockError

    def release(self) -> None:
        """Release the lock."""
        self._col.update_one({"_id": _LOCK_ID}, {"$set": {"locked": False}})

    def __enter__(self) -> "SyncMigrationLock":
        self.acquire()
        return self

    def __exit__(self, *args: object) -> None:
        self.release()

acquire()

Acquire the lock or raise MigrationLockError.

Source code in src/mongrator/state.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
def acquire(self) -> None:
    """Acquire the lock or raise MigrationLockError."""
    now = datetime.now(tz=UTC)
    try:
        result = self._col.find_one_and_update(
            {
                "_id": _LOCK_ID,
                "$or": [{"locked": False}, {"expires_at": {"$lt": now}}],
            },
            {
                "$set": {
                    "locked": True,
                    "locked_by": f"{os.getpid()}@{platform.node()}",
                    "locked_at": now,
                    "expires_at": now + _LOCK_TTL,
                },
            },
            upsert=True,
            return_document=True,
        )
    except DuplicateKeyError:
        raise MigrationLockError from None
    if result is None:
        raise MigrationLockError

release()

Release the lock.

Source code in src/mongrator/state.py
131
132
133
def release(self) -> None:
    """Release the lock."""
    self._col.update_one({"_id": _LOCK_ID}, {"$set": {"locked": False}})

AsyncMigrationLock

Async advisory lock using a document in the tracking collection.

Source code in src/mongrator/state.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
class AsyncMigrationLock:
    """Async advisory lock using a document in the tracking collection."""

    def __init__(self, collection: "AsyncCollection") -> None:  # type: ignore[type-arg]
        self._col = collection

    async def acquire(self) -> None:
        """Acquire the lock or raise MigrationLockError."""
        now = datetime.now(tz=UTC)
        try:
            result = await self._col.find_one_and_update(
                {
                    "_id": _LOCK_ID,
                    "$or": [{"locked": False}, {"expires_at": {"$lt": now}}],
                },
                {
                    "$set": {
                        "locked": True,
                        "locked_by": f"{os.getpid()}@{platform.node()}",
                        "locked_at": now,
                        "expires_at": now + _LOCK_TTL,
                    },
                },
                upsert=True,
                return_document=True,
            )
        except DuplicateKeyError:
            raise MigrationLockError from None
        if result is None:
            raise MigrationLockError

    async def release(self) -> None:
        """Release the lock."""
        await self._col.update_one({"_id": _LOCK_ID}, {"$set": {"locked": False}})

    async def __aenter__(self) -> "AsyncMigrationLock":
        await self.acquire()
        return self

    async def __aexit__(self, *args: object) -> None:
        await self.release()

acquire() async

Acquire the lock or raise MigrationLockError.

Source code in src/mongrator/state.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
async def acquire(self) -> None:
    """Acquire the lock or raise MigrationLockError."""
    now = datetime.now(tz=UTC)
    try:
        result = await self._col.find_one_and_update(
            {
                "_id": _LOCK_ID,
                "$or": [{"locked": False}, {"expires_at": {"$lt": now}}],
            },
            {
                "$set": {
                    "locked": True,
                    "locked_by": f"{os.getpid()}@{platform.node()}",
                    "locked_at": now,
                    "expires_at": now + _LOCK_TTL,
                },
            },
            upsert=True,
            return_document=True,
        )
    except DuplicateKeyError:
        raise MigrationLockError from None
    if result is None:
        raise MigrationLockError

release() async

Release the lock.

Source code in src/mongrator/state.py
174
175
176
async def release(self) -> None:
    """Release the lock."""
    await self._col.update_one({"_id": _LOCK_ID}, {"$set": {"locked": False}})

make_record(migration_id, checksum, direction, duration_ms)

Construct a MigrationRecord with the current UTC timestamp.

Source code in src/mongrator/state.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
def make_record(
    migration_id: MigrationId,
    checksum: str,
    direction: Literal["up", "down"],
    duration_ms: int,
) -> MigrationRecord:
    """Construct a MigrationRecord with the current UTC timestamp."""
    return MigrationRecord(
        _id=migration_id,
        applied_at=datetime.now(tz=UTC),
        checksum=checksum,
        direction=direction,
        duration_ms=duration_ms,
    )