ts-rules-composer 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.editorconfig +15 -0
- package/.eslintrc.json +66 -0
- package/.github/CONTRIBUTING.md +3 -0
- package/.github/ISSUE_TEMPLATE.md +9 -0
- package/.github/PULL_REQUEST_TEMPLATE.md +7 -0
- package/.github/workflows/docs.yml +29 -0
- package/.github/workflows/publish.yml +25 -0
- package/.github/workflows/test.yml +37 -0
- package/.prettierignore +2 -0
- package/.releaserc +11 -0
- package/LICENSE +21 -0
- package/README.md +625 -0
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +634 -0
- package/dist/index.d.ts +634 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/package.json +64 -0
- package/src/lib/combinators/index.ts +2 -0
- package/src/lib/combinators/logic/every.spec.ts +264 -0
- package/src/lib/combinators/logic/every.ts +47 -0
- package/src/lib/combinators/logic/if-else.spec.ts +72 -0
- package/src/lib/combinators/logic/if-else.ts +39 -0
- package/src/lib/combinators/logic/index.ts +8 -0
- package/src/lib/combinators/logic/match.spec.ts +186 -0
- package/src/lib/combinators/logic/match.ts +92 -0
- package/src/lib/combinators/logic/not.spec.ts +62 -0
- package/src/lib/combinators/logic/not.ts +25 -0
- package/src/lib/combinators/logic/one-of.spec.ts +68 -0
- package/src/lib/combinators/logic/one-of.ts +41 -0
- package/src/lib/combinators/logic/unless.spec.ts +61 -0
- package/src/lib/combinators/logic/unless.ts +27 -0
- package/src/lib/combinators/logic/when.spec.ts +123 -0
- package/src/lib/combinators/logic/when.ts +29 -0
- package/src/lib/combinators/logic/with-fallback.spec.ts +72 -0
- package/src/lib/combinators/logic/with-fallback.ts +37 -0
- package/src/lib/combinators/utility/index.ts +8 -0
- package/src/lib/combinators/utility/inject.spec.ts +55 -0
- package/src/lib/combinators/utility/inject.ts +25 -0
- package/src/lib/combinators/utility/map-error.spec.ts +63 -0
- package/src/lib/combinators/utility/map-error.ts +35 -0
- package/src/lib/combinators/utility/tap.spec.ts +102 -0
- package/src/lib/combinators/utility/tap.ts +38 -0
- package/src/lib/combinators/utility/validate-field.spec.ts +150 -0
- package/src/lib/combinators/utility/validate-field.ts +59 -0
- package/src/lib/combinators/utility/with-debug.spec.ts +71 -0
- package/src/lib/combinators/utility/with-debug.ts +55 -0
- package/src/lib/combinators/utility/with-memoize.spec.ts +82 -0
- package/src/lib/combinators/utility/with-memoize.ts +81 -0
- package/src/lib/combinators/utility/with-retry.spec.ts +220 -0
- package/src/lib/combinators/utility/with-retry.ts +68 -0
- package/src/lib/combinators/utility/with-timeout.spec.ts +115 -0
- package/src/lib/combinators/utility/with-timeout.ts +34 -0
- package/src/lib/composition/compose-rules.spec.ts +211 -0
- package/src/lib/composition/compose-rules.ts +47 -0
- package/src/lib/composition/index.ts +3 -0
- package/src/lib/composition/pipe-rules.spec.ts +220 -0
- package/src/lib/composition/pipe-rules.ts +44 -0
- package/src/lib/composition/pipe.spec.ts +47 -0
- package/src/lib/composition/pipe.ts +106 -0
- package/src/lib/helpers/context/has-context.ts +13 -0
- package/src/lib/helpers/context/index.ts +3 -0
- package/src/lib/helpers/context/require-context.spec.ts +55 -0
- package/src/lib/helpers/context/require-context.ts +61 -0
- package/src/lib/helpers/context/with-lazy-context.spec.ts +74 -0
- package/src/lib/helpers/context/with-lazy-context.ts +35 -0
- package/src/lib/helpers/index.ts +6 -0
- package/src/lib/helpers/result/fail.ts +15 -0
- package/src/lib/helpers/result/index.ts +2 -0
- package/src/lib/helpers/result/pass.ts +14 -0
- package/src/lib/helpers/retry/calculate-delay.ts +31 -0
- package/src/lib/index.ts +4 -0
- package/src/lib/types/composition-options.ts +7 -0
- package/src/lib/types/debug-options.ts +36 -0
- package/src/lib/types/index.ts +4 -0
- package/src/lib/types/rule-result.ts +16 -0
- package/src/lib/types/rule.ts +21 -0
- package/src/test/helpers/get-rule-error.ts +23 -0
- package/src/test/integration.spec.ts +285 -0
- package/tsconfig.json +55 -0
- package/tsup.config.ts +36 -0
- package/vitest.config.ts +16 -0
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { describe, vi, beforeEach, it, expect } from "vitest";
|
|
2
|
+
import { pass, fail } from "../../helpers";
|
|
3
|
+
import { Rule } from "../../types";
|
|
4
|
+
import { withDebug } from "./with-debug";
|
|
5
|
+
|
|
6
|
+
describe("withDebug", () => {
|
|
7
|
+
const mockRule = vi.fn((input: string) =>
|
|
8
|
+
input === "valid" ? pass() : fail("Invalid input"),
|
|
9
|
+
);
|
|
10
|
+
|
|
11
|
+
beforeEach(() => {
|
|
12
|
+
vi.clearAllMocks();
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
it("should call onStart and onEnd for successful rules", async () => {
|
|
16
|
+
const onStart = vi.fn();
|
|
17
|
+
const onEnd = vi.fn();
|
|
18
|
+
|
|
19
|
+
const rule = withDebug(mockRule, {
|
|
20
|
+
name: "test-rule",
|
|
21
|
+
onStart,
|
|
22
|
+
onEnd,
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
const result = await rule("valid");
|
|
26
|
+
|
|
27
|
+
expect(onStart).toHaveBeenCalledWith("valid", undefined);
|
|
28
|
+
expect(onEnd).toHaveBeenCalledWith(
|
|
29
|
+
"valid",
|
|
30
|
+
pass(),
|
|
31
|
+
undefined,
|
|
32
|
+
expect.objectContaining({
|
|
33
|
+
duration: expect.any(Number),
|
|
34
|
+
}),
|
|
35
|
+
);
|
|
36
|
+
expect(result.status).toBe("passed");
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it("should handle errors with onError callback", async () => {
|
|
40
|
+
const error = new Error("Boom!");
|
|
41
|
+
const failingRule = vi.fn(() => {
|
|
42
|
+
throw error;
|
|
43
|
+
});
|
|
44
|
+
const onError = vi.fn();
|
|
45
|
+
|
|
46
|
+
const rule = withDebug(failingRule, {
|
|
47
|
+
onError,
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
await expect(rule("input")).rejects.toThrow("Boom!");
|
|
51
|
+
expect(onError).toHaveBeenCalled();
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it("should preserve context", async () => {
|
|
55
|
+
const contextRule: Rule<string, string, { userId: number }> = (
|
|
56
|
+
_input,
|
|
57
|
+
ctx,
|
|
58
|
+
) => (ctx?.userId === 42 ? pass() : fail("Invalid"));
|
|
59
|
+
|
|
60
|
+
const onEnd = vi.fn();
|
|
61
|
+
const rule = withDebug(contextRule, { onEnd });
|
|
62
|
+
|
|
63
|
+
await rule("test", { userId: 42 });
|
|
64
|
+
expect(onEnd).toHaveBeenCalledWith(
|
|
65
|
+
"test",
|
|
66
|
+
pass(),
|
|
67
|
+
{ userId: 42 },
|
|
68
|
+
expect.anything(),
|
|
69
|
+
);
|
|
70
|
+
});
|
|
71
|
+
});
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { DebugOptions, Rule } from "../../types";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Wraps a rule with debugging capabilities.
|
|
5
|
+
* @template TInput - The type of the input to validate
|
|
6
|
+
* @template TError - The type of the error
|
|
7
|
+
* @template TContext - The type of the context object
|
|
8
|
+
* @param rule - The rule to wrap with debug capabilities
|
|
9
|
+
* @param options - Debug configuration or simple name string
|
|
10
|
+
* @param options.name - Name for the debug output
|
|
11
|
+
* @param options.onStart - Callback when rule starts executing
|
|
12
|
+
* @param options.onEnd - Callback when rule completes successfully
|
|
13
|
+
* @param options.onError - Callback when rule throws an error
|
|
14
|
+
* @returns A new rule with debug capabilities
|
|
15
|
+
* @example
|
|
16
|
+
* const rule = withDebug(expensiveValidation, {
|
|
17
|
+
* name: "Expensive Validation",
|
|
18
|
+
* onStart: (input) => console.log(`Starting with input: ${input}`),
|
|
19
|
+
* onEnd: (input, result, ctx, { duration }) => {
|
|
20
|
+
* console.log(`Completed in ${duration}ms`);
|
|
21
|
+
* }
|
|
22
|
+
* });
|
|
23
|
+
* @caveats
|
|
24
|
+
* - Debug callbacks are executed synchronously and may impact performance
|
|
25
|
+
* - Errors in callbacks will propagate and potentially mask rule errors
|
|
26
|
+
*/
|
|
27
|
+
export const withDebug = <TInput, TError, TContext>(
|
|
28
|
+
rule: Rule<TInput, TError, TContext>,
|
|
29
|
+
options: DebugOptions<TInput, TError, TContext> | string,
|
|
30
|
+
): Rule<TInput, TError, TContext> => {
|
|
31
|
+
const config = typeof options === "string" ? { name: options } : options;
|
|
32
|
+
|
|
33
|
+
return async (input, context) => {
|
|
34
|
+
const startTime = performance.now();
|
|
35
|
+
const ruleName = config.name || rule.name || "anonymous_rule";
|
|
36
|
+
|
|
37
|
+
try {
|
|
38
|
+
config.onStart?.(input, context);
|
|
39
|
+
const result = await rule(input, context);
|
|
40
|
+
const duration = performance.now() - startTime;
|
|
41
|
+
|
|
42
|
+
config.onEnd?.(input, result, context, {
|
|
43
|
+
ruleName,
|
|
44
|
+
duration,
|
|
45
|
+
startTime,
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
return result;
|
|
49
|
+
} catch (error) {
|
|
50
|
+
const duration = performance.now() - startTime;
|
|
51
|
+
config.onError?.(error, input, context, duration);
|
|
52
|
+
throw error; // Preserve original error throwing behavior
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
};
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { describe, vi, beforeEach, it, expect } from "vitest";
|
|
2
|
+
import { Rule } from "../../types";
|
|
3
|
+
import { withMemoize } from "./with-memoize";
|
|
4
|
+
import { pass } from "../../helpers";
|
|
5
|
+
|
|
6
|
+
describe("withMemoize", () => {
|
|
7
|
+
const mockRule = vi.fn(() => pass());
|
|
8
|
+
const keyFn = (input: { id: string }) => input.id;
|
|
9
|
+
|
|
10
|
+
beforeEach(() => {
|
|
11
|
+
vi.clearAllMocks();
|
|
12
|
+
mockRule.mockClear();
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
it("should cache results", async () => {
|
|
16
|
+
const memoized = withMemoize(mockRule, keyFn);
|
|
17
|
+
const input = { id: "123" };
|
|
18
|
+
|
|
19
|
+
await memoized(input);
|
|
20
|
+
await memoized(input);
|
|
21
|
+
|
|
22
|
+
expect(mockRule).toHaveBeenCalledTimes(1);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it("should distinguish different inputs", async () => {
|
|
26
|
+
const memoized = withMemoize(mockRule, keyFn);
|
|
27
|
+
|
|
28
|
+
await memoized({ id: "123" });
|
|
29
|
+
await memoized({ id: "456" });
|
|
30
|
+
|
|
31
|
+
expect(mockRule).toHaveBeenCalledTimes(2);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it("should handle async rules", async () => {
|
|
35
|
+
const asyncRule = vi.fn(async () => {
|
|
36
|
+
await Promise.resolve();
|
|
37
|
+
return pass();
|
|
38
|
+
});
|
|
39
|
+
const memoized = withMemoize(asyncRule, keyFn);
|
|
40
|
+
|
|
41
|
+
await memoized({ id: "123" });
|
|
42
|
+
await memoized({ id: "123" });
|
|
43
|
+
|
|
44
|
+
expect(asyncRule).toHaveBeenCalledTimes(1);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it("should respect TTL", async () => {
|
|
48
|
+
vi.useFakeTimers();
|
|
49
|
+
const memoized = withMemoize(mockRule, keyFn, { ttl: 1000 });
|
|
50
|
+
|
|
51
|
+
await memoized({ id: "123" });
|
|
52
|
+
vi.advanceTimersByTime(1500);
|
|
53
|
+
await memoized({ id: "123" });
|
|
54
|
+
|
|
55
|
+
expect(mockRule).toHaveBeenCalledTimes(2);
|
|
56
|
+
vi.useRealTimers();
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it("should enforce max size", async () => {
|
|
60
|
+
const memoized = withMemoize(mockRule, keyFn, { maxSize: 2 });
|
|
61
|
+
|
|
62
|
+
await memoized({ id: "1" });
|
|
63
|
+
await memoized({ id: "2" });
|
|
64
|
+
await memoized({ id: "3" }); // Evicts '1'
|
|
65
|
+
await memoized({ id: "1" }); // Cache miss
|
|
66
|
+
|
|
67
|
+
expect(mockRule).toHaveBeenCalledTimes(4);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it("should maintain type safety", () => {
|
|
71
|
+
type StrictInput = { id: string };
|
|
72
|
+
const typedRule: Rule<StrictInput, string> = () => pass();
|
|
73
|
+
|
|
74
|
+
// Valid usage
|
|
75
|
+
withMemoize(typedRule, (input) => input.id);
|
|
76
|
+
|
|
77
|
+
// @ts-expect-error - Should fail if keyFn doesn't match input type
|
|
78
|
+
withMemoize(typedRule, (input: { other: number }) =>
|
|
79
|
+
input.other.toString(),
|
|
80
|
+
);
|
|
81
|
+
});
|
|
82
|
+
});
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { Rule, RuleResult } from "../../types";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Creates a memoized version of a rule that caches results based on input keys.
|
|
5
|
+
* @template TInput - The type of the input to validate
|
|
6
|
+
* @template TError - The type of the error (defaults to string)
|
|
7
|
+
* @template TContext - The type of the context object (optional)
|
|
8
|
+
* @param rule - The rule to memoize
|
|
9
|
+
* @param keyFn - Function that generates a cache key from the input
|
|
10
|
+
* @param options - Memoization options
|
|
11
|
+
* @param options.ttl - Time-to-live for cache entries in milliseconds
|
|
12
|
+
* @param options.maxSize - Maximum number of entries to keep in cache
|
|
13
|
+
* @returns A memoized version of the rule
|
|
14
|
+
* @example
|
|
15
|
+
* const memoizedRule = withMemoize(
|
|
16
|
+
* expensiveValidationRule,
|
|
17
|
+
* (input) => input.id,
|
|
18
|
+
* { ttl: 60000, maxSize: 100 }
|
|
19
|
+
* );
|
|
20
|
+
* @caveats
|
|
21
|
+
* - Context changes don't invalidate cache by default
|
|
22
|
+
* - Cache cleanup happens during rule execution
|
|
23
|
+
* - Rejected promises are automatically evicted from cache
|
|
24
|
+
*/
|
|
25
|
+
export const withMemoize = <TInput, TError = string, TContext = unknown>(
|
|
26
|
+
rule: Rule<TInput, TError, TContext>,
|
|
27
|
+
keyFn: (input: TInput) => string,
|
|
28
|
+
options: {
|
|
29
|
+
ttl?: number; // Milliseconds
|
|
30
|
+
maxSize?: number;
|
|
31
|
+
} = {},
|
|
32
|
+
): Rule<TInput, TError, TContext> => {
|
|
33
|
+
const cache = new Map<
|
|
34
|
+
string,
|
|
35
|
+
{
|
|
36
|
+
result: Promise<RuleResult<TError>> | RuleResult<TError>;
|
|
37
|
+
timestamp: number;
|
|
38
|
+
}
|
|
39
|
+
>();
|
|
40
|
+
|
|
41
|
+
return async (input: TInput, context?: TContext) => {
|
|
42
|
+
const key = keyFn(input);
|
|
43
|
+
const now = Date.now();
|
|
44
|
+
|
|
45
|
+
// Cache cleanup
|
|
46
|
+
if (options.ttl) {
|
|
47
|
+
for (const [key, entry] of cache) {
|
|
48
|
+
if (now - entry.timestamp > options.ttl) {
|
|
49
|
+
cache.delete(key);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Size management
|
|
55
|
+
if (options.maxSize && cache.size >= options.maxSize) {
|
|
56
|
+
const oldestKey = cache.keys().next().value;
|
|
57
|
+
if (oldestKey) {
|
|
58
|
+
cache.delete(oldestKey);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Cache hit
|
|
63
|
+
if (cache.has(key)) {
|
|
64
|
+
return cache.get(key)!.result;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Cache miss
|
|
68
|
+
const result = rule(input, context);
|
|
69
|
+
cache.set(key, {
|
|
70
|
+
result,
|
|
71
|
+
timestamp: now,
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
// Handle Promise cleanup if rejected
|
|
75
|
+
if (result instanceof Promise) {
|
|
76
|
+
result.catch(() => cache.delete(key));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
return result;
|
|
80
|
+
};
|
|
81
|
+
};
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import { describe, vi, beforeEach, it, expect, afterEach } from "vitest";
|
|
2
|
+
import { fail, pass } from "../../helpers";
|
|
3
|
+
import { Rule } from "../../types";
|
|
4
|
+
import { withRetry } from "./with-retry";
|
|
5
|
+
|
|
6
|
+
describe("withRetry combinator", () => {
|
|
7
|
+
const successOnThirdTry = vi
|
|
8
|
+
.fn()
|
|
9
|
+
.mockImplementationOnce(() => fail("First error"))
|
|
10
|
+
.mockImplementationOnce(() => fail("Second error"))
|
|
11
|
+
.mockImplementationOnce(() => pass());
|
|
12
|
+
|
|
13
|
+
beforeEach(() => {
|
|
14
|
+
vi.clearAllMocks();
|
|
15
|
+
vi.useFakeTimers();
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
afterEach(() => {
|
|
19
|
+
vi.useRealTimers();
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
it("should succeed if rule eventually passes", async () => {
|
|
23
|
+
const rule = withRetry(successOnThirdTry, {
|
|
24
|
+
attempts: 3,
|
|
25
|
+
delayMs: 100,
|
|
26
|
+
retryStrategy: "fixed",
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
const resultPromise = rule({});
|
|
30
|
+
|
|
31
|
+
// Advance through all retries
|
|
32
|
+
await vi.advanceTimersByTimeAsync(300);
|
|
33
|
+
const result = await resultPromise;
|
|
34
|
+
|
|
35
|
+
expect(result).toEqual(pass());
|
|
36
|
+
expect(successOnThirdTry).toHaveBeenCalledTimes(3);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it("should apply exponential backoff strategy", async () => {
|
|
40
|
+
const mockRule = vi.fn(() => fail("Error"));
|
|
41
|
+
const rule = withRetry(mockRule, {
|
|
42
|
+
attempts: 3,
|
|
43
|
+
delayMs: 100,
|
|
44
|
+
retryStrategy: "exponential", // 100ms, 200ms, 400ms
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
const resultPromise = rule({});
|
|
48
|
+
|
|
49
|
+
// First attempt (no delay)
|
|
50
|
+
expect(mockRule).toHaveBeenCalledTimes(1);
|
|
51
|
+
|
|
52
|
+
// First retry after 100ms
|
|
53
|
+
await vi.advanceTimersByTimeAsync(100);
|
|
54
|
+
expect(mockRule).toHaveBeenCalledTimes(2);
|
|
55
|
+
|
|
56
|
+
// Second retry after 200ms (total 300ms)
|
|
57
|
+
await vi.advanceTimersByTimeAsync(200);
|
|
58
|
+
expect(mockRule).toHaveBeenCalledTimes(3);
|
|
59
|
+
|
|
60
|
+
await vi.advanceTimersByTimeAsync(400);
|
|
61
|
+
const result = await resultPromise;
|
|
62
|
+
expect(result).toEqual(fail("MAX_RETRIES_EXCEEDED"));
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it("should apply linear backoff strategy", async () => {
|
|
66
|
+
const mockRule = vi.fn(() => fail("Error"));
|
|
67
|
+
const rule = withRetry(mockRule, {
|
|
68
|
+
attempts: 3,
|
|
69
|
+
delayMs: 50,
|
|
70
|
+
retryStrategy: "linear", // 50ms, 100ms, 150ms
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
const resultPromise = rule({});
|
|
74
|
+
|
|
75
|
+
await vi.advanceTimersByTimeAsync(50);
|
|
76
|
+
expect(mockRule).toHaveBeenCalledTimes(2);
|
|
77
|
+
|
|
78
|
+
await vi.advanceTimersByTimeAsync(100);
|
|
79
|
+
expect(mockRule).toHaveBeenCalledTimes(3);
|
|
80
|
+
|
|
81
|
+
await vi.advanceTimersByTimeAsync(150);
|
|
82
|
+
const result = await resultPromise;
|
|
83
|
+
expect(result.status).toBe("failed");
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it("should use custom strategy function", async () => {
|
|
87
|
+
const mockRule = vi.fn(() => fail("Error"));
|
|
88
|
+
const customStrategy = vi.fn((attempt) => attempt * 25);
|
|
89
|
+
|
|
90
|
+
const rule = withRetry(mockRule, {
|
|
91
|
+
attempts: 3,
|
|
92
|
+
delayMs: 25,
|
|
93
|
+
retryStrategy: customStrategy,
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
const resultPromise = rule({});
|
|
97
|
+
|
|
98
|
+
// First attempt (no delay)
|
|
99
|
+
expect(mockRule).toHaveBeenCalledTimes(1);
|
|
100
|
+
|
|
101
|
+
// First retry after 25ms (attempt 1 * 25ms)
|
|
102
|
+
await vi.advanceTimersByTimeAsync(25);
|
|
103
|
+
expect(customStrategy).toHaveBeenCalledWith(1); // Only expect attempt number
|
|
104
|
+
expect(mockRule).toHaveBeenCalledTimes(2);
|
|
105
|
+
|
|
106
|
+
// Second retry after 50ms (attempt 2 * 25ms)
|
|
107
|
+
await vi.advanceTimersByTimeAsync(50);
|
|
108
|
+
expect(customStrategy).toHaveBeenCalledWith(2);
|
|
109
|
+
expect(mockRule).toHaveBeenCalledTimes(3);
|
|
110
|
+
|
|
111
|
+
await vi.advanceTimersByTimeAsync(75);
|
|
112
|
+
const result = await resultPromise;
|
|
113
|
+
expect(result.status).toBe("failed");
|
|
114
|
+
expect(customStrategy).toHaveBeenCalledTimes(2); // Called for attempts 1 and 2
|
|
115
|
+
});
|
|
116
|
+
it("should fail after max attempts", async () => {
|
|
117
|
+
const alwaysFails = vi.fn(() => fail("Persistent error"));
|
|
118
|
+
const rule = withRetry(alwaysFails, {
|
|
119
|
+
attempts: 2,
|
|
120
|
+
delayMs: 10,
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
const resultPromise = rule({});
|
|
124
|
+
await vi.runAllTimersAsync();
|
|
125
|
+
const result = await resultPromise;
|
|
126
|
+
|
|
127
|
+
expect(result).toEqual(fail("MAX_RETRIES_EXCEEDED"));
|
|
128
|
+
expect(alwaysFails).toHaveBeenCalledTimes(2);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
it("should use shouldRetry predicate", async () => {
|
|
132
|
+
const mockRule = vi
|
|
133
|
+
.fn()
|
|
134
|
+
.mockImplementationOnce(() => fail("First error"))
|
|
135
|
+
.mockImplementationOnce(() => fail("Second error"));
|
|
136
|
+
|
|
137
|
+
const shouldRetry = vi
|
|
138
|
+
.fn()
|
|
139
|
+
.mockReturnValueOnce(true) // Retry first error
|
|
140
|
+
.mockReturnValue(false); // Don't retry second
|
|
141
|
+
|
|
142
|
+
const rule = withRetry(mockRule, {
|
|
143
|
+
attempts: 3,
|
|
144
|
+
shouldRetry,
|
|
145
|
+
delayMs: 10,
|
|
146
|
+
retryStrategy: "fixed", // Explicit strategy for predictability
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
// Run the test without waiting for actual delays
|
|
150
|
+
vi.spyOn(global, "setTimeout").mockImplementation((fn) => fn() as any);
|
|
151
|
+
|
|
152
|
+
const result = await rule({});
|
|
153
|
+
|
|
154
|
+
expect(result).toEqual(fail("Second error"));
|
|
155
|
+
expect(shouldRetry).toHaveBeenCalledWith("First error", 1);
|
|
156
|
+
expect(mockRule).toHaveBeenCalledTimes(2);
|
|
157
|
+
|
|
158
|
+
// Clean up
|
|
159
|
+
vi.restoreAllMocks();
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it("should pass context to each attempt", async () => {
|
|
163
|
+
const context = { userId: 123 };
|
|
164
|
+
const rule = withRetry(successOnThirdTry, {
|
|
165
|
+
attempts: 3,
|
|
166
|
+
delayMs: 10,
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
// Run the test without waiting for actual delays
|
|
170
|
+
vi.spyOn(global, "setTimeout").mockImplementation((fn) => fn() as any);
|
|
171
|
+
|
|
172
|
+
await rule({}, context);
|
|
173
|
+
|
|
174
|
+
expect(successOnThirdTry).toHaveBeenCalledWith({}, context);
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
it("should handle thrown errors", async () => {
|
|
178
|
+
const errorRule = vi
|
|
179
|
+
.fn()
|
|
180
|
+
.mockRejectedValueOnce(new Error("Network error"))
|
|
181
|
+
.mockResolvedValueOnce(pass());
|
|
182
|
+
|
|
183
|
+
const rule = withRetry(errorRule, {
|
|
184
|
+
attempts: 2,
|
|
185
|
+
shouldRetry: (e) => (e as Error).message === "Network error",
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
// Run the test without waiting for actual delays
|
|
189
|
+
vi.spyOn(global, "setTimeout").mockImplementation((fn) => fn() as any);
|
|
190
|
+
|
|
191
|
+
const result = await rule({});
|
|
192
|
+
expect(result).toEqual(pass());
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
it("should fail on non-retryable thrown errors", async () => {
|
|
196
|
+
const errorRule = vi.fn().mockRejectedValue(new Error("Fatal"));
|
|
197
|
+
|
|
198
|
+
const rule = withRetry(errorRule, {
|
|
199
|
+
shouldRetry: (e) => (e as Error).message !== "Fatal",
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
const result = await rule({});
|
|
203
|
+
expect(result.status).toBe("failed");
|
|
204
|
+
expect((result as any).error.message).toBe("Fatal");
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
// Type safety tests
|
|
208
|
+
it("should preserve input types", () => {
|
|
209
|
+
type StrictInput = { id: string };
|
|
210
|
+
const typedRule: Rule<StrictInput, string> = () => pass();
|
|
211
|
+
|
|
212
|
+
// Valid usage
|
|
213
|
+
withRetry(typedRule, { attempts: 2 });
|
|
214
|
+
|
|
215
|
+
withRetry((_: { other: number }) => pass(), { attempts: 2 })({
|
|
216
|
+
// @ts-expect-error - Should fail if input types mismatch
|
|
217
|
+
id: "123",
|
|
218
|
+
});
|
|
219
|
+
});
|
|
220
|
+
});
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import type { Rule } from "../../types";
|
|
2
|
+
import { calculateDelay, fail } from "../../helpers";
|
|
3
|
+
|
|
4
|
+
export type RetryStrategy =
|
|
5
|
+
| "fixed"
|
|
6
|
+
| "linear"
|
|
7
|
+
| "exponential"
|
|
8
|
+
| ((attempt: number) => number);
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Wraps a rule with retry logic for handling transient failures.
|
|
12
|
+
* @template TInput - The type of the input to validate
|
|
13
|
+
* @template TError - The type of the error (defaults to string)
|
|
14
|
+
* @template TContext - The type of the context object (optional)
|
|
15
|
+
* @param rule - The rule to wrap with retry logic
|
|
16
|
+
* @param options - Retry configuration
|
|
17
|
+
* @param options.attempts - Maximum number of attempts (default: 3)
|
|
18
|
+
* @param options.delayMs - Delay between attempts in milliseconds (default: 100)
|
|
19
|
+
* @param options.shouldRetry - Function to determine if a failure should be retried
|
|
20
|
+
* @returns A new rule with retry capability
|
|
21
|
+
* @example
|
|
22
|
+
* const rule = withRetry(apiCheckRule, {
|
|
23
|
+
* attempts: 5,
|
|
24
|
+
* delayMs: 500,
|
|
25
|
+
* shouldRetry: (error) => error.statusCode === 503
|
|
26
|
+
* });
|
|
27
|
+
* @caveats
|
|
28
|
+
* - Only retries on failed RuleResults, not on thrown exceptions
|
|
29
|
+
* - The final error will be "MAX_RETRIES_EXCEEDED" if all attempts fail
|
|
30
|
+
*/
|
|
31
|
+
export const withRetry = <TInput, TError = string, TContext = unknown>(
|
|
32
|
+
rule: Rule<TInput, TError, TContext>,
|
|
33
|
+
options: {
|
|
34
|
+
attempts?: number;
|
|
35
|
+
delayMs?: number;
|
|
36
|
+
retryStrategy?: RetryStrategy;
|
|
37
|
+
shouldRetry?: (error: TError | unknown, attempt: number) => boolean;
|
|
38
|
+
} = {},
|
|
39
|
+
): Rule<TInput, TError | "MAX_RETRIES_EXCEEDED", TContext> => {
|
|
40
|
+
const { attempts = 3, delayMs = 100, shouldRetry = () => true } = options;
|
|
41
|
+
|
|
42
|
+
return async (input, context) => {
|
|
43
|
+
let lastError: TError | unknown;
|
|
44
|
+
|
|
45
|
+
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
46
|
+
try {
|
|
47
|
+
const result = await rule(input, context);
|
|
48
|
+
if (result.status === "passed") return result;
|
|
49
|
+
lastError = result.error;
|
|
50
|
+
} catch (error) {
|
|
51
|
+
lastError = error;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Check if we should retry the last error
|
|
55
|
+
if (!shouldRetry(lastError as TError, attempt)) {
|
|
56
|
+
return fail(lastError as TError);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Delay if not the last attempt
|
|
60
|
+
if (attempt < attempts && delayMs > 0) {
|
|
61
|
+
const delay = calculateDelay(options?.retryStrategy, attempt, delayMs);
|
|
62
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
return fail("MAX_RETRIES_EXCEEDED" as const);
|
|
67
|
+
};
|
|
68
|
+
};
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import {
|
|
2
|
+
describe,
|
|
3
|
+
beforeAll,
|
|
4
|
+
vi,
|
|
5
|
+
afterEach,
|
|
6
|
+
afterAll,
|
|
7
|
+
it,
|
|
8
|
+
expect,
|
|
9
|
+
} from "vitest";
|
|
10
|
+
import { pass, fail } from "../../helpers";
|
|
11
|
+
import { Rule } from "../../types";
|
|
12
|
+
import { withTimeout } from "./with-timeout";
|
|
13
|
+
import { getRuleError } from "../../../test/helpers/get-rule-error";
|
|
14
|
+
|
|
15
|
+
describe("withTimeout", () => {
|
|
16
|
+
beforeAll(() => {
|
|
17
|
+
vi.useFakeTimers();
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
afterEach(() => {
|
|
21
|
+
vi.clearAllTimers();
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
afterAll(() => {
|
|
25
|
+
vi.useRealTimers();
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
// Mock rules
|
|
29
|
+
const mockPassingRule: Rule<string> = vi.fn(() => Promise.resolve(pass()));
|
|
30
|
+
const mockFailingRule: Rule<string> = vi.fn(() =>
|
|
31
|
+
Promise.resolve(fail("Expected error")),
|
|
32
|
+
);
|
|
33
|
+
const createSlowRule = (delayMs: number): Rule<string> =>
|
|
34
|
+
vi.fn(async () => {
|
|
35
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
36
|
+
return pass();
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it("should pass through immediate success", async () => {
|
|
40
|
+
const rule = withTimeout(mockPassingRule, 100, "Timeout error");
|
|
41
|
+
const resultPromise = rule("input");
|
|
42
|
+
|
|
43
|
+
// Advance just enough to let microtasks run
|
|
44
|
+
await Promise.resolve();
|
|
45
|
+
vi.advanceTimersByTime(0);
|
|
46
|
+
|
|
47
|
+
const result = await resultPromise;
|
|
48
|
+
expect(result.status).toBe("passed");
|
|
49
|
+
expect(mockPassingRule).toHaveBeenCalledWith("input", undefined);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it("should pass through immediate failure", async () => {
|
|
53
|
+
const rule = withTimeout(mockFailingRule, 100, "Timeout error");
|
|
54
|
+
const resultPromise = rule("input");
|
|
55
|
+
|
|
56
|
+
await Promise.resolve();
|
|
57
|
+
vi.advanceTimersByTime(0);
|
|
58
|
+
|
|
59
|
+
const result = await resultPromise;
|
|
60
|
+
expect(result.status).toBe("failed");
|
|
61
|
+
expect(getRuleError(result)).toBe("Expected error");
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it("should timeout when rule exceeds limit", async () => {
|
|
65
|
+
const slowRule = createSlowRule(200);
|
|
66
|
+
const rule = withTimeout(slowRule, 100, "Timeout exceeded");
|
|
67
|
+
|
|
68
|
+
const resultPromise = rule("input");
|
|
69
|
+
vi.advanceTimersByTime(100); // Trigger timeout
|
|
70
|
+
|
|
71
|
+
const result = await resultPromise;
|
|
72
|
+
expect(result.status).toBe("failed");
|
|
73
|
+
|
|
74
|
+
expect(getRuleError(result)).toBe("Timeout exceeded");
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it("should complete successfully if finished before timeout", async () => {
|
|
78
|
+
const slowRule = createSlowRule(50);
|
|
79
|
+
const rule = withTimeout(slowRule, 100, "Timeout error");
|
|
80
|
+
|
|
81
|
+
const resultPromise = rule("input");
|
|
82
|
+
vi.advanceTimersByTime(50); // Rule completes
|
|
83
|
+
|
|
84
|
+
const result = await resultPromise;
|
|
85
|
+
expect(result.status).toBe("passed");
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it("should handle context correctly", async () => {
|
|
89
|
+
const contextRule: Rule<string, string, { id: number }> = vi.fn(
|
|
90
|
+
async (_, ctx) => (ctx?.id === 1 ? pass() : fail("Invalid context")),
|
|
91
|
+
);
|
|
92
|
+
|
|
93
|
+
const rule = withTimeout(contextRule, 100, "Timeout error");
|
|
94
|
+
const resultPromise = rule("input", { id: 1 });
|
|
95
|
+
|
|
96
|
+
await Promise.resolve();
|
|
97
|
+
vi.advanceTimersByTime(0);
|
|
98
|
+
|
|
99
|
+
const result = await resultPromise;
|
|
100
|
+
expect(result.status).toBe("passed");
|
|
101
|
+
expect(contextRule).toHaveBeenCalledWith("input", { id: 1 });
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it("should work with immediate timeout (0ms)", async () => {
|
|
105
|
+
const slowRule = createSlowRule(10);
|
|
106
|
+
const rule = withTimeout(slowRule, 0, "Instant error");
|
|
107
|
+
|
|
108
|
+
const resultPromise = rule("input");
|
|
109
|
+
vi.advanceTimersByTime(0); // Trigger immediate timeout
|
|
110
|
+
|
|
111
|
+
const result = await resultPromise;
|
|
112
|
+
expect(result.status).toBe("failed");
|
|
113
|
+
expect(getRuleError(result)).toBe("Instant error");
|
|
114
|
+
});
|
|
115
|
+
});
|