@h1r-ai/croche-react-native 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +32 -4
- package/THIRD-PARTY-NOTICES +899 -6
- package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +4 -3
- package/android/src/main/AndroidManifest.xml +0 -5
- package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +33 -8
- package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +139 -5
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +5 -2
- package/android/src/main/java/dev/croche/reactnative/NativePal.kt +23 -6
- package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +28 -6
- package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +4 -11
- package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
- package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
- package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +19 -4
- package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +2 -2
- package/android/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
- package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +5 -3
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +4 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +11 -11
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +11 -16
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +3 -3
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +45 -10
- package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +0 -3
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +1 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +9 -23
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +11 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +83 -20
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +54 -8
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +19 -360
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +79 -10
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +8 -5
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +8 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +426 -33
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +1 -351
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +15 -29
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +196 -10
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +86 -3
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +33 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +1 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +68 -4
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +3403 -6894
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +89 -18
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +1 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +2 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +3 -3
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +17 -18
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +12 -14
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +36 -6
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +21 -6
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +16 -7
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +25 -4
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -0
- package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
- package/croche-react-native.podspec +1 -0
- package/dist/react-native/src/core-native.d.ts +3 -0
- package/dist/react-native/src/core-native.js +148 -25
- package/dist/react-native/src/core-wire.d.ts +20 -3
- package/dist/rn-shared-build.json +8 -8
- package/dist/runtime/src/adapters.d.ts +8 -0
- package/dist/runtime/src/adapters.js +29 -0
- package/dist/runtime/src/agent.d.ts +53 -5
- package/dist/runtime/src/agent.js +69 -7
- package/dist/runtime/src/app-api.d.ts +307 -19
- package/dist/runtime/src/cancel.d.ts +2 -2
- package/dist/runtime/src/cancel.js +7 -4
- package/dist/runtime/src/core/foreground.d.ts +3 -0
- package/dist/runtime/src/core/foreground.js +40 -0
- package/dist/runtime/src/core/port.d.ts +48 -35
- package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
- package/dist/runtime/src/core/wasm-owner.js +237 -0
- package/dist/runtime/src/croche.d.ts +64 -9
- package/dist/runtime/src/croche.js +78 -17
- package/dist/runtime/src/errors.d.ts +7 -0
- package/dist/runtime/src/errors.js +15 -1
- package/dist/runtime/src/generated/app-stream.d.ts +155 -1
- package/dist/runtime/src/generated/app-stream.js +7 -4
- package/dist/runtime/src/image-input.d.ts +5 -0
- package/dist/runtime/src/image-input.js +60 -0
- package/dist/runtime/src/index.d.ts +6 -0
- package/dist/runtime/src/index.js +5 -0
- package/dist/runtime/src/index.native.d.ts +1 -21
- package/dist/runtime/src/index.native.js +2 -8
- package/dist/runtime/src/native-adapter.d.ts +1 -1
- package/dist/runtime/src/native-adapter.js +10 -4
- package/dist/runtime/src/pal/host.d.ts +3 -3
- package/dist/runtime/src/pal/host.js +34 -9
- package/dist/runtime/src/pal/platform.d.ts +11 -6
- package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
- package/dist/runtime/src/pal/state-store-lock.js +2 -0
- package/dist/runtime/src/pal/state-store.d.ts +66 -0
- package/dist/runtime/src/pal/state-store.js +1 -0
- package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
- package/dist/runtime/src/pal/storage-version-contract.js +68 -0
- package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
- package/dist/runtime/src/pal/transactional-storage.js +124 -0
- package/dist/runtime/src/tools.d.ts +20 -4
- package/dist/runtime/src/tools.js +31 -7
- package/ios/CoreAgentTransport.swift +2 -2
- package/ios/CoreNativePal.swift +26 -21
- package/ios/CorePlatformTransport.swift +4 -4
- package/ios/CoreWireDispatch.swift +38 -8
- package/ios/CoreWireSupport.swift +179 -4
- package/ios/CrocheRuntimeBridge.swift +1 -1
- package/ios/ProjectPal.swift +15 -12
- package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
- package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +2 -6
- package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
- package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +1 -174
- package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +233 -4
- package/ios/vendor/CrocheRuntimeSDK/Host.swift +1 -399
- package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +3 -3
- package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
- package/ios/vendor/CrocheRuntimeSDK/JSON.swift +26 -10
- package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +0 -155
- package/ios/vendor/CrocheRuntimeSDK/Platform.swift +1 -27
- package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +8 -4
- package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +57 -21
- package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +96 -10
- package/ios/vendor/CrocheRuntimeSDK/Project.swift +3 -382
- package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +1 -412
- package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +86 -33
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +1 -1
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +12 -3
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +135 -56
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +17 -8
- package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +184 -15
- package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +31 -3
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +131 -61
- package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +10 -15
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +86 -17
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
- package/ios/vendor/CrocheRuntimeSDK/Storage.swift +3 -249
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +40 -8
- package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +1720 -3883
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +816 -1649
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +816 -1649
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +2 -2
- package/package.json +3 -3
- package/scripts/README.md +1 -1
- package/scripts/check-swift-vendor-modules.sh +15 -0
- package/scripts/vendor-native.sh +4 -3
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -113
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -201
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +0 -18
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -252
- package/dist/runtime/src/pal/codec.d.ts +0 -15
- package/dist/runtime/src/pal/codec.js +0 -52
- package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
- package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -496
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -44
|
@@ -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 CrocheError("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 CrocheError("storage_error", "Invalid project record key")
|
|
33
|
-
val location = directory() ?: throw CrocheError("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 CrocheError("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 CrocheError("store_busy", "Project record is already owned")
|
|
45
|
-
owned[key] = Ownership(opened, lock)
|
|
46
|
-
} catch (failure: Exception) {
|
|
47
|
-
opened.close()
|
|
48
|
-
if (failure is CrocheError) throw failure
|
|
49
|
-
if (failure is java.nio.channels.OverlappingFileLockException)
|
|
50
|
-
throw CrocheError("store_busy", "Project record is already owned")
|
|
51
|
-
throw CrocheError("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 CrocheError("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 CrocheError("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 CrocheError("store_busy", "Storage is already owned")
|
|
76
|
-
handle = opened; lock = acquired
|
|
77
|
-
} catch (error: Exception) {
|
|
78
|
-
opened.close(); throw CrocheError("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 CrocheError("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 CrocheError("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 CrocheError("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 CrocheError("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 CrocheError("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,18 +0,0 @@
|
|
|
1
|
-
package dev.croche
|
|
2
|
-
|
|
3
|
-
/** ARCHITECTURE §2a: app storage reports facts only; Core owns keys, framing and error policy. */
|
|
4
|
-
interface StoragePal {
|
|
5
|
-
suspend fun read(key: String): String?
|
|
6
|
-
suspend fun write(key: String, value: String)
|
|
7
|
-
suspend fun remove(key: String)
|
|
8
|
-
suspend fun list(prefix: String): List<String>
|
|
9
|
-
suspend fun lock(name: String): LockOutcome
|
|
10
|
-
suspend fun unlock(name: String)
|
|
11
|
-
val secrets: SecretsPal
|
|
12
|
-
}
|
|
13
|
-
interface SecretsPal {
|
|
14
|
-
suspend fun read(key: String): String?
|
|
15
|
-
suspend fun write(key: String, value: String)
|
|
16
|
-
suspend fun remove(key: String)
|
|
17
|
-
}
|
|
18
|
-
enum class LockOutcome { ACQUIRED, HELD }
|
|
@@ -1,252 +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
|
-
/** Byte images need Core's reserved entry and a native PAL; JSON-only ports refuse them. */
|
|
17
|
-
suspend fun sendWithImages(input: SendInput, options: SendOptions): Receipt =
|
|
18
|
-
throw CrocheError("image_unsupported", "The image could not be prepared.")
|
|
19
|
-
suspend fun readOutcome(id: String, fromSeq: Long, captured: (CapturedOutcome) -> Unit): RetainedEnds
|
|
20
|
-
suspend fun cancel(id: String)
|
|
21
|
-
suspend fun clearHistory()
|
|
22
|
-
fun setTools(tools: JsonArray, handlers: Map<String, ToolHandler>)
|
|
23
|
-
fun close()
|
|
24
|
-
interface Projection : AutoCloseable {
|
|
25
|
-
/** Joins Core's synchronous listener, not buffered Flow/UI consumers. A synchronous
|
|
26
|
-
* close from that listener itself fences without waiting for its own stack.
|
|
27
|
-
* An app callback that waits for work on the closer's thread deadlocks under any
|
|
28
|
-
* wait-for-callback fence. */
|
|
29
|
-
override fun close()
|
|
30
|
-
suspend fun history(before: Long?, limit: Int)
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
/** Typed fake-port failure; the future native adapter supplies the flag, never a code heuristic. */
|
|
34
|
-
internal class CoreStreamFailure(val code: String, override val message: String, val poisoned: Boolean) : RuntimeException(message)
|
|
35
|
-
internal fun streamEnd(cause: Throwable?): RuntimeEvent.StreamError {
|
|
36
|
-
val typed = cause as? CoreStreamFailure
|
|
37
|
-
val code = typed?.code ?: (cause as? CrocheError)?.code ?: "closed"
|
|
38
|
-
return RuntimeEvent.StreamError(code, cause?.message ?: "Runtime is closed", typed?.poisoned ?: false)
|
|
39
|
-
}
|
|
40
|
-
internal data class CapturedOutcome(val head: Long, val floor: Long, val status: InputStatus, val idle: Boolean)
|
|
41
|
-
internal data class RetainedEnds(val messages: List<RuntimeEvent.MessageEnd>, val gap: Boolean = false)
|
|
42
|
-
internal fun InputStatus.terminal(): Boolean = this in setOf(InputStatus.ANSWERED, InputStatus.NO_REPLY,
|
|
43
|
-
InputStatus.FAILED, InputStatus.CANCELLED, InputStatus.SETTLED_BEFORE_UPGRADE)
|
|
44
|
-
internal fun maintenanceInterval(value: Long): Long = value.coerceAtLeast(1000)
|
|
45
|
-
|
|
46
|
-
/** No app code executes on the canonical callback stack. All bookkeeping is monitor-protected. */
|
|
47
|
-
internal class StreamHub(private val port: CoreStreamPort) : AutoCloseable {
|
|
48
|
-
private val lock = Any()
|
|
49
|
-
private val waiters = linkedSetOf<Waiter>()
|
|
50
|
-
private var ended = false
|
|
51
|
-
private var app: AppStreamBranch? = null
|
|
52
|
-
private var projection: CoreStreamPort.Projection? = null
|
|
53
|
-
private val observation = port.observe({ event ->
|
|
54
|
-
synchronized(lock) { waiters.toList().forEach { it.event(event) } }
|
|
55
|
-
}, { cause -> end(cause) })
|
|
56
|
-
val logId get() = port.logId
|
|
57
|
-
val state get() = port.state
|
|
58
|
-
|
|
59
|
-
internal inner class Collection(private val branch: AppStreamBranch, private val selected: CoreStreamPort.Projection?) {
|
|
60
|
-
suspend fun deliver(emit: suspend (RuntimeEvent) -> Unit) {
|
|
61
|
-
try { branch.deliver(emit) } finally { detach() }
|
|
62
|
-
}
|
|
63
|
-
fun close(last: RuntimeEvent? = RuntimeEvent.StreamError("closed", "Subscription is closed", false)) {
|
|
64
|
-
branch.end(last)
|
|
65
|
-
selected?.close()
|
|
66
|
-
}
|
|
67
|
-
private fun detach() {
|
|
68
|
-
branch.close()
|
|
69
|
-
selected?.close()
|
|
70
|
-
synchronized(lock) { if (app === branch) { app = null; projection = null } }
|
|
71
|
-
}
|
|
72
|
-
suspend fun history(before: Long?, limit: Int) {
|
|
73
|
-
if (limit !in 1..256) throw CrocheError("invalid_configuration", "history limit must be 1..256")
|
|
74
|
-
val current = synchronized(lock) { if (app === branch && !branch.isEnded) selected else null }
|
|
75
|
-
?: throw CrocheError("invalid_configuration", "history requires an active subscription")
|
|
76
|
-
current.history(before, limit)
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
internal fun openCollection(initialMessages: Int?, after: Cursor?): Collection {
|
|
80
|
-
val branch = AppStreamBranch()
|
|
81
|
-
val selected = synchronized(lock) {
|
|
82
|
-
if (ended) null else {
|
|
83
|
-
projection?.close()
|
|
84
|
-
projection = null
|
|
85
|
-
app?.end(RuntimeEvent.Replaced)
|
|
86
|
-
app = branch
|
|
87
|
-
if ((initialMessages != null && after != null) || (initialMessages != null && initialMessages !in 0..256)) {
|
|
88
|
-
branch.push(RuntimeEvent.StreamError("invalid_configuration", "Select initialMessages in 0..256 or after, not both", false))
|
|
89
|
-
null
|
|
90
|
-
} else try {
|
|
91
|
-
port.select(initialMessages, after, branch::push).also { projection = it }
|
|
92
|
-
} catch (failure: Exception) {
|
|
93
|
-
branch.end(streamEnd(failure))
|
|
94
|
-
null
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
if (selected == null && !branch.isEnded) branch.end(RuntimeEvent.StreamError("closed", "Runtime is closed", false))
|
|
99
|
-
return Collection(branch, selected)
|
|
100
|
-
}
|
|
101
|
-
fun events(initialMessages: Int? = 50, after: Cursor? = null): Flow<RuntimeEvent> = flow {
|
|
102
|
-
openCollection(initialMessages, after).deliver { emit(it) }
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
suspend fun send(input: SendInput, options: SendOptions): Receipt {
|
|
106
|
-
currentCoroutineContext().ensureActive()
|
|
107
|
-
synchronized(lock) { if (ended) throw CrocheError("closed", "Runtime is closed") }
|
|
108
|
-
return sendOwned(input.owned(), options.owned())
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
/** Plain inputs stay on the JSON send; only byte images take Core's reserved entry. */
|
|
112
|
-
private suspend fun sendOwned(input: SendInput, options: SendOptions): Receipt =
|
|
113
|
-
if (input.imageCaptures().isEmpty()) port.send(input.encoded(options), options) else port.sendWithImages(input, options)
|
|
114
|
-
|
|
115
|
-
suspend fun request(input: SendInput, options: SendOptions, wait: RequestWait?): LegacyRequestResult = coroutineScope {
|
|
116
|
-
ensureActive()
|
|
117
|
-
val owned = input.owned()
|
|
118
|
-
val waiter = Waiter(null, wait)
|
|
119
|
-
synchronized(lock) {
|
|
120
|
-
if (ended) throw CrocheError("closed", "Runtime is closed")
|
|
121
|
-
waiters.add(waiter) // Before send: immediate canonical progress must not outrun registration.
|
|
122
|
-
}
|
|
123
|
-
val read = launch(start = CoroutineStart.UNDISPATCHED) {
|
|
124
|
-
try {
|
|
125
|
-
val receipt = sendOwned(owned, options.owned())
|
|
126
|
-
val proceed = synchronized(lock) {
|
|
127
|
-
waiter.id = receipt.requestId
|
|
128
|
-
waiter.receipt = receipt
|
|
129
|
-
val early = waiter.beforeReceipt.toList()
|
|
130
|
-
waiter.dropBeforeReceipt()
|
|
131
|
-
early.forEach { waiter.event(it) }
|
|
132
|
-
// Terminal same-id retries emit no new input event. Seed before idle
|
|
133
|
-
// overtakes capture, without regressing an already observed disposition.
|
|
134
|
-
if (waiter.status == null || (waiter.status?.terminal() != true && receipt.status.terminal())) {
|
|
135
|
-
waiter.status = receipt.status
|
|
136
|
-
}
|
|
137
|
-
if (waiter.lost) { waiter.failLost(); false } else true
|
|
138
|
-
}
|
|
139
|
-
if (!proceed) return@launch
|
|
140
|
-
if (receipt.seq == null) {
|
|
141
|
-
waiter.result.complete(LegacyRequestResult(receipt.requestId, receipt.status, emptyList(), false, true))
|
|
142
|
-
return@launch
|
|
143
|
-
}
|
|
144
|
-
var captured = false
|
|
145
|
-
val retained = port.readOutcome(receipt.requestId, receipt.seq) { snapshot ->
|
|
146
|
-
synchronized(lock) {
|
|
147
|
-
captured = true
|
|
148
|
-
if (waiter.status?.terminal() != true) waiter.status = snapshot.status
|
|
149
|
-
waiter.gap = receipt.seq < snapshot.floor
|
|
150
|
-
if (completion(waiter.status, snapshot.idle, waiter.wait)) waiter.complete = true
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
check(captured) { "Core outcome read omitted its ordered capture" }
|
|
154
|
-
synchronized(lock) {
|
|
155
|
-
waiter.gap = waiter.gap || retained.gap
|
|
156
|
-
retained.messages.filter { receipt.requestId in it.causedBy }.forEach { waiter.add(it) }
|
|
157
|
-
waiter.reading = false
|
|
158
|
-
waiter.finish()
|
|
159
|
-
}
|
|
160
|
-
} catch (cancelled: CancellationException) {
|
|
161
|
-
throw cancelled
|
|
162
|
-
} catch (failure: Exception) {
|
|
163
|
-
synchronized(lock) {
|
|
164
|
-
waiter.result.completeExceptionally(if (waiter.receipt != null)
|
|
165
|
-
CrocheError("observation_lost", "Observation ended after acceptance") else failure)
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
try { waiter.result.await() }
|
|
170
|
-
finally {
|
|
171
|
-
synchronized(lock) { waiter.dropBeforeReceipt(); waiters.remove(waiter) }
|
|
172
|
-
read.cancel() // Stops observation/storage wait only; never calls port.cancel.
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
// Keel #361 6071161214: Both forms require an attached stream; pin its projection generation.
|
|
177
|
-
suspend fun history(before: Long?, limit: Int) {
|
|
178
|
-
if (limit !in 1..256) throw CrocheError("invalid_configuration", "history limit must be 1..256")
|
|
179
|
-
val selected = synchronized(lock) { projection }
|
|
180
|
-
?: throw CrocheError("invalid_configuration", "history requires an app collection")
|
|
181
|
-
selected.history(before, limit)
|
|
182
|
-
}
|
|
183
|
-
suspend fun cancel(id: String) = port.cancel(id)
|
|
184
|
-
suspend fun clearHistory() = port.clearHistory()
|
|
185
|
-
fun setTools(tools: JsonArray, handlers: Map<String, ToolHandler>) = port.setTools(tools, handlers)
|
|
186
|
-
override fun close() { try { port.close() } finally { end(); observation.close() } }
|
|
187
|
-
private fun end(cause: Throwable? = null) = synchronized(lock) {
|
|
188
|
-
if (!ended) {
|
|
189
|
-
ended = true
|
|
190
|
-
projection?.close()
|
|
191
|
-
val terminal = streamEnd(cause)
|
|
192
|
-
app?.end(terminal)
|
|
193
|
-
waiters.toList().forEach { it.lost = true; it.dropBeforeReceipt(); if (it.receipt != null) it.failLost() }
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
// OPEN(§18.24.D): Default stays S2 terminal-plus-idle until Atlas rules on consuming-unit
|
|
198
|
-
// evidence. IDLE explicitly selects the same behavior; no unit-end heuristic or pending.
|
|
199
|
-
// One predicate is the replacement point; do not infer a unit end from state/turn/answered.
|
|
200
|
-
private fun completion(status: InputStatus?, idle: Boolean, wait: RequestWait?): Boolean = when (wait) {
|
|
201
|
-
null -> status?.terminal() == true && idle
|
|
202
|
-
RequestWait.IDLE -> status?.terminal() == true && idle
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
private inner class Waiter(var id: String?, val wait: RequestWait?) {
|
|
206
|
-
val result = CompletableDeferred<LegacyRequestResult>()
|
|
207
|
-
var receipt: Receipt? = null
|
|
208
|
-
var status: InputStatus? = null
|
|
209
|
-
var complete = false
|
|
210
|
-
var reading = true
|
|
211
|
-
var lost = false
|
|
212
|
-
var gap = false
|
|
213
|
-
val messages = linkedMapOf<Pair<String, Long>, RuntimeEvent.MessageEnd>()
|
|
214
|
-
// Per-call SDK observation bounds; losing observation never cancels Core.
|
|
215
|
-
val beforeReceipt = mutableListOf<RuntimeEvent>()
|
|
216
|
-
var beforeReceiptBytes = 0
|
|
217
|
-
fun dropBeforeReceipt() { beforeReceipt.clear(); beforeReceiptBytes = 0 }
|
|
218
|
-
fun retain(event: RuntimeEvent) {
|
|
219
|
-
if (lost) return
|
|
220
|
-
val bytes = try { event.serialized().toByteArray(Charsets.UTF_8).size }
|
|
221
|
-
catch (_: Exception) { lost = true; dropBeforeReceipt(); return }
|
|
222
|
-
if (beforeReceipt.size >= 256 || beforeReceiptBytes.toLong() + bytes > 1_048_576) {
|
|
223
|
-
lost = true; dropBeforeReceipt(); return
|
|
224
|
-
}
|
|
225
|
-
beforeReceipt.add(event.owned()); beforeReceiptBytes += bytes
|
|
226
|
-
}
|
|
227
|
-
fun add(event: RuntimeEvent.MessageEnd) { messages[event.id to event.seq] = event.owned() as RuntimeEvent.MessageEnd }
|
|
228
|
-
fun event(event: RuntimeEvent) {
|
|
229
|
-
if (complete || result.isCompleted) return
|
|
230
|
-
if (id == null) { retain(event); return }
|
|
231
|
-
when (event) {
|
|
232
|
-
is RuntimeEvent.Input -> if (event.id == id && status?.terminal() != true) status = event.status
|
|
233
|
-
is RuntimeEvent.MessageEnd -> if (id?.let { it in event.causedBy } == true) add(event)
|
|
234
|
-
is RuntimeEvent.State -> if (completion(status, event.status == AgentStatus.IDLE, wait)) complete = true
|
|
235
|
-
else -> Unit
|
|
236
|
-
}
|
|
237
|
-
finish()
|
|
238
|
-
}
|
|
239
|
-
fun finish() {
|
|
240
|
-
val accepted = receipt ?: return
|
|
241
|
-
val disposition = status ?: return
|
|
242
|
-
if (!reading && complete) result.complete(LegacyRequestResult(accepted.requestId, disposition,
|
|
243
|
-
messages.values.sortedBy { it.seq }, gap, false))
|
|
244
|
-
}
|
|
245
|
-
fun failLost() { result.completeExceptionally(CrocheError("observation_lost", "Reopen and retry the same id and input")) }
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
internal fun SendInput.owned() = copy(input = input.map {
|
|
250
|
-
when (it) { is TextInput -> it.copy(); is ImageInput -> it.owned() }
|
|
251
|
-
})
|
|
252
|
-
internal fun SendOptions.owned() = copy(responseFormat = responseFormat?.deepCopy())
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import type { CoreCancel, DecodedImage, ImageDecodeOptions } from '../core/port.js';
|
|
2
|
-
export interface Codec {
|
|
3
|
-
available(): boolean;
|
|
4
|
-
decode(bytes: Uint8Array, options: ImageDecodeOptions, cancel: CoreCancel): Promise<DecodedImage>;
|
|
5
|
-
render(request: {
|
|
6
|
-
handle: string;
|
|
7
|
-
width: number;
|
|
8
|
-
height: number;
|
|
9
|
-
format: 'png' | 'jpeg';
|
|
10
|
-
quality?: number;
|
|
11
|
-
}, cancel: CoreCancel): Promise<Uint8Array>;
|
|
12
|
-
release(handle: string): void;
|
|
13
|
-
}
|
|
14
|
-
export declare const noCodec: Codec;
|
|
15
|
-
export declare function browserCodec(): Codec;
|
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
import { HostError } from '../errors.js';
|
|
2
|
-
export const noCodec = {
|
|
3
|
-
available: () => false,
|
|
4
|
-
decode: () => Promise.reject(new HostError('image_unsupported', 'This platform has no image codec.')),
|
|
5
|
-
render: () => Promise.reject(new HostError('image_unsupported', 'This platform has no image codec.')),
|
|
6
|
-
release: () => { },
|
|
7
|
-
};
|
|
8
|
-
export function browserCodec() {
|
|
9
|
-
if (typeof createImageBitmap !== 'function' || typeof OffscreenCanvas !== 'function')
|
|
10
|
-
return noCodec;
|
|
11
|
-
const bitmaps = new Map();
|
|
12
|
-
const opened = (handle) => {
|
|
13
|
-
const bitmap = bitmaps.get(handle);
|
|
14
|
-
if (!bitmap)
|
|
15
|
-
throw new HostError('image_unsupported', 'The image handle was released.');
|
|
16
|
-
return bitmap;
|
|
17
|
-
};
|
|
18
|
-
return {
|
|
19
|
-
available: () => true,
|
|
20
|
-
async decode(bytes, { frame, applyOrientation }) {
|
|
21
|
-
// createImageBitmap decodes only the first frame (a GIF's frame 0); another frame is not this codec's.
|
|
22
|
-
if (frame !== 0)
|
|
23
|
-
throw new HostError('image_unsupported', 'This codec decodes only the first frame.');
|
|
24
|
-
// 'from-image' applies EXIF orientation when Core asks for it.
|
|
25
|
-
const bitmap = await createImageBitmap(new Blob([bytes]), { imageOrientation: applyOrientation ? 'from-image' : 'none' });
|
|
26
|
-
const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
|
|
27
|
-
const context = canvas.getContext('2d');
|
|
28
|
-
if (!context) {
|
|
29
|
-
bitmap.close();
|
|
30
|
-
throw new HostError('image_unsupported', 'No 2D canvas.');
|
|
31
|
-
}
|
|
32
|
-
context.drawImage(bitmap, 0, 0);
|
|
33
|
-
const pixels = context.getImageData(0, 0, bitmap.width, bitmap.height).data;
|
|
34
|
-
let hasAlpha = false;
|
|
35
|
-
for (let i = 3; i < pixels.length && !hasAlpha; i += 4)
|
|
36
|
-
hasAlpha = pixels[i] < 255;
|
|
37
|
-
const handle = crypto.randomUUID();
|
|
38
|
-
bitmaps.set(handle, bitmap);
|
|
39
|
-
return { handle, width: bitmap.width, height: bitmap.height, hasAlpha };
|
|
40
|
-
},
|
|
41
|
-
async render({ handle, width, height, format, quality }) {
|
|
42
|
-
const canvas = new OffscreenCanvas(width, height);
|
|
43
|
-
canvas.getContext('2d').drawImage(opened(handle), 0, 0, width, height);
|
|
44
|
-
const blob = await canvas.convertToBlob({ type: `image/${format}`, quality });
|
|
45
|
-
return new Uint8Array(await blob.arrayBuffer());
|
|
46
|
-
},
|
|
47
|
-
release(handle) {
|
|
48
|
-
bitmaps.get(handle)?.close();
|
|
49
|
-
bitmaps.delete(handle);
|
|
50
|
-
},
|
|
51
|
-
};
|
|
52
|
-
}
|
|
@@ -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
|
-
final class AppRefreshScheduler: RuntimeScheduler, @unchecked Sendable {
|
|
15
|
-
let identifier: String
|
|
16
|
-
init(identifier: String) { self.identifier = identifier }
|
|
17
|
-
|
|
18
|
-
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 LegacyCrocheError("not_configured", "Add \(identifier) to BGTaskSchedulerPermittedIdentifiers and enable Background fetch")
|
|
24
|
-
} catch let error as BGTaskScheduler.Error where error.code == .unavailable {
|
|
25
|
-
throw LegacyCrocheError("background_unavailable", "Background App Refresh is off or unavailable here")
|
|
26
|
-
} catch {
|
|
27
|
-
throw LegacyCrocheError("schedule_failed", "BGTaskScheduler refused the request")
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
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
|
-
func attach() throws { try Self.claims.claim(identifier, by: self) }
|
|
37
|
-
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
|
-
func registerHandler(runtime: @escaping @Sendable () async throws -> AgentEngine) -> 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
|