-
Notifications
You must be signed in to change notification settings - Fork 21
feat(state): add PostgresBackend, a state backend stored in the pgmq … #408
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mducros-wm
wants to merge
17
commits into
master
Choose a base branch
from
feat/pgmq-state-backend
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
3d8c8a8
feat(state): add PostgresBackend, a state backend stored in the pgmq …
mducros-wm 898792c
fix: code review
mducros-wm c2dff40
fix(postgres): validate queue names before they become SQL identifiers
mducros-wm 6aa8d69
fix(postgres): run the state patch on the broker's transaction, index…
mducros-wm e9eb62c
fix(state): drop a status naming a queue the broker never declared
mducros-wm d49b9c9
fix(state): keep the backends import alive when pgmq has no SQLAlchem…
mducros-wm d825a3a
fix(state): ignore a progress instead of refusing it, and fix stale docs
mducros-wm 6396c1f
refactor(state): require the message rather than patching by message id
mducros-wm 594401f
fix: code review
mducros-wm 06ef031
refactor(state): write the status by a query of its own
mducros-wm a1e5cb7
docs(changelog): cut the 7.1.0 entry down to feat/fix/breaking
mducros-wm 87c7876
style(state): mark PostgresBackend.set_state as an override
mducros-wm d187cba
fix: code review
mducros-wm dae039e
fix: code review
mducros-wm bf56883
fix: code review
mducros-wm 07836f3
fix: code review
mducros-wm 50a13ab
fix: code review
mducros-wm File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| # This file is a part of Remoulade. | ||
| # | ||
| # Copyright (C) 2026 WIREMIND SAS <dev@wiremind.io> | ||
| # | ||
| # Remoulade is free software; you can redistribute it and/or modify it | ||
| # under the terms of the GNU Lesser General Public License as published by | ||
| # the Free Software Foundation, either version 3 of the License, or (at | ||
| # your option) any later version. | ||
| # | ||
| # Remoulade is distributed in the hope that it will be useful, but WITHOUT | ||
| # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | ||
| # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public | ||
| # License for more details. | ||
| # | ||
| # You should have received a copy of the GNU Lesser General Public License | ||
| # along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
| """Remoulade's hand-written SQL on top of the PGMQ client. | ||
|
|
||
| Every statement remoulade writes itself lives here, so ``PostgresBroker`` and the | ||
| pgmq state backend never build SQL of their own. | ||
| """ | ||
|
|
||
| import json | ||
| from collections.abc import Iterator | ||
| from contextlib import contextmanager | ||
| from typing import Any | ||
|
|
||
| from pgmq import SQLAlchemyPGMQueue | ||
| from sqlalchemy import Connection, text | ||
|
|
||
| from ..actor import QUEUE_NAME_PATTERN | ||
|
|
||
| #: pgmq's own limit on a queue name. It also keeps the longest identifier remoulade | ||
| #: derives from one (``q_<queue>_msg_id_idx``) under PostgreSQL's 63-byte cap, past | ||
| #: which PostgreSQL truncates -- and two long queue names would collide on one index. | ||
| QUEUE_NAME_MAX_LENGTH = 47 | ||
|
|
||
|
|
||
| def assert_valid_queue_name(queue_name: str) -> None: | ||
| """Check that ``queue_name`` is safe to interpolate as a SQL identifier. | ||
|
|
||
| The character set is remoulade's own (:data:`~remoulade.actor.QUEUE_NAME_PATTERN`, | ||
| already enforced on every actor declaration), which holds nothing needing quotes | ||
| or escaping; only the length bound is specific to PostgreSQL. | ||
|
|
||
| Parameters: | ||
| queue_name(str): The name to check. | ||
|
|
||
| Raises: | ||
| ValueError: If the name does not match :data:`~remoulade.actor.QUEUE_NAME_PATTERN` | ||
| or is longer than :data:`QUEUE_NAME_MAX_LENGTH`. | ||
| """ | ||
| if not QUEUE_NAME_PATTERN.fullmatch(queue_name) or len(queue_name) > QUEUE_NAME_MAX_LENGTH: | ||
| raise ValueError( | ||
| f"{queue_name!r} is not a usable queue name for a PostgresBroker: it becomes a SQL identifier, so it " | ||
| f"must start with a letter or an underscore, hold only letters, digits, dashes, dots and underscores, " | ||
| f"and be at most {QUEUE_NAME_MAX_LENGTH} characters long." | ||
| ) | ||
|
|
||
|
|
||
| class RemouladePostgresClient(SQLAlchemyPGMQueue): | ||
| """A PGMQ client that also knows how to patch a remoulade message's headers. | ||
|
|
||
| Inherits the whole PGMQ surface (``send``, ``read``, ``archive``, | ||
| ``set_vt``, ``metrics``, ...) unchanged and adds the statements remoulade | ||
| needs on top of it. | ||
| """ | ||
|
|
||
| def create_indexes(self, queue_name: str, conn: Connection | None = None) -> None: | ||
|
mducros-wm marked this conversation as resolved.
|
||
| """Ensure the queue table carries the indexes remoulade needs. | ||
| Raises: | ||
| ValueError: If ``queue_name`` cannot be used as a SQL identifier. | ||
| """ | ||
| assert_valid_queue_name(queue_name) | ||
| with self._connection(conn) as connection: | ||
| connection.execute( | ||
| text(f'CREATE INDEX IF NOT EXISTS "q_{queue_name}_msg_id_idx" ON pgmq."q_{queue_name}" (msg_id)') | ||
| ) | ||
|
|
||
| def patch_headers(self, queue: str, msg_id: int, patch: dict[str, Any], conn: Connection | None = None) -> bool: | ||
| """Merge ``patch`` into an enqueued message's headers, key by key. | ||
|
|
||
| Only reaches a message still in ``pgmq.q_<queue>``; once archived, its | ||
| headers are out of reach. ``pgmq.archive`` carries them over. | ||
|
|
||
| Returns: | ||
| bool: Whether a row was patched. | ||
| """ | ||
| assert_valid_queue_name(queue) | ||
| statement = text(f""" | ||
| UPDATE pgmq."q_{queue}" | ||
| SET headers = coalesce(headers, '{{}}'::jsonb) || CAST(:patch AS jsonb) | ||
| WHERE msg_id = :msg_id | ||
| """) # noqa: S608 | ||
| return self._run(statement, {"msg_id": msg_id, "patch": json.dumps(patch)}, conn) > 0 | ||
|
|
||
| @contextmanager | ||
| def _connection(self, conn: Connection | None) -> Iterator[Connection]: | ||
| """Yield the caller's connection, or open a transaction of our own.""" | ||
| if conn is not None: | ||
| yield conn | ||
| return | ||
| with self.engine.begin() as connection: | ||
| yield connection | ||
|
|
||
| def _run(self, statement: Any, params: dict[str, Any], conn: Connection | None) -> int: | ||
| """Execute a write statement, returning the number of affected rows.""" | ||
| with self._connection(conn) as connection: | ||
| return connection.execute(statement, params).rowcount | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.