Transactional Outbox cho đơn đã lưu

Đơn đã lưu nhưng Worker dừng trước khi gửi xác nhận. Nếu việc gửi đã được lưu cùng đơn hàng trong cơ sở dữ liệu, Worker mới có thể đọc và gửi tiếp.

Lưu đơn và việc gửi cùng nhau

Checkout ghi đơn
Bắt đầu giao dịch → ghi order-42 vào bảng đơn và confirm:order-42 vào bảng outbox → commit → trả kết quả đã lưu đơn
Worker gửi xác nhận
Đọc việc pending đã commit → gửi mã công việc và mã đơn → bên nhận ghi xác nhận → Worker đánh dấu done sau khi nhận phản hồi thành công

Outbox là bảng việc cần gửi của ứng dụng. Nếu giao dịch bị hủy, cả đơn lẫn việc gửi đều không được lưu. Nếu giao dịch thành công, trạng thái đơn đã lưu và xác nhận đã được gửi là 2 mốc riêng.

Gửi tiếp khi Worker khởi động lại

Nếu Worker dừng trước khi gửi, việc confirm:order-42 vẫn ở trạng thái pending. Worker mới đọc lại bản ghi đã commit và gửi cùng mã công việc. Khi dùng target như notifications.confirm, CoAkka Runtime chuyển lời gọi và trả kết quả giao nhận. Ứng dụng quản lý bảng outbox và cập nhật trạng thái dựa trên phản hồi từ bên nhận.

Worker dừng ở đâu? Dữ liệu còn lại Worker mới làm gì?
Trước khi gửi Đơn đã lưu, việc còn pending, chưa có xác nhận. Đọc lại việc và gửi với mã đã lưu.
Sau khi bên nhận commit, trước khi đánh dấu done Việc còn pending. Bên nhận đã ghi xác nhận. Gửi lại cùng mã. Bên nhận trả thành công cho xác nhận đã ghi.
Sau khi đánh dấu done Việc đã hoàn tất. Bỏ qua việc này khi đọc danh sách chờ.

Nếu lời gọi timeout, Worker chưa biết bên nhận đã ghi hay chưa. Giữ việc để xử lý tiếp, đọc lý do lỗi và dùng lại mã công việc ở lần gửi sau. Mỗi lần gửi có thể có mã yêu cầu khác. Tra timeout và Deadletter.

Tránh xử lý trùng

Bên nhận đặt ràng buộc duy nhất cho mã công việc confirm:order-42. Trong ví dụ, dòng thông báo xác nhận cũng là bằng chứng đã xử lý mã đó. Nếu lưu dấu đã xử lý ở bảng riêng, ghi dấu và thay đổi nghiệp vụ trong cùng một giao dịch. Trả thành công sau khi commit. Nếu mã đã được ghi cho cùng một việc, trả thành công mà không ghi thêm xác nhận.

Nếu gửi email qua nhà cung cấp

Một giao dịch cơ sở dữ liệu chỉ bảo vệ việc ghi vào cơ sở dữ liệu đó. Nếu nhà cung cấp có khóa chống gửi lặp, gửi cùng khóa và kiểm tra thời hạn áp dụng của khóa. Khi chưa biết email đã được chấp nhận hay chưa, đối soát trạng thái gửi nếu nhà cung cấp cho phép. Khi thiếu cả 2 khả năng, lần gửi lại có thể tạo thêm email.

Nếu chạy nhiều Worker

Ghi quyền xử lý có thời hạn cho một Worker bằng một giao dịch ngắn rồi mới gửi. Chỉ Worker đang giữ quyền mới được đánh dấu hoàn tất. Khi quyền hết hạn, Worker khác có thể nhận lại việc. Bên nhận vẫn kiểm tra mã công việc vì Worker cũ có thể đã gửi ngay trước khi hết hạn.

Chạy thử 2 lần Worker dừng

Bài thử dùng Python và 2 cơ sở dữ liệu SQLite tạm trên máy local. Một tiến trình Worker mô phỏng lời gọi đến bên nhận bằng cách ghi vào cơ sở dữ liệu thứ hai. Sao chép tệp dưới đây rồi chạy.

Mã Python · tạo đơn, dừng Worker và gửi tiếp
transactional_outbox.py
"""Run both outbox recovery cases locally with two SQLite databases."""

from contextlib import closing, contextmanager
import os
from pathlib import Path
import sqlite3
import subprocess
import sys
from tempfile import TemporaryDirectory


WORKER_STOPPED = 75


@contextmanager
def transaction(path):
    with closing(sqlite3.connect(path)) as db:
        with db:
            yield db


def create_tables(root):
    with transaction(root / "checkout.db") as db:
        db.execute("CREATE TABLE orders (order_id TEXT PRIMARY KEY)")
        db.execute("""
            CREATE TABLE outbox (
                work_id TEXT PRIMARY KEY,
                order_id TEXT NOT NULL,
                state TEXT NOT NULL DEFAULT 'pending'
            )
        """)
    with transaction(root / "notifications.db") as db:
        db.execute("""
            CREATE TABLE confirmations (
                work_id TEXT PRIMARY KEY,
                order_id TEXT NOT NULL
            )
        """)


def save_order(root, order_id):
    # Commit the order and the work to publish it together.
    with transaction(root / "checkout.db") as db:
        db.execute("INSERT INTO orders VALUES (?)", (order_id,))
        db.execute(
            "INSERT INTO outbox (work_id, order_id) VALUES (?, ?)",
            (f"confirm:{order_id}", order_id),
        )


def accept_confirmation(root, work_id, order_id):
    with transaction(root / "notifications.db") as db:
        # This row is both the customer's confirmation and the deduplication record.
        db.execute(
            """INSERT INTO confirmations VALUES (?, ?)
               ON CONFLICT(work_id) DO NOTHING""",
            (work_id, order_id),
        )
        saved_order = db.execute(
            "SELECT order_id FROM confirmations WHERE work_id = ?", (work_id,)
        ).fetchone()
        if saved_order != (order_id,):
            raise ValueError("Work ID was already used for a different order")
    # The receiver returns success only after its transaction has committed.


def dispatch_one(root, stop_at):
    with transaction(root / "checkout.db") as db:
        job = db.execute("""
            SELECT work_id, order_id FROM outbox
            WHERE state = 'pending' ORDER BY work_id LIMIT 1
        """).fetchone()
    if job is None:
        return

    # Exit the Worker process without running any further application code.
    if stop_at == "before-send":
        os._exit(WORKER_STOPPED)
    work_id, order_id = job
    accept_confirmation(root, work_id, order_id)
    if stop_at == "after-receive":
        os._exit(WORKER_STOPPED)

    with transaction(root / "checkout.db") as db:
        db.execute("UPDATE outbox SET state = 'done' WHERE work_id = ?", (work_id,))


def run_worker(root, stop_at, expected_exit):
    result = subprocess.run(
        [sys.executable, str(Path(__file__).resolve()), "--worker", str(root), stop_at],
        timeout=10,
        check=False,
    )
    if result.returncode != expected_exit:
        raise RuntimeError(f"Worker exited with {result.returncode}, expected {expected_exit}")


def check_state(root, order_id, expected_state, expected_count):
    with transaction(root / "checkout.db") as db:
        saved = db.execute("""
            SELECT outbox.state FROM orders JOIN outbox USING (order_id)
            WHERE orders.order_id = ?
        """, (order_id,)).fetchone()
    with transaction(root / "notifications.db") as db:
        count, = db.execute(
            "SELECT COUNT(*) FROM confirmations WHERE order_id = ?", (order_id,)
        ).fetchone()
    if saved != (expected_state,) or count != expected_count:
        raise RuntimeError(f"{order_id}: unexpected outbox state {saved}, confirmations={count}")


def run_demo():
    with TemporaryDirectory(prefix="coakka-outbox-") as directory:
        root = Path(directory)
        create_tables(root)

        save_order(root, "order-42")
        run_worker(root, "before-send", WORKER_STOPPED)
        check_state(root, "order-42", "pending", 0)
        print("order-42: worker stopped before send, pending, confirmations=0")
        run_worker(root, "none", 0)
        check_state(root, "order-42", "done", 1)
        print("order-42: worker resumed, done, confirmations=1")

        save_order(root, "order-43")
        run_worker(root, "after-receive", WORKER_STOPPED)
        check_state(root, "order-43", "pending", 1)
        print("order-43: receiver committed, worker stopped, pending, confirmations=1")
        run_worker(root, "none", 0)
        check_state(root, "order-43", "done", 1)
        print("order-43: same work ID retried, done, confirmations=1")


if __name__ == "__main__":
    if len(sys.argv) == 4 and sys.argv[1] == "--worker":
        dispatch_one(Path(sys.argv[2]), sys.argv[3])
    elif len(sys.argv) == 1:
        run_demo()
    else:
        raise SystemExit("Usage: python3 transactional_outbox.py")
Chạy bài thử
python3 transactional_outbox.py

Kết quả mong đợi

order-42: worker stopped before send, pending, confirmations=0
order-42: worker resumed, done, confirmations=1
order-43: receiver committed, worker stopped, pending, confirmations=1
order-43: same work ID retried, done, confirmations=1

Đơn order-42 có một xác nhận sau khi Worker mới gửi tiếp. Đơn order-43 vẫn chỉ có một xác nhận dù cùng mã được gửi lại. Chương trình xóa 2 cơ sở dữ liệu tạm khi chạy xong.

Tài liệu tham khảo