Skip to content

Commit

Permalink
Refactor BotState cache hash string
Browse files Browse the repository at this point in the history
  • Loading branch information
sw-joelmut committed Jan 25, 2024
1 parent 08351d8 commit bcd9c4d
Showing 1 changed file with 33 additions and 4 deletions.
37 changes: 33 additions & 4 deletions libraries/botbuilder-core/src/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import * as z from 'zod';
import { TurnContext } from './turnContext';
import { createHash } from 'crypto';

/**
* Callback to calculate a storage key.
Expand Down Expand Up @@ -127,10 +128,38 @@ export function assertStoreItems(val: unknown, ..._args: unknown[]): asserts val
* @returns change hash string
*/
export function calculateChangeHash(item: StoreItem): string {
const cpy = { ...item };
if (cpy.eTag) {
delete cpy.eTag;
let result = '';
if (!item) {
return result;
}

return JSON.stringify(cpy);
const { eTag, ...rest } = item;

try {
result = JSON.stringify(rest);
} catch (error) {
if (!error?.message.includes('circular structure')) {
throw error;
}

const seen = new WeakMap();
result = JSON.stringify(rest, function circularReplacer(key, value) {
if (value === null || value === undefined || typeof value !== 'object') {
return value;
}

const path = seen.get(value);
if (path) {
return `[Circular *${path.join('.')}]`;
}

const parent = seen.get(this) ?? [];
seen.set(value, [...parent, key]);
return value;
});
}

const hash = createHash('sha256', { encoding: 'utf-8' });
const hashed = hash.update(result).digest('hex');
return hashed;
}

0 comments on commit bcd9c4d

Please sign in to comment.