aboutsummaryrefslogtreecommitdiff
path: root/src/metadata.ts
blob: 8899e37da114d0896a7b0f000797014765d81e11 (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
import { Db, MongoClient } from "mongodb";
import winston from "winston";
import bcrypt from "bcrypt";
import { v4 as uuid } from "uuid";

import loggerConfig from "./util/logger";
import { BranchNotFoundError } from "./errors";
import { GradientStyle } from "./formats";

interface HeadContext {
  commit: string;
  format: string;
}

interface Branch {
  head: HeadContext | string;
}

interface BranchList {
  [branch: string]: Branch;
}

interface SystemConfig {
  tokenHashed: string;
}

export interface HeadIdentity {
  organization: string;
  repository: string;
  branch: string;
  head: HeadContext;
}

export interface Repository {
  organization: string;
  name: string;
  branches: BranchList;
}

/**
 * Holds environment configuration items for the application
 */
export interface EnvConfig {
  /** Express value to bind to a given address */
  bindAddress: string;
  /** Express value for port */
  port: number;
  /** Express value to limit uploads to server */
  uploadLimit: number;
  /** Configuration for the database name */
  dbName: string;
  /** Configuration for the database URI */
  dbUri: string;
  /** The address given for communicating back to the server */
  targetUrl: string;
  /** The host directory for uploaded files */
  hostDir: string;
  /** The public directory for static files */
  publicDir: string;
  /** Gradient setting 1 */
  stage1: number;
  /** Gradient setting 2 */
  stage2: number;
  /** Log level across application */
  logLevel: string;
}

/**
 * Check if provided response is a known application error
 */
export const isError = (
  obj: HeadContext | BranchNotFoundError
): obj is BranchNotFoundError => {
  return Object.keys(obj).includes("name");
};

/**
 * Handles data routing for application
 */
class Metadata {
  private dbClient: MongoClient;
  private database: Db;
  config: EnvConfig;
  logger: winston.Logger;

  constructor(client: MongoClient, data: EnvConfig) {
    this.dbClient = client;
    this.database = client.db(data.dbName);
    this.config = data;
    this.logger = winston.createLogger(loggerConfig("META", data.logLevel));
  }

  async close(): Promise<void> {
    await this.dbClient.close();
    this.logger.info("Database client connection closed.");
  }

  /**
   * Retrieve the latest commit to the given branch
   */
  async getHeadCommit(
    organization: string,
    repository: string,
    branch: string
  ): Promise<HeadContext | BranchNotFoundError> {
    const result = await this.database
      .collection<Repository>("repository")
      .findOne({
        organization,
        name: repository,
        ["branches." + branch]: { $exists: true, $ne: null },
      });

    if (result !== null && Object.keys(result.branches).includes(branch)) {
      const limb = result.branches[branch];
      const head = typeof limb.head === "string" ? limb.head : limb.head.commit;
      const format =
        typeof limb.head === "string" ? "tarpaulin" : limb.head.format;
      this.logger.debug(
        "Found commit %s for ORB %s/%s/%s (format %s)",
        head,
        organization,
        repository,
        branch,
        format
      );
      return { commit: head, format };
    } else {
      return new BranchNotFoundError();
    }
  }

  /**
   * Update the database with the latest commit to a branch
   */
  async updateBranch(identity: HeadIdentity): Promise<boolean> {
    const { organization, repository: name, branch, head } = identity;
    const result = await this.database
      .collection<Repository>("repository")
      .findOneAndUpdate(
        { organization, name },
        { $set: { ["branches." + branch]: { head } } }
      );

    if (result.value == null) {
      return this.createRepository(identity);
    }

    return result.ok === 1;
  }

  /**
   * Add a repository metadata document to the database
   */
  async createRepository(identity: HeadIdentity): Promise<boolean> {
    const { organization, repository: name, branch, head } = identity;
    const repo: Repository = {
      organization,
      name,
      branches: { [branch]: { head } },
    };

    const result = await this.database
      .collection<Repository>("repository")
      .insertOne(repo);

    return result.acknowledged;
  }

  /**
   * Check whether the provided token matches the hashed token
   */
  async checkToken(token: string): Promise<boolean> {
    const result = await this.database
      .collection<SystemConfig>("sysconfig")
      .findOne({});

    if (result !== null) {
      return bcrypt.compare(token, result.tokenHashed);
    } else {
      return Promise.reject(Error("No system configuration in place"));
    }
  }

  /**
   * Generate a token for use as the user self-identifier.
   *
   * If the token is passed after it already exists, it will be overwritten.
   */
  async initializeToken(token?: string | undefined): Promise<boolean> {
    const config = await this.database
      .collection<SystemConfig>("sysconfig")
      .countDocuments();

    if (config > 0 && token === undefined) {
      return true;
    }

    const useToken =
      token === undefined
        ? (() => {
            const newToken = uuid();

            this.logger.warn(
              "TOKEN variable not provided, using this value instead: %s",
              newToken
            );
            this.logger.warn(
              "Use this provided token to push your coverage reports to the server."
            );

            return newToken;
          })()
        : token;

    const sysconfig = {
      tokenHashed: await bcrypt.hash(useToken, 10),
    };

    const result = await this.database
      .collection<SystemConfig>("sysconfig")
      .findOneAndReplace({}, sysconfig, { upsert: true });

    return result.ok === 1;
  }

  /**
   * Retrieve the upload limit for files from configuration
   */
  getUploadLimit(): number {
    return this.config.uploadLimit;
  }

  /**
   * Retrieve the host for uploaded documents directory from configuration
   */
  getHostDir(): string {
    return this.config.hostDir;
  }

  /**
   * Retrieve the public static file directory from configuration
   */
  getPublicDir(): string {
    return this.config.publicDir;
  }

  /**
   * Retrieve the gradient style from configuration
   */
  getGradientStyle(): GradientStyle {
    return {
      stage1: this.config.stage1,
      stage2: this.config.stage2,
    };
  }
}

export default Metadata;