Skip to content

@metric_scope makes wrong assumption to detect async event loop #131

@myagent-git

Description

@myagent-git

@metric_scope is making a wrong assumption that a sync function cannot be called in an async event loop. If the decorated function is a regular sync function, then @metric_scope incorrectly assumes that it is not in an event loop and can use asyncio.run. This assumption is obviously wrong.

To reproduce the issue:

#!/usr/bin/env python3

import asyncio

from aws_embedded_metrics import metric_scope

@metric_scope
def foo(metrics):
    print("Some businesss logic")
    metrics.put_metric("foo", 1, "Count")

async def main():
    foo()

if __name__ == "__main__":
    asyncio.run(main())

Error stack trace:

......
    foo()
  File "~/.local/share/mise/installs/python/3.12.10/lib/python3.12/site-packages/aws_embedded_metrics/metric_scope/__init__.py", line 88, in wrapper
    asyncio.run(logger.flush())
  File "~/.local/share/mise/installs/python/3.12.10/lib/python3.12/asyncio/runners.py", line 191, in run
    raise RuntimeError(
RuntimeError: asyncio.run() cannot be called from a running event loop
sys:1: RuntimeWarning: coroutine 'MetricsLogger.flush' was never awaited

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions