Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add optional abort signal to fetch json and merge with timeout #2068

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 76 additions & 3 deletions packages/cli/src/__tests__/ceramic-daemon.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,14 @@ import { Ceramic } from '@ceramicnetwork/core'
import { CeramicClient } from '@ceramicnetwork/http-client'
import tmp from 'tmp-promise'
import { CeramicDaemon } from '../ceramic-daemon.js'
import { AnchorStatus, fetchJson, Stream, StreamUtils, IpfsApi } from '@ceramicnetwork/common'
import {
AnchorStatus,
fetchJson,
Stream,
StreamUtils,
IpfsApi,
TimedAbortSignal,
} from '@ceramicnetwork/common'
import { TileDocumentHandler } from '@ceramicnetwork/stream-tile-handler'
import { TileDocument } from '@ceramicnetwork/stream-tile'
import { firstValueFrom } from 'rxjs'
Expand Down Expand Up @@ -366,7 +373,7 @@ describe('Ceramic interop: core <> http-client', () => {
expect(json).toEqual(content3)
})

it('times out if fetch is taking too long', async () => {
it('Aborts fetch if it is taking too long', async () => {
const content1 = { test: 123 }
const doc = await TileDocument.create(core, content1, null, { anchor: false })

Expand All @@ -384,11 +391,77 @@ describe('Ceramic interop: core <> http-client', () => {
fetchJson(`http://localhost:${daemon.port}/api/v0/streams/${doc.id}/content`, {
timeout: 1000,
})
).rejects.toThrow(`Http request timed out after 1000 ms`)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm frustrated by this loss of context. Looking at the node docs, it seems like AbortController.abort should be able to take an option string arg reason which could be used to provide a context string that the AbortSignal will include when it's aborted, and which can be used to give more meaningful error messages when an operation is cancelled. Sounds great! But in my testing I'm not actually able to get it to work - I keep getting an error Expected 0 arguments, but got 1.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update: I played around with different versions node using nvm. Node 16.14.0 does indeed have the reason arg, but Node 16.13.1 doesn't seem to have it. So I guess this is a very recent addition.

But even though I can select node 16.14.0 with NVM and see it working by running node manually, when I try to use it in Ceramic I still get a compilation error Expected 0 arguments, but got 1. Any ideas why that would be @ukstv? Does that mean my Ceramic build is still using Node 16.13.1 for some reason, even though node --version is showing 16.14.0?

Copy link
Contributor

@ukstv ukstv Mar 8, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@stbrody 1. Expected 0 arguments - if it is in TS, then Node.js types do not include reason parameter in the declarations. On my end vanilla Node.js (both 16.13 and 16.14) in REPL allow me to specify the reason.
2. I tend to believe, it does not matter if we pass a reason there to the AbortController. node-fetch does not respect reason anyway.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could do something like node-fetch/node-fetch#1462 (comment) though @stephhuynh18

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And, yes, it is a recent addition: https://nodejs.org/en/blog/release/v16.14.0/

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I used to do something like node-fetch/node-fetch#1462 (comment) but with this change we won't be able to tell if the request aborted because of a timeout or because the user called abort themselves.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I used to do something like node-fetch/node-fetch#1462 (comment) but with this change we won't be able to tell if the request aborted because of a timeout or because the user called abort themselves.

Not good.

Current code in the PR is indeed the most appropriate.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like there's a bunch of open issues on various repos to get this more fully supported. Agreed it's not worth doing anything more on this now, but we should revisit in the future once there's better support for abort reasons throughout the node ecosystem

).rejects.toThrow(/aborted/)

clearTimeout(id)
})

it('Aborts fetch through passed in AbortSignal', async () => {
const content1 = { test: 123 }
const doc = await TileDocument.create(core, content1, null, { anchor: false })

const loadStreamMock = jest.spyOn(core, 'loadStream')
let id = null
loadStreamMock.mockImplementation(() => {
return new Promise((resolve) => {
id = setTimeout(() => {
resolve(doc)
}, 5000)
})
})

const timedAbortSignal = new TimedAbortSignal(1000)

await expect(
fetchJson(`http://localhost:${daemon.port}/api/v0/streams/${doc.id}/content`, {
signal: timedAbortSignal.signal,
})
).rejects.toThrow(/aborted/)

timedAbortSignal.clear()
clearTimeout(id)
})

it('Aborts fetch if taking too long even if given an AbortSignal that did not get aborted', async () => {
const content1 = { test: 123 }
const doc = await TileDocument.create(core, content1, null, { anchor: false })

const loadStreamMock = jest.spyOn(core, 'loadStream')
let id = null
loadStreamMock.mockImplementation(() => {
return new Promise((resolve) => {
id = setTimeout(() => {
resolve(doc)
}, 4000)
})
})

const controller = new AbortController()

await expect(
fetchJson(`http://localhost:${daemon.port}/api/v0/streams/${doc.id}/content`, {
signal: controller.signal,
timeout: 1000,
})
).rejects.toThrow(/aborted/)

clearTimeout(id)
})

it('Aborts fetch if the AbortSignal given has already been aborted', async () => {
const content1 = { test: 123 }
const doc = await TileDocument.create(core, content1, null, { anchor: false })

const controller = new AbortController()
controller.abort()

await expect(
fetchJson(`http://localhost:${daemon.port}/api/v0/streams/${doc.id}/content`, {
signal: controller.signal,
})
).rejects.toThrow(/aborted/)
})

it('requestAnchor works via http api', async () => {
const content1 = { test: 123 }

Expand Down
1 change: 1 addition & 0 deletions packages/common/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export * from './utils/stream-utils.js'
export * from './utils/test-utils.js'
export * from './utils/accountid-utils.js'
export * from './utils/cid-utils.js'
export * from './utils/abort-signal-utils.js'
export * from './logger-provider.js'
export * from './loggers.js'
export * from './networks.js'
Expand Down
45 changes: 45 additions & 0 deletions packages/common/src/utils/abort-signal-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { timer, fromEvent, merge, Subscription } from 'rxjs'
import { first } from 'rxjs/operators'

export function mergeAbortSignals(signals: AbortSignal[]): AbortSignal {
const controller = new AbortController()

if (signals.length === 0) {
throw Error('Need abort signals to create a merged abort signal')
}

if (signals.some((signal) => signal.aborted)) {
controller.abort()
return controller.signal
}

merge(...signals.map((signal) => fromEvent(signal, 'abort')))
.pipe(first())
.subscribe(() => {
controller.abort()
})

return controller.signal
}
export class TimedAbortSignal {
private readonly _subscription: Subscription
readonly signal: AbortSignal

constructor(timeout: number) {
const controller = new AbortController()
this.signal = controller.signal

if (timeout <= 0) {
controller.abort()
return
}

this._subscription = timer(timeout).subscribe(() => {
controller.abort()
})
}

clear() {
this._subscription?.unsubscribe()
}
}
23 changes: 8 additions & 15 deletions packages/common/src/utils/http-utils.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import fetch from 'cross-fetch'
import { mergeAbortSignals, TimedAbortSignal } from './abort-signal-utils'

const DEFAULT_FETCH_TIMEOUT = 60 * 1000 * 3 // 3 minutes
interface FetchOpts {
body?: any
method?: string
headers?: any
timeout?: number
signal?: AbortSignal
}

export async function fetchJson(url: string, opts: FetchOpts = {}): Promise<any> {
Expand All @@ -17,22 +19,13 @@ export async function fetchJson(url: string, opts: FetchOpts = {}): Promise<any>
}

const timeoutLength = opts.timeout || DEFAULT_FETCH_TIMEOUT
const controller = new AbortController()
const timeout = setTimeout(() => {
controller.abort()
}, timeoutLength)
Object.assign(opts, {
signal: controller.signal,
})
const timedAbortSignal = new TimedAbortSignal(timeoutLength)

const res = await fetch(url, opts)
.catch((err) => {
if (err.name == 'AbortError') {
throw new Error(`Http request timed out after ${timeoutLength} ms`)
}
throw err
})
.finally(() => timeout && clearTimeout(timeout))
opts.signal = opts.signal
? mergeAbortSignals([opts.signal, timedAbortSignal.signal])
: timedAbortSignal.signal

const res = await fetch(url, opts).finally(() => timedAbortSignal.clear())

if (!res.ok) {
const text = await res.text()
Expand Down