-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathfilecoin-pinning-server.ts
More file actions
328 lines (291 loc) · 9.19 KB
/
filecoin-pinning-server.ts
File metadata and controls
328 lines (291 loc) · 9.19 KB
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
import fastify, { type FastifyInstance, type FastifyRequest } from 'fastify'
import { CID } from 'multiformats/cid'
import type { Logger } from 'pino'
import type { Config } from './core/synapse/index.js'
import { initializeSynapse, type PrivateKeyConfig } from './core/synapse/index.js'
import { FilecoinPinStore, type PinOptions } from './filecoin-pin-store.js'
import type { ServiceInfo } from './server.js'
declare module 'fastify' {
interface FastifyRequest {
user?: {
id: string
name: string
}
}
}
const DEFAULT_USER_INFO = {
id: 'default-user',
name: 'Default User',
}
export async function createFilecoinPinningServer(
config: Config,
logger: Logger,
serviceInfo: ServiceInfo
): Promise<{ server: FastifyInstance; pinStore: FilecoinPinStore }> {
// Set up Synapse service
if (!config.privateKey) {
throw new Error('PRIVATE_KEY environment variable is required to start the pinning server')
}
const synapseConfig: PrivateKeyConfig = {
privateKey: config.privateKey as `0x${string}`,
rpcUrl: config.rpcUrl,
}
const synapse = await initializeSynapse(synapseConfig, logger)
const filecoinPinStore = new FilecoinPinStore({
config,
logger,
synapse,
})
// Set up event handlers for monitoring
filecoinPinStore.on('pin:block:stored', (data) => {
logger.debug(
{
pinId: data.pinId,
userId: data.userId,
cid: data.cid.toString(),
size: data.size,
},
'Block stored for pin'
)
})
filecoinPinStore.on('pin:block:missing', (data) => {
logger.warn(
{
pinId: data.pinId,
userId: data.userId,
cid: data.cid.toString(),
},
'Block missing for pin'
)
})
filecoinPinStore.on('pin:car:completed', (data) => {
logger.info(
{
pinId: data.pinId,
userId: data.userId,
cid: data.cid.toString(),
blocksWritten: data.stats.blocksWritten,
totalSize: data.stats.totalSize,
missingBlocks: data.stats.missingBlocks.size,
carFilePath: data.carFilePath,
},
'CAR file completed for pin'
)
})
filecoinPinStore.on('pin:failed', (data) => {
logger.error(
{
pinId: data.pinId,
userId: data.userId,
cid: data.cid.toString(),
error: data.error,
},
'Pin operation failed'
)
})
// Create a custom Fastify server
const server = fastify({
logger: false, // We'll use our own logger
})
// Add root route for health check (no auth required)
server.get('/', async (_request, reply) => {
await reply.send({
service: serviceInfo.service,
version: serviceInfo.version,
status: 'ok',
})
})
// Add authentication hook
server.addHook('preHandler', async (request, reply) => {
// Skip auth for root health check
if (request.url === '/') {
return
}
// If no access token is configured, allow all requests
if (!config.accessToken) {
request.user = DEFAULT_USER_INFO
return
}
const authHeader = request.headers.authorization
if (authHeader?.startsWith('Bearer ') !== true) {
await reply.code(401).send({ error: 'Missing or invalid authorization header' })
return
}
const token = authHeader.slice(7).trim() // Remove 'Bearer ' prefix
if (token.length === 0) {
await reply.code(401).send({ error: 'Invalid access token' })
return
}
if (token !== config.accessToken) {
await reply.code(403).send({ error: 'Invalid access token' })
return
}
// Add user to request context
request.user = DEFAULT_USER_INFO
})
// Add our custom pin store to the Fastify context
server.decorate('pinStore', filecoinPinStore)
// Register custom routes that use our pin store
await server.register(async (fastify) => {
// Override the default routes with our custom implementations
await registerCustomPinRoutes(fastify, filecoinPinStore, logger)
})
await filecoinPinStore.start()
// Start listening
await server.listen({
port: config.port ?? 0, // Use random port for testing
host: config.host,
})
logger.info('Filecoin pinning service API server started')
return {
server,
pinStore: filecoinPinStore,
}
}
async function registerCustomPinRoutes(
fastify: FastifyInstance,
pinStore: FilecoinPinStore,
logger: Logger
): Promise<void> {
// POST /pins - Create a new pin
fastify.post(
'/pins',
async (
request: FastifyRequest<{
Body: { cid?: string; name?: string; origins?: string[]; meta?: Record<string, string> }
}>,
reply
) => {
try {
const { cid, name, origins, meta } = request.body
if (cid == null) {
await reply.code(400).send({ error: 'Missing required field: cid' })
return
}
// Parse the CID string to CID object
let cidObject: CID
try {
cidObject = CID.parse(cid)
} catch (_error) {
await reply.code(400).send({ error: `Invalid CID format: ${cid}` })
return
}
const pinOptions: PinOptions = {}
if (name != null) pinOptions.name = name
if (origins != null) pinOptions.origins = origins
if (meta != null) pinOptions.meta = meta
if (request.user == null) {
await reply.code(401).send({ error: 'Unauthorized' })
return
}
const result = await pinStore.pin(request.user, cidObject, pinOptions)
await reply.code(202).send({
requestid: result.id,
status: result.status,
created: new Date(result.created).toISOString(),
pin: result.pin,
delegates: [],
info: result.info,
})
} catch (error) {
logger.error({ error }, 'Failed to create pin')
await reply.code(500).send({ error: 'Internal server error' })
}
}
)
// GET /pins/:requestId - Get pin status
fastify.get('/pins/:requestId', async (request: FastifyRequest<{ Params: { requestId: string } }>, reply) => {
try {
if (request.user == null) {
await reply.code(401).send({ error: 'Unauthorized' })
return
}
const result = await pinStore.get(request.user, request.params.requestId)
if (result == null) {
await reply.code(404).send({ error: 'Pin not found' })
return
}
await reply.send({
requestid: result.id,
status: result.status,
created: new Date(result.created).toISOString(),
pin: result.pin,
delegates: [],
info: result.info,
})
} catch (error) {
logger.error({ error }, 'Failed to get pin status')
await reply.code(500).send({ error: 'Internal server error' })
}
})
// GET /pins - List pins
fastify.get(
'/pins',
async (
request: FastifyRequest<{ Querystring: { cid?: string; name?: string; status?: string; limit?: string } }>,
reply
) => {
try {
const { cid, name, status, limit } = request.query
const limitNum = limit != null ? parseInt(limit, 10) : undefined
const listQuery: Parameters<typeof pinStore.list>[1] = {}
if (cid != null) listQuery.cid = cid
if (name != null) listQuery.name = name
if (status != null) listQuery.status = status
if (limitNum != null && !Number.isNaN(limitNum)) listQuery.limit = limitNum
if (request.user == null) {
await reply.code(401).send({ error: 'Unauthorized' })
return
}
const result = await pinStore.list(request.user, listQuery)
const results = result.results.map((pin) => ({
requestid: pin.id,
status: pin.status,
created: new Date(pin.created).toISOString(),
pin: pin.pin,
delegates: [],
info: pin.info,
}))
await reply.send({
count: result.count,
results,
})
} catch (error) {
logger.error({ error }, 'Failed to list pins')
await reply.code(500).send({ error: 'Internal server error' })
}
}
)
// POST /pins/:requestId - Update pin (not commonly used)
fastify.post('/pins/:requestId', async (request: any, reply: any) => {
try {
const { name, origins, meta } = request.body
const result = await pinStore.update(request.user, request.params.requestId, { name, origins, meta })
if (result == null) {
await reply.code(404).send({ error: 'Pin not found' })
return
}
await reply.send({
requestid: result.id,
status: result.status,
created: new Date(result.created).toISOString(),
pin: result.pin,
delegates: [],
info: result.info,
})
} catch (error) {
logger.error({ error }, 'Failed to update pin')
await reply.code(500).send({ error: 'Internal server error' })
}
})
// DELETE /pins/:requestId - Cancel/delete pin and clean up CAR file
fastify.delete('/pins/:requestId', async (request: any, reply: any) => {
try {
await pinStore.cancel(request.user, request.params.requestId)
await reply.code(202).send()
} catch (error) {
logger.error({ error }, 'Failed to cancel pin')
await reply.code(500).send({ error: 'Internal server error' })
}
})
}