react-native-nitro-storage 0.11.0 → 0.13.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 (36) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +71 -11
  3. package/SECURITY.md +2 -2
  4. package/android/build.gradle +5 -0
  5. package/android/src/main/cpp/AndroidStorageAdapterCpp.cpp +12 -13
  6. package/android/src/main/cpp/JniSize.hpp +21 -0
  7. package/android/src/main/java/com/nitrostorage/AndroidStorageAdapter.kt +124 -16
  8. package/android/src/main/java/com/nitrostorage/DiskSqliteStore.kt +160 -43
  9. package/cpp/bindings/HybridStorage.cpp +12 -4
  10. package/cpp/core/SqliteDiskStore.cpp +191 -33
  11. package/cpp/core/SqliteDiskStore.hpp +11 -1
  12. package/docs/api-reference.md +11 -10
  13. package/docs/native-libraries.md +28 -0
  14. package/ios/IOSStorageAdapterCpp.mm +89 -22
  15. package/lib/commonjs/index.web.js +2 -1
  16. package/lib/commonjs/index.web.js.map +1 -1
  17. package/lib/commonjs/storage-core.js +26 -6
  18. package/lib/commonjs/storage-core.js.map +1 -1
  19. package/lib/commonjs/storage-runtime.js +1 -1
  20. package/lib/commonjs/storage-runtime.js.map +1 -1
  21. package/lib/module/index.web.js +2 -1
  22. package/lib/module/index.web.js.map +1 -1
  23. package/lib/module/storage-core.js +26 -6
  24. package/lib/module/storage-core.js.map +1 -1
  25. package/lib/module/storage-runtime.js +1 -1
  26. package/lib/module/storage-runtime.js.map +1 -1
  27. package/lib/typescript/index.d.ts.map +1 -1
  28. package/lib/typescript/index.web.d.ts.map +1 -1
  29. package/lib/typescript/storage-core.d.ts.map +1 -1
  30. package/lib/typescript/storage-runtime.d.ts +1 -1
  31. package/lib/typescript/storage-runtime.d.ts.map +1 -1
  32. package/lib/typescript/testing.d.ts.map +1 -1
  33. package/package.json +2 -1
  34. package/src/index.web.ts +5 -1
  35. package/src/storage-core.ts +26 -6
  36. package/src/storage-runtime.ts +2 -0
package/CHANGELOG.md CHANGED
@@ -6,6 +6,53 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
  Breaking changes are always listed first in each release section.
8
8
 
9
+ ## [0.13.0] - 2026-10-01
10
+
11
+ ### Breaking changes
12
+
13
+ - **Android no longer deletes a corrupt Disk database.** In 0.12.0, Android replaced a corrupt Disk database with an empty one when it opened. Now the file is kept and every Disk call fails with `storage_corruption`, as on iOS, until the app calls `storage.clear(StorageScope.Disk)` or `storage.clearAll()`. Migration: catch `storage_corruption` on Disk calls and call `storage.clear(StorageScope.Disk)` when the app can continue without the stored data.
14
+ - **iOS reports undecodable Secure data as `storage_corruption`.** Reading a Secure or biometric item whose Keychain data is empty or is not UTF-8 text failed with an untagged `failed with status 0` error. It now fails with the `storage_corruption` code. The item can still be deleted or replaced. Migration: handle `storage_corruption` on Secure reads if you matched the old message.
15
+
16
+ ### Added
17
+
18
+ - `storage.clear(StorageScope.Disk)` and `storage.clearAll()` recover a corrupt Disk database on iOS and Android: they delete the database and its journal files and create an empty store. `clear` with `except`, namespace clears, and `removeByPrefix` need to read keys and still fail on a corrupt database.
19
+ - `storage.clear(StorageScope.Disk)` works on a full device. When the delete fails with `storage_full`, the database is deleted and created again, which frees its space.
20
+
21
+ ### Changed
22
+
23
+ - Android Disk uses SQLite WAL. 0.12.0 documented WAL but did not enable it. An existing database converts on first open and keeps its rows. If the conversion cannot run, for example on a full device, the database opens without WAL so reads keep working, and the next launch tries again. With WAL and `synchronous=NORMAL`, a power loss can drop the most recent commits; an app kill cannot. This matches iOS.
24
+ - `getKeysByPrefix` on Disk uses the key index instead of reading every key, on iOS and Android. On iOS, `size(StorageScope.Disk)` no longer builds the full key list. Results are unchanged.
25
+
26
+ ### Fixed
27
+
28
+ - `storage.clear(StorageScope.Disk)` no longer fails before it reaches native storage when a Disk listener or event observer is registered and the stored values cannot be read, or when pending async Disk writes cannot be flushed. The pending writes are dropped and listeners receive a `clear` batch with no key changes.
29
+ - Android: `setBatch`, `removeBatch`, and the first-launch import report a full Disk database with the `storage_full` code. They used to fail with an untagged `cannot rollback` error.
30
+ - Android: Disk values larger than 2 MiB can be read. They could be written but not read.
31
+ - Android: a Disk I/O error that occurs with less than 1 MiB of free space carries the `storage_full` code. Read errors do not.
32
+ - iOS: Disk I/O errors caused by a full device or an exceeded quota carry the `storage_full` code, including while the database opens.
33
+ - iOS: a Disk read of a legacy value that is not yet migrated no longer fails when the Disk database is full.
34
+ - iOS: `clearSecureBiometric` reports an unavailable Keychain with the `keychain_locked` code.
35
+ - iOS: the Disk WAL file is truncated after checkpoints on every SQLite build.
36
+ - iOS: a Disk key that is not valid UTF-8 is rejected before anything is written or removed.
37
+ - `removeByPrefix("", scope)` rejects an invalid scope.
38
+ - Unknown native failures in `hasSecureBiometric`, `setSecureAccessControl`, `setSecureWritesAsync`, and `setKeychainAccessGroup` surface as a `NitroStorage: … failed (unknown error)` error.
39
+ - The Android library declares its unit-test dependencies only inside the repository, so consumer builds do not resolve them.
40
+
41
+ ## [0.12.0] - 2026-10-01
42
+
43
+ ### Breaking changes
44
+
45
+ - **Disk failures carry error codes.** A full device or database reports the new `storage_full` code, and a corrupt or unreadable Disk database reports `storage_corruption`, which until now came only from Secure storage. Android still deletes and recreates a database that is already corrupt when it opens; only corruption found after that reports the code. The message starts with the `[nitro-error:<code>]` tag. Migration: add `storage_full` if your `StorageErrorCode` switch is exhaustive, and check the storage scope before you treat `storage_corruption` as a Secure failure.
46
+ - **Android Disk errors use the iOS message format.** SQLite failures read `NitroStorage: Disk SQLite <operation> failed: <platform message>` instead of the raw Android exception text; the original exception is kept as the cause. Migration: match on the error code instead of the message text.
47
+
48
+ ### Added
49
+
50
+ - `storage_full` error code. iOS and Android report it when SQLite returns `SQLITE_FULL`, for writes and for deletes. Web reports it when the Disk or Secure backend throws `QuotaExceededError`. Use `isStorageError(error, "storage_full")` to treat a full device as an expected condition.
51
+
52
+ ### Fixed
53
+
54
+ - Android opens the Disk database on first Disk use instead of at app start, so a full or corrupt database surfaces as a Disk error instead of crashing the app at launch. A failed open closes the database handle and the next Disk call retries.
55
+
9
56
  ## [0.11.0] - 2026-09-30
10
57
 
11
58
  ### Breaking changes
package/README.md CHANGED
@@ -91,7 +91,7 @@ before installing this package, then rebuild the native app so the generated
91
91
  Nitro bindings and native runtime use the same major-minor version:
92
92
 
93
93
  ```sh
94
- bun add react-native-nitro-modules@0.37.1 react-native-nitro-storage@0.11.0
94
+ bun add react-native-nitro-modules@0.37.1 react-native-nitro-storage@0.13.0
95
95
  bunx expo prebuild
96
96
  ```
97
97
 
@@ -752,20 +752,80 @@ Native and web adapters tag classified failures with stable error codes. Use
752
752
  Errors never swallow the underlying cause silently: the original platform
753
753
  message is preserved on the error for diagnostics.
754
754
 
755
- | Code | Meaning |
756
- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
757
- | `keychain_locked` | The protected store is locked. Retry after the device unlocks. |
758
- | `authentication_required` | The item needs user authentication, or the user cancelled the prompt. |
759
- | `key_invalidated` | The protecting key was invalidated, for example by a biometric enrolment change. |
760
- | `biometric_unavailable` | The requested biometric level is not available on this device or OS version. |
761
- | `storage_corruption` | Stored secure data could not be decrypted, or (Android) the Secure master key or store cannot be created. Do not retry. |
762
- | `storage_compensation_failed` | A multi-step write failed and restoring the previous state also failed. |
763
- | `unsupported` | The operation is not available on this platform or environment. |
764
- | `invalid_key` | The storage key is empty. Keys must be non-empty strings. |
755
+ | Code | Meaning |
756
+ | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
757
+ | `keychain_locked` | The protected store is locked. Retry after the device unlocks. |
758
+ | `authentication_required` | The item needs user authentication, or the user cancelled the prompt. |
759
+ | `key_invalidated` | The protecting key was invalidated, for example by a biometric enrolment change. |
760
+ | `biometric_unavailable` | The requested biometric level is not available on this device or OS version. |
761
+ | `storage_corruption` | Stored secure data could not be decoded, the Disk database is corrupt, or (Android) the Secure master key or store cannot be created. Do not retry. |
762
+ | `storage_compensation_failed` | A multi-step write failed and restoring the previous state also failed. |
763
+ | `unsupported` | The operation is not available on this platform or environment. |
764
+ | `storage_full` | The device or database is out of space, or the web storage quota is exceeded. Free space before retrying. |
765
+ | `invalid_key` | The storage key is empty. Keys must be non-empty strings. |
765
766
 
766
767
  Invalid scopes and non-finite numeric levels are rejected with untagged errors
767
768
  before they reach native storage.
768
769
 
770
+ A full device is an expected condition, not a bug. Disk writes and deletes both
771
+ fail with `storage_full` until the user frees space:
772
+
773
+ ```ts
774
+ import {
775
+ isStorageError,
776
+ storage,
777
+ StorageScope,
778
+ } from "react-native-nitro-storage";
779
+
780
+ function saveDraft(draft: string): "saved" | "storage_full" {
781
+ try {
782
+ storage.setString("draft", draft, StorageScope.Disk);
783
+ return "saved";
784
+ } catch (error) {
785
+ if (!isStorageError(error, "storage_full")) throw error;
786
+ return "storage_full";
787
+ }
788
+ }
789
+ ```
790
+
791
+ A full device does not block cleanup. `storage.clear(StorageScope.Disk)`
792
+ deletes and recreates the Disk database when a normal delete fails with
793
+ `storage_full`, which frees the space the database used. `remove` and
794
+ `removeBatch` can still fail with `storage_full`, because a delete also writes
795
+ to the database log.
796
+
797
+ A corrupt Disk database is never deleted automatically. Every Disk call fails
798
+ with `storage_corruption` until the app clears Disk storage:
799
+
800
+ ```ts
801
+ import {
802
+ isStorageError,
803
+ storage,
804
+ StorageScope,
805
+ } from "react-native-nitro-storage";
806
+
807
+ function readDraft(): string | undefined {
808
+ try {
809
+ return storage.getString("draft", StorageScope.Disk);
810
+ } catch (error) {
811
+ if (!isStorageError(error, "storage_corruption")) throw error;
812
+ storage.clear(StorageScope.Disk);
813
+ return undefined;
814
+ }
815
+ }
816
+ ```
817
+
818
+ `storage.clear(StorageScope.Disk)` and `storage.clearAll()` are the recovery
819
+ calls. `clear` with `except`, namespace clears, and `removeByPrefix` read keys
820
+ first and fail on a corrupt database. A `clear` batch event with an empty
821
+ `changes` array means every key in that scope was removed and the previous
822
+ values could not be read; treat all keys in the scope as deleted.
823
+
824
+ On Android, Disk values above 512 KiB are read in 512 KiB chunks, and read
825
+ time grows faster than value size (about 30 ms for 5 MiB and 265 ms for 20 MiB
826
+ in a host measurement; devices are slower). Keep single Disk values below about
827
+ 5 MiB.
828
+
769
829
  ## Platform Support
770
830
 
771
831
  | Platform | Status |
package/SECURITY.md CHANGED
@@ -6,8 +6,8 @@ Security fixes are shipped for the latest published `0.x` release line.
6
6
 
7
7
  | Version | Supported |
8
8
  | -------- | --------- |
9
- | `0.11.x` | Yes |
10
- | `< 0.11` | No |
9
+ | `0.13.x` | Yes |
10
+ | `< 0.13` | No |
11
11
 
12
12
  ## Reporting a Vulnerability
13
13
 
@@ -83,4 +83,9 @@ dependencies {
83
83
  implementation "com.facebook.react:react-native:+"
84
84
  implementation "androidx.security:security-crypto:1.1.0"
85
85
  implementation project(":react-native-nitro-modules")
86
+
87
+ if (file("src/test").exists()) {
88
+ testImplementation "junit:junit:4.13.2"
89
+ testImplementation "org.robolectric:robolectric:4.13"
90
+ }
86
91
  }
@@ -1,4 +1,5 @@
1
1
  #include "AndroidStorageAdapterCpp.hpp"
2
+ #include "JniSize.hpp"
2
3
 
3
4
  #include <limits>
4
5
  #include <stdexcept>
@@ -13,11 +14,8 @@ namespace {
13
14
  local_ref<JString> toJavaString(const std::string& value) {
14
15
  // fbjni's std::string overload uses c_str(), which truncates embedded NUL.
15
16
  if (value.find('\0') == std::string::npos) return make_jstring(value);
16
- if (value.size() > static_cast<size_t>(std::numeric_limits<jsize>::max())) {
17
- throw std::length_error("Storage string exceeds the Java array limit");
18
- }
19
- const auto size = static_cast<jsize>(value.size());
20
- auto bytes = JArrayByte::newArray(size);
17
+ const jsize size = toJniSize(value.size(), "Storage string exceeds the Java array limit");
18
+ auto bytes = JArrayByte::newArray(value.size());
21
19
  bytes->setRegion(0, size, reinterpret_cast<const jbyte*>(value.data()));
22
20
  static auto constructor = JString::javaClassStatic()->getConstructor<
23
21
  jstring(jbyteArray, jstring)>();
@@ -26,10 +24,11 @@ local_ref<JString> toJavaString(const std::string& value) {
26
24
  }
27
25
 
28
26
  local_ref<JavaStringArray> toJavaStringArray(const std::vector<std::string>& values) {
29
- auto javaArray = JavaStringArray::newArray(static_cast<jsize>(values.size()));
27
+ toJniSize(values.size(), "Storage batch exceeds the Java array limit");
28
+ auto javaArray = JavaStringArray::newArray(values.size());
30
29
  for (size_t i = 0; i < values.size(); ++i) {
31
30
  auto javaValue = toJavaString(values[i]);
32
- javaArray->setElement(static_cast<jsize>(i), javaValue.get());
31
+ javaArray->setElement(i, javaValue.get());
33
32
  }
34
33
  return javaArray;
35
34
  }
@@ -38,9 +37,9 @@ std::vector<std::optional<std::string>> fromNullableJavaStringArray(alias_ref<Ja
38
37
  std::vector<std::optional<std::string>> parsedValues;
39
38
  if (!values) return parsedValues;
40
39
 
41
- const jsize size = static_cast<jsize>(values->size());
40
+ const size_t size = values->size();
42
41
  parsedValues.reserve(size);
43
- for (jsize i = 0; i < size; ++i) {
42
+ for (size_t i = 0; i < size; ++i) {
44
43
  auto currentValue = values->getElement(i);
45
44
  if (!currentValue) {
46
45
  parsedValues.push_back(std::nullopt);
@@ -53,10 +52,10 @@ std::vector<std::optional<std::string>> fromNullableJavaStringArray(alias_ref<Ja
53
52
 
54
53
  std::vector<std::string> fromJavaStringArray(alias_ref<JavaStringArray> values) {
55
54
  if (!values) return {};
56
- const jsize size = values->size();
55
+ const size_t size = values->size();
57
56
  std::vector<std::string> result;
58
57
  result.reserve(size);
59
- for (jsize i = 0; i < size; ++i) {
58
+ for (size_t i = 0; i < size; ++i) {
60
59
  auto currentValue = values->getElement(i);
61
60
  // Null entries are dropped so a missing key can never surface as the
62
61
  // empty-string clear sentinel used by change listeners.
@@ -115,7 +114,7 @@ std::vector<std::string> AndroidStorageAdapterCpp::getKeysByPrefixDisk(const std
115
114
 
116
115
  size_t AndroidStorageAdapterCpp::sizeDisk() {
117
116
  static auto method = AndroidStorageAdapterJava::javaClassStatic()->getStaticMethod<jint()>("sizeDisk");
118
- return static_cast<size_t>(method(AndroidStorageAdapterJava::javaClassStatic()));
117
+ return fromJniSize(method(AndroidStorageAdapterJava::javaClassStatic()));
119
118
  }
120
119
 
121
120
  void AndroidStorageAdapterCpp::setDiskBatch(
@@ -199,7 +198,7 @@ std::vector<std::string> AndroidStorageAdapterCpp::getKeysByPrefixSecure(const s
199
198
 
200
199
  size_t AndroidStorageAdapterCpp::sizeSecure() {
201
200
  static auto method = AndroidStorageAdapterJava::javaClassStatic()->getStaticMethod<jint()>("sizeSecure");
202
- return static_cast<size_t>(method(AndroidStorageAdapterJava::javaClassStatic()));
201
+ return fromJniSize(method(AndroidStorageAdapterJava::javaClassStatic()));
203
202
  }
204
203
 
205
204
  void AndroidStorageAdapterCpp::setSecureBatch(
@@ -0,0 +1,21 @@
1
+ #pragma once
2
+
3
+ #include <cstddef>
4
+ #include <cstdint>
5
+ #include <limits>
6
+ #include <stdexcept>
7
+
8
+ namespace NitroStorage {
9
+
10
+ inline int32_t toJniSize(size_t size, const char* what) {
11
+ if (size > static_cast<size_t>(std::numeric_limits<int32_t>::max())) {
12
+ throw std::length_error(what);
13
+ }
14
+ return static_cast<int32_t>(size);
15
+ }
16
+
17
+ inline size_t fromJniSize(int32_t size) {
18
+ return size > 0 ? static_cast<size_t>(size) : 0;
19
+ }
20
+
21
+ } // namespace NitroStorage
@@ -3,7 +3,12 @@
3
3
  package com.nitrostorage
4
4
 
5
5
  import android.content.Context
6
+ import android.database.sqlite.SQLiteDatabaseCorruptException
7
+ import android.database.sqlite.SQLiteDiskIOException
8
+ import android.database.sqlite.SQLiteException
9
+ import android.database.sqlite.SQLiteFullException
6
10
  import android.os.Build
11
+ import android.os.StatFs
7
12
  import android.security.keystore.KeyGenParameterSpec
8
13
  import android.security.keystore.KeyPermanentlyInvalidatedException
9
14
  import android.security.keystore.KeyProperties
@@ -17,7 +22,7 @@ import java.security.KeyStore
17
22
  import java.security.KeyStoreException
18
23
  import javax.crypto.AEADBadTagException
19
24
 
20
- private fun Throwable.hasCause(type: Class<*>): Boolean {
25
+ internal fun Throwable.hasCause(type: Class<*>): Boolean {
21
26
  var current: Throwable? = this
22
27
  while (current != null) {
23
28
  if (type.isInstance(current)) return true
@@ -26,14 +31,16 @@ private fun Throwable.hasCause(type: Class<*>): Boolean {
26
31
  return false
27
32
  }
28
33
 
29
- private fun Throwable.storageErrorCode(): String? {
34
+ internal fun Throwable.storageErrorCode(): String? {
30
35
  val taggedCode = message
31
36
  ?.let { Regex("\\[nitro-error:([a-z_]+)]").find(it)?.groupValues?.get(1) }
32
37
  if (taggedCode == "storage_compensation_failed") {
33
38
  return taggedCode
34
39
  }
35
40
  return when {
36
- hasCause(AEADBadTagException::class.java) -> "storage_corruption"
41
+ hasCause(SQLiteFullException::class.java) -> "storage_full"
42
+ hasCause(SQLiteDatabaseCorruptException::class.java) ||
43
+ hasCause(AEADBadTagException::class.java) -> "storage_corruption"
37
44
  hasCause(UserNotAuthenticatedException::class.java) ||
38
45
  hasCause(KeyStoreException::class.java) -> "authentication_required"
39
46
  hasCause(KeyPermanentlyInvalidatedException::class.java) ||
@@ -42,7 +49,34 @@ private fun Throwable.storageErrorCode(): String? {
42
49
  }
43
50
  }
44
51
 
45
- private fun Throwable.wrapStorageException(
52
+ internal const val OUT_OF_SPACE_USABLE_BYTES = 1L shl 20
53
+
54
+ private val sqliteExtendedCodePattern = Regex("\\(code (\\d+)")
55
+ private const val SQLITE_IOERR_READ = 266
56
+ private const val SQLITE_IOERR_SHORT_READ = 522
57
+
58
+ internal fun isOutOfSpaceFailure(error: Throwable, usableBytes: Long): Boolean {
59
+ var current: Throwable? = error
60
+ while (current != null && current !is SQLiteDiskIOException) {
61
+ current = current.cause
62
+ }
63
+ val ioError = current ?: return false
64
+ val extendedCode = ioError.message
65
+ ?.let { sqliteExtendedCodePattern.find(it)?.groupValues?.get(1)?.toIntOrNull() }
66
+ ?: return false
67
+ if (extendedCode == SQLITE_IOERR_READ || extendedCode == SQLITE_IOERR_SHORT_READ) {
68
+ return false
69
+ }
70
+ return usableBytes in 0 until OUT_OF_SPACE_USABLE_BYTES
71
+ }
72
+
73
+ internal fun isRecoverableByRecreate(error: Throwable): Boolean {
74
+ val message = error.message ?: return false
75
+ return message.startsWith("[nitro-error:storage_corruption] NitroStorage: Disk SQLite ") ||
76
+ message.startsWith("[nitro-error:storage_full] NitroStorage: Disk SQLite ")
77
+ }
78
+
79
+ internal fun Throwable.wrapStorageException(
46
80
  defaultMessage: String,
47
81
  defaultCode: String? = null,
48
82
  ): RuntimeException {
@@ -61,7 +95,35 @@ private fun Throwable.wrapStorageException(
61
95
  class AndroidStorageAdapter private constructor(private val context: Context) {
62
96
  private val sharedPreferences: SharedPreferences =
63
97
  context.getSharedPreferences("NitroStorage", Context.MODE_PRIVATE)
64
- private val diskStore: DiskSqliteStore = DiskSqliteStore(context, sharedPreferences)
98
+ private val diskStoreLock = Any()
99
+ private var openDiskStore: DiskSqliteStore? = null
100
+ private val diskStore: DiskSqliteStore
101
+ get() = synchronized(diskStoreLock) {
102
+ openDiskStore ?: DiskSqliteStore(context, sharedPreferences, diskDatabaseOpener)
103
+ .also { openDiskStore = it }
104
+ }
105
+
106
+ private fun recreateDiskStore() {
107
+ synchronized(diskStoreLock) {
108
+ openDiskStore?.let { store -> runCatching { store.close() } }
109
+ openDiskStore = null
110
+ DiskSqliteStore.deleteDatabaseFiles(context)
111
+ sharedPreferences.edit().clear().commit()
112
+ openDiskStore = DiskSqliteStore(context, sharedPreferences, diskDatabaseOpener)
113
+ }
114
+ }
115
+
116
+ private fun diskFullCodeFor(error: Throwable): String? {
117
+ if (!error.hasCause(SQLiteDiskIOException::class.java)) {
118
+ return null
119
+ }
120
+ val usableBytes = try {
121
+ StatFs(context.filesDir.path).availableBytes
122
+ } catch (statError: IllegalArgumentException) {
123
+ return null
124
+ }
125
+ return if (isOutOfSpaceFailure(error, usableBytes)) "storage_full" else null
126
+ }
65
127
 
66
128
  private val masterKeyAlias = "${context.packageName}.nitro_storage.master_key"
67
129
 
@@ -542,6 +604,9 @@ class AndroidStorageAdapter private constructor(private val context: Context) {
542
604
  @Volatile
543
605
  private var instance: AndroidStorageAdapter? = null
544
606
 
607
+ @Volatile
608
+ internal var diskDatabaseOpener: DiskDatabaseOpener = ::openDiskDatabase
609
+
545
610
  private fun getInstanceOrThrow(): AndroidStorageAdapter {
546
611
  return instance ?: throw IllegalStateException(
547
612
  "NitroStorage not initialized. Call AndroidStorageAdapter.init(this) in your MainApplication.onCreate(), " +
@@ -572,59 +637,102 @@ class AndroidStorageAdapter private constructor(private val context: Context) {
572
637
 
573
638
  // --- Disk ---
574
639
 
640
+ private inline fun <T> diskOperation(
641
+ operation: String,
642
+ block: DiskSqliteStore.() -> T,
643
+ ): T {
644
+ val instance = getInstanceOrThrow()
645
+ try {
646
+ val store = instance.diskStore
647
+ return try {
648
+ store.block()
649
+ } catch (closed: IllegalStateException) {
650
+ val current = instance.diskStore
651
+ if (current === store) {
652
+ throw closed
653
+ }
654
+ current.block()
655
+ }
656
+ } catch (e: SQLiteException) {
657
+ throw e.wrapStorageException(
658
+ "NitroStorage: Disk SQLite $operation failed: ${e.message}",
659
+ instance.diskFullCodeFor(e),
660
+ )
661
+ } catch (e: IllegalStateException) {
662
+ throw e.wrapStorageException(
663
+ "NitroStorage: Disk SQLite $operation failed: ${e.message}",
664
+ )
665
+ }
666
+ }
667
+
575
668
  @JvmStatic
576
669
  fun setDisk(key: String, value: String) {
577
- getInstanceOrThrow().diskStore.set(key, value)
670
+ diskOperation("set") { set(key, value) }
578
671
  }
579
672
 
580
673
  @JvmStatic
581
674
  fun setDiskBatch(keys: Array<String>, values: Array<String>) {
582
- getInstanceOrThrow().diskStore.setBatch(keys, values)
675
+ diskOperation("set") { setBatch(keys, values) }
583
676
  }
584
677
 
585
678
  @JvmStatic
586
679
  fun getDisk(key: String): String? {
587
- return getInstanceOrThrow().diskStore.get(key)
680
+ return diskOperation("get") { get(key) }
588
681
  }
589
682
 
590
683
  @JvmStatic
591
684
  fun getDiskBatch(keys: Array<String>): Array<String?> {
592
- return getInstanceOrThrow().diskStore.getBatch(keys)
685
+ return diskOperation("get") { getBatch(keys) }
593
686
  }
594
687
 
595
688
  @JvmStatic
596
689
  fun deleteDisk(key: String) {
597
- getInstanceOrThrow().diskStore.remove(key)
690
+ diskOperation("remove") { remove(key) }
598
691
  }
599
692
 
600
693
  @JvmStatic
601
694
  fun deleteDiskBatch(keys: Array<String>) {
602
- getInstanceOrThrow().diskStore.removeBatch(keys)
695
+ diskOperation("remove") { removeBatch(keys) }
603
696
  }
604
697
 
605
698
  @JvmStatic
606
699
  fun hasDisk(key: String): Boolean {
607
- return getInstanceOrThrow().diskStore.has(key)
700
+ return diskOperation("has") { has(key) }
608
701
  }
609
702
 
610
703
  @JvmStatic
611
704
  fun getAllKeysDisk(): Array<String> {
612
- return getInstanceOrThrow().diskStore.getAllKeys()
705
+ return diskOperation("getAllKeys") { getAllKeys() }
613
706
  }
614
707
 
615
708
  @JvmStatic
616
709
  fun getKeysByPrefixDisk(prefix: String): Array<String> {
617
- return getInstanceOrThrow().diskStore.getKeysByPrefix(prefix)
710
+ return diskOperation("getKeysByPrefix") { getKeysByPrefix(prefix) }
618
711
  }
619
712
 
620
713
  @JvmStatic
621
714
  fun sizeDisk(): Int {
622
- return getInstanceOrThrow().diskStore.size()
715
+ return diskOperation("size") { size() }
623
716
  }
624
717
 
625
718
  @JvmStatic
626
719
  fun clearDisk() {
627
- getInstanceOrThrow().diskStore.clear()
720
+ try {
721
+ diskOperation("clear") { clear() }
722
+ } catch (e: RuntimeException) {
723
+ if (!isRecoverableByRecreate(e)) {
724
+ throw e
725
+ }
726
+ val instance = getInstanceOrThrow()
727
+ try {
728
+ instance.recreateDiskStore()
729
+ } catch (recreateError: SQLiteException) {
730
+ throw recreateError.wrapStorageException(
731
+ "NitroStorage: Disk SQLite clear failed: ${recreateError.message}",
732
+ instance.diskFullCodeFor(recreateError),
733
+ )
734
+ }
735
+ }
628
736
  }
629
737
 
630
738
  // --- Secure (async apply by default, sync commit when requested) ---