aboutsummaryrefslogtreecommitdiff
path: root/src/routes.ts
blob: 7d2c2fb72c002c7e405392ba918a6d71fd9bc03d (plain) (blame)
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
import express, { Router } from "express";
import { badgen } from "badgen";
import winston from "winston";
import path from "path";
import fs from "fs";

import formats, { Format } from "./formats";
import Metadata, { HeadIdentity, isError } from "./metadata";
import loggerConfig from "./util/logger";
import { InvalidReportDocumentError, Messages } from "./errors";

const logger = winston.createLogger(loggerConfig("HTTP"));

export default (metadata: Metadata): Router => {
  const router = Router();

  const commitFormatDocs = async (
    contents: string,
    identity: HeadIdentity,
    formatter: Format
  ): Promise<boolean | InvalidReportDocumentError> => {
    const reportPath = path.join(
      metadata.getHostDir(),
      identity.organization,
      identity.repository,
      identity.branch,
      identity.head.commit
    );
    const coverage = await formatter.parseCoverage(contents);
    if (typeof coverage !== "number") {
      return coverage;
    }

    // Create report directory if not exists
    await fs.promises.mkdir(reportPath, { recursive: true });

    // Create report badge
    const style = metadata.getGradientStyle();
    const badge = badgen({
      label: "coverage",
      status: Math.floor(coverage).toString() + "%",
      color: formatter.matchColor(coverage, style),
    });

    // Write report and badge to directory
    await fs.promises.writeFile(path.join(reportPath, "badge.svg"), badge);
    await fs.promises.writeFile(
      path.join(reportPath, formatter.fileName),
      contents
    );

    // Update (or create) given branch with commit info
    return await metadata.updateBranch(identity);
  };

  // serve landing page
  router.get("/", (_, res) => {
    res.sendFile(path.join(metadata.getHostDir(), "index.html"));
  });

  // health check endpoint
  router.get("/v1/health-check", (_, res) => {
    res.sendStatus(200);
  });

  // serve script for posting coverage report
  router.use(
    "/:shell(bash|sh)",
    express.static(path.join(metadata.getHostDir(), "sh"), {
      setHeaders: (res) => res.contentType("text/plain"),
    })
  );

  // favicon should be served directly on root
  router.get("/favicon.ico", (_, res) => {
    res.sendFile(path.join(metadata.getPublicDir(), "static", "favicon.ico"));
  });
  // serve static files
  router.use(
    "/static",
    express.static(path.join(metadata.getPublicDir(), "static"))
  );

  // Upload file
  router.post("/v1/:org/:repo/:branch/:commit.:ext(html|xml)", (req, res) => {
    const { org, repo, branch, commit } = req.params;

    const { token, format } = req.query;
    if (token != metadata.getToken()) {
      return res.status(401).send(Messages.InvalidToken);
    }

    if (typeof format !== "string" || !formats.listFormats().includes(format)) {
      return res.status(406).send(Messages.InvalidFormat);
    }

    const limit = metadata.getUploadLimit();
    if (Number(req.headers["content-length"] ?? 0) > limit) {
      return res.status(413).send(Messages.FileTooLarge);
    }

    let contents = "";
    req.on("data", (raw) => {
      if (contents.length <= limit) {
        contents += raw;
      }
    });
    req.on("end", async () => {
      // Ignore large requests
      if (contents.length > limit) {
        return res.status(413).send(Messages.FileTooLarge);
      }

      const formatter = formats.getFormat(format);
      const identity = {
        organization: org,
        repository: repo,
        branch,
        head: { commit, format },
      };

      try {
        const result = await commitFormatDocs(contents, identity, formatter);

        if (typeof result === "boolean") {
          if (result) {
            return res.status(200).send();
          } else {
            logger.error(
              "Unknown error while attempting to commit branch update"
            );
            return res.status(500).send(Messages.UnknownError);
          }
        } else {
          return res.status(400).send(Messages.InvalidFormat);
        }
      } catch (err) {
        logger.error(
          err ?? "Unknown error occurred while processing POST request"
        );
        return res.status(500).send(Messages.UnknownError);
      }
    });
  });

  const retrieveFile = (
    res: express.Response,
    identity: HeadIdentity,
    file: string
  ): void => {
    const { organization: org, repository: repo, branch, head } = identity;

    const pathname = path.join(
      metadata.getHostDir(),
      org,
      repo,
      branch,
      head.commit,
      file
    );
    fs.access(pathname, fs.constants.R_OK, (err) =>
      err === null
        ? res.sendFile(pathname)
        : res.status(404).send(Messages.FileNotFound)
    );
  };

  router.get("/v1/:org/:repo/:branch.svg", (req, res) => {
    const { org, repo, branch } = req.params;

    metadata.getHeadCommit(org, repo, branch).then(
      (result) => {
        if (!isError(result)) {
          const identity = {
            organization: org,
            repository: repo,
            branch,
            head: result,
          };
          retrieveFile(res, identity, "badge.svg");
        } else {
          res.status(404).send(result.message);
        }
      },
      (err) => {
        logger.error(
          err ?? "Error occurred while fetching commit for GET request"
        );
        res.status(500).send(Messages.UnknownError);
      }
    );
  });

  router.get("/v1/:org/:repo/:branch.:ext(html|xml)", (req, res) => {
    const { org, repo, branch } = req.params;

    metadata.getHeadCommit(org, repo, branch).then(
      (result) => {
        if (!isError(result)) {
          const identity = {
            organization: org,
            repository: repo,
            branch,
            head: result,
          };
          const { fileName } = formats.getFormat(result.format);
          retrieveFile(res, identity, fileName);
        } else {
          res.status(404).send(result.message);
        }
      },
      (err) => {
        logger.error(
          err ?? "Error occurred while fetching commit for GET request"
        );
        res.status(500).send(Messages.UnknownError);
      }
    );
  });

  // provide hard link for commit
  router.get("/v1/:org/:repo/:branch/:commit.svg", (req, res) => {
    const { org, repo, branch, commit } = req.params;
    const identity = {
      organization: org,
      repository: repo,
      branch,
      head: { commit, format: "_" },
    };
    retrieveFile(res, identity, "badge.svg");
  });

  // provide hard link for commit
  router.get("/v1/:org/:repo/:branch/:commit.html", (req, res) => {
    const { org, repo, branch, commit } = req.params;
    const format = formats.formats.tarpaulin;
    const identity = {
      organization: org,
      repository: repo,
      branch,
      head: { commit, format: "tarpaulin" },
    };
    retrieveFile(res, identity, format.fileName);
  });

  router.get("/v1/:org/:repo/:branch/:commit.xml", (req, res) => {
    const { org, repo, branch, commit } = req.params;
    const format = formats.formats.cobertura;
    const identity = {
      organization: org,
      repository: repo,
      branch,
      head: { commit, format: "cobertura" },
    };
    retrieveFile(res, identity, format.fileName);
  });

  router.use((_, res) => {
    res.status(404);
    res.sendFile(path.join(metadata.getPublicDir(), "static", "404.html"));
  });

  return router;
};