summaryrefslogtreecommitdiffstats
path: root/server/utils/simple-migration-server.js
blob: 680f8df240f5dded4fc0a176ae3d27c050906793 (plain)
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
const express = require("express");
const http = require("node:http");
const { log } = require("../../src/util");

/**
 * SimpleMigrationServer
 * For displaying the migration status of the server
 * Also, it is used to let Docker healthcheck know the status of the server, as the main server is not started yet, healthcheck will think the server is down incorrectly.
 */
class SimpleMigrationServer {
    /**
     * Express app instance
     * @type {?Express}
     */
    app;

    /**
     * Server instance
     * @type {?Server}
     */
    server;

    /**
     * Response object
     * @type {?Response}
     */
    response;

    /**
     * Start the server
     * @param {number} port Port
     * @param {string} hostname Hostname
     * @returns {Promise<void>}
     */
    start(port, hostname) {
        this.app = express();
        this.server = http.createServer(this.app);

        this.app.get("/", (req, res) => {
            res.set("Content-Type", "text/plain");
            res.write("Migration is in progress, listening message...\n");
            if (this.response) {
                this.response.write("Disconnected\n");
                this.response.end();
            }
            this.response = res;
            // never ending response
        });

        return new Promise((resolve) => {
            this.server.listen(port, hostname, () => {
                if (hostname) {
                    log.info("migration", `Migration server is running on http://${hostname}:${port}`);
                } else {
                    log.info("migration", `Migration server is running on http://localhost:${port}`);
                }
                resolve();
            });
        });
    }

    /**
     * Update the message
     * @param {string} msg Message to update
     * @returns {void}
     */
    update(msg) {
        this.response?.write(msg + "\n");
    }

    /**
     * Stop the server
     * @returns {Promise<void>}
     */
    async stop() {
        this.response?.write("Finished, please refresh this page.\n");
        this.response?.end();
        await this.server?.close();
    }
}

module.exports = {
    SimpleMigrationServer,
};