@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
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
package dev.croche.s7.pal
|
|
2
|
+
|
|
3
|
+
import java.io.File
|
|
4
|
+
import java.io.FileOutputStream
|
|
5
|
+
import java.io.RandomAccessFile
|
|
6
|
+
import java.nio.channels.FileLock
|
|
7
|
+
import java.nio.channels.OverlappingFileLockException
|
|
8
|
+
import java.nio.file.Files
|
|
9
|
+
import java.nio.file.StandardCopyOption.ATOMIC_MOVE
|
|
10
|
+
import java.nio.file.StandardCopyOption.REPLACE_EXISTING
|
|
11
|
+
import java.util.Base64
|
|
12
|
+
|
|
13
|
+
/** Physical encoding only: Core owns keys, values, segmentation and recovery. No legacy probing.
|
|
14
|
+
* Segments stay below filesystem filename limits even for Core's longest keys. */
|
|
15
|
+
internal class AtomicKeyFiles(private val root: File, private val syncDirectory: (File) -> Unit) {
|
|
16
|
+
private val held = mutableMapOf<String, Pair<RandomAccessFile, FileLock>>()
|
|
17
|
+
internal var beforeReplace: (() -> Unit)? = null
|
|
18
|
+
private fun encoded(key: String) = Base64.getUrlEncoder().withoutPadding()
|
|
19
|
+
.encodeToString(key.toByteArray(Charsets.UTF_8)).ifEmpty { "_" }
|
|
20
|
+
private fun path(key: String, area: String): File = encoded(key).chunked(100)
|
|
21
|
+
.fold(File(root, area)) { parent, part -> File(parent, part) }.resolve("value")
|
|
22
|
+
private fun mkdirs(directory: File) {
|
|
23
|
+
if (directory.isDirectory) return
|
|
24
|
+
directory.parentFile?.let { mkdirs(it) }
|
|
25
|
+
if (!directory.mkdir() && !directory.isDirectory) throw java.io.IOException("Cannot create PAL directory")
|
|
26
|
+
directory.parentFile?.let(syncDirectory)
|
|
27
|
+
}
|
|
28
|
+
internal fun instancePurgePlan(prefix: String) = planInstancePayloads(File(root, "values"), prefix, syncDirectory)
|
|
29
|
+
private val versioned by lazy { VersionedKeyFiles(this) }
|
|
30
|
+
fun read(key: String) = versioned.read(key)
|
|
31
|
+
fun write(key: String, value: String) = versioned.write(key, value)
|
|
32
|
+
fun remove(key: String) = versioned.remove(key)
|
|
33
|
+
fun list(prefix: String) = versioned.list(prefix)
|
|
34
|
+
fun readVersioned(key: String) = versioned.readVersioned(key)
|
|
35
|
+
fun writeIf(key: String, value: String?, expect: String?) = versioned.writeIf(key, value, expect)
|
|
36
|
+
// Private physical paths only; never expose a reservation bypass at the PAL boundary.
|
|
37
|
+
internal fun readRaw(key: String): String? = storage {
|
|
38
|
+
val file = path(key, "values")
|
|
39
|
+
try { file.readText(Charsets.UTF_8) } catch (e: java.io.FileNotFoundException) {
|
|
40
|
+
if (file.exists()) throw e else null
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
internal fun writeRaw(key: String, value: String) = storage {
|
|
44
|
+
val target = path(key, "values")
|
|
45
|
+
mkdirs(target.parentFile!!)
|
|
46
|
+
val temporary = File.createTempFile("pending-", ".tmp", target.parentFile)
|
|
47
|
+
try {
|
|
48
|
+
FileOutputStream(temporary).use { it.write(value.toByteArray(Charsets.UTF_8)); it.fd.sync() }
|
|
49
|
+
beforeReplace?.invoke()
|
|
50
|
+
Files.move(temporary.toPath(), target.toPath(), ATOMIC_MOVE, REPLACE_EXISTING)
|
|
51
|
+
syncDirectory(target.parentFile!!)
|
|
52
|
+
} finally { temporary.delete() }
|
|
53
|
+
Unit
|
|
54
|
+
}
|
|
55
|
+
internal fun removeRaw(key: String) = storage {
|
|
56
|
+
val file = path(key, "values")
|
|
57
|
+
if (Files.deleteIfExists(file.toPath())) syncDirectory(file.parentFile!!)
|
|
58
|
+
Unit
|
|
59
|
+
}
|
|
60
|
+
internal fun listRaw(prefix: String): List<String> = storage {
|
|
61
|
+
val directory = File(root, "values")
|
|
62
|
+
if (!directory.exists()) return@storage emptyList()
|
|
63
|
+
directory.walkTopDown().filter { it.isFile && it.name == "value" }.map { file ->
|
|
64
|
+
val parts = file.parentFile!!.relativeTo(directory).invariantSeparatorsPath.replace("/", "")
|
|
65
|
+
if (parts == "_") "" else String(Base64.getUrlDecoder().decode(parts), Charsets.UTF_8)
|
|
66
|
+
}.filter { it.startsWith(prefix) }.toList()
|
|
67
|
+
}
|
|
68
|
+
@Synchronized fun lock(key: String): Boolean {
|
|
69
|
+
if (held.containsKey(key)) return false
|
|
70
|
+
return storage {
|
|
71
|
+
val file = path(key, "locks")
|
|
72
|
+
mkdirs(file.parentFile!!)
|
|
73
|
+
val opened = RandomAccessFile(file, "rw")
|
|
74
|
+
try {
|
|
75
|
+
val lock = try { opened.channel.tryLock() } catch (_: OverlappingFileLockException) { null }
|
|
76
|
+
if (lock == null) { opened.close(); false }
|
|
77
|
+
else { held[key] = opened to lock; true }
|
|
78
|
+
} catch (e: Throwable) { opened.close(); throw e }
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
@Synchronized fun unlock(key: String) = storage {
|
|
82
|
+
held.remove(key)?.let { (file, lock) -> try { lock.release() } finally { file.close() } }
|
|
83
|
+
// Never unlink the lock inode: another process may already hold it.
|
|
84
|
+
Unit
|
|
85
|
+
}
|
|
86
|
+
/** Independent per-key cross-process gate; never reacquire a Core lifetime lock. */
|
|
87
|
+
internal fun <T> mutation(key: String, block: () -> T): T {
|
|
88
|
+
// Custody metadata contains no reversible key, value, version or deletion receipt.
|
|
89
|
+
val name = java.security.MessageDigest.getInstance("SHA-256").digest(key.toByteArray(Charsets.UTF_8))
|
|
90
|
+
.joinToString("") { "%02x".format(it.toInt() and 255) }
|
|
91
|
+
val file = File(File(root, "writers"), "$name.lock"); mkdirs(file.parentFile!!)
|
|
92
|
+
return RandomAccessFile(file, "rw").use { opened ->
|
|
93
|
+
val gate = try { opened.channel.tryLock() } catch (_: OverlappingFileLockException) { null }
|
|
94
|
+
if (gate == null) throw java.io.IOException("A value mutation is already active")
|
|
95
|
+
try { block() } finally { gate.release() }
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
// Exceptions remain raw facts; the Core callback boundary assigns storage_error.
|
|
99
|
+
private inline fun <T> storage(block: () -> T): T = block()
|
|
100
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
package dev.croche.s7.pal
|
|
2
|
+
|
|
3
|
+
import dev.croche.ffi.FfiException
|
|
4
|
+
import dev.croche.ffi.PalBlobEntry
|
|
5
|
+
import dev.croche.ffi.PalBlobReply
|
|
6
|
+
import java.io.File
|
|
7
|
+
import java.io.FileOutputStream
|
|
8
|
+
import java.io.IOException
|
|
9
|
+
import java.nio.file.FileAlreadyExistsException
|
|
10
|
+
import java.nio.file.Files
|
|
11
|
+
import java.nio.file.LinkOption.NOFOLLOW_LINKS
|
|
12
|
+
import java.nio.file.NoSuchFileException
|
|
13
|
+
import java.nio.file.StandardCopyOption.ATOMIC_MOVE
|
|
14
|
+
import java.nio.file.StandardCopyOption.REPLACE_EXISTING
|
|
15
|
+
import java.nio.file.attribute.BasicFileAttributes
|
|
16
|
+
|
|
17
|
+
/** Private file transport for Core's blob keys. The bytes on disk are the original bytes. */
|
|
18
|
+
internal class BlobFiles(
|
|
19
|
+
private val parent: File,
|
|
20
|
+
private val prepareParent: (() -> Unit)? = null,
|
|
21
|
+
private val syncDirectory: (File) -> Unit,
|
|
22
|
+
) {
|
|
23
|
+
internal data class Entry(val key: String, val size: Long)
|
|
24
|
+
internal data class Page(val entries: List<Entry>, val nextCursor: String?)
|
|
25
|
+
|
|
26
|
+
private val root = File(parent, "blobs")
|
|
27
|
+
private val segment = Regex("[a-z0-9~][a-z0-9._~-]*")
|
|
28
|
+
|
|
29
|
+
private fun createDirectory(path: File) {
|
|
30
|
+
try {
|
|
31
|
+
Files.createDirectory(path.toPath())
|
|
32
|
+
syncDirectory(path.parentFile)
|
|
33
|
+
} catch (_: FileAlreadyExistsException) {
|
|
34
|
+
// A concurrent publisher may have created the same ancestor.
|
|
35
|
+
}
|
|
36
|
+
if (!Files.isDirectory(path.toPath(), NOFOLLOW_LINKS)) throw IOException("Invalid blob directory")
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
private fun directory(key: String, create: Boolean): File? {
|
|
40
|
+
val parts = if (key.isEmpty()) emptyList() else key.split('/')
|
|
41
|
+
require(key.length <= 1024 && parts.all(segment::matches)) { "Invalid blob key" }
|
|
42
|
+
if (create && !Files.isDirectory(parent.toPath(), NOFOLLOW_LINKS)) {
|
|
43
|
+
if (!Files.exists(parent.toPath(), NOFOLLOW_LINKS)) prepareParent?.invoke()
|
|
44
|
+
createDirectory(parent)
|
|
45
|
+
}
|
|
46
|
+
var path = root
|
|
47
|
+
for (part in listOf("") + parts) {
|
|
48
|
+
if (part.isNotEmpty()) path = path.resolve(part)
|
|
49
|
+
if (create) createDirectory(path)
|
|
50
|
+
else {
|
|
51
|
+
if (!Files.exists(path.toPath(), NOFOLLOW_LINKS)) return null
|
|
52
|
+
if (!Files.isDirectory(path.toPath(), NOFOLLOW_LINKS)) throw IOException("Invalid blob directory")
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return path
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
fun operation(operation: String, key: String, cursor: String?, bytes: ByteArray?): PalBlobReply {
|
|
59
|
+
try {
|
|
60
|
+
when (operation) {
|
|
61
|
+
"get" -> return PalBlobReply(get(key), emptyList(), null)
|
|
62
|
+
"put" -> put(key, requireNotNull(bytes))
|
|
63
|
+
"delete" -> delete(key)
|
|
64
|
+
"list" -> {
|
|
65
|
+
val page = list(key, cursor)
|
|
66
|
+
return PalBlobReply(null, page.entries.map { PalBlobEntry(it.key, it.size.toULong()) }, page.nextCursor)
|
|
67
|
+
}
|
|
68
|
+
"purgeStaging" -> purgeStaging(key)
|
|
69
|
+
else -> throw IOException("Unknown blob operation")
|
|
70
|
+
}
|
|
71
|
+
return PalBlobReply(null, emptyList(), null)
|
|
72
|
+
} catch (error: Exception) {
|
|
73
|
+
// Keep platform diagnostics attached locally. The FFI detail carries no filesystem paths.
|
|
74
|
+
throw FfiException.Failure("storage_error", "Blob operation failed").apply { initCause(error) }
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
fun put(key: String, bytes: ByteArray) {
|
|
79
|
+
require(key.isNotEmpty())
|
|
80
|
+
val dir = directory(key, true) ?: throw IOException("Blob directory disappeared")
|
|
81
|
+
val temporary = Files.createTempFile(dir.toPath(), ".tmp-", "").toFile()
|
|
82
|
+
try {
|
|
83
|
+
FileOutputStream(temporary).use { file -> file.write(bytes); file.fd.sync() }
|
|
84
|
+
Files.move(temporary.toPath(), dir.resolve("object").toPath(), ATOMIC_MOVE, REPLACE_EXISTING)
|
|
85
|
+
syncDirectory(dir)
|
|
86
|
+
} finally {
|
|
87
|
+
Files.deleteIfExists(temporary.toPath())
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
fun get(key: String): ByteArray? {
|
|
92
|
+
require(key.isNotEmpty())
|
|
93
|
+
val path = directory(key, false)?.resolve("object")?.toPath() ?: return null
|
|
94
|
+
if (!Files.exists(path, NOFOLLOW_LINKS)) return null
|
|
95
|
+
if (!Files.isRegularFile(path, NOFOLLOW_LINKS)) throw IOException("Invalid blob object")
|
|
96
|
+
return Files.readAllBytes(path)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
fun delete(key: String) {
|
|
100
|
+
require(key.isNotEmpty())
|
|
101
|
+
val dir = directory(key, false) ?: return
|
|
102
|
+
if (Files.deleteIfExists(dir.resolve("object").toPath())) syncDirectory(dir)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
fun list(prefix: String, cursor: String?): Page {
|
|
106
|
+
val parent = prefix.substringBeforeLast('/', "")
|
|
107
|
+
val dir = directory(parent, false) ?: return Page(emptyList(), null)
|
|
108
|
+
val entries = ArrayList<Entry>()
|
|
109
|
+
fun walk(folder: File, key: String) {
|
|
110
|
+
Files.newDirectoryStream(folder.toPath()).use { children ->
|
|
111
|
+
for (child in children) {
|
|
112
|
+
val name = child.fileName.toString()
|
|
113
|
+
if (name == "object" && key.startsWith(prefix) &&
|
|
114
|
+
(cursor == null || key > cursor) && Files.isRegularFile(child, NOFOLLOW_LINKS)) {
|
|
115
|
+
entries.add(Entry(key, Files.size(child)))
|
|
116
|
+
} else if (segment.matches(name) && Files.isDirectory(child, NOFOLLOW_LINKS)) {
|
|
117
|
+
val childKey = if (key.isEmpty()) name else "$key/$name"
|
|
118
|
+
if (childKey.startsWith(prefix) || prefix.startsWith("$childKey/")) {
|
|
119
|
+
walk(child.toFile(), childKey)
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
walk(dir, parent)
|
|
126
|
+
entries.sortBy(Entry::key)
|
|
127
|
+
val page = entries.take(1000)
|
|
128
|
+
return Page(page, if (entries.size > page.size) page.last().key else null)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The owning Core writer has drained this scope before calling this. */
|
|
132
|
+
fun purgeStaging(prefix: String) {
|
|
133
|
+
require(prefix.length > 1 && prefix.endsWith('/'))
|
|
134
|
+
val dir = directory(prefix.dropLast(1), false) ?: return
|
|
135
|
+
removeStagedFiles(dir)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
private fun removeStagedFiles(dir: File) {
|
|
139
|
+
// The exact owner lease covers the no-follow check and subsequent unlink.
|
|
140
|
+
Files.newDirectoryStream(dir.toPath()).use { children ->
|
|
141
|
+
for (child in children) {
|
|
142
|
+
val name = child.fileName.toString()
|
|
143
|
+
val facts = try {
|
|
144
|
+
Files.readAttributes(child, BasicFileAttributes::class.java, NOFOLLOW_LINKS)
|
|
145
|
+
} catch (_: NoSuchFileException) {
|
|
146
|
+
continue
|
|
147
|
+
}
|
|
148
|
+
if (facts.isRegularFile && name.startsWith(".tmp-")) {
|
|
149
|
+
Files.deleteIfExists(child)
|
|
150
|
+
} else if (facts.isDirectory && segment.matches(name)) {
|
|
151
|
+
removeStagedFiles(child.toFile())
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
syncDirectory(dir)
|
|
156
|
+
}
|
|
157
|
+
}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
package dev.croche.s7.pal
|
|
2
|
+
|
|
3
|
+
import dev.croche.CrocheError
|
|
4
|
+
import dev.croche.ResponseSink
|
|
5
|
+
import dev.croche.RuntimeCancellation
|
|
6
|
+
import dev.croche.ffi.PalHeader
|
|
7
|
+
import dev.croche.ffi.PalHttpRequest
|
|
8
|
+
import java.io.BufferedInputStream
|
|
9
|
+
import java.io.EOFException
|
|
10
|
+
import java.io.InputStream
|
|
11
|
+
import java.io.IOException
|
|
12
|
+
import java.net.InetAddress
|
|
13
|
+
import java.net.InetSocketAddress
|
|
14
|
+
import java.net.Socket
|
|
15
|
+
import java.net.URI
|
|
16
|
+
import java.util.concurrent.ExecutionException
|
|
17
|
+
import java.util.concurrent.Executors
|
|
18
|
+
import java.util.concurrent.TimeUnit
|
|
19
|
+
import java.util.concurrent.TimeoutException
|
|
20
|
+
import javax.net.ssl.SSLSocket
|
|
21
|
+
import javax.net.ssl.SSLSocketFactory
|
|
22
|
+
|
|
23
|
+
/** One direct HTTP/1.1 transport for pinned and ordinary effects. No proxy, connection pool,
|
|
24
|
+
* cookies, cache or redirect machinery. Core supplies policy; this adapter supplies bytes.
|
|
25
|
+
* The sole connection pin is the generated request.connectTo field. */
|
|
26
|
+
internal class DirectHttpPal(
|
|
27
|
+
private val tlsFactory: SSLSocketFactory = SSLSocketFactory.getDefault() as SSLSocketFactory,
|
|
28
|
+
private val resolveAddresses: (String) -> List<String> = { host ->
|
|
29
|
+
InetAddress.getAllByName(host).map { it.hostAddress!! }
|
|
30
|
+
},
|
|
31
|
+
) {
|
|
32
|
+
fun resolve(host: String, cancellation: RuntimeCancellation): List<String> = resolveBefore(host, cancellation, null)
|
|
33
|
+
|
|
34
|
+
private fun resolveBefore(host: String, cancellation: RuntimeCancellation, deadline: Long?): List<String> {
|
|
35
|
+
cancellation.check()
|
|
36
|
+
val lookup = resolver.submit<List<String>> { resolveAddresses(host) }
|
|
37
|
+
try {
|
|
38
|
+
while (true) {
|
|
39
|
+
cancellation.check()
|
|
40
|
+
if (deadline != null && System.nanoTime() >= deadline) throw CrocheError("network_error", "DNS resolution timed out")
|
|
41
|
+
try { return lookup.get(50, TimeUnit.MILLISECONDS).also { cancellation.check() } }
|
|
42
|
+
catch (_: TimeoutException) { /* Core owns the deadline and cancellation. */ }
|
|
43
|
+
}
|
|
44
|
+
} catch (e: CrocheError) { throw e }
|
|
45
|
+
catch (error: ExecutionException) {
|
|
46
|
+
cancellation.check()
|
|
47
|
+
// Future.get wraps the resolver's failure: classify its cause, not the wrapper.
|
|
48
|
+
val code = if (error.cause is IOException) "network_error" else "internal"
|
|
49
|
+
throw CrocheError(code, "DNS resolution failed")
|
|
50
|
+
} catch (_: Exception) {
|
|
51
|
+
cancellation.check()
|
|
52
|
+
throw CrocheError("internal", "DNS resolution failed")
|
|
53
|
+
}
|
|
54
|
+
finally { lookup.cancel(true) }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
fun http(request: PalHttpRequest, sink: ResponseSink, cancellation: RuntimeCancellation) {
|
|
58
|
+
cancellation.check()
|
|
59
|
+
val uri = URI(request.url)
|
|
60
|
+
val host = uri.host?.removeSurrounding("[", "]") ?: throw CrocheError("invalid_abi", "HTTP URL needs a host")
|
|
61
|
+
val tls = when (uri.scheme) {
|
|
62
|
+
"https" -> true
|
|
63
|
+
"http" -> false
|
|
64
|
+
else -> throw CrocheError("invalid_abi", "Invalid HTTP scheme")
|
|
65
|
+
}
|
|
66
|
+
val port = if (uri.port >= 0) uri.port else if (tls) 443 else 80
|
|
67
|
+
val timeout = request.timeoutMs.coerceIn(1uL, Int.MAX_VALUE.toULong()).toInt()
|
|
68
|
+
val address = request.connectTo?.let(::numericAddress)
|
|
69
|
+
if (uri.rawUserInfo != null) throw CrocheError("invalid_abi", "HTTP user info is unsupported")
|
|
70
|
+
val expires = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeout.toLong())
|
|
71
|
+
val raw = Socket()
|
|
72
|
+
val cancelled = cancellation.observe { try { raw.close() } catch (_: Exception) {} }
|
|
73
|
+
val deadline = timer.schedule({ try { raw.close() } catch (_: Exception) {} }, timeout.toLong(), TimeUnit.MILLISECONDS)
|
|
74
|
+
try {
|
|
75
|
+
val resolved = address ?: numericAddress(resolveBefore(host, cancellation, expires).firstOrNull()
|
|
76
|
+
?: throw CrocheError("network_error", "DNS returned no address"))
|
|
77
|
+
val destination = InetSocketAddress(resolved, port)
|
|
78
|
+
raw.connect(destination, timeout)
|
|
79
|
+
raw.soTimeout = timeout
|
|
80
|
+
val socket = if (tls) {
|
|
81
|
+
(tlsFactory.createSocket(raw, host, port, true) as SSLSocket).apply {
|
|
82
|
+
sslParameters = sslParameters.apply { endpointIdentificationAlgorithm = "HTTPS" }
|
|
83
|
+
startHandshake()
|
|
84
|
+
}
|
|
85
|
+
} else raw
|
|
86
|
+
socket.use {
|
|
87
|
+
cancellation.check()
|
|
88
|
+
writeRequest(it, uri, request)
|
|
89
|
+
readResponse(it.getInputStream(), request, sink, cancellation)
|
|
90
|
+
}
|
|
91
|
+
} catch (e: CrocheError) { throw e }
|
|
92
|
+
catch (_: IOException) {
|
|
93
|
+
cancellation.check()
|
|
94
|
+
throw CrocheError("network_error", "HTTP transport failed")
|
|
95
|
+
} catch (_: Exception) {
|
|
96
|
+
cancellation.check()
|
|
97
|
+
throw CrocheError("internal", "HTTP transport failed")
|
|
98
|
+
} finally {
|
|
99
|
+
deadline.cancel(false)
|
|
100
|
+
cancellation.remove(cancelled)
|
|
101
|
+
raw.close()
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
private fun writeRequest(socket: Socket, uri: URI, request: PalHttpRequest) {
|
|
106
|
+
val body = request.body?.toByteArray(Charsets.UTF_8)
|
|
107
|
+
val target = (uri.rawPath?.ifEmpty { "/" } ?: "/") + (uri.rawQuery?.let { "?$it" } ?: "")
|
|
108
|
+
requireLine(request.method); requireLine(target)
|
|
109
|
+
val lines = StringBuilder("${request.method} $target HTTP/1.1\r\nHost: ${uri.rawAuthority}\r\nConnection: close\r\n")
|
|
110
|
+
for (header in request.headers) {
|
|
111
|
+
requireLine(header.name); requireLine(header.value)
|
|
112
|
+
if (header.name.lowercase() !in setOf("host", "connection", "content-length", "transfer-encoding"))
|
|
113
|
+
lines.append("${header.name}: ${header.value}\r\n")
|
|
114
|
+
}
|
|
115
|
+
if (body != null) lines.append("Content-Length: ${body.size}\r\n")
|
|
116
|
+
lines.append("\r\n")
|
|
117
|
+
socket.getOutputStream().apply {
|
|
118
|
+
write(lines.toString().toByteArray(Charsets.ISO_8859_1))
|
|
119
|
+
if (body != null) write(body)
|
|
120
|
+
flush()
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
private fun requireLine(value: String) {
|
|
124
|
+
if (value.any { it == '\r' || it == '\n' }) throw CrocheError("invalid_abi", "Invalid HTTP request line")
|
|
125
|
+
}
|
|
126
|
+
private fun numericAddress(pin: String): InetAddress {
|
|
127
|
+
// Guard before InetAddress: a malformed pin MUST NOT trigger DNS or an unpinned fallback.
|
|
128
|
+
if (pin.contains(':')) {
|
|
129
|
+
if (!pin.matches(Regex("[0-9a-fA-F:.]+"))) throw CrocheError("invalid_abi", "Invalid HTTP connectTo")
|
|
130
|
+
} else {
|
|
131
|
+
val parts = pin.split('.')
|
|
132
|
+
if (parts.size != 4 || parts.any { part ->
|
|
133
|
+
part.isEmpty() || part.any { !it.isDigit() } || part.toIntOrNull()?.let { it in 0..255 } != true
|
|
134
|
+
}) throw CrocheError("invalid_abi", "Invalid HTTP connectTo")
|
|
135
|
+
}
|
|
136
|
+
return try { InetAddress.getByName(pin) }
|
|
137
|
+
catch (_: Exception) { throw CrocheError("invalid_abi", "Invalid HTTP connectTo") }
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
private fun readResponse(source: InputStream, request: PalHttpRequest, sink: ResponseSink, cancellation: RuntimeCancellation) {
|
|
141
|
+
val input = BufferedInputStream(source)
|
|
142
|
+
var status: Int
|
|
143
|
+
var headers: List<PalHeader>
|
|
144
|
+
var informational = 0
|
|
145
|
+
do {
|
|
146
|
+
val statusLine = line(input)
|
|
147
|
+
status = statusLine.split(' ').getOrNull(1)?.toIntOrNull()
|
|
148
|
+
?: throw java.io.IOException("Invalid HTTP status")
|
|
149
|
+
if (!statusLine.startsWith("HTTP/1.") || status !in 100..599) throw java.io.IOException("Invalid HTTP status")
|
|
150
|
+
val fields = mutableListOf<PalHeader>()
|
|
151
|
+
var bytes = statusLine.length
|
|
152
|
+
while (true) {
|
|
153
|
+
val field = line(input)
|
|
154
|
+
bytes += field.length + 2
|
|
155
|
+
if (bytes > 65536) throw java.io.IOException("HTTP headers exceed bound")
|
|
156
|
+
if (field.isEmpty()) break
|
|
157
|
+
val colon = field.indexOf(':')
|
|
158
|
+
if (colon <= 0 || field.first().isWhitespace()) throw java.io.IOException("Invalid HTTP header")
|
|
159
|
+
fields += PalHeader(field.substring(0, colon), field.substring(colon + 1).trim())
|
|
160
|
+
}
|
|
161
|
+
headers = fields
|
|
162
|
+
if (++informational > 16) throw java.io.IOException("Too many interim responses")
|
|
163
|
+
} while (status in 100..199 && status != 101)
|
|
164
|
+
sink.head(status, headers)
|
|
165
|
+
if (request.method == "HEAD" || status in 100..199 || status == 204 || status == 304) return
|
|
166
|
+
val lengths = headers.filter { it.name.equals("content-length", true) }.map { it.value }
|
|
167
|
+
if (lengths.distinct().size > 1) throw java.io.IOException("Conflicting HTTP lengths")
|
|
168
|
+
val transfer = headers.filter { it.name.equals("transfer-encoding", true) }.map { it.value.lowercase() }
|
|
169
|
+
if (transfer.isNotEmpty() && transfer != listOf("chunked")) throw java.io.IOException("Unsupported HTTP transfer coding")
|
|
170
|
+
var received = 0uL
|
|
171
|
+
fun copy(count: Long?): Boolean {
|
|
172
|
+
var remaining = count
|
|
173
|
+
val buffer = ByteArray(8192)
|
|
174
|
+
while (remaining == null || remaining > 0) {
|
|
175
|
+
cancellation.check()
|
|
176
|
+
val n = input.read(buffer, 0, remaining?.coerceAtMost(buffer.size.toLong())?.toInt() ?: buffer.size)
|
|
177
|
+
if (n < 0) { if (remaining != null) throw EOFException(); return true }
|
|
178
|
+
received += n.toULong()
|
|
179
|
+
if (received > request.maxResponseBytes) throw CrocheError("invalid_response", "HTTP response exceeds bound")
|
|
180
|
+
if (!sink.chunk(buffer.copyOf(n))) return false
|
|
181
|
+
remaining = remaining?.minus(n)
|
|
182
|
+
}
|
|
183
|
+
return true
|
|
184
|
+
}
|
|
185
|
+
if (transfer.isNotEmpty()) {
|
|
186
|
+
while (true) {
|
|
187
|
+
val size = line(input).substringBefore(';').trim().toLongOrNull(16)
|
|
188
|
+
?: throw java.io.IOException("Invalid HTTP chunk")
|
|
189
|
+
if (size < 0) throw java.io.IOException("Invalid HTTP chunk")
|
|
190
|
+
if (size == 0L) {
|
|
191
|
+
var trailerBytes = 0
|
|
192
|
+
while (true) {
|
|
193
|
+
val trailer = line(input); trailerBytes += trailer.length + 2
|
|
194
|
+
if (trailerBytes > 65536) throw java.io.IOException("HTTP trailers exceed bound")
|
|
195
|
+
if (trailer.isEmpty()) return
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
if (!copy(size)) return
|
|
199
|
+
if (line(input).isNotEmpty()) throw java.io.IOException("Invalid chunk terminator")
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
val length = lengths.firstOrNull()?.toLongOrNull()
|
|
203
|
+
if (lengths.isNotEmpty() && (length == null || length < 0)) throw java.io.IOException("Invalid HTTP length")
|
|
204
|
+
copy(length)
|
|
205
|
+
}
|
|
206
|
+
private fun line(input: InputStream): String {
|
|
207
|
+
val bytes = java.io.ByteArrayOutputStream()
|
|
208
|
+
while (bytes.size() <= 8192) {
|
|
209
|
+
val next = input.read()
|
|
210
|
+
if (next < 0) throw EOFException()
|
|
211
|
+
if (next == 13) {
|
|
212
|
+
if (input.read() != 10) throw java.io.IOException("Invalid HTTP line ending")
|
|
213
|
+
return bytes.toString("ISO-8859-1")
|
|
214
|
+
}
|
|
215
|
+
bytes.write(next)
|
|
216
|
+
}
|
|
217
|
+
throw java.io.IOException("HTTP line exceeds bound")
|
|
218
|
+
}
|
|
219
|
+
private companion object {
|
|
220
|
+
val timer = Executors.newSingleThreadScheduledExecutor { Thread(it, "croche-http-deadline").apply { isDaemon = true } }
|
|
221
|
+
val resolver = Executors.newFixedThreadPool(4) { Thread(it, "croche-resolve").apply { isDaemon = true } }
|
|
222
|
+
}
|
|
223
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
package dev.croche.s7.pal
|
|
2
|
+
|
|
3
|
+
import java.io.File
|
|
4
|
+
import java.io.IOException
|
|
5
|
+
import java.nio.ByteBuffer
|
|
6
|
+
import java.nio.charset.StandardCharsets
|
|
7
|
+
import java.nio.file.Files
|
|
8
|
+
import java.nio.file.LinkOption.NOFOLLOW_LINKS
|
|
9
|
+
import java.util.Base64
|
|
10
|
+
|
|
11
|
+
internal data class PayloadPurgePlan(
|
|
12
|
+
val temporaries: List<File>, val values: List<File>, val directories: Set<File>,
|
|
13
|
+
val sync: (File) -> Unit,
|
|
14
|
+
) {
|
|
15
|
+
fun erase(files: List<File>) { for (file in files) Files.deleteIfExists(file.toPath()) }
|
|
16
|
+
fun durable() { for (directory in directories) sync(directory) }
|
|
17
|
+
}
|
|
18
|
+
private val portableKey = Regex("[A-Za-z0-9._/-]{1,200}")
|
|
19
|
+
private fun keyAt(base: File, directory: File): String? {
|
|
20
|
+
val parts = directory.relativeTo(base).invariantSeparatorsPath.split('/')
|
|
21
|
+
if (parts.any { it.isEmpty() || it.length > 100 } || parts.dropLast(1).any { it.length != 100 }) return null
|
|
22
|
+
return try {
|
|
23
|
+
val encoded = parts.joinToString("")
|
|
24
|
+
val bytes = Base64.getUrlDecoder().decode(encoded)
|
|
25
|
+
if (Base64.getUrlEncoder().withoutPadding().encodeToString(bytes) != encoded) return null
|
|
26
|
+
StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString().takeIf { portableKey.matches(it) }
|
|
27
|
+
} catch (_: IllegalArgumentException) { null } catch (_: java.nio.charset.CharacterCodingException) { null }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Physical encoding only: one base64url key directory, never Core's namespace layout. */
|
|
31
|
+
internal fun planInstancePayloads(base: File, prefix: String, sync: (File) -> Unit): PayloadPurgePlan {
|
|
32
|
+
val temps = mutableListOf<File>(); val values = mutableListOf<File>(); val directories = linkedSetOf<File>()
|
|
33
|
+
val attributes = try {
|
|
34
|
+
// The area check alone follows a replaced backend-managed state/secrets ancestor.
|
|
35
|
+
val parent = Files.readAttributes(base.parentFile.toPath(), java.nio.file.attribute.BasicFileAttributes::class.java, NOFOLLOW_LINKS)
|
|
36
|
+
if (!parent.isDirectory) throw IOException("Invalid payload ancestor")
|
|
37
|
+
Files.readAttributes(base.toPath(), java.nio.file.attribute.BasicFileAttributes::class.java, NOFOLLOW_LINKS)
|
|
38
|
+
}
|
|
39
|
+
catch (_: java.nio.file.NoSuchFileException) { return PayloadPurgePlan(temps, values, directories, sync) }
|
|
40
|
+
if (!attributes.isDirectory) throw IOException("Invalid payload area")
|
|
41
|
+
Files.walk(base.toPath()).use { paths ->
|
|
42
|
+
paths.forEach { path ->
|
|
43
|
+
if (path == base.toPath()) return@forEach
|
|
44
|
+
val file = path.toFile()
|
|
45
|
+
if (Files.isDirectory(path, NOFOLLOW_LINKS)) {
|
|
46
|
+
// Retained empty key directories allow a retry to acknowledge prior temp deletion.
|
|
47
|
+
if (keyAt(base, file)?.startsWith(prefix) == true) directories.add(file)
|
|
48
|
+
return@forEach
|
|
49
|
+
}
|
|
50
|
+
val key = keyAt(base, file.parentFile) ?: throw IOException("Undecodable payload path")
|
|
51
|
+
if (!key.startsWith(prefix)) return@forEach
|
|
52
|
+
if (!Files.isRegularFile(path, NOFOLLOW_LINKS)) throw IOException("Invalid selected payload")
|
|
53
|
+
directories.add(file.parentFile)
|
|
54
|
+
when {
|
|
55
|
+
file.name == "value" -> values.add(file)
|
|
56
|
+
file.name.startsWith("pending-") && file.name.endsWith(".tmp") -> temps.add(file)
|
|
57
|
+
else -> throw IOException("Unrecognized selected payload")
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return PayloadPurgePlan(temps, values, directories, sync)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Erases every payload file of one instance, not log-floor pruning. Core owns exact lifetime custody. */
|
|
65
|
+
internal fun purgeInstanceFiles(
|
|
66
|
+
values: AtomicKeyFiles?, secrets: AtomicKeyFiles?, prefix: String,
|
|
67
|
+
deleteSecret: () -> Unit = {}, deleteState: () -> Unit = {},
|
|
68
|
+
) {
|
|
69
|
+
require(portableKey.matches(prefix) && prefix.length > 1 && prefix.endsWith('/')) { "Invalid purge prefix" }
|
|
70
|
+
val ordinary = values?.instancePurgePlan(prefix)
|
|
71
|
+
val secret = secrets?.instancePurgePlan(prefix)
|
|
72
|
+
// Validate both local areas before a write. Durable temp erasure precedes canonical deletion.
|
|
73
|
+
ordinary?.let { it.erase(it.temporaries); it.durable() }
|
|
74
|
+
secret?.let { it.erase(it.temporaries); it.durable() }
|
|
75
|
+
deleteSecret()
|
|
76
|
+
secret?.let { it.erase(it.values); it.durable() }
|
|
77
|
+
deleteState()
|
|
78
|
+
ordinary?.let { it.erase(it.values); it.durable() }
|
|
79
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
package dev.croche.s7.pal
|
|
2
|
+
|
|
3
|
+
import com.google.gson.JsonArray
|
|
4
|
+
import com.google.gson.JsonParser
|
|
5
|
+
import dev.croche.VersionedValue
|
|
6
|
+
import dev.croche.WriteOutcome
|
|
7
|
+
import dev.croche.s7.logicalStorageKey
|
|
8
|
+
import dev.croche.s7.storageVersion
|
|
9
|
+
import dev.croche.s7.versionedStorageKey
|
|
10
|
+
import java.io.IOException
|
|
11
|
+
import java.security.SecureRandom
|
|
12
|
+
|
|
13
|
+
/** Integral frames at K/.p1 through the same physical encoder and atomic writer. */
|
|
14
|
+
internal class VersionedKeyFiles(private val files: AtomicKeyFiles) {
|
|
15
|
+
private fun frame(key: String): String? =
|
|
16
|
+
if (Regex("[A-Za-z0-9._/-]{1,196}").matches(key) && !key.split('/').contains("secret-index")) "$key/.p1" else null
|
|
17
|
+
private fun snapshot(key: String): VersionedValue {
|
|
18
|
+
val encoded = frame(key)?.let { files.readRaw(it) }
|
|
19
|
+
if (encoded != null) {
|
|
20
|
+
val raw = JsonParser.parseString(encoded)
|
|
21
|
+
if (!raw.isJsonArray) throw IOException("Invalid versioned value frame")
|
|
22
|
+
val parts = raw.asJsonArray
|
|
23
|
+
if (parts.size() != 3 || !parts[0].isJsonPrimitive || !parts[0].asJsonPrimitive.isNumber || parts[0].asString != "1"
|
|
24
|
+
|| !parts[1].isJsonPrimitive || !parts[1].asJsonPrimitive.isString || !Regex("[a-f0-9]{32}").matches(parts[1].asString)
|
|
25
|
+
|| !parts[2].isJsonPrimitive || !parts[2].asJsonPrimitive.isString) throw IOException("Invalid versioned value frame")
|
|
26
|
+
return VersionedValue(parts[2].asString, parts[1].asString)
|
|
27
|
+
}
|
|
28
|
+
val value = files.readRaw(key)
|
|
29
|
+
return VersionedValue(value, if (value == null) null else "legacy")
|
|
30
|
+
}
|
|
31
|
+
private fun publish(key: String, value: String): String {
|
|
32
|
+
val token = ByteArray(16).also(random::nextBytes).joinToString("") { "%02x".format(it.toInt() and 255) }
|
|
33
|
+
val encoded = JsonArray().apply { add(1); add(token); add(value) }.toString()
|
|
34
|
+
files.writeRaw(frame(key) ?: throw IOException("Invalid versioned key"), encoded)
|
|
35
|
+
return token
|
|
36
|
+
}
|
|
37
|
+
private fun erase(key: String) {
|
|
38
|
+
// A partial failure leaves the authoritative frame, never stale raw bytes.
|
|
39
|
+
files.removeRaw(key); frame(key)?.let(files::removeRaw)
|
|
40
|
+
}
|
|
41
|
+
fun read(key: String): String? = snapshot(logicalStorageKey(key)).value
|
|
42
|
+
fun write(key: String, value: String) {
|
|
43
|
+
logicalStorageKey(key)
|
|
44
|
+
files.mutation(key) {
|
|
45
|
+
val current = snapshot(key)
|
|
46
|
+
if (current.version != null && current.version != "legacy") publish(key, value)
|
|
47
|
+
else files.writeRaw(key, value)
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
fun remove(key: String) { logicalStorageKey(key); files.mutation(key) { erase(key) } }
|
|
51
|
+
fun list(prefix: String): List<String> {
|
|
52
|
+
logicalStorageKey(prefix)
|
|
53
|
+
return files.listRaw(prefix).map { key ->
|
|
54
|
+
if (key.endsWith("/.p1")) versionedStorageKey(key.dropLast(4)) else logicalStorageKey(key)
|
|
55
|
+
}.filter { it.startsWith(prefix) }.distinct()
|
|
56
|
+
}
|
|
57
|
+
fun readVersioned(key: String): VersionedValue {
|
|
58
|
+
versionedStorageKey(key)
|
|
59
|
+
return files.mutation(key) { snapshot(key) }
|
|
60
|
+
}
|
|
61
|
+
fun writeIf(key: String, value: String?, expect: String?): WriteOutcome {
|
|
62
|
+
versionedStorageKey(key); storageVersion(expect)
|
|
63
|
+
return files.mutation(key) {
|
|
64
|
+
val current = snapshot(key)
|
|
65
|
+
if (current.version != expect) WriteOutcome.Conflict(current.version)
|
|
66
|
+
else if (value == null) { erase(key); WriteOutcome.Written(null) }
|
|
67
|
+
else WriteOutcome.Written(publish(key, value))
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
private companion object { val random = SecureRandom() }
|
|
71
|
+
}
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -22,6 +22,7 @@ Pod::Spec.new do |s|
|
|
|
22
22
|
# compiled into one module; the bindings import the croche_ffiFFI C module.
|
|
23
23
|
s.source_files = "ios/*.{h,m,mm,swift}", "ios/vendor/CrocheRuntimeSDK/**/*.swift"
|
|
24
24
|
s.vendored_frameworks = "ios/vendor/croche_ffiFFI.xcframework"
|
|
25
|
+
s.libraries = "sqlite3"
|
|
25
26
|
s.frameworks = "DeviceCheck", "Security"
|
|
26
27
|
|
|
27
28
|
install_modules_dependencies(s)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"module"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { TurboModule } from 'react-native';
|
|
2
|
+
export type OwnedImage = {
|
|
3
|
+
element: number;
|
|
4
|
+
bytes: ReadonlyArray<number>;
|
|
5
|
+
};
|
|
6
|
+
export interface Spec extends TurboModule {
|
|
7
|
+
coreCall(handle: string, method: string, argsJson: string, images: ReadonlyArray<OwnedImage>): Promise<string>;
|
|
8
|
+
coreCallSync(handle: string, method: string, argsJson: string): string;
|
|
9
|
+
coreReply(call: string, completionJson: string): void;
|
|
10
|
+
platformCall(method: string, argsJson: string): Promise<string>;
|
|
11
|
+
platformCallSync(method: string, argsJson: string): string;
|
|
12
|
+
addListener(eventName: string): void;
|
|
13
|
+
removeListeners(count: number): void;
|
|
14
|
+
}
|
|
15
|
+
declare const _default: Spec;
|
|
16
|
+
export default _default;
|