@h1r-ai/croche-react-native 0.5.5 → 0.7.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/LICENSE +1 -1
- package/README.md +90 -451
- package/THIRD-PARTY-NOTICES +906 -14
- package/android/build.gradle +6 -1
- package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +126 -0
- package/android/src/main/AndroidManifest.xml +0 -5
- package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +106 -0
- package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +217 -0
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +48 -824
- package/android/src/main/java/dev/croche/reactnative/NativePal.kt +68 -0
- package/android/src/main/java/dev/croche/reactnative/RNHostPal.kt +9 -0
- package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +64 -41
- package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +64 -0
- package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
- package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
- package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +44 -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/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
- package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidEventSink.kt +27 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +10 -8
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundRegistration.kt +16 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +55 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +162 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -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/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 +116 -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/AndroidStateStore.kt +216 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +108 -0
- package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +8 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +31 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +25 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +121 -103
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +89 -103
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +20 -360
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +136 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +23 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +26 -21
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +715 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +9 -322
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ImagePal.kt +183 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +16 -28
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +294 -37
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +127 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ReaderValues.kt +73 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +73 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +23 -21
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +88 -24
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +5723 -3088
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppEventSink.kt +34 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +96 -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 +30 -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 +127 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +70 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +64 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/LifecycleBinding.kt +18 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +60 -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 +43 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ScopeJson.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ToolCompletionEncoding.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +100 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/DirectHttpPal.kt +223 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -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/croche-react-native.podspec +1 -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 +6 -0
- package/dist/react-native/src/core-native.js +316 -0
- package/dist/react-native/src/core-wire.d.ts +55 -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/adapters.d.ts +8 -0
- package/dist/runtime/src/adapters.js +29 -0
- package/dist/runtime/src/agent.d.ts +91 -0
- package/dist/runtime/src/agent.js +137 -0
- package/dist/runtime/src/app-api.d.ts +572 -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 +27 -0
- package/dist/runtime/src/core/foreground.d.ts +3 -0
- package/dist/runtime/src/core/foreground.js +40 -0
- package/dist/runtime/src/core/port.d.ts +247 -0
- package/dist/runtime/src/core/port.js +1 -0
- package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
- package/dist/runtime/src/core/wasm-owner.js +237 -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 +97 -0
- package/dist/runtime/src/croche.js +172 -0
- package/dist/runtime/src/errors.d.ts +33 -0
- package/dist/runtime/src/errors.js +63 -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 +328 -0
- package/dist/runtime/src/generated/app-stream.js +127 -0
- package/dist/runtime/src/image-input.d.ts +5 -0
- package/dist/runtime/src/image-input.js +60 -0
- package/dist/runtime/src/index.d.ts +6 -0
- package/dist/runtime/src/index.js +5 -0
- package/dist/runtime/src/index.native.d.ts +1 -0
- package/dist/runtime/src/index.native.js +2 -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 +30 -0
- package/dist/runtime/src/pal/host.d.ts +5 -0
- package/dist/runtime/src/pal/host.js +60 -0
- package/dist/runtime/src/pal/platform.d.ts +21 -0
- package/dist/runtime/src/pal/platform.js +7 -0
- package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
- package/dist/runtime/src/pal/state-store-lock.js +2 -0
- package/dist/runtime/src/pal/state-store.d.ts +66 -0
- package/dist/runtime/src/pal/state-store.js +1 -0
- package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
- package/dist/runtime/src/pal/storage-version-contract.js +68 -0
- package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
- package/dist/runtime/src/pal/transactional-storage.js +124 -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 +35 -0
- package/dist/runtime/src/tools.js +94 -0
- package/ios/CoreAgentTransport.swift +14 -0
- package/ios/CoreDeliveryTransport.swift +58 -0
- package/ios/CoreNativePal.swift +98 -0
- package/ios/CorePlatformTransport.swift +44 -0
- package/ios/CoreWireDispatch.swift +122 -0
- package/ios/CoreWireSupport.swift +286 -0
- package/ios/CrocheRuntimeBridge.swift +34 -994
- package/ios/ProjectPal.swift +49 -0
- package/ios/RNCrocheRuntime.mm +18 -201
- package/ios/vendor/CrocheRuntimeSDK/AppBuildFacts.swift +112 -0
- package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
- package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +60 -0
- package/ios/vendor/CrocheRuntimeSDK/DirectHTTP.swift +258 -0
- package/ios/vendor/CrocheRuntimeSDK/Effects.swift +17 -17
- package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
- package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +26 -157
- package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +672 -0
- package/ios/vendor/CrocheRuntimeSDK/Host.swift +34 -371
- package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +410 -0
- package/ios/vendor/CrocheRuntimeSDK/Images.swift +10 -9
- package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
- package/ios/vendor/CrocheRuntimeSDK/JSON.swift +30 -14
- package/ios/vendor/CrocheRuntimeSDK/Offload.swift +24 -0
- package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +1 -155
- package/ios/vendor/CrocheRuntimeSDK/Platform.swift +33 -59
- package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +289 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +302 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +281 -0
- package/ios/vendor/CrocheRuntimeSDK/Project.swift +4 -269
- package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +24 -461
- package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +248 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +33 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +170 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +313 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +37 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +346 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +89 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +165 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +100 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +278 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
- package/ios/vendor/CrocheRuntimeSDK/Storage.swift +23 -269
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +163 -116
- package/ios/vendor/CrocheRuntimeSDK/Truncate.swift +12 -0
- package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +4712 -2469
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +899 -608
- 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 +899 -608
- 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/check-swift-vendor-modules.sh +15 -0
- package/scripts/vendor-native.sh +8 -6
- 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/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -110
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +0 -178
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -173
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +0 -79
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +0 -46
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -227
- package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
- package/ios/vendor/CrocheRuntimeSDK/Control.swift +0 -192
- package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -453
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -38
- 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
|
@@ -7,18 +7,36 @@ import FoundationNetworking
|
|
|
7
7
|
// everything else, including SSE framing, response bounds, timeouts' meaning, persistence
|
|
8
8
|
// order, upkeep and cancellation rules. Its calls into this host block a background thread.
|
|
9
9
|
|
|
10
|
-
extension
|
|
10
|
+
extension LegacyCrocheError {
|
|
11
11
|
init(_ error: Error) {
|
|
12
|
-
if let e = error as?
|
|
12
|
+
if let e = error as? LegacyCrocheError { self = e }
|
|
13
13
|
else if case let .Failure(code, message)? = error as? FfiError { self.init(code, message) }
|
|
14
|
+
// Core's App API carrier (truncate since #830 2eb98fbc): its code and public detail, unchanged.
|
|
15
|
+
else if case let .Failure(code, detail, _, _, _)? = error as? CoreApiError { self.init(code, detail) }
|
|
14
16
|
else { self.init("host_error", "The host operation failed") }
|
|
15
17
|
}
|
|
16
18
|
var ffi: FfiError { .Failure(code: code, message: message) }
|
|
17
19
|
}
|
|
18
20
|
|
|
19
|
-
///
|
|
21
|
+
/// An effect failure is a platform FACT (Keel 18:44Z): a code from Core's closed per-effect list
|
|
22
|
+
/// and a detail. Core validates the code. An unexpected error with no fact code IS `internal`, sent
|
|
23
|
+
/// literally (Atlas's PAL error contract, Keel 21:00Z), with this detail kept for debugging.
|
|
24
|
+
/// Storage never comes through here: it reports no code.
|
|
25
|
+
func effectFailure(_ error: Error) -> CorePalError {
|
|
26
|
+
if let error = error as? CorePalError { return error }
|
|
27
|
+
if let error = error as? LegacyCrocheError { return .Failure(code: error.code, detail: error.message) }
|
|
28
|
+
if case let .Failure(code, message)? = error as? FfiError { return .Failure(code: code, detail: message) }
|
|
29
|
+
return .Failure(code: "internal", detail: "\(error)")
|
|
30
|
+
}
|
|
31
|
+
func effect<T>(_ body: () throws -> T) throws -> T {
|
|
32
|
+
do { return try body() } catch { throw effectFailure(error) }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/// The binding's `identity`, named so the SDK's `storageIdentity` reads as its own. Unqualified:
|
|
20
36
|
/// the React Native pod compiles the SDK and its bindings into one module.
|
|
21
37
|
func ffiIdentity(_ config: String) throws -> String { try identity(config: config) }
|
|
38
|
+
/// The binding's `truncate`, named so `Croche.truncate` does not shadow it.
|
|
39
|
+
func ffiTruncate(_ text: String, _ max: Double) throws -> String { try truncate(text: text, max: max) }
|
|
22
40
|
|
|
23
41
|
/// Runs `body` on the Swift concurrency pool and blocks this (Rust-owned, background) thread
|
|
24
42
|
/// until it finishes, `cancel` fires or `milliseconds` pass.
|
|
@@ -34,7 +52,7 @@ func blockOn<T: Sendable>(milliseconds: Double?, cancel: CancelToken?,
|
|
|
34
52
|
done.signal()
|
|
35
53
|
}
|
|
36
54
|
done.wait()
|
|
37
|
-
do { return try box.get() } catch { throw
|
|
55
|
+
do { return try box.get() } catch { throw LegacyCrocheError(error).ffi }
|
|
38
56
|
}
|
|
39
57
|
|
|
40
58
|
/// An app command (H1): runs `body` until it returns, however long after a cancel. The cancel
|
|
@@ -65,7 +83,7 @@ func blockUntilSettled<T: Sendable>(cancel: CancelToken,
|
|
|
65
83
|
}
|
|
66
84
|
cancel.onCancel(callback: CancelHook(cancellation))
|
|
67
85
|
done.wait()
|
|
68
|
-
if cancellation.isCancelled { throw
|
|
86
|
+
if cancellation.isCancelled { throw LegacyCrocheError("cancelled", "The operation was cancelled").ffi }
|
|
69
87
|
do { return try box.get() } catch { throw handlerError(error).ffi }
|
|
70
88
|
}
|
|
71
89
|
|
|
@@ -79,23 +97,10 @@ struct ToolNotDispatched: Error {}
|
|
|
79
97
|
/// An error from a tool handler. "Nothing ran" is the host's to say, never a handler's: a
|
|
80
98
|
/// handler that throws `tool_not_dispatched` or `host_unresponsive` (perhaps passing on another
|
|
81
99
|
/// Runtime's error) may already have had its effect, so the call fails as `tool_failed`.
|
|
82
|
-
func handlerError(_ error: Error) ->
|
|
83
|
-
if error is ToolNotDispatched { return
|
|
84
|
-
let e =
|
|
85
|
-
return ["tool_not_dispatched", "host_unresponsive"].contains(e.code) ?
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
/// Where app command handlers run (H1), where the OS has task executors: GCD threads, apart from
|
|
89
|
-
/// Swift's cooperative pool, which also runs the Runtime's own requests. This does not make a
|
|
90
|
-
/// blocking async handler safe (measured on Linux, #342); blocking work uses `blockingTool`.
|
|
91
|
-
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, *)
|
|
92
|
-
final class ToolThreads: TaskExecutor, @unchecked Sendable {
|
|
93
|
-
static let shared = ToolThreads()
|
|
94
|
-
private let queue = DispatchQueue(label: "dev.croche.tools", attributes: .concurrent)
|
|
95
|
-
func enqueue(_ job: consuming ExecutorJob) {
|
|
96
|
-
let job = UnownedJob(job), executor = asUnownedTaskExecutor()
|
|
97
|
-
queue.async { job.runSynchronously(on: executor) }
|
|
98
|
-
}
|
|
100
|
+
func handlerError(_ error: Error) -> LegacyCrocheError {
|
|
101
|
+
if error is ToolNotDispatched { return LegacyCrocheError("tool_not_dispatched", "No handler ran for this tool") }
|
|
102
|
+
let e = LegacyCrocheError(error)
|
|
103
|
+
return ["tool_not_dispatched", "host_unresponsive"].contains(e.code) ? LegacyCrocheError("tool_failed", e.message) : e
|
|
99
104
|
}
|
|
100
105
|
|
|
101
106
|
final class CancelHook: CancelCallback, @unchecked Sendable {
|
|
@@ -103,12 +108,8 @@ final class CancelHook: CancelCallback, @unchecked Sendable {
|
|
|
103
108
|
init(_ cancellation: RuntimeCancellation) { self.cancellation = cancellation }
|
|
104
109
|
func cancelled() { cancellation.cancel() }
|
|
105
110
|
}
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
init(_ callback: @escaping @Sendable (JSON) -> Void) { self.callback = callback }
|
|
109
|
-
func onEvent(event: String) { if let value = try? JSON(event) { callback(value) } }
|
|
110
|
-
}
|
|
111
|
-
private final class ResultBox<T>: @unchecked Sendable {
|
|
111
|
+
|
|
112
|
+
final class ResultBox<T>: @unchecked Sendable {
|
|
112
113
|
private let lock = NSLock()
|
|
113
114
|
private var value: Result<T, Error>?
|
|
114
115
|
func set(_ result: Result<T, Error>) { lock.withLock { value = result } }
|
|
@@ -128,344 +129,6 @@ func times(_ entries: JSON) -> [Double] { (entries.array ?? []).compactMap { $0[
|
|
|
128
129
|
/// A delivery's `retryAt` (epoch ms, or an ISO time), or nil.
|
|
129
130
|
func retryAt(_ value: JSON) -> Double? { value.number ?? value.string.flatMap(epochMs) }
|
|
130
131
|
|
|
131
|
-
/// The Swift PAL handed to the Rust Runtime.
|
|
132
|
-
final class SwiftHost: HostPal, @unchecked Sendable {
|
|
133
|
-
private let storage: any RuntimeStorage
|
|
134
|
-
private let projectRecords: ProjectRecordFiles
|
|
135
|
-
// Internal test trace, configured before Core starts; records only delegated store calls.
|
|
136
|
-
var beforeStoreAccess: (@Sendable (String) -> Void)?
|
|
137
|
-
private let secretStore: any RuntimeSecretStore
|
|
138
|
-
private let attestor: (any RuntimeAttestor)?
|
|
139
|
-
private let http: RuntimeHTTP?
|
|
140
|
-
/// The default transport's session, closed with the Runtime.
|
|
141
|
-
let session = RuntimeSession()
|
|
142
|
-
// Accepted tools are never removed: a tool change waits its turn in the Core's queue, and turns queued before it
|
|
143
|
-
// still run the old list. The Core alone decides which commands a turn may call.
|
|
144
|
-
private var handlers: [String: ToolHandler]
|
|
145
|
-
private var staged: [String: Int] = [:], stamp = 0 // names whose only handler is from a call in flight
|
|
146
|
-
private let identity: String
|
|
147
|
-
private let background: Bool
|
|
148
|
-
private let lock = NSLock()
|
|
149
|
-
private weak var core: CoreRuntime?
|
|
150
|
-
private var wakeTarget: Double?
|
|
151
|
-
private var timer: Task<Void, Never>?
|
|
152
|
-
private var stopped = false
|
|
153
|
-
/// This Runtime's attachment to `osScheduler` (attached right after the host is built),
|
|
154
|
-
/// released once: a second stop, or a stale close after the scheduler was attached again for
|
|
155
|
-
/// another Runtime, must not free an identifier someone else holds. Guarded by `lock`.
|
|
156
|
-
private var osAttached = false
|
|
157
|
-
private let osScheduler: (any RuntimeScheduler)?
|
|
158
|
-
var timeZone: TimeZone?
|
|
159
|
-
private var wallClock: @Sendable () -> Double = { Date().timeIntervalSince1970 * 1000 }
|
|
160
|
-
/// The wall clock (epoch ms) the Runtime and its timers read. Tests move it.
|
|
161
|
-
var clock: @Sendable () -> Double {
|
|
162
|
-
get { lock.withLock { wallClock } }
|
|
163
|
-
set { lock.withLock { wallClock = newValue } }
|
|
164
|
-
}
|
|
165
|
-
private var deliverDue: (@Sendable () async -> Void)?
|
|
166
|
-
/// Runs `deliverDue()` on the Runtime when the earliest note's time comes.
|
|
167
|
-
var deliver: (@Sendable () async -> Void)? {
|
|
168
|
-
get { lock.withLock { deliverDue } }
|
|
169
|
-
set { lock.withLock { deliverDue = newValue } }
|
|
170
|
-
}
|
|
171
|
-
private var dueAt: Double?
|
|
172
|
-
private var fired: Double?
|
|
173
|
-
private var dueTimer: Task<Void, Never>?
|
|
174
|
-
|
|
175
|
-
init(storage: any RuntimeStorage, secrets: any RuntimeSecretStore, attestor: (any RuntimeAttestor)?,
|
|
176
|
-
http: RuntimeHTTP?, tools: [String: ToolHandler], background: Bool,
|
|
177
|
-
scheduler: (any RuntimeScheduler)? = nil, projectRecords: ProjectRecordFiles = ProjectRecordFiles()) {
|
|
178
|
-
self.storage = storage; self.projectRecords = projectRecords; secretStore = secrets; self.attestor = attestor; self.http = http
|
|
179
|
-
handlers = tools; self.background = background; osScheduler = scheduler
|
|
180
|
-
identity = "\(ObjectIdentifier(storage as AnyObject).hashValue)"
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
private func host<T>(_ body: () throws -> T) throws -> T {
|
|
184
|
-
do { return try body() } catch { throw CrocheError(error).ffi }
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
// MARK: HTTP
|
|
188
|
-
func http(request: PalHttpRequest, sink: HttpSink, cancel: CancelToken) throws {
|
|
189
|
-
let transport = http, session = session
|
|
190
|
-
_ = try blockOn(milliseconds: Double(request.timeoutMs), cancel: cancel) { signal -> Bool in
|
|
191
|
-
if let transport { try await Self.adapt(transport, request, sink, signal) }
|
|
192
|
-
else { try await session.stream(request, into: sink, cancellation: signal) }
|
|
193
|
-
return true
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
/// An app transport speaks whole effects (`RuntimeHTTP`): its answer goes to the Runtime as
|
|
198
|
-
/// a response, and its stream deltas as server-sent events.
|
|
199
|
-
private static func adapt(_ transport: RuntimeHTTP, _ request: PalHttpRequest, _ sink: HttpSink,
|
|
200
|
-
_ signal: RuntimeCancellation) async throws {
|
|
201
|
-
var headers: [String: JSON] = [:]
|
|
202
|
-
for header in request.headers { headers[header.name] = .string(header.value) }
|
|
203
|
-
let effect = JSON.object(["url": .string(request.url), "method": .string(request.method), "headers": .object(headers),
|
|
204
|
-
"body": (try? JSON(request.body)) ?? .string(request.body),
|
|
205
|
-
"timeoutMs": .number(Double(request.timeoutMs))])
|
|
206
|
-
let streaming = StreamStart()
|
|
207
|
-
let reply = try await transport(effect, signal) { data in
|
|
208
|
-
if streaming.begin() {
|
|
209
|
-
sink.head(status: 200, headers: [PalHeader(name: "content-type", value: "text/event-stream")])
|
|
210
|
-
}
|
|
211
|
-
let frame = data.split(separator: "\n", omittingEmptySubsequences: false).map { "data: \($0)\n" }.joined() + "\n"
|
|
212
|
-
_ = sink.chunk(bytes: Data(frame.utf8))
|
|
213
|
-
}
|
|
214
|
-
let status = UInt16(reply["status"].number ?? 0)
|
|
215
|
-
var fields = (reply["headers"].object ?? [:]).compactMap { key, value in value.string.map { PalHeader(name: key, value: $0) } }
|
|
216
|
-
if reply["streamed"] == .bool(true) {
|
|
217
|
-
if streaming.begin() { sink.head(status: status, headers: [PalHeader(name: "content-type", value: "text/event-stream")]) }
|
|
218
|
-
return
|
|
219
|
-
}
|
|
220
|
-
fields.removeAll { $0.name.lowercased() == "content-type" }
|
|
221
|
-
fields.append(PalHeader(name: "content-type", value: "application/json"))
|
|
222
|
-
sink.head(status: status, headers: fields)
|
|
223
|
-
let body = reply["body"] != .null ? try reply["body"].encoded() : Data((reply["raw"].string ?? "").utf8)
|
|
224
|
-
if !body.isEmpty { _ = sink.chunk(bytes: body) }
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
// MARK: Storage
|
|
228
|
-
/// The Core names its snapshot by the key it locks, and other records `<key>.<entry>` (F19's
|
|
229
|
-
/// held sends: `<key>.held`). Each goes to its own place: an entry never replaces the snapshot.
|
|
230
|
-
private var snapshotKey: String? { get { lock.withLock { lockedKey } } set { lock.withLock { lockedKey = newValue } } }
|
|
231
|
-
private var lockedKey: String?
|
|
232
|
-
private func entry(_ key: String) throws -> String? {
|
|
233
|
-
guard let main = snapshotKey, key != main else { return nil }
|
|
234
|
-
guard key.hasPrefix(main + "."), key.count > main.count + 1 else { throw CrocheError("storage_error", "Unknown storage key") }
|
|
235
|
-
return String(key.dropFirst(main.count + 1))
|
|
236
|
-
}
|
|
237
|
-
func read(key: String) throws -> String? {
|
|
238
|
-
try host {
|
|
239
|
-
if ProjectRecordFiles.owns(key) { return try projectRecords.read(key) }
|
|
240
|
-
beforeStoreAccess?(key)
|
|
241
|
-
let state: JSON
|
|
242
|
-
if let name = try entry(key) {
|
|
243
|
-
// A storage without entries never stored one.
|
|
244
|
-
guard let keyed = storage as? any KeyedRuntimeStorage else { return nil }
|
|
245
|
-
state = try keyed.load(entry: name)
|
|
246
|
-
} else { state = try storage.load() }
|
|
247
|
-
return state == .null ? nil : String(decoding: try state.encoded(), as: UTF8.self)
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
func write(key: String, value: String) throws {
|
|
251
|
-
try host {
|
|
252
|
-
if ProjectRecordFiles.owns(key) { return try projectRecords.write(key, value) }
|
|
253
|
-
beforeStoreAccess?(key)
|
|
254
|
-
guard let name = try entry(key) else { return try storage.save(try JSON(value)) }
|
|
255
|
-
guard let keyed = storage as? any KeyedRuntimeStorage else {
|
|
256
|
-
throw CrocheError("storage_error", "This RuntimeStorage keeps only its snapshot")
|
|
257
|
-
}
|
|
258
|
-
try keyed.save(entry: name, try JSON(value))
|
|
259
|
-
}
|
|
260
|
-
}
|
|
261
|
-
func readSecret(key: String) throws -> String? {
|
|
262
|
-
try host { String(decoding: try secretStore.load().encoded(), as: UTF8.self) }
|
|
263
|
-
}
|
|
264
|
-
func writeSecret(key: String, value: String) throws { try host { try secretStore.save(try JSON(value)) } }
|
|
265
|
-
func remove(key: String) throws {
|
|
266
|
-
try host {
|
|
267
|
-
guard !ProjectRecordFiles.owns(key) else { throw CrocheError("storage_error", "The project record is kept when agent data is removed") }
|
|
268
|
-
beforeStoreAccess?(key)
|
|
269
|
-
if let name = try entry(key) {
|
|
270
|
-
guard let keyed = storage as? any KeyedRuntimeStorage else { return }
|
|
271
|
-
try keyed.remove(entry: name)
|
|
272
|
-
} else { try storage.remove() }
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
func removeSecret(key: String) throws { try host { try secretStore.remove() } }
|
|
276
|
-
func lock(key: String) throws {
|
|
277
|
-
try host {
|
|
278
|
-
if ProjectRecordFiles.owns(key) { return try projectRecords.acquire(key) }
|
|
279
|
-
guard !projectRecords.held else { throw CrocheError("storage_error", "Release the project record lock before taking a store lock") }
|
|
280
|
-
beforeStoreAccess?(key)
|
|
281
|
-
try storage.acquire(); snapshotKey = key
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
func unlock(key: String) {
|
|
285
|
-
if ProjectRecordFiles.owns(key) { projectRecords.release(key); return }
|
|
286
|
-
beforeStoreAccess?(key)
|
|
287
|
-
stop(); storage.release(); snapshotKey = nil
|
|
288
|
-
}
|
|
289
|
-
func storeIdentity() -> String { identity }
|
|
290
|
-
|
|
291
|
-
// MARK: The turn archive (F20.6)
|
|
292
|
-
/// The storage's archive, or the typed "no archive": the Runtime then keeps none, and every
|
|
293
|
-
/// turn, clearHistory and memory work as before.
|
|
294
|
-
private func archive() throws -> any ArchiveRuntimeStorage {
|
|
295
|
-
guard let archive = storage as? any ArchiveRuntimeStorage else {
|
|
296
|
-
throw CrocheError("archive_unavailable", "This host keeps no turn archive.")
|
|
297
|
-
}
|
|
298
|
-
return archive
|
|
299
|
-
}
|
|
300
|
-
func archiveAppendLine(entry: String, line: String) throws { try host { try archive().appendLine(entry: entry, line) } }
|
|
301
|
-
func archiveReadLines(entry: String) throws -> [String] { try host { try archive().readLines(entry: entry) } }
|
|
302
|
-
func archiveReplaceLines(entry: String, lines: [String]) throws { try host { try archive().replaceLines(entry: entry, lines) } }
|
|
303
|
-
func archiveRemove(entry: String) throws { try host { try archive().remove(entry: entry) } }
|
|
304
|
-
func archiveEntries(prefix: String) throws -> [ArchiveEntry] {
|
|
305
|
-
try host { try archive().entries(prefix: prefix).sorted { $0.key < $1.key }.map { ArchiveEntry(entry: $0.key, bytes: UInt64($0.value)) } }
|
|
306
|
-
}
|
|
307
|
-
/// Where the message log goes (S1, rev 4 §17.13): in lines when the storage appends them, in
|
|
308
|
-
/// entries when it keeps entries, else inside the snapshot. Never refused.
|
|
309
|
-
func storageCapability() -> StorageCapability {
|
|
310
|
-
if storage is any ArchiveRuntimeStorage { return .lines }
|
|
311
|
-
if storage is any KeyedRuntimeStorage { return .keyed }
|
|
312
|
-
return .snapshot
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
/// Stages the handlers for names with none yet, or with one only staged by a call still in
|
|
316
|
-
/// flight (a later call wins). Returns the stamp that `unstageTools` needs.
|
|
317
|
-
func stageTools(_ tools: [String: ToolHandler]) -> Int {
|
|
318
|
-
lock.withLock {
|
|
319
|
-
stamp += 1
|
|
320
|
-
for (name, handler) in tools where handlers[name] == nil || staged[name] != nil {
|
|
321
|
-
handlers[name] = handler; staged[name] = stamp
|
|
322
|
-
}
|
|
323
|
-
return stamp
|
|
324
|
-
}
|
|
325
|
-
}
|
|
326
|
-
/// A refused call: removes what it staged, unless a later call has staged the name since.
|
|
327
|
-
func unstageTools(_ names: Dictionary<String, ToolHandler>.Keys, stamp: Int) {
|
|
328
|
-
lock.withLock { for name in names where staged[name] == stamp { handlers[name] = nil; staged[name] = nil } }
|
|
329
|
-
}
|
|
330
|
-
/// An accepted call: its handlers serve every name it passed.
|
|
331
|
-
func acceptTools(_ tools: [String: ToolHandler]) {
|
|
332
|
-
lock.withLock { for (name, handler) in tools { handlers[name] = handler; staged[name] = nil } }
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
// MARK: Tools and attestation
|
|
336
|
-
func tool(invocation: String, cancel: CancelToken) throws -> ToolOutput {
|
|
337
|
-
let call = try host { try JSON(invocation) }
|
|
338
|
-
guard let name = call["tool"].string, let handler = lock.withLock({ handlers[name] }) else {
|
|
339
|
-
// Nothing ran, and the Runtime may tell the model so (driver.rs NOT_DISPATCHED).
|
|
340
|
-
throw FfiError.Failure(code: "tool_not_dispatched", message: "The host tool is not available")
|
|
341
|
-
}
|
|
342
|
-
var invocation = JSON.object(["tool": call["tool"], "key": call["key"], "args": call["args"]])
|
|
343
|
-
if call["command"] != .null { invocation["command"] = call["command"] }
|
|
344
|
-
let context = call["context"], request = invocation, sink = ImageSink()
|
|
345
|
-
// No deadline here: the Runtime times the call and cancels it (H4). This returns when
|
|
346
|
-
// the handler does, so a stuck one keeps its slot (H1).
|
|
347
|
-
let value = try blockUntilSettled(cancel: cancel) { signal in
|
|
348
|
-
try await handler(request, ToolContext(data: context, cancellation: signal, images: sink))
|
|
349
|
-
}
|
|
350
|
-
// A plain handler's JSON is the value as it was; a `withResult` one's images ride beside
|
|
351
|
-
// it, one sink per call (never shared between concurrent calls).
|
|
352
|
-
return ToolOutput(value: String(decoding: try host { try value.encoded() }, as: UTF8.self),
|
|
353
|
-
images: try sink.take().map(Images.record))
|
|
354
|
-
}
|
|
355
|
-
func attest(request: String, timeoutMs: UInt64) throws -> String {
|
|
356
|
-
guard let attestor else { throw FfiError.Failure(code: "attestation_unsupported", message: "This host has no attestor") }
|
|
357
|
-
let effect = try host { try JSON(request) }
|
|
358
|
-
guard let clientData = effect["clientData"].string, let hash = base64URLDecode(effect["clientDataHash"].string ?? "") else {
|
|
359
|
-
throw FfiError.Failure(code: "invalid_abi", message: "Malformed attest effect")
|
|
360
|
-
}
|
|
361
|
-
let proof = try blockOn(milliseconds: Double(timeoutMs), cancel: nil) { _ -> JSON in
|
|
362
|
-
let proof = try await attestor.attest(clientData: clientData, clientDataHash: hash)
|
|
363
|
-
return .object(["platform": .string(attestor.platform), "token": .string(proof.token),
|
|
364
|
-
"keyId": proof.keyId.map { .string($0) } ?? .null])
|
|
365
|
-
}
|
|
366
|
-
return String(decoding: try host { try proof.encoded() }, as: UTF8.self)
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
// MARK: Clock, entropy, timer
|
|
370
|
-
func nowMs() -> Double { clock() }
|
|
371
|
-
func utcOffsetMinutes(atMs: Double) -> Int64 {
|
|
372
|
-
Int64((timeZone ?? TimeZone.current).secondsFromGMT(for: Date(timeIntervalSince1970: atMs / 1000)) / 60)
|
|
373
|
-
}
|
|
374
|
-
func random() -> String { UUID().uuidString }
|
|
375
|
-
func wake(atMs: Double?) {
|
|
376
|
-
lock.withLock { wakeTarget = atMs }
|
|
377
|
-
arm()
|
|
378
|
-
}
|
|
379
|
-
/// The agent's whole pending schedule set (JSON `[{id, at}]`), after each durable change and at
|
|
380
|
-
/// open: a timer while running, and the OS's deferred work (`scheduler`) for after. A refused
|
|
381
|
-
/// registration fails this acknowledgement, which the Core reports as `schedule.degraded`
|
|
382
|
-
/// with its code.
|
|
383
|
-
func schedule(entries: String) throws { try host { try applySchedule(target(times(try JSON(entries)))) } }
|
|
384
|
-
private var retryFloor: Double?
|
|
385
|
-
/// A failed delivery answered `retryAt`: a note already due waits until then.
|
|
386
|
-
func retryAfter(_ at: Double) { lock.withLock { retryFloor = at } }
|
|
387
|
-
/// When to wake for these notes: the earliest `at`, except that a note already due waits for
|
|
388
|
-
/// a later `retryAt` (a delivery failed).
|
|
389
|
-
func target(_ times: [Double]) -> Double? {
|
|
390
|
-
let now = clock()
|
|
391
|
-
let floor = lock.withLock { retryFloor }.flatMap { $0 > now ? $0 : nil }
|
|
392
|
-
return times.map { at in floor.map { at <= now ? $0 : at } ?? at }.min()
|
|
393
|
-
}
|
|
394
|
-
/// Arms the timer for `at` (nil: nothing pending) and registers it with the OS.
|
|
395
|
-
func applySchedule(_ at: Double?) throws {
|
|
396
|
-
lock.withLock { dueAt = at }
|
|
397
|
-
armDelivery()
|
|
398
|
-
guard let os = osScheduler else { return }
|
|
399
|
-
do {
|
|
400
|
-
if let at { try os.schedule(earliest: Date(timeIntervalSince1970: at / 1000)) } else { os.cancel() }
|
|
401
|
-
} catch let error as CrocheError { throw error }
|
|
402
|
-
catch { throw CrocheError("schedule_failed", "The OS scheduler refused the request") }
|
|
403
|
-
}
|
|
404
|
-
/// A delivery is starting: it covers every note due now, so the timer never retries one.
|
|
405
|
-
func attempted() { let now = clock(); lock.withLock { fired = max(fired ?? -.infinity, now) } }
|
|
406
|
-
/// The Runtime is open: a wake it asked for while opening can now fire.
|
|
407
|
-
func attach(_ core: CoreRuntime) { lock.withLock { self.core = core }; arm(); armDelivery() }
|
|
408
|
-
/// The Runtime is opening: attach it to the OS scheduler (which may refuse with
|
|
409
|
-
/// `scheduler_conflict`); `stop` releases that attachment once.
|
|
410
|
-
func attachScheduler() throws {
|
|
411
|
-
guard let os = osScheduler else { return }
|
|
412
|
-
try os.attach()
|
|
413
|
-
lock.withLock { osAttached = true }
|
|
414
|
-
}
|
|
415
|
-
func stop() {
|
|
416
|
-
let release = lock.withLock {
|
|
417
|
-
stopped = true; timer?.cancel(); timer = nil; dueTimer?.cancel(); dueTimer = nil
|
|
418
|
-
defer { osAttached = false }
|
|
419
|
-
return osAttached
|
|
420
|
-
}
|
|
421
|
-
if release { osScheduler?.detach() }
|
|
422
|
-
}
|
|
423
|
-
/// One timer at the earliest note, never firing a delivery before its time (a timer that ends
|
|
424
|
-
/// early re-arms), and at most once per time: a delivery that was cut short leaves its notes
|
|
425
|
-
/// for the next open, foreground or OS run rather than retrying at once.
|
|
426
|
-
private func armDelivery() {
|
|
427
|
-
let now = clock()
|
|
428
|
-
lock.withLock {
|
|
429
|
-
dueTimer?.cancel(); dueTimer = nil
|
|
430
|
-
guard !stopped, core != nil, let target = dueAt, !(fired.map { target <= $0 } ?? false) else { return }
|
|
431
|
-
let delay = max(0, target - now)
|
|
432
|
-
dueTimer = Task.detached { [weak self] in
|
|
433
|
-
try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000))
|
|
434
|
-
guard !Task.isCancelled, let self else { return }
|
|
435
|
-
await self.due(target)
|
|
436
|
-
}
|
|
437
|
-
}
|
|
438
|
-
}
|
|
439
|
-
private func due(_ target: Double) async {
|
|
440
|
-
if clock() < target { armDelivery(); return }
|
|
441
|
-
let run: (@Sendable () async -> Void)? = lock.withLock {
|
|
442
|
-
if stopped { return nil }
|
|
443
|
-
fired = target
|
|
444
|
-
return deliverDue
|
|
445
|
-
}
|
|
446
|
-
await run?()
|
|
447
|
-
}
|
|
448
|
-
private func arm() {
|
|
449
|
-
lock.withLock {
|
|
450
|
-
timer?.cancel(); timer = nil
|
|
451
|
-
guard background, !stopped, let target = wakeTarget, let core else { return }
|
|
452
|
-
timer = Task.detached { [weak core] in
|
|
453
|
-
let delay = max(0, target - Date().timeIntervalSince1970 * 1000)
|
|
454
|
-
try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000))
|
|
455
|
-
guard !Task.isCancelled, let core else { return }
|
|
456
|
-
Thread.detachNewThread { core.tick() }
|
|
457
|
-
}
|
|
458
|
-
}
|
|
459
|
-
}
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
private final class StreamStart: @unchecked Sendable {
|
|
463
|
-
private let lock = NSLock()
|
|
464
|
-
private var started = false
|
|
465
|
-
/// True once: the first caller starts the stream.
|
|
466
|
-
func begin() -> Bool { lock.withLock { if started { return false }; started = true; return true } }
|
|
467
|
-
}
|
|
468
|
-
|
|
469
132
|
/// The default transport's connections: one ephemeral URLSession per Runtime, so consecutive
|
|
470
133
|
/// calls (a first launch's challenge, register and sync; a turn's gateway calls) reuse a
|
|
471
134
|
/// connection instead of paying DNS, TCP and TLS again. As before: no cookies, cache, stored
|
|
@@ -492,7 +155,7 @@ final class RuntimeSession: @unchecked Sendable {
|
|
|
492
155
|
private func start(_ request: URLRequest) throws -> (URLSessionDataTask, AsyncThrowingStream<HTTPPart, Error>) {
|
|
493
156
|
let (parts, continuation) = AsyncThrowingStream<HTTPPart, Error>.makeStream()
|
|
494
157
|
return try lock.withLock {
|
|
495
|
-
guard let session else { throw
|
|
158
|
+
guard let session else { throw LegacyCrocheError("network_error", "The Runtime is closed") }
|
|
496
159
|
let task = session.dataTask(with: request)
|
|
497
160
|
router.register(task, continuation)
|
|
498
161
|
return (task, parts)
|
|
@@ -501,10 +164,10 @@ final class RuntimeSession: @unchecked Sendable {
|
|
|
501
164
|
/// The response goes to the Runtime as it arrives. The Runtime frames and bounds it.
|
|
502
165
|
func stream(_ request: PalHttpRequest, into sink: any HttpSinkProtocol, cancellation: RuntimeCancellation) async throws {
|
|
503
166
|
try cancellation.check()
|
|
504
|
-
guard let url = URL(string: request.url) else { throw
|
|
167
|
+
guard let url = URL(string: request.url) else { throw LegacyCrocheError("network_error", "Invalid HTTP effect URL") }
|
|
505
168
|
var urlRequest = URLRequest(url: url)
|
|
506
169
|
urlRequest.httpMethod = request.method
|
|
507
|
-
if !["GET", "HEAD"].contains(request.method) { urlRequest.httpBody = Data(
|
|
170
|
+
if !["GET", "HEAD"].contains(request.method), let body = request.body { urlRequest.httpBody = Data(body.utf8) }
|
|
508
171
|
urlRequest.timeoutInterval = Double(request.timeoutMs) / 1000
|
|
509
172
|
urlRequest.httpShouldHandleCookies = false
|
|
510
173
|
for header in request.headers { urlRequest.setValue(header.value, forHTTPHeaderField: header.name) }
|
|
@@ -547,7 +210,7 @@ private final class HTTPStreamDelegate: NSObject, URLSessionDataDelegate, @unche
|
|
|
547
210
|
didReceive response: URLResponse, completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void) {
|
|
548
211
|
guard let sink = sink(dataTask) else { completionHandler(.cancel); return }
|
|
549
212
|
guard let http = response as? HTTPURLResponse else {
|
|
550
|
-
sink.finish(throwing:
|
|
213
|
+
sink.finish(throwing: LegacyCrocheError("network_error", "No HTTP response")); completionHandler(.cancel); return
|
|
551
214
|
}
|
|
552
215
|
var headers: [String: JSON] = [:]
|
|
553
216
|
for (key, value) in http.allHeaderFields { headers[String(describing: key)] = .string(String(describing: value)) }
|
|
@@ -557,6 +220,6 @@ private final class HTTPStreamDelegate: NSObject, URLSessionDataDelegate, @unche
|
|
|
557
220
|
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive chunk: Data) { sink(dataTask)?.yield(.body(chunk)) }
|
|
558
221
|
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
|
|
559
222
|
let sink = lock.withLock { sinks.removeValue(forKey: task.taskIdentifier) }
|
|
560
|
-
if error != nil { sink?.finish(throwing:
|
|
223
|
+
if error != nil { sink?.finish(throwing: LegacyCrocheError("network_error", "HTTP transport failed")) } else { sink?.finish() }
|
|
561
224
|
}
|
|
562
225
|
}
|