Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import com.opentest.common.exception.CryBusinessException;
import com.opentest.common.exception.ErrorCode;
import com.opentest.service.CppHttpProxyService;
import com.opentest.service.FirmwareHttpTransferService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
Expand All @@ -25,6 +26,8 @@
import jakarta.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
* C++层HTTP接口调用控制层
Expand All @@ -44,6 +47,15 @@ public class CppHttpController extends BaseController {

@Resource
private CppHttpProxyService cppHttpProxyService;
@Resource
private FirmwareHttpTransferService firmwareHttpTransferService;

@PostMapping("/api/system/upgrade/upload/cancel")
public Object cancelFirmwareUpload(@RequestHeader(CPP_SERVER_IP_HEADER) String serverIp,
@RequestBody Map<String, String> command) {
firmwareHttpTransferService.cancel(command.get("uploadId"), serverIp);
return Map.of("code", 0, "data", Map.of("success", true));
}

/**
* 具体的接口示例 - 更新设备配置
Expand Down Expand Up @@ -97,7 +109,13 @@ public Object proxyRequest(

private Object forwardUpgrade(String serverIp, String path, HttpServletRequest request, byte[] body) {
try (var target = cppHttpProxyService.openFirmwareTarget(serverIp, path)) {
return forward(target.url(), request, body);
Map<String, String> headers = new HashMap<>();
for (String name : new String[]{"Accept-Language", "Content-Type"}) {
if (request.getHeader(name) != null) headers.put(name, request.getHeader(name));
}
String uploadId = UPGRADE_UPLOAD.equals(path) ? request.getHeader("Firmware-Upload-Id") : null;
var response = firmwareHttpTransferService.forward(target.url(), headers, body, uploadId, serverIp);
return buildProxyResponse(response.status(), response.body());
}
}

Expand Down Expand Up @@ -149,8 +167,10 @@ private Object forward(String targetUrl, HttpServletRequest request, byte[] body
}

private Object buildProxyResponse(HttpResponse response) {
int status = response.getStatus();
String responseBody = response.body();
return buildProxyResponse(response.getStatus(), response.body());
}

private Object buildProxyResponse(int status, String responseBody) {
Object body = responseBody;
boolean jsonResponse = false;
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
import com.opentest.common.exception.CryBusinessException;
import com.opentest.common.exception.ErrorCode;
import com.opentest.service.CppHttpProxyService;
import com.opentest.service.FirmwareHttpTransferService;
import com.opentest.service.jni.FirmwareUpgradeAccess;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.mock.web.MockHttpServletRequest;
Expand All @@ -16,6 +18,11 @@
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.junit.jupiter.api.Assertions.assertEquals;
Expand All @@ -35,9 +42,40 @@ class CppHttpFirmwareUpgradeTest {

private final CppHttpProxyService service = mock(CppHttpProxyService.class);
private final CppHttpController controller = new CppHttpController();
private final FirmwareHttpTransferService transfers = new FirmwareHttpTransferService();

CppHttpFirmwareUpgradeTest() {
ReflectionTestUtils.setField(controller, "cppHttpProxyService", service);
ReflectionTestUtils.setField(controller, "firmwareHttpTransferService", transfers);
}

@AfterEach void closeTransfers() { transfers.close(); }

@Test void cancelEndsTheStalledForwardAndReleasesTheDeviceReservation() throws Exception {
var access = new FirmwareUpgradeAccess();
var entered = new CountDownLatch(1);
var release = new CountDownLatch(1);
String id = UUID.randomUUID().toString();
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext(UPLOAD, exchange -> {
exchange.getRequestBody().readAllBytes(); entered.countDown();
try { release.await(5, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
exchange.close();
});
server.start();
try (var executor = Executors.newSingleThreadExecutor()) {
when(service.openFirmwareTarget(DEVICE, UPLOAD)).thenAnswer(invocation ->
new CppHttpProxyService.FirmwareTarget("http://127.0.0.1:" + server.getAddress().getPort() + UPLOAD,
access.reserveUpgrade(DEVICE)));
var request = post(UPLOAD); request.addHeader("Firmware-Upload-Id", id);
var result = executor.submit(() -> assertThrows(CryBusinessException.class,
() -> controller.proxyRequest(DEVICE, request, new byte[]{1})));
assertTrue(entered.await(2, TimeUnit.SECONDS));
assertThrows(CryBusinessException.class, () -> access.reserveActivity(List.of(DEVICE)));
controller.cancelFirmwareUpload(DEVICE, Map.of("uploadId", id));
result.get(2, TimeUnit.SECONDS);
try (var activity = access.reserveActivity(List.of(DEVICE))) { assertTrue(activity != null); }
} finally { release.countDown(); server.stop(0); }
}

@Test void uploadAndConfirmTakeTheSameGuardThroughNormalizedRoutes() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package com.opentest.controller;

import com.opentest.common.exception.CryBusinessException;
import com.opentest.service.FirmwareHttpTransferService;
import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.Test;
import org.springframework.test.util.ReflectionTestUtils;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

class FirmwareHttpTransferTest {
@Test void noResponseEndsAtTheConfiguredDeadline() throws Exception {
exerciseStalledTransfer(false);
}

@Test void cancellingTheAttemptEndsAStalledTransfer() throws Exception {
exerciseStalledTransfer(true);
}

@Test void cancellationBeforeAdmissionPreventsSendingTheUpload() {
var service = new FirmwareHttpTransferService();
String id = UUID.randomUUID().toString();
try {
service.cancel(id, "192.0.2.5");
assertThrows(CryBusinessException.class, () -> service.forward("http://127.0.0.1:1/upload",
Map.of(), new byte[]{1}, id, "192.0.2.5"));
assertThrows(CryBusinessException.class, () -> service.cancel("bad-id", "192.0.2.5"));
service.cancel(id, "192.0.2.5");
assertThrows(CryBusinessException.class, () -> service.cancel(id, "192.0.2.6"));
} finally { service.close(); }
}

private void exerciseStalledTransfer(boolean cancel) throws Exception {
var entered = new CountDownLatch(1);
var release = new CountDownLatch(1);
var service = new FirmwareHttpTransferService();
ReflectionTestUtils.setField(service, "timeoutMs", cancel ? 10_000L : 500L);
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/upload", exchange -> {
exchange.getRequestBody().readAllBytes(); entered.countDown();
try { release.await(5, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
exchange.close();
});
server.start();
try (var executor = Executors.newSingleThreadExecutor()) {
String id = UUID.randomUUID().toString();
var result = executor.submit(() -> assertThrows(CryBusinessException.class,
() -> service.forward("http://127.0.0.1:" + server.getAddress().getPort() + "/upload",
Map.of(), new byte[]{1}, id, "192.0.2.5")));
assertTrue(entered.await(2, TimeUnit.SECONDS));
if (cancel) service.cancel(id, "192.0.2.5");
result.get(2, TimeUnit.SECONDS);
assertEquals(0L, entered.getCount());
} finally { release.countDown(); server.stop(0); service.close(); }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package com.opentest.service;

import com.opentest.common.exception.CryBusinessException;
import com.opentest.common.exception.ErrorCode;
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/** Bounded firmware transfers; a client can cancel only its own upload attempt. */
@Service
public class FirmwareHttpTransferService {
private static final long CANCEL_RETENTION_MS = 660_000;
private final Map<String, Upload> uploads = new ConcurrentHashMap<>();
private final HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
@Value("${crydaq.firmware.http-timeout-ms:600000}")
private long timeoutMs = 600_000;

public record Response(int status, String body) { }

private static final class Upload {
private final String address;
private final long created = System.currentTimeMillis();
private volatile CompletableFuture<HttpResponse<String>> request;
private boolean cancelled;
private boolean started;
private Upload(String address) { this.address = address; }
}

public void cancel(String id, String address) {
Upload upload = entry(id, address);
synchronized (upload) {
upload.cancelled = true;
if (upload.request != null) upload.request.cancel(true);
}
}

public Response forward(String url, Map<String, String> headers, byte[] body, String uploadId, String address) {
Upload upload = uploadId == null ? null : entry(uploadId, address);
CompletableFuture<HttpResponse<String>> request = null;
boolean ownsUpload = false;
try {
long transferBudget = Math.max(30_000L, ((body == null ? 0L : body.length) + 511_999L) / 512_000L * 1_000L);
long deadlineMs = Math.min(timeoutMs, transferBudget);
HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(url))
.timeout(Duration.ofMillis(deadlineMs)).POST(HttpRequest.BodyPublishers.ofByteArray(body == null ? new byte[0] : body));
headers.forEach(builder::header);
if (upload == null) {
request = client.sendAsync(builder.build(), HttpResponse.BodyHandlers.ofString());
} else {
synchronized (upload) {
if (upload.cancelled) {
ownsUpload = true;
throw new CancellationException();
}
if (upload.started) throw new CryBusinessException(ErrorCode.PARAMETER, "固件上传标识已使用");
upload.started = true;
ownsUpload = true;
request = client.sendAsync(builder.build(), HttpResponse.BodyHandlers.ofString());
upload.request = request;
}
}
HttpResponse<String> response = request.get(deadlineMs, TimeUnit.MILLISECONDS);
return new Response(response.statusCode(), response.body());
} catch (InterruptedException failure) {
Thread.currentThread().interrupt();
throw new CryBusinessException(ErrorCode.FAILED, failure);
} catch (ExecutionException | TimeoutException | CancellationException failure) {
throw new CryBusinessException(ErrorCode.FAILED, failure);
} finally {
if (request != null) request.cancel(true);
if (ownsUpload) uploads.remove(uploadId, upload);
}
}

private Upload entry(String id, String address) {
try {
if (!UUID.fromString(id).toString().equalsIgnoreCase(id)) throw new IllegalArgumentException();
} catch (IllegalArgumentException | NullPointerException failure) {
throw new CryBusinessException(ErrorCode.PARAMETER, "固件上传标识无效");
}
long cutoff = System.currentTimeMillis() - CANCEL_RETENTION_MS;
uploads.entrySet().removeIf(entry -> entry.getValue().created < cutoff && entry.getValue().request == null);
Upload upload = uploads.computeIfAbsent(id, ignored -> new Upload(address));
if (!Objects.equals(upload.address, address)) {
throw new CryBusinessException(ErrorCode.PARAMETER, "固件上传目标不匹配");
}
return upload;
}

@PreDestroy
public void close() { client.shutdownNow(); }
}
Original file line number Diff line number Diff line change
Expand Up @@ -2045,11 +2045,20 @@ public void continueCaptureStop(Device device, List<ChannelDto> channels) throws
return;
}
// Stop也允许接收同一设备的完整领域对象,不能依赖Start曾改写某个共享对象的名称。
device.setDeviceName(getJniDeviceId(device));
String identity = device.getId() == null ? "name:" + device.getDeviceName() : "id:" + device.getId();
String nativeId = normalizeJniDeviceId(device.getDeviceName(), device.getIpAddress());
String identity = device.getId() == null ? "name:" + nativeId : "id:" + device.getId();
List<Integer> stoppedChannels = channels.stream().map(ChannelDto::getJniChannelNumber).toList();
// 仅串行同一设备的停止,不让慢设备占用整个 JNI 服务的实例锁。
synchronized (continuousCaptureStopLocks.computeIfAbsent(identity, key -> new Object())) {
stopContinuousCaptureDevice(device, channels);
boolean openDaq = "OPENDAQ".equalsIgnoreCase(channels.getFirst().getProtocol());
try {
device.setDeviceName(getJniDeviceId(device));
stopContinuousCaptureDevice(device, channels);
if (openDaq) continueCaptureManager.firmwareUpgradeAccess().captureStopped(nativeId, stoppedChannels);
} catch (RuntimeException | Error failure) {
if (openDaq) continueCaptureManager.firmwareUpgradeAccess().captureStopFailed(nativeId, stoppedChannels);
throw failure;
}
}
}

Expand Down Expand Up @@ -4018,6 +4027,7 @@ public void disconnectDevice(String deviceId) {
requireSelectedDevice("OPENDAQ", deviceId);
int code = audioJNIBridge.disconnectDevice("OPENDAQ", deviceId);
JNIUtils.checkJniReturn(code, "断开OPENDAQ设备");
continueCaptureManager.firmwareUpgradeAccess().deviceDisconnected(deviceId);
ownedOpenDaqConnections.remove(deviceId);
explicitDeviceConnections.forget(deviceId);
} finally {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,23 @@
public final class FirmwareUpgradeAccess {
private final Map<String, Integer> activities = new HashMap<>();
private final Set<String> upgrades = new HashSet<>();
private final Map<String, Set<Integer>> unconfirmedStops = new HashMap<>();

public synchronized void captureStopFailed(String deviceId, Collection<Integer> channels) {
unconfirmedStops.computeIfAbsent(deviceId, ignored -> new HashSet<>()).addAll(channels);
}

public synchronized void captureStopped(String deviceId, Collection<Integer> channels) {
Set<Integer> pending = unconfirmedStops.get(deviceId);
if (pending != null) {
pending.removeAll(channels);
if (pending.isEmpty()) unconfirmedStops.remove(deviceId);
}
}

public synchronized void deviceDisconnected(String deviceId) {
unconfirmedStops.remove(deviceId);
}

public synchronized Lease reserveActivity(Collection<String> deviceIds) {
List<String> ids = deviceIds.stream().distinct().toList();
Expand All @@ -25,7 +42,7 @@ public synchronized Lease reserveActivity(Collection<String> deviceIds) {
}

public synchronized Lease reserveUpgrade(String deviceId) {
if (activities.containsKey(deviceId) || !upgrades.add(deviceId)) {
if (activities.containsKey(deviceId) || unconfirmedStops.containsKey(deviceId) || !upgrades.add(deviceId)) {
throw new CryBusinessException(ErrorCode.JNI_DEVICE_BUSY);
}
return new Lease(List.of(deviceId), true);
Expand Down
Loading
Loading