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

@ -1,158 +1,24 @@
#!/bin/bash
#!/usr/bin/env bash
set -euo pipefail
# Build All Script for Stock Bot
# Builds libraries first, then apps with Turbo, then dashboard with Angular CLI
cd "$(dirname "${BASH_SOURCE[0]}")/.."
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
GRAY='\033[0;37m'
NC='\033[0m' # No Color
# Default options
CLEAN=false
VERBOSE=false
# Parse command line arguments
while [[ $# -gt 0 ]]; do
case $1 in
--clean|-c)
CLEAN=true
shift
;;
--verbose|-v)
VERBOSE=true
shift
;;
--help|-h)
echo "Usage: $0 [--clean] [--verbose]"
echo " --clean, -c Clean previous builds before building"
echo " --verbose, -v Show verbose output"
echo " --help, -h Show this help message"
exit 0
;;
*)
echo "Unknown option: $1"
echo "Use --help for usage information"
exit 1
;;
esac
args=()
for option in "$@"; do
case "$option" in
--clean|-c) args+=(--force) ;;
--verbose|-v) args+=(--output-logs=full) ;;
--dry|--dry=json|--dry-run|--dry-run=json) args+=("$option") ;;
--help|-h)
echo "Usage: $0 [--clean] [--verbose]"
echo " --clean Force every workspace build, ignoring cached results"
echo " --verbose Print complete workspace build logs"
exit 0
;;
*) echo "Unknown option: $option" >&2; exit 1 ;;
esac
done
echo -e "${CYAN}🚀 Starting complete build process...${NC}"
# Store original location
ORIGINAL_DIR=$(pwd)
# Find git root directory
GIT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null)
if [ $? -ne 0 ]; then
echo -e "${RED}Error: Not in a git repository. Please run this script from within the stock-bot git repository.${NC}"
exit 1
fi
cd "$GIT_ROOT"
cleanup() {
cd "$ORIGINAL_DIR"
}
# Set up cleanup on exit
trap cleanup EXIT
# Step 1: Clean if requested
if [ "$CLEAN" = true ]; then
echo -e "${YELLOW}🧹 Cleaning previous builds...${NC}"
./scripts/clean.sh --dist
if [ $? -ne 0 ]; then
echo -e "${RED}❌ Clean failed${NC}"
exit 1
fi
fi
# Step 2: Build libraries first
echo -e "${GREEN}📚 Building libraries...${NC}"
./scripts/build-libs.sh
if [ $? -ne 0 ]; then
echo -e "${RED}❌ Library build failed${NC}"
exit 1
fi
# Step 3: Build apps with Turbo (excluding dashboard)
echo -e "${GREEN}🏗️ Building applications with Turbo...${NC}"
# Get list of apps excluding dashboard
if [ -d "apps" ]; then
app_dirs=$(find apps -maxdepth 1 -type d -name "*" ! -name "dashboard" ! -name "apps" | sort)
if [ -n "$app_dirs" ]; then
# Build each app individually to avoid filter syntax issues
for app_dir in $app_dirs; do
app_name=$(basename "$app_dir")
app_path="./apps/$app_name"
echo -e "${CYAN} Building $app_name...${NC}"
turbo_cmd="turbo run build --filter=$app_path"
if [ "$VERBOSE" = true ]; then
echo -e "${GRAY} Running: $turbo_cmd${NC}"
fi
eval $turbo_cmd
if [ $? -ne 0 ]; then
echo -e "${RED}❌ Failed to build app: $app_name${NC}"
exit 1
fi
done
app_names=$(echo "$app_dirs" | xargs -n1 basename | tr '\n' ', ' | sed 's/,$//')
echo -e "${GREEN}✅ Apps built successfully: $app_names${NC}"
else
echo -e "${YELLOW}ℹ️ No non-dashboard apps found to build with Turbo${NC}"
fi
fi
# Step 4: Build dashboard with Angular CLI
dashboard_path="apps/dashboard"
if [ -d "$dashboard_path" ]; then
echo -e "${GREEN}🎨 Building Angular dashboard...${NC}"
cd "$dashboard_path"
# Check if ng is available
if ! command -v ng &> /dev/null; then
echo -e "${RED}❌ Angular CLI not found. Installing...${NC}"
npm install -g @angular/cli
if [ $? -ne 0 ]; then
echo -e "${RED}❌ Failed to install Angular CLI${NC}"
exit 1
fi
fi
# Build dashboard
ng build --configuration production
if [ $? -ne 0 ]; then
echo -e "${RED}❌ Dashboard build failed${NC}"
exit 1
fi
echo -e "${GREEN}✅ Dashboard built successfully${NC}"
cd "$ORIGINAL_DIR"
else
echo -e "${YELLOW}⚠️ Dashboard not found at $dashboard_path${NC}"
fi
echo -e "${GREEN}🎉 Complete build finished successfully!${NC}"
echo ""
echo -e "${CYAN}Build Summary:${NC}"
echo -e "${GREEN} ✅ Libraries built${NC}"
if [ -n "$app_dirs" ]; then
echo -e "${GREEN} ✅ Apps built: $app_names${NC}"
fi
if [ -d "apps/dashboard" ]; then
echo -e "${GREEN} ✅ Dashboard built${NC}"
fi
# The stock-app package contains convenience commands, not buildable source.
# Select all leaf workspaces so nested stock services are actually built.
exec bun run turbo run build --filter='!@stock-bot/stock-app' "${args[@]}"

View file

@ -1,92 +1,7 @@
#!/bin/bash
#!/usr/bin/env bash
set -euo pipefail
# Build and install the new libraries
cd "$(dirname "${BASH_SOURCE[0]}")/.."
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
echo -e "${CYAN}Building and installing new libraries...${NC}"
# Store original location
ORIGINAL_DIR=$(pwd)
# Find git root directory
GIT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null)
if [ $? -ne 0 ]; then
echo -e "${RED}Error: Not in a git repository. Please run this script from within the stock-bot git repository.${NC}"
exit 1
fi
cd "$GIT_ROOT"
cleanup() {
cd "$ORIGINAL_DIR"
}
# Set up cleanup on exit
trap cleanup EXIT
# Build order is important due to dependencies
libs=(
# Core Libraries - minimal dependencies
"core/types" # Base types - no dependencies
"core/logger" # Logging utilities - depends on types
"core/config" # Configuration - depends on types and logger
# Utils - needed by many libraries
"utils" # Utilities - minimal dependencies
# Data access libraries
"data/mongodb" # MongoDB client - depends on core libs
"data/postgres" # PostgreSQL client - depends on core libs
"data/questdb" # QuestDB client - depends on core libs
# Core infrastructure services
"core/shutdown" # Shutdown - no dependencies
"core/cache" # Cache - depends on core libs
"core/event-bus" # Event bus - depends on core libs
"core/handler-registry" # Handler registry - depends on core libs
"core/handlers" # Handlers - depends on core libs, handler-registry, and utils
"core/queue" # Queue - depends on core libs, cache, handlers, and handler-registry
# Application services
"services/browser" # Browser - depends on core libs
"services/proxy" # Proxy manager - depends on core libs and cache
# DI - dependency injection library
"core/di" # Dependency injection - depends on data, service libs, and handlers
)
# Build each library in order
for lib in "${libs[@]}"; do
lib_path="$GIT_ROOT/libs/$lib"
echo -e "${GREEN}Building $lib...${NC}"
cd "$lib_path"
# Clean previous build artifacts
rm -rf dist tsconfig.tsbuildinfo
# Use tsc with build mode to respect project references
# npx tsc -b
bun run build
if [ $? -ne 0 ]; then
echo -e "${RED}Failed to build $lib. Exiting.${NC}"
exit 1
fi
# Verify build was successful
if [ -d "dist" ]; then
echo -e "${GREEN}✓ Built successfully${NC}"
else
echo -e "${RED}✗ Build did not create dist directory${NC}"
exit 1
fi
done
echo -e "${GREEN}All libraries built successfully!${NC}"
cd "$GIT_ROOT"
# Turbo derives ordering from package dependencies, including contract packages.
exec bun run turbo run build --filter='./libs/**' "$@"

42
scripts/check.ts Normal file
View file

@ -0,0 +1,42 @@
/** Run every repository gate and report failures without hiding later checks. */
import { fileURLToPath } from 'node:url';
export const checks = [
'build',
'typecheck',
'test:contracts',
'test:tooling',
'lint:check',
] as const;
async function runTask(check: string): Promise<number> {
process.stdout.write(`\nRunning ${check}\n`);
const child = Bun.spawn([process.execPath, 'run', check], {
cwd: fileURLToPath(new URL('..', import.meta.url)),
stdin: 'inherit',
stdout: 'inherit',
stderr: 'inherit',
});
return child.exited;
}
export async function runChecks(
tasks: readonly string[] = checks,
run: (task: string) => Promise<number> = runTask
): Promise<string[]> {
const failed: string[] = [];
for (const task of tasks) {
if ((await run(task)) !== 0) failed.push(task);
}
return failed;
}
if (import.meta.main) {
const failed = await runChecks();
if (failed.length > 0) {
process.stderr.write(`\nFailed checks: ${failed.join(', ')}\n`);
process.exitCode = 1;
} else {
process.stdout.write('\nAll repository checks passed.\n');
}
}

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']);
});
});