feat(nexxa): estado en su Postgres propio con Nexxa::Estado (motores archivo|pg), mutar atómico y dispensa en un paso; 1.7.0 (P335/F17)
Tests ADN / test (push) Canceled after 0s
Tests ADN / test (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-Authored-By: GEMMA <noreply@gemma.dtic>
This commit is contained in:
co-authored by
Claude Opus 5.5
GEMMA
parent
4df538283f
commit
84d51ed669
@@ -32,10 +32,11 @@ require 'json'
|
||||
require 'time'
|
||||
require_relative 'lib_cripto'
|
||||
require_relative 'lib_usos'
|
||||
require_relative 'lib_estado'
|
||||
|
||||
module Nexxa
|
||||
module Registro
|
||||
STATE_FILE = File.expand_path('registro.json', __dir__).freeze
|
||||
STATE_FILE = Estado.ruta('registro')
|
||||
|
||||
# Reserva corta de contención (P204/Fase3, D045 §8) — no asume agotamiento,
|
||||
# solo evita que 2 consumidores reciban la misma key mientras uno la está
|
||||
@@ -43,18 +44,18 @@ module Nexxa
|
||||
# aparte) si nadie reporta nada; self.reportar la renueva o la libera.
|
||||
RESERVA_TTL_SEGUNDOS = 600
|
||||
|
||||
# Estado vía Nexxa::Estado (P335/Fase 17): archivo o Postgres según NEXXA_ESTADO
|
||||
def self.leer
|
||||
if File.exist?(STATE_FILE)
|
||||
JSON.parse(File.read(STATE_FILE))
|
||||
else
|
||||
{ 'keys' => [] }
|
||||
end
|
||||
rescue JSON::ParserError
|
||||
{ 'keys' => [] }
|
||||
Estado.leer('registro', STATE_FILE, { 'keys' => [] })
|
||||
end
|
||||
|
||||
def self.guardar(state)
|
||||
File.write(STATE_FILE, JSON.pretty_generate(state) + "\n")
|
||||
Estado.guardar('registro', STATE_FILE, state)
|
||||
end
|
||||
|
||||
# Leer-modificar-guardar atómico (nexxa-http y nexxa comparten el registro)
|
||||
def self.mutar(&)
|
||||
Estado.mutar('registro', STATE_FILE, { 'keys' => [] }, &)
|
||||
end
|
||||
|
||||
# provider: "gemini"/"groq"/... ; identificador: ETIQUETA legible (ej. "gemini-01"),
|
||||
@@ -70,56 +71,61 @@ module Nexxa
|
||||
# error, ME-603). Pasar ultimo_uso explícito solo cuando se sabe que la key
|
||||
# SÍ se agotó en ese momento.
|
||||
def self.registrar(provider:, identificador:, cuenta_origen:, reset_segundos:, valor: nil, ultimo_uso: nil)
|
||||
state = leer
|
||||
ahora = Time.now
|
||||
disponible_desde = ultimo_uso ? (Time.parse(ultimo_uso) + reset_segundos).iso8601(3) : ahora.iso8601(3)
|
||||
ultimo_uso ||= ahora.iso8601(3)
|
||||
|
||||
valor_cifrado = valor ? cifrar(valor) : nil
|
||||
|
||||
existente = state['keys'].find { |k| k['provider'] == provider && k['identificador'] == identificador }
|
||||
if existente
|
||||
existente.merge!(
|
||||
'ultimo_uso' => ultimo_uso,
|
||||
'disponible_desde' => disponible_desde,
|
||||
'cuenta_origen' => cuenta_origen,
|
||||
'reset_segundos' => reset_segundos
|
||||
)
|
||||
existente['valor_cifrado'] = valor_cifrado if valor_cifrado
|
||||
else
|
||||
state['keys'] << {
|
||||
'provider' => provider,
|
||||
'identificador' => identificador,
|
||||
'cuenta_origen' => cuenta_origen,
|
||||
'reset_segundos' => reset_segundos,
|
||||
'ultimo_uso' => ultimo_uso,
|
||||
'ultimo_individuo' => nil,
|
||||
'disponible_desde' => disponible_desde,
|
||||
'valor_cifrado' => valor_cifrado,
|
||||
'activo' => true,
|
||||
'reservado_por' => nil,
|
||||
'reservado_hasta' => nil
|
||||
}
|
||||
mutar do |state|
|
||||
existente = state['keys'].find { |k| k['provider'] == provider && k['identificador'] == identificador }
|
||||
if existente
|
||||
existente.merge!(
|
||||
'ultimo_uso' => ultimo_uso,
|
||||
'disponible_desde' => disponible_desde,
|
||||
'cuenta_origen' => cuenta_origen,
|
||||
'reset_segundos' => reset_segundos
|
||||
)
|
||||
existente['valor_cifrado'] = valor_cifrado if valor_cifrado
|
||||
else
|
||||
state['keys'] << {
|
||||
'provider' => provider,
|
||||
'identificador' => identificador,
|
||||
'cuenta_origen' => cuenta_origen,
|
||||
'reset_segundos' => reset_segundos,
|
||||
'ultimo_uso' => ultimo_uso,
|
||||
'ultimo_individuo' => nil,
|
||||
'disponible_desde' => disponible_desde,
|
||||
'valor_cifrado' => valor_cifrado,
|
||||
'activo' => true,
|
||||
'reservado_por' => nil,
|
||||
'reservado_hasta' => nil
|
||||
}
|
||||
end
|
||||
state
|
||||
end
|
||||
guardar(state)
|
||||
state
|
||||
end
|
||||
|
||||
# Edita metadata de una key existente (P201/Fase3) — NUNCA el valor (eso no
|
||||
# se re-muestra, se reemplaza vía 'registrar' con un valor nuevo si hace
|
||||
# falta rotarlo). Cada parámetro es opcional: solo se actualiza lo pasado.
|
||||
def self.actualizar(provider:, identificador:, cuenta_origen: nil, reset_segundos: nil, activo: nil)
|
||||
state = leer
|
||||
entrada = state['keys'].find { |k| k['provider'] == provider && k['identificador'] == identificador }
|
||||
raise "Key no encontrada: #{provider}/#{identificador}" unless entrada
|
||||
|
||||
entrada['cuenta_origen'] = cuenta_origen unless cuenta_origen.nil?
|
||||
entrada['reset_segundos'] = reset_segundos unless reset_segundos.nil?
|
||||
entrada['activo'] = activo unless activo.nil?
|
||||
guardar(state)
|
||||
entrada = nil
|
||||
mutar do |state|
|
||||
entrada = buscar!(state, provider, identificador)
|
||||
entrada['cuenta_origen'] = cuenta_origen unless cuenta_origen.nil?
|
||||
entrada['reset_segundos'] = reset_segundos unless reset_segundos.nil?
|
||||
entrada['activo'] = activo unless activo.nil?
|
||||
state
|
||||
end
|
||||
entrada
|
||||
end
|
||||
|
||||
def self.buscar!(state, provider, identificador)
|
||||
state['keys'].find { |k| k['provider'] == provider && k['identificador'] == identificador } ||
|
||||
raise("Key no encontrada: #{provider}/#{identificador}")
|
||||
end
|
||||
|
||||
IDENTIFICADOR_VALIDO = /\A[a-z0-9][a-z0-9._-]{0,63}\z/.freeze
|
||||
|
||||
# Cambia el identificador de una key (P335/Fase 13). Único dentro del provider; rechazado mientras esté RESERVADA
|
||||
@@ -130,16 +136,17 @@ module Nexxa
|
||||
raise "Identificador inválido: '#{a}' (minúsculas, números, punto, guion o guion bajo)" unless a.match?(IDENTIFICADOR_VALIDO)
|
||||
return leer['keys'].find { |k| k['provider'] == provider && k['identificador'] == de } if a == de
|
||||
|
||||
state = leer
|
||||
entrada = state['keys'].find { |k| k['provider'] == provider && k['identificador'] == de }
|
||||
raise "Key no encontrada: #{provider}/#{de}" unless entrada
|
||||
raise "Ya existe #{provider}/#{a}" if state['keys'].any? { |k| k['provider'] == provider && k['identificador'] == a }
|
||||
if entrada['reservado_hasta'] && Time.parse(entrada['reservado_hasta']) > ahora
|
||||
raise "#{provider}/#{de} está reservada por #{entrada['reservado_por']}: esperá a que la libere para renombrarla"
|
||||
end
|
||||
entrada = nil
|
||||
mutar do |state|
|
||||
entrada = buscar!(state, provider, de)
|
||||
raise "Ya existe #{provider}/#{a}" if state['keys'].any? { |k| k['provider'] == provider && k['identificador'] == a }
|
||||
if entrada['reservado_hasta'] && Time.parse(entrada['reservado_hasta']) > ahora
|
||||
raise "#{provider}/#{de} está reservada por #{entrada['reservado_por']}: esperá a que la libere para renombrarla"
|
||||
end
|
||||
|
||||
entrada['identificador'] = a
|
||||
guardar(state)
|
||||
entrada['identificador'] = a
|
||||
state
|
||||
end
|
||||
Nexxa::Usos.registrar(provider: provider, identificador: a, individuo: usuario ? "web:#{usuario}" : 'web',
|
||||
en: ahora, evento: "renombrada (antes #{de})")
|
||||
entrada
|
||||
@@ -148,9 +155,11 @@ module Nexxa
|
||||
# Elimina una key del registro — destructivo, sin deshacer (P201/Fase3).
|
||||
# No borra su historial en lib_usos.rb (log append-only, queda como evidencia).
|
||||
def self.eliminar(provider:, identificador:)
|
||||
state = leer
|
||||
existia = state['keys'].reject! { |k| k['provider'] == provider && k['identificador'] == identificador }
|
||||
guardar(state) if existia
|
||||
existia = nil
|
||||
mutar do |state|
|
||||
existia = state['keys'].reject! { |k| k['provider'] == provider && k['identificador'] == identificador }
|
||||
state
|
||||
end
|
||||
!existia.nil?
|
||||
end
|
||||
|
||||
@@ -177,18 +186,43 @@ module Nexxa
|
||||
# self.reportar(estado: 'agotada'), con la señal del consumidor. Se llama
|
||||
# automático al dispensar (server.rb, GET /disponible).
|
||||
def self.reservar(provider:, identificador:, individuo:)
|
||||
state = leer
|
||||
entrada = state['keys'].find { |k| k['provider'] == provider && k['identificador'] == identificador }
|
||||
raise "Key no encontrada: #{provider}/#{identificador}" unless entrada
|
||||
|
||||
ahora = Time.now
|
||||
entrada = nil
|
||||
mutar do |state|
|
||||
entrada = aplicar_reserva(buscar!(state, provider, identificador), individuo, ahora)
|
||||
state
|
||||
end
|
||||
Nexxa::Usos.registrar(provider: provider, identificador: identificador, individuo: individuo, en: ahora, evento: 'dispensada')
|
||||
entrada
|
||||
end
|
||||
|
||||
# Elegir la key libre y reservarla en UN paso atómico (P335/Fase 17). Antes se elegía (leer) y se reservaba después
|
||||
# (otro leer/guardar): dos consumidores simultáneos podían recibir la misma key. Candidatas: las refs de un pool
|
||||
# o todas las de un provider. Una key solo-metadata (sin valor_cifrado, D045 §9) se devuelve SIN reservar para que
|
||||
# el llamador responda sin_valor_migrado como antes. => entrada (con valor_cifrado) o nil si no hay libre.
|
||||
def self.reservar_libre(individuo:, refs: nil, provider: nil)
|
||||
ahora = Time.now
|
||||
elegida = nil
|
||||
mutar do |state|
|
||||
candidatas = state['keys'].select do |k|
|
||||
refs ? Array(refs).include?("#{k['provider']}/#{k['identificador']}") : k['provider'] == provider
|
||||
end
|
||||
elegida = elegir_libre(candidatas)
|
||||
aplicar_reserva(elegida, individuo, ahora) if elegida && elegida['valor_cifrado']
|
||||
state
|
||||
end
|
||||
if elegida && elegida['valor_cifrado']
|
||||
Nexxa::Usos.registrar(provider: elegida['provider'], identificador: elegida['identificador'], individuo: individuo,
|
||||
en: ahora, evento: 'dispensada')
|
||||
end
|
||||
elegida
|
||||
end
|
||||
|
||||
def self.aplicar_reserva(entrada, individuo, ahora)
|
||||
entrada['ultimo_uso'] = ahora.iso8601(3)
|
||||
entrada['ultimo_individuo'] = individuo
|
||||
entrada['reservado_por'] = individuo
|
||||
entrada['reservado_hasta'] = (ahora + RESERVA_TTL_SEGUNDOS).iso8601(3)
|
||||
guardar(state)
|
||||
|
||||
Nexxa::Usos.registrar(provider: provider, identificador: identificador, individuo: individuo, en: ahora, evento: 'dispensada')
|
||||
entrada
|
||||
end
|
||||
|
||||
@@ -208,57 +242,67 @@ module Nexxa
|
||||
# 2026-10-01 19:46: un 429 por minuto reportado como agotada bloqueó el pool compartido y el consumidor no podía
|
||||
# revertirlo (409). Solo el autor del reporte: nadie libera lo que bloqueó otro.
|
||||
def self.reportar(provider:, identificador:, individuo:, estado:, liberar_en_segundos: nil, motivo: nil)
|
||||
state = leer
|
||||
entrada = state['keys'].find { |k| k['provider'] == provider && k['identificador'] == identificador }
|
||||
raise "Key no encontrada: #{provider}/#{identificador}" unless entrada
|
||||
|
||||
ahora = Time.now
|
||||
if estado == 'liberada' && entrada['reservado_por'] != individuo && revertible_por?(entrada, individuo, ahora)
|
||||
entrada['disponible_desde'] = ahora.iso8601(3)
|
||||
entrada['agotada_por'] = nil
|
||||
guardar(state)
|
||||
Nexxa::Usos.registrar(provider: provider, identificador: identificador, individuo: individuo, en: ahora, evento: 'revertida')
|
||||
return entrada
|
||||
end
|
||||
raise "Key #{provider}/#{identificador} no está reservada por #{individuo}" unless entrada['reservado_por'] == individuo
|
||||
entrada = nil
|
||||
evento = nil
|
||||
mutar do |state| # sin 'return' adentro (P335/Fase 17): el bloque es una transacción
|
||||
entrada = buscar!(state, provider, identificador)
|
||||
if estado == 'liberada' && entrada['reservado_por'] != individuo && revertible_por?(entrada, individuo, ahora)
|
||||
entrada['disponible_desde'] = ahora.iso8601(3)
|
||||
entrada['agotada_por'] = nil
|
||||
evento = 'revertida'
|
||||
else
|
||||
raise "Key #{provider}/#{identificador} no está reservada por #{individuo}" unless entrada['reservado_por'] == individuo
|
||||
|
||||
evento = aplicar_reporte(entrada, estado, individuo, ahora, liberar_en_segundos, motivo)
|
||||
end
|
||||
state
|
||||
end
|
||||
Nexxa::Usos.registrar(provider: provider, identificador: identificador, individuo: individuo, en: ahora, evento: evento) if evento
|
||||
entrada
|
||||
end
|
||||
|
||||
# => evento de usos a registrar ('agotada') o nil
|
||||
def self.aplicar_reporte(entrada, estado, individuo, ahora, liberar_en_segundos, motivo)
|
||||
case estado
|
||||
when 'sana'
|
||||
entrada['reservado_hasta'] = (ahora + RESERVA_TTL_SEGUNDOS).iso8601(3)
|
||||
nil
|
||||
when 'liberada'
|
||||
entrada['reservado_por'] = nil
|
||||
entrada['reservado_hasta'] = nil
|
||||
nil
|
||||
when 'agotada'
|
||||
reset_segundos = entrada['reset_segundos']
|
||||
raise "Key #{provider}/#{identificador} sin reset_segundos persistido — no se puede reportar agotada" unless reset_segundos
|
||||
unless reset_segundos
|
||||
raise "Key #{entrada['provider']}/#{entrada['identificador']} sin reset_segundos persistido — no se puede reportar agotada"
|
||||
end
|
||||
|
||||
entrada['disponible_desde'] = (ahora + (liberar_en_segundos || reset_segundos)).iso8601(3)
|
||||
entrada['agotada_por'] = individuo
|
||||
entrada['motivo_agotada'] = motivo.to_s[0, 200] unless motivo.to_s.empty?
|
||||
entrada['reservado_por'] = nil
|
||||
entrada['reservado_hasta'] = nil
|
||||
Nexxa::Usos.registrar(provider: provider, identificador: identificador, individuo: individuo, en: ahora, evento: 'agotada')
|
||||
'agotada'
|
||||
else
|
||||
raise "estado inválido: #{estado} (esperado: sana|liberada|agotada)"
|
||||
end
|
||||
guardar(state)
|
||||
entrada
|
||||
end
|
||||
|
||||
# Liberación por un ADMIN desde nexxa-web (P335/Fase 7): la key queda disponible ya, sin reserva ni marca de
|
||||
# agotada, sea quien sea que la bloqueó. El rastro queda en usos ('liberada-admin', con el usuario de la web).
|
||||
def self.liberar_admin(provider:, identificador:, usuario:)
|
||||
state = leer
|
||||
entrada = state['keys'].find { |k| k['provider'] == provider && k['identificador'] == identificador }
|
||||
raise "Key no encontrada: #{provider}/#{identificador}" unless entrada
|
||||
|
||||
ahora = Time.now
|
||||
entrada['disponible_desde'] = ahora.iso8601(3) if Time.parse(entrada['disponible_desde']) > ahora
|
||||
entrada['reservado_por'] = nil
|
||||
entrada['reservado_hasta'] = nil
|
||||
entrada['agotada_por'] = nil
|
||||
entrada['motivo_agotada'] = nil
|
||||
guardar(state)
|
||||
entrada = nil
|
||||
mutar do |state|
|
||||
entrada = buscar!(state, provider, identificador)
|
||||
entrada['disponible_desde'] = ahora.iso8601(3) if Time.parse(entrada['disponible_desde']) > ahora
|
||||
entrada['reservado_por'] = nil
|
||||
entrada['reservado_hasta'] = nil
|
||||
entrada['agotada_por'] = nil
|
||||
entrada['motivo_agotada'] = nil
|
||||
state
|
||||
end
|
||||
Nexxa::Usos.registrar(provider: provider, identificador: identificador, individuo: "web:#{usuario}", en: ahora,
|
||||
evento: 'liberada-admin')
|
||||
entrada
|
||||
|
||||
Reference in New Issue
Block a user