Skip to content

Commit

Permalink
fix cachingSub behavior.
Browse files Browse the repository at this point in the history
  • Loading branch information
fiatjaf committed Sep 14, 2023
1 parent 1cf44fa commit 087061c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
14 changes: 13 additions & 1 deletion src/lib/cards/Relay.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,26 @@
import { parsePlainText } from '$lib/articleParser';
import UserLabel from '$components/UserLabel.svelte';
import { next } from '$lib/utils';
import { cachingSub, getA, wikiKind } from '$lib/nostr';
export let tab: Tab;
export let replaceSelf: (tab: Tab) => void;
export let createChild: (tab: Tab) => void;
let results: Event[] = [];
let tried = false;
onMount(() => {});
onMount(() => {
return cachingSub(
`relay-${tab.data}`,
tab.data,
{ kinds: [wikiKind], limit: 25 },
handleUpdate,
getA
);
function handleUpdate(events: Event[]) {
results = events;
}
});
function openArticle(result: Event, ev: MouseEvent) {
let articleTab: ArticleTab = { id: next(), type: 'article', data: result.id };
Expand Down
17 changes: 11 additions & 6 deletions src/lib/nostr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ export function cachingSub(
relays: string[],
filter: Filter,
hook: HookFunc,
keyfn: KeyFunc | null = null
keyfn: KeyFunc = (event: Event) => event.id
): CancelFunc {
const invokeHook = debounce(() => {
const s = _subscriptions[name];
Expand All @@ -178,18 +178,23 @@ export function cachingSub(
const cache = new Map<string, Event>();
_subscriptions[name] = { cache, hook, cancel };

if (!keyfn) {
keyfn = (event) => event.id;
}

relays.forEach(async (url) => {
const r = await ensureRelay(url);
const subscription = r.sub([filter], {
id: name,
alreadyHaveEvent: (id, relay) => {
const event = cachedArticles.get(id);
if (event) {
// we already have this event, so no need to parse it again
cacheSeenOn(event, relay);

// if we didn't have this in the cache yet we add it then trigger the hook
const k = keyfn(event);
if (!cache.has(k)) {
cache.set(k, event);
invokeHook();
}

return true;
}
return false;
Expand All @@ -199,7 +204,7 @@ export function cachingSub(
subs.push(subscription);

subscription.on('event', (event) => {
_subscriptions[name]?.cache?.set?.(event.id, event);
_subscriptions[name]?.cache?.set?.(keyfn(event), event);
if (event.kind === wikiKind) {
if (!cachedArticles.has(event.id)) {
// only set if not already set otherwise we lose the seenOn stuff
Expand Down

0 comments on commit 087061c

Please sign in to comment.