@h1r-ai/croche-react-native 0.5.5 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +69 -458
- package/THIRD-PARTY-NOTICES +7 -8
- package/android/build.gradle +6 -1
- package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +125 -0
- package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +81 -0
- package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +83 -0
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +45 -824
- package/android/src/main/java/dev/croche/reactnative/NativePal.kt +51 -0
- package/android/src/main/java/dev/croche/reactnative/RNHostPal.kt +9 -0
- package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +42 -41
- package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +71 -0
- package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +29 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +19 -32
- package/android/src/test/java/dev/croche/reactnative/ProjectHandlerStagesTest.kt +32 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectRecoveryTest.kt +12 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +11 -15
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidEventSink.kt +27 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +6 -6
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundRegistration.kt +16 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +51 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +162 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageInput.kt +15 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapOrientation.kt +40 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapPalCodec.kt +66 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +8 -8
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidAssetPal.kt +30 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreFactory.kt +35 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +121 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidMainDispatcher.kt +17 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +17 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidS2Pal.kt +14 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +73 -0
- package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +5 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +45 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +16 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +60 -105
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +47 -107
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +41 -40
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +67 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +20 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +18 -20
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +322 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +71 -34
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ImagePal.kt +183 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +9 -7
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +47 -19
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +5 -5
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +1 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +9 -9
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +108 -37
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +44 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ReaderValues.kt +73 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +40 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +23 -21
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +8 -8
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +18 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +50 -25
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +22 -22
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8285 -2159
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppEventSink.kt +34 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +25 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundOsRegistration.kt +35 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundSink.kt +37 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreDefinitionCalls.kt +35 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +31 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +41 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +35 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +128 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +72 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +34 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/LifecycleBinding.kt +18 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +45 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PalCallbacks.kt +27 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PlainToolJson.kt +56 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +34 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ScopeJson.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ToolCompletionEncoding.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +79 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/DirectHttpPal.kt +223 -0
- package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
- package/dist/package.json +1 -0
- package/dist/react-native/src/NativeCrocheRuntime.d.ts +16 -0
- package/dist/react-native/src/NativeCrocheRuntime.js +2 -0
- package/dist/react-native/src/core-native.d.ts +3 -0
- package/dist/react-native/src/core-native.js +193 -0
- package/dist/react-native/src/core-wire.d.ts +38 -0
- package/dist/react-native/src/core-wire.js +1 -0
- package/dist/react-native/src/native-module.d.ts +8 -0
- package/dist/react-native/src/native-module.js +53 -0
- package/dist/rn-shared-build.json +16 -0
- package/dist/runtime/src/agent.d.ts +43 -0
- package/dist/runtime/src/agent.js +75 -0
- package/dist/runtime/src/app-api.d.ts +284 -0
- package/dist/runtime/src/app-api.js +1 -0
- package/dist/runtime/src/cancel.d.ts +9 -0
- package/dist/runtime/src/cancel.js +24 -0
- package/dist/runtime/src/core/port.d.ts +234 -0
- package/dist/runtime/src/core/port.js +1 -0
- package/dist/runtime/src/core/wasm.d.ts +1 -0
- package/dist/runtime/src/core/wasm.js +2 -0
- package/dist/runtime/src/croche.d.ts +42 -0
- package/dist/runtime/src/croche.js +111 -0
- package/dist/runtime/src/errors.d.ts +26 -0
- package/dist/runtime/src/errors.js +49 -0
- package/dist/runtime/src/events.d.ts +5 -0
- package/dist/runtime/src/events.js +31 -0
- package/dist/runtime/src/generated/app-stream.d.ts +174 -0
- package/dist/runtime/src/generated/app-stream.js +124 -0
- package/dist/runtime/src/index.native.d.ts +21 -0
- package/dist/runtime/src/index.native.js +8 -0
- package/dist/runtime/src/json.d.ts +13 -0
- package/dist/runtime/src/json.js +120 -0
- package/dist/runtime/src/native-adapter.d.ts +3 -0
- package/dist/runtime/src/native-adapter.js +24 -0
- package/dist/runtime/src/pal/codec.d.ts +15 -0
- package/dist/runtime/src/pal/codec.js +52 -0
- package/dist/runtime/src/pal/host.d.ts +5 -0
- package/dist/runtime/src/pal/host.js +35 -0
- package/dist/runtime/src/pal/platform.d.ts +16 -0
- package/dist/runtime/src/pal/platform.js +7 -0
- package/dist/runtime/src/rn-entry.d.ts +1 -0
- package/dist/runtime/src/rn-entry.js +4 -0
- package/dist/runtime/src/run-tool.d.ts +33 -0
- package/dist/runtime/src/run-tool.js +7 -0
- package/dist/runtime/src/tools.d.ts +19 -0
- package/dist/runtime/src/tools.js +70 -0
- package/ios/CoreAgentTransport.swift +14 -0
- package/ios/CoreDeliveryTransport.swift +58 -0
- package/ios/CoreNativePal.swift +93 -0
- package/ios/CorePlatformTransport.swift +44 -0
- package/ios/CoreWireDispatch.swift +92 -0
- package/ios/CoreWireSupport.swift +111 -0
- package/ios/CrocheRuntimeBridge.swift +34 -994
- package/ios/ProjectPal.swift +46 -0
- package/ios/RNCrocheRuntime.mm +18 -201
- package/ios/vendor/CrocheRuntimeSDK/AppBuildFacts.swift +112 -0
- package/ios/vendor/CrocheRuntimeSDK/Background.swift +11 -11
- package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +64 -0
- package/ios/vendor/CrocheRuntimeSDK/DirectHTTP.swift +258 -0
- package/ios/vendor/CrocheRuntimeSDK/Effects.swift +17 -17
- package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +85 -43
- package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +443 -0
- package/ios/vendor/CrocheRuntimeSDK/Host.swift +122 -61
- package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +410 -0
- package/ios/vendor/CrocheRuntimeSDK/Images.swift +10 -9
- package/ios/vendor/CrocheRuntimeSDK/JSON.swift +4 -4
- package/ios/vendor/CrocheRuntimeSDK/Offload.swift +24 -0
- package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +37 -36
- package/ios/vendor/CrocheRuntimeSDK/Platform.swift +35 -35
- package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +285 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +266 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +195 -0
- package/ios/vendor/CrocheRuntimeSDK/Project.swift +209 -95
- package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +97 -123
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +195 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +33 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +161 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +234 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +28 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +177 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +61 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +95 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +105 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +209 -0
- package/ios/vendor/CrocheRuntimeSDK/Storage.swift +52 -52
- package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +180 -137
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +16 -10
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +131 -116
- package/ios/vendor/CrocheRuntimeSDK/Truncate.swift +12 -0
- package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +7209 -2803
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +1342 -218
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +1342 -218
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
- package/package.json +18 -8
- package/scripts/README.md +11 -0
- package/scripts/build-shared.mjs +46 -0
- package/scripts/build.mjs +11 -0
- package/scripts/vendor-native.sh +5 -4
- package/src/NativeCrocheRuntime.ts +12 -159
- package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +0 -25
- package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +0 -17
- package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +0 -14
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +0 -178
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +0 -79
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +0 -46
- package/ios/vendor/CrocheRuntimeSDK/Control.swift +0 -192
- package/src/index.ts +0 -664
- package/src/project-types.ts +0 -35
- package/src/project.ts +0 -434
- package/src/protocol.ts +0 -28
- package/src/types.ts +0 -9
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
#if canImport(Network)
|
|
3
|
+
import Network
|
|
4
|
+
import Security
|
|
5
|
+
|
|
6
|
+
/// One direct HTTP/1.1 exchange to Core's pinned address (parity with Android's DirectHttpPal):
|
|
7
|
+
/// Network.framework to `connectTo`, TLS server name AND peer verification = the URL host, ALPN
|
|
8
|
+
/// http/1.1 only, no redirects, proxy, pool, cookies or cache. Core supplies policy and the
|
|
9
|
+
/// deadline; this supplies bytes. Shared cases: vectors/http-pal-direct.json.
|
|
10
|
+
final class DirectHTTP: @unchecked Sendable {
|
|
11
|
+
/// Test anchors only (the vector harness's throwaway certificate); nil = the system trust store.
|
|
12
|
+
private let anchors: [SecCertificate]?
|
|
13
|
+
init(anchors: [SecCertificate]? = nil) { self.anchors = anchors }
|
|
14
|
+
|
|
15
|
+
private static let lineLimit = 8192, headLimit = 65536, interimLimit = 16
|
|
16
|
+
|
|
17
|
+
func http(_ request: PalHttpRequest, pin: String, sink: any HttpSinkProtocol, cancel: CancelToken) throws {
|
|
18
|
+
guard let url = URLComponents(string: request.url), let rawHost = url.host, !rawHost.isEmpty,
|
|
19
|
+
let scheme = url.scheme, scheme == "https" || scheme == "http" else { throw LegacyCrocheError("invalid_abi", "Invalid HTTP URL") }
|
|
20
|
+
guard url.user == nil, url.password == nil else { throw LegacyCrocheError("invalid_abi", "HTTP user info is unsupported") }
|
|
21
|
+
let host = rawHost.hasPrefix("[") ? String(rawHost.dropFirst().dropLast()) : rawHost
|
|
22
|
+
let address = try Self.numeric(pin)
|
|
23
|
+
let tls = scheme == "https"
|
|
24
|
+
let port = url.port ?? (tls ? 443 : 80)
|
|
25
|
+
guard let endpointPort = NWEndpoint.Port(rawValue: UInt16(clamping: port)) else { throw LegacyCrocheError("invalid_abi", "Invalid HTTP port") }
|
|
26
|
+
let head = try Self.requestHead(request, url: url)
|
|
27
|
+
if cancel.isCancelled() { throw LegacyCrocheError("cancelled", "The request was cancelled.") }
|
|
28
|
+
|
|
29
|
+
let connection = NWConnection(host: address, port: endpointPort, using: parameters(tls: tls, host: host))
|
|
30
|
+
let wire = Wire(connection)
|
|
31
|
+
cancel.onCancel(callback: Closer(wire, reason: "cancelled"))
|
|
32
|
+
let deadline = DispatchWorkItem { wire.close(reason: "deadline") }
|
|
33
|
+
DispatchQueue.global().asyncAfter(deadline: .now() + .milliseconds(Int(clamping: max(1, request.timeoutMs))), execute: deadline)
|
|
34
|
+
defer { deadline.cancel(); wire.close(reason: nil) }
|
|
35
|
+
do {
|
|
36
|
+
try wire.start()
|
|
37
|
+
try wire.send(head + Data((request.body ?? "").utf8))
|
|
38
|
+
try Self.readResponse(wire, request, sink, cancel)
|
|
39
|
+
} catch {
|
|
40
|
+
if cancel.isCancelled() { throw LegacyCrocheError("cancelled", "The request was cancelled.") }
|
|
41
|
+
if let error = error as? LegacyCrocheError, error.code != "network_error" { throw error }
|
|
42
|
+
throw LegacyCrocheError("network_error", "HTTP transport failed")
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
private func parameters(tls: Bool, host: String) -> NWParameters {
|
|
47
|
+
let tcp = NWProtocolTCP.Options()
|
|
48
|
+
guard tls else { let p = NWParameters(tls: nil, tcp: tcp); p.preferNoProxies = true; return p }
|
|
49
|
+
let options = NWProtocolTLS.Options(), sec = options.securityProtocolOptions
|
|
50
|
+
sec_protocol_options_set_tls_server_name(sec, host)
|
|
51
|
+
sec_protocol_options_add_tls_application_protocol(sec, "http/1.1")
|
|
52
|
+
let anchors = self.anchors
|
|
53
|
+
// The name verified is the URL host, never the pinned address.
|
|
54
|
+
sec_protocol_options_set_verify_block(sec, { _, trustRef, complete in
|
|
55
|
+
let trust = sec_trust_copy_ref(trustRef).takeRetainedValue()
|
|
56
|
+
SecTrustSetPolicies(trust, SecPolicyCreateSSL(true, host as CFString))
|
|
57
|
+
if let anchors { SecTrustSetAnchorCertificates(trust, anchors as CFArray); SecTrustSetAnchorCertificatesOnly(trust, true) }
|
|
58
|
+
complete(SecTrustEvaluateWithError(trust, nil))
|
|
59
|
+
}, DispatchQueue.global())
|
|
60
|
+
let p = NWParameters(tls: options, tcp: tcp); p.preferNoProxies = true
|
|
61
|
+
return p
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/// A malformed pin never reaches a resolver or an unpinned fallback.
|
|
65
|
+
static func numeric(_ pin: String) throws -> NWEndpoint.Host {
|
|
66
|
+
if let v4 = IPv4Address(pin), pin.split(separator: ".").count == 4, pin.allSatisfy({ $0.isNumber || $0 == "." }) { return .ipv4(v4) }
|
|
67
|
+
if pin.contains(":"), pin.allSatisfy({ $0.isHexDigit || $0 == ":" || $0 == "." }), let v6 = IPv6Address(pin) { return .ipv6(v6) }
|
|
68
|
+
throw LegacyCrocheError("invalid_abi", "Invalid HTTP connectTo")
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
static func requestHead(_ request: PalHttpRequest, url: URLComponents) throws -> Data {
|
|
72
|
+
let target = (url.percentEncodedPath.isEmpty ? "/" : url.percentEncodedPath) + (url.percentEncodedQuery.map { "?" + $0 } ?? "")
|
|
73
|
+
let authority = (url.percentEncodedHost ?? "") + (url.port.map { ":\($0)" } ?? "")
|
|
74
|
+
func line(_ value: String) throws -> String {
|
|
75
|
+
// Bytes, not Characters: "\r\n" is one grapheme, so contains("\r") would miss it.
|
|
76
|
+
guard !value.utf8.contains(13), !value.utf8.contains(10) else { throw LegacyCrocheError("invalid_abi", "Invalid HTTP request line") }
|
|
77
|
+
return value
|
|
78
|
+
}
|
|
79
|
+
var text = "\(try line(request.method)) \(try line(target)) HTTP/1.1\r\nHost: \(authority)\r\nConnection: close\r\n"
|
|
80
|
+
for header in request.headers where !["host", "connection", "content-length", "transfer-encoding"].contains(header.name.lowercased()) {
|
|
81
|
+
text += "\(try line(header.name)): \(try line(header.value))\r\n"
|
|
82
|
+
}
|
|
83
|
+
if let body = request.body { text += "Content-Length: \(body.utf8.count)\r\n" }
|
|
84
|
+
return Data((text + "\r\n").utf8)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
private static func bad(_ what: String) -> LegacyCrocheError { LegacyCrocheError("network_error", what) }
|
|
88
|
+
|
|
89
|
+
static func readResponse(_ wire: Wire, _ request: PalHttpRequest, _ sink: any HttpSinkProtocol, _ cancel: CancelToken) throws {
|
|
90
|
+
var status = 0, headers: [PalHeader] = [], interims = 0
|
|
91
|
+
repeat {
|
|
92
|
+
let statusLine = try wire.line(limit: lineLimit)
|
|
93
|
+
let parts = statusLine.split(separator: " ", maxSplits: 2, omittingEmptySubsequences: false)
|
|
94
|
+
guard statusLine.hasPrefix("HTTP/1."), parts.count >= 2, let code = Int(parts[1]), (100...599).contains(code) else { throw bad("Invalid HTTP status") }
|
|
95
|
+
status = code; headers = []
|
|
96
|
+
var bytes = statusLine.utf8.count
|
|
97
|
+
while true {
|
|
98
|
+
let field = try wire.line(limit: lineLimit)
|
|
99
|
+
bytes += field.utf8.count + 2
|
|
100
|
+
guard bytes <= headLimit else { throw bad("HTTP headers exceed bound") }
|
|
101
|
+
if field.isEmpty { break }
|
|
102
|
+
guard let colon = field.firstIndex(of: ":"), colon != field.startIndex, !(field.first?.isWhitespace ?? true) else { throw bad("Invalid HTTP header") }
|
|
103
|
+
headers.append(PalHeader(name: String(field[..<colon]), value: field[field.index(after: colon)...].trimmingCharacters(in: .whitespaces)))
|
|
104
|
+
}
|
|
105
|
+
interims += 1
|
|
106
|
+
guard interims <= interimLimit else { throw bad("Too many interim responses") }
|
|
107
|
+
} while (100...199).contains(status) && status != 101
|
|
108
|
+
sink.head(status: UInt16(status), headers: headers)
|
|
109
|
+
if request.method == "HEAD" || (100...199).contains(status) || status == 204 || status == 304 { return }
|
|
110
|
+
let lengths = Set(headers.filter { $0.name.lowercased() == "content-length" }.map(\.value))
|
|
111
|
+
guard lengths.count <= 1 else { throw bad("Conflicting HTTP lengths") }
|
|
112
|
+
let codings = headers.filter { $0.name.lowercased() == "transfer-encoding" }.map { $0.value.lowercased() }
|
|
113
|
+
guard codings.isEmpty || codings == ["chunked"] else { throw bad("Unsupported HTTP transfer coding") }
|
|
114
|
+
var received: UInt64 = 0
|
|
115
|
+
/// false = the sink wants no more.
|
|
116
|
+
func copy(_ count: Int?) throws -> Bool {
|
|
117
|
+
var remaining = count
|
|
118
|
+
while remaining.map({ $0 > 0 }) ?? true {
|
|
119
|
+
if cancel.isCancelled() { throw LegacyCrocheError("cancelled", "The request was cancelled.") }
|
|
120
|
+
guard let piece = try wire.read(max: min(remaining ?? 65536, 65536)) else {
|
|
121
|
+
if remaining != nil { throw bad("HTTP body ended early") }
|
|
122
|
+
return true
|
|
123
|
+
}
|
|
124
|
+
received += UInt64(piece.count)
|
|
125
|
+
guard received <= request.maxResponseBytes else { throw LegacyCrocheError("invalid_response", "HTTP response exceeds bound") }
|
|
126
|
+
if !sink.chunk(bytes: piece) { return false }
|
|
127
|
+
remaining = remaining.map { $0 - piece.count }
|
|
128
|
+
}
|
|
129
|
+
return true
|
|
130
|
+
}
|
|
131
|
+
if !codings.isEmpty {
|
|
132
|
+
while true {
|
|
133
|
+
let sizeLine = try wire.line(limit: lineLimit)
|
|
134
|
+
let digits = sizeLine.split(separator: ";", maxSplits: 1, omittingEmptySubsequences: false).first?.trimmingCharacters(in: .whitespaces) ?? ""
|
|
135
|
+
guard !digits.isEmpty, digits.allSatisfy(\.isHexDigit), let size = Int(digits, radix: 16) else { throw bad("Invalid HTTP chunk") }
|
|
136
|
+
if size == 0 {
|
|
137
|
+
var trailerBytes = 0
|
|
138
|
+
while true {
|
|
139
|
+
let trailer = try wire.line(limit: lineLimit)
|
|
140
|
+
trailerBytes += trailer.utf8.count + 2
|
|
141
|
+
guard trailerBytes <= headLimit else { throw bad("HTTP trailers exceed bound") }
|
|
142
|
+
if trailer.isEmpty { return }
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
if try !copy(size) { return }
|
|
146
|
+
guard try wire.line(limit: lineLimit).isEmpty else { throw bad("Invalid chunk terminator") }
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if let text = lengths.first {
|
|
150
|
+
guard text.allSatisfy(\.isNumber), let length = Int(text) else { throw bad("Invalid HTTP length") }
|
|
151
|
+
_ = try copy(length)
|
|
152
|
+
} else { _ = try copy(nil) }
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/// A blocking view of one connection for the PAL's worker thread: start, send, and buffered reads.
|
|
157
|
+
final class Wire: @unchecked Sendable {
|
|
158
|
+
private let connection: NWConnection
|
|
159
|
+
private let queue = DispatchQueue(label: "ai.croche.direct-http")
|
|
160
|
+
private var buffer = Data()
|
|
161
|
+
private var ended = false
|
|
162
|
+
private let lock = NSLock()
|
|
163
|
+
private var closedReason: String?
|
|
164
|
+
init(_ connection: NWConnection) { self.connection = connection }
|
|
165
|
+
|
|
166
|
+
func close(reason: String?) {
|
|
167
|
+
lock.withLock { if closedReason == nil { closedReason = reason ?? "closed" } }
|
|
168
|
+
connection.cancel()
|
|
169
|
+
}
|
|
170
|
+
private func failIfClosed() throws {
|
|
171
|
+
if let reason = lock.withLock({ closedReason }) { throw LegacyCrocheError(reason == "cancelled" ? "cancelled" : "network_error", "HTTP transport \(reason)") }
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
func start() throws {
|
|
175
|
+
let ready = DispatchSemaphore(value: 0)
|
|
176
|
+
let outcome = Box<Bool>()
|
|
177
|
+
connection.stateUpdateHandler = { state in
|
|
178
|
+
switch state {
|
|
179
|
+
case .ready: outcome.once(true) { ready.signal() }
|
|
180
|
+
case .failed, .cancelled, .waiting: outcome.once(false) { ready.signal() }
|
|
181
|
+
default: break
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
connection.start(queue: queue)
|
|
185
|
+
ready.wait()
|
|
186
|
+
try failIfClosed()
|
|
187
|
+
guard outcome.value == true else { throw LegacyCrocheError("network_error", "HTTP connection failed") }
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
func send(_ data: Data) throws {
|
|
191
|
+
let done = DispatchSemaphore(value: 0), failed = Box<Bool>()
|
|
192
|
+
connection.send(content: data, completion: .contentProcessed { error in failed.once(error != nil) { done.signal() } })
|
|
193
|
+
done.wait()
|
|
194
|
+
try failIfClosed()
|
|
195
|
+
if failed.value == true { throw LegacyCrocheError("network_error", "HTTP send failed") }
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/// Fills the buffer once. false = the peer ended the stream.
|
|
199
|
+
private func fill() throws -> Bool {
|
|
200
|
+
if ended { return false }
|
|
201
|
+
let done = DispatchSemaphore(value: 0)
|
|
202
|
+
let result = Box<(Data?, Bool, Bool)>()
|
|
203
|
+
connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { data, _, complete, error in
|
|
204
|
+
result.once((data, complete, error != nil)) { done.signal() }
|
|
205
|
+
}
|
|
206
|
+
done.wait()
|
|
207
|
+
try failIfClosed()
|
|
208
|
+
guard let (data, complete, failed) = result.value, !failed else { throw LegacyCrocheError("network_error", "HTTP receive failed") }
|
|
209
|
+
if let data { buffer.append(data) }
|
|
210
|
+
if complete { ended = true }
|
|
211
|
+
return !(data?.isEmpty ?? true) || !complete
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/// One CRLF-terminated line, without it. A bare LF, an over-long line or EOF fails.
|
|
215
|
+
func line(limit: Int) throws -> String {
|
|
216
|
+
while true {
|
|
217
|
+
if let cr = buffer.firstIndex(of: 13) {
|
|
218
|
+
guard cr - buffer.startIndex <= limit else { throw LegacyCrocheError("network_error", "HTTP line exceeds bound") }
|
|
219
|
+
guard buffer.index(after: cr) < buffer.endIndex else { if try !fill() { throw LegacyCrocheError("network_error", "HTTP stream ended") }; continue }
|
|
220
|
+
guard buffer[buffer.index(after: cr)] == 10 else { throw LegacyCrocheError("network_error", "Invalid HTTP line ending") }
|
|
221
|
+
if buffer[buffer.startIndex..<cr].contains(10) { throw LegacyCrocheError("network_error", "Invalid HTTP line ending") }
|
|
222
|
+
let text = String(decoding: buffer[buffer.startIndex..<cr], as: UTF8.self)
|
|
223
|
+
buffer.removeSubrange(buffer.startIndex...buffer.index(after: cr))
|
|
224
|
+
return text
|
|
225
|
+
}
|
|
226
|
+
if buffer.contains(10) { throw LegacyCrocheError("network_error", "Invalid HTTP line ending") }
|
|
227
|
+
guard buffer.count <= limit else { throw LegacyCrocheError("network_error", "HTTP line exceeds bound") }
|
|
228
|
+
if try !fill() { throw LegacyCrocheError("network_error", "HTTP stream ended") }
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/// Up to `max` bytes; nil at the end of the stream.
|
|
233
|
+
func read(max: Int) throws -> Data? {
|
|
234
|
+
if buffer.isEmpty, try !fill(), buffer.isEmpty { return nil }
|
|
235
|
+
if buffer.isEmpty { return try read(max: max) }
|
|
236
|
+
let piece = buffer.prefix(max)
|
|
237
|
+
buffer.removeFirst(piece.count)
|
|
238
|
+
return Data(piece)
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
private final class Box<T>: @unchecked Sendable {
|
|
243
|
+
private let lock = NSLock()
|
|
244
|
+
private var stored: T?
|
|
245
|
+
var value: T? { lock.withLock { stored } }
|
|
246
|
+
func once(_ value: T, _ then: () -> Void) {
|
|
247
|
+
let first = lock.withLock { () -> Bool in guard stored == nil else { return false }; stored = value; return true }
|
|
248
|
+
if first { then() }
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
private final class Closer: CancelCallback, @unchecked Sendable {
|
|
253
|
+
private weak var wire: Wire?
|
|
254
|
+
private let reason: String
|
|
255
|
+
init(_ wire: Wire, reason: String) { self.wire = wire; self.reason = reason }
|
|
256
|
+
func cancelled() { wire?.close(reason: reason) }
|
|
257
|
+
}
|
|
258
|
+
#endif
|
|
@@ -4,16 +4,16 @@ import FoundationNetworking
|
|
|
4
4
|
#endif
|
|
5
5
|
|
|
6
6
|
/// Cooperative tool cancellation. A cancelled invocation is never automatically replayed.
|
|
7
|
-
|
|
7
|
+
final class RuntimeCancellation: @unchecked Sendable {
|
|
8
8
|
private let lock = NSLock()
|
|
9
9
|
private var stopped = false
|
|
10
10
|
private var listeners: [UUID: @Sendable () -> Void] = [:]
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
if isCancelled { throw
|
|
11
|
+
init() {}
|
|
12
|
+
var isCancelled: Bool { lock.withLock { stopped } }
|
|
13
|
+
func check() throws {
|
|
14
|
+
if isCancelled { throw LegacyCrocheError("cancelled", "The operation was cancelled") }
|
|
15
15
|
}
|
|
16
|
-
|
|
16
|
+
func cancel() {
|
|
17
17
|
let callbacks = lock.withLock { () -> [@Sendable () -> Void] in
|
|
18
18
|
guard !stopped else { return [] }; stopped = true
|
|
19
19
|
let values = Array(listeners.values); listeners.removeAll(); return values
|
|
@@ -62,7 +62,7 @@ func bounded<T: Sendable>(milliseconds: Double?, cancellation: RuntimeCancellati
|
|
|
62
62
|
return try await withCheckedThrowingContinuation { continuation in
|
|
63
63
|
let race = EffectRace<T>(continuation)
|
|
64
64
|
let listener = cancellation.observe {
|
|
65
|
-
local.cancel(); race.finish(.failure(
|
|
65
|
+
local.cancel(); race.finish(.failure(LegacyCrocheError("cancelled", "The operation was cancelled")))
|
|
66
66
|
}
|
|
67
67
|
race.add(Task {
|
|
68
68
|
do { try local.check(); let value = try await body(local); try local.check(); race.finish(.success(value)) }
|
|
@@ -73,7 +73,7 @@ func bounded<T: Sendable>(milliseconds: Double?, cancellation: RuntimeCancellati
|
|
|
73
73
|
race.add(Task {
|
|
74
74
|
do {
|
|
75
75
|
try await Task.sleep(nanoseconds: UInt64(max(1, milliseconds) * 1_000_000))
|
|
76
|
-
race.finish(.failure(
|
|
76
|
+
race.finish(.failure(LegacyCrocheError("timeout", "The effect deadline expired"))); local.cancel()
|
|
77
77
|
cancellation.remove(listener)
|
|
78
78
|
} catch {}
|
|
79
79
|
})
|
|
@@ -82,7 +82,7 @@ func bounded<T: Sendable>(milliseconds: Double?, cancellation: RuntimeCancellati
|
|
|
82
82
|
|
|
83
83
|
/// `onDelta` receives each server-sent event's data while a streamed response arrives, in
|
|
84
84
|
/// order; the Rust Core assembles them. A transport that cannot stream never calls it.
|
|
85
|
-
|
|
85
|
+
typealias RuntimeHTTP = @Sendable (_ effect: JSON, _ cancellation: RuntimeCancellation,
|
|
86
86
|
_ onDelta: @escaping @Sendable (String) async -> Void) async throws -> JSON
|
|
87
87
|
|
|
88
88
|
private let maxResponseBytes = 2 * 1024 * 1024
|
|
@@ -91,12 +91,12 @@ private let maxStreamBytes = 3 * maxResponseBytes
|
|
|
91
91
|
|
|
92
92
|
/// Ephemeral URLSession transport: no cookies/cache, no redirects, 2MiB response bound.
|
|
93
93
|
/// A `text/event-stream` answer is read incrementally and its deltas are handed on.
|
|
94
|
-
|
|
95
|
-
|
|
94
|
+
enum RuntimeURLSession {
|
|
95
|
+
static func send(_ effect: JSON, cancellation: RuntimeCancellation,
|
|
96
96
|
onDelta: @escaping @Sendable (String) async -> Void = { _ in }) async throws -> JSON {
|
|
97
97
|
try cancellation.check()
|
|
98
98
|
guard let address = effect["url"].string, let url = URL(string: address) else {
|
|
99
|
-
throw
|
|
99
|
+
throw LegacyCrocheError("network_error", "Invalid HTTP effect URL")
|
|
100
100
|
}
|
|
101
101
|
var request = URLRequest(url: url)
|
|
102
102
|
request.httpMethod = effect["method"].string
|
|
@@ -136,15 +136,15 @@ public enum RuntimeURLSession {
|
|
|
136
136
|
// event stream is read incrementally.
|
|
137
137
|
streaming = (200..<300).contains(code) && type.lowercased().hasPrefix("text/event-stream")
|
|
138
138
|
if !streaming && expected > Int64(maxResponseBytes) {
|
|
139
|
-
throw
|
|
139
|
+
throw LegacyCrocheError("invalid_response", "HTTP response exceeds 2MiB")
|
|
140
140
|
}
|
|
141
141
|
case .body(let data):
|
|
142
142
|
size += data.count
|
|
143
143
|
if !streaming {
|
|
144
|
-
guard size <= maxResponseBytes else { throw
|
|
144
|
+
guard size <= maxResponseBytes else { throw LegacyCrocheError("invalid_response", "HTTP response exceeds 2MiB") }
|
|
145
145
|
body.append(data); continue
|
|
146
146
|
}
|
|
147
|
-
guard size <= maxStreamBytes else { throw
|
|
147
|
+
guard size <= maxStreamBytes else { throw LegacyCrocheError("invalid_provider_response", "The gateway stream exceeds its bound") }
|
|
148
148
|
for event in parser.push([UInt8](data)) where !event.data.isEmpty { await onDelta(event.data) }
|
|
149
149
|
}
|
|
150
150
|
}
|
|
@@ -177,7 +177,7 @@ private final class HTTPDelegate: NSObject, URLSessionDataDelegate, @unchecked S
|
|
|
177
177
|
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask,
|
|
178
178
|
didReceive response: URLResponse, completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void) {
|
|
179
179
|
guard let http = response as? HTTPURLResponse else {
|
|
180
|
-
sink.finish(throwing:
|
|
180
|
+
sink.finish(throwing: LegacyCrocheError("network_error", "No HTTP response")); completionHandler(.cancel); return
|
|
181
181
|
}
|
|
182
182
|
var headers: [String: JSON] = [:]
|
|
183
183
|
for (key, value) in http.allHeaderFields { headers[String(describing: key)] = .string(String(describing: value)) }
|
|
@@ -188,7 +188,7 @@ private final class HTTPDelegate: NSObject, URLSessionDataDelegate, @unchecked S
|
|
|
188
188
|
sink.yield(.body(chunk))
|
|
189
189
|
}
|
|
190
190
|
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
|
|
191
|
-
if error != nil { sink.finish(throwing:
|
|
191
|
+
if error != nil { sink.finish(throwing: LegacyCrocheError("network_error", "HTTP transport failed")) }
|
|
192
192
|
else { sink.finish() }
|
|
193
193
|
}
|
|
194
194
|
}
|
|
@@ -4,9 +4,10 @@ import Foundation
|
|
|
4
4
|
// Keep the receipt method spelling in this one file/call site for the reviewed rename.
|
|
5
5
|
final class FFIStreamPort: CoreStreamPort, @unchecked Sendable {
|
|
6
6
|
private let core: CoreRuntime
|
|
7
|
+
private let images: NativeImagePal?
|
|
7
8
|
let logId: String
|
|
8
|
-
init(core: CoreRuntime) throws {
|
|
9
|
-
self.core = core
|
|
9
|
+
init(core: CoreRuntime, images: NativeImagePal? = nil) throws {
|
|
10
|
+
self.core = core; self.images = images
|
|
10
11
|
logId = try Self.blocking { try core.logId() }
|
|
11
12
|
}
|
|
12
13
|
private final class Box<T>: @unchecked Sendable { var result: Result<T, Error>? }
|
|
@@ -14,7 +15,7 @@ final class FFIStreamPort: CoreStreamPort, @unchecked Sendable {
|
|
|
14
15
|
// callbacks already on a Core thread stay there, preserving FFI's reentrancy rule.
|
|
15
16
|
private static func blocking<T>(record: Bool = true, _ body: @escaping @Sendable () throws -> T) throws -> T {
|
|
16
17
|
let measured: @Sendable () throws -> T = {
|
|
17
|
-
if record {
|
|
18
|
+
if record { Offload.starting?() }
|
|
18
19
|
return try body()
|
|
19
20
|
}
|
|
20
21
|
if !Thread.isMainThread { return try measured() }
|
|
@@ -24,19 +25,19 @@ final class FFIStreamPort: CoreStreamPort, @unchecked Sendable {
|
|
|
24
25
|
return try box.result!.get()
|
|
25
26
|
}
|
|
26
27
|
private static func offload<T: Sendable>(_ body: @escaping @Sendable () throws -> T) async throws -> T {
|
|
27
|
-
try await
|
|
28
|
+
try await Offload.run(body)
|
|
28
29
|
}
|
|
29
30
|
private final class Listener: EventListener, @unchecked Sendable {
|
|
30
31
|
let callback: @Sendable (String) -> Void
|
|
31
32
|
init(_ callback: @escaping @Sendable (String) -> Void) { self.callback = callback }
|
|
32
33
|
func onEvent(event: String) { callback(event) }
|
|
33
34
|
}
|
|
34
|
-
private static func failure(_ error: Error) ->
|
|
35
|
-
let error =
|
|
36
|
-
return
|
|
35
|
+
private static func failure(_ error: Error) -> LegacyStreamError {
|
|
36
|
+
let error = LegacyCrocheError(error)
|
|
37
|
+
return LegacyStreamError(code: error.code, message: error.message, poisoned: false)
|
|
37
38
|
}
|
|
38
39
|
func observe(_ event: @escaping @Sendable (RequestObservation) -> Void,
|
|
39
|
-
end: @escaping @Sendable (
|
|
40
|
+
end: @escaping @Sendable (LegacyStreamError?) -> Void) throws -> @Sendable () -> Void {
|
|
40
41
|
do {
|
|
41
42
|
try Self.blocking { [core] in
|
|
42
43
|
try core.observe(onEvent: Listener { text in
|
|
@@ -54,14 +55,19 @@ final class FFIStreamPort: CoreStreamPort, @unchecked Sendable {
|
|
|
54
55
|
catch { end(Self.failure(error)) }
|
|
55
56
|
})
|
|
56
57
|
}
|
|
57
|
-
} catch { throw
|
|
58
|
+
} catch { throw LegacyCrocheError(error) }
|
|
58
59
|
return { [core] in _ = try? Self.blocking { core.unobserve() } }
|
|
59
60
|
}
|
|
60
|
-
|
|
61
|
-
|
|
61
|
+
/// Core's selection JSON. A nil field is omitted (Core's default), never filled in here.
|
|
62
|
+
static func selectionText(_ selection: StreamSelection) throws -> String {
|
|
63
|
+
struct Selection: Encodable { let initialMessages: Int?; let after: Cursor?; let deltaMs: Int? }
|
|
64
|
+
let value = Selection(initialMessages: selection.initialMessages, after: selection.after, deltaMs: selection.deltaMs)
|
|
65
|
+
return String(decoding: try JSONEncoder().encode(value), as: UTF8.self)
|
|
66
|
+
}
|
|
67
|
+
func select(_ selection: StreamSelection, event: @escaping @Sendable (LegacyRuntimeEvent) -> Void) -> CoreProjection {
|
|
62
68
|
do {
|
|
63
69
|
if let after = selection.after { _ = try Self.coreSequence(after.seq) }
|
|
64
|
-
let text =
|
|
70
|
+
let text = try Self.selectionText(selection)
|
|
65
71
|
let id = try Self.blocking { [core] in
|
|
66
72
|
try core.select(selection: text, onEvent: Listener { text in
|
|
67
73
|
do { event(try CoreEvent.decode(text)) }
|
|
@@ -69,32 +75,65 @@ final class FFIStreamPort: CoreStreamPort, @unchecked Sendable {
|
|
|
69
75
|
})
|
|
70
76
|
}
|
|
71
77
|
return CoreProjection(close: { [core] in _ = try? Self.blocking { core.closeProjection(id: id) } }, history: { before, limit in
|
|
72
|
-
guard let count = UInt32(exactly: limit) else { throw
|
|
78
|
+
guard let count = UInt32(exactly: limit) else { throw LegacyCrocheError("invalid_configuration", "Invalid history range") }
|
|
73
79
|
let seq = try before.map(Self.coreSequence)
|
|
74
80
|
try await Self.offload { try self.historyNow(id: id, before: seq, limit: count) }
|
|
75
81
|
})
|
|
76
82
|
} catch {
|
|
77
83
|
event(.streamError(Self.failure(error)))
|
|
78
|
-
return CoreProjection(close: {}, history: { _, _ in throw
|
|
84
|
+
return CoreProjection(close: {}, history: { _, _ in throw LegacyCrocheError("invalid_configuration", "No stream is attached") })
|
|
79
85
|
}
|
|
80
86
|
}
|
|
81
87
|
// Also used at the synchronous callback boundary to retain FFI's reentrancy rule.
|
|
82
88
|
func historyNow(id: UInt64, before: UInt64?, limit: UInt32) throws {
|
|
83
89
|
try Self.blocking { [core] in try core.history(id: id, before: before, limit: limit) }
|
|
84
90
|
}
|
|
85
|
-
func send(_ input: JSON, options: SendOptions) async throws ->
|
|
91
|
+
func send(_ input: JSON, options: SendOptions) async throws -> LegacyReceipt {
|
|
86
92
|
let token = CancelToken()
|
|
87
93
|
return try await withTaskCancellationHandler {
|
|
88
94
|
try await send(input, options: options, cancel: token)
|
|
89
95
|
} onCancel: { token.cancel() }
|
|
90
96
|
}
|
|
91
|
-
func send(_ input: JSON, options: SendOptions, cancel: CancelToken?) async throws ->
|
|
97
|
+
func send(_ input: JSON, options: SendOptions, cancel: CancelToken?) async throws -> LegacyReceipt {
|
|
92
98
|
let text = String(decoding: try input.encoded(), as: UTF8.self)
|
|
93
99
|
let format = try options.responseFormat.map { String(decoding: try $0.encoded(), as: UTF8.self) }
|
|
94
100
|
let value = try await Self.offload { [core] in try core.send(input: text, cancel: cancel, responseFormat: format) }
|
|
95
|
-
struct WireReceipt: Decodable { let
|
|
101
|
+
struct WireReceipt: Decodable { let requestId: String; let status: LegacyInputStatus; let seq: Int? }
|
|
102
|
+
let receipt = try CoreEvent.decodeValue(WireReceipt.self, value)
|
|
103
|
+
return LegacyReceipt(requestId: receipt.requestId, status: receipt.status, seq: receipt.seq)
|
|
104
|
+
}
|
|
105
|
+
/// Byte images go through Core's reserved entry: reserve, capture, submit, all before the
|
|
106
|
+
/// first await, so the send keeps its place; only the receipt wait is offloaded. Until submit
|
|
107
|
+
/// returns, this owns the captures; afterwards Core releases them on every exit.
|
|
108
|
+
func send(_ input: SendInput, options: SendOptions) async throws -> LegacyReceipt {
|
|
109
|
+
let captured = input.imageCaptures()
|
|
110
|
+
guard !captured.isEmpty else { return try await send(try input.coreJSON(options: options), options: options) }
|
|
111
|
+
guard let images else { throw LegacyCrocheError("image_unsupported", "The image could not be prepared.") }
|
|
112
|
+
let text = String(decoding: try input.coreJSON(options: options).encoded(), as: UTF8.self)
|
|
113
|
+
let format = try options.responseFormat.map { String(decoding: try $0.encoded(), as: UTF8.self) }
|
|
114
|
+
let token = CancelToken()
|
|
115
|
+
let pending = try Self.blocking { [core] () throws -> PendingSend in
|
|
116
|
+
let entry = try core.reserveSend()
|
|
117
|
+
var tokens: [String] = []
|
|
118
|
+
do {
|
|
119
|
+
var captures: [PalCapturedImageSource] = []
|
|
120
|
+
for (element, bytes) in captured {
|
|
121
|
+
let capture = try images.capture(bytes)
|
|
122
|
+
tokens.append(capture)
|
|
123
|
+
captures.append(PalCapturedImageSource(element: UInt32(element), kind: "encoded-v1", token: capture))
|
|
124
|
+
}
|
|
125
|
+
return try entry.submit(input: text, captures: captures, cancel: token, responseFormat: format)
|
|
126
|
+
} catch {
|
|
127
|
+
for capture in tokens { images.release(capture) }
|
|
128
|
+
throw error
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
let value = try await withTaskCancellationHandler {
|
|
132
|
+
try await Self.offload { try pending.wait() }
|
|
133
|
+
} onCancel: { token.cancel() }
|
|
134
|
+
struct WireReceipt: Decodable { let requestId: String; let status: LegacyInputStatus; let seq: Int? }
|
|
96
135
|
let receipt = try CoreEvent.decodeValue(WireReceipt.self, value)
|
|
97
|
-
return
|
|
136
|
+
return LegacyReceipt(requestId: receipt.requestId, status: receipt.status, seq: receipt.seq)
|
|
98
137
|
}
|
|
99
138
|
func readOutcome(id: String, fromSeq: Int, captured: @escaping @Sendable (CapturedRequestState) -> Void) async throws -> RetainedRequestEnds {
|
|
100
139
|
let seq = try Self.coreSequence(fromSeq)
|
|
@@ -103,14 +142,14 @@ final class FFIStreamPort: CoreStreamPort, @unchecked Sendable {
|
|
|
103
142
|
let text = try await Self.offload { [core] in
|
|
104
143
|
try core.readOutcome(id: id, fromSeq: seq, captured: Listener { value in
|
|
105
144
|
do {
|
|
106
|
-
struct Capture: Decodable { let head: Int; let floor: Int; let status:
|
|
145
|
+
struct Capture: Decodable { let head: Int; let floor: Int; let status: LegacyInputStatus; let idle: Bool; let consumedBy: String? }
|
|
107
146
|
let at = try CoreEvent.decodeValue(Capture.self, value)
|
|
108
147
|
captured(CapturedRequestState(head: at.head, floor: at.floor, status: at.status, idle: at.idle, carried: at.consumedBy != nil, unitEnd: nil))
|
|
109
148
|
} catch { captureError.set(error) }
|
|
110
149
|
})
|
|
111
150
|
}
|
|
112
151
|
if let error = captureError.get() { throw error }
|
|
113
|
-
struct Outcome: Decodable { let messages: [
|
|
152
|
+
struct Outcome: Decodable { let messages: [LegacyMessageEnd]; let gap: Bool? }
|
|
114
153
|
let outcome = try CoreEvent.decodeValue(Outcome.self, text)
|
|
115
154
|
return RetainedRequestEnds(messages: outcome.messages, gap: outcome.gap ?? false)
|
|
116
155
|
}
|
|
@@ -120,7 +159,7 @@ final class FFIStreamPort: CoreStreamPort, @unchecked Sendable {
|
|
|
120
159
|
func get() -> Error? { lock.withLock { error } }
|
|
121
160
|
}
|
|
122
161
|
static func coreSequence(_ value: Int) throws -> UInt64 {
|
|
123
|
-
guard let result = UInt64(exactly: value) else { throw
|
|
162
|
+
guard let result = UInt64(exactly: value) else { throw LegacyCrocheError("invalid_input", "Sequence is outside the Core range") }
|
|
124
163
|
return result
|
|
125
164
|
}
|
|
126
165
|
func cancel(_ id: String) async throws {
|
|
@@ -137,7 +176,7 @@ final class FFIStreamPort: CoreStreamPort, @unchecked Sendable {
|
|
|
137
176
|
// Extra Core keys stay internal; unknown event types remain forward-compatible.
|
|
138
177
|
enum CoreEvent {
|
|
139
178
|
static func publicSequence(_ value: UInt64) throws -> Int {
|
|
140
|
-
guard let result = Int(exactly: value) else { throw
|
|
179
|
+
guard let result = Int(exactly: value) else { throw LegacyCrocheError("invalid_input", "Core sequence is outside the public range") }
|
|
141
180
|
return result
|
|
142
181
|
}
|
|
143
182
|
// Validate only Core envelope fields, never arbitrary app data/output or usage values.
|
|
@@ -149,7 +188,7 @@ enum CoreEvent {
|
|
|
149
188
|
if keys.contains(key), !(try keys.decodeNil(forKey: key)) {
|
|
150
189
|
let value: UInt64
|
|
151
190
|
do { value = try keys.decode(UInt64.self, forKey: key) }
|
|
152
|
-
catch { throw
|
|
191
|
+
catch { throw LegacyCrocheError("invalid_input", "Invalid Core sequence") }
|
|
153
192
|
_ = try CoreEvent.publicSequence(value)
|
|
154
193
|
}
|
|
155
194
|
}
|
|
@@ -168,48 +207,51 @@ enum CoreEvent {
|
|
|
168
207
|
let text = try value.singleValueContainer().decode(String.self)
|
|
169
208
|
let fractional = ISO8601DateFormatter(); fractional.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
|
170
209
|
guard let date = fractional.date(from: text) ?? ISO8601DateFormatter().date(from: text) else {
|
|
171
|
-
throw
|
|
210
|
+
throw LegacyCrocheError("invalid_input", "Invalid Core event date")
|
|
172
211
|
}
|
|
173
212
|
return date
|
|
174
213
|
}
|
|
175
214
|
return decoder
|
|
176
215
|
}
|
|
177
216
|
private struct Failure: Decodable { let code: String; let message: String; let poisoned: Bool? }
|
|
178
|
-
static func decodeFailure(_ text: String) throws ->
|
|
217
|
+
static func decodeFailure(_ text: String) throws -> LegacyStreamError {
|
|
179
218
|
let value = try decoder().decode(Failure.self, from: Data(text.utf8))
|
|
180
|
-
return
|
|
219
|
+
return LegacyStreamError(code: value.code, message: value.message, poisoned: value.poisoned ?? false)
|
|
181
220
|
}
|
|
182
221
|
private struct Event: Decodable {
|
|
183
|
-
let value:
|
|
222
|
+
let value: LegacyRuntimeEvent
|
|
184
223
|
enum Keys: String, CodingKey { case type, seq, images, messages, reachedFloor, logId, clearedSeq }
|
|
185
224
|
init(from decoder: Decoder) throws {
|
|
186
225
|
let keys = try decoder.container(keyedBy: Keys.self)
|
|
187
226
|
let type = try keys.decode(String.self, forKey: .type)
|
|
188
227
|
switch type {
|
|
189
228
|
case "input":
|
|
190
|
-
struct Input: Decodable { let seq: Int; let firstSeq: Int; let id: String; let kind: InputKind; let text: String?; let images: [
|
|
229
|
+
struct Input: Decodable { let seq: Int; let firstSeq: Int; let id: String; let kind: InputKind; let text: String?; let images: [LegacyImageSummary]?; let status: LegacyInputStatus; let error: LegacyRuntimeError?; let at: Date }
|
|
191
230
|
let v = try Input(from: decoder)
|
|
192
|
-
value = .input(
|
|
193
|
-
case "message.start": value = .messageStart(try
|
|
194
|
-
case "message.delta": value = .messageDelta(try
|
|
195
|
-
case "message.end": value = .messageEnd(try
|
|
196
|
-
case "state": value = .state(try
|
|
197
|
-
case "snapshot": value = .snapshot(try
|
|
198
|
-
case "gap": value = .gap(try
|
|
199
|
-
case "app": value = .app(try
|
|
200
|
-
case "turn": value = .turn(try
|
|
201
|
-
case "cleared": value = .cleared(try
|
|
231
|
+
value = .input(LegacyInputEvent(seq: v.seq, firstSeq: v.firstSeq, id: v.id, kind: v.kind, text: v.text, images: v.images ?? [], status: v.status, error: v.error, at: v.at))
|
|
232
|
+
case "message.start": value = .messageStart(try LegacyMessageStart(from: decoder))
|
|
233
|
+
case "message.delta": value = .messageDelta(try LegacyMessageDelta(from: decoder))
|
|
234
|
+
case "message.end": value = .messageEnd(try LegacyMessageEnd(from: decoder))
|
|
235
|
+
case "state": value = .state(try LegacyStateEvent(from: decoder))
|
|
236
|
+
case "snapshot": value = .snapshot(try LegacySnapshot(from: decoder))
|
|
237
|
+
case "gap": value = .gap(try LegacyGap(from: decoder))
|
|
238
|
+
case "app": value = .app(try LegacyAppStreamEvent(from: decoder))
|
|
239
|
+
case "turn": value = .turn(try LegacyTurnEvent(from: decoder))
|
|
240
|
+
case "cleared": value = .cleared(try LegacyCleared(from: decoder))
|
|
202
241
|
case "error":
|
|
203
|
-
if keys.contains(.seq) { value = .error(try
|
|
242
|
+
if keys.contains(.seq) { value = .error(try LegacyErrorEvent(from: decoder)) }
|
|
204
243
|
else {
|
|
205
244
|
let e = try Failure(from: decoder)
|
|
206
|
-
value = .streamError(
|
|
245
|
+
value = .streamError(LegacyStreamError(code: e.code, message: e.message, poisoned: e.poisoned ?? false))
|
|
207
246
|
}
|
|
208
|
-
case "page": value = .page(
|
|
247
|
+
case "page": value = .page(LegacyPage(messages: try keys.decode([Event].self, forKey: .messages).map(\.value), reachedFloor: try keys.decode(Bool.self, forKey: .reachedFloor), logId: try keys.decode(String.self, forKey: .logId), clearedSeq: try keys.decode(Int.self, forKey: .clearedSeq)))
|
|
209
248
|
case "replaced": value = .replaced
|
|
210
|
-
default:
|
|
249
|
+
default:
|
|
250
|
+
var fields = try JSON(from: decoder).object ?? [:]
|
|
251
|
+
fields.removeValue(forKey: "type")
|
|
252
|
+
value = .unknown(type: type, fields: .object(fields))
|
|
211
253
|
}
|
|
212
254
|
}
|
|
213
255
|
}
|
|
214
|
-
static func decode(_ text: String) throws ->
|
|
256
|
+
static func decode(_ text: String) throws -> LegacyRuntimeEvent { try decodeValue(Event.self, text).value }
|
|
215
257
|
}
|