Spaces:
Runtime error
Runtime error
File size: 8,746 Bytes
cd8bd0a | 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 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 | import { getDbInstance, rowToCamel, objToSnake } from "./core";
import { deleteFile } from "./files";
import { v4 as uuidv4 } from "uuid";
function parseBatchRow(row: any): BatchRecord {
const camel = rowToCamel(row) as any;
if (camel.metadata && typeof camel.metadata === "string") {
try {
camel.metadata = JSON.parse(camel.metadata);
} catch {
camel.metadata = null;
}
}
if (camel.errors && typeof camel.errors === "string") {
try {
camel.errors = JSON.parse(camel.errors);
} catch {
camel.errors = null;
}
}
if (camel.usage && typeof camel.usage === "string") {
try {
camel.usage = JSON.parse(camel.usage);
} catch {
camel.usage = null;
}
}
// Normalize numeric date fields to ensure they are valid numbers
const coerceNum = (v: any): number | null => {
if (typeof v === "number" && Number.isFinite(v)) return v;
if (v == null) return null;
const n = Number(v);
return Number.isFinite(n) ? n : null;
};
camel.createdAt = coerceNum(camel.createdAt) ?? 0;
camel.inProgressAt = coerceNum(camel.inProgressAt);
camel.expiresAt = coerceNum(camel.expiresAt);
camel.finalizingAt = coerceNum(camel.finalizingAt);
camel.completedAt = coerceNum(camel.completedAt);
camel.failedAt = coerceNum(camel.failedAt);
camel.expiredAt = coerceNum(camel.expiredAt);
camel.cancellingAt = coerceNum(camel.cancellingAt);
camel.cancelledAt = coerceNum(camel.cancelledAt);
return camel as BatchRecord;
}
export interface BatchRecord {
id: string;
endpoint: string;
completionWindow: string;
status:
| "validating"
| "failed"
| "in_progress"
| "finalizing"
| "completed"
| "expired"
| "cancelling"
| "cancelled";
inputFileId: string;
outputFileId?: string | null;
errorFileId?: string | null;
createdAt: number;
inProgressAt?: number | null;
expiresAt?: number | null;
finalizingAt?: number | null;
completedAt?: number | null;
failedAt?: number | null;
expiredAt?: number | null;
cancellingAt?: number | null;
cancelledAt?: number | null;
requestCountsTotal: number;
requestCountsCompleted: number;
requestCountsFailed: number;
metadata?: Record<string, any> | null;
apiKeyId?: string | null;
errors?: any | null;
model?: string | null;
usage?: any | null;
outputExpiresAfterSeconds?: number | null;
outputExpiresAfterAnchor?: string | null;
}
export function createBatch(
batch: Omit<
BatchRecord,
| "id"
| "createdAt"
| "requestCountsTotal"
| "requestCountsCompleted"
| "requestCountsFailed"
| "status"
> & { status?: BatchRecord["status"] }
): BatchRecord {
const db = getDbInstance();
const id = "batch_" + uuidv4().replaceAll("-", "").substring(0, 24);
const createdAt = Math.floor(Date.now() / 1000);
const record: BatchRecord = {
...batch,
id,
createdAt,
status: batch.status || "validating",
requestCountsTotal: 0,
requestCountsCompleted: 0,
requestCountsFailed: 0,
errors: batch.errors || null,
model: batch.model || null,
usage: batch.usage || null,
outputExpiresAfterSeconds: batch.outputExpiresAfterSeconds || null,
outputExpiresAfterAnchor: batch.outputExpiresAfterAnchor || null,
};
const snakeRecord = objToSnake({
...record,
metadata: record.metadata ? JSON.stringify(record.metadata) : null,
errors: record.errors ? JSON.stringify(record.errors) : null,
usage: record.usage ? JSON.stringify(record.usage) : null,
}) as any;
const keys = Object.keys(snakeRecord);
const values = Object.values(snakeRecord);
const placeholders = keys.map(() => "?").join(", ");
db.prepare(`INSERT INTO batches (${keys.join(", ")}) VALUES (${placeholders})`).run(...values);
return record;
}
export function getBatch(id: string): BatchRecord | null {
const db = getDbInstance();
const row = db.prepare("SELECT * FROM batches WHERE id = ?").get(id);
if (!row) return null;
return parseBatchRow(row);
}
export function updateBatch(id: string, updates: Partial<BatchRecord>): boolean {
const db = getDbInstance();
const snakeUpdates = objToSnake(updates) as any;
if (snakeUpdates.metadata && typeof snakeUpdates.metadata !== "string") {
snakeUpdates.metadata = JSON.stringify(snakeUpdates.metadata);
}
if (snakeUpdates.errors && typeof snakeUpdates.errors !== "string") {
snakeUpdates.errors = JSON.stringify(snakeUpdates.errors);
}
if (snakeUpdates.usage && typeof snakeUpdates.usage !== "string") {
snakeUpdates.usage = JSON.stringify(snakeUpdates.usage);
}
const keys = Object.keys(snakeUpdates);
if (keys.length === 0) return false;
const setClause = keys.map((k) => `${k} = ?`).join(", ");
const values = Object.values(snakeUpdates);
const result = db.prepare(`UPDATE batches SET ${setClause} WHERE id = ?`).run(...values, id);
return result.changes > 0;
}
export function listBatches(apiKeyId?: string, limit: number = 20, after?: string): BatchRecord[] {
const db = getDbInstance();
const afterBatch = after ? getBatch(after) : null;
let rows: any[];
if (apiKeyId) {
if (afterBatch) {
rows = db
.prepare(
"SELECT * FROM batches WHERE api_key_id = ? AND (created_at < ? OR (created_at = ? AND id < ?)) ORDER BY created_at DESC, id DESC LIMIT ?"
)
.all(apiKeyId, afterBatch.createdAt, afterBatch.createdAt, after, limit);
} else {
rows = db
.prepare(
"SELECT * FROM batches WHERE api_key_id = ? ORDER BY created_at DESC, id DESC LIMIT ?"
)
.all(apiKeyId, limit);
}
} else if (afterBatch) {
rows = db
.prepare(
"SELECT * FROM batches WHERE (created_at < ? OR (created_at = ? AND id < ?)) ORDER BY created_at DESC, id DESC LIMIT ?"
)
.all(afterBatch.createdAt, afterBatch.createdAt, after, limit);
} else {
rows = db.prepare("SELECT * FROM batches ORDER BY created_at DESC, id DESC LIMIT ?").all(limit);
}
return rows.map((row) => parseBatchRow(row));
}
export function countBatches(apiKeyId?: string): number {
const db = getDbInstance();
if (apiKeyId) {
const row = db
.prepare("SELECT COUNT(*) as c FROM batches WHERE api_key_id = ?")
.get(apiKeyId) as { c: number } | undefined;
return row ? Number(row.c) : 0;
} else {
const row = db.prepare("SELECT COUNT(*) as c FROM batches").get() as { c: number } | undefined;
return row ? Number(row.c) : 0;
}
}
export function getPendingBatches(): BatchRecord[] {
const db = getDbInstance();
const rows = db
.prepare(
"SELECT * FROM batches WHERE status IN ('validating', 'in_progress', 'finalizing', 'cancelling')"
)
.all();
return rows.map((row) => parseBatchRow(row));
}
export function getTerminalBatches(): BatchRecord[] {
const db = getDbInstance();
const rows = db
.prepare(
"SELECT * FROM batches WHERE status IN ('completed', 'failed', 'cancelled', 'expired') ORDER BY created_at ASC"
)
.all();
return rows.map((row) => parseBatchRow(row));
}
export function deleteBatch(id: string): boolean {
const db = getDbInstance();
const batch = getBatch(id);
if (!batch) return false;
// Soft-delete associated files (input, output, error)
if (batch.inputFileId) {
try {
deleteFile(batch.inputFileId);
} catch {
/* ignore */
}
}
if (batch.outputFileId) {
try {
deleteFile(batch.outputFileId);
} catch {
/* ignore */
}
}
if (batch.errorFileId) {
try {
deleteFile(batch.errorFileId);
} catch {
/* ignore */
}
}
const result = db.prepare("DELETE FROM batches WHERE id = ?").run(id);
return result.changes > 0;
}
export function deleteCompletedBatches(): { deletedBatches: number; deletedFiles: number } {
const db = getDbInstance();
// Collect unique file IDs from all completed batches
const rows = db
.prepare(
"SELECT input_file_id, output_file_id, error_file_id FROM batches WHERE status = 'completed'"
)
.all() as Array<{
input_file_id: string | null;
output_file_id: string | null;
error_file_id: string | null;
}>;
const fileIds = new Set<string>();
for (const row of rows) {
if (row.input_file_id) fileIds.add(row.input_file_id);
if (row.output_file_id) fileIds.add(row.output_file_id);
if (row.error_file_id) fileIds.add(row.error_file_id);
}
let deletedFiles = 0;
for (const fid of fileIds) {
try {
if (deleteFile(fid)) deletedFiles++;
} catch {
/* ignore */
}
}
const result = db.prepare("DELETE FROM batches WHERE status = 'completed'").run();
return { deletedBatches: result.changes, deletedFiles };
}
|