|
| 1 | +from flask import Flask, request, make_response, jsonify |
| 2 | +import os |
| 3 | +import random |
| 4 | +import psycopg2 |
| 5 | + |
| 6 | +app = Flask(__name__) |
| 7 | + |
| 8 | +DATABASE_URL = os.environ.get("DATABASE_URL") |
| 9 | + |
| 10 | +# Probability (0.0–1.0) that a transaction will fail between UPDATE and COMMIT. |
| 11 | +# Set to 0 for normal operation; raise to stress-test seek-back recovery. |
| 12 | +FAIL_PROBABILITY = float(os.environ.get("FAIL_PROBABILITY", "0")) |
| 13 | +_db_initialized = False |
| 14 | + |
| 15 | + |
| 16 | +def get_db(): |
| 17 | + return psycopg2.connect(DATABASE_URL) |
| 18 | + |
| 19 | + |
| 20 | +def ensure_db(): |
| 21 | + """Create the running_sum table if it doesn't exist (runs once per sandbox).""" |
| 22 | + global _db_initialized |
| 23 | + if _db_initialized: |
| 24 | + return |
| 25 | + conn = get_db() |
| 26 | + try: |
| 27 | + with conn.cursor() as cur: |
| 28 | + cur.execute( |
| 29 | + """ |
| 30 | + CREATE TABLE IF NOT EXISTS running_sum ( |
| 31 | + id INTEGER PRIMARY KEY DEFAULT 1, |
| 32 | + total BIGINT NOT NULL DEFAULT 0, |
| 33 | + last_offset BIGINT NOT NULL DEFAULT -1, |
| 34 | + message_count BIGINT NOT NULL DEFAULT 0, |
| 35 | + CHECK (id = 1) |
| 36 | + ) |
| 37 | + """ |
| 38 | + ) |
| 39 | + cur.execute( |
| 40 | + """ |
| 41 | + INSERT INTO running_sum (id, total, last_offset, message_count) |
| 42 | + VALUES (1, 0, -1, 0) |
| 43 | + ON CONFLICT (id) DO NOTHING |
| 44 | + """ |
| 45 | + ) |
| 46 | + conn.commit() |
| 47 | + _db_initialized = True |
| 48 | + finally: |
| 49 | + conn.close() |
| 50 | + |
| 51 | + |
| 52 | +@app.route("/reset", methods=["POST"]) |
| 53 | +def reset(): |
| 54 | + """Reset running_sum to zero so the demo can be re-run cleanly.""" |
| 55 | + ensure_db() |
| 56 | + conn = get_db() |
| 57 | + try: |
| 58 | + with conn.cursor() as cur: |
| 59 | + cur.execute( |
| 60 | + "UPDATE running_sum SET total = 0, last_offset = -1, " |
| 61 | + "message_count = 0 WHERE id = 1" |
| 62 | + ) |
| 63 | + conn.commit() |
| 64 | + return jsonify({"status": "reset"}) |
| 65 | + finally: |
| 66 | + conn.close() |
| 67 | + |
| 68 | + |
| 69 | +@app.route("/", methods=["GET", "POST"]) |
| 70 | +def handle(): |
| 71 | + ensure_db() |
| 72 | + |
| 73 | + # GET — return current state (useful for checking progress via HTTP) |
| 74 | + if request.method == "GET": |
| 75 | + conn = get_db() |
| 76 | + try: |
| 77 | + with conn.cursor() as cur: |
| 78 | + cur.execute( |
| 79 | + "SELECT total, last_offset, message_count " |
| 80 | + "FROM running_sum WHERE id = 1" |
| 81 | + ) |
| 82 | + row = cur.fetchone() |
| 83 | + if row: |
| 84 | + return jsonify( |
| 85 | + { |
| 86 | + "running_sum": row[0], |
| 87 | + "last_offset": row[1], |
| 88 | + "message_count": row[2], |
| 89 | + } |
| 90 | + ) |
| 91 | + return jsonify( |
| 92 | + {"running_sum": 0, "last_offset": -1, "message_count": 0} |
| 93 | + ) |
| 94 | + finally: |
| 95 | + conn.close() |
| 96 | + |
| 97 | + # POST — process a Kafka message containing a number |
| 98 | + offset = int(request.headers.get("X-Kafka-Offset", "-1")) |
| 99 | + topic = request.headers.get("X-Kafka-Topic", "unknown") |
| 100 | + partition = request.headers.get("X-Kafka-Partition", "unknown") |
| 101 | + |
| 102 | + body = request.get_json(silent=True) |
| 103 | + |
| 104 | + # Accept {"number": N} |
| 105 | + if isinstance(body, dict): |
| 106 | + number = body.get("number", 0) |
| 107 | + |
| 108 | + conn = None |
| 109 | + try: |
| 110 | + conn = get_db() |
| 111 | + with conn.cursor() as cur: |
| 112 | + # Lock the row and read last processed offset |
| 113 | + cur.execute( |
| 114 | + "SELECT last_offset FROM running_sum WHERE id = 1 FOR UPDATE" |
| 115 | + ) |
| 116 | + row = cur.fetchone() |
| 117 | + last_offset = row[0] if row else -1 |
| 118 | + |
| 119 | + # Idempotency: skip if this offset was already processed. |
| 120 | + # This prevents double-counting after a seek-back replays |
| 121 | + # messages that were already committed. |
| 122 | + if offset <= last_offset: |
| 123 | + conn.rollback() |
| 124 | + print(f"[skip] offset={offset} already processed (last={last_offset})") |
| 125 | + return jsonify( |
| 126 | + { |
| 127 | + "status": "skipped", |
| 128 | + "reason": "already processed", |
| 129 | + "offset": offset, |
| 130 | + "last_offset": last_offset, |
| 131 | + } |
| 132 | + ) |
| 133 | + |
| 134 | + # Atomically add number to running sum and advance the offset |
| 135 | + cur.execute( |
| 136 | + """ |
| 137 | + UPDATE running_sum |
| 138 | + SET total = total + %s, |
| 139 | + last_offset = %s, |
| 140 | + message_count = message_count + 1 |
| 141 | + WHERE id = 1 |
| 142 | + """, |
| 143 | + (number, offset), |
| 144 | + ) |
| 145 | + |
| 146 | + # --- Fault injection ------------------------------------------------ |
| 147 | + # Simulate a crash between UPDATE and COMMIT. |
| 148 | + if FAIL_PROBABILITY > 0 and random.random() < FAIL_PROBABILITY: |
| 149 | + raise Exception( |
| 150 | + f"Simulated DB failure at offset {offset} " |
| 151 | + f"(FAIL_PROBABILITY={FAIL_PROBABILITY})" |
| 152 | + ) |
| 153 | + # -------------------------------------------------------------------- |
| 154 | + |
| 155 | + conn.commit() |
| 156 | + |
| 157 | + # Read back the new state for the response |
| 158 | + cur.execute( |
| 159 | + "SELECT total, last_offset, message_count " |
| 160 | + "FROM running_sum WHERE id = 1" |
| 161 | + ) |
| 162 | + total, last_off, count = cur.fetchone() |
| 163 | + |
| 164 | + print(f"[ok] offset={offset} number={number} sum={total} count={count}") |
| 165 | + return jsonify( |
| 166 | + { |
| 167 | + "status": "ok", |
| 168 | + "offset": offset, |
| 169 | + "number_added": number, |
| 170 | + "running_sum": total, |
| 171 | + "message_count": count, |
| 172 | + } |
| 173 | + ) |
| 174 | + |
| 175 | + except Exception as e: |
| 176 | + print(f"[error] offset={offset} error={e}") |
| 177 | + if conn: |
| 178 | + try: |
| 179 | + conn.rollback() |
| 180 | + except Exception: |
| 181 | + pass |
| 182 | + |
| 183 | + # Tell OL's Kafka consumer to seek back to this offset and retry. |
| 184 | + # The consumer's LRU cache will serve the replay without re-fetching |
| 185 | + # from Kafka, and the idempotency check above prevents double-counting |
| 186 | + # for any offsets that were already committed before the failure. |
| 187 | + resp = make_response( |
| 188 | + jsonify({"status": "error", "offset": offset, "error": str(e)}), 500 |
| 189 | + ) |
| 190 | + resp.headers["X-Kafka-Seek-Offset"] = str(offset) |
| 191 | + return resp |
| 192 | + |
| 193 | + finally: |
| 194 | + if conn: |
| 195 | + try: |
| 196 | + conn.close() |
| 197 | + except Exception: |
| 198 | + pass |
0 commit comments