[+] add project

This commit is contained in:
2026-11-17 02:09:04 +03:00
parent ec540a1a72
commit 1fdd40bb42
42 changed files with 2963 additions and 52 deletions
View File
+1030
View File
File diff suppressed because it is too large Load Diff
+35
View File
@@ -0,0 +1,35 @@
from pathlib import Path
import psycopg
from app.settings import database_connection
def main() -> None:
migration_dir = Path(__file__).with_name("migrations")
with psycopg.connect(**database_connection(), autocommit=False) as connection:
connection.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
version varchar(255) PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT clock_timestamp()
)
"""
)
for migration in sorted(migration_dir.glob("*.sql")):
already_applied = connection.execute(
"SELECT 1 FROM schema_migrations WHERE version = %s",
(migration.name,),
).fetchone()
if already_applied:
continue
connection.execute(migration.read_text(encoding="utf-8"))
connection.execute(
"INSERT INTO schema_migrations (version) VALUES (%s)",
(migration.name,),
)
connection.commit()
if __name__ == "__main__":
main()
+54
View File
@@ -0,0 +1,54 @@
CREATE TABLE IF NOT EXISTS users (
id uuid PRIMARY KEY,
username varchar(32) NOT NULL UNIQUE,
display_name varchar(100) NOT NULL,
password_hash text NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
CONSTRAINT users_display_name_nonblank CHECK (length(btrim(display_name)) > 0)
);
CREATE TABLE IF NOT EXISTS chats (
id uuid PRIMARY KEY,
title varchar(100) NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
CONSTRAINT chats_title_nonblank CHECK (length(btrim(title)) > 0)
);
CREATE TABLE IF NOT EXISTS chat_members (
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
PRIMARY KEY (chat_id, user_id)
);
CREATE INDEX IF NOT EXISTS chat_members_by_user
ON chat_members (user_id, chat_id);
CREATE TABLE IF NOT EXISTS messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
sender_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
text varchar(4000) NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
CONSTRAINT messages_text_nonblank CHECK (length(btrim(text)) > 0)
);
CREATE INDEX IF NOT EXISTS messages_history_keyset
ON messages (chat_id, created_at, id);
CREATE TABLE IF NOT EXISTS sessions (
token_hash bytea PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at timestamptz NOT NULL,
revoked_at timestamptz,
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE INDEX IF NOT EXISTS sessions_active_by_expiry
ON sessions (expires_at)
WHERE revoked_at IS NULL;
CREATE TABLE IF NOT EXISTS schema_migrations (
version varchar(255) PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
+12
View File
@@ -0,0 +1,12 @@
CREATE TABLE IF NOT EXISTS idempotency_keys (
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
idempotency_key varchar(128) NOT NULL,
request_hash bytea NOT NULL,
message_id uuid REFERENCES messages(id) ON DELETE SET NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
PRIMARY KEY (user_id, chat_id, idempotency_key)
);
CREATE INDEX IF NOT EXISTS idempotency_keys_expiry
ON idempotency_keys (created_at);
+34
View File
@@ -0,0 +1,34 @@
CREATE TABLE IF NOT EXISTS attachments (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
owner_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
filename varchar(255) NOT NULL,
content_type varchar(32) NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')),
size_bytes bigint NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
sha256 char(64) NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'),
object_key varchar(160) NOT NULL UNIQUE,
status varchar(16) NOT NULL DEFAULT 'ready' CHECK (status = 'ready'),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
CONSTRAINT attachments_filename_nonblank CHECK (length(filename) > 0),
UNIQUE (id, chat_id)
);
CREATE INDEX IF NOT EXISTS attachments_by_chat
ON attachments (chat_id, created_at, id);
CREATE UNIQUE INDEX IF NOT EXISTS messages_id_chat_unique
ON messages (id, chat_id);
CREATE TABLE IF NOT EXISTS message_attachments (
message_id uuid NOT NULL,
chat_id uuid NOT NULL,
attachment_id uuid NOT NULL,
ordinal smallint NOT NULL CHECK (ordinal BETWEEN 0 AND 9),
PRIMARY KEY (message_id, ordinal),
UNIQUE (message_id, attachment_id),
FOREIGN KEY (message_id, chat_id)
REFERENCES messages(id, chat_id) ON DELETE CASCADE,
FOREIGN KEY (attachment_id, chat_id)
REFERENCES attachments(id, chat_id) ON DELETE RESTRICT
);
@@ -0,0 +1,2 @@
ALTER TABLE messages
DROP CONSTRAINT IF EXISTS messages_text_nonblank;
+54
View File
@@ -0,0 +1,54 @@
import os
from pathlib import Path
from typing import Dict, Optional
def read_setting(
name: str,
file_name: str,
default: Optional[str] = None,
default_file: Optional[str] = None,
) -> str:
configured_secret_path = os.environ.get(file_name)
secret_path = configured_secret_path or default_file
if secret_path and (configured_secret_path or Path(secret_path).is_file()):
try:
return Path(secret_path).read_text(encoding="utf-8").strip()
except OSError as exc:
raise RuntimeError("Unable to read configured secret file") from exc
value = os.environ.get(name, default)
if value is None:
if default_file:
raise RuntimeError(
"Required setting is missing: "
+ name
+ "; set "
+ file_name
+ " or mount the secret at "
+ default_file
)
raise RuntimeError("Required application setting is missing: " + name)
return value
def database_connection() -> Dict[str, object]:
return {
"host": os.environ.get("DB_HOST", "localhost"),
"port": int(os.environ.get("DB_PORT", "5432")),
"dbname": os.environ.get("DB_NAME", "messenger"),
"user": os.environ.get("DB_USER", "messenger"),
"password": read_setting(
"DB_PASSWORD",
"DB_PASSWORD_FILE",
default_file="/run/secrets/database_password",
),
"connect_timeout": int(os.environ.get("DB_CONNECT_TIMEOUT_SECONDS", "3")),
"options": "-c statement_timeout=5000 -c lock_timeout=3000",
}
def session_ttl_seconds() -> int:
value = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
if value < 1:
raise RuntimeError("SESSION_TTL_SECONDS must be at least 1")
return value