Skip to content

Commit

Permalink
feat(resiliance): automatically recover from malformed cache files; j…
Browse files Browse the repository at this point in the history
…ust warn and move on
  • Loading branch information
uladkasach committed Nov 25, 2022
1 parent 1b8c298 commit 9bb3569
Showing 1 changed file with 23 additions and 5 deletions.
28 changes: 23 additions & 5 deletions src/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,11 +217,29 @@ export const createCache = ({
key,
});
if (cacheContentSerialized === undefined) return undefined; // if not in cache, then undefined
const cacheContent = JSON.parse(cacheContentSerialized);
if (isRecordExpired(cacheContent)) return undefined; // if already expired, then undefined
if (cacheContent.deserializedForObservability)
return JSON.stringify(cacheContent.value); // if it had been deserialized for observability, reserialize it
return cacheContent.value as string; // otherwise, its in the cache and not expired, so return the value
try {
const cacheContent = JSON.parse(cacheContentSerialized);
if (isRecordExpired(cacheContent)) return undefined; // if already expired, then undefined
if (cacheContent.deserializedForObservability)
return JSON.stringify(cacheContent.value); // if it had been deserialized for observability, reserialize it
return cacheContent.value as string; // otherwise, its in the cache and not expired, so return the value
} catch (error) {
// if it was a json parsing error, warn about it and treat the key as invalid
if (
error instanceof Error &&
error.message.includes('Unexpected string in JSON at position')
) {
// eslint-disable-next-line no-console
console.warn(
'simple-on-disk-cache: detected unparseable cache file. treating the result as invalid. this should not have occured',
{ key },
);
return undefined;
}

// otherwise, propagate the error, we dont know how to handle it
throw error;
}
};

/**
Expand Down

0 comments on commit 9bb3569

Please sign in to comment.