Skip to content

Commit 479f0ad

Browse files
committed
refactor: code refactor
1 parent ae2c3eb commit 479f0ad

File tree

4 files changed

+53
-67
lines changed

4 files changed

+53
-67
lines changed

__tests__/worker.ts

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,24 @@
11
import { ContainerInitialization } from "../src/types/worker";
22
import JobWorker from "../src/worker";
33

4-
54
describe("Docker initialization test", () => {
6-
75
it("should create a python container", async () => {
8-
const worker = new JobWorker("python3", {code: "", functionName: ""});
9-
worker.createContainer().then(({ error, containerID }) => {
10-
expect(error).toBe(false);
11-
expect(containerID).toBeTruthy;
12-
worker.removeContainer();
13-
}).catch(_ => {})
6+
const worker = new JobWorker("python3", { code: "", functionName: "" });
7+
worker
8+
.createContainer()
9+
.then(({ error, containerID }) => {
10+
expect(error).toBe(false);
11+
expect(containerID).toBeTruthy;
12+
worker.removeContainer();
13+
})
14+
.catch((_) => {});
1415
});
15-
16+
1617
it("should not create a container", async () => {
17-
const worker = new JobWorker("invalidName" as any, {code: "", functionName: ""});
18+
const worker = new JobWorker("invalidName" as any, {
19+
code: "",
20+
functionName: "",
21+
});
1822
worker
1923
.createContainer()
2024
.catch(
@@ -26,5 +30,3 @@ describe("Docker initialization test", () => {
2630
);
2731
});
2832
});
29-
30-

src/index.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1 @@
11
import JobWorker from "./worker";
2-

src/types/worker.ts

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,29 @@
11
export type language = "python3" | "javascript";
22
export type fileFormat = "py" | "js";
3-
export type Stdout = string
3+
export type Stdout = string;
44

55
export interface CodeContext {
66
/**
77
* raw string code to be excuted
88
*/
9-
code: string
9+
code: string;
1010

1111
/**
1212
* A method name in class to be executed
1313
*/
14-
functionName: string
14+
functionName: string;
1515
}
1616

1717
interface BaseError {
1818
/**
1919
* Indicates an error during the process of spinning up the container
2020
*/
21-
error: boolean
21+
error: boolean;
2222

2323
/**
2424
* An error message in case the job fails
2525
*/
26-
errorMessage?: string
26+
errorMessage?: string;
2727
}
2828

2929
export interface ContainerInitialization extends BaseError {
@@ -39,16 +39,13 @@ export interface WriteFileStatus {
3939
*/
4040
filePath: string;
4141

42-
4342
/**
4443
* The file format of the created file
4544
*/
4645
fileFormat: string;
4746
}
4847

49-
50-
51-
export interface JobStatus extends BaseError{
48+
export interface JobStatus extends BaseError {
5249
/**
5350
* A brief message that describes that job status
5451
*/
@@ -65,10 +62,9 @@ export interface JobStatus extends BaseError{
6562
filePath?: string;
6663
}
6764

68-
export interface ExecuteContainer extends BaseError{
65+
export interface ExecuteContainer extends BaseError {
6966
/**
7067
* stdout from the container as a result of running the code
7168
*/
72-
codeOutput?: Stdout
73-
74-
}
69+
codeOutput?: Stdout;
70+
}

src/worker.ts

Lines changed: 30 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -14,27 +14,24 @@ import {
1414
} from "./types/worker";
1515
import { containerCPULimit, containerMemLimit, mainClassName } from "./config";
1616

17-
1817
const fileFormats: Record<language, fileFormat> = {
1918
python3: "py",
2019
javascript: "js",
2120
};
2221

2322
class JobWorker {
24-
public language: language
25-
public codeContext: CodeContext
26-
public filename: string
23+
public language: language;
24+
public codeContext: CodeContext;
25+
public filename: string;
26+
public containerID: string;
2727

2828
constructor(language: language, codeContext: CodeContext) {
29-
this.language = language
30-
this.codeContext = codeContext
31-
this.filename = ""
29+
this.language = language;
30+
this.codeContext = codeContext;
31+
this.filename = "";
32+
this.containerID = "";
3233
}
3334

34-
containerID: string = ""
35-
cacheFilename: string = ""
36-
37-
3835
/**
3936
* Creates an appropriate docker container
4037
* to execute the target code
@@ -61,10 +58,10 @@ class JobWorker {
6158
errorMessage: stderr,
6259
});
6360
} else {
64-
this.containerID = containerID.trim()
61+
this.containerID = containerID.trim();
6562
resolve({
6663
error: false,
67-
containerID: containerID.trim(),
64+
containerID: this.containerID,
6865
});
6966
}
7067
});
@@ -76,11 +73,12 @@ class JobWorker {
7673
* this is language specific, so defined using switch cases
7774
*/
7875
transformCodeIntoExecutable(): string {
79-
switch(this.language) {
76+
switch (this.language) {
8077
case "python3": {
81-
return `\nprint(${mainClassName}().${this.codeContext.functionName}())`
78+
return `\nprint(${mainClassName}().${this.codeContext.functionName}())`;
8279
}
83-
default: return ""
80+
default:
81+
return "";
8482
}
8583
}
8684

@@ -90,16 +88,11 @@ class JobWorker {
9088
private async writeFile(): Promise<WriteFileStatus> {
9189
return new Promise((resolve, reject) => {
9290
const fileFormat: string = fileFormats[this.language];
93-
this.filename = `${crypto.randomBytes(32).toString("hex")}.${fileFormat}`
94-
const filePath = path.join(
95-
__dirname,
96-
"..",
97-
"temp",
98-
`${this.filename}`
99-
);
91+
this.filename = `${crypto.randomBytes(32).toString("hex")}.${fileFormat}`;
92+
const filePath = path.join(__dirname, "..", "temp", `${this.filename}`);
10093

10194
// appending a line to execute a specific function
102-
this.codeContext.code += this.transformCodeIntoExecutable()
95+
this.codeContext.code += this.transformCodeIntoExecutable();
10396

10497
fs.writeFile(filePath, this.codeContext.code, (error) => {
10598
if (error) {
@@ -111,14 +104,13 @@ class JobWorker {
111104
});
112105
}
113106

114-
115107
/**
116108
* copies the target code into the newly created
117109
* isolated container
118110
*/
119111
copyContext(): Promise<string> {
120112
return new Promise(async (resolve, reject) => {
121-
if(!this.containerID) {
113+
if (!this.containerID) {
122114
reject("ContainerID not found.");
123115
}
124116
this.writeFile()
@@ -187,12 +179,12 @@ class JobWorker {
187179
if (error) {
188180
reject({
189181
error: true,
190-
errorMessage: error.message
191-
} as ExecuteContainer);
182+
errorMessage: error.message,
183+
} as ExecuteContainer);
192184
} else if (stderr) {
193185
reject({
194186
error: true,
195-
errorMessage: stderr
187+
errorMessage: stderr,
196188
} as ExecuteContainer);
197189
} else {
198190
resolve({
@@ -205,22 +197,20 @@ class JobWorker {
205197
// job failed
206198
reject({
207199
error: true,
208-
errorMessage: `Job has failed in the process of initializing the container for the following reason(s): ${jobStatus.message}`
209-
} as ExecuteContainer);
200+
errorMessage: `Job has failed in the process of initializing the container for the following reason(s): ${jobStatus.message}`,
201+
} as ExecuteContainer);
210202
}
211203
})
212-
.catch(_ => {});
204+
.catch((_) => {});
213205
});
214206
}
215207

216-
217-
218208
/**
219209
* Removes a container with the provided containerID
220210
*/
221211
async removeContainer(): Promise<Stdout> {
222212
return new Promise((resolve, reject) => {
223-
if(!this.containerID) {
213+
if (!this.containerID) {
224214
reject("ContainerID not found.");
225215
}
226216
const removeContainer = `docker rm --force ${this.containerID}`;
@@ -236,13 +226,12 @@ class JobWorker {
236226
});
237227
}
238228

239-
240229
/**
241230
* Deletes the temp file in /temp folder
242231
*/
243232
async removeCacheFile(): Promise<Stdout> {
244233
return new Promise((resolve, reject) => {
245-
if(!this.filename) {
234+
if (!this.filename) {
246235
return reject("Filename not found.");
247236
}
248237
const removeContainer = `rm ${__dirname}/../temp/${this.filename}`;
@@ -263,10 +252,10 @@ class JobWorker {
263252
* Destroys the docker container & deletes cache files
264253
*/
265254
async cleanupJob(): Promise<any> {
266-
const jobs: Promise<any>[] = []
267-
jobs.push(this.removeContainer())
268-
jobs.push(this.removeCacheFile())
269-
return Promise.all(jobs)
255+
const jobs: Promise<any>[] = [];
256+
jobs.push(this.removeContainer());
257+
jobs.push(this.removeCacheFile());
258+
return Promise.all(jobs);
270259
}
271260
}
272261

0 commit comments

Comments
 (0)