PK’/N <<mod_ngarn/__init__.py"""Simple async worker""" __version__ = "2.4" import asyncio import os import click from . import utils from .worker import JobRunner global script global run global init_table @click.group() def script(): pass @click.command() def run(): job_runner = JobRunner() loop = asyncio.get_event_loop() loop.run_until_complete(job_runner.run()) @click.command() @click.option( '--name', help='mod-ngarn table name.', ) def create_table(name): asyncio.run(utils.create_table(name)) script.add_command(run) script.add_command(create_table) PK/NlBEEmod_ngarn/api.pyimport os from datetime import datetime from typing import Callable, Optional, Union import asyncpg from .utils import escape_table_name, get_fn_name async def add_job( cnx: asyncpg.Connection, job_id: str, func: Union[str, Callable], schedule_time: Optional[datetime] = None, priority: int = 0, args: list = [], kwargs: dict = {}, table: str = escape_table_name(os.getenv('DBTABLE', 'modngarn_job')), ) -> asyncpg.Record: fn_name = await get_fn_name(func) return await cnx.fetchrow( """ INSERT INTO "{table}" (id, fn_name, priority, scheduled, args, kwargs) VALUES ($1, $2, $3, $4, $5, $6) RETURNING *; """.format( table=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/NxI 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 escape_table_name(table_name: str): return re.split("[, \"\']", table_name)[0] 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=None): 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 "{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( table=escape_table_name(name) ) ) await cnx.execute( f"""CREATE INDEX IF NOT EXISTS idx_pending_jobs ON "{name}" (executed) WHERE executed IS NULL;""" ) print(f"Done") PK/Npmod_ngarn/worker.pyimport asyncio import functools import logging 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 escape_table_name, 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 id: str fn_name: str priority: int args: List[Any] = field(default_factory=list) kwargs: Dict = field(default_factory=dict) table: str = escape_table_name(os.getenv('DBTABLE', 'modngarn_job')) 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: log.error("Error#{}, {}".format(self.id, e.__repr__())) await self.failed(e.__repr__()) 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 WHERE id=$3", result, processing_time, self.id, ) async def failed(self, error: str) -> str: """ Failed execution handler """ delay = 2 ** self.priority 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, ) @dataclass class JobRunner: async def fetch_job( self, cnx: asyncpg.Connection, table: str = escape_table_name(os.getenv('DBTABLE', 'modngarn_job')), ): result = await cnx.fetchrow( f"""SELECT id, fn_name, args, kwargs, priority FROM "{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, result["id"], result["fn_name"], result["priority"], result["args"], result["kwargs"], ) async def run(self, table: str = escape_table_name(os.getenv('DBTABLE', 'modngarn_job'))): cnx = await get_connection() async with cnx.transaction(): job = await self.fetch_job(cnx, table) if job: log.info(f'Executing: {job.id}') result = await job.execute() log.info(f'Executed: {result}') await cnx.close() PK!H1'.(mod_ngarn-2.4.dist-info/entry_points.txtN+I/N.,()OKO,ʳ,+$PKsM 55mod_ngarn-2.4.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.4.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,rzd&Y)r$[)T&UrPK!H7 mod_ngarn-2.4.dist-info/METADATAT]o0}ϯj_(]e4ՆV>V6I.GbC ԡ ^9snn<@fp)B8` 2-="E: /TZ$uNHK]zf2arsˢ1bi8k.cƥ GA!L]7yHy/c52^;#jˠ&\Yt(,em8#D>3c뺑aI:Jiğuqcz *&m]sxEnbQtA_kp4(ƞ<竵Fg5vyDG~"}$TM^YMiq-4wLKڴu۲O\ƵBB +Ap 5d_*6| wƽ`6SKx ' a;o' U+h s0،(bDp]>2T FfX6u)*^N_UPq9һU%ԒAGw)e){߿loupNa3bgnVQ/GpXj|2 L&<^gꪀ6]] RmmGIwg*JbKwT!Л#5i\sn21E-PK!Hײmod_ngarn-2.4.dist-info/RECORDuɖ0}= XP^0 lP{e7_- !"A I~=>`~o]d1j[pxT)ޚ qwpF ~_Yԋ3O:$v-Mo9CNT d[mvq(tSY9ft/Iy˦*-F0]HMIgqo>J([7T/(S-q#yۄuPWx 1m31_#'*6}PK’/N <<mod_ngarn/__init__.pyPK/NlBEEomod_ngarn/api.pyPKvVM  mod_ngarn/connection.pyPK/NxI !mod_ngarn/utils.pyPK/Np4mod_ngarn/worker.pyPK!H1'.(!mod_ngarn-2.4.dist-info/entry_points.txtPKsM 55Q"mod_ngarn-2.4.dist-info/LICENSEPK!H>*RQ&mod_ngarn-2.4.dist-info/WHEELPK!H7 P'mod_ngarn-2.4.dist-info/METADATAPK!Hײ5*mod_ngarn-2.4.dist-info/RECORDPK O,