第195回 再送応答を一部だけ取り込まない:PythonとSQLiteで作る完全一致受信ゲート

第193回では欠番範囲から上限付きの再送要求を作り、第194回では送信元のSQLite保管庫から要求範囲だけを取り出しました。今回は受信側で、元の要求と再送応答を照合してからSQLiteへ保存します。

available応答では、要求したすべての連番が昇順でそろっている場合だけ、バッチ全体を一つのトランザクションで保存します。1件でも不足、余分、順序違い、ペイロード不一致があれば、どの行も保存しません。unavailable応答も状況報告にとどめ、データベースを更新しません。

今回のテーブルは受信ステージです。在庫数量や適用済み連番は更新しません。保存後のイベントは、第190回のような通常の並べ替え・重複防止処理へ渡します。

要求した連番と完全に一致させる

要求範囲が11~12と14~14なら、必要な連番は11、12、14です。第193回で要求件数を最大1000件に制限しているため、受信時はこの範囲だけを個別の連番へ展開して比較できます。

応答内容 判定 DB更新
11、12、14 accepted 3件をまとめて保存
11、14 12が不足 更新しない
11、12、13、14 13が要求外 更新しない
14、12、11 契約した昇順ではない 更新しない
連番は一致するが、ペイロード内の連番が異なる 包みと内容が不一致 更新しない
unavailableで12が欠落 再取得できない範囲を報告 更新しない
同じ要求と応答を再実行 already_accepted 重複保存しない
同じ要求IDで異なる内容 conflict 更新しない

応答内のrequest_sha256は、元の要求JSONをキー順、空白なし、UTF-8で直列化して計算します。これは本稿独自の正規化方法であり、一般的なJSON正規化規格ではありません。

SHA-256は送信者を認証しません。応答を変更できる主体は、ペイロードとハッシュを一緒に作り直せます。敵対的な書き換えを想定する場合は、認証済み通信や署名を別途用意してください。

今回の入出力契約

項目 仕様
動作環境 Python 3.10以上、標準ライブラリのみ
要求JSON UTF-8、最大64KiB、1~100範囲、合計1~1000件
応答JSON UTF-8、最大8MiB
ペイロード Base64復号後1~4096バイトのJSON
在庫イベント event_id、sku、sequence、quantityの4項目
識別子 ASCIIの英数字で始まり、英数字、ピリオド、アンダースコア、コロン、ハイフンで1~128文字
数量 0~1000000の整数。真偽値は不可
標準出力 結果を1行JSONで出力
標準エラー 入力、競合、DBエラーを1行JSONで出力
終了コード 意味
0 初期化、受理、または同一バッチの再確認
2 ファイル、JSON、範囲、イベント内容の不正。引数解析エラーも2だが、その場合はargparseの使用方法を出力
3 unavailable。DB更新なし
4 同じ要求IDが異なる内容で受理済み
5 SQLiteの接続、スキーマ、書き込みエラー

完全な応答だけを保存するCLI

次をaccept_replay.pyとして保存します。

#!/usr/bin/env python3
import argparse
import base64
import binascii
import hashlib
import json
import re
import sqlite3
import sys
from datetime import datetime, timezone
from pathlib import Path

REQUEST_LIMIT = 64 * 1024
RESPONSE_LIMIT = 8 * 1024 * 1024
PAYLOAD_LIMIT = 4 * 1024
MAX_EVENTS = 1000
MAX_RANGES = 100
MAX_SEQUENCE = 2_147_483_647
ID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")
SHA256_RE = re.compile(r"[0-9a-f]{64}")


class AppError(Exception):
    exit_code = 2
    kind = "invalid_input"


class InputError(AppError):
    pass


class ConflictError(AppError):
    exit_code = 4
    kind = "conflict"


class DatabaseError(AppError):
    exit_code = 5
    kind = "database_error"


def no_duplicate_keys(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise InputError(f"duplicate JSON key: {key}")
        result[key] = value
    return result


def reject_constant(value):
    raise InputError(f"non-standard JSON number: {value}")


def parse_json(raw, label):
    try:
        text = raw.decode("utf-8")
    except UnicodeDecodeError as exc:
        raise InputError(f"{label} is not UTF-8") from exc
    try:
        return json.loads(
            text,
            object_pairs_hook=no_duplicate_keys,
            parse_constant=reject_constant,
        )
    except InputError:
        raise
    except (json.JSONDecodeError, ValueError, RecursionError) as exc:
        raise InputError(f"{label} is not valid JSON") from exc


def read_limited(path, limit, label):
    try:
        with open(path, "rb") as source:
            raw = source.read(limit + 1)
    except OSError as exc:
        raise InputError(f"cannot read {label}: {exc}") from exc
    if len(raw) > limit:
        raise InputError(f"{label} exceeds {limit} bytes")
    return raw


def exact_object(value, expected, label):
    if type(value) is not dict:
        raise InputError(f"{label} must be an object")
    actual = set(value)
    if actual != expected:
        missing = sorted(expected - actual)
        extra = sorted(actual - expected)
        raise InputError(
            f"{label} keys differ; missing={missing}, extra={extra}"
        )


def checked_id(value, label):
    if type(value) is not str or ID_RE.fullmatch(value) is None:
        raise InputError(f"{label} is not a valid ASCII identifier")
    return value


def checked_hash(value, label):
    if type(value) is not str or SHA256_RE.fullmatch(value) is None:
        raise InputError(
            f"{label} must be a lowercase SHA-256 hex string"
        )
    return value


def checked_int(value, minimum, maximum, label):
    if type(value) is not int or not minimum <= value <= maximum:
        raise InputError(
            f"{label} must be an integer from {minimum} to {maximum}"
        )
    return value


def validate_ranges(value, label):
    if type(value) is not list or not 1 <= len(value) <= MAX_RANGES:
        raise InputError(
            f"{label} must contain 1 to {MAX_RANGES} ranges"
        )
    result = []
    previous_end = None
    total = 0
    for index, item in enumerate(value):
        item_label = f"{label}[{index}]"
        exact_object(item, {"start", "end"}, item_label)
        start = checked_int(
            item["start"], 1, MAX_SEQUENCE, f"{item_label}.start"
        )
        end = checked_int(
            item["end"], start, MAX_SEQUENCE, f"{item_label}.end"
        )
        if previous_end is not None and start <= previous_end + 1:
            raise InputError(
                f"{label} must be sorted, disjoint, and non-adjacent"
            )
        total += end - start + 1
        if total > MAX_EVENTS:
            raise InputError(
                f"{label} contains more than {MAX_EVENTS} events"
            )
        result.append((start, end))
        previous_end = end
    return result, total


def expand_ranges(ranges):
    return [
        sequence
        for start, end in ranges
        for sequence in range(start, end + 1)
    ]


def canonical_hash(value):
    raw = json.dumps(
        value,
        ensure_ascii=False,
        allow_nan=False,
        sort_keys=True,
        separators=(",", ":"),
    ).encode("utf-8")
    return hashlib.sha256(raw).hexdigest()


def validate_request(value):
    exact_object(
        value,
        {"format", "request_id", "sku", "ranges", "event_count"},
        "request",
    )
    if value["format"] != "bounded-replay-request-v1":
        raise InputError("unsupported request format")
    request_id = checked_id(value["request_id"], "request.request_id")
    sku = checked_id(value["sku"], "request.sku")
    ranges, total = validate_ranges(value["ranges"], "request.ranges")
    event_count = checked_int(
        value["event_count"], 1, MAX_EVENTS, "request.event_count"
    )
    if event_count != total:
        raise InputError("request.event_count does not match its ranges")
    return {
        "request_id": request_id,
        "sku": sku,
        "sequences": expand_ranges(ranges),
        "event_count": event_count,
    }


def validate_payload(raw, event_id, sequence, sku):
    if not 1 <= len(raw) <= PAYLOAD_LIMIT:
        raise InputError(
            f"payload must contain 1 to {PAYLOAD_LIMIT} bytes"
        )
    value = parse_json(raw, "payload")
    exact_object(
        value,
        {"event_id", "sku", "sequence", "quantity"},
        "payload",
    )
    checked_id(value["event_id"], "payload.event_id")
    checked_id(value["sku"], "payload.sku")
    checked_int(
        value["sequence"], 1, MAX_SEQUENCE, "payload.sequence"
    )
    checked_int(value["quantity"], 0, 1_000_000, "payload.quantity")
    if value["event_id"] != event_id:
        raise InputError(
            "payload.event_id differs from the response envelope"
        )
    if value["sequence"] != sequence:
        raise InputError(
            "payload.sequence differs from the response envelope"
        )
    if value["sku"] != sku:
        raise InputError("payload.sku differs from the request")


def validate_response(value, request, request_hash):
    if type(value) is not dict:
        raise InputError("response must be an object")
    common = {
        "format",
        "request_id",
        "request_sha256",
        "sku",
        "status",
    }
    status = value.get("status")
    if status == "available":
        exact_object(
            value, common | {"event_count", "events"}, "response"
        )
    elif status == "unavailable":
        exact_object(
            value, common | {"missing_ranges"}, "response"
        )
    else:
        raise InputError(
            "response.status must be available or unavailable"
        )

    if value["format"] != "bounded-replay-response-v1":
        raise InputError("unsupported response format")
    if checked_id(
        value["request_id"], "response.request_id"
    ) != request["request_id"]:
        raise InputError("response.request_id differs from the request")
    if checked_id(value["sku"], "response.sku") != request["sku"]:
        raise InputError("response.sku differs from the request")
    if checked_hash(
        value["request_sha256"], "response.request_sha256"
    ) != request_hash:
        raise InputError(
            "response.request_sha256 differs from the request"
        )

    if status == "unavailable":
        missing_ranges, _ = validate_ranges(
            value["missing_ranges"], "response.missing_ranges"
        )
        missing = set(expand_ranges(missing_ranges))
        if not missing <= set(request["sequences"]):
            raise InputError(
                "response.missing_ranges contains an unrequested sequence"
            )
        return {
            "status": status,
            "missing_ranges": value["missing_ranges"],
        }

    event_count = checked_int(
        value["event_count"], 1, MAX_EVENTS, "response.event_count"
    )
    if event_count != request["event_count"]:
        raise InputError(
            "response.event_count differs from the request"
        )
    if type(value["events"]) is not list:
        raise InputError("response.events must be an array")
    if len(value["events"]) != event_count:
        raise InputError(
            "response.events length differs from response.event_count"
        )

    events = []
    seen_event_ids = set()
    for index, expected_sequence in enumerate(request["sequences"]):
        item = value["events"][index]
        label = f"response.events[{index}]"
        exact_object(
            item,
            {"sequence", "event_id", "payload_b64", "payload_sha256"},
            label,
        )
        sequence = checked_int(
            item["sequence"], 1, MAX_SEQUENCE, f"{label}.sequence"
        )
        if sequence != expected_sequence:
            raise InputError(
                f"{label}.sequence is missing, extra, or out of order"
            )
        event_id = checked_id(item["event_id"], f"{label}.event_id")
        if event_id in seen_event_ids:
            raise InputError("response contains a duplicate event_id")
        seen_event_ids.add(event_id)
        payload_hash = checked_hash(
            item["payload_sha256"], f"{label}.payload_sha256"
        )
        if type(item["payload_b64"]) is not str:
            raise InputError(f"{label}.payload_b64 must be a string")
        try:
            payload = base64.b64decode(
                item["payload_b64"], validate=True
            )
        except (binascii.Error, ValueError) as exc:
            raise InputError(
                f"{label}.payload_b64 is not strict Base64"
            ) from exc
        if base64.b64encode(payload).decode("ascii") != item["payload_b64"]:
            raise InputError(
                f"{label}.payload_b64 is not canonical Base64"
            )
        if hashlib.sha256(payload).hexdigest() != payload_hash:
            raise InputError(f"{label} payload hash mismatch")
        validate_payload(
            payload, event_id, sequence, request["sku"]
        )
        events.append(
            {
                "sequence": sequence,
                "event_id": event_id,
                "payload": payload,
                "payload_sha256": payload_hash,
            }
        )
    return {"status": status, "events": events}


SCHEMA = """
CREATE TABLE IF NOT EXISTS replay_meta (
    key TEXT PRIMARY KEY,
    value TEXT NOT NULL
);
INSERT OR IGNORE INTO replay_meta(key, value)
VALUES ('schema_version', '1');

CREATE TABLE IF NOT EXISTS replay_batches (
    request_id TEXT PRIMARY KEY,
    request_sha256 TEXT NOT NULL,
    response_sha256 TEXT NOT NULL,
    sku TEXT NOT NULL,
    event_count INTEGER NOT NULL CHECK(event_count BETWEEN 1 AND 1000),
    accepted_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS replay_events (
    request_id TEXT NOT NULL REFERENCES replay_batches(request_id),
    sequence INTEGER NOT NULL,
    sku TEXT NOT NULL,
    event_id TEXT NOT NULL,
    payload BLOB NOT NULL,
    payload_sha256 TEXT NOT NULL,
    PRIMARY KEY(request_id, sequence),
    UNIQUE(request_id, event_id)
);
"""


def utc_now():
    return (
        datetime.now(timezone.utc)
        .replace(microsecond=0)
        .isoformat()
        .replace("+00:00", "Z")
    )


def init_db(path):
    with sqlite3.connect(path, timeout=5) as connection:
        connection.execute("PRAGMA foreign_keys = ON")
        connection.executescript(SCHEMA)
        row = connection.execute(
            "SELECT value FROM replay_meta WHERE key = 'schema_version'"
        ).fetchone()
        if row is None or row[0] != "1":
            raise DatabaseError(
                "unsupported database schema version"
            )


def open_db_for_write(path):
    uri = Path(path).resolve().as_uri() + "?mode=rw"
    connection = sqlite3.connect(
        uri, uri=True, timeout=5, isolation_level=None
    )
    try:
        connection.execute("PRAGMA foreign_keys = ON")
        row = connection.execute(
            "SELECT value FROM replay_meta WHERE key = 'schema_version'"
        ).fetchone()
        if row is None or row[0] != "1":
            raise DatabaseError(
                "database is not initialized with schema version 1"
            )
        return connection
    except Exception:
        connection.close()
        raise


def store_batch(
    connection, request, request_hash, response_hash, events
):
    try:
        connection.execute("BEGIN IMMEDIATE")
        row = connection.execute(
            """
            SELECT request_sha256, response_sha256, sku, event_count
            FROM replay_batches
            WHERE request_id = ?
            """,
            (request["request_id"],),
        ).fetchone()
        expected = (
            request_hash,
            response_hash,
            request["sku"],
            request["event_count"],
        )
        if row is not None:
            if row != expected:
                raise ConflictError(
                    "request_id was already accepted with different content"
                )
            stored_count = connection.execute(
                """
                SELECT COUNT(*) FROM replay_events
                WHERE request_id = ?
                """,
                (request["request_id"],),
            ).fetchone()[0]
            if stored_count != request["event_count"]:
                raise DatabaseError(
                    "accepted batch has an inconsistent event count"
                )
            connection.rollback()
            return "already_accepted", 0

        connection.execute(
            """
            INSERT INTO replay_batches(
                request_id, request_sha256, response_sha256,
                sku, event_count, accepted_at
            ) VALUES (?, ?, ?, ?, ?, ?)
            """,
            (
                request["request_id"],
                request_hash,
                response_hash,
                request["sku"],
                request["event_count"],
                utc_now(),
            ),
        )
        connection.executemany(
            """
            INSERT INTO replay_events(
                request_id, sequence, sku, event_id,
                payload, payload_sha256
            ) VALUES (?, ?, ?, ?, ?, ?)
            """,
            (
                (
                    request["request_id"],
                    event["sequence"],
                    request["sku"],
                    event["event_id"],
                    event["payload"],
                    event["payload_sha256"],
                )
                for event in events
            ),
        )
        connection.commit()
        return "accepted", len(events)
    except Exception:
        if connection.in_transaction:
            connection.rollback()
        raise


def accept_batch(path, request, request_hash, response_hash, events):
    connection = open_db_for_write(path)
    try:
        return store_batch(
            connection,
            request,
            request_hash,
            response_hash,
            events,
        )
    finally:
        connection.close()


def emit(value, stream=sys.stdout):
    print(
        json.dumps(
            value,
            ensure_ascii=False,
            sort_keys=True,
            separators=(",", ":"),
        ),
        file=stream,
    )


def build_parser():
    parser = argparse.ArgumentParser(
        description="Accept an exact bounded replay response"
    )
    commands = parser.add_subparsers(
        dest="command", required=True
    )
    init_command = commands.add_parser("init")
    init_command.add_argument("database")
    accept_command = commands.add_parser("accept")
    accept_command.add_argument("database")
    accept_command.add_argument("request")
    accept_command.add_argument("response")
    return parser


def main():
    args = build_parser().parse_args()
    try:
        if args.command == "init":
            init_db(args.database)
            emit(
                {
                    "status": "initialized",
                    "database": args.database,
                }
            )
            return 0

        request_raw = read_limited(
            args.request, REQUEST_LIMIT, "request"
        )
        response_raw = read_limited(
            args.response, RESPONSE_LIMIT, "response"
        )
        request_document = parse_json(request_raw, "request")
        response_document = parse_json(response_raw, "response")
        request = validate_request(request_document)
        request_hash = canonical_hash(request_document)
        response = validate_response(
            response_document, request, request_hash
        )

        if response["status"] == "unavailable":
            emit(
                {
                    "status": "unavailable",
                    "request_id": request["request_id"],
                    "missing_ranges": response["missing_ranges"],
                }
            )
            return 3

        status, stored_events = accept_batch(
            args.database,
            request,
            request_hash,
            canonical_hash(response_document),
            response["events"],
        )
        emit(
            {
                "status": status,
                "request_id": request["request_id"],
                "event_count": request["event_count"],
                "stored_events": stored_events,
            }
        )
        return 0
    except AppError as exc:
        emit(
            {
                "status": "error",
                "error": exc.kind,
                "detail": str(exc),
            },
            sys.stderr,
        )
        return exc.exit_code
    except sqlite3.Error as exc:
        emit(
            {
                "status": "error",
                "error": "database_error",
                "detail": str(exc),
            },
            sys.stderr,
        )
        return 5


if __name__ == "__main__":
    raise SystemExit(main())

要求と応答のサンプルを用意する

要求ファイルrequest.jsonを作ります。範囲は両端を含むため、要求件数は3件です。

{
  "format": "bounded-replay-request-v1",
  "request_id": "req-demo-001",
  "sku": "SKU-001",
  "ranges": [
    {"start": 11, "end": 12},
    {"start": 14, "end": 14}
  ],
  "event_count": 3
}

この要求を本稿の方法で正規化したSHA-256は、2dd49a8ee51fafc8d348139a21360af4e5ff0f11a06dd6871f785fadb514a5a9です。次をresponse.jsonとして保存します。

{
  "format": "bounded-replay-response-v1",
  "request_id": "req-demo-001",
  "request_sha256": "2dd49a8ee51fafc8d348139a21360af4e5ff0f11a06dd6871f785fadb514a5a9",
  "sku": "SKU-001",
  "status": "available",
  "event_count": 3,
  "events": [
    {
      "sequence": 11,
      "event_id": "evt-011",
      "payload_b64": "eyJldmVudF9pZCI6ImV2dC0wMTEiLCJxdWFudGl0eSI6MjQsInNlcXVlbmNlIjoxMSwic2t1IjoiU0tVLTAwMSJ9",
      "payload_sha256": "044db529c7b93c789c09caf12146e22f387aa15b3b5cf5bbf552a0e6ebc14991"
    },
    {
      "sequence": 12,
      "event_id": "evt-012",
      "payload_b64": "eyJldmVudF9pZCI6ImV2dC0wMTIiLCJxdWFudGl0eSI6MzAsInNlcXVlbmNlIjoxMiwic2t1IjoiU0tVLTAwMSJ9",
      "payload_sha256": "6540f6889863ac8fe9382d5db6947f1b323cc3381c21480bf4a7ac5446b9995a"
    },
    {
      "sequence": 14,
      "event_id": "evt-014",
      "payload_b64": "eyJldmVudF9pZCI6ImV2dC0wMTQiLCJxdWFudGl0eSI6MjcsInNlcXVlbmNlIjoxNCwic2t1IjoiU0tVLTAwMSJ9",
      "payload_sha256": "35938deaac7e90e785b77040174cb86999e3de738790aec9376df71440ba346c"
    }
  ]
}

最初のBase64を復号すると、次のJSONバイト列になります。応答の外側と内側で、イベントID、SKU、連番を照合します。

{"event_id":"evt-011","quantity":24,"sequence":11,"sku":"SKU-001"}

unavailableでは保存しない

最初にデータベースを初期化します。

$ python3 accept_replay.py init receiver.db
{"database":"receiver.db","status":"initialized"}

次の内容をresponse-unavailable.jsonとして保存します。

{
  "format": "bounded-replay-response-v1",
  "request_id": "req-demo-001",
  "request_sha256": "2dd49a8ee51fafc8d348139a21360af4e5ff0f11a06dd6871f785fadb514a5a9",
  "sku": "SKU-001",
  "status": "unavailable",
  "missing_ranges": [{"start": 12, "end": 12}]
}
$ python3 accept_replay.py accept receiver.db request.json response-unavailable.json
{"missing_ranges":[{"end":12,"start":12}],"request_id":"req-demo-001","status":"unavailable"}
$ echo $?
3

この経路ではデータベースを開く前に終了するため、バッチもイベントも追加されません。

完全な応答をまとめて保存する

$ python3 accept_replay.py accept receiver.db request.json response.json
{"event_count":3,"request_id":"req-demo-001","status":"accepted","stored_events":3}
$ echo $?
0

標準ライブラリのsqlite3で保存結果を確認します。

import sqlite3

with sqlite3.connect("receiver.db") as connection:
    batches = connection.execute(
        """
        SELECT request_id, event_count
        FROM replay_batches
        ORDER BY request_id
        """
    ).fetchall()
    events = connection.execute(
        """
        SELECT request_id, sku, sequence, event_id
        FROM replay_events
        ORDER BY request_id, sequence
        """
    ).fetchall()

print(batches)
print(events)
[('req-demo-001', 3)]
[('req-demo-001', 'SKU-001', 11, 'evt-011'), ('req-demo-001', 'SKU-001', 12, 'evt-012'), ('req-demo-001', 'SKU-001', 14, 'evt-014')]

同じコマンドを再実行しても、イベント行は増えません。

$ python3 accept_replay.py accept receiver.db request.json response.json
{"event_count":3,"request_id":"req-demo-001","status":"already_accepted","stored_events":0}

不足した応答がDBへ残らないことを確認する

12番のイベントだけを除いたファイルを作ります。event_countは3のままなので、配列長との不一致になります。

import json

with open("response.json", encoding="utf-8") as source:
    response = json.load(source)

response["events"].pop(1)

with open(
    "response-incomplete.json", "w", encoding="utf-8"
) as destination:
    json.dump(
        response,
        destination,
        ensure_ascii=False,
        separators=(",", ":"),
    )
$ python3 accept_replay.py accept receiver.db request.json response-incomplete.json
{"detail":"response.events length differs from response.event_count","error":"invalid_input","status":"error"}
$ echo $?
2

この検証はSQLiteを開く前に終わります。バッチは1件、イベントは3件のままです。入力検証後にSQLite制約エラーが起きた場合も、BEGIN IMMEDIATEからコミットまでの処理全体をロールバックします。

受信ステージの限界を分けておく

  • 異なる要求IDで同じイベントを再要求した場合は、別のステージ行として保存されます。業務更新の重複防止は、通常の受信処理でevent_idとSKU別連番を照合します。
  • このCLIは在庫更新、適用済み連番の更新、ステージ行の処理済み管理や削除を行いません。
  • 応答全体を最大8MiBまでメモリへ読み込みます。さらに大きな応答が必要なら、要求上限を増やす前にストリーミング形式と途中失敗時の扱いを設計する必要があります。
  • accepted_atは受信側のシステム時計から取得します。信頼できる時刻証明ではありません。
  • SQLiteファイルを別のプログラムが直接変更する状況や、ファイル自体の巻き戻しは検出しません。

実運用へ組み込む前に、テスト用DBでunavailable、正常受理、同一応答の再実行、不足イベントの4経路を確認してください。そのうえで、ステージから取り出したペイロードを通常の重複防止・順序制御処理へ渡します。