Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion lib/run-checks.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { TO_FINISH_WITH_OPTIONS } from './consts.js';
import type { RunTestResult } from './run-test-result.js';
import type { Interval, ToFinishWithOptions } from './types.js';
import { sleep } from './utils.js';

const CHARGED_EVENTS_POLL_INTERVAL_MS = 5_000;
const CHARGED_EVENTS_TIMEOUT_MS = 60_000;

type Check = {
name: string;
Expand Down Expand Up @@ -52,6 +56,28 @@ const ppeChecks = (expected: Record<string, Interval>, actual: Record<string, nu
});
};

/**
* The platform reconciles charged events onto the run some time after it finished, even more so when the run hit
* its charge limit, so keep re-fetching the run until the expected counts show up or the timeout passes. Counts only
* grow, so one already past its maximum ends the wait. Once the platform's storages become immediately consistent,
* the first fetch settles this and the loop never runs, so it can stay.
*/
const getRunInfo = async (run: RunTestResult, expected: Record<string, Interval> | undefined) => {
let runInfo = await run.getRunInfo();
const intervals = Object.entries(expected ?? {});
const settled = () =>
intervals.every(([event, interval]) => isWithinInterval(runInfo.chargedEventCounts?.[event], interval)) ||
intervals.some(([event, interval]) => {
const max = typeof interval === 'number' ? interval : interval.max;
return max !== undefined && (runInfo.chargedEventCounts?.[event] ?? 0) > max;
});
for (let waited = 0; !settled() && waited < CHARGED_EVENTS_TIMEOUT_MS; waited += CHARGED_EVENTS_POLL_INTERVAL_MS) {
await sleep(CHARGED_EVENTS_POLL_INTERVAL_MS);
runInfo = await run.fetchRunInfo();
}
return runInfo;
};

/**
* Evaluates every `toFinishWith` expectation against the run, so a failing assertion reports all of them at once.
*/
Expand All @@ -64,7 +90,7 @@ export const checkRun = async <PpeEvent extends string>(
// The dataset's item count lags the run by 10-20 seconds, so counting the downloaded items is the only way to
// be in sync. Don't swap it for the count from the dataset info.
const [runInfo, { items }, stats, log] = await Promise.all([
run.getRunInfo(),
getRunInfo(run, options.chargedEventCounts),
run.getDataset(),
run.getStatistics(),
run.getLog(),
Expand Down
9 changes: 6 additions & 3 deletions lib/run-test-result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,13 @@ export class RunTestResult {

getInput = async <T>(): Promise<T> => (await this.inputRecord()) as T;

/** Fetches the run again, so unlike `id` and `status` it also reflects what changed after the run finished. */
getRunInfo = once(async (): Promise<ActorRun> => {
/** Like `getRunInfo`, but fetches the run on every call instead of sharing the first response. */
fetchRunInfo = async (): Promise<ActorRun> => {
return (await this.apifyClient.run(this.run.id).get())!;
});
};

/** Fetches the run again, so unlike `id` and `status` it also reflects what changed after the run finished. */
getRunInfo = once(this.fetchRunInfo);

get id(): string {
return this.run.id;
Expand Down
83 changes: 71 additions & 12 deletions test/unit/run-checks.test.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import { describe, expect, it } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { checkRun } from '../../lib/run-checks.js';
import type { RunTestResult } from '../../lib/run-test-result.js';

const fakeRun = (overrides: { status?: string; log?: string; stats?: object; chargedEventCounts?: object } = {}) =>
({
const fakeRun = (overrides: { status?: string; log?: string; stats?: object; chargedEventCounts?: object } = {}) => {
const getRunInfo = async () => ({
stats: { durationMillis: 5_000 },
chargedEventCounts: overrides.chargedEventCounts,
});
return {
status: overrides.status ?? 'SUCCEEDED',
getRunInfo: async () => ({
stats: { durationMillis: 5_000 },
chargedEventCounts: overrides.chargedEventCounts,
}),
getRunInfo,
fetchRunInfo: getRunInfo,
getDataset: async () => ({ items: new Array(10) }),
getStatistics: async () => ({
requestsFailed: 0,
Expand All @@ -18,7 +20,8 @@ const fakeRun = (overrides: { status?: string; log?: string; stats?: object; cha
...overrides.stats,
}),
getLog: async () => overrides.log ?? 'all good',
}) as unknown as RunTestResult;
} as unknown as RunTestResult;
};

const failures = async (run: RunTestResult, options: Parameters<typeof checkRun>[1]) =>
(await checkRun(run, options)).filter(({ pass }) => !pass).map(({ name }) => name);
Expand Down Expand Up @@ -56,21 +59,77 @@ describe('checkRun()', () => {
});

describe('chargedEventCounts', () => {
const run = fakeRun({ chargedEventCounts: { start: 1, item: 7 } });
const chargedRun = fakeRun({ chargedEventCounts: { start: 1, item: 7 } });

beforeEach(() => {
vi.useFakeTimers();
});

afterEach(() => {
vi.useRealTimers();
});

const settled = async <T>(result: Promise<T>): Promise<T> => {
await vi.runAllTimersAsync();
return result;
};

it('passes matching counts and intervals', async () => {
const options = { datasetItemCount: 10, chargedEventCounts: { start: 1, item: { min: 5 } } };
expect(await failures(run, options)).toEqual([]);
expect(await failures(chargedRun, options)).toEqual([]);
});

it('expects unlisted charged events to not happen', async () => {
const options = { datasetItemCount: 10, chargedEventCounts: { start: 1 } as Record<string, number> };
expect(await failures(run, options)).toEqual(['chargedEventCounts.item']);
expect(await failures(chargedRun, options)).toEqual(['chargedEventCounts.item']);
});

it('fails an expected event that was never charged', async () => {
const options = { datasetItemCount: 10, chargedEventCounts: { start: 1, item: 7, extra: { min: 0 } } };
expect(await failures(run, options)).toEqual(['chargedEventCounts.extra']);
expect(await settled(failures(chargedRun, options))).toEqual(['chargedEventCounts.extra']);
});

describe('waiting for the counts to reach the run', () => {
const options = { datasetItemCount: 10, chargedEventCounts: { start: 1, item: { min: 5 } } };
const laggingRun = (...fetched: object[]) => {
const fetchRunInfo = vi.fn(async () => ({
stats: { durationMillis: 5_000 },
chargedEventCounts: fetched.shift(),
}));
return { ...fakeRun(), getRunInfo: fetchRunInfo, fetchRunInfo };
};

it('re-fetches the run until the expected counts show up', async () => {
const run = laggingRun({}, { start: 1 }, { start: 1, item: 7 }, { start: 1, item: 99 });
expect(await settled(failures(run as unknown as RunTestResult, options))).toEqual([]);
expect(run.fetchRunInfo).toHaveBeenCalledTimes(3);
});

it('gives up after a minute and reports the last counts', async () => {
const run = laggingRun();
const result = checkRun(run as unknown as RunTestResult, options);
await vi.advanceTimersByTimeAsync(59_999);
expect(run.fetchRunInfo).toHaveBeenCalledTimes(12);
await vi.advanceTimersByTimeAsync(1);
expect(run.fetchRunInfo).toHaveBeenCalledTimes(13);
expect((await result).filter(({ pass }) => !pass)).toEqual([
{ name: 'chargedEventCounts.start', pass: false, actual: 'X', expected: '1' },
{ name: 'chargedEventCounts.item', pass: false, actual: 'X', expected: '<5,>' },
]);
});

it('stops waiting once a count is past its maximum', async () => {
const run = laggingRun({ start: 2 }, { start: 1, item: 7 });
const result = await settled(failures(run as unknown as RunTestResult, options));
expect(result).toEqual(['chargedEventCounts.start', 'chargedEventCounts.item']);
expect(run.fetchRunInfo).toHaveBeenCalledTimes(1);
});

it('fetches the run once without chargedEventCounts expectations', async () => {
const run = laggingRun();
expect(await failures(run as unknown as RunTestResult, { datasetItemCount: 10 })).toEqual([]);
expect(run.fetchRunInfo).toHaveBeenCalledTimes(1);
});
});
});
});
Loading