Skip to content
This repository has been archived by the owner on Dec 27, 2022. It is now read-only.

Commit

Permalink
Add a little more flexibility to the home feed cache
Browse files Browse the repository at this point in the history
  • Loading branch information
pfrazee committed Apr 26, 2021
1 parent b300a55 commit d76a2a7
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 9 deletions.
12 changes: 6 additions & 6 deletions db/feed-getters.js
Expand Up @@ -11,17 +11,18 @@ const lexintEncoder = lexint('hex')
export async function listHomeFeed (opts, auth) {
opts = opts && typeof opts === 'object' ? opts : {}
const didSpecifyLt = !!opts.lt
const limit = Math.min(opts?.limit || 100, 100)
opts.lt = opts.lt && typeof opts.lt === 'string' ? opts.lt : lexintEncoder.encode(Date.now())

if (!auth) throw new errors.SessionError()
const publicDb = publicDbs.get(auth.userId)
if (!publicDb) throw new errors.NotFoundError('User database not found')

if (!didSpecifyLt && (!opts.limit || opts.limit <= 15)) {
let cached = cache.getHomeFeed(auth.userId)
if (!didSpecifyLt) {
let cached = cache.getHomeFeed(auth.userId, limit)
if (cached) {
debugLog.cacheHit('home-feed', auth.userId)
let cachedEntries = opts.limit ? cached.slice(0, opts.limit) : cached
let cachedEntries = opts.limit ? cached.slice(0, limit) : cached
for (let entry of cachedEntries) {
entry.reactions = (await fetchReactions(entry)).reactions
entry.replyCount = await fetchReplyCount(entry)
Expand Down Expand Up @@ -58,7 +59,6 @@ export async function listHomeFeed (opts, auth) {

const postEntries = []
const authorsCache = {}
const limit = Math.min(opts?.limit || 100, 100)
const mergedCursor = mergeCursors(cursors)
for await (let [db, entry] of mergedCursor) {
if (db.dbType === 'ctzn.network/public-server-db') {
Expand Down Expand Up @@ -88,8 +88,8 @@ export async function listHomeFeed (opts, auth) {
}
}

if (!didSpecifyLt && (!opts.limit || opts.limit >= 15)) {
cache.setHomeFeed(auth.userId, postEntries, 60e3)
if (!didSpecifyLt) {
cache.setHomeFeed(auth.userId, postEntries, limit, 60e3)
}

return postEntries
Expand Down
10 changes: 7 additions & 3 deletions lib/cache.js
Expand Up @@ -4,17 +4,21 @@ export function invalidateHomeFeed (userId) {
delete homeFeedCache[userId]
}

export function getHomeFeed (userId) {
export function getHomeFeed (userId, limit) {
let entry = homeFeedCache[userId]
if (!entry || entry.expires < Date.now()) {
if (!entry || entry.expires < Date.now() || entry.limit < limit) {
return undefined
}
return entry.value
}

export function setHomeFeed (userId, value, ttl) {
export function setHomeFeed (userId, value, limit, ttl) {
if (homeFeedCache[userId] && limit < homeFeedCache[userId].limit) {
return
}
homeFeedCache[userId] = {
expires: Date.now() + ttl,
limit,
value
}
}
Expand Down

0 comments on commit d76a2a7

Please sign in to comment.