@h1r-ai/croche-react-native 0.5.5 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (248) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +90 -451
  3. package/THIRD-PARTY-NOTICES +906 -14
  4. package/android/build.gradle +6 -1
  5. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +126 -0
  6. package/android/src/main/AndroidManifest.xml +0 -5
  7. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +106 -0
  8. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +217 -0
  9. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +48 -824
  10. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +68 -0
  11. package/android/src/main/java/dev/croche/reactnative/RNHostPal.kt +9 -0
  12. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +64 -41
  13. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +64 -0
  14. package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
  15. package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
  16. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +44 -0
  17. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +19 -32
  18. package/android/src/test/java/dev/croche/reactnative/ProjectHandlerStagesTest.kt +32 -0
  19. package/android/src/test/java/dev/croche/reactnative/ProjectRecoveryTest.kt +12 -0
  20. package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +11 -15
  21. package/android/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
  22. package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidEventSink.kt +27 -0
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +10 -8
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundRegistration.kt +16 -0
  26. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +55 -0
  27. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +162 -0
  28. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
  29. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageInput.kt +15 -0
  30. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapOrientation.kt +40 -0
  31. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapPalCodec.kt +66 -0
  32. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidAssetPal.kt +30 -0
  33. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreFactory.kt +35 -0
  34. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +116 -0
  35. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidMainDispatcher.kt +17 -0
  36. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +17 -0
  37. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidS2Pal.kt +14 -0
  38. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
  39. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +108 -0
  40. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +8 -2
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +29 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +31 -0
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +25 -1
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +121 -103
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +89 -103
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +20 -360
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +136 -0
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +23 -0
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +26 -21
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +715 -0
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +9 -322
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ImagePal.kt +183 -0
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +16 -28
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +294 -37
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +127 -0
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ReaderValues.kt +73 -0
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +73 -0
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +23 -21
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +88 -24
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +5723 -3088
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppEventSink.kt +34 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +96 -0
  70. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundOsRegistration.kt +35 -0
  71. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundSink.kt +37 -0
  72. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreDefinitionCalls.kt +35 -0
  73. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +30 -0
  74. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +41 -0
  75. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +35 -0
  76. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +127 -0
  77. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
  78. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +70 -0
  79. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
  80. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +64 -0
  81. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/LifecycleBinding.kt +18 -0
  82. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
  83. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +60 -0
  84. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PalCallbacks.kt +27 -0
  85. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PlainToolJson.kt +56 -0
  86. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +43 -0
  87. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ScopeJson.kt +29 -0
  88. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
  89. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
  90. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ToolCompletionEncoding.kt +29 -0
  91. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +100 -0
  92. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
  93. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/DirectHttpPal.kt +223 -0
  94. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
  95. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -0
  96. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  97. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  98. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  99. package/croche-react-native.podspec +1 -0
  100. package/dist/package.json +1 -0
  101. package/dist/react-native/src/NativeCrocheRuntime.d.ts +16 -0
  102. package/dist/react-native/src/NativeCrocheRuntime.js +2 -0
  103. package/dist/react-native/src/core-native.d.ts +6 -0
  104. package/dist/react-native/src/core-native.js +316 -0
  105. package/dist/react-native/src/core-wire.d.ts +55 -0
  106. package/dist/react-native/src/core-wire.js +1 -0
  107. package/dist/react-native/src/native-module.d.ts +8 -0
  108. package/dist/react-native/src/native-module.js +53 -0
  109. package/dist/rn-shared-build.json +16 -0
  110. package/dist/runtime/src/adapters.d.ts +8 -0
  111. package/dist/runtime/src/adapters.js +29 -0
  112. package/dist/runtime/src/agent.d.ts +91 -0
  113. package/dist/runtime/src/agent.js +137 -0
  114. package/dist/runtime/src/app-api.d.ts +572 -0
  115. package/dist/runtime/src/app-api.js +1 -0
  116. package/dist/runtime/src/cancel.d.ts +9 -0
  117. package/dist/runtime/src/cancel.js +27 -0
  118. package/dist/runtime/src/core/foreground.d.ts +3 -0
  119. package/dist/runtime/src/core/foreground.js +40 -0
  120. package/dist/runtime/src/core/port.d.ts +247 -0
  121. package/dist/runtime/src/core/port.js +1 -0
  122. package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
  123. package/dist/runtime/src/core/wasm-owner.js +237 -0
  124. package/dist/runtime/src/core/wasm.d.ts +1 -0
  125. package/dist/runtime/src/core/wasm.js +2 -0
  126. package/dist/runtime/src/croche.d.ts +97 -0
  127. package/dist/runtime/src/croche.js +172 -0
  128. package/dist/runtime/src/errors.d.ts +33 -0
  129. package/dist/runtime/src/errors.js +63 -0
  130. package/dist/runtime/src/events.d.ts +5 -0
  131. package/dist/runtime/src/events.js +31 -0
  132. package/dist/runtime/src/generated/app-stream.d.ts +328 -0
  133. package/dist/runtime/src/generated/app-stream.js +127 -0
  134. package/dist/runtime/src/image-input.d.ts +5 -0
  135. package/dist/runtime/src/image-input.js +60 -0
  136. package/dist/runtime/src/index.d.ts +6 -0
  137. package/dist/runtime/src/index.js +5 -0
  138. package/dist/runtime/src/index.native.d.ts +1 -0
  139. package/dist/runtime/src/index.native.js +2 -0
  140. package/dist/runtime/src/json.d.ts +13 -0
  141. package/dist/runtime/src/json.js +120 -0
  142. package/dist/runtime/src/native-adapter.d.ts +3 -0
  143. package/dist/runtime/src/native-adapter.js +30 -0
  144. package/dist/runtime/src/pal/host.d.ts +5 -0
  145. package/dist/runtime/src/pal/host.js +60 -0
  146. package/dist/runtime/src/pal/platform.d.ts +21 -0
  147. package/dist/runtime/src/pal/platform.js +7 -0
  148. package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
  149. package/dist/runtime/src/pal/state-store-lock.js +2 -0
  150. package/dist/runtime/src/pal/state-store.d.ts +66 -0
  151. package/dist/runtime/src/pal/state-store.js +1 -0
  152. package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
  153. package/dist/runtime/src/pal/storage-version-contract.js +68 -0
  154. package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
  155. package/dist/runtime/src/pal/transactional-storage.js +124 -0
  156. package/dist/runtime/src/rn-entry.d.ts +1 -0
  157. package/dist/runtime/src/rn-entry.js +4 -0
  158. package/dist/runtime/src/run-tool.d.ts +33 -0
  159. package/dist/runtime/src/run-tool.js +7 -0
  160. package/dist/runtime/src/tools.d.ts +35 -0
  161. package/dist/runtime/src/tools.js +94 -0
  162. package/ios/CoreAgentTransport.swift +14 -0
  163. package/ios/CoreDeliveryTransport.swift +58 -0
  164. package/ios/CoreNativePal.swift +98 -0
  165. package/ios/CorePlatformTransport.swift +44 -0
  166. package/ios/CoreWireDispatch.swift +122 -0
  167. package/ios/CoreWireSupport.swift +286 -0
  168. package/ios/CrocheRuntimeBridge.swift +34 -994
  169. package/ios/ProjectPal.swift +49 -0
  170. package/ios/RNCrocheRuntime.mm +18 -201
  171. package/ios/vendor/CrocheRuntimeSDK/AppBuildFacts.swift +112 -0
  172. package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
  173. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +60 -0
  174. package/ios/vendor/CrocheRuntimeSDK/DirectHTTP.swift +258 -0
  175. package/ios/vendor/CrocheRuntimeSDK/Effects.swift +17 -17
  176. package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
  177. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +26 -157
  178. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +672 -0
  179. package/ios/vendor/CrocheRuntimeSDK/Host.swift +34 -371
  180. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +410 -0
  181. package/ios/vendor/CrocheRuntimeSDK/Images.swift +10 -9
  182. package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
  183. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +30 -14
  184. package/ios/vendor/CrocheRuntimeSDK/Offload.swift +24 -0
  185. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +1 -155
  186. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +33 -59
  187. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +289 -0
  188. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +302 -0
  189. package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
  190. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +281 -0
  191. package/ios/vendor/CrocheRuntimeSDK/Project.swift +4 -269
  192. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +24 -461
  193. package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
  194. package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
  195. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +248 -0
  196. package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
  197. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +33 -0
  198. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +170 -0
  199. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +313 -0
  200. package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
  201. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +37 -0
  202. package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
  203. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +346 -0
  204. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +89 -0
  205. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +165 -0
  206. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +100 -0
  207. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +278 -0
  208. package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
  209. package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
  210. package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
  211. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +23 -269
  212. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +163 -116
  213. package/ios/vendor/CrocheRuntimeSDK/Truncate.swift +12 -0
  214. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +4712 -2469
  215. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +899 -608
  216. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  217. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +899 -608
  218. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  219. package/package.json +18 -8
  220. package/scripts/README.md +11 -0
  221. package/scripts/build-shared.mjs +46 -0
  222. package/scripts/build.mjs +11 -0
  223. package/scripts/check-swift-vendor-modules.sh +15 -0
  224. package/scripts/vendor-native.sh +8 -6
  225. package/src/NativeCrocheRuntime.ts +12 -159
  226. package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +0 -25
  227. package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +0 -17
  228. package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +0 -14
  229. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
  230. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
  231. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -110
  232. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +0 -178
  233. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -173
  234. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +0 -79
  235. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
  236. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +0 -46
  237. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
  238. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
  239. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -227
  240. package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
  241. package/ios/vendor/CrocheRuntimeSDK/Control.swift +0 -192
  242. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -453
  243. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -38
  244. package/src/index.ts +0 -664
  245. package/src/project-types.ts +0 -35
  246. package/src/project.ts +0 -434
  247. package/src/protocol.ts +0 -28
  248. package/src/types.ts +0 -9
@@ -1,87 +0,0 @@
1
- package dev.croche
2
-
3
- import java.io.File
4
- import java.io.FileOutputStream
5
- import java.io.RandomAccessFile
6
- import java.nio.channels.FileLock
7
- import java.nio.file.Files
8
- import java.nio.file.StandardCopyOption.*
9
-
10
- /** Android supplies filesDir at app startup. A plain JVM has no implicit install directory. */
11
- internal fun defaultProjectDirectory(): File? = try {
12
- Class.forName("dev.croche.android.CrocheProjectRecordProvider")
13
- .getMethod("directory").invoke(null) as? File
14
- } catch (_: ClassNotFoundException) { null }
15
-
16
- /** Explicit locations are allowed only on hosts without an app-private default. */
17
- internal fun projectRecordDirectory(option: File?, default: File?): File? {
18
- if (option != null && default != null)
19
- throw CrocheException("invalid_configuration", "this platform keeps the project record in the app's private storage")
20
- return option ?: default
21
- }
22
-
23
- internal fun isProjectKey(key: String) = key.startsWith("croche.project.")
24
-
25
- /** Raw project records, never the app's RuntimeStorage or its snapshot/entry namespace. */
26
- internal class ProjectRecords(private val directory: () -> File?) {
27
- private data class Ownership(val file: RandomAccessFile, val lock: FileLock)
28
- private val owned = mutableMapOf<String, Ownership>()
29
-
30
- private fun record(key: String): File {
31
- if (!Regex("croche\\.project\\.v1\\.[0-9a-f]{64}").matches(key))
32
- throw CrocheException("storage_error", "Invalid project record key")
33
- val location = directory() ?: throw CrocheException("storage_error",
34
- "Project records require projectDirectory on this platform; no app-private default exists")
35
- return File(location, "$key.json")
36
- }
37
-
38
- @Synchronized fun acquire(key: String) {
39
- val target = record(key)
40
- if (key in owned) throw CrocheException("store_busy", "Project record is already owned")
41
- target.parentFile.mkdirs()
42
- val opened = RandomAccessFile(File(target.path + ".lock"), "rw")
43
- try {
44
- val lock = opened.channel.tryLock() ?: throw CrocheException("store_busy", "Project record is already owned")
45
- owned[key] = Ownership(opened, lock)
46
- } catch (failure: Exception) {
47
- opened.close()
48
- if (failure is CrocheException) throw failure
49
- if (failure is java.nio.channels.OverlappingFileLockException)
50
- throw CrocheException("store_busy", "Project record is already owned")
51
- throw CrocheException("storage_error", "Could not lock the project record")
52
- }
53
- }
54
-
55
- @Synchronized fun read(key: String): String? {
56
- requireOwnership(key)
57
- val target = record(key)
58
- return if (target.exists()) target.readText(Charsets.UTF_8) else null
59
- }
60
-
61
- @Synchronized fun write(key: String, value: String) {
62
- requireOwnership(key)
63
- val target = record(key)
64
- val temporary = File.createTempFile("croche-project-", ".tmp", target.parentFile)
65
- try {
66
- FileOutputStream(temporary).use { output ->
67
- output.write(value.toByteArray(Charsets.UTF_8)); output.fd.sync()
68
- }
69
- Files.move(temporary.toPath(), target.toPath(), ATOMIC_MOVE, REPLACE_EXISTING)
70
- } finally { temporary.delete() }
71
- }
72
-
73
- @Synchronized fun remove(key: String) {
74
- requireOwnership(key)
75
- Files.deleteIfExists(record(key).toPath())
76
- }
77
-
78
- private fun requireOwnership(key: String) {
79
- if (key !in owned) throw CrocheException("storage_error", "Project record is not locked")
80
- }
81
-
82
- @Synchronized fun release(key: String) {
83
- val ownership = owned.remove(key) ?: return
84
- try { ownership.lock.release() } finally { ownership.file.close() }
85
- }
86
- @Synchronized fun releaseAll() { owned.keys.toList().forEach(::release) }
87
- }
@@ -1,181 +0,0 @@
1
- package dev.croche
2
-
3
- import com.google.gson.*
4
- import java.io.File
5
- import java.io.FileOutputStream
6
- import java.io.RandomAccessFile
7
- import java.nio.channels.FileLock
8
- import java.nio.file.Files
9
- import java.nio.file.StandardCopyOption.*
10
-
11
- /** Storage owns its namespace exclusively until release; save must be atomic and never
12
- * interrupted by Runtime cancellation. Snapshots contain private Runtime credentials. */
13
- interface RuntimeStorage {
14
- fun acquire()
15
- fun load(): JsonElement
16
- fun save(state: JsonElement)
17
- /** Delete the snapshot for real; an absent snapshot is already removed. */
18
- fun remove()
19
- fun release()
20
- }
21
-
22
- /** A RuntimeStorage that also keeps named entries beside the snapshot, such as `held`: the sends
23
- * waiting behind a running turn (F19). Each entry is replaced atomically and independently of the
24
- * snapshot, under the same ownership. `load(entry)` returns JsonNull for an entry never saved.
25
- * A storage without entries still works; the Runtime then cannot keep sends that arrive while a
26
- * turn runs, and refuses them (`storage_error`) rather than overwrite the snapshot. */
27
- interface KeyedRuntimeStorage : RuntimeStorage {
28
- fun load(entry: String): JsonElement
29
- fun save(entry: String, value: JsonElement)
30
- /** Delete this entry for real; an absent entry is already removed. */
31
- fun remove(entry: String)
32
- }
33
-
34
- /** A RuntimeStorage that also keeps the turn archive (F20.6): every finished turn in full, as JSON
35
- * lines in entries named `archive<NNNN>` (100 turns each) beside the snapshot. Opt-in and separate
36
- * from [KeyedRuntimeStorage]: a storage without it keeps no archive, typed (`archive_unavailable`),
37
- * and everything else works. The Runtime keeps the rules (segments, the byte bound, the last record
38
- * per turn); the storage keeps lines:
39
- * - `appendLine` writes a newline first when the entry does not end with one, and is durable when
40
- * it returns;
41
- * - `readLines` returns complete lines only: a torn last line (a crash mid-append) is not one;
42
- * - `replaceLines` is atomic: after a crash the entry holds every old line or every new one, never
43
- * a mix and never none; an empty list deletes the entry;
44
- * - `remove` deletes for real; an absent entry is not an error;
45
- * - `entries` lists the entries whose names start with `prefix`, with their sizes in bytes. */
46
- interface ArchiveRuntimeStorage : RuntimeStorage {
47
- fun appendLine(entry: String, line: String)
48
- fun readLines(entry: String): List<String>
49
- fun replaceLines(entry: String, lines: List<String>)
50
- fun remove(entry: String)
51
- fun entries(prefix: String): Map<String, Long>
52
- }
53
-
54
- private val ENTRY = Regex("[a-z0-9]+")
55
- /** Line entries: the archive's segments, and the message log's (S1). */
56
- private val SEGMENT = Regex("archive[0-9]{4}|log[0-9]{6}")
57
- internal fun isLineStorageEntry(entry: String) = SEGMENT.matches(entry)
58
- private val STALE = Regex("(archive[0-9]{4}|log[0-9]{6})\\.tmp-[0-9a-f-]+")
59
-
60
- /** Application-private file storage. Java NIO file operations require Android API 26+. Entries are
61
- * sidecar files beside the snapshot (`<file>.held`), each replaced atomically. The turn archive is
62
- * sidecars too (`<file>.archive0001`, JSON lines), under the same lock; a segment is rewritten to
63
- * `<file>.archive0001.tmp-<nonce>` and moved over it, and stale temporaries are deleted when the
64
- * storage is acquired. */
65
- class FileRuntimeStorage(private val file: File) : KeyedRuntimeStorage, ArchiveRuntimeStorage {
66
- private var handle: RandomAccessFile? = null
67
- private var lock: FileLock? = null
68
- /** Runs after a segment's temporary is complete and before the move (tests inject a crash). */
69
- internal var beforeCommit: ((File) -> Unit)? = null
70
- @Synchronized override fun acquire() {
71
- if (handle != null) throw CrocheException("store_busy", "Storage is already owned")
72
- file.absoluteFile.parentFile.mkdirs()
73
- val opened = RandomAccessFile(File(file.path + ".lock"), "rw")
74
- try {
75
- val acquired = opened.channel.tryLock() ?: throw CrocheException("store_busy", "Storage is already owned")
76
- handle = opened; lock = acquired
77
- } catch (error: Exception) {
78
- opened.close(); throw CrocheException("store_busy", "Could not acquire storage ownership")
79
- }
80
- removeStaleTemporaries()
81
- }
82
- @Synchronized override fun load(): JsonElement {
83
- check(handle != null) { "Storage is not owned" }
84
- if (!file.exists()) return JsonNull.INSTANCE
85
- val saved = JsonParser.parseString(file.readText(Charsets.UTF_8))
86
- if (!saved.isJsonObject) throw CrocheException("storage_error", "Existing Runtime snapshot must be an object")
87
- return saved
88
- }
89
- @Synchronized override fun save(state: JsonElement) {
90
- check(handle != null) { "Storage is not owned" }
91
- replace(file, state)
92
- }
93
- @Synchronized override fun load(entry: String): JsonElement {
94
- val sidecar = sidecar(entry)
95
- if (!sidecar.exists()) return JsonNull.INSTANCE
96
- return JsonParser.parseString(sidecar.readText(Charsets.UTF_8))
97
- }
98
- @Synchronized override fun save(entry: String, value: JsonElement) = replace(sidecar(entry), value)
99
- private fun sidecar(entry: String): File {
100
- check(handle != null) { "Storage is not owned" }
101
- if (!Regex("[a-z0-9]+").matches(entry)) throw CrocheException("storage_error", "Invalid storage entry")
102
- return File(file.path + "." + entry)
103
- }
104
- private fun replace(target: File, value: JsonElement) {
105
- val temporary = File.createTempFile("croche-", ".tmp", target.absoluteFile.parentFile)
106
- try {
107
- FileOutputStream(temporary).use { output ->
108
- output.write(value.toString().toByteArray(Charsets.UTF_8)); output.fd.sync()
109
- }
110
- Files.move(temporary.toPath(), target.toPath(), ATOMIC_MOVE, REPLACE_EXISTING)
111
- } finally { temporary.delete() }
112
- }
113
- // The turn archive (F20.6)
114
- @Synchronized override fun appendLine(entry: String, line: String) {
115
- val target = segment(entry)
116
- if (line.contains('\n')) throw CrocheException("storage_error", "An archive line holds no newline")
117
- RandomAccessFile(target, "rw").use { output ->
118
- val size = output.length()
119
- val bytes = java.io.ByteArrayOutputStream()
120
- if (size > 0) {
121
- output.seek(size - 1)
122
- if (output.read() != '\n'.code) bytes.write('\n'.code) // a torn line never swallows this record
123
- }
124
- bytes.write(line.toByteArray(Charsets.UTF_8)); bytes.write('\n'.code)
125
- output.seek(size)
126
- output.write(bytes.toByteArray())
127
- output.fd.sync()
128
- }
129
- }
130
- @Synchronized override fun readLines(entry: String): List<String> {
131
- val target = segment(entry)
132
- if (!target.exists()) return emptyList()
133
- val lines = target.readText(Charsets.UTF_8).split('\n')
134
- // The piece after the last newline: a torn line, or "" when the file ends whole.
135
- return lines.dropLast(1).filter { it.isNotEmpty() }
136
- }
137
- @Synchronized override fun replaceLines(entry: String, lines: List<String>) {
138
- val target = segment(entry)
139
- if (lines.isEmpty()) { Files.deleteIfExists(target.toPath()); return }
140
- if (lines.any { it.contains('\n') }) throw CrocheException("storage_error", "An archive line holds no newline")
141
- // '.' and '-' are outside the entry rule: a temporary is never an entry, `held` or `lock`.
142
- val temporary = File(target.path + ".tmp-" + java.util.UUID.randomUUID().toString())
143
- try {
144
- FileOutputStream(temporary).use { output ->
145
- output.write(lines.joinToString("") { it + "\n" }.toByteArray(Charsets.UTF_8)); output.fd.sync()
146
- }
147
- beforeCommit?.invoke(temporary)
148
- Files.move(temporary.toPath(), target.toPath(), ATOMIC_MOVE, REPLACE_EXISTING)
149
- } finally { temporary.delete() }
150
- }
151
- @Synchronized override fun remove() {
152
- check(handle != null) { "Storage is not owned" }
153
- Files.deleteIfExists(file.toPath())
154
- }
155
- @Synchronized override fun remove(entry: String) { Files.deleteIfExists(sidecar(entry).toPath()) }
156
- @Synchronized override fun entries(prefix: String): Map<String, Long> {
157
- check(handle != null) { "Storage is not owned" }
158
- return siblings().filter { (name, _) -> ENTRY.matches(name) && name.startsWith(prefix) }
159
- .associate { (name, path) -> name to path.length() }
160
- }
161
- /** The archive's entries are segments only (`archive` and four digits): never the snapshot's
162
- * own sidecars (`held`) or its lock file (`lock`). */
163
- private fun segment(entry: String): File {
164
- if (!SEGMENT.matches(entry)) throw CrocheException("storage_error", "Invalid archive entry")
165
- return sidecar(entry)
166
- }
167
- /** The files beside the snapshot, `<file>.<suffix>`, as (suffix, file). */
168
- private fun siblings(): List<Pair<String, File>> {
169
- val directory = file.absoluteFile.parentFile ?: return emptyList()
170
- val base = file.name + "."
171
- return (directory.listFiles() ?: emptyArray()).filter { it.name.startsWith(base) }
172
- .map { it.name.substring(base.length) to it }
173
- }
174
- /** Segment rewrites a crash interrupted (`archive<NNNN>.tmp-<nonce>`): deleted by the owner. */
175
- private fun removeStaleTemporaries() {
176
- for ((suffix, path) in siblings()) if (STALE.matches(suffix)) path.delete()
177
- }
178
- @Synchronized override fun release() {
179
- try { lock?.release() } finally { lock = null; handle?.close(); handle = null }
180
- }
181
- }
@@ -1,227 +0,0 @@
1
- package dev.croche
2
-
3
- import com.google.gson.JsonArray
4
- import com.google.gson.JsonObject
5
- import kotlinx.coroutines.*
6
- import kotlinx.coroutines.flow.Flow
7
- import kotlinx.coroutines.flow.flow
8
-
9
- /** Proposed SDK adapter only, not a Rust ABI. Core owns all projection and durable reads. */
10
- internal interface CoreStreamPort {
11
- val logId: String
12
- val state: RuntimeEvent.State
13
- fun observe(event: (RuntimeEvent) -> Unit, end: (Throwable?) -> Unit): AutoCloseable
14
- fun select(initialMessages: Int?, after: Cursor?, event: (RuntimeEvent) -> Unit): Projection
15
- suspend fun send(input: JsonObject, options: SendOptions): Receipt
16
- suspend fun readOutcome(id: String, fromSeq: Long, captured: (CapturedOutcome) -> Unit): RetainedEnds
17
- suspend fun cancel(id: String)
18
- suspend fun clearHistory()
19
- fun setTools(tools: JsonArray, handlers: Map<String, ToolHandler>)
20
- fun close()
21
- interface Projection : AutoCloseable {
22
- /** Joins Core's synchronous listener, not buffered Flow/UI consumers. A synchronous
23
- * close from that listener itself fences without waiting for its own stack.
24
- * An app callback that waits for work on the closer's thread deadlocks under any
25
- * wait-for-callback fence. */
26
- override fun close()
27
- suspend fun history(before: Long?, limit: Int)
28
- }
29
- }
30
- /** Typed fake-port failure; the future native adapter supplies the flag, never a code heuristic. */
31
- internal class CoreStreamFailure(val code: String, override val message: String, val poisoned: Boolean) : RuntimeException(message)
32
- internal fun streamEnd(cause: Throwable?): RuntimeEvent.StreamError {
33
- val typed = cause as? CoreStreamFailure
34
- val code = typed?.code ?: (cause as? CrocheException)?.code ?: "closed"
35
- return RuntimeEvent.StreamError(code, cause?.message ?: "Runtime is closed", typed?.poisoned ?: false)
36
- }
37
- internal data class CapturedOutcome(val head: Long, val floor: Long, val status: InputStatus, val idle: Boolean)
38
- internal data class RetainedEnds(val messages: List<RuntimeEvent.MessageEnd>, val gap: Boolean = false)
39
- internal fun InputStatus.terminal(): Boolean = this in setOf(InputStatus.ANSWERED, InputStatus.NO_REPLY,
40
- InputStatus.FAILED, InputStatus.CANCELLED, InputStatus.SETTLED_BEFORE_UPGRADE)
41
- internal fun maintenanceInterval(value: Long): Long = value.coerceAtLeast(1000)
42
-
43
- /** No app code executes on the canonical callback stack. All bookkeeping is monitor-protected. */
44
- internal class StreamHub(private val port: CoreStreamPort) : AutoCloseable {
45
- private val lock = Any()
46
- private val waiters = linkedSetOf<Waiter>()
47
- private var ended = false
48
- private var app: AppStreamBranch? = null
49
- private var projection: CoreStreamPort.Projection? = null
50
- private val observation = port.observe({ event ->
51
- synchronized(lock) { waiters.toList().forEach { it.event(event) } }
52
- }, { cause -> end(cause) })
53
- val logId get() = port.logId
54
- val state get() = port.state
55
-
56
- internal inner class Collection(private val branch: AppStreamBranch, private val selected: CoreStreamPort.Projection?) {
57
- suspend fun deliver(emit: suspend (RuntimeEvent) -> Unit) {
58
- try { branch.deliver(emit) } finally { detach() }
59
- }
60
- fun close(last: RuntimeEvent? = RuntimeEvent.StreamError("closed", "Subscription is closed", false)) {
61
- branch.end(last)
62
- selected?.close()
63
- }
64
- private fun detach() {
65
- branch.close()
66
- selected?.close()
67
- synchronized(lock) { if (app === branch) { app = null; projection = null } }
68
- }
69
- suspend fun history(before: Long?, limit: Int) {
70
- if (limit !in 1..256) throw CrocheException("invalid_configuration", "history limit must be 1..256")
71
- val current = synchronized(lock) { if (app === branch && !branch.isEnded) selected else null }
72
- ?: throw CrocheException("invalid_configuration", "history requires an active subscription")
73
- current.history(before, limit)
74
- }
75
- }
76
- internal fun openCollection(initialMessages: Int?, after: Cursor?): Collection {
77
- val branch = AppStreamBranch()
78
- val selected = synchronized(lock) {
79
- if (ended) null else {
80
- projection?.close()
81
- projection = null
82
- app?.end(RuntimeEvent.Replaced)
83
- app = branch
84
- if ((initialMessages != null && after != null) || (initialMessages != null && initialMessages !in 0..256)) {
85
- branch.push(RuntimeEvent.StreamError("invalid_configuration", "Select initialMessages in 0..256 or after, not both", false))
86
- null
87
- } else try {
88
- port.select(initialMessages, after, branch::push).also { projection = it }
89
- } catch (failure: Exception) {
90
- branch.end(streamEnd(failure))
91
- null
92
- }
93
- }
94
- }
95
- if (selected == null && !branch.isEnded) branch.end(RuntimeEvent.StreamError("closed", "Runtime is closed", false))
96
- return Collection(branch, selected)
97
- }
98
- fun events(initialMessages: Int? = 50, after: Cursor? = null): Flow<RuntimeEvent> = flow {
99
- openCollection(initialMessages, after).deliver { emit(it) }
100
- }
101
-
102
- suspend fun send(input: SendInput, options: SendOptions): Receipt {
103
- currentCoroutineContext().ensureActive()
104
- synchronized(lock) { if (ended) throw CrocheException("closed", "Runtime is closed") }
105
- return port.send(input.encoded(options), options.owned())
106
- }
107
-
108
- suspend fun request(input: SendInput, options: SendOptions, wait: RequestWait?): RequestResult = coroutineScope {
109
- ensureActive()
110
- val owned = input.owned()
111
- val waiter = Waiter(owned.id, wait)
112
- synchronized(lock) {
113
- if (ended) throw CrocheException("closed", "Runtime is closed")
114
- waiters.add(waiter) // Before send: immediate canonical progress must not outrun registration.
115
- }
116
- val read = launch(start = CoroutineStart.UNDISPATCHED) {
117
- try {
118
- val encoded = owned.encoded(options)
119
- val receipt = port.send(encoded, options.owned())
120
- val proceed = synchronized(lock) {
121
- waiter.receipt = receipt
122
- // Terminal same-id retries emit no new input event. Seed before idle
123
- // overtakes capture, without regressing an already observed disposition.
124
- if (waiter.status == null || (waiter.status?.terminal() != true && receipt.status.terminal())) {
125
- waiter.status = receipt.status
126
- }
127
- if (waiter.lost) { waiter.failLost(); false } else true
128
- }
129
- if (!proceed) return@launch
130
- if (receipt.seq == null) {
131
- waiter.result.complete(RequestResult(receipt.id, receipt.status, emptyList(), false, true))
132
- return@launch
133
- }
134
- var captured = false
135
- val retained = port.readOutcome(receipt.id, receipt.seq) { snapshot ->
136
- synchronized(lock) {
137
- captured = true
138
- if (waiter.status?.terminal() != true) waiter.status = snapshot.status
139
- waiter.gap = receipt.seq < snapshot.floor
140
- if (completion(waiter.status, snapshot.idle, waiter.wait)) waiter.complete = true
141
- }
142
- }
143
- check(captured) { "Core outcome read omitted its ordered capture" }
144
- synchronized(lock) {
145
- waiter.gap = waiter.gap || retained.gap
146
- retained.messages.filter { receipt.id in it.causedBy }.forEach { waiter.add(it) }
147
- waiter.reading = false
148
- waiter.finish()
149
- }
150
- } catch (cancelled: CancellationException) {
151
- throw cancelled
152
- } catch (failure: Exception) {
153
- synchronized(lock) {
154
- waiter.result.completeExceptionally(if (waiter.receipt != null)
155
- CrocheException("observation_lost", "Observation ended after acceptance", waiter.receipt) else failure)
156
- }
157
- }
158
- }
159
- try { waiter.result.await() }
160
- finally {
161
- synchronized(lock) { waiters.remove(waiter) }
162
- read.cancel() // Stops observation/storage wait only; never calls port.cancel.
163
- }
164
- }
165
-
166
- // Keel #361 6071161214: Both forms require an attached stream; pin its projection generation.
167
- suspend fun history(before: Long?, limit: Int) {
168
- if (limit !in 1..256) throw CrocheException("invalid_configuration", "history limit must be 1..256")
169
- val selected = synchronized(lock) { projection }
170
- ?: throw CrocheException("invalid_configuration", "history requires an app collection")
171
- selected.history(before, limit)
172
- }
173
- suspend fun cancel(id: String) = port.cancel(id)
174
- suspend fun clearHistory() = port.clearHistory()
175
- fun setTools(tools: JsonArray, handlers: Map<String, ToolHandler>) = port.setTools(tools, handlers)
176
- override fun close() { try { port.close() } finally { end(); observation.close() } }
177
- private fun end(cause: Throwable? = null) = synchronized(lock) {
178
- if (!ended) {
179
- ended = true
180
- projection?.close()
181
- val terminal = streamEnd(cause)
182
- app?.end(terminal)
183
- waiters.toList().forEach { it.lost = true; if (it.receipt != null) it.failLost() }
184
- }
185
- }
186
-
187
- // OPEN(§18.24.D): Default stays S2 terminal-plus-idle until Atlas rules on consuming-unit
188
- // evidence. IDLE explicitly selects the same behavior; no unit-end heuristic or pending.
189
- // One predicate is the replacement point; do not infer a unit end from state/turn/answered.
190
- private fun completion(status: InputStatus?, idle: Boolean, wait: RequestWait?): Boolean = when (wait) {
191
- null -> status?.terminal() == true && idle
192
- RequestWait.IDLE -> status?.terminal() == true && idle
193
- }
194
-
195
- private inner class Waiter(val id: String, val wait: RequestWait?) {
196
- val result = CompletableDeferred<RequestResult>()
197
- var receipt: Receipt? = null
198
- var status: InputStatus? = null
199
- var complete = false
200
- var reading = true
201
- var lost = false
202
- var gap = false
203
- val messages = linkedMapOf<Pair<String, Long>, RuntimeEvent.MessageEnd>()
204
- fun add(event: RuntimeEvent.MessageEnd) { messages[event.id to event.seq] = event.owned() as RuntimeEvent.MessageEnd }
205
- fun event(event: RuntimeEvent) {
206
- if (complete || result.isCompleted) return
207
- when (event) {
208
- is RuntimeEvent.Input -> if (event.id == id && status?.terminal() != true) status = event.status
209
- is RuntimeEvent.MessageEnd -> if (id in event.causedBy) add(event)
210
- is RuntimeEvent.State -> if (completion(status, event.status == AgentStatus.IDLE, wait)) complete = true
211
- else -> Unit
212
- }
213
- finish()
214
- }
215
- fun finish() {
216
- val accepted = receipt ?: return
217
- val disposition = status ?: return
218
- if (!reading && complete) result.complete(RequestResult(accepted.id, disposition,
219
- messages.values.sortedBy { it.seq }, gap, false))
220
- }
221
- fun failLost() { result.completeExceptionally(CrocheException("observation_lost", "Reopen and retry the same id and input", receipt)) }
222
- }
223
- }
224
-
225
- internal fun SendInput.owned() = copy(images = images.toList(), context = context?.deepCopy(),
226
- inputs = inputs.map { it.copy(images = it.images.toList()) })
227
- internal fun SendOptions.owned() = copy(responseFormat = responseFormat?.deepCopy())
@@ -1,59 +0,0 @@
1
- import Foundation
2
- #if canImport(BackgroundTasks) && os(iOS)
3
- import BackgroundTasks
4
-
5
- /// The agent's scheduled notes on iOS while the app is not running: one `BGAppRefreshTaskRequest`
6
- /// at the earliest note (`earliestBeginDate`), replaced at each change and withdrawn when none is
7
- /// pending. iOS decides when it runs, possibly late or never for a rarely used app; the next
8
- /// foreground delivers what it missed. No permission prompt, no notification.
9
- ///
10
- /// App setup (Xcode): add `identifier` to `BGTaskSchedulerPermittedIdentifiers` in Info.plist,
11
- /// enable Background Modes > Background fetch, and call `registerHandler` before
12
- /// `application(_:didFinishLaunchingWithOptions:)` returns. Without the Info.plist entry a request
13
- /// is refused, and the Runtime reports `schedule.degraded` with reason `not_configured`.
14
- public final class AppRefreshScheduler: RuntimeScheduler, @unchecked Sendable {
15
- public let identifier: String
16
- public init(identifier: String) { self.identifier = identifier }
17
-
18
- public func schedule(earliest: Date) throws {
19
- let request = BGAppRefreshTaskRequest(identifier: identifier)
20
- request.earliestBeginDate = earliest
21
- do { try BGTaskScheduler.shared.submit(request) }
22
- catch let error as BGTaskScheduler.Error where error.code == .notPermitted {
23
- throw CrocheError("not_configured", "Add \(identifier) to BGTaskSchedulerPermittedIdentifiers and enable Background fetch")
24
- } catch let error as BGTaskScheduler.Error where error.code == .unavailable {
25
- throw CrocheError("background_unavailable", "Background App Refresh is off or unavailable here")
26
- } catch {
27
- throw CrocheError("schedule_failed", "BGTaskScheduler refused the request")
28
- }
29
- }
30
- public func cancel() { BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: identifier) }
31
-
32
- /// One open Runtime per identifier: a run delivers through the one Runtime its identifier
33
- /// names (Atlas, #323 P1-2). This scheduler object is no exception: `create` attaches once per
34
- /// Runtime, so a second attach while the identifier is held is refused, whoever holds it
35
- /// (Atlas, #323 at dc38bf0). Close-and-reuse stays valid.
36
- public func attach() throws { try Self.claims.claim(identifier, by: self) }
37
- public func detach() { Self.claims.release(identifier, by: self) }
38
- private static let claims = SchedulerClaims(what: "task identifier")
39
-
40
- /// Registers what runs when iOS launches the task: `runtime` returns the app's Runtime
41
- /// (opening it when the app was launched for this task), whose `deliverDue()` then runs. When
42
- /// iOS ends the background time first, the delivery turn is cancelled and its notes stay
43
- /// pending. Call once, before `application(_:didFinishLaunchingWithOptions:)` returns.
44
- @discardableResult
45
- public func registerHandler(runtime: @escaping @Sendable () async throws -> CrocheRuntime) -> Bool {
46
- BGTaskScheduler.shared.register(forTaskWithIdentifier: identifier, using: nil) { task in
47
- let granted = GrantedTask(task)
48
- let delivery = BackgroundDelivery(open: runtime)
49
- task.expirationHandler = { delivery.expire() }
50
- delivery.start { success in granted.task.setTaskCompleted(success: success) }
51
- }
52
- }
53
- }
54
-
55
- private final class GrantedTask: @unchecked Sendable {
56
- let task: BGTask
57
- init(_ task: BGTask) { self.task = task }
58
- }
59
- #endif