PK{NHmod_ngarn/__init__.py"""Simple async worker""" __version__ = "3.2" import asyncio import os import sys 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): "Run mod-ngarn job" 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): "Create mod-ngarn queue table" table_name = utils.sql_table_name(queue_table) asyncio.run(utils.create_table(table_name)) @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 wait_for_notify(queue_table): "Wait and listening for NOTIFY" table_name = utils.sql_table_name(queue_table) loop = asyncio.get_event_loop() notification_queue = asyncio.Queue(loop=loop) loop.create_task(utils.wait_for_notify(table_name, notification_queue)) loop.run_until_complete(utils.shutdown(notification_queue)) loop.run_forever() script.add_command(run) script.add_command(create_table) script.add_command(wait_for_notify) PKNuL..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, ) PKN  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鴉N_..mod_ngarn/utils.pyimport asyncio import os import re import sys from inspect import getmembers, getmodule, ismethod from typing import Callable, Union from asyncpg.connection import Connection 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.replace('"', "").split(".")]) def notify_channel(queue_table: str) -> str: return queue_table.replace('"', "").replace(".", "_") 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): 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;""" ) await cnx.execute( """ CREATE OR REPLACE FUNCTION {notify_channel}_notify_job() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN NOTIFY {notify_channel}; RETURN NEW; END; $$; DROP TRIGGER IF EXISTS {notify_channel}_notify_job_inserted ON {table_name}; CREATE TRIGGER {notify_channel}_notify_job_inserted AFTER INSERT ON {table_name} FOR EACH ROW EXECUTE PROCEDURE {notify_channel}_notify_job(); """.format( notify_channel=notify_channel(name), table_name=name ) ) print(f"Done") async def wait_for_notify(queue_table: str, q: asyncio.Queue): """ Wait for notification and put channel to the Queue """ notify_ch = notify_channel(queue_table) print(f"LISTENING ON {notify_ch}...") cnx = await get_connection() def notified(cnx: Connection, pid: int, channel: str, payload: str): print("Notified, shutting down...") asyncio.gather(cnx.close(), q.put(channel)) await cnx.add_listener(notify_ch, notified) async def shutdown(q: asyncio.Queue): """ Gracefully shutdown when something put to the Queue """ await q.get() sys.exit() PK{NF=mod_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): # max int > e^21 and max int < e^22 priority = min(self.priority, 21) if self.max_delay: priority = min(priority, math.log(self.max_delay)) return math.exp(priority) @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-3.2.dist-info/entry_points.txtN+I/N.,()OKO,ʳ,+$PKN 55mod_ngarn-3.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!HMuSamod_ngarn-3.2.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,szd&Y)r$[)T&UD"PK!HBn mod_ngarn-3.2.dist-info/METADATAVKs6Wl5SBr&SlHJ-)Ҵ" C{^vƹH/ǡ&hh(0ӗX=DtG4]0}N LqChԦ_ (E{]O02zOD.!!XVM>b"BDX\>J!IUX;=↺l-bY6 v w@(d۩Dj~]^'?iSgҿ|T/X8AT̈́ug7졧O۔3xk Rd~y2ścnPt~Y 0OThQˀ1Q. VA;H!7go+* Q. tDžW44bU' nB &.cІg8a)Jpcx v#\ZoBANUF+5K_Wg=Z`>%vDN<'ћхC9 A^s~ǘ^M"{h$QpHRQMd탮8ЊXgKYۄ&t4̤638.mv :U!,ݷ}5 srRF)l[fMWv"QG2S0%#fQ F@PK!Hmod_ngarn-3.2.dist-info/RECORDuI0},  % <dЧl6äHzqE*8Z&@V~b񈝩߫i) 1з? \ӘF` 'eOKj6d쯬 ;ŭ0pjzCcy (͜KKH~aUKf\Wft/cpdF.90$P {3i@d{ w 8.WyL {خ'Ҝz-g:U"0m8t-EՉw'@oXde|EwNX?ᮭ 6w/\#F[%Xrj1y Q,,|-D՜o~