refactor: switch SDK methods to asynchronous
Migrate SDK interactions to asynchronous calls, relax admin setup email constraints, and add event retrieval functionality.
This commit is contained in:
1 parent
81c5e4e2fd
commit
bb938c33c0
36 files changed
+1679
-754
No files matched your search
+110
-80
@@ -3,93 +3,116 @@ import { CSVStorageManager, DataEvent } from '../Storage/csvStorage';
|
||||
export type EventSubscriber = (event: DataEvent) => void;
|
||||
export type FlushCallback = (count: number, files: string[]) => void;
|
||||
|
||||
interface BufferGlobalState {
|
||||
buffer: DataEvent[];
|
||||
recentEvents: DataEvent[];
|
||||
batchFlushThreshold: number;
|
||||
batchFlushIntervalMs: number;
|
||||
flushTimer: NodeJS.Timeout | null;
|
||||
subscribers: Set<EventSubscriber>;
|
||||
flushListeners: Set<FlushCallback>;
|
||||
totalIngested: number;
|
||||
totalFlushed: number;
|
||||
isFlushing: boolean;
|
||||
}
|
||||
|
||||
type BufferGlobals = typeof globalThis & {
|
||||
__dataStackBufferState?: BufferGlobalState;
|
||||
};
|
||||
|
||||
const globals = globalThis as BufferGlobals;
|
||||
|
||||
function getState(): BufferGlobalState {
|
||||
if (!globals.__dataStackBufferState) {
|
||||
globals.__dataStackBufferState = {
|
||||
buffer: [],
|
||||
recentEvents: [],
|
||||
batchFlushThreshold: 500,
|
||||
batchFlushIntervalMs: 2000,
|
||||
flushTimer: null,
|
||||
subscribers: new Set(),
|
||||
flushListeners: new Set(),
|
||||
totalIngested: 0,
|
||||
totalFlushed: 0,
|
||||
isFlushing: false,
|
||||
};
|
||||
}
|
||||
return globals.__dataStackBufferState;
|
||||
}
|
||||
|
||||
export class DataBufferEngine {
|
||||
private static buffer: DataEvent[] = [];
|
||||
private static recentEvents: DataEvent[] = [];
|
||||
private static maxRecentEvents = 200;
|
||||
|
||||
// Thresholds
|
||||
public static batchFlushThreshold = 500; // rows
|
||||
public static batchFlushIntervalMs = 2000; // 2 seconds
|
||||
public static get batchFlushThreshold(): number {
|
||||
return getState().batchFlushThreshold;
|
||||
}
|
||||
|
||||
private static flushTimer: NodeJS.Timeout | null = null;
|
||||
private static subscribers: Set<EventSubscriber> = new Set();
|
||||
private static flushListeners: Set<FlushCallback> = new Set();
|
||||
public static set batchFlushThreshold(value: number) {
|
||||
getState().batchFlushThreshold = Math.max(1, Number(value) || 500);
|
||||
}
|
||||
|
||||
private static totalIngested = 5;
|
||||
private static totalFlushed = 1420;
|
||||
private static isFlushing = false;
|
||||
public static get batchFlushIntervalMs(): number {
|
||||
return getState().batchFlushIntervalMs;
|
||||
}
|
||||
|
||||
static {
|
||||
const now = Date.now();
|
||||
DataBufferEngine.recentEvents = [
|
||||
{
|
||||
clientId: 'py_telemetry_agent_01',
|
||||
eventId: 'evt_10482_a8',
|
||||
timestamp: new Date(now - 8000).toISOString(),
|
||||
payload: JSON.stringify({ action: 'crawler_metric', pages_scraped: 38, latency_ms: 24, status: 200 }),
|
||||
},
|
||||
{
|
||||
clientId: 'py_scraper_prod_02',
|
||||
eventId: 'evt_10481_f2',
|
||||
timestamp: new Date(now - 22000).toISOString(),
|
||||
payload: JSON.stringify({ spider: 'market_catalog', items: 114, parse_time_s: 1.28, errors: 0 }),
|
||||
},
|
||||
{
|
||||
clientId: 'iot_fleet_east_03',
|
||||
eventId: 'evt_10480_c1',
|
||||
timestamp: new Date(now - 45000).toISOString(),
|
||||
payload: JSON.stringify({ sensor_node: 'gw_alpha_09', temp_c: 24.3, humidity_pct: 58.1, battery_v: 3.32 }),
|
||||
},
|
||||
{
|
||||
clientId: 'py_telemetry_agent_01',
|
||||
eventId: 'evt_10479_d9',
|
||||
timestamp: new Date(now - 78000).toISOString(),
|
||||
payload: JSON.stringify({ action: 'heartbeat', memory_usage_mb: 284, cpu_load_pct: 12.8 }),
|
||||
},
|
||||
{
|
||||
clientId: 'py_scraper_prod_02',
|
||||
eventId: 'evt_10478_e4',
|
||||
timestamp: new Date(now - 110000).toISOString(),
|
||||
payload: JSON.stringify({ action: 'batch_sync', batch_size: 50, duration_ms: 82 }),
|
||||
},
|
||||
];
|
||||
public static set batchFlushIntervalMs(value: number) {
|
||||
this.setFlushInterval(value);
|
||||
}
|
||||
|
||||
public static init() {
|
||||
if (!this.flushTimer) {
|
||||
this.flushTimer = setInterval(() => {
|
||||
this.flush();
|
||||
}, this.batchFlushIntervalMs);
|
||||
const state = getState();
|
||||
if (!state.flushTimer) {
|
||||
state.flushTimer = setInterval(() => {
|
||||
void this.flush();
|
||||
}, state.batchFlushIntervalMs);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates flush interval and immediately restarts the active interval timer.
|
||||
*/
|
||||
public static setFlushInterval(intervalMs: number) {
|
||||
const state = getState();
|
||||
const nextInterval = Math.max(100, Number(intervalMs) || 2000);
|
||||
state.batchFlushIntervalMs = nextInterval;
|
||||
|
||||
if (state.flushTimer) {
|
||||
clearInterval(state.flushTimer);
|
||||
state.flushTimer = null;
|
||||
}
|
||||
|
||||
state.flushTimer = setInterval(() => {
|
||||
void this.flush();
|
||||
}, state.batchFlushIntervalMs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push incoming event to in-memory buffer.
|
||||
* If buffer hits threshold (e.g. 500 rows), triggers immediate batch flush.
|
||||
*/
|
||||
public static push(event: DataEvent): void {
|
||||
this.buffer.push(event);
|
||||
this.totalIngested += 1;
|
||||
const state = getState();
|
||||
state.buffer.push(event);
|
||||
state.totalIngested += 1;
|
||||
|
||||
// Cache in recent events for live dashboard viewer
|
||||
this.recentEvents.unshift(event);
|
||||
if (this.recentEvents.length > this.maxRecentEvents) {
|
||||
this.recentEvents.pop();
|
||||
state.recentEvents.unshift(event);
|
||||
if (state.recentEvents.length > this.maxRecentEvents) {
|
||||
state.recentEvents.pop();
|
||||
}
|
||||
|
||||
// Notify live subscribers
|
||||
for (const sub of this.subscribers) {
|
||||
for (const sub of state.subscribers) {
|
||||
try {
|
||||
sub(event);
|
||||
} catch {
|
||||
// Ignore subscriber err
|
||||
// Ignore subscriber error
|
||||
}
|
||||
}
|
||||
|
||||
// Check if buffer threshold reached
|
||||
if (this.buffer.length >= this.batchFlushThreshold) {
|
||||
this.flush();
|
||||
if (state.buffer.length >= state.batchFlushThreshold) {
|
||||
void this.flush();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,19 +120,20 @@ export class DataBufferEngine {
|
||||
* Flushes current buffer to CSV files via CSVStorageManager
|
||||
*/
|
||||
public static async flush(): Promise<{ count: number; files: string[] }> {
|
||||
if (this.buffer.length === 0 || this.isFlushing) {
|
||||
const state = getState();
|
||||
if (state.buffer.length === 0 || state.isFlushing) {
|
||||
return { count: 0, files: [] };
|
||||
}
|
||||
|
||||
this.isFlushing = true;
|
||||
const batchToFlush = [...this.buffer];
|
||||
this.buffer = [];
|
||||
state.isFlushing = true;
|
||||
const batchToFlush = [...state.buffer];
|
||||
state.buffer = [];
|
||||
|
||||
try {
|
||||
const result = await CSVStorageManager.appendBatch(batchToFlush);
|
||||
this.totalFlushed += result.written;
|
||||
state.totalFlushed += result.written;
|
||||
|
||||
for (const listener of this.flushListeners) {
|
||||
for (const listener of state.flushListeners) {
|
||||
try {
|
||||
listener(result.written, result.filesUpdated);
|
||||
} catch {
|
||||
@@ -120,10 +144,10 @@ export class DataBufferEngine {
|
||||
return { count: result.written, files: result.filesUpdated };
|
||||
} catch (err) {
|
||||
// On failure, re-queue to buffer front for retry
|
||||
this.buffer.unshift(...batchToFlush);
|
||||
state.buffer.unshift(...batchToFlush);
|
||||
throw err;
|
||||
} finally {
|
||||
this.isFlushing = false;
|
||||
state.isFlushing = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,36 +155,42 @@ export class DataBufferEngine {
|
||||
* Subscribe to real-time events (for UI monitoring)
|
||||
*/
|
||||
public static subscribe(subscriber: EventSubscriber): () => void {
|
||||
this.subscribers.add(subscriber);
|
||||
const state = getState();
|
||||
state.subscribers.add(subscriber);
|
||||
return () => {
|
||||
this.subscribers.delete(subscriber);
|
||||
state.subscribers.delete(subscriber);
|
||||
};
|
||||
}
|
||||
|
||||
public static onFlush(callback: FlushCallback): () => void {
|
||||
this.flushListeners.add(callback);
|
||||
const state = getState();
|
||||
state.flushListeners.add(callback);
|
||||
return () => {
|
||||
this.flushListeners.delete(callback);
|
||||
state.flushListeners.delete(callback);
|
||||
};
|
||||
}
|
||||
|
||||
public static getRecentEvents(limit = 50, filterClientId?: string): DataEvent[] {
|
||||
const state = getState();
|
||||
if (filterClientId && filterClientId !== 'all') {
|
||||
return this.recentEvents.filter((e) => e.clientId === filterClientId).slice(0, limit);
|
||||
return state.recentEvents
|
||||
.filter((e) => e.clientId === filterClientId)
|
||||
.slice(0, limit);
|
||||
}
|
||||
return this.recentEvents.slice(0, limit);
|
||||
return state.recentEvents.slice(0, limit);
|
||||
}
|
||||
|
||||
public static getBufferStats() {
|
||||
const state = getState();
|
||||
return {
|
||||
currentBufferSize: this.buffer.length,
|
||||
batchFlushThreshold: this.batchFlushThreshold,
|
||||
batchFlushIntervalMs: this.batchFlushIntervalMs,
|
||||
totalIngested: this.totalIngested,
|
||||
totalFlushed: this.totalFlushed,
|
||||
recentEventsCached: this.recentEvents.length,
|
||||
activeSubscribers: this.subscribers.size,
|
||||
isFlushing: this.isFlushing,
|
||||
currentBufferSize: state.buffer.length,
|
||||
batchFlushThreshold: state.batchFlushThreshold,
|
||||
batchFlushIntervalMs: state.batchFlushIntervalMs,
|
||||
totalIngested: state.totalIngested,
|
||||
totalFlushed: state.totalFlushed,
|
||||
recentEventsCached: state.recentEvents.length,
|
||||
activeSubscribers: state.subscribers.size,
|
||||
isFlushing: state.isFlushing,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user