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 all 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.
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
46 changes: 46 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 { getRandomFileFromFolder } 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,39 @@ export class Client {
await this.typing(rid, false);
}

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

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

const { fullPath: filePath } = getRandomFileFromFolder(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' });
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()}`,
},
});

endAction({ status: 'success' });
} catch (e) {
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 +548,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,9 @@ const {
QUEUED_INQUIRIES_PER_SEC = '0.5',
TAKE_INQUIRY_PER_SEC = '1',

FILES_PER_SECOND = '10',
FILE_UPLOADING_RATE = '0,0001', // ~8 files per day per user

DYNAMIC_LOGIN = 'false',
} = process.env;

Expand Down Expand Up @@ -96,5 +99,7 @@ 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),
};
11 changes: 11 additions & 0 deletions src/lib/file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import fs from 'fs';
import path from 'path';

export const getRandomFileFromFolder = (folderPath: string): { fileName: string; fullPath: string } => {
const files = fs.readdirSync(folderPath);

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

return { fileName: randomFile, fullPath: path.join(folderPath, randomFile) };
};
16 changes: 16 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,21 @@ 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(subscription.rid);
} catch (error) {
console.error('Error uploading file', error);
}
});

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