-
Notifications
You must be signed in to change notification settings - Fork 54
feat: initial obs implementation #732
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
Draft
maciejmajek
wants to merge
1
commit into
main
Choose a base branch
from
feat/obs
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.
Draft
Changes from all commits
Commits
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
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
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,27 @@ | ||
| # Copyright (C) 2025 Robotec.AI | ||
| # | ||
| # 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 .builder import build_sink_from_env | ||
| from .meta import EVENT_SCHEMA_VERSION, ObservabilityMeta | ||
| from .sink import BufferedSink, LoggingSink, NoOpSink, ObservabilitySink | ||
|
|
||
| __all__ = [ | ||
| "EVENT_SCHEMA_VERSION", | ||
| "BufferedSink", | ||
| "LoggingSink", | ||
| "NoOpSink", | ||
| "ObservabilityMeta", | ||
| "ObservabilitySink", | ||
| "build_sink_from_env", | ||
| ] |
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,98 @@ | ||
| # Copyright (C) 2025 Robotec.AI | ||
| # | ||
| # 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 logging | ||
| import os | ||
| from typing import Callable, Mapping, Optional | ||
| from urllib.parse import urlparse | ||
|
|
||
| from .sink import ( | ||
| BufferedSink, | ||
| LoggingSink, | ||
| NoOpSink, | ||
| ObservabilitySink, | ||
| StdoutSink, | ||
| default_buffer_size, | ||
| ) | ||
|
|
||
| LOGGER = logging.getLogger("ObservabilityBuilder") | ||
|
|
||
|
|
||
| def _make_logging_sink(_endpoint: str) -> ObservabilitySink: | ||
| return LoggingSink(logger=logging.getLogger("ObservabilityLoggingSink")) | ||
|
|
||
|
|
||
| def _make_stdout_sink(_endpoint: str) -> ObservabilitySink: | ||
| return StdoutSink() | ||
|
|
||
|
|
||
| DEFAULT_FACTORY: Mapping[str, Callable[[str], ObservabilitySink]] = { | ||
| "ws": _make_stdout_sink, # visible by default for local debugging | ||
| "wss": _make_logging_sink, | ||
| "tcp": _make_logging_sink, | ||
| "http": _make_logging_sink, | ||
| "https": _make_logging_sink, | ||
| "file": _make_logging_sink, | ||
| } | ||
|
|
||
|
|
||
| def build_sink_from_env( | ||
| endpoint: Optional[str] = None, | ||
| buffer_size: Optional[int] = None, | ||
| factory: Mapping[str, Callable[[str], ObservabilitySink]] = DEFAULT_FACTORY, | ||
| ) -> ObservabilitySink: | ||
| """Build an observability sink from configuration. | ||
|
|
||
| If no endpoint is provided or parsing fails, falls back to NoOpSink. | ||
| """ | ||
| raw_target = endpoint or os.getenv("RAI_OBS_ENDPOINT") | ||
| if not raw_target: | ||
| return NoOpSink() | ||
|
|
||
| # Accept scheme-less values like "ws" to mean "use the ws factory". | ||
| parsed = urlparse(raw_target) | ||
| if not parsed.scheme and raw_target in factory: | ||
| target_scheme = raw_target | ||
| target_full = raw_target | ||
| else: | ||
| target_scheme = parsed.scheme | ||
| target_full = raw_target | ||
|
|
||
| if not target_scheme: | ||
| LOGGER.debug( | ||
| "Observability endpoint missing scheme and not recognized: %s; using NoOpSink", | ||
| raw_target, | ||
| ) | ||
| return NoOpSink() | ||
|
|
||
| factory_fn = factory.get(target_scheme) | ||
| if not factory_fn: | ||
| LOGGER.debug( | ||
| "Observability endpoint scheme not recognized (%s), using NoOpSink", | ||
| target_scheme, | ||
| ) | ||
| return NoOpSink() | ||
|
|
||
| try: | ||
| sink = factory_fn(target_full) | ||
| except Exception as exc: # pragma: no cover - defensive | ||
| LOGGER.debug("Failed to create sink for %s: %s", target_full, exc) | ||
| return NoOpSink() | ||
|
|
||
| buf_size = buffer_size if buffer_size is not None else default_buffer_size() | ||
| if buf_size and buf_size > 0: | ||
| return BufferedSink( | ||
| sink, maxlen=buf_size, logger=logging.getLogger("BufferedSink") | ||
| ) | ||
| return sink |
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,121 @@ | ||
| # Copyright (C) 2025 Robotec.AI | ||
| # | ||
| # 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 functools | ||
| import time | ||
| from typing import Any, Callable, Dict | ||
|
|
||
| from .sink import NoOpSink | ||
|
|
||
| EVENT_SCHEMA_VERSION = "v1" | ||
|
|
||
|
|
||
| def _extract_target( | ||
| fn_name: str, args: tuple[Any, ...], kwargs: dict[str, Any] | ||
| ) -> dict[str, Any]: | ||
| """Extract common fields like target/source from known method signatures.""" | ||
| fields: dict[str, Any] = {} | ||
| if fn_name in { | ||
| "send_message", | ||
| "service_call", | ||
| "call_service", | ||
| "start_action", | ||
| "terminate_action", | ||
| }: | ||
| # target is usually the second positional argument or a kwarg named target | ||
| if "target" in kwargs: | ||
| fields["target"] = kwargs["target"] | ||
| elif len(args) >= 2: | ||
| fields["target"] = args[1] | ||
| if fn_name in {"receive_message"}: | ||
| # source is usually the first positional argument or kwarg named source | ||
| if "source" in kwargs: | ||
| fields["source"] = kwargs["source"] | ||
| elif len(args) >= 1: | ||
| fields["source"] = args[0] | ||
| if fn_name in {"create_service", "create_action"}: | ||
| if "service_name" in kwargs: | ||
| fields["target"] = kwargs["service_name"] | ||
| elif "action_name" in kwargs: | ||
| fields["target"] = kwargs["action_name"] | ||
| elif len(args) >= 1: | ||
| fields["target"] = args[0] | ||
| return fields | ||
|
|
||
|
|
||
| def _timed_handler(self, fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: | ||
| started = time.time() | ||
| try: | ||
| return fn(self, *args, **kwargs) | ||
| finally: | ||
| sink = getattr(self, "observability_sink", None) or NoOpSink() | ||
| connector_name = getattr(self, "connector_name", None) | ||
| agent_name = getattr(self, "agent_name", None) | ||
| try: | ||
| event = { | ||
| "schema_version": EVENT_SCHEMA_VERSION, | ||
| "event_type": fn.__name__, | ||
| "phase": "close", | ||
| "latency_ms": (time.time() - started) * 1000.0, | ||
| "component": agent_name, | ||
| "connector_name": connector_name, | ||
| } | ||
| if agent_name: | ||
| event["agent_name"] = agent_name | ||
| event.update(_extract_target(fn.__name__, args, kwargs)) | ||
| sink.record(event) | ||
| except Exception: | ||
| # Best-effort: never raise into caller. | ||
| pass | ||
|
|
||
|
|
||
| HANDLERS: Dict[str, Dict[str, Callable[..., Any]]] = { | ||
| EVENT_SCHEMA_VERSION: { | ||
| "send_message": _timed_handler, | ||
| "receive_message": _timed_handler, | ||
| "service_call": _timed_handler, | ||
| "call_service": _timed_handler, | ||
| "create_service": _timed_handler, | ||
| "create_action": _timed_handler, | ||
| "start_action": _timed_handler, | ||
| "terminate_action": _timed_handler, | ||
| } | ||
| } | ||
|
|
||
| DEFAULT_METHODS = tuple(HANDLERS[EVENT_SCHEMA_VERSION].keys()) | ||
|
|
||
|
|
||
| class ObservabilityMeta(type): | ||
| """Metaclass that wraps selected methods with observability handlers.""" | ||
|
|
||
| def __new__(mcls, name, bases, attrs): | ||
| cls = super().__new__(mcls, name, bases, attrs) | ||
| methods = getattr(cls, "__observability_methods__", DEFAULT_METHODS) | ||
| schema_version = getattr( | ||
| cls, "__observability_schema_version__", EVENT_SCHEMA_VERSION | ||
| ) | ||
| handler_map = HANDLERS.get(schema_version, {}) | ||
|
|
||
| for method_name in methods: | ||
| fn = getattr(cls, method_name, None) | ||
| handler = handler_map.get(method_name) | ||
| if not fn or not handler: | ||
| continue | ||
|
|
||
| @functools.wraps(fn) | ||
| def wrapper(self, *args, __fn=fn, __handler=handler, **kwargs): | ||
| return __handler(self, __fn, *args, **kwargs) | ||
|
|
||
| setattr(cls, method_name, wrapper) | ||
| return cls | ||
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When running unit test, this caused one of the tests to fail with timeout. This in turn revealed an issue of double-wrapping inherited methods. This can happen when a base class is created with this metaclass and a subclass is created with the same metaclass. See more details at here