@h1r-ai/croche-react-native 0.6.0 → 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 +32 -4
- package/THIRD-PARTY-NOTICES +899 -6
- package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +4 -3
- package/android/src/main/AndroidManifest.xml +0 -5
- package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +33 -8
- package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +139 -5
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +5 -2
- package/android/src/main/java/dev/croche/reactnative/NativePal.kt +23 -6
- package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +28 -6
- package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +4 -11
- 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 +19 -4
- package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +2 -2
- 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/AndroidPlatform.kt +5 -3
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +4 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +11 -11
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +11 -16
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +3 -3
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +45 -10
- package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +0 -3
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +1 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +9 -23
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +11 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +83 -20
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +54 -8
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +19 -360
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +79 -10
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +8 -5
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +8 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +426 -33
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +1 -351
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +15 -29
- 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 +196 -10
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +86 -3
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +33 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +1 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +68 -4
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +3403 -6894
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +89 -18
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +1 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +2 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +3 -3
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +17 -18
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +12 -14
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +36 -6
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +21 -6
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +16 -7
- 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/pal/AtomicKeyFiles.kt +25 -4
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -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/react-native/src/core-native.d.ts +3 -0
- package/dist/react-native/src/core-native.js +148 -25
- package/dist/react-native/src/core-wire.d.ts +20 -3
- package/dist/rn-shared-build.json +8 -8
- package/dist/runtime/src/adapters.d.ts +8 -0
- package/dist/runtime/src/adapters.js +29 -0
- package/dist/runtime/src/agent.d.ts +53 -5
- package/dist/runtime/src/agent.js +69 -7
- package/dist/runtime/src/app-api.d.ts +307 -19
- package/dist/runtime/src/cancel.d.ts +2 -2
- package/dist/runtime/src/cancel.js +7 -4
- 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 +48 -35
- 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/croche.d.ts +64 -9
- package/dist/runtime/src/croche.js +78 -17
- package/dist/runtime/src/errors.d.ts +7 -0
- package/dist/runtime/src/errors.js +15 -1
- package/dist/runtime/src/generated/app-stream.d.ts +155 -1
- package/dist/runtime/src/generated/app-stream.js +7 -4
- 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 -21
- package/dist/runtime/src/index.native.js +2 -8
- package/dist/runtime/src/native-adapter.d.ts +1 -1
- package/dist/runtime/src/native-adapter.js +10 -4
- package/dist/runtime/src/pal/host.d.ts +3 -3
- package/dist/runtime/src/pal/host.js +34 -9
- package/dist/runtime/src/pal/platform.d.ts +11 -6
- 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/tools.d.ts +20 -4
- package/dist/runtime/src/tools.js +31 -7
- package/ios/CoreAgentTransport.swift +2 -2
- package/ios/CoreNativePal.swift +26 -21
- package/ios/CorePlatformTransport.swift +4 -4
- package/ios/CoreWireDispatch.swift +38 -8
- package/ios/CoreWireSupport.swift +179 -4
- package/ios/CrocheRuntimeBridge.swift +1 -1
- package/ios/ProjectPal.swift +15 -12
- package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
- package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +2 -6
- package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
- package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +1 -174
- package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +233 -4
- package/ios/vendor/CrocheRuntimeSDK/Host.swift +1 -399
- package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +3 -3
- package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
- package/ios/vendor/CrocheRuntimeSDK/JSON.swift +26 -10
- package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +0 -155
- package/ios/vendor/CrocheRuntimeSDK/Platform.swift +1 -27
- package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +8 -4
- package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +57 -21
- package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +96 -10
- package/ios/vendor/CrocheRuntimeSDK/Project.swift +3 -382
- package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +1 -412
- package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +86 -33
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +1 -1
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +12 -3
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +135 -56
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +17 -8
- package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +184 -15
- package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +31 -3
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +131 -61
- package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +10 -15
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +86 -17
- 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 +3 -249
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +40 -8
- package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +1720 -3883
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +816 -1649
- 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 +816 -1649
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +2 -2
- package/package.json +3 -3
- package/scripts/README.md +1 -1
- package/scripts/check-swift-vendor-modules.sh +15 -0
- package/scripts/vendor-native.sh +4 -3
- 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 -113
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -201
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
- 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/StoragePal.kt +0 -18
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -252
- package/dist/runtime/src/pal/codec.d.ts +0 -15
- package/dist/runtime/src/pal/codec.js +0 -52
- package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
- package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -496
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -44
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
package dev.croche.reactnative
|
|
2
|
+
|
|
3
|
+
import com.google.gson.JsonNull
|
|
4
|
+
import com.google.gson.JsonParser
|
|
5
|
+
import dev.croche.ffi.HostPal
|
|
6
|
+
import dev.croche.s7.pal.BlobFiles
|
|
7
|
+
import java.nio.file.Files
|
|
8
|
+
import java.lang.reflect.Proxy
|
|
9
|
+
import org.junit.Assert.assertArrayEquals
|
|
10
|
+
import org.junit.Assert.assertEquals
|
|
11
|
+
import org.junit.Test
|
|
12
|
+
|
|
13
|
+
class ImageAdapterWireTest {
|
|
14
|
+
@Test fun supportIsAnObjectAtTheFactoryBoundaryAndAllOtherEffectsStayNative() {
|
|
15
|
+
val support = JsonParser.parseString("""{"inputMediaTypes":["image/jpeg"],"outputMediaTypes":["image/png"]}""")
|
|
16
|
+
val options = "{}"
|
|
17
|
+
assertEquals(options, forwardedOpen(options, support = support))
|
|
18
|
+
assertEquals(options, forwardedOpen(options, support = JsonNull.INSTANCE))
|
|
19
|
+
}
|
|
20
|
+
@Test fun defaultBlobCallbacksReachTheNativeFileStore() {
|
|
21
|
+
val directory = Files.createTempDirectory("rn-default-blobs").toFile()
|
|
22
|
+
try {
|
|
23
|
+
val store = BlobFiles(directory) {}
|
|
24
|
+
val base = Proxy.newProxyInstance(HostPal::class.java.classLoader, arrayOf(HostPal::class.java)) { _, method, args ->
|
|
25
|
+
check(method.name == "blobOperation")
|
|
26
|
+
store.operation(args[0] as String, args[1] as String, args[2] as String?, args[3] as ByteArray?)
|
|
27
|
+
} as HostPal
|
|
28
|
+
val host = CallbackHost(base, "host-blob", null, CoreCallbacks { error("Unexpected JS callback") },
|
|
29
|
+
CoreHandles(), customBlobs = false)
|
|
30
|
+
val bytes = byteArrayOf(0, -1, -128)
|
|
31
|
+
host.blobOperation("put", "test/blob", null, bytes)
|
|
32
|
+
assertArrayEquals(bytes, directory.resolve("blobs/test/blob/object").readBytes())
|
|
33
|
+
} finally {
|
|
34
|
+
directory.deleteRecursively()
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
@Test fun selectedBlobCallbacksPassBytesAndOpaqueCursor() {
|
|
39
|
+
val base = Proxy.newProxyInstance(HostPal::class.java.classLoader, arrayOf(HostPal::class.java)) { _, method, _ ->
|
|
40
|
+
error("Unexpected native host operation: ${method.name}")
|
|
41
|
+
} as HostPal
|
|
42
|
+
lateinit var callbacks: CoreCallbacks
|
|
43
|
+
callbacks = CoreCallbacks { raw ->
|
|
44
|
+
val packet = JsonParser.parseString(raw).asJsonObject
|
|
45
|
+
assertEquals("blob", packet["type"].asString)
|
|
46
|
+
assertEquals("host-blob", packet["host"].asString)
|
|
47
|
+
val response = when (packet["operation"].asString) {
|
|
48
|
+
"put" -> {
|
|
49
|
+
assertEquals(listOf(0, 255, 128), packet.getAsJsonArray("bytes").map { it.asInt })
|
|
50
|
+
"""{"value":{}}"""
|
|
51
|
+
}
|
|
52
|
+
"get" -> """{"value":{"bytes":[0,255,128]}}"""
|
|
53
|
+
"list" -> {
|
|
54
|
+
assertEquals("opaque", packet["cursor"].asString)
|
|
55
|
+
"""{"value":{"entries":[{"key":"p/a","size":3}],"nextCursor":"continue"}}"""
|
|
56
|
+
}
|
|
57
|
+
else -> error("Unexpected blob callback")
|
|
58
|
+
}
|
|
59
|
+
callbacks.reply(packet["call"].asString, response)
|
|
60
|
+
}
|
|
61
|
+
val host = CallbackHost(base, "host-blob", null, callbacks, CoreHandles(), customBlobs = true)
|
|
62
|
+
val bytes = byteArrayOf(0, -1, -128)
|
|
63
|
+
host.blobOperation("put", "p/a", null, bytes)
|
|
64
|
+
assertArrayEquals(bytes, host.blobOperation("get", "p/a", null, null).bytes)
|
|
65
|
+
val page = host.blobOperation("list", "p/", "opaque", null)
|
|
66
|
+
assertEquals("p/a", page.entries.single().key)
|
|
67
|
+
assertEquals(3uL, page.entries.single().size)
|
|
68
|
+
assertEquals("continue", page.nextCursor)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
@@ -1,17 +1,24 @@
|
|
|
1
1
|
package dev.croche.reactnative
|
|
2
2
|
|
|
3
3
|
import com.google.gson.JsonArray
|
|
4
|
+
import com.google.gson.JsonElement
|
|
5
|
+
import com.google.gson.JsonParser
|
|
4
6
|
import dev.croche.ffi.HostPal
|
|
7
|
+
import dev.croche.ffi.HostStreamPlatform
|
|
5
8
|
import java.lang.reflect.Proxy
|
|
6
9
|
import kotlinx.coroutines.runBlocking
|
|
7
10
|
import org.junit.Assert.*
|
|
8
11
|
|
|
9
12
|
/** Capture the actual RN open boundary before the native factory; no native library or network. */
|
|
10
|
-
internal fun forwardedOpen(options: String, recovery: String? = null): String {
|
|
13
|
+
internal fun forwardedOpen(options: String, recovery: String? = null, support: JsonElement? = null): String {
|
|
11
14
|
class Captured : RuntimeException()
|
|
12
15
|
var observed: String? = null
|
|
16
|
+
var factReads = 0
|
|
13
17
|
val host = Proxy.newProxyInstance(HostPal::class.java.classLoader, arrayOf(HostPal::class.java)) { _, method, _ ->
|
|
14
|
-
|
|
18
|
+
when (method.name) {
|
|
19
|
+
"streamPlatform" -> { factReads++; HostStreamPlatform.REACT_NATIVE }
|
|
20
|
+
else -> error("Open forwarding must not run a host effect: ${method.name}")
|
|
21
|
+
}
|
|
15
22
|
} as HostPal
|
|
16
23
|
val bridge = CoreDispatch({ host }, { error("Open must use its storage argument") },
|
|
17
24
|
openFactory = { json, registrations, storage, actualHost, actualRecovery ->
|
|
@@ -19,10 +26,18 @@ internal fun forwardedOpen(options: String, recovery: String? = null): String {
|
|
|
19
26
|
assertEquals(recovery, actualRecovery)
|
|
20
27
|
assertTrue(registrations.isEmpty())
|
|
21
28
|
assertTrue(storage is CallbackStorage)
|
|
22
|
-
|
|
29
|
+
assertEquals(0, factReads)
|
|
30
|
+
assertTrue(actualHost is CallbackHost)
|
|
31
|
+
assertEquals(HostStreamPlatform.REACT_NATIVE, actualHost.streamPlatform())
|
|
32
|
+
assertEquals(1, factReads)
|
|
33
|
+
assertEquals(support?.takeUnless { it.isJsonNull },
|
|
34
|
+
actualHost.imageSupport()?.let(JsonParser::parseString))
|
|
23
35
|
throw Captured()
|
|
24
36
|
}, emit = { error("Open forwarding must not emit an event") })
|
|
25
|
-
val arguments = JsonArray().apply {
|
|
37
|
+
val arguments = JsonArray().apply {
|
|
38
|
+
add(options); add(JsonArray()); add("storage"); add("host"); add(recovery)
|
|
39
|
+
if (support != null) add(support)
|
|
40
|
+
}
|
|
26
41
|
try { runBlocking { bridge.open(arguments) }; fail("Capture must interrupt the native factory") }
|
|
27
42
|
catch (_: Captured) { }
|
|
28
43
|
return requireNotNull(observed) { "The real RN open path did not call the factory" }
|
|
@@ -15,11 +15,11 @@ class ProjectAttestationTest {
|
|
|
15
15
|
return rnHostPal(base)
|
|
16
16
|
}
|
|
17
17
|
@Test fun availableAttestorFactReachesCoreUnchanged() {
|
|
18
|
-
val facts = PalPlatformFacts(PalTargetKind.ANDROID, false, "ko-KR", "android-play-integrity"
|
|
18
|
+
val facts = PalPlatformFacts(PalTargetKind.ANDROID, false, "ko-KR", "android-play-integrity")
|
|
19
19
|
assertSame("platform facts unchanged", facts, host(facts).platformFacts())
|
|
20
20
|
}
|
|
21
21
|
@Test fun absentAttestorFactStaysAbsentWithoutSdkDefaults() {
|
|
22
|
-
val facts = PalPlatformFacts(PalTargetKind.OTHER, null, null, null
|
|
22
|
+
val facts = PalPlatformFacts(PalTargetKind.OTHER, null, null, null)
|
|
23
23
|
assertSame("platform facts unchanged", facts, host(facts).platformFacts())
|
|
24
24
|
}
|
|
25
25
|
@Test fun factsAreNotInjectedIntoTheOptions() {
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
package dev.croche.reactnative
|
|
2
|
+
|
|
3
|
+
import com.google.gson.JsonParser
|
|
4
|
+
import dev.croche.ffi.*
|
|
5
|
+
import org.junit.Assert.*
|
|
6
|
+
import org.junit.Test
|
|
7
|
+
|
|
8
|
+
class StorageVersionWireTest {
|
|
9
|
+
@Test fun requiredNullFieldsSurviveRealWireSerialization() {
|
|
10
|
+
val value = JsonParser.parseString(json(mapOf("value" to mapOf("value" to null, "version" to null)))).asJsonObject.getAsJsonObject("value")
|
|
11
|
+
assertTrue(value.has("value")); assertTrue(value.get("value").isJsonNull)
|
|
12
|
+
assertTrue(value.has("version")); assertTrue(value.get("version").isJsonNull)
|
|
13
|
+
}
|
|
14
|
+
@Test fun callbackDecodingPairsWithTheCapturedRequestAndRejectsMissingFields() {
|
|
15
|
+
var reply = "{\"type\":\"written\",\"version\":null}"
|
|
16
|
+
lateinit var callbacks: CoreCallbacks
|
|
17
|
+
callbacks = CoreCallbacks { packet ->
|
|
18
|
+
val call = JsonParser.parseString(packet).asJsonObject.get("call").asString
|
|
19
|
+
callbacks.reply(call, "{\"value\":$reply}")
|
|
20
|
+
}
|
|
21
|
+
val storage = CallbackStorage("storage", "host", callbacks)
|
|
22
|
+
fun refused(body: () -> Unit) {
|
|
23
|
+
try { body(); fail("P1_WIRE_MISMATCH: invalid reply accepted") }
|
|
24
|
+
catch (_: CoreStorageFailure.Failure) { }
|
|
25
|
+
}
|
|
26
|
+
try {
|
|
27
|
+
assertEquals(CoreWriteOutcome.Written(null), storage.writeIf("key", null, null))
|
|
28
|
+
refused { storage.writeIf("key", "write", null) }
|
|
29
|
+
reply = "{\"type\":\"written\",\"version\":\"token\"}"
|
|
30
|
+
assertEquals(CoreWriteOutcome.Written("token"), storage.writeIf("key", "write", null))
|
|
31
|
+
refused { storage.writeIf("key", null, "token") }
|
|
32
|
+
for (malformed in listOf("{}", "null", "{\"value\":\"raw\"}", "{\"value\":null,\"version\":\"token\"}")) {
|
|
33
|
+
reply = malformed; refused { storage.readVersioned("key") }
|
|
34
|
+
}
|
|
35
|
+
} finally { callbacks.invalidate() }
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
package dev.croche.reactnative
|
|
2
|
+
|
|
3
|
+
import dev.croche.ffi.*
|
|
4
|
+
import org.junit.Assert.*
|
|
5
|
+
import org.junit.Test
|
|
6
|
+
|
|
7
|
+
class VerificationDispatchTest {
|
|
8
|
+
/** RN croche.verification() is one read on the root Core handle; its JSON and errors pass through. */
|
|
9
|
+
@Test fun verificationForwardsToTheRootAndErrorsPassThrough() {
|
|
10
|
+
var closed = false
|
|
11
|
+
val root = object : CoreCroche(NoHandle) {
|
|
12
|
+
override fun verification(): String {
|
|
13
|
+
if (closed) throw CoreApiException.Failure("closed", "Croche is closed", "closed", null, null)
|
|
14
|
+
return """{"status":"unverified","lastAttestation":"attestation_timeout"}"""
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
val bridge = CoreDispatch({ error("No new host") }, { error("No platform storage") }) { error("No event") }
|
|
18
|
+
val id = bridge.handles.hold(root)
|
|
19
|
+
assertEquals("""{"status":"unverified","lastAttestation":"attestation_timeout"}""", bridge.call(id, "verification", com.google.gson.JsonArray()))
|
|
20
|
+
closed = true
|
|
21
|
+
try { bridge.call(id, "verification", com.google.gson.JsonArray()); fail("closed root must refuse") }
|
|
22
|
+
catch (error: CoreApiException.Failure) { assertEquals("closed", error.code) }
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -24,7 +24,7 @@ import javax.crypto.KeyGenerator
|
|
|
24
24
|
import javax.crypto.SecretKey
|
|
25
25
|
import javax.crypto.spec.GCMParameterSpec
|
|
26
26
|
|
|
27
|
-
// Android implementations of the Platform Abstraction Layer. See docs/
|
|
27
|
+
// Android implementations of the Platform Abstraction Layer. See docs/hld/surface-and-hosts.md.
|
|
28
28
|
// Not compiled on the Linux host (no Android SDK): build and run on the Mac before relying on it.
|
|
29
29
|
|
|
30
30
|
/**
|
|
@@ -34,7 +34,7 @@ import javax.crypto.spec.GCMParameterSpec
|
|
|
34
34
|
* instance (the local conversation stays). Unlike the iOS Keychain, it does not survive
|
|
35
35
|
* uninstall. That asymmetry is by platform design; see the design document.
|
|
36
36
|
*/
|
|
37
|
-
class KeystoreSecretStore(context: Context, name: String) : RuntimeSecretStore {
|
|
37
|
+
internal class KeystoreSecretStore(context: Context, name: String) : RuntimeSecretStore {
|
|
38
38
|
private val file = File(context.noBackupFilesDir, "croche/${name.replace(Regex("[^A-Za-z0-9._-]"), "_")}.secrets")
|
|
39
39
|
|
|
40
40
|
private fun key(): SecretKey {
|
|
@@ -102,8 +102,10 @@ class KeystoreSecretStore(context: Context, name: String) : RuntimeSecretStore {
|
|
|
102
102
|
*/
|
|
103
103
|
class PlayIntegrityAttestor(context: Context, private val cloudProjectNumber: Long) : RuntimeAttestor {
|
|
104
104
|
private val manager = IntegrityManagerFactory.create(context.applicationContext)
|
|
105
|
+
/** Platform identifier sent to Core for this attestor. */
|
|
105
106
|
override val platform = "android-play-integrity"
|
|
106
107
|
|
|
108
|
+
/** Request a Play Integrity proof using the supplied client-data hash as the nonce. */
|
|
107
109
|
override fun attest(clientData: String, clientDataHash: String, cancellation: RuntimeCancellation): RuntimeAttestation {
|
|
108
110
|
cancellation.check()
|
|
109
111
|
// The nonce must be URL-safe, no-wrap Base64 of 16-500 characters; the 43-character
|
|
@@ -125,7 +127,7 @@ class PlayIntegrityAttestor(context: Context, private val cloudProjectNumber: Lo
|
|
|
125
127
|
}
|
|
126
128
|
|
|
127
129
|
/** The wiki documents shipped in the app's assets under `folder` (`src/main/assets/wiki/`),
|
|
128
|
-
* paths relative to it: `
|
|
130
|
+
* paths relative to it: `wikiFromAssets(context.assets)`. */
|
|
129
131
|
fun wikiFromAssets(assets: android.content.res.AssetManager, folder: String = "wiki"): List<dev.croche.WikiDocument> =
|
|
130
132
|
dev.croche.WikiDocument.fromTree(
|
|
131
133
|
list = { path -> assets.list(if (path.isEmpty()) folder else "$folder/$path") },
|
|
@@ -9,6 +9,7 @@ import androidx.work.WorkerParameters
|
|
|
9
9
|
import dev.croche.ffi.CancelToken
|
|
10
10
|
import dev.croche.ffi.CoreBackgroundWake
|
|
11
11
|
import dev.croche.s7.BackgroundOsRegistration
|
|
12
|
+
import dev.croche.s7.ensureNativeCoreInitialized
|
|
12
13
|
import java.util.concurrent.TimeUnit
|
|
13
14
|
|
|
14
15
|
/** Process callback only. The Core wake object owns a weak service reference. */
|
|
@@ -35,9 +36,11 @@ internal object AndroidBackgroundWake {
|
|
|
35
36
|
|
|
36
37
|
/** No SDK retries, tools or turns. WorkManager stop cancels only this Core wake run. */
|
|
37
38
|
class BackgroundWakeWorker(context: Context, params: WorkerParameters) : Worker(context, params) {
|
|
39
|
+
init { ensureNativeCoreInitialized() }
|
|
38
40
|
private val cancel = CancelToken()
|
|
39
41
|
private val stopLock = Any()
|
|
40
42
|
private var finished = false
|
|
43
|
+
/** Run the registered Core wake callback and report the worker outcome to WorkManager. */
|
|
41
44
|
override fun doWork(): Result {
|
|
42
45
|
if (isStopped) cancel.cancel()
|
|
43
46
|
try {
|
|
@@ -47,5 +50,6 @@ class BackgroundWakeWorker(context: Context, params: WorkerParameters) : Worker(
|
|
|
47
50
|
} catch (_: Exception) { return Result.failure() }
|
|
48
51
|
finally { synchronized(stopLock) { finished = true; cancel.close() } }
|
|
49
52
|
}
|
|
53
|
+
/** Request cancellation of the wake run if the worker has not finished. */
|
|
50
54
|
override fun onStopped() { synchronized(stopLock) { if (!finished) cancel.cancel() } }
|
|
51
55
|
}
|
package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt
CHANGED
|
@@ -7,10 +7,10 @@ import dev.croche.CrocheError
|
|
|
7
7
|
import dev.croche.DecodedImageCodec
|
|
8
8
|
import dev.croche.NativeImagePal
|
|
9
9
|
import dev.croche.ffi.CancelToken
|
|
10
|
-
import dev.croche.
|
|
11
|
-
import dev.croche.
|
|
12
|
-
import dev.croche.
|
|
13
|
-
import dev.croche.
|
|
10
|
+
import dev.croche.DecodedImage
|
|
11
|
+
import dev.croche.ImageDecodeOptions
|
|
12
|
+
import dev.croche.ImageFormat
|
|
13
|
+
import dev.croche.ImageRenderRequest
|
|
14
14
|
import java.io.ByteArrayOutputStream
|
|
15
15
|
import java.util.UUID
|
|
16
16
|
import kotlin.math.roundToInt
|
|
@@ -30,7 +30,7 @@ internal class BitmapDecodedImageCodec(
|
|
|
30
30
|
private val entries = mutableMapOf<String, Entry>()
|
|
31
31
|
private var closed = false
|
|
32
32
|
|
|
33
|
-
override fun decode(bytes: ByteArray, options:
|
|
33
|
+
override fun decode(bytes: ByteArray, options: ImageDecodeOptions, cancel: CancelToken): DecodedImage {
|
|
34
34
|
NativeImagePal.check(cancel)
|
|
35
35
|
if (options.frame != 0u) invalid("Only frame zero can be decoded")
|
|
36
36
|
var owned: Bitmap? = null
|
|
@@ -53,14 +53,14 @@ internal class BitmapDecodedImageCodec(
|
|
|
53
53
|
val handle = UUID.randomUUID().toString()
|
|
54
54
|
entries[handle] = Entry(bitmap)
|
|
55
55
|
owned = null // The private table owns the pixels from this point.
|
|
56
|
-
|
|
56
|
+
DecodedImage(handle, bitmap.width.toUInt(), bitmap.height.toUInt(), alpha)
|
|
57
57
|
}
|
|
58
58
|
} finally {
|
|
59
59
|
owned?.recycle()
|
|
60
60
|
}
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
-
override fun render(request:
|
|
63
|
+
override fun render(request: ImageRenderRequest, cancel: CancelToken): ByteArray {
|
|
64
64
|
NativeImagePal.check(cancel)
|
|
65
65
|
val entry = synchronized(lock) {
|
|
66
66
|
val entry = entries[request.handle] ?: unsupported("The decoded image handle is unavailable")
|
|
@@ -72,15 +72,15 @@ internal class BitmapDecodedImageCodec(
|
|
|
72
72
|
val width = dimension(request.width)
|
|
73
73
|
val height = dimension(request.height)
|
|
74
74
|
val format = when (request.format) {
|
|
75
|
-
|
|
76
|
-
|
|
75
|
+
ImageFormat.PNG -> Bitmap.CompressFormat.PNG
|
|
76
|
+
ImageFormat.JPEG -> Bitmap.CompressFormat.JPEG
|
|
77
77
|
}
|
|
78
78
|
val quality = when (request.format) {
|
|
79
|
-
|
|
79
|
+
ImageFormat.PNG -> {
|
|
80
80
|
if (request.quality != null) unsupported("PNG does not take a quality argument")
|
|
81
81
|
100 // Android ignores this parameter for PNG.
|
|
82
82
|
}
|
|
83
|
-
|
|
83
|
+
ImageFormat.JPEG -> {
|
|
84
84
|
val value = request.quality ?: unsupported("JPEG requires a quality argument")
|
|
85
85
|
if (!value.isFinite() || value < 0 || value > 1) unsupported("JPEG quality is outside its range")
|
|
86
86
|
(value * 100).roundToInt()
|
|
@@ -17,6 +17,7 @@ import kotlin.math.roundToInt
|
|
|
17
17
|
* (`CrocheImages.codec`): an Android app needs no setup.
|
|
18
18
|
*/
|
|
19
19
|
class BitmapImageCodec : ImageCodec {
|
|
20
|
+
/** Decode and orient the first frame, fitting its longest side to the requested size, and encode the resulting image. */
|
|
20
21
|
override fun render(bytes: ByteArray, maxSide: Int): ImageCodec.Rendered? {
|
|
21
22
|
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
|
22
23
|
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
|
|
@@ -12,8 +12,10 @@ import dev.croche.android.BitmapDecodedImageCodec
|
|
|
12
12
|
import dev.croche.ffi.*
|
|
13
13
|
import dev.croche.s7.attached
|
|
14
14
|
import dev.croche.s7.effectCallback
|
|
15
|
+
import dev.croche.s7.pal.BlobFiles
|
|
15
16
|
import dev.croche.s7.pal.DirectHttpPal
|
|
16
17
|
import java.io.ByteArrayOutputStream
|
|
18
|
+
import java.io.File
|
|
17
19
|
import java.util.TimeZone
|
|
18
20
|
import java.util.UUID
|
|
19
21
|
|
|
@@ -27,17 +29,16 @@ internal class AndroidCoreHost(
|
|
|
27
29
|
private val http = DirectHttpPal()
|
|
28
30
|
private val codec = BitmapDecodedImageCodec()
|
|
29
31
|
private val captures = NativeImagePal()
|
|
32
|
+
private val blobs = BlobFiles(File(this.context.noBackupFilesDir, "croche-pal-v1"), syncDirectory = ::syncDirectory)
|
|
33
|
+
override fun blobOperation(operation: String, key: String, cursor: String?, bytes: ByteArray?) =
|
|
34
|
+
blobs.operation(operation, key, cursor, bytes)
|
|
30
35
|
override fun streamPlatform() = HostStreamPlatform.OTHER
|
|
31
36
|
override fun platformFacts() = PalPlatformFacts(PalTargetKind.ANDROID, androidPlatformFacts(context).debuggable,
|
|
32
|
-
context.resources.configuration.locales[0]?.toLanguageTag(), "android-play-integrity"
|
|
33
|
-
|
|
34
|
-
override fun
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
effectCallback { codec.render(request, cancel) }
|
|
38
|
-
override fun releaseDecodedImage(handle: String) = codec.release(handle)
|
|
39
|
-
override fun prepareImage(source: PalImageBytes, plan: PalImagePreparePlan, cancel: CancelToken) =
|
|
40
|
-
effectCallback { captures.prepare(source, plan, cancel) }
|
|
37
|
+
context.resources.configuration.locales[0]?.toLanguageTag(), "android-play-integrity")
|
|
38
|
+
private val encodedImages = dev.croche.EncodedImageCodec(codec)
|
|
39
|
+
override fun imageSupport() = com.google.gson.Gson().toJson(encodedImages.support)
|
|
40
|
+
override fun imageOperation(operation: String, bytes: ByteArray, optionsJson: String, cancel: CancelToken) =
|
|
41
|
+
effectCallback { encodedImages.operation(operation, bytes, optionsJson, cancel) }
|
|
41
42
|
override fun releaseImage(capture: String) = captures.release(capture)
|
|
42
43
|
|
|
43
44
|
override fun readImage(request: PalImageReadRequest, cancel: CancelToken): ByteArray = effectCallback {
|
|
@@ -82,6 +83,7 @@ internal class AndroidCoreHost(
|
|
|
82
83
|
override fun read(key: String) = storage.read(key)
|
|
83
84
|
override fun write(key: String, value: String) = storage.write(key, value)
|
|
84
85
|
override fun remove(key: String) = storage.remove(key)
|
|
86
|
+
override fun purgeInstance(prefix: String) = storage.purgeInstance(prefix, null)
|
|
85
87
|
override fun list(prefix: String) = storage.list(prefix)
|
|
86
88
|
override fun readSecret(key: String) = storage.readSecret(key)
|
|
87
89
|
override fun writeSecret(key: String, value: String) = storage.writeSecret(key, value)
|
|
@@ -89,7 +91,6 @@ internal class AndroidCoreHost(
|
|
|
89
91
|
override fun lock(key: String) = storage.lock(key)
|
|
90
92
|
override fun unlock(key: String) = storage.unlock(key)
|
|
91
93
|
override fun storeIdentity() = context.noBackupFilesDir.canonicalPath
|
|
92
|
-
override fun storageCapability() = StorageCapability.KEYED
|
|
93
94
|
override fun nowMs() = System.currentTimeMillis().toDouble()
|
|
94
95
|
override fun utcOffsetMinutes(atMs: Double) = TimeZone.getDefault().getOffset(atMs.toLong()).toLong() / 60_000
|
|
95
96
|
override fun random() = UUID.randomUUID().toString()
|
|
@@ -107,12 +108,6 @@ internal class AndroidCoreHost(
|
|
|
107
108
|
throw CorePalException.Failure("capability_unsupported", "S1 uses registered Core tool definitions")
|
|
108
109
|
override fun attest(request: String, timeoutMs: ULong): String =
|
|
109
110
|
throw CorePalException.Failure("attestation_unsupported", "No attestation provider is attached")
|
|
110
|
-
override fun archiveAppendLine(entry: String, line: String): Unit = legacyArchive()
|
|
111
|
-
override fun archiveReadLines(entry: String): List<String> = legacyArchive()
|
|
112
|
-
override fun archiveReplaceLines(entry: String, lines: List<String>): Unit = legacyArchive()
|
|
113
|
-
override fun archiveRemove(entry: String): Unit = legacyArchive()
|
|
114
|
-
override fun archiveEntries(prefix: String): List<ArchiveEntry> = legacyArchive()
|
|
115
|
-
private fun legacyArchive(): Nothing = throw CoreStorageFailure.Failure("Snapshot archive callbacks were removed; Core owns keyed records")
|
|
116
111
|
|
|
117
112
|
private fun signal(cancel: CancelToken) = RuntimeCancellation().also { signal ->
|
|
118
113
|
if (cancel.isCancelled()) signal.cancel()
|
package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
package dev.croche.android.pal
|
|
2
2
|
|
|
3
3
|
import android.content.Context
|
|
4
|
-
import dev.croche.
|
|
4
|
+
import dev.croche.SelectedAdapters
|
|
5
5
|
import dev.croche.s7.NativePlatformPals
|
|
6
6
|
import dev.croche.s7.NativePlatformProvider
|
|
7
7
|
import dev.croche.s7.backgroundStorage
|
|
8
8
|
|
|
9
9
|
/** Loaded by the common facade; the app's Context remains an opaque platform handle. */
|
|
10
10
|
internal class AndroidPublicPlatform : NativePlatformProvider {
|
|
11
|
-
override fun create(platform: Any?,
|
|
11
|
+
override fun create(platform: Any?, adapters: SelectedAdapters): NativePlatformPals {
|
|
12
12
|
val context = (platform as Context).applicationContext
|
|
13
|
-
val (pal, platformStorage) = backgroundStorage(
|
|
13
|
+
val (pal, platformStorage) = backgroundStorage(adapters, AndroidStoragePal(context))
|
|
14
14
|
val host = AndroidCoreHost(context, pal)
|
|
15
15
|
return NativePlatformPals(pal, host, AndroidMainDispatcher, platformStorage)
|
|
16
16
|
}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
package dev.croche.android.pal
|
|
2
|
+
|
|
3
|
+
import android.database.AbstractWindowedCursor
|
|
4
|
+
import android.database.Cursor
|
|
5
|
+
import android.database.sqlite.SQLiteBlobTooBigException
|
|
6
|
+
import android.database.sqlite.SQLiteDatabase
|
|
7
|
+
import android.os.ParcelFileDescriptor
|
|
8
|
+
import dev.croche.StateCommitResult
|
|
9
|
+
import dev.croche.StateCondition
|
|
10
|
+
import dev.croche.StateEntry
|
|
11
|
+
import dev.croche.StateListOptions
|
|
12
|
+
import dev.croche.StateOp
|
|
13
|
+
import dev.croche.StatePage
|
|
14
|
+
import dev.croche.VersionedValue
|
|
15
|
+
import dev.croche.WriteOutcome
|
|
16
|
+
import dev.croche.s7.StateRange
|
|
17
|
+
import dev.croche.s7.stateKey
|
|
18
|
+
import dev.croche.s7.storageVersion
|
|
19
|
+
import dev.croche.s7.validateStateBatch
|
|
20
|
+
import java.io.File
|
|
21
|
+
import java.io.IOException
|
|
22
|
+
import java.nio.file.Files
|
|
23
|
+
import java.nio.file.LinkOption.NOFOLLOW_LINKS
|
|
24
|
+
import java.util.UUID
|
|
25
|
+
|
|
26
|
+
/** The rows of one CursorWindow, and how many rows the statement produced (at most its LIMIT). */
|
|
27
|
+
internal class WindowRows(val entries: List<StateEntry>, val total: Int)
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The most entries one Android page returns (HLD storage, "Range reads"). With the look-ahead row
|
|
31
|
+
* that is 33 rows, and 33 rows of Core's largest size (key plus value 60 KiB) fit one default
|
|
32
|
+
* 2 MiB CursorWindow. The statement's LIMIT has to be this small from the outset: Android's first
|
|
33
|
+
* window fill steps and counts every row the statement produces, whether or not it fits.
|
|
34
|
+
*/
|
|
35
|
+
internal const val WINDOW_PAGE_ROWS = 32
|
|
36
|
+
|
|
37
|
+
/** The range with its page held to [WINDOW_PAGE_ROWS]. A cursor does not encode the limit. */
|
|
38
|
+
internal fun windowRange(prefix: String, options: StateListOptions) =
|
|
39
|
+
StateRange(prefix, options.copy(limit = minOf(options.limit ?: WINDOW_PAGE_ROWS.toUInt(), WINDOW_PAGE_ROWS.toUInt())))
|
|
40
|
+
|
|
41
|
+
/** Runs the page statement of [range]: the page plus one look-ahead row, through one window. */
|
|
42
|
+
internal fun readPage(db: SQLiteDatabase, range: StateRange): WindowRows =
|
|
43
|
+
db.rawQuery("SELECT key, value ${range.bounds}", arrayOf(range.from, range.to, (range.limit + 1).toString())).use(::firstWindow)
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Reads a `(key, value)` query through ONE CursorWindow fill.
|
|
47
|
+
*
|
|
48
|
+
* `count` fills the first window and steps every row of the statement to count it, so the caller's
|
|
49
|
+
* LIMIT is the bound on rows visited. A refill would run the query again from its first row, so
|
|
50
|
+
* rows that did not fit the window are not read here: the caller returns a short page with a
|
|
51
|
+
* cursor, and the next call seeks to it. That only happens for rows above Core's row size.
|
|
52
|
+
* A first row too large for an empty window is reported as [SQLiteBlobTooBigException].
|
|
53
|
+
*/
|
|
54
|
+
internal fun firstWindow(cursor: Cursor): WindowRows {
|
|
55
|
+
val total = cursor.count
|
|
56
|
+
val window = (cursor as? AbstractWindowedCursor)?.window
|
|
57
|
+
// No window to inspect (not a platform SQLite cursor): read the rows as they come.
|
|
58
|
+
val held = if (window == null) total else {
|
|
59
|
+
check(window.startPosition == 0) { "StateStore page did not start at its first row" }
|
|
60
|
+
minOf(window.numRows, total)
|
|
61
|
+
}
|
|
62
|
+
if (total > 0 && held == 0) throw SQLiteBlobTooBigException("StateStore row does not fit one CursorWindow")
|
|
63
|
+
val entries = buildList(held) {
|
|
64
|
+
for (position in 0 until held) {
|
|
65
|
+
check(cursor.moveToPosition(position)) { "StateStore page row is missing" }
|
|
66
|
+
add(StateEntry(cursor.getString(0), cursor.getBlob(1).decodeToString(throwOnInvalidSequence = true)))
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return WindowRows(entries, total)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** One database per platform storage root. Each batch stays on the calling effect thread. */
|
|
73
|
+
internal class AndroidStateStore(private val path: File) : AutoCloseable {
|
|
74
|
+
private var connection: SQLiteDatabase? = null
|
|
75
|
+
|
|
76
|
+
@Synchronized private fun database(create: Boolean): SQLiteDatabase? {
|
|
77
|
+
connection?.let { return it }
|
|
78
|
+
val parent = requireNotNull(path.parentFile)
|
|
79
|
+
if (create) Files.createDirectories(parent.toPath())
|
|
80
|
+
if (!Files.exists(path.toPath(), NOFOLLOW_LINKS) && !create) return null
|
|
81
|
+
if (!Files.isDirectory(parent.toPath(), NOFOLLOW_LINKS) ||
|
|
82
|
+
(Files.exists(path.toPath(), NOFOLLOW_LINKS) && !Files.isRegularFile(path.toPath(), NOFOLLOW_LINKS))) {
|
|
83
|
+
throw IOException("Invalid StateStore path")
|
|
84
|
+
}
|
|
85
|
+
val flags = SQLiteDatabase.OPEN_READWRITE or SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING or
|
|
86
|
+
(if (create) SQLiteDatabase.CREATE_IF_NECESSARY else 0)
|
|
87
|
+
val db = SQLiteDatabase.openDatabase(path.path, null, flags)
|
|
88
|
+
try {
|
|
89
|
+
db.rawQuery("PRAGMA busy_timeout = 5000", null).use { check(it.moveToFirst()) }
|
|
90
|
+
db.execSQL("PRAGMA synchronous = NORMAL")
|
|
91
|
+
db.execSQL("CREATE TABLE IF NOT EXISTS state (key TEXT PRIMARY KEY NOT NULL, value BLOB NOT NULL, version TEXT NOT NULL)")
|
|
92
|
+
connection = db
|
|
93
|
+
return db
|
|
94
|
+
} catch (error: Throwable) {
|
|
95
|
+
db.close()
|
|
96
|
+
throw error
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
@Synchronized override fun close() {
|
|
101
|
+
connection?.close()
|
|
102
|
+
connection = null
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
private fun version(db: SQLiteDatabase, key: String): String? =
|
|
106
|
+
db.rawQuery("SELECT version FROM state WHERE key = ?", arrayOf(key)).use { row ->
|
|
107
|
+
if (row.moveToFirst()) row.getString(0) else null
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// CursorWindow has a platform-dependent row size. A large value must not become
|
|
111
|
+
// unreadable after a successful commit. SQLite can return that value through a descriptor.
|
|
112
|
+
private fun largeValue(db: SQLiteDatabase, key: String): String =
|
|
113
|
+
db.compileStatement("SELECT value FROM state WHERE key = ?").use { statement ->
|
|
114
|
+
statement.bindString(1, key)
|
|
115
|
+
val descriptor = statement.simpleQueryForBlobFileDescriptor()
|
|
116
|
+
?: throw IOException("Could not read StateStore value")
|
|
117
|
+
ParcelFileDescriptor.AutoCloseInputStream(descriptor).use {
|
|
118
|
+
it.readBytes().decodeToString(throwOnInvalidSequence = true)
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
fun get(key: String): VersionedValue {
|
|
123
|
+
stateKey(key)
|
|
124
|
+
val db = database(false) ?: return VersionedValue(null, null)
|
|
125
|
+
return try {
|
|
126
|
+
db.rawQuery("SELECT value, version FROM state WHERE key = ?", arrayOf(key)).use { row ->
|
|
127
|
+
if (row.moveToFirst()) VersionedValue(row.getBlob(0).decodeToString(throwOnInvalidSequence = true), row.getString(1))
|
|
128
|
+
else VersionedValue(null, null)
|
|
129
|
+
}
|
|
130
|
+
} catch (_: SQLiteBlobTooBigException) {
|
|
131
|
+
transaction(db) {
|
|
132
|
+
val version = version(db, key)
|
|
133
|
+
VersionedValue(version?.let { largeValue(db, key) }, version)
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
fun list(prefix: String, options: StateListOptions): StatePage {
|
|
139
|
+
val range = windowRange(prefix, options)
|
|
140
|
+
val db = database(false) ?: return StatePage(emptyList())
|
|
141
|
+
val bounds = range.bounds
|
|
142
|
+
return try {
|
|
143
|
+
val rows = readPage(db, range)
|
|
144
|
+
range.page(rows.entries, more = rows.entries.size < rows.total)
|
|
145
|
+
} catch (_: SQLiteBlobTooBigException) {
|
|
146
|
+
// The first row is larger than a whole window (far above Core's 60 KiB row size). It is
|
|
147
|
+
// returned alone, read as a stream; the two-key query only tells whether more rows follow.
|
|
148
|
+
transaction(db) {
|
|
149
|
+
val keys = db.rawQuery("SELECT key $bounds", arrayOf(range.from, range.to, "2")).use { cursor ->
|
|
150
|
+
buildList { while (cursor.moveToNext()) add(cursor.getString(0)) }
|
|
151
|
+
}
|
|
152
|
+
range.page(keys.take(1).map { StateEntry(it, largeValue(db, it)) }, more = keys.size > 1)
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
private fun apply(db: SQLiteDatabase, op: StateOp): String? = when (op) {
|
|
158
|
+
is StateOp.Put -> UUID.randomUUID().toString().also { version ->
|
|
159
|
+
db.execSQL("INSERT OR REPLACE INTO state(key, value, version) VALUES (?, ?, ?)", arrayOf(op.key, op.value.encodeToByteArray(), version))
|
|
160
|
+
}
|
|
161
|
+
is StateOp.Delete -> {
|
|
162
|
+
db.execSQL("DELETE FROM state WHERE key = ?", arrayOf(op.key))
|
|
163
|
+
null
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
private inline fun <T> transaction(db: SQLiteDatabase, block: () -> T): T {
|
|
168
|
+
db.beginTransactionNonExclusive()
|
|
169
|
+
try {
|
|
170
|
+
val result = block()
|
|
171
|
+
db.setTransactionSuccessful()
|
|
172
|
+
return result
|
|
173
|
+
} finally { db.endTransaction() }
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
fun commit(ops: List<StateOp>, condition: StateCondition): StateCommitResult {
|
|
177
|
+
validateStateBatch(ops, condition)
|
|
178
|
+
val db = requireNotNull(database(true))
|
|
179
|
+
return transaction(db) {
|
|
180
|
+
var version = version(db, condition.key)
|
|
181
|
+
if (version != condition.version) return@transaction StateCommitResult.Conflict
|
|
182
|
+
for (op in ops) {
|
|
183
|
+
val written = apply(db, op)
|
|
184
|
+
if (op.key == condition.key) version = written
|
|
185
|
+
}
|
|
186
|
+
StateCommitResult.Committed(version)
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
fun write(key: String, value: String) {
|
|
191
|
+
val validKey = stateKey(key)
|
|
192
|
+
apply(requireNotNull(database(true)), StateOp.Put(validKey, value))
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
fun remove(key: String) {
|
|
196
|
+
stateKey(key)
|
|
197
|
+
database(false)?.let { apply(it, StateOp.Delete(key)) }
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
fun writeIf(key: String, value: String?, expect: String?): WriteOutcome {
|
|
201
|
+
stateKey(key)
|
|
202
|
+
storageVersion(expect)
|
|
203
|
+
val db = requireNotNull(database(true))
|
|
204
|
+
return transaction(db) {
|
|
205
|
+
val current = version(db, key)
|
|
206
|
+
if (current != expect) return@transaction WriteOutcome.Conflict(current)
|
|
207
|
+
WriteOutcome.Written(apply(db, if (value != null) StateOp.Put(key, value) else StateOp.Delete(key)))
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
fun purge(prefix: String) {
|
|
212
|
+
require(prefix.length > 1 && prefix.endsWith('/'))
|
|
213
|
+
val range = StateRange(prefix, StateListOptions())
|
|
214
|
+
database(false)?.execSQL("DELETE FROM state WHERE key >= ? AND key < ?", arrayOf(range.lower, range.upper))
|
|
215
|
+
}
|
|
216
|
+
}
|