shqaff 0.0.1__tar.gz

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.
shqaff-0.0.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 ice1x
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
shqaff-0.0.1/PKG-INFO ADDED
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.4
2
+ Name: shqaff
3
+ Version: 0.0.1
4
+ Summary: A lightweight, PostgreSQL-backed task queue for Python
5
+ Author: ilia iakhin
6
+ License-Expression: MIT
7
+ Requires-Python: >=3.8
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: SQLAlchemy>=2.0
11
+ Requires-Dist: psycopg2-binary>=2.9
12
+ Dynamic: license-file
13
+
14
+ # shqaff
15
+
16
+ ## Overview
17
+
18
+ shqaff is a minimal task queue built with Python and SQLAlchemy. It stores jobs in a PostgreSQL table and processes them with registered consumers.
19
+
20
+ ## Installation
21
+
22
+ 1. Install dependencies:
23
+ ```bash
24
+ pip install -r requirements.txt
25
+ ```
26
+ 2. Configure database settings with environment variables such as `SHAQAFF_DB_HOST` and `SHAQAFF_DB_NAME` or rely on defaults.
27
+
28
+ ## Usage
29
+
30
+ 1. Initialize the database and start the example process:
31
+ ```bash
32
+ python main.py
33
+ ```
34
+ 2. The demo task creates a payload and processes it through a consumer.
35
+
36
+ ## Testing
37
+
38
+ Run the test suite:
39
+ ```bash
40
+ pytest
41
+ ```
shqaff-0.0.1/README.md ADDED
@@ -0,0 +1,28 @@
1
+ # shqaff
2
+
3
+ ## Overview
4
+
5
+ shqaff is a minimal task queue built with Python and SQLAlchemy. It stores jobs in a PostgreSQL table and processes them with registered consumers.
6
+
7
+ ## Installation
8
+
9
+ 1. Install dependencies:
10
+ ```bash
11
+ pip install -r requirements.txt
12
+ ```
13
+ 2. Configure database settings with environment variables such as `SHAQAFF_DB_HOST` and `SHAQAFF_DB_NAME` or rely on defaults.
14
+
15
+ ## Usage
16
+
17
+ 1. Initialize the database and start the example process:
18
+ ```bash
19
+ python main.py
20
+ ```
21
+ 2. The demo task creates a payload and processes it through a consumer.
22
+
23
+ ## Testing
24
+
25
+ Run the test suite:
26
+ ```bash
27
+ pytest
28
+ ```
@@ -0,0 +1,21 @@
1
+ [project]
2
+ name = "shqaff"
3
+ version = "0.0.1"
4
+ description = "A lightweight, PostgreSQL-backed task queue for Python"
5
+ authors = [
6
+ { name="ilia iakhin" }
7
+ ]
8
+ license = "MIT"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ dependencies = [
12
+ "SQLAlchemy>=2.0",
13
+ "psycopg2-binary>=2.9",
14
+ ]
15
+
16
+ [build-system]
17
+ requires = ["setuptools>=61.0"]
18
+ build-backend = "setuptools.build_meta"
19
+
20
+ [tool.setuptools.packages.find]
21
+ include = ["shqaff*"]
shqaff-0.0.1/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
File without changes
@@ -0,0 +1,11 @@
1
+ import os
2
+
3
+
4
+ DB_HOST = os.getenv("SHAQAFF_DB_HOST", "localhost")
5
+ DB_PORT = os.getenv("SHAQAFF_DB_PORT", "5432")
6
+ DB_NAME = os.getenv("SHAQAFF_DB_NAME", "shqaff")
7
+ DB_USER = os.getenv("SHAQAFF_DB_USER", "postgres")
8
+ DB_PASS = os.getenv("SHAQAFF_DB_PASS", "")
9
+
10
+
11
+ DATABASE_URL = f"postgresql://{DB_USER}:{DB_PASS}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
@@ -0,0 +1,13 @@
1
+ from abc import ABC, abstractmethod
2
+
3
+
4
+ class Consumer(ABC):
5
+
6
+ @property
7
+ @abstractmethod
8
+ def name(self) -> str:
9
+ pass
10
+
11
+ @abstractmethod
12
+ def run(self, payload: dict) -> None:
13
+ pass
@@ -0,0 +1,22 @@
1
+ from sqlalchemy import create_engine
2
+ from sqlalchemy.orm import sessionmaker, scoped_session
3
+
4
+ from .config import DATABASE_URL
5
+ from .models import Base
6
+
7
+
8
+ engine = create_engine(DATABASE_URL, pool_pre_ping=True)
9
+
10
+ SessionLocal = scoped_session(sessionmaker(bind=engine))
11
+
12
+
13
+ def get_db():
14
+ db = SessionLocal()
15
+ try:
16
+ yield db
17
+ finally:
18
+ db.close()
19
+
20
+
21
+ def init_db():
22
+ Base.metadata.create_all(bind=engine)
@@ -0,0 +1,53 @@
1
+ import time
2
+ from datetime import datetime
3
+
4
+ from shqaff.models import TaskQueue
5
+ from shqaff.registry import consumer_registry
6
+ from shqaff.task import Task
7
+ from shqaff.status import TaskStatus
8
+
9
+
10
+ def process_once(db, batch_size: int = 10):
11
+ tasks = (
12
+ db.query(TaskQueue)
13
+ .filter(TaskQueue.status == TaskStatus.PENDING.value)
14
+ .limit(batch_size)
15
+ .with_for_update(skip_locked=True)
16
+ .all()
17
+ )
18
+
19
+ for task_model in tasks:
20
+ consumer_cls = consumer_registry.get(task_model.consumer)
21
+ if not consumer_cls:
22
+ continue
23
+
24
+ task = Task(task_model)
25
+
26
+ try:
27
+ task.start()
28
+ task_model.last_attempt_at = datetime.utcnow()
29
+ db.commit()
30
+
31
+ consumer = consumer_cls()
32
+ consumer.run(task_model.payload)
33
+
34
+ task.succeed()
35
+
36
+ except Exception as e:
37
+ task_model.retries += 1
38
+ task_model.error = str(e)
39
+
40
+ if task_model.retries >= task_model.max_retries:
41
+ task.fail()
42
+ else:
43
+ task_model.status = TaskStatus.PENDING.value
44
+
45
+ finally:
46
+ task_model.updated_at = datetime.utcnow()
47
+ db.commit()
48
+
49
+
50
+ def process_tasks(db, poll_interval: int = 5, batch_size: int = 10):
51
+ while True:
52
+ process_once(db, batch_size=batch_size)
53
+ time.sleep(poll_interval)
@@ -0,0 +1,24 @@
1
+ from transitions import Machine
2
+
3
+ from .status import TaskStatus
4
+
5
+
6
+ class TaskStateMachine:
7
+
8
+ states = [status.value for status in TaskStatus]
9
+
10
+ def __init__(self, initial: TaskStatus | str = TaskStatus.PENDING):
11
+ self.state = initial.value if isinstance(initial, TaskStatus) else initial
12
+
13
+ self.machine = Machine(
14
+ model=self,
15
+ states=TaskStateMachine.states,
16
+ initial=self.state,
17
+ )
18
+
19
+ self.machine.add_transition("start", source=TaskStatus.PENDING.value, dest=TaskStatus.IN_PROGRESS.value)
20
+ self.machine.add_transition("succeed", source=TaskStatus.IN_PROGRESS.value, dest=TaskStatus.DONE.value)
21
+ self.machine.add_transition("fail", source=TaskStatus.IN_PROGRESS.value, dest=TaskStatus.FAILED.value)
22
+
23
+ def get_state(self) -> TaskStatus:
24
+ return TaskStatus(self.state)
@@ -0,0 +1,22 @@
1
+ from sqlalchemy import Column, Integer, String, Text, DateTime, JSON, func
2
+
3
+ from sqlalchemy.orm import declarative_base
4
+
5
+
6
+ Base = declarative_base()
7
+
8
+
9
+ class TaskQueue(Base):
10
+ __tablename__ = "task_queue"
11
+
12
+ id = Column(Integer, primary_key=True)
13
+ task_name = Column(String, nullable=False)
14
+ payload = Column(JSON, nullable=True)
15
+ consumer = Column(String, nullable=False)
16
+ status = Column(String, default="pending", nullable=False)
17
+ retries = Column(Integer, default=0, nullable=False)
18
+ max_retries = Column(Integer, default=3, nullable=False)
19
+ error = Column(Text, nullable=True)
20
+ created_at = Column(DateTime, server_default=func.now())
21
+ updated_at = Column(DateTime, onupdate=func.now())
22
+ last_attempt_at = Column(DateTime)
@@ -0,0 +1,17 @@
1
+ from sqlalchemy.orm import Session
2
+ from .models import TaskQueue
3
+ from .status import TaskStatus
4
+
5
+
6
+ def create_task(
7
+ db: Session, task_name: str, consumer: str, payload: dict, max_retries: int = 3
8
+ ) -> None:
9
+ task = TaskQueue(
10
+ task_name=task_name,
11
+ consumer=consumer,
12
+ payload=payload,
13
+ max_retries=max_retries,
14
+ status=TaskStatus.PENDING.value,
15
+ )
16
+ db.add(task)
17
+ db.commit()
@@ -0,0 +1,9 @@
1
+ from typing import Dict, Type
2
+ from .consumer import Consumer
3
+
4
+
5
+ consumer_registry: Dict[str, Type[Consumer]] = {}
6
+
7
+
8
+ def register_consumer(consumer_cls: Type[Consumer]) -> None:
9
+ consumer_registry[consumer_cls().name] = consumer_cls
@@ -0,0 +1,7 @@
1
+ from enum import Enum
2
+
3
+ class TaskStatus(str, Enum):
4
+ PENDING = "pending"
5
+ IN_PROGRESS = "in_progress"
6
+ DONE = "done"
7
+ FAILED = "failed"
@@ -0,0 +1,29 @@
1
+ from dataclasses import dataclass, field
2
+
3
+ from shqaff.models import TaskQueue
4
+ from shqaff.fsm import TaskStateMachine
5
+
6
+
7
+ @dataclass
8
+ class Task:
9
+ task: TaskQueue
10
+ fsm: TaskStateMachine = field(init=False)
11
+
12
+ def __post_init__(self):
13
+ self.fsm = TaskStateMachine(initial=self.task.status)
14
+
15
+ def start(self):
16
+ self.fsm.start()
17
+ self.task.status = self.fsm.get_state().value
18
+
19
+ def succeed(self):
20
+ self.fsm.succeed()
21
+ self.task.status = self.fsm.get_state().value
22
+
23
+ def fail(self):
24
+ self.fsm.fail()
25
+ self.task.status = self.fsm.get_state().value
26
+
27
+ @property
28
+ def model(self) -> TaskQueue:
29
+ return self.task
File without changes
@@ -0,0 +1,25 @@
1
+ import pytest
2
+ from shqaff.db import init_db, SessionLocal
3
+ from shqaff.models import TaskQueue
4
+ from shqaff.registry import consumer_registry
5
+
6
+
7
+ @pytest.fixture(autouse=True)
8
+ def clear_consumer_registry():
9
+ consumer_registry.clear()
10
+ yield
11
+ consumer_registry.clear()
12
+
13
+
14
+ @pytest.fixture(scope="function")
15
+ def db():
16
+ init_db()
17
+ session = SessionLocal()
18
+
19
+ # Clean the table before each test
20
+ session.query(TaskQueue).delete()
21
+ session.commit()
22
+
23
+ yield session
24
+
25
+ session.close()
@@ -0,0 +1,34 @@
1
+ from shqaff.models import TaskQueue
2
+ from shqaff.registry import register_consumer
3
+ from shqaff.event_loop import process_once
4
+ from shqaff.consumer import Consumer
5
+ from shqaff.producer import create_task
6
+ from shqaff.status import TaskStatus
7
+
8
+
9
+ class DummyConsumer(Consumer):
10
+ name = "dummy"
11
+ processed = []
12
+
13
+ def run(self, payload: dict) -> None:
14
+ self.__class__.processed.append(payload)
15
+
16
+
17
+ def test_event_loop_processes_task(db):
18
+ register_consumer(DummyConsumer)
19
+
20
+ create_task(
21
+ db=db,
22
+ task_name="some_task",
23
+ consumer="dummy",
24
+ payload={"hello": "world"},
25
+ max_retries=1,
26
+ )
27
+
28
+ process_once(db=db, batch_size=1)
29
+
30
+ task = db.query(TaskQueue).filter_by(consumer="dummy").first()
31
+ assert task.status == TaskStatus.DONE.value
32
+ assert task.error is None
33
+ assert task.retries == 0
34
+ assert DummyConsumer.processed[-1] == {"hello": "world"}
@@ -0,0 +1,32 @@
1
+ from shqaff.consumer import Consumer
2
+ from shqaff.registry import register_consumer
3
+ from shqaff.producer import create_task
4
+ from shqaff.event_loop import process_once
5
+ from shqaff.models import TaskQueue
6
+ from shqaff.status import TaskStatus
7
+
8
+
9
+ class AlwaysFailingConsumer(Consumer):
10
+ name = "always_fail"
11
+
12
+ def run(self, payload: dict) -> None:
13
+ raise RuntimeError("crash")
14
+
15
+
16
+ def test_task_fails_permanently_after_max_retries(db):
17
+ register_consumer(AlwaysFailingConsumer)
18
+
19
+ create_task(
20
+ db=db,
21
+ task_name="fail_task",
22
+ consumer="always_fail",
23
+ payload={},
24
+ max_retries=1,
25
+ )
26
+
27
+ process_once(db)
28
+
29
+ task = db.query(TaskQueue).first()
30
+ assert task.status == TaskStatus.FAILED.value
31
+ assert task.retries == 1
32
+ assert "crash" in task.error
@@ -0,0 +1,11 @@
1
+ import pytest
2
+ from shqaff.fsm import TaskStateMachine
3
+ from transitions.core import MachineError
4
+ from shqaff.status import TaskStatus
5
+
6
+
7
+ def test_invalid_fsm_transition_raises():
8
+ fsm = TaskStateMachine(initial=TaskStatus.DONE)
9
+
10
+ with pytest.raises(MachineError):
11
+ fsm.start()
@@ -0,0 +1,36 @@
1
+ from shqaff.consumer import Consumer
2
+ from shqaff.registry import register_consumer
3
+ from shqaff.producer import create_task
4
+ from shqaff.event_loop import process_once
5
+ from shqaff.models import TaskQueue
6
+ from shqaff.status import TaskStatus
7
+
8
+
9
+ class FailingOnceConsumer(Consumer):
10
+ name = "fail_once"
11
+ call_count = 0
12
+
13
+ def run(self, payload: dict) -> None:
14
+ self.__class__.call_count += 1
15
+ if self.__class__.call_count == 1:
16
+ raise Exception("fail once")
17
+
18
+
19
+ def test_retry_logic(db):
20
+ FailingOnceConsumer.call_count = 0
21
+ register_consumer(FailingOnceConsumer)
22
+
23
+ create_task(
24
+ db=db,
25
+ task_name="retry_task",
26
+ consumer="fail_once",
27
+ payload={},
28
+ max_retries=2,
29
+ )
30
+
31
+ process_once(db=db, batch_size=1)
32
+
33
+ task = db.query(TaskQueue).filter_by(consumer="fail_once").first()
34
+ assert task.status == TaskStatus.PENDING.value
35
+ assert task.retries == 1
36
+ assert "fail once" in task.error
@@ -0,0 +1,24 @@
1
+ from shqaff.models import TaskQueue
2
+ from shqaff.producer import create_task
3
+ from shqaff.status import TaskStatus
4
+
5
+
6
+ def test_create_task(db):
7
+ create_task(
8
+ db=db,
9
+ task_name="test_task",
10
+ consumer="test_consumer",
11
+ payload={"foo": "bar"},
12
+ max_retries=2,
13
+ )
14
+
15
+ task = (
16
+ db.query(TaskQueue)
17
+ .filter_by(task_name="test_task", consumer="test_consumer")
18
+ .first()
19
+ )
20
+
21
+ assert task is not None
22
+ assert task.payload["foo"] == "bar"
23
+ assert task.status == TaskStatus.PENDING.value
24
+ assert task.max_retries == 2
@@ -0,0 +1,27 @@
1
+ from shqaff.models import TaskQueue
2
+ from shqaff.task import Task
3
+ from shqaff.status import TaskStatus
4
+
5
+
6
+ def test_fsm_transitions():
7
+ task_model = TaskQueue(status=TaskStatus.PENDING.value)
8
+ task = Task(task_model)
9
+
10
+ assert task_model.status == TaskStatus.PENDING.value
11
+
12
+ task.start()
13
+ assert task_model.status == TaskStatus.IN_PROGRESS.value
14
+
15
+ task.succeed()
16
+ assert task_model.status == TaskStatus.DONE.value
17
+
18
+
19
+ def test_fsm_failure_transition():
20
+ task_model = TaskQueue(status=TaskStatus.PENDING.value)
21
+ task = Task(task_model)
22
+
23
+ task.start()
24
+ assert task_model.status == TaskStatus.IN_PROGRESS.value
25
+
26
+ task.fail()
27
+ assert task_model.status == TaskStatus.FAILED.value
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.4
2
+ Name: shqaff
3
+ Version: 0.0.1
4
+ Summary: A lightweight, PostgreSQL-backed task queue for Python
5
+ Author: ilia iakhin
6
+ License-Expression: MIT
7
+ Requires-Python: >=3.8
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: SQLAlchemy>=2.0
11
+ Requires-Dist: psycopg2-binary>=2.9
12
+ Dynamic: license-file
13
+
14
+ # shqaff
15
+
16
+ ## Overview
17
+
18
+ shqaff is a minimal task queue built with Python and SQLAlchemy. It stores jobs in a PostgreSQL table and processes them with registered consumers.
19
+
20
+ ## Installation
21
+
22
+ 1. Install dependencies:
23
+ ```bash
24
+ pip install -r requirements.txt
25
+ ```
26
+ 2. Configure database settings with environment variables such as `SHAQAFF_DB_HOST` and `SHAQAFF_DB_NAME` or rely on defaults.
27
+
28
+ ## Usage
29
+
30
+ 1. Initialize the database and start the example process:
31
+ ```bash
32
+ python main.py
33
+ ```
34
+ 2. The demo task creates a payload and processes it through a consumer.
35
+
36
+ ## Testing
37
+
38
+ Run the test suite:
39
+ ```bash
40
+ pytest
41
+ ```
@@ -0,0 +1,27 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ shqaff/__init__.py
5
+ shqaff/config.py
6
+ shqaff/consumer.py
7
+ shqaff/db.py
8
+ shqaff/event_loop.py
9
+ shqaff/fsm.py
10
+ shqaff/models.py
11
+ shqaff/producer.py
12
+ shqaff/registry.py
13
+ shqaff/status.py
14
+ shqaff/task.py
15
+ shqaff.egg-info/PKG-INFO
16
+ shqaff.egg-info/SOURCES.txt
17
+ shqaff.egg-info/dependency_links.txt
18
+ shqaff.egg-info/requires.txt
19
+ shqaff.egg-info/top_level.txt
20
+ shqaff/tests/__init__.py
21
+ shqaff/tests/conftest.py
22
+ shqaff/tests/test_event_loop.py
23
+ shqaff/tests/test_fail_after_max_retries.py
24
+ shqaff/tests/test_invalid_fsm_transition.py
25
+ shqaff/tests/test_retry_logic.py
26
+ shqaff/tests/test_smoke.py
27
+ shqaff/tests/test_task_fsm.py
@@ -0,0 +1,2 @@
1
+ SQLAlchemy>=2.0
2
+ psycopg2-binary>=2.9
@@ -0,0 +1 @@
1
+ shqaff