Volver al índice
src/main/java/ar/com/companeros/decision/PromotionLedger.java
package ar.com.companeros.decision;
import com.google.gson.JsonObject;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.time.Instant;
import java.util.Set;
/** Contabilidad compartida de tokens promocionales; no reemplaza el registro de dólares. */
final class PromotionLedger implements AutoCloseable {
record State(String windowId, Instant expiresAt, long usedTokens, long reservedTokens) { }
private final Path file;
private FileChannel channel;
private FileLock lock;
PromotionLedger(Path file) { this.file = file.toAbsolutePath().normalize(); }
// Un único controlador puede reservar esta cuota. Las reservas de otro arranque no se liberan.
State load() throws IOException {
checkPath();
Path lockFile = file.resolveSibling("promotion-usage.lock");
if (Files.isSymbolicLink(lockFile)) throw new IOException("Bloqueo promocional inválido");
channel = FileChannel.open(lockFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
try { lock = channel.tryLock(); }
catch (RuntimeException failure) { close(); throw new IOException("Cuota promocional ya utilizada", failure); }
if (lock == null) { close(); throw new IOException("Cuota promocional ya utilizada"); }
if (!Files.exists(file, LinkOption.NOFOLLOW_LINKS)) return null;
if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS) || Files.size(file) > 16_384)
throw new IOException("Registro promocional inválido");
try {
JsonObject data = DecisionCodec.strictObject(Files.readString(file, StandardCharsets.UTF_8), 16_384);
if (!data.keySet().equals(Set.of("schemaVersion", "windowId", "expiresAt", "usedTokens", "reservedTokens"))
|| data.get("schemaVersion").getAsBigDecimal().intValueExact() != 1)
throw new IllegalArgumentException("Formato promocional inválido");
long used = data.get("usedTokens").getAsBigDecimal().longValueExact();
long reserved = data.get("reservedTokens").getAsBigDecimal().longValueExact();
checked(used, reserved);
return new State(data.get("windowId").getAsString(), Instant.parse(data.get("expiresAt").getAsString()), used, reserved);
} catch (RuntimeException failure) { throw new IOException("Registro promocional inválido", failure); }
}
// Confirmar la reserva antes del HTTP; una caída deja el saldo conservador en disco.
void save(State state) throws IOException {
checked(state.usedTokens(), state.reservedTokens()); checkPath();
if (lock == null || !lock.isValid()) throw new IOException("Cuota promocional sin bloqueo");
JsonObject data = new JsonObject(); data.addProperty("schemaVersion", 1);
data.addProperty("windowId", state.windowId()); data.addProperty("expiresAt", state.expiresAt().toString());
data.addProperty("usedTokens", state.usedTokens()); data.addProperty("reservedTokens", state.reservedTokens());
Path temporary = Files.createTempFile(file.getParent(), "promotion-usage-", ".tmp");
try {
Files.writeString(temporary, data + System.lineSeparator(), StandardCharsets.UTF_8);
try (FileChannel output = FileChannel.open(temporary, StandardOpenOption.WRITE)) { output.force(true); }
try { Files.move(temporary, file, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); }
catch (java.nio.file.AtomicMoveNotSupportedException unsupported) {
Files.move(temporary, file, StandardCopyOption.REPLACE_EXISTING);
}
} finally { Files.deleteIfExists(temporary); }
}
private void checkPath() throws IOException {
Files.createDirectories(file.getParent());
for (Path current = file.getParent(); current != null; current = current.getParent()) {
if (Files.isSymbolicLink(current)) throw new IOException("Ruta promocional inválida");
}
if (Files.isSymbolicLink(file)) throw new IOException("Registro promocional enlazado");
}
private static void checked(long used, long reserved) {
if (used < 0 || reserved < 0) throw new IllegalArgumentException("Contador promocional negativo");
Math.addExact(used, reserved);
}
@Override public void close() {
try { if (lock != null) lock.release(); } catch (IOException ignored) { }
try { if (channel != null) channel.close(); } catch (IOException ignored) { }
lock = null; channel = null;
}
}