Skip to content

Commit

Permalink
fix: prevent caching of per-invocation constants (#21)
Browse files Browse the repository at this point in the history
  • Loading branch information
bchrobot authored Mar 21, 2020
1 parent c58dc35 commit d241e8e
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 9 deletions.
15 changes: 9 additions & 6 deletions lib/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@ const CacheKeys = Object.freeze({

const TTL_404 = 5 * 60;

// Expire record at the end of the day. Only need to compute these once per invocation
const cacheTtl = moment()
.endOf("day")
.diff(moment(), "seconds");
const cacheOpts = { ttl: cacheTtl, tags: [CacheKeys.EntryTag] };
// Expire record at the end of the day. Compute every time to prevent caching by Fly
const eodTtl = () =>
moment()
.endOf("day")
.diff(moment(), "seconds");

const eodCacheOpts = () => ({ ttl: eodTtl(), tags: [CacheKeys.EntryTag] });

const regexReducer = (acc: string[][], current: LinkRecord): string[][] =>
acc.concat([[current.from, current.to]]);
Expand All @@ -38,6 +40,7 @@ const getEntry = async (path: string) =>
cache.getString(`${CacheKeys.EntryTag}:${path}`);

const setEntry = async (path: string, content: string, ttl?: number) => {
const cacheOpts = eodCacheOpts();
const options = ttl ? Object.assign(cacheOpts, { ttl }) : cacheOpts;
// Prefix path to avoid collisions with internal cache keys
return cache.set(`${CacheKeys.EntryTag}:${path}`, content, options);
Expand All @@ -53,7 +56,7 @@ const getRegexEntries = async (): Promise<string[][]> => {
const setRegexEntries = async (entries: LinkRecord[]) => {
const regexEntries = entries.reduce(regexReducer, []);
const regexEntry = JSON.stringify(regexEntries);
return cache.set(CacheKeys.RegexEntries, regexEntry, { ttl: cacheTtl });
return cache.set(CacheKeys.RegexEntries, regexEntry, { ttl: eodTtl() });
};

export const normalize = (str: string) => str.toLowerCase().trim();
Expand Down
4 changes: 1 addition & 3 deletions lib/shortener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,14 @@ export const refreshCache = async (path?: string) => {
return Promise.all([regexEntriesPromise, ...regularEntriesPromise]);
};

// Only need to compute these once per invocation
const currentYYMMDD = moment().format("YYMMDD");

/**
* Create a one-day cache entry for a short link record containing minimal html comprised of the
* destination URLs metadata, if it can be fetched, and the necessary redirect meta tag.
*
* @param record The short link record from the source spreadsheet to persist
*/
const persistRecordWithMetadata = async (record: LinkRecord) => {
const currentYYMMDD = moment().format("YYMMDD");
const destination = record.to.replace(/YYMMDD/g, currentYYMMDD);

try {
Expand Down

0 comments on commit d241e8e

Please sign in to comment.