Jobbergate API Reference
jobbergate_api
Main components of the application: routers, config, main, pagination and create super user script.
apps
Resources of the API.
clusters
Module to track agent's health on the clusters.
models
Database models for the cluster health resource.
Bases: CommonMixin
, TimestampMixin
, Base
Cluster status table definition.
routers
Cluster status API endpoints.
async
get_cluster_status(secure_session: SecureSession = Depends(secure_session(Permissions.ADMIN, Permissions.CLUSTERS_READ, commit=False)))
Get the status of the cluster.
schemas
Schema definitions for the cluster app.
Bases: BaseModel
Describes the status of a cluster.
constants
Constants to be shared by all models.
FileType
Bases: str
, Enum
File type enum.
dependencies
Router dependencies shared for multiple resources.
Note
The dependencies can be reused multiple times, since FastAPI caches the results.
CrudServices
Bases: NamedTuple
Provide a container class for the CRUD services.
FileServices
Bases: NamedTuple
Provide a container class for the file services.
SecureService
dataclass
Services
Bases: NamedTuple
Provide a container class for the services.
get_bucket_name
Get the bucket name based on the environment.
The name can be overridden when multi tenancy is enabled by passing a bucket name.
s3_bucket
async
Create a bucket using a context manager.
file_validation
Validation methods for the uploaded files.
SyntaxValidationEquation
module-attribute
Type alias describing the function signature used to validate file syntax.
syntax_validation_dispatch
module-attribute
Dictionary mapping file extensions to the function used to validate their syntax.
check_uploaded_file_syntax
Check the syntax of a given file.
is_valid_jinja2_template
Check if a given jinja2 template is valid by creating a Template object and trying to render it.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
template |
Union[str, bytes]
|
Jinja2 template. |
required |
Returns:
Type | Description |
---|---|
bool
|
Boolean indicating if the template is valid or not. |
is_valid_python_file
Check if a given Python source code is valid by parsing it into an AST node.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
source_code |
Union[str, bytes]
|
Python source code. |
required |
Returns:
Type | Description |
---|---|
bool
|
Boolean indicating if the source code is valid or not. |
is_valid_yaml_file
Check if a given YAML file is valid by parsing it with yaml.safe_load.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
yaml_file |
Union[str, bytes]
|
YAML file. |
required |
Returns:
Type | Description |
---|---|
bool
|
Boolean indicating if the file is valid or not. |
register_syntax_validator
Use this decorator to register file syntax validation functions.
It creates a new entry on validation_dispatch
, mapping the equation to
the file extensions that are provided as arguments.
Raise ValueError if the provided file extensions do not start with a dot.
garbage_collector
Delete unused files from jobbergate's file storage.
delete_files_from_bucket
async
Delete files from the bucket.
garbage_collector
async
Delete unused files from jobbergate's file storage.
get_files_to_delete
async
Get a set of files to delete.
get_set_of_files_from_bucket
async
Get a set of files from the bucket.
job_script_templates
Module for the job script templates.
constants
Describe constants for the job script templates module.
models
Database models for the job_script_templates resource.
Job script template table definition.
Notice all relationships are lazy="raise" to prevent n+1 implicit queries. This means that the relationships must be explicitly eager loaded using helper functions in the class.
Attributes:
Name | Type | Description |
---|---|---|
identifier |
Mapped[Optional[str]]
|
The identifier of the job script template. |
template_vars |
Mapped[dict[str, Any]]
|
The template variables of the job script template. |
See Mixin class definitions for other columns.
routers
Router for the Job Script Template resource.
async
job_script_template_clone(id_or_identifier: str = Path(), clone_request: JobTemplateCloneRequest | None = None, secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_TEMPLATES_CREATE, ensure_email=True)))
Clone a job script template by id or identifier.
async
job_script_template_create(create_request: JobTemplateCreateRequest, secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_TEMPLATES_CREATE, ensure_email=True)))
Create a new job script template.
async
job_script_template_delete(id_or_identifier: str = Path(), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_TEMPLATES_DELETE, ensure_email=True)))
Delete a job script template by id or identifier.
async
job_script_template_delete_file(id_or_identifier: str = Path(), file_name: str = Path(), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_TEMPLATES_DELETE, ensure_email=True)))
Delete a file from a job script template by id or identifier.
async
job_script_template_garbage_collector(background_tasks: BackgroundTasks, secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_TEMPLATES_DELETE)))
Delete all unused files from jobbergate templates on the file storage.
async
job_script_template_get(id_or_identifier: str = Path(), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_TEMPLATES_READ, commit=False)))
Get a job script template by id or identifier.
async
job_script_template_get_file(id_or_identifier: str = Path(), file_name: str = Path(), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_TEMPLATES_READ, commit=False)))
Get a job script template file by id or identifier.
Note
See https://fastapi.tiangolo.com/advanced/custom-response/#streamingresponse
async
job_script_template_get_list(list_params: ListParams = Depends(), include_null_identifier: bool = Query(False), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_TEMPLATES_READ, commit=False)))
Get a list of job script templates.
async
job_script_template_update(update_request: JobTemplateUpdateRequest, id_or_identifier: str = Path(), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_TEMPLATES_UPDATE, ensure_email=True)))
Update a job script template by id or identifier.
async
job_script_template_upload_file(id_or_identifier: str = Path(), file_type: FileType = Path(), filename: str | None = Query(None, max_length=255), upload_file: UploadFile | None = File(None, description='File to upload'), previous_filename: str | None = Query(None, description='Previous name of the file in case a rename is needed', max_length=255), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_TEMPLATES_CREATE, ensure_email=True)))
Upload a file to a job script template by id or identifier.
async
job_script_template_upload_file_by_url(id_or_identifier: str = Path(), file_type: FileType = Path(), filename: str | None = Query(None, max_length=255), file_url: AnyUrl = Query(..., description='URL of the file to upload'), previous_filename: str | None = Query(None, description='Previous name of the file in case a rename is needed', max_length=255), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_TEMPLATES_CREATE, ensure_email=True)))
Upload a file to a job script template by id or identifier using file URL.
async
job_script_upload_file_by_url(id_or_identifier: str = Path(), runtime_config: RunTimeConfig | None = Body(None, description='Runtime configuration is optional when the workflow file already exists'), file_url: AnyUrl = Query(..., description='URL of the file to upload'), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_TEMPLATES_CREATE, ensure_email=True)))
Upload a file to a job script workflow by id or identifier from a URL.
async
job_script_workflow_delete_file(id_or_identifier: str = Path(), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_TEMPLATES_DELETE, ensure_email=True)))
Delete a workflow file from a job script template by id or identifier.
async
job_script_workflow_get_file(id_or_identifier: str = Path(), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_TEMPLATES_READ, commit=False)))
Get a workflow file by id or identifier.
Note
See https://fastapi.tiangolo.com/advanced/custom-response/#streamingresponse
async
job_script_workflow_upload_file(id_or_identifier: str = Path(), runtime_config: RunTimeConfig | None = Body(None, description='Runtime configuration is optional when the workflow file already exists'), upload_file: UploadFile = File(..., description='File to upload'), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_TEMPLATES_CREATE, ensure_email=True)))
Upload a file to a job script workflow by id or identifier.
schemas
Provide schemas for the job script templates component.
Bases: JobTemplateBaseDetailedView
Schema for the request to an entry.
Notice the files default to None, as they are not always requested, to differentiate between an empty list when they are requested, but no file is found.
Bases: BaseModel
Schema for the response to get a template file.
Bases: BaseModel
Schema for the response to get a workflow file.
services
Services for the job_script_templates resource, including module specific business logic.
Bases: FileService
Provide an empty derived class of FileService.
Although it doesn't do anything, it fixes errors with mypy: error: Value of type variable "FileModel" of "FileService" cannot be "JobScriptTemplateFile" error: Value of type variable "FileModel" of "FileService" cannot be "WorkflowFile"
Bases: CrudService
Provide a CrudService that overloads the list query builder and locator logic.
build_list_query(sort_ascending: bool = True, search: str | None = None, sort_field: str | None = None, include_archived: bool = True, include_files: bool = False, include_parent: bool = False, include_null_identifier: bool = True, **additional_filters) -> Select
List all job_script_templates.
Locate an instance using the id or identifier field.
async
Update a row by locator with supplied data.
Validate that the identifier is not an empty string nor composed only by digits.
Raise a ServiceError with status code 422 if the validation fails.
Many of the job-script-template endpoints use the id or identifier interchangeably as a path parameter. With that, we need to ensure that the identifier is not a number, as that would be identified as id.
tools
Provide a method for coercing id_or_identifier to a string or int.
Determine whether the id_or_identifier should be a string or an integer.
This is necessary because FastAPI no longer automatically converts path parameters to integers automatically if they may also be string values.
job_scripts
Provide module for job_scripts.
models
Database model for the JobScript resource.
Job script table definition.
Notice all relationships are lazy="raise" to prevent n+1 implicit queries. This means that the relationships must be explicitly eager loaded using helper functions in the class.
Attributes:
Name | Type | Description |
---|---|---|
parent_template_id |
Mapped[int]
|
The id of the parent template. |
See Mixin class definitions for other columns.
classmethod
Include custom options on a query to eager load files.
classmethod
Include custom options on a query to eager load parent data.
routers
Router for the Job Script Template resource.
job_script_auto_clean_unused_entries(background_tasks: BackgroundTasks, secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_SCRIPTS_DELETE)))
Automatically clean unused job scripts depending on a threshold.
async
job_script_clone(id: int = Path(), clone_request: JobScriptCloneRequest | None = None, secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_SCRIPTS_CREATE, ensure_email=True)))
Clone a job script by its id.
async
job_script_create(create_request: JobScriptCreateRequest, secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_SCRIPTS_CREATE)))
Create a stand alone job script.
async
job_script_create_from_template(create_request: JobScriptCreateRequest, render_request: RenderFromTemplateRequest, id_or_identifier: str = Path(...), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_SCRIPTS_CREATE, ensure_email=True)))
Create a new job script from a job script template.
async
job_script_delete(id: int = Path(...), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_SCRIPTS_DELETE, ensure_email=True)))
Delete a job script template by id or identifier.
async
job_script_delete_file(id: int = Path(...), file_name: str = Path(...), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_SCRIPTS_DELETE, ensure_email=True)))
Delete a file from a job script template by id or identifier.
job_script_garbage_collector(background_tasks: BackgroundTasks, secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_SCRIPTS_DELETE)))
Delete all unused files from job scripts on the file storage.
async
job_script_get(id: int = Path(), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_SCRIPTS_READ, commit=False)))
Get a job script by id.
async
job_script_get_file(id: int = Path(...), file_name: str = Path(...), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_SCRIPTS_READ, commit=False)))
Get a job script file.
Note
See https://fastapi.tiangolo.com/advanced/custom-response/#streamingresponse
async
job_script_get_list(list_params: ListParams = Depends(), from_job_script_template_id: int | None = Query(None, description='Filter job-scripts by the job-script-template-id they were created from.'), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_SCRIPTS_READ, commit=False)))
Get a list of job scripts.
async
job_script_update(update_params: JobScriptUpdateRequest, id: int = Path(), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_SCRIPTS_UPDATE, ensure_email=True)))
Update a job script template by id or identifier.
async
job_script_upload_file(id: int = Path(...), file_type: FileType = Path(...), filename: str | None = Query(None, max_length=255), upload_file: UploadFile | None = File(None, description='File to upload'), previous_filename: str | None = Query(None, description='Previous name of the file in case a rename is needed', max_length=255), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_SCRIPTS_CREATE, ensure_email=True)))
Upload a file to a job script.
async
job_script_upload_file_by_url(id: int = Path(...), file_type: FileType = Path(...), filename: str | None = Query(None, max_length=255), file_url: AnyUrl = Query(..., description='URL of the file to upload'), previous_filename: str | None = Query(None, description='Previous name of the file in case a rename is needed', max_length=255), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_SCRIPTS_CREATE, ensure_email=True)))
Upload a file to a job script from a URL.
schemas
JobScript resource schema.
Bases: TableResource
Base model to match database for the JobScript resource.
Omits parent relationship.
Bases: BaseModel
Request model for cloning JobScript instances.
Bases: BaseModel
Request model for creating JobScript instances.
Bases: BaseModel
Model for the job_script_files field of the JobScript resource.
Bases: BaseModel
Request model for updating JobScript instances.
Bases: BaseModel
Request model for creating a JobScript entry from a template.
services
Services for the job_scripts resource, including module specific business logic.
Bases: NamedTuple
Named tuple for the response of auto_clean_unused_job_scripts.
Bases: CrudService
Provide an empty derived class of CrudService.
Although it doesn't do anything, it fixes an error with mypy: error: Value of type variable "CrudModel" of "CrudService" cannot be "JobScript"
async
Automatically clean unused job scripts depending on a threshold.
Based on the last time each job script was updated or used to create a job submission, this will archived job scripts that were unarchived and delete jos script that were archived.
async
Extend delete a row by locator.
Orphaned job-scripts are now allowed on Jobbergate. However, the agent relies on them to submit jobs after requesting GET /agent/pending. This creates a race condition and errors occur when a job-script is deleted before the agent handles its submissions.
To avoid this, they are marked as reject in this scenario.
Bases: FileService
Provide an empty derived class of FileService.
Although it doesn't do anything, it fixes an error with mypy: error: Value of type variable "FileModel" of "FileService" cannot be "JobScriptFile"
tools
Provide a convenience class for managing job-script files.
job_submissions
Provide module for job_submissions.
constants
Describe constants for the job_submissions module.
Bases: AutoNameEnum
Defines the set of possible statuses for a Job Submission.
Bases: AutoNameEnum
Defines the set of possible states for a job submitted to Slurm.
dataclass
Defines the details for a given SlurmJobState including abbreviation and description.
models
Database model for the JobSubmission resource.
Job submission table definition.
Notice all relationships are lazy="raise" to prevent n+1 implicit queries. This means that the relationships must be explicitly eager loaded using helper functions in the class.
Attributes:
Name | Type | Description |
---|---|---|
job_script_id |
Mapped[int]
|
Id number of the job scrip this submissions is based on. |
execution_directory |
Mapped[str]
|
The directory where the job is executed. |
slurm_job_id |
Mapped[int]
|
The id of the job in the slurm queue. |
slurm_job_state |
Mapped[SlurmJobState]
|
The Slurm Job state as reported by the agent |
slurm_job_info |
Mapped[str]
|
Detailed information about the Slurm Job as reported by the agent |
client_id |
Mapped[str]
|
The id of the custer this submission runs on. |
status |
Mapped[JobSubmissionStatus]
|
The status of the job submission. |
report_message |
Mapped[str]
|
The message returned by the job. |
sbatch_arguments |
Mapped[list[str]]
|
The arguments used to submit the job to the slurm queue. |
See Mixin class definitions for other columns
classmethod
Include custom options on a query to eager load files.
classmethod
Include custom options on a query to eager load parent data.
routers
Router for the JobSubmission resource.
async
job_submission_agent_update(update_params: JobSubmissionAgentUpdateRequest, id: int = Path(), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_SUBMISSIONS_UPDATE, ensure_client_id=True)))
Update a job_submission with slurm_job_state and slurm_job_info.
Note that if the new slurm_job_state is a termination state, the job submission status will be updated.
async
job_submission_clone(id: int = Path(...), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_SUBMISSIONS_CREATE, ensure_email=True)))
Clone a job_submission given its id.
async
job_submission_create(create_request: JobSubmissionCreateRequest, secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_SUBMISSIONS_CREATE, ensure_email=True)))
Create a new job submission.
Make a post request to this endpoint with the required values to create a new job submission.
async
job_submission_delete(id: int = Path(..., description='id of the job submission to delete'), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_SUBMISSIONS_DELETE, ensure_email=True)))
Delete job_submission given its id.
async
job_submission_get(id: int = Path(...), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_SUBMISSIONS_READ, commit=False)))
Return the job_submission given its id.
async
job_submission_get_list(list_params: ListParams = Depends(), slurm_job_ids: str | None = Query(None, description='Comma-separated list of slurm-job-ids to match active job_submissions'), submit_status: JobSubmissionStatus | None = Query(None, description='Limit results to those with matching status'), from_job_script_id: int | None = Query(None, description='Filter job-submissions by the job-script-id they were created from.'), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_SUBMISSIONS_READ, commit=False)))
List job_submissions for the authenticated user.
async
job_submission_update(update_params: JobSubmissionUpdateRequest, id: int = Path(), secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_SUBMISSIONS_UPDATE, ensure_email=True)))
Update a job_submission given its id.
async
job_submissions_agent_active(secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_SUBMISSIONS_READ, commit=False, ensure_client_id=True)))
Get a list of active job submissions for the cluster-agent.
async
job_submissions_agent_pending(secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_SUBMISSIONS_READ, commit=False, ensure_client_id=True)))
Get a list of pending job submissions for the cluster-agent.
async
job_submissions_agent_rejected(rejected_request: JobSubmissionAgentRejectedRequest, secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_SUBMISSIONS_UPDATE, ensure_client_id=True)))
Update a job_submission to indicate that it was rejected by Slurm.
async
job_submissions_agent_submitted(submitted_request: JobSubmissionAgentSubmittedRequest, secure_services: SecureService = Depends(secure_services(Permissions.ADMIN, Permissions.JOB_SUBMISSIONS_UPDATE, ensure_client_id=True)))
Update a job_submission to indicate that it was submitted to Slurm.
schemas
JobSubmission resource schema.
Bases: BaseModel
Specialized model for the cluster-agent to pull an active job_submission.
Bases: BaseModel
Request model for marking JobSubmission instances as REJECTED.
Bases: BaseModel
Request model for marking JobSubmission instances as SUBMITTED.
Bases: BaseModel
Request model for updating JobSubmission instances.
Bases: TableResource
Base model to match the database for the JobSubmission resource.
Omits parent relationship.
Bases: JobSubmissionBaseView
Complete model to match the database for the JobSubmission resource in a detailed view.
Bases: JobSubmissionBaseView
Complete model to match the database for the JobSubmission resource in a list view.
Bases: BaseModel
Specialized model for the cluster-agent to pull pending job_submissions.
Model also includes data from its job_script and application sources.
services
Services for the job_submissions resource, including module specific business logic.
Bases: CrudService
Provide a CrudService that overloads the list query builder.
build_list_query(sort_ascending: bool = True, search: str | None = None, sort_field: str | None = None, include_archived: bool = True, include_files: bool = False, include_parent: bool = False, filter_slurm_job_ids: list[int] | None = None, **additional_filters) -> Select
List all job_script_templates.
models
Functionalities to be shared by all models.
ArchiveMixin
Add is_archived column to a table.
Attributes:
Name | Type | Description |
---|---|---|
is_archived |
Mapped[bool]
|
Specify is a row is considered archived, hidden it by default when listing rows. |
Base
Bases: DeclarativeBase
Base class for all models.
References
https://docs.sqlalchemy.org/en/20/orm/declarative_mixins.html
CommonMixin
CrudMixin
Bases: CommonMixin
, IdMixin
, TimestampMixin
, OwnerMixin
, NameMixin
, ArchiveMixin
Add needed columns and declared attributes for all models that support a CrudService.
classmethod
Include custom options on a query to eager load files.
This should be overridden by derived classes.
classmethod
Include custom options on a query to eager load parent data.
This should be overridden by derived classes.
classmethod
Describe the fields that may be used in search queries.
FileMixin
Bases: CommonMixin
, TimestampMixin
Add needed columns and declared attributes for all models that support a FileService.
Attributes:
Name | Type | Description |
---|---|---|
parent_id |
Mapped[int]
|
The id of the parent row in another table. Note: Derived classes should override this attribute to make it a foreign key as well. |
description |
Mapped[int]
|
The description of the job script template. |
IdMixin
NameMixin
Add name and description columns to a table.
Attributes:
Name | Type | Description |
---|---|---|
name |
Mapped[str]
|
The name of the job script template. |
description |
Mapped[str | None]
|
The description of the job script template. |
OwnerMixin
Add an owner email columns to a table.
Attributes:
Name | Type | Description |
---|---|---|
owner_email |
Mapped[str]
|
The email of the owner of the job script template. |
TimestampMixin
Add timestamp columns to a table.
Attributes:
Name | Type | Description |
---|---|---|
created_at |
Mapped[DateTime]
|
The date and time when the job script template was created. |
updated_at |
Mapped[DateTime]
|
The date and time when the job script template was updated. |
permissions
Provide a module that describes permissions in the API.
schemas
Define app-wide, reusable pydantic schemas.
ListParams
Bases: BaseModel
Describe the shared parameters for a list request.
PydanticDateTime
Bases: DateTime
A pendulum.DateTime
object. At runtime, this type decomposes into pendulum.DateTime automatically.
This type exists because Pydantic throws a fit on unknown types.
This code is borrowed and enhanced from the pydantic-extra-types
module but provides conversion from
standard datetimes as well.
classmethod
__get_pydantic_core_schema__(source: Type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema
Return a Pydantic CoreSchema with the Datetime validation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
source |
Type[Any]
|
The source type to be converted. |
required |
handler |
GetCoreSchemaHandler
|
The handler to get the CoreSchema. |
required |
Returns:
Type | Description |
---|---|
CoreSchema
|
A Pydantic CoreSchema with the Datetime validation. |
TableResource
Bases: BaseModel
Describes a base for table models that include basic, common info.
services
Provide a generic services for CRUD and file operations in routers.
BucketBoundService
Provide base class for services that bind to an s3 bucket.
This class holds a reference to the bucket and provides methods to bind and unbind the bucket. It also keeps track of all instances of the service so that they can be iterated over.
property
Fetch the currently bound bucket.
Raise an exception if the service is not bound to a bucket.
Provide a context within which the service is bound to a bucket.
CrudModelProto
Bases: Protocol
Provide a protocol for models that can be operated on by the CrudService.
This protocol enables type hints for editors and type checking with mypy.
These services would best be served by an intersection type so that the model_type is actually specified to inherit from both the mixins and the Base. This would allow static type checkers to recognize that all of the columns in a mixin are available and that the class can be instantiated in the create method. However, intersection types are not supported yet. For more information, see this discussion: https://github.com/python/typing/issues/213
Declare that the protocol has a method to dynamically produce the table name.
classmethod
Declare that the protocol has a method to include files in a query.
classmethod
Declare that the protocol has a method to include details about the parent entry in a query.
classmethod
Declare that the protocol has searchable fields.
CrudService
Bases: DatabaseBoundService
, Generic[CrudModel]
Provide a service that can perform various crud operations using a supplied ORM model type.
build_list_query(sort_ascending: bool = True, search: str | None = None, sort_field: str | None = None, include_archived: bool = True, include_files: bool = False, include_parent: bool = False, **additional_filters) -> Select
Build the query to list matching rows.
Decomposed into a separate function so that deriving subclasses can add additional logic into the query.
async
Clone an instance and update it with the supplied data.
async
Delete a row by locator.
In almost all cases, the locator will just be an id
value.
Ensure that a model instance has the specified values on key attributes.
Raises HTTPException if the instance does not have the specified values.
async
get(locator: Any, include_files: bool = False, include_parent: bool = False, ensure_attributes: dict[str, Any] | None = None) -> CrudModel
Get a row by locator.
In almost all cases, the locator will just be an id
value.
Key value pairs can be provided as ensure_attributes
to assert that the
key fields have the specified values. This is useful to assert email ownership
of a row before modifying it, besides any other attribute.
async
List all crud rows matching specified filters.
For details on the supported filters, see the build_list_query()
method.
Provide the where clause expression to locate a row by locator.
This method allows derived classes to locate by alternative identifiers, though
locator is an id
value in almost all cases.
compound primary keys.
async
List all crud rows matching specified filters with pagination.
For details on the supported filters, see the build_list_query()
method.
DatabaseBoundService
Provide base class for services that bind to a database session.
This class holds a reference to the session and provides methods to bind and unbind the session. It also keeps track of all instances of the service so that they can be iterated over.
property
Fetch the currently bound session.
Raise an exception if the service is not bound to a session.
Provide a context within which the service is bound to a session.
FileModelProto
Bases: Protocol
Provide a protocol for models that can be operated on by the FileService.
This protocol enables type hints for editors and type checking with mypy.
These services would best be served by an intersection type so that the model_type is actually specified to inherit from both the mixins and the Base. This would allow static type checkers to recognize that all of the columns in a mixin are available and that the class can be instantiated in the create method. However, intersection types are not supported yet. For more information, see this discussion: https://github.com/python/typing/issues/213
FileService
Bases: DatabaseBoundService
, BucketBoundService
, Generic[FileModel]
Provide a service that can perform various file management operations using a supplied ORM model type.
async
Add a file instance to the database.
async
Clone a file instance and assign it to a new parent-id.
async
Copy the content of a file from one instance to another.
async
Delete a file from s3 and from the corresponding table.
async
Find matching instances by parent_id.
async
Get a single instance by its parent id and filename (primary keys).
Requires that one and only one result is found.
async
Get the full contents for a file entry.
async
Render the file using Jinja2.
The parameters are passed to the template as the context, and two of them are supported:
* Directly as the context, for instance, if the template contains {{ foo }}
.
* As a data
key for backward compatibility, for instance, if the
template contains {{ data.foo }}
.
async
Stream the content of a file using a boto3 StreamingBody.
The StreamingBody is an async generator that can be used for a StreamingResponse in a FastAPI app.
async
Upload the content of a file to s3.
async
upsert(parent_id: int, filename: str, upload_content: str | bytes | AnyUrl | UploadFile | None, previous_filename: str | None = None, **upsert_kwargs) -> FileModel
Upsert a file instance.
This method will either create a new file instance or update an existing one.
If a 'previous_filename' is provided, it is replaced by the new one, being deleted in the process. In this case, the 'upload_content' is optional, as the content can be copied from the previous file.
ServiceError
Bases: HTTPException
Make HTTPException more friendly by changing the default behavior so that the first arg is a message.
Also needed to play nice with py-buzz methods.
config
Provide configuration settings for the app.
Pull settings from environment variables or a .env file if available.
LogLevelEnum
Bases: str
, Enum
Provide an enumeration class describing the available log levels.
Settings
Bases: BaseSettings
Provide a pydantic BaseSettings
model for the application settings.
email_notification
Email notification system for Jobbergate.
EmailManager
dataclass
EmailNotificationError
Bases: Buzz
Custom error to be raised for problems at the email notification system.
logging
Provide functions to configure logging.
InterceptHandler
main
Main file to startup the fastapi server.
lifespan
async
Provide a lifespan context for the app.
Will set up logging and cleanup database engines when the app is shut down.
This is the preferred method of handling lifespan events in FastAPI. For mor details, see: https://fastapi.tiangolo.com/advanced/events/
meta_mapper
Provides a metadata-mapper for re-using descriptions and examples across many pydantic models.
MetaField
dataclass
Provides a dataclass that describes the metadata that will be mapped for an individual field.
MetaMapper
Maps re-usable metadata for fields. Should be used with the schema_extra
property of a Model's Config.
Example::
foo_meta = MetaMapper(
id=MetaField(
description="The unique identifier of this Foo",
example=13,
),
name=MetaField(
description="The name of this Foo",
example="Bar",
),
is_active=MetaField(
description="Indicates if this Foo is active",
example=True,
),
created_at=MetaField(
description="The timestamp indicating when this Foo was created",
example="2023-08-18T13:55:37.172285",
),
)
class CreateFooRequest(BaseModel):
name: str
is_active: Optional[bool]
class Config:
schema_extra = foo_meta
class UpdateFooRequest(BaseModel):
name: Optional[str] = None
is_active: Optional[bool] = None
class Config:
schema_extra = foo_meta
class FooResponse(BaseModel):
id: int
name: str
is_active: bool
created_at: DateTime
class Config:
schema_extra = foo_meta
Notice in this example that the fields may be required in some models and optional in others. Further, not all the fields are present in all the models. The MetaMapper allows the models to share field metadata and yet define the fields independently.
__call__
Map the MetaFields onto the metadata properties of a schema.
Should be used in a pydantic Model's Config class.
rabbitmq_notification
RabbitMQ notification system for Jobbergate.
publish_status_change
async
Publish a status change for a JobSubmission to the RabbitMQ exchange used for notifications.
safe_types
Provide "safe" type annotatons to avoid issues with mypy and Fast api.
Regarding the JobScript and JobSubmission type
These are needed for the relationships in the models. This avoids issues with circular imports at runtime.
Regarding the Bucket type
This is necessary because the Bucket type isn't importable from the normal boto3 modules. Instead, it must be imported from the mypy typing plugin for boto3.
The "type" must be bound to Any when not type checking because FastAPI does type inspection for its dependency injection system. Thus, there must be a type associated with Bucket even when not type checking.
security
Instantiates armasec resources for auth on api endpoints using project settings.
Also provides a factory function for TokenSecurity to reduce boilerplate.
IdentityPayload
Bases: TokenPayload
Provide an extension of TokenPayload that includes the user's identity.
get_domain_configs
Return a list of DomainConfig objects based on the input variables for the Settings class.
lockdown_with_identity
lockdown_with_identity(*scopes: str, permission_mode: PermissionMode = PermissionMode.SOME, ensure_email: bool = False, ensure_organization: bool = False, ensure_client_id: bool = False)
Provide a wrapper to be used with dependency injection to extract identity on a secured route.
storage
Provide functions to interact with persistent data storage.
EngineFactory
Provide a factory class that creates engines and keeps track of them in an engine mapping.
This is used for multi-tenancy and database URL creation at request time.
SecureSession
dataclass
Provide a container class for an IdentityPayload and AsyncSesson for the current request.
build_db_url
build_db_url(override_db_name: str | None = None, force_test: bool = False, asynchronous: bool = True) -> str
Build a database url based on settings.
If force_test
is set, build from the test database settings.
If asynchronous
is set, use asyncpg.
If override_db_name
replace the database name in the settings with the supplied value.
handle_fk_error
Unpack metadata from a ForeignKeyViolationError and return a 409 response.
render_sql
Render a sqlalchemy query into a string for debugging.
search_clause
Create search clause across searchable fields with search terms.
Regarding the False first argument to or_(): The or_() function must have one fixed positional argument. See: https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.or_
secure_session
secure_session(*scopes: str, permission_mode: PermissionMode = PermissionMode.SOME, commit: bool = True, ensure_email: bool = False, ensure_organization: bool = False, ensure_client_id: bool = False)
Provide an injectable for FastAPI that checks permissions and returns a database session for this request.
This should be used for all secured routes that need access to the database. It will commit the transaction upon completion of the request. If an exception occurs, it will rollback the transaction. If multi-tenancy is enabled, it will retrieve a database session for the database associated with the client_id found in the requesting user's auth token.
If testing mode is enabled, it will flush the session instead of committing changes to the database.
Note that the session should NEVER be explicitly committed anywhere else in the source code.
version
Provide the version of the package.
get_version
Get the version from the metadata if available, otherwise from pyproject.toml.
Returns "unknown" if both methods fail.
get_version_from_metadata
Get the version from the metadata.
This is the preferred method of getting the version, but only works if the package is properly installed in a Python environment.