# Local Reactive Store (crow-store) (https://crow.build/docs/stack/store)

`crow-store` gives your app durable, signal-backed local storage with **zero reflection**, **zero annotation processors**, and **crash-safe atomic persistence**.

## Defining Keys & Codecs [#defining-keys--codecs]

Declare typed keys with `StoreKeys` and reflection-free `StoreCodec`s for structured documents:

```kotlin
object PrefsKeys {
    val ThemeMode = StoreKeys.enum("theme_mode", ThemeMode.entries, ThemeMode.System)
    val Accent = StoreKeys.enum("accent", AccentOption.entries, AccentOption.Violet)
    val CompactDensity = StoreKeys.boolean("compact_density", false)
    val BrewCount = StoreKeys.int("brew_count", 0)
}
```

For rich models, implement `StoreCodec<T>` using `StoreCodecs.packFields` / `unpackFields` (length-prefixed, escaping-safe, and reflection-free):

```kotlin
val BeanCodec = object : StoreCodec<CoffeeBean> {
    override fun encode(value: CoffeeBean): String = StoreCodecs.packFields(
        listOf(value.id.toString(), value.name, value.roaster, value.remainingGrams.toString()),
    )

    override fun decode(raw: String): CoffeeBean {
        val f = StoreCodecs.unpackFields(raw)
        return CoffeeBean(
            id = f[0].toInt(),
            name = f[1],
            roaster = f[2],
            remainingGrams = f[3].toInt(),
        )
    }
}
```

## Reading & Writing Reactively [#reading--writing-reactively]

Open a crash-safe file-backed store (writes to a temporary file, calls `fsync`, and performs an atomic move) or an `InMemoryStoreBackend` for tests:

```kotlin
val store = openFileStore(
    file = File(filesDir, "app.crowstore"),
    schemaVersion = 1,
)

// Every key is a fine-grained Signal<T> — reading it inside @Ui subscribes directly
val themeSignal = store.state(PrefsKeys.ThemeMode)
val beans = store.collection("beans", idOf = { it.id.toString() }, codec = BeanCodec)

// Atomic multi-key transaction
store.transaction {
    store.set(PrefsKeys.BrewCount, currentCount + 1)
    beans.upsert(updatedBean)
}
```

### Migrations & Testing [#migrations--testing]

- **Versioned migrations**: Pass `migrations = listOf(StoreMigration(fromVersion = 1, toVersion = 2) { ... })` to evolve keys cleanly across app releases.
- **Process-scoped lifetime**: Pair `ReactiveStore` with `@CrowApp(process = AppStore::class)` so your store opens once per OS process and survives Activity recreations effortlessly.
- **Instant JVM tests**: Swap `FileStoreBackend` for `InMemoryStoreBackend` to test every persistence flow deterministically with zero disk I/O.