From 5bd4a779dfe638d0350876bb0db7a47bbdf67656 Mon Sep 17 00:00:00 2001 From: Jennifer Davis Date: Fri, 13 Nov 2026 23:50:03 +0000 Subject: [PATCH] feat(workflows): Add end-to-end idempotent HTTP call samples Retrying a timed-out HTTP step or a failed workflow execution risks running downstream side effects twice unless both tiers coordinate on a client-supplied key. Claiming each order with a Firestore lease and forwarding an Idempotency-Key outside the transaction guarantees at-most-once execution across retries. --- workflows/idempotent_payment/.python-version | 1 + workflows/idempotent_payment/README.md | 49 +++ workflows/idempotent_payment/__init__.py | 13 + workflows/idempotent_payment/main.py | 172 ++++++++++ .../idempotent_payment/noxfile_config.py | 42 +++ .../idempotent_payment/requirements-test.txt | 2 + workflows/idempotent_payment/requirements.txt | 6 + .../idempotent_payment/tests/__init__.py | 13 + .../idempotent_payment/tests/conftest.py | 24 ++ .../tests/integration_test.py | 182 +++++++++++ .../idempotent_payment/tests/main_test.py | 295 ++++++++++++++++++ workflows/idempotent_payment/workflow.yaml | 84 +++++ workflows/payment_provider/__init__.py | 13 + workflows/payment_provider/main.py | 131 ++++++++ workflows/payment_provider/noxfile_config.py | 42 +++ .../payment_provider/requirements-test.txt | 1 + workflows/payment_provider/requirements.txt | 3 + workflows/payment_provider/tests/__init__.py | 13 + workflows/payment_provider/tests/conftest.py | 19 ++ workflows/payment_provider/tests/main_test.py | 157 ++++++++++ 20 files changed, 1262 insertions(+) create mode 100644 workflows/idempotent_payment/.python-version create mode 100644 workflows/idempotent_payment/README.md create mode 100644 workflows/idempotent_payment/__init__.py create mode 100644 workflows/idempotent_payment/main.py create mode 100644 workflows/idempotent_payment/noxfile_config.py create mode 100644 workflows/idempotent_payment/requirements-test.txt create mode 100644 workflows/idempotent_payment/requirements.txt create mode 100644 workflows/idempotent_payment/tests/__init__.py create mode 100644 workflows/idempotent_payment/tests/conftest.py create mode 100644 workflows/idempotent_payment/tests/integration_test.py create mode 100644 workflows/idempotent_payment/tests/main_test.py create mode 100644 workflows/idempotent_payment/workflow.yaml create mode 100644 workflows/payment_provider/__init__.py create mode 100644 workflows/payment_provider/main.py create mode 100644 workflows/payment_provider/noxfile_config.py create mode 100644 workflows/payment_provider/requirements-test.txt create mode 100644 workflows/payment_provider/requirements.txt create mode 100644 workflows/payment_provider/tests/__init__.py create mode 100644 workflows/payment_provider/tests/conftest.py create mode 100644 workflows/payment_provider/tests/main_test.py diff --git a/workflows/idempotent_payment/.python-version b/workflows/idempotent_payment/.python-version new file mode 100644 index 00000000000..24ee5b1be99 --- /dev/null +++ b/workflows/idempotent_payment/.python-version @@ -0,0 +1 @@ +3.13 diff --git a/workflows/idempotent_payment/README.md b/workflows/idempotent_payment/README.md new file mode 100644 index 00000000000..72fd4580f91 --- /dev/null +++ b/workflows/idempotent_payment/README.md @@ -0,0 +1,49 @@ +# Make HTTP calls idempotent from Cloud Workflows + +When a workflow retries a timed-out HTTP call, or a client retries a workflow execution, neither caller knows whether the downstream service already ran. This sample pairs a Cloud Workflow with a Cloud Run function backed by Firestore so each request runs its side effect at most once, using an order payment as the example. + +The workflow claims the request in Firestore by client-supplied ID (or resumes from the stored state on conflict), and the function holds a short lease while calling an external provider with an `Idempotency-Key` outside the transaction. + +## Deploy + +Set `PROJECT_ID`, `REGION`, `SERVICE_ACCOUNT` (needs `roles/datastore.user` and `roles/run.invoker`), and `DATABASE` (for example `(default)` for a Firestore Native database). + +Deploy the stand-in payment provider first (in production, point `PAYMENT_PROVIDER_URL` at your provider's API instead): + +```sh +gcloud functions deploy payment-provider --gen2 --runtime=python313 \ + --region="$REGION" --source=../payment_provider --entry-point=payment_provider \ + --trigger-http --no-allow-unauthenticated --service-account="$SERVICE_ACCOUNT" \ + --set-env-vars="FIRESTORE_DATABASE=$DATABASE" --project="$PROJECT_ID" + +PROVIDER_URL=$(gcloud functions describe payment-provider --gen2 \ + --region="$REGION" --project="$PROJECT_ID" --format='value(serviceConfig.uri)') +``` + +Deploy the idempotent function and the workflow: + +```sh +gcloud functions deploy process-payment --gen2 --runtime=python313 \ + --region="$REGION" --source=. --entry-point=process_payment \ + --trigger-http --no-allow-unauthenticated --service-account="$SERVICE_ACCOUNT" \ + --set-env-vars="FIRESTORE_DATABASE=$DATABASE,PAYMENT_PROVIDER_URL=$PROVIDER_URL" \ + --project="$PROJECT_ID" + +FUNCTION_URL=$(gcloud functions describe process-payment --gen2 \ + --region="$REGION" --project="$PROJECT_ID" --format='value(serviceConfig.uri)') + +gcloud workflows deploy idempotent-order-workflow --source=workflow.yaml \ + --location="$REGION" --service-account="$SERVICE_ACCOUNT" \ + --set-env-vars="PAYMENT_FUNCTION_URL=$FUNCTION_URL,FIRESTORE_DATABASE=$DATABASE" \ + --project="$PROJECT_ID" +``` + +## Test + +```sh +pytest tests/main_test.py + +RUN_INTEGRATION_TESTS=true GOOGLE_CLOUD_PROJECT="$PROJECT_ID" \ + GOOGLE_CLOUD_LOCATION="$REGION" FIRESTORE_DATABASE="$DATABASE" \ + pytest tests/integration_test.py +``` diff --git a/workflows/idempotent_payment/__init__.py b/workflows/idempotent_payment/__init__.py new file mode 100644 index 00000000000..58d482ea386 --- /dev/null +++ b/workflows/idempotent_payment/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/workflows/idempotent_payment/main.py b/workflows/idempotent_payment/main.py new file mode 100644 index 00000000000..a2512704904 --- /dev/null +++ b/workflows/idempotent_payment/main.py @@ -0,0 +1,172 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# With a real payment provider, replace the ID token with the provider's own +# credentials, such as an API key in Secret Manager. Keep the Idempotency-Key. + +# [START workflows_idempotent_process_payment] +import datetime +import os +import uuid + +import flask +import functions_framework +from google.api_core import exceptions +from google.auth.transport.requests import Request +from google.cloud import firestore +from google.oauth2 import id_token +import requests + +# Longer than a payment takes, so only a crashed attempt's claim expires. +LEASE = datetime.timedelta(minutes=2) +# The payment provider's base URL. Required: the function fails to start without it. +PAYMENT_PROVIDER_URL = os.environ["PAYMENT_PROVIDER_URL"] +# Later states, such as refunded, are final: retrying the order doesn't charge again. +CHARGEABLE_STATES = ("created", "payment_failed", "payment_in_progress") +# Errors that can succeed on retry. Firestore raises a ValueError caused by +# Aborted when a transaction runs out of attempts under contention. +TEMPORARY_ERRORS = ( + exceptions.Aborted, + exceptions.DeadlineExceeded, + exceptions.InternalServerError, + exceptions.ServiceUnavailable, + exceptions.TooManyRequests, +) + +db = firestore.Client(database=os.environ.get("FIRESTORE_DATABASE", "(default)")) + + +def is_temporary(err: Exception) -> bool: + """Returns True if the error, or the error that caused it, is temporary.""" + cause = err.__cause__ or err.__context__ + return isinstance(err, TEMPORARY_ERRORS) or isinstance(cause, TEMPORARY_ERRORS) + + +def payment_status(order: dict | None, now: datetime.datetime) -> str: + """Returns what to do with the order: charge it, or why not.""" + if order is None: + return "missing" + if order["order_state"] == "paid": + return "paid" + if order["order_state"] == "payment_in_progress" and order["lease_expires"] > now: + return "in_progress" + if order["order_state"] not in CHARGEABLE_STATES: + return "final" + return "chargeable" + + +@firestore.transactional +def claim_payment( + transaction: firestore.Transaction, + order_ref: firestore.DocumentReference, + attempt_id: str, + now: datetime.datetime, +) -> tuple[str, int]: + """Claims the order's payment unless it's paid or another attempt holds it. + + Returns the order's status and amount. + """ + order = order_ref.get(transaction=transaction).to_dict() + status = payment_status(order, now) + if status == "chargeable": + transaction.update( + order_ref, + { + "order_state": "payment_in_progress", + "attempt_id": attempt_id, + "lease_expires": now + LEASE, + }, + ) + status = "claimed" + return status, (order or {}).get("amount_cents", 0) + + +@firestore.transactional +def finish_payment( + transaction: firestore.Transaction, + order_ref: firestore.DocumentReference, + attempt_id: str, + order_state: str, +) -> None: + """Records the result, if this attempt still holds the claim.""" + snapshot = order_ref.get(transaction=transaction) + if snapshot.exists and snapshot.to_dict().get("attempt_id") == attempt_id: + transaction.update(order_ref, {"order_state": order_state}) + + +def charge(order_id: str, amount_cents: int) -> None: + """Charges the order through the payment provider, at most once per order ID.""" + token = id_token.fetch_id_token(Request(), PAYMENT_PROVIDER_URL) + response = requests.post( + f"{PAYMENT_PROVIDER_URL}/charges", + json={"order_id": order_id, "amount_cents": amount_cents}, + # The provider charges each idempotency key only once, so a retry + # after an ambiguous failure can't charge the customer twice. + headers={"Authorization": f"Bearer {token}", "Idempotency-Key": order_id}, + timeout=30, + ) + response.raise_for_status() + + +def pay(order_id: str) -> tuple[dict, int]: + """Charges the order unless it's already paid, final, or in progress.""" + order_ref = db.collection("orders").document(order_id) + attempt_id = uuid.uuid4().hex + now = datetime.datetime.now(datetime.timezone.utc) + + # Most retries find the order paid or in progress. Checking with a plain + # read first keeps them out of transactions on this order's document. + status = payment_status(order_ref.get().to_dict(), now) + amount_cents = 0 + if status == "chargeable": + status, amount_cents = claim_payment( + db.transaction(), order_ref, attempt_id, now + ) + if status == "missing": + return {"error": f"order {order_id} not found"}, 404 + if status == "paid": + return {"order_id": order_id, "status": "paid", "already_processed": True}, 200 + if status == "in_progress": + # The workflow's retry policy retries 503 responses after a backoff. + return {"error": "payment in progress"}, 503 + if status == "final": + return {"error": f"order {order_id} can't be charged again"}, 409 + + # Charge outside the transaction: Firestore can rerun a transaction, but it + # can't undo a call to another service. + try: + charge(order_id, amount_cents) + except requests.RequestException as err: + finish_payment(db.transaction(), order_ref, attempt_id, "payment_failed") + return {"error": f"payment failed: {err}"}, 503 + finish_payment(db.transaction(), order_ref, attempt_id, "paid") + return {"order_id": order_id, "status": "paid", "already_processed": False}, 200 + + +@functions_framework.http +def process_payment(request: flask.Request) -> tuple[dict, int]: + """Processes an order's payment once, even when the workflow retries the call.""" + order_id = (request.get_json(silent=True) or {}).get("order_id") + if not order_id: + return {"error": "missing order_id"}, 400 + try: + return pay(str(order_id)) + except Exception as err: + if is_temporary(err): + # Contention or a brief outage: let the workflow retry. + return {"error": f"temporary error: {err}"}, 503 + raise # A permanent error, such as missing permissions: fail with 500. + + +# [END workflows_idempotent_process_payment] diff --git a/workflows/idempotent_payment/noxfile_config.py b/workflows/idempotent_payment/noxfile_config.py new file mode 100644 index 00000000000..95c2d9ac875 --- /dev/null +++ b/workflows/idempotent_payment/noxfile_config.py @@ -0,0 +1,42 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Default TEST_CONFIG_OVERRIDE for python repos. + +# You can copy this file into your directory, then it will be imported from +# the noxfile.py. + +# The source of truth: +# https://github.com/GoogleCloudPlatform/python-docs-samples/blob/main/noxfile_config.py + +TEST_CONFIG_OVERRIDE = { + # You can opt out from the test for specific Python versions. + "ignored_versions": ["2.7", "3.7", "3.8", "3.9", "3.10", "3.11", "3.12"], + # Old samples are opted out of enforcing Python type hints + # All new samples should feature them + "enforce_type_hints": True, + # An envvar key for determining the project id to use. Change it + # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a + # build specific Cloud project. You can also use your own string + # to use your own Cloud project. + "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", + # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', + # If you need to use a specific version of pip, + # change pip_version_override to the string representation + # of the version number, for example, "20.2.4" + "pip_version_override": None, + # A dictionary you want to inject into your test. Don't put any + # secrets here. These values will override predefined values. + "envs": {}, +} diff --git a/workflows/idempotent_payment/requirements-test.txt b/workflows/idempotent_payment/requirements-test.txt new file mode 100644 index 00000000000..19d9a802dcf --- /dev/null +++ b/workflows/idempotent_payment/requirements-test.txt @@ -0,0 +1,2 @@ +google-cloud-workflows==1.24.0 +pytest==9.2.0 diff --git a/workflows/idempotent_payment/requirements.txt b/workflows/idempotent_payment/requirements.txt new file mode 100644 index 00000000000..e9565e230b0 --- /dev/null +++ b/workflows/idempotent_payment/requirements.txt @@ -0,0 +1,6 @@ +flask==3.1.3 +functions-framework==3.10.2 +google-api-core==2.44.0 +google-auth==2.62.2 +google-cloud-firestore==2.34.1 +requests==2.34.2 diff --git a/workflows/idempotent_payment/tests/__init__.py b/workflows/idempotent_payment/tests/__init__.py new file mode 100644 index 00000000000..58d482ea386 --- /dev/null +++ b/workflows/idempotent_payment/tests/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/workflows/idempotent_payment/tests/conftest.py b/workflows/idempotent_payment/tests/conftest.py new file mode 100644 index 00000000000..253d7525145 --- /dev/null +++ b/workflows/idempotent_payment/tests/conftest.py @@ -0,0 +1,24 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +from unittest import mock + +# main.py creates a Firestore client when it's imported. Without credentials +# that fails, so unit-test runs replace the client class. The unit tests then +# swap in a fake database, and the integration tests use a real one. +if os.environ.get("RUN_INTEGRATION_TESTS") != "true": + mock.patch("google.cloud.firestore.Client").start() + # main.py requires this setting; unit tests never call the provider. + os.environ.setdefault("PAYMENT_PROVIDER_URL", "https://payments.example.com") diff --git a/workflows/idempotent_payment/tests/integration_test.py b/workflows/idempotent_payment/tests/integration_test.py new file mode 100644 index 00000000000..4be919a31b3 --- /dev/null +++ b/workflows/idempotent_payment/tests/integration_test.py @@ -0,0 +1,182 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Fault-injection tests that run the order workflow end to end. + +These tests are skipped unless RUN_INTEGRATION_TESTS is "true". They need the +workflow (workflow.yaml), the payment function (main.py), and the stand-in +payment provider (../payment_provider) deployed, and: + GOOGLE_CLOUD_PROJECT, GOOGLE_CLOUD_LOCATION (default 'us-central1'), + WORKFLOW_ID (default 'idempotent-order-workflow'), and FIRESTORE_DATABASE. + +Each test checks how many times the stand-in payment service charged. +""" + +import concurrent.futures +import datetime +import json +import os +import time +from typing import Any, Iterator +import uuid + +from google.cloud import firestore +from google.cloud.workflows import executions_v1 +import pytest + +pytestmark = pytest.mark.skipif( + os.environ.get("RUN_INTEGRATION_TESTS") != "true", + reason="Set RUN_INTEGRATION_TESTS=true to run integration tests.", +) + +PROJECT_ID = os.environ.get("GOOGLE_CLOUD_PROJECT", "") +LOCATION_ID = os.environ.get("GOOGLE_CLOUD_LOCATION", "us-central1") +WORKFLOW_ID = os.environ.get("WORKFLOW_ID", "idempotent-order-workflow") +DATABASE = os.environ.get("FIRESTORE_DATABASE", "(default)") +AMOUNT_CENTS = 1999 + + +@pytest.fixture(scope="module") +def db() -> firestore.Client: + return firestore.Client(database=DATABASE) + + +@pytest.fixture +def order_id(db: firestore.Client) -> Iterator[str]: + """Provides a unique order ID and deletes its test records afterward.""" + order_id = f"test-order-{uuid.uuid4().hex[:12]}" + yield order_id + for collection in ("orders", "payment_provider_charges", "payment_provider_faults"): + db.collection(collection).document(order_id).delete() + + +def run_workflow(order_id: str) -> executions_v1.Execution: + """Runs the workflow for an order and waits for the execution to finish.""" + client = executions_v1.ExecutionsClient() + parent = f"projects/{PROJECT_ID}/locations/{LOCATION_ID}/workflows/{WORKFLOW_ID}" + argument = json.dumps({"order_id": order_id, "amount_cents": AMOUNT_CENTS}) + execution = client.create_execution( + parent=parent, execution=executions_v1.Execution(argument=argument) + ) + deadline = time.monotonic() + 600 + while execution.state == executions_v1.Execution.State.ACTIVE: + assert time.monotonic() < deadline, "The execution didn't finish." + time.sleep(3) + execution = client.get_execution(name=execution.name) + assert execution.state == executions_v1.Execution.State.SUCCEEDED, execution.error + return execution + + +def charge_record(db: firestore.Client, order_id: str) -> dict[str, Any]: + snapshot = db.collection("payment_provider_charges").document(order_id).get() + assert snapshot.exists, "The payment service wasn't called." + return snapshot.to_dict() + + +def order_state(db: firestore.Client, order_id: str) -> str: + return db.collection("orders").document(order_id).get().to_dict()["order_state"] + + +def test_duplicate_execution_charges_once(db: firestore.Client, order_id: str) -> None: + first = json.loads(run_workflow(order_id).result) + second = json.loads(run_workflow(order_id).result) + + assert first["already_processed"] is False + assert second["already_processed"] is True + assert charge_record(db, order_id)["status"] == "charged" + assert order_state(db, order_id) == "paid" + + +def test_client_retry_resumes_after_partial_failure( + db: firestore.Client, order_id: str +) -> None: + # A previous execution created the order and then failed before payment. + db.collection("orders").document(order_id).set( + {"order_state": "created", "amount_cents": AMOUNT_CENTS} + ) + + run_workflow(order_id) + + assert order_state(db, order_id) == "paid" + assert charge_record(db, order_id)["status"] == "charged" + + +def test_ambiguous_payment_failure_charges_once( + db: firestore.Client, order_id: str +) -> None: + # The payment service charges, then responds with a gateway timeout. + db.collection("payment_provider_faults").document(order_id).set( + {"mode": "fail_after_charge"} + ) + + run_workflow(order_id) + + record = charge_record(db, order_id) + assert record["status"] == "charged" + assert record["requests"] >= 2 + assert order_state(db, order_id) == "paid" + + +def test_timeouts_at_two_tiers_charge_once(db: firestore.Client, order_id: str) -> None: + # The payment service charges, then responds after both the payment + # function and the workflow stop waiting. + db.collection("payment_provider_faults").document(order_id).set( + {"mode": "slow_after_charge", "seconds": 45} + ) + + run_workflow(order_id) + + assert charge_record(db, order_id)["status"] == "charged" + assert order_state(db, order_id) == "paid" + + +def test_crashed_attempt_is_taken_over(db: firestore.Client, order_id: str) -> None: + # An earlier attempt claimed the payment and crashed; its claim expired. + expired = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta( + minutes=5 + ) + db.collection("orders").document(order_id).set( + { + "order_state": "payment_in_progress", + "amount_cents": AMOUNT_CENTS, + "attempt_id": "crashed-attempt", + "lease_expires": expired, + } + ) + + run_workflow(order_id) + + assert order_state(db, order_id) == "paid" + assert charge_record(db, order_id)["status"] == "charged" + + +def test_concurrent_executions_charge_once(db: firestore.Client, order_id: str) -> None: + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + results = list(pool.map(run_workflow, [order_id, order_id])) + + outcomes = sorted(json.loads(r.result)["already_processed"] for r in results) + assert outcomes == [False, True] + assert charge_record(db, order_id)["status"] == "charged" + + +def test_order_id_reaches_the_payment_provider( + db: firestore.Client, order_id: str +) -> None: + run_workflow(order_id) + + # The stand-in stores charges by Idempotency-Key, and records the order ID + # from the request body. + record = charge_record(db, order_id) + assert record["order_id"] == order_id + assert record["amount_cents"] == AMOUNT_CENTS diff --git a/workflows/idempotent_payment/tests/main_test.py b/workflows/idempotent_payment/tests/main_test.py new file mode 100644 index 00000000000..4239a333075 --- /dev/null +++ b/workflows/idempotent_payment/tests/main_test.py @@ -0,0 +1,295 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import datetime +import os +import pathlib +import subprocess +import sys +from typing import Any +from unittest import mock + +import flask +from google.api_core import exceptions +import pytest +import requests + +from .. import main + +app = flask.Flask(__name__) +ORDER_ID = "order-1001" +NOW = datetime.datetime.now(datetime.timezone.utc) + + +class FakeSnapshot: + def __init__(self, data: dict[str, Any] | None) -> None: + self._data = data + self.exists = data is not None + + def to_dict(self) -> dict[str, Any] | None: + return None if self._data is None else dict(self._data) + + +class FakeDocument: + def __init__(self, store: dict[str, dict[str, Any]], doc_id: str) -> None: + self.store = store + self.id = doc_id + + def get(self, transaction: object = None) -> FakeSnapshot: + return FakeSnapshot(self.store.get(self.id)) + + +class FakeDatabase: + """An in-memory stand-in for the orders collection.""" + + def __init__(self) -> None: + self.store: dict[str, dict[str, Any]] = {} + + def collection(self, name: str) -> mock.MagicMock: + collection = mock.MagicMock() + collection.document.side_effect = lambda doc_id: FakeDocument( + self.store, doc_id + ) + return collection + + def transaction(self) -> mock.MagicMock: + # firestore.transactional begins, commits, and retries the transaction. + transaction = mock.MagicMock(_max_attempts=1, _id=b"test", _read_only=False) + transaction.update.side_effect = lambda ref, data: self.store[ref.id].update( + data + ) + return transaction + + +@pytest.fixture +def db(monkeypatch: pytest.MonkeyPatch) -> FakeDatabase: + database = FakeDatabase() + monkeypatch.setattr(main, "db", database) + return database + + +@pytest.fixture +def charge(monkeypatch: pytest.MonkeyPatch) -> mock.MagicMock: + charge_mock = mock.MagicMock() + monkeypatch.setattr(main, "charge", charge_mock) + return charge_mock + + +def create_order(db: FakeDatabase, **fields: object) -> dict[str, Any]: + db.store[ORDER_ID] = {"order_state": "created", "amount_cents": 1999, **fields} + return db.store[ORDER_ID] + + +def call(body: dict[str, Any] | None = None) -> tuple[dict, int]: + body = {"order_id": ORDER_ID} if body is None else body + with app.test_request_context("/", method="POST", json=body): + return main.process_payment(flask.request) + + +def test_new_order_is_charged_once(db: FakeDatabase, charge: mock.MagicMock) -> None: + order = create_order(db) + + body, status = call() + + assert status == 200 + assert body["already_processed"] is False + charge.assert_called_once_with(ORDER_ID, 1999) + assert order["order_state"] == "paid" + + +def test_paid_order_is_not_charged_again( + db: FakeDatabase, charge: mock.MagicMock +) -> None: + create_order(db, order_state="paid") + + body, status = call() + + assert (status, body["already_processed"]) == (200, True) + charge.assert_not_called() + + +def test_refunded_order_is_not_charged_again( + db: FakeDatabase, charge: mock.MagicMock +) -> None: + order = create_order(db, order_state="refunded") + + _, status = call() + + assert status == 409 + charge.assert_not_called() + assert order["order_state"] == "refunded" + + +def test_order_with_active_claim_returns_503( + db: FakeDatabase, charge: mock.MagicMock +) -> None: + create_order( + db, + order_state="payment_in_progress", + attempt_id="other-attempt", + lease_expires=NOW + main.LEASE, + ) + + _, status = call() + + assert status == 503 + charge.assert_not_called() + + +@pytest.mark.parametrize( + "fields", + [ + { + "order_state": "payment_in_progress", + "attempt_id": "crashed-attempt", + "lease_expires": NOW - datetime.timedelta(seconds=1), + }, + {"order_state": "payment_failed"}, + ], + ids=["expired_claim", "failed_payment"], +) +def test_unfinished_order_is_charged( + db: FakeDatabase, charge: mock.MagicMock, fields: dict[str, Any] +) -> None: + order = create_order(db, **fields) + + _, status = call() + + assert status == 200 + charge.assert_called_once() + assert order["order_state"] == "paid" + + +def test_ambiguous_payment_failure_is_retryable( + db: FakeDatabase, charge: mock.MagicMock +) -> None: + order = create_order(db) + charge.side_effect = requests.Timeout("timed out") + + _, status = call() + + assert status == 503 + assert order["order_state"] == "payment_failed" + + +def test_stale_attempt_does_not_overwrite_newer_claim( + db: FakeDatabase, charge: mock.MagicMock +) -> None: + order = create_order(db) + # While this attempt charges, its lease expires and a retry claims the order. + charge.side_effect = lambda *args: order.update(attempt_id="newer-attempt") + + call() + + assert order["order_state"] == "payment_in_progress" + assert order["attempt_id"] == "newer-attempt" + + +@pytest.mark.parametrize( + "body, expected_status", + [({}, 400), ({"order_id": "missing-order"}, 404)], +) +def test_bad_requests( + db: FakeDatabase, + charge: mock.MagicMock, + body: dict[str, Any], + expected_status: int, +) -> None: + _, status = call(body) + + assert status == expected_status + charge.assert_not_called() + + +def test_charge_sends_order_id_as_idempotency_key( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(main, "PAYMENT_PROVIDER_URL", "https://payments.example.com") + monkeypatch.setattr(main.id_token, "fetch_id_token", lambda *args: "token") + post = mock.MagicMock() + monkeypatch.setattr(main.requests, "post", post) + + main.charge(ORDER_ID, 1999) + + kwargs = post.call_args.kwargs + assert post.call_args.args == ("https://payments.example.com/charges",) + assert kwargs["headers"]["Idempotency-Key"] == ORDER_ID + assert kwargs["headers"]["Authorization"] == "Bearer token" + assert kwargs["json"] == {"order_id": ORDER_ID, "amount_cents": 1999} + + +def test_paid_order_skips_the_transaction( + db: FakeDatabase, charge: mock.MagicMock, monkeypatch: pytest.MonkeyPatch +) -> None: + create_order(db, order_state="paid") + transaction = mock.MagicMock() + monkeypatch.setattr(db, "transaction", transaction) + + _, status = call() + + assert status == 200 + transaction.assert_not_called() + + +def contention_error() -> ValueError: + """Builds the error Firestore raises when a transaction runs out of attempts.""" + try: + raise ValueError("Failed to commit transaction") from exceptions.Aborted("busy") + except ValueError as err: + return err + + +@pytest.mark.parametrize( + "error", + [contention_error(), exceptions.DeadlineExceeded("slow")], + ids=["contention", "deadline"], +) +def test_temporary_database_error_returns_503( + db: FakeDatabase, + charge: mock.MagicMock, + monkeypatch: pytest.MonkeyPatch, + error: Exception, +) -> None: + create_order(db) + monkeypatch.setattr(main, "claim_payment", mock.MagicMock(side_effect=error)) + + _, status = call() + + assert status == 503 + charge.assert_not_called() + + +def test_permanent_database_error_is_not_retried( + db: FakeDatabase, charge: mock.MagicMock, monkeypatch: pytest.MonkeyPatch +) -> None: + create_order(db) + error = exceptions.PermissionDenied("missing roles/datastore.user") + monkeypatch.setattr(main, "claim_payment", mock.MagicMock(side_effect=error)) + + with pytest.raises(exceptions.PermissionDenied): + call() + + +def test_function_requires_payment_provider_url() -> None: + env = {k: v for k, v in os.environ.items() if k != "PAYMENT_PROVIDER_URL"} + result = subprocess.run( + [sys.executable, "-c", "import main"], + cwd=pathlib.Path(main.__file__).parent, + env=env, + capture_output=True, + text=True, + ) + + assert result.returncode != 0 + assert "KeyError: 'PAYMENT_PROVIDER_URL'" in result.stderr diff --git a/workflows/idempotent_payment/workflow.yaml b/workflows/idempotent_payment/workflow.yaml new file mode 100644 index 00000000000..0dac95ec9ad --- /dev/null +++ b/workflows/idempotent_payment/workflow.yaml @@ -0,0 +1,84 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Processes an order once per client-supplied order_id, even when the client +# retries the execution or the workflow retries the payment call. +# Deploy with the PAYMENT_FUNCTION_URL environment variable, and optionally +# FIRESTORE_DATABASE. + +# [START workflows_idempotent_order_workflow] +main: + params: [args] + steps: + - init: + assign: + - order_id: ${string(args.order_id)} + - database: ${default(sys.get_env("FIRESTORE_DATABASE"), "(default)")} + - documents: ${"projects/" + sys.get_env("GOOGLE_CLOUD_PROJECT_ID") + "/databases/" + database + "/documents"} + - create_order: + try: + # Creating a document with the order ID fails with 409 if it exists, + # so concurrent executions can't both create the order. + call: googleapis.firestore.v1.projects.databases.documents.createDocument + args: + collectionId: orders + parent: ${documents} + documentId: ${order_id} + body: + fields: + order_state: + stringValue: created + amount_cents: + integerValue: ${string(args.amount_cents)} + except: + as: e + steps: + - check_conflict: + switch: + - condition: ${map.get(e, "code") == 409} + next: read_order + - unhandled_error: + raise: ${e} + next: call_payment + - read_order: + # A retried request finds the existing order and resumes from its state, + # instead of exiting and leaving an unpaid order behind. + call: googleapis.firestore.v1.projects.databases.documents.get + args: + name: ${documents + "/orders/" + order_id} + result: existing_order + - check_state: + switch: + - condition: ${existing_order.fields.order_state.stringValue == "paid"} + return: + order_id: ${order_id} + status: paid + already_processed: true + - call_payment: + try: + call: http.post + args: + url: ${sys.get_env("PAYMENT_FUNCTION_URL")} + auth: + type: OIDC + body: + order_id: ${order_id} + timeout: 30 + result: payment + # The payment function is idempotent, so retrying timeouts and + # 429, 502, 503, and 504 responses can't charge twice. + retry: ${http.default_retry} + - finish: + return: ${payment.body} +# [END workflows_idempotent_order_workflow] diff --git a/workflows/payment_provider/__init__.py b/workflows/payment_provider/__init__.py new file mode 100644 index 00000000000..58d482ea386 --- /dev/null +++ b/workflows/payment_provider/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/workflows/payment_provider/main.py b/workflows/payment_provider/main.py new file mode 100644 index 00000000000..8cd806433e9 --- /dev/null +++ b/workflows/payment_provider/main.py @@ -0,0 +1,131 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# A stand-in for a real payment provider, used by the idempotent_payment and +# order_saga samples. Deploy it as a Cloud Run function and set its URL as +# PAYMENT_PROVIDER_URL on the functions that call it. To simulate an ambiguous +# failure, create a document in payment_provider_faults with the charge's +# Idempotency-Key as its ID and a mode of "fail_after_charge" (charge, then +# respond 504) or "slow_after_charge" (charge, then respond after `seconds`). + +# [START workflows_payment_provider] +import os +import time +import uuid + +import flask +import functions_framework +from google.cloud import firestore + +db = firestore.Client(database=os.environ.get("FIRESTORE_DATABASE", "(default)")) +charges = db.collection("payment_provider_charges") + + +@firestore.transactional +def record_charge( + transaction: firestore.Transaction, + charge_ref: firestore.DocumentReference, + order_id: str, + amount_cents: int, +) -> dict: + """Charges once per key. Returns the charge, new or existing.""" + snapshot = charge_ref.get(transaction=transaction) + if snapshot.exists: + transaction.update(charge_ref, {"requests": firestore.Increment(1)}) + return snapshot.to_dict() + charge = { + "charge_id": uuid.uuid4().hex, + "order_id": order_id, + "amount_cents": amount_cents, + "status": "charged", + "requests": 1, + } + transaction.set(charge_ref, charge) + return charge + + +@firestore.transactional +def record_refund( + transaction: firestore.Transaction, charge_ref: firestore.DocumentReference +) -> bool: + """Refunds the charge once. Returns True if money was charged and refunded. + + If the charge doesn't exist yet, voids its key, so a charge request that + arrives late is rejected instead of charging after the refund. + """ + snapshot = charge_ref.get(transaction=transaction) + if not snapshot.exists: + transaction.set( + charge_ref, {"status": "voided", "requests": 0, "refund_requests": 1} + ) + return False + status = snapshot.to_dict()["status"] + updates: dict = {"refund_requests": firestore.Increment(1)} + if status == "charged": + updates["status"] = "refunded" + transaction.update(charge_ref, updates) + return status in ("charged", "refunded") + + +def simulate_fault(key: str) -> tuple[dict, int] | None: + """Applies a simulated fault for the key, if one is set.""" + fault_ref = db.collection("payment_provider_faults").document(key) + fault = fault_ref.get() + if not fault.exists: + return None + data = fault.to_dict() + remaining = data.get("remaining", 1) - 1 + if remaining <= 0: + fault_ref.delete() + else: + fault_ref.update({"remaining": remaining}) + if data.get("mode") == "fail_after_charge": + return {"error": "gateway timeout"}, 504 + time.sleep(data.get("seconds", 40)) + return None + + +@functions_framework.http +def payment_provider(request: flask.Request) -> tuple[dict, int]: + """Handles POST /charges and POST /refunds.""" + body = request.get_json(silent=True) or {} + if request.path.endswith("/refunds"): + # Refunds are keyed by the charge, so repeating a refund has no effect. + charge_key = body.get("charge_key") + if not charge_key: + return {"error": "missing charge_key"}, 400 + refunded = record_refund(db.transaction(), charges.document(charge_key)) + fault = simulate_fault(f"refund-{charge_key}") + if fault: + return fault + return {"charge_key": charge_key, "refunded": refunded}, 200 + + key = request.headers.get("Idempotency-Key") + if not key: + return {"error": "missing Idempotency-Key"}, 400 + charge = record_charge( + db.transaction(), + charges.document(key), + body.get("order_id"), + body.get("amount_cents"), + ) + if charge["status"] == "voided": + return {"error": "the charge was cancelled"}, 409 + fault = simulate_fault(key) + if fault: + return fault + return {"charge_id": charge["charge_id"], "status": charge["status"]}, 200 + + +# [END workflows_payment_provider] diff --git a/workflows/payment_provider/noxfile_config.py b/workflows/payment_provider/noxfile_config.py new file mode 100644 index 00000000000..95c2d9ac875 --- /dev/null +++ b/workflows/payment_provider/noxfile_config.py @@ -0,0 +1,42 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Default TEST_CONFIG_OVERRIDE for python repos. + +# You can copy this file into your directory, then it will be imported from +# the noxfile.py. + +# The source of truth: +# https://github.com/GoogleCloudPlatform/python-docs-samples/blob/main/noxfile_config.py + +TEST_CONFIG_OVERRIDE = { + # You can opt out from the test for specific Python versions. + "ignored_versions": ["2.7", "3.7", "3.8", "3.9", "3.10", "3.11", "3.12"], + # Old samples are opted out of enforcing Python type hints + # All new samples should feature them + "enforce_type_hints": True, + # An envvar key for determining the project id to use. Change it + # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a + # build specific Cloud project. You can also use your own string + # to use your own Cloud project. + "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", + # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', + # If you need to use a specific version of pip, + # change pip_version_override to the string representation + # of the version number, for example, "20.2.4" + "pip_version_override": None, + # A dictionary you want to inject into your test. Don't put any + # secrets here. These values will override predefined values. + "envs": {}, +} diff --git a/workflows/payment_provider/requirements-test.txt b/workflows/payment_provider/requirements-test.txt new file mode 100644 index 00000000000..3fdf1e14fe9 --- /dev/null +++ b/workflows/payment_provider/requirements-test.txt @@ -0,0 +1 @@ +pytest==9.2.0 diff --git a/workflows/payment_provider/requirements.txt b/workflows/payment_provider/requirements.txt new file mode 100644 index 00000000000..58a2835e909 --- /dev/null +++ b/workflows/payment_provider/requirements.txt @@ -0,0 +1,3 @@ +flask==3.1.3 +functions-framework==3.10.2 +google-cloud-firestore==2.34.1 diff --git a/workflows/payment_provider/tests/__init__.py b/workflows/payment_provider/tests/__init__.py new file mode 100644 index 00000000000..58d482ea386 --- /dev/null +++ b/workflows/payment_provider/tests/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/workflows/payment_provider/tests/conftest.py b/workflows/payment_provider/tests/conftest.py new file mode 100644 index 00000000000..2a161f5c3bb --- /dev/null +++ b/workflows/payment_provider/tests/conftest.py @@ -0,0 +1,19 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +from unittest import mock + +if os.environ.get("RUN_INTEGRATION_TESTS") != "true": + mock.patch("google.cloud.firestore.Client").start() diff --git a/workflows/payment_provider/tests/main_test.py b/workflows/payment_provider/tests/main_test.py new file mode 100644 index 00000000000..fd9fdbe61d5 --- /dev/null +++ b/workflows/payment_provider/tests/main_test.py @@ -0,0 +1,157 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any +from unittest import mock + +import flask +import pytest + +from .. import main + +app = flask.Flask(__name__) + + +class FakeSnapshot: + def __init__(self, data: dict[str, Any] | None) -> None: + self._data = data + self.exists = data is not None + + def to_dict(self) -> dict[str, Any]: + return dict(self._data or {}) + + +class FakeDocument: + def __init__(self, store: dict[str, dict[str, Any]], doc_id: str) -> None: + self.store = store + self.id = doc_id + + def get(self, transaction: object = None) -> FakeSnapshot: + return FakeSnapshot(self.store.get(self.id)) + + def delete(self) -> None: + self.store.pop(self.id, None) + + +class FakeDatabase: + def __init__(self) -> None: + self.collections: dict[str, dict[str, dict[str, Any]]] = {} + + def collection(self, name: str) -> mock.MagicMock: + store = self.collections.setdefault(name, {}) + collection = mock.MagicMock() + collection.document.side_effect = lambda doc_id: FakeDocument(store, doc_id) + return collection + + def transaction(self) -> mock.MagicMock: + transaction = mock.MagicMock(_max_attempts=1, _id=b"test", _read_only=False) + transaction.set.side_effect = lambda ref, data: ref.store.__setitem__( + ref.id, dict(data) + ) + + def update(ref: FakeDocument, data: dict[str, Any]) -> None: + record = ref.store[ref.id] + for key, value in data.items(): + if hasattr(value, "value"): + record[key] = record.get(key, 0) + value.value + else: + record[key] = value + + transaction.update.side_effect = update + return transaction + + +@pytest.fixture +def db(monkeypatch: pytest.MonkeyPatch) -> FakeDatabase: + database = FakeDatabase() + monkeypatch.setattr(main, "db", database) + monkeypatch.setattr( + main, "charges", database.collection("payment_provider_charges") + ) + return database + + +def post( + path: str, + body: dict[str, Any] | None = None, + headers: dict[str, str] | None = None, +) -> tuple[dict[str, Any], int]: + with app.test_request_context(path, method="POST", json=body, headers=headers): + return main.payment_provider(flask.request) + + +def test_charges_once_per_idempotency_key(db: FakeDatabase) -> None: + headers = {"Idempotency-Key": "order-1"} + first, status1 = post( + "/charges", {"order_id": "order-1", "amount_cents": 500}, headers + ) + second, status2 = post( + "/charges", {"order_id": "order-1", "amount_cents": 500}, headers + ) + + assert (status1, status2) == (200, 200) + assert first["charge_id"] == second["charge_id"] + assert db.collections["payment_provider_charges"]["order-1"]["requests"] == 2 + + +def test_refund_reverses_existing_charge_once(db: FakeDatabase) -> None: + post( + "/charges", + {"order_id": "order-1", "amount_cents": 500}, + {"Idempotency-Key": "order-1"}, + ) + + first, status1 = post("/refunds", {"charge_key": "order-1"}) + second, status2 = post("/refunds", {"charge_key": "order-1"}) + + assert (status1, first["refunded"]) == (200, True) + assert (status2, second["refunded"]) == (200, True) + assert db.collections["payment_provider_charges"]["order-1"]["status"] == "refunded" + + +def test_refund_before_charge_voids_the_key(db: FakeDatabase) -> None: + refund_body, refund_status = post("/refunds", {"charge_key": "order-2"}) + _, charge_status = post( + "/charges", + {"order_id": "order-2", "amount_cents": 500}, + {"Idempotency-Key": "order-2"}, + ) + + assert (refund_status, refund_body["refunded"]) == (200, False) + assert charge_status == 409 + + +def test_simulated_fault_runs_once_after_charging(db: FakeDatabase) -> None: + db.collection("payment_provider_faults").store = {} + db.collections["payment_provider_faults"]["order-3"] = {"mode": "fail_after_charge"} + headers = {"Idempotency-Key": "order-3"} + + _, first_status = post( + "/charges", {"order_id": "order-3", "amount_cents": 500}, headers + ) + _, retry_status = post( + "/charges", {"order_id": "order-3", "amount_cents": 500}, headers + ) + + assert (first_status, retry_status) == (504, 200) + assert db.collections["payment_provider_charges"]["order-3"]["status"] == "charged" + + +@pytest.mark.parametrize("path, body", [("/charges", {}), ("/refunds", {})]) +def test_missing_keys_are_rejected( + db: FakeDatabase, path: str, body: dict[str, Any] +) -> None: + _, status = post(path, body) + + assert status == 400