in modules/example-node/hkr-demo/hkr.ts [56:132]
export async function runRoundTrips(
keyring: KeyringNode,
numRoundTrips: number
) {
// set up spies to monitor network call volume
const kmsSpy = sinon.spy(KMSClient.prototype, 'send')
const ddbSpy = sinon.spy(DynamoDBClient.prototype, 'send')
const padding = String(numRoundTrips).length
let successes = 0
console.log()
console.log(YELLO_LOG, `${keyring.constructor.name} Roundtrips`) // Print constructor name in yellow
console.time('Total runtime') // Start the timer
// for each roundtrip
for (let i = 0; i < numRoundTrips; i++) {
// create an encryption context
const encryptionContext = {
roundtrip: i.toString(),
}
// generate a random string
const encryptionInput = generateRandomString(
MIN_INPUT_LENGTH,
MAX_INPUT_LENGTH
)
// try to do the roundtrip. If any error arises, log it properly
let decryptionOutput: string
try {
const { plaintext } = await roundtrip(
keyring,
encryptionContext,
encryptionInput
)
decryptionOutput = plaintext.toString()
} catch {
decryptionOutput = 'ERROR'
}
const encryptionInputPadding = ' '.repeat(
MAX_INPUT_LENGTH - encryptionInput.length
)
const decryptionOutputPadding = ' '.repeat(
MAX_INPUT_LENGTH - decryptionOutput.length
)
// log message
const logMessage = `Roundtrip ${String(i + 1).padStart(
padding,
' '
)}: ${encryptionInput}${encryptionInputPadding} ----encrypt & decrypt----> ${decryptionOutput}${decryptionOutputPadding}`
// print the log green if successful. Otherwise, red
let logColor: string
if (encryptionInput === decryptionOutput) {
logColor = GREEN_LOG
successes += 1
} else {
logColor = RED_LOG
}
console.log(logColor, logMessage)
}
// print metrics for runtime and call volume
console.log()
console.log(YELLO_LOG, `${keyring.constructor.name} metrics`) // Print constructor name in yellow
console.timeEnd('Total runtime')
console.log(PURPLE_LOG, `KMS calls: ${kmsSpy.callCount}`)
console.log(PURPLE_LOG, `DynamoDB calls: ${ddbSpy.callCount}`)
console.log(
PURPLE_LOG,
`Successful roundtrips: ${successes} / ${numRoundTrips}`
)
kmsSpy.restore()
ddbSpy.restore()
}