Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: adding file upload test #37

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions assets/file.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"app": "wow"
}
Binary file added assets/file.mp3
Binary file not shown.
Binary file added assets/file.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions assets/file.txt

Large diffs are not rendered by default.

Binary file added assets/file.zip
Binary file not shown.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"lint": "eslint src",
"lint-fix": "eslint --fix src",
"lint-staged": "lint-staged",
"test": "jest --runInBand",
"test": "jest --runInBand --passWithNoTests",
"dev": "nodemon src/index.ts",
"start": "ts-node ./src/index.ts"
},
Expand Down
3 changes: 2 additions & 1 deletion src/BenchmarkRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ type EventKeys =
| 'subscribePresence'
| 'getRoutingConfig'
| 'getQueuedInquiries'
| 'takeInquiry';
| 'takeInquiry'
| 'uploadFile';

const eventsPerSecond = (events: number): number => Math.ceil(1000 / events);

Expand Down
49 changes: 49 additions & 0 deletions src/client/Client.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import fs from 'fs';
import path from 'path';
import { URLSearchParams } from 'url';

import RocketChatClient from '@rocket.chat/sdk/lib/clients/Rocketchat';
import EJSON from 'ejson';
import FormData from 'form-data';
import type { BodyInit, RequestInit } from 'node-fetch';
import fetch from 'node-fetch';

import { config } from '../config';
import type { Subscription, Department, Inquiry, Visitor } from '../definifitons';
import { delay } from '../lib/delay';
import { getRandomFileInFolder } from '../lib/file';
import { username, email } from '../lib/ids';
import * as prom from '../lib/prom';
import { rand } from '../lib/rand';
Expand Down Expand Up @@ -264,6 +269,42 @@ export class Client {
await this.typing(rid, false);
}

async uploadFile({ rid }: { rid: string }): Promise<void> {
if (!this.client.currentLogin) {
return;
}

const folderPath = path.join(__dirname, '..', '..', 'assets');

const { filePath } = getRandomFileInFolder(folderPath);

const { authToken, userId } = this.client.currentLogin;

Check failure

Code scanning / CodeQL

Insecure randomness

This uses a cryptographically insecure random number generated at [Math.random()](1) in a security context. This uses a cryptographically insecure random number generated at [Math.random()](1) in a security context.

const endAction = prom.actions.startTimer({ action: 'uploadFile' });
const end = prom.messages.startTimer();
try {
const fileFormData = new FormData();

fileFormData.append('file', fs.createReadStream(filePath));

await this.httpPost(`/api/v1/rooms.upload/${rid}`, {
body: fileFormData as unknown as BodyInit,
headers: {
'X-Auth-Token': authToken,
'X-User-Id': userId,
'Content-Type': `multipart/form-data; boundary=${fileFormData.getBoundary()}`,
},
});

end({ status: 'success' });
endAction({ status: 'success' });
} catch (e) {
end({ status: 'error' });
endAction({ status: 'error' });
throw e;
}
}

async typing(rid: string, typing: boolean): Promise<void> {
if (!this.loggedIn) {
await this.login();
Expand Down Expand Up @@ -510,4 +551,12 @@ export class Client {
});
return result.json();
}

protected async httpPost(endpoint: string, init?: RequestInit): Promise<unknown> {
const result = await fetch(`${this.host}${endpoint}`, {
method: 'POST',
...init,
});
return result.json();
}
}
1 change: 1 addition & 0 deletions src/client/WebClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ export class WebClient extends Client {
'roles-change',
'voip.statuschanged',
'permissions-changed',
'uploadFile',
].map((event) => this.client.subscribe('stream-notify-logged', event, false)),
);

Expand Down
5 changes: 5 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ const {
QUEUED_INQUIRIES_PER_SEC = '0.5',
TAKE_INQUIRY_PER_SEC = '1',

FILES_PER_SECOND = '10',
FILE_UPLOADING_RATE = '0.00115428571', // ='0.001428571,
DYNAMIC_LOGIN = 'false',
} = process.env;

Expand Down Expand Up @@ -96,5 +98,8 @@ export const config = {
QUEUED_INQUIRIES_PER_SEC: parseFloat(QUEUED_INQUIRIES_PER_SEC),
TAKE_INQUIRY_PER_SEC: parseInt(TAKE_INQUIRY_PER_SEC),

FILES_PER_SECOND: FILE_UPLOADING_RATE
? parseInt(HOW_MANY_USERS) * parseFloat(FILE_UPLOADING_RATE)
: parseInt(FILES_PER_SECOND),
DYNAMIC_LOGIN: ['true', 'yes'].includes(DYNAMIC_LOGIN),
};
25 changes: 25 additions & 0 deletions src/lib/file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import fs from 'fs';

type FileInformation = {
fileName: string;
fileSize: number;
fileContent: Buffer;
filePath: string;
};

export const getRandomFileInFolder = (folderPath: string): FileInformation => {
const files = fs.readdirSync(folderPath);

const randomIndex = Math.floor(Math.random() * files.length);
const randomFile = files[randomIndex];

const filePath = `${folderPath}/${randomFile}`;
const fileContent = fs.readFileSync(filePath);

return {
fileName: randomFile,
fileSize: fileContent.length,
fileContent,
filePath,
};
};
18 changes: 18 additions & 0 deletions src/profile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ export default (): void => {
openRoom: config.OPEN_ROOM_PER_SECOND,
setUserStatus: config.SET_STATUS_PER_SECOND,
subscribePresence: config.SUBSCRIBE_PRESENCE_PER_SECOND,
uploadFile: config.FILES_PER_SECOND,
});

b.on('ready', async () => {
Expand Down Expand Up @@ -149,6 +150,23 @@ export default (): void => {
await client.listenPresence(userIds);
});

b.on('uploadFile', async () => {
try {
const client = await getLoggedInClient();
const subscription = client.getRandomSubscription();

if (!subscription) {
return;
}

await client.uploadFile({
rid: subscription.rid,
});
} catch (error) {
console.error('Error uploading file', error);
}
});

b.run().catch((e) => {
console.error('Error during run', e);
});
Expand Down