/
ipfs.js
158 lines (146 loc) · 4.8 KB
/
ipfs.js
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
import { compose } from 'node:stream'
import { CID } from 'multiformats/cid'
import { Multiaddr } from 'multiaddr'
import debounce from 'debounce'
import fetch from 'node-fetch'
import { logger } from './logger.js'
import { STATE_DOWNLOADING } from './downloadStatusManager.js'
export const ERROR_TIMEOUT = 'TIMEOUT'
/**
* Start the fetch of a car
*
* @param string cid - The CID requested
* @param string ipfsApiUrl - The IPFS server url
* @param object downloadError - The error object, is filled in if an error occurs
* @param int timeoutMs - The timeout for each block fetch in milliseconds.
* The Download is set to `failed` if the IPFS server
* fetch action do not respond while is downloading the blocks.
* @param {DownloadStatusManager} downloadStatusManager
* @returns {Promise<*>}
*/
export async function fetchCar (cid, ipfsApiUrl, downloadError, timeoutMs = 30000, downloadStatusManager) {
if (!isCID(cid)) {
throw new Error({ message: `Invalid CID: ${cid}` })
}
const url = new URL(`/api/v0/dag/export?arg=${cid}`, ipfsApiUrl)
const ctl = new AbortController()
const startCountdown = debounce(() => {
downloadError.code = ERROR_TIMEOUT
ctl.abort()
}, timeoutMs)
startCountdown()
const res = await fetch(url, { method: 'POST', signal: ctl.signal })
if (!res.ok) {
throw new Error(`${res.status} ${res.statusText} ${url}`)
}
let downloadSize = 0
async function * restartCountdown (source) {
// startCountdown.clear()
// throw new Error('There was an error!!')
for await (const chunk of source) {
downloadSize += chunk.length
downloadStatusManager.setStatus(cid, STATE_DOWNLOADING, downloadSize)
startCountdown()
yield chunk
}
startCountdown.clear()
}
return compose(res.body, restartCountdown)
}
/**
* Add origins to the IPFS server
* @param {string[]} origins
* @param {string} ipfsApiUrl
* @param {number} timeoutMs
* @returns {Promise<void>}
*/
export async function connectTo (origins = [], ipfsApiUrl, timeoutMs = 10000) {
for (const addr of origins.filter(isMultiaddr)) {
const url = new URL(`/api/v0/swarm/connect?arg=${addr}`, ipfsApiUrl)
const signal = AbortSignal.timeout(timeoutMs)
const res = await fetch(url, { method: 'POST', signal })
if (!res.ok) {
logger.error({ addr, status: res.status, statusText: res.statusText }, 'Error connecting')
}
}
}
/**
* Remove origins from IPFS server
* @param {string[]} origins
* @param {string} ipfsApiUrl
* @param {number} timeoutMs
* @returns {Promise<void>}
*/
export async function disconnect (origins = [], ipfsApiUrl, timeoutMs = 10000) {
for (const addr of origins.filter(isMultiaddr)) {
const url = new URL(`/api/v0/swarm/disconnect?arg=${addr}`, ipfsApiUrl)
const signal = AbortSignal.timeout(timeoutMs)
const res = await fetch(url, { method: 'POST', signal })
if (!res.ok) {
logger.error({ addr, status: res.status, statusText: res.statusText }, 'Error disconnecting')
}
}
}
/**
* Run the GC on IPFS server
*
* @param {string} ipfsApiUrl
* @param {number} timeoutMs
* @returns {Promise<void>}
*/
export async function waitForGC (ipfsApiUrl, timeoutMs = 60000) {
const url = new URL('/api/v0/repo/gc?silent=true', ipfsApiUrl)
const signal = AbortSignal.timeout(timeoutMs)
const res = await fetch(url, { method: 'POST', signal })
if (!res.ok) {
logger.error({ url, status: res.status, statusText: res.statusText }, 'Error GC')
}
await res.text()
}
/**
* Verify if the value is a valid multiaddress
* @param input
* @returns {boolean}
*/
export function isMultiaddr (input) {
if (!input) return false
try {
new Multiaddr(input) // eslint-disable-line no-new
return true
} catch (e) {
return false
}
}
/**
* Verify if the value is a CID
*
* @param {string} cid
* @returns {boolean}
*/
export function isCID (cid) {
return Boolean(CID.parse(cid))
}
/**
* Test the connection with IPFS server
* @param {string} ipfsApiUrl
* @param {number} timeoutMs
* @returns {Promise<void>}
*/
export async function testIpfsApi (ipfsApiUrl, timeoutMs = 10000) {
const url = new URL('/api/v0/id', ipfsApiUrl)
const signal = AbortSignal.timeout(timeoutMs)
try {
const res = await fetch(url, { method: 'POST', signal })
if (!res.ok) {
if (res.status === 404) {
throw new Error('IPFS API returned 404. IPFS_API_URL must be the RPC API port (:5001) rather than the ipfsApiUrl port (:8080)')
}
throw new Error(`IPFS API test failed. POST ${url} returned ${res.status} ${res.statusText}`)
}
const { AgentVersion, ID } = await res.json()
logger.info({ agentVersion: AgentVersion, peerId: ID }, 'Connected')
} catch (err) {
logger.error({ err }, 'Test ipfs fail')
throw new Error('IPFS API test failed.', { cause: err })
}
}