logdetective 2.4.1__py3-none-any.whl → 2.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,15 +1,14 @@
1
1
  from os import getenv
2
- from contextlib import contextmanager
3
- from sqlalchemy import create_engine
4
- from sqlalchemy.orm import sessionmaker, declarative_base
5
-
2
+ from contextlib import asynccontextmanager
3
+ from sqlalchemy.orm import declarative_base
4
+ from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
6
5
  from logdetective import logger
7
6
 
8
7
 
9
8
  def get_pg_url() -> str:
10
9
  """create postgresql connection string"""
11
10
  return (
12
- f"postgresql+psycopg2://{getenv('POSTGRESQL_USER')}"
11
+ f"postgresql+asyncpg://{getenv('POSTGRESQL_USER')}"
13
12
  f":{getenv('POSTGRESQL_PASSWORD')}@{getenv('POSTGRESQL_HOST', 'postgres')}"
14
13
  f":{getenv('POSTGRESQL_PORT', '5432')}/{getenv('POSTGRESQL_DATABASE')}"
15
14
  )
@@ -23,13 +22,13 @@ sqlalchemy_echo = getenv("SQLALCHEMY_ECHO", "False").lower() in (
23
22
  "y",
24
23
  "1",
25
24
  )
26
- engine = create_engine(get_pg_url(), echo=sqlalchemy_echo)
27
- SessionFactory = sessionmaker(autoflush=True, bind=engine)
25
+ engine = create_async_engine(get_pg_url(), echo=sqlalchemy_echo)
26
+ SessionFactory = async_sessionmaker(autoflush=True, bind=engine) # pylint: disable=invalid-name
28
27
  Base = declarative_base()
29
28
 
30
29
 
31
- @contextmanager
32
- def transaction(commit: bool = False):
30
+ @asynccontextmanager
31
+ async def transaction(commit: bool = False):
33
32
  """
34
33
  Context manager for 'framing' a db transaction.
35
34
 
@@ -39,27 +38,30 @@ def transaction(commit: bool = False):
39
38
  """
40
39
 
41
40
  session = SessionFactory()
42
- try:
43
- yield session
44
- if commit:
45
- session.commit()
46
- except Exception as ex:
47
- logger.warning("Exception while working with database: %s", str(ex))
48
- session.rollback()
49
- raise
50
- finally:
51
- session.close()
41
+ async with session:
42
+ try:
43
+ yield session
44
+ if commit:
45
+ await session.commit()
46
+ except Exception as ex:
47
+ logger.warning("Exception while working with database: %s", str(ex))
48
+ await session.rollback()
49
+ raise
50
+ finally:
51
+ await session.close()
52
52
 
53
53
 
54
- def init():
54
+ async def init():
55
55
  """Init db"""
56
- Base.metadata.create_all(engine)
56
+ async with engine.begin() as conn:
57
+ await conn.run_sync(Base.metadata.create_all)
57
58
  logger.debug("Database initialized")
58
59
 
59
60
 
60
- def destroy():
61
+ async def destroy():
61
62
  """Destroy db"""
62
- Base.metadata.drop_all(engine)
63
+ async with engine.begin() as conn:
64
+ await conn.run_sync(Base.metadata.drop_all)
63
65
  logger.warning("Database cleaned")
64
66
 
65
67
 
@@ -1,5 +1,5 @@
1
1
  from datetime import datetime, timedelta, timezone
2
- from sqlalchemy import Column, BigInteger, DateTime, ForeignKey, Integer, String
2
+ from sqlalchemy import Column, BigInteger, DateTime, ForeignKey, Integer, String, select
3
3
  from sqlalchemy.orm import relationship
4
4
  from sqlalchemy.exc import OperationalError
5
5
  import backoff
@@ -26,7 +26,7 @@ class KojiTaskAnalysis(Base):
26
26
  task_id = Column(BigInteger, nullable=False, index=True, unique=True)
27
27
  log_file_name = Column(String(255), nullable=False, index=True)
28
28
  request_received_at = Column(
29
- DateTime,
29
+ DateTime(timezone=True),
30
30
  nullable=False,
31
31
  index=True,
32
32
  default=datetime.now(timezone.utc),
@@ -43,20 +43,22 @@ class KojiTaskAnalysis(Base):
43
43
 
44
44
  @classmethod
45
45
  @backoff.on_exception(backoff.expo, OperationalError, max_tries=DB_MAX_RETRIES)
46
- def create_or_restart(cls, koji_instance: str, task_id: int, log_file_name: str):
46
+ async def create_or_restart(
47
+ cls, koji_instance: str, task_id: int, log_file_name: str
48
+ ):
47
49
  """Create a new koji task analysis"""
48
- with transaction(commit=True) as session:
50
+ query = select(cls).filter(
51
+ cls.koji_instance == koji_instance, cls.task_id == task_id
52
+ )
53
+ async with transaction(commit=True) as session:
49
54
  # Check if the task analysis already exists
50
- koji_task_analysis = (
51
- session.query(cls)
52
- .filter_by(koji_instance=koji_instance, task_id=task_id)
53
- .first()
54
- )
55
+ query_result = await session.execute(query)
56
+ koji_task_analysis = query_result.first()
55
57
  if koji_task_analysis:
56
58
  # If it does, update the request_received_at timestamp
57
59
  koji_task_analysis.request_received_at = datetime.now(timezone.utc)
58
60
  session.add(koji_task_analysis)
59
- session.flush()
61
+ await session.flush()
60
62
  return
61
63
 
62
64
  # If it doesn't, create a new one
@@ -65,14 +67,19 @@ class KojiTaskAnalysis(Base):
65
67
  koji_task_analysis.task_id = task_id
66
68
  koji_task_analysis.log_file_name = log_file_name
67
69
  session.add(koji_task_analysis)
68
- session.flush()
70
+ await session.flush()
69
71
 
70
72
  @classmethod
71
73
  @backoff.on_exception(backoff.expo, OperationalError, max_tries=DB_MAX_RETRIES)
72
- def add_response(cls, task_id: int, metric_id: int):
74
+ async def add_response(cls, task_id: int, metric_id: int):
73
75
  """Add a response to a koji task analysis"""
74
- with transaction(commit=True) as session:
75
- koji_task_analysis = session.query(cls).filter_by(task_id=task_id).first()
76
+ query = select(cls).filter(cls.task_id == task_id)
77
+ metrics_query = select(AnalyzeRequestMetrics).filter(
78
+ AnalyzeRequestMetrics.id == metric_id
79
+ )
80
+ async with transaction(commit=True) as session:
81
+ query_result = await session.execute(query)
82
+ koji_task_analysis = query_result.scalars().first()
76
83
  # Ensure that the task analysis doesn't already have a response
77
84
  if koji_task_analysis.response:
78
85
  # This is probably due to an analysis that took so long that
@@ -81,20 +88,20 @@ class KojiTaskAnalysis(Base):
81
88
  # returned to the consumer, so we'll just drop this extra one
82
89
  # on the floor and keep the one saved in the database.
83
90
  return
84
-
85
- metric = (
86
- session.query(AnalyzeRequestMetrics).filter_by(id=metric_id).first()
87
- )
91
+ metrics_query_result = await session.execute(metrics_query)
92
+ metric = metrics_query_result.scalars().first()
88
93
  koji_task_analysis.response = metric
89
94
  session.add(koji_task_analysis)
90
- session.flush()
95
+ await session.flush()
91
96
 
92
97
  @classmethod
93
98
  @backoff.on_exception(backoff.expo, OperationalError, max_tries=DB_MAX_RETRIES)
94
- def get_response_by_task_id(cls, task_id: int) -> KojiStagedResponse:
99
+ async def get_response_by_task_id(cls, task_id: int) -> KojiStagedResponse:
95
100
  """Get a koji task analysis by task id"""
96
- with transaction(commit=False) as session:
97
- koji_task_analysis = session.query(cls).filter_by(task_id=task_id).first()
101
+ query = select(cls).filter(cls.task_id == task_id)
102
+ async with transaction(commit=False) as session:
103
+ query_result = await session.execute(query)
104
+ koji_task_analysis = query_result.scalars().first()
98
105
  if not koji_task_analysis:
99
106
  raise KojiTaskNotFoundError(f"Task {task_id} not yet analyzed")
100
107