package com.zksy.video.lifecycle; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.ruoyi.wvp.gb28181.bean.SsrcTransaction; import com.ruoyi.wvp.gb28181.session.SipInviteSessionManager; import com.ruoyi.wvp.service.bean.SSRCInfo; import org.springframework.data.redis.core.RedisOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SessionCallback; import org.springframework.stereotype.Component; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.function.UnaryOperator; /** * Durable stop evidence and allocation fencing, shared by all API instances (not serverId scoped). * A missing snapshot is UNKNOWN, not stopped. No TTL: unknown dispatches must not unlock a name. * update runs against a detached typed snapshot under Redis WATCH/MULTI/EXEC; null rejects a change. * An aborted CAS returns null, never success. Exceptions (including ambiguous EXEC) propagate. * Callers must never dispatch external I/O inside an update, nor use a local cache as evidence. */ @Component public class VideoStopReceipts { private final RedisTemplate redis; private final ObjectMapper json = new ObjectMapper(); public VideoStopReceipts(RedisTemplate redis) { this.redis = Objects.requireNonNull(redis); } public enum RtpState { INTENT, CREATING, OPEN, CLOSING, CLOSED, NEVER_CREATED } public static class Allocation { public String token; public String ssrc; /** Device-chosen SSRC after a real renegotiation; the pool number above stays the return identity. */ public String negotiatedSsrc; /** The pre-existing legacy path already returned the pool number while negotiating. */ public boolean poolReturned; public boolean poolTracked; public boolean externalSsrc; public int port; public RtpState state; public String callId; public SSRCInfo info(String stream) { return new SSRCInfo(port, ssrc, "rtp", stream, token); } public boolean matches(SSRCInfo info) { return info != null && Objects.equals(token, info.getTimeOutTaskKey()) && "rtp".equals(info.getApp()) && (Objects.equals(ssrc, info.getSsrc()) || (negotiatedSsrc != null && Objects.equals(negotiatedSsrc, info.getSsrc()))); } /** Pool return always uses the originally allocated number, never the negotiated one. */ public String poolSsrc() { return ssrc; } public boolean terminal() { return state == RtpState.CLOSED || state == RtpState.NEVER_CREATED; } } public static class Play { public String deviceId; public Integer channelId; public String channelCode; public String allocationToken; /** Frozen allocation identity retained even when the legacy name is allocated again. */ public Allocation allocation; public boolean inviteSent; public boolean cancelled; /** Original dialog is never discarded, even after the live session registry removes it. */ public SsrcTransaction dialog; } public static class Snapshot { public String nodeId; public String stream; public Allocation allocation; /** managed uses stream as key; adoption uses its full UUID capability. */ public Map plays = new LinkedHashMap<>(); /** Ordinary legacy OPEN is provenance, not a lease. Adoption and uncertain I/O fence reuse. */ public boolean canReplaceAllocation() { if (allocation == null) return true; if (stream.startsWith("managed_")) return false; return allocation.terminal() || (allocation.state == RtpState.OPEN && allocation.callId == null && plays.values().stream().noneMatch(play -> Objects.equals(play.allocationToken, allocation.token))); } } public Snapshot read(String nodeId, String stream) { Snapshot snapshot = decode(redis.opsForValue().get(key(nodeId, stream))); return snapshot != null && Objects.equals(nodeId, snapshot.nodeId) ? snapshot : null; } /** Record a real device renegotiation without changing the original pool number. * Only the holder of the original allocation token may add it. */ public boolean recordNegotiatedSsrc(String nodeId, String stream, String allocationToken, String poolSsrc, String negotiatedSsrc) { if (nodeId == null || stream == null || allocationToken == null || negotiatedSsrc == null) return false; return update(nodeId, stream, snapshot -> { Allocation allocation = snapshot.allocation; if (allocation == null || !Objects.equals(allocation.token, allocationToken)) return null; if (poolSsrc != null && !Objects.equals(allocation.ssrc, poolSsrc)) return null; if (allocation.negotiatedSsrc != null && !Objects.equals(allocation.negotiatedSsrc, negotiatedSsrc)) return null; allocation.negotiatedSsrc = negotiatedSsrc; return snapshot; }) != null; } /** Legacy negotiation happens before any stop receipt exists; create the original allocation * from the typed handle and remember that its pool number was already returned by that path. */ public boolean recordNegotiatedSsrc(String nodeId, String stream, SSRCInfo original, String negotiatedSsrc, boolean poolAlreadyReturned) { if (nodeId == null || stream == null || original == null || original.getTimeOutTaskKey() == null || original.getSsrc() == null || negotiatedSsrc == null || !"rtp".equals(original.getApp())) return false; return update(nodeId, stream, snapshot -> { Allocation allocation = snapshot.allocation; if (allocation == null) { allocation = new Allocation(); allocation.token = original.getTimeOutTaskKey(); allocation.ssrc = original.getSsrc(); allocation.port = original.getPort(); allocation.state = RtpState.OPEN; snapshot.allocation = allocation; } if (!Objects.equals(allocation.token, original.getTimeOutTaskKey()) || !Objects.equals(allocation.ssrc, original.getSsrc())) return null; if (allocation.negotiatedSsrc != null && !Objects.equals(allocation.negotiatedSsrc, negotiatedSsrc)) return null; allocation.negotiatedSsrc = negotiatedSsrc; allocation.poolReturned = allocation.poolReturned || poolAlreadyReturned; return snapshot; }) != null; } /** Retain the original managed dialog before an automatic/late BYE can erase the live index. */ public boolean retainDialog(SsrcTransaction expected) { if (expected == null || expected.getMediaServerId() == null || expected.getStream() == null || !expected.getStream().matches("managed_[0-9a-fA-F]{32}") || !"rtp".equals(expected.getApp()) || expected.getCallId() == null || expected.getSipTransactionInfo() == null || !Objects.equals(expected.getCallId(), expected.getSipTransactionInfo().getCallId()) || expected.getSipTransactionInfo().getFromTag() == null || expected.getSipTransactionInfo().getToTag() == null) return false; return update(expected.getMediaServerId(), expected.getStream(), snapshot -> { Play play = snapshot.plays.get(expected.getStream()); if (play == null || snapshot.allocation == null || !Objects.equals(snapshot.allocation.ssrc, expected.getSsrc()) || !Objects.equals(play.deviceId, expected.getDeviceId()) || !Objects.equals(play.channelId, expected.getChannelId()) || (play.dialog != null && !SipInviteSessionManager.sameDialog(play.dialog, expected))) return null; play.dialog = expected; play.inviteSent = true; return snapshot; }) != null; } public Snapshot update(String nodeId, String stream, UnaryOperator change) { final String key = key(nodeId, stream); // A conflict does not entitle the caller to repeat a name-close; only a committed transition does. return redis.execute(new SessionCallback() { @Override @SuppressWarnings({"unchecked", "rawtypes"}) public Snapshot execute(RedisOperations operations) { RedisOperations ops = operations; ops.watch(key); boolean transaction = false; try { Snapshot before = decode(ops.opsForValue().get(key)); if (before != null && !Objects.equals(nodeId, before.nodeId)) return null; Snapshot proposed = before == null ? new Snapshot() : decode(encode(before)); proposed.nodeId = nodeId; proposed.stream = stream; Snapshot next = change.apply(proposed); if (next == null) return null; validate(before, next, nodeId, stream); String encoded = encode(next); ops.multi(); transaction = true; ops.opsForValue().set(key, encoded); List committed = ops.exec(); transaction = false; if (committed == null || committed.isEmpty()) return null; for (Object result : committed) { if (result == null || Boolean.FALSE.equals(result)) throw new IllegalStateException("Receipt write not acknowledged"); if (result instanceof RuntimeException) throw (RuntimeException) result; if (result instanceof Throwable) throw new IllegalStateException("Receipt write failed", (Throwable) result); } return decode(encoded); } finally { if (transaction) ops.discard(); else ops.unwatch(); } } }); } private void validate(Snapshot old, Snapshot next, String nodeId, String stream) { if (!Objects.equals(nodeId, next.nodeId) || !Objects.equals(stream, next.stream) || next.plays == null) throw new IllegalArgumentException("Receipt identity cannot change"); Allocation a = old == null ? null : old.allocation, b = next.allocation; if (b != null && (b.token == null || b.ssrc == null || b.state == null)) throw new IllegalArgumentException("Allocation requires SSRC and timeout token"); if (a != null) { if (b == null) throw new IllegalArgumentException("Allocation evidence cannot disappear"); if (!Objects.equals(a.token, b.token)) { if (!old.canReplaceAllocation() || b.state != RtpState.INTENT) throw new IllegalArgumentException("Previous allocation is not closed"); } else if (!Objects.equals(a.ssrc, b.ssrc) || a.poolTracked != b.poolTracked || a.externalSsrc != b.externalSsrc || (a.negotiatedSsrc != null && !Objects.equals(a.negotiatedSsrc, b.negotiatedSsrc)) || (a.poolReturned && !b.poolReturned) || !transition(a.state, b.state) || (a.port != b.port && !(a.state == RtpState.CREATING && b.state == RtpState.OPEN)) || (a.callId != null && !Objects.equals(a.callId, b.callId))) { throw new IllegalArgumentException("Allocation evidence cannot regress or change owner"); } } if (old == null) return; for (Map.Entry entry : old.plays.entrySet()) { Play p = entry.getValue(), q = next.plays.get(entry.getKey()); if (q == null || !Objects.equals(p.deviceId, q.deviceId) || !Objects.equals(p.channelId, q.channelId) || !Objects.equals(p.channelCode, q.channelCode) || (p.inviteSent && !q.inviteSent) || (p.cancelled && !q.cancelled) || (p.allocationToken != null && !Objects.equals(p.allocationToken, q.allocationToken)) || (p.allocation != null && (q.allocation == null || !Objects.equals(p.allocation.token, q.allocation.token) || !Objects.equals(p.allocation.ssrc, q.allocation.ssrc) || p.allocation.port != q.allocation.port || !Objects.equals(p.allocation.negotiatedSsrc, q.allocation.negotiatedSsrc) || (p.allocation.poolReturned && !q.allocation.poolReturned) || p.allocation.poolTracked != q.allocation.poolTracked || p.allocation.externalSsrc != q.allocation.externalSsrc)) || (p.dialog != null && !SipInviteSessionManager.sameDialog(p.dialog, q.dialog))) throw new IllegalArgumentException("Original play evidence cannot regress or change dialog"); } } private boolean transition(RtpState old, RtpState next) { if (old == next) return true; switch (old) { case INTENT: return next == RtpState.CREATING || next == RtpState.NEVER_CREATED; case CREATING: return next == RtpState.OPEN; case OPEN: return next == RtpState.CLOSING; case CLOSING: return next == RtpState.CLOSED; default: return false; } } private String key(String nodeId, String stream) { if (nodeId == null || stream == null) throw new IllegalArgumentException("Original node and stream required"); Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); // Managed UUIDs are single-use even if an API request later names a different node. String owner = stream.matches("managed_[0-9a-fA-F]{32}") ? "managed" : encoder.encodeToString(nodeId.getBytes(StandardCharsets.UTF_8)); return "video:stop-receipts:v1:" + owner + ":" + encoder.encodeToString(stream.getBytes(StandardCharsets.UTF_8)); } private String encode(Snapshot value) { try { return json.writeValueAsString(value); } catch (JsonProcessingException ex) { throw new IllegalStateException("Cannot encode stop receipt", ex); } } private Snapshot decode(Object value) { if (value == null) return null; if (!(value instanceof String)) throw new IllegalStateException("Unsupported stop receipt representation"); try { return json.readValue((String) value, Snapshot.class); } catch (JsonProcessingException ex) { throw new IllegalStateException("Cannot decode stop receipt", ex); } } }