Allow non-tuple values

This commit is contained in:
Alex Gleason 2023-03-24 20:06:03 -05:00
parent 2d7d2da964
commit f2f4dd7b8e
No known key found for this signature in database
GPG Key ID: 7211D1F99744FBB7
2 changed files with 14 additions and 7 deletions

View File

@ -13,10 +13,10 @@ import {
const msg = await readStdin(); const msg = await readStdin();
const result = await pipeline(msg, [ const result = await pipeline(msg, [
[noopPolicy], noopPolicy,
[hellthreadPolicy, { limit: 100 }], [hellthreadPolicy, { limit: 100 }],
[antiDuplicationPolicy], antiDuplicationPolicy,
[rateLimitPolicy], rateLimitPolicy,
]); ]);
writeStdout(result); writeStdout(result);

View File

@ -1,15 +1,17 @@
import { InputMessage, OutputMessage, Policy } from './types.ts'; import { InputMessage, OutputMessage, Policy } from './types.ts';
type PolicyTuple<Opts = any> = [policy: Policy<Opts>, opts?: Opts]; type PolicyTuple<Opts = unknown> = [policy: Policy<Opts>, opts?: Opts];
// https://stackoverflow.com/a/75806165
// https://stackoverflow.com/a/54608401
type PolicyTuplesRest<T extends PolicyTuple[]> = { type PolicyTuplesRest<T extends PolicyTuple[]> = {
[K in keyof T]: PolicyTuple<T[K]> [K in keyof T]: PolicyTuple<T[K]> | Policy<T[K]>
} }
/** Processes messages through multiple policies, bailing early on rejection. */ /** Processes messages through multiple policies, bailing early on rejection. */
async function pipeline<P extends any[]>(msg: InputMessage, policies: [...PolicyTuplesRest<P>]): Promise<OutputMessage> { async function pipeline<P extends any[]>(msg: InputMessage, policies: [...PolicyTuplesRest<P>]): Promise<OutputMessage> {
for (const tuple of policies) { for (const item of policies) {
const [policy, opts] = tuple; const [policy, opts] = toTuple(item);
const result = await policy(msg, opts); const result = await policy(msg, opts);
if (result.action !== 'accept') { if (result.action !== 'accept') {
return result; return result;
@ -23,4 +25,9 @@ async function pipeline<P extends any[]>(msg: InputMessage, policies: [...Policy
}; };
} }
/** Coerce item into a tuple if it isn't already. */
function toTuple<T>(item: PolicyTuple<T> | Policy<T>): PolicyTuple<T> {
return typeof item === 'function' ? [item] : item;
}
export default pipeline; export default pipeline;