forked from mtusi2026/mtusi2026lab4
4682 lines
175 KiB
Plaintext
4682 lines
175 KiB
Plaintext
|
||
|
||
===== java/src/main/java/com/vnp/demo/GlobalExceptionHandler.java =====
|
||
|
||
|
||
package com.vnp.demo;
|
||
|
||
import org.slf4j.MDC;
|
||
import org.springframework.dao.DataAccessException;
|
||
import org.springframework.http.HttpStatus;
|
||
import org.springframework.http.ResponseEntity;
|
||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||
import org.springframework.web.bind.MissingRequestHeaderException;
|
||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||
import org.springframework.web.server.ResponseStatusException;
|
||
import org.springframework.web.servlet.resource.NoResourceFoundException;
|
||
|
||
import com.vnp.demo.dto.ErrorResponse;
|
||
|
||
import jakarta.servlet.http.HttpServletRequest;
|
||
|
||
@RestControllerAdvice
|
||
public class GlobalExceptionHandler {
|
||
|
||
private ErrorResponse build(String code, String msg) {
|
||
return new ErrorResponse(
|
||
new ErrorResponse.ErrorBody(
|
||
code,
|
||
msg,
|
||
MDC.get("requestId")
|
||
)
|
||
);
|
||
}
|
||
|
||
@ExceptionHandler(BusinessException.class)
|
||
public ResponseEntity<ErrorResponse> handleBusiness(
|
||
BusinessException e,
|
||
HttpServletRequest request
|
||
) {
|
||
ResponseEntity.BodyBuilder builder =
|
||
ResponseEntity.status(e.getStatus());
|
||
|
||
if (e.getStatus() == HttpStatus.TOO_MANY_REQUESTS) {
|
||
builder.header("Retry-After", "1");
|
||
}
|
||
|
||
if (e.getStatus() == HttpStatus.UNAUTHORIZED) {
|
||
String path = request.getRequestURI();
|
||
|
||
String challenge = path.equals("/api/v1/auth/sessions")
|
||
? "Basic realm=\"messenger\", charset=\"UTF-8\""
|
||
: "Bearer realm=\"messenger\"";
|
||
|
||
builder.header("WWW-Authenticate", challenge);
|
||
}
|
||
|
||
return builder.body(
|
||
build(e.getCode(), e.getMessage())
|
||
);
|
||
}
|
||
|
||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||
public ResponseEntity<ErrorResponse> handleValidation(
|
||
MethodArgumentNotValidException e
|
||
) {
|
||
String msg = e.getBindingResult()
|
||
.getFieldErrors()
|
||
.stream()
|
||
.findFirst()
|
||
.map(f -> f.getField() + ": " + f.getDefaultMessage())
|
||
.orElse("Ошибка валидации");
|
||
|
||
return ResponseEntity.badRequest()
|
||
.body(build("invalid_request", msg));
|
||
}
|
||
|
||
@ExceptionHandler({
|
||
HttpMessageNotReadableException.class,
|
||
MethodArgumentTypeMismatchException.class
|
||
})
|
||
public ResponseEntity<ErrorResponse> handleMalformed(Exception e) {
|
||
return ResponseEntity.badRequest()
|
||
.body(build(
|
||
"invalid_request",
|
||
"Неверный формат запроса"
|
||
));
|
||
}
|
||
|
||
@ExceptionHandler(NoResourceFoundException.class)
|
||
public ResponseEntity<ErrorResponse> handleNotFound(
|
||
NoResourceFoundException e
|
||
) {
|
||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||
.body(build(
|
||
"not_found",
|
||
"Ресурс не найден"
|
||
));
|
||
}
|
||
|
||
@ExceptionHandler(MissingRequestHeaderException.class)
|
||
public ResponseEntity<ErrorResponse> handleMissingHeader(
|
||
MissingRequestHeaderException e
|
||
) {
|
||
return ResponseEntity.badRequest()
|
||
.body(build(
|
||
"invalid_request",
|
||
"Отсутствует обязательный заголовок: "
|
||
+ e.getHeaderName()
|
||
));
|
||
}
|
||
|
||
@ExceptionHandler(DataAccessException.class)
|
||
public ResponseEntity<ErrorResponse> handleDataAccess(
|
||
DataAccessException e
|
||
) {
|
||
return ResponseEntity
|
||
.status(HttpStatus.SERVICE_UNAVAILABLE)
|
||
.body(build(
|
||
"unavailable",
|
||
"Сервис временно недоступен"
|
||
));
|
||
}
|
||
|
||
@ExceptionHandler(ResponseStatusException.class)
|
||
public ResponseEntity<ErrorResponse> handleStatus(
|
||
ResponseStatusException e
|
||
) {
|
||
int status = e.getStatusCode().value();
|
||
|
||
String code = status == 503
|
||
? "unavailable"
|
||
: "request_failed";
|
||
|
||
String message = status == 503
|
||
? "Сервис временно недоступен"
|
||
: "Запрос не может быть выполнен";
|
||
|
||
return ResponseEntity.status(status)
|
||
.body(build(code, message));
|
||
}
|
||
|
||
@ExceptionHandler(Exception.class)
|
||
public ResponseEntity<ErrorResponse> handleGeneric(Exception e) {
|
||
return ResponseEntity
|
||
.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||
.body(build(
|
||
"internal_error",
|
||
"Внутренняя ошибка"
|
||
));
|
||
}
|
||
}
|
||
|
||
|
||
===== java/src/main/java/com/vnp/demo/dto/AttachmentResponse.java =====
|
||
|
||
package com.vnp.demo.dto;
|
||
|
||
import java.time.Instant;
|
||
import java.util.List;
|
||
import java.util.UUID;
|
||
|
||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||
import com.vnp.demo.models.Attachment;
|
||
|
||
public record AttachmentResponse(
|
||
UUID id,
|
||
|
||
@JsonProperty("chat_id")
|
||
UUID chatId,
|
||
|
||
@JsonProperty("owner_id")
|
||
UUID ownerId,
|
||
|
||
String filename,
|
||
|
||
@JsonProperty("content_type")
|
||
String contentType,
|
||
|
||
@JsonProperty("size_bytes")
|
||
long sizeBytes,
|
||
|
||
String sha256,
|
||
String status,
|
||
List<Object> variants,
|
||
|
||
@JsonProperty("error_code")
|
||
String errorCode,
|
||
|
||
@JsonProperty("created_at")
|
||
Instant createdAt,
|
||
|
||
@JsonProperty("updated_at")
|
||
Instant updatedAt
|
||
) {
|
||
public static AttachmentResponse from(Attachment attachment) {
|
||
return new AttachmentResponse(
|
||
attachment.id(),
|
||
attachment.chatId(),
|
||
attachment.ownerId(),
|
||
attachment.filename(),
|
||
attachment.contentType(),
|
||
attachment.sizeBytes(),
|
||
attachment.sha256(),
|
||
attachment.status(),
|
||
List.of(),
|
||
null,
|
||
attachment.createdAt(),
|
||
attachment.updatedAt()
|
||
);
|
||
}
|
||
}
|
||
|
||
===== java/src/main/java/com/vnp/demo/models/Attachment.java =====
|
||
|
||
package com.vnp.demo.models;
|
||
|
||
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,
|
||
String status,
|
||
Instant createdAt,
|
||
Instant updatedAt
|
||
) {
|
||
}
|
||
|
||
===== java/src/main/java/com/vnp/demo/repositories/AttachmentRepository.java =====
|
||
|
||
package com.vnp.demo.repositories;
|
||
|
||
import java.sql.ResultSet;
|
||
import java.sql.SQLException;
|
||
import java.sql.Timestamp;
|
||
import java.util.Optional;
|
||
import java.util.UUID;
|
||
|
||
import org.springframework.jdbc.core.JdbcTemplate;
|
||
import org.springframework.stereotype.Repository;
|
||
|
||
import com.vnp.demo.models.Attachment;
|
||
|
||
@Repository
|
||
public class AttachmentRepository {
|
||
|
||
private final JdbcTemplate jdbc;
|
||
|
||
public AttachmentRepository(JdbcTemplate jdbc) {
|
||
this.jdbc = jdbc;
|
||
}
|
||
|
||
public void 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||
""",
|
||
attachment.id(),
|
||
attachment.chatId(),
|
||
attachment.ownerId(),
|
||
attachment.filename(),
|
||
attachment.contentType(),
|
||
attachment.sizeBytes(),
|
||
attachment.sha256(),
|
||
attachment.objectKey(),
|
||
attachment.status(),
|
||
Timestamp.from(attachment.createdAt()),
|
||
Timestamp.from(attachment.updatedAt())
|
||
);
|
||
}
|
||
|
||
public Optional<Attachment> findById(UUID id) {
|
||
return jdbc.query(
|
||
"SELECT * FROM attachments WHERE id = ?",
|
||
this::mapRow,
|
||
id
|
||
).stream().findFirst();
|
||
}
|
||
|
||
private Attachment mapRow(ResultSet rs, int rowNum)
|
||
throws 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.getString("status"),
|
||
rs.getTimestamp("created_at").toInstant(),
|
||
rs.getTimestamp("updated_at").toInstant()
|
||
);
|
||
}
|
||
|
||
public boolean existsByObjectKey(String objectKey) {
|
||
Boolean exists = jdbc.queryForObject(
|
||
"""
|
||
SELECT EXISTS (
|
||
SELECT 1
|
||
FROM attachments
|
||
WHERE object_key = ?
|
||
)
|
||
""",
|
||
Boolean.class,
|
||
objectKey
|
||
);
|
||
|
||
return Boolean.TRUE.equals(exists);
|
||
}
|
||
|
||
public void lockObject(String objectKey) {
|
||
jdbc.query(
|
||
"""
|
||
SELECT pg_advisory_xact_lock(
|
||
hashtextextended(?, 0)
|
||
)
|
||
""",
|
||
(rs, rowNum) -> Boolean.TRUE,
|
||
"attachment-object:" + objectKey
|
||
);
|
||
}
|
||
|
||
public boolean tryLockObject(String objectKey) {
|
||
Boolean acquired = jdbc.queryForObject(
|
||
"""
|
||
SELECT pg_try_advisory_xact_lock(
|
||
hashtextextended(?, 0)
|
||
)
|
||
""",
|
||
Boolean.class,
|
||
"attachment-object:" + objectKey
|
||
);
|
||
|
||
return Boolean.TRUE.equals(acquired);
|
||
}
|
||
}
|
||
|
||
===== java/src/main/java/com/vnp/demo/service/AttachmentCleanupJob.java =====
|
||
|
||
package com.vnp.demo.service;
|
||
|
||
import java.time.Instant;
|
||
|
||
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 com.vnp.demo.service.AttachmentPersistenceService.CleanupResult;
|
||
|
||
import io.minio.Result;
|
||
import io.minio.messages.Item;
|
||
|
||
@Component
|
||
@ConditionalOnProperty(
|
||
name = "app.cleanup.enabled",
|
||
havingValue = "true",
|
||
matchIfMissing = true
|
||
)
|
||
public class AttachmentCleanupJob {
|
||
|
||
private static final Logger log =
|
||
LoggerFactory.getLogger(AttachmentCleanupJob.class);
|
||
|
||
private final S3StorageService storage;
|
||
private final AttachmentPersistenceService persistence;
|
||
private final long graceSeconds;
|
||
|
||
public AttachmentCleanupJob(
|
||
S3StorageService storage,
|
||
AttachmentPersistenceService persistence,
|
||
@Value("${app.cleanup.grace-seconds:3600}")
|
||
long graceSeconds
|
||
) {
|
||
if (graceSeconds < 60) {
|
||
throw new IllegalArgumentException(
|
||
"Grace period должен быть не меньше 60 секунд"
|
||
);
|
||
}
|
||
|
||
this.storage = storage;
|
||
this.persistence = persistence;
|
||
this.graceSeconds = graceSeconds;
|
||
}
|
||
|
||
@Scheduled(
|
||
initialDelayString =
|
||
"${app.cleanup.initial-delay-ms:60000}",
|
||
fixedDelayString =
|
||
"${app.cleanup.interval-ms:300000}"
|
||
)
|
||
public void cleanup() {
|
||
Instant cutoff = Instant.now()
|
||
.minusSeconds(graceSeconds);
|
||
|
||
long scanned = 0;
|
||
long candidates = 0;
|
||
long deleted = 0;
|
||
|
||
try {
|
||
for (Result<Item> result : storage.listOriginals()) {
|
||
Item item = result.get();
|
||
|
||
if (item.isDir()) {
|
||
continue;
|
||
}
|
||
|
||
scanned++;
|
||
|
||
Instant lastModified = item.lastModified()
|
||
.toInstant();
|
||
|
||
if (!lastModified.isBefore(cutoff)) {
|
||
continue;
|
||
}
|
||
|
||
candidates++;
|
||
|
||
CleanupResult outcome =
|
||
persistence.removeIfOrphan(
|
||
item.objectName(),
|
||
cutoff
|
||
);
|
||
|
||
if (outcome == CleanupResult.DELETED) {
|
||
deleted++;
|
||
|
||
log.info(
|
||
"Attachment cleanup removed orphan: {}",
|
||
item.objectName()
|
||
);
|
||
}
|
||
}
|
||
|
||
log.info(
|
||
"Attachment cleanup completed: "
|
||
+ "scanned={}, candidates={}, deleted={}",
|
||
scanned,
|
||
candidates,
|
||
deleted
|
||
);
|
||
} catch (Exception e) {
|
||
// Прерываем текущий проход при ошибке БД или S3.
|
||
// Следующий запуск повторит проверку.
|
||
// Не выводим credentials или содержимое ответа S3.
|
||
log.warn(
|
||
"Attachment cleanup interrupted: "
|
||
+ "scanned={}, candidates={}, deleted={}, errorType={}",
|
||
scanned,
|
||
candidates,
|
||
deleted,
|
||
e.getClass().getSimpleName()
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
===== java/src/main/java/com/vnp/demo/service/AttachmentPersistenceService.java =====
|
||
|
||
package com.vnp.demo.service;
|
||
|
||
import java.nio.file.Path;
|
||
import java.time.Instant;
|
||
|
||
import org.springframework.stereotype.Service;
|
||
import org.springframework.transaction.annotation.Isolation;
|
||
import org.springframework.transaction.annotation.Transactional;
|
||
|
||
import com.vnp.demo.models.Attachment;
|
||
import com.vnp.demo.repositories.AttachmentRepository;
|
||
|
||
@Service
|
||
public class AttachmentPersistenceService {
|
||
|
||
private final AttachmentRepository attachmentRepository;
|
||
private final S3StorageService storage;
|
||
|
||
public AttachmentPersistenceService(
|
||
AttachmentRepository attachmentRepository,
|
||
S3StorageService storage
|
||
) {
|
||
this.attachmentRepository = attachmentRepository;
|
||
this.storage = storage;
|
||
}
|
||
|
||
@Transactional(
|
||
isolation = Isolation.READ_COMMITTED,
|
||
timeout = 60
|
||
)
|
||
public void save(
|
||
Attachment attachment,
|
||
Path temporaryFile
|
||
) {
|
||
attachmentRepository.lockObject(
|
||
attachment.objectKey()
|
||
);
|
||
|
||
storage.put(
|
||
attachment.objectKey(),
|
||
temporaryFile,
|
||
attachment.sizeBytes(),
|
||
attachment.contentType()
|
||
);
|
||
|
||
attachmentRepository.save(attachment);
|
||
}
|
||
|
||
@Transactional(
|
||
isolation = Isolation.READ_COMMITTED,
|
||
timeout = 30
|
||
)
|
||
public CleanupResult removeIfOrphan(
|
||
String objectKey,
|
||
Instant cutoff
|
||
) {
|
||
if (!objectKey.startsWith("originals/")) {
|
||
return CleanupResult.SKIPPED;
|
||
}
|
||
|
||
if (!attachmentRepository.tryLockObject(objectKey)) {
|
||
return CleanupResult.BUSY;
|
||
}
|
||
|
||
if (attachmentRepository.existsByObjectKey(objectKey)) {
|
||
return CleanupResult.REFERENCED;
|
||
}
|
||
|
||
Instant lastModified = storage.lastModifiedOrNull(
|
||
objectKey
|
||
);
|
||
|
||
if (lastModified == null) {
|
||
return CleanupResult.MISSING;
|
||
}
|
||
|
||
if (!lastModified.isBefore(cutoff)) {
|
||
return CleanupResult.RECENT;
|
||
}
|
||
|
||
storage.remove(objectKey);
|
||
|
||
return CleanupResult.DELETED;
|
||
}
|
||
|
||
public enum CleanupResult {
|
||
DELETED,
|
||
REFERENCED,
|
||
RECENT,
|
||
BUSY,
|
||
MISSING,
|
||
SKIPPED
|
||
}
|
||
}
|
||
|
||
===== java/src/main/java/com/vnp/demo/service/AttachmentService.java =====
|
||
|
||
package com.vnp.demo.service;
|
||
|
||
import java.io.InputStream;
|
||
import java.time.Instant;
|
||
import java.time.temporal.ChronoUnit;
|
||
import java.util.UUID;
|
||
|
||
import org.springframework.stereotype.Service;
|
||
|
||
import com.vnp.demo.BusinessException;
|
||
import com.vnp.demo.dto.AttachmentResponse;
|
||
import com.vnp.demo.models.Attachment;
|
||
import com.vnp.demo.repositories.AttachmentRepository;
|
||
import com.vnp.demo.repositories.ChatMemberRepository;
|
||
import com.vnp.demo.validation.ImageValidator;
|
||
import com.vnp.demo.validation.ImageValidator.ValidatedImage;
|
||
|
||
@Service
|
||
public class AttachmentService {
|
||
|
||
private final AttachmentRepository attachmentRepository;
|
||
private final ChatMemberRepository chatMemberRepository;
|
||
private final ImageValidator imageValidator;
|
||
private final S3StorageService storage;
|
||
private final UploadLimiter uploadLimiter;
|
||
private final AttachmentPersistenceService persistence;
|
||
|
||
public AttachmentService(
|
||
AttachmentRepository attachmentRepository,
|
||
ChatMemberRepository chatMemberRepository,
|
||
ImageValidator imageValidator,
|
||
S3StorageService storage,
|
||
UploadLimiter uploadLimiter,
|
||
AttachmentPersistenceService persistence
|
||
) {
|
||
this.attachmentRepository = attachmentRepository;
|
||
this.chatMemberRepository = chatMemberRepository;
|
||
this.imageValidator = imageValidator;
|
||
this.storage = storage;
|
||
this.uploadLimiter = uploadLimiter;
|
||
this.persistence = persistence;
|
||
}
|
||
|
||
public AttachmentResponse upload(
|
||
UUID userId,
|
||
UUID chatId,
|
||
String filename,
|
||
String contentType,
|
||
long contentLength,
|
||
InputStream input
|
||
) {
|
||
checkChatAccess(userId, chatId);
|
||
|
||
imageValidator.validateFilename(filename);
|
||
|
||
try (UploadLimiter.Permit permit = uploadLimiter.acquire();
|
||
ValidatedImage image = imageValidator.validate(
|
||
input,
|
||
contentLength,
|
||
contentType
|
||
)) {
|
||
|
||
UUID attachmentId = UUID.randomUUID();
|
||
|
||
String objectKey = "originals/"
|
||
+ chatId
|
||
+ "/"
|
||
+ attachmentId;
|
||
|
||
Instant now = Instant.now()
|
||
.truncatedTo(ChronoUnit.MICROS);
|
||
|
||
Attachment attachment = new Attachment(
|
||
attachmentId,
|
||
chatId,
|
||
userId,
|
||
filename,
|
||
image.contentType(),
|
||
image.sizeBytes(),
|
||
image.sha256(),
|
||
objectKey,
|
||
"ready",
|
||
now,
|
||
now
|
||
);
|
||
|
||
persistence.save(attachment, image.path());
|
||
|
||
return AttachmentResponse.from(attachment);
|
||
}
|
||
}
|
||
|
||
public AttachmentResponse getMetadata(
|
||
UUID userId,
|
||
UUID attachmentId
|
||
) {
|
||
return AttachmentResponse.from(
|
||
getAccessibleAttachment(userId, attachmentId)
|
||
);
|
||
}
|
||
|
||
public Download download(
|
||
UUID userId,
|
||
UUID attachmentId,
|
||
String variant
|
||
) {
|
||
Attachment attachment = getAccessibleAttachment(
|
||
userId,
|
||
attachmentId
|
||
);
|
||
|
||
if (!"ready".equals(attachment.status())) {
|
||
throw BusinessException.conflict(
|
||
"Вложение ещё не готово"
|
||
);
|
||
}
|
||
|
||
if (!"original".equals(variant)) {
|
||
throw BusinessException.notFound();
|
||
}
|
||
|
||
byte[] bytes = storage.get(
|
||
attachment.objectKey(),
|
||
attachment.sizeBytes(),
|
||
attachment.sha256()
|
||
);
|
||
|
||
return new Download(
|
||
attachment.filename(),
|
||
attachment.contentType(),
|
||
bytes
|
||
);
|
||
}
|
||
|
||
private Attachment getAccessibleAttachment(
|
||
UUID userId,
|
||
UUID attachmentId
|
||
) {
|
||
Attachment attachment = attachmentRepository
|
||
.findById(attachmentId)
|
||
.orElseThrow(BusinessException::notFound);
|
||
|
||
checkChatAccess(userId, attachment.chatId());
|
||
|
||
return attachment;
|
||
}
|
||
|
||
private void checkChatAccess(UUID userId, UUID chatId) {
|
||
boolean member = chatMemberRepository
|
||
.existsByIdChatIdAndIdUserId(chatId, userId);
|
||
|
||
if (!member) {
|
||
throw BusinessException.notFound();
|
||
}
|
||
}
|
||
|
||
public record Download(
|
||
String filename,
|
||
String contentType,
|
||
byte[] bytes
|
||
) {
|
||
}
|
||
}
|
||
|
||
===== java/src/main/java/com/vnp/demo/service/S3StorageService.java =====
|
||
|
||
package com.vnp.demo.service;
|
||
|
||
import java.io.InputStream;
|
||
import java.nio.file.Files;
|
||
import java.nio.file.Path;
|
||
import java.time.Instant;
|
||
import java.util.concurrent.TimeUnit;
|
||
|
||
import org.springframework.beans.factory.annotation.Value;
|
||
import org.springframework.http.HttpStatus;
|
||
import org.springframework.stereotype.Service;
|
||
|
||
import com.vnp.demo.BusinessException;
|
||
import com.vnp.demo.validation.ImageValidator;
|
||
|
||
import io.minio.BucketExistsArgs;
|
||
import io.minio.GetObjectArgs;
|
||
import io.minio.ListObjectsArgs;
|
||
import io.minio.MinioClient;
|
||
import io.minio.PutObjectArgs;
|
||
import io.minio.RemoveObjectArgs;
|
||
import io.minio.Result;
|
||
import io.minio.StatObjectArgs;
|
||
import io.minio.StatObjectResponse;
|
||
import io.minio.errors.ErrorResponseException;
|
||
import io.minio.messages.Item;
|
||
import okhttp3.OkHttpClient;
|
||
|
||
@Service
|
||
public class S3StorageService {
|
||
|
||
private final MinioClient client;
|
||
private final String bucket;
|
||
|
||
public S3StorageService(
|
||
@Value("${app.s3.endpoint}") String endpoint,
|
||
@Value("${app.s3.access-key}") String accessKey,
|
||
@Value("${app.s3.secret-key}") String secretKey,
|
||
@Value("${app.s3.bucket}") String bucket
|
||
) {
|
||
this.bucket = bucket;
|
||
|
||
OkHttpClient httpClient = new OkHttpClient.Builder()
|
||
.connectTimeout(2, TimeUnit.SECONDS)
|
||
.writeTimeout(10, TimeUnit.SECONDS)
|
||
.readTimeout(10, TimeUnit.SECONDS)
|
||
.callTimeout(30, TimeUnit.SECONDS)
|
||
.retryOnConnectionFailure(false)
|
||
.build();
|
||
|
||
this.client = MinioClient.builder()
|
||
.endpoint(endpoint)
|
||
.credentials(accessKey, secretKey)
|
||
.region("us-east-1")
|
||
.httpClient(httpClient)
|
||
.build();
|
||
}
|
||
|
||
public void put(
|
||
String objectKey,
|
||
Path file,
|
||
long sizeBytes,
|
||
String contentType
|
||
) {
|
||
if (sizeBytes < 1
|
||
|| sizeBytes > ImageValidator.MAX_BYTES) {
|
||
throw new BusinessException(
|
||
"payload_too_large",
|
||
"Некорректный размер загружаемого файла",
|
||
HttpStatus.PAYLOAD_TOO_LARGE
|
||
);
|
||
}
|
||
|
||
try (InputStream input = Files.newInputStream(file)) {
|
||
client.putObject(
|
||
PutObjectArgs.builder()
|
||
.bucket(bucket)
|
||
.object(objectKey)
|
||
.contentType(contentType)
|
||
.stream(input, sizeBytes, ImageValidator.MAX_BYTES)
|
||
.build()
|
||
);
|
||
} catch (Exception e) {
|
||
throw unavailable();
|
||
}
|
||
}
|
||
|
||
public byte[] get(
|
||
String objectKey,
|
||
long expectedSize,
|
||
String expectedSha256
|
||
) {
|
||
if (expectedSize < 1
|
||
|| expectedSize > ImageValidator.MAX_BYTES) {
|
||
throw unavailable();
|
||
}
|
||
|
||
try (InputStream input = client.getObject(
|
||
GetObjectArgs.builder()
|
||
.bucket(bucket)
|
||
.object(objectKey)
|
||
.build()
|
||
)) {
|
||
byte[] bytes = input.readNBytes(
|
||
Math.toIntExact(expectedSize) + 1
|
||
);
|
||
|
||
if (bytes.length != expectedSize
|
||
|| !ImageValidator.sha256(bytes)
|
||
.equals(expectedSha256)) {
|
||
throw unavailable();
|
||
}
|
||
|
||
return bytes;
|
||
} catch (BusinessException e) {
|
||
throw e;
|
||
} catch (Exception e) {
|
||
throw unavailable();
|
||
}
|
||
}
|
||
|
||
public Iterable<Result<Item>> listOriginals() {
|
||
return client.listObjects(
|
||
ListObjectsArgs.builder()
|
||
.bucket(bucket)
|
||
.prefix("originals/")
|
||
.recursive(true)
|
||
.build()
|
||
);
|
||
}
|
||
|
||
public Instant lastModifiedOrNull(String objectKey) {
|
||
try {
|
||
StatObjectResponse response = client.statObject(
|
||
StatObjectArgs.builder()
|
||
.bucket(bucket)
|
||
.object(objectKey)
|
||
.build()
|
||
);
|
||
|
||
return response.lastModified().toInstant();
|
||
} catch (ErrorResponseException e) {
|
||
String code = e.errorResponse().code();
|
||
|
||
if ("NoSuchKey".equals(code)
|
||
|| "NoSuchObject".equals(code)) {
|
||
return null;
|
||
}
|
||
|
||
throw unavailable();
|
||
} catch (Exception e) {
|
||
throw unavailable();
|
||
}
|
||
}
|
||
|
||
public void remove(String objectKey) {
|
||
try {
|
||
client.removeObject(
|
||
RemoveObjectArgs.builder()
|
||
.bucket(bucket)
|
||
.object(objectKey)
|
||
.build()
|
||
);
|
||
} catch (Exception e) {
|
||
throw unavailable();
|
||
}
|
||
}
|
||
|
||
public void checkReady() {
|
||
try {
|
||
boolean exists = client.bucketExists(
|
||
BucketExistsArgs.builder()
|
||
.bucket(bucket)
|
||
.build()
|
||
);
|
||
|
||
if (!exists) {
|
||
throw unavailable();
|
||
}
|
||
} catch (BusinessException e) {
|
||
throw e;
|
||
} catch (Exception e) {
|
||
throw unavailable();
|
||
}
|
||
}
|
||
|
||
private static BusinessException unavailable() {
|
||
return new BusinessException(
|
||
"unavailable",
|
||
"Хранилище файлов временно недоступно",
|
||
HttpStatus.SERVICE_UNAVAILABLE
|
||
);
|
||
}
|
||
}
|
||
|
||
===== java/src/main/resources/db/migration/V1__create_tables.sql =====
|
||
|
||
|
||
CREATE TABLE users (
|
||
id UUID PRIMARY KEY,
|
||
username VARCHAR(32) NOT NULL UNIQUE,
|
||
display_name VARCHAR(400) NOT NULL,
|
||
password_hash TEXT NOT NULL,
|
||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||
|
||
CONSTRAINT chk_username
|
||
CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||
CONSTRAINT chk_display_name
|
||
CHECK (
|
||
char_length(display_name) BETWEEN 1 AND 100
|
||
AND length(btrim(display_name)) > 0
|
||
)
|
||
);
|
||
|
||
CREATE TABLE chats (
|
||
id UUID PRIMARY KEY,
|
||
title VARCHAR(400) NOT NULL,
|
||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||
|
||
CONSTRAINT chk_chat_title
|
||
CHECK (
|
||
char_length(title) BETWEEN 1 AND 100
|
||
AND length(btrim(title)) > 0
|
||
)
|
||
);
|
||
|
||
CREATE TABLE chat_members (
|
||
chat_id UUID NOT NULL REFERENCES chats(id),
|
||
user_id UUID NOT NULL REFERENCES users(id),
|
||
|
||
PRIMARY KEY (chat_id, user_id)
|
||
);
|
||
|
||
CREATE TABLE messages (
|
||
id UUID PRIMARY KEY,
|
||
chat_id UUID NOT NULL REFERENCES chats(id),
|
||
sender_id UUID NOT NULL,
|
||
text VARCHAR(16000) NOT NULL,
|
||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||
|
||
CONSTRAINT fk_message_membership
|
||
FOREIGN KEY (chat_id, sender_id)
|
||
REFERENCES chat_members(chat_id, user_id),
|
||
|
||
CONSTRAINT chk_message_text
|
||
CHECK (
|
||
char_length(text) BETWEEN 1 AND 4000
|
||
AND length(btrim(text)) > 0
|
||
)
|
||
);
|
||
|
||
CREATE TABLE sessions (
|
||
id UUID PRIMARY KEY,
|
||
user_id UUID NOT NULL REFERENCES users(id),
|
||
token_hash CHAR(64) NOT NULL UNIQUE,
|
||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||
expires_at TIMESTAMPTZ NOT NULL,
|
||
revoked_at TIMESTAMPTZ,
|
||
|
||
CONSTRAINT chk_session_expiry
|
||
CHECK (expires_at > created_at)
|
||
);
|
||
|
||
CREATE INDEX idx_chat_members_user
|
||
ON chat_members(user_id, chat_id);
|
||
|
||
CREATE INDEX idx_chats_history
|
||
ON chats(created_at, id);
|
||
|
||
CREATE INDEX idx_messages_history
|
||
ON messages(chat_id, created_at, id);
|
||
|
||
CREATE INDEX idx_sessions_user
|
||
ON sessions(user_id);
|
||
|
||
|
||
===== java/src/main/resources/db/migration/V2__message_idempotency.sql =====
|
||
|
||
CREATE TABLE message_idempotency (
|
||
user_id UUID NOT NULL REFERENCES users(id),
|
||
chat_id UUID NOT NULL REFERENCES chats(id),
|
||
key VARCHAR(128) COLLATE "C" NOT NULL,
|
||
request_text TEXT NOT NULL,
|
||
message_id UUID NOT NULL UNIQUE REFERENCES messages(id),
|
||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||
PRIMARY KEY (user_id, chat_id, key)
|
||
);
|
||
|
||
|
||
===== java/src/main/resources/db/migration/V3__attachments.sql =====
|
||
|
||
CREATE TABLE attachments (
|
||
id UUID PRIMARY KEY,
|
||
chat_id UUID NOT NULL REFERENCES chats(id),
|
||
owner_id UUID NOT NULL REFERENCES users(id),
|
||
|
||
filename TEXT NOT NULL,
|
||
content_type VARCHAR(32) NOT NULL,
|
||
size_bytes BIGINT NOT NULL,
|
||
sha256 CHAR(64) NOT NULL,
|
||
|
||
object_key TEXT NOT NULL UNIQUE,
|
||
status VARCHAR(16) NOT NULL DEFAULT 'ready',
|
||
|
||
created_at TIMESTAMPTZ NOT NULL,
|
||
updated_at TIMESTAMPTZ NOT NULL,
|
||
|
||
CONSTRAINT chk_attachment_filename
|
||
CHECK (char_length(filename) BETWEEN 1 AND 255),
|
||
|
||
CONSTRAINT chk_attachment_content_type
|
||
CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||
|
||
CONSTRAINT chk_attachment_size
|
||
CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||
|
||
CONSTRAINT chk_attachment_sha256
|
||
CHECK (sha256 ~ '^[a-f0-9]{64}$'),
|
||
|
||
CONSTRAINT chk_attachment_status
|
||
CHECK (status = 'ready'),
|
||
|
||
CONSTRAINT fk_attachment_membership
|
||
FOREIGN KEY (chat_id, owner_id)
|
||
REFERENCES chat_members(chat_id, user_id)
|
||
);
|
||
|
||
CREATE INDEX idx_attachments_chat
|
||
ON attachments(chat_id, created_at, id);
|
||
|
||
CREATE TABLE message_attachments (
|
||
message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
||
attachment_id UUID NOT NULL REFERENCES attachments(id),
|
||
position INTEGER NOT NULL,
|
||
|
||
PRIMARY KEY (message_id, position),
|
||
|
||
CONSTRAINT uq_message_attachment
|
||
UNIQUE (message_id, attachment_id),
|
||
|
||
CONSTRAINT chk_attachment_position
|
||
CHECK (position BETWEEN 0 AND 9)
|
||
);
|
||
|
||
CREATE INDEX idx_message_attachments_attachment
|
||
ON message_attachments(attachment_id);
|
||
|
||
|
||
ALTER TABLE messages
|
||
DROP CONSTRAINT chk_message_text;
|
||
|
||
ALTER TABLE messages
|
||
ADD CONSTRAINT chk_message_text
|
||
CHECK (char_length(text) BETWEEN 0 AND 4000);
|
||
|
||
-- Старые запросы не содержали вложений, поэтому для них значение пустое.
|
||
ALTER TABLE message_idempotency
|
||
ADD COLUMN request_attachment_ids TEXT NOT NULL DEFAULT '';
|
||
|
||
===== contracts/openapi.json =====
|
||
|
||
{
|
||
"openapi": "3.1.0",
|
||
"info": {
|
||
"title": "MTUSI Messenger — лабораторная 4",
|
||
"version": "1.4.0",
|
||
"description": "Нормативный минимум на 3. Семантика: contracts/README.md. Расширения на 4/5 не должны менять этот API. Наличие кода ошибки в схеме не требует реализовать факультативную причину его выдачи."
|
||
},
|
||
"servers": [
|
||
{
|
||
"url": "http://localhost:8080",
|
||
"description": "Локальный учебный стенд"
|
||
}
|
||
],
|
||
"security": [
|
||
{
|
||
"bearerAuth": []
|
||
}
|
||
],
|
||
"paths": {
|
||
"/health/live": {
|
||
"get": {
|
||
"operationId": "liveness",
|
||
"summary": "Процесс жив",
|
||
"responses": {
|
||
"200": {
|
||
"description": "Успех",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Health"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"500": {
|
||
"description": "Неожиданная ошибка без внутренних деталей",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"security": []
|
||
}
|
||
},
|
||
"/health/ready": {
|
||
"get": {
|
||
"operationId": "readiness",
|
||
"summary": "Готов принимать трафик",
|
||
"responses": {
|
||
"200": {
|
||
"description": "Успех",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Health"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"503": {
|
||
"description": "Зависимость недоступна",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"500": {
|
||
"description": "Неожиданная ошибка без внутренних деталей",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"security": []
|
||
}
|
||
},
|
||
"/api/v1/users": {
|
||
"post": {
|
||
"operationId": "registerUser",
|
||
"summary": "Создать пользователя",
|
||
"responses": {
|
||
"201": {
|
||
"description": "Успех",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/User"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"400": {
|
||
"description": "Неверный запрос",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"409": {
|
||
"description": "Конфликт",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"429": {
|
||
"description": "Ограничение частоты запросов",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"Retry-After": {
|
||
"description": "Положительное число секунд.",
|
||
"schema": {
|
||
"type": "integer",
|
||
"minimum": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"503": {
|
||
"description": "Зависимость недоступна",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"500": {
|
||
"description": "Неожиданная ошибка без внутренних деталей",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"security": [],
|
||
"requestBody": {
|
||
"required": true,
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/CreateUser"
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"/api/v1/users/me": {
|
||
"get": {
|
||
"operationId": "currentUser",
|
||
"summary": "Текущий пользователь",
|
||
"responses": {
|
||
"200": {
|
||
"description": "Успех",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/User"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"400": {
|
||
"description": "Неверный запрос",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"401": {
|
||
"description": "Нет действительной аутентификации",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"WWW-Authenticate": {
|
||
"description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.",
|
||
"schema": {
|
||
"type": "string"
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"404": {
|
||
"description": "Объект отсутствует или недоступен",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"409": {
|
||
"description": "Конфликт",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"429": {
|
||
"description": "Ограничение частоты запросов",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"Retry-After": {
|
||
"description": "Положительное число секунд.",
|
||
"schema": {
|
||
"type": "integer",
|
||
"minimum": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"503": {
|
||
"description": "Зависимость недоступна",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"500": {
|
||
"description": "Неожиданная ошибка без внутренних деталей",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"/api/v1/chats": {
|
||
"post": {
|
||
"operationId": "createChat",
|
||
"summary": "Создать чат; вызывающий должен входить в member_ids",
|
||
"responses": {
|
||
"201": {
|
||
"description": "Успех",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Chat"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"400": {
|
||
"description": "Неверный запрос",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"401": {
|
||
"description": "Нет действительной аутентификации",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"WWW-Authenticate": {
|
||
"description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.",
|
||
"schema": {
|
||
"type": "string"
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"404": {
|
||
"description": "Объект отсутствует или недоступен",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"409": {
|
||
"description": "Конфликт",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"429": {
|
||
"description": "Ограничение частоты запросов",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"Retry-After": {
|
||
"description": "Положительное число секунд.",
|
||
"schema": {
|
||
"type": "integer",
|
||
"minimum": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"503": {
|
||
"description": "Зависимость недоступна",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"500": {
|
||
"description": "Неожиданная ошибка без внутренних деталей",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"requestBody": {
|
||
"required": true,
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/CreateChat"
|
||
}
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"get": {
|
||
"operationId": "listChats",
|
||
"summary": "Чаты текущего пользователя",
|
||
"responses": {
|
||
"200": {
|
||
"description": "Успех",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/ChatPage"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"400": {
|
||
"description": "Неверный запрос",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"401": {
|
||
"description": "Нет действительной аутентификации",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"WWW-Authenticate": {
|
||
"description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.",
|
||
"schema": {
|
||
"type": "string"
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"404": {
|
||
"description": "Объект отсутствует или недоступен",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"409": {
|
||
"description": "Конфликт",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"429": {
|
||
"description": "Ограничение частоты запросов",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"Retry-After": {
|
||
"description": "Положительное число секунд.",
|
||
"schema": {
|
||
"type": "integer",
|
||
"minimum": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"503": {
|
||
"description": "Зависимость недоступна",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"500": {
|
||
"description": "Неожиданная ошибка без внутренних деталей",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"parameters": [
|
||
{
|
||
"name": "limit",
|
||
"in": "query",
|
||
"schema": {
|
||
"type": "integer",
|
||
"minimum": 1,
|
||
"maximum": 100,
|
||
"default": 50
|
||
}
|
||
},
|
||
{
|
||
"name": "cursor",
|
||
"in": "query",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
]
|
||
}
|
||
},
|
||
"/api/v1/chats/{chat_id}": {
|
||
"get": {
|
||
"operationId": "getChat",
|
||
"summary": "Получить доступный чат",
|
||
"responses": {
|
||
"200": {
|
||
"description": "Успех",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Chat"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"400": {
|
||
"description": "Неверный запрос",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"401": {
|
||
"description": "Нет действительной аутентификации",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"WWW-Authenticate": {
|
||
"description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.",
|
||
"schema": {
|
||
"type": "string"
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"404": {
|
||
"description": "Объект отсутствует или недоступен",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"409": {
|
||
"description": "Конфликт",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"429": {
|
||
"description": "Ограничение частоты запросов",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"Retry-After": {
|
||
"description": "Положительное число секунд.",
|
||
"schema": {
|
||
"type": "integer",
|
||
"minimum": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"503": {
|
||
"description": "Зависимость недоступна",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"500": {
|
||
"description": "Неожиданная ошибка без внутренних деталей",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"parameters": [
|
||
{
|
||
"name": "chat_id",
|
||
"in": "path",
|
||
"required": true,
|
||
"schema": {
|
||
"type": "string",
|
||
"format": "uuid"
|
||
}
|
||
}
|
||
]
|
||
}
|
||
},
|
||
"/api/v1/chats/{chat_id}/messages": {
|
||
"post": {
|
||
"operationId": "createMessage",
|
||
"summary": "Отправить сообщение",
|
||
"responses": {
|
||
"201": {
|
||
"description": "Успех",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Message"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"400": {
|
||
"description": "Неверный запрос",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"401": {
|
||
"description": "Нет действительной аутентификации",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"WWW-Authenticate": {
|
||
"description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.",
|
||
"schema": {
|
||
"type": "string"
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"404": {
|
||
"description": "Объект отсутствует или недоступен",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"409": {
|
||
"description": "Конфликт",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"429": {
|
||
"description": "Ограничение частоты запросов",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"Retry-After": {
|
||
"description": "Положительное число секунд.",
|
||
"schema": {
|
||
"type": "integer",
|
||
"minimum": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"503": {
|
||
"description": "Зависимость недоступна",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"500": {
|
||
"description": "Неожиданная ошибка без внутренних деталей",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"parameters": [
|
||
{
|
||
"name": "chat_id",
|
||
"in": "path",
|
||
"required": true,
|
||
"schema": {
|
||
"type": "string",
|
||
"format": "uuid"
|
||
}
|
||
},
|
||
{
|
||
"name": "Idempotency-Key",
|
||
"in": "header",
|
||
"required": true,
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1,
|
||
"maxLength": 128,
|
||
"pattern": "^[A-Za-z0-9._:-]+$"
|
||
},
|
||
"description": "Обязателен с lab3. Область: пользователь + метод + путь + ключ; хранить результат не менее 24 ч. Повтор того же JSON возвращает исходный 201 и то же сообщение, другой JSON — 409."
|
||
}
|
||
],
|
||
"requestBody": {
|
||
"required": true,
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/CreateMessage"
|
||
}
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"get": {
|
||
"operationId": "listMessages",
|
||
"summary": "Сообщения по (created_at, id) по возрастанию",
|
||
"responses": {
|
||
"200": {
|
||
"description": "Успех",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/MessagePage"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"400": {
|
||
"description": "Неверный запрос",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"401": {
|
||
"description": "Нет действительной аутентификации",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"WWW-Authenticate": {
|
||
"description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.",
|
||
"schema": {
|
||
"type": "string"
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"404": {
|
||
"description": "Объект отсутствует или недоступен",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"409": {
|
||
"description": "Конфликт",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"429": {
|
||
"description": "Ограничение частоты запросов",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"Retry-After": {
|
||
"description": "Положительное число секунд.",
|
||
"schema": {
|
||
"type": "integer",
|
||
"minimum": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"503": {
|
||
"description": "Зависимость недоступна",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"500": {
|
||
"description": "Неожиданная ошибка без внутренних деталей",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"parameters": [
|
||
{
|
||
"name": "chat_id",
|
||
"in": "path",
|
||
"required": true,
|
||
"schema": {
|
||
"type": "string",
|
||
"format": "uuid"
|
||
}
|
||
},
|
||
{
|
||
"name": "limit",
|
||
"in": "query",
|
||
"schema": {
|
||
"type": "integer",
|
||
"minimum": 1,
|
||
"maximum": 100,
|
||
"default": 50
|
||
}
|
||
},
|
||
{
|
||
"name": "cursor",
|
||
"in": "query",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
]
|
||
}
|
||
},
|
||
"/api/v1/auth/sessions": {
|
||
"post": {
|
||
"operationId": "createSession",
|
||
"summary": "Вход: Basic username:password; выдаёт сессию",
|
||
"responses": {
|
||
"201": {
|
||
"description": "Успех",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Session"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"400": {
|
||
"description": "Неверный запрос",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"401": {
|
||
"description": "Нет действительной аутентификации",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"WWW-Authenticate": {
|
||
"description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.",
|
||
"schema": {
|
||
"type": "string"
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"429": {
|
||
"description": "Ограничение частоты запросов",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"Retry-After": {
|
||
"description": "Положительное число секунд.",
|
||
"schema": {
|
||
"type": "integer",
|
||
"minimum": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"503": {
|
||
"description": "Зависимость недоступна",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"500": {
|
||
"description": "Неожиданная ошибка без внутренних деталей",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"security": [
|
||
{
|
||
"basicAuth": []
|
||
}
|
||
]
|
||
}
|
||
},
|
||
"/api/v1/auth/sessions/current": {
|
||
"delete": {
|
||
"operationId": "revokeSession",
|
||
"summary": "Отозвать текущую сессию",
|
||
"responses": {
|
||
"204": {
|
||
"description": "Успех",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"401": {
|
||
"description": "Нет действительной аутентификации",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"WWW-Authenticate": {
|
||
"description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.",
|
||
"schema": {
|
||
"type": "string"
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"429": {
|
||
"description": "Ограничение частоты запросов",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"Retry-After": {
|
||
"description": "Положительное число секунд.",
|
||
"schema": {
|
||
"type": "integer",
|
||
"minimum": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"503": {
|
||
"description": "Зависимость недоступна",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"500": {
|
||
"description": "Неожиданная ошибка без внутренних деталей",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"/api/v1/chats/{chat_id}/attachments": {
|
||
"post": {
|
||
"operationId": "uploadAttachment",
|
||
"summary": "Принять один PNG/JPEG, до 10 MiB",
|
||
"responses": {
|
||
"201": {
|
||
"description": "Успех",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Attachment"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"400": {
|
||
"description": "Неверный запрос",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"401": {
|
||
"description": "Нет действительной аутентификации",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"WWW-Authenticate": {
|
||
"description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.",
|
||
"schema": {
|
||
"type": "string"
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"404": {
|
||
"description": "Объект отсутствует или недоступен",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"413": {
|
||
"description": "Превышен лимит",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"415": {
|
||
"description": "Неподдерживаемый тип",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"429": {
|
||
"description": "Ограничение частоты запросов",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"Retry-After": {
|
||
"description": "Положительное число секунд.",
|
||
"schema": {
|
||
"type": "integer",
|
||
"minimum": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"503": {
|
||
"description": "Зависимость недоступна",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"500": {
|
||
"description": "Неожиданная ошибка без внутренних деталей",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"parameters": [
|
||
{
|
||
"name": "chat_id",
|
||
"in": "path",
|
||
"required": true,
|
||
"schema": {
|
||
"type": "string",
|
||
"format": "uuid"
|
||
}
|
||
},
|
||
{
|
||
"name": "filename",
|
||
"in": "query",
|
||
"required": true,
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1,
|
||
"maxLength": 255
|
||
}
|
||
}
|
||
],
|
||
"requestBody": {
|
||
"required": true,
|
||
"description": "Сырые байты изображения, НЕ multipart и НЕ JSON/base64.",
|
||
"content": {
|
||
"image/png": {
|
||
"schema": {
|
||
"type": "string",
|
||
"format": "binary"
|
||
}
|
||
},
|
||
"image/jpeg": {
|
||
"schema": {
|
||
"type": "string",
|
||
"format": "binary"
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"/api/v1/attachments/{attachment_id}": {
|
||
"get": {
|
||
"operationId": "getAttachment",
|
||
"summary": "Метаданные вложения, доступ участникам чата",
|
||
"responses": {
|
||
"200": {
|
||
"description": "Успех",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Attachment"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"400": {
|
||
"description": "Неверный запрос",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"401": {
|
||
"description": "Нет действительной аутентификации",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"WWW-Authenticate": {
|
||
"description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.",
|
||
"schema": {
|
||
"type": "string"
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"404": {
|
||
"description": "Объект отсутствует или недоступен",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"409": {
|
||
"description": "Конфликт",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"429": {
|
||
"description": "Ограничение частоты запросов",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"Retry-After": {
|
||
"description": "Положительное число секунд.",
|
||
"schema": {
|
||
"type": "integer",
|
||
"minimum": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"503": {
|
||
"description": "Зависимость недоступна",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"500": {
|
||
"description": "Неожиданная ошибка без внутренних деталей",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"parameters": [
|
||
{
|
||
"name": "attachment_id",
|
||
"in": "path",
|
||
"required": true,
|
||
"schema": {
|
||
"type": "string",
|
||
"format": "uuid"
|
||
}
|
||
}
|
||
]
|
||
}
|
||
},
|
||
"/api/v1/attachments/{attachment_id}/content": {
|
||
"get": {
|
||
"operationId": "downloadAttachment",
|
||
"summary": "Скачать байты через авторизованный API",
|
||
"responses": {
|
||
"200": {
|
||
"description": "Успех",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"image/png": {
|
||
"schema": {
|
||
"type": "string",
|
||
"format": "binary"
|
||
}
|
||
},
|
||
"image/jpeg": {
|
||
"schema": {
|
||
"type": "string",
|
||
"format": "binary"
|
||
}
|
||
},
|
||
"image/webp": {
|
||
"schema": {
|
||
"type": "string",
|
||
"format": "binary"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"400": {
|
||
"description": "Неверный запрос",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"401": {
|
||
"description": "Нет действительной аутентификации",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"WWW-Authenticate": {
|
||
"description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.",
|
||
"schema": {
|
||
"type": "string"
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"404": {
|
||
"description": "Объект отсутствует или недоступен",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"409": {
|
||
"description": "Конфликт",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"429": {
|
||
"description": "Ограничение частоты запросов",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"Retry-After": {
|
||
"description": "Положительное число секунд.",
|
||
"schema": {
|
||
"type": "integer",
|
||
"minimum": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"503": {
|
||
"description": "Зависимость недоступна",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"500": {
|
||
"description": "Неожиданная ошибка без внутренних деталей",
|
||
"headers": {
|
||
"X-Request-Id": {
|
||
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"X-Instance-Id": {
|
||
"description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.",
|
||
"schema": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
"content": {
|
||
"application/json": {
|
||
"schema": {
|
||
"$ref": "#/components/schemas/Error"
|
||
}
|
||
}
|
||
}
|
||
}
|
||
},
|
||
"parameters": [
|
||
{
|
||
"name": "attachment_id",
|
||
"in": "path",
|
||
"required": true,
|
||
"schema": {
|
||
"type": "string",
|
||
"format": "uuid"
|
||
}
|
||
},
|
||
{
|
||
"name": "variant",
|
||
"in": "query",
|
||
"schema": {
|
||
"type": "string",
|
||
"enum": [
|
||
"original"
|
||
],
|
||
"default": "original"
|
||
}
|
||
}
|
||
]
|
||
}
|
||
}
|
||
},
|
||
"components": {
|
||
"securitySchemes": {
|
||
"basicAuth": {
|
||
"type": "http",
|
||
"scheme": "basic"
|
||
},
|
||
"bearerAuth": {
|
||
"type": "http",
|
||
"scheme": "bearer",
|
||
"bearerFormat": "opaque session token"
|
||
}
|
||
},
|
||
"schemas": {
|
||
"Error": {
|
||
"type": "object",
|
||
"properties": {
|
||
"error": {
|
||
"type": "object",
|
||
"properties": {
|
||
"code": {
|
||
"type": "string",
|
||
"enum": [
|
||
"invalid_request",
|
||
"unauthorized",
|
||
"not_found",
|
||
"conflict",
|
||
"payload_too_large",
|
||
"unsupported_media_type",
|
||
"rate_limited",
|
||
"unavailable",
|
||
"internal_error"
|
||
]
|
||
},
|
||
"message": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
},
|
||
"request_id": {
|
||
"type": "string",
|
||
"minLength": 1
|
||
}
|
||
},
|
||
"required": [
|
||
"code",
|
||
"message",
|
||
"request_id"
|
||
],
|
||
"additionalProperties": false
|
||
}
|
||
},
|
||
"required": [
|
||
"error"
|
||
],
|
||
"additionalProperties": false,
|
||
"examples": [
|
||
{
|
||
"error": {
|
||
"code": "not_found",
|
||
"message": "Объект не найден",
|
||
"request_id": "example-request-id"
|
||
}
|
||
}
|
||
]
|
||
},
|
||
"Health": {
|
||
"type": "object",
|
||
"properties": {
|
||
"status": {
|
||
"type": "string",
|
||
"enum": [
|
||
"ok"
|
||
]
|
||
}
|
||
},
|
||
"required": [
|
||
"status"
|
||
],
|
||
"additionalProperties": false
|
||
},
|
||
"User": {
|
||
"type": "object",
|
||
"properties": {
|
||
"id": {
|
||
"type": "string",
|
||
"format": "uuid"
|
||
},
|
||
"username": {
|
||
"type": "string",
|
||
"pattern": "^[a-z0-9_]{3,32}$"
|
||
},
|
||
"display_name": {
|
||
"type": "string",
|
||
"minLength": 1,
|
||
"maxLength": 100
|
||
},
|
||
"created_at": {
|
||
"type": "string",
|
||
"format": "date-time"
|
||
}
|
||
},
|
||
"required": [
|
||
"id",
|
||
"username",
|
||
"display_name",
|
||
"created_at"
|
||
],
|
||
"additionalProperties": false,
|
||
"examples": [
|
||
{
|
||
"id": "11111111-1111-4111-8111-111111111111",
|
||
"username": "alice",
|
||
"display_name": "Алиса",
|
||
"created_at": "2026-09-01T12:00:00Z"
|
||
}
|
||
]
|
||
},
|
||
"CreateUser": {
|
||
"type": "object",
|
||
"properties": {
|
||
"username": {
|
||
"type": "string",
|
||
"pattern": "^[a-z0-9_]{3,32}$"
|
||
},
|
||
"display_name": {
|
||
"type": "string",
|
||
"minLength": 1,
|
||
"maxLength": 100
|
||
},
|
||
"password": {
|
||
"type": "string",
|
||
"minLength": 12,
|
||
"maxLength": 128,
|
||
"writeOnly": true
|
||
}
|
||
},
|
||
"required": [
|
||
"username",
|
||
"display_name",
|
||
"password"
|
||
],
|
||
"additionalProperties": false,
|
||
"examples": [
|
||
{
|
||
"username": "alice",
|
||
"display_name": "Алиса",
|
||
"password": "Example-only-not-a-real-secret-123"
|
||
}
|
||
]
|
||
},
|
||
"Chat": {
|
||
"type": "object",
|
||
"properties": {
|
||
"id": {
|
||
"type": "string",
|
||
"format": "uuid"
|
||
},
|
||
"title": {
|
||
"type": "string",
|
||
"minLength": 1,
|
||
"maxLength": 100
|
||
},
|
||
"member_ids": {
|
||
"type": "array",
|
||
"items": {
|
||
"type": "string",
|
||
"format": "uuid"
|
||
},
|
||
"minItems": 1,
|
||
"maxItems": 100,
|
||
"uniqueItems": true
|
||
},
|
||
"created_at": {
|
||
"type": "string",
|
||
"format": "date-time"
|
||
}
|
||
},
|
||
"required": [
|
||
"id",
|
||
"title",
|
||
"member_ids",
|
||
"created_at"
|
||
],
|
||
"additionalProperties": false,
|
||
"examples": [
|
||
{
|
||
"title": "Проект по ВНП",
|
||
"member_ids": [
|
||
"11111111-1111-4111-8111-111111111111",
|
||
"22222222-2222-4222-8222-222222222222"
|
||
],
|
||
"id": "33333333-3333-4333-8333-333333333333",
|
||
"created_at": "2026-09-01T12:00:00Z"
|
||
}
|
||
]
|
||
},
|
||
"CreateChat": {
|
||
"type": "object",
|
||
"properties": {
|
||
"title": {
|
||
"type": "string",
|
||
"minLength": 1,
|
||
"maxLength": 100
|
||
},
|
||
"member_ids": {
|
||
"type": "array",
|
||
"items": {
|
||
"type": "string",
|
||
"format": "uuid"
|
||
},
|
||
"minItems": 1,
|
||
"maxItems": 100,
|
||
"uniqueItems": true
|
||
}
|
||
},
|
||
"required": [
|
||
"title",
|
||
"member_ids"
|
||
],
|
||
"additionalProperties": false,
|
||
"examples": [
|
||
{
|
||
"title": "Проект по ВНП",
|
||
"member_ids": [
|
||
"11111111-1111-4111-8111-111111111111",
|
||
"22222222-2222-4222-8222-222222222222"
|
||
]
|
||
}
|
||
]
|
||
},
|
||
"Message": {
|
||
"type": "object",
|
||
"properties": {
|
||
"id": {
|
||
"type": "string",
|
||
"format": "uuid"
|
||
},
|
||
"chat_id": {
|
||
"type": "string",
|
||
"format": "uuid"
|
||
},
|
||
"sender_id": {
|
||
"type": "string",
|
||
"format": "uuid"
|
||
},
|
||
"text": {
|
||
"type": "string",
|
||
"maxLength": 4000
|
||
},
|
||
"created_at": {
|
||
"type": "string",
|
||
"format": "date-time"
|
||
},
|
||
"attachment_ids": {
|
||
"type": "array",
|
||
"items": {
|
||
"type": "string",
|
||
"format": "uuid"
|
||
},
|
||
"maxItems": 10,
|
||
"uniqueItems": true
|
||
}
|
||
},
|
||
"required": [
|
||
"id",
|
||
"chat_id",
|
||
"sender_id",
|
||
"text",
|
||
"created_at",
|
||
"attachment_ids"
|
||
],
|
||
"additionalProperties": false,
|
||
"anyOf": [
|
||
{
|
||
"properties": {
|
||
"text": {
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
{
|
||
"properties": {
|
||
"attachment_ids": {
|
||
"minItems": 1
|
||
}
|
||
}
|
||
}
|
||
],
|
||
"examples": [
|
||
{
|
||
"id": "44444444-4444-4444-8444-444444444444",
|
||
"chat_id": "33333333-3333-4333-8333-333333333333",
|
||
"sender_id": "11111111-1111-4111-8111-111111111111",
|
||
"text": "Привет, Боб!",
|
||
"created_at": "2026-09-01T12:00:00Z",
|
||
"attachment_ids": []
|
||
}
|
||
]
|
||
},
|
||
"CreateMessage": {
|
||
"type": "object",
|
||
"properties": {
|
||
"text": {
|
||
"type": "string",
|
||
"maxLength": 4000
|
||
},
|
||
"attachment_ids": {
|
||
"type": "array",
|
||
"items": {
|
||
"type": "string",
|
||
"format": "uuid"
|
||
},
|
||
"maxItems": 10,
|
||
"uniqueItems": true,
|
||
"default": []
|
||
}
|
||
},
|
||
"required": [
|
||
"text"
|
||
],
|
||
"additionalProperties": false,
|
||
"anyOf": [
|
||
{
|
||
"properties": {
|
||
"text": {
|
||
"minLength": 1
|
||
}
|
||
}
|
||
},
|
||
{
|
||
"properties": {
|
||
"attachment_ids": {
|
||
"minItems": 1
|
||
}
|
||
},
|
||
"required": [
|
||
"attachment_ids"
|
||
]
|
||
}
|
||
],
|
||
"examples": [
|
||
{
|
||
"text": "Привет, Боб!"
|
||
}
|
||
]
|
||
},
|
||
"ChatPage": {
|
||
"type": "object",
|
||
"properties": {
|
||
"items": {
|
||
"type": "array",
|
||
"items": {
|
||
"$ref": "#/components/schemas/Chat"
|
||
}
|
||
},
|
||
"next_cursor": {
|
||
"type": [
|
||
"string",
|
||
"null"
|
||
]
|
||
}
|
||
},
|
||
"required": [
|
||
"items",
|
||
"next_cursor"
|
||
],
|
||
"additionalProperties": false
|
||
},
|
||
"MessagePage": {
|
||
"type": "object",
|
||
"properties": {
|
||
"items": {
|
||
"type": "array",
|
||
"items": {
|
||
"$ref": "#/components/schemas/Message"
|
||
}
|
||
},
|
||
"next_cursor": {
|
||
"type": [
|
||
"string",
|
||
"null"
|
||
]
|
||
}
|
||
},
|
||
"required": [
|
||
"items",
|
||
"next_cursor"
|
||
],
|
||
"additionalProperties": false,
|
||
"examples": [
|
||
{
|
||
"items": [
|
||
{
|
||
"id": "44444444-4444-4444-8444-444444444444",
|
||
"chat_id": "33333333-3333-4333-8333-333333333333",
|
||
"sender_id": "11111111-1111-4111-8111-111111111111",
|
||
"text": "Привет, Боб!",
|
||
"created_at": "2026-09-01T12:00:00Z",
|
||
"attachment_ids": []
|
||
}
|
||
],
|
||
"next_cursor": null
|
||
}
|
||
]
|
||
},
|
||
"Session": {
|
||
"type": "object",
|
||
"properties": {
|
||
"token": {
|
||
"type": "string",
|
||
"minLength": 32
|
||
},
|
||
"token_type": {
|
||
"type": "string",
|
||
"const": "Bearer"
|
||
},
|
||
"expires_at": {
|
||
"type": "string",
|
||
"format": "date-time"
|
||
},
|
||
"user": {
|
||
"$ref": "#/components/schemas/User"
|
||
}
|
||
},
|
||
"required": [
|
||
"token",
|
||
"token_type",
|
||
"expires_at",
|
||
"user"
|
||
],
|
||
"additionalProperties": false
|
||
},
|
||
"Variant": {
|
||
"type": "object",
|
||
"properties": {
|
||
"name": {
|
||
"type": "string",
|
||
"enum": [
|
||
"thumbnail",
|
||
"crop",
|
||
"optimized"
|
||
]
|
||
},
|
||
"content_type": {
|
||
"type": "string",
|
||
"enum": [
|
||
"image/jpeg",
|
||
"image/png",
|
||
"image/webp"
|
||
]
|
||
},
|
||
"size_bytes": {
|
||
"type": "integer",
|
||
"minimum": 1
|
||
},
|
||
"width": {
|
||
"type": "integer",
|
||
"minimum": 1
|
||
},
|
||
"height": {
|
||
"type": "integer",
|
||
"minimum": 1
|
||
},
|
||
"sha256": {
|
||
"type": "string",
|
||
"pattern": "^[a-f0-9]{64}$"
|
||
}
|
||
},
|
||
"required": [
|
||
"name",
|
||
"content_type",
|
||
"size_bytes",
|
||
"width",
|
||
"height",
|
||
"sha256"
|
||
],
|
||
"additionalProperties": false
|
||
},
|
||
"Attachment": {
|
||
"type": "object",
|
||
"properties": {
|
||
"id": {
|
||
"type": "string",
|
||
"format": "uuid"
|
||
},
|
||
"chat_id": {
|
||
"type": "string",
|
||
"format": "uuid"
|
||
},
|
||
"owner_id": {
|
||
"type": "string",
|
||
"format": "uuid"
|
||
},
|
||
"filename": {
|
||
"type": "string",
|
||
"minLength": 1,
|
||
"maxLength": 255
|
||
},
|
||
"content_type": {
|
||
"type": "string",
|
||
"enum": [
|
||
"image/png",
|
||
"image/jpeg"
|
||
]
|
||
},
|
||
"size_bytes": {
|
||
"type": "integer",
|
||
"minimum": 1,
|
||
"maximum": 10485760
|
||
},
|
||
"sha256": {
|
||
"type": "string",
|
||
"pattern": "^[a-f0-9]{64}$"
|
||
},
|
||
"status": {
|
||
"type": "string",
|
||
"enum": [
|
||
"ready"
|
||
]
|
||
},
|
||
"variants": {
|
||
"type": "array",
|
||
"items": {
|
||
"$ref": "#/components/schemas/Variant"
|
||
}
|
||
},
|
||
"error_code": {
|
||
"type": [
|
||
"string",
|
||
"null"
|
||
]
|
||
},
|
||
"created_at": {
|
||
"type": "string",
|
||
"format": "date-time"
|
||
},
|
||
"updated_at": {
|
||
"type": "string",
|
||
"format": "date-time"
|
||
}
|
||
},
|
||
"required": [
|
||
"id",
|
||
"chat_id",
|
||
"owner_id",
|
||
"filename",
|
||
"content_type",
|
||
"size_bytes",
|
||
"sha256",
|
||
"status",
|
||
"variants",
|
||
"error_code",
|
||
"created_at",
|
||
"updated_at"
|
||
],
|
||
"additionalProperties": false
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
|
||
===== contracts/README.md =====
|
||
|
||
# Семантика API
|
||
|
||
Этот текст дополняет [openapi.json](openapi.json). Обязательный API соответствует уровню 3 текущей лабораторной. Факультативный crop или rate limiting не становятся обязательными только из-за наличия допустимого имени варианта или кода ошибки в схеме.
|
||
|
||
## Формат и ошибки
|
||
|
||
- JSON — UTF-8, `Content-Type: application/json`. UUID — строка; время — RFC 3339 UTC с `Z`, назначается сервером. Часы не считаются уникальным ID.
|
||
- Каждый ответ API, включая ошибки и health, содержит непустой `X-Request-Id`. Тело ошибки: `{"error":{"code":"invalid_request","message":"...","request_id":"..."}}`; `request_id` совпадает с заголовком. Сообщение ошибки не раскрывает stack trace, SQL, credentials или наличие чужого объекта.
|
||
- Обязательные строки не состоят только из пробельных символов. `username` строго `[a-z0-9_]{3,32}`, уникален; `display_name` — 1–100 Unicode code points. JSON с лишними полями или неверными типами — `400`; malformed JSON также `400`.
|
||
- `400 invalid_request` — неверные поля, UUID, cursor, limit; `401 unauthorized` — нет действительной идентификации/сессии; `404 not_found` — объекта нет или он чужой; `409 conflict` — username занят, повторный ключ с другим сообщением, объект ещё не готов; `413 payload_too_large`; `415 unsupported_media_type`; `429 rate_limited`; `503 unavailable`. Неожиданное исключение — `500 internal_error` без внутренних деталей.
|
||
- Сначала аутентификация, затем доступ к конкретному ресурсу. Любой аутентифицированный участник чата может читать его историю и вложения и писать в него; посторонний получает `404`. Списки содержат только доступные объекты. Не используйте `403` для раскрытия существования чужого чата.
|
||
- `GET /health/live` проверяет только жизнь процесса, возвращает `200 {"status":"ok"}`. `GET /health/ready` возвращает 200, если приложение может безопасно обслуживать обязательный синхронный путь; иначе 503 в общем формате ошибки. Какие зависимости критичны, зафиксируйте в отчёте; недоступность Grafana не должна останавливать API.
|
||
|
||
## Пользователи, чаты и сообщения
|
||
|
||
- `POST /users` публичен; возвращает `201 User`. Пароль/его hash и сессионные данные никогда не входят в User.
|
||
- `POST /chats` принимает title и явный список существующих `member_ids`, включая вызывающего. Дубликаты, неизвестные участники и отсутствие вызывающего — 400. Чат создаётся атомарно. GET списка чатов сортируется по `(created_at, id)` по возрастанию.
|
||
- Отправитель сообщения выводится из текущей идентификации, поле `sender_id` в запросе не принимается. Текст — до 4000 Unicode code points. Нельзя отправить пустой/пробельный текст без вложений.
|
||
- История использует keyset cursor: `(created_at, id)`, по возрастанию; `limit` — целое 1–100, по умолчанию 50. Ответ `{"items":[...],"next_cursor":null}`. Непустой cursor — непрозрачная для клиента строка; последний элемент предыдущей страницы не повторяется. Cursor привязан к ресурсу/запросу: от другого чата — 400. Изменять `limit` при продолжении можно.
|
||
- `next_cursor` равен null, если на момент чтения следующей записи нет. Гарантируется отсутствие повторов при обходе неизменной истории; snapshot изоляция между несколькими HTTP-запросами не требуется. При конкурентных вставках опишите выбранную семантику и ограничения часов.
|
||
- Подтверждённое сообщение видно следующему чтению через любую API-реплику. Допускается кэш, но он не должен возвращать устаревшую историю после успешной записи. Удаление и изменение участников в обязательный API не входят.
|
||
|
||
## Идентификация и сессии
|
||
|
||
**Lab1:** защищённые endpoint требуют `X-User-Id: <UUID существующего пользователя>`; отсутствие/неизвестный ID — 401. Это учебный выбор пользователя: любой клиент может выдать себя за другого.
|
||
|
||
**Lab2–7:** `POST /auth/sessions` принимает только `Authorization: Basic <base64(username:password)>`, без JSON body. Username ограничен ASCII; пароль кодируется UTF-8, 12–128 code points, двоеточие в пароле допустимо. Неверные credentials — одинаковый 401 и `WWW-Authenticate: Basic realm="messenger", charset="UTF-8"`.
|
||
|
||
Вход возвращает `201 {"token":"...","token_type":"Bearer","expires_at":"...Z","user":{...}}`. Токен — непрозрачное случайное значение, не username/UUID и не обязательный JWT; энтропия не менее 256 бит. Храните серверную сессию с expiry; TTL задаётся `SESSION_TTL_SECONDS`, по умолчанию 3600 (в тесте истечения можно 2). В обычном smoke TTL должен быть не менее 300.
|
||
|
||
Все защищённые endpoint принимают только `Authorization: Bearer <token>`. Истёкший/отозванный/неизвестный токен — 401 с `WWW-Authenticate: Bearer realm="messenger"`. Basic на бизнес-endpoint — 401. `X-User-Id` с lab2 игнорируется: он не меняет владельца сессии и сам по себе не даёт доступ. `DELETE /auth/sessions/current` отзывает текущий токен и возвращает 204 без тела; повтор с отозванным токеном — 401.
|
||
|
||
Пользователи, чаты, сообщения и ещё действительные сессии переживают перезапуск приложения и используемых хранилищ с сохранёнными volumes. TTL не продлевается из-за рестарта. Пароли уже с lab2 хешируются библиотечным password KDF (Argon2id, scrypt или bcrypt с учётом ограничений библиотеки), не SHA-256 и не plaintext. Если bcrypt не поддерживает весь диапазон UTF-8 паролей без усечения, выберите другую библиотечную схему. В lab7 обязателен Argon2id.
|
||
|
||
Basic — это кодирование, не шифрование. HTTP lab1–6 допускается только для локального изолированного стенда с синтетическими данными; для удалённой демонстрации нужен TLS. Lab7 использует HTTPS обязательно. См. [RFC 7617](https://www.rfc-editor.org/info/rfc7617/).
|
||
|
||
## Балансировка и повторная отправка (с lab3)
|
||
|
||
- Каждый ответ, созданный API, содержит `X-Instance-Id`; значение стабильно для жизни процесса. Ошибки соединения, созданные самим LB, могут не иметь этого заголовка. В lab7 используйте случайный alias реплики без раскрытия hostname/IP.
|
||
- Для POST сообщения обязателен `Idempotency-Key` (ASCII `[A-Za-z0-9._:-]{1,128}`). Нет/неверный ключ — 400. Область уникальности: текущий пользователь + HTTP-метод + путь чата + ключ.
|
||
- При повторе того же валидного JSON в течение 24 часов сервер возвращает тот же код 201 и то же Message. Порядок ключей JSON и отсутствующий `attachment_ids` вместо `[]` семантически равны. Другой body при том же ключе — 409. Разные пользователи/чаты могут использовать одинаковый ключ независимо.
|
||
- Одновременные повторы через разные реплики создают ровно одно сообщение. Повтор снова проверяет действительность сессии и доступ. Транзиентные 5xx не фиксируются как окончательный результат; побочный эффект и запись результата должны быть атомарны.
|
||
- Ключ обязателен только для сообщений. Самостоятельный retry загрузки файла или создания чата может создать ещё один объект; не добавляйте прозрачные повторы этих POST без расширения контракта.
|
||
|
||
## Вложения (с lab4)
|
||
|
||
- `POST /chats/{chat_id}/attachments?filename=photo.png`: сырые bytes одного PNG/JPEG; `Content-Type: image/png` или `image/jpeg`. Не multipart. Максимум **10 MiB = 10 485 760 байт**. MIME проверяется по содержимому; заведомо повреждённые/чужие форматы — 415, превышение bytes — 413. Не более 40 миллионов декодированных пикселей (превышение — 413). Устанавливайте лимит до полной распаковки изображения.
|
||
- `filename` — отображаемое имя (1–255 code points). Не используйте его как путь/ключ S3. Имя с `/`, `\`, NUL или управляющими символами — 400. Bucket приватен; object key генерирует сервер. Оригинал возвращается побайтно, его lowercase SHA-256 и размер соответствуют исходному файлу.
|
||
- Lab4 возвращает `201 Attachment` со `status=ready`, `variants=[]`, `error_code=null` только после сохранения оригинала и метаданных. Lab5–7 возвращают `202 Attachment` со снимком `status=queued`; готовность определяется последующим GET метаданных. Быстрый worker может закончить до первого GET — это нормально.
|
||
- Файл заранее привязан к чату. В POST сообщения добавляется `attachment_ids` (0–10 уникальных ID, по умолчанию []). Можно отправить `text=""` с хотя бы одним вложением. Все вложения должны принадлежать этому чату; чужое/неизвестное — 404. Любой участник может ссылаться на доступное вложение чата. Failed-вложение прикреплять нельзя (409); queued/processing с lab5 можно.
|
||
- `GET /attachments/{id}` и `/content` доступны только участникам чата. Download возвращает байты с истинным Content-Type, через авторизованный API, **без redirect** в обязательном контракте. Приватный bucket сам по себе не заменяет эту проверку. `variant` по умолчанию original. Для queued/processing content — 409; для failed — 409. Отсутствующий вариант ready-объекта — 404.
|
||
- В ready-метаданных `error_code=null`. В failed — краткий машинный код (например `invalid_image`, `processing_failed`, `retry_exhausted`), без stack trace. `size_bytes`, `sha256`, `content_type` всегда описывают оригинал; у вариантов отдельные поля. Публичный API не раскрывает ключи бакета, внутренние адреса и credentials.
|
||
- Прямой upload/download по временной подписи — факультативное расширение. Его дополняют ограничение срока/размера, уникальный ключ и подтверждение реально загруженного объекта; он не заменяет стандартный endpoint. Особенности подписанных URL: [S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html).
|
||
|
||
## Фоновая обработка (с lab5)
|
||
|
||
До 202 все байты приняты в **устойчивый staging**, а намерение обработать файл надёжно сохранено. HTTP-передача клиента не исчезает и не становится мгновенной. Staging — приватный S3-prefix либо общий persistent volume, доступный worker; локальная память/API ephemeral disk не подходит. Worker асинхронно переносит/публикует оригинал в конечный S3-prefix и создаёт варианты; если staging уже в S3, опишите эту границу честно.
|
||
|
||
Обязательный thumbnail: JPEG, изображение вписано в 256×256 с сохранением пропорций, без увеличения маленьких исходников, EXIF orientation применяется; alpha компонуется на белый. Размеры округляются вниз, минимум 1 px. Fixture 320×200 должен дать 256×160. Статус ready ставится после сохранения оригинала и thumbnail. Crop на 4: JPEG, центрированный квадрат 128×128 (для маленьких исходников допускается увеличение). Optimized на 4: WebP, вписан в 1280×1280 без увеличения, параметры качества и удаления EXIF документируются; не обещайте уменьшение каждого маленького файла.
|
||
|
||
Допустимые состояния и события описаны в `jobs.schema.json` и `attachment-states.md`. Доставка — at least once; обработка идемпотентна, повторы не размножают варианты. Финальные ошибки наблюдаемы, бесконечный немой retry недопустим. Обязательный smoke ждёт ready до 60 секунд; это бюджет локального smoke для одного файла при свободном worker, не универсальный production SLA. В очередь идут ссылки/ID, не бинарное содержимое.
|