package run.webup.platform; import com.fasterxml.jackson.databind.*; import java.net.*; import java.net.http.*; import java.time.Duration; import java.util.*; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class RuntimeGateway { private final String base, token; private final ObjectMapper json; private final HttpClient client = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(5)) .followRedirects(HttpClient.Redirect.NEVER) .build(); public RuntimeGateway( @Value("${app.runtime-url:}") String base, @Value("${app.runtime-token:}") String token, ObjectMapper json) { this.base = base; this.token = token; this.json = json; } public JsonNode request(String path, Object payload) { if (base.isBlank() || token.length() < 32) throw new ApiError.Failure(503, "尚未配置 RUNTIME_URL 与 RUNTIME_TOKEN"); try { URI uri = URI.create(base.replaceAll("/+$", "") + path); if (!Set.of("http", "https").contains(uri.getScheme()) || uri.getUserInfo() != null) throw new IllegalArgumentException(); var builder = HttpRequest.newBuilder(uri) .timeout(Duration.ofSeconds(120)) .header("Authorization", "Bearer " + token) .header("Content-Type", "application/json"); if (payload != null) builder.POST(HttpRequest.BodyPublishers.ofString(json.writeValueAsString(payload))); else builder.GET(); var response = client.send(builder.build(), HttpResponse.BodyHandlers.ofInputStream()); try (var input = response.body()) { byte[] bytes = input.readNBytes(1048577); if (bytes.length > 1048576) throw new ApiError.Failure(502, "运行网关响应超出限制"); if (response.statusCode() != 200) throw new ApiError.Failure(502, "运行网关返回 HTTP " + response.statusCode()); return json.readTree(bytes); } } catch (ApiError.Failure f) { throw f; } catch (Exception e) { if (e instanceof InterruptedException) Thread.currentThread().interrupt(); throw new ApiError.Failure(502, "运行网关连接失败,已保留状态供重试核对"); } } }