VideoStopReceipts.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. /** True only after the token-owned pool number was positively returned. */
  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. /** Legacy negotiation happens before any stop receipt exists; create the original allocation
  81. * from the typed handle. The pool number is returned only if returnPoolSsrc actually succeeds. */
  82. public boolean recordNegotiatedSsrc(String nodeId, String stream, SSRCInfo original, String negotiatedSsrc,
  83. java.util.function.Supplier<Boolean> returnPoolSsrc) {
  84. if (nodeId == null || stream == null || original == null || original.getTimeOutTaskKey() == null
  85. || original.getSsrc() == null || negotiatedSsrc == null || !"rtp".equals(original.getApp())) return false;
  86. Snapshot recorded = update(nodeId, stream, snapshot -> {
  87. Allocation allocation = snapshot.allocation;
  88. if (allocation == null) {
  89. allocation = new Allocation(); allocation.token = original.getTimeOutTaskKey();
  90. allocation.ssrc = original.getSsrc(); allocation.port = original.getPort(); allocation.state = RtpState.OPEN;
  91. snapshot.allocation = allocation;
  92. }
  93. if (!Objects.equals(allocation.token, original.getTimeOutTaskKey())
  94. || !Objects.equals(allocation.ssrc, original.getSsrc())) return null;
  95. if (allocation.negotiatedSsrc != null && !Objects.equals(allocation.negotiatedSsrc, negotiatedSsrc)) return null;
  96. allocation.negotiatedSsrc = negotiatedSsrc;
  97. return snapshot;
  98. });
  99. if (recorded == null || !Boolean.TRUE.equals(returnPoolSsrc.get())) return false;
  100. // Persist the positive return receipt only after the Factory confirmed this token returned it.
  101. return update(nodeId, stream, snapshot -> {
  102. Allocation allocation = snapshot.allocation;
  103. if (allocation == null || !Objects.equals(allocation.token, original.getTimeOutTaskKey())
  104. || !Objects.equals(allocation.ssrc, original.getSsrc())) return null;
  105. allocation.poolReturned = true;
  106. return snapshot;
  107. }) != null;
  108. }
  109. /** Retain the original managed dialog before an automatic/late BYE can erase the live index. */
  110. public boolean retainDialog(SsrcTransaction expected) {
  111. if (expected == null || expected.getMediaServerId() == null || expected.getStream() == null
  112. || !expected.getStream().matches("managed_[0-9a-fA-F]{32}") || !"rtp".equals(expected.getApp())
  113. || expected.getCallId() == null || expected.getSipTransactionInfo() == null
  114. || !Objects.equals(expected.getCallId(), expected.getSipTransactionInfo().getCallId())
  115. || expected.getSipTransactionInfo().getFromTag() == null || expected.getSipTransactionInfo().getToTag() == null) return false;
  116. return update(expected.getMediaServerId(), expected.getStream(), snapshot -> {
  117. Play play = snapshot.plays.get(expected.getStream());
  118. if (play == null || snapshot.allocation == null || !Objects.equals(snapshot.allocation.ssrc, expected.getSsrc())
  119. || !Objects.equals(play.deviceId, expected.getDeviceId()) || !Objects.equals(play.channelId, expected.getChannelId())
  120. || (play.dialog != null && !SipInviteSessionManager.sameDialog(play.dialog, expected))) return null;
  121. play.dialog = expected; play.inviteSent = true; return snapshot;
  122. }) != null;
  123. }
  124. public Snapshot update(String nodeId, String stream, UnaryOperator<Snapshot> change) {
  125. final String key = key(nodeId, stream);
  126. // A conflict does not entitle the caller to repeat a name-close; only a committed transition does.
  127. return redis.execute(new SessionCallback<Snapshot>() {
  128. @Override @SuppressWarnings({"unchecked", "rawtypes"})
  129. public <K, V> Snapshot execute(RedisOperations<K, V> operations) {
  130. RedisOperations ops = operations;
  131. ops.watch(key);
  132. boolean transaction = false;
  133. try {
  134. Snapshot before = decode(ops.opsForValue().get(key));
  135. if (before != null && !Objects.equals(nodeId, before.nodeId)) return null;
  136. Snapshot proposed = before == null ? new Snapshot() : decode(encode(before));
  137. proposed.nodeId = nodeId; proposed.stream = stream;
  138. Snapshot next = change.apply(proposed);
  139. if (next == null) return null;
  140. validate(before, next, nodeId, stream);
  141. String encoded = encode(next);
  142. ops.multi(); transaction = true;
  143. // Only a terminal receipt may expire: an unresolved allocation has to stay
  144. // readable after restart. Confirmed stops keep a bounded retention window
  145. // via a single SET ... EX inside this same transaction.
  146. if (retired(next)) ops.opsForValue().set(key, encoded, java.time.Duration.ofDays(7));
  147. else ops.opsForValue().set(key, encoded);
  148. List<Object> committed = ops.exec(); transaction = false;
  149. if (committed == null || committed.isEmpty()) return null;
  150. for (Object result : committed) {
  151. if (result == null || Boolean.FALSE.equals(result)) throw new IllegalStateException("Receipt write not acknowledged");
  152. if (result instanceof RuntimeException) throw (RuntimeException) result;
  153. if (result instanceof Throwable) throw new IllegalStateException("Receipt write failed", (Throwable) result);
  154. }
  155. return decode(encoded);
  156. } finally {
  157. if (transaction) ops.discard();
  158. else ops.unwatch();
  159. }
  160. }
  161. });
  162. }
  163. /** A terminal allocation is retired: nothing can be reclaimed from it any more. */
  164. private static boolean retired(Snapshot snapshot) {
  165. return snapshot.allocation != null && snapshot.allocation.terminal();
  166. }
  167. private void validate(Snapshot old, Snapshot next, String nodeId, String stream) {
  168. if (!Objects.equals(nodeId, next.nodeId) || !Objects.equals(stream, next.stream) || next.plays == null)
  169. throw new IllegalArgumentException("Receipt identity cannot change");
  170. Allocation a = old == null ? null : old.allocation, b = next.allocation;
  171. if (b != null && (b.token == null || b.ssrc == null || b.state == null))
  172. throw new IllegalArgumentException("Allocation requires SSRC and timeout token");
  173. if (a != null) {
  174. if (b == null) throw new IllegalArgumentException("Allocation evidence cannot disappear");
  175. if (!Objects.equals(a.token, b.token)) {
  176. if (!old.canReplaceAllocation() || b.state != RtpState.INTENT)
  177. throw new IllegalArgumentException("Previous allocation is not closed");
  178. } else if (!Objects.equals(a.ssrc, b.ssrc) || a.poolTracked != b.poolTracked || a.externalSsrc != b.externalSsrc
  179. || (a.negotiatedSsrc != null && !Objects.equals(a.negotiatedSsrc, b.negotiatedSsrc))
  180. || (a.poolReturned && !b.poolReturned)
  181. || !transition(a.state, b.state)
  182. || (a.port != b.port && !(a.state == RtpState.CREATING && b.state == RtpState.OPEN))
  183. || (a.callId != null && !Objects.equals(a.callId, b.callId))) {
  184. throw new IllegalArgumentException("Allocation evidence cannot regress or change owner");
  185. }
  186. }
  187. if (old == null) return;
  188. for (Map.Entry<String, Play> entry : old.plays.entrySet()) {
  189. Play p = entry.getValue(), q = next.plays.get(entry.getKey());
  190. if (q == null || !Objects.equals(p.deviceId, q.deviceId) || !Objects.equals(p.channelId, q.channelId)
  191. || !Objects.equals(p.channelCode, q.channelCode) || (p.inviteSent && !q.inviteSent)
  192. || (p.cancelled && !q.cancelled)
  193. || (p.allocationToken != null && !Objects.equals(p.allocationToken, q.allocationToken))
  194. || (p.allocation != null && (q.allocation == null || !Objects.equals(p.allocation.token, q.allocation.token)
  195. || !Objects.equals(p.allocation.ssrc, q.allocation.ssrc) || p.allocation.port != q.allocation.port
  196. || !Objects.equals(p.allocation.negotiatedSsrc, q.allocation.negotiatedSsrc)
  197. || (p.allocation.poolReturned && !q.allocation.poolReturned)
  198. || p.allocation.poolTracked != q.allocation.poolTracked || p.allocation.externalSsrc != q.allocation.externalSsrc))
  199. || (p.dialog != null && !SipInviteSessionManager.sameDialog(p.dialog, q.dialog)))
  200. throw new IllegalArgumentException("Original play evidence cannot regress or change dialog");
  201. }
  202. }
  203. private boolean transition(RtpState old, RtpState next) {
  204. if (old == next) return true;
  205. switch (old) {
  206. case INTENT: return next == RtpState.CREATING || next == RtpState.NEVER_CREATED;
  207. case CREATING: return next == RtpState.OPEN;
  208. case OPEN: return next == RtpState.CLOSING;
  209. case CLOSING: return next == RtpState.CLOSED;
  210. default: return false;
  211. }
  212. }
  213. private String key(String nodeId, String stream) {
  214. if (nodeId == null || stream == null) throw new IllegalArgumentException("Original node and stream required");
  215. Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding();
  216. // Managed UUIDs are single-use even if an API request later names a different node.
  217. String owner = stream.matches("managed_[0-9a-fA-F]{32}") ? "managed" : encoder.encodeToString(nodeId.getBytes(StandardCharsets.UTF_8));
  218. return "video:stop-receipts:v1:" + owner
  219. + ":" + encoder.encodeToString(stream.getBytes(StandardCharsets.UTF_8));
  220. }
  221. private String encode(Snapshot value) {
  222. try { return json.writeValueAsString(value); }
  223. catch (JsonProcessingException ex) { throw new IllegalStateException("Cannot encode stop receipt", ex); }
  224. }
  225. private Snapshot decode(Object value) {
  226. if (value == null) return null;
  227. if (!(value instanceof String)) throw new IllegalStateException("Unsupported stop receipt representation");
  228. try { return json.readValue((String) value, Snapshot.class); }
  229. catch (JsonProcessingException ex) { throw new IllegalStateException("Cannot decode stop receipt", ex); }
  230. }
  231. }