diff --git a/spanner/queues/README.md b/spanner/queues/README.md new file mode 100644 index 0000000000..bd019b165e --- /dev/null +++ b/spanner/queues/README.md @@ -0,0 +1,27 @@ +# Cloud Spanner Queues Samples + +Python samples demonstrating sending immediate and scheduled messages to Cloud Spanner queues, streaming `RECEIVE_` rows, and acknowledging messages. + +## Setup + +1. Create and activate a Python 3.13+ virtual environment: + + ```sh + python3 -m venv env + source env/bin/activate + ``` + +2. Install the samples and their dependencies: + + ```sh + pip install -e . + ``` + +## Running Tests + +Run unit tests offline: + +```sh +pip install -r requirements-test.txt +pytest tests +``` diff --git a/spanner/queues/noxfile_config.py b/spanner/queues/noxfile_config.py new file mode 100644 index 0000000000..fe371aaf48 --- /dev/null +++ b/spanner/queues/noxfile_config.py @@ -0,0 +1,21 @@ +# 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. + +TEST_CONFIG_OVERRIDE = { + "ignored_versions": ["2.7", "3.7", "3.8", "3.9", "3.10", "3.11", "3.12"], + "enforce_type_hints": True, + "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", + "pip_version_override": None, + "envs": {}, +} diff --git a/spanner/queues/pyproject.toml b/spanner/queues/pyproject.toml new file mode 100644 index 0000000000..c15138fe17 --- /dev/null +++ b/spanner/queues/pyproject.toml @@ -0,0 +1,31 @@ +# 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. + +# Local samples only. This package isn't published: install it from this +# directory with `pip install -e .`, never by name from PyPI. +[build-system] +requires = ["setuptools>=64"] +build-backend = "setuptools.build_meta" + +[project] +name = "spanner-queues-samples" +version = "0.0.0" +requires-python = ">=3.13" +# Dependencies are pinned in requirements.txt, the single source of truth. +dynamic = ["dependencies"] +# PyPI rejects uploads with this classifier. +classifiers = ["Private :: Do Not Upload"] + +[tool.setuptools.dynamic] +dependencies = {file = ["requirements.txt"]} diff --git a/spanner/queues/requirements-test.txt b/spanner/queues/requirements-test.txt new file mode 100644 index 0000000000..ac63bdc5a9 --- /dev/null +++ b/spanner/queues/requirements-test.txt @@ -0,0 +1,2 @@ +-e . +pytest==9.2.0 diff --git a/spanner/queues/requirements.txt b/spanner/queues/requirements.txt new file mode 100644 index 0000000000..a56c81cc2e --- /dev/null +++ b/spanner/queues/requirements.txt @@ -0,0 +1,2 @@ +google-api-core==2.44.0 +google-cloud-spanner==3.72.0 diff --git a/spanner/queues/src/spanner_queues/__init__.py b/spanner/queues/src/spanner_queues/__init__.py new file mode 100644 index 0000000000..58d482ea38 --- /dev/null +++ b/spanner/queues/src/spanner_queues/__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/spanner/queues/src/spanner_queues/queue_send_message.py b/spanner/queues/src/spanner_queues/queue_send_message.py new file mode 100644 index 0000000000..cda53c67bd --- /dev/null +++ b/spanner/queues/src/spanner_queues/queue_send_message.py @@ -0,0 +1,102 @@ +# 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. + +# [START spanner_queue_send_message] +import base64 +from datetime import datetime, timezone +import sys +import uuid + +from google.api_core import exceptions +from google.cloud import spanner + + +def send_queue_message(project_id: str, instance_id: str, database_id: str) -> None: + """Sends a message to a Cloud Spanner queue using a Send mutation. + + Args: + project_id: The Google Cloud project ID. + instance_id: The Spanner instance ID. + database_id: The Spanner database ID containing Users and UserTasks. + """ + client = spanner.Client(project=project_id) + database = client.instance(instance_id).database(database_id) + queue_name = "UserTasks" + user_id = 1 + message_id = str(uuid.uuid4()) + # Python protobuf Value encodes BYTES payloads from base64-encoded strings. + encoded_payload = base64.b64encode(b"example-task-payload").decode("ascii") + deliver_time = datetime.now(timezone.utc) + + try: + with database.batch() as batch: + batch.send( + queue=queue_name, + key=[user_id, message_id], + payload=encoded_payload, + deliver_time=deliver_time, + ) + except exceptions.NotFound as err: + print( + f"error: queue '{queue_name}' or parent row on database " + f"'{database_id}' in instance '{instance_id}'" + f" was not found: {err.message}", + file=sys.stderr, + ) + except exceptions.GoogleAPICallError as err: + print( + f"error: failed to send message to queue '{queue_name}' on " + f"database '{database_id}' in instance '{instance_id}'" + f": {err.message}", + file=sys.stderr, + ) + else: + print(f"Resource ID: {database_id}") + print(f"Message ID: {message_id}") + print(f"Queue Name: {queue_name}") + print(f"User ID: {user_id}") + + +# [END spanner_queue_send_message] + + +if __name__ == "__main__": + import argparse + import os + + parser = argparse.ArgumentParser( + description="Send a message to a Cloud Spanner queue." + ) + parser.add_argument( + "--project-id", + default=os.environ.get("GOOGLE_CLOUD_PROJECT", "example-project-id"), + help="Google Cloud project ID (default: $GOOGLE_CLOUD_PROJECT)", + ) + parser.add_argument( + "--instance-id", + default=os.environ.get("SPANNER_INSTANCE_ID", "example-instance"), + help="Spanner instance ID (default: $SPANNER_INSTANCE_ID)", + ) + parser.add_argument( + "--database-id", + default=os.environ.get("SPANNER_DATABASE_ID", "example-db"), + help="Spanner database ID (default: $SPANNER_DATABASE_ID)", + ) + args = parser.parse_args() + + send_queue_message( + project_id=args.project_id, + instance_id=args.instance_id, + database_id=args.database_id, + ) diff --git a/spanner/queues/tests/__init__.py b/spanner/queues/tests/__init__.py new file mode 100644 index 0000000000..58d482ea38 --- /dev/null +++ b/spanner/queues/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/spanner/queues/tests/conftest.py b/spanner/queues/tests/conftest.py new file mode 100644 index 0000000000..eb01c59c97 --- /dev/null +++ b/spanner/queues/tests/conftest.py @@ -0,0 +1,36 @@ +# 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. + +"""Shared live-test configuration for Cloud Spanner Queues Samples.""" + +import os + +import pytest + +LIVE_PROJECT_ID = os.environ.get("GOOGLE_CLOUD_PROJECT", "") +LIVE_INSTANCE_ID = os.environ.get("SPANNER_INSTANCE_ID", "") +LIVE_DATABASE_ID = os.environ.get("SPANNER_DATABASE_ID", "") + +if os.environ.get("RUN_INTEGRATION_TESTS") == "true" and ( + not LIVE_PROJECT_ID or not LIVE_INSTANCE_ID or not LIVE_DATABASE_ID +): + raise RuntimeError( + "Set GOOGLE_CLOUD_PROJECT, SPANNER_INSTANCE_ID, and " + "SPANNER_DATABASE_ID when RUN_INTEGRATION_TESTS=true." + ) + +live_only = pytest.mark.skipif( + os.environ.get("RUN_INTEGRATION_TESTS") != "true", + reason="Set RUN_INTEGRATION_TESTS=true to run integration tests.", +) diff --git a/spanner/queues/tests/queue_send_message_test.py b/spanner/queues/tests/queue_send_message_test.py new file mode 100644 index 0000000000..a8ba138c79 --- /dev/null +++ b/spanner/queues/tests/queue_send_message_test.py @@ -0,0 +1,121 @@ +# 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 runpy +from unittest import mock + +from google.api_core import exceptions +import pytest +from spanner_queues import queue_send_message + +from . import conftest + +PROJECT_ID = "example-project-id" +INSTANCE_ID = "example-instance" +DATABASE_ID = "example-db" +SPANNER_CLIENT = "google.cloud.spanner.Client" + + +@mock.patch(SPANNER_CLIENT, autospec=True) +def test_send_queue_message_success( + mock_client_class: mock.MagicMock, capsys: pytest.CaptureFixture[str] +) -> None: + database = ( + mock_client_class.return_value.instance.return_value.database.return_value + ) + batch = database.batch.return_value.__enter__.return_value + + queue_send_message.send_queue_message(PROJECT_ID, INSTANCE_ID, DATABASE_ID) + + batch.send.assert_called_once() + assert batch.send.call_args.kwargs["queue"] == "UserTasks" + out, err = capsys.readouterr() + assert f"Resource ID: {DATABASE_ID}" in out + assert PROJECT_ID not in out + assert "Queue Name: UserTasks" in out + assert "User ID: 1" in out + assert err == "" + + +@pytest.mark.parametrize( + "error, expected_prefix", + [ + ( + exceptions.NotFound("missing queue"), + "error: queue 'UserTasks' or parent row", + ), + ( + exceptions.PermissionDenied("denied"), + "error: failed to send message to queue 'UserTasks'", + ), + ], +) +@mock.patch(SPANNER_CLIENT, autospec=True) +def test_send_queue_message_errors( + mock_client_class: mock.MagicMock, + capsys: pytest.CaptureFixture[str], + error: Exception, + expected_prefix: str, +) -> None: + database = ( + mock_client_class.return_value.instance.return_value.database.return_value + ) + database.batch.return_value.__enter__.side_effect = error + + queue_send_message.send_queue_message(PROJECT_ID, INSTANCE_ID, DATABASE_ID) + + out, err = capsys.readouterr() + assert out == "" + assert err.startswith(expected_prefix) + assert PROJECT_ID not in err + + +@mock.patch(SPANNER_CLIENT, autospec=True) +def test_send_queue_message_cli_entrypoint( + mock_client_class: mock.MagicMock, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + monkeypatch.setattr( + "sys.argv", + [ + "queue_send_message.py", + "--project-id", + PROJECT_ID, + "--instance-id", + INSTANCE_ID, + "--database-id", + DATABASE_ID, + ], + ) + + runpy.run_module("spanner_queues.queue_send_message", run_name="__main__") + + assert "Queue Name: UserTasks" in capsys.readouterr().out + + +# Live integration test: skipped unless RUN_INTEGRATION_TESTS=true is set along with +# GOOGLE_CLOUD_PROJECT, SPANNER_INSTANCE_ID, and SPANNER_DATABASE_ID. +@conftest.live_only +def test_send_queue_message_live(capsys: pytest.CaptureFixture[str]) -> None: + queue_send_message.send_queue_message( + conftest.LIVE_PROJECT_ID, + conftest.LIVE_INSTANCE_ID, + conftest.LIVE_DATABASE_ID, + ) + + out, err = capsys.readouterr() + assert err == "" + assert "Queue Name: UserTasks" in out + assert "User ID: 1" in out