Skip to content

Commit

Permalink
fix: retry runtime file reads -- on slow machines the delay causes er…
Browse files Browse the repository at this point in the history
…rors (#1254)
  • Loading branch information
pavelgj authored Nov 12, 2024
1 parent 53f6aaa commit 8b37692
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
13 changes: 10 additions & 3 deletions genkit-tools/common/src/manager/manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
import * as apis from '../types/apis';
import { TraceData } from '../types/trace';
import { logger } from '../utils/logger';
import { checkServerHealth, findRuntimesDir } from '../utils/utils';
import { checkServerHealth, findRuntimesDir, retriable } from '../utils/utils';
import {
GenkitToolsError,
RuntimeEvent,
Expand Down Expand Up @@ -308,8 +308,15 @@ export class RuntimeManager {
*/
private async handleNewRuntime(filePath: string) {
try {
const content = await fs.readFile(filePath, 'utf-8');
const runtimeInfo = JSON.parse(content) as RuntimeInfo;
const { content, runtimeInfo } = await retriable(
async () => {
const content = await fs.readFile(filePath, 'utf-8');
const runtimeInfo = JSON.parse(content) as RuntimeInfo;
return { content, runtimeInfo };
},
{ maxRetries: 10, delayMs: 500 }
);

if (isValidRuntimeInfo(runtimeInfo)) {
const fileName = path.basename(filePath);
if (await checkServerHealth(runtimeInfo.reflectionServerUrl)) {
Expand Down
23 changes: 23 additions & 0 deletions genkit-tools/common/src/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,26 @@ export async function waitUntilUnresponsive(
}
return false;
}

export async function retriable<T>(
fn: () => Promise<T>,
opts: { maxRetries?: number; delayMs?: number }
): Promise<T> {
const maxRetries = opts.maxRetries ?? 3;
const delayMs = opts.delayMs ?? 0;

let attempt = 0;
while (true) {
try {
return await fn();
} catch (e) {
if (attempt >= maxRetries - 1) {
throw e;
}
if (delayMs > 0) {
await new Promise((r) => setTimeout(r, delayMs));
}
}
attempt++;
}
}

0 comments on commit 8b37692

Please sign in to comment.