-
Notifications
You must be signed in to change notification settings - Fork 17
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
improve storage wrapper #1115
Closed
Closed
improve storage wrapper #1115
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,50 +1,19 @@ | ||
import { localExtStorage } from '@penumbra-zone/storage/chrome/local'; | ||
import { WalletJson } from '@penumbra-zone/types/wallet'; | ||
|
||
/** | ||
* When a user first onboards with the extension, they won't have chosen a gRPC | ||
* endpoint yet. So we'll wait until they've chosen one to start trying to make | ||
* requests against it. | ||
*/ | ||
export const onboardGrpcEndpoint = async (): Promise<string> => { | ||
const grpcEndpoint = await localExtStorage.get('grpcEndpoint'); | ||
if (grpcEndpoint) return grpcEndpoint; | ||
|
||
return new Promise(resolve => { | ||
const storageListener = (changes: Record<string, { newValue?: unknown }>) => { | ||
const newValue = changes['grpcEndpoint']?.newValue; | ||
if (newValue && typeof newValue === 'string') { | ||
resolve(newValue); | ||
localExtStorage.removeListener(storageListener); | ||
} | ||
}; | ||
localExtStorage.addListener(storageListener); | ||
}); | ||
}; | ||
|
||
export const onboardWallet = async (): Promise<WalletJson> => { | ||
const wallets = await localExtStorage.get('wallets'); | ||
if (wallets[0]) return wallets[0]; | ||
|
||
return new Promise(resolve => { | ||
const storageListener = (changes: Record<string, { newValue?: unknown }>) => { | ||
const newValue: unknown = changes['wallets']?.newValue; | ||
if (Array.isArray(newValue) && newValue[0]) { | ||
resolve(newValue[0] as WalletJson); | ||
localExtStorage.removeListener(storageListener); | ||
} | ||
}; | ||
localExtStorage.addListener(storageListener); | ||
}); | ||
}; | ||
export const onboardGrpcEndpoint = () => localExtStorage.waitFor('grpcEndpoint'); | ||
export const onboardWallet = () => localExtStorage.waitFor('wallets'); | ||
|
||
/** | ||
This fixes an issue where some users do not have 'grpcEndpoint' set after they have finished onboarding | ||
*/ | ||
export const fixEmptyGrpcEndpointAfterOnboarding = async () => { | ||
console.log('fix grpc endpoint'); | ||
//TODO change to mainnet default RPC | ||
const DEFAULT_GRPC_URL = 'https://grpc.testnet.penumbra.zone'; | ||
const grpcEndpoint = await localExtStorage.get('grpcEndpoint'); | ||
const wallets = await localExtStorage.get('wallets'); | ||
if (!grpcEndpoint && wallets[0]) await localExtStorage.set('grpcEndpoint', DEFAULT_GRPC_URL); | ||
if (!grpcEndpoint && wallets[0]) { | ||
console.log('fixing grpc'); | ||
await localExtStorage.set('grpcEndpoint', DEFAULT_GRPC_URL); | ||
} else console.log('NOT fixing grpc'); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,16 +1,11 @@ | ||
import { EmptyObject, isEmptyObj } from '@penumbra-zone/types/utility'; | ||
|
||
type Listener = (changes: Record<string, { oldValue?: unknown; newValue?: unknown }>) => void; | ||
type ChromeStorageChangedListener = (changes: Record<string, chrome.storage.StorageChange>) => void; | ||
|
||
export interface IStorage { | ||
get(key: string): Promise<Record<string, unknown>>; | ||
set(items: Record<string, unknown>): Promise<void>; | ||
remove(key: string): Promise<void>; | ||
onChanged: { | ||
addListener(listener: Listener): void; | ||
removeListener(listener: Listener): void; | ||
}; | ||
} | ||
// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style | ||
export type StorageListener<T> = ( | ||
changes: Partial<{ [K in keyof T]: { newValue?: StorageItem<T[K]>; oldValue?: unknown } }>, | ||
) => void; | ||
|
||
export interface StorageItem<T> { | ||
version: string; | ||
|
@@ -23,26 +18,36 @@ type Version = string; | |
// See `migration.test.ts` for an example. | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
type Migration = Record<Version, (a: any) => any>; | ||
type Migrations<K extends string | number | symbol> = Partial<Record<K, Migration>>; | ||
|
||
export class ExtensionStorage<T> { | ||
export class ExtensionStorage<T, D extends keyof T> { | ||
constructor( | ||
private storage: IStorage, | ||
private defaults: T, | ||
private storage: chrome.storage.StorageArea, | ||
private defaults: Pick<T, D>, | ||
private version: Version, | ||
private migrations: Migrations<keyof T>, | ||
private migrations: Partial<Record<keyof T, Migration>>, | ||
) {} | ||
|
||
async get<K extends keyof T>(key: K): Promise<T[K]> { | ||
async get<K extends keyof T>(key: K): Promise<Partial<T>[K]> { | ||
console.log('GET', key); | ||
const result = (await this.storage.get(String(key))) as | ||
| Record<K, StorageItem<T[K]>> | ||
| EmptyObject; | ||
|
||
if (isEmptyObj(result)) return this.defaults[key]; | ||
else return await this.migrateIfNeeded(key, result[key]); | ||
// no value in storage | ||
if (isEmptyObj(result)) { | ||
if (key in this.defaults) return this.defaults[key as K & D]; | ||
else return (result as Partial<T>)[key as Exclude<K, D>]; | ||
} | ||
|
||
// old version in storage | ||
if (result[key].version !== this.version) return await this.migrate(key, result[key]); | ||
|
||
// normal case | ||
return result[key].value; | ||
} | ||
Comment on lines
-36
to
47
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ideally, any PR doing this would type the getter such that keys in |
||
|
||
async set<K extends keyof T>(key: K, value: T[K]): Promise<void> { | ||
console.log('SET', key, value); | ||
await this.storage.set({ | ||
[String(key)]: { | ||
version: this.version, | ||
|
@@ -51,31 +56,47 @@ export class ExtensionStorage<T> { | |
}); | ||
} | ||
|
||
async remove<K extends keyof T>(key: K): Promise<void> { | ||
await this.storage.remove(String(key)); | ||
async remove<K extends keyof T & string>(key: K): Promise<void> { | ||
await this.storage.remove(key); | ||
} | ||
|
||
addListener(listener: Listener) { | ||
addListener(listener: ChromeStorageChangedListener & StorageListener<T>): void { | ||
this.storage.onChanged.addListener(listener); | ||
} | ||
|
||
removeListener(listener: Listener) { | ||
this.storage.onChanged.removeListener(listener); | ||
removeListener(remove: ChromeStorageChangedListener): void { | ||
this.storage.onChanged.removeListener(remove); | ||
} | ||
|
||
private async migrateIfNeeded<K extends keyof T>(key: K, item: StorageItem<T[K]>): Promise<T[K]> { | ||
if (item.version !== this.version) { | ||
const migrationFn = this.migrations[key]?.[item.version]; | ||
if (migrationFn) { | ||
// Update the value to latest schema | ||
const transformedVal = migrationFn(item.value) as T[K]; | ||
await this.set(key, transformedVal); | ||
return transformedVal; | ||
} else { | ||
// If there's no migration function, handle it appropriately, possibly by just returning the current value | ||
return item.value; | ||
public async waitFor<K extends keyof T>(key: K): Promise<NonNullable<T[K]>> { | ||
const existing = await this.get(key); | ||
if (existing != null) return existing; | ||
const { promise, resolve, reject } = Promise.withResolvers<NonNullable<T[K]>>(); | ||
const listener: ChromeStorageChangedListener & StorageListener<T> = changes => { | ||
if (key in changes && changes[key]?.newValue != null) { | ||
const newValue = changes[key]?.newValue as StorageItem<T[K]>; | ||
if (typeof newValue === 'object' && 'value' in newValue) { | ||
if (newValue.value != null) resolve(newValue.value); | ||
else reject(new Error('Storage item removed')); | ||
} else reject(new TypeError('Invalid structure in storage update')); | ||
} | ||
}; | ||
void promise.finally(() => this.removeListener(listener)); | ||
this.addListener(listener); | ||
return promise; | ||
} | ||
|
||
private async migrate<K extends keyof T>(key: K, stored: StorageItem<T[K]>): Promise<T[K]> { | ||
const migrateFrom = this.migrations[key]?.[stored.version]; | ||
if (!migrateFrom) { | ||
// No migration, set to bump version | ||
await this.set(key, stored.value); | ||
return stored.value; | ||
} else { | ||
// Run migration, save and bump version | ||
const migratedValue = migrateFrom(stored.value) as T[K]; | ||
await this.set(key, migratedValue); | ||
return migratedValue; | ||
} | ||
return item.value; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
remove extraneous log statements