diff --git a/ATTRIBUTIONS.md b/ATTRIBUTIONS.md index 3bb8081..6c5e503 100644 --- a/ATTRIBUTIONS.md +++ b/ATTRIBUTIONS.md @@ -360,7 +360,7 @@ SOFTWARE. ``` -## aignostics-foundry-core (0.8.2) - MIT License +## aignostics-foundry-core (0.9.0) - MIT License 🏭 Foundational infrastructure for Foundry components. @@ -2543,6 +2543,36 @@ THE SOFTWARE. ``` +## chancy (0.25.1) - MIT License + +A simple and flexible job queue for Python + +* URL: https://github.com/tktech/chancy +* Author(s): Tyler Kennedy + +### License Text + +``` +Copyright (c) 2024 Tyler Kennedy + +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. +``` + ## chardet (5.2.0) - GNU Lesser General Public License v2 or later (LGPLv2+) Universal encoding detector for Python 3 @@ -3406,7 +3436,26 @@ Code coverage measurement for Python ``` -## cryptography (46.0.6) - UNKNOWN +## croniter (6.2.2) - MIT License + +croniter provides iteration for datetime object with cron like format + +* URL: https://github.com/pallets-eco/croniter +* Author(s): Matsumoto Taichi , kiorky , Ash Berlin-Taylor , Jarek Potiuk + +### License Text + +``` +Copyright (C) 2010-2012 Matsumoto Taichi + +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. +``` + +## cryptography (46.0.7) - UNKNOWN cryptography is a package which provides cryptographic recipes and primitives to Python developers. @@ -8515,6 +8564,184 @@ Library. ``` +## psycopg-pool (3.3.0) - UNKNOWN + +Connection Pool for Psycopg + +* URL: https://psycopg.org/ +* Author(s): Daniele Varrazzo + +### License Text + +``` + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. + +``` + ## py-serializable (2.1.0) - Apache Software License Library for serializing and deserializing Python Objects to and from JSON and XML. diff --git a/pyproject.toml b/pyproject.toml index 7de196f..e8a75d8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -62,6 +62,7 @@ dependencies = [ "rich>=14,<15", "sentry-sdk>=2,<3", "sqlalchemy[postgresql-psycopgbinary,asyncio]>=2,<3", + "chancy[cron]>=0.25.1,<1", "nicegui>=3,<4", "truststore>=0.9,<1", "typer>=0.14,<1", diff --git a/src/aignostics_foundry_core/AGENTS.md b/src/aignostics_foundry_core/AGENTS.md index 0a3d186..a6a054d 100644 --- a/src/aignostics_foundry_core/AGENTS.md +++ b/src/aignostics_foundry_core/AGENTS.md @@ -26,6 +26,7 @@ This file provides an overview of all modules in `aignostics_foundry_core`, thei | **foundry** | Project context injection | `PackageMetadata`, `FoundryContext`, `FoundryContext.from_package()`, `set_context()`, `get_context()` — centralised project-specific values (name, version, `version_full`, `version_with_vcs_ref`, environment, env files, URLs, `python_version`, `metadata: PackageMetadata` (description, author_name, author_email), runtime mode flags `is_container`, `is_cli`, `is_test`, `is_library`, `database: DatabaseSettings \| None`) derived from package metadata and environment variables; `from_package()` populates `metadata` from `importlib.metadata` and `database` from `{env_prefix}DB_*` env vars when `{env_prefix}DB_URL` is present | | **di** | Dependency injection | `locate_subclasses(cls, *, context=None)`, `locate_implementations(cls, *, context=None)`, `load_modules(*, context=None)`, `discover_plugin_packages`, `clear_caches`, `PLUGIN_ENTRY_POINT_GROUP` for plugin and subclass discovery | | **health** | Service health checks | `Health` model and `HealthStatus` enum for tree-structured health status | +| **scheduler** | Chancy-backed job module base class | `BaseJoblet` ABC with `get_queues()`, `get_jobs()`, `get_crons()`, `get_triggers()` hooks and `register_queues/jobs/crons/triggers()` / `unregister_queues/jobs/crons/triggers()` lifecycle methods; `key()` returns second-to-last module component for identification | | **settings** | Pydantic settings loading | `OpaqueSettings`, `load_settings`, `strip_to_none_before_validator`, `UNHIDE_SENSITIVE_INFO` for env-based settings with secret masking and user-friendly validation errors; `console`, `Panel`, and `Text` are imported lazily inside `load_settings` (error path only) | ## Module Descriptions @@ -314,6 +315,45 @@ This file provides an overview of all modules in `aignostics_foundry_core`, thei - **Dependencies**: `fastapi>=0.110,<1` (for typing/DI); `pydantic-settings>=2`; `aignostics_foundry_core.health`, `aignostics_foundry_core.settings` - **Import**: `from aignostics_foundry_core.service import BaseService` +### scheduler + +**Chancy-backed job module base class** + +- **Purpose**: Provides `BaseJoblet` — a reusable base class for building modular Chancy job units (joblets) that can be auto-registered with the scheduler. Any Foundry component that wants to define queues, one-time jobs, cron schedules, or database triggers extends `BaseJoblet` instead of coupling directly to the scheduler's internals. +- **Key Features**: + - `get_queues()` — override to return `list[Queue]` declarations for this joblet (empty by default) + - `get_jobs()` — override to return `list[Job]` for one-time or delayed pushes (empty by default) + - `get_crons()` — override to return `list[tuple[str, Job]]` of `(cron_expression, job)` pairs; jobs **must** have a `unique_key` set or they will be skipped with a warning + - `get_triggers()` — override to return `list[tuple[str, list[str], Job]]` of `(table, operations, job_template)` for PostgreSQL trigger-based dispatch + - `register_queues/jobs/crons/triggers(chancy)` — async lifecycle methods; call them on startup to declare resources + - `unregister_queues/jobs/crons/triggers(chancy)` — async lifecycle methods; call them on shutdown to clean up resources + - `key()` — classmethod; returns the second-to-last dotted segment of `cls.__module__` (e.g. `"hello_world"` from `"bridge.hello_world.Joblet"`) for logging and identification +- **Location**: `aignostics_foundry_core/scheduler.py` +- **Dependencies**: `chancy[cron]>=0.25.1,<1` (mandatory); `loguru>=0.7,<1` +- **Import**: + ```python + from aignostics_foundry_core.scheduler import BaseJoblet + ``` +- **Usage example**: + ```python + from chancy import Job, Queue, job + from aignostics_foundry_core.scheduler import BaseJoblet + + + @job(queue="my_module") + async def my_task() -> None: ... + + + class Joblet(BaseJoblet): + @staticmethod + def get_queues() -> list[Queue]: + return [Queue("my_module", concurrency=4)] + + @staticmethod + def get_crons() -> list[tuple[str, Job]]: + return [("* * * * *", my_task.job.with_unique_key("my_cron"))] + ``` + ### cli **Typer CLI preparation utilities** diff --git a/src/aignostics_foundry_core/scheduler.py b/src/aignostics_foundry_core/scheduler.py new file mode 100644 index 0000000..1fea6cf --- /dev/null +++ b/src/aignostics_foundry_core/scheduler.py @@ -0,0 +1,290 @@ +"""Scheduler abstractions — BaseJoblet for Chancy-backed job modules.""" + +import asyncio + +from chancy import Chancy, Job, Queue +from chancy.plugins.cron import Cron +from chancy.plugins.trigger import Trigger +from loguru import logger + + +class BaseJoblet: + """Base class for joblets that can be auto-registered with the scheduler. + + Implement one or all of get_queues, get_jobs, and get_crons to define the joblet's behavior. + + Note: For advanced use cases, you can implement special handling when registering or unregistering, + override the respective methods. + """ + + @staticmethod + def get_queues() -> list[Queue]: + """ + Get queues for this joblet. + + Subclasses can override this method to return custom queues with specific + configurations (concurrency, rate limits, etc.). + + Returns: + list[Queue]: List of Queue instances to declare. Empty list by default. + """ + return [] + + @staticmethod + def get_jobs() -> list[Job]: + """ + Get one-time or scheduled jobs for this joblet. + + Subclasses can override this method to return jobs that should be pushed + to the scheduler (e.g., one-time jobs with scheduled_at, jobs with delays). + + Returns: + list[Job]: List of Job instances to push. Empty list by default. + """ + return [] + + @staticmethod + def get_crons() -> list[tuple[str, Job]]: + """ + Get cron jobs for this joblet. + + This method should be implemented by subclasses to return their cron schedules. + + Returns: + list[tuple[str, Job]]: List of tuples containing (cron_expression, job). + Example: [("* * * * *", my_job.job.with_unique_key("my_cron"))] + """ + return [] + + @staticmethod + def get_triggers() -> list[ + tuple[ + str, + list[str], + Job, + ] + ]: + """ + Get trigger jobs for this joblet. + + This method should be implemented by subclasses to return their trigger configurations. + + Returns: + list[tuple[str, list[str], Job]]: List of tuples containing (table_name, operations, job_template). + Example: [("my_table", ["INSERT", "UPDATE"], my_job)] + """ + return [] + + async def register_queues(self, chancy: Chancy) -> None: + """ + Register queues with the scheduler. + + Args: + chancy: The Chancy instance to register queues with. + """ + for queue in self.get_queues(): + logger.trace("Joblet {} registering queue '{}'.", self.key(), queue.name) + await chancy.declare(queue, upsert=True) + logger.debug("Joblet {} registered queue '{}' with state {}.", self.key(), queue.name, queue.state) + + async def register_jobs(self, chancy: Chancy) -> None: + """ + Register jobs with the scheduler. + + Args: + chancy: The Chancy instance to register jobs with. + """ + for job in self.get_jobs(): + logger.trace("Joblet {} pushing job '{}'.", self.key(), job) + reference = await chancy.push(job) + logger.debug( + "Joblet {} registered job {} with reference {}.", + self.key(), + job, + reference, + ) + + async def register_crons(self, chancy: Chancy) -> None: + """ + Register cron jobs with the scheduler. + + Args: + chancy: The Chancy instance to register cron jobs with. + """ + for cron_expression, job in self.get_crons(): + logger.trace( + "Joblet {} scheduling cron job with expression '{}' and unique key '{}'.", + self.key(), + cron_expression, + job.unique_key, + ) + if not job.unique_key: + logger.warning( + "Joblet {} tried to schedule cron job without unique key - scheduling skipped", + self.key(), + ) + continue + await Cron.schedule(chancy, cron_expression, job) # pyright: ignore[reportUnknownMemberType] + logger.debug( + "Joblet {} scheduled cron job with expression '{}' and unique key '{}'.", + self.key(), + cron_expression, + job.unique_key, + ) + + async def register_triggers(self, chancy: Chancy) -> None: + """ + Register trigger jobs with the scheduler. + + Args: + chancy: The Chancy instance to register trigger jobs with. + """ + triggers_to_register = self.get_triggers() + if not triggers_to_register: + return + triggers = await Trigger.get_triggers(chancy) + logger.trace("Found existing triggers: {}", triggers) + for table_name, operations, job_template in triggers_to_register: + logger.trace( + "Joblet {} registering trigger for table name '{}', operations '{}', and job template '{}'.", + self.key(), + table_name, + operations, + job_template, + ) + for trigger_id, trigger_config in triggers.items(): + if ( + trigger_config.table_name == table_name + and set(trigger_config.operations) == set(operations) + and trigger_config.job_template.func == job_template.func + ): + logger.debug( + "Joblet {} found existing trigger with id '{}' for table name '{}', " + "operations '{}', and job template '{}'. Skipping registration.", + self.key(), + trigger_id, + table_name, + operations, + job_template, + ) + break + else: + trigger_id = await Trigger.register_trigger( # pyright: ignore[reportUnknownMemberType] + chancy=chancy, table_name=table_name, operations=operations, job_template=job_template + ) + logger.debug( + "Joblet {} registered trigger with id '{}' for table name '{}', " + "operations '{}', and job template '{}'.", + self.key(), + trigger_id, + table_name, + operations, + job_template, + ) + + async def unregister_queues(self, chancy: Chancy, purge_jobs: bool = True) -> None: + """ + Unregister queues from the scheduler. + + Args: + chancy: The Chancy instance to unregister queues from. + purge_jobs: Whether to purge all jobs from the queue before deletion. + """ + for queue in self.get_queues(): + logger.trace("Joblet {} unregistering queue '{}'.", self.key(), queue.name) + await chancy.delete_queue(queue.name, purge_jobs=purge_jobs) + logger.debug("Joblet {} unregistered queue '{}'.", self.key(), queue.name) + + async def unregister_jobs(self, chancy: Chancy) -> None: + """ + Unregister jobs from the scheduler. + + This removes jobs that were pushed with unique keys. + Note: Currently no-op as Chancy doesn't provide delete_job API. + + Args: + chancy: The Chancy instance to unregister jobs from. + """ + # TODO(helmut): Implement when Chancy provides delete_job API + _ = chancy + await asyncio.sleep(0) # SonarQube wants this function to do something async + logger.warning( + "Joblet {} unregister_jobs called, but not implemented as Chancy does not provide delete_job API.", + self.key(), + ) + + async def unregister_crons(self, chancy: Chancy) -> None: + """ + Unregister cron jobs from the scheduler. + + This removes cron schedules that were registered with unique keys. + + Args: + chancy: The Chancy instance to unregister cron jobs from. + """ + for _, job in self.get_crons(): + if job.unique_key: + logger.trace("Joblet {} unregistering cron job with unique key '{}'.", self.key(), job.unique_key) + await Cron.unschedule(chancy, job.unique_key) + logger.debug("Joblet {} unregistered cron job with unique key '{}'.", self.key(), job.unique_key) + else: + logger.critical( + "When unregistering crons Joblet {} found cron job without unique key - this must not happen.", + self.key(), + ) + + async def unregister_triggers(self, chancy: Chancy) -> None: + """ + Unregister trigger jobs from the scheduler. + + This removes triggers that were registered by this joblet. + + Args: + chancy: The Chancy instance to unregister trigger jobs from. + """ + triggers = await Trigger.get_triggers(chancy) + for table_name, operations, job_template in self.get_triggers(): + logger.trace( + "Joblet {} unregistering trigger for table name '{}', operations '{}', and job template '{}'.", + self.key(), + table_name, + operations, + job_template, + ) + unregistered = False + for trigger_id, trigger_config in triggers.items(): + if ( + trigger_config.table_name == table_name + and set(trigger_config.operations) == set(operations) + and trigger_config.job_template.func == job_template.func + ): + await Trigger.unregister_trigger(chancy, trigger_id) + unregistered = True + logger.debug( + "Joblet {} unregistered trigger with id '{}' for table name '{}', " + "operations '{}', and job template '{}'.", + self.key(), + trigger_id, + table_name, + operations, + job_template, + ) + if not unregistered: + logger.debug( + "Joblet {} found no matching trigger to unregister for table name '{}', " + "operations '{}', and job template '{}'.", + self.key(), + table_name, + operations, + job_template, + ) + + @classmethod + def key(cls) -> str: + """ + Return the module name of the joblet class. + + Returns: + str: Module name (e.g., 'hello_world' for bridge.hello_world.Joblet). + """ + return cls.__module__.split(".")[-2] diff --git a/tests/aignostics_foundry_core/scheduler_test.py b/tests/aignostics_foundry_core/scheduler_test.py new file mode 100644 index 0000000..ef7761a --- /dev/null +++ b/tests/aignostics_foundry_core/scheduler_test.py @@ -0,0 +1,338 @@ +"""Tests for scheduler module — BaseJoblet behaviour.""" + +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +from chancy import Chancy, Job, Queue + +from aignostics_foundry_core.scheduler import BaseJoblet + +QUEUE_NAME = "test_queue" +CRON_EXPRESSION = "* * * * *" +UNIQUE_KEY = "my_cron" +JOB_UNIQUE_KEY = "my_job" +TABLE_NAME = "my_table" +TABLE_NAME_2 = "other_table" +OPERATIONS = ["INSERT", "UPDATE"] +TRIGGER_ID = "tid-1" + + +class _QueueJoblet(BaseJoblet): + """Joblet that declares a single named queue.""" + + @staticmethod + def get_queues() -> list[Queue]: + return [Queue(QUEUE_NAME)] + + +class _JobJoblet(BaseJoblet): + """Joblet that declares a single job.""" + + @staticmethod + def get_jobs() -> list[Job]: + return [MagicMock(spec=Job)] + + +def _make_trigger_joblet(job_template: Job) -> BaseJoblet: + """Return a BaseJoblet instance whose get_triggers() yields the given job_template.""" + + class _TriggerJoblet(BaseJoblet): + @staticmethod + def get_triggers() -> list[tuple[str, list[str], Job]]: + return [(TABLE_NAME, OPERATIONS, job_template)] + + return _TriggerJoblet() + + +def _make_cron_joblet(job: Job) -> BaseJoblet: + """Return a BaseJoblet instance whose get_crons() yields the given job.""" + + class _CronJoblet(BaseJoblet): + @staticmethod + def get_crons() -> list[tuple[str, Job]]: + return [(CRON_EXPRESSION, job)] + + return _CronJoblet() + + +class TestDefaultHooks: + """Tests for BaseJoblet default hook return values.""" + + @pytest.mark.unit + def test_get_queues_returns_empty_list(self) -> None: + """get_queues() returns an empty list by default.""" + assert BaseJoblet().get_queues() == [] + + @pytest.mark.unit + def test_get_jobs_returns_empty_list(self) -> None: + """get_jobs() returns an empty list by default.""" + assert BaseJoblet().get_jobs() == [] + + @pytest.mark.unit + def test_get_crons_returns_empty_list(self) -> None: + """get_crons() returns an empty list by default.""" + assert BaseJoblet().get_crons() == [] + + +class TestRegisterJobs: + """Tests for BaseJoblet.register_jobs().""" + + @pytest.mark.unit + async def test_register_jobs_pushes_each_job(self) -> None: + """register_jobs calls chancy.push once for each job returned by get_jobs().""" + joblet = _JobJoblet() + mock_chancy = MagicMock(spec=Chancy) + mock_chancy.push = AsyncMock(return_value="ref") + + await joblet.register_jobs(mock_chancy) + + assert mock_chancy.push.call_count == 1 + pushed_job = mock_chancy.push.call_args.args[0] + assert isinstance(pushed_job, MagicMock) + + +class TestRegisterQueues: + """Tests for BaseJoblet.register_queues().""" + + @pytest.mark.unit + async def test_register_queues_declares_each_queue(self) -> None: + """register_queues calls chancy.declare once per queue with upsert=True.""" + joblet = _QueueJoblet() + mock_chancy = MagicMock(spec=Chancy) + mock_chancy.declare = AsyncMock() + + await joblet.register_queues(mock_chancy) + + assert mock_chancy.declare.call_count == 1 + call_args = mock_chancy.declare.call_args + assert call_args.args[0].name == QUEUE_NAME + assert call_args.kwargs == {"upsert": True} + + +class TestRegisterCrons: + """Tests for BaseJoblet.register_crons().""" + + @pytest.mark.unit + async def test_register_crons_skips_job_without_unique_key(self) -> None: + """register_crons never calls Cron.schedule when job.unique_key is falsy.""" + job = MagicMock(spec=Job) + job.unique_key = None + joblet = _make_cron_joblet(job) + mock_chancy = MagicMock(spec=Chancy) + + with patch("aignostics_foundry_core.scheduler.Cron.schedule", new_callable=AsyncMock) as mock_schedule: + await joblet.register_crons(mock_chancy) + + mock_schedule.assert_not_called() + + @pytest.mark.unit + async def test_register_crons_schedules_job_with_unique_key(self) -> None: + """register_crons calls Cron.schedule with (chancy, expression, job) when unique_key is set.""" + job = MagicMock(spec=Job) + job.unique_key = UNIQUE_KEY + joblet = _make_cron_joblet(job) + mock_chancy = MagicMock(spec=Chancy) + + with patch("aignostics_foundry_core.scheduler.Cron.schedule", new_callable=AsyncMock) as mock_schedule: + await joblet.register_crons(mock_chancy) + + mock_schedule.assert_called_once_with(mock_chancy, CRON_EXPRESSION, job) + + +class TestRegisterTriggers: + """Tests for BaseJoblet.register_triggers().""" + + @pytest.mark.unit + async def test_register_triggers_is_noop_when_no_triggers(self) -> None: + """register_triggers returns early without calling Trigger.get_triggers when get_triggers() is empty.""" + joblet = BaseJoblet() + mock_chancy = MagicMock(spec=Chancy) + + with patch("aignostics_foundry_core.scheduler.Trigger.get_triggers", new_callable=AsyncMock) as mock_get: + await joblet.register_triggers(mock_chancy) + + mock_get.assert_not_called() + + @pytest.mark.unit + async def test_register_triggers_registers_new_trigger(self) -> None: + """register_triggers calls Trigger.register_trigger when no matching trigger exists.""" + job_template = MagicMock() + joblet = _make_trigger_joblet(job_template) + mock_chancy = MagicMock(spec=Chancy) + + with ( + patch("aignostics_foundry_core.scheduler.Trigger.get_triggers", new_callable=AsyncMock) as mock_get, + patch("aignostics_foundry_core.scheduler.Trigger.register_trigger", new_callable=AsyncMock) as mock_reg, + ): + mock_get.return_value = {} + await joblet.register_triggers(mock_chancy) + + mock_reg.assert_called_once_with( + chancy=mock_chancy, table_name=TABLE_NAME, operations=OPERATIONS, job_template=job_template + ) + + @pytest.mark.unit + async def test_register_triggers_handles_multiple_triggers(self) -> None: + """register_triggers registers only non-matching triggers when multiple are configured.""" + job1 = MagicMock() + job2 = MagicMock() + + class _MultiTriggerJoblet(BaseJoblet): + @staticmethod + def get_triggers() -> list[tuple[str, list[str], Job]]: + return [(TABLE_NAME, OPERATIONS, job1), (TABLE_NAME_2, OPERATIONS, job2)] + + joblet = _MultiTriggerJoblet() + mock_chancy = MagicMock(spec=Chancy) + + mock_config = MagicMock() + mock_config.table_name = TABLE_NAME + mock_config.operations = list(OPERATIONS) + mock_config.job_template.func = job1.func + + with ( + patch("aignostics_foundry_core.scheduler.Trigger.get_triggers", new_callable=AsyncMock) as mock_get, + patch("aignostics_foundry_core.scheduler.Trigger.register_trigger", new_callable=AsyncMock) as mock_reg, + ): + mock_get.return_value = {TRIGGER_ID: mock_config} + await joblet.register_triggers(mock_chancy) + + mock_reg.assert_called_once_with( + chancy=mock_chancy, table_name=TABLE_NAME_2, operations=OPERATIONS, job_template=job2 + ) + + @pytest.mark.unit + async def test_register_triggers_skips_existing_matching_trigger(self) -> None: + """register_triggers does not call Trigger.register_trigger when a matching trigger exists.""" + job_template = MagicMock() + joblet = _make_trigger_joblet(job_template) + mock_chancy = MagicMock(spec=Chancy) + + mock_config = MagicMock() + mock_config.table_name = TABLE_NAME + mock_config.operations = list(OPERATIONS) + mock_config.job_template.func = job_template.func + + with ( + patch("aignostics_foundry_core.scheduler.Trigger.get_triggers", new_callable=AsyncMock) as mock_get, + patch("aignostics_foundry_core.scheduler.Trigger.register_trigger", new_callable=AsyncMock) as mock_reg, + ): + mock_get.return_value = {TRIGGER_ID: mock_config} + await joblet.register_triggers(mock_chancy) + + mock_reg.assert_not_called() + + +class TestUnregisterQueues: + """Tests for BaseJoblet.unregister_queues().""" + + @pytest.mark.unit + async def test_unregister_queues_calls_delete_queue(self) -> None: + """unregister_queues calls chancy.delete_queue with correct name and purge_jobs=True.""" + joblet = _QueueJoblet() + mock_chancy = MagicMock(spec=Chancy) + mock_chancy.delete_queue = AsyncMock() + + await joblet.unregister_queues(mock_chancy) + + mock_chancy.delete_queue.assert_called_once_with(QUEUE_NAME, purge_jobs=True) + + +class TestUnregisterJobs: + """Tests for BaseJoblet.unregister_jobs().""" + + @pytest.mark.unit + async def test_unregister_jobs_completes_without_error(self) -> None: + """unregister_jobs runs to completion without raising an exception.""" + await BaseJoblet().unregister_jobs(MagicMock(spec=Chancy)) + + +class TestUnregisterCrons: + """Tests for BaseJoblet.unregister_crons().""" + + @pytest.mark.unit + async def test_unregister_crons_unschedules_job_with_unique_key(self) -> None: + """unregister_crons calls Cron.unschedule with the job's unique_key.""" + job = MagicMock(spec=Job) + job.unique_key = UNIQUE_KEY + joblet = _make_cron_joblet(job) + mock_chancy = MagicMock(spec=Chancy) + + with patch("aignostics_foundry_core.scheduler.Cron.unschedule", new_callable=AsyncMock) as mock_unschedule: + await joblet.unregister_crons(mock_chancy) + + mock_unschedule.assert_called_once_with(mock_chancy, UNIQUE_KEY) + + @pytest.mark.unit + async def test_unregister_crons_skips_job_without_unique_key(self) -> None: + """unregister_crons does not call Cron.unschedule when job has no unique_key.""" + job = MagicMock(spec=Job) + job.unique_key = None + joblet = _make_cron_joblet(job) + mock_chancy = MagicMock(spec=Chancy) + + with patch("aignostics_foundry_core.scheduler.Cron.unschedule", new_callable=AsyncMock) as mock_unschedule: + await joblet.unregister_crons(mock_chancy) + + mock_unschedule.assert_not_called() + + +class TestUnregisterTriggers: + """Tests for BaseJoblet.unregister_triggers().""" + + @pytest.mark.unit + async def test_unregister_triggers_unregisters_matching_trigger(self) -> None: + """unregister_triggers calls Trigger.unregister_trigger with the matching trigger ID.""" + job_template = MagicMock() + joblet = _make_trigger_joblet(job_template) + mock_chancy = MagicMock(spec=Chancy) + + mock_config = MagicMock() + mock_config.table_name = TABLE_NAME + mock_config.operations = list(OPERATIONS) + mock_config.job_template.func = job_template.func + + with ( + patch("aignostics_foundry_core.scheduler.Trigger.get_triggers", new_callable=AsyncMock) as mock_get, + patch("aignostics_foundry_core.scheduler.Trigger.unregister_trigger", new_callable=AsyncMock) as mock_unreg, + ): + mock_get.return_value = {TRIGGER_ID: mock_config} + await joblet.unregister_triggers(mock_chancy) + + mock_unreg.assert_called_once_with(mock_chancy, TRIGGER_ID) + + @pytest.mark.unit + async def test_unregister_triggers_logs_when_no_matching_trigger(self) -> None: + """unregister_triggers does not call Trigger.unregister_trigger when no trigger matches.""" + job_template = MagicMock() + joblet = _make_trigger_joblet(job_template) + mock_chancy = MagicMock(spec=Chancy) + + mock_config = MagicMock() + mock_config.table_name = "other_table" + mock_config.operations = list(OPERATIONS) + mock_config.job_template.func = job_template.func + + with ( + patch("aignostics_foundry_core.scheduler.Trigger.get_triggers", new_callable=AsyncMock) as mock_get, + patch("aignostics_foundry_core.scheduler.Trigger.unregister_trigger", new_callable=AsyncMock) as mock_unreg, + ): + mock_get.return_value = {TRIGGER_ID: mock_config} + await joblet.unregister_triggers(mock_chancy) + + mock_unreg.assert_not_called() + + +class TestKey: + """Tests for BaseJoblet.key().""" + + @pytest.mark.unit + def test_key_returns_second_to_last_module_component(self) -> None: + """key() returns the second-to-last dotted segment of the subclass __module__.""" + + class _LocalJoblet(BaseJoblet): + pass + + expected = _LocalJoblet.__module__.split(".")[-2] + assert _LocalJoblet.key() == expected + assert len(_LocalJoblet.key()) > 0 diff --git a/uv.lock b/uv.lock index 9f5fdea..cc02ead 100644 --- a/uv.lock +++ b/uv.lock @@ -13,6 +13,7 @@ dependencies = [ { name = "asyncpg" }, { name = "auth0-fastapi" }, { name = "certifi" }, + { name = "chancy", extra = ["cron"] }, { name = "fastapi" }, { name = "loguru" }, { name = "nicegui" }, @@ -63,6 +64,7 @@ requires-dist = [ { name = "asyncpg", specifier = ">=0.29,<1" }, { name = "auth0-fastapi", specifier = ">=1.0.0b5,<2" }, { name = "certifi", specifier = ">=2024" }, + { name = "chancy", extras = ["cron"], specifier = ">=0.25.1,<1" }, { name = "fastapi", specifier = ">=0.110,<1" }, { name = "loguru", specifier = ">=0.7,<1" }, { name = "nicegui", specifier = ">=3,<4" }, @@ -527,6 +529,23 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/db/3c/33bac158f8ab7f89b2e59426d5fe2e4f63f7ed25df84c036890172b412b5/cfgv-3.5.0-py2.py3-none-any.whl", hash = "sha256:a8dc6b26ad22ff227d2634a65cb388215ce6cc96bbcc5cfde7641ae87e8dacc0", size = 7445, upload-time = "2025-11-19T20:55:50.744Z" }, ] +[[package]] +name = "chancy" +version = "0.25.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "psycopg", extra = ["pool"] }, +] +sdist = { url = "https://files.pythonhosted.org/packages/3c/1e/d30cc2ecc39cc6941ce7f1004c443777a28733d7a688538fe1ceb2a6b582/chancy-0.25.1.tar.gz", hash = "sha256:264ed4f732cb51c405b789e0727c4d045fdfa1dcee1e3eed6d762df6c44122d7", size = 2128541, upload-time = "2025-10-29T00:34:27.697Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f0/17/8d7be15484ad627c8b0a94d43c8b213f5d5fee54384fd124343102308388/chancy-0.25.1-py3-none-any.whl", hash = "sha256:bcc8cd296c3268dbebb156c658fe47417d4f67b0c2722ffd21cfd4c0f32f892f", size = 523914, upload-time = "2025-10-29T00:34:25.914Z" }, +] + +[package.optional-dependencies] +cron = [ + { name = "croniter" }, +] + [[package]] name = "chardet" version = "5.2.0" @@ -785,6 +804,18 @@ toml = [ { name = "tomli", marker = "python_full_version <= '3.11'" }, ] +[[package]] +name = "croniter" +version = "6.2.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "python-dateutil" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/df/de/5832661ed55107b8a09af3f0a2e71e0957226a59eb1dcf0a445cce6daf20/croniter-6.2.2.tar.gz", hash = "sha256:ba60832a5ec8e12e51b8691c3309a113d1cf6526bdf1a48150ce8ec7a532d0ab", size = 113762, upload-time = "2026-03-15T08:43:48.112Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d0/39/783980e78cb92c2d7bdb1fc7dbc86e94ccc6d58224d76a7f1f51b6c51e30/croniter-6.2.2-py3-none-any.whl", hash = "sha256:a5d17b1060974d36251ea4faf388233eca8acf0d09cbd92d35f4c4ac8f279960", size = 45422, upload-time = "2026-03-15T08:43:46.626Z" }, +] + [[package]] name = "cryptography" version = "46.0.7" @@ -2249,6 +2280,9 @@ wheels = [ binary = [ { name = "psycopg-binary", marker = "implementation_name != 'pypy'" }, ] +pool = [ + { name = "psycopg-pool" }, +] [[package]] name = "psycopg-binary" @@ -2301,6 +2335,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/98/5a/291d89f44d3820fffb7a04ebc8f3ef5dda4f542f44a5daea0c55a84abf45/psycopg_binary-3.3.3-cp314-cp314-win_amd64.whl", hash = "sha256:165f22ab5a9513a3d7425ffb7fcc7955ed8ccaeef6d37e369d6cc1dff1582383", size = 3652796, upload-time = "2026-02-18T16:52:14.02Z" }, ] +[[package]] +name = "psycopg-pool" +version = "3.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/56/9a/9470d013d0d50af0da9c4251614aeb3c1823635cab3edc211e3839db0bcf/psycopg_pool-3.3.0.tar.gz", hash = "sha256:fa115eb2860bd88fce1717d75611f41490dec6135efb619611142b24da3f6db5", size = 31606, upload-time = "2025-12-01T11:34:33.11Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/c3/26b8a0908a9db249de3b4169692e1c7c19048a9bc41a4d3209cee7dbb758/psycopg_pool-3.3.0-py3-none-any.whl", hash = "sha256:2e44329155c410b5e8666372db44276a8b1ebd8c90f1c3026ebba40d4bc81063", size = 39995, upload-time = "2025-12-01T11:34:29.761Z" }, +] + [[package]] name = "py-serializable" version = "2.1.0"