aboutsummaryrefslogtreecommitdiffhomepage
path: root/packages/server-commands/src/server/server.ts
diff options
context:
space:
mode:
authorChocobozzz <me@florianbigard.com>2023-07-31 14:34:36 +0200
committerChocobozzz <me@florianbigard.com>2023-08-11 15:02:33 +0200
commit3a4992633ee62d5edfbb484d9c6bcb3cf158489d (patch)
treee4510b39bdac9c318fdb4b47018d08f15368b8f0 /packages/server-commands/src/server/server.ts
parent04d1da5621d25d59bd5fa1543b725c497bf5d9a8 (diff)
downloadPeerTube-3a4992633ee62d5edfbb484d9c6bcb3cf158489d.tar.gz
PeerTube-3a4992633ee62d5edfbb484d9c6bcb3cf158489d.tar.zst
PeerTube-3a4992633ee62d5edfbb484d9c6bcb3cf158489d.zip
Migrate server to ESM
Sorry for the very big commit that may lead to git log issues and merge conflicts, but it's a major step forward: * Server can be faster at startup because imports() are async and we can easily lazy import big modules * Angular doesn't seem to support ES import (with .js extension), so we had to correctly organize peertube into a monorepo: * Use yarn workspace feature * Use typescript reference projects for dependencies * Shared projects have been moved into "packages", each one is now a node module (with a dedicated package.json/tsconfig.json) * server/tools have been moved into apps/ and is now a dedicated app bundled and published on NPM so users don't have to build peertube cli tools manually * server/tests have been moved into packages/ so we don't compile them every time we want to run the server * Use isolatedModule option: * Had to move from const enum to const (https://www.typescriptlang.org/docs/handbook/enums.html#objects-vs-enums) * Had to explictely specify "type" imports when used in decorators * Prefer tsx (that uses esbuild under the hood) instead of ts-node to load typescript files (tests with mocha or scripts): * To reduce test complexity as esbuild doesn't support decorator metadata, we only test server files that do not import server models * We still build tests files into js files for a faster CI * Remove unmaintained peertube CLI import script * Removed some barrels to speed up execution (less imports)
Diffstat (limited to 'packages/server-commands/src/server/server.ts')
-rw-r--r--packages/server-commands/src/server/server.ts451
1 files changed, 451 insertions, 0 deletions
diff --git a/packages/server-commands/src/server/server.ts b/packages/server-commands/src/server/server.ts
new file mode 100644
index 000000000..57a897c17
--- /dev/null
+++ b/packages/server-commands/src/server/server.ts
@@ -0,0 +1,451 @@
1import { ChildProcess, fork } from 'child_process'
2import { copy } from 'fs-extra/esm'
3import { join } from 'path'
4import { randomInt } from '@peertube/peertube-core-utils'
5import { Video, VideoChannel, VideoChannelSync, VideoCreateResult, VideoDetails } from '@peertube/peertube-models'
6import { parallelTests, root } from '@peertube/peertube-node-utils'
7import { BulkCommand } from '../bulk/index.js'
8import { CLICommand } from '../cli/index.js'
9import { CustomPagesCommand } from '../custom-pages/index.js'
10import { FeedCommand } from '../feeds/index.js'
11import { LogsCommand } from '../logs/index.js'
12import { AbusesCommand } from '../moderation/index.js'
13import { OverviewsCommand } from '../overviews/index.js'
14import { RunnerJobsCommand, RunnerRegistrationTokensCommand, RunnersCommand } from '../runners/index.js'
15import { SearchCommand } from '../search/index.js'
16import { SocketIOCommand } from '../socket/index.js'
17import {
18 AccountsCommand,
19 BlocklistCommand,
20 LoginCommand,
21 NotificationsCommand,
22 RegistrationsCommand,
23 SubscriptionsCommand,
24 TwoFactorCommand,
25 UsersCommand
26} from '../users/index.js'
27import {
28 BlacklistCommand,
29 CaptionsCommand,
30 ChangeOwnershipCommand,
31 ChannelsCommand,
32 ChannelSyncsCommand,
33 CommentsCommand,
34 HistoryCommand,
35 ImportsCommand,
36 LiveCommand,
37 PlaylistsCommand,
38 ServicesCommand,
39 StoryboardCommand,
40 StreamingPlaylistsCommand,
41 VideoPasswordsCommand,
42 VideosCommand,
43 VideoStatsCommand,
44 VideoStudioCommand,
45 VideoTokenCommand,
46 ViewsCommand
47} from '../videos/index.js'
48import { ConfigCommand } from './config-command.js'
49import { ContactFormCommand } from './contact-form-command.js'
50import { DebugCommand } from './debug-command.js'
51import { FollowsCommand } from './follows-command.js'
52import { JobsCommand } from './jobs-command.js'
53import { MetricsCommand } from './metrics-command.js'
54import { PluginsCommand } from './plugins-command.js'
55import { RedundancyCommand } from './redundancy-command.js'
56import { ServersCommand } from './servers-command.js'
57import { StatsCommand } from './stats-command.js'
58
59export type RunServerOptions = {
60 hideLogs?: boolean
61 nodeArgs?: string[]
62 peertubeArgs?: string[]
63 env?: { [ id: string ]: string }
64}
65
66export class PeerTubeServer {
67 app?: ChildProcess
68
69 url: string
70 host?: string
71 hostname?: string
72 port?: number
73
74 rtmpPort?: number
75 rtmpsPort?: number
76
77 parallel?: boolean
78 internalServerNumber: number
79
80 serverNumber?: number
81 customConfigFile?: string
82
83 store?: {
84 client?: {
85 id?: string
86 secret?: string
87 }
88
89 user?: {
90 username: string
91 password: string
92 email?: string
93 }
94
95 channel?: VideoChannel
96 videoChannelSync?: Partial<VideoChannelSync>
97
98 video?: Video
99 videoCreated?: VideoCreateResult
100 videoDetails?: VideoDetails
101
102 videos?: { id: number, uuid: string }[]
103 }
104
105 accessToken?: string
106 refreshToken?: string
107
108 bulk?: BulkCommand
109 cli?: CLICommand
110 customPage?: CustomPagesCommand
111 feed?: FeedCommand
112 logs?: LogsCommand
113 abuses?: AbusesCommand
114 overviews?: OverviewsCommand
115 search?: SearchCommand
116 contactForm?: ContactFormCommand
117 debug?: DebugCommand
118 follows?: FollowsCommand
119 jobs?: JobsCommand
120 metrics?: MetricsCommand
121 plugins?: PluginsCommand
122 redundancy?: RedundancyCommand
123 stats?: StatsCommand
124 config?: ConfigCommand
125 socketIO?: SocketIOCommand
126 accounts?: AccountsCommand
127 blocklist?: BlocklistCommand
128 subscriptions?: SubscriptionsCommand
129 live?: LiveCommand
130 services?: ServicesCommand
131 blacklist?: BlacklistCommand
132 captions?: CaptionsCommand
133 changeOwnership?: ChangeOwnershipCommand
134 playlists?: PlaylistsCommand
135 history?: HistoryCommand
136 imports?: ImportsCommand
137 channelSyncs?: ChannelSyncsCommand
138 streamingPlaylists?: StreamingPlaylistsCommand
139 channels?: ChannelsCommand
140 comments?: CommentsCommand
141 notifications?: NotificationsCommand
142 servers?: ServersCommand
143 login?: LoginCommand
144 users?: UsersCommand
145 videoStudio?: VideoStudioCommand
146 videos?: VideosCommand
147 videoStats?: VideoStatsCommand
148 views?: ViewsCommand
149 twoFactor?: TwoFactorCommand
150 videoToken?: VideoTokenCommand
151 registrations?: RegistrationsCommand
152 videoPasswords?: VideoPasswordsCommand
153
154 storyboard?: StoryboardCommand
155
156 runners?: RunnersCommand
157 runnerRegistrationTokens?: RunnerRegistrationTokensCommand
158 runnerJobs?: RunnerJobsCommand
159
160 constructor (options: { serverNumber: number } | { url: string }) {
161 if ((options as any).url) {
162 this.setUrl((options as any).url)
163 } else {
164 this.setServerNumber((options as any).serverNumber)
165 }
166
167 this.store = {
168 client: {
169 id: null,
170 secret: null
171 },
172 user: {
173 username: null,
174 password: null
175 }
176 }
177
178 this.assignCommands()
179 }
180
181 setServerNumber (serverNumber: number) {
182 this.serverNumber = serverNumber
183
184 this.parallel = parallelTests()
185
186 this.internalServerNumber = this.parallel ? this.randomServer() : this.serverNumber
187 this.rtmpPort = this.parallel ? this.randomRTMP() : 1936
188 this.rtmpsPort = this.parallel ? this.randomRTMP() : 1937
189 this.port = 9000 + this.internalServerNumber
190
191 this.url = `http://127.0.0.1:${this.port}`
192 this.host = `127.0.0.1:${this.port}`
193 this.hostname = '127.0.0.1'
194 }
195
196 setUrl (url: string) {
197 const parsed = new URL(url)
198
199 this.url = url
200 this.host = parsed.host
201 this.hostname = parsed.hostname
202 this.port = parseInt(parsed.port)
203 }
204
205 getDirectoryPath (directoryName: string) {
206 const testDirectory = 'test' + this.internalServerNumber
207
208 return join(root(), testDirectory, directoryName)
209 }
210
211 async flushAndRun (configOverride?: object, options: RunServerOptions = {}) {
212 await ServersCommand.flushTests(this.internalServerNumber)
213
214 return this.run(configOverride, options)
215 }
216
217 async run (configOverrideArg?: any, options: RunServerOptions = {}) {
218 // These actions are async so we need to be sure that they have both been done
219 const serverRunString = {
220 'HTTP server listening': false
221 }
222 const key = 'Database peertube_test' + this.internalServerNumber + ' is ready'
223 serverRunString[key] = false
224
225 const regexps = {
226 client_id: 'Client id: (.+)',
227 client_secret: 'Client secret: (.+)',
228 user_username: 'Username: (.+)',
229 user_password: 'User password: (.+)'
230 }
231
232 await this.assignCustomConfigFile()
233
234 const configOverride = this.buildConfigOverride()
235
236 if (configOverrideArg !== undefined) {
237 Object.assign(configOverride, configOverrideArg)
238 }
239
240 // Share the environment
241 const env = { ...process.env }
242 env['NODE_ENV'] = 'test'
243 env['NODE_APP_INSTANCE'] = this.internalServerNumber.toString()
244 env['NODE_CONFIG'] = JSON.stringify(configOverride)
245
246 if (options.env) {
247 Object.assign(env, options.env)
248 }
249
250 const execArgv = options.nodeArgs || []
251 // FIXME: too slow :/
252 // execArgv.push('--enable-source-maps')
253
254 const forkOptions = {
255 silent: true,
256 env,
257 detached: false,
258 execArgv
259 }
260
261 const peertubeArgs = options.peertubeArgs || []
262
263 return new Promise<void>((res, rej) => {
264 const self = this
265 let aggregatedLogs = ''
266
267 this.app = fork(join(root(), 'dist', 'server.js'), peertubeArgs, forkOptions)
268
269 const onPeerTubeExit = () => rej(new Error('Process exited:\n' + aggregatedLogs))
270 const onParentExit = () => {
271 if (!this.app?.pid) return
272
273 try {
274 process.kill(self.app.pid)
275 } catch { /* empty */ }
276 }
277
278 this.app.on('exit', onPeerTubeExit)
279 process.on('exit', onParentExit)
280
281 this.app.stdout.on('data', function onStdout (data) {
282 let dontContinue = false
283
284 const log: string = data.toString()
285 aggregatedLogs += log
286
287 // Capture things if we want to
288 for (const key of Object.keys(regexps)) {
289 const regexp = regexps[key]
290 const matches = log.match(regexp)
291 if (matches !== null) {
292 if (key === 'client_id') self.store.client.id = matches[1]
293 else if (key === 'client_secret') self.store.client.secret = matches[1]
294 else if (key === 'user_username') self.store.user.username = matches[1]
295 else if (key === 'user_password') self.store.user.password = matches[1]
296 }
297 }
298
299 // Check if all required sentences are here
300 for (const key of Object.keys(serverRunString)) {
301 if (log.includes(key)) serverRunString[key] = true
302 if (serverRunString[key] === false) dontContinue = true
303 }
304
305 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
306 if (dontContinue === true) return
307
308 if (options.hideLogs === false) {
309 console.log(log)
310 } else {
311 process.removeListener('exit', onParentExit)
312 self.app.stdout.removeListener('data', onStdout)
313 self.app.removeListener('exit', onPeerTubeExit)
314 }
315
316 res()
317 })
318 })
319 }
320
321 kill () {
322 if (!this.app) return Promise.resolve()
323
324 process.kill(this.app.pid)
325
326 this.app = null
327
328 return Promise.resolve()
329 }
330
331 private randomServer () {
332 const low = 2500
333 const high = 10000
334
335 return randomInt(low, high)
336 }
337
338 private randomRTMP () {
339 const low = 1900
340 const high = 2100
341
342 return randomInt(low, high)
343 }
344
345 private async assignCustomConfigFile () {
346 if (this.internalServerNumber === this.serverNumber) return
347
348 const basePath = join(root(), 'config')
349
350 const tmpConfigFile = join(basePath, `test-${this.internalServerNumber}.yaml`)
351 await copy(join(basePath, `test-${this.serverNumber}.yaml`), tmpConfigFile)
352
353 this.customConfigFile = tmpConfigFile
354 }
355
356 private buildConfigOverride () {
357 if (!this.parallel) return {}
358
359 return {
360 listen: {
361 port: this.port
362 },
363 webserver: {
364 port: this.port
365 },
366 database: {
367 suffix: '_test' + this.internalServerNumber
368 },
369 storage: {
370 tmp: this.getDirectoryPath('tmp') + '/',
371 tmp_persistent: this.getDirectoryPath('tmp-persistent') + '/',
372 bin: this.getDirectoryPath('bin') + '/',
373 avatars: this.getDirectoryPath('avatars') + '/',
374 web_videos: this.getDirectoryPath('web-videos') + '/',
375 streaming_playlists: this.getDirectoryPath('streaming-playlists') + '/',
376 redundancy: this.getDirectoryPath('redundancy') + '/',
377 logs: this.getDirectoryPath('logs') + '/',
378 previews: this.getDirectoryPath('previews') + '/',
379 thumbnails: this.getDirectoryPath('thumbnails') + '/',
380 storyboards: this.getDirectoryPath('storyboards') + '/',
381 torrents: this.getDirectoryPath('torrents') + '/',
382 captions: this.getDirectoryPath('captions') + '/',
383 cache: this.getDirectoryPath('cache') + '/',
384 plugins: this.getDirectoryPath('plugins') + '/',
385 well_known: this.getDirectoryPath('well-known') + '/'
386 },
387 admin: {
388 email: `admin${this.internalServerNumber}@example.com`
389 },
390 live: {
391 rtmp: {
392 port: this.rtmpPort
393 }
394 }
395 }
396 }
397
398 private assignCommands () {
399 this.bulk = new BulkCommand(this)
400 this.cli = new CLICommand(this)
401 this.customPage = new CustomPagesCommand(this)
402 this.feed = new FeedCommand(this)
403 this.logs = new LogsCommand(this)
404 this.abuses = new AbusesCommand(this)
405 this.overviews = new OverviewsCommand(this)
406 this.search = new SearchCommand(this)
407 this.contactForm = new ContactFormCommand(this)
408 this.debug = new DebugCommand(this)
409 this.follows = new FollowsCommand(this)
410 this.jobs = new JobsCommand(this)
411 this.metrics = new MetricsCommand(this)
412 this.plugins = new PluginsCommand(this)
413 this.redundancy = new RedundancyCommand(this)
414 this.stats = new StatsCommand(this)
415 this.config = new ConfigCommand(this)
416 this.socketIO = new SocketIOCommand(this)
417 this.accounts = new AccountsCommand(this)
418 this.blocklist = new BlocklistCommand(this)
419 this.subscriptions = new SubscriptionsCommand(this)
420 this.live = new LiveCommand(this)
421 this.services = new ServicesCommand(this)
422 this.blacklist = new BlacklistCommand(this)
423 this.captions = new CaptionsCommand(this)
424 this.changeOwnership = new ChangeOwnershipCommand(this)
425 this.playlists = new PlaylistsCommand(this)
426 this.history = new HistoryCommand(this)
427 this.imports = new ImportsCommand(this)
428 this.channelSyncs = new ChannelSyncsCommand(this)
429 this.streamingPlaylists = new StreamingPlaylistsCommand(this)
430 this.channels = new ChannelsCommand(this)
431 this.comments = new CommentsCommand(this)
432 this.notifications = new NotificationsCommand(this)
433 this.servers = new ServersCommand(this)
434 this.login = new LoginCommand(this)
435 this.users = new UsersCommand(this)
436 this.videos = new VideosCommand(this)
437 this.videoStudio = new VideoStudioCommand(this)
438 this.videoStats = new VideoStatsCommand(this)
439 this.views = new ViewsCommand(this)
440 this.twoFactor = new TwoFactorCommand(this)
441 this.videoToken = new VideoTokenCommand(this)
442 this.registrations = new RegistrationsCommand(this)
443
444 this.storyboard = new StoryboardCommand(this)
445
446 this.runners = new RunnersCommand(this)
447 this.runnerRegistrationTokens = new RunnerRegistrationTokensCommand(this)
448 this.runnerJobs = new RunnerJobsCommand(this)
449 this.videoPasswords = new VideoPasswordsCommand(this)
450 }
451}