XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEServerManager

【Java】我的世界XFE服务器管理器

公开
关注 0 Fork 0 Star 0
UTF-8
package com.xfestudio.xfeservermanager.infra.http;

import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Supplier;

/** Bounded same-process idempotency cache for mutating HTTP requests. */
final class IdempotencyRegistry {
    private final int maximumEntries;
    private final Duration lifetime;
    private final Clock clock;
    private final LinkedHashMap<Key, Entry> entries = new LinkedHashMap<>(64, 0.75f, true);

    IdempotencyRegistry(int maximumEntries, Duration lifetime, Clock clock) {
        if (maximumEntries < 1 || lifetime.isNegative() || lifetime.isZero()) {
            throw new IllegalArgumentException("invalid idempotency cache configuration");
        }
        this.maximumEntries = maximumEntries;
        this.lifetime = lifetime;
        this.clock = Objects.requireNonNull(clock, "clock");
    }

    CompletionStage<?> execute(
            UUID accountId,
            String method,
            String path,
            String idempotencyKey,
            String fingerprint,
            Supplier<? extends CompletionStage<?>> operation) {
        Objects.requireNonNull(operation, "operation");
        Key key = new Key(accountId, method, path, idempotencyKey);
        Entry created;
        synchronized (entries) {
            Instant now = clock.instant();
            evict(now);
            Entry existing = entries.get(key);
            if (existing != null) {
                if (!existing.fingerprint().equals(fingerprint)) {
                    throw new IdempotencyConflictException();
                }
                return existing.result();
            }
            makeRoom();
            created = new Entry(fingerprint, now.plus(lifetime), new CompletableFuture<>());
            entries.put(key, created);
        }

        try {
            operation.get().whenComplete((value, failure) -> {
                if (failure == null) {
                    created.result().complete(value);
                } else {
                    created.result().completeExceptionally(failure);
                }
            });
        } catch (RuntimeException failure) {
            synchronized (entries) {
                entries.remove(key, created);
            }
            throw failure;
        }
        return created.result();
    }

    private void evict(Instant now) {
        entries.entrySet().removeIf(entry ->
                !now.isBefore(entry.getValue().expiresAt()) && entry.getValue().result().isDone());
    }

    private void makeRoom() {
        if (entries.size() >= maximumEntries) {
            // A completed result remains part of the idempotency guarantee until its advertised
            // lifetime expires. Evicting it early would let the same destructive request execute
            // again under load; reject new unique keys instead.
            throw new IdempotencyCapacityException();
        }
    }

    private record Key(UUID accountId, String method, String path, String idempotencyKey) { }

    private record Entry(
            String fingerprint, Instant expiresAt, CompletableFuture<Object> result) { }

    static final class IdempotencyConflictException extends RuntimeException {
        private static final long serialVersionUID = 1L;

        private IdempotencyConflictException() {
            super("the Idempotency-Key was already used with a different request");
        }
    }

    static final class IdempotencyCapacityException extends RuntimeException {
        private static final long serialVersionUID = 1L;

        private IdempotencyCapacityException() {
            super("too many idempotent operations are still in progress");
        }
    }
}