Skip to content

Commit cf95372

Browse files
committed
Allow passing in extra filters on the session
1 parent a0cb6dc commit cf95372

File tree

9 files changed

+42
-123
lines changed

9 files changed

+42
-123
lines changed

docs/mobile/session.md

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
`ndk-mobile` provides a way to manage session events that are typically necessary to have available throughout an entire app.
44

5-
Wrapping your application with `<NDKSessionProvider>` provides access to the session context.
5+
The `useNDKSession` hook provides access to user's information.
66

77
Say for example you want to allow your user to interface with their bookmarks, you want to have access to their bookmarks anywhere in the app both for reading and writing.
88

@@ -12,9 +12,28 @@ const kinds = new Map([
1212
[NDKKind.ImageCurationSet, { wrapper: NDKList }],
1313
]);
1414

15-
<NDKSessionProvider follows={true} kinds={kinds}>
16-
<YourApp />
17-
</NDKSessionProvider>
15+
const { ndk } = useNDK();
16+
const currentUser = useNDKCurrentUser();
17+
const { init: initializeSession } = useNDKSession();
18+
const follows = useFollws();
19+
const muteList = useMuteList();
20+
21+
useEffect(() => {
22+
if (!currentUser) return;
23+
initializeSession(
24+
ndk,
25+
currentUser,
26+
{
27+
follows: true, // get the user's follow list
28+
muteList: true, // get the user's mute list
29+
}
30+
);
31+
}, [currentUser?.pubkey])
32+
33+
return (<View>
34+
<Text>Follows: {follows ? 'not loaded yet' : follows?.length}</Text>
35+
</View>)
36+
1837
```
1938
2039
Now say you want to allow the user to bookmark something with the click of a button:
@@ -30,7 +49,3 @@ const bookmark = async () => {
3049
```
3150
3251
Now, when your app calls the `bookmark` function, it will add the event to the user's image curation set, if none exists it will create one for you.
33-
34-
```
35-
36-
```

ndk-mobile/src/cache-adapter/sqlite.ts

Lines changed: 3 additions & 93 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,6 @@ type EventRecord = {
2525
relay: string;
2626
};
2727

28-
let processID = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
29-
3028
type UnpublishedEventRecord = {
3129
id: string;
3230
event: string;
@@ -36,32 +34,6 @@ type UnpublishedEventRecord = {
3634

3735
type PendingCallback = (...arg: any) => any;
3836

39-
// Overhead monitoring variables
40-
let foundEventsOverhead = 0;
41-
let queryOverhead = 0;
42-
let setEventOverhead = 0;
43-
let setEventDeletePreviousOverhead = 0;
44-
let setEventInsertEventOverhead = 0;
45-
let setEventInsertTagsOverhead = 0;
46-
let fetchProfileOverhead = 0;
47-
let saveProfileOverhead = 0;
48-
let addUnpublishedEventOverhead = 0;
49-
let getUnpublishedEventsOverhead = 0;
50-
let saveWotOverhead = 0;
51-
let fetchWotOverhead = 0;
52-
setInterval(() => {
53-
// console.log('foundEvents overhead', foundEventsOverhead);
54-
console.log('query overhead', queryOverhead);
55-
console.log('setEventDeletePreviousOverhead', setEventDeletePreviousOverhead);
56-
console.log('setEventInsertEventOverhead', setEventInsertEventOverhead);
57-
console.log('setEventInsertTagsOverhead', setEventInsertTagsOverhead);
58-
// console.log('fetchProfile overhead', fetchProfileOverhead);
59-
// console.log('saveProfile overhead', saveProfileOverhead);
60-
// console.log('addUnpublishedEvent overhead', addUnpublishedEventOverhead);
61-
// console.log('getUnpublishedEvents overhead', getUnpublishedEventsOverhead);
62-
// console.log('saveWot overhead', saveWotOverhead);
63-
// console.log('fetchWot overhead', fetchWotOverhead);
64-
}, 10000);
6537

6638
export class NDKCacheAdapterSqlite implements NDKCacheAdapter {
6739
readonly dbName: string;
@@ -78,9 +50,7 @@ export class NDKCacheAdapterSqlite implements NDKCacheAdapter {
7850
}
7951

8052
private async initialize() {
81-
console.log('initializing cache adapter', this.dbName);
8253
this.db = SQLite.openDatabaseSync(this.dbName);
83-
console.log('cache adapter initialized', this.dbName);
8454

8555
try {
8656
let { user_version: schemaVersion } = (await this.db.getFirstAsync(`PRAGMA user_version;`)) as { user_version: number };
@@ -90,9 +60,7 @@ export class NDKCacheAdapterSqlite implements NDKCacheAdapter {
9060
}
9161

9262
// get current schema version
93-
console.log('getting schema version');
9463
let { user_version: schemaVersion } = (this.db.getFirstSync(`PRAGMA user_version;`)) as { user_version: number };
95-
console.log('schema version', schemaVersion);
9664

9765
if (!schemaVersion) {
9866
schemaVersion = 0;
@@ -102,7 +70,6 @@ export class NDKCacheAdapterSqlite implements NDKCacheAdapter {
10270
}
10371

10472
if (!schemaVersion || Number(schemaVersion) < migrations.length) {
105-
console.log('running migrations', schemaVersion, migrations.length);
10673
await this.db.withTransactionAsync(async () => {
10774
for (let i = Number(schemaVersion); i < migrations.length; i++) {
10875
try {
@@ -117,16 +84,13 @@ export class NDKCacheAdapterSqlite implements NDKCacheAdapter {
11784
// set the schema version
11885
await this.db.execAsync(`PRAGMA user_version = ${migrations.length};`);
11986
});
120-
} else {
121-
console.log('no migrations to run', schemaVersion, migrations.length);
12287
}
12388

12489
this.ready = true;
12590
this.locking = true;
12691

12792
Promise.all(this.pendingCallbacks.map((f) => {
12893
try {
129-
console.log('we are ready: calling callback onReady', f, processID);
13094
return f();
13195
} catch (e) {
13296
console.error('error calling cache adapter pending callback', e);
@@ -152,11 +116,8 @@ export class NDKCacheAdapterSqlite implements NDKCacheAdapter {
152116

153117
async query(subscription: NDKSubscription): Promise<void> {
154118
this.ifReady(() => {
155-
if (subscription.filters.some((filter) => !this.cachableKinds.includes(filter.kinds?.[0]))) return;
156-
console.log('querying', subscription.filters);
119+
// if (subscription.filters.some((filter) => !this.cachableKinds.includes(filter.kinds?.[0]))) return;
157120

158-
const start = performance.now();
159-
160121
// Process filters from the subscription
161122
for (const filter of subscription.filters) {
162123
if (filter.authors) {
@@ -175,31 +136,24 @@ export class NDKCacheAdapterSqlite implements NDKCacheAdapter {
175136
if (events.length > 0) foundEvents(subscription, events, filter);
176137
}
177138
}
178-
179-
const end = performance.now();
180-
queryOverhead += end - start;
181139
});
182140
}
183141

184-
public cachableKinds = [3, 10002, NDKKind.MuteList, NDKKind.BlossomList, NDKKind.Image, NDKKind.Text ];
142+
// public cachableKinds = [3, 10002, NDKKind.MuteList, NDKKind.BlossomList, NDKKind.Image, NDKKind.Text ];
185143

186144
async setEvent(event: NDKEvent, filters: NDKFilter[], relay?: NDKRelay): Promise<void> {
187-
if (!this.cachableKinds.includes(event.kind!)) return;
145+
// if (!this.cachableKinds.includes(event.kind!)) return;
188146

189147
this.onReady(async () => {
190148
// is the event replaceable?
191149
if (event.isReplaceable()) {
192-
const start = performance.now();
193150
await Promise.all([
194151
this.db.runAsync(`DELETE FROM events WHERE id = ?;`, [event.id]),
195152
this.db.runAsync(`DELETE FROM event_tags WHERE event_id = ?;`, [event.id]),
196153
]);
197-
const end = performance.now();
198-
setEventDeletePreviousOverhead += end - start;
199154
return;
200155
}
201156

202-
let start = performance.now();
203157
this.db.runAsync(`INSERT INTO events (id, created_at, pubkey, event, kind, relay) VALUES (?, ?, ?, ?, ?, ?);`, [
204158
event.id,
205159
event.created_at!,
@@ -208,18 +162,13 @@ export class NDKCacheAdapterSqlite implements NDKCacheAdapter {
208162
event.kind!,
209163
relay?.url || '',
210164
])
211-
let end = performance.now();
212-
setEventInsertEventOverhead += end - start;
213165

214-
start = performance.now();
215166
const filterTags: [string, string][] = event.tags.filter((tag) => tag[0].length === 1).map((tag) => [tag[0], tag[1]]);
216167
if (filterTags.length < 10) {
217168
filterTags.forEach((tag) =>
218169
this.db.runAsync(`INSERT INTO event_tags (event_id, tag, value) VALUES (?, ?, ?);`, [event.id, tag[0], tag[1]])
219170
)
220171
}
221-
end = performance.now();
222-
setEventInsertTagsOverhead += end - start;
223172

224173
// if this event is a delete event, see if the deleted events are in the cache and remove them
225174
if (event.kind === NDKKind.EventDeletion) {
@@ -236,12 +185,9 @@ export class NDKCacheAdapterSqlite implements NDKCacheAdapter {
236185
}
237186

238187
fetchProfileSync(pubkey: Hexpubkey): NDKCacheEntry<NDKUserProfile> | null {
239-
const start = performance.now();
240188

241189
const cached = this.profileCache.get(pubkey);
242190
if (cached) {
243-
const end = performance.now();
244-
fetchProfileOverhead += end - start;
245191
return cached;
246192
}
247193

@@ -264,26 +210,18 @@ export class NDKCacheAdapterSqlite implements NDKCacheAdapter {
264210
const profile = JSON.parse(result.profile);
265211
const entry = { ...profile, fetchedAt: result.catched_at };
266212
this.profileCache.set(pubkey, entry);
267-
const end = performance.now();
268-
fetchProfileOverhead += end - start;
269213
return entry;
270214
} catch (e) {
271215
console.error('failed to parse profile', result.profile);
272216
}
273217
}
274218

275-
const end = performance.now();
276-
fetchProfileOverhead += end - start;
277219
return null;
278220
}
279221

280222
async fetchProfile(pubkey: Hexpubkey): Promise<NDKCacheEntry<NDKUserProfile> | null> {
281-
const start = performance.now();
282-
283223
const cached = this.profileCache.get(pubkey);
284224
if (cached) {
285-
const end = performance.now();
286-
fetchProfileOverhead += end - start;
287225
return cached;
288226
}
289227

@@ -298,29 +236,21 @@ export class NDKCacheAdapterSqlite implements NDKCacheAdapter {
298236
const profile = JSON.parse(result.profile);
299237
const entry = { ...profile, fetchedAt: result.catched_at };
300238
this.profileCache.set(pubkey, entry);
301-
const end = performance.now();
302-
fetchProfileOverhead += end - start;
303239
return entry;
304240
} catch (e) {
305241
console.error('failed to parse profile', result.profile);
306242
}
307243
}
308244

309-
const end = performance.now();
310-
fetchProfileOverhead += end - start;
311245
return null;
312246
});
313247
}
314248

315249
async saveProfile(pubkey: Hexpubkey, profile: NDKUserProfile): Promise<void> {
316-
const start = performance.now();
317-
318250
this.onReady(async () => {
319251
// check if the profile we have is newer based on created_at
320252
const existingProfile = await this.fetchProfile(pubkey);
321253
if (existingProfile?.created_at && profile.created_at && existingProfile.created_at >= profile.created_at) {
322-
const end = performance.now();
323-
saveProfileOverhead += end - start;
324254
return;
325255
}
326256

@@ -335,15 +265,11 @@ export class NDKCacheAdapterSqlite implements NDKCacheAdapter {
335265
profile.created_at,
336266
]);
337267

338-
const end = performance.now();
339-
saveProfileOverhead += end - start;
340268
});
341269
}
342270

343271
addUnpublishedEvent(event: NDKEvent, relayUrls: WebSocket['url'][]): void {
344272
this.onReady(async () => {
345-
const start = performance.now();
346-
347273
const relayStatus: { [key: string]: boolean } = {};
348274
relayUrls.forEach(url => relayStatus[url] = false);
349275

@@ -389,15 +315,11 @@ export class NDKCacheAdapterSqlite implements NDKCacheAdapter {
389315
console.error('error adding unpublished event', e);
390316
}
391317

392-
const end = performance.now();
393-
addUnpublishedEventOverhead += end - start;
394318
});
395319
}
396320

397321
async getUnpublishedEvents(): Promise<{ event: NDKEvent; relays?: WebSocket['url'][]; lastTryAt?: number }[]> {
398322
return await this.onReady(async () => {
399-
const start = performance.now();
400-
401323
const call = () => this._getUnpublishedEvents();
402324

403325
if (!this.ready) {
@@ -406,8 +328,6 @@ export class NDKCacheAdapterSqlite implements NDKCacheAdapter {
406328
});
407329
} else {
408330
const result = await call();
409-
const end = performance.now();
410-
getUnpublishedEventsOverhead += end - start;
411331
return result;
412332
}
413333
});
@@ -436,22 +356,16 @@ export class NDKCacheAdapterSqlite implements NDKCacheAdapter {
436356

437357
async saveWot(wot: Map<Hexpubkey, number>) {
438358
this.onReady(async () => {
439-
const start = performance.now();
440359
this.db.runSync(`DELETE FROM wot;`);
441360
for (const [pubkey, value] of wot) {
442361
this.db.runSync(`INSERT INTO wot (pubkey, wot) VALUES (?, ?);`, [pubkey, value]);
443362
}
444-
const end = performance.now();
445-
saveWotOverhead += end - start;
446363
});
447364
}
448365

449366
async fetchWot(): Promise<Map<Hexpubkey, number>> {
450367
return await this.onReady(async () => {
451-
const start = performance.now();
452368
const wot = (await this.db.getAllAsync(`SELECT * FROM wot`)) as { pubkey: string; wot: number }[];
453-
const end = performance.now();
454-
fetchWotOverhead += end - start;
455369
return new Map(wot.map((wot) => [wot.pubkey, wot.wot]));
456370
});
457371
}
@@ -468,7 +382,6 @@ export class NDKCacheAdapterSqlite implements NDKCacheAdapter {
468382
}
469383

470384
export function foundEvents(subscription: NDKSubscription, events: EventRecord[], filter?: NDKFilter) {
471-
const start = performance.now();
472385
// if we have a limit, sort and slice
473386
if (filter?.limit && events.length > filter.limit) {
474387
events = events.sort((a, b) => b.created_at - a.created_at).slice(0, filter.limit);
@@ -477,9 +390,6 @@ export function foundEvents(subscription: NDKSubscription, events: EventRecord[]
477390
for (const event of events) {
478391
foundEvent(subscription, event, event.relay, filter);
479392
}
480-
481-
const end = performance.now();
482-
foundEventsOverhead += end - start;
483393
}
484394

485395
export function foundEvent(subscription: NDKSubscription, event: EventRecord, relayUrl: WebSocket['url'] | undefined, filter?: NDKFilter) {

0 commit comments

Comments
 (0)