feat(drone-dock): 完善真实联调、状态轮询与准备页反馈
开放 Release 真实操作并保留 Debug 拦截;恢复前台 shooting 串行轮询;统一打印机巢请求与完整原值响应;优化长点位名称、未拍摄文案、报备失败及已结束任务提示,移除成功回执 UI。补充相关测试、离线策略检查和联调说明。
This commit is contained in:
@@ -24,6 +24,7 @@ final class APIClient {
|
||||
private let decoder: JSONDecoder
|
||||
private let notificationCenter: NotificationCenter
|
||||
private let debugLogSink: (String) -> Void
|
||||
private let droneDockLogSink: (String) -> Void
|
||||
private var authTokenProvider: (() -> String?)?
|
||||
|
||||
private let environment: APIEnvironment
|
||||
@@ -39,7 +40,8 @@ final class APIClient {
|
||||
appVersion: String = AppClientInfo.appVersion(),
|
||||
osType: String = AppClientInfo.osType,
|
||||
notificationCenter: NotificationCenter = .default,
|
||||
debugLogSink: @escaping (String) -> Void = { print($0) }
|
||||
debugLogSink: @escaping (String) -> Void = { print($0) },
|
||||
droneDockLogSink: @escaping (String) -> Void = DroneDockDiagnostics.write
|
||||
) {
|
||||
self.environment = environment
|
||||
self.session = session
|
||||
@@ -47,6 +49,7 @@ final class APIClient {
|
||||
self.decoder = decoder
|
||||
self.notificationCenter = notificationCenter
|
||||
self.debugLogSink = debugLogSink
|
||||
self.droneDockLogSink = droneDockLogSink
|
||||
self.appVersion = appVersion.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty ?? "1.0.0"
|
||||
self.osType = osType.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty ?? AppClientInfo.osType
|
||||
}
|
||||
@@ -69,36 +72,69 @@ final class APIClient {
|
||||
_ apiRequest: APIRequest<Response>,
|
||||
tokenOverride: String? = nil
|
||||
) async throws -> Response {
|
||||
let request = try DeviceCommandDebugPolicy.prepare(
|
||||
makeURLRequest(apiRequest, tokenOverride: tokenOverride),
|
||||
isLocalSimulation: session is any LocalSimulationURLSession)
|
||||
logRequest(request, includeBody: apiRequest.logsPayload, category: apiRequest.redactedLogCategory)
|
||||
let original = try makeURLRequest(apiRequest, tokenOverride: tokenOverride)
|
||||
let isSimulation = session is any LocalSimulationURLSession
|
||||
let request: URLRequest
|
||||
do {
|
||||
request = try DeviceCommandDebugPolicy.prepare(original, isLocalSimulation: isSimulation)
|
||||
} catch {
|
||||
if let trace = DroneDockRequestTrace(request: original, isSimulation: isSimulation) {
|
||||
var fields = DroneDockDiagnostics.errorFields(error)
|
||||
fields["body"] = DroneDockDiagnostics.payload(original.httpBody)
|
||||
droneDockLogSink(trace.message("request.blocked", fields: fields))
|
||||
}
|
||||
throw error
|
||||
}
|
||||
let trace = DroneDockRequestTrace(request: request, isSimulation: isSimulation)
|
||||
if let trace {
|
||||
droneDockLogSink(trace.message("request.started", fields: ["body": DroneDockDiagnostics.payload(request.httpBody)]))
|
||||
} else {
|
||||
logRequest(request, includeBody: apiRequest.logsPayload, category: apiRequest.redactedLogCategory)
|
||||
}
|
||||
|
||||
let data: Data
|
||||
let response: URLResponse
|
||||
do {
|
||||
(data, response) = try await session.data(for: request)
|
||||
} catch is CancellationError {
|
||||
logCancelled(for: request, reason: "CancellationError", category: apiRequest.redactedLogCategory)
|
||||
if let trace { droneDockLogSink(trace.message("request.cancelled")) }
|
||||
else { logCancelled(for: request, reason: "CancellationError", category: apiRequest.redactedLogCategory) }
|
||||
throw CancellationError()
|
||||
} catch let error as URLError {
|
||||
if let trace { droneDockLogSink(trace.message(error.code == .cancelled ? "request.cancelled" : "request.failed",
|
||||
fields: DroneDockDiagnostics.errorFields(error))) }
|
||||
if error.code == .cancelled {
|
||||
logCancelled(for: request, reason: "URLError.cancelled", category: apiRequest.redactedLogCategory)
|
||||
if trace == nil { logCancelled(for: request, reason: "URLError.cancelled", category: apiRequest.redactedLogCategory) }
|
||||
throw CancellationError()
|
||||
}
|
||||
logFailure(for: request, error: error, category: apiRequest.redactedLogCategory)
|
||||
if trace == nil { logFailure(for: request, error: error, category: apiRequest.redactedLogCategory) }
|
||||
throw APIError.networkFailed(networkErrorMessage(for: error))
|
||||
} catch {
|
||||
logFailure(for: request, error: error, category: apiRequest.redactedLogCategory)
|
||||
if let trace { droneDockLogSink(trace.message("request.failed", fields: DroneDockDiagnostics.errorFields(error))) }
|
||||
if trace == nil { logFailure(for: request, error: error, category: apiRequest.redactedLogCategory) }
|
||||
throw APIError.networkFailed(error.localizedDescription)
|
||||
}
|
||||
|
||||
logResponse(for: request, response: response, data: data, includeBody: apiRequest.logsPayload,
|
||||
category: apiRequest.redactedLogCategory)
|
||||
if let trace {
|
||||
// 用户要求机巢接口原样记录请求和响应,含 live / STS;统一通路避免重复打印。
|
||||
droneDockLogSink(trace.message("response.received", fields: [
|
||||
"http_status": (response as? HTTPURLResponse)?.statusCode ?? 0,
|
||||
"response_headers": (response as? HTTPURLResponse)?.allHeaderFields.reduce(into: [String: String]()) {
|
||||
$0[String(describing: $1.key)] = String(describing: $1.value)
|
||||
} ?? [:],
|
||||
"body": DroneDockDiagnostics.payload(data)
|
||||
]))
|
||||
} else {
|
||||
logResponse(for: request, response: response, data: data, includeBody: apiRequest.logsPayload,
|
||||
category: apiRequest.redactedLogCategory)
|
||||
}
|
||||
do {
|
||||
try validateHTTPResponse(response, data: data)
|
||||
return try decodeEnvelope(Response.self, from: data)
|
||||
let value = try decodeEnvelope(Response.self, from: data)
|
||||
if let trace { droneDockLogSink(trace.message("response.decoded")) }
|
||||
return value
|
||||
} catch let error as APIError {
|
||||
if let trace { droneDockLogSink(trace.message("response.rejected", fields: DroneDockDiagnostics.errorFields(error))) }
|
||||
notifySessionErrorIfNeeded(for: error, request: request)
|
||||
throw error
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ nonisolated struct APIRequest<Response: Decodable> {
|
||||
var queryItems: [URLQueryItem]
|
||||
var headers: [String: String]
|
||||
var body: AnyEncodable?
|
||||
/// 敏感请求关闭正文日志,避免验证码和注销资产进入调试日志。
|
||||
/// 控制普通正文日志;机巢范围按用户要求始终记录完整请求和响应。
|
||||
var logsPayload: Bool
|
||||
/// 为指定模块输出带标签的脱敏日志;隐藏凭证字段和响应中媒体 URL 的查询参数。
|
||||
var redactedLogCategory: String?
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import Foundation
|
||||
|
||||
/// 禁飞期间的请求边界;正式包仅允许用户手动图传,不允许创建或飞控。
|
||||
/// 调试请求边界:Debug 禁止真实设备操作,Release 按用户授权开放已对接的操作。
|
||||
enum DeviceCommandDebugPolicy {
|
||||
/// 飞控与真实待飞任务在所有构建中关闭,不因打 Release 包而解除禁飞。
|
||||
static let blocksFlightRequests = true
|
||||
/// 2026-11-02 用户授权 Release 真机联调;Debug 仍无运行时放行开关。
|
||||
static var blocksFlightRequests: Bool {
|
||||
#if DEBUG
|
||||
true
|
||||
#else
|
||||
false
|
||||
#endif
|
||||
}
|
||||
/// 所有 Debug 构建禁止真实设备操作,没有启动参数或设置开关可临时放行。
|
||||
static var blocksLiveRequests: Bool {
|
||||
#if DEBUG
|
||||
@@ -20,12 +26,15 @@ enum DeviceCommandDebugPolicy {
|
||||
static func prepare(_ request: URLRequest, isLocalSimulation: Bool) throws -> URLRequest {
|
||||
guard !isLocalSimulation, let url = request.url else { return request }
|
||||
let path = "/" + url.path.split(separator: "/").joined(separator: "/")
|
||||
// 创建虽不直接起飞,但会改变真实订单状态;禁飞调试使用本地待飞任务。
|
||||
// Debug 创建也必须拦截,避免调试残留真实待飞任务。
|
||||
if path == "/api/yf-handset-app/photog/multi-plane/tasks/create" {
|
||||
throw DeviceCommandDebugBlockedError()
|
||||
guard !blocksFlightRequests, request.httpMethod == "POST" else { throw DeviceCommandDebugBlockedError() }
|
||||
return request
|
||||
}
|
||||
guard path == "/api/app/airport" || path.hasPrefix("/api/app/airport/") else { return request }
|
||||
// 2026-11-02 仅为用户后续手动图传测试提供 Release 入口;Debug 仍禁止开流。
|
||||
let flightPaths: Set<String> = ["/api/app/airport/shoot", "/api/app/airport/start-shoot", "/api/app/airport/command"]
|
||||
if !blocksFlightRequests, request.httpMethod == "POST", flightPaths.contains(path) { return request }
|
||||
// 仅允许已确认的图传和飞控接口;未知设备操作仍阻断。
|
||||
if request.httpMethod == "GET", path == "/api/app/airport/live", !blocksLiveRequests { return request }
|
||||
let readablePaths: Set<String> = [
|
||||
"/api/app/airport/home", "/api/app/airport/plane-status",
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import Foundation
|
||||
import OSLog
|
||||
|
||||
/// 机巢联调日志:按用户要求在 Debug 与 Release 控制台原样记录字段,不做脱敏。
|
||||
enum DroneDockDiagnostics {
|
||||
private static let logger = Logger(subsystem: "com.yuanzhixiang.suixinkan", category: "DroneDock")
|
||||
private static let sessionID = String(UUID().uuidString.prefix(8))
|
||||
|
||||
/// 按 UTF-8 字节分段,避免系统日志截断大响应;每段携带同一事件 ID 和序号。
|
||||
static func write(_ message: String) {
|
||||
let entry = String(UUID().uuidString.prefix(8))
|
||||
let chunks = chunks(message)
|
||||
for (index, chunk) in chunks.enumerated() {
|
||||
let line = "[DroneDock] session=\(sessionID) entry=\(entry) part=\(index + 1)/\(chunks.count) \(chunk)"
|
||||
logger.notice("\(line, privacy: .public)")
|
||||
}
|
||||
}
|
||||
|
||||
/// 页面、业务与 RTC 事件以结构化字段记录。
|
||||
static func event(_ name: String, taskID: Int? = nil, fields: [String: Any] = [:]) {
|
||||
var fields = fields
|
||||
fields["task_id"] = taskID
|
||||
fields["event"] = name
|
||||
write(json(fields))
|
||||
}
|
||||
|
||||
/// 覆盖机巢全部业务接口、景区空境库及共用 STS;不依赖页面或构建环境开关。
|
||||
static func includes(path: String) -> Bool {
|
||||
["/api/app/airport/", "/api/yf-handset-app/photog/multi-plane/", "/api/app/scenic-media/"]
|
||||
.contains(where: path.hasPrefix) || path == "/api/app/config/get-sts-token"
|
||||
}
|
||||
|
||||
/// JSON 保留完整字段,文本错误页原样记录;二进制正文只记录字节数。
|
||||
static func payload(_ data: Data?) -> Any {
|
||||
guard let data, !data.isEmpty else { return "<empty>" }
|
||||
return (try? JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed))
|
||||
?? String(data: data, encoding: .utf8)
|
||||
?? "<binary: \(data.count) bytes>"
|
||||
}
|
||||
|
||||
/// 排序 JSON 便于复制比对,所有字段值保持原样。
|
||||
static func json(_ object: Any) -> String {
|
||||
guard let data = try? JSONSerialization.data(withJSONObject: object,
|
||||
options: [.sortedKeys, .fragmentsAllowed, .withoutEscapingSlashes]),
|
||||
let text = String(data: data, encoding: .utf8) else { return "<invalid diagnostic fields>" }
|
||||
return text
|
||||
}
|
||||
|
||||
/// 记录业务码、HTTP 状态及原始错误说明,便于与后端回包对应。
|
||||
static func errorFields(_ error: Error) -> [String: Any] {
|
||||
if error is CancellationError { return ["kind": "cancelled"] }
|
||||
if error is DeviceCommandDebugBlockedError { return ["kind": "locally_blocked", "sent": false] }
|
||||
if case APIError.serverCode(let code, let message) = error {
|
||||
return ["kind": "business_rejected", "code": code, "message": message]
|
||||
}
|
||||
if case APIError.decodeFailed(let message) = error { return ["kind": "decode_failed", "message": message] }
|
||||
if case APIError.httpStatus(let code, let message) = error {
|
||||
return ["kind": "http_rejected", "http_status": code, "message": message]
|
||||
}
|
||||
if case APIError.emptyData = error { return ["kind": "empty_data"] }
|
||||
let value = error as NSError
|
||||
var fields: [String: Any] = ["kind": "error", "domain": value.domain, "code": value.code,
|
||||
"message": value.localizedDescription]
|
||||
fields["failing_url"] = value.userInfo[NSURLErrorFailingURLStringErrorKey] as? String
|
||||
return fields
|
||||
}
|
||||
|
||||
/// 单段最多 600 字节,长 JSON 可按 entry 和 part 拼回完整响应。
|
||||
static func chunks(_ text: String) -> [String] {
|
||||
var result: [String] = []
|
||||
var current = ""
|
||||
var bytes = 0
|
||||
for scalar in text.unicodeScalars {
|
||||
let next = String(scalar)
|
||||
if bytes + next.utf8.count > 600 { result.append(current); current = ""; bytes = 0 }
|
||||
current += next
|
||||
bytes += next.utf8.count
|
||||
}
|
||||
if !current.isEmpty { result.append(current) }
|
||||
return result.isEmpty ? [""] : result
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// 视频上传和素材下载的网络摘要,保留完整地址和传输状态。
|
||||
struct DroneDockFileTransferTrace: Sendable {
|
||||
private let requestID = UUID().uuidString
|
||||
private let started = ProcessInfo.processInfo.systemUptime
|
||||
private let operation: String
|
||||
private let method: String
|
||||
private let remoteURL: URL?
|
||||
|
||||
/// 仅在实际文件传输边界创建,记录传入的完整目标地址。
|
||||
init(operation: String, method: String, remoteURL: URL?) {
|
||||
self.operation = operation
|
||||
self.method = method
|
||||
self.remoteURL = remoteURL
|
||||
}
|
||||
|
||||
/// 请求、响应和错误共用同一关联 ID;文件响应仅记录状态与大小。
|
||||
func message(_ event: String, fields: [String: Any] = [:]) -> String {
|
||||
var fields = fields
|
||||
fields["event"] = operation + "." + event
|
||||
fields["request_id"] = requestID
|
||||
fields["elapsed_ms"] = Int((ProcessInfo.processInfo.systemUptime - started) * 1_000)
|
||||
fields["source"] = "network"
|
||||
fields["method"] = method
|
||||
fields["host"] = remoteURL?.host
|
||||
fields["url"] = remoteURL?.absoluteString
|
||||
return DroneDockDiagnostics.json(fields)
|
||||
}
|
||||
}
|
||||
|
||||
/// 一次请求的关联 ID 与耗时;模拟/真实传输明确区分,不把 HTTP 成功当作设备执行成功。
|
||||
struct DroneDockRequestTrace {
|
||||
private let requestID = UUID().uuidString
|
||||
private let started = ProcessInfo.processInfo.systemUptime
|
||||
private let request: URLRequest
|
||||
private let isSimulation: Bool
|
||||
|
||||
/// 未在机巢范围的请求不生成日志。
|
||||
init?(request: URLRequest, isSimulation: Bool) {
|
||||
guard DroneDockDiagnostics.includes(path: request.url?.path ?? "") else { return nil }
|
||||
self.request = request
|
||||
self.isSimulation = isSimulation
|
||||
}
|
||||
|
||||
/// 保留完整地址、请求头、业务参数与固定身份。
|
||||
func message(_ event: String, fields: [String: Any] = [:]) -> String {
|
||||
var fields = fields
|
||||
fields["event"] = event
|
||||
fields["request_id"] = requestID
|
||||
fields["elapsed_ms"] = Int((ProcessInfo.processInfo.systemUptime - started) * 1_000)
|
||||
fields["source"] = isSimulation ? "local_simulation" : "network"
|
||||
fields["host"] = request.url?.host
|
||||
fields["path"] = request.url?.path
|
||||
fields["method"] = request.httpMethod
|
||||
fields["url"] = request.url?.absoluteString
|
||||
fields["request_headers"] = request.allHTTPHeaderFields ?? [:]
|
||||
fields["app_version"] = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
|
||||
fields["app_build"] = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String
|
||||
#if DEBUG
|
||||
fields["build"] = "Debug"
|
||||
#else
|
||||
fields["build"] = "Release"
|
||||
#endif
|
||||
fields["flight_blocked"] = DeviceCommandDebugPolicy.blocksFlightRequests
|
||||
fields["live_blocked"] = DeviceCommandDebugPolicy.blocksLiveRequests
|
||||
let items = request.url.flatMap { URLComponents(url: $0, resolvingAgainstBaseURL: false)?.queryItems } ?? []
|
||||
fields["query"] = items.map { [$0.name: $0.value ?? ""] }
|
||||
return DroneDockDiagnostics.json(fields)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user