Complete lab 5 asynchronous image processing

This commit is contained in:
sinveria
2026-11-10 18:51:02 +03:00
parent 276dbdad8a
commit 115223f920
69 changed files with 7706 additions and 31 deletions
+1
View File
@@ -0,0 +1 @@
Generic single-database configuration.
+60
View File
@@ -0,0 +1,60 @@
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
from app.core.config import settings
from app.db.base import Base
from app.db import models
config = context.config
if config.config_file_name is not None:
fileConfig(config.config_file_name)
config.set_main_option(
"sqlalchemy.url",
settings.database_url.replace("%", "%%"),
)
target_metadata = Base.metadata
def run_migrations_offline() -> None:
url = settings.database_url
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
compare_type=True,
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
compare_type=True,
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
+26
View File
@@ -0,0 +1,26 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}
@@ -0,0 +1,79 @@
"""create initial database schema
Revision ID: 21ad89656327
Revises:
Create Date: 2026-11-04 17:31:39.336368
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '21ad89656327'
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('chats',
sa.Column('id', sa.UUID(), nullable=False),
sa.Column('title', sa.String(length=100), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
sa.PrimaryKeyConstraint('id')
)
op.create_table('users',
sa.Column('id', sa.UUID(), nullable=False),
sa.Column('username', sa.String(length=32), nullable=False),
sa.Column('display_name', sa.String(length=100), nullable=False),
sa.Column('password_hash', sa.String(length=255), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True)
op.create_table('chat_members',
sa.Column('chat_id', sa.UUID(), nullable=False),
sa.Column('user_id', sa.UUID(), nullable=False),
sa.ForeignKeyConstraint(['chat_id'], ['chats.id'], ondelete='CASCADE'),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('chat_id', 'user_id')
)
op.create_table('messages',
sa.Column('id', sa.UUID(), nullable=False),
sa.Column('chat_id', sa.UUID(), nullable=False),
sa.Column('sender_id', sa.UUID(), nullable=False),
sa.Column('text', sa.Text(), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
sa.ForeignKeyConstraint(['chat_id'], ['chats.id'], ondelete='CASCADE'),
sa.ForeignKeyConstraint(['sender_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index('ix_messages_chat_created_id', 'messages', ['chat_id', 'created_at', 'id'], unique=False)
op.create_table('sessions',
sa.Column('id', sa.UUID(), nullable=False),
sa.Column('token_hash', sa.String(length=64), nullable=False),
sa.Column('user_id', sa.UUID(), nullable=False),
sa.Column('expires_at', sa.DateTime(timezone=True), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_sessions_token_hash'), 'sessions', ['token_hash'], unique=True)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_sessions_token_hash'), table_name='sessions')
op.drop_table('sessions')
op.drop_index('ix_messages_chat_created_id', table_name='messages')
op.drop_table('messages')
op.drop_table('chat_members')
op.drop_index(op.f('ix_users_username'), table_name='users')
op.drop_table('users')
op.drop_table('chats')
# ### end Alembic commands ###
@@ -0,0 +1,37 @@
"""add attachment metadata"""
from alembic import op
import sqlalchemy as sa
from typing import Sequence, Union
revision: str = "4d9a1f2c7b10"
down_revision: Union[str, None] = "8c3d9f4a21b7"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column("messages", sa.Column("attachment_ids", sa.JSON(), nullable=False, server_default="[]"))
op.create_table(
"attachments",
sa.Column("id", sa.UUID(), nullable=False),
sa.Column("chat_id", sa.UUID(), nullable=False),
sa.Column("owner_id", sa.UUID(), nullable=False),
sa.Column("filename", sa.String(255), nullable=False),
sa.Column("content_type", sa.String(32), nullable=False),
sa.Column("size_bytes", sa.Integer(), nullable=False),
sa.Column("sha256", sa.String(64), nullable=False),
sa.Column("object_key", sa.String(512), nullable=False),
sa.Column("status", sa.String(16), nullable=False),
sa.Column("error_code", sa.String(64), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.ForeignKeyConstraint(["chat_id"], ["chats.id"], ondelete="CASCADE"),
sa.ForeignKeyConstraint(["owner_id"], ["users.id"], ondelete="CASCADE"),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("object_key"),
)
op.create_index("ix_attachments_chat_id", "attachments", ["chat_id"])
def downgrade() -> None:
op.drop_index("ix_attachments_chat_id", table_name="attachments")
op.drop_table("attachments")
op.drop_column("messages", "attachment_ids")
@@ -0,0 +1,39 @@
"""add shared PostgreSQL idempotency records
Revision ID: 8c3d9f4a21b7
Revises: 21ad89656327
Create Date: 2026-11-05
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
revision: str = "8c3d9f4a21b7"
down_revision: Union[str, None] = "21ad89656327"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.create_table(
"idempotency_records",
sa.Column("id", sa.UUID(), nullable=False),
sa.Column("user_id", sa.UUID(), nullable=False),
sa.Column("method", sa.String(length=10), nullable=False),
sa.Column("path", sa.String(length=255), nullable=False),
sa.Column("idempotency_key", sa.String(length=128), nullable=False),
sa.Column("request_hash", sa.String(length=64), nullable=False),
sa.Column("message_id", sa.UUID(), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("expires_at", sa.DateTime(timezone=True), nullable=False),
sa.ForeignKeyConstraint(["message_id"], ["messages.id"], ondelete="CASCADE"),
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("user_id", "method", "path", "idempotency_key", name="uq_idempotency_scope_key"),
)
op.create_index("ix_idempotency_records_expires_at", "idempotency_records", ["expires_at"], unique=False)
def downgrade() -> None:
op.drop_index("ix_idempotency_records_expires_at", table_name="idempotency_records")
op.drop_table("idempotency_records")
@@ -0,0 +1,78 @@
"""add attachment uploads
Revision ID: a7c2e91d5f40
Revises: 4d9a1f2c7b10
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
revision: str = "a7c2e91d5f40"
down_revision: Union[str, None] = "4d9a1f2c7b10"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"attachment_uploads",
sa.Column("id", sa.UUID(), nullable=False),
sa.Column("chat_id", sa.UUID(), nullable=False),
sa.Column("owner_id", sa.UUID(), nullable=False),
sa.Column("filename", sa.String(length=255), nullable=False),
sa.Column("content_type", sa.String(length=32), nullable=False),
sa.Column("expected_size_bytes", sa.Integer(), nullable=False),
sa.Column("expected_sha256", sa.String(length=64), nullable=False),
sa.Column("object_key", sa.String(length=512), nullable=False),
sa.Column("status", sa.String(length=16), nullable=False),
sa.Column("expires_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("completed_at", sa.DateTime(timezone=True), nullable=True),
sa.ForeignKeyConstraint(
["chat_id"],
["chats.id"],
ondelete="CASCADE",
),
sa.ForeignKeyConstraint(
["owner_id"],
["users.id"],
ondelete="CASCADE",
),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("object_key"),
)
op.create_index(
"ix_attachment_uploads_chat_id",
"attachment_uploads",
["chat_id"],
)
op.create_index(
"ix_attachment_uploads_owner_id",
"attachment_uploads",
["owner_id"],
)
op.create_index(
"ix_attachment_uploads_expires_at",
"attachment_uploads",
["expires_at"],
)
def downgrade() -> None:
op.drop_index(
"ix_attachment_uploads_expires_at",
table_name="attachment_uploads",
)
op.drop_index(
"ix_attachment_uploads_owner_id",
table_name="attachment_uploads",
)
op.drop_index(
"ix_attachment_uploads_chat_id",
table_name="attachment_uploads",
)
op.drop_table("attachment_uploads")
@@ -0,0 +1,210 @@
"""add durable image processing jobs"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
revision: str = "a9d670bf1c16"
down_revision: Union[str, None] = "a7c2e91d5f40"
branch_labels = None
depends_on = None
def upgrade() -> None:
# Дополнительные поля для хранения исходника и версии конвейера.
op.add_column(
"attachments",
sa.Column("staging_key", sa.String(length=512), nullable=True),
)
op.create_unique_constraint(
"uq_attachments_staging_key",
"attachments",
["staging_key"],
)
op.add_column(
"attachments",
sa.Column(
"pipeline_version",
sa.Integer(),
nullable=False,
server_default="1",
),
)
# Задания на асинхронную обработку.
op.create_table(
"processing_jobs",
sa.Column("id", sa.UUID(), nullable=False),
sa.Column("attachment_id", sa.UUID(), nullable=False),
sa.Column(
"pipeline_version",
sa.Integer(),
nullable=False,
server_default="1",
),
sa.Column(
"attempt",
sa.Integer(),
nullable=False,
server_default="1",
),
sa.Column(
"status",
sa.String(length=16),
nullable=False,
server_default="queued",
),
sa.Column(
"available_at",
sa.DateTime(timezone=True),
nullable=False,
),
sa.Column("lease_until", sa.DateTime(timezone=True), nullable=True),
sa.Column("worker_id", sa.String(length=128), nullable=True),
sa.Column(
"last_error_code",
sa.String(length=64),
nullable=True,
),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
nullable=False,
),
sa.Column(
"updated_at",
sa.DateTime(timezone=True),
nullable=False,
),
sa.ForeignKeyConstraint(
["attachment_id"],
["attachments.id"],
ondelete="CASCADE",
),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint(
"attachment_id",
"pipeline_version",
name="uq_processing_job_attachment_pipeline",
),
)
op.create_index(
"ix_processing_jobs_status_available",
"processing_jobs",
["status", "available_at"],
)
op.create_index(
"ix_processing_jobs_lease_until",
"processing_jobs",
["lease_until"],
)
# Созданные варианты изображений.
op.create_table(
"attachment_variants",
sa.Column("id", sa.UUID(), nullable=False),
sa.Column("attachment_id", sa.UUID(), nullable=False),
sa.Column("variant", sa.String(length=32), nullable=False),
sa.Column("object_key", sa.String(length=512), nullable=False),
sa.Column("content_type", sa.String(length=32), nullable=False),
sa.Column("width", sa.Integer(), nullable=False),
sa.Column("height", sa.Integer(), nullable=False),
sa.Column("size_bytes", sa.Integer(), nullable=False),
sa.Column("sha256", sa.String(length=64), nullable=False),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
nullable=False,
),
sa.ForeignKeyConstraint(
["attachment_id"],
["attachments.id"],
ondelete="CASCADE",
),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("object_key"),
sa.UniqueConstraint(
"attachment_id",
"variant",
name="uq_attachment_variant",
),
)
op.create_index(
"ix_attachment_variants_attachment_id",
"attachment_variants",
["attachment_id"],
)
# Transactional outbox: события публикуются в брокер
# отдельным процессом после фиксации транзакции.
op.create_table(
"outbox_events",
sa.Column("id", sa.UUID(), nullable=False),
sa.Column("event_type", sa.String(length=128), nullable=False),
sa.Column("aggregate_id", sa.UUID(), nullable=False),
sa.Column("payload", sa.JSON(), nullable=False),
sa.Column(
"status",
sa.String(length=16),
nullable=False,
server_default="pending",
),
sa.Column(
"attempts",
sa.Integer(),
nullable=False,
server_default="0",
),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
nullable=False,
),
sa.Column(
"published_at",
sa.DateTime(timezone=True),
nullable=True,
),
sa.Column("last_error", sa.String(length=256), nullable=True),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(
"ix_outbox_events_status_created",
"outbox_events",
["status", "created_at"],
)
def downgrade() -> None:
op.drop_index(
"ix_outbox_events_status_created",
table_name="outbox_events",
)
op.drop_table("outbox_events")
op.drop_index(
"ix_attachment_variants_attachment_id",
table_name="attachment_variants",
)
op.drop_table("attachment_variants")
op.drop_index(
"ix_processing_jobs_lease_until",
table_name="processing_jobs",
)
op.drop_index(
"ix_processing_jobs_status_available",
table_name="processing_jobs",
)
op.drop_table("processing_jobs")
op.drop_column("attachments", "pipeline_version")
op.drop_constraint(
"uq_attachments_staging_key",
"attachments",
type_="unique",
)
op.drop_column("attachments", "staging_key")