Skip to content
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
05c0cdc
feat(publisher): degrade PubSubPublisher to noop when GCP credentials…
julietshen Jun 29, 2026
0d5f06c
Merge branch 'main' into julietshen/noop-publisher-fallback
julietshen Jul 6, 2026
f7d7fd6
fix(publisher): address review feedback on noop fallback
julietshen Jul 6, 2026
641717a
docs(changelog): note PubSubPublisher noop fallback
julietshen Jul 7, 2026
3b40c28
test(publisher): force GCP creds in validation-exporter conftest
julietshen Jul 7, 2026
749156e
test(publisher): scope forced-creds patch to function to stop leak
julietshen Jul 9, 2026
f0cee7c
feat(publisher): add DISABLE_GCP_PUBSUB opt-out, drop per-send noop m…
julietshen Jul 10, 2026
b678c6f
feat(async-publisher): degrade AsyncPubSubPublisher to noop without G…
julietshen Jul 7, 2026
e8e2770
docs(changelog): cover both sync and async publisher noop fallback
julietshen Jul 7, 2026
362a860
test(publisher): point exporter conftest at renamed cred helper
julietshen Jul 9, 2026
48cefda
feat(async-publisher): add DISABLE_GCP_PUBSUB opt-out, drop noop metric
julietshen Jul 10, 2026
6cbe134
style(test): collapse test signature to satisfy ruff format
julietshen Jul 10, 2026
2d40415
feat(publisher): emit startup configuration.errors metric on missing …
julietshen Jul 10, 2026
6b84b57
refactor(publisher): move enable/disable decision into a make_publish…
julietshen Jul 10, 2026
e825f47
test: drop vestigial cred patch from exporter conftest
julietshen Jul 10, 2026
b1adab9
refactor(publisher): opt-in OSPREY_PUBSUB_ENABLED, catch creds error …
julietshen Jul 10, 2026
f0b8f6e
refactor(publisher): default OSPREY_PUBSUB_ENABLED to true, restore p…
julietshen Jul 13, 2026
707a180
docs(changelog): scope the entry to the publisher noop, not full GCP-…
julietshen Jul 13, 2026
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ For more information about each release including git tags and artifacts, see [R
- Event stream shows sensible defaults so first-load isn't empty ([#297](https://github.com/roostorg/osprey/pull/297) by [@haileyok](https://github.com/haileyok))
- Replace `react-scripts` with `rsbuild`/`rspack` for UI builds ([#235](https://github.com/roostorg/osprey/pull/235) by [@chimosky](https://github.com/chimosky))
- Migrate from npm to pnpm via Corepack ([#252](https://github.com/roostorg/osprey/pull/252) by [@haileyok](https://github.com/haileyok))
- `PubSubPublisher` degrades to a noop when GCP credentials are absent, so Osprey runs without GCP config instead of failing ([#388](https://github.com/roostorg/osprey/pull/388) by [@julietshen](https://github.com/julietshen))

### Fixed

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,19 @@ def monkeypatch_session(request):


@pytest.fixture(scope='function', autouse=True)
def pubsub_client_mock(monkeypatch_session) -> MagicMock:
def pubsub_client_mock(monkeypatch_session, monkeypatch) -> MagicMock:
# tagging as potential opensource item
from google.cloud import pubsub_v1
from osprey.worker.lib import publisher

pubsub_client_mock = MagicMock()
publisher_class_mock = MagicMock(return_value=pubsub_client_mock)

monkeypatch_session.setattr(pubsub_v1, 'PublisherClient', publisher_class_mock)
# PubSubPublisher degrades to noop without GCP credentials, which CI lacks;
# force detection so the mocked client is actually exercised. Function-scoped
# monkeypatch so it reverts after each test instead of leaking into later
# modules (e.g. test_publisher.py, whose disabled-publisher tests would then
# build a real client and hang on stop()).
monkeypatch.setattr(publisher, '_check_gcp_credentials', lambda: True)
return pubsub_client_mock
50 changes: 48 additions & 2 deletions osprey_worker/src/osprey/worker/lib/publisher.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
import abc
import logging
import threading
from typing import TypeVar

import google.auth
from google.auth.exceptions import DefaultCredentialsError
from google.cloud import pubsub_v1
from osprey.worker.lib.instruments import metrics
from osprey.worker.lib.pubsub.publisher_client import BatchPubsubPublisherClient
from pydantic import BaseModel

_PydanticModelT = TypeVar('_PydanticModelT', bound=BaseModel)

logger = logging.getLogger(__name__)


class BasePublisher(abc.ABC):
"""
Expand Down Expand Up @@ -40,6 +46,15 @@ def stop(self) -> None:


class PubSubPublisher(BasePublisher):
"""Publishes Pydantic models to a Google Cloud Pub/Sub topic.

Degrades to noop mode when GCP credentials cannot be resolved at construction
time (e.g. local dev or adopter environments without GCP). In noop mode no
underlying client is built, publish() and stop() return immediately, and a
`PubSubPublisher.publisher.noop` metric is incremented per call so the inert
state is visible in dashboards. A one-time warning is logged at construction.
"""

def __init__(
self,
project_id: str,
Expand All @@ -54,15 +69,23 @@ def __init__(
topic_id=topic_id,
)
self._project = project_id
self._raise_on_error = raise_on_error
self._tags = [f'project:{self._project}', f'topic:{self._topic_name}']
self._enabled = _check_gcp_credentials()
if not self._enabled:
logger.warning(
'GCP credentials not detected, PubSubPublisher running in noop mode (project=%s, topic=%s)',
project_id,
topic_id,
)
return
batch_settings = pubsub_v1.types.BatchSettings(
max_bytes=max_bytes, # default 1MB
max_messages=max_messages, # default 100 messages
max_latency=max_latency,
)
# self._publisher = pubsub_v1.PublisherClient(batch_settings=batch_settings)
self._publisher = BatchPubsubPublisherClient(batch_settings=batch_settings)
self._raise_on_error = raise_on_error
self._tags = [f'project:{self._project}', f'topic:{self._topic_name}']

def prepare_data(self, data: _PydanticModelT) -> bytes:
"""
Expand All @@ -72,6 +95,9 @@ def prepare_data(self, data: _PydanticModelT) -> bytes:
return data.json(exclude_none=True).encode()

def publish(self, data: _PydanticModelT, attributes: dict[str, str] | None = None) -> None:
if not self._enabled:
metrics.increment(f'{self.__class__.__name__}.publisher.noop', tags=self._tags)

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.

Not sure on the usage of another metric here, and I think the dashboard could probably just surface this as a warning banner or something "Publishing to GCP PubSub is currently disabled due to invalid credentials"

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

ooooh good idea! I'll work that in

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

i'm actually going to add that separately, since it's a UI change and i want to keep this and #411 focused on the publisher changes

return
if attributes is None:
attributes = {}

Expand All @@ -89,6 +115,8 @@ def publish(self, data: _PydanticModelT, attributes: dict[str, str] | None = Non
metrics.increment(f'{self.__class__.__name__}.publisher.success', tags=self._tags)

def stop(self) -> None:
if not self._enabled:
return
self._publisher.stop()


Expand All @@ -103,3 +131,21 @@ def publish(self, data: str, attributes: dict[str, str] | None = None) -> None:
attributes = {}

super().publish(data, attributes) # type: ignore[type-var]


_gcp_credentials_available: bool | None = None
_gcp_credentials_lock = threading.Lock()


def _check_gcp_credentials() -> bool:
global _gcp_credentials_available
if _gcp_credentials_available is None:
with _gcp_credentials_lock:
# Re-check under the lock so concurrent constructors probe google.auth.default() only once.
if _gcp_credentials_available is None:
try:
google.auth.default()
_gcp_credentials_available = True
except DefaultCredentialsError:
_gcp_credentials_available = False
return _gcp_credentials_available
76 changes: 76 additions & 0 deletions osprey_worker/src/osprey/worker/lib/tests/test_publisher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
from typing import Iterator
from unittest.mock import MagicMock, patch

import pytest
from google.auth.exceptions import DefaultCredentialsError
from osprey.worker.lib import publisher
from osprey.worker.lib.publisher import PubSubPublisher, _check_gcp_credentials


@pytest.fixture(autouse=True)
def reset_cred_cache() -> Iterator[None]:
publisher._gcp_credentials_available = None
yield
publisher._gcp_credentials_available = None


def test_check_gcp_credentials_true_when_default_resolves() -> None:
with patch.object(publisher.google.auth, 'default', return_value=(MagicMock(), 'proj')):
assert _check_gcp_credentials() is True


def test_check_gcp_credentials_false_when_default_raises() -> None:
with patch.object(publisher.google.auth, 'default', side_effect=DefaultCredentialsError()):
assert _check_gcp_credentials() is False


def test_check_gcp_credentials_is_cached() -> None:
with patch.object(publisher.google.auth, 'default', return_value=(MagicMock(), 'proj')) as default_mock:
_check_gcp_credentials()
_check_gcp_credentials()
_check_gcp_credentials()
assert default_mock.call_count == 1


def test_pubsub_publisher_constructs_client_when_creds_present() -> None:
with (
patch.object(publisher.google.auth, 'default', return_value=(MagicMock(), 'proj')),
patch.object(publisher, 'BatchPubsubPublisherClient') as client_cls,
):
pub = PubSubPublisher('proj', 'topic')
assert pub._enabled is True
assert client_cls.called


def test_pubsub_publisher_noops_when_creds_absent(caplog: pytest.LogCaptureFixture) -> None:
with (
patch.object(publisher.google.auth, 'default', side_effect=DefaultCredentialsError()),
patch.object(publisher, 'BatchPubsubPublisherClient') as client_cls,
):
with caplog.at_level('WARNING', logger=publisher.logger.name):
pub = PubSubPublisher('proj', 'topic')
assert pub._enabled is False
assert not client_cls.called
assert 'noop mode' in caplog.text
assert 'project=proj' in caplog.text
assert 'topic=topic' in caplog.text


def test_publish_short_circuits_and_emits_noop_metric_when_disabled() -> None:
with (
patch.object(publisher.google.auth, 'default', side_effect=DefaultCredentialsError()),
patch.object(publisher, 'metrics') as metrics_mock,
):
pub = PubSubPublisher('proj', 'topic')
pub.publish(MagicMock())
metrics_mock.increment.assert_called_once_with(
'PubSubPublisher.publisher.noop',
tags=['project:proj', 'topic:projects/proj/topics/topic'],
)


def test_stop_short_circuits_when_disabled() -> None:
with patch.object(publisher.google.auth, 'default', side_effect=DefaultCredentialsError()):
pub = PubSubPublisher('proj', 'topic')
pub.stop()
assert not hasattr(pub, '_publisher')
Loading