125 lines
5.3 KiB
TypeScript
125 lines
5.3 KiB
TypeScript
// @vitest-environment node
|
|
import { beforeEach, describe, expect, test, vi } from "vitest";
|
|
|
|
const integrationMocks = vi.hoisted(() => ({
|
|
cleanupExpiredKwpPendingAttemptsForTenant: vi.fn(),
|
|
executeKwpHealthProbe: vi.fn(),
|
|
listKwpHealthConnectionIdsForTenant: vi.fn(),
|
|
persistKwpHealthProbe: vi.fn(),
|
|
prepareKwpHealthProbeForConnection: vi.fn(),
|
|
refreshExpiringTokensForTenant: vi.fn(),
|
|
sweepConnectionHealthForTenant: vi.fn(),
|
|
}));
|
|
const kwpResourceMocks = vi.hoisted(() => ({
|
|
ensureKwpAccessTokenForConnection: vi.fn(),
|
|
}));
|
|
const dbMocks = vi.hoisted(() => ({ getDbClient: vi.fn() }));
|
|
|
|
vi.mock("@hivegrid/integrations/worker-tasks.server", () => integrationMocks);
|
|
vi.mock("@hivegrid/integrations/kwp-resource-client.server", () => kwpResourceMocks);
|
|
vi.mock("@hivegrid/db/client.server", () => dbMocks);
|
|
|
|
import { buildCleanupJob, queueNames } from "@hivegrid/queue";
|
|
import { createSharedStore, MemoryAdapter } from "@hivegrid/shared-store";
|
|
import { buildHandlerRegistry } from "./handlers.js";
|
|
|
|
describe("KWP demand-driven refresh maintenance", () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
integrationMocks.cleanupExpiredKwpPendingAttemptsForTenant.mockResolvedValue({ restored: 0, purged: 0, failed: 0 });
|
|
integrationMocks.refreshExpiringTokensForTenant.mockResolvedValue({ refreshed: 2, failed: 0 });
|
|
integrationMocks.sweepConnectionHealthForTenant.mockResolvedValue({ checked: 0, unhealthy: 0 });
|
|
integrationMocks.listKwpHealthConnectionIdsForTenant.mockResolvedValue([]);
|
|
kwpResourceMocks.ensureKwpAccessTokenForConnection.mockResolvedValue(undefined);
|
|
});
|
|
|
|
test("keeps KWP out of the minute refresh sweep while retaining generic refresh and pending cleanup", async () => {
|
|
const tx = { $executeRaw: vi.fn(async () => 1) };
|
|
const db = {
|
|
tenant: { findMany: vi.fn(async () => [{ id: "tenant_1" }]) },
|
|
$transaction: vi.fn(async <T>(callback: (transaction: typeof tx) => Promise<T>) => callback(tx)),
|
|
};
|
|
dbMocks.getDbClient.mockResolvedValue(db);
|
|
const logger = { info: vi.fn(), error: vi.fn() };
|
|
const registry = buildHandlerRegistry({
|
|
env: { KWP_HIVEGRID_TENANT_ID: "tenant_1" },
|
|
logger,
|
|
tenantMaintenanceLeaseStore: createSharedStore({ namespace: "kwp-demand-refresh-handler", adapter: new MemoryAdapter() }),
|
|
});
|
|
|
|
await expect(
|
|
registry[queueNames.maintenance](buildCleanupJob({ task: "integrations-token-refresh", olderThanMinutes: 10 }).payload, {}),
|
|
).resolves.toEqual({
|
|
handled: true,
|
|
action: "integrations.token-refresh.completed",
|
|
details: {
|
|
task: "integrations-token-refresh",
|
|
tenants: 1,
|
|
refreshed: 2,
|
|
failed: 0,
|
|
retryScheduled: 0,
|
|
pendingRestored: 0,
|
|
pendingPurged: 0,
|
|
pendingCleanupFailed: 0,
|
|
},
|
|
});
|
|
|
|
expect(integrationMocks.refreshExpiringTokensForTenant).toHaveBeenCalledWith(
|
|
tx,
|
|
"tenant_1",
|
|
{ now: expect.any(Date), windowMs: 10 * 60_000 },
|
|
);
|
|
expect(integrationMocks.cleanupExpiredKwpPendingAttemptsForTenant).toHaveBeenCalledWith(
|
|
tx,
|
|
"tenant_1",
|
|
{ now: expect.any(Date) },
|
|
);
|
|
expect(kwpResourceMocks.ensureKwpAccessTokenForConnection).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("ensures one demand-refreshed token before the scheduled KWP health probe", async () => {
|
|
const tx = { $executeRaw: vi.fn(async () => 1) };
|
|
const db = {
|
|
tenant: { findMany: vi.fn(async () => [{ id: "tenant_1" }]) },
|
|
$transaction: vi.fn(async <T>(callback: (transaction: typeof tx) => Promise<T>) => callback(tx)),
|
|
};
|
|
dbMocks.getDbClient.mockResolvedValue(db);
|
|
integrationMocks.listKwpHealthConnectionIdsForTenant.mockResolvedValue(["kwp_connection_1"]);
|
|
const snapshot = { tenantId: "tenant_1", connectionId: "kwp_connection_1" };
|
|
integrationMocks.prepareKwpHealthProbeForConnection.mockResolvedValue({ state: "ready", snapshot });
|
|
integrationMocks.executeKwpHealthProbe.mockResolvedValue({ health: "active", messageKey: "integrations.kwp.health.active" });
|
|
integrationMocks.persistKwpHealthProbe.mockResolvedValue({ checked: 1, unhealthy: 0 });
|
|
const registry = buildHandlerRegistry({
|
|
env: { KWP_HIVEGRID_TENANT_ID: "tenant_1" },
|
|
logger: { info: vi.fn(), error: vi.fn() },
|
|
tenantMaintenanceLeaseStore: createSharedStore({ namespace: "kwp-demand-health-handler", adapter: new MemoryAdapter() }),
|
|
});
|
|
|
|
await expect(
|
|
registry[queueNames.maintenance](buildCleanupJob({ task: "integrations-health-sweep" }).payload, {}),
|
|
).resolves.toMatchObject({
|
|
action: "integrations.health-sweep.completed",
|
|
details: { checked: 1, unhealthy: 0 },
|
|
});
|
|
|
|
expect(kwpResourceMocks.ensureKwpAccessTokenForConnection).toHaveBeenCalledWith({
|
|
connectionId: "kwp_connection_1",
|
|
allowPaused: true,
|
|
});
|
|
expect(kwpResourceMocks.ensureKwpAccessTokenForConnection.mock.invocationCallOrder[0]).toBeLessThan(
|
|
integrationMocks.prepareKwpHealthProbeForConnection.mock.invocationCallOrder[0] ?? Number.MAX_SAFE_INTEGER,
|
|
);
|
|
expect(integrationMocks.prepareKwpHealthProbeForConnection).toHaveBeenCalledWith(
|
|
tx,
|
|
"tenant_1",
|
|
"kwp_connection_1",
|
|
{ now: expect.any(Date), kwpHiveGridTenantId: "tenant_1" },
|
|
);
|
|
expect(integrationMocks.listKwpHealthConnectionIdsForTenant).toHaveBeenCalledWith(
|
|
tx,
|
|
"tenant_1",
|
|
{ now: expect.any(Date) },
|
|
);
|
|
});
|
|
});
|