| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195 |
- package com.zksy.video.lifecycle;
- import org.springframework.beans.BeanUtils;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import java.time.Clock;
- import java.util.*;
- import java.util.function.Consumer;
- /** Durable generation intent. Each transition is CAS; no persistence lock spans a media operation. */
- @Service
- public class VideoLifecycleService {
- private static final Set<String> TERMINAL = Set.of("STOPPED", "FAILED");
- private static final Set<String> STATES = Set.of("STARTING", "ACTIVE", "CLEANUP_PENDING", "STOPPED", "FAILED");
- private final VideoLifecycleStore store;
- private final List<VideoLifecycleMedia> adapters;
- private final Clock clock;
- @Autowired public VideoLifecycleService(VideoLifecycleStore store, List<VideoLifecycleMedia> adapters) {
- this(store, adapters, Clock.systemUTC());
- }
- public VideoLifecycleService(VideoLifecycleStore store, List<VideoLifecycleMedia> adapters, Clock clock) {
- this.store = store; this.adapters = adapters; this.clock = clock;
- }
- public Map<String,Object> start(Map<String,Object> body) {
- VideoLifecycleRecord request = parse(body), current = store.find(request.getGeneration());
- if (current != null) {
- sameSource(current, request);
- if (current.isCancelled() || TERMINAL.contains(current.getStatus()) || current.isStartInFlight()) return result(current);
- return status(body); // A repeated start observes, it never issues a second allocation.
- }
- VideoLifecycleRecord initial = copy(request);
- if (expired(request)) {
- initial.setCancelled(true); initial.setStatus("FAILED");
- } else {
- VideoLifecycleMedia media = adapter(initial);
- try {
- media.prepare(initial); // Validation/node selection cannot allocate resources.
- initial.setStatus("STARTING"); initial.setStartInFlight(true);
- } catch (RuntimeException notDispatched) {
- initial.setCancelled(true);
- initial.setStatus(request.getStream() == null && request.getProxyKey() == null ? "FAILED" : "CLEANUP_PENDING");
- }
- }
- if (!store.compareAndSet(null, initial)) return start(body);
- if (TERMINAL.contains(initial.getStatus()) || !initial.isStartInFlight()) return result(initial);
- // Cancellation may have won after allocation intent was persisted, but before dispatch.
- current = store.find(initial.getGeneration());
- if (current.isCancelled() || expired(current)) {
- return result(transition(request, row -> {
- row.setStartInFlight(false); row.setCancelled(true);
- row.setStatus(request.getStream() == null ? "STOPPED" : "CLEANUP_PENDING"); row.setMedia(null);
- }));
- }
- Map<String,Object> outcome;
- try { outcome = adapter(initial).start(initial); }
- catch (RuntimeException unknown) { outcome = Map.of("status", "CLEANUP_PENDING"); }
- current = merge(request, initial, outcome, true, false);
- if (current.isCancelled() && !TERMINAL.contains(current.getStatus())) return cleanup(request, current);
- return result(current);
- }
- public Map<String,Object> status(Map<String,Object> body) {
- VideoLifecycleRecord request = parse(body), row = store.find(request.getGeneration());
- if (row == null) return pending(request);
- sameSource(row, request);
- if (TERMINAL.contains(row.getStatus())) return result(row);
- if (row.isCancelled() || ("STARTING".equals(row.getStatus()) && expired(row))) return cancel(body);
- if (row.isStartInFlight()) return result(row);
- Map<String,Object> outcome;
- try { outcome = adapter(row).status(row); }
- catch (RuntimeException unknown) { outcome = Map.of("status", "CLEANUP_PENDING"); }
- return result(merge(request, row, outcome, false, false));
- }
- public Map<String,Object> cancel(Map<String,Object> body) {
- VideoLifecycleRecord request = parse(body), row = store.find(request.getGeneration());
- if (row == null) {
- VideoLifecycleRecord tombstone = copy(request);
- tombstone.setCancelled(true); tombstone.setStatus("CLEANUP_PENDING");
- if (!store.compareAndSet(null, tombstone)) return cancel(body);
- // No dispatch evidence: do not guess a physical handle or claim completion.
- return result(tombstone);
- }
- sameSource(row, request);
- if (TERMINAL.contains(row.getStatus())) return result(row);
- row = transition(request, value -> {
- if (!TERMINAL.contains(value.getStatus())) {
- value.setCancelled(true); value.setStatus("CLEANUP_PENDING"); value.setMedia(null);
- }
- });
- if (row.getStream() != null) store.markStreamCancelled(row.getStream());
- return cleanup(request, row);
- }
- private Map<String,Object> cleanup(VideoLifecycleRecord request, VideoLifecycleRecord row) {
- Map<String,Object> outcome;
- try { outcome = adapter(row).cancel(row); }
- catch (RuntimeException unknown) { outcome = Map.of("status", "CLEANUP_PENDING"); }
- return result(merge(request, row, outcome, false, true));
- }
- /** Merge returned handles, but cancellation and terminal state always beat a stale snapshot. */
- private VideoLifecycleRecord merge(VideoLifecycleRecord request, VideoLifecycleRecord attempt,
- Map<String,Object> outcome, boolean completedStart, boolean cleanup) {
- return transition(request, row -> {
- if (TERMINAL.contains(row.getStatus())) return;
- if (completedStart) {
- row.setStartInFlight(false);
- if (expired(row)) row.setCancelled(true);
- }
- String state = outcome != null && outcome.get("status") != null && STATES.contains(outcome.get("status")) ? (String) outcome.get("status") : "CLEANUP_PENDING";
- if (row.getMediaServerId() == null) row.setMediaServerId(attempt.getMediaServerId());
- if (row.getStream() == null) row.setStream(attempt.getStream());
- if (row.getProxyKey() == null) row.setProxyKey(attempt.getProxyKey());
- if (row.getAdoptedHandle() == null) row.setAdoptedHandle(attempt.getAdoptedHandle());
- if (outcome != null) {
- if (outcome.get("stream") instanceof String) {
- String returned = (String) outcome.get("stream");
- if (row.getStream() != null && !row.getStream().equals(returned)) state = "CLEANUP_PENDING";
- else row.setStream(returned);
- }
- if (outcome.get("proxyKey") instanceof String) row.setProxyKey((String) outcome.get("proxyKey"));
- }
- if (row.isCancelled()) {
- row.setStatus(cleanup && !attempt.isStartInFlight() && !row.isStartInFlight() && TERMINAL.contains(state) ? state : "CLEANUP_PENDING");
- row.setMedia(null);
- } else if ("CLEANUP_PENDING".equals(state)) {
- row.setStatus(state); row.setCancelled(true); row.setMedia(null);
- } else if ("ACTIVE".equals(state)) {
- if (outcome.get("media") instanceof Map) {
- row.setMedia(new LinkedHashMap<>(cast(outcome.get("media")))); row.setStatus(state);
- } else { row.setStatus("CLEANUP_PENDING"); row.setCancelled(true); row.setMedia(null); }
- } else {
- row.setStatus(state); row.setMedia(null);
- }
- });
- }
- private VideoLifecycleRecord transition(VideoLifecycleRecord request, Consumer<VideoLifecycleRecord> change) {
- for (int retry = 0; retry < 32; retry++) {
- VideoLifecycleRecord before = store.find(request.getGeneration());
- if (before == null) throw new IllegalStateException("观看代次记录丢失,结果未确认");
- sameSource(before, request);
- VideoLifecycleRecord after = copy(before); change.accept(after);
- if (store.compareAndSet(before, after)) return after;
- }
- throw new IllegalStateException("观看代次状态变更繁忙,结果未确认");
- }
- private boolean expired(VideoLifecycleRecord row) { return row.getDeadline() <= clock.millis(); }
- private VideoLifecycleMedia adapter(VideoLifecycleRecord row) {
- return adapters.stream().filter(item -> item.supports(row.getSourceType())).findFirst()
- .orElseThrow(() -> new IllegalArgumentException("不支持的视频来源类型"));
- }
- private static void sameSource(VideoLifecycleRecord saved, VideoLifecycleRecord request) {
- if (!Objects.equals(saved.getSourceType(), request.getSourceType()) || !Objects.equals(saved.getVideoId(), request.getVideoId())
- || !Objects.equals(saved.getDeviceId(), request.getDeviceId()) || !Objects.equals(saved.getChannelId(), request.getChannelId())
- || !Objects.equals(saved.getUrl(), request.getUrl()) || !Objects.equals(saved.getDeadline(), request.getDeadline()))
- throw new IllegalArgumentException("观看代次的来源与截止时间不可改变");
- }
- private static VideoLifecycleRecord parse(Map<String,Object> body) {
- if (body == null) throw new IllegalArgumentException("请求体缺失");
- VideoLifecycleRecord row = new VideoLifecycleRecord();
- row.setGeneration(text(body.get("generation")));
- if (row.getGeneration() == null || !row.getGeneration().matches("[A-Za-z0-9_-]{1,64}")) throw new IllegalArgumentException("观看代次标识无效");
- if (!(body.get("source") instanceof Map)) throw new IllegalArgumentException("视频来源缺失");
- Map<String,Object> source = cast(body.get("source"));
- row.setSourceType(text(source.get("type"))); row.setVideoId(text(source.get("videoId")));
- row.setDeviceId(text(source.get("deviceId"))); row.setChannelId(text(source.get("channelId"))); row.setUrl(text(source.get("url")));
- if (row.getVideoId() == null || row.getSourceType() == null || !Set.of("GB28181", "MANUAL").contains(row.getSourceType())) throw new IllegalArgumentException("视频来源无效");
- if (!(body.get("startDeadline") instanceof Number)) throw new IllegalArgumentException("启动截止时间缺失");
- row.setDeadline(((Number) body.get("startDeadline")).longValue());
- if (row.getDeadline() <= 0) throw new IllegalArgumentException("启动截止时间无效");
- if (body.get("existingMedia") instanceof Map) {
- Map<String,Object> existing = cast(body.get("existingMedia"));
- row.setStream(text(existing.get("stream"))); row.setProxyKey(text(existing.get("proxyKey")));
- row.setMediaServerId(text(existing.get("mediaServerId")));
- }
- return row;
- }
- private static VideoLifecycleRecord copy(VideoLifecycleRecord row) {
- VideoLifecycleRecord copy = new VideoLifecycleRecord(); BeanUtils.copyProperties(row, copy); return copy;
- }
- @SuppressWarnings("unchecked") private static Map<String,Object> cast(Object value) { return (Map<String,Object>) value; }
- private static String text(Object value) { return value instanceof String && !((String) value).isBlank() ? (String) value : null; }
- private static Map<String,Object> pending(VideoLifecycleRecord row) {
- return Map.of("generation", row.getGeneration(), "status", "CLEANUP_PENDING");
- }
- private static Map<String,Object> result(VideoLifecycleRecord row) {
- Map<String,Object> result = new LinkedHashMap<>(); result.put("generation", row.getGeneration()); result.put("status", row.getStatus());
- if (!row.isCancelled() && "ACTIVE".equals(row.getStatus()) && row.getMedia() != null) result.put("media", row.getMedia());
- return result;
- }
- }
|