Source code for smarter.apps.account.tasks.queue

"""
The one place that queues the account app's Celery tasks.

Every task of the app is queued by a function of this module, never by ``<task>.delay()`` or
``<task>.apply_async()`` anywhere else: not by the web console's apis, not by the other apps that charge for what
they do, the provider's chat and the proxy, and not by the tasks themselves (ADR-030, rule 10, issue #1098). So this
module is where to look for what queues a task, and the one place that a test patches so that nothing reaches a
real worker. Celery Beat sends the account's scheduled tasks by their names.

Each function checks, with reads alone, what can be checked now, so that a mistake is an error to its caller,
records what it queued, e.g. a data export's row, and queues the task once the current transaction commits, so that
the worker finds the row. Outside a transaction, the task is queued at once.
"""

from typing import Optional

from django.db import transaction
from django.utils.translation import gettext as _

from smarter.apps.account.models import DataExport, RepositoryApply, User, UserProfile
from smarter.apps.account.repositories.apply import (
    REPOSITORY_APPLIES_PER_DAY,
    RepositoryApplyRefusedError,
    normalize_repository_url,
    runs_started_today,
)
from smarter.apps.account.utils.data_export import (
    DATA_EXPORTS_PER_DAY,
    DataExportStartRefusedError,
    exports_started_today,
    latest_data_export,
)
from smarter.lib import logging
from smarter.lib.django.waffle import SmarterWaffleSwitches

from .billing import create_charge
from .data_exports import create_data_export
from .repositories import apply_repository

logger = logging.getSmarterLogger(
    __name__, any_switches=[SmarterWaffleSwitches.TASK_LOGGING, SmarterWaffleSwitches.ACCOUNT_LOGGING]
)


[docs] def queue_create_charge( # pylint: disable=too-many-arguments resource_locator: str, charge_type: str, prompt_tokens: int, completion_tokens: int, total_tokens: int, *, provider: Optional[str] = None, model: Optional[str] = None, ) -> None: """ Queue :func:`~smarter.apps.account.tasks.billing.create_charge`, which records a charge against a resource. The provider's chat (:class:`~smarter.apps.provider.services.text_completion.lib.mixins.ChatDbMixin`) and the proxy (:func:`smarter.apps.proxy.services.record_charges`) call it, once for each resource that a request is charged to. It is a record, so there is nothing to check: the callers decide what is charged. :param resource_locator: The record locator of the resource that is charged, e.g. an account's. :param charge_type: The kind of charge, e.g. ``prompt_completion``. :param prompt_tokens: The prompt's tokens. :param completion_tokens: The completion's tokens. :param total_tokens: All of the tokens. :param provider: The LLM provider's name, to price the tokens with ``LLMPrices``. :param model: The LLM's name, to price the tokens with ``LLMPrices``. """ kwargs = { "resource_locator": resource_locator, "charge_type": charge_type, "prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens, "total_tokens": total_tokens, "provider": provider, "model": model, } transaction.on_commit(lambda: create_charge.delay(**kwargs))
[docs] def queue_create_data_export(user: User) -> tuple[DataExport, bool]: """ Start a data export for the user, unless one is already in progress, and queue :func:`~smarter.apps.account.tasks.data_exports.create_data_export`. The web console's and the api's Download My Data call it. The task is queued once the export's row is committed, so that the worker finds it. :param user: The user. :returns: The export, and True if it was started now, or False if one was already in progress. :raises DataExportStartRefusedError: If the user has no email address, or started :data:`~smarter.apps.account.utils.data_export.DATA_EXPORTS_PER_DAY` exports in the last 24 hours. """ latest = latest_data_export(user) if latest is not None and latest.is_in_progress: logger.info("export %s of %s is in progress", latest.pk, user) return latest, False if not user.email: raise DataExportStartRefusedError(_("Your account has no email address to send the download link to.")) if exports_started_today(user) >= DATA_EXPORTS_PER_DAY: message = _("You can download your data %(count)s times a day. Please try again tomorrow.") % { "count": DATA_EXPORTS_PER_DAY } raise DataExportStartRefusedError(message) export = DataExport.objects.create(user=user) export_id = export.pk transaction.on_commit(lambda: create_data_export.delay(export_id)) logger.info("started export %s for %s", export_id, user) return export, True
[docs] def queue_apply_repository(user_profile: UserProfile, url: str) -> tuple[RepositoryApply, bool]: """ Start a batch apply of a repository, unless one of the user's is in progress, and queue :func:`~smarter.apps.account.tasks.repositories.apply_repository`. The web console's Apply page calls it. The task is queued once the run's row is committed, so that the worker finds it. :param user_profile: The user, as whom the manifests are applied. :param url: The repository's url. :returns: The run, and True if it was started now, or False if one was already in progress. :raises RepositoryApplyRefusedError: If the url isn't a public GitHub repository's, or the user started :data:`~smarter.apps.account.repositories.apply.REPOSITORY_APPLIES_PER_DAY` runs in the last 24 hours. """ normalized = normalize_repository_url(url) latest = RepositoryApply.objects.filter(user_profile=user_profile).order_by("-created_at", "-pk").first() if latest is not None and latest.is_in_progress: logger.info("batch apply %s is in progress.", latest.pk) return latest, False if runs_started_today(user_profile) >= REPOSITORY_APPLIES_PER_DAY: message = _("You can apply %(count)s repositories a day. Please try again tomorrow.") % { "count": REPOSITORY_APPLIES_PER_DAY } raise RepositoryApplyRefusedError(message) run = RepositoryApply.objects.create(user_profile=user_profile, url=normalized) run_id = run.pk transaction.on_commit(lambda: apply_repository.delay(run_id)) logger.info("started batch apply %s of %s.", run_id, normalized) return run, True
__all__ = ["queue_apply_repository", "queue_create_charge", "queue_create_data_export"]