Skip to content

Commit

Permalink
typing
Browse files Browse the repository at this point in the history
  • Loading branch information
21e8 committed Dec 8, 2024
1 parent e87de8c commit 9331692
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 19 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "0xalice-tgram-bot",
"version": "0.2.17",
"version": "0.2.18",
"description": "Batched Telegram notification bot for 0xAlice",
"type": "module",
"main": "./dist/cjs/index.js",
Expand Down
12 changes: 7 additions & 5 deletions src/__tests__/batcher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ describe('MessageBatcher', () => {
let batcher: MessageBatcher;

beforeEach(() => {
jest.useFakeTimers();
processedMessages = [];
mockProcessor = {
name: 'mock',
Expand All @@ -22,6 +23,7 @@ describe('MessageBatcher', () => {
}
jest.clearAllMocks();
jest.clearAllTimers();
jest.useRealTimers();
});

it('should process messages with concurrent processors', async () => {
Expand Down Expand Up @@ -170,9 +172,9 @@ describe('MessageBatcher', () => {
batcher.info('message 1');
batcher.info('message 2');

// Wait for processing
await new Promise(process.nextTick);
await batcher.flush();
// Run timers and wait for processing
jest.advanceTimersByTime(1000);
await Promise.resolve();

expect(processBatchSpy).toHaveBeenCalledWith(
expect.arrayContaining([
Expand All @@ -184,7 +186,7 @@ describe('MessageBatcher', () => {
}),
])
);
}, 10000);
});

it('should handle sync processor errors', async () => {
const errorProcessor = {
Expand Down Expand Up @@ -264,7 +266,7 @@ describe('MessageBatcher', () => {
const slowProcessor = {
name: 'processor1',
processBatch: jest.fn().mockImplementation(async () => {
await new Promise(resolve => setTimeout(resolve, 50));
await Promise.resolve();
}),
};
const fastProcessor = {
Expand Down
20 changes: 11 additions & 9 deletions src/batcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,8 @@ import {
type MessageProcessor,
type MessageBatcher,
} from './types';

// Export for testing
let globalBatcher: MessageBatcher | null = null;
const resetGlobalBatcher = () => {
globalBatcher = null;
};

export function createMessageBatcher(
processors: MessageProcessor[],
Expand All @@ -30,6 +26,9 @@ export function createMessageBatcher(
const maxWaitMs = config.maxWaitMs ?? 60_000; // 1 minute

function startProcessing(): void {
if (processInterval) {
clearInterval(processInterval);
}
processInterval = setInterval(async () => {
for (const chatId of queues.keys()) {
await processBatch(chatId);
Expand All @@ -47,8 +46,10 @@ export function createMessageBatcher(
}

function removeAllExtraProcessors(): void {
for (const processor of extraProcessors) {
removeExtraProcessor(processor);
}
extraProcessors = [];
// processorNames.clear();
}

function removeExtraProcessor(processor: MessageProcessor): void {
Expand Down Expand Up @@ -161,10 +162,8 @@ export function createMessageBatcher(
queues.set(chatId, []);

const allProcessors = [...processors, ...extraProcessors];
await concurrentExhaust(
allProcessors,
concurrentProcessors,
(processor) => exhaustProcessor(processor, batch)
await concurrentExhaust(allProcessors, concurrentProcessors, (processor) =>
exhaustProcessor(processor, batch)
);
}

Expand Down Expand Up @@ -218,6 +217,7 @@ export function createMessageBatcher(
globalBatcher = null;
}

// Initialize processing
startProcessing();

globalBatcher = {
Expand All @@ -233,6 +233,8 @@ export function createMessageBatcher(
timers,
addExtraProcessor,
removeExtraProcessor,
removeAllExtraProcessors,
};

return globalBatcher;
}
8 changes: 8 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
export type NotificationLevel = 'info' | 'warning' | 'error';

// Predefined severity levels with option for custom strings
export type SeverityLevel =
| 'low'
| 'medium'
| 'high'
| (string & NonNullable<unknown>);

export type Message = {
chatId: string;
text: string;
Expand Down Expand Up @@ -39,6 +46,7 @@ export interface MessageBatcher {
timers: Map<string, NodeJS.Timeout>;
addExtraProcessor(processor: MessageProcessor): void;
removeExtraProcessor(processor: MessageProcessor): void;
removeAllExtraProcessors(): void;
}

export type ProcessorOptions = {
Expand Down
10 changes: 6 additions & 4 deletions src/utils/errorClassifier.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { SeverityLevel } from "../types";

// Define the named object interface
export type ErrorPatternConfig = {
name: string;
Expand All @@ -7,7 +9,7 @@ export type ErrorPatternConfig = {
| Promise<boolean>
| ((message: string) => Promise<boolean>);
category: string;
severity: 'low' | 'medium' | 'high';
severity: SeverityLevel;
aggregation?: {
windowMs: number;
countThreshold: number;
Expand All @@ -23,7 +25,7 @@ type ErrorPattern = readonly [
| ((message: string) => Promise<boolean>)
),
string, // category
'low' | 'medium' | 'high', // severity
SeverityLevel, // severity
[number, number]? // [windowMs, countThreshold] for aggregation
];

Expand Down Expand Up @@ -68,7 +70,7 @@ const DEFAULT_ERROR_PATTERNS: ErrorPatternConfig[] = [
// Store custom patterns
let customPatterns: ErrorPattern[] = [];

export function addErrorPatterns(patterns: ErrorPatternConfig[]): void {
export function addErrorPatterns(patterns: readonly ErrorPatternConfig[]): void {
customPatterns = customPatterns.concat(patterns.map(configToPattern));
}

Expand All @@ -95,7 +97,7 @@ const errorTracker = new Map<
type ClassifiedError = readonly [
string, // originalMessage
string, // category
'low' | 'medium' | 'high', // severity
SeverityLevel, // severity
string[], // details (key-value pairs flattened)
boolean, // isAggregated
number?, // occurrences
Expand Down

0 comments on commit 9331692

Please sign in to comment.