Merge branch 'policy-once' into 'main'

Import the custom policy only once

See merge request soapbox-pub/ditto!340
This commit is contained in:
Alex Gleason 2024-05-31 19:00:07 +00:00
commit 2c5c093a39
3 changed files with 28 additions and 21 deletions

View File

@ -1,4 +1,4 @@
import { NKinds, NostrEvent, NPolicy, NSchema as n } from '@nostrify/nostrify';
import { NKinds, NostrEvent, NSchema as n } from '@nostrify/nostrify';
import { PipePolicy } from '@nostrify/nostrify/policies';
import Debug from '@soapbox/stickynotes/debug';
import { sql } from 'kysely';
@ -58,24 +58,10 @@ async function handleEvent(event: DittoEvent, signal: AbortSignal): Promise<void
async function policyFilter(event: NostrEvent): Promise<void> {
const debug = Debug('ditto:policy');
const policies: NPolicy[] = [
const policy = new PipePolicy([
new MuteListPolicy(Conf.pubkey, await Storages.admin()),
];
try {
await policyWorker.import(Conf.policy);
policies.push(policyWorker);
debug(`Using custom policy: ${Conf.policy}`);
} catch (e) {
if (e.message.includes('Module not found')) {
debug('Custom policy not found <https://docs.soapbox.pub/ditto/policies/>');
} else {
console.error(`DITTO_POLICY (error importing policy): ${Conf.policy}`, e);
throw new RelayError('blocked', 'policy could not be loaded');
}
}
const policy = new PipePolicy(policies.reverse());
policyWorker,
]);
try {
const result = await policy.call(event);

View File

@ -1,8 +1,11 @@
import { Stickynotes } from '@soapbox/stickynotes';
import * as Comlink from 'comlink';
import { Conf } from '@/config.ts';
import type { CustomPolicy } from '@/workers/policy.worker.ts';
const console = new Stickynotes('ditto:policy');
export const policyWorker = Comlink.wrap<CustomPolicy>(
new Worker(
new URL('./policy.worker.ts', import.meta.url),
@ -19,3 +22,14 @@ export const policyWorker = Comlink.wrap<CustomPolicy>(
},
),
);
try {
await policyWorker.import(Conf.policy);
console.debug(`Using custom policy: ${Conf.policy}`);
} catch (e) {
if (e.message.includes('Module not found')) {
console.debug('Custom policy not found <https://docs.soapbox.pub/ditto/policies/>');
} else {
throw new Error(`DITTO_POLICY (error importing policy): ${Conf.policy}`, e);
}
}

View File

@ -1,6 +1,6 @@
import 'deno-safe-fetch/load';
import { NostrEvent, NostrRelayOK, NPolicy } from '@nostrify/nostrify';
import { ReadOnlyPolicy } from '@nostrify/nostrify/policies';
import { NoOpPolicy, ReadOnlyPolicy } from '@nostrify/nostrify/policies';
import * as Comlink from 'comlink';
export class CustomPolicy implements NPolicy {
@ -12,8 +12,15 @@ export class CustomPolicy implements NPolicy {
}
async import(path: string): Promise<void> {
const Policy = (await import(path)).default;
this.policy = new Policy();
try {
const Policy = (await import(path)).default;
this.policy = new Policy();
} catch (e) {
if (e.message.includes('Module not found')) {
this.policy = new NoOpPolicy();
}
throw e;
}
}
}