VideoLifecycleService.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. package com.zksy.video.lifecycle;
  2. import org.springframework.beans.BeanUtils;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Service;
  5. import java.time.Clock;
  6. import java.util.*;
  7. import java.util.function.Consumer;
  8. /** Durable generation intent. Each transition is CAS; no persistence lock spans a media operation. */
  9. @Service
  10. public class VideoLifecycleService {
  11. private static final Set<String> TERMINAL = Set.of("STOPPED", "FAILED");
  12. private static final Set<String> STATES = Set.of("STARTING", "ACTIVE", "CLEANUP_PENDING", "STOPPED", "FAILED");
  13. private final VideoLifecycleStore store;
  14. private final List<VideoLifecycleMedia> adapters;
  15. private final Clock clock;
  16. @Autowired public VideoLifecycleService(VideoLifecycleStore store, List<VideoLifecycleMedia> adapters) {
  17. this(store, adapters, Clock.systemUTC());
  18. }
  19. public VideoLifecycleService(VideoLifecycleStore store, List<VideoLifecycleMedia> adapters, Clock clock) {
  20. this.store = store; this.adapters = adapters; this.clock = clock;
  21. }
  22. public Map<String,Object> start(Map<String,Object> body) {
  23. VideoLifecycleRecord request = parse(body), current = store.find(request.getGeneration());
  24. if (current != null) {
  25. sameSource(current, request);
  26. if (current.isCancelled() || TERMINAL.contains(current.getStatus()) || current.isStartInFlight()) return result(current);
  27. return status(body); // A repeated start observes, it never issues a second allocation.
  28. }
  29. VideoLifecycleRecord initial = copy(request);
  30. if (expired(request)) {
  31. initial.setCancelled(true); initial.setStatus("FAILED");
  32. } else {
  33. VideoLifecycleMedia media = adapter(initial);
  34. try {
  35. media.prepare(initial); // Validation/node selection cannot allocate resources.
  36. initial.setStatus("STARTING"); initial.setStartInFlight(true);
  37. } catch (RuntimeException notDispatched) {
  38. initial.setCancelled(true);
  39. initial.setStatus(request.getStream() == null && request.getProxyKey() == null ? "FAILED" : "CLEANUP_PENDING");
  40. }
  41. }
  42. if (!store.compareAndSet(null, initial)) return start(body);
  43. if (TERMINAL.contains(initial.getStatus()) || !initial.isStartInFlight()) return result(initial);
  44. // Cancellation may have won after allocation intent was persisted, but before dispatch.
  45. current = store.find(initial.getGeneration());
  46. if (current.isCancelled() || expired(current)) {
  47. return result(transition(request, row -> {
  48. row.setStartInFlight(false); row.setCancelled(true);
  49. row.setStatus(request.getStream() == null ? "STOPPED" : "CLEANUP_PENDING"); row.setMedia(null);
  50. }));
  51. }
  52. Map<String,Object> outcome;
  53. try { outcome = adapter(initial).start(initial); }
  54. catch (RuntimeException unknown) { outcome = Map.of("status", "CLEANUP_PENDING"); }
  55. current = merge(request, initial, outcome, true, false);
  56. if (current.isCancelled() && !TERMINAL.contains(current.getStatus())) return cleanup(request, current);
  57. return result(current);
  58. }
  59. public Map<String,Object> status(Map<String,Object> body) {
  60. VideoLifecycleRecord request = parse(body), row = store.find(request.getGeneration());
  61. if (row == null) return pending(request);
  62. sameSource(row, request);
  63. if (TERMINAL.contains(row.getStatus())) return result(row);
  64. if (row.isCancelled() || ("STARTING".equals(row.getStatus()) && expired(row))) return cancel(body);
  65. if (row.isStartInFlight()) return result(row);
  66. Map<String,Object> outcome;
  67. try { outcome = adapter(row).status(row); }
  68. catch (RuntimeException unknown) { outcome = Map.of("status", "CLEANUP_PENDING"); }
  69. return result(merge(request, row, outcome, false, false));
  70. }
  71. public Map<String,Object> cancel(Map<String,Object> body) {
  72. VideoLifecycleRecord request = parse(body), row = store.find(request.getGeneration());
  73. if (row == null) {
  74. VideoLifecycleRecord tombstone = copy(request);
  75. tombstone.setCancelled(true); tombstone.setStatus("CLEANUP_PENDING");
  76. if (!store.compareAndSet(null, tombstone)) return cancel(body);
  77. // No dispatch evidence: do not guess a physical handle or claim completion.
  78. return result(tombstone);
  79. }
  80. sameSource(row, request);
  81. if (TERMINAL.contains(row.getStatus())) return result(row);
  82. row = transition(request, value -> {
  83. if (!TERMINAL.contains(value.getStatus())) {
  84. value.setCancelled(true); value.setStatus("CLEANUP_PENDING"); value.setMedia(null);
  85. }
  86. });
  87. if (row.getStream() != null) store.markStreamCancelled(row.getStream());
  88. return cleanup(request, row);
  89. }
  90. private Map<String,Object> cleanup(VideoLifecycleRecord request, VideoLifecycleRecord row) {
  91. Map<String,Object> outcome;
  92. try { outcome = adapter(row).cancel(row); }
  93. catch (RuntimeException unknown) { outcome = Map.of("status", "CLEANUP_PENDING"); }
  94. return result(merge(request, row, outcome, false, true));
  95. }
  96. /** Merge returned handles, but cancellation and terminal state always beat a stale snapshot. */
  97. private VideoLifecycleRecord merge(VideoLifecycleRecord request, VideoLifecycleRecord attempt,
  98. Map<String,Object> outcome, boolean completedStart, boolean cleanup) {
  99. return transition(request, row -> {
  100. if (TERMINAL.contains(row.getStatus())) return;
  101. if (completedStart) {
  102. row.setStartInFlight(false);
  103. if (expired(row)) row.setCancelled(true);
  104. }
  105. String state = outcome != null && outcome.get("status") != null && STATES.contains(outcome.get("status")) ? (String) outcome.get("status") : "CLEANUP_PENDING";
  106. if (row.getMediaServerId() == null) row.setMediaServerId(attempt.getMediaServerId());
  107. if (row.getStream() == null) row.setStream(attempt.getStream());
  108. if (row.getProxyKey() == null) row.setProxyKey(attempt.getProxyKey());
  109. if (row.getAdoptedHandle() == null) row.setAdoptedHandle(attempt.getAdoptedHandle());
  110. if (outcome != null) {
  111. if (outcome.get("stream") instanceof String) {
  112. String returned = (String) outcome.get("stream");
  113. if (row.getStream() != null && !row.getStream().equals(returned)) state = "CLEANUP_PENDING";
  114. else row.setStream(returned);
  115. }
  116. if (outcome.get("proxyKey") instanceof String) row.setProxyKey((String) outcome.get("proxyKey"));
  117. }
  118. if (row.isCancelled()) {
  119. row.setStatus(cleanup && !attempt.isStartInFlight() && !row.isStartInFlight() && TERMINAL.contains(state) ? state : "CLEANUP_PENDING");
  120. row.setMedia(null);
  121. } else if ("CLEANUP_PENDING".equals(state)) {
  122. row.setStatus(state); row.setCancelled(true); row.setMedia(null);
  123. } else if ("ACTIVE".equals(state)) {
  124. if (outcome.get("media") instanceof Map) {
  125. row.setMedia(new LinkedHashMap<>(cast(outcome.get("media")))); row.setStatus(state);
  126. } else { row.setStatus("CLEANUP_PENDING"); row.setCancelled(true); row.setMedia(null); }
  127. } else {
  128. row.setStatus(state); row.setMedia(null);
  129. }
  130. });
  131. }
  132. private VideoLifecycleRecord transition(VideoLifecycleRecord request, Consumer<VideoLifecycleRecord> change) {
  133. for (int retry = 0; retry < 32; retry++) {
  134. VideoLifecycleRecord before = store.find(request.getGeneration());
  135. if (before == null) throw new IllegalStateException("观看代次记录丢失,结果未确认");
  136. sameSource(before, request);
  137. VideoLifecycleRecord after = copy(before); change.accept(after);
  138. if (store.compareAndSet(before, after)) return after;
  139. }
  140. throw new IllegalStateException("观看代次状态变更繁忙,结果未确认");
  141. }
  142. private boolean expired(VideoLifecycleRecord row) { return row.getDeadline() <= clock.millis(); }
  143. private VideoLifecycleMedia adapter(VideoLifecycleRecord row) {
  144. return adapters.stream().filter(item -> item.supports(row.getSourceType())).findFirst()
  145. .orElseThrow(() -> new IllegalArgumentException("不支持的视频来源类型"));
  146. }
  147. private static void sameSource(VideoLifecycleRecord saved, VideoLifecycleRecord request) {
  148. if (!Objects.equals(saved.getSourceType(), request.getSourceType()) || !Objects.equals(saved.getVideoId(), request.getVideoId())
  149. || !Objects.equals(saved.getDeviceId(), request.getDeviceId()) || !Objects.equals(saved.getChannelId(), request.getChannelId())
  150. || !Objects.equals(saved.getUrl(), request.getUrl()) || !Objects.equals(saved.getDeadline(), request.getDeadline()))
  151. throw new IllegalArgumentException("观看代次的来源与截止时间不可改变");
  152. }
  153. private static VideoLifecycleRecord parse(Map<String,Object> body) {
  154. if (body == null) throw new IllegalArgumentException("请求体缺失");
  155. VideoLifecycleRecord row = new VideoLifecycleRecord();
  156. row.setGeneration(text(body.get("generation")));
  157. if (row.getGeneration() == null || !row.getGeneration().matches("[A-Za-z0-9_-]{1,64}")) throw new IllegalArgumentException("观看代次标识无效");
  158. if (!(body.get("source") instanceof Map)) throw new IllegalArgumentException("视频来源缺失");
  159. Map<String,Object> source = cast(body.get("source"));
  160. row.setSourceType(text(source.get("type"))); row.setVideoId(text(source.get("videoId")));
  161. row.setDeviceId(text(source.get("deviceId"))); row.setChannelId(text(source.get("channelId"))); row.setUrl(text(source.get("url")));
  162. if (row.getVideoId() == null || row.getSourceType() == null || !Set.of("GB28181", "MANUAL").contains(row.getSourceType())) throw new IllegalArgumentException("视频来源无效");
  163. if (!(body.get("startDeadline") instanceof Number)) throw new IllegalArgumentException("启动截止时间缺失");
  164. row.setDeadline(((Number) body.get("startDeadline")).longValue());
  165. if (row.getDeadline() <= 0) throw new IllegalArgumentException("启动截止时间无效");
  166. if (body.get("existingMedia") instanceof Map) {
  167. Map<String,Object> existing = cast(body.get("existingMedia"));
  168. row.setStream(text(existing.get("stream"))); row.setProxyKey(text(existing.get("proxyKey")));
  169. row.setMediaServerId(text(existing.get("mediaServerId")));
  170. }
  171. return row;
  172. }
  173. private static VideoLifecycleRecord copy(VideoLifecycleRecord row) {
  174. VideoLifecycleRecord copy = new VideoLifecycleRecord(); BeanUtils.copyProperties(row, copy); return copy;
  175. }
  176. @SuppressWarnings("unchecked") private static Map<String,Object> cast(Object value) { return (Map<String,Object>) value; }
  177. private static String text(Object value) { return value instanceof String && !((String) value).isBlank() ? (String) value : null; }
  178. private static Map<String,Object> pending(VideoLifecycleRecord row) {
  179. return Map.of("generation", row.getGeneration(), "status", "CLEANUP_PENDING");
  180. }
  181. private static Map<String,Object> result(VideoLifecycleRecord row) {
  182. Map<String,Object> result = new LinkedHashMap<>(); result.put("generation", row.getGeneration()); result.put("status", row.getStatus());
  183. if (!row.isCancelled() && "ACTIVE".equals(row.getStatus()) && row.getMedia() != null) result.put("media", row.getMedia());
  184. return result;
  185. }
  186. }