Implement lab3 load balancing and failover
This commit is contained in:
@@ -0,0 +1,204 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const maxJSONBytes = 1 << 20
|
||||
|
||||
var (
|
||||
usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
uuidPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`)
|
||||
)
|
||||
|
||||
type apiError struct {
|
||||
status int
|
||||
code, message string
|
||||
challenge string // значение WWW-Authenticate для 401
|
||||
}
|
||||
|
||||
func fail(status int, code, message string) *apiError {
|
||||
return &apiError{status: status, code: code, message: message}
|
||||
}
|
||||
func invalid(message string) *apiError {
|
||||
return fail(http.StatusBadRequest, "invalid_request", message)
|
||||
}
|
||||
func notFound() *apiError {
|
||||
return fail(http.StatusNotFound, "not_found", "Объект не найден")
|
||||
}
|
||||
func unavailable() *apiError {
|
||||
return fail(http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен")
|
||||
}
|
||||
func unauthorized(challenge, message string) *apiError {
|
||||
e := fail(http.StatusUnauthorized, "unauthorized", message)
|
||||
e.challenge = challenge
|
||||
return e
|
||||
}
|
||||
|
||||
const (
|
||||
bearerChallenge = `Bearer realm="messenger"`
|
||||
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
)
|
||||
|
||||
func newUUID() string {
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
panic("crypto/rand failed")
|
||||
}
|
||||
b[6] = (b[6] & 0x0f) | 0x40
|
||||
b[8] = (b[8] & 0x3f) | 0x80
|
||||
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
|
||||
}
|
||||
|
||||
// formatTime — RFC 3339 UTC, всегда 6 знаков долей секунды (точность PostgreSQL).
|
||||
func formatTime(t time.Time) string { return t.UTC().Format("2006-01-02T15:04:05.000000Z") }
|
||||
|
||||
func validUUID(value string) (string, bool) {
|
||||
if !uuidPattern.MatchString(value) {
|
||||
return "", false
|
||||
}
|
||||
return strings.ToLower(value), true
|
||||
}
|
||||
|
||||
// cleanText: валидный UTF-8 без NUL (PostgreSQL не хранит \x00 в text).
|
||||
func cleanText(s string) bool { return utf8.ValidString(s) && !strings.ContainsRune(s, 0) }
|
||||
|
||||
func requiredString(value any, limit int, field string) (string, *apiError) {
|
||||
text, ok := value.(string)
|
||||
if !ok || text == "" || strings.TrimSpace(text) == "" || !cleanText(text) || utf8.RuneCountInString(text) > limit {
|
||||
return "", invalid("Некорректное поле " + field)
|
||||
}
|
||||
return text, nil
|
||||
}
|
||||
|
||||
func exactFields(body map[string]any, expected ...string) *apiError {
|
||||
if len(body) != len(expected) {
|
||||
return invalid("Неожиданные или отсутствующие поля")
|
||||
}
|
||||
for _, name := range expected {
|
||||
if _, ok := body[name]; !ok {
|
||||
return invalid("Неожиданные или отсутствующие поля")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func readJSON(r *http.Request) (map[string]any, *apiError) {
|
||||
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil || mediaType != "application/json" {
|
||||
return nil, fail(http.StatusUnsupportedMediaType, "unsupported_media_type", "Требуется application/json")
|
||||
}
|
||||
raw, err := io.ReadAll(io.LimitReader(r.Body, maxJSONBytes+1))
|
||||
if err != nil {
|
||||
return nil, invalid("Некорректное тело запроса")
|
||||
}
|
||||
if len(raw) > maxJSONBytes {
|
||||
return nil, fail(http.StatusRequestEntityTooLarge, "payload_too_large", "Слишком большой JSON")
|
||||
}
|
||||
if !utf8.Valid(raw) {
|
||||
return nil, invalid("Некорректный JSON")
|
||||
}
|
||||
decoder := json.NewDecoder(strings.NewReader(string(raw)))
|
||||
var body map[string]any
|
||||
if err := decoder.Decode(&body); err != nil || body == nil {
|
||||
return nil, invalid("Некорректный JSON")
|
||||
}
|
||||
var trailing any
|
||||
if err := decoder.Decode(&trailing); err != io.EOF {
|
||||
return nil, invalid("Некорректный JSON")
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, id string, status int, body any) {
|
||||
w.Header().Set("X-Request-Id", id)
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
enc := json.NewEncoder(w)
|
||||
enc.SetEscapeHTML(false)
|
||||
_ = enc.Encode(body)
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, id string, err *apiError) {
|
||||
if err.challenge != "" {
|
||||
w.Header().Set("WWW-Authenticate", err.challenge)
|
||||
}
|
||||
writeJSON(w, id, err.status, map[string]any{"error": map[string]string{"code": err.code, "message": err.message, "request_id": id}})
|
||||
}
|
||||
|
||||
func parsePage(r *http.Request) (int, string, *apiError) {
|
||||
query := r.URL.Query()
|
||||
if len(query["limit"]) > 1 || len(query["cursor"]) > 1 {
|
||||
return 0, "", invalid("Повторяющийся параметр пагинации")
|
||||
}
|
||||
limit := 50
|
||||
if values, exists := query["limit"]; exists {
|
||||
n, err := strconv.Atoi(values[0])
|
||||
if err != nil || n < 1 || n > 100 || strconv.Itoa(n) != values[0] {
|
||||
return 0, "", invalid("Некорректный limit")
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
if values, exists := query["cursor"]; exists {
|
||||
if values[0] == "" {
|
||||
return 0, "", invalid("Некорректный cursor")
|
||||
}
|
||||
return limit, values[0], nil
|
||||
}
|
||||
return limit, "", nil
|
||||
}
|
||||
|
||||
// cursor — непрозрачная для клиента строка: ключ (created_at, id) + тип списка + владелец
|
||||
// (id чата либо пользователя). Курсор другого ресурса отклоняется с 400.
|
||||
type cursor struct {
|
||||
Kind string `json:"k"`
|
||||
Owner string `json:"o"`
|
||||
Time string `json:"t"`
|
||||
ID string `json:"i"`
|
||||
}
|
||||
|
||||
func encodeCursor(kind, owner string, created time.Time, id string) string {
|
||||
raw, _ := json.Marshal(cursor{kind, owner, formatTime(created), id})
|
||||
return base64.RawURLEncoding.EncodeToString(raw)
|
||||
}
|
||||
|
||||
func decodeCursor(value, kind, owner string) (time.Time, string, *apiError) {
|
||||
raw, err := base64.RawURLEncoding.DecodeString(value)
|
||||
if err != nil {
|
||||
return time.Time{}, "", invalid("Некорректный cursor")
|
||||
}
|
||||
var fields map[string]any
|
||||
if json.Unmarshal(raw, &fields) != nil || len(fields) != 4 {
|
||||
return time.Time{}, "", invalid("Некорректный cursor")
|
||||
}
|
||||
for _, name := range []string{"k", "o", "t", "i"} {
|
||||
if _, ok := fields[name].(string); !ok {
|
||||
return time.Time{}, "", invalid("Некорректный cursor")
|
||||
}
|
||||
}
|
||||
c := cursor{fields["k"].(string), fields["o"].(string), fields["t"].(string), fields["i"].(string)}
|
||||
if c.Kind != kind || c.Owner != owner {
|
||||
return time.Time{}, "", invalid("Некорректный cursor")
|
||||
}
|
||||
id, ok := validUUID(c.ID)
|
||||
if !ok {
|
||||
return time.Time{}, "", invalid("Некорректный cursor")
|
||||
}
|
||||
t, err := time.Parse("2006-01-02T15:04:05.000000Z", c.Time)
|
||||
if err != nil {
|
||||
return time.Time{}, "", invalid("Некорректный cursor")
|
||||
}
|
||||
return t, id, nil
|
||||
}
|
||||
Reference in New Issue
Block a user