summaryrefslogtreecommitdiffstats
path: root/remote/test/puppeteer/tools/internal/job.ts
blob: ef6ea10237331a0475a42c58cb06152bd9cb5d92 (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
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
import {createHash} from 'crypto';
import {existsSync, Stats} from 'fs';
import {mkdir, readFile, stat, writeFile} from 'fs/promises';
import {tmpdir} from 'os';
import {dirname, join} from 'path';

import glob from 'glob';

interface JobContext {
  name: string;
  inputs: string[];
  outputs: string[];
}

class JobBuilder {
  #inputs: string[] = [];
  #outputs: string[] = [];
  #callback: (ctx: JobContext) => Promise<void>;
  #name: string;
  #value = '';
  #force = false;

  constructor(name: string, callback: (ctx: JobContext) => Promise<void>) {
    this.#name = name;
    this.#callback = callback;
  }

  get jobHash(): string {
    return createHash('sha256').update(this.#name).digest('hex');
  }

  force() {
    this.#force = true;
    return this;
  }

  value(value: string) {
    this.#value = value;
    return this;
  }

  inputs(inputs: string[]): JobBuilder {
    this.#inputs = inputs.flatMap(value => {
      if (glob.hasMagic(value)) {
        return glob.sync(value);
      }
      return value;
    });
    return this;
  }

  outputs(outputs: string[]): JobBuilder {
    if (!this.#name) {
      this.#name = outputs.join(' and ');
    }

    this.#outputs = outputs;
    return this;
  }

  async build(): Promise<void> {
    console.log(`Running job ${this.#name}...`);
    // For debugging.
    if (this.#force) {
      return this.#run();
    }
    // In case we deleted an output file on purpose.
    if (!this.getOutputStats()) {
      return this.#run();
    }
    // Run if the job has a value, but it changes.
    if (this.#value) {
      if (!(await this.isValueDifferent())) {
        return;
      }
      return this.#run();
    }
    // Always run when there is no output.
    if (!this.#outputs.length) {
      return this.#run();
    }
    // Make-like comparator.
    if (!(await this.areInputsNewer())) {
      return;
    }
    return this.#run();
  }

  async isValueDifferent(): Promise<boolean> {
    const file = join(tmpdir(), `puppeteer/${this.jobHash}.txt`);
    await mkdir(dirname(file), {recursive: true});
    if (!existsSync(file)) {
      await writeFile(file, this.#value);
      return true;
    }
    return this.#value !== (await readFile(file, 'utf8'));
  }

  #outputStats?: Stats[];
  async getOutputStats(): Promise<Stats[] | undefined> {
    if (this.#outputStats) {
      return this.#outputStats;
    }
    try {
      this.#outputStats = await Promise.all(
        this.#outputs.map(output => {
          return stat(output);
        })
      );
    } catch {}
    return this.#outputStats;
  }

  async areInputsNewer(): Promise<boolean> {
    const inputStats = await Promise.all(
      this.#inputs.map(input => {
        return stat(input);
      })
    );
    const outputStats = await this.getOutputStats();
    if (
      outputStats &&
      outputStats.reduce(reduceMinTime, Infinity) >
        inputStats.reduce(reduceMaxTime, 0)
    ) {
      return false;
    }
    return true;
  }

  #run(): Promise<void> {
    return this.#callback({
      name: this.#name,
      inputs: this.#inputs,
      outputs: this.#outputs,
    });
  }
}

export const job = (
  name: string,
  callback: (ctx: JobContext) => Promise<void>
): JobBuilder => {
  return new JobBuilder(name, callback);
};

const reduceMaxTime = (time: number, stat: Stats) => {
  return time < stat.mtimeMs ? stat.mtimeMs : time;
};

const reduceMinTime = (time: number, stat: Stats) => {
  return time > stat.mtimeMs ? stat.mtimeMs : time;
};