refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack
- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched) - Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations() - Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation - Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims - Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution - Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
This commit is contained in:
parent
ce9e2df67c
commit
4cd6038063
432 changed files with 1247 additions and 44469 deletions
|
|
@ -1,23 +1,15 @@
|
|||
# General utilities
|
||||
|
||||
`@stock-bot/utils` is a private workspace package for infrastructure-neutral general
|
||||
helpers. Financial/feature calculations belong to `@stock-bot/calculations`, not here.
|
||||
`@stock-bot/utils` is a private workspace package for infrastructure-neutral HTTP and
|
||||
user-agent helpers. Financial/feature calculations belong to
|
||||
[`@stock-bot/calculations`](../calculations/README.md), not here.
|
||||
|
||||
## Supported capabilities
|
||||
|
||||
- `@stock-bot/utils/fetch`: `fetch` and the type-only `FetchOptions`.
|
||||
- `@stock-bot/utils/user-agent`: `getRandomUserAgent` selects from a fixed local list.
|
||||
- `@stock-bot/utils/common`: `createProxyUrl` encodes proxy credentials; `sleep`
|
||||
returns a timer-backed promise.
|
||||
- `@stock-bot/utils/dates`: `utcDates` supplies `isWeekday`, `nextWeekday`,
|
||||
`previousWeekday`, strict `parseDate` (`YYYY-MM-DD`) and `formatDate`.
|
||||
|
||||
The root explicitly exports these six runtime values (`fetch`, `getRandomUserAgent`,
|
||||
`createProxyUrl`, `sleep`, `utcDates`, `dateUtils`) plus the `FetchOptions` type.
|
||||
Capability subpaths avoid loading unrelated helpers. There are no wildcard/deep exports.
|
||||
|
||||
```ts
|
||||
import { utcDates } from '@stock-bot/utils/dates';
|
||||
import { fetch, type FetchOptions } from '@stock-bot/utils/fetch';
|
||||
import { getRandomUserAgent } from '@stock-bot/utils/user-agent';
|
||||
|
||||
|
|
@ -26,54 +18,16 @@ const options: FetchOptions = {
|
|||
timeout: 5_000,
|
||||
};
|
||||
const response = await fetch('https://example.com/data', options);
|
||||
const next = utcDates.nextWeekday(utcDates.parseDate('2024-03-08'));
|
||||
```
|
||||
|
||||
Fetch keeps its existing logging, Bun proxy, timeout and original-`Response` behavior.
|
||||
Non-OK statuses are returned, not thrown. Timeout cancellation and caller cancellation
|
||||
are not composed: a configured timeout currently replaces the supplied signal. The
|
||||
user-agent list is not fingerprinting or a guarantee of provider access.
|
||||
|
||||
Date arithmetic is explicitly UTC, validates inputs and does not mutate the supplied
|
||||
date. Weekdays are **not** exchange sessions: holidays, exchange time zones and trading
|
||||
hours are not modeled. The deprecated `dateUtils` names (`isTradingDay`,
|
||||
`getNextTradingDay`, `getPreviousTradingDay`, `formatDate`, `parseDate`) remain
|
||||
as aliases for migration, not as verified trading-calendar APIs. This replaces the old
|
||||
environment-dependent local weekday arithmetic; use `utcDates` in new code.
|
||||
|
||||
`@stock-bot/invariants` is the only runtime workspace dependency. `LoggerLike`
|
||||
from `@stock-bot/logger` is type-only. No databases, configuration initialization,
|
||||
application service containers or mandatory native bindings may be added here.
|
||||
|
||||
## Calculation migration and removals
|
||||
|
||||
The financial modules and OHLCV helpers were **relocated/preserved**, not discarded:
|
||||
|
||||
- Reviewed returns/analytics/window math and OHLCV processing:
|
||||
`@stock-bot/calculations` and its explicit capability subpaths.
|
||||
- All 105 formerly active calculation functions with their original bodies:
|
||||
`@stock-bot/calculations/legacy`, an opt-in historical API, not reviewed core.
|
||||
- All seven disabled numerical/indicator prototypes:
|
||||
non-executable source-verified snapshots in `libs/calculations/research/`.
|
||||
|
||||
See [the calculation contract](../calculations/README.md) and
|
||||
[the complete cleanup audit](../../docs/cleanup-audit.md) for readiness, preserved test
|
||||
scenarios and deliberate removals. The empty `analyzePortfolio` placeholder remains
|
||||
removed because it calculated nothing.
|
||||
|
||||
Import assertions directly from `@stock-bot/invariants`; the redundant utility assertion
|
||||
facade was removed, not its functionality. Import domain types from `@stock-bot/types`.
|
||||
No finance compatibility re-export is added to the general utility package.
|
||||
`@stock-bot/invariants` is the only runtime workspace dependency. `LoggerLike` from
|
||||
`@stock-bot/logger` is type-only. Import assertions directly from `@stock-bot/invariants`
|
||||
and domain types from `@stock-bot/types`.
|
||||
|
||||
## Verify
|
||||
|
||||
From the repository root:
|
||||
|
||||
```sh
|
||||
bun run test:utils
|
||||
bun run test:calculations
|
||||
bun run check
|
||||
```
|
||||
|
||||
The root gate includes general-utility and handler HTTP-consumer tests, calculation
|
||||
regressions and architecture checks for the explicit APIs and dependency boundaries.
|
||||
|
|
|
|||
|
|
@ -22,8 +22,6 @@
|
|||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./fetch": "./src/fetch.ts",
|
||||
"./user-agent": "./src/user-agent.ts",
|
||||
"./common": "./src/common.ts",
|
||||
"./dates": "./src/dateUtils.ts"
|
||||
"./user-agent": "./src/user-agent.ts"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,17 +0,0 @@
|
|||
export function createProxyUrl(proxy: {
|
||||
protocol: string;
|
||||
host: string;
|
||||
port: number;
|
||||
username?: string;
|
||||
password?: string;
|
||||
}): string {
|
||||
const { protocol, host, port, username, password } = proxy;
|
||||
if (username && password) {
|
||||
return `${protocol}://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${host}:${port}`;
|
||||
}
|
||||
return `${protocol}://${host}:${port}`;
|
||||
}
|
||||
|
||||
export function sleep(ms: number): Promise<void> {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
|
@ -1,48 +0,0 @@
|
|||
function valid(date: Date): Date {
|
||||
if (!Number.isFinite(date.getTime())) {
|
||||
throw new RangeError('Invalid UTC date');
|
||||
}
|
||||
return date;
|
||||
}
|
||||
|
||||
/** Weekdays in UTC, NOT an exchange calendar: holidays and venue sessions are not modeled. */
|
||||
function isWeekday(date: Date): boolean {
|
||||
const day = valid(date).getUTCDay();
|
||||
return day > 0 && day < 6;
|
||||
}
|
||||
|
||||
function shiftWeekday(date: Date, direction: 1 | -1): Date {
|
||||
const result = new Date(valid(date).getTime());
|
||||
do {
|
||||
result.setUTCDate(result.getUTCDate() + direction);
|
||||
} while (!isWeekday(result));
|
||||
return result;
|
||||
}
|
||||
|
||||
function parseDate(value: string): Date {
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) {
|
||||
throw new RangeError('Expected YYYY-MM-DD');
|
||||
}
|
||||
const date = valid(new Date(`${value}T00:00:00.000Z`));
|
||||
if (date.toISOString().slice(0, 10) !== value) {
|
||||
throw new RangeError('Invalid calendar date');
|
||||
}
|
||||
return date;
|
||||
}
|
||||
|
||||
export const utcDates = {
|
||||
isWeekday,
|
||||
nextWeekday: (date: Date): Date => shiftWeekday(date, 1),
|
||||
previousWeekday: (date: Date): Date => shiftWeekday(date, -1),
|
||||
formatDate: (date: Date): string => valid(date).toISOString().slice(0, 10),
|
||||
parseDate,
|
||||
};
|
||||
|
||||
/** @deprecated Compatibility names only. These are UTC weekdays, never verified trading sessions. */
|
||||
export const dateUtils = {
|
||||
isTradingDay: utcDates.isWeekday,
|
||||
getNextTradingDay: utcDates.nextWeekday,
|
||||
getPreviousTradingDay: utcDates.previousWeekday,
|
||||
formatDate: utcDates.formatDate,
|
||||
parseDate: utcDates.parseDate,
|
||||
};
|
||||
|
|
@ -1,5 +1,3 @@
|
|||
export { fetch } from './fetch';
|
||||
export type { FetchOptions } from './fetch';
|
||||
export { getRandomUserAgent } from './user-agent';
|
||||
export { createProxyUrl, sleep } from './common';
|
||||
export { dateUtils, utcDates } from './dateUtils';
|
||||
|
|
|
|||
|
|
@ -1,117 +0,0 @@
|
|||
import { describe, expect, it } from 'bun:test';
|
||||
import { createProxyUrl, sleep } from '@stock-bot/utils/common';
|
||||
import { dateUtils, utcDates } from '@stock-bot/utils/dates';
|
||||
|
||||
describe('restored general utilities', () => {
|
||||
describe('common utilities', () => {
|
||||
it('should create proxy URL with auth', () => {
|
||||
const proxy = {
|
||||
protocol: 'http',
|
||||
host: '192.168.1.1',
|
||||
port: 8080,
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
};
|
||||
|
||||
const url = createProxyUrl(proxy);
|
||||
expect(url).toBe('http://user:pass@192.168.1.1:8080');
|
||||
});
|
||||
|
||||
it('should create proxy URL without auth', () => {
|
||||
const proxy = {
|
||||
protocol: 'socks5',
|
||||
host: '192.168.1.1',
|
||||
port: 1080,
|
||||
};
|
||||
|
||||
const url = createProxyUrl(proxy);
|
||||
expect(url).toBe('socks5://192.168.1.1:1080');
|
||||
});
|
||||
|
||||
it('should sleep for specified milliseconds', async () => {
|
||||
const start = Date.now();
|
||||
await sleep(100);
|
||||
const elapsed = Date.now() - start;
|
||||
|
||||
expect(elapsed).toBeGreaterThanOrEqual(90);
|
||||
});
|
||||
|
||||
it('UTC weekday helpers preserve the supplied instant time and never mutate inputs', () => {
|
||||
const friday = new Date('2024-03-08T23:30:00.000Z');
|
||||
expect(utcDates.nextWeekday(friday).toISOString()).toBe('2024-03-11T23:30:00.000Z');
|
||||
expect(friday.toISOString()).toBe('2024-03-08T23:30:00.000Z');
|
||||
expect(utcDates.previousWeekday(new Date('2024-03-11T23:30:00Z')).toISOString()).toBe(
|
||||
'2024-03-08T23:30:00.000Z'
|
||||
);
|
||||
// Christmas is a weekday, not a promise that any particular exchange is open.
|
||||
expect(utcDates.isWeekday(new Date('2023-12-25T00:00:00Z'))).toBe(true);
|
||||
const detached = utcDates.nextWeekday;
|
||||
expect(detached(friday).getUTCDay()).toBe(1);
|
||||
});
|
||||
|
||||
it('strict UTC dates reject invalid inputs and impossible calendar dates', () => {
|
||||
expect(utcDates.parseDate('2024-02-29').toISOString()).toBe('2024-02-29T00:00:00.000Z');
|
||||
for (const value of ['2023-02-29', '2024-02-30', '2024-13-01', '2024-01-01T00:00:00Z', '']) {
|
||||
expect(() => utcDates.parseDate(value)).toThrow();
|
||||
}
|
||||
expect(() => utcDates.nextWeekday(new Date(NaN))).toThrow();
|
||||
expect(() => utcDates.formatDate(new Date(NaN))).toThrow();
|
||||
});
|
||||
|
||||
it('proxy credentials remain encoded and sleep remains asynchronous', async () => {
|
||||
expect(
|
||||
createProxyUrl({
|
||||
protocol: 'http',
|
||||
host: 'localhost',
|
||||
port: 8080,
|
||||
username: 'a@b',
|
||||
password: 'p:/?',
|
||||
})
|
||||
).toBe('http://a%40b:p%3A%2F%3F@localhost:8080');
|
||||
const wait = sleep(0);
|
||||
expect(wait).toBeInstanceOf(Promise);
|
||||
await wait;
|
||||
});
|
||||
});
|
||||
|
||||
describe('date utilities', () => {
|
||||
it('should check if date is trading day', () => {
|
||||
const monday = new Date('2023-12-25'); // Monday
|
||||
const saturday = new Date('2023-12-23'); // Saturday
|
||||
const sunday = new Date('2023-12-24'); // Sunday
|
||||
|
||||
expect(dateUtils.isTradingDay(monday)).toBe(true);
|
||||
expect(dateUtils.isTradingDay(saturday)).toBe(false);
|
||||
expect(dateUtils.isTradingDay(sunday)).toBe(false);
|
||||
});
|
||||
|
||||
it('should get next trading day', () => {
|
||||
const friday = new Date('2023-12-22'); // Friday
|
||||
const nextDay = dateUtils.getNextTradingDay(friday);
|
||||
|
||||
expect(nextDay.getUTCDay()).toBe(1); // Monday
|
||||
});
|
||||
|
||||
it('should get previous trading day', () => {
|
||||
const monday = new Date('2023-12-25'); // Monday
|
||||
const prevDay = dateUtils.getPreviousTradingDay(monday);
|
||||
|
||||
expect(prevDay.getUTCDay()).toBe(5); // Friday
|
||||
});
|
||||
|
||||
it('should format date as YYYY-MM-DD', () => {
|
||||
const date = new Date('2023-12-25T10:30:00Z');
|
||||
const formatted = dateUtils.formatDate(date);
|
||||
|
||||
expect(formatted).toBe('2023-12-25');
|
||||
});
|
||||
|
||||
it('should parse date from string', () => {
|
||||
const date = dateUtils.parseDate('2023-12-25');
|
||||
|
||||
expect(date.getUTCFullYear()).toBe(2023);
|
||||
expect(date.getUTCMonth()).toBe(11); // 0-based
|
||||
expect(date.getUTCDate()).toBe(25);
|
||||
});
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue