-
Notifications
You must be signed in to change notification settings - Fork 16
Publish analysis results to platform for BYOK contribution #88
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
suung
wants to merge
4
commits into
main
Choose a base branch
from
feature/byok-contribution-publish
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
c3a973b
Publish analysis results to platform for BYOK contribution
suung 2aa32c0
Move BYOK contribution publisher into enterprise package
suung a1efee2
Fix black formatting and ruff BLE001 on BYOK publish path.
suung a9d5056
Merge branch 'main' into feature/byok-contribution-publish
suung File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| """Publish analysis results to platform (BYOK contribution / enterprise). | ||
|
|
||
| Enterprise-only: open-core callers import this optionally and no-op if absent. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import logging | ||
| import os | ||
| import uuid | ||
| from typing import Any, Dict, Optional | ||
|
|
||
| import nats | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| async def publish_analysis_result( | ||
| resource_id: str, | ||
| results: Dict[str, Any], | ||
| provenance: Optional[Dict[str, Any]] = None, | ||
| analysis_config: Optional[Dict[str, Any]] = None, | ||
| owner_user_id: Optional[str] = None, | ||
| duration_ms: Optional[int] = None, | ||
| ) -> str: | ||
| """Publish analysis.result.{id} for platform to persist.""" | ||
| request_id = str(uuid.uuid4()) | ||
| nats_url = os.getenv("NATS_URL", "nats://localhost:4222") | ||
| nats_token = os.getenv("NATS_TOKEN") | ||
| if nats_token and "@" not in nats_url: | ||
| protocol, rest = nats_url.split("://", 1) | ||
| nats_url = f"{protocol}://{nats_token}@{rest}" | ||
|
|
||
| payload = { | ||
| "request_id": request_id, | ||
| "resource_id": resource_id, | ||
| "results": results, | ||
| "results_summary": results, | ||
| "provenance": provenance or {}, | ||
| "analysis_config": analysis_config or {}, | ||
| "owner_user_id": owner_user_id, | ||
| "duration_ms": duration_ms, | ||
| "source": os.getenv("NATS_USER", "report-analyst"), | ||
| } | ||
|
|
||
| nc = await nats.connect(nats_url, connect_timeout=15) | ||
| try: | ||
| js = nc.jetstream() | ||
| subject = f"analysis.result.{request_id}" | ||
| try: | ||
| await js.publish(subject, json.dumps(payload).encode()) | ||
| except Exception: # noqa: BLE001 — JetStream may be absent; fall back to core NATS | ||
| await nc.publish(subject, json.dumps(payload).encode()) | ||
| logger.info("Published %s for resource %s", subject, resource_id) | ||
| return request_id | ||
| finally: | ||
| await nc.close() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| """Unit tests for enterprise BYOK contribution publish (analysis.result NATS events).""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| from unittest.mock import AsyncMock, MagicMock | ||
|
|
||
| import pytest | ||
|
|
||
| from report_analyst_enterprise.contribution import publish_analysis_result | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_publish_analysis_result_uses_analysis_result_subject_and_payload(monkeypatch): | ||
| mock_nc = MagicMock() | ||
| mock_js = AsyncMock() | ||
| mock_nc.jetstream.return_value = mock_js | ||
| mock_nc.close = AsyncMock() | ||
|
|
||
| async def fake_connect(url, **kwargs): | ||
| return mock_nc | ||
|
|
||
| monkeypatch.setenv("NATS_URL", "nats://localhost:4222") | ||
| monkeypatch.setenv("NATS_USER", "report-analyst-test") | ||
| monkeypatch.setattr("report_analyst_enterprise.contribution.nats.connect", fake_connect) | ||
|
|
||
| request_id = await publish_analysis_result( | ||
| resource_id="res-123", | ||
| results={"answers": ["answer one"], "questions": ["question one"]}, | ||
| provenance={"mode": "byok_contribution", "provider": "report_analyst"}, | ||
| owner_user_id="user-42", | ||
| duration_ms=1500, | ||
| ) | ||
|
|
||
| mock_js.publish.assert_awaited_once() | ||
| subject, payload_bytes = mock_js.publish.call_args[0] | ||
| assert subject == f"analysis.result.{request_id}" | ||
| payload = json.loads(payload_bytes.decode()) | ||
| assert payload["request_id"] == request_id | ||
| assert payload["resource_id"] == "res-123" | ||
| assert payload["results"] == {"answers": ["answer one"], "questions": ["question one"]} | ||
| assert payload["results_summary"] == payload["results"] | ||
| assert payload["provenance"]["mode"] == "byok_contribution" | ||
| assert payload["owner_user_id"] == "user-42" | ||
| assert payload["duration_ms"] == 1500 | ||
| assert payload["source"] == "report-analyst-test" | ||
| mock_nc.close.assert_awaited_once() | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_publish_analysis_result_falls_back_to_core_publish(monkeypatch): | ||
| mock_nc = MagicMock() | ||
| mock_js = AsyncMock() | ||
| mock_js.publish.side_effect = RuntimeError("jetstream unavailable") | ||
| mock_nc.jetstream.return_value = mock_js | ||
| mock_nc.close = AsyncMock() | ||
| mock_nc.publish = AsyncMock() | ||
|
|
||
| async def fake_connect(url, **kwargs): | ||
| return mock_nc | ||
|
|
||
| monkeypatch.setenv("NATS_URL", "nats://localhost:4222") | ||
| monkeypatch.setattr("report_analyst_enterprise.contribution.nats.connect", fake_connect) | ||
|
|
||
| request_id = await publish_analysis_result( | ||
| resource_id="res-456", | ||
| results={"answers": ["a"], "questions": ["q"]}, | ||
| ) | ||
|
|
||
| mock_nc.publish.assert_awaited_once() | ||
| subject, payload_bytes = mock_nc.publish.call_args[0] | ||
| assert subject == f"analysis.result.{request_id}" | ||
| payload = json.loads(payload_bytes.decode()) | ||
| assert payload["resource_id"] == "res-456" |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.