Files
bpsets/src/Memorizer.ts

63 lines
1.7 KiB
TypeScript
Raw Normal View History

2024-12-23 21:52:08 +09:00
import { Client } from '@smithy/smithy-client'
import shajs from 'sha.js'
2024-12-24 10:36:06 +09:00
/**
* Memorize AWS SDK operation results.
* This util class tend to be always re-use AWS SDK Client
* which makes operation more faster and optimize memory usage.
*
* All results will be store as Key-Value hash map.
* * Key: sha256(serialize([OPERATION_NAME, OPERATION_INPUT_PARAMETER]))
* * Value: OPERATION_OUTPUT
*
* @author Minhyeok Park <pmh_only@pmh.codes>
*/
2024-12-23 21:52:08 +09:00
export class Memorizer {
private static memorized = new Map<string, Memorizer>()
2024-12-30 11:19:53 +09:00
public static memo(client: Client<any, any, any, any>, salt = '') {
2024-12-26 11:53:29 +09:00
const serialized = JSON.stringify([client.constructor.name, salt])
const hashed = shajs('sha256').update(serialized).digest('hex')
const memorized = this.memorized.get(hashed)
2024-12-23 21:52:08 +09:00
if (memorized !== undefined)
return memorized
const newMemo = new Memorizer(client)
2024-12-26 11:53:29 +09:00
this.memorized.set(hashed, newMemo)
2024-12-23 21:52:08 +09:00
return newMemo
}
2024-12-30 11:19:53 +09:00
public static reset() {
for (const memorized of Memorizer.memorized.values())
memorized.reset()
}
2024-12-23 21:52:08 +09:00
private memorized = new Map<string, any>()
private constructor (
private client: Client<any, any, any, any>
) {}
public readonly send: typeof this.client.send = async (command) => {
const serialized = JSON.stringify([command.constructor.name, command.input])
const hashed = shajs('sha256').update(serialized).digest('hex')
const memorized = this.memorized.get(hashed)
if (memorized !== undefined)
return memorized
2024-12-30 11:19:53 +09:00
console.log(command.constructor.name, 'Executed.')
2024-12-23 21:52:08 +09:00
const newMemo = await this.client.send(command)
this.memorized.set(hashed, newMemo)
return newMemo
}
2024-12-30 11:19:53 +09:00
private readonly reset = () =>
this.memorized.clear()
2024-12-23 21:52:08 +09:00
}