File size: 6,199 Bytes
6111b2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import { batchSaveCostEntries } from "@/lib/db/domainState";

export interface BufferedCostEntry {
  apiKeyId: string;
  cost: number;
  timestamp: number;
}

interface SpendBatchWriterOptions {
  flushIntervalMs?: number;
  maxBufferSize?: number;
  persistEntries?: (entries: BufferedCostEntry[]) => Promise<void> | void;
  logger?: Pick<Console, "log" | "error">;
}

type FlushResult = {
  flushedEntries: number;
  uniqueKeys: number;
  requeued: boolean;
};

const DEFAULT_FLUSH_INTERVAL_MS = 60_000;
const DEFAULT_MAX_BUFFER_SIZE = 1_000;

function getFlushIntervalMs() {
  const parsed = Number.parseInt(process.env.OMNIROUTE_SPEND_FLUSH_INTERVAL_MS || "", 10);
  return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_FLUSH_INTERVAL_MS;
}

function getMaxBufferSize() {
  const parsed = Number.parseInt(process.env.OMNIROUTE_SPEND_MAX_BUFFER_SIZE || "", 10);
  return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_MAX_BUFFER_SIZE;
}

function normalizeEntry(entry: BufferedCostEntry): BufferedCostEntry | null {
  if (!entry?.apiKeyId || !Number.isFinite(entry.cost) || entry.cost <= 0) return null;
  return {
    apiKeyId: entry.apiKeyId,
    cost: entry.cost,
    timestamp: Number.isFinite(entry.timestamp) ? entry.timestamp : Date.now(),
  };
}

export class SpendBatchWriter {
  private buffer: BufferedCostEntry[] = [];
  private inFlightEntries: BufferedCostEntry[] = [];
  private discardedApiKeyIds = new Set<string>();
  private timer: NodeJS.Timeout | null = null;
  private started = false;
  private flushPromise: Promise<FlushResult> | null = null;
  private persistEntries: (entries: BufferedCostEntry[]) => Promise<void> | void;
  private logger: Pick<Console, "log" | "error">;
  private flushIntervalMs: number;
  private maxBufferSize: number;

  constructor(options: SpendBatchWriterOptions = {}) {
    this.persistEntries = options.persistEntries || batchSaveCostEntries;
    this.logger = options.logger || console;
    this.flushIntervalMs = options.flushIntervalMs ?? getFlushIntervalMs();
    this.maxBufferSize = options.maxBufferSize ?? getMaxBufferSize();
  }

  start() {
    if (this.started) return;
    this.started = true;
    this.timer = setInterval(() => {
      void this.flush();
    }, this.flushIntervalMs);
    this.timer.unref?.();
  }

  increment(apiKeyId: string, cost: number, timestamp = Date.now()) {
    const entry = normalizeEntry({ apiKeyId, cost, timestamp });
    if (!entry) return;

    this.start();
    this.discardedApiKeyIds.delete(entry.apiKeyId);
    this.buffer.push(entry);

    if (this.buffer.length >= this.maxBufferSize) {
      void this.flush();
    }
  }

  getBufferedEntries(

    apiKeyId: string,

    sinceTimestamp = 0,

    untilTimestamp = Number.POSITIVE_INFINITY

  ) {
    const matchesWindow = (entry: BufferedCostEntry) =>
      entry.apiKeyId === apiKeyId &&
      entry.timestamp >= sinceTimestamp &&
      entry.timestamp < untilTimestamp;

    return [...this.inFlightEntries, ...this.buffer].filter(matchesWindow);
  }

  getPendingCostTotal(

    apiKeyId: string,

    sinceTimestamp = 0,

    untilTimestamp = Number.POSITIVE_INFINITY

  ) {
    return this.getBufferedEntries(apiKeyId, sinceTimestamp, untilTimestamp).reduce(
      (sum, entry) => sum + entry.cost,
      0
    );
  }

  discardEntries(apiKeyId: string) {
    this.discardedApiKeyIds.add(apiKeyId);
    this.buffer = this.buffer.filter((entry) => entry.apiKeyId !== apiKeyId);
    this.inFlightEntries = this.inFlightEntries.filter((entry) => entry.apiKeyId !== apiKeyId);
  }

  async flush(): Promise<FlushResult> {
    if (this.flushPromise) {
      return this.flushPromise;
    }

    if (this.buffer.length === 0) {
      return { flushedEntries: 0, uniqueKeys: 0, requeued: false };
    }

    const entriesToFlush = [...this.buffer];
    this.buffer = [];
    this.inFlightEntries = entriesToFlush;

    this.flushPromise = (async () => {
      const entriesToPersist = entriesToFlush.filter(
        (entry) => !this.discardedApiKeyIds.has(entry.apiKeyId)
      );
      const uniqueKeys = new Set(entriesToPersist.map((entry) => entry.apiKeyId)).size;

      try {
        if (entriesToPersist.length > 0) {
          await this.persistEntries(entriesToPersist);
        }
        this.logger.log(
          `[SpendWriter] Flushed ${entriesToPersist.length} cost entr${

            entriesToPersist.length === 1 ? "y" : "ies"

          } across ${uniqueKeys} key(s)`
        );
        return {
          flushedEntries: entriesToPersist.length,
          uniqueKeys,
          requeued: false,
        };
      } catch (error) {
        this.buffer = [...entriesToPersist, ...this.buffer];
        const message = error instanceof Error ? error.message : String(error);
        this.logger.error(`[SpendWriter] Flush error: ${message}`);
        return {
          flushedEntries: 0,
          uniqueKeys,
          requeued: true,
        };
      } finally {
        this.inFlightEntries = [];
        this.flushPromise = null;
      }
    })();

    return this.flushPromise;
  }

  async stop() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
    this.started = false;
    return this.flush();
  }

  resetForTests() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
    this.started = false;
    this.buffer = [];
    this.inFlightEntries = [];
    this.discardedApiKeyIds.clear();
    this.flushPromise = null;
  }
}

export const spendBatchWriter = new SpendBatchWriter();

export function startSpendBatchWriter() {
  spendBatchWriter.start();
}

export async function flushSpendBatchWriter() {
  return spendBatchWriter.flush();
}

export async function stopSpendBatchWriter() {
  return spendBatchWriter.stop();
}

export function resetSpendBatchWriterForTests() {
  spendBatchWriter.resetForTests();
}

export function discardSpendBatchEntries(apiKeyId: string) {
  spendBatchWriter.discardEntries(apiKeyId);
}