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

@ -0,0 +1,18 @@
import { createRequire } from 'node:module';
import { describe, expect, it } from 'bun:test';
import { IncrementalSMA, TechnicalIndicators } from '@stock-bot/engine';
describe('generated native bindings', () => {
it('ESM loads the generated artifact and exposes the documented constructor aliases', () => {
const sma = new IncrementalSMA(2);
sma.update(10);
expect(sma.update(12)).toBe(11);
expect(new TechnicalIndicators().calculateSma([1, 2, 3], 2)).toEqual([1.5, 2.5]);
});
it('CommonJS exposes the same native constructors', () => {
const binding = createRequire(import.meta.url)('@stock-bot/engine');
expect(binding.TechnicalIndicators).toBe(TechnicalIndicators);
expect(binding.IncrementalSMA).toBe(IncrementalSMA);
});
});

View file

@ -0,0 +1,62 @@
import { describe, expect, it, mock } from 'bun:test';
import { getLogger } from '@stock-bot/logger';
import type { IServiceContainer, QueueManager } from '@stock-bot/services';
import { createQueueRoutes } from '../../apps/stock/data-ingestion/src/routes/queue.routes';
import { PipelineService } from '../../apps/stock/web-api/src/services/pipeline.service';
function fixture() {
const job = { id: 'job-1' };
const queue = {
add: mock(async () => job),
waitForJob: mock(async () => ({ exchanges: 12 })),
};
const manager = {
getQueue: mock(() => queue),
getGlobalStats: mock(async () => ({ totalJobs: 3 })),
};
const container: IServiceContainer = {
logger: getLogger('service-consumer-test'),
queueManager: manager as unknown as QueueManager,
};
return { container, manager, queue, job };
}
describe('service consumers', () => {
it('the web API submits work to the pipeline queue through the real adapter API', async () => {
const { container, manager, queue } = fixture();
const result = await new PipelineService(container).syncQMSymbols();
expect(result.success).toBe(true);
expect(result.jobId).toBe('job-1');
expect(manager.getQueue).toHaveBeenCalledWith('{data-pipeline_symbols}');
expect(queue.add).toHaveBeenCalledWith('sync-qm-symbols', {
handler: 'symbols',
operation: 'sync-qm-symbols',
payload: {},
});
});
it('statistics wait for completion through the queue-owned events connection', async () => {
const { container, manager, queue, job } = fixture();
const result = await new PipelineService(container).getExchangeStats();
expect(result).toEqual({ success: true, data: { exchanges: 12 } });
expect(manager.getQueue).toHaveBeenCalledWith('{data-pipeline_exchanges}');
expect(queue.waitForJob).toHaveBeenCalledWith(job);
});
it('queue monitoring uses queueManager without requiring an individual queue', async () => {
const { container, manager } = fixture();
const response = await createQueueRoutes(container).request('http://localhost/status');
expect(response.status).toBe(200);
expect(manager.getGlobalStats).toHaveBeenCalledTimes(1);
expect(await response.json()).toMatchObject({ status: 'success', data: { totalJobs: 3 } });
});
it('a missing queue manager produces an explicit unavailable result', async () => {
const { container } = fixture();
container.queueManager = null;
expect(await new PipelineService(container).syncQMSymbols()).toEqual({
success: false,
error: 'Queue manager not available',
});
});
});

View file

@ -0,0 +1,101 @@
import { existsSync, readFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'bun:test';
import ts from 'typescript';
import { runChecks } from '../check';
const root = fileURLToPath(new URL('../../', import.meta.url));
const manifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
const packageFiles = [
...new Set<string>(
manifest.workspaces.flatMap((pattern: string) =>
Array.from(new Bun.Glob(`${pattern}/package.json`).scanSync({ cwd: root }))
)
),
];
function config(path: string) {
const result = ts.getParsedCommandLineOfConfigFile(
path,
{},
{
...ts.sys,
onUnRecoverableConfigFileDiagnostic(diagnostic) {
throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'));
},
}
);
if (!result) throw new Error(`Cannot read ${path}`);
return result;
}
describe('workspace verification', () => {
it('the real root build selects every buildable workspace and excludes the command aggregate', () => {
const result = Bun.spawnSync([process.execPath, 'run', 'build', '--dry=json'], {
cwd: root,
env: { ...process.env, TURBO_TELEMETRY_DISABLED: '1' },
});
expect(result.exitCode).toBe(0);
const plan = JSON.parse(new TextDecoder().decode(result.stdout));
const planned = new Set(plan.tasks.map((task: { taskId: string }) => task.taskId));
for (const file of packageFiles) {
const pkg = JSON.parse(readFileSync(join(root, file), 'utf8'));
if (pkg.scripts?.build && pkg.name !== '@stock-bot/stock-app') {
expect(planned.has(`${pkg.name}#build`)).toBe(true);
}
}
expect(planned.has('@stock-bot/stock-app#build')).toBe(false);
});
it('each TypeScript workspace has source inputs covered by the root type check', () => {
const checked = new Set(
config(join(root, 'tsconfig.check.json')).fileNames.map(file => resolve(file))
);
for (const file of packageFiles) {
const directory = join(root, dirname(file));
const project = join(directory, 'tsconfig.json');
if (!existsSync(join(directory, 'src')) || !existsSync(project)) continue;
const parsed = config(project);
expect(parsed.errors).toHaveLength(0);
expect(parsed.fileNames.length).toBeGreaterThan(0);
for (const source of parsed.fileNames.filter(path => /\.tsx?$/.test(path))) {
expect(checked.has(resolve(source))).toBe(true);
}
}
});
it('the package dependency graph remains acyclic', () => {
const packages = new Map<string, string[]>();
for (const file of packageFiles) {
const pkg = JSON.parse(readFileSync(join(root, file), 'utf8'));
packages.set(pkg.name, Object.keys(pkg.dependencies ?? {}));
}
function visit(name: string, stack: string[]) {
if (stack.includes(name))
throw new Error(`Dependency cycle: ${[...stack, name].join(' -> ')}`);
for (const dependency of packages.get(name) ?? []) {
if (packages.has(dependency)) visit(dependency, [...stack, name]);
}
}
for (const name of packages.keys()) visit(name, []);
});
it('the foundational types package has no adapter dependencies', () => {
const pkg = JSON.parse(readFileSync(join(root, 'libs/core/types/package.json'), 'utf8'));
expect(Object.keys(pkg.dependencies ?? {})).toHaveLength(0);
const source = readFileSync(join(root, 'libs/core/types/src/index.ts'), 'utf8');
expect(source).not.toContain('./services');
expect(source).not.toContain('./service-container');
});
it('a failed gate does not prevent later gates from running', async () => {
const visited: string[] = [];
const failed = await runChecks(['build', 'typecheck', 'tests'], async task => {
visited.push(task);
return task === 'build' ? 1 : 0;
});
expect(visited).toEqual(['build', 'typecheck', 'tests']);
expect(failed).toEqual(['build']);
});
});