Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 | 4x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 15x 15x 15x 15x 53x 53x 64x 45x 45x 45x 1x 45x 1x 43x 43x 4x 4x 43x 43x 43x 43x 43x 60x 43x 33x 33x 10x 8x 7x 40x 40x 40x 40x 1x 40x 57x 57x 57x 43x 43x 60x 60x 43x 57x 4x | import type { Logger } from '@metamask/logger';
import type { Json } from '@metamask/utils';
import { enablePatches, produce, produceWithPatches } from 'immer';
import type { Patch } from 'immer';
import type { StorageAdapter } from './types.ts';
// Enable immer patches globally (called once at module load)
enablePatches();
// TODO: Add migration utility for converting from per-key storage format
// (e.g., caplet.{id}.manifest) to consolidated state format (caplet.manifests)
// when there is deployed data to migrate.
/**
* Configuration for creating a ControllerStorage instance.
*/
export type ControllerStorageConfig<State extends Record<string, Json>> = {
/** The namespace prefix for storage keys (e.g., 'caplet') */
namespace: string;
/** The underlying storage adapter */
adapter: StorageAdapter;
/** Default state values - used for initialization and type inference */
makeDefaultState: () => State;
/** Logger for storage operations */
logger: Logger;
/** Debounce delay in milliseconds (default: 100, set to 0 for tests) */
debounceMs?: number;
};
/**
* Internal options passed to constructor after async initialization.
*/
type ControllerStorageOptions<State extends Record<string, Json>> =
ControllerStorageConfig<State> & {
/** Initial state loaded from storage */
initialState: State;
};
/**
* ControllerStorage provides a simplified state management interface for controllers.
*
* Features:
* - Flat top-level key mapping: `state.foo` maps to `{namespace}.foo` in storage
* - Immer-based updates with automatic change detection
* - Synchronous state updates with debounced persistence
* - Only modified top-level keys are persisted
* - Fire-and-forget persistence (errors logged but don't rollback state)
* - Eager loading on initialization
*
* @template State - The state object type (must have Json-serializable values)
*/
export class ControllerStorage<State extends Record<string, Json>> {
readonly #adapter: StorageAdapter;
readonly #prefix: string;
readonly #makeDefaultState: () => State;
readonly #logger: Logger;
readonly #debounceMs: number;
#state: State;
#pendingPersist: ReturnType<typeof setTimeout> | null = null;
readonly #pendingKeys: Set<string> = new Set();
#lastWriteTime: number = 0;
/**
* Private constructor - use static make() factory method.
*
* @param options - Configuration including initial loaded state.
*/
// eslint-disable-next-line no-restricted-syntax -- TypeScript doesn't support # for constructors
private constructor(options: ControllerStorageOptions<State>) {
this.#adapter = options.adapter;
this.#prefix = `${options.namespace}.`;
this.#makeDefaultState = options.makeDefaultState;
this.#logger = options.logger;
this.#debounceMs = options.debounceMs ?? 100;
this.#state = options.initialState;
}
/**
* Create a ControllerStorage instance for a controller.
*
* This factory function:
* 1. Loads existing state from storage for the namespace
* 2. Merges with defaults (storage values take precedence)
* 3. Returns a hardened ControllerStorage instance
*
* @param config - Configuration including namespace, adapter, and default state.
* @returns Promise resolving to a hardened ControllerStorage instance.
*
* @example
* ```typescript
* const capletState = await ControllerStorage.make({
* namespace: 'caplet',
* adapter: storageAdapter,
* defaultState: { installed: [], manifests: {} },
* logger: logger.subLogger({ tags: ['storage'] }),
* });
*
* // Read state
* console.log(capletState.state.installed);
*
* // Update state (synchronous)
* capletState.update(draft => {
* draft.installed.push('com.example.app');
* });
* ```
*/
static async make<State extends Record<string, Json>>(
config: ControllerStorageConfig<State>,
): Promise<ControllerStorage<State>> {
const initialState = await this.#loadState(config);
return harden(
new ControllerStorage({
...config,
initialState,
}),
);
}
/**
* Load all state from storage, merging with defaults.
* Storage values take precedence over defaults.
*
* @param config - Configuration with adapter, namespace, and defaults.
* @returns The merged state object.
*/
static async #loadState<State extends Record<string, Json>>(
config: ControllerStorageConfig<State>,
): Promise<State> {
const { namespace, adapter, makeDefaultState } = config;
const prefix = `${namespace}.`;
const allKeys = await adapter.keys(prefix);
const state = makeDefaultState();
// Load and merge values from storage
await Promise.all(
allKeys.map(async (fullKey) => {
const key = fullKey.slice(prefix.length) as keyof State;
const value = await adapter.get<Json>(fullKey);
Eif (value !== undefined) {
state[key] = value as State[keyof State];
}
}),
);
return produce({}, (draft) => {
Object.assign(draft, state);
}) as State;
}
/**
* Current state (readonly, deeply frozen by immer).
* Access individual properties: `storage.state.installed`
*
* @returns The current readonly state.
*/
get state(): Readonly<State> {
return this.#state;
}
/**
* Update state using an immer producer function.
* State is updated synchronously in memory.
* Persistence is queued and debounced (fire-and-forget).
*
* @param producer - Function that mutates a draft of the state or returns new state
*
* @example
* ```typescript
* // Mutate draft
* storage.update(draft => {
* draft.installed.push('com.example.app');
* draft.manifests['com.example.app'] = manifest;
* });
*/
update(producer: (draft: State) => void): void {
const [nextState, patches] = produceWithPatches(this.#state, (draft) => {
// @ts-expect-error - ~infinite type recursion (ts2589)
const result = producer(draft);
if (result !== undefined) {
throw new Error('Controller producers must return undefined');
}
});
if (patches.length === 0) {
return;
}
this.#state = nextState;
this.#schedulePersist(patches);
}
/**
* Clear all state and reset to default values.
*/
clear(): void {
this.update((draft) => {
Object.assign(draft, this.#makeDefaultState());
});
}
/**
* Schedule debounced persistence with key accumulation.
* Implements bounded latency (timer not reset) and immediate writes after idle.
*
* @param patches - Immer patches describing changes.
*/
#schedulePersist(patches: Patch[]): void {
const now = Date.now();
const timeSinceLastWrite = now - this.#lastWriteTime;
this.#lastWriteTime = now;
const modifiedKeys = this.#getModifiedKeys(patches);
for (const key of modifiedKeys) {
this.#pendingKeys.add(key);
}
if (
timeSinceLastWrite > this.#debounceMs &&
this.#pendingPersist === null
) {
this.#flushPendingWrites();
return;
}
if (this.#pendingPersist === null) {
this.#pendingPersist = setTimeout(() => {
this.#flushPendingWrites();
}, this.#debounceMs);
}
// else: timer already running, just accumulate keys, don't reset
}
/**
* Flush pending writes to storage.
* Captures accumulated keys and persists current state values.
*/
#flushPendingWrites(): void {
const keysToWrite = new Set(this.#pendingKeys);
this.#pendingKeys.clear();
this.#pendingPersist = null;
// Persist current state values for accumulated keys
this.#persistAccumulatedKeys(this.#state, keysToWrite).catch((error) => {
this.#logger.error('Failed to persist state changes:', error);
});
}
/**
* Persist accumulated keys to storage.
* Always persists current state values (last-write-wins).
*
* @param state - The current state to persist from.
* @param keys - Set of top-level keys to persist.
*/
async #persistAccumulatedKeys(
state: State,
keys: Set<string>,
): Promise<void> {
await Promise.all(
Array.from(keys).map(async (key) => {
const storageKey = this.#buildKey(key);
// Correct use of the controller API guarantees that the key is defined.
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const value = state[key]!;
await this.#adapter.set(storageKey, value);
}),
);
}
/**
* Extract top-level keys that were modified from immer patches.
*
* @param patches - Array of immer patches describing changes.
* @returns Set of modified top-level keys.
*/
#getModifiedKeys(patches: Patch[]): Set<string> {
const keys = new Set<string>();
for (const patch of patches) {
// The first element of path is always the top-level key
Eif (patch.path.length > 0) {
keys.add(String(patch.path[0]));
}
// Because we forbid producers from returning a new state, there will be
// no patches with `path: []` (i.e. where the entire state was replaced).
}
return keys;
}
/**
* Build a storage key from a state property name.
*
* @param stateKey - The state property name.
* @returns The namespaced storage key.
*/
#buildKey(stateKey: string): string {
return `${this.#prefix}${stateKey}`;
}
}
harden(ControllerStorage);
|