test: Block get timeout.

This commit is contained in:
Hayden Young 2024-01-12 13:25:00 +00:00
parent 5282fb2d77
commit 8ab276026a
2 changed files with 58 additions and 3 deletions

View File

@ -6,6 +6,7 @@
*/
import { CID } from 'multiformats/cid'
import { base58btc } from 'multiformats/bases/base58'
import { TimeoutController } from 'timeout-abort-controller'
const DefaultTimeout = 30000 // 30 seconds
@ -26,7 +27,7 @@ const DefaultTimeout = 30000 // 30 seconds
const IPFSBlockStorage = async ({ ipfs, pin, timeout } = {}) => {
if (!ipfs) throw new Error('An instance of ipfs is required.')
timeout = timeout || DefaultTimeout
const { signal } = new TimeoutController(timeout || DefaultTimeout)
/**
* Puts data to an IPFS block.
@ -38,7 +39,7 @@ const IPFSBlockStorage = async ({ ipfs, pin, timeout } = {}) => {
*/
const put = async (hash, data) => {
const cid = CID.parse(hash, base58btc)
await ipfs.blockstore.put(cid, data, { signal: AbortSignal.timeout(timeout) })
await ipfs.blockstore.put(cid, data, { signal })
if (pin && !(await ipfs.pins.isPinned(cid))) {
await ipfs.pins.add(cid)
@ -57,7 +58,7 @@ const IPFSBlockStorage = async ({ ipfs, pin, timeout } = {}) => {
*/
const get = async (hash) => {
const cid = CID.parse(hash, base58btc)
const block = await ipfs.blockstore.get(cid, { signal: AbortSignal.timeout(timeout) })
const block = await ipfs.blockstore.get(cid, { signal })
if (block) {
return block
}

View File

@ -0,0 +1,54 @@
import { strictEqual, notStrictEqual } from 'assert'
import * as Block from 'multiformats/block'
import * as dagCbor from '@ipld/dag-cbor'
import { sha256 } from 'multiformats/hashes/sha2'
import { base58btc } from 'multiformats/bases/base58'
import createHelia from '../utils/create-helia.js'
import IPFSBlockStorage from '../../src/storage/ipfs-block.js'
describe('IPFSBlockStorage', function () {
const codec = dagCbor
const hasher = sha256
let ipfs, storage
beforeEach(async () => {
ipfs = await createHelia()
const pin = true
const timeout = 1000
storage = await IPFSBlockStorage({ ipfs, pin, timeout })
})
afterEach(async () => {
await ipfs.stop()
})
it('gets a block', async () => {
const expected = 'hello world'
const block = await Block.encode({ value: expected, codec, hasher })
const cid = block.cid.toString(base58btc)
await storage.put(cid, 'hello world')
const actual = await storage.get(cid)
strictEqual(actual, expected)
})
it('throws an error if a block does not exist', async () => {
const value = 'i don\'t exist'
const block = await Block.encode({ value, codec, hasher })
const cid = block.cid.toString(base58btc)
let err = null
try {
await storage.get(cid)
} catch (error) {
err = error
}
notStrictEqual(err, null)
strictEqual(err.message, 'All promises were rejected')
})
})