APISigner: refactor with InternalRelay

This commit is contained in:
Alex Gleason 2024-04-25 18:28:19 -05:00
parent 7aa931a69e
commit 05534d532b
No known key found for this signature in database
GPG Key ID: 7211D1F99744FBB7
3 changed files with 31 additions and 20 deletions

View File

@ -6,7 +6,7 @@ import { Stickynotes } from '@/deps.ts';
import { connectResponseSchema } from '@/schemas/nostr.ts';
import { jsonSchema } from '@/schema.ts';
import { AdminSigner } from '@/signers/AdminSigner.ts';
import { Sub } from '@/subs.ts';
import { Storages } from '@/storages.ts';
import { eventMatchesTemplate } from '@/utils.ts';
import { createAdminEvent } from '@/utils/api.ts';
@ -78,16 +78,14 @@ export class APISigner implements NostrSigner {
messageId: string,
template: Omit<NostrEvent, 'id' | 'pubkey' | 'sig'>,
): Promise<NostrEvent> {
const sub = Sub.sub(messageId, '1', [{ kinds: [24133], authors: [pubkey], '#p': [Conf.pubkey] }]);
const sub = Storages.pubsub.req(
[{ kinds: [24133], authors: [pubkey], '#p': [Conf.pubkey] }],
{ signal: this.#c.req.raw.signal },
);
const close = (): void => {
Sub.close(messageId);
this.#c.req.raw.signal.removeEventListener('abort', close);
};
this.#c.req.raw.signal.addEventListener('abort', close);
for await (const event of sub) {
for await (const msg of sub) {
if (msg[0] === 'EVENT') {
const event = msg[2];
const decrypted = await new AdminSigner().nip04.decrypt(event.pubkey, event.content);
const result = jsonSchema
@ -97,10 +95,10 @@ export class APISigner implements NostrSigner {
.safeParse(decrypted);
if (result.success) {
close();
return result.data.result;
}
}
}
throw new HTTPException(408, {
res: this.#c.json({ id: 'ditto.timeout', error: 'Signing timeout' }),

View File

@ -8,6 +8,7 @@ import { Optimizer } from '@/storages/optimizer.ts';
import { PoolStore } from '@/storages/pool-store.ts';
import { Reqmeister } from '@/storages/reqmeister.ts';
import { SearchStore } from '@/storages/search-store.ts';
import { InternalRelay } from '@/storages/InternalRelay.ts';
import { Time } from '@/utils/time.ts';
/** Relay pool storage. */
@ -43,4 +44,16 @@ const searchStore = new SearchStore({
fallback: optimizer,
});
export class Storages {
private static _subsub: InternalRelay | undefined;
static get pubsub(): InternalRelay {
if (!this._subsub) {
this._subsub = new InternalRelay();
}
return this._subsub;
}
}
export { cache, client, eventsDB, optimizer, reqmeister, searchStore };

View File

@ -23,7 +23,7 @@ export class InternalRelay implements NRelay {
async *req(
filters: NostrFilter[],
opts: { signal?: AbortSignal },
opts?: { signal?: AbortSignal },
): AsyncGenerator<NostrRelayEVENT | NostrRelayEOSE | NostrRelayCLOSED> {
const id = crypto.randomUUID();
const machina = new Machina<NostrEvent>(opts?.signal);