Skip to content

Commit

Permalink
fix: Reuse mmkv instance once created (#11139)
Browse files Browse the repository at this point in the history
## **Description**
We should reuse MMKV instance instead of creating a new one each time we
want to access storage.

## **Related issues**

N/A

## **Manual testing steps**

1. Fresh install the app
2. Press import with SRP
3. Accept share data and terms of use
4. kill the app
5. Open it
6. go to import with SRP again
7. Should not show the same modals (This means it's being saved and read
under MMKV)

## **Screenshots/Recordings**



https://github.com/user-attachments/assets/2d342876-9675-482c-8d54-f6b4e1258100


### **Before**

N/A

### **After**

N/A

## **Pre-merge author checklist**

- [x] I’ve followed [MetaMask Contributor
Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask Mobile
Coding
Standards](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/CODING_GUIDELINES.md).
- [x] I've completed the PR template to the best of my ability
- [x] I’ve included tests if applicable
- [x] I’ve documented my code using [JSDoc](https://jsdoc.app/) format
if applicable
- [x] I’ve applied the right labels on the PR (see [labeling
guidelines](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/LABELING_GUIDELINES.md)).
Not required for external contributors.

## **Pre-merge reviewer checklist**

- [ ] I've manually tested the PR (e.g. pull and build branch, run the
app, test code being changed).
- [ ] I confirm that this PR addresses all acceptance criteria described
in the ticket it closes and includes the necessary testing evidence such
as recordings and or screenshots.

---------

Co-authored-by: Aslau Mario-Daniel <marioaslau@gmail.com>
  • Loading branch information
tommasini and MarioAslau authored Oct 9, 2024
1 parent ea3948c commit 5b7b39b
Show file tree
Hide file tree
Showing 4 changed files with 258 additions and 69 deletions.
69 changes: 0 additions & 69 deletions app/store/storage-wrapper.js

This file was deleted.

95 changes: 95 additions & 0 deletions app/store/storage-wrapper.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
// Unmocking storage-wrapper as it's mocked in testSetup directly
// to allow easy testing of other parts of the app
// but here we want to actually test storage-wrapper
jest.unmock('./storage-wrapper');
import StorageWrapper from './storage-wrapper';

describe('StorageWrapper', () => {
it('return the value from Storage Wrapper', async () => {
const setItemSpy = jest.spyOn(StorageWrapper, 'setItem');
const getItemSpy = jest.spyOn(StorageWrapper, 'getItem');

await StorageWrapper.setItem('test-key', 'test-value');

const result = await StorageWrapper.getItem('test-key');

expect(setItemSpy).toHaveBeenCalledWith('test-key', 'test-value');
expect(getItemSpy).toHaveBeenCalledWith('test-key');
expect(result).toBe('test-value');
});
it('throws when setItem value param is not a string', async () => {
const setItemSpy = jest.spyOn(StorageWrapper, 'setItem');

try {
//@ts-expect-error - Expected to test non string scenario
await StorageWrapper.setItem('test-key', 123);
} catch (error) {
const e = error as unknown as Error;
expect(e).toBeInstanceOf(Error);
expect(e.message).toBe(
'MMKV value must be a string, received value 123 for key test-key',
);
}

expect(setItemSpy).toHaveBeenCalledWith('test-key', 123);
});

it('removes value from the store', async () => {
const removeItemSpy = jest.spyOn(StorageWrapper, 'removeItem');
await StorageWrapper.setItem('test-key', 'test-value');

const resultBeforeRemove = await StorageWrapper.getItem('test-key');
expect(resultBeforeRemove).toBe('test-value');

await StorageWrapper.removeItem('test-key');
expect(removeItemSpy).toHaveBeenCalledWith('test-key');

const resultAfterRemoval = await StorageWrapper.getItem('test-key');
expect(resultAfterRemoval).toBeNull();
});

it('removes all values from the store', async () => {
const clearAllSpy = jest.spyOn(StorageWrapper, 'clearAll');
await StorageWrapper.setItem('test-key', 'test-value');
await StorageWrapper.setItem('test-key-2', 'test-value');

const resultBeforeRemove = await StorageWrapper.getItem('test-key');
const result2BeforeRemove = await StorageWrapper.getItem('test-key-2');

expect(resultBeforeRemove).toBe('test-value');
expect(result2BeforeRemove).toBe('test-value');

await StorageWrapper.clearAll();
expect(clearAllSpy).toHaveBeenCalled();

const result = await StorageWrapper.getItem('test-key');
const result2 = await StorageWrapper.getItem('test-key-2');
expect(result).toBeNull();
expect(result2).toBeNull();
});

it('singleton instance is defined and unique', () => {
expect(StorageWrapper).toBeDefined();
expect(StorageWrapper.getItem).toBeDefined();
expect(StorageWrapper.setItem).toBeDefined();
// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires
const storageWrapper = require('./storage-wrapper').default;

expect(StorageWrapper).toBe(storageWrapper);
});

it('use ReadOnlyStore on E2E', async () => {
process.env.IS_TEST = 'true';

const getItemSpy = jest.spyOn(StorageWrapper, 'getItem');
const setItemSpy = jest.spyOn(StorageWrapper, 'setItem');

await StorageWrapper.setItem('test-key', 'test-value');

const result = await StorageWrapper.getItem('test-key');

expect(setItemSpy).toHaveBeenCalledWith('test-key', 'test-value');
expect(getItemSpy).toHaveBeenCalledWith('test-key');
expect(result).toBe('test-value');
});
});
158 changes: 158 additions & 0 deletions app/store/storage-wrapper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
import ReadOnlyNetworkStore from '../util/test/network-store';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { isE2E } from '../util/test/utils';
import { MMKV } from 'react-native-mmkv';

/**
* Wrapper class for MMKV.
* Provides a unified interface for storage operations, with fallback to AsyncStorage in E2E test mode.
*
* @example
* // Import the StorageWrapper instance
* import StorageWrapper from './StorageWrapper';
*
* // Set an item
* await StorageWrapper.setItem('user_id', '12345');
*
* // Get an item
* const userId = await StorageWrapper.getItem('user_id');
* console.log(userId); // Outputs: '12345'
*
* // Remove an item
* await StorageWrapper.removeItem('user_id');
*
* // Clear all items
* await StorageWrapper.clearAll();
*/
class StorageWrapper {
private static instance: StorageWrapper | null = null;
private storage: typeof ReadOnlyNetworkStore | MMKV;

/**
* Private constructor to enforce singleton pattern.
* Initializes the storage based on the environment (E2E test or production).
*/
private constructor() {
/**
* The underlying storage implementation.
* Use `ReadOnlyNetworkStore` in test mode otherwise use `AsyncStorage`.
*/
this.storage = isE2E ? ReadOnlyNetworkStore : new MMKV();
}

/**
* Retrieves an item from storage.
* @param key - The key of the item to retrieve.
* @returns A promise that resolves with the value of the item, or null if not found.
* @throws Will throw an error if retrieval fails (except in E2E mode, where it falls back to AsyncStorage).
*
* @example
* const value = await StorageWrapper.getItem('my_key');
* if (value !== null) {
* console.log('Retrieved value:', value);
* } else {
* console.log('No value found for key: my_key');
* }
*/
async getItem(key: string) {
try {
// asyncStorage returns null for no value
// mmkv returns undefined for no value
// therefore must return null if no value is found
// to keep app behavior consistent
const value = (await this.storage.getString(key)) ?? null;
return value;
} catch (error) {
if (isE2E) {
// Fall back to AsyncStorage in test mode if ReadOnlyNetworkStore fails
return await AsyncStorage.getItem(key);
}
throw error;
}
}

/**
* Sets an item in storage.
* @param key - The key under which to store the value.
* @param value - The value to store. Must be a string.
* @throws Will throw an error if the value is not a string or if setting fails (except in E2E mode, where it falls back to AsyncStorage).
*
* @example
* try {
* await StorageWrapper.setItem('user_preferences', JSON.stringify({ theme: 'dark' }));
* console.log('User preferences saved successfully');
* } catch (error) {
* console.error('Failed to save user preferences:', error);
* }
*/
async setItem(key: string, value: string) {
try {
if (typeof value !== 'string')
throw new Error(
`MMKV value must be a string, received value ${value} for key ${key}`,
);
return await this.storage.set(key, value);
} catch (error) {
if (isE2E) {
// Fall back to AsyncStorage in test mode if ReadOnlyNetworkStore fails
return await AsyncStorage.setItem(key, value);
}
throw error;
}
}

/**
* Removes an item from storage.
* @param key - The key of the item to remove.
* @throws Will throw an error if removal fails (except in E2E mode, where it falls back to AsyncStorage).
*
* @example
* try {
* await StorageWrapper.removeItem('temporary_data');
* console.log('Temporary data removed successfully');
* } catch (error) {
* console.error('Failed to remove temporary data:', error);
* }
*/
async removeItem(key: string) {
try {
return await this.storage.delete(key);
} catch (error) {
if (isE2E) {
// Fall back to AsyncStorage in test mode if ReadOnlyNetworkStore fails
return await AsyncStorage.removeItem(key);
}
throw error;
}
}

/**
* Removes an item from storage.
* @param key - The key of the item to remove.
* @throws Will throw an error if removal fails (except in E2E mode, where it falls back to AsyncStorage).
*
* @example
* try {
* await StorageWrapper.clearAll();
* console.log('All storage data cleared successfully');
* } catch (error) {
* console.error('Failed to clear storage data:', error);
* }
*/
async clearAll() {
await this.storage.clearAll();
}

/**
* Gets the singleton instance of StorageWrapper.
* @returns The StorageWrapper instance.
*/
static getInstance() {
if (!StorageWrapper.instance) {
StorageWrapper.instance = new StorageWrapper();
}
return StorageWrapper.instance;
}
}

export default StorageWrapper.getInstance();
5 changes: 5 additions & 0 deletions app/util/test/network-store.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,11 @@ class ReadOnlyNetworkStore {
delete this._asyncState[key];
}

async clearAll() {
await this._initIfRequired();
delete this._asyncState;
}

async _initIfRequired() {
if (!this._initialized) {
await this._init();
Expand Down

0 comments on commit 5b7b39b

Please sign in to comment.