Load activity items from cache immediately, network later

Considerably improves time to first render, and usually there isn't
anything more to load once having opened the cache before in the same
session
This commit is contained in:
raucao committed 2026-09-03 08:16:24 -06:00
1 parent 39e5240af2
commit 1b60915e3f
4 files changed
+215 -121

No files matched your search

+103 -53
View File
@@ -44,6 +44,7 @@ export default class ActivityService extends Service {
_since = null;
_sourceMode = 'home';
_isLoadingMore = false;
_cacheReadyCallback = null;
/**
* Loads the user's incoming zap receipts and social photo activity.
@@ -64,6 +65,9 @@ export default class ActivityService extends Service {
this._userPubkey = pubkey || null;
this._since = Math.floor(Date.now() / 1000) - SINCE_WINDOW;
this.isLoading = true;
this._cacheReadyCallback = () => {
this.isLoading = false;
};
try {
if (pubkey) {
@@ -81,6 +85,7 @@ export default class ActivityService extends Service {
await this._fetchWithBackoff(this._since, now);
} finally {
this.isLoading = false;
this._cacheReadyCallback = null;
}
}
@@ -103,12 +108,16 @@ export default class ActivityService extends Service {
this._mergeItems();
this.isLoading = true;
this._cacheReadyCallback = () => {
this.isLoading = false;
};
try {
const now = Math.floor(Date.now() / 1000);
await this._fetchWithBackoff(this._since, now);
} finally {
this.isLoading = false;
this._cacheReadyCallback = null;
}
}
@@ -159,85 +168,126 @@ export default class ActivityService extends Service {
super.willDestroy(...arguments);
}
/**
* Processes photo events into social items and appends them to the timeline.
*
* @param {object[]} events Photo events to process
* @returns {boolean} True if any items were added
*/
_processPhotoEvents(events) {
if (events.length === 0) return false;
this._lastSocialEvents = [...this._lastSocialEvents, ...events];
const filtered = events.filter((e) => this._matchesSourceMode(e));
if (filtered.length === 0) return false;
const newEntries = groupSocialPhotos(filtered);
for (const entry of newEntries) {
this._resolveSender(entry);
}
for (const entry of newEntries) {
if (entry.osmId) {
const bookmarkName = this.placeNameResolver.resolveBookmark(
entry.osmId
);
if (bookmarkName) {
entry.placeName = bookmarkName;
entry.placeNameLoading = false;
}
}
}
this._socialItems = [...this._socialItems, ...newEntries];
this._mergeItems();
void this.placeNameResolver
.resolveInBackground(newEntries)
.then(() => this._mergeItems());
return true;
}
/**
* Processes zap receipt events and appends them to the timeline.
*
* @param {object[]} events Zap receipt events to process
* @returns {boolean} True if any items were added
*/
_processZapEventsIntoTimeline(events) {
if (events.length === 0) return false;
const newZapEntries = this._processZapEvents(events, this._userPubkey);
if (newZapEntries.length === 0) return false;
this._zapItems = [...this._zapItems, ...newZapEntries];
this._mergeItems();
void this.placeNameResolver
.resolveInBackground(newZapEntries)
.then(() => this._mergeItems());
return true;
}
/**
* Fetches photos and zaps for a single time window, processes them, and
* appends to the respective item arrays.
* appends to the respective item arrays. Cache events are processed first
* (firing `_cacheReadyCallback` to dismiss the loading spinner), then
* network events are awaited and processed.
*
* @param {number} batchSince Start of the window (seconds)
* @param {number} batchUntil End of the window (seconds)
* @returns {Promise<boolean>} True if any events were found
*/
async _fetchAndProcessWindow(batchSince, batchUntil) {
const newEvents = await this.nostrData.fetchActivityPhotos(
const photoResult = await this.nostrData.fetchActivityPhotos(
batchSince,
batchUntil,
this._sourceMode
);
let newZapEvents = [];
let zapResult = {
cacheEvents: [],
networkEvents: Promise.resolve([]),
};
if (this._sourceMode === 'home' && this._userPubkey) {
newZapEvents = await this.nostrData.fetchIncomingZaps(
zapResult = await this.nostrData.fetchIncomingZaps(
this._userPubkey,
batchSince,
batchUntil
);
}
if (newEvents.length === 0 && newZapEvents.length === 0) {
return false;
}
// Phase 1: Process cache events immediately
let added = false;
if (newEvents.length > 0) {
this._lastSocialEvents = [...this._lastSocialEvents, ...newEvents];
const filtered = newEvents.filter((e) => this._matchesSourceMode(e));
if (filtered.length > 0) {
const newEntries = groupSocialPhotos(filtered);
for (const entry of newEntries) {
this._resolveSender(entry);
}
for (const entry of newEntries) {
if (entry.osmId) {
const bookmarkName = this.placeNameResolver.resolveBookmark(
entry.osmId
);
if (bookmarkName) {
entry.placeName = bookmarkName;
entry.placeNameLoading = false;
}
}
}
this._socialItems = [...this._socialItems, ...newEntries];
this._mergeItems();
void this.placeNameResolver
.resolveInBackground(newEntries)
.then(() => this._mergeItems());
added = true;
}
if (photoResult.cacheEvents.length > 0) {
added = this._processPhotoEvents(photoResult.cacheEvents) || added;
}
if (zapResult.cacheEvents.length > 0) {
added =
this._processZapEventsIntoTimeline(zapResult.cacheEvents) || added;
}
if (newZapEvents.length > 0) {
const newZapEntries = this._processZapEvents(
newZapEvents,
this._userPubkey
);
if (newZapEntries.length > 0) {
this._zapItems = [...this._zapItems, ...newZapEntries];
this._mergeItems();
// Signal that cached items are ready for display
if (added) {
this._cacheReadyCallback?.();
}
void this.placeNameResolver
.resolveInBackground(newZapEntries)
.then(() => this._mergeItems());
// Phase 2: Await network events and process them
const [networkPhotos, networkZaps] = await Promise.all([
photoResult.networkEvents,
zapResult.networkEvents,
]);
added = true;
}
if (networkPhotos.length > 0) {
added = this._processPhotoEvents(networkPhotos) || added;
}
if (networkZaps.length > 0) {
added = this._processZapEventsIntoTimeline(networkZaps) || added;
}
return added;
+42 -35
View File
@@ -771,9 +771,10 @@ export default class NostrDataService extends Service {
}
/**
* Fetches kind 360 (Place Photo) events for the activity feed as a Promise
* that resolves on EOSE. Loads from the IDB cache first (instant), then from
* the network with provenance tracking for trust filtering.
* Fetches kind 360 (Place Photo) events for the activity feed.
*
* Returns `{ cacheEvents, networkEvents }` so the caller can show cached
* items instantly while the network request resolves on EOSE.
*
* - `'home'` mode: fetches photos authored by the user's followed contacts
* (followees), batched by author pubkey.
@@ -783,7 +784,7 @@ export default class NostrDataService extends Service {
* @param {number} since Unix timestamp (seconds) for the start of the window
* @param {number} [until] Unix timestamp (seconds) for the end of the window
* @param {string} [mode='home'] Source mode
* @returns {Promise<object[]>} Deduplicated events
* @returns {Promise<{cacheEvents: object[], networkEvents: Promise<object[]>}>}
*/
async fetchActivityPhotos(since, until, mode = 'home') {
let filters;
@@ -791,62 +792,66 @@ export default class NostrDataService extends Service {
const pubkeys = this._contactPubkeys
? Array.from(this._contactPubkeys)
: [];
if (pubkeys.length === 0) return [];
if (pubkeys.length === 0)
return { cacheEvents: [], networkEvents: Promise.resolve([]) };
filters = this._batchAuthorFilters(pubkeys, [360], since, until);
} else if (mode === 'explore') {
const filter = { kinds: [360], since };
if (until !== undefined) filter.until = until;
filters = [filter];
} else {
return [];
return { cacheEvents: [], networkEvents: Promise.resolve([]) };
}
// 1. Populate the store from the local Nostr IDB cache (instant)
const seen = new Set();
const cacheResult = [];
const cacheEvents = await this._cachePromise
.then(() => this.cache.query(filters))
.catch(() => []);
const seen = new Set();
const all = [];
if (cacheEvents) {
for (const event of cacheEvents) {
if (!seen.has(event.id)) {
seen.add(event.id);
all.push(event);
cacheResult.push(event);
this.store.add(event);
}
}
}
// 2. Request fresh events from the network (resolves on EOSE)
const networkEvents = await this._fetchEventsWithProvenance(
const networkEvents = this._fetchEventsWithProvenance(
filters,
'[nostr-data] Error fetching activity photos:'
);
for (const event of networkEvents) {
if (!seen.has(event.id)) {
seen.add(event.id);
all.push(event);
).then((events) => {
const result = [];
for (const event of events) {
if (!seen.has(event.id)) {
seen.add(event.id);
result.push(event);
}
}
}
return result;
});
return all;
return { cacheEvents: cacheResult, networkEvents };
}
/**
* Fetches incoming zap receipts (kind 9735) where the user is the recipient,
* as a Promise that resolves on EOSE. Loads from the IDB cache first, then
* from the network.
* Fetches incoming zap receipts (kind 9735) where the user is the recipient.
*
* Returns `{ cacheEvents, networkEvents }` so the caller can show cached
* items instantly while the network request resolves on EOSE.
*
* @param {string} pubkey The user's Nostr pubkey
* @param {number} [since] Unix timestamp (seconds) for the start of the window
* @param {number} [until] Unix timestamp (seconds) for the end of the window
* @returns {Promise<object[]>} Deduplicated zap receipt events
* @returns {Promise<{cacheEvents: object[], networkEvents: Promise<object[]>}>}
*/
async fetchIncomingZaps(pubkey, since, until) {
if (!pubkey) return [];
if (!pubkey) return { cacheEvents: [], networkEvents: Promise.resolve([]) };
const filter = { kinds: [9735], '#p': [pubkey] };
if (since !== undefined) filter.since = since;
@@ -854,7 +859,7 @@ export default class NostrDataService extends Service {
const filters = [filter];
const seen = new Set();
const all = [];
const cacheResult = [];
// 1. IDB cache
const cacheEvents = await this._cachePromise
@@ -865,26 +870,28 @@ export default class NostrDataService extends Service {
for (const event of cacheEvents) {
if (!seen.has(event.id)) {
seen.add(event.id);
all.push(event);
cacheResult.push(event);
this.store.add(event);
}
}
}
// 2. Network (resolves on EOSE)
const networkEvents = await this._fetchEventsWithProvenance(
const networkEvents = this._fetchEventsWithProvenance(
filters,
'[nostr-data] Error fetching incoming zap receipts:'
);
for (const event of networkEvents) {
if (!seen.has(event.id)) {
seen.add(event.id);
all.push(event);
).then((events) => {
const result = [];
for (const event of events) {
if (!seen.has(event.id)) {
seen.add(event.id);
result.push(event);
}
}
}
return result;
});
return all;
return { cacheEvents: cacheResult, networkEvents };
}
/**
+46 -26
View File
@@ -131,11 +131,11 @@ class MockNostrDataService extends Service {
}
async fetchActivityPhotos() {
return [];
return { cacheEvents: [], networkEvents: Promise.resolve([]) };
}
async fetchIncomingZaps() {
return [];
return { cacheEvents: [], networkEvents: Promise.resolve([]) };
}
getProfile(pubkey) {
@@ -509,8 +509,12 @@ module('Unit | Service | activity', function (hooks) {
});
service.nostrData.fetchActivityPhotos = async (_since, _until, mode) => {
if (mode === 'home') return [followedPhoto];
return [];
if (mode === 'home')
return {
cacheEvents: [followedPhoto],
networkEvents: Promise.resolve([]),
};
return { cacheEvents: [], networkEvents: Promise.resolve([]) };
};
service._updateSocialItems([followedPhoto]);
@@ -572,7 +576,10 @@ module('Unit | Service | activity', function (hooks) {
service.nostrData.fetchActivityPhotos = async (since, until) => {
assert.strictEqual(since, NOW - 30 * 24 * 60 * 60, 'since extended');
assert.strictEqual(until, NOW, 'until set to old since');
return [oldPhoto];
return {
cacheEvents: [oldPhoto],
networkEvents: Promise.resolve([]),
};
};
await service.loadMore();
@@ -623,12 +630,18 @@ module('Unit | Service | activity', function (hooks) {
});
let zapCallCount = 0;
service.nostrData.fetchActivityPhotos = async () => [];
service.nostrData.fetchActivityPhotos = async () => ({
cacheEvents: [],
networkEvents: Promise.resolve([]),
});
service.nostrData.fetchIncomingZaps = async (_pubkey, since, until) => {
zapCallCount++;
assert.strictEqual(since, NOW - 30 * 24 * 60 * 60, 'zap since matches');
assert.strictEqual(until, NOW, 'zap until matches');
return [oldZapReceipt];
return {
cacheEvents: [oldZapReceipt],
networkEvents: Promise.resolve([]),
};
};
await service.loadMore();
@@ -658,15 +671,19 @@ module('Unit | Service | activity', function (hooks) {
service.nostrData.fetchActivityPhotos = async (since, until) => {
callArgs.push({ since, until });
callCount++;
if (callCount < 2) return [];
return [
makePhotoEvent({
id: 'old2'.padEnd(64, '0'),
author: SENDER_PUBKEY,
placeIdentifier: 'osm:node:300',
created_at: NOW - 100000,
}),
];
if (callCount < 2)
return { cacheEvents: [], networkEvents: Promise.resolve([]) };
return {
cacheEvents: [
makePhotoEvent({
id: 'old2'.padEnd(64, '0'),
author: SENDER_PUBKEY,
placeIdentifier: 'osm:node:300',
created_at: NOW - 100000,
}),
],
networkEvents: Promise.resolve([]),
};
};
await service.loadMore();
@@ -699,7 +716,7 @@ module('Unit | Service | activity', function (hooks) {
let callCount = 0;
service.nostrData.fetchActivityPhotos = async () => {
callCount++;
return [];
return { cacheEvents: [], networkEvents: Promise.resolve([]) };
};
await service.loadMore();
@@ -729,14 +746,17 @@ module('Unit | Service | activity', function (hooks) {
let callCount = 0;
service.nostrData.fetchActivityPhotos = async () => {
callCount++;
return [
makePhotoEvent({
id: 'old3'.padEnd(64, '0'),
author: SENDER_PUBKEY,
placeIdentifier: 'osm:node:200',
created_at: NOW - 5000,
}),
];
return {
cacheEvents: [
makePhotoEvent({
id: 'old3'.padEnd(64, '0'),
author: SENDER_PUBKEY,
placeIdentifier: 'osm:node:200',
created_at: NOW - 5000,
}),
],
networkEvents: Promise.resolve([]),
};
};
const promise1 = service.loadMore();
@@ -755,7 +775,7 @@ module('Unit | Service | activity', function (hooks) {
let called = false;
service.nostrData.fetchActivityPhotos = async () => {
called = true;
return [];
return { cacheEvents: [], networkEvents: Promise.resolve([]) };
};
await service.loadMore();
+24 -7
View File
@@ -1068,10 +1068,11 @@ module('Unit | Service | nostr-data | fetchActivityPhotos', function (hooks) {
});
};
const events = await service.fetchActivityPhotos(1000, undefined, 'home');
const result = await service.fetchActivityPhotos(1000, undefined, 'home');
const networkEvents = await result.networkEvents;
assert.ok(
events.some((e) => e.id === photo.id),
networkEvents.some((e) => e.id === photo.id),
'photo event from network returned'
);
});
@@ -1141,9 +1142,19 @@ module('Unit | Service | nostr-data | fetchActivityPhotos', function (hooks) {
service.nostrRelay.pool.req = () => EMPTY;
const events = await service.fetchActivityPhotos(1000, undefined, 'home');
const result = await service.fetchActivityPhotos(1000, undefined, 'home');
assert.strictEqual(events.length, 0, 'empty array when no contacts');
assert.strictEqual(
result.cacheEvents.length,
0,
'empty cache events when no contacts'
);
const networkEvents = await result.networkEvents;
assert.strictEqual(
networkEvents.length,
0,
'empty network events when no contacts'
);
});
test('fetchActivityPhotos deduplicates cache and network events', async function (assert) {
@@ -1170,12 +1181,18 @@ module('Unit | Service | nostr-data | fetchActivityPhotos', function (hooks) {
});
};
const events = await service.fetchActivityPhotos(1000, undefined, 'home');
const result = await service.fetchActivityPhotos(1000, undefined, 'home');
const networkEvents = await result.networkEvents;
assert.strictEqual(
events.filter((e) => e.id === photo.id).length,
result.cacheEvents.filter((e) => e.id === photo.id).length,
1,
'photo appears only once despite being in both cache and network'
'photo appears once in cache events'
);
assert.strictEqual(
networkEvents.filter((e) => e.id === photo.id).length,
0,
'photo not in network events (deduplicated against cache)'
);
});