-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.ts
176 lines (155 loc) · 5.16 KB
/
index.ts
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
import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox'
import fastify, {
FastifyBaseLogger,
RawReplyDefaultExpression,
RawRequestDefaultExpression,
RawServerDefault,
FastifyInstance
} from 'fastify'
import multipart from '@fastify/multipart'
import swagger from '@fastify/swagger'
import swagger_ui from '@fastify/swagger-ui'
import metrics from 'fastify-metrics'
import path from 'node:path'
import envPaths from 'env-paths'
import { Level } from 'level'
import { MemoryLevel } from 'memory-level'
import { siteRoutes } from './sites.js'
import { adminRoutes } from './admin.js'
import { publisherRoutes } from './publisher.js'
import Store, { StoreI } from '../config/index.js'
import { registerAuth } from '../authorization/cfg.js'
import { authRoutes } from './auth.js'
import { ServerI } from '../index.js'
import { ConcreteProtocolManager } from '../protocols/index.js'
import { initDnsServer } from '../dns/index.js'
import cors from '@fastify/cors'
const paths = envPaths('distributed-press')
export type FastifyTypebox = FastifyInstance<
RawServerDefault,
RawRequestDefaultExpression<RawServerDefault>,
RawReplyDefaultExpression<RawServerDefault>,
FastifyBaseLogger,
TypeBoxTypeProvider
>
export type APIConfig = Partial<{
useLogging: boolean
useSwagger: boolean
usePrometheus: boolean
useMemoryBackedDB: boolean
useSigIntHandler: boolean
useWebringDirectoryListing: boolean
}> & ServerI
async function apiBuilder (cfg: APIConfig): Promise<FastifyTypebox> {
const basePath = cfg.storage ?? paths.data
const cfgStoragePath = path.join(basePath, 'cfg')
const db = cfg.useMemoryBackedDB === true
? new MemoryLevel({ valueEncoding: 'json' })
: new Level(cfgStoragePath, { valueEncoding: 'json' })
const protocolStoragePath = path.join(basePath, 'protocols')
const protocols = new ConcreteProtocolManager({
ipfs: {
path: path.join(protocolStoragePath, 'ipfs'),
provider: cfg.ipfsProvider
},
hyper: {
path: path.join(protocolStoragePath, 'hyper')
},
http: {
path: path.join(protocolStoragePath, 'http')
}
})
const server = fastify({ logger: cfg.useLogging }).withTypeProvider<TypeBoxTypeProvider>()
server.log.info('Initializing protocols')
await protocols.load()
const store = new Store(cfg, db, protocols)
server.log.info('Initializing DNS server')
const dns = await initDnsServer(cfg.dnsport, store.sites, server.log, cfg.domain)
server.log.info('Done')
await registerAuth(cfg, server, store)
await server.register(multipart)
// handle cleanup on shutdown
server.addHook('onClose', async server => {
server.log.info('Begin shutdown, unloading protocols...')
await dns.close()
await protocols.unload()
.then(() => {
server.log.info('Done')
})
.catch(err => {
server.log.fatal(err)
})
})
// catch SIGINTs
if (cfg.useSigIntHandler === true) {
process.on('SIGINT', () => {
server.log.warn('Caught SIGINT')
server.close(() => {
process.exit()
})
})
}
server.get('/healthz', () => {
return 'ok\n'
})
await server.register(v1Routes(cfg, store), { prefix: '/v1' })
await server.ready()
// pre-sync all sites
const allSites = await store.sites.keys()
Promise.all(allSites.map(async (siteId) => {
server.log.info(`Presyncing site: ${siteId}`)
const fp = store.fs.getPath(siteId)
await store.sites.sync(siteId, fp, { logger: server.log })
})).catch((e) => {
server.log.error(e)
})
return server
}
const v1Routes = (cfg: APIConfig, store: StoreI) => async (server: FastifyTypebox): Promise<void> => {
if (cfg.usePrometheus ?? false) {
await server.register(metrics, { endpoint: '/metrics' })
}
if (cfg.useSwagger ?? false) {
await server.register(swagger, {
openapi: {
info: {
title: 'Distributed Press API',
description: 'Documentation on how to use the Distributed Press API to publish your website content and the Distributed Press API for your project',
version: '1.0.0'
},
tags: [
{ name: 'site', description: 'Managing site deployments' },
{ name: 'publisher', description: 'Publisher account management. Publishers can manage site deployments' },
{ name: 'admin', description: 'Admin management. Admins can create, modify, and delete publishers' }
],
components: {
securitySchemes: {
jwt: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'String containing the full JWT token'
}
}
}
}
})
await server.register(swagger_ui, {
routePrefix: '/docs'
})
}
// Register Routes
await server.register(authRoutes(cfg, store))
await server.register(siteRoutes(cfg, store))
await server.register(publisherRoutes(cfg, store))
await server.register(adminRoutes(cfg, store))
await server.register(cors, {
origin: true,
methods: ['DELETE', 'GET', 'POST', 'PUT'],
allowedHeaders: ['Authorization', 'Content-Type']
})
if (cfg.useSwagger ?? false) {
server.swagger()
server.log.info('Registered Swagger endpoints')
}
}
export default apiBuilder