From 77a43fa9cf16ac7a2fb6d932658279c2dc2190b3 Mon Sep 17 00:00:00 2001 From: EgorAnti Date: Wed, 18 Nov 2026 20:33:27 +0300 Subject: [PATCH 1/3] init --- Dockerfile | 37 ++ build.gradle | 55 +++ compose.yaml | 219 +++++++++++ evidence/lab4-2026-11-11.md | 79 ++++ evidence/upload-memory-2026-11-11.json | 14 + gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 47505 bytes gradle/wrapper/gradle-wrapper.properties | 9 + gradlew | 248 ++++++++++++ gradlew.bat | 82 ++++ infra/minio-api-policy.json | 26 ++ infra/nginx.conf | 103 +++++ scripts/check-private-bucket.cmd | 7 + scripts/check-private-bucket.sh | 9 + scripts/restart.cmd | 10 + scripts/restart.sh | 15 + scripts/restore-api.cmd | 7 + scripts/restore-api.sh | 10 + scripts/rolling-update.cmd | 16 + scripts/rolling-update.sh | 22 ++ scripts/stop-one.cmd | 26 ++ scripts/stop-one.sh | 29 ++ scripts/swarm-lab-down.ps1 | 19 + scripts/swarm-lab-up.ps1 | 171 ++++++++ settings.gradle | 1 + .../MtusiMessengerApplication.java | 20 + .../mtusi_messenger/cache/UserCache.java | 83 ++++ .../mtusi_messenger/config/JacksonConfig.java | 28 ++ .../mtusi_messenger/config/OpenApiConfig.java | 21 + .../config/PasswordConfig.java | 14 + .../config/SecurityConfig.java | 107 +++++ .../mtusi_messenger/config/WebConfig.java | 19 + .../controller/AttachmentController.java | 78 ++++ .../controller/ChatController.java | 83 ++++ .../controller/HealthController.java | 32 ++ .../controller/MessageController.java | 79 ++++ .../controller/SessionController.java | 41 ++ .../controller/UserController.java | 32 ++ .../dto/AttachmentResponse.java | 36 ++ .../mtusi_messenger/dto/ChatPageResponse.java | 8 + .../mtusi_messenger/dto/ChatResponse.java | 18 + .../dto/CreateChatRequest.java | 19 + .../dto/CreateMessageRequest.java | 31 ++ .../dto/CreateUserRequest.java | 20 + .../mtusi_messenger/dto/ErrorResponse.java | 8 + .../mtusi_messenger/dto/HealthResponse.java | 3 + .../dto/MessagePageResponse.java | 8 + .../mtusi_messenger/dto/MessageResponse.java | 22 ++ .../mtusi_messenger/dto/SessionResponse.java | 10 + .../mtusi_messenger/dto/UserResponse.java | 18 + .../exception/ApiException.java | 14 + .../exception/ApiExceptions.java | 17 + .../mtusi_messenger/model/Attachment.java | 16 + .../example/mtusi_messenger/model/Chat.java | 11 + .../model/IdempotentMessage.java | 3 + .../mtusi_messenger/model/Message.java | 16 + .../mtusi_messenger/model/MessageKey.java | 35 ++ .../mtusi_messenger/model/Session.java | 15 + .../example/mtusi_messenger/model/User.java | 6 + .../repository/AttachmentRepository.java | 15 + .../repository/ChatRepository.java | 14 + .../repository/MessageRepository.java | 18 + .../PostgresAttachmentRepository.java | 82 ++++ .../repository/PostgresChatRepository.java | 106 +++++ .../repository/PostgresMessageRepository.java | 172 ++++++++ .../repository/PostgresSessionRepository.java | 51 +++ .../repository/PostgresUserRepository.java | 72 ++++ .../repository/SessionRepository.java | 12 + .../repository/UserRepository.java | 14 + .../security/ApiAuthenticationFilter.java | 130 +++++++ .../DatabaseAuthenticationProvider.java | 63 +++ .../RestAuthenticationEntryPoint.java | 46 +++ .../security/SessionPrincipal.java | 14 + .../service/AttachmentReconciler.java | 104 +++++ .../service/AttachmentService.java | 239 ++++++++++++ .../service/AuthenticationService.java | 104 +++++ .../mtusi_messenger/service/ChatService.java | 38 ++ .../service/CursorService.java | 40 ++ .../service/MessageService.java | 102 +++++ .../service/ReadinessService.java | 81 ++++ .../mtusi_messenger/service/UserService.java | 34 ++ .../service/UuidValidator.java | 27 ++ .../storage/MinioObjectStorage.java | 92 +++++ .../storage/ObjectStorage.java | 14 + .../storage/ObjectStorageException.java | 7 + .../web/GlobalExceptionHandler.java | 56 +++ .../mtusi_messenger/web/InstanceIdFilter.java | 47 +++ .../mtusi_messenger/web/NotUnicodeBlank.java | 21 + .../web/ReadinessGuardFilter.java | 56 +++ .../mtusi_messenger/web/RequestIdFilter.java | 40 ++ .../web/UnicodeBlankValidator.java | 23 ++ .../mtusi_messenger/web/UnicodeSize.java | 35 ++ .../web/UnicodeSizeValidator.java | 32 ++ src/main/resources/application.yml | 77 ++++ .../migration/V1__create_messenger_schema.sql | 60 +++ .../V2__add_credentials_and_sessions.sql | 28 ++ .../migration/V3__add_message_idempotency.sql | 25 ++ .../db/migration/V4__add_attachments.sql | 53 +++ .../MtusiMessengerApplicationTests.java | 368 ++++++++++++++++++ .../mtusi_messenger/cache/UserCacheTest.java | 31 ++ .../service/AttachmentReconcilerTest.java | 75 ++++ .../service/AttachmentServiceTest.java | 194 +++++++++ .../web/ReadinessGuardFilterTest.java | 62 +++ student_tests/README.md | 18 + student_tests/concurrent_upload_memory.py | 145 +++++++ student_tests/failover_each.py | 135 +++++++ student_tests/idempotency_concurrent.py | 53 +++ student_tests/lab4_negative.py | 65 ++++ student_tests/node_failover.py | 182 +++++++++ student_tests/readiness_gate.py | 104 +++++ student_tests/rolling_update.py | 110 ++++++ swarm/nginx.Dockerfile | 3 + swarm/nginx.conf | 86 ++++ swarm/stack.app.yaml | 88 +++++ swarm/stack.state.yaml | 123 ++++++ 114 files changed, 6271 insertions(+) create mode 100644 Dockerfile create mode 100644 build.gradle create mode 100644 compose.yaml create mode 100644 evidence/lab4-2026-11-11.md create mode 100644 evidence/upload-memory-2026-11-11.json create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100644 gradlew create mode 100644 gradlew.bat create mode 100644 infra/minio-api-policy.json create mode 100644 infra/nginx.conf create mode 100644 scripts/check-private-bucket.cmd create mode 100644 scripts/check-private-bucket.sh create mode 100644 scripts/restart.cmd create mode 100644 scripts/restart.sh create mode 100644 scripts/restore-api.cmd create mode 100644 scripts/restore-api.sh create mode 100644 scripts/rolling-update.cmd create mode 100644 scripts/rolling-update.sh create mode 100644 scripts/stop-one.cmd create mode 100644 scripts/stop-one.sh create mode 100644 scripts/swarm-lab-down.ps1 create mode 100644 scripts/swarm-lab-up.ps1 create mode 100644 settings.gradle create mode 100644 src/main/java/com/example/mtusi_messenger/MtusiMessengerApplication.java create mode 100644 src/main/java/com/example/mtusi_messenger/cache/UserCache.java create mode 100644 src/main/java/com/example/mtusi_messenger/config/JacksonConfig.java create mode 100644 src/main/java/com/example/mtusi_messenger/config/OpenApiConfig.java create mode 100644 src/main/java/com/example/mtusi_messenger/config/PasswordConfig.java create mode 100644 src/main/java/com/example/mtusi_messenger/config/SecurityConfig.java create mode 100644 src/main/java/com/example/mtusi_messenger/config/WebConfig.java create mode 100644 src/main/java/com/example/mtusi_messenger/controller/AttachmentController.java create mode 100644 src/main/java/com/example/mtusi_messenger/controller/ChatController.java create mode 100644 src/main/java/com/example/mtusi_messenger/controller/HealthController.java create mode 100644 src/main/java/com/example/mtusi_messenger/controller/MessageController.java create mode 100644 src/main/java/com/example/mtusi_messenger/controller/SessionController.java create mode 100644 src/main/java/com/example/mtusi_messenger/controller/UserController.java create mode 100644 src/main/java/com/example/mtusi_messenger/dto/AttachmentResponse.java create mode 100644 src/main/java/com/example/mtusi_messenger/dto/ChatPageResponse.java create mode 100644 src/main/java/com/example/mtusi_messenger/dto/ChatResponse.java create mode 100644 src/main/java/com/example/mtusi_messenger/dto/CreateChatRequest.java create mode 100644 src/main/java/com/example/mtusi_messenger/dto/CreateMessageRequest.java create mode 100644 src/main/java/com/example/mtusi_messenger/dto/CreateUserRequest.java create mode 100644 src/main/java/com/example/mtusi_messenger/dto/ErrorResponse.java create mode 100644 src/main/java/com/example/mtusi_messenger/dto/HealthResponse.java create mode 100644 src/main/java/com/example/mtusi_messenger/dto/MessagePageResponse.java create mode 100644 src/main/java/com/example/mtusi_messenger/dto/MessageResponse.java create mode 100644 src/main/java/com/example/mtusi_messenger/dto/SessionResponse.java create mode 100644 src/main/java/com/example/mtusi_messenger/dto/UserResponse.java create mode 100644 src/main/java/com/example/mtusi_messenger/exception/ApiException.java create mode 100644 src/main/java/com/example/mtusi_messenger/exception/ApiExceptions.java create mode 100644 src/main/java/com/example/mtusi_messenger/model/Attachment.java create mode 100644 src/main/java/com/example/mtusi_messenger/model/Chat.java create mode 100644 src/main/java/com/example/mtusi_messenger/model/IdempotentMessage.java create mode 100644 src/main/java/com/example/mtusi_messenger/model/Message.java create mode 100644 src/main/java/com/example/mtusi_messenger/model/MessageKey.java create mode 100644 src/main/java/com/example/mtusi_messenger/model/Session.java create mode 100644 src/main/java/com/example/mtusi_messenger/model/User.java create mode 100644 src/main/java/com/example/mtusi_messenger/repository/AttachmentRepository.java create mode 100644 src/main/java/com/example/mtusi_messenger/repository/ChatRepository.java create mode 100644 src/main/java/com/example/mtusi_messenger/repository/MessageRepository.java create mode 100644 src/main/java/com/example/mtusi_messenger/repository/PostgresAttachmentRepository.java create mode 100644 src/main/java/com/example/mtusi_messenger/repository/PostgresChatRepository.java create mode 100644 src/main/java/com/example/mtusi_messenger/repository/PostgresMessageRepository.java create mode 100644 src/main/java/com/example/mtusi_messenger/repository/PostgresSessionRepository.java create mode 100644 src/main/java/com/example/mtusi_messenger/repository/PostgresUserRepository.java create mode 100644 src/main/java/com/example/mtusi_messenger/repository/SessionRepository.java create mode 100644 src/main/java/com/example/mtusi_messenger/repository/UserRepository.java create mode 100644 src/main/java/com/example/mtusi_messenger/security/ApiAuthenticationFilter.java create mode 100644 src/main/java/com/example/mtusi_messenger/security/DatabaseAuthenticationProvider.java create mode 100644 src/main/java/com/example/mtusi_messenger/security/RestAuthenticationEntryPoint.java create mode 100644 src/main/java/com/example/mtusi_messenger/security/SessionPrincipal.java create mode 100644 src/main/java/com/example/mtusi_messenger/service/AttachmentReconciler.java create mode 100644 src/main/java/com/example/mtusi_messenger/service/AttachmentService.java create mode 100644 src/main/java/com/example/mtusi_messenger/service/AuthenticationService.java create mode 100644 src/main/java/com/example/mtusi_messenger/service/ChatService.java create mode 100644 src/main/java/com/example/mtusi_messenger/service/CursorService.java create mode 100644 src/main/java/com/example/mtusi_messenger/service/MessageService.java create mode 100644 src/main/java/com/example/mtusi_messenger/service/ReadinessService.java create mode 100644 src/main/java/com/example/mtusi_messenger/service/UserService.java create mode 100644 src/main/java/com/example/mtusi_messenger/service/UuidValidator.java create mode 100644 src/main/java/com/example/mtusi_messenger/storage/MinioObjectStorage.java create mode 100644 src/main/java/com/example/mtusi_messenger/storage/ObjectStorage.java create mode 100644 src/main/java/com/example/mtusi_messenger/storage/ObjectStorageException.java create mode 100644 src/main/java/com/example/mtusi_messenger/web/GlobalExceptionHandler.java create mode 100644 src/main/java/com/example/mtusi_messenger/web/InstanceIdFilter.java create mode 100644 src/main/java/com/example/mtusi_messenger/web/NotUnicodeBlank.java create mode 100644 src/main/java/com/example/mtusi_messenger/web/ReadinessGuardFilter.java create mode 100644 src/main/java/com/example/mtusi_messenger/web/RequestIdFilter.java create mode 100644 src/main/java/com/example/mtusi_messenger/web/UnicodeBlankValidator.java create mode 100644 src/main/java/com/example/mtusi_messenger/web/UnicodeSize.java create mode 100644 src/main/java/com/example/mtusi_messenger/web/UnicodeSizeValidator.java create mode 100644 src/main/resources/application.yml create mode 100644 src/main/resources/db/migration/V1__create_messenger_schema.sql create mode 100644 src/main/resources/db/migration/V2__add_credentials_and_sessions.sql create mode 100644 src/main/resources/db/migration/V3__add_message_idempotency.sql create mode 100644 src/main/resources/db/migration/V4__add_attachments.sql create mode 100644 src/test/java/com/example/mtusi_messenger/MtusiMessengerApplicationTests.java create mode 100644 src/test/java/com/example/mtusi_messenger/cache/UserCacheTest.java create mode 100644 src/test/java/com/example/mtusi_messenger/service/AttachmentReconcilerTest.java create mode 100644 src/test/java/com/example/mtusi_messenger/service/AttachmentServiceTest.java create mode 100644 src/test/java/com/example/mtusi_messenger/web/ReadinessGuardFilterTest.java create mode 100644 student_tests/README.md create mode 100644 student_tests/concurrent_upload_memory.py create mode 100644 student_tests/failover_each.py create mode 100644 student_tests/idempotency_concurrent.py create mode 100644 student_tests/lab4_negative.py create mode 100644 student_tests/node_failover.py create mode 100644 student_tests/readiness_gate.py create mode 100644 student_tests/rolling_update.py create mode 100644 swarm/nginx.Dockerfile create mode 100644 swarm/nginx.conf create mode 100644 swarm/stack.app.yaml create mode 100644 swarm/stack.state.yaml diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..4729dd8b --- /dev/null +++ b/Dockerfile @@ -0,0 +1,37 @@ +# Stage 1: Build +FROM eclipse-temurin:23-jdk AS build + +WORKDIR /app + +COPY gradlew . +COPY gradle gradle +COPY build.gradle settings.gradle ./ + +COPY src src + +RUN --mount=type=cache,target=/root/.gradle \ + chmod +x gradlew && ./gradlew bootJar --no-daemon + + +# Stage 2: Runtime +FROM eclipse-temurin:23-jre + +WORKDIR /app + +COPY --from=build /app/build/libs/*.jar app.jar + +RUN apt-get update \ + && apt-get install --yes --no-install-recommends curl \ + && rm -rf /var/lib/apt/lists/* \ + && useradd --system --create-home messenger + +USER messenger + +EXPOSE 8080 + +STOPSIGNAL SIGTERM + +HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \ + CMD curl --fail --silent --show-error http://localhost:8080/health/ready || exit 1 + +ENTRYPOINT ["java", "-jar", "app.jar"] diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..22435bce --- /dev/null +++ b/build.gradle @@ -0,0 +1,55 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '4.1.1' + id 'io.spring.dependency-management' version '1.1.7' +} + +group = 'com.example' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(23) + } +} + +repositories { + mavenCentral() +} + +dependencies { +// implementation 'org.springframework.boot:spring-boot-starter-data-jpa' +// implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.springframework.boot:spring-boot-starter-webmvc' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'org.springframework.boot:spring-boot-starter-jdbc' + implementation 'org.springframework.boot:spring-boot-starter-data-redis' + implementation 'org.springframework.boot:spring-boot-flyway' + implementation 'org.flywaydb:flyway-core' + implementation 'org.flywaydb:flyway-database-postgresql' + implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.bouncycastle:bcprov-jdk18on:1.84' + implementation 'org.apache.commons:commons-pool2' + implementation 'io.minio:minio:8.6.0' + runtimeOnly 'org.postgresql:postgresql' + + implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310' + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.3' + compileOnly 'org.projectlombok:lombok' + developmentOnly 'org.springframework.boot:spring-boot-devtools' + annotationProcessor 'org.projectlombok:lombok' +// testImplementation 'org.springframework.boot:spring-boot-starter-data-jpa-test' +// testImplementation 'org.springframework.boot:spring-boot-starter-security-test' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test' + testCompileOnly 'org.projectlombok:lombok' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + testAnnotationProcessor 'org.projectlombok:lombok' + + implementation("com.github.f4b6a3:uuid-creator:6.1.1") + +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..bc0ebf42 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,219 @@ +name: hla-lab4 + +x-api-environment: &api-environment + APP_HOST: 0.0.0.0 + APP_PORT: 8080 + DATABASE_URL: jdbc:postgresql://postgres:5432/${DATABASE_NAME:-messenger} + DATABASE_USER: ${DATABASE_USER:-messenger} + DATABASE_PASSWORD: ${DATABASE_PASSWORD:?Set DATABASE_PASSWORD in .env} + DATABASE_POOL_SIZE: ${DATABASE_POOL_SIZE:-10} + DATABASE_MIN_IDLE: ${DATABASE_MIN_IDLE:-2} + DATABASE_QUERY_TIMEOUT_SECONDS: ${DATABASE_QUERY_TIMEOUT_SECONDS:-5} + DATABASE_TRANSACTION_TIMEOUT_SECONDS: ${DATABASE_TRANSACTION_TIMEOUT_SECONDS:-5} + REDIS_HOST: redis + REDIS_PORT: 6379 + REDIS_CONNECT_TIMEOUT: ${REDIS_CONNECT_TIMEOUT:-1s} + REDIS_COMMAND_TIMEOUT: ${REDIS_COMMAND_TIMEOUT:-500ms} + REDIS_POOL_MAX_ACTIVE: ${REDIS_POOL_MAX_ACTIVE:-8} + REDIS_POOL_MAX_IDLE: ${REDIS_POOL_MAX_IDLE:-8} + REDIS_POOL_MIN_IDLE: ${REDIS_POOL_MIN_IDLE:-0} + REDIS_POOL_MAX_WAIT: ${REDIS_POOL_MAX_WAIT:-500ms} + USER_CACHE_TTL_SECONDS: ${USER_CACHE_TTL_SECONDS:-300} + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} + S3_ENDPOINT: http://minio:9000 + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:?Set S3_ACCESS_KEY_ID in .env} + S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:?Set S3_SECRET_ACCESS_KEY in .env} + MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760} + MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} + MAX_CONCURRENT_UPLOADS: ${MAX_CONCURRENT_UPLOADS:-3} + UPLOAD_PERMIT_WAIT_MILLIS: ${UPLOAD_PERMIT_WAIT_MILLIS:-10000} + ATTACHMENT_CLEANUP_GRACE_SECONDS: ${ATTACHMENT_CLEANUP_GRACE_SECONDS:-3600} + ATTACHMENT_CLEANUP_DRY_RUN: ${ATTACHMENT_CLEANUP_DRY_RUN:-false} + ATTACHMENT_RECONCILE_INTERVAL_MILLIS: ${ATTACHMENT_RECONCILE_INTERVAL_MILLIS:-600000} + ATTACHMENT_RECONCILE_INITIAL_DELAY_MILLIS: ${ATTACHMENT_RECONCILE_INITIAL_DELAY_MILLIS:-60000} + +services: + postgres: + image: postgres:16.4-bookworm + environment: + POSTGRES_DB: ${DATABASE_NAME:-messenger} + POSTGRES_USER: ${DATABASE_USER:-messenger} + POSTGRES_PASSWORD: ${DATABASE_PASSWORD:?Set DATABASE_PASSWORD in .env} + volumes: + - postgres-data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"] + interval: 2s + timeout: 2s + retries: 30 + restart: unless-stopped + cpus: 1.0 + mem_limit: 768m + networks: [backend] + + redis: + image: redis:7.4-bookworm + command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec"] + volumes: + - redis-data:/data + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 2s + timeout: 2s + retries: 30 + restart: unless-stopped + cpus: 0.25 + mem_limit: 256m + networks: [backend] + + minio: + image: bitnamilegacy/minio:2025.4.22-debian-12-r1@sha256:d7cd0e172c4cc0870f4bdc3142018e2a37be9acf04d68f386600daad427e0cab + environment: + MINIO_ROOT_USER: ${MINIO_ROOT_USER:?Set MINIO_ROOT_USER in .env} + MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?Set MINIO_ROOT_PASSWORD in .env} + volumes: + - minio-data:/bitnami/minio/data + healthcheck: + test: ["CMD", "curl", "--fail", "--silent", "http://localhost:9000/minio/health/live"] + interval: 2s + timeout: 2s + retries: 30 + restart: unless-stopped + cpus: 0.75 + mem_limit: 512m + networks: [backend] + + minio-init: + image: bitnamilegacy/minio-client:2025.4.16-debian-12-r0@sha256:28e38f52642c06a2344fa974cf55786b4c52601b6b9b0676c68d40ee0876a5bc + depends_on: + minio: + condition: service_healthy + environment: + MINIO_ROOT_USER: ${MINIO_ROOT_USER:?Set MINIO_ROOT_USER in .env} + MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?Set MINIO_ROOT_PASSWORD in .env} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:?Set S3_ACCESS_KEY_ID in .env} + S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:?Set S3_SECRET_ACCESS_KEY in .env} + volumes: + - ./infra/minio-api-policy.json:/policy/minio-api-policy.json:ro + entrypoint: ["/bin/sh", "-c"] + command: + - | + set -eu + mc alias set local http://minio:9000 "$$MINIO_ROOT_USER" "$$MINIO_ROOT_PASSWORD" + mc mb --ignore-existing "local/$$S3_BUCKET" + mc anonymous set none "local/$$S3_BUCKET" + sed "s/__S3_BUCKET__/$$S3_BUCKET/g" /policy/minio-api-policy.json > /tmp/minio-api-policy.json + mc admin user add local "$$S3_ACCESS_KEY_ID" "$$S3_SECRET_ACCESS_KEY" || true + mc admin policy create local messenger-attachments-rw /tmp/minio-api-policy.json || true + mc admin policy attach local messenger-attachments-rw --user "$$S3_ACCESS_KEY_ID" + restart: "no" + networks: [backend] + + private-bucket-check: + profiles: ["verification"] + image: bitnamilegacy/minio-client:2025.4.16-debian-12-r0@sha256:28e38f52642c06a2344fa974cf55786b4c52601b6b9b0676c68d40ee0876a5bc + depends_on: + minio-init: + condition: service_completed_successfully + environment: + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:?Set S3_ACCESS_KEY_ID in .env} + S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:?Set S3_SECRET_ACCESS_KEY in .env} + entrypoint: ["/bin/sh", "-c"] + command: + - | + set -eu + mc alias set anonymous http://minio:9000 + if mc ls "anonymous/$$S3_BUCKET" >/dev/null 2>&1; then + echo "FAIL: anonymous bucket listing succeeded" >&2 + exit 1 + fi + mc alias set restricted http://minio:9000 "$$S3_ACCESS_KEY_ID" "$$S3_SECRET_ACCESS_KEY" + mc ls "restricted/$$S3_BUCKET" >/dev/null + if mc admin info restricted >/dev/null 2>&1; then + echo "FAIL: API credentials have administrative access" >&2 + exit 1 + fi + echo "PASS: bucket is private and API credentials are non-admin" + restart: "no" + networks: [backend] + + # One-shot Flyway runner. It is invoked explicitly before API replicas. + migrate: + image: hla-lab4-api:local + build: + context: . + environment: + <<: *api-environment + FLYWAY_ENABLED: "true" + MIGRATE_ONLY: "true" + SPRING_MAIN_WEB_APPLICATION_TYPE: none + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + restart: "no" + cpus: 0.75 + mem_limit: 768m + networks: [backend] + + api: + image: hla-lab4-api:local + build: + context: . + environment: + <<: *api-environment + FLYWAY_ENABLED: "false" + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + minio-init: + condition: service_completed_successfully + healthcheck: + test: ["CMD", "curl", "--fail", "--silent", "http://localhost:8080/health/ready"] + interval: 2s + timeout: 2s + retries: 15 + start_period: 45s + init: true + stop_grace_period: 12s + restart: unless-stopped + cpus: 0.75 + mem_limit: 768m + networks: [backend] + + nginx: + image: nginx:1.27.4-bookworm + ports: + - "127.0.0.1:${APP_PORT:-8080}:80" + volumes: + - ./infra/nginx.conf:/etc/nginx/nginx.conf:ro + depends_on: + api: + condition: service_healthy + healthcheck: + test: ["CMD", "nginx", "-t"] + interval: 2s + timeout: 2s + retries: 15 + stop_grace_period: 10s + restart: unless-stopped + cpus: 0.25 + mem_limit: 128m + networks: [backend] + +networks: + backend: + driver: bridge + +volumes: + postgres-data: + redis-data: + minio-data: diff --git a/evidence/lab4-2026-11-11.md b/evidence/lab4-2026-11-11.md new file mode 100644 index 00000000..c386a7aa --- /dev/null +++ b/evidence/lab4-2026-11-11.md @@ -0,0 +1,79 @@ +# Lab4 evidence — 2026-11-11 + +Стенд: Docker Compose, nginx на `127.0.0.1:18084`, API ×2, PostgreSQL, Redis, MinIO. Секреты и session tokens в evidence не сохранялись. + +## Bootstrap и миграции + +- MinIO server image: `bitnamilegacy/minio:2025.4.22-debian-12-r1@sha256:d7cd…e0cab`. +- `minio-init`: bucket `messenger-attachments` создан, anonymous access установлен `private`, пользователь `messenger-api` создан, policy `messenger-attachments-rw` назначена. +- Flyway: успешно проверены и применены 4 миграции, итоговая версия schema `v4`. +- `docker compose ps`: две здоровые API-реплики; MinIO/PostgreSQL/Redis/nginx healthy; наружу опубликован только nginx. + +## Проверки + +```text +AttachmentServiceTest + AttachmentReconcilerTest: BUILD SUCCESSFUL, 10 tests. +tests/smoke.py: PASS: lab4 public API scenario. +student_tests/lab4_negative.py: +PASS: unknown/foreign attachment, foreign chat/user, MIME spoof, corruption, +byte limit and filename checks. +``` + +Persistence hook останавливал nginx, обе API, Redis, PostgreSQL и MinIO, затем запускал те же named volumes и повторял idempotent bucket bootstrap: + +```text +PASS: persistence preserved confirmed data and existing session. +``` + +Failover hook остановил replica из `X-Instance-Id`, обслужившую тестовый запрос: + +```json +{"observed_instances_before":2,"successful_writes":102,"failed_attempts":0,"first_recovery_seconds":1.386} +``` + +```text +PASS: failover preserved confirmed data and existing session. +``` + +При остановленном MinIO: + +```text +PASS: unavailable S3 returns contract JSON 503 +``` + +После запуска того же MinIO volume публичный smoke повторно завершился PASS, checksum скачанного original совпал. + +## Level 4: consistency, memory and private S3 + +Unit tests inject an interrupted request stream before S3 PUT and a repository +failure after S3 PUT. The first leaves storage empty; the second verifies the +compensating DELETE. Reconciler tests prove that an orphan younger than the +one-hour grace period survives, an older orphan is deleted, dry-run never +deletes, and a missing object is reported. + +Bootstrap was executed again against the existing bucket and completed with +exit code 0. The direct S3 probe (without application API) produced: + +```text +PASS: bucket is private and API credentials are non-admin +``` + +Full Gradle suite using the live Compose PostgreSQL/Redis/MinIO network: + +```text +BUILD SUCCESSFUL in 11m 47s +``` + +Concurrent memory experiment (`evidence/upload-memory-2026-11-11.json`): + +```json +{"concurrency":12,"successful_uploads":12,"payload_bytes_each":6835833, + "duration_seconds":10.156,"api_replicas":2,"memory_samples":5, + "baseline_api_memory_bytes":668467200,"peak_api_memory_bytes":839909375, + "peak_increase_bytes":171442175,"configured_max_concurrent_uploads_per_replica":3} +``` + +The memory values are the aggregate of both API containers from `docker stats`. +Sampling can miss a shorter peak, so this is an operational bound observation, +not a JVM heap proof. The code-level bounds are 10 MiB/request, 40M pixels and +three active uploads per replica. diff --git a/evidence/upload-memory-2026-11-11.json b/evidence/upload-memory-2026-11-11.json new file mode 100644 index 00000000..6ee7149e --- /dev/null +++ b/evidence/upload-memory-2026-11-11.json @@ -0,0 +1,14 @@ +{ + "concurrency": 12, + "successful_uploads": 12, + "payload_bytes_each": 6835833, + "duration_seconds": 10.156, + "api_replicas": 2, + "memory_samples": 5, + "baseline_api_memory_bytes": 668467200, + "peak_api_memory_bytes": 839909375, + "peak_increase_bytes": 171442175, + "configured_max_concurrent_uploads_per_replica": 3, + "configured_max_upload_bytes": 10485760, + "configured_max_image_pixels": 40000000 +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..eddabd2eef8d94a5437d6168ff9c87a78ff725b3 GIT binary patch literal 47505 zcma%jV|XRZx@BzJPRF)w+qP|W2RrDP9UC1d9oxo^)3I%LIQh<*=g!Qz_k45q^VI&e z|5VkgwQ8;Rt*tBv4uJsz0|NsB0z&#Z{?7*m1QtX=LS2MGMp2SUUPeqpQB6Wa9TEie zub-^z>bb3QVg*ju^jKS3o#9H#w4Yxz1*n>pYH+2nC3dC@ic(OUh@sI7>n^@O3t+EN zk19TR2&69-M23X8{h9JYx|8)kwwf7ttr>teD4+VN#nkbK$s(IG`^odY38j0~G5LYI zE8yj!-3t3WJpbc*GP8f1Ijv!GZFxNt(Cq4DxZU@%dVh&ur@bEGnl2N^*QNXDgt%%uIzL8-|f9*0a_P$gWq1W= zyYFqsd}OSk24kb~1dN}B%z?^{HGmwKoogz&O?>^nlNT;9zKwXe(^*#}CA6|3JU~$) z84gW6*^!J(I2cJ6Fex`F@*8Z;s#mTo^y2AJ6hSf>Ei3lYhvt>4{wrqH*`8wlt+NqV zs$Y#ZDUzSWF!beISEBi0Dvx#amw4A=5p>tM)l(wMg*GU=hp|-Z=aZM_pw^OegdgFE z#1Jtd_&p~_;Lb@JjM5MZdJErBWf7~hq^IxX89(}?*<2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r{DI`(TCN5TCVxIm zz3W43S4iMc+V&iDsHDgdkhpYZ&i>iy%7 z2?xtRtNz2>eb2i6(Rl{Pe>nfwO#KEE{_~gldqnFUF87@w`o4YS9bMs@6)F8z>K{V=`&NT@+g{&n#qgJY|DYA+&&U3K`@J874c+878h>wm z{Pz}yKkIy7^?cXN@0;nH{+Z4{OxE`W!*|8g-|U6^F9rTvDfQ1s{(UX$k7vQvYMdv{Mz{+ '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..a51ec4f5 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,82 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/infra/minio-api-policy.json b/infra/minio-api-policy.json new file mode 100644 index 00000000..97085216 --- /dev/null +++ b/infra/minio-api-policy.json @@ -0,0 +1,26 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "s3:GetBucketLocation", + "s3:ListBucket" + ], + "Resource": [ + "arn:aws:s3:::__S3_BUCKET__" + ] + }, + { + "Effect": "Allow", + "Action": [ + "s3:GetObject", + "s3:PutObject", + "s3:DeleteObject" + ], + "Resource": [ + "arn:aws:s3:::__S3_BUCKET__/attachments/*" + ] + } + ] +} diff --git a/infra/nginx.conf b/infra/nginx.conf new file mode 100644 index 00000000..7aabc52a --- /dev/null +++ b/infra/nginx.conf @@ -0,0 +1,103 @@ +worker_processes auto; +worker_shutdown_timeout 10s; + +events { + worker_connections 1024; +} + +http { + # Let the application enforce the exact 10 MiB contract and return JSON. + client_max_body_size 11m; + client_body_timeout 10s; + access_log /var/log/nginx/access.log; + error_log /var/log/nginx/error.log warn; + + # Docker embedded DNS returns current Compose replicas. Nginx OSS 1.27.3+ + # refreshes these addresses without a configuration reload. + resolver 127.0.0.11 valid=2s ipv6=off; + resolver_timeout 1s; + + upstream api_backend { + zone api_backend 64k; + least_conn; + server api:8080 resolve max_fails=1 fail_timeout=2s; + keepalive 32; + } + + server { + listen 80; + server_name _; + proxy_intercept_errors on; + error_page 502 503 504 = @no_ready_api; + + location = /nginx-health { + access_log off; + default_type application/json; + return 200 '{"status":"ok"}'; + } + + # After both peers have refused traffic or become unreachable, Nginx + # would normally emit its own HTML 502. Keep the public API contract: + # no ready backend is a JSON 503 with the required tracing headers. + location @no_ready_api { + internal; + default_type application/json; + add_header X-Request-Id $request_id always; + add_header X-Instance-Id nginx always; + add_header Cache-Control "no-store" always; + return 503 '{"error":{"code":"unavailable","message":"No ready API backend","request_id":"$request_id"}}'; + } + + # Message POST is the only non-idempotent HTTP method that is safe to + # replay here: the API requires Idempotency-Key and commits the message + # together with its shared PostgreSQL idempotency record. + location ~ ^/api/v1/chats/[0-9a-fA-F-]+/messages$ { + proxy_pass http://api_backend; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_request_buffering on; + + proxy_connect_timeout 500ms; + proxy_send_timeout 4s; + proxy_read_timeout 4s; + proxy_next_upstream error timeout http_502 http_503 http_504 non_idempotent; + proxy_next_upstream_tries 2; + } + + location ~ ^/api/v1/chats/[0-9a-fA-F-]+/attachments$ { + proxy_pass http://api_backend; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_request_buffering on; + + proxy_connect_timeout 500ms; + proxy_send_timeout 20s; + proxy_read_timeout 20s; + # Upload is not replayed: it has no idempotency key. The client may retry explicitly. + proxy_next_upstream off; + } + + location / { + proxy_pass http://api_backend; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + proxy_connect_timeout 500ms; + proxy_send_timeout 4s; + proxy_read_timeout 4s; + + # No sticky sessions. Failed/unready peers are retried elsewhere. + proxy_next_upstream error timeout http_502 http_503 http_504; + proxy_next_upstream_tries 2; + } + } +} diff --git a/scripts/check-private-bucket.cmd b/scripts/check-private-bucket.cmd new file mode 100644 index 00000000..1065a92d --- /dev/null +++ b/scripts/check-private-bucket.cmd @@ -0,0 +1,7 @@ +@echo off +setlocal EnableExtensions +cd /d "%~dp0\.." +if not defined ENV_FILE set "ENV_FILE=.env" + +docker compose --env-file "%ENV_FILE%" --profile verification run --rm private-bucket-check +exit /b %ERRORLEVEL% diff --git a/scripts/check-private-bucket.sh b/scripts/check-private-bucket.sh new file mode 100644 index 00000000..eab94689 --- /dev/null +++ b/scripts/check-private-bucket.sh @@ -0,0 +1,9 @@ +#!/bin/sh +set -eu + +SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +PROJECT_DIR=$(dirname -- "$SCRIPT_DIR") +cd "$PROJECT_DIR" +: "${ENV_FILE:=.env}" + +docker compose --env-file "$ENV_FILE" --profile verification run --rm private-bucket-check diff --git a/scripts/restart.cmd b/scripts/restart.cmd new file mode 100644 index 00000000..ddc596a3 --- /dev/null +++ b/scripts/restart.cmd @@ -0,0 +1,10 @@ +@echo off +setlocal EnableExtensions +cd /d "%~dp0\.." +if not defined ENV_FILE set "ENV_FILE=.env" + +docker compose --env-file "%ENV_FILE%" stop nginx api redis postgres minio || exit /b 1 +docker compose --env-file "%ENV_FILE%" up -d --wait --wait-timeout 90 postgres redis minio || exit /b 1 +docker compose --env-file "%ENV_FILE%" run --rm minio-init || exit /b 1 +docker compose --env-file "%ENV_FILE%" up -d --wait --wait-timeout 90 --no-deps --scale api=2 api || exit /b 1 +docker compose --env-file "%ENV_FILE%" up -d --no-deps nginx || exit /b 1 diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 00000000..d8a5cec9 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,15 @@ +#!/bin/sh +set -eu + +SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +PROJECT_DIR=$(dirname -- "$SCRIPT_DIR") +cd "$PROJECT_DIR" +: "${ENV_FILE:=.env}" + +# Preserve named volumes and the network. The migration job is intentionally +# not re-run during a same-version restart. +docker compose --env-file "$ENV_FILE" stop nginx api redis postgres minio +docker compose --env-file "$ENV_FILE" up -d --wait --wait-timeout 90 postgres redis minio +docker compose --env-file "$ENV_FILE" run --rm minio-init +docker compose --env-file "$ENV_FILE" up -d --wait --wait-timeout 90 --no-deps --scale api=2 api +docker compose --env-file "$ENV_FILE" up -d --no-deps nginx diff --git a/scripts/restore-api.cmd b/scripts/restore-api.cmd new file mode 100644 index 00000000..adebf598 --- /dev/null +++ b/scripts/restore-api.cmd @@ -0,0 +1,7 @@ +@echo off +setlocal EnableExtensions +cd /d "%~dp0\.." +if not defined ENV_FILE set "ENV_FILE=.env" + +docker compose --env-file "%ENV_FILE%" up -d --wait --wait-timeout 90 --no-deps --scale api=2 api +exit /b %ERRORLEVEL% diff --git a/scripts/restore-api.sh b/scripts/restore-api.sh new file mode 100644 index 00000000..75184739 --- /dev/null +++ b/scripts/restore-api.sh @@ -0,0 +1,10 @@ +#!/bin/sh +set -eu + +SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +PROJECT_DIR=$(dirname -- "$SCRIPT_DIR") +cd "$PROJECT_DIR" +: "${ENV_FILE:=.env}" + +docker compose --env-file "$ENV_FILE" up -d --wait --wait-timeout 90 \ + --no-deps --scale api=2 api diff --git a/scripts/rolling-update.cmd b/scripts/rolling-update.cmd new file mode 100644 index 00000000..a881740c --- /dev/null +++ b/scripts/rolling-update.cmd @@ -0,0 +1,16 @@ +@echo off +setlocal EnableExtensions +cd /d "%~dp0\.." + +set /a REPLICA_COUNT=0 +for /f "usebackq delims=" %%C in (`docker compose --env-file .env ps -q api`) do set /a REPLICA_COUNT+=1 +if %REPLICA_COUNT% LSS 2 exit /b 2 + +for /f "usebackq delims=" %%C in (`docker compose --env-file .env ps -q api`) do call :replace_one %%C +exit /b 0 + +:replace_one +docker stop --time 10 %1 >nul || exit /b 1 +docker rm %1 >nul || exit /b 1 +docker compose --env-file .env up -d --wait --wait-timeout 90 --no-deps --scale api=2 api >nul || exit /b 1 +exit /b 0 diff --git a/scripts/rolling-update.sh b/scripts/rolling-update.sh new file mode 100644 index 00000000..17a6c19c --- /dev/null +++ b/scripts/rolling-update.sh @@ -0,0 +1,22 @@ +#!/bin/sh +set -eu + +SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +PROJECT_DIR=$(dirname -- "$SCRIPT_DIR") +cd "$PROJECT_DIR" + +original_ids=$(docker compose --env-file .env ps -q api) +count=$(printf '%s\n' "$original_ids" | sed '/^$/d' | wc -l | tr -d ' ') +if [ "$count" -lt 2 ]; then + printf '%s\n' 'Rolling update requires at least two API replicas' >&2 + exit 2 +fi + +for container_id in $original_ids; do + # Replace exactly one original replica and wait for the replacement before + # touching the next one. Named volumes and state stores are not changed. + docker stop --time 10 "$container_id" >/dev/null + docker rm "$container_id" >/dev/null + docker compose --env-file .env up -d --wait --wait-timeout 90 \ + --no-deps --scale api=2 api >/dev/null +done diff --git a/scripts/stop-one.cmd b/scripts/stop-one.cmd new file mode 100644 index 00000000..1137fb8b --- /dev/null +++ b/scripts/stop-one.cmd @@ -0,0 +1,26 @@ +@echo off +setlocal EnableExtensions EnableDelayedExpansion + +if "%TARGET_INSTANCE_ID%"=="" exit /b 2 +cd /d "%~dp0\.." +if not defined ENV_FILE set "ENV_FILE=.env" + +set "TARGET_CONTAINER=" +set /a MATCHES=0 +for /f "usebackq delims=" %%C in (`docker compose --env-file "%ENV_FILE%" ps -q api`) do ( + set "CONTAINER_ID=%%C" + set "SHORT_ID=!CONTAINER_ID:~0,12!" + set "HOSTNAME_VALUE=" + for /f "usebackq delims=" %%H in (`docker inspect --format "{{.Config.Hostname}}" %%C`) do set "HOSTNAME_VALUE=%%H" + if "!HOSTNAME_VALUE!"=="%TARGET_INSTANCE_ID%" ( + set "TARGET_CONTAINER=%%C" + set /a MATCHES+=1 + ) else if "!SHORT_ID!"=="%TARGET_INSTANCE_ID%" ( + set "TARGET_CONTAINER=%%C" + set /a MATCHES+=1 + ) +) + +if not "!MATCHES!"=="1" exit /b 2 +docker stop --time 5 "!TARGET_CONTAINER!" >nul +exit /b %ERRORLEVEL% diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100644 index 00000000..19370e19 --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,29 @@ +#!/bin/sh +set -eu + +: "${TARGET_INSTANCE_ID:?test provides target API instance alias}" + +SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +PROJECT_DIR=$(dirname -- "$SCRIPT_DIR") +cd "$PROJECT_DIR" +: "${ENV_FILE:=.env}" + +target="" +matches=0 +for container_id in $(docker compose --env-file "$ENV_FILE" ps -q api); do + hostname=$(docker inspect --format '{{.Config.Hostname}}' "$container_id") + short_id=$(printf '%s' "$container_id" | cut -c1-12) + if [ "$TARGET_INSTANCE_ID" = "$hostname" ] || [ "$TARGET_INSTANCE_ID" = "$short_id" ]; then + target=$container_id + matches=$((matches + 1)) + fi +done + +if [ "$matches" -ne 1 ]; then + printf '%s\n' "Expected one API replica for X-Instance-Id, found $matches" >&2 + exit 2 +fi + +# Five seconds keeps the operator hook below the test's ten-second budget while +# still delivering SIGTERM and allowing Spring's graceful shutdown phase. +docker stop --time 5 "$target" >/dev/null diff --git a/scripts/swarm-lab-down.ps1 b/scripts/swarm-lab-down.ps1 new file mode 100644 index 00000000..e894742b --- /dev/null +++ b/scripts/swarm-lab-down.ps1 @@ -0,0 +1,19 @@ +$ErrorActionPreference = 'Continue' +if (Test-Path variable:PSNativeCommandUseErrorActionPreference) { + $PSNativeCommandUseErrorActionPreference = $false +} + +$nodes = @('hla-swarm-manager', 'hla-swarm-worker1', 'hla-swarm-worker2', 'hla-swarm-registry') +foreach ($node in $nodes) { + $existing = (& docker ps --all --filter "name=^/${node}$" --format '{{.Names}}') + if ($existing -eq $node) { + docker rm --force $node | Out-Null + if ($LASTEXITCODE -ne 0) { throw "Cannot remove $node" } + } +} +$existingNetwork = (& docker network ls --filter 'name=^hla-swarm-underlay$' --format '{{.Name}}') +if ($existingNetwork -eq 'hla-swarm-underlay') { + docker network rm hla-swarm-underlay | Out-Null + if ($LASTEXITCODE -ne 0) { throw 'Cannot remove hla-swarm-underlay' } +} +Write-Output 'Removed the disposable three-node Swarm lab and its nested volumes.' diff --git a/scripts/swarm-lab-up.ps1 b/scripts/swarm-lab-up.ps1 new file mode 100644 index 00000000..51ca1601 --- /dev/null +++ b/scripts/swarm-lab-up.ps1 @@ -0,0 +1,171 @@ +$ErrorActionPreference = 'Continue' +if (Test-Path variable:PSNativeCommandUseErrorActionPreference) { + $PSNativeCommandUseErrorActionPreference = $false +} + +$projectDir = Split-Path -Parent $PSScriptRoot +Set-Location $projectDir + +$manager = 'hla-swarm-manager' +$nodes = @($manager, 'hla-swarm-worker1', 'hla-swarm-worker2') +$network = 'hla-swarm-underlay' +$registry = 'hla-swarm-registry' + +function Invoke-Checked { + param([Parameter(ValueFromRemainingArguments = $true)][string[]]$Command) + $executable = $Command[0] + $arguments = if ($Command.Length -gt 1) { + $Command[1..($Command.Length - 1)] + } else { + @() + } + & $executable @arguments + if ($LASTEXITCODE -ne 0) { + throw "Command failed: $($Command -join ' ')" + } +} + +function Wait-InnerDocker([string]$Node) { + $deadline = (Get-Date).AddSeconds(90) + do { + & docker exec $Node docker info *> $null + if ($LASTEXITCODE -eq 0) { return } + Start-Sleep -Seconds 2 + } while ((Get-Date) -lt $deadline) + throw "Docker daemon did not start in $Node" +} + +function Wait-Service([string]$Service, [string]$Expected, [int]$Seconds = 180) { + $deadline = (Get-Date).AddSeconds($Seconds) + do { + $replicas = (& docker exec $manager docker service ls ` + --filter "name=$Service" --format '{{.Replicas}}' 2>$null | Select-Object -First 1) + if ($replicas -like "$Expected*") { return } + Start-Sleep -Seconds 2 + } while ((Get-Date) -lt $deadline) + throw "Service $Service did not reach $Expected replicas" +} + +foreach ($node in $nodes) { + $existing = (& docker ps --all --filter "name=^/${node}$" --format '{{.Names}}') + if ($existing -eq $node) { + throw "Container $node already exists. Run scripts/swarm-lab-down.ps1 first." + } +} +$existingRegistry = (& docker ps --all --filter "name=^/${registry}$" --format '{{.Names}}') +if ($existingRegistry -eq $registry) { + throw "Container $registry already exists. Run scripts/swarm-lab-down.ps1 first." +} + +$envValues = @{} +Get-Content -LiteralPath '.env' | ForEach-Object { + if ($_ -match '^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$') { + $envValues[$matches[1]] = $matches[2].Trim('"', "'") + } +} +$password = $envValues['DATABASE_PASSWORD'] +if ([string]::IsNullOrWhiteSpace($password)) { throw 'DATABASE_PASSWORD is missing from .env' } +$database = if ($envValues['DATABASE_NAME']) { $envValues['DATABASE_NAME'] } else { 'messenger' } +$user = if ($envValues['DATABASE_USER']) { $envValues['DATABASE_USER'] } else { 'messenger' } +$minioRootUser = $envValues['MINIO_ROOT_USER'] +$minioRootPassword = $envValues['MINIO_ROOT_PASSWORD'] +$s3AccessKey = $envValues['S3_ACCESS_KEY_ID'] +$s3SecretKey = $envValues['S3_SECRET_ACCESS_KEY'] +$s3Bucket = if ($envValues['S3_BUCKET']) { $envValues['S3_BUCKET'] } else { 'messenger-attachments' } +$s3Region = if ($envValues['S3_REGION']) { $envValues['S3_REGION'] } else { 'us-east-1' } +foreach ($required in @{ + MINIO_ROOT_USER = $minioRootUser + MINIO_ROOT_PASSWORD = $minioRootPassword + S3_ACCESS_KEY_ID = $s3AccessKey + S3_SECRET_ACCESS_KEY = $s3SecretKey +}.GetEnumerator()) { + if ([string]::IsNullOrWhiteSpace($required.Value)) { throw "$($required.Key) is missing from .env" } +} + +$existingNetwork = (& docker network ls --filter "name=^${network}$" --format '{{.Name}}') +if ($existingNetwork -ne $network) { Invoke-Checked docker network create $network } + +Invoke-Checked docker run --detach --name $registry --hostname $registry ` + --network $network --publish 127.0.0.1:15000:5000 registry:2 + +Invoke-Checked docker run --privileged --detach --name $manager --hostname $manager ` + --network $network --publish 127.0.0.1:18080:8080 ` + --volume "${projectDir}:/project:ro" --env DOCKER_TLS_CERTDIR= docker:28-dind ` + --storage-driver=overlay2 --insecure-registry=${registry}:5000 +foreach ($worker in $nodes[1..2]) { + Invoke-Checked docker run --privileged --detach --name $worker --hostname $worker ` + --network $network --env DOCKER_TLS_CERTDIR= docker:28-dind ` + --storage-driver=overlay2 --insecure-registry=${registry}:5000 +} +foreach ($node in $nodes) { Wait-InnerDocker $node } + +$managerIp = (& docker inspect --format ` + '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $manager).Trim() +Invoke-Checked docker exec $manager docker swarm init --advertise-addr $managerIp +$token = (& docker exec $manager docker swarm join-token --quiet worker).Trim() +foreach ($worker in $nodes[1..2]) { + Invoke-Checked docker exec $worker docker swarm join --token $token "$managerIp`:2377" +} +Invoke-Checked docker exec $manager docker node update ` + --label-add hla.state=true --label-add hla.lb=true $manager + +Invoke-Checked docker compose --env-file .env build api +Invoke-Checked docker tag hla-lab4-api:local localhost:15000/hla-lab4-api:swarm +Invoke-Checked docker build --file swarm/nginx.Dockerfile ` + --tag localhost:15000/hla-lab4-nginx:swarm . +Invoke-Checked docker push localhost:15000/hla-lab4-api:swarm +Invoke-Checked docker push localhost:15000/hla-lab4-nginx:swarm + +Invoke-Checked docker exec --env "DATABASE_PASSWORD=$password" ` + --env "DATABASE_NAME=$database" --env "DATABASE_USER=$user" ` + --env "MINIO_ROOT_USER=$minioRootUser" --env "MINIO_ROOT_PASSWORD=$minioRootPassword" ` + --env "S3_ACCESS_KEY_ID=$s3AccessKey" --env "S3_SECRET_ACCESS_KEY=$s3SecretKey" ` + --env "S3_BUCKET=$s3Bucket" ` + $manager docker stack deploy --compose-file /project/swarm/stack.state.yaml hla-state +Wait-Service 'hla-state_postgres' '1/1' +Wait-Service 'hla-state_redis' '1/1' +Wait-Service 'hla-state_minio' '1/1' + +$deadline = (Get-Date).AddSeconds(180) +do { + $minioInitState = (& docker exec $manager docker service ps hla-state_minio-init ` + --no-trunc --format '{{.CurrentState}}' | Select-Object -First 1) + if ($minioInitState -like 'Complete*') { break } + Start-Sleep -Seconds 2 +} while ((Get-Date) -lt $deadline) +if ($minioInitState -notlike 'Complete*') { throw 'MinIO bucket bootstrap did not complete' } + +Invoke-Checked docker exec $manager docker service create --name hla-migrate ` + --mode replicated-job --replicas 1 --max-concurrent 1 ` + --network hla-state_backend --constraint node.labels.hla.state==true ` + --restart-condition on-failure --restart-delay 3s ` + --limit-cpu 0.75 --limit-memory 768M ` + --env "DATABASE_URL=jdbc:postgresql://hla-state_postgres:5432/$database" ` + --env "DATABASE_USER=$user" --env "DATABASE_PASSWORD=$password" ` + --env FLYWAY_ENABLED=true --env MIGRATE_ONLY=true ` + --env SPRING_MAIN_WEB_APPLICATION_TYPE=none ` + --env "S3_ENDPOINT=http://hla-state_minio:9000" ` + --env "S3_BUCKET=$s3Bucket" --env "S3_REGION=$s3Region" ` + --env "S3_ACCESS_KEY_ID=$s3AccessKey" --env "S3_SECRET_ACCESS_KEY=$s3SecretKey" ` + hla-swarm-registry:5000/hla-lab4-api:swarm +$deadline = (Get-Date).AddSeconds(180) +do { + $state = (& docker exec $manager docker service ps hla-migrate ` + --no-trunc --format '{{.CurrentState}}' | Select-Object -First 1) + if ($state -like 'Complete*') { break } + Start-Sleep -Seconds 2 +} while ((Get-Date) -lt $deadline) +if ($state -notlike 'Complete*') { throw 'Migration job did not complete' } +Invoke-Checked docker exec $manager docker service rm hla-migrate + +Invoke-Checked docker exec --env "DATABASE_PASSWORD=$password" ` + --env "DATABASE_NAME=$database" --env "DATABASE_USER=$user" ` + --env "S3_BUCKET=$s3Bucket" --env "S3_REGION=$s3Region" ` + --env "S3_ACCESS_KEY_ID=$s3AccessKey" --env "S3_SECRET_ACCESS_KEY=$s3SecretKey" ` + $manager docker stack deploy --compose-file /project/swarm/stack.app.yaml hla-app +Wait-Service 'hla-app_api' '2/2' +Wait-Service 'hla-app_nginx' '1/1' + +Write-Output 'Swarm lab is ready at http://localhost:18080' +Invoke-Checked docker exec $manager docker node ls +Invoke-Checked docker exec $manager docker service ps hla-app_api diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 00000000..d8f971ad --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'mtusi-messenger' diff --git a/src/main/java/com/example/mtusi_messenger/MtusiMessengerApplication.java b/src/main/java/com/example/mtusi_messenger/MtusiMessengerApplication.java new file mode 100644 index 00000000..4e0eb367 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/MtusiMessengerApplication.java @@ -0,0 +1,20 @@ +package com.example.mtusi_messenger; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.scheduling.annotation.EnableScheduling; + +@SpringBootApplication +@EnableScheduling +public class MtusiMessengerApplication { + + public static void main(String[] args) { + ConfigurableApplicationContext context = SpringApplication.run( + MtusiMessengerApplication.class, args); + if (Boolean.parseBoolean(System.getenv("MIGRATE_ONLY"))) { + System.exit(SpringApplication.exit(context)); + } + } + +} diff --git a/src/main/java/com/example/mtusi_messenger/cache/UserCache.java b/src/main/java/com/example/mtusi_messenger/cache/UserCache.java new file mode 100644 index 00000000..04ad8036 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/cache/UserCache.java @@ -0,0 +1,83 @@ +package com.example.mtusi_messenger.cache; + +import com.example.mtusi_messenger.model.User; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessException; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Component; + +import java.time.Duration; +import java.util.Optional; +import java.util.UUID; + +@Component +public class UserCache { + private static final Logger log = LoggerFactory.getLogger(UserCache.class); + private static final String KEY_PREFIX = "messenger:user:"; + + private final StringRedisTemplate redis; + private final ObjectMapper mapper; + private final Duration ttl; + + public UserCache( + StringRedisTemplate redis, + ObjectMapper mapper, + @Value("${messenger.cache.user-ttl-seconds:300}") long ttlSeconds + ) { + if (ttlSeconds <= 0) { + throw new IllegalArgumentException("User cache TTL must be positive"); + } + this.redis = redis; + this.mapper = mapper; + this.ttl = Duration.ofSeconds(ttlSeconds); + } + + public Optional find(UUID userId) { + try { + String value = redis.opsForValue().get(key(userId)); + if (value == null) { + return Optional.empty(); + } + User cachedUser = mapper.readValue(value, User.class); + if (cachedUser == null) { + log.warn("Ignoring null Redis user cache entry for {}", userId); + evict(userId); + return Optional.empty(); + } + return Optional.of(cachedUser); + } catch (DataAccessException e) { + log.warn("Redis user cache is unavailable; using PostgreSQL fallback"); + return Optional.empty(); + } catch (JsonProcessingException e) { + log.warn("Ignoring malformed Redis user cache entry for {}", userId); + evict(userId); + return Optional.empty(); + } + } + + public void put(User user) { + try { + redis.opsForValue().set(key(user.id()), mapper.writeValueAsString(user), ttl); + } catch (DataAccessException e) { + log.warn("Redis user cache is unavailable; user was not cached"); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Cannot serialize user cache entry", e); + } + } + + public void evict(UUID userId) { + try { + redis.delete(key(userId)); + } catch (DataAccessException e) { + log.warn("Redis user cache is unavailable; cache eviction was skipped"); + } + } + + private String key(UUID userId) { + return KEY_PREFIX + userId; + } +} diff --git a/src/main/java/com/example/mtusi_messenger/config/JacksonConfig.java b/src/main/java/com/example/mtusi_messenger/config/JacksonConfig.java new file mode 100644 index 00000000..568a65e2 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/config/JacksonConfig.java @@ -0,0 +1,28 @@ +package com.example.mtusi_messenger.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.boot.jackson.autoconfigure.JsonMapperBuilderCustomizer; + +import tools.jackson.databind.cfg.CoercionAction; +import tools.jackson.databind.cfg.CoercionInputShape; +import tools.jackson.databind.type.LogicalType; + +@Configuration +public class JacksonConfig { + + @Bean + JsonMapperBuilderCustomizer strictStringTypes() { + return builder -> builder.withCoercionConfig( + LogicalType.Textual, + config -> { + config.setCoercion( + CoercionInputShape.Integer, CoercionAction.Fail); + config.setCoercion( + CoercionInputShape.Float, CoercionAction.Fail); + config.setCoercion( + CoercionInputShape.Boolean, CoercionAction.Fail); + } + ); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/mtusi_messenger/config/OpenApiConfig.java b/src/main/java/com/example/mtusi_messenger/config/OpenApiConfig.java new file mode 100644 index 00000000..14cc24f6 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/config/OpenApiConfig.java @@ -0,0 +1,21 @@ +package com.example.mtusi_messenger.config; + + +import io.swagger.v3.oas.annotations.enums.SecuritySchemeType; +import io.swagger.v3.oas.annotations.security.SecurityScheme; +import org.springframework.context.annotation.Configuration; + +@SecurityScheme( + name = "basicAuth", + type = SecuritySchemeType.HTTP, + scheme = "basic" +) +@SecurityScheme( + name = "bearerAuth", + type = SecuritySchemeType.HTTP, + scheme = "bearer", + bearerFormat = "opaque session token" +) +@Configuration +public class OpenApiConfig { +} diff --git a/src/main/java/com/example/mtusi_messenger/config/PasswordConfig.java b/src/main/java/com/example/mtusi_messenger/config/PasswordConfig.java new file mode 100644 index 00000000..98436f17 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/config/PasswordConfig.java @@ -0,0 +1,14 @@ +package com.example.mtusi_messenger.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.crypto.argon2.Argon2PasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class PasswordConfig { + @Bean + PasswordEncoder passwordEncoder() { + return Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8(); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/config/SecurityConfig.java b/src/main/java/com/example/mtusi_messenger/config/SecurityConfig.java new file mode 100644 index 00000000..f2b9ae41 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/config/SecurityConfig.java @@ -0,0 +1,107 @@ +package com.example.mtusi_messenger.config; + +import com.example.mtusi_messenger.security.ApiAuthenticationFilter; +import com.example.mtusi_messenger.security.DatabaseAuthenticationProvider; +import com.example.mtusi_messenger.security.RestAuthenticationEntryPoint; +import com.example.mtusi_messenger.service.AuthenticationService; +import com.example.mtusi_messenger.web.ReadinessGuardFilter; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.ProviderManager; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.AnonymousAuthenticationFilter; + +@Configuration +@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) +public class SecurityConfig { + @Bean + AuthenticationManager authenticationManager(DatabaseAuthenticationProvider provider) { + return new ProviderManager(provider); + } + + @Bean + RestAuthenticationEntryPoint basicAuthenticationEntryPoint(ObjectMapper mapper) { + return new RestAuthenticationEntryPoint( + mapper, + "Basic realm=\"messenger\", charset=\"UTF-8\""); + } + + @Bean + RestAuthenticationEntryPoint bearerAuthenticationEntryPoint(ObjectMapper mapper) { + return new RestAuthenticationEntryPoint(mapper, "Bearer realm=\"messenger\""); + } + + @Bean + ApiAuthenticationFilter apiAuthenticationFilter( + AuthenticationManager authenticationManager, + AuthenticationService authenticationService, + @Qualifier("basicAuthenticationEntryPoint") RestAuthenticationEntryPoint basicAuthenticationEntryPoint, + @Qualifier("bearerAuthenticationEntryPoint") RestAuthenticationEntryPoint bearerAuthenticationEntryPoint + ) { + return new ApiAuthenticationFilter( + authenticationManager, + authenticationService, + basicAuthenticationEntryPoint, + bearerAuthenticationEntryPoint); + } + + @Bean + FilterRegistrationBean disableServletFilterRegistration( + ApiAuthenticationFilter filter + ) { + var registration = new FilterRegistrationBean<>(filter); + registration.setEnabled(false); + return registration; + } + + @Bean + FilterRegistrationBean disableReadinessGuardServletRegistration( + ReadinessGuardFilter filter + ) { + var registration = new FilterRegistrationBean<>(filter); + registration.setEnabled(false); + return registration; + } + + @Bean + SecurityFilterChain securityFilterChain( + HttpSecurity http, + ApiAuthenticationFilter apiAuthenticationFilter, + ReadinessGuardFilter readinessGuardFilter, + @Qualifier("bearerAuthenticationEntryPoint") RestAuthenticationEntryPoint bearerAuthenticationEntryPoint + ) throws Exception { + http + .csrf(csrf -> csrf.disable()) + .formLogin(form -> form.disable()) + .httpBasic(basic -> basic.disable()) + .logout(logout -> logout.disable()) + .requestCache(cache -> cache.disable()) + .sessionManagement(session -> session + .sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .exceptionHandling(errors -> errors + .authenticationEntryPoint(bearerAuthenticationEntryPoint)) + .authorizeHttpRequests(authorize -> authorize + .requestMatchers(HttpMethod.GET, "/health/**").permitAll() + .requestMatchers( + "/swagger-ui.html", + "/swagger-ui/**", + "/v3/api-docs/**" + ).permitAll() + .requestMatchers(HttpMethod.POST, "/api/v1/users").permitAll() + .anyRequest().authenticated()) + // Refuse business traffic before authentication touches storage. + // Nginx retries this 503 on another peer and passively excludes + // the refusing replica according to max_fails/fail_timeout. + .addFilterBefore(readinessGuardFilter, AnonymousAuthenticationFilter.class) + .addFilterAfter(apiAuthenticationFilter, ReadinessGuardFilter.class); + return http.build(); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/config/WebConfig.java b/src/main/java/com/example/mtusi_messenger/config/WebConfig.java new file mode 100644 index 00000000..ac26bb39 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/config/WebConfig.java @@ -0,0 +1,19 @@ +package com.example.mtusi_messenger.config; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.json.JsonMapper; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class WebConfig { + @Bean + ObjectMapper objectMapper() { + return JsonMapper.builder().findAndAddModules() + .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true) + .build(); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/controller/AttachmentController.java b/src/main/java/com/example/mtusi_messenger/controller/AttachmentController.java new file mode 100644 index 00000000..9d5a116b --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/controller/AttachmentController.java @@ -0,0 +1,78 @@ +package com.example.mtusi_messenger.controller; + +import com.example.mtusi_messenger.dto.AttachmentResponse; +import com.example.mtusi_messenger.exception.ApiExceptions; +import com.example.mtusi_messenger.model.Attachment; +import com.example.mtusi_messenger.security.SessionPrincipal; +import com.example.mtusi_messenger.service.AttachmentService; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ContentDisposition; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.UUID; + +import static com.example.mtusi_messenger.service.UuidValidator.parse; + +@RequiredArgsConstructor +@RestController +@RequestMapping("/api/v1") +@SecurityRequirement(name = "bearerAuth") +public class AttachmentController { + private final AttachmentService attachments; + + @PostMapping(value = "/chats/{chatId}/attachments", + consumes = {"image/png", "image/jpeg"}, + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity upload( + @AuthenticationPrincipal SessionPrincipal principal, + @PathVariable String chatId, + @RequestParam String filename, + @RequestHeader(HttpHeaders.CONTENT_TYPE) String contentType, + HttpServletRequest request + ) throws IOException { + Attachment attachment = attachments.upload(parse(chatId), principal.user().id(), filename, + contentType, request.getContentLengthLong(), request.getInputStream()); + return ResponseEntity.status(HttpStatus.CREATED).body(AttachmentResponse.from(attachment)); + } + + @GetMapping("/attachments/{attachmentId}") + public AttachmentResponse metadata( + @AuthenticationPrincipal SessionPrincipal principal, + @PathVariable String attachmentId + ) { + return AttachmentResponse.from(attachments.getAccessible(parse(attachmentId), principal.user().id())); + } + + @GetMapping("/attachments/{attachmentId}/content") + public ResponseEntity download( + @AuthenticationPrincipal SessionPrincipal principal, + @PathVariable String attachmentId, + @RequestParam(defaultValue = "original") String variant + ) { + if (!"original".equals(variant)) { + throw ApiExceptions.invalid("Unsupported attachment variant"); + } + AttachmentService.Download download = attachments.download(parse(attachmentId), principal.user().id()); + return ResponseEntity.ok() + .contentType(MediaType.parseMediaType(download.attachment().contentType())) + .contentLength(download.bytes().length) + .header(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.inline() + .filename(download.attachment().filename(), StandardCharsets.UTF_8).build().toString()) + .body(download.bytes()); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/controller/ChatController.java b/src/main/java/com/example/mtusi_messenger/controller/ChatController.java new file mode 100644 index 00000000..ff02c9bf --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/controller/ChatController.java @@ -0,0 +1,83 @@ +package com.example.mtusi_messenger.controller; + +import com.example.mtusi_messenger.exception.ApiExceptions; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.*; +import com.example.mtusi_messenger.dto.*; +import com.example.mtusi_messenger.model.Chat; +import com.example.mtusi_messenger.service.ChatService; +import com.example.mtusi_messenger.security.SessionPrincipal; +import java.util.List; +import java.util.UUID; + +import static com.example.mtusi_messenger.service.UuidValidator.parse; + +@RestController +@RequestMapping("/api/v1/chats") +@SecurityRequirement(name = "bearerAuth") +@RequiredArgsConstructor +public class ChatController { + + private final ChatService chats; + + @PostMapping + public ResponseEntity create(@AuthenticationPrincipal SessionPrincipal principal, + @Valid @RequestBody CreateChatRequest body + ) { + UUID userId = principal.user().id(); + Chat c = chats.create(body, userId); + return ResponseEntity.status(HttpStatus.CREATED).body(ChatResponse.from(c)); + } + + @GetMapping + public ChatPageResponse list(@AuthenticationPrincipal SessionPrincipal principal, + @RequestParam(required = false) String limit, + @RequestParam(required = false) String cursor + ) { + UUID userId = principal.user().id(); + int parsedLimit = validateLimit(limit); + validateCursorPresence(cursor); + List page = chats.page(userId, parsedLimit, cursor); + boolean hasNext = page.size() > parsedLimit; + if (hasNext) page = page.subList(0, parsedLimit); + return new ChatPageResponse(page.stream().map(ChatResponse::from).toList(), page.isEmpty() ? null : + chats.nextCursor(userId, page.get(page.size() - 1), hasNext)); + } + + @GetMapping("/{chatId}") + public ChatResponse get(@AuthenticationPrincipal SessionPrincipal principal, + @PathVariable String chatId + ) { + UUID userId = principal.user().id(); + return ChatResponse.from(chats.getAccessible(parse(chatId), userId)); + } + + private static int validateLimit(String limit) { + if (limit == null) { + return 50; + } + if (!limit.matches("[0-9]+")) { + throw ApiExceptions.invalid("Invalid limit"); + } + try { + int value = Integer.parseInt(limit); + + if (value < 1 || value > 100) { + throw ApiExceptions.invalid("Invalid limit"); + } + + return value; + } catch (NumberFormatException ex) { + throw ApiExceptions.invalid("Invalid limit"); + } + } + + private static void validateCursorPresence(String c) { + if (c != null && c.isBlank()) throw ApiExceptions.invalid("Invalid cursor"); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/controller/HealthController.java b/src/main/java/com/example/mtusi_messenger/controller/HealthController.java new file mode 100644 index 00000000..e4bfec30 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/controller/HealthController.java @@ -0,0 +1,32 @@ +package com.example.mtusi_messenger.controller; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import com.example.mtusi_messenger.dto.HealthResponse; +import com.example.mtusi_messenger.exception.ApiExceptions; +import com.example.mtusi_messenger.service.ReadinessService; + +@RestController +public class HealthController { + private final ReadinessService readiness; + + public HealthController(ReadinessService readiness) { + this.readiness = readiness; + } + + @GetMapping("/health/live") + public ResponseEntity live() { + return ResponseEntity.ok(new HealthResponse("ok")); + } + + @GetMapping("/health/ready") + public ResponseEntity ready() { + // Always probe dependencies, even after a failure, so a restored schema + // can move this process back to ACCEPTING_TRAFFIC without a restart. + if (!readiness.probeDependencies() || !readiness.acceptsBusinessTraffic()) { + throw ApiExceptions.unavailable("Application is not accepting traffic"); + } + return ResponseEntity.ok(new HealthResponse("ok")); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/controller/MessageController.java b/src/main/java/com/example/mtusi_messenger/controller/MessageController.java new file mode 100644 index 00000000..e26c4cb2 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/controller/MessageController.java @@ -0,0 +1,79 @@ +package com.example.mtusi_messenger.controller; + +import com.example.mtusi_messenger.exception.ApiExceptions; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.*; +import com.example.mtusi_messenger.dto.*; +import com.example.mtusi_messenger.model.Message; +import com.example.mtusi_messenger.service.MessageService; +import com.example.mtusi_messenger.security.SessionPrincipal; +import java.util.List; +import java.util.UUID; + +import static com.example.mtusi_messenger.service.UuidValidator.parse; + +@RequiredArgsConstructor +@RestController +@RequestMapping("/api/v1/chats/{chatId}/messages") +@SecurityRequirement(name = "bearerAuth") +public class MessageController { + private static final String IDEMPOTENCY_KEY_PATTERN = "[A-Za-z0-9._:-]{1,128}"; + private final MessageService messages; + + @PostMapping + public ResponseEntity create(@AuthenticationPrincipal SessionPrincipal principal, + @PathVariable String chatId, + @RequestHeader(name = "Idempotency-Key", required = false) String idempotencyKey, + @Valid @RequestBody CreateMessageRequest body + ) { + if (idempotencyKey == null || !idempotencyKey.matches(IDEMPOTENCY_KEY_PATTERN)) { + throw ApiExceptions.invalid("Invalid or missing Idempotency-Key"); + } + UUID userId = principal.user().id(); + UUID parsedChatId = parse(chatId); + Message m = messages.create(parsedChatId, userId, body, idempotencyKey); + return ResponseEntity.status(HttpStatus.CREATED).body(MessageResponse.from(m)); + } + + @GetMapping + public MessagePageResponse list(@AuthenticationPrincipal SessionPrincipal principal, + @PathVariable String chatId, + @RequestParam(required = false) String limit, + @RequestParam(required=false) String cursor + ) { + UUID userId = principal.user().id(); + UUID parsedChatId = parse(chatId); + int parsedLimit = validateLimit(limit); + if (cursor != null && cursor.isBlank()) throw ApiExceptions.invalid("Invalid cursor"); + List page = messages.page(parsedChatId, userId, parsedLimit, cursor); + boolean hasNext = page.size() > parsedLimit; if (hasNext) page = page.subList(0, parsedLimit); + return new MessagePageResponse(page.stream().map(MessageResponse::from).toList(), + page.isEmpty() ? null : messages.nextCursor(parsedChatId, page.get(page.size()-1), hasNext)); + } + + private static int validateLimit(String limit) { + if (limit == null) { + return 50; + } + if (!limit.matches("[0-9]+")) { + throw ApiExceptions.invalid("Invalid limit"); + } + try { + int value = Integer.parseInt(limit); + + if (value < 1 || value > 100) { + throw ApiExceptions.invalid("Invalid limit"); + } + + return value; + } catch (NumberFormatException ex) { + throw ApiExceptions.invalid("Invalid limit"); + } + } + +} diff --git a/src/main/java/com/example/mtusi_messenger/controller/SessionController.java b/src/main/java/com/example/mtusi_messenger/controller/SessionController.java new file mode 100644 index 00000000..f79528f3 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/controller/SessionController.java @@ -0,0 +1,41 @@ +package com.example.mtusi_messenger.controller; + +import com.example.mtusi_messenger.dto.SessionResponse; +import com.example.mtusi_messenger.dto.UserResponse; +import com.example.mtusi_messenger.service.AuthenticationService; +import com.example.mtusi_messenger.model.User; +import com.example.mtusi_messenger.security.SessionPrincipal; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/v1/auth/sessions") +@RequiredArgsConstructor +public class SessionController { + private final AuthenticationService authentication; + + @PostMapping + @SecurityRequirement(name = "basicAuth") + public ResponseEntity create(@AuthenticationPrincipal User user) { + var issued = authentication.issueSession(user); + return ResponseEntity.status(HttpStatus.CREATED).body(new SessionResponse( + issued.token(), + "Bearer", + issued.expiresAt(), + UserResponse.from(issued.user()))); + } + + @DeleteMapping("/current") + @SecurityRequirement(name = "bearerAuth") + public ResponseEntity revoke(@AuthenticationPrincipal SessionPrincipal principal) { + authentication.revoke(principal); + return ResponseEntity.noContent().build(); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/controller/UserController.java b/src/main/java/com/example/mtusi_messenger/controller/UserController.java new file mode 100644 index 00000000..0d2d9cf6 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/controller/UserController.java @@ -0,0 +1,32 @@ +package com.example.mtusi_messenger.controller; + +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.*; +import com.example.mtusi_messenger.dto.*; +import com.example.mtusi_messenger.service.UserService; +import com.example.mtusi_messenger.security.SessionPrincipal; + +@RestController +@RequestMapping("/api/v1/users") +@RequiredArgsConstructor +public class UserController { + + private final UserService users; + + @PostMapping + public ResponseEntity create(@Valid @RequestBody CreateUserRequest request) { + var user = users.create(request); + return ResponseEntity.status(HttpStatus.CREATED).body(UserResponse.from(user)); + } + + @GetMapping("/me") + @SecurityRequirement(name = "bearerAuth") + public UserResponse me(@AuthenticationPrincipal SessionPrincipal principal) { + return UserResponse.from(principal.user()); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/dto/AttachmentResponse.java b/src/main/java/com/example/mtusi_messenger/dto/AttachmentResponse.java new file mode 100644 index 00000000..01a551b0 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/AttachmentResponse.java @@ -0,0 +1,36 @@ +package com.example.mtusi_messenger.dto; + +import com.example.mtusi_messenger.model.Attachment; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public record AttachmentResponse(UUID id, + UUID chat_id, + UUID owner_id, + String filename, + String content_type, + long size_bytes, + String sha256, + String status, + List variants, + String error_code, + Instant created_at, + Instant updated_at) { + public static AttachmentResponse from(Attachment attachment) { + return new AttachmentResponse( + attachment.id(), + attachment.chatId(), + attachment.ownerId(), + attachment.filename(), + attachment.contentType(), + attachment.sizeBytes(), + attachment.sha256(), + "ready", + List.of(), + null, + attachment.createdAt(), + attachment.updatedAt()); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/dto/ChatPageResponse.java b/src/main/java/com/example/mtusi_messenger/dto/ChatPageResponse.java new file mode 100644 index 00000000..e1d54bf2 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/ChatPageResponse.java @@ -0,0 +1,8 @@ +package com.example.mtusi_messenger.dto; + +import java.util.List; + +public record ChatPageResponse( + List items, + String next_cursor +) {} diff --git a/src/main/java/com/example/mtusi_messenger/dto/ChatResponse.java b/src/main/java/com/example/mtusi_messenger/dto/ChatResponse.java new file mode 100644 index 00000000..96b2abb4 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/ChatResponse.java @@ -0,0 +1,18 @@ +package com.example.mtusi_messenger.dto; + +import com.example.mtusi_messenger.model.Chat; +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public record ChatResponse(UUID id, + String title, + List member_ids, + Instant created_at) { + public static ChatResponse from(Chat c) { + return new ChatResponse( + c.id(), + c.title(), + c.memberIds(), + c.createdAt()); } +} diff --git a/src/main/java/com/example/mtusi_messenger/dto/CreateChatRequest.java b/src/main/java/com/example/mtusi_messenger/dto/CreateChatRequest.java new file mode 100644 index 00000000..3f792346 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/CreateChatRequest.java @@ -0,0 +1,19 @@ +package com.example.mtusi_messenger.dto; + +import com.example.mtusi_messenger.web.NotUnicodeBlank; +import com.example.mtusi_messenger.web.UnicodeSize; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.Size; +import java.util.List; +import java.util.UUID; + +public record CreateChatRequest( + @NotUnicodeBlank + @UnicodeSize(min = 1, max = 100) + String title, + + @NotEmpty + @Size(min = 1, max = 100) + List member_ids +) {} diff --git a/src/main/java/com/example/mtusi_messenger/dto/CreateMessageRequest.java b/src/main/java/com/example/mtusi_messenger/dto/CreateMessageRequest.java new file mode 100644 index 00000000..202f9116 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/CreateMessageRequest.java @@ -0,0 +1,31 @@ +package com.example.mtusi_messenger.dto; + +import com.example.mtusi_messenger.web.UnicodeSize; +import jakarta.validation.constraints.AssertTrue; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; + +import java.util.HashSet; +import java.util.List; +import java.util.UUID; + +public record CreateMessageRequest( + @NotNull @UnicodeSize(max = 4000) String text, + @Size(max = 10) List attachment_ids +) { + public CreateMessageRequest { + attachment_ids = attachment_ids == null ? List.of() : List.copyOf(attachment_ids); + } + + @AssertTrue(message = "text or attachment_ids must be present") + public boolean isContentPresent() { + return text != null && (!text.isBlank() || !attachment_ids.isEmpty()); + } + + @AssertTrue(message = "attachment_ids must be unique and non-null") + public boolean isAttachmentIdsValid() { + return attachment_ids != null + && attachment_ids.stream().noneMatch(java.util.Objects::isNull) + && new HashSet<>(attachment_ids).size() == attachment_ids.size(); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/dto/CreateUserRequest.java b/src/main/java/com/example/mtusi_messenger/dto/CreateUserRequest.java new file mode 100644 index 00000000..6d6e5a91 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/CreateUserRequest.java @@ -0,0 +1,20 @@ +package com.example.mtusi_messenger.dto; + +import com.example.mtusi_messenger.web.NotUnicodeBlank; +import com.example.mtusi_messenger.web.UnicodeSize; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Pattern; + +public record CreateUserRequest( + @NotBlank + @Pattern(regexp = "[a-z0-9_]{3,32}") + String username, + + @NotUnicodeBlank + @UnicodeSize(min = 1, max = 100) + String display_name, + + @NotUnicodeBlank + @UnicodeSize(min = 12, max = 128) + String password +) {} diff --git a/src/main/java/com/example/mtusi_messenger/dto/ErrorResponse.java b/src/main/java/com/example/mtusi_messenger/dto/ErrorResponse.java new file mode 100644 index 00000000..4b1a2a92 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/ErrorResponse.java @@ -0,0 +1,8 @@ +package com.example.mtusi_messenger.dto; + +public record ErrorResponse(ErrorBody error) { + public record ErrorBody(String code, + String message, + String request_id) + {} +} diff --git a/src/main/java/com/example/mtusi_messenger/dto/HealthResponse.java b/src/main/java/com/example/mtusi_messenger/dto/HealthResponse.java new file mode 100644 index 00000000..9630b107 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/HealthResponse.java @@ -0,0 +1,3 @@ +package com.example.mtusi_messenger.dto; + +public record HealthResponse(String status) {} diff --git a/src/main/java/com/example/mtusi_messenger/dto/MessagePageResponse.java b/src/main/java/com/example/mtusi_messenger/dto/MessagePageResponse.java new file mode 100644 index 00000000..db72eee8 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/MessagePageResponse.java @@ -0,0 +1,8 @@ +package com.example.mtusi_messenger.dto; + +import java.util.List; + +public record MessagePageResponse( + List items, + String next_cursor +) {} diff --git a/src/main/java/com/example/mtusi_messenger/dto/MessageResponse.java b/src/main/java/com/example/mtusi_messenger/dto/MessageResponse.java new file mode 100644 index 00000000..2f59187c --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/MessageResponse.java @@ -0,0 +1,22 @@ +package com.example.mtusi_messenger.dto; + +import com.example.mtusi_messenger.model.Message; +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public record MessageResponse(UUID id, + UUID chat_id, + UUID sender_id, + String text, + Instant created_at, + List attachment_ids) { + public static MessageResponse from(Message m) { + return new MessageResponse(m.id(), + m.chatId(), + m.senderId(), + m.text(), + m.createdAt(), + m.attachmentIds()); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/dto/SessionResponse.java b/src/main/java/com/example/mtusi_messenger/dto/SessionResponse.java new file mode 100644 index 00000000..64b54f99 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/SessionResponse.java @@ -0,0 +1,10 @@ +package com.example.mtusi_messenger.dto; + +import java.time.Instant; + +public record SessionResponse( + String token, + String token_type, + Instant expires_at, + UserResponse user +) {} diff --git a/src/main/java/com/example/mtusi_messenger/dto/UserResponse.java b/src/main/java/com/example/mtusi_messenger/dto/UserResponse.java new file mode 100644 index 00000000..e84bcb71 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/UserResponse.java @@ -0,0 +1,18 @@ +package com.example.mtusi_messenger.dto; + +import com.example.mtusi_messenger.model.User; +import java.time.Instant; +import java.util.UUID; + +public record UserResponse(UUID id, + String username, + String display_name, + Instant created_at) { + public static UserResponse from(User u) { + return new UserResponse( + u.id(), + u.username(), + u.displayName(), + u.createdAt()); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/exception/ApiException.java b/src/main/java/com/example/mtusi_messenger/exception/ApiException.java new file mode 100644 index 00000000..2c07f225 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/exception/ApiException.java @@ -0,0 +1,14 @@ +package com.example.mtusi_messenger.exception; + +import org.springframework.http.HttpStatus; + +public class ApiException extends RuntimeException { + private final String code; private final HttpStatus status; private final String authenticate; + public ApiException(String code, HttpStatus status, String message) { this(code, status, message, null); } + public ApiException(String code, HttpStatus status, String message, String authenticate) { + super(message); this.code = code; this.status = status; this.authenticate = authenticate; + } + public String code() { return code; } + public HttpStatus status() { return status; } + public String authenticate() { return authenticate; } +} diff --git a/src/main/java/com/example/mtusi_messenger/exception/ApiExceptions.java b/src/main/java/com/example/mtusi_messenger/exception/ApiExceptions.java new file mode 100644 index 00000000..d7cecee4 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/exception/ApiExceptions.java @@ -0,0 +1,17 @@ +package com.example.mtusi_messenger.exception; + +import org.springframework.http.HttpStatus; + +public final class ApiExceptions { + private ApiExceptions() {} + public static ApiException invalid(String m) { return new ApiException("invalid_request", HttpStatus.BAD_REQUEST, m); } + public static ApiException unauthorized(String m) { return unauthorizedBearer(m); } + public static ApiException unauthorizedBasic(String m) { return new ApiException("unauthorized", HttpStatus.UNAUTHORIZED, m, "Basic realm=\"messenger\", charset=\"UTF-8\""); } + public static ApiException unauthorizedBearer(String m) { return new ApiException("unauthorized", HttpStatus.UNAUTHORIZED, m, "Bearer realm=\"messenger\""); } + public static ApiException notFound(String m) { return new ApiException("not_found", HttpStatus.NOT_FOUND, m); } + public static ApiException conflict(String m) { return new ApiException("conflict", HttpStatus.CONFLICT, m); } + public static ApiException payloadTooLarge(String m) { return new ApiException("payload_too_large", HttpStatus.PAYLOAD_TOO_LARGE, m); } + public static ApiException unsupportedMediaType(String m) { return new ApiException("unsupported_media_type", HttpStatus.UNSUPPORTED_MEDIA_TYPE, m); } + public static ApiException tooManyRequests(String m) { return new ApiException("too_many_requests", HttpStatus.TOO_MANY_REQUESTS, m); } + public static ApiException unavailable(String m) { return new ApiException("unavailable", HttpStatus.SERVICE_UNAVAILABLE, m); } +} diff --git a/src/main/java/com/example/mtusi_messenger/model/Attachment.java b/src/main/java/com/example/mtusi_messenger/model/Attachment.java new file mode 100644 index 00000000..b93415be --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/model/Attachment.java @@ -0,0 +1,16 @@ +package com.example.mtusi_messenger.model; + +import java.time.Instant; +import java.util.UUID; + +public record Attachment(UUID id, + UUID chatId, + UUID ownerId, + String filename, + String contentType, + long sizeBytes, + String sha256, + String objectKey, + Instant createdAt, + Instant updatedAt) { +} diff --git a/src/main/java/com/example/mtusi_messenger/model/Chat.java b/src/main/java/com/example/mtusi_messenger/model/Chat.java new file mode 100644 index 00000000..829d99e5 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/model/Chat.java @@ -0,0 +1,11 @@ +package com.example.mtusi_messenger.model; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public record Chat(UUID id, String title, List memberIds, Instant createdAt) { + public Chat { + memberIds = List.copyOf(memberIds); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/model/IdempotentMessage.java b/src/main/java/com/example/mtusi_messenger/model/IdempotentMessage.java new file mode 100644 index 00000000..424d7a33 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/model/IdempotentMessage.java @@ -0,0 +1,3 @@ +package com.example.mtusi_messenger.model; + +public record IdempotentMessage(byte[] requestHash, Message message) {} diff --git a/src/main/java/com/example/mtusi_messenger/model/Message.java b/src/main/java/com/example/mtusi_messenger/model/Message.java new file mode 100644 index 00000000..2539faaf --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/model/Message.java @@ -0,0 +1,16 @@ +package com.example.mtusi_messenger.model; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public record Message(UUID id, + UUID chatId, + UUID senderId, + String text, + Instant createdAt, + List attachmentIds) { + public Message { + attachmentIds = attachmentIds == null ? List.of() : List.copyOf(attachmentIds); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/model/MessageKey.java b/src/main/java/com/example/mtusi_messenger/model/MessageKey.java new file mode 100644 index 00000000..545fd607 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/model/MessageKey.java @@ -0,0 +1,35 @@ +package com.example.mtusi_messenger.model; + +import java.time.Instant; +import java.util.UUID; + +public record MessageKey(Instant createdAt, UUID id) + implements Comparable { + + private static int compareUuidV7(UUID a, UUID b) { + int result = Long.compareUnsigned( + a.getMostSignificantBits(), + b.getMostSignificantBits() + ); + + if (result != 0) { + return result; + } + + return Long.compareUnsigned( + a.getLeastSignificantBits(), + b.getLeastSignificantBits() + ); + } + + @Override + public int compareTo(MessageKey other) { + int result = createdAt.compareTo(other.createdAt); + + if (result != 0) { + return result; + } + + return compareUuidV7(id, other.id); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/mtusi_messenger/model/Session.java b/src/main/java/com/example/mtusi_messenger/model/Session.java new file mode 100644 index 00000000..27aa2fbe --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/model/Session.java @@ -0,0 +1,15 @@ +package com.example.mtusi_messenger.model; + +import java.time.Instant; +import java.util.UUID; + +public record Session(UUID id, UUID userId, byte[] tokenHash, Instant createdAt, Instant expiresAt) { + public Session { + tokenHash = tokenHash.clone(); + } + + @Override + public byte[] tokenHash() { + return tokenHash.clone(); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/model/User.java b/src/main/java/com/example/mtusi_messenger/model/User.java new file mode 100644 index 00000000..1fefb17c --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/model/User.java @@ -0,0 +1,6 @@ +package com.example.mtusi_messenger.model; + +import java.time.Instant; +import java.util.UUID; + +public record User(UUID id, String username, String displayName, Instant createdAt) {} diff --git a/src/main/java/com/example/mtusi_messenger/repository/AttachmentRepository.java b/src/main/java/com/example/mtusi_messenger/repository/AttachmentRepository.java new file mode 100644 index 00000000..a6b1ce32 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/AttachmentRepository.java @@ -0,0 +1,15 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.Attachment; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.Set; + +public interface AttachmentRepository { + Attachment save(Attachment attachment); + Optional findById(UUID id); + List findAllByIdsInChat(UUID chatId, List ids); + Set findAllObjectKeys(); +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/ChatRepository.java b/src/main/java/com/example/mtusi_messenger/repository/ChatRepository.java new file mode 100644 index 00000000..66085e44 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/ChatRepository.java @@ -0,0 +1,14 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.Chat; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +public interface ChatRepository { + Chat save(Chat chat); + Optional findById(UUID id); + boolean isMember(UUID chatId, UUID userId); + List findAllForUser(UUID userId); + List findPageForUser(UUID userId, UUID afterId, java.time.Instant afterCreatedAt, int limitPlusOne); +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/MessageRepository.java b/src/main/java/com/example/mtusi_messenger/repository/MessageRepository.java new file mode 100644 index 00000000..23ea4814 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/MessageRepository.java @@ -0,0 +1,18 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.Message; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +public interface MessageRepository { + Message save(Message message); + void lockIdempotencyScope(UUID userId, String method, String path, String key); + void deleteExpiredIdempotency(UUID userId, String method, String path, String key, Instant expiresBefore); + Optional findIdempotent( + UUID userId, String method, String path, String key); + void saveIdempotency(UUID userId, String method, String path, String key, + byte[] requestHash, UUID messageId, Instant createdAt); + List findPage(UUID chatId, Instant afterCreatedAt, UUID afterId, int limitPlusOne); +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/PostgresAttachmentRepository.java b/src/main/java/com/example/mtusi_messenger/repository/PostgresAttachmentRepository.java new file mode 100644 index 00000000..e56e4461 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/PostgresAttachmentRepository.java @@ -0,0 +1,82 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.Attachment; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +import java.sql.Timestamp; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.Set; +import java.util.HashSet; + +@Repository +public class PostgresAttachmentRepository implements AttachmentRepository { + private static final String COLUMNS = """ + id, chat_id, owner_id, filename, content_type, size_bytes, + sha256, object_key, created_at, updated_at + """; + private final JdbcTemplate jdbc; + + public PostgresAttachmentRepository(JdbcTemplate jdbc) { + this.jdbc = jdbc; + } + + @Override + public Attachment save(Attachment attachment) { + jdbc.update(""" + INSERT INTO attachments + (id, chat_id, owner_id, filename, content_type, size_bytes, + sha256, object_key, status, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'ready', ?, ?) + """, attachment.id(), attachment.chatId(), attachment.ownerId(), + attachment.filename(), attachment.contentType(), attachment.sizeBytes(), + attachment.sha256(), attachment.objectKey(), Timestamp.from(attachment.createdAt()), + Timestamp.from(attachment.updatedAt())); + return attachment; + } + + @Override + public Optional findById(UUID id) { + return jdbc.query("SELECT " + COLUMNS + " FROM attachments WHERE id = ?", + (rs, rowNum) -> map(rs), id).stream().findFirst(); + } + + @Override + public List findAllByIdsInChat(UUID chatId, List ids) { + if (ids.isEmpty()) { + return List.of(); + } + String placeholders = String.join(",", Collections.nCopies(ids.size(), "?")); + Object[] args = new Object[ids.size() + 1]; + args[0] = chatId; + for (int i = 0; i < ids.size(); i++) { + args[i + 1] = ids.get(i); + } + return jdbc.query("SELECT " + COLUMNS + " FROM attachments WHERE chat_id = ? AND id IN (" + + placeholders + ") AND status = 'ready'", + (rs, rowNum) -> map(rs), args); + } + + @Override + public Set findAllObjectKeys() { + return new HashSet<>(jdbc.query("SELECT object_key FROM attachments", + (rs, rowNum) -> rs.getString("object_key"))); + } + + private static Attachment map(java.sql.ResultSet rs) throws java.sql.SQLException { + return new Attachment( + rs.getObject("id", UUID.class), + rs.getObject("chat_id", UUID.class), + rs.getObject("owner_id", UUID.class), + rs.getString("filename"), + rs.getString("content_type"), + rs.getLong("size_bytes"), + rs.getString("sha256"), + rs.getString("object_key"), + rs.getTimestamp("created_at").toInstant(), + rs.getTimestamp("updated_at").toInstant()); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/PostgresChatRepository.java b/src/main/java/com/example/mtusi_messenger/repository/PostgresChatRepository.java new file mode 100644 index 00000000..17d825d7 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/PostgresChatRepository.java @@ -0,0 +1,106 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.Chat; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import java.sql.Timestamp; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Repository +public class PostgresChatRepository implements ChatRepository { + private final JdbcTemplate jdbc; + + public PostgresChatRepository(JdbcTemplate jdbc) { + this.jdbc = jdbc; + } + + @Override + @Transactional(timeout = 5) + public Chat save(Chat chat) { + jdbc.update(""" + INSERT INTO chats (id, title, created_at) + VALUES (?, ?, ?) + """, chat.id(), chat.title(), Timestamp.from(chat.createdAt())); + + for (UUID memberId : chat.memberIds()) { + jdbc.update(""" + INSERT INTO chat_members (chat_id, user_id) + VALUES (?, ?) + """, chat.id(), memberId); + } + return chat; + } + + @Override + public Optional findById(UUID id) { + return jdbc.query(""" + SELECT id, title, created_at + FROM chats + WHERE id = ? + """, (rs, rowNum) -> new ChatRow( + rs.getObject("id", UUID.class), + rs.getString("title"), + rs.getTimestamp("created_at").toInstant()), id) + .stream().findFirst() + .map(this::toChat); + } + + @Override + public boolean isMember(UUID chatId, UUID userId) { + return Boolean.TRUE.equals(jdbc.queryForObject(""" + SELECT EXISTS ( + SELECT 1 FROM chat_members + WHERE chat_id = ? AND user_id = ? + ) + """, Boolean.class, chatId, userId)); + } + + @Override + public List findAllForUser(UUID userId) { + return findPageForUser(userId, null, null, Integer.MAX_VALUE); + } + + @Override + public List findPageForUser(UUID userId, UUID afterId, Instant afterCreatedAt, int limitPlusOne) { + StringBuilder sql = new StringBuilder(""" + SELECT c.id, c.title, c.created_at + FROM chats c + JOIN chat_members cm ON cm.chat_id = c.id + WHERE cm.user_id = ? + """); + List parameters = new ArrayList<>(); + parameters.add(userId); + + if (afterCreatedAt != null) { + sql.append(" AND (c.created_at, c.id) > (?, ?) "); + parameters.add(Timestamp.from(afterCreatedAt)); + parameters.add(afterId); + } + sql.append(" ORDER BY c.created_at, c.id LIMIT ? "); + parameters.add(limitPlusOne); + + return jdbc.query(sql.toString(), (rs, rowNum) -> new ChatRow( + rs.getObject("id", UUID.class), + rs.getString("title"), + rs.getTimestamp("created_at").toInstant()), parameters.toArray()) + .stream().map(this::toChat).toList(); + } + + private Chat toChat(ChatRow row) { + List members = jdbc.queryForList(""" + SELECT user_id + FROM chat_members + WHERE chat_id = ? + ORDER BY joined_at, user_id + """, UUID.class, row.id()); + return new Chat(row.id(), row.title(), members, row.createdAt()); + } + + private record ChatRow(UUID id, String title, Instant createdAt) {} +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/PostgresMessageRepository.java b/src/main/java/com/example/mtusi_messenger/repository/PostgresMessageRepository.java new file mode 100644 index 00000000..f9c67484 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/PostgresMessageRepository.java @@ -0,0 +1,172 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.Message; +import com.example.mtusi_messenger.model.IdempotentMessage; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +import java.sql.Timestamp; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import org.springframework.jdbc.core.BatchPreparedStatementSetter; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +@Repository +public class PostgresMessageRepository implements MessageRepository { + private final JdbcTemplate jdbc; + + public PostgresMessageRepository(JdbcTemplate jdbc) { + this.jdbc = jdbc; + } + + @Override + public Message save(Message message) { + jdbc.update(""" + INSERT INTO messages (id, chat_id, sender_id, text, created_at) + VALUES (?, ?, ?, ?, ?) + """, message.id(), message.chatId(), message.senderId(), message.text(), + Timestamp.from(message.createdAt())); + if (!message.attachmentIds().isEmpty()) { + jdbc.batchUpdate(""" + INSERT INTO message_attachments + (message_id, chat_id, attachment_id, position) + VALUES (?, ?, ?, ?) + """, new BatchPreparedStatementSetter() { + @Override + public void setValues(PreparedStatement statement, int index) throws SQLException { + statement.setObject(1, message.id()); + statement.setObject(2, message.chatId()); + statement.setObject(3, message.attachmentIds().get(index)); + statement.setInt(4, index); + } + + @Override + public int getBatchSize() { + return message.attachmentIds().size(); + } + }); + } + return message; + } + + @Override + public void lockIdempotencyScope(UUID userId, String method, String path, String key) { + String scope = userId + "\n" + method + "\n" + path + "\n" + key; + jdbc.query( + "SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", + rs -> { + rs.next(); + return null; + }, + scope); + } + + @Override + public void deleteExpiredIdempotency( + UUID userId, + String method, + String path, + String key, + Instant expiresBefore + ) { + jdbc.update(""" + DELETE FROM message_idempotency + WHERE user_id = ? + AND method = ? + AND request_path = ? + AND idempotency_key = ? + AND created_at < ? + """, userId, method, path, key, Timestamp.from(expiresBefore)); + } + + @Override + public Optional findIdempotent( + UUID userId, + String method, + String path, + String key + ) { + Optional result = jdbc.query(""" + SELECT i.request_hash, + m.id, m.chat_id, m.sender_id, m.text, m.created_at + FROM message_idempotency i + JOIN messages m ON m.id = i.message_id + WHERE i.user_id = ? + AND i.method = ? + AND i.request_path = ? + AND i.idempotency_key = ? + """, (rs, rowNum) -> new IdempotentMessage( + rs.getBytes("request_hash"), + new Message( + rs.getObject("id", UUID.class), + rs.getObject("chat_id", UUID.class), + rs.getObject("sender_id", UUID.class), + rs.getString("text"), + rs.getTimestamp("created_at").toInstant(), + List.of())), + userId, method, path, key).stream().findFirst(); + return result.map(value -> new IdempotentMessage( + value.requestHash(), withAttachments(value.message()))); + } + + @Override + public void saveIdempotency( + UUID userId, + String method, + String path, + String key, + byte[] requestHash, + UUID messageId, + Instant createdAt + ) { + jdbc.update(""" + INSERT INTO message_idempotency + (user_id, method, request_path, idempotency_key, + request_hash, message_id, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?) + """, userId, method, path, key, requestHash, messageId, + Timestamp.from(createdAt)); + } + + @Override + public List findPage(UUID chatId, Instant afterCreatedAt, UUID afterId, int limitPlusOne) { + StringBuilder sql = new StringBuilder(""" + SELECT id, chat_id, sender_id, text, created_at + FROM messages + WHERE chat_id = ? + """); + List parameters = new ArrayList<>(); + parameters.add(chatId); + + if (afterCreatedAt != null) { + sql.append(" AND (created_at, id) > (?, ?) "); + parameters.add(Timestamp.from(afterCreatedAt)); + parameters.add(afterId); + } + sql.append(" ORDER BY created_at, id LIMIT ? "); + parameters.add(limitPlusOne); + + return jdbc.query(sql.toString(), (rs, rowNum) -> new Message( + rs.getObject("id", UUID.class), + rs.getObject("chat_id", UUID.class), + rs.getObject("sender_id", UUID.class), + rs.getString("text"), + rs.getTimestamp("created_at").toInstant(), + List.of()), parameters.toArray()).stream().map(this::withAttachments).toList(); + } + + private Message withAttachments(Message message) { + List attachmentIds = jdbc.query(""" + SELECT attachment_id + FROM message_attachments + WHERE message_id = ? + ORDER BY position + """, (rs, rowNum) -> rs.getObject("attachment_id", UUID.class), message.id()); + return new Message(message.id(), message.chatId(), message.senderId(), message.text(), + message.createdAt(), attachmentIds); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/PostgresSessionRepository.java b/src/main/java/com/example/mtusi_messenger/repository/PostgresSessionRepository.java new file mode 100644 index 00000000..d0b210b0 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/PostgresSessionRepository.java @@ -0,0 +1,51 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.Session; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +import java.sql.Timestamp; +import java.util.Optional; +import java.util.UUID; + +@Repository +public class PostgresSessionRepository implements SessionRepository { + private final JdbcTemplate jdbc; + + public PostgresSessionRepository(JdbcTemplate jdbc) { + this.jdbc = jdbc; + } + + @Override + public Session save(Session session) { + jdbc.update(""" + INSERT INTO sessions (id, user_id, token_hash, created_at, expires_at) + VALUES (?, ?, ?, ?, ?) + """, session.id(), session.userId(), session.tokenHash(), + Timestamp.from(session.createdAt()), Timestamp.from(session.expiresAt())); + return session; + } + + @Override + public Optional findActiveUserId(byte[] tokenHash) { + return jdbc.query(""" + SELECT user_id + FROM sessions + WHERE token_hash = ? + AND revoked_at IS NULL + AND expires_at > CURRENT_TIMESTAMP + """, (rs, rowNum) -> rs.getObject("user_id", UUID.class), tokenHash) + .stream().findFirst(); + } + + @Override + public boolean revoke(byte[] tokenHash) { + return jdbc.update(""" + UPDATE sessions + SET revoked_at = CURRENT_TIMESTAMP + WHERE token_hash = ? + AND revoked_at IS NULL + AND expires_at > CURRENT_TIMESTAMP + """, tokenHash) == 1; + } +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/PostgresUserRepository.java b/src/main/java/com/example/mtusi_messenger/repository/PostgresUserRepository.java new file mode 100644 index 00000000..e096b480 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/PostgresUserRepository.java @@ -0,0 +1,72 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.User; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +import java.sql.Timestamp; +import java.util.Optional; +import java.util.UUID; + +@Repository +public class PostgresUserRepository implements UserRepository { + private final JdbcTemplate jdbc; + + public PostgresUserRepository(JdbcTemplate jdbc) { + this.jdbc = jdbc; + } + + @Override + public User save(User user, String passwordHash) { + jdbc.update(""" + INSERT INTO users (id, username, display_name, password_hash, created_at) + VALUES (?, ?, ?, ?, ?) + """, user.id(), user.username(), user.displayName(), passwordHash, + Timestamp.from(user.createdAt())); + return user; + } + + @Override + public Optional findById(UUID id) { + return jdbc.query(""" + SELECT id, username, display_name, created_at + FROM users + WHERE id = ? + """, (rs, rowNum) -> new User( + rs.getObject("id", UUID.class), + rs.getString("username"), + rs.getString("display_name"), + rs.getTimestamp("created_at").toInstant()), id) + .stream().findFirst(); + } + + @Override + public Optional findByUsername(String username) { + return jdbc.query(""" + SELECT id, username, display_name, created_at + FROM users + WHERE username = ? + """, (rs, rowNum) -> new User( + rs.getObject("id", UUID.class), + rs.getString("username"), + rs.getString("display_name"), + rs.getTimestamp("created_at").toInstant()), username) + .stream().findFirst(); + } + + @Override + public Optional findCredentialsByUsername(String username) { + return jdbc.query(""" + SELECT id, username, display_name, password_hash, created_at + FROM users + WHERE username = ? + """, (rs, rowNum) -> new UserCredentials( + new User( + rs.getObject("id", UUID.class), + rs.getString("username"), + rs.getString("display_name"), + rs.getTimestamp("created_at").toInstant()), + rs.getString("password_hash")), username) + .stream().findFirst(); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/SessionRepository.java b/src/main/java/com/example/mtusi_messenger/repository/SessionRepository.java new file mode 100644 index 00000000..801c9cf4 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/SessionRepository.java @@ -0,0 +1,12 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.Session; + +import java.util.Optional; +import java.util.UUID; + +public interface SessionRepository { + Session save(Session session); + Optional findActiveUserId(byte[] tokenHash); + boolean revoke(byte[] tokenHash); +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/UserRepository.java b/src/main/java/com/example/mtusi_messenger/repository/UserRepository.java new file mode 100644 index 00000000..e4861960 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/UserRepository.java @@ -0,0 +1,14 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.User; +import java.util.Optional; +import java.util.UUID; + +public interface UserRepository { + User save(User user, String passwordHash); + Optional findById(UUID id); + Optional findByUsername(String username); + Optional findCredentialsByUsername(String username); + + record UserCredentials(User user, String passwordHash) {} +} diff --git a/src/main/java/com/example/mtusi_messenger/security/ApiAuthenticationFilter.java b/src/main/java/com/example/mtusi_messenger/security/ApiAuthenticationFilter.java new file mode 100644 index 00000000..213d8a35 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/security/ApiAuthenticationFilter.java @@ -0,0 +1,130 @@ +package com.example.mtusi_messenger.security; + +import com.example.mtusi_messenger.service.AuthenticationService; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Enumeration; +import java.util.List; + +public class ApiAuthenticationFilter extends OncePerRequestFilter { + private static final String AUTHORIZATION = "Authorization"; + private static final String SESSION_PATH = "/api/v1/auth/sessions"; + + private final AuthenticationManager authenticationManager; + private final AuthenticationService sessions; + private final RestAuthenticationEntryPoint basicEntryPoint; + private final RestAuthenticationEntryPoint bearerEntryPoint; + + public ApiAuthenticationFilter( + AuthenticationManager authenticationManager, + AuthenticationService sessions, + RestAuthenticationEntryPoint basicEntryPoint, + RestAuthenticationEntryPoint bearerEntryPoint + ) { + this.authenticationManager = authenticationManager; + this.sessions = sessions; + this.basicEntryPoint = basicEntryPoint; + this.bearerEntryPoint = bearerEntryPoint; + } + + @Override + protected void doFilterInternal( + HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain + ) throws ServletException, IOException { + boolean basicLogin = HttpMethod.POST.matches(request.getMethod()) + && SESSION_PATH.equals(request.getRequestURI()); + if (isPublicRequest(request) && !basicLogin) { + filterChain.doFilter(request, response); + return; + } + + try { + Authentication authentication = basicLogin + ? authenticateBasic(request) + : authenticateBearer(request); + var context = SecurityContextHolder.createEmptyContext(); + context.setAuthentication(authentication); + SecurityContextHolder.setContext(context); + filterChain.doFilter(request, response); + } catch (AuthenticationException e) { + SecurityContextHolder.clearContext(); + (basicLogin ? basicEntryPoint : bearerEntryPoint) + .commence(request, response, e); + } finally { + SecurityContextHolder.clearContext(); + } + } + + private Authentication authenticateBasic(HttpServletRequest request) { + String header = singleAuthorizationHeader(request); + if (!header.startsWith("Basic ") || header.length() == 6) { + throw new BadCredentialsException("Invalid Basic credentials"); + } + try { + byte[] decoded = Base64.getDecoder().decode(header.substring(6)); + String credentials = new String(decoded, StandardCharsets.UTF_8); + int separator = credentials.indexOf(':'); + if (separator <= 0) { + throw new BadCredentialsException("Invalid Basic credentials"); + } + return authenticationManager.authenticate( + UsernamePasswordAuthenticationToken.unauthenticated( + credentials.substring(0, separator), + credentials.substring(separator + 1))); + } catch (IllegalArgumentException e) { + throw new BadCredentialsException("Invalid Basic credentials", e); + } + } + + private Authentication authenticateBearer(HttpServletRequest request) { + String header = singleAuthorizationHeader(request); + if (!header.startsWith("Bearer ") || header.length() == 7) { + throw new BadCredentialsException("Invalid Bearer token"); + } + String token = header.substring(7); + if (!token.matches("[A-Za-z0-9_-]{43}")) { + throw new BadCredentialsException("Invalid Bearer token"); + } + SessionPrincipal principal = sessions.authenticateBearer(token); + return UsernamePasswordAuthenticationToken.authenticated(principal, null, List.of()); + } + + private String singleAuthorizationHeader(HttpServletRequest request) { + Enumeration values = request.getHeaders(AUTHORIZATION); + if (values == null || !values.hasMoreElements()) { + throw new BadCredentialsException("Authentication required"); + } + String value = values.nextElement(); + if (values.hasMoreElements()) { + throw new BadCredentialsException("Multiple Authorization headers"); + } + return value; + } + + private boolean isPublicRequest(HttpServletRequest request) { + String path = request.getRequestURI(); + return path.startsWith("/health/") + || path.equals("/swagger-ui.html") + || path.startsWith("/swagger-ui/") + || path.equals("/v3/api-docs") + || path.startsWith("/v3/api-docs/") + || (HttpMethod.POST.matches(request.getMethod()) + && "/api/v1/users".equals(path)); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/security/DatabaseAuthenticationProvider.java b/src/main/java/com/example/mtusi_messenger/security/DatabaseAuthenticationProvider.java new file mode 100644 index 00000000..0a0c04da --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/security/DatabaseAuthenticationProvider.java @@ -0,0 +1,63 @@ +package com.example.mtusi_messenger.security; + +import com.example.mtusi_messenger.repository.UserRepository; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.AuthenticationServiceException; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Component; +import org.springframework.dao.DataAccessException; + +import java.util.List; + +@Component +public class DatabaseAuthenticationProvider implements AuthenticationProvider { + private final UserRepository users; + private final PasswordEncoder passwordEncoder; + private final String dummyPasswordHash; + + public DatabaseAuthenticationProvider(UserRepository users, PasswordEncoder passwordEncoder) { + this.users = users; + this.passwordEncoder = passwordEncoder; + this.dummyPasswordHash = passwordEncoder.encode("dummy-password-used-only-for-timing"); + } + + @Override + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + String username = authentication.getName(); + String password = String.valueOf(authentication.getCredentials()); + final java.util.Optional stored; + try { + stored = users.findCredentialsByUsername(username); + } catch (DataAccessException e) { + throw new AuthenticationServiceException("Authentication database is unavailable", e); + } + String passwordHash = stored.map(UserRepository.UserCredentials::passwordHash) + .filter(hash -> hash.startsWith("$argon2")) + .orElse(dummyPasswordHash); + + boolean matches; + try { + matches = passwordEncoder.matches(password, passwordHash); + } catch (IllegalArgumentException e) { + matches = false; + } + + if (stored.isEmpty() || !matches) { + throw new BadCredentialsException("Invalid credentials"); + } + + return UsernamePasswordAuthenticationToken.authenticated( + stored.get().user(), + null, + List.of()); + } + + @Override + public boolean supports(Class authentication) { + return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/security/RestAuthenticationEntryPoint.java b/src/main/java/com/example/mtusi_messenger/security/RestAuthenticationEntryPoint.java new file mode 100644 index 00000000..4442f35c --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/security/RestAuthenticationEntryPoint.java @@ -0,0 +1,46 @@ +package com.example.mtusi_messenger.security; + +import com.example.mtusi_messenger.dto.ErrorResponse; +import com.example.mtusi_messenger.web.RequestIdFilter; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.http.MediaType; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.authentication.AuthenticationServiceException; +import org.springframework.security.web.AuthenticationEntryPoint; + +import java.io.IOException; + +public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { + private final ObjectMapper mapper; + private final String challenge; + + public RestAuthenticationEntryPoint(ObjectMapper mapper, String challenge) { + this.mapper = mapper; + this.challenge = challenge; + } + + @Override + public void commence( + HttpServletRequest request, + HttpServletResponse response, + AuthenticationException exception + ) throws IOException { + String requestId = (String) request.getAttribute(RequestIdFilter.ATTRIBUTE); + boolean unavailable = exception instanceof AuthenticationServiceException; + response.setStatus(unavailable + ? HttpServletResponse.SC_SERVICE_UNAVAILABLE + : HttpServletResponse.SC_UNAUTHORIZED); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setCharacterEncoding("UTF-8"); + if (!unavailable) { + response.setHeader("WWW-Authenticate", challenge); + } + mapper.writeValue(response.getOutputStream(), new ErrorResponse( + new ErrorResponse.ErrorBody( + unavailable ? "unavailable" : "unauthorized", + unavailable ? "Authentication service temporarily unavailable" : "Authentication required", + requestId))); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/security/SessionPrincipal.java b/src/main/java/com/example/mtusi_messenger/security/SessionPrincipal.java new file mode 100644 index 00000000..03c39516 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/security/SessionPrincipal.java @@ -0,0 +1,14 @@ +package com.example.mtusi_messenger.security; + +import com.example.mtusi_messenger.model.User; + +public record SessionPrincipal(User user, byte[] tokenHash) { + public SessionPrincipal { + tokenHash = tokenHash.clone(); + } + + @Override + public byte[] tokenHash() { + return tokenHash.clone(); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/service/AttachmentReconciler.java b/src/main/java/com/example/mtusi_messenger/service/AttachmentReconciler.java new file mode 100644 index 00000000..4e45794b --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/AttachmentReconciler.java @@ -0,0 +1,104 @@ +package com.example.mtusi_messenger.service; + +import com.example.mtusi_messenger.repository.AttachmentRepository; +import com.example.mtusi_messenger.storage.ObjectStorage; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.HashSet; +import java.util.Set; + +@Component +public class AttachmentReconciler { + private static final Logger log = LoggerFactory.getLogger(AttachmentReconciler.class); + private static final String PREFIX = "attachments/"; + private final AttachmentRepository attachments; + private final ObjectStorage storage; + private final Duration gracePeriod; + private final boolean dryRun; + private final Clock clock; + + @Autowired + public AttachmentReconciler( + AttachmentRepository attachments, + ObjectStorage storage, + @Value("${messenger.attachments.cleanup-grace-seconds:3600}") long graceSeconds, + @Value("${messenger.attachments.cleanup-dry-run:false}") boolean dryRun + ) { + this(attachments, storage, Duration.ofSeconds(graceSeconds), dryRun, Clock.systemUTC()); + } + + AttachmentReconciler(AttachmentRepository attachments, + ObjectStorage storage, + Duration gracePeriod, + boolean dryRun, + Clock clock) { + if (gracePeriod.isNegative() || gracePeriod.isZero()) { + throw new IllegalArgumentException("Attachment cleanup grace period must be positive"); + } + this.attachments = attachments; + this.storage = storage; + this.gracePeriod = gracePeriod; + this.dryRun = dryRun; + this.clock = clock; + } + + @Scheduled( + fixedDelayString = "${messenger.attachments.reconcile-interval-millis:600000}", + initialDelayString = "${messenger.attachments.reconcile-initial-delay-millis:60000}") + public void scheduledReconcile() { + try { + Report report = reconcile(); + if (report.orphanObjects() > 0 || report.missingObjects() > 0) { + log.warn("Attachment reconciliation: {} orphan, {} deleted, {} missing, dryRun={}", + report.orphanObjects(), report.deletedObjects(), report.missingObjects(), dryRun); + } + } catch (RuntimeException error) { + log.warn("Attachment reconciliation postponed: {}", error.getMessage()); + } + } + + public Report reconcile() { + Set databaseKeys = attachments.findAllObjectKeys(); + var storedObjects = storage.list(PREFIX); + Set storageKeys = new HashSet<>(); + Instant deleteBefore = clock.instant().minus(gracePeriod); + int orphans = 0; + int deleted = 0; + + for (ObjectStorage.StoredObject object : storedObjects) { + storageKeys.add(object.objectKey()); + if (!databaseKeys.contains(object.objectKey()) && object.lastModified().isBefore(deleteBefore)) { + orphans++; + if (!dryRun) { + storage.delete(object.objectKey()); + deleted++; + } + } + } + + int missing = 0; + for (String databaseKey : databaseKeys) { + if (!storageKeys.contains(databaseKey)) { + missing++; + log.error("Attachment metadata references missing object {}", databaseKey); + } + } + return new Report(databaseKeys.size(), storedObjects.size(), orphans, deleted, missing, dryRun); + } + + public record Report(int metadataObjects, + int storageObjects, + int orphanObjects, + int deletedObjects, + int missingObjects, + boolean dryRun) { + } +} diff --git a/src/main/java/com/example/mtusi_messenger/service/AttachmentService.java b/src/main/java/com/example/mtusi_messenger/service/AttachmentService.java new file mode 100644 index 00000000..83a15875 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/AttachmentService.java @@ -0,0 +1,239 @@ +package com.example.mtusi_messenger.service; + +import com.example.mtusi_messenger.exception.ApiExceptions; +import com.example.mtusi_messenger.model.Attachment; +import com.example.mtusi_messenger.repository.AttachmentRepository; +import com.example.mtusi_messenger.storage.ObjectStorage; +import com.example.mtusi_messenger.storage.ObjectStorageException; +import com.github.f4b6a3.uuid.UuidCreator; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.support.TransactionTemplate; + +import javax.imageio.ImageIO; +import javax.imageio.ImageReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.HexFormat; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + +@Service +public class AttachmentService { + private static final List ALLOWED_TYPES = List.of("image/png", "image/jpeg"); + private final AttachmentRepository attachments; + private final ChatService chats; + private final ObjectStorage storage; + private final TransactionTemplate transaction; + private final long maxUploadBytes; + private final long maxImagePixels; + private final Semaphore uploadPermits; + private final long uploadPermitWaitMillis; + + public AttachmentService( + AttachmentRepository attachments, + ChatService chats, + ObjectStorage storage, + TransactionTemplate transaction, + @Value("${messenger.attachments.max-upload-bytes:10485760}") long maxUploadBytes, + @Value("${messenger.attachments.max-image-pixels:40000000}") long maxImagePixels, + @Value("${messenger.attachments.max-concurrent-uploads:3}") int maxConcurrentUploads, + @Value("${messenger.attachments.upload-permit-wait-millis:10000}") long uploadPermitWaitMillis + ) { + this.attachments = attachments; + this.chats = chats; + this.storage = storage; + this.transaction = transaction; + this.maxUploadBytes = maxUploadBytes; + this.maxImagePixels = maxImagePixels; + if (maxConcurrentUploads < 1 || uploadPermitWaitMillis < 1) { + throw new IllegalArgumentException("Upload concurrency limits must be positive"); + } + this.uploadPermits = new Semaphore(maxConcurrentUploads, true); + this.uploadPermitWaitMillis = uploadPermitWaitMillis; + } + + public Attachment upload(UUID chatId, + UUID ownerId, + String filename, + String declaredContentType, + long declaredLength, + InputStream input) { + chats.getAccessible(chatId, ownerId); + String safeFilename = validateFilename(filename); + String contentType = normalizeContentType(declaredContentType); + if (declaredLength > maxUploadBytes) { + throw ApiExceptions.payloadTooLarge("Attachment exceeds 10 MiB"); + } + + try { + try { + if (!uploadPermits.tryAcquire(uploadPermitWaitMillis, TimeUnit.MILLISECONDS)) { + throw ApiExceptions.tooManyRequests("Upload capacity is temporarily exhausted"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw ApiExceptions.unavailable("Upload was interrupted"); + } + try { + return storeValidated(chatId, ownerId, safeFilename, contentType, input); + } finally { + uploadPermits.release(); + } + } catch (com.example.mtusi_messenger.exception.ApiException error) { + throw error; + } + } + + private Attachment storeValidated(UUID chatId, + UUID ownerId, + String safeFilename, + String contentType, + InputStream input) { + byte[] bytes = readBounded(input); + if (bytes.length == 0) { + throw ApiExceptions.unsupportedMediaType("Image is empty"); + } + validateImage(bytes, contentType); + + UUID id = UuidCreator.getTimeOrderedEpochPlus1(); + String objectKey = "attachments/" + id + "/original"; + Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS); + Attachment attachment = new Attachment(id, chatId, ownerId, safeFilename, contentType, + bytes.length, sha256(bytes), objectKey, now, now); + + storage.put(objectKey, bytes, contentType); + try { + return transaction.execute(status -> attachments.save(attachment)); + } catch (RuntimeException databaseFailure) { + try { + storage.delete(objectKey); + } catch (RuntimeException cleanupFailure) { + databaseFailure.addSuppressed(cleanupFailure); + } + throw databaseFailure; + } + } + + public Attachment getAccessible(UUID attachmentId, UUID userId) { + Attachment attachment = attachments.findById(attachmentId) + .orElseThrow(() -> ApiExceptions.notFound("Attachment not found")); + chats.getAccessible(attachment.chatId(), userId); + return attachment; + } + + public Download download(UUID attachmentId, UUID userId) { + Attachment attachment = getAccessible(attachmentId, userId); + return new Download(attachment, storage.get(attachment.objectKey())); + } + + public void validateForMessage(UUID chatId, List attachmentIds) { + if (attachmentIds.isEmpty()) { + return; + } + if (attachments.findAllByIdsInChat(chatId, attachmentIds).size() != attachmentIds.size()) { + throw ApiExceptions.notFound("Attachment not found"); + } + } + + private byte[] readBounded(InputStream input) { + try { + ByteArrayOutputStream output = new ByteArrayOutputStream( + (int) Math.min(maxUploadBytes, 1024 * 1024)); + byte[] chunk = new byte[8192]; + long total = 0; + int read; + while ((read = input.read(chunk)) != -1) { + total += read; + if (total > maxUploadBytes) { + throw ApiExceptions.payloadTooLarge("Attachment exceeds 10 MiB"); + } + output.write(chunk, 0, read); + } + return output.toByteArray(); + } catch (IOException error) { + throw ApiExceptions.invalid("Cannot read request body"); + } + } + + private void validateImage(byte[] bytes, String declaredContentType) { + ImageIO.setUseCache(false); + try (var imageInput = ImageIO.createImageInputStream(new ByteArrayInputStream(bytes))) { + if (imageInput == null) { + throw ApiExceptions.unsupportedMediaType("Invalid image"); + } + Iterator readers = ImageIO.getImageReaders(imageInput); + if (!readers.hasNext()) { + throw ApiExceptions.unsupportedMediaType("Invalid PNG/JPEG image"); + } + ImageReader reader = readers.next(); + try { + reader.setInput(imageInput, true, true); + String actualType = switch (reader.getFormatName().toLowerCase(Locale.ROOT)) { + case "png" -> "image/png"; + case "jpeg", "jpg" -> "image/jpeg"; + default -> throw ApiExceptions.unsupportedMediaType("Only PNG and JPEG are supported"); + }; + if (!actualType.equals(declaredContentType)) { + throw ApiExceptions.unsupportedMediaType("Content-Type does not match image bytes"); + } + int width = reader.getWidth(0); + int height = reader.getHeight(0); + if (width <= 0 || height <= 0) { + throw ApiExceptions.unsupportedMediaType("Invalid image dimensions"); + } + if ((long) width * height > maxImagePixels) { + throw ApiExceptions.payloadTooLarge("Image exceeds 40 million pixels"); + } + if (reader.read(0) == null) { + throw ApiExceptions.unsupportedMediaType("Image cannot be decoded"); + } + } finally { + reader.dispose(); + } + } catch (com.example.mtusi_messenger.exception.ApiException error) { + throw error; + } catch (IOException | RuntimeException error) { + throw ApiExceptions.unsupportedMediaType("Corrupted PNG/JPEG image"); + } + } + + private static String validateFilename(String filename) { + if (filename == null || filename.isBlank() || filename.length() > 255 + || filename.equals(".") || filename.equals("..") + || filename.indexOf('/') >= 0 || filename.indexOf('\\') >= 0 + || filename.codePoints().anyMatch(Character::isISOControl)) { + throw ApiExceptions.invalid("Invalid filename"); + } + return filename; + } + + private static String normalizeContentType(String contentType) { + String normalized = contentType == null ? "" : contentType.split(";", 2)[0].trim().toLowerCase(Locale.ROOT); + if (!ALLOWED_TYPES.contains(normalized)) { + throw ApiExceptions.unsupportedMediaType("Only image/png and image/jpeg are supported"); + } + return normalized; + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + public record Download(Attachment attachment, byte[] bytes) { + } +} diff --git a/src/main/java/com/example/mtusi_messenger/service/AuthenticationService.java b/src/main/java/com/example/mtusi_messenger/service/AuthenticationService.java new file mode 100644 index 00000000..42abab99 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/AuthenticationService.java @@ -0,0 +1,104 @@ +package com.example.mtusi_messenger.service; + +import com.example.mtusi_messenger.cache.UserCache; +import com.example.mtusi_messenger.model.Session; +import com.example.mtusi_messenger.model.User; +import com.example.mtusi_messenger.repository.SessionRepository; +import com.example.mtusi_messenger.repository.UserRepository; +import com.example.mtusi_messenger.security.SessionPrincipal; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessException; +import org.springframework.security.authentication.AuthenticationServiceException; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.stereotype.Service; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Base64; +import java.util.UUID; + +@Service +public class AuthenticationService { + private static final SecureRandom SECURE_RANDOM = new SecureRandom(); + + private final UserRepository users; + private final SessionRepository sessions; + private final UserCache userCache; + private final long ttlSeconds; + + public AuthenticationService( + UserRepository users, + SessionRepository sessions, + UserCache userCache, + @Value("${messenger.session.ttl-seconds:3600}") long ttlSeconds + ) { + if (ttlSeconds <= 0) { + throw new IllegalArgumentException("Session TTL must be positive"); + } + this.users = users; + this.sessions = sessions; + this.userCache = userCache; + this.ttlSeconds = ttlSeconds; + } + + public IssuedSession issueSession(User user) { + String token = newToken(); + Instant createdAt = Instant.now().truncatedTo(ChronoUnit.MICROS); + Instant expiresAt = createdAt.plusSeconds(ttlSeconds); + sessions.save(new Session( + UUID.randomUUID(), + user.id(), + hashToken(token), + createdAt, + expiresAt)); + return new IssuedSession(token, expiresAt, user); + } + + public SessionPrincipal authenticateBearer(String token) { + byte[] tokenHash = hashToken(token); + try { + UUID userId = sessions.findActiveUserId(tokenHash) + .orElseThrow(() -> new BadCredentialsException("Invalid or expired session")); + User user = userCache.find(userId).orElseGet(() -> { + User loaded = users.findById(userId) + .orElseThrow(() -> new BadCredentialsException("Invalid or expired session")); + userCache.put(loaded); + return loaded; + }); + return new SessionPrincipal(user, tokenHash); + } catch (DataAccessException e) { + throw new AuthenticationServiceException("Authentication database is unavailable", e); + } + } + + public void revoke(SessionPrincipal principal) { + try { + if (!sessions.revoke(principal.tokenHash())) { + throw new BadCredentialsException("Invalid or expired session"); + } + } catch (DataAccessException e) { + throw new AuthenticationServiceException("Authentication database is unavailable", e); + } + } + + private String newToken() { + byte[] bytes = new byte[32]; + SECURE_RANDOM.nextBytes(bytes); + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + + private byte[] hashToken(String token) { + try { + return MessageDigest.getInstance("SHA-256") + .digest(token.getBytes(StandardCharsets.US_ASCII)); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is unavailable", e); + } + } + + public record IssuedSession(String token, Instant expiresAt, User user) {} +} diff --git a/src/main/java/com/example/mtusi_messenger/service/ChatService.java b/src/main/java/com/example/mtusi_messenger/service/ChatService.java new file mode 100644 index 00000000..38eeff2d --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/ChatService.java @@ -0,0 +1,38 @@ +package com.example.mtusi_messenger.service; + +import org.springframework.stereotype.Service; +import com.example.mtusi_messenger.dto.CreateChatRequest; +import com.example.mtusi_messenger.exception.ApiExceptions; +import com.example.mtusi_messenger.model.Chat; +import com.example.mtusi_messenger.repository.ChatRepository; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.*; + +@Service +public class ChatService { + private final ChatRepository chats; private final UserService users; private final CursorService cursors; + public ChatService(ChatRepository chats, UserService users, CursorService cursors) { this.chats=chats; this.users=users; this.cursors=cursors; } + public Chat create(CreateChatRequest r, UUID caller) { + Set ids = new LinkedHashSet<>(r.member_ids()); + if (ids.size() != r.member_ids().size() || !ids.contains(caller)) throw ApiExceptions.invalid("Invalid member_ids"); + for (UUID id : ids) if (id == null || !users.exists(id)) throw ApiExceptions.invalid("Invalid member_ids"); + return chats.save(new Chat(UUID.randomUUID(), r.title(), List.copyOf(ids), + Instant.now().truncatedTo(ChronoUnit.MICROS))); + } + public Chat getAccessible(UUID chatId, UUID userId) { + users.get(userId); + if (!chats.isMember(chatId, userId)) throw ApiExceptions.notFound("Chat not found"); + return chats.findById(chatId).orElseThrow(() -> ApiExceptions.notFound("Chat not found")); + } + public List page(UUID userId, int limit, String cursor) { + CursorService.Cursor c = cursor == null ? null : cursors.decode(cursor, "chats", userId); + return chats.findPageForUser(userId, c == null ? null : c.id(), c == null ? null : c.createdAt(), limit + 1); + } + public String nextCursor(UUID userId, + Chat last, + boolean hasNext + ) { + return hasNext ? cursors.encode("chats", userId, last.createdAt(), last.id()) : null; + } +} diff --git a/src/main/java/com/example/mtusi_messenger/service/CursorService.java b/src/main/java/com/example/mtusi_messenger/service/CursorService.java new file mode 100644 index 00000000..87cd7ffb --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/CursorService.java @@ -0,0 +1,40 @@ +package com.example.mtusi_messenger.service; + +import com.example.mtusi_messenger.exception.ApiException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.stereotype.Service; +import com.example.mtusi_messenger.exception.ApiExceptions; +import java.time.Instant; +import java.util.Base64; +import java.util.UUID; + +@Service +public class CursorService { + private final ObjectMapper mapper; + public CursorService(ObjectMapper mapper) { this.mapper = mapper; } + + public String encode(String resource, UUID resourceId, Instant createdAt, UUID id) { + try { + byte[] json = mapper.writeValueAsBytes(new CursorPayload(1, resource, resourceId, createdAt.toString(), id)); + return Base64.getUrlEncoder().withoutPadding().encodeToString(json); + } catch (Exception e) { throw new IllegalStateException(e); } + } + public Cursor decode(String raw, String resource, UUID resourceId) { + if (raw == null || raw.isBlank()) throw ApiExceptions.invalid("Invalid cursor"); + try { + CursorPayload p = mapper.readValue(Base64.getUrlDecoder().decode(raw), CursorPayload.class); + if (p.v != 1 + || !resource.equals(p.resource) + || !Objects.equals(resourceId, p.resourceId) + || p.createdAt() == null + || p.createdAt().isBlank() + || p.id() == null + ) throw ApiExceptions.invalid("Invalid cursor"); + return new Cursor(Instant.parse(p.createdAt), p.id); + } catch (ApiException e) { throw e; } + catch (Exception e) { throw ApiExceptions.invalid("Invalid cursor"); } + } + public record Cursor(Instant createdAt, UUID id) {} + private record CursorPayload(int v, String resource, UUID resourceId, String createdAt, UUID id) {} + private static final class Objects { static boolean equals(Object a, Object b) { return java.util.Objects.equals(a,b); } } +} diff --git a/src/main/java/com/example/mtusi_messenger/service/MessageService.java b/src/main/java/com/example/mtusi_messenger/service/MessageService.java new file mode 100644 index 00000000..c1645533 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/MessageService.java @@ -0,0 +1,102 @@ +package com.example.mtusi_messenger.service; + +import com.github.f4b6a3.uuid.UuidCreator; +import com.example.mtusi_messenger.exception.ApiExceptions; +import com.example.mtusi_messenger.model.IdempotentMessage; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import com.example.mtusi_messenger.dto.CreateMessageRequest; +import com.example.mtusi_messenger.model.Message; +import com.example.mtusi_messenger.repository.MessageRepository; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Duration; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; + +@Service +public class MessageService { + private static final String METHOD = "POST"; + private final MessageRepository messages; + private final ChatService chats; + private final CursorService cursors; + private final AttachmentService attachments; + private final Duration idempotencyTtl; + + public MessageService( + MessageRepository messages, + ChatService chats, + CursorService cursors, + AttachmentService attachments, + @Value("${messenger.idempotency.ttl-seconds:86400}") long idempotencyTtlSeconds + ) { + if (idempotencyTtlSeconds < 86400) { + throw new IllegalArgumentException("Idempotency TTL must be at least 24 hours"); + } + this.messages = messages; + this.chats = chats; + this.cursors = cursors; + this.attachments = attachments; + this.idempotencyTtl = Duration.ofSeconds(idempotencyTtlSeconds); + } + + @Transactional + public Message create(UUID chatId, UUID senderId, CreateMessageRequest r, String idempotencyKey) { + chats.getAccessible(chatId, senderId); + attachments.validateForMessage(chatId, r.attachment_ids()); + String path = "/api/v1/chats/" + chatId + "/messages"; + byte[] requestHash = hash(r.text(), r.attachment_ids()); + Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS); + + // The transaction-scoped PostgreSQL advisory lock serializes the same + // idempotency scope across every API replica. A hash collision only + // causes harmless extra serialization; the full scope is still checked. + messages.lockIdempotencyScope(senderId, METHOD, path, idempotencyKey); + messages.deleteExpiredIdempotency( + senderId, METHOD, path, idempotencyKey, now.minus(idempotencyTtl)); + + var existing = messages.findIdempotent(senderId, METHOD, path, idempotencyKey); + if (existing.isPresent()) { + IdempotentMessage value = existing.get(); + if (!Arrays.equals(value.requestHash(), requestHash)) { + throw ApiExceptions.conflict("Idempotency-Key was already used with another request body"); + } + return value.message(); + } + + Message message = messages.save(new Message( + UuidCreator.getTimeOrderedEpochPlus1(), chatId, senderId, r.text(), now, + r.attachment_ids())); + messages.saveIdempotency( + senderId, METHOD, path, idempotencyKey, requestHash, message.id(), now); + return message; + } + + private static byte[] hash(String text, List attachmentIds) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] textBytes = text.getBytes(StandardCharsets.UTF_8); + digest.update(java.nio.ByteBuffer.allocate(Integer.BYTES).putInt(textBytes.length).array()); + digest.update(textBytes); + for (UUID id : attachmentIds) { + digest.update(java.nio.ByteBuffer.allocate(16) + .putLong(id.getMostSignificantBits()) + .putLong(id.getLeastSignificantBits()).array()); + } + return digest.digest(); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is unavailable", e); + } + } + public List page(UUID chatId, UUID userId, int limit, String cursor) { + chats.getAccessible(chatId, userId); + CursorService.Cursor c = cursor == null ? null : cursors.decode(cursor, "messages", chatId); + return messages.findPage(chatId, c == null ? null : c.createdAt(), c == null ? null : c.id(), limit + 1); + } + public String nextCursor(UUID chatId, Message last, boolean hasNext) { return hasNext ? cursors.encode("messages", chatId, last.createdAt(), last.id()) : null; } +} diff --git a/src/main/java/com/example/mtusi_messenger/service/ReadinessService.java b/src/main/java/com/example/mtusi_messenger/service/ReadinessService.java new file mode 100644 index 00000000..8e18b949 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/ReadinessService.java @@ -0,0 +1,81 @@ +package com.example.mtusi_messenger.service; + +import org.springframework.boot.availability.ApplicationAvailability; +import org.springframework.boot.availability.AvailabilityChangeEvent; +import org.springframework.boot.availability.ReadinessState; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.context.event.ContextClosedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.dao.DataAccessException; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; + +import java.util.concurrent.atomic.AtomicBoolean; + +@Service +public class ReadinessService { + private final JdbcTemplate jdbc; + private final StringRedisTemplate redis; + private final ApplicationAvailability availability; + private final ApplicationEventPublisher events; + private final AtomicBoolean dependencyUnavailable = new AtomicBoolean(false); + private final AtomicBoolean shuttingDown = new AtomicBoolean(false); + + public ReadinessService( + JdbcTemplate jdbc, + StringRedisTemplate redis, + ApplicationAvailability availability, + ApplicationEventPublisher events + ) { + this.jdbc = jdbc; + this.redis = redis; + this.availability = availability; + this.events = events; + } + + public boolean probeDependencies() { + try { + // Redis is an optional cache. Ping only warms the lazy connection; + // its failure must not make the authoritative API unavailable. + redis.execute((RedisCallback) connection -> connection.ping()); + } catch (DataAccessException ignored) { + // PostgreSQL remains the source of truth. + } + + try { + // The schema-level probe also proves that the separate lab4 migration + // completed before this replica is allowed to serve business traffic. + jdbc.queryForObject("SELECT count(*) FROM attachments", Long.class); + markDependenciesAvailable(); + return true; + } catch (DataAccessException e) { + markDependenciesUnavailable(); + return false; + } + } + + public boolean acceptsBusinessTraffic() { + return !shuttingDown.get() + && !dependencyUnavailable.get() + && availability.getReadinessState() == ReadinessState.ACCEPTING_TRAFFIC; + } + + @EventListener(ContextClosedEvent.class) + void onContextClosed() { + shuttingDown.set(true); + } + + private void markDependenciesUnavailable() { + dependencyUnavailable.set(true); + AvailabilityChangeEvent.publish(events, this, ReadinessState.REFUSING_TRAFFIC); + } + + private void markDependenciesAvailable() { + boolean recovered = dependencyUnavailable.getAndSet(false); + if (recovered && !shuttingDown.get()) { + AvailabilityChangeEvent.publish(events, this, ReadinessState.ACCEPTING_TRAFFIC); + } + } +} diff --git a/src/main/java/com/example/mtusi_messenger/service/UserService.java b/src/main/java/com/example/mtusi_messenger/service/UserService.java new file mode 100644 index 00000000..c8bed8b4 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/UserService.java @@ -0,0 +1,34 @@ +package com.example.mtusi_messenger.service; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.security.crypto.password.PasswordEncoder; +import com.example.mtusi_messenger.dto.CreateUserRequest; +import com.example.mtusi_messenger.exception.ApiExceptions; +import com.example.mtusi_messenger.model.User; +import com.example.mtusi_messenger.repository.UserRepository; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.UUID; + +@Service +@RequiredArgsConstructor +public class UserService { + private final UserRepository users; + private final PasswordEncoder passwordEncoder; + + public User create(CreateUserRequest r) { + String username = r.username(); String display = r.display_name(); + if (users.findByUsername(username).isPresent()) throw ApiExceptions.conflict("Username is already taken"); + String passwordHash = passwordEncoder.encode(r.password()); + try { + return users.save(new User(UUID.randomUUID(), username, display, + Instant.now().truncatedTo(ChronoUnit.MICROS)), passwordHash); + } catch (DuplicateKeyException e) { + throw ApiExceptions.conflict("Username is already taken"); + } + } + public User get(UUID id) { return users.findById(id).orElseThrow(() -> ApiExceptions.unauthorized("Unknown user identity")); } + public boolean exists(UUID id) { return users.findById(id).isPresent(); } +} diff --git a/src/main/java/com/example/mtusi_messenger/service/UuidValidator.java b/src/main/java/com/example/mtusi_messenger/service/UuidValidator.java new file mode 100644 index 00000000..ea292fee --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/UuidValidator.java @@ -0,0 +1,27 @@ +package com.example.mtusi_messenger.service; + +import com.example.mtusi_messenger.exception.ApiExceptions; + +import java.util.UUID; +import java.util.regex.Pattern; + +public final class UuidValidator { + + private static final Pattern UUID_PATTERN = Pattern.compile( + "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" + ); + + private UuidValidator() {} + + public static UUID parse(String value) { + if (value == null || !UUID_PATTERN.matcher(value).matches()) { + throw ApiExceptions.invalid("Invalid UUID"); + } + + try { + return UUID.fromString(value); + } catch (IllegalArgumentException e) { + throw ApiExceptions.invalid("Invalid UUID"); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/example/mtusi_messenger/storage/MinioObjectStorage.java b/src/main/java/com/example/mtusi_messenger/storage/MinioObjectStorage.java new file mode 100644 index 00000000..b50f4b4c --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/storage/MinioObjectStorage.java @@ -0,0 +1,92 @@ +package com.example.mtusi_messenger.storage; + +import io.minio.GetObjectArgs; +import io.minio.MinioClient; +import io.minio.ListObjectsArgs; +import io.minio.PutObjectArgs; +import io.minio.RemoveObjectArgs; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import okhttp3.OkHttpClient; + +import java.io.ByteArrayInputStream; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; + +@Component +public class MinioObjectStorage implements ObjectStorage { + private final MinioClient client; + private final String bucket; + + public MinioObjectStorage( + @Value("${messenger.s3.endpoint}") String endpoint, + @Value("${messenger.s3.access-key}") String accessKey, + @Value("${messenger.s3.secret-key}") String secretKey, + @Value("${messenger.s3.bucket}") String bucket, + @Value("${messenger.s3.region:us-east-1}") String region + ) { + OkHttpClient httpClient = new OkHttpClient.Builder() + .connectTimeout(Duration.ofSeconds(2)) + .readTimeout(Duration.ofSeconds(10)) + .writeTimeout(Duration.ofSeconds(10)) + .callTimeout(Duration.ofSeconds(15)) + .build(); + this.client = MinioClient.builder() + .endpoint(endpoint) + .credentials(accessKey, secretKey) + .region(region) + .httpClient(httpClient) + .build(); + this.bucket = bucket; + } + + @Override + public void put(String objectKey, byte[] bytes, String contentType) { + try (var stream = new ByteArrayInputStream(bytes)) { + client.putObject(PutObjectArgs.builder() + .bucket(bucket) + .object(objectKey) + .contentType(contentType) + .stream(stream, bytes.length, -1) + .build()); + } catch (Exception error) { + throw new ObjectStorageException("Cannot write attachment object", error); + } + } + + @Override + public byte[] get(String objectKey) { + try (var stream = client.getObject(GetObjectArgs.builder() + .bucket(bucket).object(objectKey).build())) { + return stream.readAllBytes(); + } catch (Exception error) { + throw new ObjectStorageException("Cannot read attachment object", error); + } + } + + @Override + public void delete(String objectKey) { + try { + client.removeObject(RemoveObjectArgs.builder() + .bucket(bucket).object(objectKey).build()); + } catch (Exception error) { + throw new ObjectStorageException("Cannot remove attachment object", error); + } + } + + @Override + public List list(String prefix) { + try { + List objects = new ArrayList<>(); + for (var result : client.listObjects(ListObjectsArgs.builder() + .bucket(bucket).prefix(prefix).recursive(true).build())) { + var item = result.get(); + objects.add(new StoredObject(item.objectName(), item.lastModified().toInstant(), item.size())); + } + return List.copyOf(objects); + } catch (Exception error) { + throw new ObjectStorageException("Cannot list attachment objects", error); + } + } +} diff --git a/src/main/java/com/example/mtusi_messenger/storage/ObjectStorage.java b/src/main/java/com/example/mtusi_messenger/storage/ObjectStorage.java new file mode 100644 index 00000000..bb521dd9 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/storage/ObjectStorage.java @@ -0,0 +1,14 @@ +package com.example.mtusi_messenger.storage; + +import java.time.Instant; +import java.util.List; + +public interface ObjectStorage { + void put(String objectKey, byte[] bytes, String contentType); + byte[] get(String objectKey); + void delete(String objectKey); + List list(String prefix); + + record StoredObject(String objectKey, Instant lastModified, long sizeBytes) { + } +} diff --git a/src/main/java/com/example/mtusi_messenger/storage/ObjectStorageException.java b/src/main/java/com/example/mtusi_messenger/storage/ObjectStorageException.java new file mode 100644 index 00000000..6173a46c --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/storage/ObjectStorageException.java @@ -0,0 +1,7 @@ +package com.example.mtusi_messenger.storage; + +public class ObjectStorageException extends RuntimeException { + public ObjectStorageException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/web/GlobalExceptionHandler.java b/src/main/java/com/example/mtusi_messenger/web/GlobalExceptionHandler.java new file mode 100644 index 00000000..d9209c3c --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/web/GlobalExceptionHandler.java @@ -0,0 +1,56 @@ +package com.example.mtusi_messenger.web; + +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.dao.DataAccessException; +import org.springframework.web.HttpMediaTypeNotSupportedException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; +import com.example.mtusi_messenger.dto.ErrorResponse; +import com.example.mtusi_messenger.exception.ApiException; +import com.example.mtusi_messenger.storage.ObjectStorageException; + +@RestControllerAdvice +public class GlobalExceptionHandler { + @ExceptionHandler(ApiException.class) + ResponseEntity api(ApiException e, HttpServletRequest req) { + var body = body(e.code(), e.getMessage(), req); + var builder = ResponseEntity.status(e.status()); + if (e.status() == HttpStatus.UNAUTHORIZED && e.authenticate() != null) { + builder.header("WWW-Authenticate", e.authenticate()); + } + if (e.status() == HttpStatus.TOO_MANY_REQUESTS) { + builder.header("Retry-After", "1"); + } + return builder.body(body); + } + @ExceptionHandler({MethodArgumentNotValidException.class, MethodArgumentTypeMismatchException.class, HttpMessageNotReadableException.class}) + ResponseEntity bad(Exception e, HttpServletRequest req) { return ResponseEntity.badRequest().body(body("invalid_request", "Invalid request", req)); } + @ExceptionHandler(HttpMediaTypeNotSupportedException.class) + ResponseEntity unsupported(HttpServletRequest req) { return ResponseEntity.status(415).body(body("unsupported_media_type", "Unsupported media type", req)); } + @ExceptionHandler(DataAccessException.class) + ResponseEntity unavailable(DataAccessException e, HttpServletRequest req) { + return ResponseEntity.status(503).body(body("unavailable", "Storage temporarily unavailable", req)); + } + @ExceptionHandler(ObjectStorageException.class) + ResponseEntity storageUnavailable(ObjectStorageException e, HttpServletRequest req) { + return ResponseEntity.status(503).body(body("unavailable", "Object storage temporarily unavailable", req)); + } + @ExceptionHandler(Exception.class) + ResponseEntity internal(Exception e, HttpServletRequest req) { return ResponseEntity.status(500).body(body("internal_error", "Internal server error", req)); } + private ErrorResponse body( + String code, + String message, + HttpServletRequest req + ) { + String id = (String) req.getAttribute(RequestIdFilter.ATTRIBUTE); + + return new ErrorResponse( + new ErrorResponse.ErrorBody(code, message, id) + ); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/web/InstanceIdFilter.java b/src/main/java/com/example/mtusi_messenger/web/InstanceIdFilter.java new file mode 100644 index 00000000..9c56a393 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/web/InstanceIdFilter.java @@ -0,0 +1,47 @@ +package com.example.mtusi_messenger.web; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.UUID; + +@Component +@Order(Ordered.HIGHEST_PRECEDENCE + 1) +public class InstanceIdFilter extends OncePerRequestFilter { + public static final String HEADER = "X-Instance-Id"; + private final String instanceId; + + public InstanceIdFilter() { + String configured = System.getenv("INSTANCE_ID"); + this.instanceId = configured == null || configured.isBlank() + ? localHostOrRandom() + : configured; + } + + @Override + protected void doFilterInternal( + HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain + ) throws ServletException, IOException { + response.setHeader(HEADER, instanceId); + filterChain.doFilter(request, response); + } + + private static String localHostOrRandom() { + try { + return InetAddress.getLocalHost().getHostName(); + } catch (UnknownHostException e) { + return "api-" + UUID.randomUUID(); + } + } +} diff --git a/src/main/java/com/example/mtusi_messenger/web/NotUnicodeBlank.java b/src/main/java/com/example/mtusi_messenger/web/NotUnicodeBlank.java new file mode 100644 index 00000000..a4213fc7 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/web/NotUnicodeBlank.java @@ -0,0 +1,21 @@ +package com.example.mtusi_messenger.web; + +import jakarta.validation.Constraint; +import jakarta.validation.Payload; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Documented +@Constraint(validatedBy = UnicodeBlankValidator.class) +@Target({ FIELD, PARAMETER, RECORD_COMPONENT, ANNOTATION_TYPE }) +@Retention(RUNTIME) +public @interface NotUnicodeBlank { + String message() default "must not be blank"; + Class[] groups() default {}; + Class[] payload() default {}; +} diff --git a/src/main/java/com/example/mtusi_messenger/web/ReadinessGuardFilter.java b/src/main/java/com/example/mtusi_messenger/web/ReadinessGuardFilter.java new file mode 100644 index 00000000..c69594ea --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/web/ReadinessGuardFilter.java @@ -0,0 +1,56 @@ +package com.example.mtusi_messenger.web; + +import com.example.mtusi_messenger.dto.ErrorResponse; +import com.example.mtusi_messenger.service.ReadinessService; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +@Component +public class ReadinessGuardFilter extends OncePerRequestFilter { + private final ReadinessService readiness; + private final ObjectMapper mapper; + + public ReadinessGuardFilter(ReadinessService readiness, ObjectMapper mapper) { + this.readiness = readiness; + this.mapper = mapper; + } + + @Override + protected boolean shouldNotFilter(HttpServletRequest request) { + String path = request.getRequestURI(); + return path.startsWith("/health/") + || path.equals("/swagger-ui.html") + || path.startsWith("/swagger-ui/") + || path.startsWith("/v3/api-docs/") + || path.equals("/v3/api-docs"); + } + + @Override + protected void doFilterInternal( + HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain + ) throws ServletException, IOException { + if (readiness.acceptsBusinessTraffic()) { + filterChain.doFilter(request, response); + return; + } + + response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + String requestId = (String) request.getAttribute(RequestIdFilter.ATTRIBUTE); + mapper.writeValue(response.getOutputStream(), new ErrorResponse( + new ErrorResponse.ErrorBody( + "unavailable", + "Application is not ready to serve business traffic", + requestId))); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/web/RequestIdFilter.java b/src/main/java/com/example/mtusi_messenger/web/RequestIdFilter.java new file mode 100644 index 00000000..2b991b7a --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/web/RequestIdFilter.java @@ -0,0 +1,40 @@ +package com.example.mtusi_messenger.web; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.slf4j.MDC; +import org.springframework.stereotype.Component; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.web.filter.OncePerRequestFilter; +import java.io.IOException; +import java.util.UUID; + +@Component +@Order(Ordered.HIGHEST_PRECEDENCE) +public class RequestIdFilter extends OncePerRequestFilter { + + public static final String HEADER = "X-Request-Id"; + public static final String ATTRIBUTE = "request_id"; + + @Override + protected void doFilterInternal( + HttpServletRequest req, + HttpServletResponse res, + FilterChain chain + ) throws ServletException, IOException { + + String id = UUID.randomUUID().toString(); + + req.setAttribute(ATTRIBUTE, id); + res.setHeader(HEADER, id); + + try { + chain.doFilter(req, res); + } finally { + MDC.remove(ATTRIBUTE); + } + } +} diff --git a/src/main/java/com/example/mtusi_messenger/web/UnicodeBlankValidator.java b/src/main/java/com/example/mtusi_messenger/web/UnicodeBlankValidator.java new file mode 100644 index 00000000..59893614 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/web/UnicodeBlankValidator.java @@ -0,0 +1,23 @@ +package com.example.mtusi_messenger.web; + +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; + +public class UnicodeBlankValidator + implements ConstraintValidator { + + @Override + public boolean isValid( + String value, + ConstraintValidatorContext context) { + + if (value == null || value.isEmpty()) { + return false; + } + + return value.codePoints().anyMatch(codePoint -> + !Character.isWhitespace(codePoint) + && !Character.isSpaceChar(codePoint) + ); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/web/UnicodeSize.java b/src/main/java/com/example/mtusi_messenger/web/UnicodeSize.java new file mode 100644 index 00000000..dde7ca9a --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/web/UnicodeSize.java @@ -0,0 +1,35 @@ +package com.example.mtusi_messenger.web; +import jakarta.validation.Constraint; +import jakarta.validation.Payload; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.ANNOTATION_TYPE; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.PARAMETER; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Documented +@Constraint(validatedBy = UnicodeSizeValidator.class) +@Target({ + FIELD, + METHOD, + PARAMETER, + ANNOTATION_TYPE +}) +@Retention(RUNTIME) +public @interface UnicodeSize { + + String message() default "size must be between {min} and {max} Unicode code points"; + + int min() default 0; + + int max() default Integer.MAX_VALUE; + + Class[] groups() default {}; + + Class[] payload() default {}; +} \ No newline at end of file diff --git a/src/main/java/com/example/mtusi_messenger/web/UnicodeSizeValidator.java b/src/main/java/com/example/mtusi_messenger/web/UnicodeSizeValidator.java new file mode 100644 index 00000000..f978d54d --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/web/UnicodeSizeValidator.java @@ -0,0 +1,32 @@ +package com.example.mtusi_messenger.web; + +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; + +public class UnicodeSizeValidator + implements ConstraintValidator { + + private int min; + private int max; + + @Override + public void initialize(UnicodeSize annotation) { + this.min = annotation.min(); + this.max = annotation.max(); + } + + @Override + public boolean isValid( + String value, + ConstraintValidatorContext context + ) { + if (value == null) { + return true; + } + + int codePointCount = value.codePointCount(0, value.length()); + + return codePointCount >= min + && codePointCount <= max; + } +} \ No newline at end of file diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 00000000..6a55c26a --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,77 @@ +spring: + application: + name: mtusi-messenger + + datasource: + url: ${DATABASE_URL:jdbc:postgresql://localhost:5432/messenger} + username: ${DATABASE_USER:messenger} + password: ${DATABASE_PASSWORD:messenger} + hikari: + maximum-pool-size: ${DATABASE_POOL_SIZE:10} + minimum-idle: ${DATABASE_MIN_IDLE:2} + connection-timeout: 5000 + validation-timeout: 2000 + idle-timeout: 600000 + max-lifetime: 1800000 + + data: + redis: + host: ${REDIS_HOST:localhost} + port: ${REDIS_PORT:6379} + connect-timeout: ${REDIS_CONNECT_TIMEOUT:1s} + timeout: ${REDIS_COMMAND_TIMEOUT:500ms} + lettuce: + pool: + max-active: ${REDIS_POOL_MAX_ACTIVE:8} + max-idle: ${REDIS_POOL_MAX_IDLE:8} + min-idle: ${REDIS_POOL_MIN_IDLE:0} + max-wait: ${REDIS_POOL_MAX_WAIT:500ms} + + jdbc: + template: + query-timeout: ${DATABASE_QUERY_TIMEOUT_SECONDS:5} + + transaction: + default-timeout: ${DATABASE_TRANSACTION_TIMEOUT_SECONDS:5} + + flyway: + # API replicas never race one another for migrations. Compose runs the + # same image once as the dedicated migrate service with this overridden. + enabled: ${FLYWAY_ENABLED:false} + locations: classpath:db/migration + + jackson: + deserialization: + fail-on-unknown-properties: true + + lifecycle: + timeout-per-shutdown-phase: 10s + +server: + address: ${APP_HOST:0.0.0.0} + port: ${APP_PORT:8080} + shutdown: graceful + +messenger: + storage: postgres + session: + ttl-seconds: ${SESSION_TTL_SECONDS:3600} + cache: + user-ttl-seconds: ${USER_CACHE_TTL_SECONDS:300} + idempotency: + ttl-seconds: ${IDEMPOTENCY_TTL_SECONDS:86400} + s3: + endpoint: ${S3_ENDPOINT:http://localhost:9000} + region: ${S3_REGION:us-east-1} + bucket: ${S3_BUCKET:messenger-attachments} + access-key: ${S3_ACCESS_KEY_ID:messenger-api} + secret-key: ${S3_SECRET_ACCESS_KEY:messenger-api-local-only} + attachments: + max-upload-bytes: ${MAX_UPLOAD_BYTES:10485760} + max-image-pixels: ${MAX_IMAGE_PIXELS:40000000} + max-concurrent-uploads: ${MAX_CONCURRENT_UPLOADS:3} + upload-permit-wait-millis: ${UPLOAD_PERMIT_WAIT_MILLIS:10000} + cleanup-grace-seconds: ${ATTACHMENT_CLEANUP_GRACE_SECONDS:3600} + cleanup-dry-run: ${ATTACHMENT_CLEANUP_DRY_RUN:false} + reconcile-interval-millis: ${ATTACHMENT_RECONCILE_INTERVAL_MILLIS:600000} + reconcile-initial-delay-millis: ${ATTACHMENT_RECONCILE_INITIAL_DELAY_MILLIS:60000} diff --git a/src/main/resources/db/migration/V1__create_messenger_schema.sql b/src/main/resources/db/migration/V1__create_messenger_schema.sql new file mode 100644 index 00000000..06885a1c --- /dev/null +++ b/src/main/resources/db/migration/V1__create_messenger_schema.sql @@ -0,0 +1,60 @@ +CREATE TABLE users ( + id uuid PRIMARY KEY, + username varchar(32) NOT NULL, + display_name text NOT NULL, + created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT users_username_uk UNIQUE (username), + CONSTRAINT users_username_format_chk + CHECK (username ~ '^[a-z0-9_]{3,32}$'), + CONSTRAINT users_display_name_length_chk + CHECK (char_length(display_name) BETWEEN 1 AND 100) +); + +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title text NOT NULL, + created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT chats_title_length_chk + CHECK (char_length(title) BETWEEN 1 AND 100) +); + +CREATE TABLE chat_members ( + chat_id uuid NOT NULL, + user_id uuid NOT NULL, + joined_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT chat_members_pk PRIMARY KEY (chat_id, user_id), + CONSTRAINT chat_members_chat_fk + FOREIGN KEY (chat_id) REFERENCES chats(id) ON DELETE CASCADE, + CONSTRAINT chat_members_user_fk + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE RESTRICT +); + +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL, + sender_id uuid NOT NULL, + text text NOT NULL, + created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT messages_text_length_chk + CHECK (char_length(text) BETWEEN 1 AND 4000), + CONSTRAINT messages_sender_membership_fk + FOREIGN KEY (chat_id, sender_id) + REFERENCES chat_members(chat_id, user_id) + ON DELETE RESTRICT +); + +CREATE INDEX chat_members_user_chat_idx + ON chat_members (user_id, chat_id); + +CREATE INDEX chats_created_id_idx + ON chats (created_at, id); + +CREATE INDEX messages_chat_created_id_idx + ON messages (chat_id, created_at, id); + +CREATE INDEX messages_sender_created_idx + ON messages (sender_id, created_at); diff --git a/src/main/resources/db/migration/V2__add_credentials_and_sessions.sql b/src/main/resources/db/migration/V2__add_credentials_and_sessions.sql new file mode 100644 index 00000000..d5d74279 --- /dev/null +++ b/src/main/resources/db/migration/V2__add_credentials_and_sessions.sql @@ -0,0 +1,28 @@ +ALTER TABLE users + ADD COLUMN password_hash text; + +ALTER TABLE users + ALTER COLUMN password_hash SET NOT NULL; + +CREATE TABLE sessions ( + id uuid PRIMARY KEY, + user_id uuid NOT NULL, + token_hash bytea NOT NULL, + created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, + expires_at timestamptz NOT NULL, + revoked_at timestamptz, + + CONSTRAINT sessions_user_fk + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + CONSTRAINT sessions_token_hash_uk UNIQUE (token_hash), + CONSTRAINT sessions_token_hash_length_chk + CHECK (octet_length(token_hash) = 32), + CONSTRAINT sessions_expiry_chk + CHECK (expires_at > created_at), + CONSTRAINT sessions_revocation_chk + CHECK (revoked_at IS NULL OR revoked_at >= created_at) +); + +CREATE INDEX sessions_active_expiry_idx + ON sessions (expires_at) + WHERE revoked_at IS NULL; diff --git a/src/main/resources/db/migration/V3__add_message_idempotency.sql b/src/main/resources/db/migration/V3__add_message_idempotency.sql new file mode 100644 index 00000000..dfa127ca --- /dev/null +++ b/src/main/resources/db/migration/V3__add_message_idempotency.sql @@ -0,0 +1,25 @@ +CREATE TABLE message_idempotency ( + user_id uuid NOT NULL, + method varchar(8) NOT NULL, + request_path text NOT NULL, + idempotency_key varchar(128) NOT NULL, + request_hash bytea NOT NULL, + message_id uuid NOT NULL, + created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT message_idempotency_pk + PRIMARY KEY (user_id, method, request_path, idempotency_key), + CONSTRAINT message_idempotency_user_fk + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + CONSTRAINT message_idempotency_message_fk + FOREIGN KEY (message_id) REFERENCES messages(id) ON DELETE CASCADE, + CONSTRAINT message_idempotency_method_chk + CHECK (method = 'POST'), + CONSTRAINT message_idempotency_key_format_chk + CHECK (idempotency_key ~ '^[A-Za-z0-9._:-]{1,128}$'), + CONSTRAINT message_idempotency_hash_length_chk + CHECK (octet_length(request_hash) = 32) +); + +CREATE INDEX message_idempotency_created_idx + ON message_idempotency (created_at); diff --git a/src/main/resources/db/migration/V4__add_attachments.sql b/src/main/resources/db/migration/V4__add_attachments.sql new file mode 100644 index 00000000..ca018ebf --- /dev/null +++ b/src/main/resources/db/migration/V4__add_attachments.sql @@ -0,0 +1,53 @@ +ALTER TABLE messages DROP CONSTRAINT messages_text_length_chk; +ALTER TABLE messages ADD CONSTRAINT messages_text_length_chk + CHECK (char_length(text) BETWEEN 0 AND 4000); +ALTER TABLE messages ADD CONSTRAINT messages_id_chat_uk UNIQUE (id, chat_id); + +CREATE TABLE attachments ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL, + owner_id uuid NOT NULL, + filename varchar(255) NOT NULL, + content_type varchar(32) NOT NULL, + size_bytes bigint NOT NULL, + sha256 char(64) NOT NULL, + object_key text NOT NULL, + status varchar(16) NOT NULL DEFAULT 'ready', + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + + CONSTRAINT attachments_id_chat_uk UNIQUE (id, chat_id), + CONSTRAINT attachments_object_key_uk UNIQUE (object_key), + CONSTRAINT attachments_owner_membership_fk + FOREIGN KEY (chat_id, owner_id) + REFERENCES chat_members(chat_id, user_id) ON DELETE RESTRICT, + CONSTRAINT attachments_content_type_chk + CHECK (content_type IN ('image/png', 'image/jpeg')), + CONSTRAINT attachments_size_chk + CHECK (size_bytes BETWEEN 1 AND 10485760), + CONSTRAINT attachments_sha256_chk + CHECK (sha256 ~ '^[a-f0-9]{64}$'), + CONSTRAINT attachments_status_chk CHECK (status = 'ready'), + CONSTRAINT attachments_filename_chk + CHECK (char_length(filename) BETWEEN 1 AND 255) +); + +CREATE TABLE message_attachments ( + message_id uuid NOT NULL, + chat_id uuid NOT NULL, + attachment_id uuid NOT NULL, + position smallint NOT NULL, + + CONSTRAINT message_attachments_pk PRIMARY KEY (message_id, attachment_id), + CONSTRAINT message_attachments_position_uk UNIQUE (message_id, position), + CONSTRAINT message_attachments_message_fk + FOREIGN KEY (message_id, chat_id) + REFERENCES messages(id, chat_id) ON DELETE CASCADE, + CONSTRAINT message_attachments_attachment_fk + FOREIGN KEY (attachment_id, chat_id) + REFERENCES attachments(id, chat_id) ON DELETE RESTRICT, + CONSTRAINT message_attachments_position_chk CHECK (position BETWEEN 0 AND 9) +); + +CREATE INDEX attachments_chat_created_idx ON attachments (chat_id, created_at, id); +CREATE INDEX message_attachments_attachment_idx ON message_attachments (attachment_id); diff --git a/src/test/java/com/example/mtusi_messenger/MtusiMessengerApplicationTests.java b/src/test/java/com/example/mtusi_messenger/MtusiMessengerApplicationTests.java new file mode 100644 index 00000000..6a71efe7 --- /dev/null +++ b/src/test/java/com/example/mtusi_messenger/MtusiMessengerApplicationTests.java @@ -0,0 +1,368 @@ +package com.example.mtusi_messenger; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; + +import java.util.*; + +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@SpringBootTest +@AutoConfigureMockMvc +class MtusiMessengerApplicationTests { + + private static final String USERS_URL = "/api/v1/users"; + private static final String CHATS_URL = "/api/v1/chats"; + private static final String SESSIONS_URL = "/api/v1/auth/sessions"; + private static final String TEST_PASSWORD = "correct horse battery staple"; + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + private User alice; + private User bob; + private User eve; + + @BeforeEach + void setUp() throws Exception { + String suffix = UUID.randomUUID() + .toString() + .replace("-", "") + .substring(0, 12); + + alice = registerUser("alice_" + suffix, "Alice"); + bob = registerUser("bob_" + suffix, "Bob"); + eve = registerUser("eve_" + suffix, "Eve"); + } + + @Test + void shouldReturn400WhenJsonIsMalformed() throws Exception { + mockMvc.perform(post(USERS_URL) + .contentType(MediaType.APPLICATION_JSON) + .content("{ \"username\": ")) + .andExpect(status().isBadRequest()) + .andExpect(header().exists("X-Request-Id")) + .andExpect(jsonPath("$.error.code") + .value("invalid_request")); + } + + @Test + void shouldReturn400WhenPasswordContainsOnlyWhitespace() throws Exception { + String requestBody = objectMapper.writeValueAsString( + Map.of( + "username", "blank_password_" + UUID.randomUUID().toString().substring(0, 8), + "display_name", "Blank password probe", + "password", " " + ) + ); + + mockMvc.perform(post(USERS_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isBadRequest()) + .andExpect(header().exists("X-Request-Id")) + .andExpect(jsonPath("$.error.code") + .value("invalid_request")); + } + + @Test + void shouldNotAllowNonMemberToReadChatMessages() throws Exception { + String chatId = createChat(alice, bob); + + mockMvc.perform(get(CHATS_URL + "/" + chatId + "/messages") + .header("Authorization", bearer(eve)) + .param("limit", "10")) + .andExpect(status().isNotFound()) + .andExpect(header().exists("X-Request-Id")) + .andExpect(jsonPath("$.error.code") + .value("not_found")); + } + + @Test + void shouldNotAllowNonMemberToSendMessage() throws Exception { + String chatId = createChat(alice, bob); + + String requestBody = """ + { + "text": "Hello from Eve" + } + """; + + mockMvc.perform(post(CHATS_URL + "/" + chatId + "/messages") + .header("Authorization", bearer(eve)) + .header("Idempotency-Key", UUID.randomUUID().toString()) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isNotFound()) + .andExpect(header().exists("X-Request-Id")) + .andExpect(jsonPath("$.error.code") + .value("not_found")); + } + + @Test + void shouldReturn400WhenMessageTextIsEmpty() throws Exception { + String chatId = createChat(alice, bob); + + String requestBody = """ + { + "text": "" + } + """; + + mockMvc.perform(post(CHATS_URL + "/" + chatId + "/messages") + .header("Authorization", bearer(alice)) + .header("Idempotency-Key", UUID.randomUUID().toString()) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isBadRequest()) + .andExpect(header().exists("X-Request-Id")) + .andExpect(jsonPath("$.error.code") + .value("invalid_request")); + } + + @Test + void shouldReturn400WhenMessageTextIsMissing() throws Exception { + String chatId = createChat(alice, bob); + + mockMvc.perform(post(CHATS_URL + "/" + chatId + "/messages") + .header("Authorization", bearer(alice)) + .header("Idempotency-Key", UUID.randomUUID().toString()) + .contentType(MediaType.APPLICATION_JSON) + .content("{}")) + .andExpect(status().isBadRequest()) + .andExpect(header().exists("X-Request-Id")) + .andExpect(jsonPath("$.error.code") + .value("invalid_request")); + } + + @Test + void shouldReturn409WhenUsernameAlreadyExists() throws Exception { + String requestBody = """ + { + "username": "%s", + "display_name": "Another Alice", + "password": "correct horse battery staple" + } + """.formatted(alice.username()); + + mockMvc.perform(post(USERS_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isConflict()) + .andExpect(header().exists("X-Request-Id")) + .andExpect(jsonPath("$.error.code") + .value("conflict")); + } + + @Test + void shouldReturnAllMessagesAcrossMultiplePagesWithoutDuplicates() + throws Exception { + + String chatId = createChat(alice, bob); + + int messageCount = 5; + int pageSize = 2; + int expectedPageCount = 3; + + List expectedTexts = new ArrayList<>(); + + for (int i = 1; i <= messageCount; i++) { + String text = "Message " + i; + sendMessage(chatId, alice, text); + expectedTexts.add(text); + } + + List actualIds = new ArrayList<>(); + List actualTexts = new ArrayList<>(); + + String cursor = null; + int pageCount = 0; + + while (true) { + var request = get(CHATS_URL + "/" + chatId + "/messages") + .header("Authorization", bearer(alice)) + .param("limit", String.valueOf(pageSize)); + + if (cursor != null) { + request.param("cursor", cursor); + } + + MvcResult result = mockMvc.perform(request) + .andExpect(status().isOk()) + .andExpect(header().exists("X-Request-Id")) + .andExpect(jsonPath("$.items").isArray()) + .andReturn(); + + JsonNode response = objectMapper.readTree( + result.getResponse().getContentAsString() + ); + + JsonNode items = response.get("items"); + + assertNotNull(items); + assertTrue(items.size() <= pageSize); + + for (JsonNode item : items) { + actualIds.add(item.get("id").asText()); + actualTexts.add(item.get("text").asText()); + } + + pageCount++; + + JsonNode nextCursor = response.get("next_cursor"); + + if (nextCursor.isNull()) { + break; + } + + cursor = nextCursor.asText(); + + assertFalse(cursor.isBlank(), + "next_cursor must not be blank when more pages exist"); + + assertTrue(pageCount <= messageCount, + "Pagination did not terminate"); + } + + assertEquals(expectedPageCount, pageCount); + + assertEquals(messageCount, actualIds.size()); + assertEquals(messageCount, actualTexts.size()); + + assertEquals(actualIds.size(), new HashSet<>(actualIds).size()); + + assertEquals(expectedTexts, actualTexts); + } + + @Test + void shouldIgnoreXUserIdForProtectedEndpoints() throws Exception { + mockMvc.perform(get(USERS_URL + "/me") + .header("X-User-Id", alice.id())) + .andExpect(status().isUnauthorized()) + .andExpect(header().string("WWW-Authenticate", "Bearer realm=\"messenger\"")); + } + + @Test + void shouldRevokeCurrentSession() throws Exception { + mockMvc.perform(delete(SESSIONS_URL + "/current") + .header("Authorization", bearer(alice))) + .andExpect(status().isNoContent()); + + mockMvc.perform(get(USERS_URL + "/me") + .header("Authorization", bearer(alice))) + .andExpect(status().isUnauthorized()) + .andExpect(header().string("WWW-Authenticate", "Bearer realm=\"messenger\"")); + } + + @Test + void shouldRejectWrongPasswordWithBasicChallenge() throws Exception { + String basic = Base64.getEncoder().encodeToString( + (alice.username() + ":definitely-wrong-password") + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + + mockMvc.perform(post(SESSIONS_URL) + .header("Authorization", "Basic " + basic)) + .andExpect(status().isUnauthorized()) + .andExpect(header().string( + "WWW-Authenticate", + "Basic realm=\"messenger\", charset=\"UTF-8\"")); + } + + private User registerUser(String username, String displayName) + throws Exception { + + String requestBody = objectMapper.writeValueAsString( + Map.of( + "username", username, + "display_name", displayName, + "password", TEST_PASSWORD + ) + ); + + MvcResult result = mockMvc.perform(post(USERS_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isCreated()) + .andExpect(header().exists("X-Request-Id")) + .andReturn(); + + JsonNode response = objectMapper.readTree( + result.getResponse().getContentAsString() + ); + + String basic = Base64.getEncoder().encodeToString( + (username + ":" + TEST_PASSWORD).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + MvcResult loginResult = mockMvc.perform(post(SESSIONS_URL) + .header("Authorization", "Basic " + basic)) + .andExpect(status().isCreated()) + .andReturn(); + JsonNode session = objectMapper.readTree(loginResult.getResponse().getContentAsString()); + + return new User( + response.get("id").asText(), + response.get("username").asText(), + session.get("token").asText() + ); + } + + private String createChat(User owner, User member) + throws Exception { + + String requestBody = objectMapper.writeValueAsString( + java.util.Map.of( + "title", "Test chat " + UUID.randomUUID(), + "member_ids", List.of(owner.id(), member.id()) + ) + ); + + MvcResult result = mockMvc.perform(post(CHATS_URL) + .header("Authorization", bearer(owner)) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isCreated()) + .andExpect(header().exists("X-Request-Id")) + .andReturn(); + + JsonNode response = objectMapper.readTree( + result.getResponse().getContentAsString() + ); + + return response.get("id").asText(); + } + + private void sendMessage(String chatId, User sender, String text) + throws Exception { + + String requestBody = objectMapper.writeValueAsString( + java.util.Map.of("text", text) + ); + + mockMvc.perform(post(CHATS_URL + "/" + chatId + "/messages") + .header("Authorization", bearer(sender)) + .header("Idempotency-Key", UUID.randomUUID().toString()) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isCreated()) + .andExpect(header().exists("X-Request-Id")); + } + + private static String bearer(User user) { + return "Bearer " + user.token(); + } + + private record User(String id, String username, String token) { + } +} diff --git a/src/test/java/com/example/mtusi_messenger/cache/UserCacheTest.java b/src/test/java/com/example/mtusi_messenger/cache/UserCacheTest.java new file mode 100644 index 00000000..fdc05347 --- /dev/null +++ b/src/test/java/com/example/mtusi_messenger/cache/UserCacheTest.java @@ -0,0 +1,31 @@ +package com.example.mtusi_messenger.cache; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.ValueOperations; + +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class UserCacheTest { + + @Test + void shouldEvictJsonNullAndReturnCacheMiss() { + UUID userId = UUID.randomUUID(); + String key = "messenger:user:" + userId; + StringRedisTemplate redis = mock(StringRedisTemplate.class); + @SuppressWarnings("unchecked") + ValueOperations values = mock(ValueOperations.class); + when(redis.opsForValue()).thenReturn(values); + when(values.get(key)).thenReturn("null"); + UserCache cache = new UserCache(redis, new ObjectMapper(), 300); + + assertTrue(cache.find(userId).isEmpty()); + verify(redis).delete(key); + } +} diff --git a/src/test/java/com/example/mtusi_messenger/service/AttachmentReconcilerTest.java b/src/test/java/com/example/mtusi_messenger/service/AttachmentReconcilerTest.java new file mode 100644 index 00000000..49573d28 --- /dev/null +++ b/src/test/java/com/example/mtusi_messenger/service/AttachmentReconcilerTest.java @@ -0,0 +1,75 @@ +package com.example.mtusi_messenger.service; + +import com.example.mtusi_messenger.repository.AttachmentRepository; +import com.example.mtusi_messenger.storage.ObjectStorage; +import org.junit.jupiter.api.Test; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class AttachmentReconcilerTest { + private static final Instant NOW = Instant.parse("2026-11-11T12:00:00Z"); + + @Test + void deletesOnlyOrphansOlderThanGracePeriodAndReportsMissingObjects() { + AttachmentRepository repository = mock(AttachmentRepository.class); + when(repository.findAllObjectKeys()).thenReturn(Set.of( + "attachments/present/original", "attachments/missing/original")); + FakeStorage storage = new FakeStorage(List.of( + object("attachments/present/original", NOW.minusSeconds(7200)), + object("attachments/old-orphan/original", NOW.minusSeconds(7200)), + object("attachments/fresh-orphan/original", NOW.minusSeconds(30)))); + AttachmentReconciler reconciler = new AttachmentReconciler(repository, storage, + Duration.ofHours(1), false, Clock.fixed(NOW, ZoneOffset.UTC)); + + AttachmentReconciler.Report report = reconciler.reconcile(); + + assertEquals(List.of("attachments/old-orphan/original"), storage.deleted); + assertEquals(1, report.orphanObjects()); + assertEquals(1, report.deletedObjects()); + assertEquals(1, report.missingObjects()); + } + + @Test + void dryRunNeverDeletesOldOrphan() { + AttachmentRepository repository = mock(AttachmentRepository.class); + when(repository.findAllObjectKeys()).thenReturn(Set.of()); + FakeStorage storage = new FakeStorage(List.of( + object("attachments/old-orphan/original", NOW.minusSeconds(7200)))); + AttachmentReconciler reconciler = new AttachmentReconciler(repository, storage, + Duration.ofHours(1), true, Clock.fixed(NOW, ZoneOffset.UTC)); + + AttachmentReconciler.Report report = reconciler.reconcile(); + + assertEquals(List.of(), storage.deleted); + assertEquals(1, report.orphanObjects()); + assertEquals(0, report.deletedObjects()); + } + + private static ObjectStorage.StoredObject object(String key, Instant modified) { + return new ObjectStorage.StoredObject(key, modified, 100); + } + + private static final class FakeStorage implements ObjectStorage { + private final List objects; + private final List deleted = new ArrayList<>(); + + private FakeStorage(List objects) { + this.objects = objects; + } + + @Override public void put(String objectKey, byte[] bytes, String contentType) { } + @Override public byte[] get(String objectKey) { return new byte[0]; } + @Override public void delete(String objectKey) { deleted.add(objectKey); } + @Override public List list(String prefix) { return objects; } + } +} diff --git a/src/test/java/com/example/mtusi_messenger/service/AttachmentServiceTest.java b/src/test/java/com/example/mtusi_messenger/service/AttachmentServiceTest.java new file mode 100644 index 00000000..8a53cb45 --- /dev/null +++ b/src/test/java/com/example/mtusi_messenger/service/AttachmentServiceTest.java @@ -0,0 +1,194 @@ +package com.example.mtusi_messenger.service; + +import com.example.mtusi_messenger.exception.ApiException; +import com.example.mtusi_messenger.model.Attachment; +import com.example.mtusi_messenger.model.Chat; +import com.example.mtusi_messenger.repository.AttachmentRepository; +import com.example.mtusi_messenger.storage.ObjectStorage; +import com.example.mtusi_messenger.storage.ObjectStorageException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionCallback; +import org.springframework.transaction.support.TransactionTemplate; + +import java.io.ByteArrayInputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +class AttachmentServiceTest { + private final UUID chatId = UUID.randomUUID(); + private final UUID ownerId = UUID.randomUUID(); + private AttachmentRepository repository; + private ChatService chats; + private InMemoryStorage storage; + private AttachmentService service; + private byte[] png; + + @BeforeEach + void setUp() throws Exception { + repository = mock(AttachmentRepository.class); + chats = mock(ChatService.class); + storage = new InMemoryStorage(); + TransactionTemplate transaction = mock(TransactionTemplate.class); + when(transaction.execute(any())).thenAnswer(invocation -> { + @SuppressWarnings("unchecked") + TransactionCallback callback = invocation.getArgument(0); + return callback.doInTransaction(mock(TransactionStatus.class)); + }); + when(chats.getAccessible(chatId, ownerId)).thenReturn( + new Chat(chatId, "test", List.of(ownerId), Instant.now())); + when(repository.save(any())).thenAnswer(invocation -> invocation.getArgument(0)); + service = new AttachmentService(repository, chats, storage, transaction, + 10_485_760, 40_000_000, 3, 10_000); + png = Files.readAllBytes(Path.of("tests", "fixtures", "sample.png")); + } + + @Test + void uploadsValidPngUsingServerGeneratedObjectKey() { + Attachment attachment = service.upload(chatId, ownerId, "photo.png", "image/png", + png.length, new ByteArrayInputStream(png)); + + assertEquals("photo.png", attachment.filename()); + assertEquals("image/png", attachment.contentType()); + assertEquals(png.length, attachment.sizeBytes()); + assertTrue(attachment.objectKey().matches("attachments/[0-9a-f-]+/original")); + assertFalse(attachment.objectKey().contains("photo.png")); + assertArrayEquals(png, storage.objects.get(attachment.objectKey())); + verify(repository).save(attachment); + } + + @Test + void rejectsMimeSpoofingBeforeS3Write() { + ApiException error = assertThrows(ApiException.class, () -> service.upload( + chatId, ownerId, "photo.jpg", "image/jpeg", png.length, + new ByteArrayInputStream(png))); + + assertEquals(HttpStatus.UNSUPPORTED_MEDIA_TYPE, error.status()); + assertTrue(storage.objects.isEmpty()); + } + + @Test + void rejectsOversizedBodyBeforeReadingIt() { + ApiException error = assertThrows(ApiException.class, () -> service.upload( + chatId, ownerId, "photo.png", "image/png", 10_485_761, + new ByteArrayInputStream(png))); + + assertEquals(HttpStatus.PAYLOAD_TOO_LARGE, error.status()); + assertTrue(storage.objects.isEmpty()); + } + + @Test + void rejectsAttachmentFromAnotherChat() { + UUID attachmentId = UUID.randomUUID(); + when(repository.findAllByIdsInChat(chatId, List.of(attachmentId))).thenReturn(List.of()); + + ApiException error = assertThrows(ApiException.class, + () -> service.validateForMessage(chatId, List.of(attachmentId))); + + assertEquals(HttpStatus.NOT_FOUND, error.status()); + } + + @Test + void surfacesS3OutageWithoutWritingMetadata() { + storage.failure = true; + + assertThrows(ObjectStorageException.class, () -> service.upload( + chatId, ownerId, "photo.png", "image/png", png.length, + new ByteArrayInputStream(png))); + verify(repository, never()).save(any()); + } + + @Test + void interruptedRequestDoesNotCreateS3Object() { + java.io.InputStream source = new java.io.InputStream() { + private int position; + + @Override + public int read() throws IOException { + if (position >= 16_384) { + throw new IOException("client disconnected"); + } + return png[position++]; + } + }; + + ApiException error = assertThrows(ApiException.class, () -> service.upload( + chatId, ownerId, "photo.png", "image/png", -1, source)); + + assertEquals(HttpStatus.BAD_REQUEST, error.status()); + assertTrue(storage.objects.isEmpty()); + verify(repository, never()).save(any()); + } + + @Test + void databaseFailureCompensatesAlreadyWrittenS3Object() { + when(repository.save(any())).thenThrow(new IllegalStateException("database commit failed")); + + assertThrows(IllegalStateException.class, () -> service.upload( + chatId, ownerId, "photo.png", "image/png", png.length, + new ByteArrayInputStream(png))); + + assertTrue(storage.objects.isEmpty(), "compensating delete must remove the orphan"); + } + + @Test + void downloadsOnlyAfterChatAuthorization() { + Attachment attachment = new Attachment(UUID.randomUUID(), chatId, ownerId, "photo.png", + "image/png", png.length, "a".repeat(64), "attachments/key/original", + Instant.now(), Instant.now()); + when(repository.findById(attachment.id())).thenReturn(Optional.of(attachment)); + storage.objects.put(attachment.objectKey(), png); + + AttachmentService.Download download = service.download(attachment.id(), ownerId); + + verify(chats).getAccessible(chatId, ownerId); + assertArrayEquals(png, download.bytes()); + } + + private static final class InMemoryStorage implements ObjectStorage { + private final Map objects = new HashMap<>(); + private boolean failure; + + @Override + public void put(String objectKey, byte[] bytes, String contentType) { + if (failure) throw new ObjectStorageException("S3 unavailable", new IOExceptionForTest()); + objects.put(objectKey, bytes.clone()); + } + + @Override + public byte[] get(String objectKey) { + if (failure) throw new ObjectStorageException("S3 unavailable", new IOExceptionForTest()); + return objects.get(objectKey).clone(); + } + + @Override + public void delete(String objectKey) { + objects.remove(objectKey); + } + + @Override + public List list(String prefix) { + return objects.entrySet().stream() + .filter(entry -> entry.getKey().startsWith(prefix)) + .map(entry -> new StoredObject(entry.getKey(), Instant.now(), entry.getValue().length)) + .toList(); + } + } + + private static final class IOExceptionForTest extends RuntimeException { + } + +} diff --git a/src/test/java/com/example/mtusi_messenger/web/ReadinessGuardFilterTest.java b/src/test/java/com/example/mtusi_messenger/web/ReadinessGuardFilterTest.java new file mode 100644 index 00000000..a8374d13 --- /dev/null +++ b/src/test/java/com/example/mtusi_messenger/web/ReadinessGuardFilterTest.java @@ -0,0 +1,62 @@ +package com.example.mtusi_messenger.web; + +import com.example.mtusi_messenger.service.ReadinessService; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class ReadinessGuardFilterTest { + private final ReadinessService readiness = mock(ReadinessService.class); + private final ObjectMapper mapper = new ObjectMapper(); + private final ReadinessGuardFilter filter = new ReadinessGuardFilter(readiness, mapper); + + @Test + void refusingReplicaRejectsBusinessTrafficBeforeItReachesTheChain() throws Exception { + when(readiness.acceptsBusinessTraffic()).thenReturn(false); + var request = new MockHttpServletRequest("GET", "/api/v1/users/me"); + request.setAttribute(RequestIdFilter.ATTRIBUTE, "request-1"); + var response = new MockHttpServletResponse(); + var chain = new MockFilterChain(); + + filter.doFilter(request, response, chain); + + assertEquals(503, response.getStatus()); + assertNull(chain.getRequest()); + JsonNode body = mapper.readTree(response.getContentAsByteArray()); + assertEquals("unavailable", body.at("/error/code").asText()); + assertEquals("request-1", body.at("/error/request_id").asText()); + } + + @Test + void readyReplicaPassesBusinessTrafficToTheChain() throws Exception { + when(readiness.acceptsBusinessTraffic()).thenReturn(true); + var request = new MockHttpServletRequest("GET", "/api/v1/users/me"); + var response = new MockHttpServletResponse(); + var chain = new MockFilterChain(); + + filter.doFilter(request, response, chain); + + assertSame(request, chain.getRequest()); + } + + @Test + void healthProbeIsNeverBlockedByTheBusinessGuard() throws Exception { + when(readiness.acceptsBusinessTraffic()).thenReturn(false); + var request = new MockHttpServletRequest("GET", "/health/ready"); + var response = new MockHttpServletResponse(); + var chain = new MockFilterChain(); + + filter.doFilter(request, response, chain); + + assertSame(request, chain.getRequest()); + } +} diff --git a/student_tests/README.md b/student_tests/README.md new file mode 100644 index 00000000..c08c4d23 --- /dev/null +++ b/student_tests/README.md @@ -0,0 +1,18 @@ +# Student-owned tests + +This directory contains additional experiments written for this implementation. +The course-provided black-box suite remains in `tests/`; Spring tests remain in +`src/test/java`. + +- `idempotency_concurrent.py` — one key through multiple API replicas. +- `readiness_gate.py` — both replicas become unhealthy after the required + schema table disappears; readiness and business traffic must return 503, + then recover after the table is restored. +- `failover_each.py` — sequential process failover of both Compose replicas. +- `rolling_update.py` — sequential replacement under write load. +- `node_failover.py` — hard loss of one worker in the disposable three-node + Swarm lab, task relocation and confirmed-data verification. +- `lab4_negative.py` — oversized/corrupt/MIME-spoofed uploads, unsafe filename, + unknown attachment, foreign user and cross-chat binding; every user error is 4xx. +- `concurrent_upload_memory.py` — 12 simultaneous ~6.5 MiB valid PNG uploads and + aggregate API container memory sampling through `docker stats`. diff --git a/student_tests/concurrent_upload_memory.py b/student_tests/concurrent_upload_memory.py new file mode 100644 index 00000000..a268da4d --- /dev/null +++ b/student_tests/concurrent_upload_memory.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 +"""Run 10+ simultaneous valid PNG uploads and sample aggregate API container RAM.""" +import argparse +import binascii +import concurrent.futures +import json +import random +import re +import struct +import subprocess +import sys +import threading +import time +import zlib +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) +from client import Client, Failure, check, run # noqa: E402 + + +def png_chunk(kind, payload): + return (struct.pack('>I', len(payload)) + kind + payload + + struct.pack('>I', binascii.crc32(kind + payload) & 0xffffffff)) + + +def make_png(width=1800, height=1200): + rng = random.Random(20261111) + rows = bytearray() + for _ in range(height): + rows.append(0) + rows.extend(rng.randbytes(width * 3)) + return (b'\x89PNG\r\n\x1a\n' + + png_chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0)) + + png_chunk(b'IDAT', zlib.compress(bytes(rows), 1)) + + png_chunk(b'IEND', b'')) + + +def memory_bytes(value): + match = re.fullmatch(r'([0-9]+(?:\.[0-9]+)?)\s*([A-Za-z]+)', value.strip()) + if not match: + raise ValueError('unrecognized Docker memory value: ' + value) + number, unit = match.groups() + factors = {'B': 1, 'kB': 1000, 'KiB': 1024, 'MB': 1000**2, + 'MiB': 1024**2, 'GB': 1000**3, 'GiB': 1024**3} + return int(float(number) * factors[unit]) + + +def api_containers(env_file): + result = subprocess.run( + ['docker', 'compose', '--env-file', env_file, 'ps', '-q', 'api'], + cwd=ROOT, check=True, capture_output=True, text=True) + ids = [line for line in result.stdout.splitlines() if line] + check(len(ids) >= 2, 'memory experiment requires at least two API containers') + return ids + + +def sample_total_memory(container_ids): + result = subprocess.run( + ['docker', 'stats', '--no-stream', '--format', '{{.MemUsage}}', *container_ids], + check=True, capture_output=True, text=True) + usages = [] + for line in result.stdout.splitlines(): + if line.strip(): + usages.append(memory_bytes(line.split('/', 1)[0].strip())) + check(len(usages) == len(container_ids), 'docker stats did not return every API container') + return sum(usages) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--base-url', default='http://localhost:8080') + parser.add_argument('--compose-env-file', default='.env') + parser.add_argument('--concurrency', type=int, default=12) + parser.add_argument('--output', default='evidence/upload-memory.json') + args = parser.parse_args() + check(args.concurrency >= 10, 'experiment requires concurrency >= 10') + + bootstrap = Client(args.base_url, timeout=30) + alice, bob, _, chat = bootstrap.bootstrap() + payload = make_png() + check(len(payload) <= 10_485_760, 'generated PNG exceeds upload limit') + containers = api_containers(args.compose_env_file) + baseline = sample_total_memory(containers) + peak = baseline + samples = [] + stop = threading.Event() + + def monitor(): + nonlocal peak + while not stop.is_set(): + try: + current = sample_total_memory(containers) + samples.append(current) + peak = max(peak, current) + except (subprocess.SubprocessError, Failure, ValueError): + pass + stop.wait(0.1) + + barrier = threading.Barrier(args.concurrency) + + def upload(index): + client = Client(args.base_url, timeout=30) + barrier.wait(timeout=30) + path = (f"/api/v1/chats/{chat['id']}/attachments" + f"?filename=memory-{index}.png") + return client.call('POST', path, 201, actor=alice, raw=payload, + headers={'Content-Type': 'image/png'}, schema='Attachment')['json']['id'] + + monitor_thread = threading.Thread(target=monitor, daemon=True) + monitor_thread.start() + started = time.monotonic() + try: + with concurrent.futures.ThreadPoolExecutor(max_workers=args.concurrency) as pool: + ids = list(pool.map(upload, range(args.concurrency))) + finally: + stop.set() + monitor_thread.join(timeout=5) + duration = time.monotonic() - started + check(len(ids) == args.concurrency and len(set(ids)) == len(ids), + 'not every concurrent upload completed exactly once') + + result = { + 'concurrency': args.concurrency, + 'successful_uploads': len(ids), + 'payload_bytes_each': len(payload), + 'duration_seconds': round(duration, 3), + 'api_replicas': len(containers), + 'memory_samples': len(samples), + 'baseline_api_memory_bytes': baseline, + 'peak_api_memory_bytes': peak, + 'peak_increase_bytes': max(0, peak - baseline), + 'configured_max_concurrent_uploads_per_replica': 3, + 'configured_max_upload_bytes': 10_485_760, + 'configured_max_image_pixels': 40_000_000, + } + output = ROOT / args.output + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') + print(json.dumps(result, ensure_ascii=False)) + print('PASS: concurrent upload memory experiment') + + +if __name__ == '__main__': + run(main) diff --git a/student_tests/failover_each.py b/student_tests/failover_each.py new file mode 100644 index 00000000..996f072d --- /dev/null +++ b/student_tests/failover_each.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""Stop every observed API replica in turn and record recovery metrics.""" +import json +import os +from pathlib import Path +import subprocess +import sys +import time +import uuid +from urllib.parse import quote + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) +from client import Client, Failure, arguments, check, run + + +def executable(path, label): + value = Path(path).expanduser().resolve() + check(value.is_file() and os.access(value, os.X_OK), label + ' must be executable') + return value + + +def observe_instances(client, actor, attempts=60): + result = set() + for _ in range(attempts): + result.add(client.call( + 'GET', '/api/v1/users/me', actor=actor, schema='User' + )['headers']['X-Instance-Id']) + return result + + +def message_history(client, actor, chat_id): + path = '/api/v1/chats/' + chat_id + '/messages?limit=100' + result = [] + for _ in range(1000): + page = client.call( + 'GET', path, actor=actor, schema='MessagePage')['json'] + result.extend(page['items']) + if page['next_cursor'] is None: + return result + path = ('/api/v1/chats/' + chat_id + '/messages?limit=100&cursor=' + + quote(page['next_cursor'], safe='')) + raise Failure('history pagination exceeded safety bound') + + +def main(): + def configure(parser): + parser.add_argument('--action-script', required=True) + parser.add_argument('--restore-script', required=True) + parser.add_argument('--window', type=float, default=15) + parser.add_argument('--output', default=None) + args = arguments('Sequential failover of every API replica', configure) + check(5 <= args.window <= 60, 'window must be 5..60 seconds') + action = executable(args.action_script, 'action script') + restore = executable(args.restore_script, 'restore script') + client = Client(args.base_url, args.ca_file, timeout=2) + alice, bob, _, chat = client.bootstrap() + targets = sorted(observe_instances(client, alice)) + check(len(targets) >= 2, 'expected at least two API replicas') + targets = targets[:2] + summaries = [] + + for target in targets: + check(target in observe_instances(client, alice), + 'target replica is not observable before stop') + env = dict(os.environ) + env['TARGET_INSTANCE_ID'] = target + process = subprocess.Popen( + [str(action)], env=env, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + started = time.monotonic() + first_recovery = None + reads = writes = failures = 0 + confirmed = [] + key = uuid.uuid4().hex + text = 'failover-each-' + target + '-' + key + + while time.monotonic() - started < args.window: + try: + if (reads + writes) % 2 == 0: + response = client.message(alice, chat, text, key=key) + confirmed.append(response['json']) + writes += 1 + key = uuid.uuid4().hex + text = 'failover-each-' + target + '-' + key + else: + client.call('GET', '/api/v1/users/me', actor=bob, schema='User') + reads += 1 + if process.poll() == 0 and first_recovery is None: + first_recovery = time.monotonic() - started + except Failure: + failures += 1 + time.sleep(0.05) + + check(process.wait(timeout=5) == 0, 'stop-one action failed') + elapsed = time.monotonic() - started + check(first_recovery is not None and first_recovery <= 10, + 'recovery exceeded 10 seconds') + history = message_history(client, bob, chat['id']) + history_ids = {message['id'] for message in history} + check(all(message['id'] in history_ids for message in confirmed), + 'confirmed message disappeared after failover') + + summaries.append({ + 'target_instance_id': target, + 'window_seconds': round(elapsed, 3), + 'successful_reads': reads, + 'successful_writes': writes, + 'failed_attempts': failures, + 'successful_rps': round((reads + writes) / elapsed, 3), + 'first_recovery_seconds': round(first_recovery, 3), + }) + + check(subprocess.run( + [str(restore)], stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, timeout=100).returncode == 0, + 'restore action failed') + check(target in observe_instances(client, alice), + 'stopped replica did not return after restore') + + report = { + 'scenario': 'sequential failover of each API replica', + 'replicas': len(targets), + 'results': summaries, + } + output = json.dumps(report, ensure_ascii=False, indent=2) + if args.output: + destination = Path(args.output) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text(output + '\n', encoding='utf-8') + print(output) + + +if __name__ == '__main__': + run(main) diff --git a/student_tests/idempotency_concurrent.py b/student_tests/idempotency_concurrent.py new file mode 100644 index 00000000..1ed1f04c --- /dev/null +++ b/student_tests/idempotency_concurrent.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +"""Prove that one idempotency scope is shared across API replicas.""" +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import sys +import uuid + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) +from client import Client, arguments, check, run + + +def main(): + args = arguments('Concurrent cross-replica idempotency check') + bootstrap = Client(args.base_url, args.ca_file, timeout=5) + alice, _, _, chat = bootstrap.bootstrap() + key = uuid.uuid4().hex + text = 'Один результат для всех реплик ' + key + path = '/api/v1/chats/' + chat['id'] + '/messages' + + def send(_): + client = Client(args.base_url, args.ca_file, timeout=10) + return client.call( + 'POST', + path, + 201, + actor=alice, + body={'text': text}, + headers={'Idempotency-Key': key}, + schema='Message') + + with ThreadPoolExecutor(max_workers=16) as pool: + responses = list(pool.map(send, range(32))) + + messages = [response['json'] for response in responses] + instances = { + response['headers']['X-Instance-Id'] for response in responses + } + check(all(message == messages[0] for message in messages), + 'same key returned different messages') + check(len(instances) >= 2, + 'requests did not exercise at least two API replicas') + + page = bootstrap.call( + 'GET', path + '?limit=100', actor=alice, schema='MessagePage')['json'] + matches = [item for item in page['items'] if item['id'] == messages[0]['id']] + check(len(matches) == 1, 'idempotent message is missing or duplicated') + print('PASS: 32 concurrent requests used ' + str(len(instances)) + + ' replicas and created one message') + + +if __name__ == '__main__': + run(main) diff --git a/student_tests/lab4_negative.py b/student_tests/lab4_negative.py new file mode 100644 index 00000000..ae285434 --- /dev/null +++ b/student_tests/lab4_negative.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""Negative black-box checks for lab4; uses only synthetic users and files.""" +import argparse +import sys +import uuid +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) + +from client import Client, Failure, check, run # noqa: E402 + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--base-url', default='http://localhost:8080') + parser.add_argument('--expect-s3-unavailable', action='store_true') + args = parser.parse_args() + + client = Client(args.base_url, timeout=20) + alice, bob, eve, chat = client.bootstrap() + png = (ROOT / 'tests' / 'fixtures' / 'sample.png').read_bytes() + upload_path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png' + + if args.expect_s3_unavailable: + response = client.call('POST', upload_path, 503, actor=alice, raw=png, + headers={'Content-Type': 'image/png'}) + check(response['json']['error']['code'] == 'unavailable', 'S3 outage must return unavailable') + print('PASS: unavailable S3 returns contract JSON 503') + return + + attachment, original = client.attachment(alice, chat) + client.call('GET', '/api/v1/attachments/' + attachment['id'], 404, actor=eve) + client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', 404, actor=eve) + + other_chat = client.call('POST', '/api/v1/chats', 201, actor=alice, + body={'title': 'Другой чат', 'member_ids': [alice['id'], eve['id']]}, + schema='Chat')['json'] + client.call('POST', '/api/v1/chats/' + other_chat['id'] + '/messages', 404, + actor=alice, headers={'Idempotency-Key': uuid.uuid4().hex}, + body={'text': '', 'attachment_ids': [attachment['id']]}) + client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, + actor=alice, headers={'Idempotency-Key': uuid.uuid4().hex}, + body={'text': '', 'attachment_ids': [str(uuid.uuid4())]}) + client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 400, + actor=alice, headers={'Idempotency-Key': uuid.uuid4().hex}, + body={'text': '', 'attachment_ids': [attachment['id'], attachment['id']]}) + + client.call('POST', upload_path, 415, actor=alice, raw=png, + headers={'Content-Type': 'image/jpeg'}) + client.call('POST', upload_path, 415, actor=alice, raw=b'\x89PNG\r\n\x1a\ntruncated', + headers={'Content-Type': 'image/png'}) + client.call('POST', upload_path, 413, actor=alice, raw=b'x' * (10_485_760 + 1), + headers={'Content-Type': 'image/png'}) + client.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=../escape.png', + 400, actor=alice, raw=png, headers={'Content-Type': 'image/png'}) + + downloaded = client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', + actor=bob) + check(downloaded['bytes'] == original, 'authorized download changed bytes') + print('PASS: unknown/foreign attachment, foreign chat/user, MIME spoof, corruption, byte limit and filename checks') + + +if __name__ == '__main__': + run(main) diff --git a/student_tests/node_failover.py b/student_tests/node_failover.py new file mode 100644 index 00000000..2cf00a6d --- /dev/null +++ b/student_tests/node_failover.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Hard-stop one Swarm worker and prove API task relocation and data safety.""" +import json +import atexit +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import subprocess +import sys +import time +import uuid +from urllib.parse import quote + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) +from client import Client, Failure, arguments, check, run + + +def command(*parts, timeout=30): + result = subprocess.run( + parts, capture_output=True, text=True, timeout=timeout) + check(result.returncode == 0, 'command failed: ' + ' '.join(parts[:3])) + return result.stdout.strip() + + +def api_tasks(manager): + output = command( + 'docker', 'exec', manager, 'docker', 'service', 'ps', 'hla-app_api', + '--filter', 'desired-state=running', + '--format', '{{.ID}}\t{{.Node}}\t{{.CurrentState}}') + result = [] + for line in output.splitlines(): + fields = line.split('\t') + if len(fields) == 3 and fields[2].startswith('Running'): + result.append({'task_id': fields[0], 'node': fields[1]}) + return result + + +def history(client, actor, chat_id): + path = '/api/v1/chats/' + chat_id + '/messages?limit=100' + result = [] + for _ in range(1000): + page = client.call('GET', path, actor=actor, schema='MessagePage')['json'] + result.extend(page['items']) + if page['next_cursor'] is None: + return result + path = ('/api/v1/chats/' + chat_id + '/messages?limit=100&cursor=' + + quote(page['next_cursor'], safe='')) + raise Failure('history pagination exceeded safety bound') + + +def observe(client, actor, attempts=40): + def request(_): + local = Client(client.base, timeout=2) + return local.call( + 'GET', '/api/v1/users/me', actor=actor, schema='User') + with ThreadPoolExecutor(max_workers=16) as pool: + responses = list(pool.map(request, range(attempts))) + return {response['headers']['X-Instance-Id'] for response in responses} + + +def restore_worker(manager, node): + subprocess.run( + ['docker', 'start', node], stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, timeout=30) + deadline = time.monotonic() + 90 + status = '' + while time.monotonic() < deadline: + result = subprocess.run( + ['docker', 'exec', manager, 'docker', 'node', 'ls', + '--filter', 'name=' + node, '--format', '{{.Status}}'], + capture_output=True, text=True, timeout=30) + status = result.stdout.strip() + if result.returncode == 0 and status == 'Ready': + return True + time.sleep(2) + return False + + +def main(): + def configure(parser): + parser.add_argument('--manager-container', default='hla-swarm-manager') + parser.add_argument('--window', type=float, default=30) + parser.add_argument('--output', default=None) + args = arguments('Swarm worker loss and API relocation', configure) + check(15 <= args.window <= 120, 'window must be 15..120 seconds') + client = Client(args.base_url, args.ca_file, timeout=2) + alice, bob, _, chat = client.bootstrap() + before_instances = observe(client, alice) + check(len(before_instances) >= 2, 'expected two API instances before node loss') + before_tasks = api_tasks(args.manager_container) + check(len(before_tasks) == 2, 'expected two running API tasks') + candidates = [task for task in before_tasks + if task['node'].startswith('hla-swarm-worker')] + check(bool(candidates), 'no API task is running on a worker node') + victim = candidates[0] + confirmed_before = client.message( + alice, chat, 'confirmed-before-node-loss-' + uuid.uuid4().hex)['json'] + + started = time.monotonic() + command('docker', 'stop', '--time', '1', victim['node'], timeout=15) + restore_at_exit = lambda: restore_worker(args.manager_container, victim['node']) + atexit.register(restore_at_exit) + first_recovery = None + reads = writes = failures = 0 + confirmed_during = [] + key = uuid.uuid4().hex + text = 'during-node-loss-' + key + while time.monotonic() - started < args.window: + try: + if (reads + writes) % 2 == 0: + response = client.message(alice, chat, text, key=key) + confirmed_during.append(response['json']) + writes += 1 + key = uuid.uuid4().hex + text = 'during-node-loss-' + key + else: + client.call('GET', '/api/v1/users/me', actor=bob, schema='User') + reads += 1 + if first_recovery is None: + first_recovery = time.monotonic() - started + except Failure: + failures += 1 + time.sleep(0.05) + + deadline = time.monotonic() + 90 + after_tasks = [] + while time.monotonic() < deadline: + after_tasks = api_tasks(args.manager_container) + if (len(after_tasks) == 2 + and all(task['node'] != victim['node'] for task in after_tasks) + and any(task['task_id'] != victim['task_id'] for task in after_tasks)): + break + time.sleep(2) + check(len(after_tasks) == 2, 'API service did not return to two tasks') + check(all(task['node'] != victim['node'] for task in after_tasks), + 'API task was not relocated away from failed node') + check(first_recovery is not None and first_recovery <= 10, + 'API did not recover within 10 seconds') + + stored = history(client, bob, chat['id']) + stored_ids = {message['id'] for message in stored} + check(confirmed_before['id'] in stored_ids, + 'pre-failure confirmed message was lost') + check(all(message['id'] in stored_ids for message in confirmed_during), + 'message confirmed during node loss was lost') + check(restore_worker(args.manager_container, victim['node']), + 'failed worker did not rejoin the Swarm') + atexit.unregister(restore_at_exit) + after_instances = observe(client, alice, attempts=96) + check(len(after_instances - before_instances) >= 1, + 'replacement API process was not visible through X-Instance-Id') + + elapsed = time.monotonic() - started + report = { + 'scenario': 'hard loss of one Swarm worker', + 'failed_node': victim['node'], + 'old_task_id': victim['task_id'], + 'tasks_before': before_tasks, + 'tasks_after_relocation': after_tasks, + 'instance_ids_before': sorted(before_instances), + 'instance_ids_after': sorted(after_instances), + 'successful_reads': reads, + 'successful_writes': writes, + 'failed_attempts': failures, + 'first_recovery_seconds': round(first_recovery, 3), + 'successful_rps': round((reads + writes) / args.window, 3), + 'experiment_seconds_including_rejoin': round(elapsed, 3), + 'confirmed_data_preserved': True, + 'database_node_failed': False, + 'note': ('PostgreSQL, Nginx, manager quorum and local volumes are not ' + 'protected by this experiment.'), + } + output = json.dumps(report, ensure_ascii=False, indent=2) + if args.output: + destination = Path(args.output) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text(output + '\n', encoding='utf-8') + print(output) + + +if __name__ == '__main__': + run(main) diff --git a/student_tests/readiness_gate.py b/student_tests/readiness_gate.py new file mode 100644 index 00000000..1a9df4c6 --- /dev/null +++ b/student_tests/readiness_gate.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""Reproduce and guard against serving business traffic from unready APIs.""" +from pathlib import Path +import subprocess +import sys +import time + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) +from client import Client, Failure, arguments, check, run + +ORIGINAL_TABLE = 'message_idempotency' +TEMPORARY_TABLE = 'message_idempotency_readiness_test' + + +def command(*args): + result = subprocess.run( + args, + cwd=ROOT, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + check=False) + if result.returncode != 0: + output = result.stdout.strip() + raise Failure('command failed: ' + ' '.join(args[:3]) + + (': ' + output if output else '')) + return result.stdout.strip() + + +def rename_table(source, target): + sql = 'ALTER TABLE ' + source + ' RENAME TO ' + target + ';' + command( + 'docker', 'compose', 'exec', '-T', 'postgres', 'sh', '-ec', + 'psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" ' + '-d "$POSTGRES_DB" -c \'' + sql + '\'') + + +def api_container_ids(): + output = command('docker', 'compose', 'ps', '-q', 'api') + return [line.strip() for line in output.splitlines() if line.strip()] + + +def health_status(container_id): + return command( + 'docker', 'inspect', + '--format={{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}', + container_id) + + +def wait_for_all_health(expected, timeout): + deadline = time.monotonic() + timeout + last = [] + while time.monotonic() < deadline: + containers = api_container_ids() + last = [health_status(container) for container in containers] + if len(containers) >= 2 and all(value == expected for value in last): + return containers + time.sleep(1) + raise Failure('API health did not become ' + expected + + '; last statuses: ' + repr(last)) + + +def configure(parser): + parser.add_argument( + '--health-timeout', type=float, default=45.0, + help='seconds to wait for both Docker health states') + + +def main(): + args = arguments('Readiness must gate business traffic through the LB', configure) + client = Client(args.base_url, args.ca_file, timeout=8) + client.call('GET', '/health/ready', 200, schema='Health') + actor = client.user('readiness_gate') + + renamed = False + try: + rename_table(ORIGINAL_TABLE, TEMPORARY_TABLE) + renamed = True + containers = wait_for_all_health('unhealthy', args.health_timeout) + + client.call('GET', '/health/ready', 503) + instances = set() + for _ in range(8): + response = client.call( + 'GET', '/api/v1/users/me', 503, actor=actor) + instances.add(response['headers']['X-Instance-Id']) + check(instances, 'no refusing API instance was observed') + finally: + if renamed: + rename_table(TEMPORARY_TABLE, ORIGINAL_TABLE) + + wait_for_all_health('healthy', args.health_timeout) + # Nginx may retain a passive failure for fail_timeout=2s. + time.sleep(3) + client.call('GET', '/health/ready', 200, schema='Health') + client.call('GET', '/api/v1/users/me', 200, actor=actor, schema='User') + print('PASS: ' + str(len(containers)) + + ' unhealthy API containers refused business traffic with 503 ' + + 'and recovered after schema restoration') + + +if __name__ == '__main__': + run(main) diff --git a/student_tests/rolling_update.py b/student_tests/rolling_update.py new file mode 100644 index 00000000..20effca9 --- /dev/null +++ b/student_tests/rolling_update.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Run closed-loop writes while API replicas are replaced one at a time.""" +from concurrent.futures import ThreadPoolExecutor +import json +import math +import os +from pathlib import Path +import subprocess +import sys +import threading +import time + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) +from client import Client, Failure, arguments, check, run + + +def main(): + def configure(parser): + parser.add_argument('--action-script', required=True) + parser.add_argument('--duration', type=float, default=180) + parser.add_argument('--concurrency', type=int, default=4) + parser.add_argument('--output', default=None) + args = arguments('Rolling replacement under write load', configure) + check(30 <= args.duration <= 300, 'duration must be 30..300 seconds') + check(1 <= args.concurrency <= 32, 'concurrency must be 1..32') + action = Path(args.action_script).expanduser().resolve() + check(action.is_file() and os.access(action, os.X_OK), + 'action script must be executable') + bootstrap = Client(args.base_url, args.ca_file, timeout=5) + alice, _, _, chat = bootstrap.bootstrap() + barrier = threading.Barrier(args.concurrency + 1) + + def worker(worker_id): + client = Client(args.base_url, args.ca_file, timeout=5) + barrier.wait() + deadline = time.monotonic() + args.duration + latencies = [] + errors = 0 + instances = set() + index = 0 + while time.monotonic() < deadline: + started = time.monotonic() + try: + response = client.message( + alice, chat, 'rolling-%s-%s' % (worker_id, index)) + latencies.append(time.monotonic() - started) + instances.add(response['headers']['X-Instance-Id']) + except Failure: + errors += 1 + index += 1 + return latencies, errors, instances + + started = time.monotonic() + with ThreadPoolExecutor(max_workers=args.concurrency) as pool: + futures = [pool.submit(worker, number) + for number in range(args.concurrency)] + barrier.wait() + time.sleep(3) + action_started = time.monotonic() + process = subprocess.run( + [str(action)], stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, timeout=args.duration - 5) + action_seconds = time.monotonic() - action_started + check(process.returncode == 0, 'rolling action failed') + results = [future.result() for future in futures] + + elapsed = time.monotonic() - started + latencies = sorted(value for values, _, _ in results for value in values) + errors = sum(value for _, value, _ in results) + instances = set().union(*(value for _, _, value in results)) + total = len(latencies) + errors + + def percentile(fraction): + if not latencies: + return None + index = max(0, math.ceil(fraction * len(latencies)) - 1) + return round(1000 * latencies[index], 3) + + report = { + 'scenario': 'sequential API replacement under closed-loop writes', + 'requested_duration_seconds': args.duration, + 'elapsed_seconds': round(elapsed, 3), + 'rolling_action_seconds': round(action_seconds, 3), + 'concurrency': args.concurrency, + 'observed_instance_ids': sorted(instances), + 'successful_requests': len(latencies), + 'failed_requests': errors, + 'error_ratio': round(errors / total, 6) if total else None, + 'successful_rps': round(len(latencies) / elapsed, 3), + 'successful_latency_ms': { + 'p50': percentile(.50), + 'p95': percentile(.95), + 'p99': percentile(.99), + }, + 'note': 'Closed-loop result on one host; success latency excludes failures.', + } + output = json.dumps(report, ensure_ascii=False, indent=2) + if args.output: + destination = Path(args.output) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text(output + '\n', encoding='utf-8') + print(output) + check(bool(latencies), 'no successful writes') + check(len(instances) >= 3, + 'rolling replacement did not expose replacement instance IDs') + + +if __name__ == '__main__': + run(main) diff --git a/swarm/nginx.Dockerfile b/swarm/nginx.Dockerfile new file mode 100644 index 00000000..9d74ead5 --- /dev/null +++ b/swarm/nginx.Dockerfile @@ -0,0 +1,3 @@ +FROM nginx:1.27.4-bookworm +COPY swarm/nginx.conf /etc/nginx/nginx.conf +HEALTHCHECK --interval=2s --timeout=2s --retries=15 CMD nginx -t diff --git a/swarm/nginx.conf b/swarm/nginx.conf new file mode 100644 index 00000000..74b00a1d --- /dev/null +++ b/swarm/nginx.conf @@ -0,0 +1,86 @@ +worker_processes auto; +worker_shutdown_timeout 10s; + +events { + worker_connections 1024; +} + +http { + client_max_body_size 11m; + client_body_timeout 10s; + access_log /var/log/nginx/access.log; + error_log /var/log/nginx/error.log warn; + resolver 127.0.0.11 valid=2s ipv6=off; + resolver_timeout 1s; + + upstream api_backend { + zone api_backend 64k; + least_conn; + server tasks.hla-app_api:8080 resolve max_fails=1 fail_timeout=2s; + keepalive 32; + } + + server { + listen 80; + server_name _; + proxy_intercept_errors on; + error_page 502 503 504 = @no_ready_api; + + location = /nginx-health { + default_type application/json; + return 200 '{"status":"ok"}'; + } + + location @no_ready_api { + internal; + default_type application/json; + add_header X-Request-Id $request_id always; + add_header X-Instance-Id nginx always; + add_header Cache-Control "no-store" always; + return 503 '{"error":{"code":"unavailable","message":"No ready API backend","request_id":"$request_id"}}'; + } + + location ~ ^/api/v1/chats/[0-9a-fA-F-]+/messages$ { + proxy_pass http://api_backend; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_request_buffering on; + proxy_connect_timeout 500ms; + proxy_send_timeout 4s; + proxy_read_timeout 4s; + proxy_next_upstream error timeout http_502 http_503 http_504 non_idempotent; + proxy_next_upstream_tries 2; + } + + location ~ ^/api/v1/chats/[0-9a-fA-F-]+/attachments$ { + proxy_pass http://api_backend; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_request_buffering on; + proxy_connect_timeout 500ms; + proxy_send_timeout 20s; + proxy_read_timeout 20s; + proxy_next_upstream off; + } + + location / { + proxy_pass http://api_backend; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_connect_timeout 500ms; + proxy_send_timeout 4s; + proxy_read_timeout 4s; + proxy_next_upstream error timeout http_502 http_503 http_504; + proxy_next_upstream_tries 2; + } + } +} diff --git a/swarm/stack.app.yaml b/swarm/stack.app.yaml new file mode 100644 index 00000000..5be08131 --- /dev/null +++ b/swarm/stack.app.yaml @@ -0,0 +1,88 @@ +version: "3.9" + +services: + api: + image: hla-swarm-registry:5000/hla-lab4-api:swarm + environment: + APP_HOST: 0.0.0.0 + APP_PORT: 8080 + DATABASE_URL: jdbc:postgresql://hla-state_postgres:5432/${DATABASE_NAME:-messenger} + DATABASE_USER: ${DATABASE_USER:-messenger} + DATABASE_PASSWORD: ${DATABASE_PASSWORD:?DATABASE_PASSWORD is required} + DATABASE_POOL_SIZE: 10 + DATABASE_MIN_IDLE: 2 + DATABASE_QUERY_TIMEOUT_SECONDS: 5 + DATABASE_TRANSACTION_TIMEOUT_SECONDS: 5 + REDIS_HOST: hla-state_redis + REDIS_PORT: 6379 + REDIS_CONNECT_TIMEOUT: 1s + REDIS_COMMAND_TIMEOUT: 500ms + SESSION_TTL_SECONDS: 3600 + USER_CACHE_TTL_SECONDS: 300 + IDEMPOTENCY_TTL_SECONDS: 86400 + S3_ENDPOINT: http://hla-state_minio:9000 + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:?S3_ACCESS_KEY_ID is required} + S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:?S3_SECRET_ACCESS_KEY is required} + MAX_UPLOAD_BYTES: 10485760 + MAX_IMAGE_PIXELS: 40000000 + MAX_CONCURRENT_UPLOADS: 3 + UPLOAD_PERMIT_WAIT_MILLIS: 10000 + ATTACHMENT_CLEANUP_GRACE_SECONDS: 3600 + ATTACHMENT_CLEANUP_DRY_RUN: "false" + ATTACHMENT_RECONCILE_INTERVAL_MILLIS: 600000 + ATTACHMENT_RECONCILE_INITIAL_DELAY_MILLIS: 60000 + FLYWAY_ENABLED: "false" + healthcheck: + test: ["CMD", "curl", "--fail", "--silent", "http://localhost:8080/health/ready"] + interval: 2s + timeout: 2s + retries: 20 + start_period: 45s + networks: [backend] + deploy: + replicas: 2 + endpoint_mode: dnsrr + placement: + max_replicas_per_node: 1 + restart_policy: + condition: on-failure + delay: 2s + update_config: + parallelism: 1 + order: start-first + monitor: 15s + failure_action: rollback + rollback_config: + parallelism: 1 + order: stop-first + resources: + limits: + cpus: "0.75" + memory: 768M + + nginx: + image: hla-swarm-registry:5000/hla-lab4-nginx:swarm + ports: + - target: 80 + published: 8080 + protocol: tcp + mode: ingress + networks: [backend] + deploy: + replicas: 1 + placement: + constraints: + - node.labels.hla.lb == true + restart_policy: + condition: on-failure + resources: + limits: + cpus: "0.25" + memory: 128M + +networks: + backend: + external: true + name: hla-state_backend diff --git a/swarm/stack.state.yaml b/swarm/stack.state.yaml new file mode 100644 index 00000000..29f30e7d --- /dev/null +++ b/swarm/stack.state.yaml @@ -0,0 +1,123 @@ +version: "3.9" + +services: + postgres: + image: postgres:16.4-bookworm + environment: + POSTGRES_DB: ${DATABASE_NAME:-messenger} + POSTGRES_USER: ${DATABASE_USER:-messenger} + POSTGRES_PASSWORD: ${DATABASE_PASSWORD:?DATABASE_PASSWORD is required} + volumes: + - postgres-data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"] + interval: 2s + timeout: 2s + retries: 30 + networks: [backend] + deploy: + replicas: 1 + placement: + constraints: + - node.labels.hla.state == true + restart_policy: + condition: on-failure + resources: + limits: + cpus: "1.00" + memory: 768M + + redis: + image: redis:7.4-bookworm + command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec"] + volumes: + - redis-data:/data + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 2s + timeout: 2s + retries: 30 + networks: [backend] + deploy: + replicas: 1 + placement: + constraints: + - node.labels.hla.state == true + restart_policy: + condition: on-failure + resources: + limits: + cpus: "0.25" + memory: 256M + + minio: + image: bitnamilegacy/minio:2025.4.22-debian-12-r1@sha256:d7cd0e172c4cc0870f4bdc3142018e2a37be9acf04d68f386600daad427e0cab + environment: + MINIO_ROOT_USER: ${MINIO_ROOT_USER:?MINIO_ROOT_USER is required} + MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?MINIO_ROOT_PASSWORD is required} + volumes: + - minio-data:/bitnami/minio/data + healthcheck: + test: ["CMD", "curl", "--fail", "--silent", "http://localhost:9000/minio/health/live"] + interval: 2s + timeout: 2s + retries: 30 + networks: [backend] + deploy: + replicas: 1 + placement: + constraints: + - node.labels.hla.state == true + restart_policy: + condition: on-failure + resources: + limits: + cpus: "0.75" + memory: 512M + + minio-init: + image: bitnamilegacy/minio-client:2025.4.16-debian-12-r0@sha256:28e38f52642c06a2344fa974cf55786b4c52601b6b9b0676c68d40ee0876a5bc + environment: + MINIO_ROOT_USER: ${MINIO_ROOT_USER:?MINIO_ROOT_USER is required} + MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?MINIO_ROOT_PASSWORD is required} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:?S3_ACCESS_KEY_ID is required} + S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:?S3_SECRET_ACCESS_KEY is required} + configs: + - source: minio_api_policy + target: /policy/minio-api-policy.json + entrypoint: ["/bin/sh", "-c"] + command: + - | + set -eu + until mc alias set local http://minio:9000 "$$MINIO_ROOT_USER" "$$MINIO_ROOT_PASSWORD"; do sleep 2; done + mc mb --ignore-existing "local/$$S3_BUCKET" + mc anonymous set none "local/$$S3_BUCKET" + sed "s/__S3_BUCKET__/$$S3_BUCKET/g" /policy/minio-api-policy.json > /tmp/minio-api-policy.json + mc admin user add local "$$S3_ACCESS_KEY_ID" "$$S3_SECRET_ACCESS_KEY" || true + mc admin policy create local messenger-attachments-rw /tmp/minio-api-policy.json || true + mc admin policy attach local messenger-attachments-rw --user "$$S3_ACCESS_KEY_ID" + networks: [backend] + deploy: + replicas: 1 + placement: + constraints: + - node.labels.hla.state == true + restart_policy: + condition: on-failure + delay: 2s + max_attempts: 20 + +networks: + backend: + driver: overlay + attachable: true + +volumes: + postgres-data: + redis-data: + minio-data: + +configs: + minio_api_policy: + file: ../infra/minio-api-policy.json -- 2.54.0 From 75d2f789130b5caae5a8ed4bb45672dacd788ca9 Mon Sep 17 00:00:00 2001 From: EgorAnti Date: Thu, 19 Nov 2026 07:57:14 +0300 Subject: [PATCH 2/3] 4 --- .env.example | 67 +++-- .gitignore | 1 + REPORT.md | 74 +++-- build.gradle | 3 + compose.yaml | 109 ++++++- evidence/lab5-2026-11-18.md | 41 +++ evidence/lab5-level4-2026-11-19.md | 56 ++++ infra/minio-api-policy.json | 3 +- scripts/replay-failed.ps1 | 57 ++++ scripts/replay-failed.sh | 45 +++ .../config/RabbitJobConfig.java | 57 ++++ .../controller/AttachmentController.java | 13 +- .../dto/AttachmentResponse.java | 8 +- .../dto/AttachmentVariantResponse.java | 16 + .../mtusi_messenger/model/Attachment.java | 22 ++ .../mtusi_messenger/model/AttachmentJob.java | 37 +++ .../model/AttachmentVariant.java | 10 + .../queue/AttachmentJobPublisher.java | 65 ++++ .../queue/ExpiredLeaseReaper.java | 55 ++++ .../mtusi_messenger/queue/RetryPolicy.java | 39 +++ .../queue/UnpublishedJobRepublisher.java | 34 +++ .../repository/AttachmentRepository.java | 24 +- .../PostgresAttachmentRepository.java | 280 +++++++++++++++++- .../service/AttachmentReconciler.java | 2 + .../service/AttachmentService.java | 65 +++- .../service/StagingCleaner.java | 65 ++++ .../worker/AttachmentWorker.java | 239 +++++++++++++++ .../worker/ImageVariantProcessor.java | 254 ++++++++++++++++ src/main/resources/application.yml | 39 +++ .../V5__add_attachment_processing_jobs.sql | 58 ++++ ..._job_leases_replay_and_fault_injection.sql | 41 +++ .../queue/RetryPolicyTest.java | 21 ++ .../service/AttachmentServiceTest.java | 25 +- .../service/StagingCleanerTest.java | 55 ++++ .../worker/ImageVariantProcessorTest.java | 70 +++++ student_tests/README.md | 6 + student_tests/lab5_dlq_replay_lease.py | 126 ++++++++ student_tests/lab5_fault_injection.py | 135 +++++++++ student_tests/lab5_worker_recovery.py | 158 ++++++++++ 39 files changed, 2382 insertions(+), 93 deletions(-) create mode 100644 evidence/lab5-2026-11-18.md create mode 100644 evidence/lab5-level4-2026-11-19.md create mode 100644 scripts/replay-failed.ps1 create mode 100644 scripts/replay-failed.sh create mode 100644 src/main/java/com/example/mtusi_messenger/config/RabbitJobConfig.java create mode 100644 src/main/java/com/example/mtusi_messenger/dto/AttachmentVariantResponse.java create mode 100644 src/main/java/com/example/mtusi_messenger/model/AttachmentJob.java create mode 100644 src/main/java/com/example/mtusi_messenger/model/AttachmentVariant.java create mode 100644 src/main/java/com/example/mtusi_messenger/queue/AttachmentJobPublisher.java create mode 100644 src/main/java/com/example/mtusi_messenger/queue/ExpiredLeaseReaper.java create mode 100644 src/main/java/com/example/mtusi_messenger/queue/RetryPolicy.java create mode 100644 src/main/java/com/example/mtusi_messenger/queue/UnpublishedJobRepublisher.java create mode 100644 src/main/java/com/example/mtusi_messenger/service/StagingCleaner.java create mode 100644 src/main/java/com/example/mtusi_messenger/worker/AttachmentWorker.java create mode 100644 src/main/java/com/example/mtusi_messenger/worker/ImageVariantProcessor.java create mode 100644 src/main/resources/db/migration/V5__add_attachment_processing_jobs.sql create mode 100644 src/main/resources/db/migration/V6__add_job_leases_replay_and_fault_injection.sql create mode 100644 src/test/java/com/example/mtusi_messenger/queue/RetryPolicyTest.java create mode 100644 src/test/java/com/example/mtusi_messenger/service/StagingCleanerTest.java create mode 100644 src/test/java/com/example/mtusi_messenger/worker/ImageVariantProcessorTest.java create mode 100644 student_tests/lab5_dlq_replay_lease.py create mode 100644 student_tests/lab5_fault_injection.py create mode 100644 student_tests/lab5_worker_recovery.py diff --git a/.env.example b/.env.example index 119384b5..c13c3ba8 100644 --- a/.env.example +++ b/.env.example @@ -1,25 +1,54 @@ -# Copy to .env for your LOCAL synthetic test environment; never commit .env. -# These are logical interface suggestions; map actual framework names in REPORT.md. -APP_HOST=0.0.0.0 +# Copy to .env for a local synthetic environment. Never commit .env. APP_PORT=8080 -APP_ENV=lab -SESSION_TTL_SECONDS=3600 -# Choose credentials locally. File paths contain no secret values. -DATABASE_URL_FILE=/run/secrets/database_url -# Optional on 3, required use on 4 in lab2; Redis OR Valkey: -SESSION_STORE=postgres -CACHE_URL_FILE=/run/secrets/cache_url -API_REPLICAS=2 -IDEMPOTENCY_TTL_SECONDS=86400 -S3_ENDPOINT=http://s3:9000 + +DATABASE_NAME=messenger +DATABASE_USER=messenger +DATABASE_PASSWORD=replace-with-a-long-random-database-password + +RABBITMQ_USER=messenger +RABBITMQ_PASSWORD=replace-with-a-long-random-rabbitmq-password +RABBITMQ_VHOST=/ +ATTACHMENT_JOB_EXCHANGE=attachments.v1 +ATTACHMENT_JOB_QUEUE=attachments.process.level4.v1 +ATTACHMENT_JOB_ROUTING_KEY=attachment.process.v1 +ATTACHMENT_DLQ_EXCHANGE=attachments.dlx.v1 +ATTACHMENT_DLQ_QUEUE=attachments.failed.v1 +ATTACHMENT_DLQ_ROUTING_KEY=attachment.failed.v1 +WORKER_CONCURRENCY=2 +WORKER_PREFETCH=1 +JOB_MAX_ATTEMPTS=5 +JOB_RETRY_BASE_DELAY=1s +JOB_RETRY_MAX_DELAY=30s +JOB_TIMEOUT=60s +JOB_LEASE_DURATION=90s +JOB_LEASE_REAPER_INTERVAL=5s +WORKER_MAX_IMAGE_PIXELS=40000000 +WORKER_MEMORY_BUDGET_BYTES=536870912 +WORKER_MEMORY_WAIT=2s + +# Fault injection is opt-in and intended only for an isolated test stand. +FAULT_CRASH_AFTER_OUTBOX_COMMIT=false +FAULT_CRASH_AFTER_RESULT_COMMIT=false + S3_REGION=us-east-1 S3_BUCKET=messenger-attachments -S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id -S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key +S3_ACCESS_KEY_ID=messenger-api +S3_SECRET_ACCESS_KEY=replace-with-a-long-random-api-secret +MINIO_ROOT_USER=minio-root +MINIO_ROOT_PASSWORD=replace-with-a-different-long-random-root-secret + +SESSION_TTL_SECONDS=3600 +IDEMPOTENCY_TTL_SECONDS=86400 MAX_UPLOAD_BYTES=10485760 MAX_IMAGE_PIXELS=40000000 -BROKER_URL_FILE=/run/secrets/broker_url -WORKER_CONCURRENCY=2 -JOB_MAX_ATTEMPTS=5 -JOB_TIMEOUT_SECONDS=60 +MAX_CONCURRENT_UPLOADS=3 +UPLOAD_PERMIT_WAIT_MILLIS=10000 + +# Staging objects are deleted only after the final result is committed. +# A separate lifecycle/cleanup policy may remove abandoned staging objects +# after this retention interval; it must never remove active jobs. STAGING_RETENTION_SECONDS=86400 +ATTACHMENT_CLEANUP_GRACE_SECONDS=3600 +ATTACHMENT_CLEANUP_DRY_RUN=false +ATTACHMENT_RECONCILE_INTERVAL_MILLIS=600000 +ATTACHMENT_RECONCILE_INITIAL_DELAY_MILLIS=60000 diff --git a/.gitignore b/.gitignore index b5a71896..affc5505 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,7 @@ data/ backups/ # Runtime/build artifacts .venv/ +.gradle/ __pycache__/ *.py[cod] node_modules/ diff --git a/REPORT.md b/REPORT.md index e98f75e9..687415e4 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,71 @@ # Отчёт — лабораторная 5 - Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO +- Целевая оценка: 4 - Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Библиотеки: Spring AMQP, RabbitMQ Java client, Thumbnailator, webp-imageio, MinIO SDK, PostgreSQL/Flyway +- Помощь ИИ: проектирование pipeline, реализация и подготовка тестов; результат проверен сборкой, unit- и black-box-тестами ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Нужны Docker Desktop/Engine с Compose v2, Java 23 и Python 3.9+. -## Архитектура и решения +```sh +cp .env.example .env +# Заменить все replace-with-* уникальными локальными значениями. +docker compose --env-file .env config --quiet +docker compose --env-file .env up -d --build +python -X utf8 tests/smoke.py --base-url http://localhost:8080 +``` -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab4, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +`docker compose --env-file .env down` сохраняет volumes. Удаление учебных данных выполняется только явной командой оператора с `--volumes`. -## Доказательства критериев +## Pipeline и гарантии -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | -| --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +Upload разделён на durable-границы: API проверяет bytes/MIME/dimensions, пишет неизменённый original в приватный `staging//original`, затем одной транзакцией создаёт `attachments(queued)` и `attachment_jobs(published=false)`. Запись job является transactional outbox. Фоновый publisher публикует persistent JSON в durable RabbitMQ queue, ждёт publisher confirm и только потом помечает job опубликованной. Поэтому COMMIT без publish восстанавливается автоматически, а HTTP `202` означает, что staging и намерение обработки уже устойчивы. -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +Отдельный `worker` захватывает job с lease, читает доверенный staging key из PostgreSQL и создаёт детерминированные S3 keys. В broker message есть только `schema_version`, `job_id`, `attachment_id`, `pipeline_version`, `attempt`, `created_at`; bytes, credentials, произвольные URL и клиентские пути отсутствуют. Эффект идемпотентен по `(attachment_id, pipeline_version, variant)`. Все variant rows и `ready` фиксируются атомарно; ack выполняется после COMMIT. Redelivery уже `ready` job — no-op. -## Эксперименты и отказы +Обязательные варианты pipeline version 1: -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +| Вариант | Правило | Формат/качество | +| --- | --- | --- | +| `original` | bytes и SHA-256 совпадают с upload | исходный MIME | +| `thumbnail` | fit в 256×256, без увеличения, EXIF orientation, alpha на белом | JPEG, quality 0.85 | +| `crop` | центрированный квадрат 128×128 после EXIF orientation | JPEG, quality 0.88 | +| `optimized` | fit до 1280×1280, без увеличения, alpha сохраняется | WebP, quality 0.82 | -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | -| --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +Новые файлы кодируются из пикселей без копирования EXIF/ICC/прочих исходных metadata. -## Ограничения и следующие шаги +## Ограничения worker и retry -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +- Upload: `MAX_UPLOAD_BYTES=10485760`, `MAX_IMAGE_PIXELS=40000000`. +- Worker повторно проверяет header/dimensions до полного decode и применяет тот же pixel cap. +- Оценка памяти на job резервируется общим честным semaphore; бюджет `WORKER_MEMORY_BUDGET_BYTES=536870912`, ожидание `WORKER_MEMORY_WAIT=2s`. Compose дополнительно ограничивает worker `1024m`, JVM использует до 70% container RAM. +- Обработка ограничена `JOB_TIMEOUT=60s`; просроченный task теряет lease и не может зафиксировать результат. +- `WORKER_CONCURRENCY=2`, `WORKER_PREFETCH=1`; lease 90s, reaper каждые 5s. +- Не более `JOB_MAX_ATTEMPTS=5`. Временные ошибки получают exponential backoff с jitter 50–100% и cap 30s. Ошибки decode/format/size постоянные и сразу становятся безопасным `failed/error_code`; exhausted retry — `retry_exhausted`. +- Permanent malformed broker delivery и исчерпанная работа dead-lettered в durable `attachments.failed.v1`. Реестр failed остаётся в PostgreSQL. + +Операторский replay выполняется `scripts/replay-failed.ps1 -JobId ` или `scripts/replay-failed.sh `. Одна транзакция блокирует одновременно failed job и attachment, пишет `attachment_job_replays`, сбрасывает outbox и состояние. Не-failed, уже recovered и `ready` jobs дают явный безопасный `no-op`. + +После безопасного COMMIT результата worker best-effort удаляет staging. `StagingCleaner` удаляет только неактивные объекты старше `STAGING_RETENTION_SECONDS=86400`; queued/processing staging защищён. + +## Fault injection и проверки + +| Критерий | Команда | Результат | +| --- | --- | --- | +| Unit tests | `gradlew test --tests '*AttachmentServiceTest' --tests '*ImageVariantProcessorTest' --tests '*RetryPolicyTest' --tests '*AttachmentReconcilerTest' --tests '*StagingCleanerTest'` | `BUILD SUCCESSFUL` | +| Contract/Compose | `python -X utf8 scripts/check_contract.py`; `docker compose --env-file .env.example config --quiet` | PASS | +| Публичный smoke | `python -X utf8 tests/smoke.py --base-url http://localhost:8080` | PASS | +| Worker stop, broker/API restart, redelivery | `python -X utf8 student_tests/lab5_worker_recovery.py` | PASS; original неизменен, 3 variants, duplicate не создаёт rows | +| COMMIT→publish и result COMMIT→ack crash | `python -X utf8 student_tests/lab5_fault_injection.py` | PASS; обе задачи автоматически дошли до ready | +| DLQ, replay, lease | `python -X utf8 student_tests/lab5_dlq_replay_lease.py` | PASS; DLQ +1, одна audit-запись, ready не replayed, expired lease восстановлен | + +Fault flags выключены по умолчанию. `FAULT_CRASH_AFTER_OUTBOX_COMMIT=true` один раз завершает API через `Runtime.halt(87)` после DB COMMIT до publish. После restart republisher находит `published=false`, и job достигает ready. `FAULT_CRASH_AFTER_RESULT_COMMIT=true` один раз завершает worker через `Runtime.halt(86)` после атомарного ready до consumer ack; RabbitMQ redelivery проверяет ready и завершает ту же job без второго набора вариантов. + +Подробный журнал: `evidence/lab5-level4-2026-11-19.md`. + +## Ограничения + +Это уровень 4, не исследовательский трек 5: производительность для матрицы concurrency/prefetch не измерялась, multi-version reorder не исследовался. RabbitMQ, PostgreSQL и MinIO развёрнуты по одному экземпляру; volumes переживают container restart, но не потерю host/disk. At-least-once + идемпотентный эффект не является exactly-once доставкой. diff --git a/build.gradle b/build.gradle index 22435bce..5c37fd68 100644 --- a/build.gradle +++ b/build.gradle @@ -24,6 +24,7 @@ dependencies { implementation 'org.springframework.boot:spring-boot-starter-validation' implementation 'org.springframework.boot:spring-boot-starter-jdbc' implementation 'org.springframework.boot:spring-boot-starter-data-redis' + implementation 'org.springframework.boot:spring-boot-starter-amqp' implementation 'org.springframework.boot:spring-boot-flyway' implementation 'org.flywaydb:flyway-core' implementation 'org.flywaydb:flyway-database-postgresql' @@ -31,6 +32,8 @@ dependencies { implementation 'org.bouncycastle:bcprov-jdk18on:1.84' implementation 'org.apache.commons:commons-pool2' implementation 'io.minio:minio:8.6.0' + implementation 'net.coobird:thumbnailator:0.4.20' + implementation 'org.sejda.imageio:webp-imageio:0.1.6' runtimeOnly 'org.postgresql:postgresql' implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310' diff --git a/compose.yaml b/compose.yaml index bc0ebf42..82fa8d81 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,4 +1,4 @@ -name: hla-lab4 +name: hla-lab5 x-api-environment: &api-environment APP_HOST: 0.0.0.0 @@ -30,6 +30,29 @@ x-api-environment: &api-environment MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} MAX_CONCURRENT_UPLOADS: ${MAX_CONCURRENT_UPLOADS:-3} UPLOAD_PERMIT_WAIT_MILLIS: ${UPLOAD_PERMIT_WAIT_MILLIS:-10000} + RABBITMQ_HOST: rabbitmq + RABBITMQ_PORT: 5672 + RABBITMQ_USER: ${RABBITMQ_USER:-messenger} + RABBITMQ_PASSWORD: ${RABBITMQ_PASSWORD:?Set RABBITMQ_PASSWORD in .env} + RABBITMQ_VHOST: ${RABBITMQ_VHOST:-/} + ATTACHMENT_JOB_EXCHANGE: ${ATTACHMENT_JOB_EXCHANGE:-attachments.v1} + ATTACHMENT_JOB_QUEUE: ${ATTACHMENT_JOB_QUEUE:-attachments.process.level4.v1} + ATTACHMENT_JOB_ROUTING_KEY: ${ATTACHMENT_JOB_ROUTING_KEY:-attachment.process.v1} + ATTACHMENT_DLQ_EXCHANGE: ${ATTACHMENT_DLQ_EXCHANGE:-attachments.dlx.v1} + ATTACHMENT_DLQ_QUEUE: ${ATTACHMENT_DLQ_QUEUE:-attachments.failed.v1} + ATTACHMENT_DLQ_ROUTING_KEY: ${ATTACHMENT_DLQ_ROUTING_KEY:-attachment.failed.v1} + WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2} + WORKER_PREFETCH: ${WORKER_PREFETCH:-1} + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + JOB_RETRY_BASE_DELAY: ${JOB_RETRY_BASE_DELAY:-1s} + JOB_RETRY_MAX_DELAY: ${JOB_RETRY_MAX_DELAY:-30s} + JOB_TIMEOUT: ${JOB_TIMEOUT:-60s} + JOB_LEASE_DURATION: ${JOB_LEASE_DURATION:-90s} + JOB_LEASE_REAPER_INTERVAL: ${JOB_LEASE_REAPER_INTERVAL:-5s} + WORKER_MAX_IMAGE_PIXELS: ${WORKER_MAX_IMAGE_PIXELS:-40000000} + WORKER_MEMORY_BUDGET_BYTES: ${WORKER_MEMORY_BUDGET_BYTES:-536870912} + WORKER_MEMORY_WAIT: ${WORKER_MEMORY_WAIT:-2s} + STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400} ATTACHMENT_CLEANUP_GRACE_SECONDS: ${ATTACHMENT_CLEANUP_GRACE_SECONDS:-3600} ATTACHMENT_CLEANUP_DRY_RUN: ${ATTACHMENT_CLEANUP_DRY_RUN:-false} ATTACHMENT_RECONCILE_INTERVAL_MILLIS: ${ATTACHMENT_RECONCILE_INTERVAL_MILLIS:-600000} @@ -69,6 +92,26 @@ services: mem_limit: 256m networks: [backend] + rabbitmq: + image: rabbitmq:4.1.4-management-alpine + environment: + RABBITMQ_DEFAULT_USER: ${RABBITMQ_USER:-messenger} + RABBITMQ_DEFAULT_PASS: ${RABBITMQ_PASSWORD:?Set RABBITMQ_PASSWORD in .env} + RABBITMQ_DEFAULT_VHOST: ${RABBITMQ_VHOST:-/} + RABBITMQ_SERVER_ADDITIONAL_ERL_ARGS: "+S 2:2" + volumes: + - rabbitmq-data:/var/lib/rabbitmq + healthcheck: + test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"] + interval: 10s + timeout: 10s + start_period: 60s + retries: 12 + restart: unless-stopped + cpus: 0.5 + mem_limit: 1024m + networks: [backend] + minio: image: bitnamilegacy/minio:2025.4.22-debian-12-r1@sha256:d7cd0e172c4cc0870f4bdc3142018e2a37be9acf04d68f386600daad427e0cab environment: @@ -103,13 +146,24 @@ services: command: - | set -eu - mc alias set local http://minio:9000 "$$MINIO_ROOT_USER" "$$MINIO_ROOT_PASSWORD" - mc mb --ignore-existing "local/$$S3_BUCKET" - mc anonymous set none "local/$$S3_BUCKET" sed "s/__S3_BUCKET__/$$S3_BUCKET/g" /policy/minio-api-policy.json > /tmp/minio-api-policy.json - mc admin user add local "$$S3_ACCESS_KEY_ID" "$$S3_SECRET_ACCESS_KEY" || true - mc admin policy create local messenger-attachments-rw /tmp/minio-api-policy.json || true - mc admin policy attach local messenger-attachments-rw --user "$$S3_ACCESS_KEY_ID" + attempt=0 + until mc alias set local http://minio:9000 "$$MINIO_ROOT_USER" "$$MINIO_ROOT_PASSWORD" \ + && mc mb --ignore-existing "local/$$S3_BUCKET" \ + && mc anonymous set none "local/$$S3_BUCKET" \ + && (mc admin user add local "$$S3_ACCESS_KEY_ID" "$$S3_SECRET_ACCESS_KEY" \ + || mc admin user info local "$$S3_ACCESS_KEY_ID") \ + && (mc admin policy create local messenger-attachments-rw /tmp/minio-api-policy.json \ + || mc admin policy info local messenger-attachments-rw) \ + && mc admin policy attach local messenger-attachments-rw --user "$$S3_ACCESS_KEY_ID" + do + attempt=$$((attempt + 1)) + if [ "$$attempt" -ge 30 ]; then + echo "MinIO bootstrap did not complete after 30 attempts" >&2 + exit 1 + fi + sleep 2 + done restart: "no" networks: [backend] @@ -144,38 +198,45 @@ services: # One-shot Flyway runner. It is invoked explicitly before API replicas. migrate: - image: hla-lab4-api:local + image: hla-lab5-app:local build: context: . environment: <<: *api-environment FLYWAY_ENABLED: "true" MIGRATE_ONLY: "true" + MESSENGER_ROLE: migration SPRING_MAIN_WEB_APPLICATION_TYPE: none depends_on: postgres: condition: service_healthy redis: condition: service_healthy + rabbitmq: + condition: service_healthy restart: "no" cpus: 0.75 mem_limit: 768m networks: [backend] api: - image: hla-lab4-api:local + image: hla-lab5-app:local build: context: . environment: <<: *api-environment FLYWAY_ENABLED: "false" + MESSENGER_ROLE: api + FAULT_CRASH_AFTER_OUTBOX_COMMIT: ${FAULT_CRASH_AFTER_OUTBOX_COMMIT:-false} depends_on: - postgres: - condition: service_healthy + migrate: + condition: service_completed_successfully redis: condition: service_healthy minio-init: condition: service_completed_successfully + rabbitmq: + condition: service_healthy healthcheck: test: ["CMD", "curl", "--fail", "--silent", "http://localhost:8080/health/ready"] interval: 2s @@ -189,6 +250,31 @@ services: mem_limit: 768m networks: [backend] + worker: + image: hla-lab5-app:local + environment: + <<: *api-environment + FLYWAY_ENABLED: "false" + MESSENGER_ROLE: worker + SPRING_MAIN_WEB_APPLICATION_TYPE: none + JAVA_TOOL_OPTIONS: -XX:MaxRAMPercentage=70 + FAULT_CRASH_AFTER_RESULT_COMMIT: ${FAULT_CRASH_AFTER_RESULT_COMMIT:-false} + depends_on: + migrate: + condition: service_completed_successfully + minio-init: + condition: service_completed_successfully + rabbitmq: + condition: service_healthy + healthcheck: + disable: true + init: true + stop_grace_period: 20s + restart: unless-stopped + cpus: 1.0 + mem_limit: 1024m + networks: [backend] + nginx: image: nginx:1.27.4-bookworm ports: @@ -217,3 +303,4 @@ volumes: postgres-data: redis-data: minio-data: + rabbitmq-data: diff --git a/evidence/lab5-2026-11-18.md b/evidence/lab5-2026-11-18.md new file mode 100644 index 00000000..a782c2fc --- /dev/null +++ b/evidence/lab5-2026-11-18.md @@ -0,0 +1,41 @@ +# Lab5 verification — 2026-11-18 + +Среда: Windows, Docker 28.0.1, Docker Compose 2.33.1, Java 23, Spring Boot 4.1.1, RabbitMQ 4.1.4. + +## Статические и unit-проверки + +```text +docker compose --env-file .env.example config --quiet +PASS (exit 0) + +gradlew test --tests '*AttachmentServiceTest' --tests '*ThumbnailProcessorTest' --tests '*AttachmentReconcilerTest' --tests '*StagingCleanerTest' +BUILD SUCCESSFUL +``` + +## Публичный сценарий + +```text +python tests/smoke.py --base-url http://localhost:8080 +PASS: lab5 public API scenario; infrastructure and grading evidence remain separate. +``` + +В момент проверки отдельные services `api`, `worker`, `rabbitmq`, `postgres`, `redis`, `minio` и `nginx` были запущены; RabbitMQ queue `attachments.process.v1` имела `durable=true`. + +## Остановка worker, restart и redelivery + +```text +python student_tests/lab5_worker_recovery.py +PASS: stopped worker, durable restart recovery and duplicate delivery +``` + +Сценарий теста: + +1. останавливает worker; +2. получает upload `202 queued`, проверяет `409` content и привязку к сообщению; +3. перезапускает API и RabbitMQ без удаления volumes; +4. запускает worker и ждёт `ready`; +5. сверяет original bytes и единственный thumbnail; +6. публикует тот же `job_id` повторно; +7. проверяет terminal `ready` и ровно одну запись thumbnail. + +Синтетические пароли и токены тест не печатает и в evidence не сохраняет. diff --git a/evidence/lab5-level4-2026-11-19.md b/evidence/lab5-level4-2026-11-19.md new file mode 100644 index 00000000..00b9be60 --- /dev/null +++ b/evidence/lab5-level4-2026-11-19.md @@ -0,0 +1,56 @@ +# Lab5 level 4 verification — 2026-11-19 + +Среда: Windows, Docker Compose, Java 23, Spring Boot 4.1.1, PostgreSQL 16.4, RabbitMQ 4.1.4, MinIO. + +## Статические и unit-проверки + +```text +python -X utf8 scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. + +docker compose --env-file .env.example config --quiet +exit 0 + +gradlew test --tests '*AttachmentServiceTest' --tests '*ImageVariantProcessorTest' \ + --tests '*RetryPolicyTest' --tests '*AttachmentReconcilerTest' \ + --tests '*StagingCleanerTest' +BUILD SUCCESSFUL +``` + +`ImageVariantProcessorTest` проверяет реальные JPEG/WebP signatures, ImageIO decode и размеры thumbnail/crop/optimized. `RetryPolicyTest` проверяет bounded exponential backoff и jitter. + +## API и recovery + +```text +python -X utf8 tests/smoke.py --base-url http://localhost:8080 +PASS: lab5 public API scenario; infrastructure and grading evidence remain separate. + +python -X utf8 student_tests/lab5_worker_recovery.py +PASS: stopped worker, durable restart recovery and duplicate delivery +``` + +Recovery test останавливает worker, получает `202 queued`, перезапускает API и RabbitMQ без удаления volumes, запускает worker и сверяет original SHA-256, thumbnail 256×160, crop 128×128, WebP signature. Повторная публикация того же `job_id` оставляет `ready` и ровно три variant rows. + +## Доказанные окна отказа + +```text +python -X utf8 student_tests/lab5_fault_injection.py +PASS: outbox commit/publish crash and result commit/ack crash recovered +``` + +1. API завершается после COMMIT attachment/outbox до publish. Перезапущенный API republisher публикует сохранённое намерение; новый upload не создаётся вручную. +2. Worker завершается после записи объектов и atomic ready COMMIT до ack. Redelivery завершает тот же effect; variant rows остаются уникальными. + +## DLQ, replay и lease + +```text +python -X utf8 student_tests/lab5_dlq_replay_lease.py +PASS: DLQ, guarded replay and expired lease recovery +``` + +- malformed persistent JSON был permanent failure и увеличил `attachments.failed.v1` ровно на 1; +- failed job replayed один раз, audit count = 1; повтор в queued/ready дал no-op; +- после replay получены те же три variant names без второго набора; +- искусственно истёкший processing lease был requeued, attempt увеличился, job дошёл до ready. + +Секреты, session tokens и contents сообщений в evidence не сохранялись. Docker volumes в проверках не удалялись. diff --git a/infra/minio-api-policy.json b/infra/minio-api-policy.json index 97085216..0ee222d4 100644 --- a/infra/minio-api-policy.json +++ b/infra/minio-api-policy.json @@ -19,7 +19,8 @@ "s3:DeleteObject" ], "Resource": [ - "arn:aws:s3:::__S3_BUCKET__/attachments/*" + "arn:aws:s3:::__S3_BUCKET__/attachments/*", + "arn:aws:s3:::__S3_BUCKET__/staging/*" ] } ] diff --git a/scripts/replay-failed.ps1 b/scripts/replay-failed.ps1 new file mode 100644 index 00000000..4bd2343e --- /dev/null +++ b/scripts/replay-failed.ps1 @@ -0,0 +1,57 @@ +param( + [Parameter(Mandatory = $true)] + [string]$JobId, + [string]$RequestedBy = $env:USERNAME, + [string]$EnvFile = ".env" +) + +$parsedJobId = [guid]::Empty +if (-not [guid]::TryParse($JobId, [ref]$parsedJobId)) { + throw "JobId must be a UUID" +} +if ($RequestedBy -notmatch '^[A-Za-z0-9_.@-]{1,128}$') { + throw "RequestedBy contains unsupported characters" +} + +$sql = @" +WITH candidate AS ( + SELECT j.id, j.attachment_id, j.attempt + FROM attachment_jobs j + JOIN attachments a ON a.id = j.attachment_id + WHERE j.id = '$parsedJobId'::uuid + AND j.status = 'failed' AND a.status = 'failed' + FOR UPDATE OF j, a +), audited AS ( + INSERT INTO attachment_job_replays (job_id, requested_by, previous_attempt) + SELECT id, '$RequestedBy', attempt FROM candidate + RETURNING job_id +), reset_job AS ( + UPDATE attachment_jobs j + SET status = 'queued', attempt = 1, published = false, + last_error_code = NULL, next_attempt_at = clock_timestamp(), + lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp() + FROM candidate c, audited a + WHERE j.id = c.id AND a.job_id = c.id + RETURNING j.attachment_id +), reset_attachment AS ( + UPDATE attachments a + SET status = 'queued', error_code = NULL, updated_at = clock_timestamp() + FROM reset_job r + WHERE a.id = r.attachment_id AND a.status = 'failed' + RETURNING a.id +) +SELECT CASE WHEN EXISTS (SELECT 1 FROM reset_attachment) + THEN 'replayed' ELSE 'no-op' END; +"@ + +$result = docker compose --env-file $EnvFile exec -T postgres ` + psql -v ON_ERROR_STOP=1 -U messenger -d messenger -At -c $sql +if ($LASTEXITCODE -ne 0) { + throw "Replay transaction failed" +} + +if (($result | Select-Object -Last 1).Trim() -eq "replayed") { + Write-Output "Replay requested for failed job $parsedJobId by $RequestedBy" +} else { + Write-Output "No-op: job $parsedJobId is missing, not failed, or already recovered" +} diff --git a/scripts/replay-failed.sh b/scripts/replay-failed.sh new file mode 100644 index 00000000..25fa5a1c --- /dev/null +++ b/scripts/replay-failed.sh @@ -0,0 +1,45 @@ +#!/bin/sh +set -eu + +job_id="${1:?usage: replay-failed.sh JOB_UUID [REQUESTED_BY] [ENV_FILE]}" +requested_by="${2:-operator}" +env_file="${3:-.env}" + +case "$job_id" in + ????????-????-????-????-????????????) ;; + *) echo "JobId must be a UUID" >&2; exit 2 ;; +esac +case "$requested_by" in + *[!A-Za-z0-9_.@-]*|'') echo "RequestedBy contains unsupported characters" >&2; exit 2 ;; +esac + +sql="WITH candidate AS ( + SELECT j.id, j.attachment_id, j.attempt FROM attachment_jobs j + JOIN attachments a ON a.id = j.attachment_id + WHERE j.id = '$job_id'::uuid AND j.status = 'failed' AND a.status = 'failed' + FOR UPDATE OF j, a +), audited AS ( + INSERT INTO attachment_job_replays (job_id, requested_by, previous_attempt) + SELECT id, '$requested_by', attempt FROM candidate RETURNING job_id +), reset_job AS ( + UPDATE attachment_jobs j SET status = 'queued', attempt = 1, published = false, + last_error_code = NULL, next_attempt_at = clock_timestamp(), + lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp() + FROM candidate c, audited a WHERE j.id = c.id AND a.job_id = c.id + RETURNING j.attachment_id +), reset_attachment AS ( + UPDATE attachments a SET status = 'queued', error_code = NULL, + updated_at = clock_timestamp() + FROM reset_job r WHERE a.id = r.attachment_id AND a.status = 'failed' + RETURNING a.id +) +SELECT CASE WHEN EXISTS (SELECT 1 FROM reset_attachment) + THEN 'replayed' ELSE 'no-op' END;" + +result="$(docker compose --env-file "$env_file" exec -T postgres \ + psql -v ON_ERROR_STOP=1 -U messenger -d messenger -At -c "$sql")" +if [ "$result" = "replayed" ]; then + echo "Replay requested for failed job $job_id by $requested_by" +else + echo "No-op: job $job_id is missing, not failed, or already recovered" +fi diff --git a/src/main/java/com/example/mtusi_messenger/config/RabbitJobConfig.java b/src/main/java/com/example/mtusi_messenger/config/RabbitJobConfig.java new file mode 100644 index 00000000..ec334a91 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/config/RabbitJobConfig.java @@ -0,0 +1,57 @@ +package com.example.mtusi_messenger.config; + +import org.springframework.amqp.core.Binding; +import org.springframework.amqp.core.BindingBuilder; +import org.springframework.amqp.core.DirectExchange; +import org.springframework.amqp.core.Queue; +import org.springframework.amqp.core.QueueBuilder; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class RabbitJobConfig { + @Bean + DirectExchange attachmentExchange(@Value("${messenger.jobs.exchange}") String name) { + return new DirectExchange(name, true, false); + } + + @Bean + Queue attachmentQueue( + @Value("${messenger.jobs.queue}") String name, + @Value("${messenger.jobs.dead-letter-exchange}") String deadLetterExchange, + @Value("${messenger.jobs.dead-letter-routing-key}") String deadLetterRoutingKey) { + return QueueBuilder.durable(name) + .withArgument("x-dead-letter-exchange", deadLetterExchange) + .withArgument("x-dead-letter-routing-key", deadLetterRoutingKey) + .build(); + } + + @Bean + DirectExchange attachmentDeadLetterExchange( + @Value("${messenger.jobs.dead-letter-exchange}") String name) { + return new DirectExchange(name, true, false); + } + + @Bean + Queue attachmentDeadLetterQueue(@Value("${messenger.jobs.dead-letter-queue}") String name) { + return QueueBuilder.durable(name).build(); + } + + @Bean + Binding attachmentBinding( + @Qualifier("attachmentQueue") Queue attachmentQueue, + @Qualifier("attachmentExchange") DirectExchange attachmentExchange, + @Value("${messenger.jobs.routing-key}") String routingKey) { + return BindingBuilder.bind(attachmentQueue).to(attachmentExchange).with(routingKey); + } + + @Bean + Binding attachmentDeadLetterBinding( + @Qualifier("attachmentDeadLetterQueue") Queue queue, + @Qualifier("attachmentDeadLetterExchange") DirectExchange exchange, + @Value("${messenger.jobs.dead-letter-routing-key}") String routingKey) { + return BindingBuilder.bind(queue).to(exchange).with(routingKey); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/controller/AttachmentController.java b/src/main/java/com/example/mtusi_messenger/controller/AttachmentController.java index 9d5a116b..72350f53 100644 --- a/src/main/java/com/example/mtusi_messenger/controller/AttachmentController.java +++ b/src/main/java/com/example/mtusi_messenger/controller/AttachmentController.java @@ -1,7 +1,6 @@ package com.example.mtusi_messenger.controller; import com.example.mtusi_messenger.dto.AttachmentResponse; -import com.example.mtusi_messenger.exception.ApiExceptions; import com.example.mtusi_messenger.model.Attachment; import com.example.mtusi_messenger.security.SessionPrincipal; import com.example.mtusi_messenger.service.AttachmentService; @@ -47,7 +46,7 @@ public class AttachmentController { ) throws IOException { Attachment attachment = attachments.upload(parse(chatId), principal.user().id(), filename, contentType, request.getContentLengthLong(), request.getInputStream()); - return ResponseEntity.status(HttpStatus.CREATED).body(AttachmentResponse.from(attachment)); + return ResponseEntity.status(HttpStatus.ACCEPTED).body(AttachmentResponse.from(attachment)); } @GetMapping("/attachments/{attachmentId}") @@ -64,15 +63,13 @@ public class AttachmentController { @PathVariable String attachmentId, @RequestParam(defaultValue = "original") String variant ) { - if (!"original".equals(variant)) { - throw ApiExceptions.invalid("Unsupported attachment variant"); - } - AttachmentService.Download download = attachments.download(parse(attachmentId), principal.user().id()); + AttachmentService.Download download = attachments.download( + parse(attachmentId), principal.user().id(), variant); return ResponseEntity.ok() - .contentType(MediaType.parseMediaType(download.attachment().contentType())) + .contentType(MediaType.parseMediaType(download.contentType())) .contentLength(download.bytes().length) .header(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.inline() - .filename(download.attachment().filename(), StandardCharsets.UTF_8).build().toString()) + .filename(download.filename(), StandardCharsets.UTF_8).build().toString()) .body(download.bytes()); } } diff --git a/src/main/java/com/example/mtusi_messenger/dto/AttachmentResponse.java b/src/main/java/com/example/mtusi_messenger/dto/AttachmentResponse.java index 01a551b0..7d7d2fa6 100644 --- a/src/main/java/com/example/mtusi_messenger/dto/AttachmentResponse.java +++ b/src/main/java/com/example/mtusi_messenger/dto/AttachmentResponse.java @@ -14,7 +14,7 @@ public record AttachmentResponse(UUID id, long size_bytes, String sha256, String status, - List variants, + List variants, String error_code, Instant created_at, Instant updated_at) { @@ -27,9 +27,9 @@ public record AttachmentResponse(UUID id, attachment.contentType(), attachment.sizeBytes(), attachment.sha256(), - "ready", - List.of(), - null, + attachment.status(), + attachment.variants().stream().map(AttachmentVariantResponse::from).toList(), + attachment.errorCode(), attachment.createdAt(), attachment.updatedAt()); } diff --git a/src/main/java/com/example/mtusi_messenger/dto/AttachmentVariantResponse.java b/src/main/java/com/example/mtusi_messenger/dto/AttachmentVariantResponse.java new file mode 100644 index 00000000..7bbdc3c1 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/AttachmentVariantResponse.java @@ -0,0 +1,16 @@ +package com.example.mtusi_messenger.dto; + +import com.example.mtusi_messenger.model.AttachmentVariant; + +public record AttachmentVariantResponse(String name, + String content_type, + long size_bytes, + int width, + int height, + String sha256) { + public static AttachmentVariantResponse from(AttachmentVariant variant) { + return new AttachmentVariantResponse( + variant.name(), variant.contentType(), variant.sizeBytes(), + variant.width(), variant.height(), variant.sha256()); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/model/Attachment.java b/src/main/java/com/example/mtusi_messenger/model/Attachment.java index b93415be..acb2515c 100644 --- a/src/main/java/com/example/mtusi_messenger/model/Attachment.java +++ b/src/main/java/com/example/mtusi_messenger/model/Attachment.java @@ -1,6 +1,7 @@ package com.example.mtusi_messenger.model; import java.time.Instant; +import java.util.List; import java.util.UUID; public record Attachment(UUID id, @@ -11,6 +12,27 @@ public record Attachment(UUID id, long sizeBytes, String sha256, String objectKey, + String stagingKey, + String status, + List variants, + String errorCode, Instant createdAt, Instant updatedAt) { + public Attachment { + variants = variants == null ? List.of() : List.copyOf(variants); + } + + public Attachment(UUID id, + UUID chatId, + UUID ownerId, + String filename, + String contentType, + long sizeBytes, + String sha256, + String objectKey, + Instant createdAt, + Instant updatedAt) { + this(id, chatId, ownerId, filename, contentType, sizeBytes, sha256, objectKey, + null, "ready", List.of(), null, createdAt, updatedAt); + } } diff --git a/src/main/java/com/example/mtusi_messenger/model/AttachmentJob.java b/src/main/java/com/example/mtusi_messenger/model/AttachmentJob.java new file mode 100644 index 00000000..0708e84e --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/model/AttachmentJob.java @@ -0,0 +1,37 @@ +package com.example.mtusi_messenger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.time.Instant; +import java.util.UUID; + +public record AttachmentJob( + @JsonProperty("schema_version") int schemaVersion, + @JsonProperty("job_id") UUID jobId, + String type, + @JsonProperty("attachment_id") UUID attachmentId, + @JsonProperty("pipeline_version") int pipelineVersion, + int attempt, + @JsonProperty("created_at") Instant createdAt) { + + public static final int SCHEMA_VERSION = 1; + public static final int PIPELINE_VERSION = 1; + public static final String TYPE = "attachment.process.v1"; + + public AttachmentJob { + if (schemaVersion != SCHEMA_VERSION || !TYPE.equals(type) + || pipelineVersion < 1 || attempt < 1) { + throw new IllegalArgumentException("Unsupported attachment job message"); + } + } + + public static AttachmentJob first(UUID jobId, UUID attachmentId, Instant createdAt) { + return new AttachmentJob(SCHEMA_VERSION, jobId, TYPE, attachmentId, + PIPELINE_VERSION, 1, createdAt); + } + + public AttachmentJob nextAttempt(int nextAttempt) { + return new AttachmentJob(schemaVersion, jobId, type, attachmentId, + pipelineVersion, nextAttempt, createdAt); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/model/AttachmentVariant.java b/src/main/java/com/example/mtusi_messenger/model/AttachmentVariant.java new file mode 100644 index 00000000..ff4e8092 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/model/AttachmentVariant.java @@ -0,0 +1,10 @@ +package com.example.mtusi_messenger.model; + +public record AttachmentVariant(String name, + String contentType, + long sizeBytes, + int width, + int height, + String sha256, + String objectKey) { +} diff --git a/src/main/java/com/example/mtusi_messenger/queue/AttachmentJobPublisher.java b/src/main/java/com/example/mtusi_messenger/queue/AttachmentJobPublisher.java new file mode 100644 index 00000000..ce87b427 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/queue/AttachmentJobPublisher.java @@ -0,0 +1,65 @@ +package com.example.mtusi_messenger.queue; + +import com.example.mtusi_messenger.model.AttachmentJob; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.core.MessageDeliveryMode; +import org.springframework.amqp.core.MessageProperties; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.time.Duration; + +@Component +public class AttachmentJobPublisher { + private final RabbitTemplate rabbit; + private final ObjectMapper mapper; + private final String exchange; + private final String routingKey; + private final long confirmTimeoutMillis; + + public AttachmentJobPublisher( + RabbitTemplate rabbit, + ObjectMapper mapper, + @Value("${messenger.jobs.exchange}") String exchange, + @Value("${messenger.jobs.routing-key}") String routingKey, + @Value("${messenger.jobs.publish-confirm-timeout:5s}") Duration confirmTimeout) { + this.rabbit = rabbit; + this.mapper = mapper; + this.exchange = exchange; + this.routingKey = routingKey; + this.confirmTimeoutMillis = confirmTimeout.toMillis(); + this.rabbit.setMandatory(true); + } + + public void publish(AttachmentJob job) { + try { + byte[] body = mapper.writeValueAsBytes(job); + MessageProperties properties = new MessageProperties(); + properties.setContentType(MessageProperties.CONTENT_TYPE_JSON); + properties.setContentEncoding("UTF-8"); + properties.setDeliveryMode(MessageDeliveryMode.PERSISTENT); + properties.setMessageId(job.jobId().toString()); + properties.setHeader("schema_version", job.schemaVersion()); + Message message = new Message(body, properties); + + rabbit.invoke(operations -> { + operations.send(exchange, routingKey, message); + operations.waitForConfirmsOrDie(confirmTimeoutMillis); + return null; + }); + } catch (JsonProcessingException error) { + throw new JobPublishException("Cannot encode attachment job", error); + } catch (RuntimeException error) { + throw new JobPublishException("RabbitMQ did not confirm attachment job", error); + } + } + + public static final class JobPublishException extends RuntimeException { + public JobPublishException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/src/main/java/com/example/mtusi_messenger/queue/ExpiredLeaseReaper.java b/src/main/java/com/example/mtusi_messenger/queue/ExpiredLeaseReaper.java new file mode 100644 index 00000000..7672b84f --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/queue/ExpiredLeaseReaper.java @@ -0,0 +1,55 @@ +package com.example.mtusi_messenger.queue; + +import com.example.mtusi_messenger.repository.AttachmentRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; +import org.springframework.transaction.support.TransactionTemplate; + +import java.time.Clock; + +@Component +@ConditionalOnProperty(name = "messenger.role", havingValue = "api", matchIfMissing = true) +public class ExpiredLeaseReaper { + private static final Logger log = LoggerFactory.getLogger(ExpiredLeaseReaper.class); + private final AttachmentRepository attachments; + private final RetryPolicy retryPolicy; + private final TransactionTemplate transaction; + private final int maxAttempts; + private final Clock clock = Clock.systemUTC(); + + public ExpiredLeaseReaper( + AttachmentRepository attachments, + RetryPolicy retryPolicy, + TransactionTemplate transaction, + @Value("${messenger.jobs.max-attempts:5}") int maxAttempts) { + this.attachments = attachments; + this.retryPolicy = retryPolicy; + this.transaction = transaction; + this.maxAttempts = maxAttempts; + } + + @Scheduled(fixedDelayString = "${messenger.jobs.lease-reaper-interval:5s}") + public void recoverExpired() { + for (var job : attachments.findExpiredJobs(50)) { + try { + transaction.executeWithoutResult(status -> { + if (job.attempt() >= maxAttempts) { + attachments.failExpired(job.jobId(), job.attachmentId(), "retry_exhausted"); + } else { + int nextAttempt = job.attempt() + 1; + attachments.requeueExpired( + job.jobId(), job.attachmentId(), nextAttempt, "processing_timeout", + clock.instant().plus(retryPolicy.delayForAttempt(nextAttempt))); + } + }); + } catch (RuntimeException error) { + log.warn("Expired attachment lease recovery postponed for job {}", job.jobId()); + return; + } + } + } +} diff --git a/src/main/java/com/example/mtusi_messenger/queue/RetryPolicy.java b/src/main/java/com/example/mtusi_messenger/queue/RetryPolicy.java new file mode 100644 index 00000000..306375e2 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/queue/RetryPolicy.java @@ -0,0 +1,39 @@ +package com.example.mtusi_messenger.queue; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.time.Duration; +import java.util.concurrent.ThreadLocalRandom; + +@Component +public class RetryPolicy { + private final long baseDelayMillis; + private final long maxDelayMillis; + + public RetryPolicy( + @Value("${messenger.jobs.retry-base-delay:1s}") Duration baseDelay, + @Value("${messenger.jobs.retry-max-delay:30s}") Duration maxDelay) { + if (baseDelay.isNegative() || baseDelay.isZero() || maxDelay.compareTo(baseDelay) < 0) { + throw new IllegalArgumentException("Invalid retry delay configuration"); + } + this.baseDelayMillis = baseDelay.toMillis(); + this.maxDelayMillis = maxDelay.toMillis(); + } + + public Duration delayForAttempt(int nextAttempt) { + int exponent = Math.max(0, Math.min(30, nextAttempt - 2)); + long exponential; + try { + exponential = Math.multiplyExact(baseDelayMillis, 1L << exponent); + } catch (ArithmeticException overflow) { + exponential = maxDelayMillis; + } + long ceiling = Math.min(maxDelayMillis, exponential); + long floor = Math.max(1, ceiling / 2); + long jittered = floor == ceiling + ? ceiling + : ThreadLocalRandom.current().nextLong(floor, ceiling + 1); + return Duration.ofMillis(jittered); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/queue/UnpublishedJobRepublisher.java b/src/main/java/com/example/mtusi_messenger/queue/UnpublishedJobRepublisher.java new file mode 100644 index 00000000..b83b1f51 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/queue/UnpublishedJobRepublisher.java @@ -0,0 +1,34 @@ +package com.example.mtusi_messenger.queue; + +import com.example.mtusi_messenger.repository.AttachmentRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Component +@ConditionalOnProperty(name = "messenger.role", havingValue = "api", matchIfMissing = true) +public class UnpublishedJobRepublisher { + private static final Logger log = LoggerFactory.getLogger(UnpublishedJobRepublisher.class); + private final AttachmentRepository attachments; + private final AttachmentJobPublisher publisher; + + public UnpublishedJobRepublisher(AttachmentRepository attachments, AttachmentJobPublisher publisher) { + this.attachments = attachments; + this.publisher = publisher; + } + + @Scheduled(fixedDelayString = "${messenger.jobs.republish-interval:5s}") + public void publishPending() { + for (var job : attachments.findUnpublishedJobs(50)) { + try { + publisher.publish(job); + attachments.markPublished(job.jobId()); + } catch (RuntimeException error) { + log.warn("Attachment job publication postponed for job {}", job.jobId()); + return; + } + } + } +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/AttachmentRepository.java b/src/main/java/com/example/mtusi_messenger/repository/AttachmentRepository.java index a6b1ce32..0e0ad5fc 100644 --- a/src/main/java/com/example/mtusi_messenger/repository/AttachmentRepository.java +++ b/src/main/java/com/example/mtusi_messenger/repository/AttachmentRepository.java @@ -1,15 +1,37 @@ package com.example.mtusi_messenger.repository; import com.example.mtusi_messenger.model.Attachment; +import com.example.mtusi_messenger.model.AttachmentJob; +import com.example.mtusi_messenger.model.AttachmentVariant; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.Set; +import java.time.Duration; +import java.time.Instant; public interface AttachmentRepository { - Attachment save(Attachment attachment); + Attachment saveQueued(Attachment attachment, AttachmentJob job); Optional findById(UUID id); List findAllByIdsInChat(UUID chatId, List ids); Set findAllObjectKeys(); + Set findActiveStagingKeys(); + void markPublished(UUID jobId); + boolean markPublishFaultInjected(UUID jobId); + List findUnpublishedJobs(int limit); + int currentAttempt(UUID jobId); + boolean claim(UUID jobId, UUID attachmentId, int attempt, UUID leaseToken, Duration leaseDuration); + boolean markQueuedForRetry(UUID jobId, UUID attachmentId, UUID leaseToken, + int nextAttempt, String errorCode, Instant nextAttemptAt); + CompletionResult markReady(UUID jobId, UUID attachmentId, UUID leaseToken, int pipelineVersion, + List variants, boolean injectCrashAfterCommit); + boolean markFailed(UUID jobId, UUID attachmentId, UUID leaseToken, String errorCode); + List findExpiredJobs(int limit); + boolean requeueExpired(UUID jobId, UUID attachmentId, int nextAttempt, + String errorCode, Instant nextAttemptAt); + boolean failExpired(UUID jobId, UUID attachmentId, String errorCode); + + record CompletionResult(boolean completed, boolean crashAfterCommit) { + } } diff --git a/src/main/java/com/example/mtusi_messenger/repository/PostgresAttachmentRepository.java b/src/main/java/com/example/mtusi_messenger/repository/PostgresAttachmentRepository.java index e56e4461..93794691 100644 --- a/src/main/java/com/example/mtusi_messenger/repository/PostgresAttachmentRepository.java +++ b/src/main/java/com/example/mtusi_messenger/repository/PostgresAttachmentRepository.java @@ -1,22 +1,28 @@ package com.example.mtusi_messenger.repository; import com.example.mtusi_messenger.model.Attachment; +import com.example.mtusi_messenger.model.AttachmentJob; +import com.example.mtusi_messenger.model.AttachmentVariant; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; +import java.sql.ResultSet; +import java.sql.SQLException; import java.sql.Timestamp; +import java.time.Duration; +import java.time.Instant; import java.util.Collections; +import java.util.HashSet; import java.util.List; import java.util.Optional; -import java.util.UUID; import java.util.Set; -import java.util.HashSet; +import java.util.UUID; @Repository public class PostgresAttachmentRepository implements AttachmentRepository { private static final String COLUMNS = """ id, chat_id, owner_id, filename, content_type, size_bytes, - sha256, object_key, created_at, updated_at + sha256, object_key, staging_key, status, error_code, created_at, updated_at """; private final JdbcTemplate jdbc; @@ -25,16 +31,22 @@ public class PostgresAttachmentRepository implements AttachmentRepository { } @Override - public Attachment save(Attachment attachment) { + public Attachment saveQueued(Attachment attachment, AttachmentJob job) { jdbc.update(""" INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, - sha256, object_key, status, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'ready', ?, ?) + sha256, object_key, staging_key, status, error_code, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', NULL, ?, ?) """, attachment.id(), attachment.chatId(), attachment.ownerId(), attachment.filename(), attachment.contentType(), attachment.sizeBytes(), - attachment.sha256(), attachment.objectKey(), Timestamp.from(attachment.createdAt()), - Timestamp.from(attachment.updatedAt())); + attachment.sha256(), attachment.objectKey(), attachment.stagingKey(), + Timestamp.from(attachment.createdAt()), Timestamp.from(attachment.updatedAt())); + jdbc.update(""" + INSERT INTO attachment_jobs + (id, attachment_id, pipeline_version, attempt, status, published, created_at, updated_at) + VALUES (?, ?, ?, ?, 'queued', false, ?, ?) + """, job.jobId(), job.attachmentId(), job.pipelineVersion(), job.attempt(), + Timestamp.from(job.createdAt()), Timestamp.from(job.createdAt())); return attachment; } @@ -56,19 +68,236 @@ public class PostgresAttachmentRepository implements AttachmentRepository { args[i + 1] = ids.get(i); } return jdbc.query("SELECT " + COLUMNS + " FROM attachments WHERE chat_id = ? AND id IN (" - + placeholders + ") AND status = 'ready'", + + placeholders + ") AND status <> 'failed'", (rs, rowNum) -> map(rs), args); } @Override public Set findAllObjectKeys() { - return new HashSet<>(jdbc.query("SELECT object_key FROM attachments", + Set keys = new HashSet<>(jdbc.query( + "SELECT object_key FROM attachments WHERE status = 'ready'", (rs, rowNum) -> rs.getString("object_key"))); + keys.addAll(jdbc.query("SELECT object_key FROM attachment_variants", + (rs, rowNum) -> rs.getString("object_key"))); + return keys; } - private static Attachment map(java.sql.ResultSet rs) throws java.sql.SQLException { + @Override + public Set findActiveStagingKeys() { + return new HashSet<>(jdbc.query(""" + SELECT staging_key + FROM attachments + WHERE status IN ('queued', 'processing') AND staging_key IS NOT NULL + """, (rs, rowNum) -> rs.getString("staging_key"))); + } + + @Override + public void markPublished(UUID jobId) { + jdbc.update(""" + UPDATE attachment_jobs + SET published = true, updated_at = clock_timestamp() + WHERE id = ? AND status = 'queued' + """, jobId); + } + + @Override + public boolean markPublishFaultInjected(UUID jobId) { + return jdbc.update(""" + UPDATE attachment_jobs + SET publish_fault_injected = true, updated_at = clock_timestamp() + WHERE id = ? AND publish_fault_injected = false AND status = 'queued' + """, jobId) == 1; + } + + @Override + public List findUnpublishedJobs(int limit) { + return jdbc.query(""" + SELECT id, attachment_id, pipeline_version, attempt, created_at + FROM attachment_jobs + WHERE status = 'queued' AND published = false + AND next_attempt_at <= clock_timestamp() + ORDER BY next_attempt_at, created_at, id + LIMIT ? + """, (rs, rowNum) -> mapJob(rs), limit); + } + + @Override + public int currentAttempt(UUID jobId) { + Integer attempt = jdbc.query("SELECT attempt FROM attachment_jobs WHERE id = ?", + (rs, rowNum) -> rs.getInt("attempt"), jobId).stream().findFirst().orElse(null); + return attempt == null ? 1 : attempt; + } + + @Override + public boolean claim(UUID jobId, UUID attachmentId, int attempt, + UUID leaseToken, Duration leaseDuration) { + int claimed = jdbc.update(""" + UPDATE attachment_jobs + SET status = 'processing', attempt = GREATEST(attempt, ?), + lease_token = ?, + lease_until = clock_timestamp() + (? * interval '1 millisecond'), + updated_at = clock_timestamp() + WHERE id = ? AND attachment_id = ? + AND (status = 'queued' + OR (status = 'processing' AND lease_until < clock_timestamp())) + """, attempt, leaseToken, leaseDuration.toMillis(), jobId, attachmentId); + if (claimed == 0) { + return false; + } + jdbc.update(""" + UPDATE attachments + SET status = 'processing', error_code = NULL, updated_at = clock_timestamp() + WHERE id = ? AND status NOT IN ('ready', 'failed') + """, attachmentId); + return true; + } + + @Override + public boolean markQueuedForRetry(UUID jobId, UUID attachmentId, UUID leaseToken, + int nextAttempt, String errorCode, Instant nextAttemptAt) { + int updated = jdbc.update(""" + UPDATE attachment_jobs + SET status = 'queued', attempt = ?, published = false, + last_error_code = ?, next_attempt_at = ?, + lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp() + WHERE id = ? AND attachment_id = ? AND status = 'processing' + AND lease_token = ? + """, nextAttempt, errorCode, Timestamp.from(nextAttemptAt), + jobId, attachmentId, leaseToken); + if (updated == 0) { + return false; + } + jdbc.update(""" + UPDATE attachments + SET status = 'queued', error_code = NULL, updated_at = clock_timestamp() + WHERE id = ? AND status NOT IN ('ready', 'failed') + """, attachmentId); + return true; + } + + @Override + public CompletionResult markReady(UUID jobId, UUID attachmentId, UUID leaseToken, int pipelineVersion, + List variants, boolean injectCrashAfterCommit) { + boolean triggerCrash = injectCrashAfterCommit && Boolean.TRUE.equals(jdbc.query(""" + SELECT NOT result_fault_injected + FROM attachment_jobs + WHERE id = ? AND attachment_id = ? AND status = 'processing' AND lease_token = ? + FOR UPDATE + """, (rs, rowNum) -> rs.getBoolean(1), jobId, attachmentId, leaseToken) + .stream().findFirst().orElse(false)); + int completed = jdbc.update(""" + UPDATE attachment_jobs + SET status = 'ready', published = true, last_error_code = NULL, + lease_token = NULL, lease_until = NULL, + result_fault_injected = result_fault_injected OR ?, + updated_at = clock_timestamp() + WHERE id = ? AND attachment_id = ? AND status = 'processing' + AND lease_token = ? + """, triggerCrash, jobId, attachmentId, leaseToken); + if (completed == 0) { + return new CompletionResult(false, false); + } + for (AttachmentVariant variant : variants) { + jdbc.update(""" + INSERT INTO attachment_variants + (attachment_id, pipeline_version, name, content_type, size_bytes, + width, height, sha256, object_key, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, clock_timestamp()) + ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE SET + content_type = EXCLUDED.content_type, + size_bytes = EXCLUDED.size_bytes, + width = EXCLUDED.width, + height = EXCLUDED.height, + sha256 = EXCLUDED.sha256, + object_key = EXCLUDED.object_key + """, attachmentId, pipelineVersion, variant.name(), variant.contentType(), + variant.sizeBytes(), variant.width(), variant.height(), variant.sha256(), + variant.objectKey()); + } + jdbc.update(""" + UPDATE attachments + SET status = 'ready', error_code = NULL, updated_at = clock_timestamp() + WHERE id = ? AND status <> 'failed' + """, attachmentId); + return new CompletionResult(true, triggerCrash); + } + + @Override + public boolean markFailed(UUID jobId, UUID attachmentId, UUID leaseToken, String errorCode) { + int updated = jdbc.update(""" + UPDATE attachment_jobs + SET status = 'failed', published = true, last_error_code = ?, + lease_token = NULL, lease_until = NULL, + updated_at = clock_timestamp() + WHERE id = ? AND attachment_id = ? AND status = 'processing' + AND lease_token = ? + """, errorCode, jobId, attachmentId, leaseToken); + if (updated == 0) { + return false; + } + jdbc.update(""" + UPDATE attachments + SET status = 'failed', error_code = ?, updated_at = clock_timestamp() + WHERE id = ? AND status <> 'ready' + """, errorCode, attachmentId); + return true; + } + + @Override + public List findExpiredJobs(int limit) { + return jdbc.query(""" + SELECT id, attachment_id, pipeline_version, attempt, created_at + FROM attachment_jobs + WHERE status = 'processing' AND lease_until < clock_timestamp() + ORDER BY lease_until, id + LIMIT ? + """, (rs, rowNum) -> mapJob(rs), limit); + } + + @Override + public boolean requeueExpired(UUID jobId, UUID attachmentId, int nextAttempt, + String errorCode, Instant nextAttemptAt) { + int updated = jdbc.update(""" + UPDATE attachment_jobs + SET status = 'queued', attempt = ?, published = false, + last_error_code = ?, next_attempt_at = ?, + lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp() + WHERE id = ? AND attachment_id = ? AND status = 'processing' + AND lease_until < clock_timestamp() + """, nextAttempt, errorCode, Timestamp.from(nextAttemptAt), jobId, attachmentId); + if (updated == 1) { + jdbc.update(""" + UPDATE attachments SET status = 'queued', error_code = NULL, + updated_at = clock_timestamp() + WHERE id = ? AND status = 'processing' + """, attachmentId); + } + return updated == 1; + } + + @Override + public boolean failExpired(UUID jobId, UUID attachmentId, String errorCode) { + int updated = jdbc.update(""" + UPDATE attachment_jobs + SET status = 'failed', published = true, last_error_code = ?, + lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp() + WHERE id = ? AND attachment_id = ? AND status = 'processing' + AND lease_until < clock_timestamp() + """, errorCode, jobId, attachmentId); + if (updated == 1) { + jdbc.update(""" + UPDATE attachments SET status = 'failed', error_code = ?, + updated_at = clock_timestamp() + WHERE id = ? AND status <> 'ready' + """, errorCode, attachmentId); + } + return updated == 1; + } + + private Attachment map(ResultSet rs) throws SQLException { + UUID id = rs.getObject("id", UUID.class); return new Attachment( - rs.getObject("id", UUID.class), + id, rs.getObject("chat_id", UUID.class), rs.getObject("owner_id", UUID.class), rs.getString("filename"), @@ -76,7 +305,34 @@ public class PostgresAttachmentRepository implements AttachmentRepository { rs.getLong("size_bytes"), rs.getString("sha256"), rs.getString("object_key"), + rs.getString("staging_key"), + rs.getString("status"), + findVariants(id), + rs.getString("error_code"), rs.getTimestamp("created_at").toInstant(), rs.getTimestamp("updated_at").toInstant()); } + + private List findVariants(UUID attachmentId) { + return jdbc.query(""" + SELECT name, content_type, size_bytes, width, height, sha256, object_key + FROM attachment_variants + WHERE attachment_id = ? AND pipeline_version = 1 + ORDER BY name + """, (rs, rowNum) -> new AttachmentVariant( + rs.getString("name"), rs.getString("content_type"), rs.getLong("size_bytes"), + rs.getInt("width"), rs.getInt("height"), rs.getString("sha256"), + rs.getString("object_key")), attachmentId); + } + + private static AttachmentJob mapJob(ResultSet rs) throws SQLException { + return new AttachmentJob( + AttachmentJob.SCHEMA_VERSION, + rs.getObject("id", UUID.class), + AttachmentJob.TYPE, + rs.getObject("attachment_id", UUID.class), + rs.getInt("pipeline_version"), + rs.getInt("attempt"), + rs.getTimestamp("created_at").toInstant()); + } } diff --git a/src/main/java/com/example/mtusi_messenger/service/AttachmentReconciler.java b/src/main/java/com/example/mtusi_messenger/service/AttachmentReconciler.java index 4e45794b..415abb0e 100644 --- a/src/main/java/com/example/mtusi_messenger/service/AttachmentReconciler.java +++ b/src/main/java/com/example/mtusi_messenger/service/AttachmentReconciler.java @@ -6,6 +6,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @@ -16,6 +17,7 @@ import java.util.HashSet; import java.util.Set; @Component +@ConditionalOnProperty(name = "messenger.role", havingValue = "api", matchIfMissing = true) public class AttachmentReconciler { private static final Logger log = LoggerFactory.getLogger(AttachmentReconciler.class); private static final String PREFIX = "attachments/"; diff --git a/src/main/java/com/example/mtusi_messenger/service/AttachmentService.java b/src/main/java/com/example/mtusi_messenger/service/AttachmentService.java index 83a15875..56d7bf63 100644 --- a/src/main/java/com/example/mtusi_messenger/service/AttachmentService.java +++ b/src/main/java/com/example/mtusi_messenger/service/AttachmentService.java @@ -2,6 +2,9 @@ package com.example.mtusi_messenger.service; import com.example.mtusi_messenger.exception.ApiExceptions; import com.example.mtusi_messenger.model.Attachment; +import com.example.mtusi_messenger.model.AttachmentJob; +import com.example.mtusi_messenger.model.AttachmentVariant; +import com.example.mtusi_messenger.queue.AttachmentJobPublisher; import com.example.mtusi_messenger.repository.AttachmentRepository; import com.example.mtusi_messenger.storage.ObjectStorage; import com.example.mtusi_messenger.storage.ObjectStorageException; @@ -34,25 +37,30 @@ public class AttachmentService { private final AttachmentRepository attachments; private final ChatService chats; private final ObjectStorage storage; + private final AttachmentJobPublisher publisher; private final TransactionTemplate transaction; private final long maxUploadBytes; private final long maxImagePixels; private final Semaphore uploadPermits; private final long uploadPermitWaitMillis; + private final boolean injectCrashAfterOutboxCommit; public AttachmentService( AttachmentRepository attachments, ChatService chats, ObjectStorage storage, + AttachmentJobPublisher publisher, TransactionTemplate transaction, @Value("${messenger.attachments.max-upload-bytes:10485760}") long maxUploadBytes, @Value("${messenger.attachments.max-image-pixels:40000000}") long maxImagePixels, @Value("${messenger.attachments.max-concurrent-uploads:3}") int maxConcurrentUploads, - @Value("${messenger.attachments.upload-permit-wait-millis:10000}") long uploadPermitWaitMillis + @Value("${messenger.attachments.upload-permit-wait-millis:10000}") long uploadPermitWaitMillis, + @Value("${messenger.jobs.fault-crash-after-outbox-commit:false}") boolean injectCrashAfterOutboxCommit ) { this.attachments = attachments; this.chats = chats; this.storage = storage; + this.publisher = publisher; this.transaction = transaction; this.maxUploadBytes = maxUploadBytes; this.maxImagePixels = maxImagePixels; @@ -61,6 +69,7 @@ public class AttachmentService { } this.uploadPermits = new Semaphore(maxConcurrentUploads, true); this.uploadPermitWaitMillis = uploadPermitWaitMillis; + this.injectCrashAfterOutboxCommit = injectCrashAfterOutboxCommit; } public Attachment upload(UUID chatId, @@ -108,16 +117,36 @@ public class AttachmentService { UUID id = UuidCreator.getTimeOrderedEpochPlus1(); String objectKey = "attachments/" + id + "/original"; + String stagingKey = "staging/" + id + "/original"; Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS); + AttachmentJob job = AttachmentJob.first(UUID.randomUUID(), id, now); Attachment attachment = new Attachment(id, chatId, ownerId, safeFilename, contentType, - bytes.length, sha256(bytes), objectKey, now, now); + bytes.length, sha256(bytes), objectKey, stagingKey, "queued", List.of(), + null, now, now); - storage.put(objectKey, bytes, contentType); + storage.put(stagingKey, bytes, contentType); try { - return transaction.execute(status -> attachments.save(attachment)); - } catch (RuntimeException databaseFailure) { + Attachment saved = transaction.execute(status -> attachments.saveQueued(attachment, job)); + if (injectCrashAfterOutboxCommit && attachments.markPublishFaultInjected(job.jobId())) { + // Opt-in fault injection for the exact DB COMMIT -> broker publish window. + // The persisted outbox row remains unpublished and is recovered after restart. + Runtime.getRuntime().halt(87); + } try { - storage.delete(objectKey); + publisher.publish(job); + attachments.markPublished(job.jobId()); + return saved; + } catch (RuntimeException publishFailure) { + // The database job and staging object are intentionally retained. + // The scheduled republisher closes the DB-commit -> broker window. + throw ApiExceptions.unavailable("Attachment was staged; queue publication is pending"); + } + } catch (RuntimeException databaseFailure) { + if (databaseFailure instanceof com.example.mtusi_messenger.exception.ApiException) { + throw databaseFailure; + } + try { + storage.delete(stagingKey); } catch (RuntimeException cleanupFailure) { databaseFailure.addSuppressed(cleanupFailure); } @@ -133,8 +162,28 @@ public class AttachmentService { } public Download download(UUID attachmentId, UUID userId) { + return download(attachmentId, userId, "original"); + } + + public Download download(UUID attachmentId, UUID userId, String variantName) { Attachment attachment = getAccessible(attachmentId, userId); - return new Download(attachment, storage.get(attachment.objectKey())); + if (!"ready".equals(attachment.status())) { + throw ApiExceptions.conflict("Attachment content is not ready"); + } + if ("original".equals(variantName)) { + return new Download(attachment, attachment.contentType(), attachment.filename(), + storage.get(attachment.objectKey())); + } + if (!List.of("thumbnail", "crop", "optimized").contains(variantName)) { + throw ApiExceptions.invalid("Unsupported attachment variant"); + } + AttachmentVariant variant = attachment.variants().stream() + .filter(candidate -> candidate.name().equals(variantName)) + .findFirst() + .orElseThrow(() -> ApiExceptions.notFound("Attachment variant not found")); + String extension = "image/webp".equals(variant.contentType()) ? ".webp" : ".jpg"; + return new Download(attachment, variant.contentType(), variantName + extension, + storage.get(variant.objectKey())); } public void validateForMessage(UUID chatId, List attachmentIds) { @@ -234,6 +283,6 @@ public class AttachmentService { } } - public record Download(Attachment attachment, byte[] bytes) { + public record Download(Attachment attachment, String contentType, String filename, byte[] bytes) { } } diff --git a/src/main/java/com/example/mtusi_messenger/service/StagingCleaner.java b/src/main/java/com/example/mtusi_messenger/service/StagingCleaner.java new file mode 100644 index 00000000..f347f895 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/StagingCleaner.java @@ -0,0 +1,65 @@ +package com.example.mtusi_messenger.service; + +import com.example.mtusi_messenger.repository.AttachmentRepository; +import com.example.mtusi_messenger.storage.ObjectStorage; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.time.Clock; +import java.time.Duration; +import java.util.Set; + +@Component +@ConditionalOnProperty(name = "messenger.role", havingValue = "api", matchIfMissing = true) +public class StagingCleaner { + private static final Logger log = LoggerFactory.getLogger(StagingCleaner.class); + private static final String PREFIX = "staging/"; + private final AttachmentRepository attachments; + private final ObjectStorage storage; + private final Duration retention; + private final Clock clock; + + @Autowired + public StagingCleaner( + AttachmentRepository attachments, + ObjectStorage storage, + @Value("${messenger.attachments.staging-retention-seconds:86400}") long retentionSeconds) { + this(attachments, storage, Duration.ofSeconds(retentionSeconds), Clock.systemUTC()); + } + + StagingCleaner( + AttachmentRepository attachments, + ObjectStorage storage, + Duration retention, + Clock clock) { + if (retention.isZero() || retention.isNegative()) { + throw new IllegalArgumentException("Staging retention must be positive"); + } + this.attachments = attachments; + this.storage = storage; + this.retention = retention; + this.clock = clock; + } + + @Scheduled( + fixedDelayString = "${messenger.attachments.reconcile-interval-millis:600000}", + initialDelayString = "${messenger.attachments.reconcile-initial-delay-millis:60000}") + public void cleanup() { + try { + Set active = attachments.findActiveStagingKeys(); + var deleteBefore = clock.instant().minus(retention); + for (ObjectStorage.StoredObject object : storage.list(PREFIX)) { + if (!active.contains(object.objectKey()) && object.lastModified().isBefore(deleteBefore)) { + storage.delete(object.objectKey()); + } + } + } catch (RuntimeException error) { + log.warn("Staging cleanup postponed: {}", error.getMessage()); + } + } +} diff --git a/src/main/java/com/example/mtusi_messenger/worker/AttachmentWorker.java b/src/main/java/com/example/mtusi_messenger/worker/AttachmentWorker.java new file mode 100644 index 00000000..571e475f --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/worker/AttachmentWorker.java @@ -0,0 +1,239 @@ +package com.example.mtusi_messenger.worker; + +import com.example.mtusi_messenger.model.Attachment; +import com.example.mtusi_messenger.model.AttachmentJob; +import com.example.mtusi_messenger.model.AttachmentVariant; +import com.example.mtusi_messenger.queue.RetryPolicy; +import com.example.mtusi_messenger.repository.AttachmentRepository; +import com.example.mtusi_messenger.storage.ObjectStorage; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.rabbitmq.client.Channel; +import jakarta.annotation.PreDestroy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Component; +import org.springframework.transaction.support.TransactionTemplate; + +import java.io.IOException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.time.Duration; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +@Component +@ConditionalOnProperty(name = "messenger.role", havingValue = "worker") +public class AttachmentWorker { + private static final Logger log = LoggerFactory.getLogger(AttachmentWorker.class); + private final ObjectMapper mapper; + private final AttachmentRepository attachments; + private final ObjectStorage storage; + private final ImageVariantProcessor images; + private final RetryPolicy retryPolicy; + private final TransactionTemplate transaction; + private final int maxAttempts; + private final Duration jobTimeout; + private final Duration leaseDuration; + private final boolean injectCrashAfterResultCommit; + private final ExecutorService processingPool; + private final Clock clock = Clock.systemUTC(); + + public AttachmentWorker( + ObjectMapper mapper, + AttachmentRepository attachments, + ObjectStorage storage, + ImageVariantProcessor images, + RetryPolicy retryPolicy, + TransactionTemplate transaction, + @Value("${messenger.jobs.max-attempts:5}") int maxAttempts, + @Value("${messenger.jobs.timeout:60s}") Duration jobTimeout, + @Value("${messenger.jobs.lease-duration:90s}") Duration leaseDuration, + @Value("${messenger.jobs.fault-crash-after-result-commit:false}") boolean injectCrashAfterResultCommit, + @Value("${spring.rabbitmq.listener.simple.concurrency:2}") int concurrency) { + if (maxAttempts < 1 || jobTimeout.isZero() || jobTimeout.isNegative() + || leaseDuration.compareTo(jobTimeout) <= 0 || concurrency < 1) { + throw new IllegalArgumentException("Invalid attachment worker limits"); + } + this.mapper = mapper; + this.attachments = attachments; + this.storage = storage; + this.images = images; + this.retryPolicy = retryPolicy; + this.transaction = transaction; + this.maxAttempts = maxAttempts; + this.jobTimeout = jobTimeout; + this.leaseDuration = leaseDuration; + this.injectCrashAfterResultCommit = injectCrashAfterResultCommit; + this.processingPool = Executors.newFixedThreadPool(concurrency, + Thread.ofPlatform().name("attachment-image-", 0).factory()); + } + + @RabbitListener(queues = "${messenger.jobs.queue}") + public void consume(Message message, Channel channel) throws IOException { + long deliveryTag = message.getMessageProperties().getDeliveryTag(); + AttachmentJob job; + try { + job = mapper.readValue(message.getBody(), AttachmentJob.class); + } catch (RuntimeException | IOException invalidMessage) { + log.error("Rejecting malformed attachment job message {}", + message.getMessageProperties().getMessageId()); + channel.basicReject(deliveryTag, false); + return; + } + + Attachment attachment = attachments.findById(job.attachmentId()).orElse(null); + if (attachment == null || "ready".equals(attachment.status()) || "failed".equals(attachment.status())) { + channel.basicAck(deliveryTag, false); + return; + } + + int attempt = Math.max(job.attempt(), attachments.currentAttempt(job.jobId())); + UUID leaseToken = UUID.randomUUID(); + boolean claimed = Boolean.TRUE.equals(transaction.execute(status -> + attachments.claim(job.jobId(), job.attachmentId(), attempt, leaseToken, leaseDuration))); + if (!claimed) { + // A live worker owns the lease, or a terminal state won the race. + // If the owner died, the DB lease reaper will create a new outbox delivery. + channel.basicAck(deliveryTag, false); + return; + } + + Future future = processingPool.submit(() -> process(job, leaseToken)); + try { + ProcessOutcome outcome = future.get(jobTimeout.toMillis(), TimeUnit.MILLISECONDS); + if (outcome.crashAfterCommit()) { + log.error("Fault injection: halting worker after durable result and before consumer ack"); + Runtime.getRuntime().halt(86); + } + channel.basicAck(deliveryTag, false); + } catch (TimeoutException timeout) { + future.cancel(true); + retryOrFail(job, leaseToken, attempt, "processing_timeout", deliveryTag, channel); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + future.cancel(true); + channel.basicNack(deliveryTag, false, true); + } catch (ExecutionException execution) { + Throwable cause = execution.getCause(); + if (cause instanceof ImageVariantProcessor.ProcessingException imageFailure + && imageFailure.permanent()) { + failPermanent(job, leaseToken, imageFailure.errorCode(), deliveryTag, channel); + } else { + String code = cause instanceof ImageVariantProcessor.ProcessingException imageFailure + ? imageFailure.errorCode() : "processing_failed"; + retryOrFail(job, leaseToken, attempt, code, deliveryTag, channel); + } + } + } + + private ProcessOutcome process(AttachmentJob job, UUID leaseToken) { + Attachment attachment = attachments.findById(job.attachmentId()) + .orElseThrow(() -> new ImageVariantProcessor.ProcessingException( + "attachment_missing", true, "Attachment metadata is missing", null)); + byte[] original = storage.get(attachment.stagingKey()); + if (original.length != attachment.sizeBytes() || !sha256(original).equals(attachment.sha256())) { + throw new ImageVariantProcessor.ProcessingException( + "invalid_image", true, "Staging checksum mismatch", null); + } + + storage.put(attachment.objectKey(), original, attachment.contentType()); + List generated = images.createVariants(original); + List variants = new ArrayList<>(generated.size()); + for (ImageVariantProcessor.GeneratedVariant item : generated) { + String objectKey = "attachments/" + attachment.id() + "/" + + item.name() + "-v" + job.pipelineVersion() + "." + item.extension(); + storage.put(objectKey, item.bytes(), item.contentType()); + variants.add(new AttachmentVariant( + item.name(), item.contentType(), item.bytes().length, + item.width(), item.height(), sha256(item.bytes()), objectKey)); + } + + AttachmentRepository.CompletionResult completion = transaction.execute(status -> + attachments.markReady(job.jobId(), job.attachmentId(), leaseToken, + job.pipelineVersion(), variants, injectCrashAfterResultCommit)); + if (completion == null || !completion.completed()) { + return new ProcessOutcome(false); + } + try { + storage.delete(attachment.stagingKey()); + } catch (RuntimeException cleanupFailure) { + log.warn("Staging cleanup postponed for attachment {}", attachment.id()); + } + return new ProcessOutcome(completion.crashAfterCommit()); + } + + private void failPermanent( + AttachmentJob job, UUID leaseToken, String errorCode, + long deliveryTag, Channel channel) throws IOException { + boolean failed = Boolean.TRUE.equals(transaction.execute(status -> + attachments.markFailed(job.jobId(), job.attachmentId(), leaseToken, errorCode))); + if (failed) { + channel.basicReject(deliveryTag, false); + } else { + channel.basicAck(deliveryTag, false); + } + } + + private void retryOrFail( + AttachmentJob job, UUID leaseToken, int attempt, String errorCode, + long deliveryTag, Channel channel) throws IOException { + try { + if (attempt >= maxAttempts) { + boolean failed = Boolean.TRUE.equals(transaction.execute(status -> + attachments.markFailed(job.jobId(), job.attachmentId(), leaseToken, + "retry_exhausted"))); + if (failed) { + log.error("Attachment job {} exhausted {} attempts: {}", + job.jobId(), attempt, errorCode); + channel.basicReject(deliveryTag, false); + } else { + channel.basicAck(deliveryTag, false); + } + return; + } + + int nextAttempt = attempt + 1; + boolean queued = Boolean.TRUE.equals(transaction.execute(status -> + attachments.markQueuedForRetry( + job.jobId(), job.attachmentId(), leaseToken, nextAttempt, errorCode, + clock.instant().plus(retryPolicy.delayForAttempt(nextAttempt))))); + // The DB outbox is now the durable retry carrier; the current broker + // delivery can be acknowledged without a DB/broker dual write. + channel.basicAck(deliveryTag, false); + if (!queued) { + log.info("Retry skipped because job {} lost its lease or became terminal", job.jobId()); + } + } catch (RuntimeException databaseFailure) { + channel.basicNack(deliveryTag, false, true); + } + } + + @PreDestroy + void shutdownPool() { + processingPool.shutdownNow(); + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private record ProcessOutcome(boolean crashAfterCommit) { + } +} diff --git a/src/main/java/com/example/mtusi_messenger/worker/ImageVariantProcessor.java b/src/main/java/com/example/mtusi_messenger/worker/ImageVariantProcessor.java new file mode 100644 index 00000000..cb077cae --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/worker/ImageVariantProcessor.java @@ -0,0 +1,254 @@ +package com.example.mtusi_messenger.worker; + +import net.coobird.thumbnailator.Thumbnails; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import javax.imageio.IIOImage; +import javax.imageio.ImageIO; +import javax.imageio.ImageReader; +import javax.imageio.ImageWriteParam; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + +@Component +public class ImageVariantProcessor { + private static final long MEBIBYTE = 1024L * 1024L; + private static final long OUTPUT_ALLOWANCE_BYTES = 64L * MEBIBYTE; + private final long maxPixels; + private final long memoryBudgetBytes; + private final Semaphore memoryPermits; + private final Duration memoryWait; + + public ImageVariantProcessor( + @Value("${messenger.jobs.worker-max-pixels:40000000}") long maxPixels, + @Value("${messenger.jobs.worker-memory-budget-bytes:536870912}") long memoryBudgetBytes, + @Value("${messenger.jobs.memory-wait:2s}") Duration memoryWait) { + if (maxPixels < 1 || memoryBudgetBytes < MEBIBYTE || memoryWait.isNegative()) { + throw new IllegalArgumentException("Invalid worker image resource limits"); + } + this.maxPixels = maxPixels; + this.memoryBudgetBytes = memoryBudgetBytes; + this.memoryPermits = new Semaphore((int) Math.min(Integer.MAX_VALUE, + Math.max(1, memoryBudgetBytes / MEBIBYTE)), true); + this.memoryWait = memoryWait; + } + + public List createVariants(byte[] original) { + ImageInfo info = inspect(original); + long estimatedBytes; + try { + estimatedBytes = Math.addExact(Math.multiplyExact(info.pixels(), 12L), + OUTPUT_ALLOWANCE_BYTES); + } catch (ArithmeticException overflow) { + throw permanent("image_too_large", "Image memory estimate overflow", overflow); + } + if (estimatedBytes > memoryBudgetBytes) { + throw permanent("image_too_large", "Image exceeds worker memory budget", null); + } + int permits = (int) Math.max(1, (estimatedBytes + MEBIBYTE - 1) / MEBIBYTE); + boolean acquired; + try { + acquired = memoryPermits.tryAcquire(permits, memoryWait.toMillis(), TimeUnit.MILLISECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw temporary("worker_interrupted", "Interrupted while waiting for memory budget", interrupted); + } + if (!acquired) { + throw temporary("worker_capacity", "Worker memory budget is currently exhausted", null); + } + + try { + return transform(original); + } finally { + memoryPermits.release(permits); + } + } + + private ImageInfo inspect(byte[] bytes) { + ImageIO.setUseCache(false); + try (var input = ImageIO.createImageInputStream(new ByteArrayInputStream(bytes))) { + if (input == null) { + throw permanent("invalid_image", "Image input is invalid", null); + } + Iterator readers = ImageIO.getImageReaders(input); + if (!readers.hasNext()) { + throw permanent("invalid_image", "Unsupported image encoding", null); + } + ImageReader reader = readers.next(); + try { + reader.setInput(input, true, true); + int width = reader.getWidth(0); + int height = reader.getHeight(0); + long pixels = Math.multiplyExact((long) width, height); + if (width < 1 || height < 1 || pixels > maxPixels) { + throw permanent("image_too_large", "Image exceeds worker pixel limit", null); + } + return new ImageInfo(width, height, pixels); + } finally { + reader.dispose(); + } + } catch (ProcessingException error) { + throw error; + } catch (IOException | RuntimeException error) { + throw permanent("invalid_image", "Image header cannot be read", error); + } + } + + private List transform(byte[] original) { + try { + BufferedImage oriented = Thumbnails.of(new ByteArrayInputStream(original)) + .useExifOrientation(true) + .scale(1.0) + .asBufferedImage(); + if (oriented == null || oriented.getWidth() < 1 || oriented.getHeight() < 1) { + throw permanent("invalid_image", "Image cannot be decoded", null); + } + try { + List variants = new ArrayList<>(3); + BufferedImage thumbnail = fit(oriented, 256, BufferedImage.TYPE_INT_RGB, true); + variants.add(encode("thumbnail", "image/jpeg", "jpg", thumbnail, "jpeg", 0.85f)); + thumbnail.flush(); + + BufferedImage crop = cropSquare(oriented, 128); + variants.add(encode("crop", "image/jpeg", "jpg", crop, "jpeg", 0.88f)); + crop.flush(); + + int webpType = oriented.getColorModel().hasAlpha() + ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB; + BufferedImage optimized = fit(oriented, 1280, webpType, !oriented.getColorModel().hasAlpha()); + variants.add(encode("optimized", "image/webp", "webp", optimized, "webp", 0.82f)); + optimized.flush(); + return List.copyOf(variants); + } finally { + oriented.flush(); + } + } catch (ProcessingException error) { + throw error; + } catch (IOException | RuntimeException error) { + throw permanent("invalid_image", "Image cannot be transformed", error); + } + } + + private static BufferedImage fit(BufferedImage source, int maxSide, int type, boolean whiteBackground) { + double scale = Math.min(1.0, Math.min( + (double) maxSide / source.getWidth(), + (double) maxSide / source.getHeight())); + int width = Math.max(1, (int) Math.floor(source.getWidth() * scale)); + int height = Math.max(1, (int) Math.floor(source.getHeight() * scale)); + BufferedImage target = new BufferedImage(width, height, type); + Graphics2D graphics = qualityGraphics(target, whiteBackground); + try { + graphics.drawImage(source, 0, 0, width, height, null); + } finally { + graphics.dispose(); + } + return target; + } + + private static BufferedImage cropSquare(BufferedImage source, int side) { + int sourceSide = Math.min(source.getWidth(), source.getHeight()); + int x = (source.getWidth() - sourceSide) / 2; + int y = (source.getHeight() - sourceSide) / 2; + BufferedImage target = new BufferedImage(side, side, BufferedImage.TYPE_INT_RGB); + Graphics2D graphics = qualityGraphics(target, true); + try { + graphics.drawImage(source, 0, 0, side, side, + x, y, x + sourceSide, y + sourceSide, null); + } finally { + graphics.dispose(); + } + return target; + } + + private static Graphics2D qualityGraphics(BufferedImage target, boolean whiteBackground) { + Graphics2D graphics = target.createGraphics(); + if (whiteBackground) { + graphics.setColor(Color.WHITE); + graphics.fillRect(0, 0, target.getWidth(), target.getHeight()); + } + graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, + RenderingHints.VALUE_INTERPOLATION_BICUBIC); + graphics.setRenderingHint(RenderingHints.KEY_RENDERING, + RenderingHints.VALUE_RENDER_QUALITY); + graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + return graphics; + } + + private static GeneratedVariant encode( + String name, String contentType, String extension, + BufferedImage image, String format, float quality) throws IOException { + Iterator writers = ImageIO.getImageWritersByFormatName(format); + if (!writers.hasNext()) { + throw new IOException(format + " writer is unavailable"); + } + var writer = writers.next(); + try (var output = new ByteArrayOutputStream(); + var imageOutput = ImageIO.createImageOutputStream(output)) { + writer.setOutput(imageOutput); + ImageWriteParam parameters = writer.getDefaultWriteParam(); + if (parameters.canWriteCompressed()) { + parameters.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); + String[] compressionTypes = parameters.getCompressionTypes(); + if (compressionTypes != null && compressionTypes.length > 0) { + parameters.setCompressionType(compressionTypes[0]); + } + parameters.setCompressionQuality(quality); + } + // Source metadata is intentionally omitted for every generated variant. + writer.write(null, new IIOImage(image, null, null), parameters); + imageOutput.flush(); + return new GeneratedVariant(name, contentType, extension, output.toByteArray(), + image.getWidth(), image.getHeight()); + } finally { + writer.dispose(); + } + } + + private static ProcessingException permanent(String code, String message, Throwable cause) { + return new ProcessingException(code, true, message, cause); + } + + private static ProcessingException temporary(String code, String message, Throwable cause) { + return new ProcessingException(code, false, message, cause); + } + + private record ImageInfo(int width, int height, long pixels) { + } + + public record GeneratedVariant(String name, String contentType, String extension, + byte[] bytes, int width, int height) { + } + + public static final class ProcessingException extends RuntimeException { + private final String errorCode; + private final boolean permanent; + + public ProcessingException( + String errorCode, boolean permanent, String message, Throwable cause) { + super(message, cause); + this.errorCode = errorCode; + this.permanent = permanent; + } + + public String errorCode() { + return errorCode; + } + + public boolean permanent() { + return permanent; + } + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 6a55c26a..10f92def 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -27,6 +27,23 @@ spring: min-idle: ${REDIS_POOL_MIN_IDLE:0} max-wait: ${REDIS_POOL_MAX_WAIT:500ms} + rabbitmq: + host: ${RABBITMQ_HOST:localhost} + port: ${RABBITMQ_PORT:5672} + username: ${RABBITMQ_USER:messenger} + password: ${RABBITMQ_PASSWORD:messenger} + virtual-host: ${RABBITMQ_VHOST:/} + connection-timeout: ${RABBITMQ_CONNECTION_TIMEOUT:5s} + publisher-confirm-type: correlated + publisher-returns: true + listener: + simple: + acknowledge-mode: manual + default-requeue-rejected: false + prefetch: ${WORKER_PREFETCH:1} + concurrency: ${WORKER_CONCURRENCY:2} + max-concurrency: ${WORKER_CONCURRENCY:2} + jdbc: template: query-timeout: ${DATABASE_QUERY_TIMEOUT_SECONDS:5} @@ -53,6 +70,7 @@ server: shutdown: graceful messenger: + role: ${MESSENGER_ROLE:api} storage: postgres session: ttl-seconds: ${SESSION_TTL_SECONDS:3600} @@ -71,7 +89,28 @@ messenger: max-image-pixels: ${MAX_IMAGE_PIXELS:40000000} max-concurrent-uploads: ${MAX_CONCURRENT_UPLOADS:3} upload-permit-wait-millis: ${UPLOAD_PERMIT_WAIT_MILLIS:10000} + staging-retention-seconds: ${STAGING_RETENTION_SECONDS:86400} cleanup-grace-seconds: ${ATTACHMENT_CLEANUP_GRACE_SECONDS:3600} cleanup-dry-run: ${ATTACHMENT_CLEANUP_DRY_RUN:false} reconcile-interval-millis: ${ATTACHMENT_RECONCILE_INTERVAL_MILLIS:600000} reconcile-initial-delay-millis: ${ATTACHMENT_RECONCILE_INITIAL_DELAY_MILLIS:60000} + jobs: + exchange: ${ATTACHMENT_JOB_EXCHANGE:attachments.v1} + queue: ${ATTACHMENT_JOB_QUEUE:attachments.process.level4.v1} + routing-key: ${ATTACHMENT_JOB_ROUTING_KEY:attachment.process.v1} + dead-letter-exchange: ${ATTACHMENT_DLQ_EXCHANGE:attachments.dlx.v1} + dead-letter-queue: ${ATTACHMENT_DLQ_QUEUE:attachments.failed.v1} + dead-letter-routing-key: ${ATTACHMENT_DLQ_ROUTING_KEY:attachment.failed.v1} + max-attempts: ${JOB_MAX_ATTEMPTS:5} + retry-base-delay: ${JOB_RETRY_BASE_DELAY:1s} + retry-max-delay: ${JOB_RETRY_MAX_DELAY:30s} + timeout: ${JOB_TIMEOUT:60s} + lease-duration: ${JOB_LEASE_DURATION:90s} + lease-reaper-interval: ${JOB_LEASE_REAPER_INTERVAL:5s} + worker-max-pixels: ${WORKER_MAX_IMAGE_PIXELS:40000000} + worker-memory-budget-bytes: ${WORKER_MEMORY_BUDGET_BYTES:536870912} + memory-wait: ${WORKER_MEMORY_WAIT:2s} + publish-confirm-timeout: ${JOB_PUBLISH_CONFIRM_TIMEOUT:5s} + republish-interval: ${JOB_REPUBLISH_INTERVAL:5s} + fault-crash-after-outbox-commit: ${FAULT_CRASH_AFTER_OUTBOX_COMMIT:false} + fault-crash-after-result-commit: ${FAULT_CRASH_AFTER_RESULT_COMMIT:false} diff --git a/src/main/resources/db/migration/V5__add_attachment_processing_jobs.sql b/src/main/resources/db/migration/V5__add_attachment_processing_jobs.sql new file mode 100644 index 00000000..5d5ecc40 --- /dev/null +++ b/src/main/resources/db/migration/V5__add_attachment_processing_jobs.sql @@ -0,0 +1,58 @@ +ALTER TABLE attachments DROP CONSTRAINT attachments_status_chk; +ALTER TABLE attachments + ADD COLUMN staging_key text, + ADD COLUMN error_code varchar(64), + ADD CONSTRAINT attachments_status_chk + CHECK (status IN ('queued', 'processing', 'ready', 'failed')), + ADD CONSTRAINT attachments_error_state_chk + CHECK ((status = 'failed' AND error_code IS NOT NULL) + OR (status <> 'failed' AND error_code IS NULL)); + +CREATE UNIQUE INDEX attachments_staging_key_uk + ON attachments (staging_key) WHERE staging_key IS NOT NULL; + +CREATE TABLE attachment_variants ( + attachment_id uuid NOT NULL REFERENCES attachments(id) ON DELETE CASCADE, + pipeline_version integer NOT NULL, + name varchar(32) NOT NULL, + content_type varchar(32) NOT NULL, + size_bytes bigint NOT NULL, + width integer NOT NULL, + height integer NOT NULL, + sha256 char(64) NOT NULL, + object_key text NOT NULL, + created_at timestamptz NOT NULL, + + CONSTRAINT attachment_variants_pk + PRIMARY KEY (attachment_id, pipeline_version, name), + CONSTRAINT attachment_variants_object_key_uk UNIQUE (object_key), + CONSTRAINT attachment_variants_name_chk + CHECK (name IN ('thumbnail', 'crop', 'optimized')), + CONSTRAINT attachment_variants_content_type_chk + CHECK (content_type IN ('image/jpeg', 'image/png', 'image/webp')), + CONSTRAINT attachment_variants_size_chk CHECK (size_bytes > 0), + CONSTRAINT attachment_variants_dimensions_chk CHECK (width > 0 AND height > 0), + CONSTRAINT attachment_variants_sha256_chk CHECK (sha256 ~ '^[a-f0-9]{64}$') +); + +CREATE TABLE attachment_jobs ( + id uuid PRIMARY KEY, + attachment_id uuid NOT NULL UNIQUE REFERENCES attachments(id) ON DELETE CASCADE, + pipeline_version integer NOT NULL DEFAULT 1, + attempt integer NOT NULL DEFAULT 1, + status varchar(16) NOT NULL DEFAULT 'queued', + published boolean NOT NULL DEFAULT false, + last_error_code varchar(64), + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + + CONSTRAINT attachment_jobs_pipeline_chk CHECK (pipeline_version > 0), + CONSTRAINT attachment_jobs_attempt_chk CHECK (attempt > 0), + CONSTRAINT attachment_jobs_status_chk + CHECK (status IN ('queued', 'processing', 'ready', 'failed')) +); + +CREATE INDEX attachment_jobs_publish_idx + ON attachment_jobs (published, status, created_at) + WHERE published = false AND status = 'queued'; + diff --git a/src/main/resources/db/migration/V6__add_job_leases_replay_and_fault_injection.sql b/src/main/resources/db/migration/V6__add_job_leases_replay_and_fault_injection.sql new file mode 100644 index 00000000..1a8539c7 --- /dev/null +++ b/src/main/resources/db/migration/V6__add_job_leases_replay_and_fault_injection.sql @@ -0,0 +1,41 @@ +ALTER TABLE attachment_jobs + ADD COLUMN next_attempt_at timestamptz, + ADD COLUMN lease_token uuid, + ADD COLUMN lease_until timestamptz, + ADD COLUMN publish_fault_injected boolean NOT NULL DEFAULT false, + ADD COLUMN result_fault_injected boolean NOT NULL DEFAULT false; + +UPDATE attachment_jobs SET next_attempt_at = created_at WHERE next_attempt_at IS NULL; +UPDATE attachment_jobs +SET status = 'queued', published = false, last_error_code = 'lease_migration_recovery' +WHERE status = 'processing'; +UPDATE attachments SET status = 'queued', error_code = NULL WHERE status = 'processing'; +ALTER TABLE attachment_jobs ALTER COLUMN next_attempt_at SET NOT NULL; +ALTER TABLE attachment_jobs ALTER COLUMN next_attempt_at SET DEFAULT clock_timestamp(); + +ALTER TABLE attachment_jobs + ADD CONSTRAINT attachment_jobs_lease_chk CHECK ( + (status = 'processing' AND lease_token IS NOT NULL AND lease_until IS NOT NULL) + OR (status <> 'processing' AND lease_token IS NULL AND lease_until IS NULL) + ); + +DROP INDEX attachment_jobs_publish_idx; +CREATE INDEX attachment_jobs_publish_idx + ON attachment_jobs (next_attempt_at, created_at, id) + WHERE published = false AND status = 'queued'; +CREATE INDEX attachment_jobs_expired_lease_idx + ON attachment_jobs (lease_until) + WHERE status = 'processing'; + +CREATE TABLE attachment_job_replays ( + id bigserial PRIMARY KEY, + job_id uuid NOT NULL REFERENCES attachment_jobs(id) ON DELETE RESTRICT, + requested_by varchar(128) NOT NULL, + previous_attempt integer NOT NULL, + requested_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT attachment_job_replays_actor_chk + CHECK (char_length(requested_by) BETWEEN 1 AND 128) +); + +CREATE INDEX attachment_job_replays_job_idx + ON attachment_job_replays (job_id, requested_at); diff --git a/src/test/java/com/example/mtusi_messenger/queue/RetryPolicyTest.java b/src/test/java/com/example/mtusi_messenger/queue/RetryPolicyTest.java new file mode 100644 index 00000000..5ca590d8 --- /dev/null +++ b/src/test/java/com/example/mtusi_messenger/queue/RetryPolicyTest.java @@ -0,0 +1,21 @@ +package com.example.mtusi_messenger.queue; + +import org.junit.jupiter.api.Test; + +import java.time.Duration; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +class RetryPolicyTest { + @Test + void appliesExponentialBackoffWithBoundedJitter() { + RetryPolicy policy = new RetryPolicy(Duration.ofSeconds(1), Duration.ofSeconds(30)); + + for (int attempt = 2; attempt <= 8; attempt++) { + long ceiling = Math.min(30_000L, 1_000L << (attempt - 2)); + long delay = policy.delayForAttempt(attempt).toMillis(); + assertTrue(delay >= Math.max(1, ceiling / 2)); + assertTrue(delay <= ceiling); + } + } +} diff --git a/src/test/java/com/example/mtusi_messenger/service/AttachmentServiceTest.java b/src/test/java/com/example/mtusi_messenger/service/AttachmentServiceTest.java index 8a53cb45..eb84fee2 100644 --- a/src/test/java/com/example/mtusi_messenger/service/AttachmentServiceTest.java +++ b/src/test/java/com/example/mtusi_messenger/service/AttachmentServiceTest.java @@ -4,6 +4,7 @@ import com.example.mtusi_messenger.exception.ApiException; import com.example.mtusi_messenger.model.Attachment; import com.example.mtusi_messenger.model.Chat; import com.example.mtusi_messenger.repository.AttachmentRepository; +import com.example.mtusi_messenger.queue.AttachmentJobPublisher; import com.example.mtusi_messenger.storage.ObjectStorage; import com.example.mtusi_messenger.storage.ObjectStorageException; import org.junit.jupiter.api.BeforeEach; @@ -34,6 +35,7 @@ class AttachmentServiceTest { private AttachmentRepository repository; private ChatService chats; private InMemoryStorage storage; + private AttachmentJobPublisher publisher; private AttachmentService service; private byte[] png; @@ -42,6 +44,7 @@ class AttachmentServiceTest { repository = mock(AttachmentRepository.class); chats = mock(ChatService.class); storage = new InMemoryStorage(); + publisher = mock(AttachmentJobPublisher.class); TransactionTemplate transaction = mock(TransactionTemplate.class); when(transaction.execute(any())).thenAnswer(invocation -> { @SuppressWarnings("unchecked") @@ -50,14 +53,14 @@ class AttachmentServiceTest { }); when(chats.getAccessible(chatId, ownerId)).thenReturn( new Chat(chatId, "test", List.of(ownerId), Instant.now())); - when(repository.save(any())).thenAnswer(invocation -> invocation.getArgument(0)); - service = new AttachmentService(repository, chats, storage, transaction, - 10_485_760, 40_000_000, 3, 10_000); + when(repository.saveQueued(any(), any())).thenAnswer(invocation -> invocation.getArgument(0)); + service = new AttachmentService(repository, chats, storage, publisher, transaction, + 10_485_760, 40_000_000, 3, 10_000, false); png = Files.readAllBytes(Path.of("tests", "fixtures", "sample.png")); } @Test - void uploadsValidPngUsingServerGeneratedObjectKey() { + void stagesValidPngAndPublishesDurableJob() { Attachment attachment = service.upload(chatId, ownerId, "photo.png", "image/png", png.length, new ByteArrayInputStream(png)); @@ -65,9 +68,13 @@ class AttachmentServiceTest { assertEquals("image/png", attachment.contentType()); assertEquals(png.length, attachment.sizeBytes()); assertTrue(attachment.objectKey().matches("attachments/[0-9a-f-]+/original")); + assertTrue(attachment.stagingKey().matches("staging/[0-9a-f-]+/original")); + assertEquals("queued", attachment.status()); assertFalse(attachment.objectKey().contains("photo.png")); - assertArrayEquals(png, storage.objects.get(attachment.objectKey())); - verify(repository).save(attachment); + assertArrayEquals(png, storage.objects.get(attachment.stagingKey())); + assertFalse(storage.objects.containsKey(attachment.objectKey())); + verify(repository).saveQueued(eq(attachment), any()); + verify(publisher).publish(any()); } @Test @@ -108,7 +115,7 @@ class AttachmentServiceTest { assertThrows(ObjectStorageException.class, () -> service.upload( chatId, ownerId, "photo.png", "image/png", png.length, new ByteArrayInputStream(png))); - verify(repository, never()).save(any()); + verify(repository, never()).saveQueued(any(), any()); } @Test @@ -130,12 +137,12 @@ class AttachmentServiceTest { assertEquals(HttpStatus.BAD_REQUEST, error.status()); assertTrue(storage.objects.isEmpty()); - verify(repository, never()).save(any()); + verify(repository, never()).saveQueued(any(), any()); } @Test void databaseFailureCompensatesAlreadyWrittenS3Object() { - when(repository.save(any())).thenThrow(new IllegalStateException("database commit failed")); + when(repository.saveQueued(any(), any())).thenThrow(new IllegalStateException("database commit failed")); assertThrows(IllegalStateException.class, () -> service.upload( chatId, ownerId, "photo.png", "image/png", png.length, diff --git a/src/test/java/com/example/mtusi_messenger/service/StagingCleanerTest.java b/src/test/java/com/example/mtusi_messenger/service/StagingCleanerTest.java new file mode 100644 index 00000000..03c90ef1 --- /dev/null +++ b/src/test/java/com/example/mtusi_messenger/service/StagingCleanerTest.java @@ -0,0 +1,55 @@ +package com.example.mtusi_messenger.service; + +import com.example.mtusi_messenger.repository.AttachmentRepository; +import com.example.mtusi_messenger.storage.ObjectStorage; +import org.junit.jupiter.api.Test; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class StagingCleanerTest { + private static final Instant NOW = Instant.parse("2026-11-18T12:00:00Z"); + + @Test + void keepsActiveAndFreshStagingButDeletesExpiredUnreferencedObject() { + AttachmentRepository repository = mock(AttachmentRepository.class); + when(repository.findActiveStagingKeys()).thenReturn(Set.of("staging/active/original")); + FakeStorage storage = new FakeStorage(List.of( + object("staging/active/original", NOW.minusSeconds(172800)), + object("staging/failed/original", NOW.minusSeconds(172800)), + object("staging/fresh/original", NOW.minusSeconds(60)))); + StagingCleaner cleaner = new StagingCleaner(repository, storage, Duration.ofDays(1), + Clock.fixed(NOW, ZoneOffset.UTC)); + + cleaner.cleanup(); + + assertEquals(List.of("staging/failed/original"), storage.deleted); + } + + private static ObjectStorage.StoredObject object(String key, Instant modified) { + return new ObjectStorage.StoredObject(key, modified, 100); + } + + private static final class FakeStorage implements ObjectStorage { + private final List objects; + private final List deleted = new ArrayList<>(); + + private FakeStorage(List objects) { + this.objects = objects; + } + + @Override public void put(String objectKey, byte[] bytes, String contentType) { } + @Override public byte[] get(String objectKey) { return new byte[0]; } + @Override public void delete(String objectKey) { deleted.add(objectKey); } + @Override public List list(String prefix) { return objects; } + } +} diff --git a/src/test/java/com/example/mtusi_messenger/worker/ImageVariantProcessorTest.java b/src/test/java/com/example/mtusi_messenger/worker/ImageVariantProcessorTest.java new file mode 100644 index 00000000..11c56b5a --- /dev/null +++ b/src/test/java/com/example/mtusi_messenger/worker/ImageVariantProcessorTest.java @@ -0,0 +1,70 @@ +package com.example.mtusi_messenger.worker; + +import org.junit.jupiter.api.Test; + +import javax.imageio.ImageIO; +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ImageVariantProcessorTest { + private final byte[] original; + + ImageVariantProcessorTest() throws Exception { + original = Files.readAllBytes(Path.of("tests", "fixtures", "sample.png")); + } + + @Test + void createsThumbnailCropAndOptimizedWebp() throws Exception { + ImageVariantProcessor processor = new ImageVariantProcessor( + 40_000_000, 512L * 1024 * 1024, Duration.ofSeconds(1)); + + Map variants = processor + .createVariants(original).stream() + .collect(Collectors.toMap(ImageVariantProcessor.GeneratedVariant::name, + Function.identity())); + + assertEquals(3, variants.size()); + assertImage(variants.get("thumbnail"), "image/jpeg", 256, 160); + assertImage(variants.get("crop"), "image/jpeg", 128, 128); + assertImage(variants.get("optimized"), "image/webp", 320, 200); + byte[] webp = variants.get("optimized").bytes(); + assertEquals("RIFF", new String(webp, 0, 4, StandardCharsets.US_ASCII)); + assertEquals("WEBP", new String(webp, 8, 4, StandardCharsets.US_ASCII)); + } + + @Test + void rejectsImageWhoseEstimateExceedsWorkerMemoryBudget() { + ImageVariantProcessor processor = new ImageVariantProcessor( + 40_000_000, 1L * 1024 * 1024, Duration.ofSeconds(1)); + + var error = assertThrows(ImageVariantProcessor.ProcessingException.class, + () -> processor.createVariants(original)); + + assertTrue(error.permanent()); + assertEquals("image_too_large", error.errorCode()); + } + + private static void assertImage( + ImageVariantProcessor.GeneratedVariant variant, + String contentType, int width, int height) throws Exception { + assertNotNull(variant); + assertEquals(contentType, variant.contentType()); + assertEquals(width, variant.width()); + assertEquals(height, variant.height()); + var decoded = ImageIO.read(new ByteArrayInputStream(variant.bytes())); + assertNotNull(decoded); + assertEquals(width, decoded.getWidth()); + assertEquals(height, decoded.getHeight()); + } +} diff --git a/student_tests/README.md b/student_tests/README.md index c08c4d23..7b14c1ae 100644 --- a/student_tests/README.md +++ b/student_tests/README.md @@ -16,3 +16,9 @@ The course-provided black-box suite remains in `tests/`; Spring tests remain in unknown attachment, foreign user and cross-chat binding; every user error is 4xx. - `concurrent_upload_memory.py` — 12 simultaneous ~6.5 MiB valid PNG uploads and aggregate API container memory sampling through `docker stats`. +- `lab5_worker_recovery.py` — durable worker stop/restart, all three variants and + idempotent duplicate delivery. +- `lab5_fault_injection.py` — crashes after outbox commit and after result commit + but before consumer acknowledgement. +- `lab5_dlq_replay_lease.py` — permanent failure DLQ routing, guarded audited + replay, and expired processing-lease recovery. diff --git a/student_tests/lab5_dlq_replay_lease.py b/student_tests/lab5_dlq_replay_lease.py new file mode 100644 index 00000000..b36b9692 --- /dev/null +++ b/student_tests/lab5_dlq_replay_lease.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Exercise DLQ routing, guarded replay and expired processing leases.""" + +from pathlib import Path +import subprocess +import sys +import time + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) + +from client import Client, Failure, check, run # noqa: E402 + +COMPOSE = ["docker", "compose", "--env-file", ".env.example"] + + +def command(*args, capture=False): + result = subprocess.run( + [*COMPOSE, *args], cwd=ROOT, check=True, text=True, + capture_output=capture) + return result.stdout.strip() if capture else "" + + +def database_scalar(sql): + return command( + "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", + "-At", "-c", sql, capture=True) + + +def env_value(name): + for line in (ROOT / ".env.example").read_text(encoding="utf-8").splitlines(): + if line.startswith(name + "="): + return line.split("=", 1)[1] + raise Failure("missing " + name + " in .env.example") + + +def queue_ready(queue): + listing = command( + "exec", "-T", "rabbitmq", "rabbitmqctl", "list_queues", + "name", "messages_ready", capture=True) + for line in listing.splitlines(): + columns = line.split("\t") + if len(columns) == 2 and columns[0] == queue: + return int(columns[1]) + raise Failure("queue not found: " + queue) + + +def wait_ready(client, actor, attachment, seconds=120): + return client.wait_ready(actor, attachment, wait_seconds=seconds) + + +def replay(job_id): + subprocess.run( + ["powershell", "-NoProfile", "-File", str(ROOT / "scripts" / "replay-failed.ps1"), + "-JobId", job_id, "-RequestedBy", "integration-test", + "-EnvFile", ".env.example"], + cwd=ROOT, check=True, text=True) + + +def main(): + client = Client("http://localhost:8080") + alice, bob, _, chat = client.bootstrap() + + # A permanently malformed delivery is rejected and dead-lettered. + before_dlq = queue_ready(env_value("ATTACHMENT_DLQ_QUEUE")) + command( + "exec", "-T", "rabbitmq", "rabbitmqadmin", + "-u", env_value("RABBITMQ_USER"), "-p", env_value("RABBITMQ_PASSWORD"), + "publish", "exchange=" + env_value("ATTACHMENT_JOB_EXCHANGE"), + "routing_key=" + env_value("ATTACHMENT_JOB_ROUTING_KEY"), + "payload={}", + 'properties={"delivery_mode":2,"content_type":"application/json"}') + deadline = time.monotonic() + 30 + while time.monotonic() < deadline and queue_ready(env_value("ATTACHMENT_DLQ_QUEUE")) <= before_dlq: + time.sleep(0.5) + check(queue_ready(env_value("ATTACHMENT_DLQ_QUEUE")) == before_dlq + 1, + "malformed permanent failure was not dead-lettered exactly once") + + # Replay is allowed only from failed and creates one audit record. + command("stop", "worker") + failed, _ = client.attachment(alice, chat) + job_id = database_scalar( + "SELECT id FROM attachment_jobs WHERE attachment_id = '" + failed["id"] + "';") + database_scalar( + "UPDATE attachment_jobs SET status='failed', published=true, " + "last_error_code='retry_exhausted', lease_token=NULL, lease_until=NULL " + "WHERE id='" + job_id + "'; " + "UPDATE attachments SET status='failed', error_code='retry_exhausted' " + "WHERE id='" + failed["id"] + "'; SELECT 1;") + replay(job_id) + replay(job_id) + audit_count = database_scalar( + "SELECT count(*) FROM attachment_job_replays WHERE job_id='" + job_id + "';") + check(audit_count == "1", "replay was not guarded or was audited more than once") + command("start", "worker") + ready = wait_ready(client, bob, failed) + check(ready["status"] == "ready", "replayed failed job did not become ready") + replay(job_id) + check(database_scalar( + "SELECT count(*) FROM attachment_job_replays WHERE job_id='" + job_id + "';") == "1", + "replay changed an already successful job") + check(database_scalar( + "SELECT count(*) FROM attachment_variants WHERE attachment_id='" + failed["id"] + "';") == "3", + "replay did not preserve exactly one variant set") + + # The API reaper returns an expired processing lease to the durable outbox. + command("stop", "worker") + leased, _ = client.attachment(alice, chat) + lease_job = database_scalar( + "SELECT id FROM attachment_jobs WHERE attachment_id='" + leased["id"] + "';") + database_scalar( + "UPDATE attachment_jobs SET status='processing', attempt=1, published=true, " + "lease_token=gen_random_uuid(), lease_until=clock_timestamp()-interval '1 second' " + "WHERE id='" + lease_job + "'; " + "UPDATE attachments SET status='processing' WHERE id='" + leased["id"] + "'; SELECT 1;") + command("start", "worker") + lease_ready = wait_ready(client, bob, leased) + check(lease_ready["status"] == "ready", "expired processing lease was not recovered") + check(int(database_scalar( + "SELECT attempt FROM attachment_jobs WHERE id='" + lease_job + "';")) >= 2, + "expired lease did not consume a bounded retry attempt") + print("PASS: DLQ, guarded replay and expired lease recovery") + + +if __name__ == "__main__": + run(main) diff --git a/student_tests/lab5_fault_injection.py b/student_tests/lab5_fault_injection.py new file mode 100644 index 00000000..73c0be55 --- /dev/null +++ b/student_tests/lab5_fault_injection.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""Prove recovery across DB-commit/publish and result-commit/ack crashes.""" + +import os +from pathlib import Path +import subprocess +import sys +import time + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) + +from client import Client, Failure, check, run # noqa: E402 + +COMPOSE = ["docker", "compose", "--env-file", ".env.example"] + + +def command(*args, capture=False, environment=None): + result = subprocess.run( + [*COMPOSE, *args], cwd=ROOT, check=True, text=True, + capture_output=capture, env=environment) + return result.stdout.strip() if capture else "" + + +def database_scalar(sql): + return command( + "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", + "-At", "-c", sql, capture=True) + + +def recreate(service, fault_name=None): + environment = os.environ.copy() + environment["FAULT_CRASH_AFTER_OUTBOX_COMMIT"] = "false" + environment["FAULT_CRASH_AFTER_RESULT_COMMIT"] = "false" + if fault_name: + environment[fault_name] = "true" + command("up", "-d", "--no-deps", "--force-recreate", service, + environment=environment) + + +def wait_http(client, seconds=120): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + try: + client.call("GET", "/health/ready", schema="Health") + return + except Failure: + time.sleep(1) + raise Failure("API did not become ready") + + +def wait_job(attachment_id, expected="ready", seconds=120): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + status = database_scalar( + "SELECT status FROM attachment_jobs WHERE attachment_id = '" + + attachment_id + "';") + if status == expected: + return + if status == "failed": + raise Failure("fault-injected job reached failed") + time.sleep(1) + raise Failure("fault-injected job did not reach " + expected) + + +def latest_attachment(chat_id, fault_column): + row = database_scalar( + "SELECT a.id FROM attachments a JOIN attachment_jobs j ON j.attachment_id = a.id " + "WHERE a.chat_id = '" + chat_id + "' AND j." + fault_column + + " = true ORDER BY a.created_at DESC LIMIT 1;") + check(bool(row), "fault marker was not persisted") + return row + + +def main(): + client = Client("http://localhost:8080") + wait_http(client) + alice, bob, _, chat = client.bootstrap() + original = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes() + + # Crash exactly after attachment + outbox COMMIT, before the request thread publishes. + recreate("api", "FAULT_CRASH_AFTER_OUTBOX_COMMIT") + wait_http(client) + try: + client.call( + "POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=outbox.png", + 202, actor=alice, raw=original, headers={"Content-Type": "image/png"}, + schema="Attachment") + raise Failure("outbox fault did not terminate the API request") + except Failure as error: + if "outbox fault did not" in str(error): + raise + + outbox_attachment = latest_attachment(chat["id"], "publish_fault_injected") + wait_job(outbox_attachment) + recreate("api") + wait_http(client) + recovered = client.call( + "GET", "/api/v1/attachments/" + outbox_attachment, + actor=bob, schema="Attachment")["json"] + check(recovered["status"] == "ready", "outbox recovery did not publish the job") + check(len(recovered["variants"]) == 3, "outbox recovery did not finish all variants") + + # Crash after S3 effects + result COMMIT, before RabbitMQ consumer ack. + recreate("worker", "FAULT_CRASH_AFTER_RESULT_COMMIT") + queued = client.call( + "POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=ack-window.png", + 202, actor=alice, raw=original, headers={"Content-Type": "image/png"}, + schema="Attachment")["json"] + wait_job(queued["id"]) + ready = client.wait_ready(bob, queued, wait_seconds=120) + check(len(ready["variants"]) == 3, "result crash lost variants") + result_marker = database_scalar( + "SELECT result_fault_injected FROM attachment_jobs WHERE attachment_id = '" + + queued["id"] + "';") + check(result_marker == "t", "result commit fault marker was not persisted") + recreate("worker") + + deadline = time.monotonic() + 60 + while time.monotonic() < deadline: + queues = command( + "exec", "-T", "rabbitmq", "rabbitmqctl", "list_queues", + "name", "messages_ready", "messages_unacknowledged", capture=True) + if "attachments.process.level4.v1\t0\t0" in queues: + break + time.sleep(1) + variant_count = database_scalar( + "SELECT count(*) FROM attachment_variants WHERE attachment_id = '" + + queued["id"] + "';") + check(variant_count == "3", "redelivery duplicated committed variants") + print("PASS: outbox commit/publish crash and result commit/ack crash recovered") + + +if __name__ == "__main__": + run(main) diff --git a/student_tests/lab5_worker_recovery.py b/student_tests/lab5_worker_recovery.py new file mode 100644 index 00000000..dadcf1ac --- /dev/null +++ b/student_tests/lab5_worker_recovery.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +"""Exercise durable queued upload, component restarts and duplicate delivery. + +Run from the repository root against the local compose.yaml: + python student_tests/lab5_worker_recovery.py +The script preserves volumes and leaves the complete stack running. +""" + +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import time + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) + +from client import Client, Failure, check, run # noqa: E402 +from image_probe import jpeg_size # noqa: E402 + +COMPOSE = ["docker", "compose", "--env-file", ".env.example"] + + +def command(*args, capture=False): + result = subprocess.run( + [*COMPOSE, *args], cwd=ROOT, check=True, + text=True, capture_output=capture) + return result.stdout.strip() if capture else "" + + +def database_scalar(sql): + return command( + "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", + "-At", "-c", sql, capture=True) + + +def env_value(name): + for line in (ROOT / ".env.example").read_text(encoding="utf-8").splitlines(): + if line.startswith(name + "="): + return line.split("=", 1)[1] + raise Failure("missing " + name + " in .env.example") + + +def wait_http_ready(client, seconds=120): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + try: + client.call("GET", "/health/ready", schema="Health") + return + except Failure: + time.sleep(1) + raise Failure("API did not become ready after restart") + + +def wait_rabbit(seconds=120): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + result = subprocess.run( + [*COMPOSE, "exec", "-T", "rabbitmq", "rabbitmq-diagnostics", "-q", "ping"], + cwd=ROOT, text=True, capture_output=True) + if result.returncode == 0: + return + time.sleep(2) + raise Failure("RabbitMQ did not become ready after restart") + + +def main(): + client = Client("http://localhost:8080") + command("stop", "worker") + try: + alice, bob, _, chat = client.bootstrap() + attachment, original = client.attachment(alice, chat) + check(attachment["status"] == "queued", "upload did not remain queued") + client.call( + "GET", "/api/v1/attachments/" + attachment["id"] + "/content", + 409, actor=bob) + linked = client.message(alice, chat, "", attachments=[attachment["id"]])["json"] + check(linked["attachment_ids"] == [attachment["id"]], + "queued attachment could not be linked") + + command("restart", "api") + command("restart", "rabbitmq") + wait_rabbit() + wait_http_ready(client) + command("start", "worker") + + ready = client.wait_ready(bob, attachment, wait_seconds=120) + check(ready["status"] == "ready", "attachment did not become ready") + downloaded = client.call( + "GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=bob) + check(downloaded["bytes"] == original, "original bytes changed") + variants = {item["name"]: item for item in ready["variants"]} + check(set(variants) == {"thumbnail", "crop", "optimized"}, + "expected thumbnail, crop and optimized variants") + check((variants["thumbnail"]["width"], variants["thumbnail"]["height"]) == (256, 160), + "thumbnail dimensions differ from contract") + check((variants["crop"]["width"], variants["crop"]["height"]) == (128, 128), + "crop dimensions differ from contract") + crop = client.call( + "GET", "/api/v1/attachments/" + attachment["id"] + "/content?variant=crop", + actor=bob) + check(crop["headers"].get_content_type() == "image/jpeg", "crop is not JPEG") + check(jpeg_size(crop["bytes"]) == (128, 128), "crop JPEG has wrong dimensions") + optimized = client.call( + "GET", "/api/v1/attachments/" + attachment["id"] + "/content?variant=optimized", + actor=bob) + check(optimized["headers"].get_content_type() == "image/webp", "optimized is not WebP") + check(optimized["bytes"][:4] == b"RIFF" and optimized["bytes"][8:12] == b"WEBP", + "optimized payload has no WebP signature") + + job_row = database_scalar( + "SELECT id || '|' || pipeline_version || '|' || attempt || '|' || " + "to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') " + "FROM attachment_jobs WHERE attachment_id = '" + attachment["id"] + "';") + job_id, pipeline_version, attempt, created_at = job_row.split("|") + payload = json.dumps({ + "schema_version": 1, + "job_id": job_id, + "type": "attachment.process.v1", + "attachment_id": attachment["id"], + "pipeline_version": int(pipeline_version), + "attempt": int(attempt), + "created_at": created_at, + }, separators=(",", ":")) + command( + "exec", "-T", "rabbitmq", "rabbitmqadmin", + "-u", env_value("RABBITMQ_USER"), + "-p", env_value("RABBITMQ_PASSWORD"), + "publish", "exchange=" + env_value("ATTACHMENT_JOB_EXCHANGE"), + "routing_key=" + env_value("ATTACHMENT_JOB_ROUTING_KEY"), + "payload=" + payload, + 'properties={"delivery_mode":2,"content_type":"application/json"}') + + deadline = time.monotonic() + 30 + while time.monotonic() < deadline: + queued = command( + "exec", "-T", "rabbitmq", "rabbitmqctl", "list_queues", + "name", "messages_ready", "messages_unacknowledged", capture=True) + if env_value("ATTACHMENT_JOB_QUEUE") + "\t0\t0" in queued: + break + time.sleep(0.5) + variant_count = database_scalar( + "SELECT count(*) FROM attachment_variants WHERE attachment_id = '" + + attachment["id"] + "';") + status = database_scalar( + "SELECT status FROM attachments WHERE id = '" + attachment["id"] + "';") + check(variant_count == "3", "duplicate delivery changed the three variant rows") + check(status == "ready", "duplicate delivery changed terminal ready state") + check(hashlib.sha256(downloaded["bytes"]).hexdigest() == attachment["sha256"], + "original checksum changed") + print("PASS: stopped worker, durable restart recovery and duplicate delivery") + finally: + command("start", "worker") + + +if __name__ == "__main__": + run(main) -- 2.54.0 From a4d58b2eec0f331fa8165589e4b17a30d6f4b154 Mon Sep 17 00:00:00 2001 From: EgorAnti Date: Thu, 19 Nov 2026 10:57:39 +0300 Subject: [PATCH 3/3] 5 --- .env.example | 3 + REPORT.md | 179 ++++++++-- compose.yaml | 3 + evidence/failover-each-2026-11-19.json | 24 ++ evidence/lab5-level5-2026-11-19.md | 213 ++++++++++++ evidence/rolling-update-2026-11-19.json | 23 ++ evidence/upload-memory-2026-11-19.json | 14 + scripts/promote-pipeline.ps1 | 73 ++++ scripts/promote-pipeline.sh | 59 ++++ scripts/replay-failed.ps1 | 1 + scripts/replay-failed.sh | 1 + .../mtusi_messenger/model/AttachmentJob.java | 11 +- .../queue/ExpiredLeaseReaper.java | 6 +- .../repository/AttachmentRepository.java | 14 +- .../PostgresAttachmentRepository.java | 122 ++++--- .../service/AttachmentService.java | 11 +- .../service/ReadinessService.java | 10 +- .../worker/AttachmentWorker.java | 51 ++- .../worker/ImageVariantProcessor.java | 28 +- src/main/resources/application.yml | 3 + ...7__versioned_pipeline_and_fault_points.sql | 33 ++ .../service/AttachmentServiceTest.java | 4 +- .../worker/ImageVariantProcessorTest.java | 28 +- student_tests/README.md | 7 +- student_tests/concurrent_upload_memory.py | 2 +- student_tests/lab5_pipeline_idempotency.py | 314 ++++++++++++++++++ 26 files changed, 1141 insertions(+), 96 deletions(-) create mode 100644 evidence/failover-each-2026-11-19.json create mode 100644 evidence/lab5-level5-2026-11-19.md create mode 100644 evidence/rolling-update-2026-11-19.json create mode 100644 evidence/upload-memory-2026-11-19.json create mode 100644 scripts/promote-pipeline.ps1 create mode 100644 scripts/promote-pipeline.sh create mode 100644 src/main/resources/db/migration/V7__versioned_pipeline_and_fault_points.sql create mode 100644 student_tests/lab5_pipeline_idempotency.py diff --git a/.env.example b/.env.example index c13c3ba8..69c730c5 100644 --- a/.env.example +++ b/.env.example @@ -14,6 +14,7 @@ ATTACHMENT_JOB_ROUTING_KEY=attachment.process.v1 ATTACHMENT_DLQ_EXCHANGE=attachments.dlx.v1 ATTACHMENT_DLQ_QUEUE=attachments.failed.v1 ATTACHMENT_DLQ_ROUTING_KEY=attachment.failed.v1 +ATTACHMENT_PIPELINE_VERSION=2 WORKER_CONCURRENCY=2 WORKER_PREFETCH=1 JOB_MAX_ATTEMPTS=5 @@ -28,6 +29,8 @@ WORKER_MEMORY_WAIT=2s # Fault injection is opt-in and intended only for an isolated test stand. FAULT_CRASH_AFTER_OUTBOX_COMMIT=false +FAULT_CRASH_BEFORE_SIDE_EFFECT=false +FAULT_CRASH_AFTER_SIDE_EFFECT=false FAULT_CRASH_AFTER_RESULT_COMMIT=false S3_REGION=us-east-1 diff --git a/REPORT.md b/REPORT.md index 687415e4..6afcfe27 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,10 +1,10 @@ # Отчёт — лабораторная 5 -- Автор, группа: TODO -- Целевая оценка: 4 +- Автор, группа: Антипин Егор Иванович +- Целевая оценка: **5**, трек 2 «Доказанная идемпотентность pipeline» - Commit/PR: TODO после публикации - Библиотеки: Spring AMQP, RabbitMQ Java client, Thumbnailator, webp-imageio, MinIO SDK, PostgreSQL/Flyway -- Помощь ИИ: проектирование pipeline, реализация и подготовка тестов; результат проверен сборкой, unit- и black-box-тестами +- Помощь ИИ: проектирование versioned pipeline, fencing и fault-injection, реализация, подготовка тестов и черновиков evidence; результат проверен сборкой, unit-, black-box- и аварийными тестами ## Запуск из чистого clone @@ -18,24 +18,135 @@ docker compose --env-file .env up -d --build python -X utf8 tests/smoke.py --base-url http://localhost:8080 ``` -`docker compose --env-file .env down` сохраняет volumes. Удаление учебных данных выполняется только явной командой оператора с `--volumes`. +Автоматические `student_tests/lab5_*.py` используют `.env.example` и рассчитаны +на одноразовый учебный стенд; для них удобно поднимать Compose с тем же файлом: + +```sh +docker compose --env-file .env.example up -d --build +python -X utf8 student_tests/lab5_pipeline_idempotency.py +``` + +`docker compose --env-file .env down` сохраняет volumes. Удаление учебных данных +выполняется только явной командой оператора с `--volumes`. ## Pipeline и гарантии -Upload разделён на durable-границы: API проверяет bytes/MIME/dimensions, пишет неизменённый original в приватный `staging//original`, затем одной транзакцией создаёт `attachments(queued)` и `attachment_jobs(published=false)`. Запись job является transactional outbox. Фоновый publisher публикует persistent JSON в durable RabbitMQ queue, ждёт publisher confirm и только потом помечает job опубликованной. Поэтому COMMIT без publish восстанавливается автоматически, а HTTP `202` означает, что staging и намерение обработки уже устойчивы. +Upload разделён на durable-границы: API проверяет bytes/MIME/dimensions, пишет +неизменённый original в приватный `staging//original`, затем одной +транзакцией создаёт `attachments(queued)` и `attachment_jobs(published=false)`. +Запись job является transactional outbox. Фоновый publisher публикует persistent +JSON в durable RabbitMQ queue, ждёт publisher confirm и только потом помечает job +опубликованной. Поэтому COMMIT без publish восстанавливается автоматически, а +HTTP `202` означает, что staging и намерение обработки уже устойчивы. -Отдельный `worker` захватывает job с lease, читает доверенный staging key из PostgreSQL и создаёт детерминированные S3 keys. В broker message есть только `schema_version`, `job_id`, `attachment_id`, `pipeline_version`, `attempt`, `created_at`; bytes, credentials, произвольные URL и клиентские пути отсутствуют. Эффект идемпотентен по `(attachment_id, pipeline_version, variant)`. Все variant rows и `ready` фиксируются атомарно; ack выполняется после COMMIT. Redelivery уже `ready` job — no-op. +Отдельный `worker` захватывает job с lease, читает доверенный staging key из +PostgreSQL и создаёт детерминированные S3 keys. В broker message есть только +`schema_version`, `job_id`, `attachment_id`, `pipeline_version`, `attempt`, +`created_at`; bytes, credentials, произвольные URL и клиентские пути отсутствуют. +Эффект идемпотентен по `(attachment_id, pipeline_version, variant)`. Все variant +rows и `ready` фиксируются атомарно; ack выполняется после COMMIT. Redelivery уже +`ready` job — no-op. -Обязательные варианты pipeline version 1: +Обязательные варианты для активной версии: | Вариант | Правило | Формат/качество | | --- | --- | --- | | `original` | bytes и SHA-256 совпадают с upload | исходный MIME | -| `thumbnail` | fit в 256×256, без увеличения, EXIF orientation, alpha на белом | JPEG, quality 0.85 | -| `crop` | центрированный квадрат 128×128 после EXIF orientation | JPEG, quality 0.88 | -| `optimized` | fit до 1280×1280, без увеличения, alpha сохраняется | WebP, quality 0.82 | +| `thumbnail` | fit в 256×256, без увеличения, EXIF orientation, alpha на белом | JPEG, quality зависит от версии | +| `crop` | центрированный квадрат 128×128 после EXIF orientation | JPEG, quality зависит от версии | +| `optimized` | fit до 1280×1280, без увеличения, alpha сохраняется | WebP, quality зависит от версии | -Новые файлы кодируются из пикселей без копирования EXIF/ICC/прочих исходных metadata. +Новые файлы кодируются из пикселей без копирования EXIF/ICC/прочих исходных +metadata. + +## Versioned pipeline v1/v2 + +Миграция `V7__versioned_pipeline_and_fault_points.sql` добавляет: + +- `attachments.pipeline_version`; +- уникальность `attachment_jobs(attachment_id, pipeline_version)`; +- состояние `superseded`; +- audit-таблицу `attachment_pipeline_promotions`; +- маркеры fault-injection до и после side effect. + +`ImageVariantProcessor` выбирает профиль по `pipeline_version`: v1 и v2 имеют +разные quality для JPEG/WebP, поэтому результаты версий различаются побайтово. +Ключи объектов версионированы: `thumbnail-v1.jpg`, `thumbnail-v2.jpg`, +`optimized-v1.webp` и т.д.; общий `original` неизменяем. Старая версия физически +не может перезаписать объект новой версии. Одна и та же `pipeline_version` +обязана быть детерминированной: изменение quality/алгоритма оформляется новой +версией, иначе `ON CONFLICT DO NOTHING` сохранит уже записанные variant rows. + +Повышение версии — одна аудированная транзакция +`scripts/promote-pipeline.ps1`/`.sh`: + +1. блокирует attachment; +2. переводит старые `queued/processing` jobs в `superseded` и `published=true`; +3. создаёт новую job версии `N`; +4. обновляет `attachments.pipeline_version` и `status=queued`; +5. пишет `attachment_pipeline_promotions`. + +Fencing выполняется в каждом переходе состояния: `claim`, `markReady`, +`markFailed`, retry, expired-lease recovery и replay проверяют одновременно +`job.pipeline_version`, `attachments.pipeline_version`, lease token и terminal +state. Поэтому старая job после promotion не может ни получить lease, ни +записать variants, ни перевести attachment в `ready`. + +Если v1 уже удалил staging после безопасного COMMIT, worker версии v2 читает +неизменяемый `attachments//original`; содержимое и SHA-256 те же. + +## Fault injection и инварианты + +| Точка | Поведение | +| --- | --- | +| `FAULT_CRASH_AFTER_OUTBOX_COMMIT` | API падает после COMMIT attachment/outbox, до publish; republisher восстанавливает намерение | +| `FAULT_CRASH_BEFORE_SIDE_EFFECT` | worker падает до S3 PUT; lease истекает, reaper возвращает job в outbox | +| `FAULT_CRASH_AFTER_SIDE_EFFECT` | worker падает после детерминированных S3 PUT, до result COMMIT; повтор сходится к тем же объектам | +| `FAULT_CRASH_AFTER_RESULT_COMMIT` | worker падает после atomic `ready` COMMIT, до consumer ack; redelivery — no-op | + +Все флаги по умолчанию выключены и предназначены только для изолированного +стенда. Автоматический `student_tests/lab5_pipeline_idempotency.py` проверяет: + +- duplicate: две одинаковые v2-доставки дают один результат; +- reorder: v2 доставляется раньше stale v1; +- stale: v1 после v2 не меняет snapshot активного результата; +- superseded: повышение ещё queued v1 job отменяет её без variant rows; +- crash до S3 side effect: 0 объектов, 0 result rows, восстановление через + повторную попытку; +- crash после S3 side effect: 4 объекта до COMMIT, после повтора — те же 4 + объекта и ровно 3 variant rows; +- crash после result COMMIT: redelivery не дублирует variants; +- все 5 подтверждённых вложений остаются `ready`. + +Зафиксированные инварианты: + +1. `ready` активной версии ⇒ ровно три variant rows активной версии и нет + `queued/processing` jobs. +2. Не более одной активной job на attachment. +3. `(attachment_id, pipeline_version, name)` уникален; повтор не создаёт дубль. +4. Versioned object keys не позволяют старой версии перезаписать новую. +5. `pipeline_version` повышается только аудированной транзакцией; старая + `queued/processing` job становится `superseded`. +6. Подтверждённые задачи не теряются после duplicate/reorder/stale/crash. +7. Нет variant rows версии больше активной. + +## Почему это не exactly-once доставка + +RabbitMQ обеспечивает **at-least-once**: сообщение может быть доставлено +повторно после потери соединения или падения worker до ack; порядок сообщений не +является бизнес-порядком. Publisher confirm подтверждает только приём брокером, +а consumer ack идёт после PostgreSQL COMMIT. Между S3 PUT и COMMIT нет +распределённой транзакции, поэтому crash в этом окне оставляет уже выполненные +side effects и вызывает повторную обработку. + +Идемпотентность достигнута на уровне **эффекта**, а не доставки: deterministic +object keys, `ON CONFLICT DO NOTHING`, уникальные PK и conditional `markReady` +приводят любые повторы к одному наблюдаемому состоянию активной версии. То же +самое можно назвать **effectively-once** результатом при at-least-once +доставке. Exactly-once доставка потребовала бы транзакционной связи RabbitMQ, +PostgreSQL и S3 или эквивалентного распределённого протокола; в этой учебной +архитектуре её нет, и тест сознательно демонстрирует лишние повторы S3 PUT, +которые не меняют результат. ## Ограничения worker и retry @@ -47,25 +158,49 @@ Upload разделён на durable-границы: API проверяет byte - Не более `JOB_MAX_ATTEMPTS=5`. Временные ошибки получают exponential backoff с jitter 50–100% и cap 30s. Ошибки decode/format/size постоянные и сразу становятся безопасным `failed/error_code`; exhausted retry — `retry_exhausted`. - Permanent malformed broker delivery и исчерпанная работа dead-lettered в durable `attachments.failed.v1`. Реестр failed остаётся в PostgreSQL. -Операторский replay выполняется `scripts/replay-failed.ps1 -JobId ` или `scripts/replay-failed.sh `. Одна транзакция блокирует одновременно failed job и attachment, пишет `attachment_job_replays`, сбрасывает outbox и состояние. Не-failed, уже recovered и `ready` jobs дают явный безопасный `no-op`. +Операторский replay выполняется `scripts/replay-failed.ps1 -JobId ` или +`scripts/replay-failed.sh `. Одна транзакция блокирует одновременно failed +job и attachment, пишет `attachment_job_replays`, сбрасывает outbox и состояние. +Не-failed, уже recovered и `ready` jobs дают явный безопасный `no-op`; replay +также требует совпадения `pipeline_version`. -После безопасного COMMIT результата worker best-effort удаляет staging. `StagingCleaner` удаляет только неактивные объекты старше `STAGING_RETENTION_SECONDS=86400`; queued/processing staging защищён. +После безопасного COMMIT результата worker best-effort удаляет staging. +`StagingCleaner` удаляет только неактивные объекты старше +`STAGING_RETENTION_SECONDS=86400`; queued/processing staging защищён. Отдельного +GC для orphan-объектов старых версий после promotion «в полёте» нет: active +результат они не перезаписывают, но место могут занимать. -## Fault injection и проверки +## Проверки | Критерий | Команда | Результат | | --- | --- | --- | -| Unit tests | `gradlew test --tests '*AttachmentServiceTest' --tests '*ImageVariantProcessorTest' --tests '*RetryPolicyTest' --tests '*AttachmentReconcilerTest' --tests '*StagingCleanerTest'` | `BUILD SUCCESSFUL` | -| Contract/Compose | `python -X utf8 scripts/check_contract.py`; `docker compose --env-file .env.example config --quiet` | PASS | +| Unit + integration | `gradlew test` | `BUILD SUCCESSFUL`, 30 tests | +| Contract/Compose | `python -X utf8 scripts/check_contract.py`; `docker compose --env-file .env.example config --quiet` | PASS, exit 0 | | Публичный smoke | `python -X utf8 tests/smoke.py --base-url http://localhost:8080` | PASS | -| Worker stop, broker/API restart, redelivery | `python -X utf8 student_tests/lab5_worker_recovery.py` | PASS; original неизменен, 3 variants, duplicate не создаёт rows | -| COMMIT→publish и result COMMIT→ack crash | `python -X utf8 student_tests/lab5_fault_injection.py` | PASS; обе задачи автоматически дошли до ready | +| Трек 5.2 | `python -X utf8 student_tests/lab5_pipeline_idempotency.py` | PASS: version fencing, superseded, duplicate/reorder, pre/post-side-effect crashes | +| Worker stop/restart, redelivery | `python -X utf8 student_tests/lab5_worker_recovery.py` | PASS; original неизменен, 3 variants, duplicate не создаёт rows | +| COMMIT→publish и result COMMIT→ack | `python -X utf8 student_tests/lab5_fault_injection.py` | PASS; обе задачи дошли до ready | | DLQ, replay, lease | `python -X utf8 student_tests/lab5_dlq_replay_lease.py` | PASS; DLQ +1, одна audit-запись, ready не replayed, expired lease восстановлен | +| Lab3: shared idempotency | `python -X utf8 student_tests/idempotency_concurrent.py` | PASS; 32 запроса, 2 реплики, одно сообщение | +| Lab3: readiness gate | `python -X utf8 student_tests/readiness_gate.py` | PASS; обе реплики 503 на сломанной схеме и восстановились | +| Lab3: failover каждой реплики | `python -X utf8 student_tests/failover_each.py ...` | PASS; 2 реплики, confirmed writes сохранены | +| Lab3: rolling update | `python -X utf8 student_tests/rolling_update.py ...` | PASS; 4 instance ID, 335 успешных записей, 3 переходных отказа | +| Lab4: negative | `python -X utf8 student_tests/lab4_negative.py` | PASS; ownership/MIME/corruption/limit/filename | +| Lab4: upload memory | `python -X utf8 student_tests/concurrent_upload_memory.py ...` | PASS; 12/12 uploads, 2 API реплики | -Fault flags выключены по умолчанию. `FAULT_CRASH_AFTER_OUTBOX_COMMIT=true` один раз завершает API через `Runtime.halt(87)` после DB COMMIT до publish. После restart republisher находит `published=false`, и job достигает ready. `FAULT_CRASH_AFTER_RESULT_COMMIT=true` один раз завершает worker через `Runtime.halt(86)` после атомарного ready до consumer ack; RabbitMQ redelivery проверяет ready и завершает ту же job без второго набора вариантов. - -Подробный журнал: `evidence/lab5-level4-2026-11-19.md`. +Подробный журнал с SQL-инвариантами и JSON-агрегатами: +`evidence/lab5-level5-2026-11-19.md`. Предыдущие уровни: +`evidence/lab5-level4-2026-11-19.md`, `evidence/lab4-2026-11-11.md`. ## Ограничения -Это уровень 4, не исследовательский трек 5: производительность для матрицы concurrency/prefetch не измерялась, multi-version reorder не исследовался. RabbitMQ, PostgreSQL и MinIO развёрнуты по одному экземпляру; volumes переживают container restart, но не потерю host/disk. At-least-once + идемпотентный эффект не является exactly-once доставкой. +- Один Docker-host, по одному экземпляру PostgreSQL, RabbitMQ, Redis и MinIO; + эксперимент не доказывает отказоустойчивость к потере host/диска. +- Exactly-once доставки нет; доказан at-least-once + идемпотентный эффект. +- Versioned orphan-объекты старых версий после promotion «в полёте» не + перезаписывают active результат, но автоматического GC для них нет. +- `promote-pipeline` — операторский скрипт с SQL-транзакцией, не публичный API. +- Исторические 3 attachment от 2026-11-18 созданы до V7 и имеют один вариант; + на чистом volume и для новых данных действует инвариант трёх вариантов. +- Числа failover/rolling — проверка сохранности на одном Windows-хосте, не + benchmark пропускной способности. diff --git a/compose.yaml b/compose.yaml index 82fa8d81..6ccc63cb 100644 --- a/compose.yaml +++ b/compose.yaml @@ -41,6 +41,7 @@ x-api-environment: &api-environment ATTACHMENT_DLQ_EXCHANGE: ${ATTACHMENT_DLQ_EXCHANGE:-attachments.dlx.v1} ATTACHMENT_DLQ_QUEUE: ${ATTACHMENT_DLQ_QUEUE:-attachments.failed.v1} ATTACHMENT_DLQ_ROUTING_KEY: ${ATTACHMENT_DLQ_ROUTING_KEY:-attachment.failed.v1} + ATTACHMENT_PIPELINE_VERSION: ${ATTACHMENT_PIPELINE_VERSION:-2} WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2} WORKER_PREFETCH: ${WORKER_PREFETCH:-1} JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} @@ -258,6 +259,8 @@ services: MESSENGER_ROLE: worker SPRING_MAIN_WEB_APPLICATION_TYPE: none JAVA_TOOL_OPTIONS: -XX:MaxRAMPercentage=70 + FAULT_CRASH_BEFORE_SIDE_EFFECT: ${FAULT_CRASH_BEFORE_SIDE_EFFECT:-false} + FAULT_CRASH_AFTER_SIDE_EFFECT: ${FAULT_CRASH_AFTER_SIDE_EFFECT:-false} FAULT_CRASH_AFTER_RESULT_COMMIT: ${FAULT_CRASH_AFTER_RESULT_COMMIT:-false} depends_on: migrate: diff --git a/evidence/failover-each-2026-11-19.json b/evidence/failover-each-2026-11-19.json new file mode 100644 index 00000000..a8241bd9 --- /dev/null +++ b/evidence/failover-each-2026-11-19.json @@ -0,0 +1,24 @@ +{ + "scenario": "sequential failover of each API replica", + "replicas": 2, + "results": [ + { + "target_instance_id": "8e081627dfc3", + "window_seconds": 15.775, + "successful_reads": 3, + "successful_writes": 4, + "failed_attempts": 0, + "successful_rps": 0.444, + "first_recovery_seconds": 5.018 + }, + { + "target_instance_id": "95b5db854bee", + "window_seconds": 16.774, + "successful_reads": 3, + "successful_writes": 3, + "failed_attempts": 1, + "successful_rps": 0.358, + "first_recovery_seconds": 6.15 + } + ] +} diff --git a/evidence/lab5-level5-2026-11-19.md b/evidence/lab5-level5-2026-11-19.md new file mode 100644 index 00000000..438c45bb --- /dev/null +++ b/evidence/lab5-level5-2026-11-19.md @@ -0,0 +1,213 @@ +# Lab5, трек 5.2 — доказанная идемпотентность pipeline + +Дата: 2026-11-19. Исходная точка: `75d2f78` + рабочее дерево с изменениями lab5. +Стенд: Windows, Docker 28.0.1, Docker Compose 2.33.1, Java 23 (контейнеры и Gradle +toolchain), Spring Boot 4.1.1, PostgreSQL 16.4, RabbitMQ 4.1.4, Redis 7.4, +MinIO `bitnamilegacy/minio:2025.4.22-debian-12-r1`. + +Все пользователи, сообщения и изображения синтетические. Секреты, session tokens, +содержимое сообщений и signed URL в evidence не сохранялись. + +## Гипотеза и инварианты + +Гипотеза: при versioned pipeline и fencing по `(attachment_id, pipeline_version, +lease)` повторная доставка, перестановка сообщений, crash в окнах до/после side +effect и устаревшая job не теряют подтверждённую работу и не заменяют результат +новой версии старым. + +Проверяемые инварианты: + +1. `attachments.status='ready'` для активной версии означает ровно три variant + rows этой версии (`thumbnail`, `crop`, `optimized`) и отсутствие + `queued/processing` jobs у вложения. +2. Для вложения существует не более одной активной (`queued/processing`) job. +3. Ключ variant rows — `(attachment_id, pipeline_version, name)`; повторная + запись не создаёт дубль. +4. Объектные ключи версионированы: `thumbnail-vN.jpg`, `crop-vN.jpg`, + `optimized-vN.webp`; `original` общий и неизменяемый. Поэтому v1 не может + перезаписать v2. +5. `attachments.pipeline_version` монотонно повышается только аудированной + транзакцией `promote-pipeline`; старая `queued/processing` job получает + `superseded` и `published=true`. +6. Все подтверждённые тестом задачи (`status='ready'`) остаются `ready` после + duplicate/reorder/stale доставок. +7. В active version нет variant rows с `pipeline_version` больше + `attachments.pipeline_version`. +8. Одна и та же `pipeline_version` детерминирована; изменение профиля + оформляется новой версией, потому что `ON CONFLICT DO NOTHING` не перезаписывает + уже зафиксированные variant rows. + +## Команды и результаты + +```text +python -X utf8 scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. + +docker compose --env-file .env.example config --quiet +exit 0 + +.\gradlew.bat test +BUILD SUCCESSFUL (30 tests; full suite against live Compose PostgreSQL/Redis/MinIO) +``` + +Для полного Gradle suite хранилища Compose не публикуют порты наружу; на время +прогона использовались временные localhost-туннели к `postgres:5432`, +`redis:6379`, `rabbitmq:5672`, `minio:9000`. После прогона туннели удалены. + +### Основной эксперимент трека + +```text +python -X utf8 student_tests/lab5_pipeline_idempotency.py +PASS: version fencing, superseded, duplicate/reorder and pre/post-side-effect crashes +``` + +Тест автоматически: + +1. создаёт v1 attachment, дожидается `ready` и снимает snapshot трёх variant rows; +2. останавливает worker, повышает версию до v2 через `scripts/promote-pipeline`, + публикует `v2, v2, v1` (порядок доставки не совпадает с порядком создания) и + запускает worker; +3. проверяет, что v2 дал отдельный результат, в БД ровно 6 rows (3 v1 + 3 v2), + active version = 2, а повторные stale v1 / duplicate v2 не меняют snapshot; +4. отдельно повышает ещё **queued** v1 job: она становится + `superseded|published=true|superseded_by_v2`, v1 variant rows не появляются, + v2 доходит до `ready` с тремя вариантами; +5. вставляет crash до S3 side effect, после S3 side effect и после result + COMMIT; каждый раз проверяет восстановление через lease/reaper/redelivery; +6. проверяет, что все 5 подтверждённых вложений остались `ready`. + +### Наблюдаемое состояние после прогона + +Пример versioned-attachment (сокращённые ID приведены для читаемости): + +```text +attachment A (v1 -> v2, сначала завершён v1) + active=2 ready + job v1 ready published=t attempt=1 + job v2 ready published=t attempt=1 + variant keys: crop-v1, optimized-v1, thumbnail-v1, + crop-v2, optimized-v2, thumbnail-v2 + +attachment B (queued v1 повышен до v2) + active=2 ready + job v1 superseded published=t last_error=superseded_by_v2 + job v2 ready published=t attempt=1 + variant keys: crop-v2, optimized-v2, thumbnail-v2 (v1 rows отсутствуют) +``` + +SQL-инварианты по всем attachment, созданным 2026-11-19 в ходе финального +прогона и регрессии lab5: + +```text +superseded_jobs|1 +today_promotions|9 +today_ready|55 +today_ready_bad_variants|0 +ready_with_nonterminal_job|0 +attachments_with_two_active_jobs|0 +duplicate_variant_keys|0 +stale_results_for_active_version|0 +``` + +Полный volume содержит также 3 attachment, созданных 2026-11-18 до миграции V7 +(тогда уровень 3 сохранял только original + thumbnail). Это исторические данные +предыдущего стенда; они не являются результатом текущего versioned pipeline. +Запросы инвариантов выше ограничены `created_at >= '2026-11-19'`; на чистом +volume исторических строк нет. + +### Точки отказа + +| Fault | Где срабатывает | Наблюдение | +| --- | --- | --- | +| `FAULT_CRASH_BEFORE_SIDE_EFFECT` | worker, до чтения staging/S3 PUT, `halt(84)` | 0 variant rows, 0 объектов; reaper возвращает job в `queued`, attempt увеличивается, задача доходит до `ready` | +| `FAULT_CRASH_AFTER_SIDE_EFFECT` | worker, после 4 S3 PUT, до result COMMIT, `halt(85)` | objects=4, variant rows=0; повтор пишет те же deterministic keys и коммитит результат, objects остаётся 4 | +| `FAULT_CRASH_AFTER_RESULT_COMMIT` | worker, после atomic `ready` COMMIT, до ack, `halt(86)` | redelivery видит `ready` и завершает no-op; 3 variant rows не дублируются | +| `FAULT_CRASH_AFTER_OUTBOX_COMMIT` | API, после COMMIT attachment/outbox, до publish, `halt(87)` | republisher находит `published=false` и публикует сохранённое намерение; задача доходит до `ready` | + +Crash-точки включаются только переменными окружения и по умолчанию выключены; +они предназначены для изолированного учебного стенда. + +## Регрессия уровней 3–4 + +```text +python -X utf8 tests/smoke.py --base-url http://localhost:8080 +PASS: lab5 public API scenario; infrastructure and grading evidence remain separate. + +python -X utf8 student_tests/lab5_worker_recovery.py +PASS: stopped worker, durable restart recovery and duplicate delivery + +python -X utf8 student_tests/lab5_fault_injection.py +PASS: outbox commit/publish crash and result commit/ack crash recovered + +python -X utf8 student_tests/lab5_dlq_replay_lease.py +PASS: DLQ, guarded replay and expired lease recovery + +python -X utf8 student_tests/idempotency_concurrent.py +PASS: 32 concurrent requests used 2 replicas and created one message + +python -X utf8 student_tests/readiness_gate.py +PASS: 2 unhealthy API containers refused business traffic with 503 and recovered after schema restoration + +python -X utf8 student_tests/failover_each.py --action-script scripts/stop-one.cmd \ + --restore-script scripts/restore-api.cmd --window 15 \ + --output evidence/failover-each-2026-11-19.json +(JSON: 2 replicas sequentially stopped and restored; confirmed writes preserved) + +python -X utf8 student_tests/rolling_update.py --action-script scripts/rolling-update.cmd \ + --duration 180 --concurrency 4 \ + --output evidence/rolling-update-2026-11-19.json +(JSON: 4 observed replacement instance IDs; 335 successful writes, 3 transitional failures) + +python -X utf8 student_tests/lab4_negative.py +PASS: unknown/foreign attachment, foreign chat/user, MIME spoof, corruption, byte limit and filename checks + +python -X utf8 student_tests/concurrent_upload_memory.py \ + --output evidence/upload-memory-2026-11-19.json +PASS: concurrent upload memory experiment (12/12 uploads accepted, 2 API replicas) +``` + +`readiness_gate.py` проверяет Google-подобный gate по обязательной схеме: +`ReadinessService` теперь пробует обе таблицы — `message_idempotency` (lab3) и +`attachments` (lab4/lab5). `concurrent_upload_memory.py` обновлён с lab4-контракта +`201` на lab5-контракт `202`. + +## Почему это at-least-once, а не exactly-once + +RabbitMQ даёт at-least-once: сообщение может быть доставлено повторно после +потери соединения или падения worker до ack; порядок между разными сообщениями +не является бизнес-порядком. Поэтому duplicate и reorder — нормальные состояния, +а не аномалии. + +Наш pipeline делает **эффект** идемпотентным, но не делает доставку exactly-once: + +- publisher confirm подтверждает только приём сообщения брокером, а consumer ack + отправляется после PostgreSQL COMMIT; между S3 PUT и COMMIT нет распределённой + транзакции; +- crash после S3 PUT и до COMMIT оставляет объекты, а crash после COMMIT и до ack + вызывает redelivery; оба окна специально инжектируются тестом; +- повторная обработка может повторно выполнить S3 PUT, но deterministic keys, + `ON CONFLICT DO NOTHING`, уникальные PK и conditional `markReady` не создают + второго набора результатов и не меняют active version; +- stale job ограничена `pipeline_version` и lease в каждом переходе состояния, + поэтому не может записать результат поверх новой версии. + +Корректная формулировка: **at-least-once delivery + idempotent effect = +effectively-once наблюдаемый результат для активной версии**. Exactly-once +доставка потребовала бы транзакционной связи RabbitMQ, PostgreSQL и S3 (или +эквивалентного распределённого протокола), которой в этой учебной архитектуре +нет и которая не нужна для данных инвариантов. + +## Границы + +- Один Docker-host, по одному экземпляру PostgreSQL, RabbitMQ, Redis и MinIO; + эксперимент не доказывает отказоустойчивость к потере host/диска. +- Versioned S3 objects старой версии после promotion «в полёте» могут остаться + orphan-объектами: active result они не перезаписывают, но отдельного GC для + versioned objects нет (чистится только staging). +- `superseded`/promotion — операторская SQL-транзакция через скрипт, не публичный + HTTP API. +- Числа failover/rolling в JSON — проверка сохранности и восстановления на одном + Windows-хосте, не benchmark пропускной способности; latency включает + особенность localhost dual-stack в Docker Desktop. +- Исторические 3 attachment от 2026-11-18 созданы до V7 и имеют один вариант; + на чистом volume и для новых данных действует инвариант трёх вариантов. diff --git a/evidence/rolling-update-2026-11-19.json b/evidence/rolling-update-2026-11-19.json new file mode 100644 index 00000000..6362bc49 --- /dev/null +++ b/evidence/rolling-update-2026-11-19.json @@ -0,0 +1,23 @@ +{ + "scenario": "sequential API replacement under closed-loop writes", + "requested_duration_seconds": 180.0, + "elapsed_seconds": 182.022, + "rolling_action_seconds": 125.275, + "concurrency": 4, + "observed_instance_ids": [ + "431acab3a50c", + "8e081627dfc3", + "d67820ebd09d", + "fdff9a67741c" + ], + "successful_requests": 335, + "failed_requests": 3, + "error_ratio": 0.008876, + "successful_rps": 1.84, + "successful_latency_ms": { + "p50": 2092.164, + "p95": 2252.301, + "p99": 3064.667 + }, + "note": "Closed-loop result on one host; success latency excludes failures." +} diff --git a/evidence/upload-memory-2026-11-19.json b/evidence/upload-memory-2026-11-19.json new file mode 100644 index 00000000..252469de --- /dev/null +++ b/evidence/upload-memory-2026-11-19.json @@ -0,0 +1,14 @@ +{ + "concurrency": 12, + "successful_uploads": 12, + "payload_bytes_each": 6835833, + "duration_seconds": 31.241, + "api_replicas": 2, + "memory_samples": 10, + "baseline_api_memory_bytes": 665321471, + "peak_api_memory_bytes": 833198489, + "peak_increase_bytes": 167877018, + "configured_max_concurrent_uploads_per_replica": 3, + "configured_max_upload_bytes": 10485760, + "configured_max_image_pixels": 40000000 +} diff --git a/scripts/promote-pipeline.ps1 b/scripts/promote-pipeline.ps1 new file mode 100644 index 00000000..6eae43de --- /dev/null +++ b/scripts/promote-pipeline.ps1 @@ -0,0 +1,73 @@ +param( + [Parameter(Mandatory = $true)] + [string]$AttachmentId, + [Parameter(Mandatory = $true)] + [ValidateRange(1, 2)] + [int]$PipelineVersion, + [string]$RequestedBy = $env:USERNAME, + [string]$EnvFile = ".env" +) + +$parsedAttachmentId = [guid]::Empty +if (-not [guid]::TryParse($AttachmentId, [ref]$parsedAttachmentId)) { + throw "AttachmentId must be a UUID" +} +if ($RequestedBy -notmatch '^[A-Za-z0-9_.@-]{1,128}$') { + throw "RequestedBy contains unsupported characters" +} + +$sql = @" +WITH candidate AS ( + SELECT id, pipeline_version + FROM attachments + WHERE id = '$parsedAttachmentId'::uuid AND pipeline_version < $PipelineVersion + FOR UPDATE +), superseded AS ( + UPDATE attachment_jobs j + SET status = 'superseded', published = true, + last_error_code = 'superseded_by_v$PipelineVersion', + lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp() + FROM candidate c + WHERE j.attachment_id = c.id AND j.pipeline_version < $PipelineVersion + AND j.status IN ('queued', 'processing') + RETURNING j.id +), created AS ( + INSERT INTO attachment_jobs + (id, attachment_id, pipeline_version, attempt, status, published, + next_attempt_at, created_at, updated_at) + SELECT gen_random_uuid(), id, $PipelineVersion, 1, 'queued', false, + clock_timestamp(), clock_timestamp(), clock_timestamp() + FROM candidate + ON CONFLICT (attachment_id, pipeline_version) DO NOTHING + RETURNING id, attachment_id +), promoted AS ( + UPDATE attachments a + SET pipeline_version = $PipelineVersion, status = 'queued', error_code = NULL, + updated_at = clock_timestamp() + FROM candidate c, created n + WHERE a.id = c.id AND n.attachment_id = c.id + RETURNING a.id +), audited AS ( + INSERT INTO attachment_pipeline_promotions + (attachment_id, from_version, to_version, job_id, requested_by) + SELECT c.id, c.pipeline_version, $PipelineVersion, n.id, '$RequestedBy' + FROM candidate c + JOIN created n ON n.attachment_id = c.id + JOIN promoted p ON p.id = c.id + RETURNING job_id +) +SELECT COALESCE((SELECT job_id::text FROM audited), 'no-op'); +"@ + +$result = docker compose --env-file $EnvFile exec -T postgres ` + psql -v ON_ERROR_STOP=1 -U messenger -d messenger -At -c $sql +if ($LASTEXITCODE -ne 0) { + throw "Pipeline promotion transaction failed" +} + +$last = ($result | Select-Object -Last 1).Trim() +if ($last -eq "no-op") { + Write-Output "No-op: attachment is missing, already at v$PipelineVersion, or that version already exists" +} else { + Write-Output "Promoted attachment $parsedAttachmentId to pipeline v$PipelineVersion with job $last" +} diff --git a/scripts/promote-pipeline.sh b/scripts/promote-pipeline.sh new file mode 100644 index 00000000..dbed0ac8 --- /dev/null +++ b/scripts/promote-pipeline.sh @@ -0,0 +1,59 @@ +#!/bin/sh +set -eu + +attachment_id="${1:?usage: promote-pipeline.sh ATTACHMENT_UUID PIPELINE_VERSION [REQUESTED_BY] [ENV_FILE]}" +pipeline_version="${2:?pipeline version is required}" +requested_by="${3:-operator}" +env_file="${4:-.env}" + +case "$attachment_id" in + ????????-????-????-????-????????????) ;; + *) echo "AttachmentId must be a UUID" >&2; exit 2 ;; +esac +case "$pipeline_version" in + 1|2) ;; + *) echo "PipelineVersion must be 1 or 2" >&2; exit 2 ;; +esac +case "$requested_by" in + *[!A-Za-z0-9_.@-]*|'') echo "RequestedBy contains unsupported characters" >&2; exit 2 ;; +esac + +sql="WITH candidate AS ( + SELECT id, pipeline_version FROM attachments + WHERE id = '$attachment_id'::uuid AND pipeline_version < $pipeline_version FOR UPDATE +), superseded AS ( + UPDATE attachment_jobs j SET status = 'superseded', published = true, + last_error_code = 'superseded_by_v$pipeline_version', + lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp() + FROM candidate c WHERE j.attachment_id = c.id + AND j.pipeline_version < $pipeline_version AND j.status IN ('queued', 'processing') + RETURNING j.id +), created AS ( + INSERT INTO attachment_jobs + (id, attachment_id, pipeline_version, attempt, status, published, + next_attempt_at, created_at, updated_at) + SELECT gen_random_uuid(), id, $pipeline_version, 1, 'queued', false, + clock_timestamp(), clock_timestamp(), clock_timestamp() FROM candidate + ON CONFLICT (attachment_id, pipeline_version) DO NOTHING + RETURNING id, attachment_id +), promoted AS ( + UPDATE attachments a SET pipeline_version = $pipeline_version, + status = 'queued', error_code = NULL, updated_at = clock_timestamp() + FROM candidate c, created n WHERE a.id = c.id AND n.attachment_id = c.id + RETURNING a.id +), audited AS ( + INSERT INTO attachment_pipeline_promotions + (attachment_id, from_version, to_version, job_id, requested_by) + SELECT c.id, c.pipeline_version, $pipeline_version, n.id, '$requested_by' + FROM candidate c JOIN created n ON n.attachment_id = c.id + JOIN promoted p ON p.id = c.id RETURNING job_id +) +SELECT COALESCE((SELECT job_id::text FROM audited), 'no-op');" + +result="$(docker compose --env-file "$env_file" exec -T postgres \ + psql -v ON_ERROR_STOP=1 -U messenger -d messenger -At -c "$sql")" +if [ "$result" = "no-op" ]; then + echo "No-op: attachment is missing, already at v$pipeline_version, or that version already exists" +else + echo "Promoted attachment $attachment_id to pipeline v$pipeline_version with job $result" +fi diff --git a/scripts/replay-failed.ps1 b/scripts/replay-failed.ps1 index 4bd2343e..ea9c4bd5 100644 --- a/scripts/replay-failed.ps1 +++ b/scripts/replay-failed.ps1 @@ -20,6 +20,7 @@ WITH candidate AS ( JOIN attachments a ON a.id = j.attachment_id WHERE j.id = '$parsedJobId'::uuid AND j.status = 'failed' AND a.status = 'failed' + AND j.pipeline_version = a.pipeline_version FOR UPDATE OF j, a ), audited AS ( INSERT INTO attachment_job_replays (job_id, requested_by, previous_attempt) diff --git a/scripts/replay-failed.sh b/scripts/replay-failed.sh index 25fa5a1c..4bfe11bc 100644 --- a/scripts/replay-failed.sh +++ b/scripts/replay-failed.sh @@ -17,6 +17,7 @@ sql="WITH candidate AS ( SELECT j.id, j.attachment_id, j.attempt FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id WHERE j.id = '$job_id'::uuid AND j.status = 'failed' AND a.status = 'failed' + AND j.pipeline_version = a.pipeline_version FOR UPDATE OF j, a ), audited AS ( INSERT INTO attachment_job_replays (job_id, requested_by, previous_attempt) diff --git a/src/main/java/com/example/mtusi_messenger/model/AttachmentJob.java b/src/main/java/com/example/mtusi_messenger/model/AttachmentJob.java index 0708e84e..a189403c 100644 --- a/src/main/java/com/example/mtusi_messenger/model/AttachmentJob.java +++ b/src/main/java/com/example/mtusi_messenger/model/AttachmentJob.java @@ -15,19 +15,22 @@ public record AttachmentJob( @JsonProperty("created_at") Instant createdAt) { public static final int SCHEMA_VERSION = 1; - public static final int PIPELINE_VERSION = 1; + public static final int MIN_PIPELINE_VERSION = 1; + public static final int CURRENT_PIPELINE_VERSION = 2; public static final String TYPE = "attachment.process.v1"; public AttachmentJob { if (schemaVersion != SCHEMA_VERSION || !TYPE.equals(type) - || pipelineVersion < 1 || attempt < 1) { + || pipelineVersion < MIN_PIPELINE_VERSION + || pipelineVersion > CURRENT_PIPELINE_VERSION || attempt < 1) { throw new IllegalArgumentException("Unsupported attachment job message"); } } - public static AttachmentJob first(UUID jobId, UUID attachmentId, Instant createdAt) { + public static AttachmentJob first( + UUID jobId, UUID attachmentId, int pipelineVersion, Instant createdAt) { return new AttachmentJob(SCHEMA_VERSION, jobId, TYPE, attachmentId, - PIPELINE_VERSION, 1, createdAt); + pipelineVersion, 1, createdAt); } public AttachmentJob nextAttempt(int nextAttempt) { diff --git a/src/main/java/com/example/mtusi_messenger/queue/ExpiredLeaseReaper.java b/src/main/java/com/example/mtusi_messenger/queue/ExpiredLeaseReaper.java index 7672b84f..4ddeb98c 100644 --- a/src/main/java/com/example/mtusi_messenger/queue/ExpiredLeaseReaper.java +++ b/src/main/java/com/example/mtusi_messenger/queue/ExpiredLeaseReaper.java @@ -38,11 +38,13 @@ public class ExpiredLeaseReaper { try { transaction.executeWithoutResult(status -> { if (job.attempt() >= maxAttempts) { - attachments.failExpired(job.jobId(), job.attachmentId(), "retry_exhausted"); + attachments.failExpired(job.jobId(), job.attachmentId(), + job.pipelineVersion(), "retry_exhausted"); } else { int nextAttempt = job.attempt() + 1; attachments.requeueExpired( - job.jobId(), job.attachmentId(), nextAttempt, "processing_timeout", + job.jobId(), job.attachmentId(), job.pipelineVersion(), + nextAttempt, "processing_timeout", clock.instant().plus(retryPolicy.delayForAttempt(nextAttempt))); } }); diff --git a/src/main/java/com/example/mtusi_messenger/repository/AttachmentRepository.java b/src/main/java/com/example/mtusi_messenger/repository/AttachmentRepository.java index 0e0ad5fc..1253575e 100644 --- a/src/main/java/com/example/mtusi_messenger/repository/AttachmentRepository.java +++ b/src/main/java/com/example/mtusi_messenger/repository/AttachmentRepository.java @@ -21,16 +21,20 @@ public interface AttachmentRepository { boolean markPublishFaultInjected(UUID jobId); List findUnpublishedJobs(int limit); int currentAttempt(UUID jobId); - boolean claim(UUID jobId, UUID attachmentId, int attempt, UUID leaseToken, Duration leaseDuration); - boolean markQueuedForRetry(UUID jobId, UUID attachmentId, UUID leaseToken, + boolean claim(UUID jobId, UUID attachmentId, int pipelineVersion, + int attempt, UUID leaseToken, Duration leaseDuration); + boolean markBeforeEffectFaultInjected(UUID jobId, UUID leaseToken); + boolean markAfterEffectFaultInjected(UUID jobId, UUID leaseToken); + boolean markQueuedForRetry(UUID jobId, UUID attachmentId, int pipelineVersion, UUID leaseToken, int nextAttempt, String errorCode, Instant nextAttemptAt); CompletionResult markReady(UUID jobId, UUID attachmentId, UUID leaseToken, int pipelineVersion, List variants, boolean injectCrashAfterCommit); - boolean markFailed(UUID jobId, UUID attachmentId, UUID leaseToken, String errorCode); + boolean markFailed(UUID jobId, UUID attachmentId, int pipelineVersion, + UUID leaseToken, String errorCode); List findExpiredJobs(int limit); - boolean requeueExpired(UUID jobId, UUID attachmentId, int nextAttempt, + boolean requeueExpired(UUID jobId, UUID attachmentId, int pipelineVersion, int nextAttempt, String errorCode, Instant nextAttemptAt); - boolean failExpired(UUID jobId, UUID attachmentId, String errorCode); + boolean failExpired(UUID jobId, UUID attachmentId, int pipelineVersion, String errorCode); record CompletionResult(boolean completed, boolean crashAfterCommit) { } diff --git a/src/main/java/com/example/mtusi_messenger/repository/PostgresAttachmentRepository.java b/src/main/java/com/example/mtusi_messenger/repository/PostgresAttachmentRepository.java index 93794691..bcfa5313 100644 --- a/src/main/java/com/example/mtusi_messenger/repository/PostgresAttachmentRepository.java +++ b/src/main/java/com/example/mtusi_messenger/repository/PostgresAttachmentRepository.java @@ -35,11 +35,13 @@ public class PostgresAttachmentRepository implements AttachmentRepository { jdbc.update(""" INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, - sha256, object_key, staging_key, status, error_code, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', NULL, ?, ?) + sha256, object_key, staging_key, pipeline_version, + status, error_code, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', NULL, ?, ?) """, attachment.id(), attachment.chatId(), attachment.ownerId(), attachment.filename(), attachment.contentType(), attachment.sizeBytes(), attachment.sha256(), attachment.objectKey(), attachment.stagingKey(), + job.pipelineVersion(), Timestamp.from(attachment.createdAt()), Timestamp.from(attachment.updatedAt())); jdbc.update(""" INSERT INTO attachment_jobs @@ -129,7 +131,7 @@ public class PostgresAttachmentRepository implements AttachmentRepository { } @Override - public boolean claim(UUID jobId, UUID attachmentId, int attempt, + public boolean claim(UUID jobId, UUID attachmentId, int pipelineVersion, int attempt, UUID leaseToken, Duration leaseDuration) { int claimed = jdbc.update(""" UPDATE attachment_jobs @@ -138,22 +140,50 @@ public class PostgresAttachmentRepository implements AttachmentRepository { lease_until = clock_timestamp() + (? * interval '1 millisecond'), updated_at = clock_timestamp() WHERE id = ? AND attachment_id = ? + AND pipeline_version = ? AND (status = 'queued' OR (status = 'processing' AND lease_until < clock_timestamp())) - """, attempt, leaseToken, leaseDuration.toMillis(), jobId, attachmentId); + AND EXISTS ( + SELECT 1 FROM attachments a + WHERE a.id = ? AND a.pipeline_version = ? + AND a.status IN ('queued', 'processing')) + """, attempt, leaseToken, leaseDuration.toMillis(), jobId, attachmentId, + pipelineVersion, attachmentId, pipelineVersion); if (claimed == 0) { return false; } jdbc.update(""" UPDATE attachments SET status = 'processing', error_code = NULL, updated_at = clock_timestamp() - WHERE id = ? AND status NOT IN ('ready', 'failed') - """, attachmentId); + WHERE id = ? AND pipeline_version = ? + AND status IN ('queued', 'processing') + """, attachmentId, pipelineVersion); return true; } @Override - public boolean markQueuedForRetry(UUID jobId, UUID attachmentId, UUID leaseToken, + public boolean markBeforeEffectFaultInjected(UUID jobId, UUID leaseToken) { + return jdbc.update(""" + UPDATE attachment_jobs + SET before_effect_fault_injected = true, updated_at = clock_timestamp() + WHERE id = ? AND status = 'processing' AND lease_token = ? + AND before_effect_fault_injected = false + """, jobId, leaseToken) == 1; + } + + @Override + public boolean markAfterEffectFaultInjected(UUID jobId, UUID leaseToken) { + return jdbc.update(""" + UPDATE attachment_jobs + SET after_effect_fault_injected = true, updated_at = clock_timestamp() + WHERE id = ? AND status = 'processing' AND lease_token = ? + AND after_effect_fault_injected = false + """, jobId, leaseToken) == 1; + } + + @Override + public boolean markQueuedForRetry(UUID jobId, UUID attachmentId, int pipelineVersion, + UUID leaseToken, int nextAttempt, String errorCode, Instant nextAttemptAt) { int updated = jdbc.update(""" UPDATE attachment_jobs @@ -161,17 +191,18 @@ public class PostgresAttachmentRepository implements AttachmentRepository { last_error_code = ?, next_attempt_at = ?, lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp() WHERE id = ? AND attachment_id = ? AND status = 'processing' - AND lease_token = ? + AND pipeline_version = ? AND lease_token = ? """, nextAttempt, errorCode, Timestamp.from(nextAttemptAt), - jobId, attachmentId, leaseToken); + jobId, attachmentId, pipelineVersion, leaseToken); if (updated == 0) { return false; } jdbc.update(""" UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = clock_timestamp() - WHERE id = ? AND status NOT IN ('ready', 'failed') - """, attachmentId); + WHERE id = ? AND pipeline_version = ? + AND status IN ('queued', 'processing') + """, attachmentId, pipelineVersion); return true; } @@ -192,8 +223,13 @@ public class PostgresAttachmentRepository implements AttachmentRepository { result_fault_injected = result_fault_injected OR ?, updated_at = clock_timestamp() WHERE id = ? AND attachment_id = ? AND status = 'processing' - AND lease_token = ? - """, triggerCrash, jobId, attachmentId, leaseToken); + AND pipeline_version = ? AND lease_token = ? + AND EXISTS ( + SELECT 1 FROM attachments a + WHERE a.id = ? AND a.pipeline_version = ? + AND a.status = 'processing') + """, triggerCrash, jobId, attachmentId, pipelineVersion, leaseToken, + attachmentId, pipelineVersion); if (completed == 0) { return new CompletionResult(false, false); } @@ -203,13 +239,7 @@ public class PostgresAttachmentRepository implements AttachmentRepository { (attachment_id, pipeline_version, name, content_type, size_bytes, width, height, sha256, object_key, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, clock_timestamp()) - ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE SET - content_type = EXCLUDED.content_type, - size_bytes = EXCLUDED.size_bytes, - width = EXCLUDED.width, - height = EXCLUDED.height, - sha256 = EXCLUDED.sha256, - object_key = EXCLUDED.object_key + ON CONFLICT (attachment_id, pipeline_version, name) DO NOTHING """, attachmentId, pipelineVersion, variant.name(), variant.contentType(), variant.sizeBytes(), variant.width(), variant.height(), variant.sha256(), variant.objectKey()); @@ -217,29 +247,33 @@ public class PostgresAttachmentRepository implements AttachmentRepository { jdbc.update(""" UPDATE attachments SET status = 'ready', error_code = NULL, updated_at = clock_timestamp() - WHERE id = ? AND status <> 'failed' - """, attachmentId); + WHERE id = ? AND pipeline_version = ? AND status = 'processing' + """, attachmentId, pipelineVersion); return new CompletionResult(true, triggerCrash); } @Override - public boolean markFailed(UUID jobId, UUID attachmentId, UUID leaseToken, String errorCode) { + public boolean markFailed(UUID jobId, UUID attachmentId, int pipelineVersion, + UUID leaseToken, String errorCode) { int updated = jdbc.update(""" UPDATE attachment_jobs SET status = 'failed', published = true, last_error_code = ?, lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp() WHERE id = ? AND attachment_id = ? AND status = 'processing' - AND lease_token = ? - """, errorCode, jobId, attachmentId, leaseToken); + AND pipeline_version = ? AND lease_token = ? + AND EXISTS (SELECT 1 FROM attachments a + WHERE a.id = ? AND a.pipeline_version = ?) + """, errorCode, jobId, attachmentId, pipelineVersion, leaseToken, + attachmentId, pipelineVersion); if (updated == 0) { return false; } jdbc.update(""" UPDATE attachments SET status = 'failed', error_code = ?, updated_at = clock_timestamp() - WHERE id = ? AND status <> 'ready' - """, errorCode, attachmentId); + WHERE id = ? AND pipeline_version = ? AND status <> 'ready' + """, errorCode, attachmentId, pipelineVersion); return true; } @@ -255,7 +289,8 @@ public class PostgresAttachmentRepository implements AttachmentRepository { } @Override - public boolean requeueExpired(UUID jobId, UUID attachmentId, int nextAttempt, + public boolean requeueExpired(UUID jobId, UUID attachmentId, int pipelineVersion, + int nextAttempt, String errorCode, Instant nextAttemptAt) { int updated = jdbc.update(""" UPDATE attachment_jobs @@ -263,33 +298,40 @@ public class PostgresAttachmentRepository implements AttachmentRepository { last_error_code = ?, next_attempt_at = ?, lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp() WHERE id = ? AND attachment_id = ? AND status = 'processing' - AND lease_until < clock_timestamp() - """, nextAttempt, errorCode, Timestamp.from(nextAttemptAt), jobId, attachmentId); + AND pipeline_version = ? AND lease_until < clock_timestamp() + AND EXISTS (SELECT 1 FROM attachments a + WHERE a.id = ? AND a.pipeline_version = ?) + """, nextAttempt, errorCode, Timestamp.from(nextAttemptAt), jobId, attachmentId, + pipelineVersion, attachmentId, pipelineVersion); if (updated == 1) { jdbc.update(""" UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = clock_timestamp() - WHERE id = ? AND status = 'processing' - """, attachmentId); + WHERE id = ? AND pipeline_version = ? AND status = 'processing' + """, attachmentId, pipelineVersion); } return updated == 1; } @Override - public boolean failExpired(UUID jobId, UUID attachmentId, String errorCode) { + public boolean failExpired(UUID jobId, UUID attachmentId, int pipelineVersion, + String errorCode) { int updated = jdbc.update(""" UPDATE attachment_jobs SET status = 'failed', published = true, last_error_code = ?, lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp() WHERE id = ? AND attachment_id = ? AND status = 'processing' - AND lease_until < clock_timestamp() - """, errorCode, jobId, attachmentId); + AND pipeline_version = ? AND lease_until < clock_timestamp() + AND EXISTS (SELECT 1 FROM attachments a + WHERE a.id = ? AND a.pipeline_version = ?) + """, errorCode, jobId, attachmentId, pipelineVersion, + attachmentId, pipelineVersion); if (updated == 1) { jdbc.update(""" UPDATE attachments SET status = 'failed', error_code = ?, updated_at = clock_timestamp() - WHERE id = ? AND status <> 'ready' - """, errorCode, attachmentId); + WHERE id = ? AND pipeline_version = ? AND status <> 'ready' + """, errorCode, attachmentId, pipelineVersion); } return updated == 1; } @@ -317,12 +359,14 @@ public class PostgresAttachmentRepository implements AttachmentRepository { return jdbc.query(""" SELECT name, content_type, size_bytes, width, height, sha256, object_key FROM attachment_variants - WHERE attachment_id = ? AND pipeline_version = 1 + WHERE attachment_id = ? + AND pipeline_version = ( + SELECT pipeline_version FROM attachments WHERE id = ?) ORDER BY name """, (rs, rowNum) -> new AttachmentVariant( rs.getString("name"), rs.getString("content_type"), rs.getLong("size_bytes"), rs.getInt("width"), rs.getInt("height"), rs.getString("sha256"), - rs.getString("object_key")), attachmentId); + rs.getString("object_key")), attachmentId, attachmentId); } private static AttachmentJob mapJob(ResultSet rs) throws SQLException { diff --git a/src/main/java/com/example/mtusi_messenger/service/AttachmentService.java b/src/main/java/com/example/mtusi_messenger/service/AttachmentService.java index 56d7bf63..cff26173 100644 --- a/src/main/java/com/example/mtusi_messenger/service/AttachmentService.java +++ b/src/main/java/com/example/mtusi_messenger/service/AttachmentService.java @@ -44,6 +44,7 @@ public class AttachmentService { private final Semaphore uploadPermits; private final long uploadPermitWaitMillis; private final boolean injectCrashAfterOutboxCommit; + private final int pipelineVersion; public AttachmentService( AttachmentRepository attachments, @@ -55,7 +56,8 @@ public class AttachmentService { @Value("${messenger.attachments.max-image-pixels:40000000}") long maxImagePixels, @Value("${messenger.attachments.max-concurrent-uploads:3}") int maxConcurrentUploads, @Value("${messenger.attachments.upload-permit-wait-millis:10000}") long uploadPermitWaitMillis, - @Value("${messenger.jobs.fault-crash-after-outbox-commit:false}") boolean injectCrashAfterOutboxCommit + @Value("${messenger.jobs.fault-crash-after-outbox-commit:false}") boolean injectCrashAfterOutboxCommit, + @Value("${messenger.jobs.pipeline-version:2}") int pipelineVersion ) { this.attachments = attachments; this.chats = chats; @@ -70,6 +72,11 @@ public class AttachmentService { this.uploadPermits = new Semaphore(maxConcurrentUploads, true); this.uploadPermitWaitMillis = uploadPermitWaitMillis; this.injectCrashAfterOutboxCommit = injectCrashAfterOutboxCommit; + if (pipelineVersion < AttachmentJob.MIN_PIPELINE_VERSION + || pipelineVersion > AttachmentJob.CURRENT_PIPELINE_VERSION) { + throw new IllegalArgumentException("Unsupported attachment pipeline version"); + } + this.pipelineVersion = pipelineVersion; } public Attachment upload(UUID chatId, @@ -119,7 +126,7 @@ public class AttachmentService { String objectKey = "attachments/" + id + "/original"; String stagingKey = "staging/" + id + "/original"; Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS); - AttachmentJob job = AttachmentJob.first(UUID.randomUUID(), id, now); + AttachmentJob job = AttachmentJob.first(UUID.randomUUID(), id, pipelineVersion, now); Attachment attachment = new Attachment(id, chatId, ownerId, safeFilename, contentType, bytes.length, sha256(bytes), objectKey, stagingKey, "queued", List.of(), null, now, now); diff --git a/src/main/java/com/example/mtusi_messenger/service/ReadinessService.java b/src/main/java/com/example/mtusi_messenger/service/ReadinessService.java index 8e18b949..3b14c4b0 100644 --- a/src/main/java/com/example/mtusi_messenger/service/ReadinessService.java +++ b/src/main/java/com/example/mtusi_messenger/service/ReadinessService.java @@ -45,9 +45,13 @@ public class ReadinessService { } try { - // The schema-level probe also proves that the separate lab4 migration - // completed before this replica is allowed to serve business traffic. - jdbc.queryForObject("SELECT count(*) FROM attachments", Long.class); + // The schema-level probe proves that both the shared idempotency + // schema (lab3) and the attachment schema (lab4/lab5) completed + // before this replica is allowed to serve business traffic. + jdbc.queryForObject(""" + SELECT (SELECT count(*) FROM message_idempotency) + + (SELECT count(*) FROM attachments) + """, Long.class); markDependenciesAvailable(); return true; } catch (DataAccessException e) { diff --git a/src/main/java/com/example/mtusi_messenger/worker/AttachmentWorker.java b/src/main/java/com/example/mtusi_messenger/worker/AttachmentWorker.java index 571e475f..e7c8d48a 100644 --- a/src/main/java/com/example/mtusi_messenger/worker/AttachmentWorker.java +++ b/src/main/java/com/example/mtusi_messenger/worker/AttachmentWorker.java @@ -6,6 +6,7 @@ import com.example.mtusi_messenger.model.AttachmentVariant; import com.example.mtusi_messenger.queue.RetryPolicy; import com.example.mtusi_messenger.repository.AttachmentRepository; import com.example.mtusi_messenger.storage.ObjectStorage; +import com.example.mtusi_messenger.storage.ObjectStorageException; import com.fasterxml.jackson.databind.ObjectMapper; import com.rabbitmq.client.Channel; import jakarta.annotation.PreDestroy; @@ -47,6 +48,8 @@ public class AttachmentWorker { private final int maxAttempts; private final Duration jobTimeout; private final Duration leaseDuration; + private final boolean injectCrashBeforeSideEffect; + private final boolean injectCrashAfterSideEffect; private final boolean injectCrashAfterResultCommit; private final ExecutorService processingPool; private final Clock clock = Clock.systemUTC(); @@ -61,6 +64,8 @@ public class AttachmentWorker { @Value("${messenger.jobs.max-attempts:5}") int maxAttempts, @Value("${messenger.jobs.timeout:60s}") Duration jobTimeout, @Value("${messenger.jobs.lease-duration:90s}") Duration leaseDuration, + @Value("${messenger.jobs.fault-crash-before-side-effect:false}") boolean injectCrashBeforeSideEffect, + @Value("${messenger.jobs.fault-crash-after-side-effect:false}") boolean injectCrashAfterSideEffect, @Value("${messenger.jobs.fault-crash-after-result-commit:false}") boolean injectCrashAfterResultCommit, @Value("${spring.rabbitmq.listener.simple.concurrency:2}") int concurrency) { if (maxAttempts < 1 || jobTimeout.isZero() || jobTimeout.isNegative() @@ -76,6 +81,8 @@ public class AttachmentWorker { this.maxAttempts = maxAttempts; this.jobTimeout = jobTimeout; this.leaseDuration = leaseDuration; + this.injectCrashBeforeSideEffect = injectCrashBeforeSideEffect; + this.injectCrashAfterSideEffect = injectCrashAfterSideEffect; this.injectCrashAfterResultCommit = injectCrashAfterResultCommit; this.processingPool = Executors.newFixedThreadPool(concurrency, Thread.ofPlatform().name("attachment-image-", 0).factory()); @@ -103,7 +110,8 @@ public class AttachmentWorker { int attempt = Math.max(job.attempt(), attachments.currentAttempt(job.jobId())); UUID leaseToken = UUID.randomUUID(); boolean claimed = Boolean.TRUE.equals(transaction.execute(status -> - attachments.claim(job.jobId(), job.attachmentId(), attempt, leaseToken, leaseDuration))); + attachments.claim(job.jobId(), job.attachmentId(), job.pipelineVersion(), + attempt, leaseToken, leaseDuration))); if (!claimed) { // A live worker owns the lease, or a terminal state won the race. // If the owner died, the DB lease reaper will create a new outbox delivery. @@ -140,17 +148,23 @@ public class AttachmentWorker { } private ProcessOutcome process(AttachmentJob job, UUID leaseToken) { + if (injectCrashBeforeSideEffect + && attachments.markBeforeEffectFaultInjected(job.jobId(), leaseToken)) { + log.error("Fault injection: halting worker before object-storage side effect"); + Runtime.getRuntime().halt(84); + } Attachment attachment = attachments.findById(job.attachmentId()) .orElseThrow(() -> new ImageVariantProcessor.ProcessingException( "attachment_missing", true, "Attachment metadata is missing", null)); - byte[] original = storage.get(attachment.stagingKey()); + byte[] original = loadOriginal(attachment); if (original.length != attachment.sizeBytes() || !sha256(original).equals(attachment.sha256())) { throw new ImageVariantProcessor.ProcessingException( "invalid_image", true, "Staging checksum mismatch", null); } storage.put(attachment.objectKey(), original, attachment.contentType()); - List generated = images.createVariants(original); + List generated = + images.createVariants(original, job.pipelineVersion()); List variants = new ArrayList<>(generated.size()); for (ImageVariantProcessor.GeneratedVariant item : generated) { String objectKey = "attachments/" + attachment.id() + "/" @@ -161,6 +175,12 @@ public class AttachmentWorker { item.width(), item.height(), sha256(item.bytes()), objectKey)); } + if (injectCrashAfterSideEffect + && attachments.markAfterEffectFaultInjected(job.jobId(), leaseToken)) { + log.error("Fault injection: halting worker after object-storage side effect before result commit"); + Runtime.getRuntime().halt(85); + } + AttachmentRepository.CompletionResult completion = transaction.execute(status -> attachments.markReady(job.jobId(), job.attachmentId(), leaseToken, job.pipelineVersion(), variants, injectCrashAfterResultCommit)); @@ -175,11 +195,27 @@ public class AttachmentWorker { return new ProcessOutcome(completion.crashAfterCommit()); } + private byte[] loadOriginal(Attachment attachment) { + try { + return storage.get(attachment.stagingKey()); + } catch (ObjectStorageException missingStaging) { + try { + // A pipeline promotion reuses the immutable final original after + // the previous version safely removed its staging object. + return storage.get(attachment.objectKey()); + } catch (ObjectStorageException missingOriginal) { + missingOriginal.addSuppressed(missingStaging); + throw missingOriginal; + } + } + } + private void failPermanent( AttachmentJob job, UUID leaseToken, String errorCode, long deliveryTag, Channel channel) throws IOException { boolean failed = Boolean.TRUE.equals(transaction.execute(status -> - attachments.markFailed(job.jobId(), job.attachmentId(), leaseToken, errorCode))); + attachments.markFailed(job.jobId(), job.attachmentId(), job.pipelineVersion(), + leaseToken, errorCode))); if (failed) { channel.basicReject(deliveryTag, false); } else { @@ -193,8 +229,8 @@ public class AttachmentWorker { try { if (attempt >= maxAttempts) { boolean failed = Boolean.TRUE.equals(transaction.execute(status -> - attachments.markFailed(job.jobId(), job.attachmentId(), leaseToken, - "retry_exhausted"))); + attachments.markFailed(job.jobId(), job.attachmentId(), + job.pipelineVersion(), leaseToken, "retry_exhausted"))); if (failed) { log.error("Attachment job {} exhausted {} attempts: {}", job.jobId(), attempt, errorCode); @@ -208,7 +244,8 @@ public class AttachmentWorker { int nextAttempt = attempt + 1; boolean queued = Boolean.TRUE.equals(transaction.execute(status -> attachments.markQueuedForRetry( - job.jobId(), job.attachmentId(), leaseToken, nextAttempt, errorCode, + job.jobId(), job.attachmentId(), job.pipelineVersion(), + leaseToken, nextAttempt, errorCode, clock.instant().plus(retryPolicy.delayForAttempt(nextAttempt))))); // The DB outbox is now the durable retry carrier; the current broker // delivery can be acknowledged without a DB/broker dual write. diff --git a/src/main/java/com/example/mtusi_messenger/worker/ImageVariantProcessor.java b/src/main/java/com/example/mtusi_messenger/worker/ImageVariantProcessor.java index cb077cae..f7e9faf9 100644 --- a/src/main/java/com/example/mtusi_messenger/worker/ImageVariantProcessor.java +++ b/src/main/java/com/example/mtusi_messenger/worker/ImageVariantProcessor.java @@ -45,7 +45,8 @@ public class ImageVariantProcessor { this.memoryWait = memoryWait; } - public List createVariants(byte[] original) { + public List createVariants(byte[] original, int pipelineVersion) { + PipelineProfile profile = PipelineProfile.forVersion(pipelineVersion); ImageInfo info = inspect(original); long estimatedBytes; try { @@ -70,7 +71,7 @@ public class ImageVariantProcessor { } try { - return transform(original); + return transform(original, profile); } finally { memoryPermits.release(permits); } @@ -106,7 +107,7 @@ public class ImageVariantProcessor { } } - private List transform(byte[] original) { + private List transform(byte[] original, PipelineProfile profile) { try { BufferedImage oriented = Thumbnails.of(new ByteArrayInputStream(original)) .useExifOrientation(true) @@ -118,17 +119,20 @@ public class ImageVariantProcessor { try { List variants = new ArrayList<>(3); BufferedImage thumbnail = fit(oriented, 256, BufferedImage.TYPE_INT_RGB, true); - variants.add(encode("thumbnail", "image/jpeg", "jpg", thumbnail, "jpeg", 0.85f)); + variants.add(encode("thumbnail", "image/jpeg", "jpg", thumbnail, "jpeg", + profile.thumbnailQuality())); thumbnail.flush(); BufferedImage crop = cropSquare(oriented, 128); - variants.add(encode("crop", "image/jpeg", "jpg", crop, "jpeg", 0.88f)); + variants.add(encode("crop", "image/jpeg", "jpg", crop, "jpeg", + profile.cropQuality())); crop.flush(); int webpType = oriented.getColorModel().hasAlpha() ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB; BufferedImage optimized = fit(oriented, 1280, webpType, !oriented.getColorModel().hasAlpha()); - variants.add(encode("optimized", "image/webp", "webp", optimized, "webp", 0.82f)); + variants.add(encode("optimized", "image/webp", "webp", optimized, "webp", + profile.webpQuality())); optimized.flush(); return List.copyOf(variants); } finally { @@ -228,6 +232,18 @@ public class ImageVariantProcessor { private record ImageInfo(int width, int height, long pixels) { } + private record PipelineProfile( + int version, float thumbnailQuality, float cropQuality, float webpQuality) { + private static PipelineProfile forVersion(int version) { + return switch (version) { + case 1 -> new PipelineProfile(1, 0.85f, 0.88f, 0.82f); + case 2 -> new PipelineProfile(2, 0.87f, 0.90f, 0.84f); + default -> throw permanent( + "unsupported_pipeline", "Unsupported pipeline version " + version, null); + }; + } + } + public record GeneratedVariant(String name, String contentType, String extension, byte[] bytes, int width, int height) { } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 10f92def..b9e1ab64 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -95,6 +95,7 @@ messenger: reconcile-interval-millis: ${ATTACHMENT_RECONCILE_INTERVAL_MILLIS:600000} reconcile-initial-delay-millis: ${ATTACHMENT_RECONCILE_INITIAL_DELAY_MILLIS:60000} jobs: + pipeline-version: ${ATTACHMENT_PIPELINE_VERSION:2} exchange: ${ATTACHMENT_JOB_EXCHANGE:attachments.v1} queue: ${ATTACHMENT_JOB_QUEUE:attachments.process.level4.v1} routing-key: ${ATTACHMENT_JOB_ROUTING_KEY:attachment.process.v1} @@ -113,4 +114,6 @@ messenger: publish-confirm-timeout: ${JOB_PUBLISH_CONFIRM_TIMEOUT:5s} republish-interval: ${JOB_REPUBLISH_INTERVAL:5s} fault-crash-after-outbox-commit: ${FAULT_CRASH_AFTER_OUTBOX_COMMIT:false} + fault-crash-before-side-effect: ${FAULT_CRASH_BEFORE_SIDE_EFFECT:false} + fault-crash-after-side-effect: ${FAULT_CRASH_AFTER_SIDE_EFFECT:false} fault-crash-after-result-commit: ${FAULT_CRASH_AFTER_RESULT_COMMIT:false} diff --git a/src/main/resources/db/migration/V7__versioned_pipeline_and_fault_points.sql b/src/main/resources/db/migration/V7__versioned_pipeline_and_fault_points.sql new file mode 100644 index 00000000..dd50c74f --- /dev/null +++ b/src/main/resources/db/migration/V7__versioned_pipeline_and_fault_points.sql @@ -0,0 +1,33 @@ +ALTER TABLE attachments + ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1, + ADD CONSTRAINT attachments_pipeline_version_chk CHECK (pipeline_version > 0); + +ALTER TABLE attachment_jobs + DROP CONSTRAINT attachment_jobs_attachment_id_key, + DROP CONSTRAINT attachment_jobs_status_chk, + ADD COLUMN before_effect_fault_injected boolean NOT NULL DEFAULT false, + ADD COLUMN after_effect_fault_injected boolean NOT NULL DEFAULT false, + ADD CONSTRAINT attachment_jobs_status_chk + CHECK (status IN ('queued', 'processing', 'ready', 'failed', 'superseded')); + +CREATE UNIQUE INDEX attachment_jobs_attachment_pipeline_uk + ON attachment_jobs (attachment_id, pipeline_version); + +CREATE TABLE attachment_pipeline_promotions ( + id bigserial PRIMARY KEY, + attachment_id uuid NOT NULL REFERENCES attachments(id) ON DELETE RESTRICT, + from_version integer NOT NULL, + to_version integer NOT NULL, + job_id uuid NOT NULL REFERENCES attachment_jobs(id) ON DELETE RESTRICT, + requested_by varchar(128) NOT NULL, + requested_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT attachment_pipeline_promotions_versions_chk + CHECK (from_version > 0 AND to_version > from_version), + CONSTRAINT attachment_pipeline_promotions_actor_chk + CHECK (char_length(requested_by) BETWEEN 1 AND 128), + CONSTRAINT attachment_pipeline_promotions_target_uk + UNIQUE (attachment_id, to_version) +); + +CREATE INDEX attachment_pipeline_promotions_attachment_idx + ON attachment_pipeline_promotions (attachment_id, requested_at); diff --git a/src/test/java/com/example/mtusi_messenger/service/AttachmentServiceTest.java b/src/test/java/com/example/mtusi_messenger/service/AttachmentServiceTest.java index eb84fee2..5df23c69 100644 --- a/src/test/java/com/example/mtusi_messenger/service/AttachmentServiceTest.java +++ b/src/test/java/com/example/mtusi_messenger/service/AttachmentServiceTest.java @@ -55,7 +55,7 @@ class AttachmentServiceTest { new Chat(chatId, "test", List.of(ownerId), Instant.now())); when(repository.saveQueued(any(), any())).thenAnswer(invocation -> invocation.getArgument(0)); service = new AttachmentService(repository, chats, storage, publisher, transaction, - 10_485_760, 40_000_000, 3, 10_000, false); + 10_485_760, 40_000_000, 3, 10_000, false, 2); png = Files.readAllBytes(Path.of("tests", "fixtures", "sample.png")); } @@ -73,7 +73,7 @@ class AttachmentServiceTest { assertFalse(attachment.objectKey().contains("photo.png")); assertArrayEquals(png, storage.objects.get(attachment.stagingKey())); assertFalse(storage.objects.containsKey(attachment.objectKey())); - verify(repository).saveQueued(eq(attachment), any()); + verify(repository).saveQueued(eq(attachment), argThat(job -> job.pipelineVersion() == 2)); verify(publisher).publish(any()); } diff --git a/src/test/java/com/example/mtusi_messenger/worker/ImageVariantProcessorTest.java b/src/test/java/com/example/mtusi_messenger/worker/ImageVariantProcessorTest.java index 11c56b5a..9601467b 100644 --- a/src/test/java/com/example/mtusi_messenger/worker/ImageVariantProcessorTest.java +++ b/src/test/java/com/example/mtusi_messenger/worker/ImageVariantProcessorTest.java @@ -9,10 +9,12 @@ import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; import java.util.Map; +import java.util.Arrays; import java.util.function.Function; import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -30,7 +32,7 @@ class ImageVariantProcessorTest { 40_000_000, 512L * 1024 * 1024, Duration.ofSeconds(1)); Map variants = processor - .createVariants(original).stream() + .createVariants(original, 2).stream() .collect(Collectors.toMap(ImageVariantProcessor.GeneratedVariant::name, Function.identity())); @@ -49,12 +51,34 @@ class ImageVariantProcessorTest { 40_000_000, 1L * 1024 * 1024, Duration.ofSeconds(1)); var error = assertThrows(ImageVariantProcessor.ProcessingException.class, - () -> processor.createVariants(original)); + () -> processor.createVariants(original, 2)); assertTrue(error.permanent()); assertEquals("image_too_large", error.errorCode()); } + @Test + void versionsProduceSeparateDeterministicProfiles() { + ImageVariantProcessor processor = new ImageVariantProcessor( + 40_000_000, 512L * 1024 * 1024, Duration.ofSeconds(1)); + + Map version1 = processor + .createVariants(original, 1).stream() + .collect(Collectors.toMap(ImageVariantProcessor.GeneratedVariant::name, + Function.identity())); + Map version2 = processor + .createVariants(original, 2).stream() + .collect(Collectors.toMap(ImageVariantProcessor.GeneratedVariant::name, + Function.identity())); + + assertFalse(Arrays.equals(version1.get("optimized").bytes(), + version2.get("optimized").bytes())); + assertTrue(Arrays.equals(version2.get("optimized").bytes(), + processor.createVariants(original, 2).stream() + .filter(item -> item.name().equals("optimized")) + .findFirst().orElseThrow().bytes())); + } + private static void assertImage( ImageVariantProcessor.GeneratedVariant variant, String contentType, int width, int height) throws Exception { diff --git a/student_tests/README.md b/student_tests/README.md index 7b14c1ae..0bd7b296 100644 --- a/student_tests/README.md +++ b/student_tests/README.md @@ -15,10 +15,15 @@ The course-provided black-box suite remains in `tests/`; Spring tests remain in - `lab4_negative.py` — oversized/corrupt/MIME-spoofed uploads, unsafe filename, unknown attachment, foreign user and cross-chat binding; every user error is 4xx. - `concurrent_upload_memory.py` — 12 simultaneous ~6.5 MiB valid PNG uploads and - aggregate API container memory sampling through `docker stats`. + aggregate API container memory sampling through `docker stats` (lab5 `202` + upload contract). - `lab5_worker_recovery.py` — durable worker stop/restart, all three variants and idempotent duplicate delivery. - `lab5_fault_injection.py` — crashes after outbox commit and after result commit but before consumer acknowledgement. - `lab5_dlq_replay_lease.py` — permanent failure DLQ routing, guarded audited replay, and expired processing-lease recovery. +- `lab5_pipeline_idempotency.py` — versioned pipeline v1/v2, audited promotion, + `superseded` fencing, duplicate/reordered/stale deliveries, and crashes before + and after the S3 side effect. The script prints invariant checks and a final + `PASS` line; it uses `.env.example` for the disposable test stand by default. diff --git a/student_tests/concurrent_upload_memory.py b/student_tests/concurrent_upload_memory.py index a268da4d..ad17b230 100644 --- a/student_tests/concurrent_upload_memory.py +++ b/student_tests/concurrent_upload_memory.py @@ -104,7 +104,7 @@ def main(): barrier.wait(timeout=30) path = (f"/api/v1/chats/{chat['id']}/attachments" f"?filename=memory-{index}.png") - return client.call('POST', path, 201, actor=alice, raw=payload, + return client.call('POST', path, 202, actor=alice, raw=payload, headers={'Content-Type': 'image/png'}, schema='Attachment')['json']['id'] monitor_thread = threading.Thread(target=monitor, daemon=True) diff --git a/student_tests/lab5_pipeline_idempotency.py b/student_tests/lab5_pipeline_idempotency.py new file mode 100644 index 00000000..75325248 --- /dev/null +++ b/student_tests/lab5_pipeline_idempotency.py @@ -0,0 +1,314 @@ +#!/usr/bin/env python3 +"""Prove version fencing and idempotent convergence under duplicate/crash faults.""" + +import json +import os +from pathlib import Path +import subprocess +import sys +import time + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) + +from client import Client, Failure, check, run # noqa: E402 + +COMPOSE = ["docker", "compose", "--env-file", ".env.example"] +FAULTS = ( + "FAULT_CRASH_AFTER_OUTBOX_COMMIT", + "FAULT_CRASH_BEFORE_SIDE_EFFECT", + "FAULT_CRASH_AFTER_SIDE_EFFECT", + "FAULT_CRASH_AFTER_RESULT_COMMIT", +) + + +def command(*args, capture=False, environment=None, check_result=True): + result = subprocess.run( + [*COMPOSE, *args], cwd=ROOT, text=True, capture_output=capture, + env=environment, check=check_result) + return result.stdout.strip() if capture else "" + + +def database_scalar(sql): + return command( + "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", + "-At", "-c", sql, capture=True) + + +def env_value(name): + for line in (ROOT / ".env.example").read_text(encoding="utf-8").splitlines(): + if line.startswith(name + "="): + return line.split("=", 1)[1] + raise Failure("missing " + name + " in .env.example") + + +def compose_environment(**overrides): + environment = os.environ.copy() + for name in FAULTS: + environment[name] = "false" + environment.update({name: str(value) for name, value in overrides.items()}) + return environment + + +def recreate(service, **overrides): + command( + "up", "-d", "--no-deps", "--force-recreate", service, + environment=compose_environment(**overrides)) + + +def wait_http(client, seconds=120): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + try: + client.call("GET", "/health/ready", schema="Health") + return + except Failure: + time.sleep(1) + raise Failure("API did not become ready") + + +def wait_database(sql, expected, seconds=120): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + if database_scalar(sql) == expected: + return + time.sleep(0.5) + raise Failure("database condition did not become " + expected + ": " + sql) + + +def job_row(attachment_id, version): + row = database_scalar( + "SELECT id || '|' || attempt || '|' || " + "to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') " + "FROM attachment_jobs WHERE attachment_id='" + attachment_id + + "' AND pipeline_version=" + str(version) + ";") + check(bool(row), "pipeline job is missing") + return row.split("|") + + +def publish(attachment_id, version): + job_id, attempt, created_at = job_row(attachment_id, version) + payload = json.dumps({ + "schema_version": 1, + "job_id": job_id, + "type": "attachment.process.v1", + "attachment_id": attachment_id, + "pipeline_version": version, + "attempt": int(attempt), + "created_at": created_at, + }, separators=(",", ":")) + command( + "exec", "-T", "rabbitmq", "rabbitmqadmin", + "-u", env_value("RABBITMQ_USER"), "-p", env_value("RABBITMQ_PASSWORD"), + "publish", "exchange=" + env_value("ATTACHMENT_JOB_EXCHANGE"), + "routing_key=" + env_value("ATTACHMENT_JOB_ROUTING_KEY"), + "payload=" + payload, + 'properties={"delivery_mode":2,"content_type":"application/json"}') + + +def promote(attachment_id, version): + subprocess.run( + ["powershell", "-NoProfile", "-File", str(ROOT / "scripts" / "promote-pipeline.ps1"), + "-AttachmentId", attachment_id, "-PipelineVersion", str(version), + "-RequestedBy", "idempotency-test", "-EnvFile", ".env.example"], + cwd=ROOT, check=True, text=True) + + +def variant_snapshot(attachment_id, version): + return database_scalar( + "SELECT string_agg(name || ':' || sha256 || ':' || object_key, ',' ORDER BY name) " + "FROM attachment_variants WHERE attachment_id='" + attachment_id + + "' AND pipeline_version=" + str(version) + ";") + + +def job_status(attachment_id, version): + return database_scalar( + "SELECT status || '|' || published || '|' || coalesce(last_error_code, '') " + "FROM attachment_jobs WHERE attachment_id='" + attachment_id + + "' AND pipeline_version=" + str(version) + ";") + + +def variant_count(attachment_id, version): + return database_scalar( + "SELECT count(*) FROM attachment_variants WHERE attachment_id='" + + attachment_id + "' AND pipeline_version=" + str(version) + ";") + + +def object_count(attachment_id): + script = ( + 'mc alias set local http://minio:9000 "$MINIO_ROOT_USER" ' + '"$MINIO_ROOT_PASSWORD" >/dev/null && ' + 'mc ls --recursive "local/$S3_BUCKET/attachments/' + attachment_id + + '/" 2>/dev/null | wc -l') + output = command( + "run", "--rm", "--no-deps", "--entrypoint", "/bin/sh", + "minio-init", "-c", script, capture=True) + return int(output.splitlines()[-1]) + + +def wait_marker(attachment_id, column, seconds=60): + wait_database( + "SELECT " + column + "::text FROM attachment_jobs WHERE attachment_id='" + + attachment_id + "' ORDER BY pipeline_version DESC LIMIT 1;", "true", seconds) + + +def wait_queue_empty(seconds=150): + deadline = time.monotonic() + seconds + marker = env_value("ATTACHMENT_JOB_QUEUE") + "\t0\t0" + while time.monotonic() < deadline: + listing = command( + "exec", "-T", "rabbitmq", "rabbitmqctl", "list_queues", + "name", "messages_ready", "messages_unacknowledged", capture=True) + if marker in listing: + return + time.sleep(0.5) + raise Failure("main queue did not drain") + + +def wait_worker_consumer(seconds=150): + deadline = time.monotonic() + seconds + queue = env_value("ATTACHMENT_JOB_QUEUE") + while time.monotonic() < deadline: + listing = command( + "exec", "-T", "rabbitmq", "rabbitmqctl", "list_queues", + "name", "consumers", capture=True) + for line in listing.splitlines(): + columns = line.split("\t") + if len(columns) == 2 and columns[0] == queue and int(columns[1]) > 0: + return + time.sleep(1) + raise Failure("worker did not register a RabbitMQ consumer") + + +def assert_ready_invariants(attachment_id, expected_version): + row = database_scalar( + "SELECT pipeline_version || '|' || status FROM attachments WHERE id='" + + attachment_id + "';") + check(row == str(expected_version) + "|ready", "active pipeline is not ready") + check(database_scalar( + "SELECT count(*) FROM attachment_variants WHERE attachment_id='" + attachment_id + + "' AND pipeline_version=" + str(expected_version) + ";") == "3", + "active pipeline does not have exactly three variants") + check(database_scalar( + "SELECT count(*) FROM attachment_jobs WHERE attachment_id='" + attachment_id + + "' AND status IN ('queued','processing');") == "0", + "acknowledged attachment still has non-terminal work") + + +def fault_case(client, alice, bob, chat, flag, marker, expected_objects_before_commit): + recreate( + "worker", **{flag: "true", "JOB_TIMEOUT": "5s", "JOB_LEASE_DURATION": "8s"}) + wait_worker_consumer() + attachment, _ = client.attachment(alice, chat) + wait_marker(attachment["id"], marker, seconds=150) + check(database_scalar( + "SELECT count(*) FROM attachment_variants WHERE attachment_id='" + + attachment["id"] + "';") == "0", + "result metadata committed before the injected pre-commit crash") + check(object_count(attachment["id"]) == expected_objects_before_commit, + "unexpected object count at injected fault point") + ready = client.wait_ready(bob, attachment, wait_seconds=150) + check(ready["status"] == "ready", "faulted job was lost") + assert_ready_invariants(attachment["id"], 2) + check(int(database_scalar( + "SELECT attempt FROM attachment_jobs WHERE attachment_id='" + + attachment["id"] + "' AND pipeline_version=2;")) >= 2, + "crashed job was not recovered through a later managed attempt") + check(object_count(attachment["id"]) == 4, + "idempotent retry did not converge to one deterministic object set") + recreate("worker") + return attachment["id"] + + +def main(): + client = Client("http://localhost:8080") + recreate("api", ATTACHMENT_PIPELINE_VERSION="1") + wait_http(client) + alice, bob, _, chat = client.bootstrap() + + # Complete v1, promote to v2, then deliver newer work before stale v1 and + # duplicate v2 messages. Arrival order intentionally differs from creation order. + versioned, _ = client.attachment(alice, chat) + client.wait_ready(bob, versioned, wait_seconds=120) + version1 = variant_snapshot(versioned["id"], 1) + check(bool(version1), "v1 result is missing") + command("stop", "worker") + promote(versioned["id"], 2) + publish(versioned["id"], 2) + publish(versioned["id"], 2) + publish(versioned["id"], 1) + command("up", "-d", "--no-deps", "worker") + client.wait_ready(bob, versioned, wait_seconds=120) + wait_queue_empty() + version2 = variant_snapshot(versioned["id"], 2) + check(bool(version2) and version2 != version1, + "v2 did not produce a distinct immutable versioned result") + check(database_scalar( + "SELECT count(*) FROM attachment_variants WHERE attachment_id='" + + versioned["id"] + "';") == "6", "versioned rows were lost or duplicated") + stable = version2 + publish(versioned["id"], 1) + publish(versioned["id"], 2) + wait_queue_empty() + check(variant_snapshot(versioned["id"], 2) == stable, + "stale or duplicate delivery overwrote the active v2 result") + assert_ready_invariants(versioned["id"], 2) + + # Promote a still-queued v1 intent to v2. The old job must become + # superseded, and its already-durable message must be a harmless no-op. + command("stop", "worker") + superseded, _ = client.attachment(alice, chat) + check(job_status(superseded["id"], 1).startswith("queued|"), + "new upload did not start as a queued v1 job") + promote(superseded["id"], 2) + check(job_status(superseded["id"], 1) == "superseded|true|superseded_by_v2", + "queued v1 job was not fenced as superseded by v2") + check(variant_count(superseded["id"], 1) == "0", + "superseded job already has v1 result rows") + publish(superseded["id"], 1) + command("up", "-d", "--no-deps", "worker") + client.wait_ready(bob, superseded, wait_seconds=120) + wait_queue_empty() + check(variant_count(superseded["id"], 1) == "0", + "stale superseded v1 delivery created v1 result rows") + check(variant_count(superseded["id"], 2) == "3", + "promoted v2 job did not produce exactly three variants") + assert_ready_invariants(superseded["id"], 2) + + recreate("api", ATTACHMENT_PIPELINE_VERSION="2") + wait_http(client) + before_id = fault_case( + client, alice, bob, chat, "FAULT_CRASH_BEFORE_SIDE_EFFECT", + "before_effect_fault_injected", 0) + after_id = fault_case( + client, alice, bob, chat, "FAULT_CRASH_AFTER_SIDE_EFFECT", + "after_effect_fault_injected", 4) + + # Existing level-4 fault point proves redelivery after result COMMIT but before ack. + recreate("worker", FAULT_CRASH_AFTER_RESULT_COMMIT="true") + wait_worker_consumer() + committed, _ = client.attachment(alice, chat) + wait_marker(committed["id"], "result_fault_injected") + client.wait_ready(bob, committed, wait_seconds=120) + wait_queue_empty() + assert_ready_invariants(committed["id"], 2) + recreate("worker") + + confirmed = database_scalar( + "SELECT count(*) FROM attachments WHERE id IN ('" + versioned["id"] + "','" + + superseded["id"] + "','" + before_id + "','" + after_id + "','" + + committed["id"] + "') AND status='ready';") + check(confirmed == "5", "a confirmed task was lost") + print("PASS: version fencing, superseded, duplicate/reorder and " + "pre/post-side-effect crashes") + + +if __name__ == "__main__": + try: + run(main) + finally: + try: + recreate("api", ATTACHMENT_PIPELINE_VERSION="2") + recreate("worker") + except Exception: + pass -- 2.54.0