Co-authored-by: Chaim Marcus <chaim@marcus-law.co.il> Co-committed-by: Chaim Marcus <chaim@marcus-law.co.il>
275 lines
9.7 KiB
TypeScript
275 lines
9.7 KiB
TypeScript
/// <reference types="node" />
|
||
|
||
import assert from "node:assert/strict";
|
||
import { test } from "node:test";
|
||
// Excluded from tsc (tsconfig.json) — never bundled/emitted, run natively via
|
||
// `node --test`, which requires the literal `.ts` extension (Node's ESM
|
||
// resolver does not remap `.js` specifiers to `.ts` files at runtime).
|
||
import { PLUGIN_RPC_ERROR_CODES } from "@paperclipai/plugin-sdk";
|
||
import {
|
||
_resetApiBaseCacheMemo,
|
||
CompanyScopeUnavailableError,
|
||
isCompanyScopeDenied,
|
||
type ResolveApiBaseDeps,
|
||
resolveApiBaseFrom,
|
||
runJobHandler,
|
||
} from "./company-scope.ts";
|
||
|
||
// ── isCompanyScopeDenied ─────────────────────────────────────────────────
|
||
|
||
test("isCompanyScopeDenied: true עבור אובייקט עם code של INVOCATION_SCOPE_DENIED", () => {
|
||
const err = { code: PLUGIN_RPC_ERROR_CODES.INVOCATION_SCOPE_DENIED };
|
||
assert.equal(isCompanyScopeDenied(err), true);
|
||
});
|
||
|
||
test("isCompanyScopeDenied: false עבור שגיאה רגילה", () => {
|
||
assert.equal(isCompanyScopeDenied(new Error("boom")), false);
|
||
assert.equal(isCompanyScopeDenied({ code: -32002 }), false);
|
||
assert.equal(isCompanyScopeDenied("boom"), false);
|
||
assert.equal(isCompanyScopeDenied(null), false);
|
||
assert.equal(isCompanyScopeDenied(undefined), false);
|
||
});
|
||
|
||
// ── runJobHandler ────────────────────────────────────────────────────────
|
||
|
||
function makeLogger() {
|
||
const calls: Array<{ level: string; message: string; meta?: unknown }> = [];
|
||
return {
|
||
calls,
|
||
logger: {
|
||
error(message: string, meta?: Record<string, unknown>) {
|
||
calls.push({ level: "error", message, meta });
|
||
},
|
||
},
|
||
};
|
||
}
|
||
|
||
test("runJobHandler: הצלחה — לא זורק ולא מלוגג שגיאה", async () => {
|
||
const { calls, logger } = makeLogger();
|
||
await runJobHandler("test-job", logger, async () => {});
|
||
assert.equal(calls.length, 0);
|
||
});
|
||
|
||
test("runJobHandler: כשל בשגיאה רגילה — מלוגג error וזורק מחדש את המקורית", async () => {
|
||
const { calls, logger } = makeLogger();
|
||
const original = new Error("plain failure");
|
||
await assert.rejects(
|
||
() =>
|
||
runJobHandler("test-job", logger, async () => {
|
||
throw original;
|
||
}),
|
||
(err: unknown) => err === original,
|
||
);
|
||
assert.equal(calls.length, 1);
|
||
assert.equal(calls[0].message, "test-job: job failed");
|
||
});
|
||
|
||
test("runJobHandler: כשל בדחיית-scope — זורק CompanyScopeUnavailableError שמזכירה #637", async () => {
|
||
const { logger } = makeLogger();
|
||
const scopeErr = { code: PLUGIN_RPC_ERROR_CODES.INVOCATION_SCOPE_DENIED };
|
||
await assert.rejects(
|
||
() =>
|
||
runJobHandler("sync-case-status", logger, async () => {
|
||
throw scopeErr;
|
||
}),
|
||
(err: unknown) => {
|
||
assert.ok(err instanceof CompanyScopeUnavailableError);
|
||
assert.match(err.message, /#637/);
|
||
assert.equal(err.jobKey, "sync-case-status");
|
||
assert.equal(err.cause, scopeErr);
|
||
return true;
|
||
},
|
||
);
|
||
});
|
||
|
||
test("runJobHandler: כשל בדחיית-scope — ההודעה כוללת גם #637 וגם את טקסט השגיאה המקורית (זה מה שנכתב ל-plugin_job_runs.error)", async () => {
|
||
const { logger } = makeLogger();
|
||
// כמו JsonRpcCallError אמיתי מהמארח (protocol.js): מופע Error שה-`message`
|
||
// שלו נושא את שם-הפעולה שנדחתה.
|
||
const scopeErr = Object.assign(new Error("issues.list"), {
|
||
code: PLUGIN_RPC_ERROR_CODES.INVOCATION_SCOPE_DENIED,
|
||
});
|
||
await assert.rejects(
|
||
() =>
|
||
runJobHandler("route-pending-comments", logger, async () => {
|
||
throw scopeErr;
|
||
}),
|
||
(err: unknown) => {
|
||
assert.ok(err instanceof CompanyScopeUnavailableError);
|
||
assert.match(err.message, /#637/);
|
||
assert.match(err.message, /issues\.list/);
|
||
// method לא ידוע ל-runJobHandler — "unknown" לא אמור להופיע בהודעה.
|
||
assert.doesNotMatch(err.message, /"unknown"/);
|
||
return true;
|
||
},
|
||
);
|
||
});
|
||
|
||
// ── resolveApiBaseFrom ───────────────────────────────────────────────────
|
||
|
||
function makeDeps(
|
||
overrides: Partial<ResolveApiBaseDeps> & {
|
||
configByCompany?: Record<string, Record<string, unknown> | undefined>;
|
||
deniedCompanyIds?: readonly (string | undefined)[];
|
||
failingCompanyIds?: readonly (string | undefined)[];
|
||
} = {},
|
||
): ResolveApiBaseDeps & {
|
||
cacheWrites: string[];
|
||
infoLogs: unknown[];
|
||
warnLogs: unknown[];
|
||
} {
|
||
const {
|
||
configByCompany = {},
|
||
deniedCompanyIds = [],
|
||
failingCompanyIds = [],
|
||
...rest
|
||
} = overrides;
|
||
const cacheWrites: string[] = [];
|
||
const infoLogs: unknown[] = [];
|
||
const warnLogs: unknown[] = [];
|
||
let cacheValue: unknown = null;
|
||
|
||
const deniedKey = (id?: string) => (id === undefined ? "__undefined__" : id);
|
||
|
||
const deps: ResolveApiBaseDeps & {
|
||
cacheWrites: string[];
|
||
infoLogs: unknown[];
|
||
warnLogs: unknown[];
|
||
} = {
|
||
knownCompanyIds: [],
|
||
defaultBaseUrl: "http://localhost:8085",
|
||
async readConfig(companyId?: string) {
|
||
const key = deniedKey(companyId);
|
||
if (deniedCompanyIds.some((d) => deniedKey(d) === key)) {
|
||
throw { code: PLUGIN_RPC_ERROR_CODES.INVOCATION_SCOPE_DENIED };
|
||
}
|
||
if (failingCompanyIds.some((d) => deniedKey(d) === key)) {
|
||
throw new Error(`boom for ${key}`);
|
||
}
|
||
return configByCompany[key] ?? null;
|
||
},
|
||
async readCache() {
|
||
return cacheValue;
|
||
},
|
||
async writeCache(url: string) {
|
||
cacheValue = url;
|
||
cacheWrites.push(url);
|
||
},
|
||
logger: {
|
||
info(message: string, meta?: Record<string, unknown>) {
|
||
infoLogs.push({ message, meta });
|
||
},
|
||
warn(message: string, meta?: Record<string, unknown>) {
|
||
warnLogs.push({ message, meta });
|
||
},
|
||
},
|
||
cacheWrites,
|
||
infoLogs,
|
||
warnLogs,
|
||
...rest,
|
||
};
|
||
// Allow overriding cache seed via readCache in `rest`.
|
||
return deps;
|
||
}
|
||
|
||
test("resolveApiBaseFrom: companyId נתון ו-readConfig מחזיר legalApiBaseUrl — מחזיר וכותב cache", async () => {
|
||
_resetApiBaseCacheMemo();
|
||
const deps = makeDeps({
|
||
configByCompany: { "company-a": { legalApiBaseUrl: "https://a.example" } },
|
||
});
|
||
const result = await resolveApiBaseFrom({ ...deps, companyId: "company-a" });
|
||
assert.equal(result, "https://a.example");
|
||
assert.deepEqual(deps.cacheWrites, ["https://a.example"]);
|
||
});
|
||
|
||
test('resolveApiBaseFrom: אין companyId — readConfig(undefined) מוסק ע"י המארח ומחזיר ערך', async () => {
|
||
_resetApiBaseCacheMemo();
|
||
const deps = makeDeps({
|
||
configByCompany: {
|
||
__undefined__: { legalApiBaseUrl: "https://derived.example" },
|
||
},
|
||
});
|
||
const result = await resolveApiBaseFrom(deps);
|
||
assert.equal(result, "https://derived.example");
|
||
assert.deepEqual(deps.cacheWrites, ["https://derived.example"]);
|
||
});
|
||
|
||
test("resolveApiBaseFrom: כל הקריאות נדחות ב-scope, יש cache תקף — מחזיר cache ומלוגג info (לא warn)", async () => {
|
||
_resetApiBaseCacheMemo();
|
||
const deps = makeDeps({
|
||
knownCompanyIds: ["c1", "c2"],
|
||
deniedCompanyIds: [undefined, "c1", "c2"],
|
||
});
|
||
// לדמות מטמון קיים: לעקוף readCache
|
||
deps.readCache = async () => "https://cached.example";
|
||
const result = await resolveApiBaseFrom(deps);
|
||
assert.equal(result, "https://cached.example");
|
||
assert.equal(deps.warnLogs.length, 0);
|
||
assert.equal(deps.infoLogs.length, 1);
|
||
});
|
||
|
||
test("resolveApiBaseFrom: כל הקריאות נדחות ב-scope ואין cache — זורק CompanyScopeUnavailableError (לא default)", async () => {
|
||
_resetApiBaseCacheMemo();
|
||
const deps = makeDeps({
|
||
knownCompanyIds: ["c1"],
|
||
deniedCompanyIds: [undefined, "c1"],
|
||
});
|
||
await assert.rejects(
|
||
() => resolveApiBaseFrom(deps),
|
||
(err: unknown) => {
|
||
assert.ok(err instanceof CompanyScopeUnavailableError);
|
||
assert.equal(err.method, "config.get");
|
||
return true;
|
||
},
|
||
);
|
||
});
|
||
|
||
test("resolveApiBaseFrom: readConfig הצליח בכל מקום אך בלי legalApiBaseUrl — default + warn", async () => {
|
||
_resetApiBaseCacheMemo();
|
||
const deps = makeDeps({
|
||
knownCompanyIds: ["c1"],
|
||
configByCompany: { __undefined__: {}, c1: {} },
|
||
});
|
||
const result = await resolveApiBaseFrom(deps);
|
||
assert.equal(result, deps.defaultBaseUrl);
|
||
assert.equal(deps.warnLogs.length, 1);
|
||
});
|
||
|
||
test("resolveApiBaseFrom: readConfig נכשל בשגיאה שאינה דחיית-scope — warn וממשיך לנסות הבא", async () => {
|
||
_resetApiBaseCacheMemo();
|
||
const deps = makeDeps({
|
||
knownCompanyIds: ["c1"],
|
||
failingCompanyIds: [undefined],
|
||
configByCompany: { c1: { legalApiBaseUrl: "https://c1.example" } },
|
||
});
|
||
const result = await resolveApiBaseFrom(deps);
|
||
assert.equal(result, "https://c1.example");
|
||
// warn אחד על הכשל ב-readConfig(undefined) — לא בליעה שקטה
|
||
assert.ok(deps.warnLogs.length >= 1);
|
||
});
|
||
|
||
// ── writeCache dedup (מתוזמן פר-בקשה, לא לכתוב cache שלא השתנה) ──────────
|
||
|
||
test("resolveApiBaseFrom: כותב ל-cache רק כשהערך משתנה בפועל", async () => {
|
||
_resetApiBaseCacheMemo();
|
||
const deps = makeDeps({
|
||
configByCompany: {
|
||
"company-a": { legalApiBaseUrl: "https://dedup.example" },
|
||
},
|
||
});
|
||
|
||
// שתי פתירות רצופות של אותו URL — writeCache נקרא פעם אחת בלבד.
|
||
await resolveApiBaseFrom({ ...deps, companyId: "company-a" });
|
||
await resolveApiBaseFrom({ ...deps, companyId: "company-a" });
|
||
assert.deepEqual(deps.cacheWrites, ["https://dedup.example"]);
|
||
|
||
// פתירה של URL שונה אחריהן — writeCache נקרא שוב.
|
||
const deps2 = makeDeps({
|
||
configByCompany: {
|
||
"company-b": { legalApiBaseUrl: "https://dedup-2.example" },
|
||
},
|
||
});
|
||
await resolveApiBaseFrom({ ...deps2, companyId: "company-b" });
|
||
assert.deepEqual(deps2.cacheWrites, ["https://dedup-2.example"]);
|
||
});
|