Skip to content

Commit

Permalink
Merge pull request #3012 from OpenNeuroOrg/dataset-query-timeout
Browse files Browse the repository at this point in the history
Add 30 second timeout to dataset resolver
  • Loading branch information
nellh authored Mar 11, 2024
2 parents 3a000a1 + f71d40f commit e410cdd
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 1 deletion.
3 changes: 2 additions & 1 deletion packages/openneuro-server/src/graphql/resolvers/dataset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,12 @@ import { getDatasetWorker } from "../../libs/datalad-service"
import { getFileName } from "../../datalad/files"
import { onBrainlife } from "./brainlife"
import { derivatives } from "./derivatives"
import { promiseTimeout } from "../../utils/promiseTimeout"
import semver from "semver"

export const dataset = async (obj, { id }, { user, userInfo }) => {
await checkDatasetRead(id, user, userInfo)
return datalad.getDataset(id)
return promiseTimeout(datalad.getDataset(id), 30000)
}

export const datasets = (parent, args, { user, userInfo }) => {
Expand Down
6 changes: 6 additions & 0 deletions packages/openneuro-server/src/types/promiseTimeoutError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export class PromiseTimeoutError extends Error {
constructor(message: string) {
super(message)
this.name = "PromiseTimeoutError"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { promiseTimeout } from "../promiseTimeout"

describe("withTimeout", () => {
it("rejects with null when the promise exceeds timeout milliseconds", async () => {
const slowPromise = new Promise((resolve) =>
setTimeout(() => resolve("Slow Result"), 500)
)
expect(await promiseTimeout(slowPromise, 100)).toBeNull()
})
it("resolves when the promise returns before timeout", async () => {
const slowPromise = new Promise((resolve) =>
setTimeout(() => resolve("Fast Result"), 10)
)
expect(await promiseTimeout(slowPromise, 500)).toBe("Fast Result")
})
})
31 changes: 31 additions & 0 deletions packages/openneuro-server/src/utils/promiseTimeout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { PromiseTimeoutError } from "../types/promiseTimeoutError.ts"

/**
* Add a timeout to a promise and return null if timeout occurs before the promise resolves
* @param promise Promise to timeout
* @param timeout Timeout in milliseconds
*/
export async function promiseTimeout<T>(
promise: Promise<T>,
timeout: number,
): Promise<T | null> {
try {
const result = await Promise.race([
promise,
new Promise((_, reject) =>
setTimeout(
() => reject(new PromiseTimeoutError("Operation timed out")),
timeout,
)
),
])

return result
} catch (error) {
if (error instanceof PromiseTimeoutError) {
return null
} else {
throw error // Re-throw other errors
}
}
}

0 comments on commit e410cdd

Please sign in to comment.