lab4: S3, MinIO, reconciler, трек 2, README

This commit is contained in:
2026-11-12 20:14:39 +03:00
parent ec540a1a72
commit d88f77cccc
104 changed files with 204719 additions and 47 deletions
+1
View File
@@ -0,0 +1 @@
Generic single-database configuration.
+91
View File
@@ -0,0 +1,91 @@
from app.models.base import Base
from app.models.user import User
from app.models.chat import Chat, ChatMember
from app.models.message import Message
from app.config import DATABASE_URL
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
from app.models.attachment import Attachment
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
config.set_main_option("sqlalchemy.url", DATABASE_URL.replace("+asyncpg", "+psycopg2"))
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
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
)
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,30 @@
"""create tables
Revision ID: 08fe661df060
Revises: bc35c1b6b748
Create Date: 2026-10-31 11:52:26.342048
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '08fe661df060'
down_revision: Union[str, None] = 'bc35c1b6b748'
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! ###
pass
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
@@ -0,0 +1,31 @@
"""add timestamps to attachments
Revision ID: 8203fbed8a46
Revises: b0f31212df2c
Create Date: 2026-11-11 15:59:23.045039
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '8203fbed8a46'
down_revision: Union[str, None] = 'b0f31212df2c'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# Добавляем колонки created_at и updated_at
op.add_column('attachments', sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False))
op.add_column('attachments', sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False))
# УДАЛЕНО: op.alter_column('attachments', 'user_id', ...) - чтобы не упасть на старых записях
def downgrade() -> None:
op.drop_column('attachments', 'updated_at')
op.drop_column('attachments', 'created_at')
# УДАЛЕНО: op.alter_column('attachments', 'user_id', nullable=True)
@@ -0,0 +1,35 @@
"""add owner and sha256 to attachments
Revision ID: b0f31212df2c
Revises: d78a7aaedac6
Create Date: 2026-11-11 15:39:07.391800
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'b0f31212df2c'
down_revision: Union[str, None] = 'd78a7aaedac6'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# 1. Добавляем user_id с nullable=True, чтобы не упасть на старых данных
op.add_column('attachments', sa.Column('user_id', sa.UUID(), nullable=True))
# 2. Добавляем sha256
op.add_column('attachments', sa.Column('sha256', sa.String(), nullable=True))
# 3. Создаем внешний ключ
op.create_foreign_key(None, 'attachments', 'users', ['user_id'], ['id'], ondelete='CASCADE')
def downgrade() -> None:
op.drop_constraint(None, 'attachments', type_='foreignkey')
op.drop_column('attachments', 'sha256')
op.drop_column('attachments', 'user_id')
@@ -0,0 +1,67 @@
"""create tables
Revision ID: b24373e3b620
Revises:
Create Date: 2026-10-24 06:54:22.471827
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'b24373e3b620'
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), server_default=sa.text('now()'), 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), server_default=sa.text('now()'), 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), server_default=sa.text('now()'), nullable=False),
sa.ForeignKeyConstraint(['chat_id'], ['chats.id'], ondelete='CASCADE'),
sa.ForeignKeyConstraint(['sender_id'], ['users.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
op.create_index('ix_messages_chat_created_id', 'messages', ['chat_id', 'created_at', 'id'], unique=False)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
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,43 @@
"""seed explain test 10k
Revision ID: bc35c1b6b748
Revises: f9b85be2b710
Create Date: 2026-10-24 07:04:09.294404
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'bc35c1b6b748'
down_revision: Union[str, None] = 'f9b85be2b710'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.execute("""
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES ('11111111-1111-1111-1111-111111111111', 'explain_test', 'Test', 'hash', NOW())
ON CONFLICT DO NOTHING;
""")
op.execute("""
INSERT INTO chats (id, title, created_at)
VALUES ('22222222-2222-2222-2222-222222222222', 'Explain Chat', NOW())
ON CONFLICT DO NOTHING;
""")
op.execute("""
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), '22222222-2222-2222-2222-222222222222', '11111111-1111-1111-1111-111111111111', 'Message ' || i, NOW() - (i || ' minutes')::interval
FROM generate_series(1, 10000) AS i;
""")
def downgrade() -> None:
op.execute("DELETE FROM messages WHERE chat_id = '22222222-2222-2222-2222-222222222222';")
op.execute("DELETE FROM chats WHERE id = '22222222-2222-2222-2222-222222222222';")
op.execute("DELETE FROM users WHERE id = '11111111-1111-1111-1111-111111111111';")
@@ -0,0 +1,30 @@
"""add attachment_ids to messages
Revision ID: d78a7aaedac6
Revises: ea4f73899364
Create Date: 2026-11-11 15:16:50.773392
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'd78a7aaedac6'
down_revision: Union[str, None] = 'ea4f73899364'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.add_column('messages', sa.Column('attachment_ids', sa.JSON(), nullable=True))
op.execute("UPDATE messages SET attachment_ids = '[]'::json WHERE attachment_ids IS NULL")
op.alter_column('messages', 'attachment_ids', nullable=False, server_default='[]')
def downgrade() -> None:
op.drop_column('messages', 'attachment_ids')
@@ -0,0 +1,40 @@
"""add attachments table
Revision ID: ea4f73899364
Revises: 08fe661df060
Create Date: 2026-11-11 14:37:24.096041
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'ea4f73899364'
down_revision: Union[str, None] = '08fe661df060'
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('attachments',
sa.Column('id', sa.Uuid(), nullable=False),
sa.Column('object_key', sa.String(), nullable=False),
sa.Column('filename', sa.String(), nullable=False),
sa.Column('mime_type', sa.String(), nullable=False),
sa.Column('size_bytes', sa.Integer(), nullable=False),
sa.Column('chat_id', sa.UUID(), nullable=False),
sa.ForeignKeyConstraint(['chat_id'], ['chats.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('object_key')
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('attachments')
# ### end Alembic commands ###
@@ -0,0 +1,69 @@
"""seed load test data
Revision ID: f9b85be2b710
Revises: b24373e3b620
Create Date: ...
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'f9b85be2b710'
down_revision: Union[str, None] = 'b24373e3b620'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.execute("""
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES ('55555555-5555-4555-8555-555555555555', 'load_test', 'Load', 'hash', NOW())
ON CONFLICT DO NOTHING;
""")
op.execute("""
INSERT INTO chats (id, title, created_at) VALUES
('66666666-6666-4666-8666-666666666666', 'Big Chat', NOW()),
('77777777-7777-4777-8777-777777777777', 'Small Chat 1', NOW()),
('88888888-8888-4888-8888-888888888888', 'Small Chat 2', NOW())
ON CONFLICT DO NOTHING;
""")
op.execute("""
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), '66666666-6666-4666-8666-666666666666', '55555555-5555-4555-8555-555555555555', 'Big ' || i, NOW() - (i || ' minutes')::interval
FROM generate_series(1, 80000) AS i;
""")
op.execute("""
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), '77777777-7777-4777-8777-777777777777', '55555555-5555-4555-8555-555555555555', 'Small1 ' || i, NOW() - (i || ' minutes')::interval
FROM generate_series(1, 10000) AS i;
""")
op.execute("""
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), '88888888-8888-4888-8888-888888888888', '55555555-5555-4555-8555-555555555555', 'Small2 ' || i, NOW() - (i || ' minutes')::interval
FROM generate_series(1, 10000) AS i;
""")
def downgrade() -> None:
op.execute("""
DELETE FROM messages WHERE chat_id IN (
'66666666-6666-4666-8666-666666666666',
'77777777-7777-4777-8777-777777777777',
'88888888-8888-4888-8888-888888888888'
);
""")
op.execute("""
DELETE FROM chats WHERE id IN (
'66666666-6666-4666-8666-666666666666',
'77777777-7777-4777-8777-777777777777',
'88888888-8888-4888-8888-888888888888'
);
""")
op.execute("DELETE FROM users WHERE id = '55555555-5555-4555-8555-555555555555';")