Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions spanner/queues/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Cloud Spanner Queues Samples

Python samples demonstrating sending immediate and scheduled messages to Cloud Spanner queues, streaming `RECEIVE_<Queue>` 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
```
21 changes: 21 additions & 0 deletions spanner/queues/noxfile_config.py
Original file line number Diff line number Diff line change
@@ -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": {},
}
31 changes: 31 additions & 0 deletions spanner/queues/pyproject.toml
Original file line number Diff line number Diff line change
@@ -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"]}
2 changes: 2 additions & 0 deletions spanner/queues/requirements-test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-e .
pytest==9.2.0
2 changes: 2 additions & 0 deletions spanner/queues/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
google-api-core==2.44.0
google-cloud-spanner==3.72.0
13 changes: 13 additions & 0 deletions spanner/queues/src/spanner_queues/__init__.py
Original file line number Diff line number Diff line change
@@ -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.
102 changes: 102 additions & 0 deletions spanner/queues/src/spanner_queues/queue_send_message.py
Original file line number Diff line number Diff line change
@@ -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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Update the function signature to accept project_id as an optional string (str | None = None). This allows the Spanner client to automatically infer the project ID from Application Default Credentials (ADC) when it is not explicitly provided.

def send_queue_message(
    project_id: str | None, instance_id: str, database_id: str
) -> None:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the suggestion! We are intentionally keeping project_id: str explicit in the sample signature so callers pass configuration directly rather than relying on implicit ADC resolution, and we intentionally omit project identifiers (project_id / client.project) from stdout and stderr output so project metadata is not echoed in logs.

"""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,
)
Comment on lines +50 to +63

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

When project_id is not provided (i.e., it is None to allow ADC inference), printing project_id will output None. Using client.project instead ensures the actual resolved project ID is printed in the error messages.

Suggested change
except exceptions.NotFound as err:
print(
f"error: queue '{queue_name}' or parent row on database "
f"'{database_id}' in instance '{instance_id}' for project "
f"'{project_id}' 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}' for project "
f"'{project_id}': {err.message}",
file=sys.stderr,
)
except exceptions.NotFound as err:
print(
f"error: queue '{queue_name}' or parent row on database "
f"'{database_id}' in instance '{instance_id}' for project "
f"'{client.project}' 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}' for project "
f"'{client.project}': {err.message}",
file=sys.stderr,
)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the suggestion! We are intentionally keeping project_id: str explicit in the sample signature so callers pass configuration directly rather than relying on implicit ADC resolution, and we intentionally omit project identifiers (project_id / client.project) from stdout and stderr output so project metadata is not echoed in logs.

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)",
)
Comment on lines +81 to +85

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

According to the general rules, the --project-id argument should be optional and allow inferring the project from Application Default Credentials (ADC) if not provided. Currently, defaulting to 'example-project-id' prevents ADC from automatically inferring the correct project when the argument and environment variable are omitted.

Setting the default to None (or omitting the default so it defaults to None) allows the Spanner client to fall back to ADC.

Suggested change
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(
"--project-id",
default=os.environ.get("GOOGLE_CLOUD_PROJECT"),
help="Google Cloud project ID (default: inferred from ADC)",
)
References
  1. When using argparse for a command-line script, the --project_id argument can be optional, as the project can be inferred from Application Default Credentials (ADC) if not provided.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the suggestion! We are intentionally keeping project_id: str explicit in the sample signature so callers pass configuration directly rather than relying on implicit ADC resolution, and we intentionally omit project identifiers (project_id / client.project) from stdout and stderr output so project metadata is not echoed in logs.

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,
)
13 changes: 13 additions & 0 deletions spanner/queues/tests/__init__.py
Original file line number Diff line number Diff line change
@@ -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.
36 changes: 36 additions & 0 deletions spanner/queues/tests/conftest.py
Original file line number Diff line number Diff line change
@@ -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.",
)
121 changes: 121 additions & 0 deletions spanner/queues/tests/queue_send_message_test.py
Original file line number Diff line number Diff line change
@@ -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