PK|ZN<mod_ngarn/__init__.py"""Simple async worker""" __version__ = "2.8" import asyncio import os import click from . import utils from .worker import JobRunner global script global run global create_table @click.group() def script(): pass @click.command() @click.option( "--queue-table", help='Queue table name (Default: os.getenv("DBTABLE", "public.modngarn_job"))', default=os.getenv("DBTABLE", "public.modngarn_job"), ) @click.option("--limit", default=300, help="Limit jobs (Default: 300)") @click.option("--max-delay", type=float, help="Max delay for failed jobs (seconds) (Default: None)") def run(queue_table, limit, max_delay): table_name = utils.sql_table_name(queue_table) job_runner = JobRunner() loop = asyncio.get_event_loop() if max_delay: max_delay = float(max_delay) loop.run_until_complete(job_runner.run(table_name, limit, max_delay)) @click.command() @click.option( "--queue-table", help='Queue table name (Default: os.getenv("DBTABLE", "public.modngarn_job"))', default=os.getenv("DBTABLE", "public.modngarn_job"), ) def create_table(queue_table): table_name = utils.sql_table_name(queue_table) asyncio.run(utils.create_table(table_name)) script.add_command(run) script.add_command(create_table) PK?NuL..mod_ngarn/api.pyimport os from datetime import datetime from typing import Callable, Optional, Union import asyncpg from .utils import sql_table_name, get_fn_name async def add_job( cnx: asyncpg.Connection, queue_table: str, job_id: str, func: Union[str, Callable], schedule_time: Optional[datetime] = None, priority: int = 0, args: list = [], kwargs: dict = {}, ) -> asyncpg.Record: fn_name = await get_fn_name(func) return await cnx.fetchrow( """ INSERT INTO {queue_table} (id, fn_name, priority, scheduled, args, kwargs) VALUES ($1, $2, $3, $4, $5, $6) RETURNING *; """.format( queue_table=sql_table_name(queue_table) ), job_id, fn_name, priority, schedule_time, args, kwargs, ) PKvVM  mod_ngarn/connection.pyimport json import os import asyncpg async def get_connection(): PGDBNAME = os.getenv('PGDBNAME') PGHOST = os.getenv('PGHOST') PGPASSWORD = os.getenv('PGPASSWORD') PGUSER = os.getenv('PGUSER') cnx = await asyncpg.connect(user=PGUSER, password=PGPASSWORD, database=PGDBNAME, host=PGHOST) await cnx.set_type_codec('jsonb', encoder=json.dumps, decoder=json.loads, schema='pg_catalog') await cnx.set_type_codec('json', encoder=json.dumps, decoder=json.loads, schema='pg_catalog') return cnx PK?NW5 mod_ngarn/utils.pyimport os import re from inspect import getmembers, getmodule, ismethod from typing import Callable, Union from .connection import get_connection class ImportNotFoundException(Exception): pass class ModuleNotfoundException(Exception): pass def sql_table_name(queue_table: str) -> str: return ('.').join([f'"{x}"' for x in queue_table.split('.')]) async def get_fn_name(func: Union[str, Callable]) -> str: try: if isinstance(func, str): return func if ismethod(func): module_name = get_fn_name(dict(getmembers(func))['__self__']) else: module_name = getmodule(func).__name__ name = func.__name__ return '.'.join([module_name, name]) except AttributeError as e: raise ModuleNotfoundException(e) async def import_fn(fn_name) -> Callable: access_path = fn_name.split(".") module = None try: for index in range(1, len(access_path)): try: # import top level module module_name = ".".join(access_path[:-index]) module = __import__(module_name) except ImportError: continue else: for step in access_path[1:-1]: # walk down it module = getattr(module, step) break if module: return getattr(module, access_path[-1]) else: return globals()["__builtins__"][fn_name] except KeyError as e: raise ImportNotFoundException(e) async def create_table(name: str): if not name: name = os.getenv('MOD_NGARN_TABLE', 'modngarn_job') print(f"Creating table {name}...") cnx = await get_connection() async with cnx.transaction(): await cnx.execute( """CREATE TABLE IF NOT EXISTS {queue_table} ( id TEXT NOT NULL CHECK (id !~ '\\|/|\u2044|\u2215|\u29f5|\u29f8|\u29f9|\ufe68|\uff0f|\uff3c'), fn_name TEXT NOT NULL, args JSON DEFAULT '[]', kwargs JSON DEFAULT '{{}}', priority INTEGER DEFAULT 0, created TIMESTAMP WITH TIME ZONE DEFAULT NOW(), scheduled TIMESTAMP WITH TIME ZONE, executed TIMESTAMP WITH TIME ZONE, canceled TIMESTAMP WITH TIME ZONE, result JSON, reason TEXT, processed_time TEXT, PRIMARY KEY (id) ); """.format( queue_table=name ) ) await cnx.execute( f"""CREATE INDEX IF NOT EXISTS idx_pending_jobs ON {name} (executed) WHERE executed IS NULL;""" ) print(f"Done") PK|ZNmod_ngarn/worker.pyimport asyncio import functools import logging import math import os import sys import time import traceback from datetime import datetime, timedelta, timezone from decimal import Decimal from typing import Any, Callable, Dict, List import asyncpg from dataclasses import dataclass, field from .connection import get_connection from .utils import import_fn logging.basicConfig( stream=sys.stdout, level=logging.INFO, format="[%(asctime)s] - %(name)s - %(levelname)s - %(message)s", ) log = logging.getLogger("mod_ngarn") @dataclass class Job: cnx: asyncpg.Connection table: str id: str fn_name: str priority: int args: List[Any] = field(default_factory=list) kwargs: Dict = field(default_factory=dict) max_delay: float = field(default=None) async def execute(self) -> Any: """ Execute the transaction """ try: start_time = time.time() func = await import_fn(self.fn_name) if asyncio.iscoroutinefunction(func): result = await func(*self.args, **self.kwargs) else: loop = asyncio.get_event_loop() result = await loop.run_in_executor( None, functools.partial(func, *self.args, **self.kwargs) ) processing_time = str(Decimal(str(time.time() - start_time)).quantize(Decimal(".001"))) await self.success(result, processing_time) return result except Exception as e: stack_trace = traceback.format_exc() error_msg = "{}\n{}".format(e.__repr__(), stack_trace) log.error("Error#{}, {}".format(self.id, error_msg)) await self.failed(error_msg) async def success(self, result: Dict, processing_time: Decimal) -> str: """ Success execution handler """ return await self.cnx.execute( f'UPDATE {self.table} SET result=$1, executed=NOW(), processed_time=$2, reason=NULL WHERE id=$3', result, processing_time, self.id, ) async def failed(self, error: str) -> str: """ Failed execution handler """ delay = await self.delay() next_schedule = datetime.now(timezone.utc) + timedelta(seconds=delay) log.error( "Rescheduled, delay for {} seconds ({}) ".format(delay, next_schedule.isoformat()) ) return await self.cnx.execute( f'UPDATE {self.table} SET priority=priority+1, reason=$2, scheduled=$3 WHERE id=$1', self.id, error, next_schedule, ) async def delay(self): delay = math.exp(self.priority) return min(delay, self.max_delay or delay) @dataclass class JobRunner: async def fetch_job( self, cnx: asyncpg.Connection, queue_table: str, max_delay: float ): result = await cnx.fetchrow( f"""SELECT id, fn_name, args, kwargs, priority FROM {queue_table} WHERE executed IS NULL AND (scheduled IS NULL OR scheduled < NOW()) AND canceled IS NULL ORDER BY priority FOR UPDATE SKIP LOCKED LIMIT 1 """ ) if result: return Job( cnx, queue_table, result["id"], result["fn_name"], result["priority"], result["args"], result["kwargs"], max_delay=max_delay ) async def run(self, queue_table, limit, max_delay): cnx = await get_connection() log.info(f"Running mod-ngarn, queue table name: {queue_table}, limit: {limit} jobs, max_delay: {max_delay}") for job_number in range(1, limit + 1): # We can reduce isolation to Read Committed # because we are using SKIP LOCK FOR UPDATE async with cnx.transaction(isolation="read_committed"): job = await self.fetch_job(cnx, queue_table, max_delay) if job: log.info(f"Executing#{job_number}: \t{job.id}") result = await job.execute() log.info(f"Executed#{job_number}: \t{result}") else: break await cnx.close() PK!H1'.(mod_ngarn-2.8.dist-info/entry_points.txtN+I/N.,()OKO,ʳ,+$PKsM 55mod_ngarn-2.8.dist-info/LICENSEMIT License Copyright (c) 2018 Proteus Technologies Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK!H>*RQmod_ngarn-2.8.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,rzd&Y)r$[)T&UrPK!Hs.T mod_ngarn-2.8.dist-info/METADATAU͎6)e T7nT:_NR b4XK$v=yaCɎ.z.f =ESxJF]3^`J?-72h_˲(G١ ިCͷ9mlk0aiCI֡a~"\~?̂~2e"XQnW$Ă<d$ۇmس`61B;Rt(]ku]d0ȹb#@|9Fb꿧|8Eu69>4r%:߳K aCCˡu|7&p]Fٞ=ñ=V Ⱥj# t`j~nN]:z0[i77 B$1pq?A561i[X(o'p&_T:z.z>+[+q |"a{Y-?JWX>o)XlrG]jPK!H'>mod_ngarn-2.8.dist-info/RECORDu͖c@}? i?%d 06PUZ~f96yso Uy> "Hl sAZfbR^J%p/,x}$7u#2UG_;(tvlvss$){~(N9b,+FRт*cԐ,%hpTɶ1鄑a >B!d(ߛa[zm4 SǾ(Č oVkM,6}suUi\Ȗ]a`SakJYP,Q}\N{H xĹr5֜ " XK3RKo}ѰOPۂ\~XĨ1ܳM$!9}xgKu> P&A08i(h={?pkFjػ#G0GmJ2דI9*zZGC:|PK|ZN<mod_ngarn/__init__.pyPK?NuL..&mod_ngarn/api.pyPKvVM  mod_ngarn/connection.pyPK?NW5  mod_ngarn/utils.pyPK|ZNmod_ngarn/worker.pyPK!H1'.( 'mod_ngarn-2.8.dist-info/entry_points.txtPKsM 55x'mod_ngarn-2.8.dist-info/LICENSEPK!H>*RQ+mod_ngarn-2.8.dist-info/WHEELPK!Hs.T w,mod_ngarn-2.8.dist-info/METADATAPK!H'>/mod_ngarn-2.8.dist-info/RECORDPK 2