@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.
Files changed (183) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +32 -4
  3. package/THIRD-PARTY-NOTICES +899 -6
  4. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +4 -3
  5. package/android/src/main/AndroidManifest.xml +0 -5
  6. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +33 -8
  7. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +139 -5
  8. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +5 -2
  9. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +23 -6
  10. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +28 -6
  11. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +4 -11
  12. package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
  13. package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
  14. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +19 -4
  15. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +2 -2
  16. package/android/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
  17. package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
  18. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +5 -3
  19. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +4 -0
  20. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +11 -11
  21. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
  22. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +11 -16
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +3 -3
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +45 -10
  26. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +0 -3
  27. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
  28. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +1 -1
  29. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +9 -23
  30. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +11 -2
  31. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +83 -20
  32. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +54 -8
  33. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +19 -360
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +79 -10
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +8 -5
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +8 -1
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +426 -33
  40. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +1 -351
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +15 -29
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +196 -10
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +86 -3
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +33 -0
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +1 -1
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +68 -4
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +3403 -6894
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +89 -18
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +1 -2
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +2 -2
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +3 -3
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +17 -18
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +12 -14
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +36 -6
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +21 -6
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +16 -7
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +25 -4
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -0
  70. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  71. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  72. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  73. package/croche-react-native.podspec +1 -0
  74. package/dist/react-native/src/core-native.d.ts +3 -0
  75. package/dist/react-native/src/core-native.js +148 -25
  76. package/dist/react-native/src/core-wire.d.ts +20 -3
  77. package/dist/rn-shared-build.json +8 -8
  78. package/dist/runtime/src/adapters.d.ts +8 -0
  79. package/dist/runtime/src/adapters.js +29 -0
  80. package/dist/runtime/src/agent.d.ts +53 -5
  81. package/dist/runtime/src/agent.js +69 -7
  82. package/dist/runtime/src/app-api.d.ts +307 -19
  83. package/dist/runtime/src/cancel.d.ts +2 -2
  84. package/dist/runtime/src/cancel.js +7 -4
  85. package/dist/runtime/src/core/foreground.d.ts +3 -0
  86. package/dist/runtime/src/core/foreground.js +40 -0
  87. package/dist/runtime/src/core/port.d.ts +48 -35
  88. package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
  89. package/dist/runtime/src/core/wasm-owner.js +237 -0
  90. package/dist/runtime/src/croche.d.ts +64 -9
  91. package/dist/runtime/src/croche.js +78 -17
  92. package/dist/runtime/src/errors.d.ts +7 -0
  93. package/dist/runtime/src/errors.js +15 -1
  94. package/dist/runtime/src/generated/app-stream.d.ts +155 -1
  95. package/dist/runtime/src/generated/app-stream.js +7 -4
  96. package/dist/runtime/src/image-input.d.ts +5 -0
  97. package/dist/runtime/src/image-input.js +60 -0
  98. package/dist/runtime/src/index.d.ts +6 -0
  99. package/dist/runtime/src/index.js +5 -0
  100. package/dist/runtime/src/index.native.d.ts +1 -21
  101. package/dist/runtime/src/index.native.js +2 -8
  102. package/dist/runtime/src/native-adapter.d.ts +1 -1
  103. package/dist/runtime/src/native-adapter.js +10 -4
  104. package/dist/runtime/src/pal/host.d.ts +3 -3
  105. package/dist/runtime/src/pal/host.js +34 -9
  106. package/dist/runtime/src/pal/platform.d.ts +11 -6
  107. package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
  108. package/dist/runtime/src/pal/state-store-lock.js +2 -0
  109. package/dist/runtime/src/pal/state-store.d.ts +66 -0
  110. package/dist/runtime/src/pal/state-store.js +1 -0
  111. package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
  112. package/dist/runtime/src/pal/storage-version-contract.js +68 -0
  113. package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
  114. package/dist/runtime/src/pal/transactional-storage.js +124 -0
  115. package/dist/runtime/src/tools.d.ts +20 -4
  116. package/dist/runtime/src/tools.js +31 -7
  117. package/ios/CoreAgentTransport.swift +2 -2
  118. package/ios/CoreNativePal.swift +26 -21
  119. package/ios/CorePlatformTransport.swift +4 -4
  120. package/ios/CoreWireDispatch.swift +38 -8
  121. package/ios/CoreWireSupport.swift +179 -4
  122. package/ios/CrocheRuntimeBridge.swift +1 -1
  123. package/ios/ProjectPal.swift +15 -12
  124. package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
  125. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +2 -6
  126. package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
  127. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +1 -174
  128. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +233 -4
  129. package/ios/vendor/CrocheRuntimeSDK/Host.swift +1 -399
  130. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +3 -3
  131. package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
  132. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +26 -10
  133. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +0 -155
  134. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +1 -27
  135. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +8 -4
  136. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +57 -21
  137. package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
  138. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +96 -10
  139. package/ios/vendor/CrocheRuntimeSDK/Project.swift +3 -382
  140. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +1 -412
  141. package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
  142. package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
  143. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +86 -33
  144. package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
  145. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +1 -1
  146. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +12 -3
  147. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +135 -56
  148. package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
  149. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +17 -8
  150. package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
  151. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +184 -15
  152. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +31 -3
  153. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +131 -61
  154. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +10 -15
  155. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +86 -17
  156. package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
  157. package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
  158. package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
  159. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +3 -249
  160. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +40 -8
  161. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +1720 -3883
  162. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +816 -1649
  163. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  164. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +816 -1649
  165. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +2 -2
  166. package/package.json +3 -3
  167. package/scripts/README.md +1 -1
  168. package/scripts/check-swift-vendor-modules.sh +15 -0
  169. package/scripts/vendor-native.sh +4 -3
  170. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
  171. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
  172. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -113
  173. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -201
  174. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
  175. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
  176. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
  177. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +0 -18
  178. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -252
  179. package/dist/runtime/src/pal/codec.d.ts +0 -15
  180. package/dist/runtime/src/pal/codec.js +0 -52
  181. package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
  182. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -496
  183. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -44
@@ -1,25 +1,96 @@
1
1
  package dev.croche.s7
2
2
 
3
- import dev.croche.LockOutcome
4
- import dev.croche.StoragePal
3
+ import dev.croche.StateListOptions
4
+ import dev.croche.StateStore
5
+ import dev.croche.VersionedValue
5
6
  import dev.croche.ffi.*
6
7
  import kotlinx.coroutines.Dispatchers
7
8
  import kotlinx.coroutines.runBlocking
8
9
 
9
- /** Core invokes these on its effect worker. The wrapper only bridges suspend app I/O. */
10
- internal fun appStorage(storage: StoragePal): CoreStoragePal = object : CoreStoragePal {
11
- private fun <T> call(block: suspend () -> T): T = storageCallback { runBlocking(Dispatchers.IO) { block() } }
12
- override fun read(key: String) = call { storage.read(key) }
13
- override fun write(key: String, value: String) {
14
- call { storage.write(key, value) }
15
- }
16
- override fun remove(key: String) = call { storage.remove(key) }
17
- override fun list(prefix: String) = call { storage.list(prefix) }
18
- override fun lock(name: String) = call {
19
- when (storage.lock(name)) { LockOutcome.ACQUIRED -> PalLockOutcome.ACQUIRED; LockOutcome.HELD -> PalLockOutcome.HELD }
20
- }
21
- override fun unlock(name: String) = call { storage.unlock(name) }
22
- override fun readSecret(key: String) = call { storage.secrets.read(key) }
23
- override fun writeSecret(key: String, value: String) = call { storage.secrets.write(key, value) }
24
- override fun removeSecret(key: String) = call { storage.secrets.remove(key) }
10
+ internal interface LocalStoragePal : CoreStoragePal {
11
+ fun purgeStorage(
12
+ prefix: String, localState: Boolean, localSecret: Boolean,
13
+ deleteSecret: () -> Unit = {}, deleteState: () -> Unit = {},
14
+ )
25
15
  }
16
+
17
+ /** Core invokes these on its effect worker. The wrapper bridges suspend app I/O. */
18
+ internal fun appStorage(platform: LocalStoragePal, state: StateStore): CoreStoragePal =
19
+ object : CoreStoragePal by platform {
20
+ private fun <T> call(block: suspend () -> T): T = storageCallback { runBlocking(Dispatchers.IO) { block() } }
21
+
22
+ override fun commitState(ops: List<CoreStateOp>, condition: CoreStateCondition): CoreStateCommit {
23
+ return call {
24
+ val batch = ops.map { it.toApp() }
25
+ val guard = condition.toApp()
26
+ validateStateBatch(batch, guard)
27
+ state.commit(batch, guard).toCore()
28
+ }
29
+ }
30
+
31
+ override fun listState(prefix: String, options: CoreStateListOptions): CoreStatePage {
32
+ return call {
33
+ val range = options.toApp()
34
+ StateRange(prefix, StateListOptions(range.start, range.reverse, range.limit))
35
+ state.list(prefix, range).toCore()
36
+ }
37
+ }
38
+
39
+ override fun readVersioned(key: String): CoreVersionedValue {
40
+ return call {
41
+ val row = state.get(stateKey(key))
42
+ VersionedValue(row?.value, row?.version).toCore()
43
+ }
44
+ }
45
+
46
+ override fun writeIf(key: String, value: String?, expect: String?): CoreWriteOutcome {
47
+ val op = if (value == null) CoreStateOp.Delete(key) else CoreStateOp.Put(key, value)
48
+ return when (val fact = commitState(listOf(op), CoreStateCondition(key, expect))) {
49
+ is CoreStateCommit.Committed -> CoreWriteOutcome.Written(fact.version)
50
+ CoreStateCommit.Conflict -> CoreWriteOutcome.Conflict(null)
51
+ }
52
+ }
53
+
54
+ override fun read(key: String): String? = readVersioned(key).value
55
+
56
+ private fun modify(key: String, value: String?) {
57
+ val version = readVersioned(key).version
58
+ if (writeIf(key, value, version) !is CoreWriteOutcome.Written) {
59
+ throw CoreStorageFailure.Failure("StateStore key changed before commit")
60
+ }
61
+ }
62
+
63
+ override fun write(key: String, value: String) {
64
+ modify(key, value)
65
+ }
66
+
67
+ override fun remove(key: String) {
68
+ modify(key, null)
69
+ }
70
+
71
+ override fun list(prefix: String): List<String> {
72
+ return buildList {
73
+ val seen = mutableSetOf<String>()
74
+ var cursor: String? = null
75
+ do {
76
+ val page = listState(prefix, CoreStateListOptions(null, false, null, cursor))
77
+ for (row in page.entries) {
78
+ if (!row.key.startsWith(prefix) || lastOrNull()?.let { it >= row.key } == true) {
79
+ throw CoreStorageFailure.Failure("StateStore returned invalid list order or scope")
80
+ }
81
+ add(row.key)
82
+ }
83
+ cursor = page.nextCursor
84
+ if (cursor != null && !seen.add(cursor)) {
85
+ throw CoreStorageFailure.Failure("StateStore cursor did not advance")
86
+ }
87
+ } while (cursor != null)
88
+ }
89
+ }
90
+
91
+ override fun purgeInstance(prefix: String, secretKey: String?) {
92
+ platform.purgeStorage(prefix, localState = false, localSecret = true, deleteState = {
93
+ for (key in list(prefix)) modify(key, null)
94
+ })
95
+ }
96
+ }
@@ -18,13 +18,12 @@ internal object CoreFactoryCalls {
18
18
 
19
19
  /** Facade groupings forward to the same Core object; they keep no state of their own. */
20
20
  internal class CrocheCalls(private val core: CoreCrocheInterface) {
21
- val agentIds: List<String> get() = core.agentIds()
22
21
  fun agent(id: String, scopeJson: String?) = core.agent(id, scopeJson)
23
22
  suspend fun deliverDue(optionsJson: String?, cancel: CancelToken?): String =
24
23
  withContext(Dispatchers.IO) { core.deliverDue(optionsJson, cancel) }
25
24
  fun wikiPut(docJson: String) = core.wikiPut(docJson)
26
25
  fun wikiRemove(path: String) = core.wikiRemove(path)
27
- fun wikiList(): String = core.wikiList()
26
+ fun wikiList(optionsJson: String?): String = core.wikiList(optionsJson)
28
27
  fun debugAttach(optionsJson: String): String = core.debugAttach(optionsJson)
29
28
  fun debugDetach() = core.debugDetach()
30
29
  fun close() = core.shutdown()
@@ -33,8 +33,8 @@ internal object CoreOptionsEncoding {
33
33
  }
34
34
  json.add("tools", tools)
35
35
  }
36
- // The PAL argument is always real. Only an app-supplied PAL gets a JSON marker.
37
- if (customStorage != null) json.add("storage", JsonNull.INSTANCE) else json.remove("storage")
36
+ // OpenOptions already carries ordered adapter-kind markers. Opaque
37
+ // storage implementations travel only through this callback argument.
38
38
  if (sink != null) json.add("sink", JsonNull.INSTANCE)
39
39
  return Encoded(json.toString(), registrations ?: emptyList(), customStorage ?: platformStorage, sink)
40
40
  }
@@ -1,7 +1,7 @@
1
1
  package dev.croche.s7
2
2
 
3
3
  import dev.croche.ffi.CancelToken
4
- import dev.croche.ffi.CoreImageInput
4
+ import dev.croche.ffi.CoreAttachmentInput
5
5
  import dev.croche.ffi.CoreAgentInterface
6
6
  import dev.croche.ffi.CoreEventSink
7
7
  import dev.croche.ffi.CoreSubscriptionInterface
@@ -11,10 +11,10 @@ import kotlinx.coroutines.withContext
11
11
  /** Thin calls to S1/S3's generated agent, not a staging port or a second request state machine.
12
12
  * JSON/options/cancellation are forwarded unchanged; Core owns all outcomes and queues. */
13
13
  internal class AgentStreamCalls(private val agent: CoreAgentInterface) {
14
- suspend fun send(inputJson: String, images: List<CoreImageInput> = emptyList(), optionsJson: String? = null, cancel: CancelToken? = null): String =
14
+ suspend fun send(inputJson: String, images: List<CoreAttachmentInput> = emptyList(), optionsJson: String? = null, cancel: CancelToken? = null): String =
15
15
  coreStreamIO { agent.send(inputJson, images, optionsJson, cancel) }
16
16
 
17
- suspend fun request(inputJson: String, images: List<CoreImageInput> = emptyList(), optionsJson: String? = null, cancel: CancelToken? = null): String =
17
+ suspend fun request(inputJson: String, images: List<CoreAttachmentInput> = emptyList(), optionsJson: String? = null, cancel: CancelToken? = null): String =
18
18
  coreStreamIO { agent.request(inputJson, images, optionsJson, cancel) }
19
19
 
20
20
  fun subscribe(selectionJson: String, eventSink: CoreEventSink): SubscriptionCalls =
@@ -51,14 +51,13 @@ internal fun <T> hostCallback(block: () -> T): T {
51
51
  /** A new member of a Core-facing interface must be added to its wrapper. */
52
52
  internal class AttachedHostPal(private val host: HostPal) : HostPal {
53
53
  private fun <T> enter(block: () -> T): T = hostCallback(block)
54
+ override fun blobOperation(operation: String, key: String, cursor: String?, bytes: ByteArray?) =
55
+ enter { host.blobOperation(operation, key, cursor, bytes) }
54
56
  override fun streamPlatform() = enter { host.streamPlatform() }
55
- override fun imageCodecAvailable() = enter { host.imageCodecAvailable() }
57
+ override fun imageSupport() = enter { host.imageSupport() }
58
+ override fun imageOperation(operation: String, bytes: ByteArray, optionsJson: String, cancel: CancelToken) = enter { host.imageOperation(operation, bytes, optionsJson, cancel) }
56
59
  override fun readImage(request: PalImageReadRequest, cancel: CancelToken) = enter { host.readImage(request, cancel) }
57
- override fun prepareImage(source: PalImageBytes, plan: PalImagePreparePlan, cancel: CancelToken) = enter { host.prepareImage(source, plan, cancel) }
58
60
  override fun releaseImage(capture: String) = enter { host.releaseImage(capture) }
59
- override fun decodeImage(bytes: ByteArray, options: PalImageDecodeOptions, cancel: CancelToken) = enter { host.decodeImage(bytes, options, cancel) }
60
- override fun renderImage(request: PalImageRenderRequest, cancel: CancelToken) = enter { host.renderImage(request, cancel) }
61
- override fun releaseDecodedImage(handle: String) = enter { host.releaseDecodedImage(handle) }
62
61
  override fun http(request: PalHttpRequest, sink: HttpSink, cancel: CancelToken) = enter { host.http(request, sink, cancel) }
63
62
  override fun resolve(host: String, cancel: CancelToken) = enter { this.host.resolve(host, cancel) }
64
63
  override fun platformFacts() = enter { host.platformFacts() }
@@ -69,6 +68,7 @@ internal class AttachedHostPal(private val host: HostPal) : HostPal {
69
68
  override fun readSecret(key: String) = enter { host.readSecret(key) }
70
69
  override fun writeSecret(key: String, value: String) = enter { host.writeSecret(key, value) }
71
70
  override fun remove(key: String) = enter { host.remove(key) }
71
+ override fun purgeInstance(prefix: String) = enter { host.purgeInstance(prefix) }
72
72
  override fun removeSecret(key: String) = enter { host.removeSecret(key) }
73
73
  override fun lock(key: String) = enter { host.lock(key) }
74
74
  override fun unlock(key: String) = enter { host.unlock(key) }
@@ -81,19 +81,22 @@ internal class AttachedHostPal(private val host: HostPal) : HostPal {
81
81
  override fun wake(atMs: Double?) = enter { host.wake(atMs) }
82
82
  override fun schedule(entries: String) = enter { host.schedule(entries) }
83
83
  override fun registerBackground(identifier: String, wake: CoreBackgroundWake) = enter { host.registerBackground(identifier, wake) }
84
- override fun archiveAppendLine(entry: String, line: String) = enter { host.archiveAppendLine(entry, line) }
85
- override fun archiveReadLines(entry: String) = enter { host.archiveReadLines(entry) }
86
- override fun archiveReplaceLines(entry: String, lines: List<String>) = enter { host.archiveReplaceLines(entry, lines) }
87
- override fun archiveRemove(entry: String) = enter { host.archiveRemove(entry) }
88
- override fun archiveEntries(prefix: String) = enter { host.archiveEntries(prefix) }
89
- override fun storageCapability() = enter { host.storageCapability() }
90
84
  }
91
85
 
92
86
  internal class AttachedStoragePal(private val storage: CoreStoragePal) : CoreStoragePal {
93
87
  private fun <T> enter(block: () -> T): T = hostCallback(block)
88
+ override fun commitState(ops: List<CoreStateOp>, condition: CoreStateCondition) = enter {
89
+ storage.commitState(ops, condition)
90
+ }
91
+ override fun listState(prefix: String, options: CoreStateListOptions) = enter {
92
+ storage.listState(prefix, options)
93
+ }
94
+ override fun readVersioned(key: String) = enter { storage.readVersioned(key) }
95
+ override fun writeIf(key: String, value: String?, expect: String?) = enter { storage.writeIf(key, value, expect) }
94
96
  override fun read(key: String) = enter { storage.read(key) }
95
97
  override fun write(key: String, value: String) = enter { storage.write(key, value) }
96
98
  override fun remove(key: String) = enter { storage.remove(key) }
99
+ override fun purgeInstance(prefix: String, secretKey: String?) = enter { storage.purgeInstance(prefix, secretKey) }
97
100
  override fun list(prefix: String) = enter { storage.list(prefix) }
98
101
  override fun lock(name: String) = enter { storage.lock(name) }
99
102
  override fun unlock(name: String) = enter { storage.unlock(name) }
@@ -101,12 +104,10 @@ internal class AttachedStoragePal(private val storage: CoreStoragePal) : CoreSto
101
104
  override fun writeSecret(key: String, value: String) = enter { storage.writeSecret(key, value) }
102
105
  override fun removeSecret(key: String) = enter { storage.removeSecret(key) }
103
106
  }
104
- private class AttachedListener(val listener: EventListener) : EventListener {
105
- override fun onEvent(event: String) = hostCallback { listener.onEvent(event) }
106
- }
107
+
107
108
  private class AttachedExecute(val execute: CoreToolExecute) : CoreToolExecute {
108
- override fun execute(callJson: String, contextJson: String, cancel: CancelToken) =
109
- hostCallback { execute.execute(callJson, contextJson, cancel) }
109
+ override fun execute(callJson: String, contextJson: String, cancel: CancelToken, attachments: dev.croche.ffi.CoreAttachmentReader) =
110
+ hostCallback { execute.execute(callJson, contextJson, cancel, attachments) }
110
111
  }
111
112
  private class AttachedSink(val sink: CoreEventSink) : CoreEventSink {
112
113
  override fun deliver(deliveryId: String, eventJson: String, delivery: CoreDelivery) =
@@ -120,8 +121,6 @@ private class AttachedCancel(val callback: CancelCallback) : CancelCallback {
120
121
  internal fun attached(host: HostPal): HostPal = host as? AttachedHostPal ?: AttachedHostPal(host)
121
122
  internal fun attached(storage: CoreStoragePal): CoreStoragePal = storage as? AttachedStoragePal ?: AttachedStoragePal(storage)
122
123
  @JvmName("attachedOrNull") internal fun attached(storage: CoreStoragePal?): CoreStoragePal? = storage?.let(::attached)
123
- internal fun attached(listener: EventListener): EventListener = listener as? AttachedListener ?: AttachedListener(listener)
124
- @JvmName("attachedListenerOrNull") internal fun attached(listener: EventListener?): EventListener? = listener?.let(::attached)
125
124
  internal fun attached(execute: CoreToolExecute): CoreToolExecute = execute as? AttachedExecute ?: AttachedExecute(execute)
126
125
  internal fun attached(sink: CoreEventSink): CoreEventSink = sink as? AttachedSink ?: AttachedSink(sink)
127
126
  @JvmName("attachedSinkOrNull") internal fun attached(sink: CoreEventSink?): CoreEventSink? = sink?.let(::attached)
@@ -0,0 +1,28 @@
1
+ package dev.croche.s7
2
+
3
+ import com.google.gson.Gson
4
+ import dev.croche.ImageAdapter
5
+ import dev.croche.ImageResizeLimits
6
+ import dev.croche.ffi.*
7
+ import kotlinx.coroutines.*
8
+
9
+ /** The only override is the app's image implementation; all other host effects stay native. */
10
+ internal class ImageAdapterHost(private val base: HostPal, private val image: ImageAdapter) : HostPal by base {
11
+ override fun imageSupport(): String = Gson().toJson(image.support)
12
+ override fun imageOperation(operation: String, bytes: ByteArray, optionsJson: String, cancel: CancelToken): PalImageReply = effectCallback {
13
+ dev.croche.NativeImagePal.check(cancel)
14
+ runBlocking(Dispatchers.IO) {
15
+ val pending = async {
16
+ dev.croche.NativeImagePal.check(cancel)
17
+ when (operation) {
18
+ "info" -> PalImageReply(Gson().toJson(image.info(bytes)), byteArrayOf())
19
+ "resize" -> PalImageReply("{}", image.resize(bytes, Gson().fromJson(optionsJson, ImageResizeLimits::class.java)))
20
+ else -> throw CorePalException.Failure("image_unsupported", "The image operation is not supported.")
21
+ }
22
+ }
23
+ cancel.onCancel(attached(object : CancelCallback { override fun cancelled() { pending.cancel() } }))
24
+ if (cancel.isCancelled()) pending.cancel()
25
+ pending.await()
26
+ }
27
+ }
28
+ }
@@ -3,6 +3,7 @@ package dev.croche.s7
3
3
  import dev.croche.ResponseSink
4
4
  import dev.croche.RuntimeCancellation
5
5
  import dev.croche.ffi.*
6
+ import dev.croche.s7.pal.BlobFiles
6
7
  import dev.croche.s7.pal.DirectHttpPal
7
8
  import java.io.File
8
9
  import java.io.FileNotFoundException
@@ -12,17 +13,20 @@ import java.util.TimeZone
12
13
  import java.util.UUID
13
14
 
14
15
  /** Plain JVM effects only. No image codec and no acquisition before Core's codec preflight. */
15
- internal class JvmCoreHost(private val storage: CoreStoragePal) : HostPal {
16
+ internal class JvmCoreHost(
17
+ private val storage: CoreStoragePal,
18
+ private val blobs: BlobFiles? = (storage as? JvmStoragePal)?.blobs,
19
+ ) : HostPal {
16
20
  private val http = DirectHttpPal()
21
+ override fun blobOperation(operation: String, key: String, cursor: String?, bytes: ByteArray?): PalBlobReply =
22
+ (blobs ?: throw FfiException.Failure("storage_error", "No JVM blob adapter is attached"))
23
+ .operation(operation, key, cursor, bytes)
17
24
  override fun streamPlatform() = HostStreamPlatform.OTHER
18
- override fun platformFacts() = PalPlatformFacts(PalTargetKind.OTHER, null, java.util.Locale.getDefault().toLanguageTag(), null, false)
19
- override fun imageCodecAvailable() = false
25
+ override fun platformFacts() = PalPlatformFacts(PalTargetKind.OTHER, null, java.util.Locale.getDefault().toLanguageTag(), null)
26
+ override fun imageSupport(): String? = null
20
27
  override fun readImage(request: PalImageReadRequest, cancel: CancelToken): ByteArray = throw CorePalException.Failure("image_fetch_failed", "No JVM image reader is attached")
21
- override fun prepareImage(source: PalImageBytes, plan: PalImagePreparePlan, cancel: CancelToken): PalImageBytes = throw CorePalException.Failure("image_unsupported", "No JVM image codec is attached")
22
- override fun decodeImage(bytes: ByteArray, options: PalImageDecodeOptions, cancel: CancelToken): PalDecodedImage = throw CorePalException.Failure("invalid_input", "No JVM image codec is attached")
23
- override fun renderImage(request: PalImageRenderRequest, cancel: CancelToken): ByteArray = throw CorePalException.Failure("image_unsupported", "No JVM image codec is attached")
28
+ override fun imageOperation(operation: String, bytes: ByteArray, optionsJson: String, cancel: CancelToken): PalImageReply = throw CorePalException.Failure("image_unsupported", "No JVM image adapter is attached")
24
29
  override fun releaseImage(capture: String) = Unit
25
- override fun releaseDecodedImage(handle: String) = Unit
26
30
  override fun resolve(host: String, cancel: CancelToken) = effectCallback { http.resolve(host, signal(cancel)) }
27
31
  override fun http(request: PalHttpRequest, sink: HttpSink, cancel: CancelToken) = effectCallback {
28
32
  http.http(request, object : ResponseSink {
@@ -40,6 +44,7 @@ internal class JvmCoreHost(private val storage: CoreStoragePal) : HostPal {
40
44
  override fun read(key: String) = storage.read(key)
41
45
  override fun write(key: String, value: String) = storage.write(key, value)
42
46
  override fun remove(key: String) = storage.remove(key)
47
+ override fun purgeInstance(prefix: String) = storage.purgeInstance(prefix, null)
43
48
  override fun list(prefix: String) = storage.list(prefix)
44
49
  override fun lock(key: String) = storage.lock(key)
45
50
  override fun unlock(key: String) = storage.unlock(key)
@@ -47,7 +52,6 @@ internal class JvmCoreHost(private val storage: CoreStoragePal) : HostPal {
47
52
  override fun writeSecret(key: String, value: String) = storage.writeSecret(key, value)
48
53
  override fun removeSecret(key: String) = storage.removeSecret(key)
49
54
  override fun storeIdentity() = "jvm-core-storage-pal"
50
- override fun storageCapability() = StorageCapability.KEYED
51
55
  override fun nowMs() = System.currentTimeMillis().toDouble()
52
56
  override fun utcOffsetMinutes(atMs: Double) = TimeZone.getDefault().getOffset(atMs.toLong()).toLong() / 60000
53
57
  override fun random() = UUID.randomUUID().toString()
@@ -59,12 +63,6 @@ internal class JvmCoreHost(private val storage: CoreStoragePal) : HostPal {
59
63
  override fun schedule(entries: String) = Unit
60
64
  override fun tool(invocation: String, cancel: CancelToken): ToolOutput = throw CorePalException.Failure("tool_not_dispatched", "S1 uses registered tool definitions")
61
65
  override fun attest(request: String, timeoutMs: ULong): String = throw CorePalException.Failure("attestation_unsupported", "No JVM attestation provider")
62
- override fun archiveAppendLine(entry: String, line: String): Unit = archive()
63
- override fun archiveReadLines(entry: String): List<String> = archive()
64
- override fun archiveReplaceLines(entry: String, lines: List<String>): Unit = archive()
65
- override fun archiveRemove(entry: String): Unit = archive()
66
- override fun archiveEntries(prefix: String): List<ArchiveEntry> = archive()
67
- private fun archive(): Nothing = throw CoreStorageFailure.Failure("Core owns keyed archives")
68
66
  private fun signal(cancel: CancelToken) = RuntimeCancellation().also { result ->
69
67
  if (cancel.isCancelled()) result.cancel()
70
68
  cancel.onCancel(attached(object : CancelCallback { override fun cancelled() = result.cancel() }))
@@ -0,0 +1,125 @@
1
+ package dev.croche.s7
2
+
3
+ import com.google.gson.Gson
4
+ import com.google.gson.JsonParser
5
+ import dev.croche.StateCommitResult
6
+ import dev.croche.StateCondition
7
+ import dev.croche.StateEntry
8
+ import dev.croche.StateListOptions
9
+ import dev.croche.StateOp
10
+ import dev.croche.StatePage
11
+ import dev.croche.VersionedValue
12
+ import dev.croche.WriteOutcome
13
+ import dev.croche.s7.pal.AtomicKeyFiles
14
+ import java.io.File
15
+ import java.io.RandomAccessFile
16
+ import java.util.UUID
17
+
18
+ /** The desktop JVM's dependency-free file backend. One atomic replacement publishes a batch. */
19
+ internal class JvmStateStore(private val root: File, private val prepareRoot: () -> Unit, sync: (File) -> Unit) {
20
+ private data class Row(val value: String, val version: String)
21
+ private val directory = File(root, "state-batches")
22
+ private val files = AtomicKeyFiles(directory, sync)
23
+ private val gson = Gson()
24
+
25
+ private fun snapshot(): MutableMap<String, Row> {
26
+ val value = files.readRaw(SNAPSHOT) ?: return mutableMapOf()
27
+ return JsonParser.parseString(value).asJsonObject.entrySet().associateTo(mutableMapOf()) { (key, item) ->
28
+ val row = item.asJsonObject
29
+ val stored = row.getAsJsonPrimitive("value")
30
+ val version = row.getAsJsonPrimitive("version")
31
+ require(stored.isString && version.isString)
32
+ stateKey(key) to Row(stored.asString, requireNotNull(storageVersion(version.asString)))
33
+ }
34
+ }
35
+
36
+ private fun save(rows: Map<String, Row>) = files.writeRaw(SNAPSHOT, gson.toJson(rows))
37
+
38
+ private inline fun <T> transaction(block: () -> T): T {
39
+ prepareRoot()
40
+ val gate = File(root, "state-batch.lock").canonicalFile
41
+ // Java rejects overlapping locks in the same JVM, even on separate channels.
42
+ return synchronized(gate.path.intern()) {
43
+ RandomAccessFile(gate, "rw").use { handle ->
44
+ handle.channel.lock().use { block() }
45
+ }
46
+ }
47
+ }
48
+
49
+ fun get(key: String): VersionedValue {
50
+ stateKey(key)
51
+ val row = snapshot()[key]
52
+ return VersionedValue(row?.value, row?.version)
53
+ }
54
+
55
+ fun list(prefix: String, options: StateListOptions): StatePage {
56
+ val range = StateRange(prefix, options)
57
+ // The walk seeks to the page. The snapshot itself is still loaded whole: this standalone
58
+ // JVM store is not a bounded backend yet (HLD storage, As Is gaps).
59
+ // A start key past the prefix leaves an empty interval; a sorted map refuses one that is inverted.
60
+ val rows = java.util.TreeMap(snapshot())
61
+ val page = if (range.from < range.to) rows.subMap(range.from, !range.fromExclusive, range.to, false) else java.util.TreeMap()
62
+ val ordered = if (range.reverse) page.descendingMap() else page
63
+ val entries = ordered.asSequence()
64
+ .take(range.limit + 1)
65
+ .map { (key, row) -> StateEntry(key, row.value) }
66
+ .toList()
67
+ return range.page(entries)
68
+ }
69
+
70
+ private fun MutableMap<String, Row>.apply(op: StateOp): String? = when (op) {
71
+ is StateOp.Put -> UUID.randomUUID().toString().also { this[op.key] = Row(op.value, it) }
72
+ is StateOp.Delete -> { remove(op.key); null }
73
+ }
74
+
75
+ fun commit(ops: List<StateOp>, condition: StateCondition): StateCommitResult {
76
+ validateStateBatch(ops, condition)
77
+ return transaction {
78
+ val rows = snapshot()
79
+ if (rows[condition.key]?.version != condition.version) return@transaction StateCommitResult.Conflict
80
+ for (op in ops) rows.apply(op)
81
+ save(rows)
82
+ StateCommitResult.Committed(rows[condition.key]?.version)
83
+ }
84
+ }
85
+
86
+ fun write(key: String, value: String) {
87
+ stateKey(key)
88
+ transaction { val rows = snapshot(); rows.apply(StateOp.Put(key, value)); save(rows) }
89
+ }
90
+
91
+ fun remove(key: String) {
92
+ stateKey(key)
93
+ if (!directory.exists()) return
94
+ transaction { val rows = snapshot(); if (rows.remove(key) != null) save(rows) }
95
+ }
96
+
97
+ fun writeIf(key: String, value: String?, expect: String?): WriteOutcome {
98
+ stateKey(key)
99
+ storageVersion(expect)
100
+ return transaction {
101
+ val rows = snapshot()
102
+ val current = rows[key]?.version
103
+ if (current != expect) return@transaction WriteOutcome.Conflict(current)
104
+ val written = rows.apply(if (value == null) StateOp.Delete(key) else StateOp.Put(key, value))
105
+ save(rows)
106
+ WriteOutcome.Written(written)
107
+ }
108
+ }
109
+
110
+ fun purge(prefix: String) {
111
+ require(prefix.length > 1 && prefix.endsWith('/'))
112
+ stateKey(prefix)
113
+ if (!directory.exists()) return
114
+ transaction {
115
+ // An interrupted publication may have left a whole unpublished snapshot.
116
+ val plan = files.instancePurgePlan("rows/")
117
+ plan.erase(plan.temporaries)
118
+ plan.durable()
119
+ val rows = snapshot()
120
+ if (rows.keys.removeAll { it.startsWith(prefix) }) save(rows)
121
+ }
122
+ }
123
+
124
+ private companion object { const val SNAPSHOT = "rows/current" }
125
+ }
@@ -1,7 +1,10 @@
1
1
  package dev.croche.s7
2
2
 
3
+ import dev.croche.StateListOptions
3
4
  import dev.croche.ffi.*
4
5
  import dev.croche.s7.pal.AtomicKeyFiles
6
+ import dev.croche.s7.pal.BlobFiles
7
+ import dev.croche.s7.pal.purgeInstanceFiles
5
8
  import java.io.File
6
9
  import java.nio.channels.FileChannel
7
10
  import java.nio.file.StandardOpenOption
@@ -10,8 +13,10 @@ import java.nio.file.Files
10
13
 
11
14
  /** Plain JVM file PAL; Android uses Keystore instead. The private root contains separate
12
15
  * opaque state and secret areas. No project identity or store layout is resolved here. */
13
- internal class JvmStoragePal(root: File = File(System.getProperty("user.home"), ".croche/pal-v1")) : CoreStoragePal {
16
+ internal class JvmStoragePal(root: File = File(System.getProperty("user.home"), ".croche/pal-v1")) : LocalStoragePal {
14
17
  private val root = root
18
+ internal val blobs = BlobFiles(root, ::prepareRoot, ::sync)
19
+ private val state = JvmStateStore(root, ::prepareRoot, ::sync)
15
20
  private val values = AtomicKeyFiles(File(root, "state"), ::sync)
16
21
  private val secrets = AtomicKeyFiles(File(root, "secrets"), ::sync)
17
22
  private fun prepareRoot() {
@@ -19,12 +24,37 @@ internal class JvmStoragePal(root: File = File(System.getProperty("user.home"),
19
24
  try { Files.setPosixFilePermissions(root.toPath(), PosixFilePermissions.fromString("rwx------")) }
20
25
  catch (_: UnsupportedOperationException) { /* Windows uses the user's profile ACL. */ }
21
26
  }
22
- override fun read(key: String) = storageCallback { values.read(key) }
23
- override fun write(key: String, value: String) = storageCallback {
24
- prepareRoot(); values.write(key, value)
27
+ override fun read(key: String) = storageCallback { state.get(logicalStorageKey(key)).value }
28
+ override fun readVersioned(key: String) = storageCallback { state.get(versionedStorageKey(key)).toCore() }
29
+ override fun writeIf(key: String, value: String?, expect: String?) = storageCallback {
30
+ state.writeIf(versionedStorageKey(key), value, expect).toCore(value)
31
+ }
32
+ override fun commitState(ops: List<CoreStateOp>, condition: CoreStateCondition) = storageCallback {
33
+ state.commit(ops.map { it.toApp() }, condition.toApp()).toCore()
34
+ }
35
+ override fun listState(prefix: String, options: CoreStateListOptions) = storageCallback {
36
+ state.list(prefix, options.toApp()).toCore()
37
+ }
38
+ override fun write(key: String, value: String) = storageCallback { state.write(logicalStorageKey(key), value) }
39
+ override fun remove(key: String) = storageCallback { state.remove(logicalStorageKey(key)) }
40
+ override fun purgeInstance(prefix: String, secretKey: String?) = purgeStorage(prefix, true, true)
41
+ override fun purgeStorage(
42
+ prefix: String, localState: Boolean, localSecret: Boolean, deleteSecret: () -> Unit, deleteState: () -> Unit,
43
+ ) = storageCallback {
44
+ purgeInstanceFiles(values.takeIf { localState }, secrets.takeIf { localSecret }, prefix, deleteSecret, deleteState)
45
+ if (localState) state.purge(prefix)
46
+ }
47
+ override fun list(prefix: String): List<String> = storageCallback {
48
+ logicalStorageKey(prefix)
49
+ buildList {
50
+ var cursor: String? = null
51
+ do {
52
+ val page = state.list(prefix, StateListOptions(cursor = cursor))
53
+ addAll(page.entries.map { it.key })
54
+ cursor = page.nextCursor
55
+ } while (cursor != null)
56
+ }
25
57
  }
26
- override fun remove(key: String) = storageCallback { values.remove(key) }
27
- override fun list(prefix: String) = storageCallback { values.list(prefix) }
28
58
  override fun lock(name: String) = storageCallback { prepareRoot(); if (values.lock(name)) PalLockOutcome.ACQUIRED else PalLockOutcome.HELD }
29
59
  override fun unlock(name: String) = storageCallback { values.unlock(name) }
30
60
  override fun readSecret(key: String) = storageCallback { secrets.read(key) }
@@ -0,0 +1,21 @@
1
+ package dev.croche.s7
2
+
3
+ import dev.croche.ffi.uniffiEnsureInitialized
4
+
5
+ // Cache a failed load too, so later calls retain the original mismatch diagnostic.
6
+ private val nativeInitializationFailure: LinkageError? by lazy {
7
+ try {
8
+ uniffiEnsureInitialized()
9
+ null
10
+ } catch (failure: LinkageError) {
11
+ failure
12
+ }
13
+ }
14
+
15
+ // Native-backed SDK methods go through publicSync/publicCall. Entry points that start a
16
+ // native lifetime directly (RN module and Android worker) must call this before using FFI.
17
+ internal fun ensureNativeCoreInitialized() {
18
+ val failure = nativeInitializationFailure ?: return
19
+ val reason = (failure as? ExceptionInInitializerError)?.cause ?: failure
20
+ throw IllegalStateException("Croche native Core initialization failed: ${reason.message ?: reason.javaClass.simpleName}", failure)
21
+ }
@@ -1,7 +1,7 @@
1
1
  package dev.croche.s7
2
2
 
3
3
  import dev.croche.ffi.*
4
- import dev.croche.StoragePal
4
+ import dev.croche.SelectedAdapters
5
5
  import kotlinx.coroutines.CoroutineDispatcher
6
6
  import kotlinx.coroutines.Dispatchers
7
7
  import java.lang.reflect.InvocationTargetException
@@ -9,7 +9,7 @@ import java.lang.reflect.InvocationTargetException
9
9
  internal data class NativePlatformPals(val storage: CoreStoragePal, val host: HostPal,
10
10
  val eventDispatcher: CoroutineDispatcher, val platformStorage: CoreStoragePal? = null)
11
11
  internal interface NativePlatformProvider {
12
- fun create(platform: Any?, storage: CoreStoragePal?): NativePlatformPals
12
+ fun create(platform: Any?, adapters: SelectedAdapters): NativePlatformPals
13
13
  }
14
14
 
15
15
  /** The second carrier exists only for Core's private custom-backend enrollment marker. */
@@ -18,24 +18,39 @@ internal fun backgroundStorage(custom: CoreStoragePal?, platform: () -> CoreStor
18
18
  return Pair(custom ?: default, default.takeIf { custom != null })
19
19
  }
20
20
 
21
+ internal fun backgroundStorage(adapters: SelectedAdapters, platform: LocalStoragePal): Pair<CoreStoragePal, CoreStoragePal?> {
22
+ val custom = adapters.state?.let { appStorage(platform, it) }
23
+ return backgroundStorage(custom) { platform }
24
+ }
25
+
21
26
  /** Android ships the provider in its AAR; plain JVM uses file effects. No Core-side default. */
22
- internal fun nativePlatform(platform: Any?, customStorage: StoragePal?): NativePlatformPals {
27
+ internal fun nativePlatform(platform: Any?, adapters: SelectedAdapters): NativePlatformPals {
23
28
  val android = try { Class.forName("dev.croche.android.pal.AndroidPublicPlatform") } catch (_: ClassNotFoundException) { null }
24
29
  if (android != null) {
25
30
  try {
26
- return (android.getDeclaredConstructor().newInstance() as NativePlatformProvider).create(platform, customStorage?.let(::appStorage))
31
+ return (android.getDeclaredConstructor().newInstance() as NativePlatformProvider).create(platform, adapters)
27
32
  } catch (error: InvocationTargetException) { throw error.targetException }
28
33
  }
29
- val (storage, platformStorage) = backgroundStorage(customStorage?.let(::appStorage)) { JvmStoragePal() }
30
- val host = JvmCoreHost(storage)
34
+ val default = JvmStoragePal()
35
+ val (storage, platformStorage) = backgroundStorage(adapters, default)
36
+ val host = JvmCoreHost(storage, default.blobs)
31
37
  return NativePlatformPals(storage, host, Dispatchers.Unconfined, platformStorage)
32
38
  }
33
39
 
34
40
  /** App storage throws facts only, just like platform storage. A supplied code is not copied. */
35
41
  internal fun storageFacts(storage: CoreStoragePal): CoreStoragePal = object : CoreStoragePal {
42
+ override fun commitState(ops: List<CoreStateOp>, condition: CoreStateCondition) = storageCallback {
43
+ storage.commitState(ops, condition)
44
+ }
45
+ override fun listState(prefix: String, options: CoreStateListOptions) = storageCallback {
46
+ storage.listState(prefix, options)
47
+ }
48
+ override fun readVersioned(key: String) = storageCallback { storage.readVersioned(key) }
49
+ override fun writeIf(key: String, value: String?, expect: String?) = storageCallback { storage.writeIf(key, value, expect) }
36
50
  override fun read(key: String) = storageCallback { storage.read(key) }
37
51
  override fun write(key: String, value: String) = storageCallback { storage.write(key, value) }
38
52
  override fun remove(key: String) = storageCallback { storage.remove(key) }
53
+ override fun purgeInstance(prefix: String, secretKey: String?) = storageCallback { storage.purgeInstance(prefix, secretKey) }
39
54
  override fun list(prefix: String) = storageCallback { storage.list(prefix) }
40
55
  override fun lock(name: String) = storageCallback { storage.lock(name) }
41
56
  override fun unlock(name: String) = storageCallback { storage.unlock(name) }