-
Notifications
You must be signed in to change notification settings - Fork 127
/
job.ts
182 lines (173 loc) Β· 5.04 KB
/
job.ts
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
//
// Copyright (c) Microsoft.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
import { hostname } from 'os';
import Debug from 'debug';
import type {
ExecutionEnvironment,
IProviders,
IReposJob,
IReposJobOptions,
IReposJobResult,
SiteConfiguration,
} from './interfaces';
import { commonStartup } from '.';
import { quitInTenSeconds } from './lib/utils';
import initialize from './middleware/initialize';
export async function runJob(
job: (job: IReposJob) => Promise<IReposJobResult | void>,
options?: IReposJobOptions
): Promise<IReposJobResult | void> {
Debug.debug('startup')('starting job...');
options = options || {};
// TODO: automatically track elapsed job time
const started = new Date();
if (options.timeoutMinutes) {
setTimeout(
() => {
// TODO: insights metric and event, if a prefix exists
console.log(`Kill bit at ${options.timeoutMinutes}m`);
process.exit(1);
},
1000 * 60 * options.timeoutMinutes
);
}
if (options.defaultDebugOutput && !process.env.DEBUG) {
process.env.DEBUG = options.defaultDebugOutput;
}
let executionEnvironment: ExecutionEnvironment = null;
try {
executionEnvironment = await commonStartup(
initializeJob,
true /* job */,
options.enableAllGitHubApps,
null /* app */,
options.name
);
} catch (startupError) {
console.error(`Job startup error before runJob: ${startupError}`);
quitInTenSeconds(false);
return;
}
const providers = executionEnvironment?.providers;
if (options.insightsPrefix && providers?.insights) {
try {
providers?.insights?.trackEvent({
name: `${options.insightsPrefix}Started`,
properties: {
hostname: hostname(),
},
});
} catch (ignoreInsightsError) {
console.error(`insights error: ${ignoreInsightsError}`);
}
}
const jobObject = {
app: providers?.app,
executionEnvironment,
providers,
started,
parameters: options && options.parameters ? options.parameters : {},
args: process.argv.length > 2 ? process.argv.slice(2) : [],
};
let result: IReposJobResult = null;
try {
result = (await job.call(null, jobObject)) as IReposJobResult;
if (result?.successProperties && providers?.insights && options.insightsPrefix) {
try {
providers?.insights?.trackEvent({
name: `${options.insightsPrefix}Success`,
properties: Object.assign(
{
hostname: hostname(),
},
result.successProperties
),
});
} catch (ignoreInsightsError) {
console.error(`insights error: ${ignoreInsightsError}`);
}
}
} catch (jobError) {
console.error(`The job failed: ${jobError}`);
if (jobError.stack) {
console.error(jobError.stack);
}
// by default, let's not show the whole inner error
const simpleError = { ...jobError };
simpleError?.cause && delete simpleError.cause;
console.dir(simpleError);
const config = providers?.config;
quitInTenSeconds(false, config);
if (options.insightsPrefix) {
try {
providers?.insights?.trackException({
exception: jobError,
properties: {
name: `${options.insightsPrefix}Failure`,
},
});
} catch (ignoreInsightsError) {
console.error(`insights error: ${ignoreInsightsError}`);
}
}
trySilentInsightsFlush(providers);
return result;
}
// CONSIDER: insights metric for job time
trySilentInsightsFlush(providers);
console.log();
console.log('The job was successful.');
quitInTenSeconds(true);
return result;
}
function trySilentInsightsFlush(providers: IProviders) {
try {
providers?.insights?.flush();
} catch (ignored) {
console.warn(ignored);
}
}
function initializeJob(
executionEnvironment: ExecutionEnvironment,
config: SiteConfiguration,
configurationError: Error
) {
if (!config || configurationError) {
console.warn(`Configuration did not resolve successfully`, configurationError);
}
return initialize(
executionEnvironment,
null /* app */,
null /* express */,
__dirname,
config,
configurationError
);
}
export const job = {
runBackgroundJob: async (
script: (providers: IProviders, jobParameters?: IReposJob) => Promise<IReposJobResult | void>,
options?: IReposJobOptions
) => {
return runJob(
async function (jobParameters: IReposJob) {
return (await script(jobParameters.providers, jobParameters)) || {};
},
Object.assign({ enableAllGitHubApps: false }, options || {})
);
},
run: async (
script: (providers: IProviders, jobParameters?: IReposJob) => Promise<IReposJobResult | void>,
options?: IReposJobOptions
) => {
return runJob(
async function (jobParameters: IReposJob) {
return (await script(jobParameters.providers, jobParameters)) || {};
},
Object.assign({ enableAllGitHubApps: true }, options || {})
);
},
};
export default job;