diff --git a/.github/workflows/ordered-report-aot.yml b/.github/workflows/ordered-report-aot.yml index 6eddbe22..328f0027 100644 --- a/.github/workflows/ordered-report-aot.yml +++ b/.github/workflows/ordered-report-aot.yml @@ -32,5 +32,10 @@ jobs: $queue = Join-Path $env:RUNNER_TEMP "ordered-aot" & $exe $queue success if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $rejectedQueue = Join-Path $env:RUNNER_TEMP "ordered-aot-rejected" + & $exe $rejectedQueue terminal + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + & $exe $rejectedQueue inspect + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } & $exe $queue success if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } diff --git a/README.md b/README.md index 3e838a5e..c4559b17 100644 --- a/README.md +++ b/README.md @@ -168,6 +168,27 @@ is busy, times out or is cancelled after the transaction commits, `ReportAsync` throw while the event remains queued; retry delivery with `ReplayAsync`, not by submitting a new report. Persistence failures before commit cannot be replayed. +#### Terminal rejection quarantine (additional opt-in) + +Only after verifying the target service supports the newer `ReportTerminalConflict` +contract (not just ordered events), pass `terminalRejectionConfirmed: true` to +`OrderedUpdateReporter` in **every** writer and replay process sharing the store. +Upgrade all processes first: older versions do not respect the quarantine. Never enable +this based on HTTP success or an untrusted endpoint. By default terminal rejection still +stops the entire queue. Other conflicts, HTTP errors, malformed replies and transient +failures always stop replay and retain the original event. + +With the extra opt-in, a confirmed terminal rejection is atomically retained in the +same database with its original JSON, event identity, sequence and reason. Later events +for that `(type, recordId)` remain pending and are never sent ahead of it; unrelated +records can proceed. Replay reports an error while any quarantine remains, even if +other records were delivered. Inspect `await reporter.GetQuarantinedAsync()` and alert +an operator; protect these payloads as sensitive. After investigating and correcting +the cause, `await reporter.RetryQuarantinedAsync(id)` restores the exact event to its +original queue position; call `ReplayAsync` to retry it. A terminal record cannot be +reopened; a genuinely new attempt requires a new server record ID. Quarantine does +not fix legacy flows that report Success before a later launch Failure. + ## 🙏 Thanks
diff --git a/eng/real-ordered-report.md b/eng/real-ordered-report.md new file mode 100644 index 00000000..f6e734ca --- /dev/null +++ b/eng/real-ordered-report.md @@ -0,0 +1,91 @@ +# Real ordered-report integration + +Run this harness in an independent workflow in the private GeneralSpace +repository, using its own `GITHUB_TOKEN` to check out server SHA +`896920c04423705fc8813818b495dfd51526e6b2` and a pinned revision of this +GeneralUpdate branch. The client revision must descend from GeneralUpdate +#550 at `1bbc64e02d30385af5b08e07cc464dccdeda6aa5`. Verify and print both +exact checked-out SHAs; neither PR is assumed merged. +The existing `ordered-report-aot.yml` separately publishes and executes the +SQLite-backed client as Native AOT on Windows and Linux. + +The job uses its own MySQL 8.0.42 service and a fresh `ordered_report_ci` +database, loopback HTTPS with a per-run certificate, temporary storage and +Data Protection keys. The harness refuses to run outside GitHub Actions and +does not upload server logs or credentials. The service and temporary files +are removed when the job ends. No cross-repository secret is needed when +GeneralSpace hosts the workflow and checks out the public GeneralUpdate repo. + +The workflow must use an Ubuntu GitHub-hosted runner, a fresh `mysql:8.0.42` +service with database `ordered_report_ci`, .NET SDKs 8 and 10, and +`PyMySQL==1.1.1` and `cryptography==44.0.3`. Check out the server at `server` +and client at `client` in the workspace, then run: + +```sh +dotnet publish server/src_api/GeneralSpace.Api -c Release -r linux-x64 --self-contained true -p:Edition=SaaS -o "$GITHUB_WORKSPACE/client/.integration/api" +dotnet publish client/tests/RealReportHarness/RealReportHarness.csproj -c Release -o "$GITHUB_WORKSPACE/client/.integration/client" +ORDERED_REPORT_DB_PORT=3306 ORDERED_REPORT_DB_USER=root ORDERED_REPORT_DB_PASSWORD='' python3 client/eng/real-ordered-report.py +``` + +It creates an upgrade record through the actual API, drops a confirmed response +after the server commits, and starts a second client process to replay the +persisted payload. It checks MySQL event and fault-log counts, record status, +duplicate success, late delivery and both kinds of conflict, including global +event ID reuse across records. It also sends a legacy `HttpUpdateReporter` +report with no ordered fields to the pinned server's legacy path and verifies +the record changed without creating an event. This does not test an older +server revision. The TLS connection is validated against the temporary test +CA; redirects and proxies are disabled. + +## Terminal rejection candidate suite + +The terminal suite additionally requires the client quarantine candidate from +GeneralUpdate #558 at `d78d9f697f37e915f083c3d0e20441a25a2d25a2` +(which descends from #550's `bb97a74f8eac25a665002722a17daea037072f2c`). +The server candidate is not frozen. Do not run this suite against the original +#330 pin or claim it verifies a final server revision: that pin cannot return +`ReportTerminalConflict`. Before running, record and verify an accessible +server candidate SHA and confirm that a committed Success followed by Failure +returns HTTP 200, `code=400`, `body=false`, and +`errorCode=ReportTerminalConflict`. + +Use the same publish commands and database environment, adding +`ORDERED_REPORT_TERMINAL_CONFIRMED=true`. This selects a separate candidate +suite, including legacy reporting, lost-response replay and late-event +registration, plus both terminal-direction rejection checks after ordered +terminal events. The default +suite remains unchanged and covers the original protocol where higher +sequences may replace a terminal status; it must not be run against the +terminal-latching candidate. + +The process CLI is: + +```text +RealReportHarness [fresh-record-id] +``` + +`terminal-seed` commits a failure to the real client outbox and interrupts +delivery before transport. `terminal-reject` actually sends it to the SaaS API +and requires the explicit terminal response plus one quarantined event. +`terminal-restart` uses a new process, inspects the retained event, verifies +Replay/Report surface operator review without sending that record, delivers a +fresh record, and explicitly retries the quarantined event. Its sixth argument +is the fresh record ID. `conflict` verifies a real ordinary `Conflict` response +retains the outbox event without quarantine. + +The Python suite compares SQLite's original payload byte-for-byte, including +event ID and sequence, with the retained quarantine across process restart +and explicit retry. It checks the stable `ReportTerminalConflict` reason; +arbitrary server messages are not persisted as reasons. MySQL checks show +the terminal record and fault attribution are unchanged, its successor was +not accepted, and the fresh record was accepted. Identity and sequence +collisions are tested separately with real API pre-registration. No payloads, +credentials, or server messages are printed or uploaded. + +The candidate suite also tests a transport failure injected before the real +request and an unrecognized business response substituted only after the +real API confirms commit. Both retain the original outbox item without +quarantine and replay it to the real API from another process. MySQL verifies +that the pre-send failure has no server effects and that the post-commit +unknown response is deduplicated and attributed only once. The unknown +response is injected by the client harness, not generated by the server. diff --git a/eng/real-ordered-report.py b/eng/real-ordered-report.py new file mode 100644 index 00000000..6b4b6247 --- /dev/null +++ b/eng/real-ordered-report.py @@ -0,0 +1,421 @@ +"""Exercise the actual ordered reporter and pinned SaaS API against disposable MySQL.""" +import hashlib +import ipaddress +import json +import os +from pathlib import Path +import secrets +import socket +import sqlite3 +import ssl +import subprocess +import tempfile +import time +import urllib.error +import urllib.request +import uuid +from contextlib import closing +from datetime import datetime, timedelta, timezone + +import pymysql +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.hazmat.primitives.serialization import pkcs12 +from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID + +ROOT = Path(__file__).resolve().parents[1] +TENANT = "ordered-report-ci" +DATABASE = "ordered_report_ci" + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + raise RuntimeError("Unexpected redirect from isolated API") + + +def certificate(directory): + key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "localhost")]) + now = datetime.now(timezone.utc) + cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name) + .public_key(key.public_key()).serial_number(x509.random_serial_number()) + .not_valid_before(now - timedelta(minutes=5)).not_valid_after(now + timedelta(days=1)) + .add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True) + .add_extension(x509.SubjectAlternativeName([ + x509.DNSName("localhost"), x509.IPAddress(ipaddress.ip_address("127.0.0.1")) + ]), critical=False) + .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False) + .sign(key, hashes.SHA256())) + password = secrets.token_hex(24) + pem = directory / "server.pem" + pem.write_bytes(cert.public_bytes(serialization.Encoding.PEM)) + (directory / "server.pfx").write_bytes(pkcs12.serialize_key_and_certificates( + b"loopback", key, cert, None, serialization.BestAvailableEncryption(password.encode()))) + return pem, password + + +def multipart(fields, payload): + boundary = uuid.uuid4().hex + parts = [f'--{boundary}\r\nContent-Disposition: form-data; name="{key}"\r\n\r\n{value}\r\n'.encode() + for key, value in fields.items()] + parts += [f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="ci.zip"\r\n' + 'Content-Type: application/octet-stream\r\n\r\n'.encode(), + payload, f"\r\n--{boundary}--\r\n".encode()] + return b"".join(parts), "multipart/form-data; boundary=" + boundary + + +def main(): + if os.environ.get("GITHUB_ACTIONS") != "true": + raise RuntimeError("This harness only runs in the isolated GitHub Actions service job") + port = int(os.environ["ORDERED_REPORT_DB_PORT"]) + user = os.environ["ORDERED_REPORT_DB_USER"] + db_password = os.environ["ORDERED_REPORT_DB_PASSWORD"] + if not 1 <= port <= 65535 or any(c in user + db_password for c in ";\"'\r\n"): + raise ValueError("Invalid disposable database configuration") + api_dir = ROOT / ".integration" / "api" + client = ROOT / ".integration" / "client" / "RealReportHarness.dll" + + with tempfile.TemporaryDirectory(prefix="ordered-report-ci-") as temp: + work = Path(temp) + pem, pfx_password = certificate(work) + with socket.socket() as reservation: + reservation.bind(("127.0.0.1", 0)) + api_port = reservation.getsockname()[1] + base = f"https://127.0.0.1:{api_port}" + environment = os.environ.copy() + environment.update({ + "ASPNETCORE_ENVIRONMENT": "Production", + "ConnectionStrings__DefaultConnection": + f"server=127.0.0.1;port={port};database={DATABASE};user={user};password={db_password}", + "AppSettings__AdminAuthSecretKey": secrets.token_hex(32), + "AppSettings__FileStoragePath": str(work / "storage"), + "AppSettings__FileStorageUrl": base + "/File/Download/", + "ObjectStorage__Provider": "Local", + "DataProtection__KeyRingPath": str(work / "keys"), + "Kestrel__Endpoints__Http__Url": base, + "Kestrel__Endpoints__Http__Certificate__Path": str(work / "server.pfx"), + "Kestrel__Endpoints__Http__Certificate__Password": pfx_password, + }) + opener = urllib.request.build_opener( + urllib.request.ProxyHandler({}), NoRedirect(), + urllib.request.HTTPSHandler(context=ssl.create_default_context(cafile=str(pem)))) + + def request(path, method="GET", body=None, token=None, content_type=None): + headers = {"X-Tenant-Id": TENANT} + if token: + headers["Authorization"] = "Bearer " + token + if body is not None and not isinstance(body, bytes): + body = json.dumps(body).encode() + content_type = "application/json" + if content_type: + headers["Content-Type"] = content_type + try: + response = opener.open(urllib.request.Request( + base + path, data=body, headers=headers, method=method), timeout=20) + except urllib.error.HTTPError as error: + response = error + with response: + data = response.read() + return response.status, json.loads(data) if data else None + + def success(result): + status, value = result + if status != 200 or value["code"] != 200: + raise AssertionError(f"API request failed: HTTP {status}, body {value}") + return value["body"] + + def worker(mode, record, outbox="outbox", extra=None): + command = ["dotnet", str(client), mode, str(work / outbox), + base + "/Upgrade/Report", str(pem), str(record)] + if extra is not None: + command.append(str(extra)) + subprocess.run(command, + check=True, timeout=60) + + def queued(outbox): + with closing(sqlite3.connect(work / outbox / "ordered-reports.db")) as queue: + return queue.execute("SELECT id,payload FROM outbox ORDER BY id").fetchall() + + def quarantined(outbox): + with closing(sqlite3.connect(work / outbox / "ordered-reports.db")) as queue: + return queue.execute("SELECT id,payload,reason FROM quarantine ORDER BY id").fetchall() + + with (work / "api.log").open("w", encoding="utf-8") as log: + process = subprocess.Popen([str(api_dir / "GeneralSpace.Api")], cwd=api_dir, + env=environment, stdout=log, stderr=subprocess.STDOUT) + try: + for _ in range(90): + if process.poll() is not None: + raise RuntimeError("SaaS API exited before readiness") + try: + with opener.open(base + "/Health", timeout=2) as response: + if response.status == 200: + break + except urllib.error.URLError: + pass + time.sleep(1) + else: + raise TimeoutError("SaaS API did not become ready") + + with pymysql.connect(host="127.0.0.1", port=port, user=user, password=db_password, + database=DATABASE, autocommit=True) as db: + password_hash = hashlib.sha256(secrets.token_bytes(32)).hexdigest() + with db.cursor() as cursor: + cursor.execute( + "INSERT INTO tb_tenant (id,name,identifier,is_active,create_time,activation_time," + "storage_traffic_quota,used_storage_traffic) VALUES (%s,%s,%s,1,UTC_TIMESTAMP()," + "UTC_TIMESTAMP(),%s,0)", (TENANT, "Ordered report CI", TENANT, 10 * 1024**3)) + cursor.execute("INSERT INTO tb_admin (name,password,account,tenant_id,is_active) " + "VALUES (%s,%s,%s,%s,1)", + ("Ordered report CI", password_hash, "ordered-admin", TENANT)) + token = success(request("/User/Login", "POST", { + "user": {"account": "ordered-admin", "password": password_hash}, "tenantId": TENANT, + }))["accessToken"] + success(request("/Product/Query", token=token)) + assert success(request("/Product/Create", "POST", {"name": "Ordered report CI"}, token)) is True + products = success(request("/Product/Query?name=Ordered%20report%20CI", token=token))["items"] + assert len(products) == 1 + product = products[0]["id"] + payload = b"ordered-report-test-package" + form, kind = multipart({"name": "ci-package", "format": ".zip", "version": "2.0.0", + "appType": "1", "platform": "1", "productId": product, + "packageType": "2"}, payload) + assert success(request("/Packet/Create", "POST", form, token, kind)) is True + assert success(request("/Client/Create", "POST", { + "appKey": "ordered-ci-app", "notes": "CI"}, token)) == "ordered-ci-app" + + def new_record(): + packages = success(request("/Upgrade/Verification", "POST", { + "appKey": "ordered-ci-app", "productId": product, "version": "1.0.0", + "appType": 1, "platform": 1, + })) + assert len(packages) == 1 and packages[0]["hash"] == hashlib.sha256(payload).hexdigest() + return packages[0]["recordId"] + + if os.environ.get("ORDERED_REPORT_TERMINAL_CONFIRMED") == "true": + def record_snapshot(record_id): + with db.cursor() as cursor: + cursor.execute("SELECT status,report_time,fault_id FROM tb_upgrade_record " + "WHERE id=%s", (record_id,)) + state = cursor.fetchone() + cursor.execute("SELECT event_id,sequence FROM tb_report_event WHERE record_type=1 " + "AND record_id=%s ORDER BY sequence", (record_id,)) + events = cursor.fetchall() + cursor.execute("SELECT COUNT(*) FROM tb_fault_log WHERE record_type=1 " + "AND record_id=%s", (record_id,)) + faults = cursor.fetchone()[0] + return state, events, faults + + def terminal_rejection(result): + http, body = result + assert http == 200 and body["code"] == 400 and body["body"] is False + assert body["errorCode"] == "ReportTerminalConflict" + + legacy_record = new_record() + worker("legacy", legacy_record, "legacy") + legacy_state = record_snapshot(legacy_record) + assert legacy_state[0][0] == 2 and legacy_state[1:] == ((), 0) + + failure_record = new_record() + worker("lost", failure_record, "lost-response") + pending_failure = queued("lost-response") + assert len(pending_failure) == 1 + accepted = json.loads(pending_failure[0][1]) + failure_state = record_snapshot(failure_record) + assert failure_state[0][0] == 3 and failure_state[2] == 1 + assert failure_state[1] == ((accepted["eventId"], 1),) + worker("replay", failure_record, "lost-response") + assert not queued("lost-response") and record_snapshot(failure_record) == failure_state + assert success(request("/Upgrade/Report", "POST", accepted)) is True + terminal_rejection(request("/Upgrade/Report", "POST", { + "recordId": failure_record, "type": 1, "status": 2, + "eventId": str(uuid.uuid4()), "sequence": 2, + })) + assert record_snapshot(failure_record) == failure_state + + for mode in ("transient-seed", "unknown-response"): + retry_record = new_record() + outbox = "retry-" + mode + initial = record_snapshot(retry_record) + worker(mode, retry_record, outbox) + pending = queued(outbox) + assert len(pending) == 1 and not quarantined(outbox) + event = json.loads(pending[0][1]) + assert event["recordId"] == retry_record and event["sequence"] == 1 + assert uuid.UUID(event["eventId"]).int != 0 + after_failure = record_snapshot(retry_record) + if mode == "transient-seed": + assert after_failure == initial + else: + assert after_failure[0][0] == 3 and after_failure[2] == 1 + assert after_failure[1] == ((event["eventId"], 1),) + worker("replay-exact", retry_record, outbox, + hashlib.sha256(pending[0][1].encode("utf-8")).hexdigest()) + final = record_snapshot(retry_record) + assert not queued(outbox) and not quarantined(outbox) + assert final[0][0] == 3 and final[2] == 1 + assert final[1] == ((event["eventId"], 1),) + if mode == "unknown-response": + assert final == after_failure + + ordered_record = new_record() + newer = {"recordId": ordered_record, "type": 1, "status": 2, + "eventId": str(uuid.uuid4()), "sequence": 4} + stale = {"recordId": ordered_record, "type": 1, "status": 3, + "eventId": str(uuid.uuid4()), "sequence": 3} + assert success(request("/Upgrade/Report", "POST", newer)) is True + final_state = record_snapshot(ordered_record)[0] + assert success(request("/Upgrade/Report", "POST", stale)) is True + assert success(request("/Upgrade/Report", "POST", stale)) is True + ordered_state = record_snapshot(ordered_record) + assert ordered_state[0] == final_state and ordered_state[2] == 0 + assert ordered_state[1] == ((stale["eventId"], 3), (newer["eventId"], 4)) + terminal_rejection(request("/Upgrade/Report", "POST", { + "recordId": ordered_record, "type": 1, "status": 3, + "eventId": str(uuid.uuid4()), "sequence": 5, + })) + assert record_snapshot(ordered_record) == ordered_state + + terminal_record, fresh_record = new_record(), new_record() + assert terminal_record != fresh_record + # This suite requires a server candidate explicitly confirmed to reject Success -> Failure. + assert success(request("/Upgrade/Report", "POST", { + "recordId": terminal_record, "type": 1, "status": 2, + })) is True + + def terminal_snapshot(): + with db.cursor() as cursor: + cursor.execute("SELECT status,report_time,fault_id FROM tb_upgrade_record " + "WHERE id=%s", (terminal_record,)) + state = cursor.fetchone() + cursor.execute("SELECT COUNT(*) FROM tb_report_event WHERE record_type=1 " + "AND record_id=%s", (terminal_record,)) + events = cursor.fetchone()[0] + cursor.execute("SELECT COUNT(*) FROM tb_fault_log WHERE record_type=1 " + "AND record_id=%s", (terminal_record,)) + faults = cursor.fetchone()[0] + return state, events, faults + + before = terminal_snapshot() + assert before[0][0] == 2 and before[1:] == (0, 0) + worker("terminal-seed", terminal_record, "terminal") + seed = queued("terminal") + assert len(seed) == 1 and not quarantined("terminal") + original = json.loads(seed[0][1]) + assert original["recordId"] == terminal_record and original["status"] == 3 + assert original["sequence"] == 1 and uuid.UUID(original["eventId"]).int != 0 + worker("terminal-reject", terminal_record, "terminal") + retained = quarantined("terminal") + assert retained == [(seed[0][0], seed[0][1], "ReportTerminalConflict")] + assert not queued("terminal") and terminal_snapshot() == before + worker("terminal-restart", terminal_record, "terminal", fresh_record) + assert quarantined("terminal") == retained and terminal_snapshot() == before + blocked = queued("terminal") + assert len(blocked) == 1 + later = json.loads(blocked[0][1]) + assert later["recordId"] == terminal_record and later["sequence"] == 2 + with db.cursor() as cursor: + cursor.execute("SELECT status FROM tb_upgrade_record WHERE id=%s", (fresh_record,)) + assert cursor.fetchone()[0] == 2 + cursor.execute("SELECT sequence FROM tb_report_event WHERE record_type=1 " + "AND record_id=%s", (fresh_record,)) + assert cursor.fetchall() == ((1,),) + + for collision in ("identity", "sequence"): + conflict_record = new_record() + outbox = "conflict-" + collision + worker("terminal-seed", conflict_record, outbox) + pending = queued(outbox) + assert len(pending) == 1 + conflicting = dict(json.loads(pending[0][1]), status=1) + if collision == "sequence": + conflicting["eventId"] = str(uuid.uuid4()) + assert success(request("/Upgrade/Report", "POST", conflicting)) is True + worker("conflict", conflict_record, outbox) + assert queued(outbox) == pending and not quarantined(outbox) + with db.cursor() as cursor: + cursor.execute("SELECT status FROM tb_upgrade_record WHERE id=%s", (conflict_record,)) + assert cursor.fetchone()[0] == 1 + cursor.execute("SELECT event_id,sequence FROM tb_report_event WHERE record_type=1 " + "AND record_id=%s", (conflict_record,)) + assert cursor.fetchall() == ((conflicting["eventId"], 1),) + cursor.execute("SELECT COUNT(*) FROM tb_fault_log WHERE record_type=1 " + "AND record_id=%s", (conflict_record,)) + assert cursor.fetchone()[0] == 0 + print("Real API candidate: legacy, lost and unknown response, transient transport, replay, " + "ordering, terminal quarantine, restart, exact payload, blocked record, " + "fresh delivery and ordinary conflicts passed.") + return + + record, other_record, legacy_record = new_record(), new_record(), new_record() + assert len({record, other_record, legacy_record}) == 3 + worker("legacy", legacy_record) + with db.cursor() as cursor: + cursor.execute("SELECT status FROM tb_upgrade_record WHERE id=%s", (legacy_record,)) + assert cursor.fetchone()[0] == 2 + cursor.execute("SELECT COUNT(*) FROM tb_report_event WHERE record_type=1 AND record_id=%s", + (legacy_record,)) + assert cursor.fetchone()[0] == 0 + + def snapshot(): + with db.cursor() as cursor: + cursor.execute("SELECT event_id,sequence FROM tb_report_event " + "WHERE record_type=1 AND record_id=%s ORDER BY sequence", (record,)) + events = cursor.fetchall() + cursor.execute("SELECT status FROM tb_upgrade_record WHERE id=%s", (record,)) + status = cursor.fetchone()[0] + cursor.execute("SELECT COUNT(*) FROM tb_fault_log WHERE record_type=1 AND record_id=%s", + (record,)) + count = cursor.fetchone()[0] + return events, status, count + + worker("lost", record) + with closing(sqlite3.connect(work / "outbox" / "ordered-reports.db")) as queue: + rows = queue.execute("SELECT payload FROM outbox").fetchall() + assert len(rows) == 1 + original = json.loads(rows[0][0]) + assert original["recordId"] == record and original["sequence"] == 1 + assert uuid.UUID(original["eventId"]).int != 0 + events, status, count = snapshot() + assert len(events) == 1 and events[0][1] == 1 and status == 3 and count == 1 + + worker("replay", record) # A separate process opens the same durable outbox. + with closing(sqlite3.connect(work / "outbox" / "ordered-reports.db")) as queue: + assert queue.execute("SELECT COUNT(*) FROM outbox").fetchone()[0] == 0 + assert snapshot() == (events, status, count) + assert success(request("/Upgrade/Report", "POST", original)) is True + assert snapshot() == (events, status, count) + + worker("success", record) + events, status, count = snapshot() + assert [row[1] for row in events] == [1, 2] and status == 2 and count == 1 + later = {"recordId": record, "type": 1, "status": 2, + "eventId": str(uuid.uuid4()), "sequence": 4} + earlier = {"recordId": record, "type": 1, "status": 3, + "eventId": str(uuid.uuid4()), "sequence": 3, + "category": 3, "phase": "Apply", "message": "Stale failure"} + assert success(request("/Upgrade/Report", "POST", later)) is True + assert success(request("/Upgrade/Report", "POST", earlier)) is True + events, status, count = snapshot() + assert [row[1] for row in events] == [1, 2, 3, 4] and status == 2 and count == 1 + conflicts = [dict(original, status=2), + dict(original, eventId=str(uuid.uuid4())), + dict(original, recordId=other_record)] + for conflict in conflicts: + http, result = request("/Upgrade/Report", "POST", conflict) + assert http == 200 and result["code"] == 400 + assert result["errorCode"] == "Conflict" and result["body"] is False + assert snapshot() == (events, status, count) + print("Real API: legacy report, lost response, process restart, deduplication, ordering and conflicts passed.") + finally: + process.terminate() + try: + process.wait(timeout=15) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + + +if __name__ == "__main__": + main() diff --git a/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs b/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs index 4f61202e..aa51e357 100644 --- a/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs +++ b/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs @@ -238,6 +238,19 @@ internal async Task SendJsonAsync(string json, CancellationToken token) var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); using var document = JsonDocument.Parse(content); var root = document.RootElement; + if (response.StatusCode == System.Net.HttpStatusCode.OK && + root.ValueKind == JsonValueKind.Object && + root.TryGetProperty("code", out var terminalCode) && terminalCode.ValueKind == JsonValueKind.Number && + terminalCode.TryGetInt32(out var terminalValue) && terminalValue == 400 && + root.TryGetProperty("body", out var terminalBody) && terminalBody.ValueKind == JsonValueKind.False && + root.TryGetProperty("errorCode", out var terminalError) && terminalError.ValueKind == JsonValueKind.String && + terminalError.GetString() == "ReportTerminalConflict") + throw new ReportTerminalConflictException(); + if (root.ValueKind == JsonValueKind.Object && + root.TryGetProperty("errorCode", out var unexpectedTerminal) && + unexpectedTerminal.ValueKind == JsonValueKind.String && + unexpectedTerminal.GetString() == "ReportTerminalConflict") + throw new InvalidOperationException("The terminal rejection response is malformed."); if (root.ValueKind == JsonValueKind.Object && root.TryGetProperty("errorCode", out var errorCode) && errorCode.ValueKind == JsonValueKind.String && @@ -249,4 +262,9 @@ internal async Task SendJsonAsync(string json, CancellationToken token) !root.TryGetProperty("body", out var body) || body.ValueKind != JsonValueKind.True) throw new InvalidOperationException("The report endpoint did not confirm business success."); } + + internal sealed class ReportTerminalConflictException : InvalidOperationException + { + public ReportTerminalConflictException() : base("The report endpoint rejected a terminal record transition.") { } + } } diff --git a/src/GeneralUpdate.Core/Download/Reporting/OrderedUpdateReporter.cs b/src/GeneralUpdate.Core/Download/Reporting/OrderedUpdateReporter.cs index 737085d4..94f9f597 100644 --- a/src/GeneralUpdate.Core/Download/Reporting/OrderedUpdateReporter.cs +++ b/src/GeneralUpdate.Core/Download/Reporting/OrderedUpdateReporter.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.Http; @@ -22,6 +23,7 @@ public sealed class OrderedUpdateReporter : IUpdateReporter private readonly string _identity; private readonly HttpUpdateReporter _sender; private readonly TimeSpan _lockTimeout; + private readonly bool _terminalRejectionConfirmed; /// /// Creates an ordered reporter. The operator must confirm that the endpoint supports @@ -30,6 +32,13 @@ public sealed class OrderedUpdateReporter : IUpdateReporter /// public OrderedUpdateReporter(string directory, HttpClient client, string reportUrl, string namespaceIdentity, bool protocolConfirmed, TimeSpan? lockTimeout = null) + : this(directory, client, reportUrl, namespaceIdentity, protocolConfirmed, false, lockTimeout) + { + } + + /// Creates a reporter with explicit confirmation of the terminal rejection protocol. + public OrderedUpdateReporter(string directory, HttpClient client, string reportUrl, + string namespaceIdentity, bool protocolConfirmed, bool terminalRejectionConfirmed, TimeSpan? lockTimeout = null) { if (!protocolConfirmed) throw new InvalidOperationException("The ordered-report protocol must be explicitly confirmed."); if (string.IsNullOrWhiteSpace(directory)) throw new ArgumentException("A private local directory is required.", nameof(directory)); @@ -43,6 +52,7 @@ public OrderedUpdateReporter(string directory, HttpClient client, string reportU _identity = Identity(reportUrl, namespaceIdentity); _sender = new HttpUpdateReporter(client, reportUrl); _lockTimeout = lockTimeout ?? TimeSpan.FromSeconds(30); + _terminalRejectionConfirmed = terminalRejectionConfirmed; if (_lockTimeout <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(lockTimeout)); } @@ -105,22 +115,70 @@ public async Task ReplayAsync(CancellationToken token = default) private async Task ReplayLockedAsync(SqliteConnection connection, CancellationToken token) { + if (!_terminalRejectionConfirmed && HasQuarantine(connection)) + throw new InvalidOperationException("Quarantined reports require explicit terminal rejection protocol confirmation."); while (true) { token.ThrowIfCancellationRequested(); - long id; - string payload; + long id = 0; + string? payload = null; + UpdateReport? report = null; + var blocked = false; using (var command = connection.CreateCommand()) { - command.CommandText = "SELECT id, payload FROM outbox ORDER BY id LIMIT 1;"; + command.CommandText = "SELECT id, payload FROM outbox ORDER BY id;"; using (var reader = command.ExecuteReader()) { - if (!reader.Read()) return; - id = reader.GetInt64(0); - payload = reader.GetString(1); + while (reader.Read()) + { + var candidate = reader.GetString(1); + var parsed = JsonSerializer.Deserialize(candidate, UpdateReportJsonContext.Default.UpdateReport) + ?? throw new InvalidDataException("A queued report is null."); + if (parsed.RecordId <= 0 || (parsed.Type != 1 && parsed.Type != 2) || + parsed.EventId == null || parsed.EventId == Guid.Empty || parsed.Sequence == null || parsed.Sequence <= 0) + throw new InvalidDataException("A queued ordered report is invalid."); + if (IsBlocked(connection, parsed.Type, parsed.RecordId)) + { + blocked = true; + continue; + } + id = reader.GetInt64(0); + payload = candidate; + report = parsed; + break; + } + } + } + if (payload == null) + { + if (blocked || HasQuarantine(connection)) + throw new InvalidOperationException("Ordered reports are quarantined; operator review is required."); + return; + } + try + { + await _sender.SendJsonAsync(payload, token).ConfigureAwait(false); + } + catch (HttpUpdateReporter.ReportTerminalConflictException) when (_terminalRejectionConfirmed) + { + using (var transaction = connection.BeginTransaction()) + { + using (var command = connection.CreateCommand()) + { + command.Transaction = transaction; + command.CommandText = @"INSERT INTO quarantine (id, type, record_id, payload, reason) + VALUES ($id, $type, $record, $payload, 'ReportTerminalConflict'); + DELETE FROM outbox WHERE id = $id;"; + command.Parameters.AddWithValue("$id", id); + command.Parameters.AddWithValue("$type", report!.Type); + command.Parameters.AddWithValue("$record", report.RecordId); + command.Parameters.AddWithValue("$payload", payload); + command.ExecuteNonQuery(); + } + transaction.Commit(); } + continue; } - await _sender.SendJsonAsync(payload, token).ConfigureAwait(false); using (var command = connection.CreateCommand()) { command.CommandText = "DELETE FROM outbox WHERE id = $id;"; @@ -130,6 +188,62 @@ private async Task ReplayLockedAsync(SqliteConnection connection, CancellationTo } } } + /// Returns quarantined reports for operator inspection. Payloads may contain sensitive diagnostics. + public async Task> GetQuarantinedAsync(CancellationToken token = default) + { + using (await AcquireLockAsync(token).ConfigureAwait(false)) + using (var connection = Open()) + using (var command = connection.CreateCommand()) + { + command.CommandText = "SELECT id, payload, reason FROM quarantine ORDER BY id;"; + using (var reader = command.ExecuteReader()) + { + var result = new List(); + while (reader.Read()) result.Add(new QuarantinedUpdateReport(reader.GetInt64(0), reader.GetString(1), reader.GetString(2))); + return result; + } + } + } + + /// Moves an inspected event back to its original place in the outbox for an explicit retry. + public async Task RetryQuarantinedAsync(long id, CancellationToken token = default) + { + using (await AcquireLockAsync(token).ConfigureAwait(false)) + using (var connection = Open()) + using (var transaction = connection.BeginTransaction()) + { + using (var command = connection.CreateCommand()) + { + command.Transaction = transaction; + command.CommandText = "INSERT INTO outbox (id, payload) SELECT id, payload FROM quarantine WHERE id = $id;"; + command.Parameters.AddWithValue("$id", id); + if (command.ExecuteNonQuery() != 1) throw new InvalidOperationException("Quarantined report not found."); + command.CommandText = "DELETE FROM quarantine WHERE id = $id;"; + if (command.ExecuteNonQuery() != 1) throw new InvalidDataException("Quarantined report changed."); + } + transaction.Commit(); + } + } + + private static bool IsBlocked(SqliteConnection connection, int type, int recordId) + { + using (var command = connection.CreateCommand()) + { + command.CommandText = "SELECT EXISTS(SELECT 1 FROM quarantine WHERE type = $type AND record_id = $record);"; + command.Parameters.AddWithValue("$type", type); + command.Parameters.AddWithValue("$record", recordId); + return (long)command.ExecuteScalar()! != 0; + } + } + + private static bool HasQuarantine(SqliteConnection connection) + { + using (var command = connection.CreateCommand()) + { + command.CommandText = "SELECT EXISTS(SELECT 1 FROM quarantine);"; + return (long)command.ExecuteScalar()! != 0; + } + } private SqliteConnection Open() { @@ -157,10 +271,13 @@ private SqliteConnection Open() CREATE TABLE IF NOT EXISTS counters (type INTEGER NOT NULL, record_id INTEGER NOT NULL, sequence INTEGER NOT NULL, PRIMARY KEY(type, record_id)); CREATE TABLE IF NOT EXISTS outbox (id INTEGER PRIMARY KEY AUTOINCREMENT, payload TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS quarantine (id INTEGER PRIMARY KEY, type INTEGER NOT NULL, + record_id INTEGER NOT NULL, payload TEXT NOT NULL, reason TEXT NOT NULL); INSERT OR IGNORE INTO metadata (id, identity) VALUES (1, $identity);"; command.Parameters.AddWithValue("$identity", _identity); command.ExecuteNonQuery(); } + using (var command = connection.CreateCommand()) { command.Transaction = transaction; @@ -206,4 +323,7 @@ private static string Identity(string endpoint, string scope) return Convert.ToBase64String(hash.ComputeHash(Encoding.UTF8.GetBytes(value))); } } + + /// A rejected report retained for operator review. The JSON is the original wire payload. + public sealed record QuarantinedUpdateReport(long Id, string Payload, string Reason); } diff --git a/tests/CoreTest/Download/OrderedUpdateReporterTests.cs b/tests/CoreTest/Download/OrderedUpdateReporterTests.cs index b0d9c79f..2133a959 100644 --- a/tests/CoreTest/Download/OrderedUpdateReporterTests.cs +++ b/tests/CoreTest/Download/OrderedUpdateReporterTests.cs @@ -61,6 +61,67 @@ await Assert.ThrowsAsync(() => Assert.Equal(handler.Bodies[1], handler.Bodies[2]); } + [Fact] + public async Task TerminalRejectionIsOptInAndPreservesPerRecordOrderingAcrossRestart() + { + var handler = new Handler { TerminalRecord = 10 }; + var legacy = Create(handler); + await Assert.ThrowsAnyAsync(() => legacy.ReportAsync(new UpdateReport(10, 3))); + Assert.Empty(await legacy.GetQuarantinedAsync()); + var reporter = Create(handler, true); + await Assert.ThrowsAsync(() => reporter.ReplayAsync()); + var quarantined = Assert.Single(await Create(handler, true).GetQuarantinedAsync()); + Assert.Equal(handler.Bodies[0], quarantined.Payload); + Assert.Equal("ReportTerminalConflict", quarantined.Reason); + await Assert.ThrowsAsync(() => reporter.ReportAsync(new UpdateReport(10, 2))); + await Assert.ThrowsAsync(() => reporter.ReportAsync(new UpdateReport(11, 3))); + Assert.Equal(new[] { 10, 10, 11 }, handler.Bodies.Select(RecordId)); + await Assert.ThrowsAsync(() => legacy.ReplayAsync()); + handler.TerminalRecord = null; + await reporter.RetryQuarantinedAsync(quarantined.Id); + await Create(handler, true).ReplayAsync(); + Assert.Equal(new[] { 10, 10, 11, 10, 10 }, handler.Bodies.Select(RecordId)); + Assert.Equal(quarantined.Payload, handler.Bodies[3]); + Assert.Equal(2, Sequence(handler.Bodies[4])); + Assert.Empty(await reporter.GetQuarantinedAsync()); + } + + [Theory] + [InlineData("{\"code\":400,\"body\":false,\"errorCode\":\"Conflict\"}", 200)] + [InlineData("{\"code\":200,\"body\":true,\"errorCode\":\"ReportTerminalConflict\"}", 200)] + [InlineData("{\"code\":400,\"body\":false,\"errorCode\":\"ReportTerminalConflict\"}", 409)] + [InlineData("{\"code\":400,\"body\":false,\"errorCode\":\"Other\"}", 200)] + public async Task OtherResponsesNeverQuarantine(string body, int status) + { + var handler = new Handler { ResponseBody = body, ResponseStatus = status }; + var reporter = Create(handler, true); + await Assert.ThrowsAnyAsync(() => reporter.ReportAsync(new UpdateReport(10, 3))); + Assert.Empty(await reporter.GetQuarantinedAsync()); + handler.ResponseBody = null; + handler.ResponseStatus = 200; + await reporter.ReplayAsync(); + Assert.Equal(handler.Bodies[0], handler.Bodies[1]); + } + + [Fact] + public async Task QuarantineSurvivesProcessRestartAndOtherRecordIsDelivered() + { + using (var worker = StartWorker("terminal")) + { + await worker.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(60)); + Assert.Equal(0, worker.ExitCode); + } + using (var worker = StartWorker("inspect")) + { + await worker.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(60)); + Assert.Equal(0, worker.ExitCode); + } + var handler = new Handler(); + await Assert.ThrowsAsync(() => Create(handler, true).ReportAsync(new UpdateReport(11, 3))); + Assert.Equal(11, RecordId(Assert.Single(handler.Bodies))); + Assert.Single(await Create(handler, true).GetQuarantinedAsync()); + } + [Fact] public async Task ConcurrentProcessesAllocateUniqueSequences() { @@ -152,8 +213,9 @@ await Task.WhenAll(Enumerable.Range(0, 12).Select(async _ => Assert.Equal(12, handler.Bodies.Select(EventId).Distinct().Count()); } - private OrderedUpdateReporter Create(Handler handler) => - new(_directory, new HttpClient(handler, false), "https://example.test/report", "tenant/database", true); + private OrderedUpdateReporter Create(Handler handler, bool terminalConfirmed = false) => + new(_directory, new HttpClient(handler, false), "https://example.test/report", "tenant/database", true, + terminalRejectionConfirmed: terminalConfirmed); private Process StartWorker(string mode) { @@ -167,6 +229,7 @@ private Process StartWorker(string mode) private static long Sequence(string body) => JsonDocument.Parse(body).RootElement.GetProperty("sequence").GetInt64(); private static Guid EventId(string body) => JsonDocument.Parse(body).RootElement.GetProperty("eventId").GetGuid(); + private static int RecordId(string body) => JsonDocument.Parse(body).RootElement.GetProperty("recordId").GetInt32(); public void Dispose() { @@ -178,6 +241,9 @@ private sealed class Handler : HttpMessageHandler public bool Fail { get; set; } public bool AcceptBeforeFailure { get; set; } public bool Conflict { get; set; } + public int? TerminalRecord { get; set; } + public string? ResponseBody { get; set; } + public int ResponseStatus { get; set; } = 200; public List Bodies { get; } = []; public HashSet Applied { get; } = []; protected override async Task SendAsync(HttpRequestMessage request, CancellationToken token) @@ -189,11 +255,13 @@ protected override async Task SendAsync(HttpRequestMessage json.RootElement.TryGetProperty("eventId", out var eventId)) Applied.Add(eventId.GetGuid()); if (Fail) throw new HttpRequestException("lost response"); - return new HttpResponseMessage(HttpStatusCode.OK) + return new HttpResponseMessage((HttpStatusCode)ResponseStatus) { - Content = new StringContent(Conflict + Content = new StringContent(ResponseBody ?? (TerminalRecord == json.RootElement.GetProperty("recordId").GetInt32() + ? "{\"code\":400,\"errorCode\":\"ReportTerminalConflict\",\"body\":false}" + : Conflict ? "{\"code\":400,\"errorCode\":\"Conflict\",\"body\":false}" - : "{\"code\":200,\"body\":true}") + : "{\"code\":200,\"body\":true}")) }; } } diff --git a/tests/RealReportHarness/Program.cs b/tests/RealReportHarness/Program.cs new file mode 100644 index 00000000..8ee9fd8e --- /dev/null +++ b/tests/RealReportHarness/Program.cs @@ -0,0 +1,225 @@ +using System.Net; +using System.Net.Security; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Text.Json; +using GeneralUpdate.Core.Download.Reporting; + +if (args.Length is not (5 or 6) || !int.TryParse(args[4], out var recordId)) + throw new ArgumentException("Expected mode, outbox, report URL, certificate, record ID, optional fresh record ID."); + +var mode = args[0]; +using var root = X509Certificate2.CreateFromPem(File.ReadAllText(args[3])); +using var transport = new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false }; +transport.ServerCertificateCustomValidationCallback = (_, certificate, _, errors) => +{ + if (certificate is null || (errors & ~SslPolicyErrors.RemoteCertificateChainErrors) != 0) + return false; + using var chain = new X509Chain(); + chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; + chain.ChainPolicy.CustomTrustStore.Add(root); + chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; + return chain.Build(certificate); +}; +using var handler = new TestHandler(transport, mode); +using var client = new HttpClient(handler); +client.DefaultRequestHeaders.Add("X-Tenant-Id", "ordered-report-ci"); +if (mode == "legacy") +{ + await new HttpUpdateReporter(client, args[2]).SendAsync(new UpdateReport(recordId, 2)); + return; +} + +var reporter = new OrderedUpdateReporter(args[1], client, args[2], "ordered-report-ci/test-database", true, + terminalRejectionConfirmed: mode.StartsWith("terminal-", StringComparison.Ordinal) || mode == "conflict"); +switch (mode) +{ + case "terminal-seed": + try + { + await reporter.ReportAsync(new UpdateReport(recordId, 3) + { + Category = FailureCategory.Apply, Phase = "Apply", ErrorCode = "CI-TERMINAL", Message = "CI failure" + }); + throw new InvalidDataException("Seed delivery was not interrupted."); + } + catch (BeforeDeliveryException) + { + Console.WriteLine("Committed original payload before transport."); + } + break; + case "transient-seed": + try + { + await reporter.ReportAsync(new UpdateReport(recordId, 3) + { + Category = FailureCategory.Apply, Phase = "Apply", ErrorCode = "CI-TRANSIENT", Message = "CI failure" + }); + throw new InvalidDataException("Transient transport failure was not observed."); + } + catch (BeforeDeliveryException) + { + Console.WriteLine("Transient transport failure retained report."); + } + break; + case "unknown-response": + try + { + await reporter.ReportAsync(new UpdateReport(recordId, 3) + { + Category = FailureCategory.Apply, Phase = "Apply", ErrorCode = "CI-UNKNOWN", Message = "CI failure" + }); + throw new InvalidDataException("Unknown response was incorrectly accepted."); + } + catch (InvalidOperationException) + { + if (handler.UnknownResponses != 1) + throw new InvalidDataException("The successful response was not replaced as expected."); + Console.WriteLine("Unrecognized response retained report."); + } + break; + case "terminal-reject": + await ExpectReviewAsync(() => reporter.ReplayAsync()); + var rejected = await reporter.GetQuarantinedAsync(); + if (rejected.Count != 1 || rejected[0].Reason != "ReportTerminalConflict" || + handler.SentRecords.Count != 1 || handler.TerminalResponses != 1) + throw new InvalidDataException("The real terminal response was not quarantined."); + break; + case "terminal-restart": + if (args.Length != 6 || !int.TryParse(args[5], out var freshRecordId) || freshRecordId == recordId) + throw new ArgumentException("terminal-restart requires a different fresh record ID."); + var retained = await reporter.GetQuarantinedAsync(); + if (retained.Count != 1 || retained[0].Reason != "ReportTerminalConflict") + throw new InvalidDataException("Quarantine did not survive process restart."); + await ExpectReviewAsync(() => reporter.ReplayAsync()); + await ExpectReviewAsync(() => reporter.ReportAsync(new UpdateReport(recordId, 2))); + if (handler.SentRecords.Count != 0) + throw new InvalidDataException("The quarantined record was sent without operator action."); + await ExpectReviewAsync(() => reporter.ReportAsync(new UpdateReport(freshRecordId, 2))); + if (!handler.SentRecords.SequenceEqual(new[] { freshRecordId })) + throw new InvalidDataException("Fresh record was not delivered independently."); + if (!(await reporter.GetQuarantinedAsync()).SequenceEqual(retained)) + throw new InvalidDataException("Original quarantine changed after unrelated delivery."); + await reporter.RetryQuarantinedAsync(retained[0].Id); + await ExpectReviewAsync(() => reporter.ReplayAsync()); + if (!(await reporter.GetQuarantinedAsync()).SequenceEqual(retained) || + !handler.SentRecords.SequenceEqual(new[] { freshRecordId, recordId }) || handler.TerminalResponses != 1) + throw new InvalidDataException("Operator retry did not preserve and re-quarantine the original event."); + break; + case "conflict": + await ExpectReviewAsync(() => reporter.ReplayAsync()); + if ((await reporter.GetQuarantinedAsync()).Count != 0 || + handler.SentRecords.Count != 1 || handler.ConflictResponses != 1) + throw new InvalidDataException("An ordinary conflict was quarantined or not sent."); + break; + case "lost": + try + { + await reporter.ReportAsync(new UpdateReport(recordId, 3) + { + Category = FailureCategory.Apply, Phase = "Apply", ErrorCode = "CI-APPLY", Message = "CI failure" + }); + throw new InvalidOperationException("The response was not dropped."); + } + catch (LostResponseException) + { + Console.WriteLine("Confirmed server success, then dropped response."); + } + break; + case "replay": + await reporter.ReplayAsync(); + break; + case "replay-exact": + if (args.Length != 6) throw new ArgumentException("Expected SHA-256 digest of retained payload."); + await reporter.ReplayAsync(); + if (handler.SentPayloadHashes.Count != 1 || + !string.Equals(handler.SentPayloadHashes[0], args[5], StringComparison.OrdinalIgnoreCase)) + throw new InvalidDataException("Replay did not send the exact retained payload."); + break; + case "success": + await reporter.ReportAsync(new UpdateReport(recordId, 2)); + break; + default: + throw new ArgumentException("Unknown mode."); +} + +static async Task ExpectReviewAsync(Func action) +{ + try + { + await action(); + } + catch (InvalidOperationException) + { + return; + } + throw new InvalidDataException("Expected explicit rejection/operator-review failure."); +} + +sealed class LostResponseException : HttpRequestException; +sealed class BeforeDeliveryException : HttpRequestException; + +sealed class TestHandler(HttpMessageHandler inner, string mode) : DelegatingHandler(inner) +{ + public List SentRecords { get; } = []; + public List SentPayloadHashes { get; } = []; + public int TerminalResponses { get; private set; } + public int ConflictResponses { get; private set; } + public int UnknownResponses { get; private set; } + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken token) + { + if (mode is "terminal-seed" or "transient-seed") throw new BeforeDeliveryException(); + var wireBytes = await request.Content!.ReadAsByteArrayAsync(token); + SentPayloadHashes.Add(Convert.ToHexString(SHA256.HashData(wireBytes))); + using var payload = JsonDocument.Parse(wireBytes); + SentRecords.Add(payload.RootElement.GetProperty("recordId").GetInt32()); + if (mode == "legacy") + { + if (payload.RootElement.TryGetProperty("eventId", out _) || + payload.RootElement.TryGetProperty("sequence", out _)) + throw new InvalidDataException("Legacy report included ordered protocol fields."); + } + var response = await base.SendAsync(request, token); + if (mode == "unknown-response") + { + using (response) + { + if (response.StatusCode != HttpStatusCode.OK) + throw new InvalidDataException("Server failed before response replacement."); + using var result = JsonDocument.Parse(await response.Content.ReadAsStringAsync(token)); + if (result.RootElement.GetProperty("code").GetInt32() != 200 || + !result.RootElement.GetProperty("body").GetBoolean()) + throw new InvalidDataException("Server did not commit before response replacement."); + } + UnknownResponses++; + return new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent("{\"code\":400,\"body\":false,\"errorCode\":\"Unrecognized\"}") + }; + } + if (mode.StartsWith("terminal-", StringComparison.Ordinal) || mode == "conflict") + { + using var result = JsonDocument.Parse(await response.Content.ReadAsStringAsync(token)); + if (response.StatusCode == HttpStatusCode.OK && + result.RootElement.GetProperty("code").GetInt32() == 400 && + result.RootElement.GetProperty("body").ValueKind == JsonValueKind.False) + { + var error = result.RootElement.GetProperty("errorCode").GetString(); + if (error == "ReportTerminalConflict") TerminalResponses++; + if (error == "Conflict") ConflictResponses++; + } + } + if (mode != "lost") return response; + using (response) + { + if (response.StatusCode != HttpStatusCode.OK) + throw new InvalidOperationException("Server did not return HTTP success before response loss."); + using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync(token)); + if (json.RootElement.GetProperty("code").GetInt32() != 200 || + !json.RootElement.GetProperty("body").GetBoolean()) + throw new InvalidOperationException("Server did not confirm report before response loss."); + } + throw new LostResponseException(); + } +} diff --git a/tests/RealReportHarness/RealReportHarness.csproj b/tests/RealReportHarness/RealReportHarness.csproj new file mode 100644 index 00000000..601478a7 --- /dev/null +++ b/tests/RealReportHarness/RealReportHarness.csproj @@ -0,0 +1,11 @@ + + + Exe + net10.0 + enable + enable + + + + + diff --git a/tests/ReportWorker/Program.cs b/tests/ReportWorker/Program.cs index efd1a059..9030b002 100644 --- a/tests/ReportWorker/Program.cs +++ b/tests/ReportWorker/Program.cs @@ -12,11 +12,21 @@ private static async Task Main(string[] args) { if (args.Length != 2) return 2; using var client = new HttpClient(new Handler(args[1])); - var reporter = new OrderedUpdateReporter(args[0], client, "https://example.test/report", "tenant/database", true); + var reporter = new OrderedUpdateReporter(args[0], client, "https://example.test/report", "tenant/database", true, + terminalRejectionConfirmed: args[1] == "terminal" || args[1] == "inspect"); + if (args[1] == "inspect") + { + var quarantined = await reporter.GetQuarantinedAsync(); + return quarantined.Count == 1 && quarantined[0].Reason == "ReportTerminalConflict" ? 0 : 1; + } try { await reporter.ReportAsync(new UpdateReport(10, 3)); } + catch (InvalidOperationException) when (args[1] == "terminal") + { + return (await reporter.GetQuarantinedAsync()).Count == 1 ? 0 : 1; + } catch (HttpRequestException) { return 0; @@ -39,6 +49,8 @@ protected override async Task SendAsync(HttpRequestMessage await Task.Delay(Timeout.InfiniteTimeSpan, token); } if (mode == "offline") throw new HttpRequestException("offline"); + if (mode == "terminal") + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("{\"code\":400,\"body\":false,\"errorCode\":\"ReportTerminalConflict\"}") }; return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("{\"code\":200,\"body\":true}") }; } }