PK{aM:!TTmod_ngarn/__init__.py"""Simple async worker""" __version__ = "2.2" import asyncio import click from .worker import JobRunner global script global run @click.group() def script(): pass @click.command() def run(): job_runner = JobRunner() loop = asyncio.get_event_loop() loop.run_until_complete(job_runner.run()) script.add_command(run) 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 PKvVM5M388mod_ngarn/utils.pyfrom typing import Callable class ImportNotFoundException(Exception): pass 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) PKp{aMڧ mod_ngarn/worker.pyimport asyncio import functools import logging 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 id: str fn_name: str priority: int args: List[Any] = field(default_factory=list) kwargs: Dict = field(default_factory=dict) 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( "UPDATE modngarn_job 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( "UPDATE modngarn_job 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): result = await cnx.fetchrow( """ SELECT id, fn_name, args, kwargs, priority FROM modngarn_job 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): cnx = await get_connection() async with cnx.transaction(): job = await self.fetch_job(cnx) if job: log.info(f'Executing: {job.id}') result = await job.execute() log.info(f'Executed: {result}') await cnx.close() PKvVM6mod_ngarn/Schema/migrations.txtenable-modules worker migrate PKVMQff,mod_ngarn/Schema/worker/001-initial.blue.sqlBEGIN; CREATE FUNCTION modngarn_url_safe(str text) RETURNS boolean AS $body$ BEGIN --- Disallow back slash, forward slash, fraction slash (2044), --- division slash (2215), reverse solidus operator (29f5), --- big solidus (29f8), big reverse solidus (29f9), --- small reverse solidus (fe68), fullwidth solidus (ff0f), --- full width reverse solidus (ff3c) RETURN str !~ '\\|/|\u2044|\u2215|\u29f5|\u29f8|\u29f9|\ufe68|\uff0f|\uff3c'; END $body$ LANGUAGE plpgsql; CREATE TABLE modngarn_job ( id TEXT NOT NULL CHECK (modngarn_url_safe(id)), fn_name TEXT NOT NULL, args JSONB DEFAULT '[]', kwargs JSONB 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 JSONB, reason TEXT, processed_time TEXT, PRIMARY KEY (id) ); CREATE INDEX idx_kwargs ON modngarn_job USING gin (kwargs); CREATE INDEX idx_pending_jobs ON modngarn_job (executed) WHERE executed IS NULL; COMMIT; PK!H1'.(mod_ngarn-2.2.dist-info/entry_points.txtN+I/N.,()OKO,ʳ,+$PKsM 55mod_ngarn-2.2.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.2.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,rzd&Y)r$[)T&UrPK!H~- mod_ngarn-2.2.dist-info/METADATATn6+ldj!nm5 XK$uaCF4ԓę73oo8㎕17V()EsZUʊ8Ok[f fe6DD kMh83Nj:OA\Z 8e};W+ӟo6]2$)@ˏ? -ɶD_3&r['%,k9ȦT24Z@"Fҟg˽TXcU[ziIk҈bX05r6 )^o 'E}D޼ ěS?,zB4 @O^ݤ  (zmrk8gʠEޑJX=6Q3UPw;[G7V(%pȖy~l6Oz|>F"&!5o4@^pr%6#' O!t2T/uiZh'.$- e(T'm6^^9}5ap69XjPr-* )6h#:A.NB+*\?~*{?i>c}'㯌.9!/\0x g$#_k% ʾanys ;8$g.*[>%HXQ/Fg\"ok'A>PK{aM:!TTmod_ngarn/__init__.pyPKvVM  mod_ngarn/connection.pyPKvVM5M388mod_ngarn/utils.pyPKp{aMڧ .mod_ngarn/worker.pyPKvVM6mod_ngarn/Schema/migrations.txtPKVMQff,:mod_ngarn/Schema/worker/001-initial.blue.sqlPK!H1'.(mod_ngarn-2.2.dist-info/entry_points.txtPKsM 55Wmod_ngarn-2.2.dist-info/LICENSEPK!H>*RQmod_ngarn-2.2.dist-info/WHEELPK!H~- Vmod_ngarn-2.2.dist-info/METADATAPK!HBX<'r"mod_ngarn-2.2.dist-info/RECORDPK 8$%