VideoStopReceipts.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. package com.zksy.video.lifecycle;
  2. import com.fasterxml.jackson.core.JsonProcessingException;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import com.ruoyi.wvp.gb28181.bean.SsrcTransaction;
  5. import com.ruoyi.wvp.gb28181.session.SipInviteSessionManager;
  6. import com.ruoyi.wvp.service.bean.SSRCInfo;
  7. import org.springframework.data.redis.core.RedisOperations;
  8. import org.springframework.data.redis.core.RedisTemplate;
  9. import org.springframework.data.redis.core.SessionCallback;
  10. import org.springframework.stereotype.Component;
  11. import java.nio.charset.StandardCharsets;
  12. import java.util.*;
  13. import java.util.function.UnaryOperator;
  14. /**
  15. * Durable stop evidence and allocation fencing, shared by all API instances (not serverId scoped).
  16. * A missing snapshot is UNKNOWN, not stopped. No TTL: unknown dispatches must not unlock a name.
  17. * update runs against a detached typed snapshot under Redis WATCH/MULTI/EXEC; null rejects a change.
  18. * An aborted CAS returns null, never success. Exceptions (including ambiguous EXEC) propagate.
  19. * Callers must never dispatch external I/O inside an update, nor use a local cache as evidence.
  20. */
  21. @Component
  22. public class VideoStopReceipts {
  23. private final RedisTemplate<Object, Object> redis;
  24. private final ObjectMapper json = new ObjectMapper();
  25. public VideoStopReceipts(RedisTemplate<Object, Object> redis) { this.redis = Objects.requireNonNull(redis); }
  26. public enum RtpState { INTENT, CREATING, OPEN, CLOSING, CLOSED, NEVER_CREATED }
  27. public static class Allocation {
  28. public String token;
  29. public String ssrc;
  30. /** Device-chosen SSRC after a real renegotiation; the pool number above stays the return identity. */
  31. public String negotiatedSsrc;
  32. /** The pre-existing legacy path already returned the pool number while negotiating. */
  33. public boolean poolReturned;
  34. public boolean poolTracked;
  35. public boolean externalSsrc;
  36. public int port;
  37. public RtpState state;
  38. public String callId;
  39. public SSRCInfo info(String stream) { return new SSRCInfo(port, ssrc, "rtp", stream, token); }
  40. public boolean matches(SSRCInfo info) {
  41. return info != null && Objects.equals(token, info.getTimeOutTaskKey())
  42. && "rtp".equals(info.getApp())
  43. && (Objects.equals(ssrc, info.getSsrc())
  44. || (negotiatedSsrc != null && Objects.equals(negotiatedSsrc, info.getSsrc())));
  45. }
  46. /** Pool return always uses the originally allocated number, never the negotiated one. */
  47. public String poolSsrc() { return ssrc; }
  48. public boolean terminal() { return state == RtpState.CLOSED || state == RtpState.NEVER_CREATED; }
  49. }
  50. public static class Play {
  51. public String deviceId;
  52. public Integer channelId;
  53. public String channelCode;
  54. public String allocationToken;
  55. /** Frozen allocation identity retained even when the legacy name is allocated again. */
  56. public Allocation allocation;
  57. public boolean inviteSent;
  58. public boolean cancelled;
  59. /** Original dialog is never discarded, even after the live session registry removes it. */
  60. public SsrcTransaction dialog;
  61. }
  62. public static class Snapshot {
  63. public String nodeId;
  64. public String stream;
  65. public Allocation allocation;
  66. /** managed uses stream as key; adoption uses its full UUID capability. */
  67. public Map<String, Play> plays = new LinkedHashMap<>();
  68. /** Ordinary legacy OPEN is provenance, not a lease. Adoption and uncertain I/O fence reuse. */
  69. public boolean canReplaceAllocation() {
  70. if (allocation == null) return true;
  71. if (stream.startsWith("managed_")) return false;
  72. return allocation.terminal() || (allocation.state == RtpState.OPEN && allocation.callId == null
  73. && plays.values().stream().noneMatch(play -> Objects.equals(play.allocationToken, allocation.token)));
  74. }
  75. }
  76. public Snapshot read(String nodeId, String stream) {
  77. Snapshot snapshot = decode(redis.opsForValue().get(key(nodeId, stream)));
  78. return snapshot != null && Objects.equals(nodeId, snapshot.nodeId) ? snapshot : null;
  79. }
  80. /** Record a real device renegotiation without changing the original pool number.
  81. * Only the holder of the original allocation token may add it. */
  82. public boolean recordNegotiatedSsrc(String nodeId, String stream, String allocationToken, String poolSsrc, String negotiatedSsrc) {
  83. if (nodeId == null || stream == null || allocationToken == null || negotiatedSsrc == null) return false;
  84. return update(nodeId, stream, snapshot -> {
  85. Allocation allocation = snapshot.allocation;
  86. if (allocation == null || !Objects.equals(allocation.token, allocationToken)) return null;
  87. if (poolSsrc != null && !Objects.equals(allocation.ssrc, poolSsrc)) return null;
  88. if (allocation.negotiatedSsrc != null && !Objects.equals(allocation.negotiatedSsrc, negotiatedSsrc)) return null;
  89. allocation.negotiatedSsrc = negotiatedSsrc;
  90. return snapshot;
  91. }) != null;
  92. }
  93. /** Legacy negotiation happens before any stop receipt exists; create the original allocation
  94. * from the typed handle and remember that its pool number was already returned by that path. */
  95. public boolean recordNegotiatedSsrc(String nodeId, String stream, SSRCInfo original, String negotiatedSsrc,
  96. boolean poolAlreadyReturned) {
  97. if (nodeId == null || stream == null || original == null || original.getTimeOutTaskKey() == null
  98. || original.getSsrc() == null || negotiatedSsrc == null || !"rtp".equals(original.getApp())) return false;
  99. return update(nodeId, stream, snapshot -> {
  100. Allocation allocation = snapshot.allocation;
  101. if (allocation == null) {
  102. allocation = new Allocation(); allocation.token = original.getTimeOutTaskKey();
  103. allocation.ssrc = original.getSsrc(); allocation.port = original.getPort(); allocation.state = RtpState.OPEN;
  104. snapshot.allocation = allocation;
  105. }
  106. if (!Objects.equals(allocation.token, original.getTimeOutTaskKey())
  107. || !Objects.equals(allocation.ssrc, original.getSsrc())) return null;
  108. if (allocation.negotiatedSsrc != null && !Objects.equals(allocation.negotiatedSsrc, negotiatedSsrc)) return null;
  109. allocation.negotiatedSsrc = negotiatedSsrc;
  110. allocation.poolReturned = allocation.poolReturned || poolAlreadyReturned;
  111. return snapshot;
  112. }) != null;
  113. }
  114. /** Retain the original managed dialog before an automatic/late BYE can erase the live index. */
  115. public boolean retainDialog(SsrcTransaction expected) {
  116. if (expected == null || expected.getMediaServerId() == null || expected.getStream() == null
  117. || !expected.getStream().matches("managed_[0-9a-fA-F]{32}") || !"rtp".equals(expected.getApp())
  118. || expected.getCallId() == null || expected.getSipTransactionInfo() == null
  119. || !Objects.equals(expected.getCallId(), expected.getSipTransactionInfo().getCallId())
  120. || expected.getSipTransactionInfo().getFromTag() == null || expected.getSipTransactionInfo().getToTag() == null) return false;
  121. return update(expected.getMediaServerId(), expected.getStream(), snapshot -> {
  122. Play play = snapshot.plays.get(expected.getStream());
  123. if (play == null || snapshot.allocation == null || !Objects.equals(snapshot.allocation.ssrc, expected.getSsrc())
  124. || !Objects.equals(play.deviceId, expected.getDeviceId()) || !Objects.equals(play.channelId, expected.getChannelId())
  125. || (play.dialog != null && !SipInviteSessionManager.sameDialog(play.dialog, expected))) return null;
  126. play.dialog = expected; play.inviteSent = true; return snapshot;
  127. }) != null;
  128. }
  129. public Snapshot update(String nodeId, String stream, UnaryOperator<Snapshot> change) {
  130. final String key = key(nodeId, stream);
  131. // A conflict does not entitle the caller to repeat a name-close; only a committed transition does.
  132. return redis.execute(new SessionCallback<Snapshot>() {
  133. @Override @SuppressWarnings({"unchecked", "rawtypes"})
  134. public <K, V> Snapshot execute(RedisOperations<K, V> operations) {
  135. RedisOperations ops = operations;
  136. ops.watch(key);
  137. boolean transaction = false;
  138. try {
  139. Snapshot before = decode(ops.opsForValue().get(key));
  140. if (before != null && !Objects.equals(nodeId, before.nodeId)) return null;
  141. Snapshot proposed = before == null ? new Snapshot() : decode(encode(before));
  142. proposed.nodeId = nodeId; proposed.stream = stream;
  143. Snapshot next = change.apply(proposed);
  144. if (next == null) return null;
  145. validate(before, next, nodeId, stream);
  146. String encoded = encode(next);
  147. ops.multi(); transaction = true;
  148. ops.opsForValue().set(key, encoded);
  149. List<Object> committed = ops.exec(); transaction = false;
  150. if (committed == null || committed.isEmpty()) return null;
  151. for (Object result : committed) {
  152. if (result == null || Boolean.FALSE.equals(result)) throw new IllegalStateException("Receipt write not acknowledged");
  153. if (result instanceof RuntimeException) throw (RuntimeException) result;
  154. if (result instanceof Throwable) throw new IllegalStateException("Receipt write failed", (Throwable) result);
  155. }
  156. return decode(encoded);
  157. } finally {
  158. if (transaction) ops.discard();
  159. else ops.unwatch();
  160. }
  161. }
  162. });
  163. }
  164. private void validate(Snapshot old, Snapshot next, String nodeId, String stream) {
  165. if (!Objects.equals(nodeId, next.nodeId) || !Objects.equals(stream, next.stream) || next.plays == null)
  166. throw new IllegalArgumentException("Receipt identity cannot change");
  167. Allocation a = old == null ? null : old.allocation, b = next.allocation;
  168. if (b != null && (b.token == null || b.ssrc == null || b.state == null))
  169. throw new IllegalArgumentException("Allocation requires SSRC and timeout token");
  170. if (a != null) {
  171. if (b == null) throw new IllegalArgumentException("Allocation evidence cannot disappear");
  172. if (!Objects.equals(a.token, b.token)) {
  173. if (!old.canReplaceAllocation() || b.state != RtpState.INTENT)
  174. throw new IllegalArgumentException("Previous allocation is not closed");
  175. } else if (!Objects.equals(a.ssrc, b.ssrc) || a.poolTracked != b.poolTracked || a.externalSsrc != b.externalSsrc
  176. || (a.negotiatedSsrc != null && !Objects.equals(a.negotiatedSsrc, b.negotiatedSsrc))
  177. || (a.poolReturned && !b.poolReturned)
  178. || !transition(a.state, b.state)
  179. || (a.port != b.port && !(a.state == RtpState.CREATING && b.state == RtpState.OPEN))
  180. || (a.callId != null && !Objects.equals(a.callId, b.callId))) {
  181. throw new IllegalArgumentException("Allocation evidence cannot regress or change owner");
  182. }
  183. }
  184. if (old == null) return;
  185. for (Map.Entry<String, Play> entry : old.plays.entrySet()) {
  186. Play p = entry.getValue(), q = next.plays.get(entry.getKey());
  187. if (q == null || !Objects.equals(p.deviceId, q.deviceId) || !Objects.equals(p.channelId, q.channelId)
  188. || !Objects.equals(p.channelCode, q.channelCode) || (p.inviteSent && !q.inviteSent)
  189. || (p.cancelled && !q.cancelled)
  190. || (p.allocationToken != null && !Objects.equals(p.allocationToken, q.allocationToken))
  191. || (p.allocation != null && (q.allocation == null || !Objects.equals(p.allocation.token, q.allocation.token)
  192. || !Objects.equals(p.allocation.ssrc, q.allocation.ssrc) || p.allocation.port != q.allocation.port
  193. || !Objects.equals(p.allocation.negotiatedSsrc, q.allocation.negotiatedSsrc)
  194. || (p.allocation.poolReturned && !q.allocation.poolReturned)
  195. || p.allocation.poolTracked != q.allocation.poolTracked || p.allocation.externalSsrc != q.allocation.externalSsrc))
  196. || (p.dialog != null && !SipInviteSessionManager.sameDialog(p.dialog, q.dialog)))
  197. throw new IllegalArgumentException("Original play evidence cannot regress or change dialog");
  198. }
  199. }
  200. private boolean transition(RtpState old, RtpState next) {
  201. if (old == next) return true;
  202. switch (old) {
  203. case INTENT: return next == RtpState.CREATING || next == RtpState.NEVER_CREATED;
  204. case CREATING: return next == RtpState.OPEN;
  205. case OPEN: return next == RtpState.CLOSING;
  206. case CLOSING: return next == RtpState.CLOSED;
  207. default: return false;
  208. }
  209. }
  210. private String key(String nodeId, String stream) {
  211. if (nodeId == null || stream == null) throw new IllegalArgumentException("Original node and stream required");
  212. Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding();
  213. // Managed UUIDs are single-use even if an API request later names a different node.
  214. String owner = stream.matches("managed_[0-9a-fA-F]{32}") ? "managed" : encoder.encodeToString(nodeId.getBytes(StandardCharsets.UTF_8));
  215. return "video:stop-receipts:v1:" + owner
  216. + ":" + encoder.encodeToString(stream.getBytes(StandardCharsets.UTF_8));
  217. }
  218. private String encode(Snapshot value) {
  219. try { return json.writeValueAsString(value); }
  220. catch (JsonProcessingException ex) { throw new IllegalStateException("Cannot encode stop receipt", ex); }
  221. }
  222. private Snapshot decode(Object value) {
  223. if (value == null) return null;
  224. if (!(value instanceof String)) throw new IllegalStateException("Unsupported stop receipt representation");
  225. try { return json.readValue((String) value, Snapshot.class); }
  226. catch (JsonProcessingException ex) { throw new IllegalStateException("Cannot decode stop receipt", ex); }
  227. }
  228. }