first refactor

This commit is contained in:
Boki 2026-10-20 12:39:38 -04:00
parent 1f5dac28c7
commit 588f666943
84 changed files with 996 additions and 1062 deletions

View file

@ -2,8 +2,8 @@
"extends": ["//"],
"tasks": {
"build": {
"dependsOn": [],
"outputs": ["dist/**"],
"dependsOn": ["^build"],
"outputs": ["dist/**", "*.tsbuildinfo"],
"inputs": [
"src/**",
"package.json",

View file

@ -9,6 +9,7 @@
"test": "bun test"
},
"dependencies": {
"@stock-bot/services": "workspace:*",
"@stock-bot/config": "workspace:*",
"@stock-bot/logger": "workspace:*",
"@stock-bot/types": "workspace:*",

View file

@ -1,59 +1,7 @@
/**
* Awilix DI Container Setup
* Creates a decoupled, reusable dependency injection container
*/
import type { AwilixContainer } from 'awilix';
import type { ServiceDefinitions } from './container/types';
import { type AwilixContainer } from 'awilix';
import type { Browser } from '@stock-bot/browser';
import type { CacheProvider } from '@stock-bot/cache';
import type { Logger } from '@stock-bot/logger';
import type { MongoDBClient } from '@stock-bot/mongodb';
import type { PostgreSQLClient } from '@stock-bot/postgres';
import type { ProxyManager } from '@stock-bot/proxy';
import type { QuestDBClient } from '@stock-bot/questdb';
import type { QueueManager } from '@stock-bot/queue';
import type { IServiceContainer } from '@stock-bot/types';
import type { AppConfig } from './config/schemas';
// Re-export for backward compatibility
export type { AppConfig };
/**
* Service type definitions for type-safe resolution
*/
export interface ServiceDefinitions {
// Configuration
config: AppConfig;
logger: Logger;
// Core services
cache: CacheProvider | null;
proxyManager: ProxyManager | null;
browser: Browser;
queueManager: QueueManager | null;
// Database clients
mongoClient: MongoDBClient | null;
postgresClient: PostgreSQLClient | null;
questdbClient: QuestDBClient | null;
// Aggregate service container
serviceContainer: IServiceContainer;
}
// Export typed container
// Compatibility exports use the same composition contract as the active builder.
export type { AppConfig } from './config/schemas';
export type { ServiceCradle, ServiceDefinitions, ServiceContainerOptions } from './container/types';
export type ServiceContainer = AwilixContainer<ServiceDefinitions>;
export type ServiceCradle = ServiceDefinitions;
/**
* Service-specific options for container creation
*/
export interface ServiceContainerOptions {
enableQuestDB?: boolean;
enableMongoDB?: boolean;
enablePostgres?: boolean;
enableCache?: boolean;
enableQueue?: boolean;
enableBrowser?: boolean;
enableProxy?: boolean;
}

View file

@ -2,6 +2,7 @@ import { asClass, asFunction, createContainer, InjectionMode, type AwilixContain
import type { BaseAppConfig as StockBotAppConfig, UnifiedAppConfig } from '@stock-bot/config';
import { toUnifiedConfig } from '@stock-bot/config';
import { HandlerRegistry } from '@stock-bot/handler-registry';
import type { IServiceContainer } from '@stock-bot/services';
import { appConfigSchema, type AppConfig } from '../config/schemas';
import {
registerApplicationServices,
@ -163,7 +164,7 @@ export class ServiceContainerBuilder {
// Register service container aggregate
container.register({
serviceContainer: asFunction(
serviceContainer: asFunction<IServiceContainer>(
({
config: _config,
logger,
@ -175,7 +176,7 @@ export class ServiceContainerBuilder {
mongoClient,
postgresClient,
questdbClient,
}) => ({
}: ServiceDefinitions) => ({
logger,
cache,
globalCache,

View file

@ -7,7 +7,7 @@ import type { PostgreSQLClient } from '@stock-bot/postgres';
import type { ProxyManager } from '@stock-bot/proxy';
import type { QuestDBClient } from '@stock-bot/questdb';
import type { QueueManager } from '@stock-bot/queue';
import type { IServiceContainer } from '@stock-bot/types';
import type { IServiceContainer } from '@stock-bot/services';
import type { AppConfig } from '../config/schemas';
import type { HandlerScanner } from '../scanner';
@ -24,7 +24,7 @@ export interface ServiceDefinitions {
cache: CacheProvider | null;
globalCache: CacheProvider | null;
proxyManager: ProxyManager | null;
browser: Browser;
browser: Browser | null;
queueManager: QueueManager | null;
// Database clients

View file

@ -5,7 +5,7 @@ export { OperationContext } from './operation-context';
export { calculatePoolSize, getServicePoolSize, getHandlerPoolSize } from './pool-size-calculator';
export { ServiceLifecycleManager } from './utils/lifecycle';
export { HandlerScanner } from './scanner/handler-scanner';
export type { IServiceContainer } from '@stock-bot/types';
export type { IServiceContainer } from '@stock-bot/services';
// Export schemas
export {

View file

@ -8,7 +8,7 @@ import { toUnifiedConfig } from '@stock-bot/config';
import type { HandlerRegistry } from '@stock-bot/handler-registry';
import { getLogger, setLoggerConfig, shutdownLoggers, type Logger } from '@stock-bot/logger';
import { Shutdown, SHUTDOWN_DEFAULTS } from '@stock-bot/shutdown';
import type { IServiceContainer } from '@stock-bot/types';
import type { IServiceContainer } from '@stock-bot/services';
import type { AwilixContainer } from 'awilix';
import { Hono } from 'hono';
import { cors } from 'hono/cors';

View file

@ -10,5 +10,10 @@
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules", "dist", "test"],
"references": [{ "path": "../config" }, { "path": "../logger" }, { "path": "../queue" }]
"references": [
{ "path": "../services" },
{ "path": "../config" },
{ "path": "../logger" },
{ "path": "../queue" }
]
}

View file

@ -10,6 +10,7 @@
"test": "bun test"
},
"dependencies": {
"@stock-bot/services": "workspace:*",
"@stock-bot/cache": "workspace:*",
"@stock-bot/config": "workspace:*",
"@stock-bot/handler-registry": "workspace:*",

View file

@ -5,12 +5,11 @@ import type {
HandlerConfigWithSchedule,
HandlerMetadata,
IHandler,
IServiceContainer,
JobHandler,
ServiceTypes,
} from '@stock-bot/types';
import type { IServiceContainer, ServiceTypes } from '@stock-bot/services';
import { fetch } from '@stock-bot/utils';
import type { Collection } from 'mongodb';
import type { Collection, Document } from 'mongodb';
// Handler registry is now injected, not imported
import { createJobHandler } from '../utils/create-job-handler';
@ -63,7 +62,7 @@ export abstract class BaseHandler<TServices extends ServiceTypes = ServiceTypes>
constructor.__handlerName || handlerName || this.constructor.name.toLowerCase();
// Flatten all services onto the handler instance
this.logger = getLogger(this.constructor.name) as TServices['logger'];
this.logger = (services.logger ?? getLogger(this.constructor.name)) as TServices['logger'];
this.cache = services.cache as TServices['cache'];
this.globalCache = services.globalCache as TServices['globalCache'];
this.queueManager = services.queueManager as TServices['queueManager'];
@ -160,11 +159,11 @@ export abstract class BaseHandler<TServices extends ServiceTypes = ServiceTypes>
/**
* Get a MongoDB collection with type safety
*/
protected collection<T extends {} = any>(name: string): Collection<T> {
protected collection<T extends Document = Document>(name: string): Collection<T> {
if (!this.mongodb) {
throw new Error('MongoDB service is not available');
}
return this.mongodb.collection(name);
return this.mongodb.collection<T>(name);
}
/**

View file

@ -14,6 +14,7 @@ export type {
RateLimitOptions
} from './decorators/rate-limit';
export { createJobHandler } from './utils/create-job-handler';
export type { IServiceContainer, ServiceTypes } from '@stock-bot/services';
// Re-export commonly used types from @stock-bot/types for convenience
export type {

View file

@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it, mock } from 'bun:test';
import type { ExecutionContext, IServiceContainer } from '@stock-bot/types';
import type { ExecutionContext } from '@stock-bot/types';
import type { IServiceContainer } from '@stock-bot/services';
import { BaseHandler } from '../src/base/BaseHandler';
// Test handler with metadata

View file

@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it, mock } from 'bun:test';
import type { ExecutionContext, IServiceContainer } from '@stock-bot/types';
import type { ExecutionContext } from '@stock-bot/types';
import type { IServiceContainer } from '@stock-bot/services';
import { BaseHandler, ScheduledHandler } from '../src/base/BaseHandler';
// Test handler implementation

View file

@ -1,5 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test';
import type { ExecutionContext, IServiceContainer } from '@stock-bot/types';
import type { ExecutionContext } from '@stock-bot/types';
import type { IServiceContainer } from '@stock-bot/services';
import * as utils from '@stock-bot/utils';
import { BaseHandler } from '../src/base/BaseHandler';

View file

@ -6,7 +6,8 @@ import type { CacheProvider } from '@stock-bot/cache';
import type { Logger } from '@stock-bot/logger';
import type { SimpleProxyManager } from '@stock-bot/proxy';
import type { Queue, QueueManager } from '@stock-bot/queue';
import type { ExecutionContext, IServiceContainer, ServiceTypes } from '@stock-bot/types';
import type { ExecutionContext } from '@stock-bot/types';
import type { IServiceContainer, ServiceTypes } from '@stock-bot/services';
import { BaseHandler, ScheduledHandler } from '../src/base/BaseHandler';
import { Handler, Operation } from '../src/decorators/decorators';

View file

@ -2,7 +2,8 @@ import { beforeEach, describe, expect, it, mock, type Mock } from 'bun:test';
import type { CacheProvider } from '@stock-bot/cache';
import type { Logger } from '@stock-bot/logger';
import type { Queue, QueueManager } from '@stock-bot/queue';
import type { ExecutionContext, IServiceContainer, ServiceTypes } from '@stock-bot/types';
import type { ExecutionContext } from '@stock-bot/types';
import type { IServiceContainer, ServiceTypes } from '@stock-bot/services';
import { BaseHandler } from '../src/base/BaseHandler';
import {
Handler,
@ -75,6 +76,7 @@ describe('BaseHandler', () => {
const handler = new BaseHandler(mockServices, 'test-handler');
expect(handler).toBeDefined();
expect(handler.logger).toBeDefined();
expect(handler.logger).toBe(mockServices.logger);
});
it('should execute operations', async () => {

View file

@ -7,6 +7,7 @@
},
"include": ["src/**/*"],
"references": [
{ "path": "../services" },
{ "path": "../config" },
{ "path": "../logger" },
{ "path": "../cache" },

View file

@ -8,4 +8,4 @@
export { Logger, getLogger, shutdownLoggers, setLoggerConfig } from './logger';
// Type definitions
export type { LogLevel, LogContext, LogMetadata, LoggerConfig } from './types';
export type { LogLevel, LogContext, LogMetadata, LoggerConfig, LoggerLike } from './types';

View file

@ -1,10 +1,15 @@
/**
* Simplified type definitions for the logger library
*/
import type { Logger } from './logger';
// Standard log levels (simplified to pino defaults)
export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
/** Logging capability accepted by adapters, including console-compatible loggers. */
export type LoggerLike = Pick<Logger, Exclude<LogLevel, 'fatal'>> &
Partial<Pick<Logger, 'child' | 'fatal'>>;
// Context that persists across log calls
export interface LogContext {
[key: string]: any;

View file

@ -3,6 +3,7 @@ import type { CacheProvider } from '@stock-bot/cache';
import { createCache } from '@stock-bot/cache';
import type { HandlerRegistry } from '@stock-bot/handler-registry';
import { getLogger } from '@stock-bot/logger';
import type { LoggerLike as Logger } from '@stock-bot/logger';
import Redis from 'ioredis';
import { Queue, type QueueWorkerConfig } from './queue';
import { QueueRateLimiter } from './rate-limiter';
@ -19,16 +20,6 @@ import type {
} from './types';
import { getRedisConnection } from './utils';
// Logger interface for type safety
interface Logger {
info(message: string, meta?: Record<string, unknown>): void;
error(message: string, meta?: Record<string, unknown>): void;
warn(message: string, meta?: Record<string, unknown>): void;
debug(message: string, meta?: Record<string, unknown>): void;
trace(message: string, meta?: Record<string, unknown>): void;
child?(name: string, context?: Record<string, unknown>): Logger;
}
/**
* QueueManager provides unified queue and cache management with service discovery
* Handles both local and cross-service queue operations

View file

@ -1,19 +1,10 @@
import { Queue as BullQueue, QueueEvents, Worker, type Job } from 'bullmq';
import type { LoggerLike as Logger } from '@stock-bot/logger';
// Handler registry will be injected
import type { HandlerRegistry } from '@stock-bot/handler-registry';
import type { ExtendedJobOptions, JobData, JobOptions, QueueStats, RedisConfig } from './types';
import { getRedisConnection } from './utils';
// Logger interface for type safety
interface Logger {
info(message: string, meta?: Record<string, unknown>): void;
error(message: string, meta?: Record<string, unknown>): void;
warn(message: string, meta?: Record<string, unknown>): void;
debug(message: string, meta?: Record<string, unknown>): void;
trace(message: string, meta?: Record<string, unknown>): void;
child?(name: string, context?: Record<string, unknown>): Logger;
}
export interface QueueWorkerConfig {
workers?: number;
concurrency?: number;
@ -205,6 +196,17 @@ export class Queue {
return await this.bullQueue.getJob(jobId);
}
/** Wait for a result using a QueueEvents connection owned by this queue. */
async waitForJob<T>(job: Job<unknown, T>, timeout = 30000): Promise<T> {
if (!this.queueEvents) {
this.queueEvents = new QueueEvents(this.queueName, {
connection: getRedisConnection(this.redisConfig),
});
}
await this.queueEvents.waitUntilReady();
return job.waitUntilFinished(this.queueEvents, timeout);
}
/**
* Get jobs by state
*/

View file

@ -9,7 +9,6 @@
"references": [
{ "path": "../cache" },
{ "path": "../handler-registry" },
{ "path": "../handlers" },
{ "path": "../logger" },
{ "path": "../types" }
]

View file

@ -2,8 +2,8 @@
"extends": ["//"],
"tasks": {
"build": {
"dependsOn": ["@stock-bot/cache#build", "@stock-bot/logger#build", "@stock-bot/types#build"],
"outputs": ["dist/**"],
"dependsOn": ["^build"],
"outputs": ["dist/**", "*.tsbuildinfo"],
"inputs": [
"src/**",
"package.json",

View file

@ -0,0 +1,29 @@
{
"name": "@stock-bot/services",
"version": "1.0.0",
"private": true,
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"scripts": {
"build": "tsc",
"clean": "rm -rf dist"
},
"dependencies": {
"@stock-bot/browser": "workspace:*",
"@stock-bot/cache": "workspace:*",
"@stock-bot/logger": "workspace:*",
"@stock-bot/mongodb": "workspace:*",
"@stock-bot/postgres": "workspace:*",
"@stock-bot/proxy": "workspace:*",
"@stock-bot/questdb": "workspace:*",
"@stock-bot/queue": "workspace:*",
"playwright": "^1.40.0"
}
}

View file

@ -0,0 +1,44 @@
import type { Browser as BrowserImplementation } from '@stock-bot/browser';
import type { CacheProvider } from '@stock-bot/cache';
import type { Logger as LoggerImplementation } from '@stock-bot/logger';
import type { MongoDBClient as MongoDBImplementation } from '@stock-bot/mongodb';
import type { PostgreSQLClient as PostgresImplementation } from '@stock-bot/postgres';
import type { ProxyManager as ProxyImplementation } from '@stock-bot/proxy';
import type { QuestDBClient as QuestDBImplementation } from '@stock-bot/questdb';
import type {
Queue as QueueImplementation,
QueueManager as QueueManagerImplementation,
} from '@stock-bot/queue';
/** Public capabilities, derived from the owning adapter instead of copied signatures. */
type Public<T> = Pick<T, keyof T>;
export type Logger = Public<LoggerImplementation>;
export type Queue = Public<QueueImplementation>;
export type QueueManager = Public<QueueManagerImplementation>;
export type MongoDBClient = Public<MongoDBImplementation>;
export type PostgresClient = Public<PostgresImplementation>;
export type QuestDBClient = Public<QuestDBImplementation>;
export type Browser = Public<BrowserImplementation>;
export type ProxyManager = Public<ProxyImplementation>;
export type { CacheProvider, CacheStats } from '@stock-bot/cache';
export type { BrowserContext, Page } from 'playwright';
export type { ProxyInfo, ProxyStats } from '@stock-bot/proxy';
/** Disabled adapters are null; omitted capabilities are undefined. */
export interface ServiceTypes {
logger: Logger;
cache?: CacheProvider | null;
globalCache?: CacheProvider | null;
queueManager?: QueueManager | null;
queue?: Queue | null;
proxy?: ProxyManager | null;
browser?: Browser | null;
mongodb?: MongoDBClient | null;
postgres?: PostgresClient | null;
questdb?: QuestDBClient | null;
}
export interface IServiceContainer extends ServiceTypes {
readonly custom?: Record<string, any>;
}

View file

@ -0,0 +1,61 @@
import type { Browser as BrowserImplementation } from '@stock-bot/browser';
import type { MongoDBClient as MongoDBImplementation } from '@stock-bot/mongodb';
import type { PostgreSQLClient as PostgresImplementation } from '@stock-bot/postgres';
import type { ProxyManager as ProxyImplementation } from '@stock-bot/proxy';
import type { QuestDBClient as QuestDBImplementation } from '@stock-bot/questdb';
import type {
Queue as QueueImplementation,
QueueManager as QueueManagerImplementation,
} from '@stock-bot/queue';
import type {
Browser,
IServiceContainer,
MongoDBClient,
PostgresClient,
ProxyManager,
QuestDBClient,
Queue,
QueueManager,
} from '../src';
// Implementations must remain assignable to the capabilities injected into consumers.
declare const implementations: {
browser: BrowserImplementation;
mongodb: MongoDBImplementation;
postgres: PostgresImplementation;
proxy: ProxyImplementation;
questdb: QuestDBImplementation;
queue: QueueImplementation;
queueManager: QueueManagerImplementation;
};
implementations satisfies {
browser: Browser;
mongodb: MongoDBClient;
postgres: PostgresClient;
proxy: ProxyManager;
questdb: QuestDBClient;
queue: Queue;
queueManager: QueueManager;
};
declare const services: IServiceContainer;
services.queueManager?.getQueue('symbols').add('sync', {
handler: 'symbols',
operation: 'sync',
payload: {},
});
services.postgres?.connected;
services.mongodb?.collection<{ symbol: string }>('symbols').findOne({ symbol: 'AAPL' });
services.browser?.createPageWithProxy('https://example.com');
// These obsolete APIs must not silently return through a copied service interface.
// @ts-expect-error An individual queue is not a queue manager.
services.queue?.getQueue('symbols');
// @ts-expect-error The queue adapter exposes add(), not addJob().
services.queue?.addJob('sync', {});
// @ts-expect-error PostgreSQL exposes connected as a property.
services.postgres?.isConnected();
// @ts-expect-error The browser capability is the managed adapter, not a Playwright Browser.
services.browser?.newPage();
// @ts-expect-error A typed collection retains its document fields.
services.mongodb?.collection<{ symbol: string }>('symbols').findOne({ symbol: 123 });

View file

@ -0,0 +1,19 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist",
"composite": true
},
"include": ["src/**/*.ts"],
"references": [
{ "path": "../../services/browser" },
{ "path": "../cache" },
{ "path": "../logger" },
{ "path": "../../data/mongodb" },
{ "path": "../../data/postgres" },
{ "path": "../../services/proxy" },
{ "path": "../../data/questdb" },
{ "path": "../queue" }
]
}

View file

@ -61,27 +61,6 @@ export type {
TypedJobHandler,
} from './handlers';
// Export service container interface
export type { IServiceContainer } from './service-container';
// Export service types
export type {
ServiceTypes,
Logger,
CacheProvider,
QueueManager,
Queue,
MongoDBClient,
PostgresClient,
QuestDBClient,
Browser,
BrowserContext,
Page,
ProxyManager,
ProxyInfo,
ProxyStats,
} from './services';
// Export decorator types
export type {
ScheduleConfig,

View file

@ -1,17 +0,0 @@
/**
* Service Container Interface
* Pure interface definition with full type safety
* Used by both DI and Handlers packages
*/
import type { ServiceTypes } from './services';
/**
* Universal service container interface
* Provides access to all common services in a type-safe manner
* Designed to work across different service contexts
*/
export interface IServiceContainer extends ServiceTypes {
// Optional extensions for future use
readonly custom?: Record<string, any>;
}

View file

@ -1,311 +0,0 @@
/**
* Service Type Definitions
* Provides full type safety for all injected services
*/
// Import actual service types from their packages
// These are type-only imports, so no runtime dependencies
// Logger types
export interface Logger {
info(message: string, meta?: Record<string, unknown>): void;
error(message: string, meta?: Record<string, unknown>): void;
warn(message: string, meta?: Record<string, unknown>): void;
debug(message: string, meta?: Record<string, unknown>): void;
trace(message: string, meta?: Record<string, unknown>): void;
fatal(message: string, meta?: Record<string, unknown>): void;
child?(name: string, context?: Record<string, unknown>): Logger;
}
// Cache types - matches the actual CacheProvider interface from @stock-bot/cache
export interface CacheProvider {
get<T>(key: string): Promise<T | null>;
set<T>(
key: string,
value: T,
options?:
| number
| {
ttl?: number;
preserveTTL?: boolean;
onlyIfExists?: boolean;
onlyIfNotExists?: boolean;
getOldValue?: boolean;
}
): Promise<T | null>;
del(key: string): Promise<void>;
exists(key: string): Promise<boolean>;
clear(): Promise<void>;
keys(pattern: string): Promise<string[]>;
getStats(): CacheStats;
health(): Promise<boolean>;
waitForReady(timeout?: number): Promise<void>;
isReady(): boolean;
}
export interface CacheStats {
hits: number;
misses: number;
errors: number;
hitRate: number;
total: number;
uptime: number;
}
// Queue Manager types
export interface QueueManager {
getQueue(queueName: string, options?: any): Queue;
createQueue(queueName: string, options?: any): Queue;
getOrCreateQueue(queueName: string, options?: any): Queue;
queueExists(queueName: string): boolean;
deleteQueue(queueName: string): Promise<void>;
getQueueStats(queueName?: string): Promise<any>;
getBatchCache(queueName: string): CacheProvider | null;
getRateLimiter(): any;
checkRateLimit(key: string, rule?: string): Promise<{ allowed: boolean; retryAfter?: number }>;
shutdown(): Promise<void>;
}
export interface Queue {
add(name: string, data: any, opts?: any): Promise<any>;
addBulk(jobs: Array<{ name: string; data: any; opts?: any }>): Promise<any[]>;
process(concurrency: number, processor: any): Promise<void>;
process(name: string, concurrency: number, processor: any): Promise<void>;
process(processor: any): Promise<void>;
on(event: string, listener: (...args: any[]) => void): void;
pause(): Promise<void>;
resume(): Promise<void>;
close(): Promise<void>;
clean(grace: number, limit?: number, type?: string): Promise<string[]>;
getJobs(types: string[], start?: number, end?: number, asc?: boolean): Promise<any[]>;
getJobCounts(...types: string[]): Promise<Record<string, number>>;
name: string;
}
// MongoDB types
export interface MongoDBClient {
connect(): Promise<void>;
disconnect(): Promise<void>;
isConnected(): boolean;
getDb(dbName?: string): any; // MongoDB Db type
collection(name: string, dbName?: string): any; // MongoDB Collection
createCollection(name: string, options?: any, dbName?: string): Promise<void>;
dropCollection(name: string, dbName?: string): Promise<boolean>;
listCollections(dbName?: string): Promise<Array<{ name: string; type: string }>>;
find<T = any>(collection: string, filter?: any, options?: any, dbName?: string): Promise<T[]>;
findOne<T = any>(
collection: string,
filter: any,
options?: any,
dbName?: string
): Promise<T | null>;
insertOne<T = any>(collection: string, document: T, options?: any, dbName?: string): Promise<any>;
insertMany<T = any>(
collection: string,
documents: T[],
options?: any,
dbName?: string
): Promise<any>;
updateOne(
collection: string,
filter: any,
update: any,
options?: any,
dbName?: string
): Promise<any>;
updateMany(
collection: string,
filter: any,
update: any,
options?: any,
dbName?: string
): Promise<any>;
deleteOne(collection: string, filter: any, options?: any, dbName?: string): Promise<any>;
deleteMany(collection: string, filter: any, options?: any, dbName?: string): Promise<any>;
countDocuments(collection: string, filter?: any, options?: any, dbName?: string): Promise<number>;
aggregate<T = any>(
collection: string,
pipeline: any[],
options?: any,
dbName?: string
): Promise<T[]>;
createIndex(collection: string, indexSpec: any, options?: any, dbName?: string): Promise<string>;
dropIndex(collection: string, indexName: string, options?: any, dbName?: string): Promise<void>;
listIndexes(collection: string, dbName?: string): Promise<any[]>;
batchUpsert<T = any>(
collection: string,
documents: T[],
uniqueKeys: string | string[],
options?: any,
dbName?: string
): Promise<any>;
batchUpsertStock<T = any>(
collection: string,
documents: T[],
uniqueKeys: string | string[],
options?: any
): Promise<any>;
batchUpsertTrading<T = any>(
collection: string,
documents: T[],
uniqueKeys: string | string[],
options?: any
): Promise<any>;
batchUpsertAnalytics<T = any>(
collection: string,
documents: T[],
uniqueKeys: string | string[],
options?: any
): Promise<any>;
}
// PostgreSQL types
export interface PostgresClient {
query<T = any>(text: string, params?: any[]): Promise<{ rows: T[]; rowCount: number }>;
queryOne<T = any>(text: string, params?: any[]): Promise<T | null>;
execute(text: string, params?: any[]): Promise<{ rowCount: number }>;
transaction<T>(callback: (client: any) => Promise<T>): Promise<T>;
insert(table: string, data: Record<string, any>, returning?: string | string[]): Promise<any>;
update(
table: string,
data: Record<string, any>,
where: Record<string, any>,
returning?: string | string[]
): Promise<any>;
delete(table: string, where: Record<string, any>, returning?: string | string[]): Promise<any>;
upsert(
table: string,
data: Record<string, any>,
conflictColumns: string | string[],
returning?: string | string[]
): Promise<any>;
batchInsert(
table: string,
data: Record<string, any>[],
returning?: string | string[]
): Promise<any[]>;
batchUpsert(
table: string,
data: Record<string, any>[],
conflictColumns: string | string[],
returning?: string | string[]
): Promise<any[]>;
exists(table: string, where: Record<string, any>): Promise<boolean>;
count(table: string, where?: Record<string, any>): Promise<number>;
getClient(): Promise<any>;
releaseClient(client: any): void;
end(): Promise<void>;
isConnected(): boolean;
}
// QuestDB types
export interface QuestDBClient {
connect(): Promise<void>;
disconnect(): Promise<void>;
isConnected(): boolean;
query<T = any>(sql: string): Promise<T[]>;
insert(table: string, data: Record<string, any> | Record<string, any>[]): Promise<void>;
insertBatch(table: string, data: Record<string, any>[]): Promise<void>;
createTable(tableDef: any): Promise<void>;
dropTable(tableName: string): Promise<void>;
tableExists(tableName: string): Promise<boolean>;
getTableSchema(tableName: string): Promise<any>;
flush(): Promise<void>;
insertWithTimestamp(
table: string,
data: Record<string, any>,
timestamp?: Date | number
): Promise<void>;
batchInsertWithTimestamp(
table: string,
data: Array<Record<string, any> & { timestamp?: Date | number }>
): Promise<void>;
}
// Browser types (Playwright)
export interface Browser {
newPage(): Promise<Page>;
newContext(options?: any): Promise<BrowserContext>;
close(): Promise<void>;
isConnected(): boolean;
version(): string;
}
export interface BrowserContext {
newPage(): Promise<Page>;
close(): Promise<void>;
pages(): Page[];
setDefaultTimeout(timeout: number): void;
setDefaultNavigationTimeout(timeout: number): void;
addCookies(cookies: any[]): Promise<void>;
clearCookies(): Promise<void>;
}
export interface Page {
goto(url: string, options?: any): Promise<any>;
waitForSelector(selector: string, options?: any): Promise<any>;
click(selector: string, options?: any): Promise<void>;
fill(selector: string, value: string, options?: any): Promise<void>;
evaluate<T = any>(pageFunction: any, arg?: any): Promise<T>;
evaluateHandle<T = any>(pageFunction: any, arg?: any): Promise<T>;
screenshot(options?: any): Promise<Buffer>;
pdf(options?: any): Promise<Buffer>;
content(): Promise<string>;
title(): Promise<string>;
url(): string;
close(): Promise<void>;
waitForTimeout(timeout: number): Promise<void>;
waitForLoadState(state?: string, options?: any): Promise<void>;
locator(selector: string): any;
$$(selector: string): Promise<any[]>;
textContent(selector: string): Promise<string | null>;
}
// Proxy Manager types
export interface ProxyManager {
getProxy(): string | null;
getProxyInfo(): ProxyInfo | null;
getProxies(count: number, key?: string): Promise<ProxyInfo[]>;
releaseProxy(proxy: ProxyInfo | string): Promise<void>;
markProxyFailed(proxy: ProxyInfo | string, reason?: string): Promise<void>;
getStats(): ProxyStats;
resetProxy(proxy: ProxyInfo | string): Promise<void>;
blacklistProxy(proxy: ProxyInfo | string, duration?: number): Promise<void>;
isBlacklisted(proxy: ProxyInfo | string): Promise<boolean>;
refreshProxies(): Promise<void>;
}
// ProxyInfo should be imported from @stock-bot/proxy package
// to avoid duplication. Using minimal definition here for type compatibility
export interface ProxyInfo {
host: string;
port: number;
protocol: 'http' | 'https';
username?: string;
password?: string;
[key: string]: any; // Allow additional properties from proxy package
}
export interface ProxyStats {
total: number;
available: number;
inUse: number;
failed: number;
blacklisted: number;
}
/**
* Complete service types for dependency injection
*/
export interface ServiceTypes {
logger: Logger;
cache?: CacheProvider;
globalCache?: CacheProvider;
queueManager?: QueueManager;
queue?: Queue; // Individual queue instance
proxy?: ProxyManager;
browser?: Browser;
mongodb?: MongoDBClient;
postgres?: PostgresClient;
questdb?: QuestDBClient;
}