Skip to content

Commit

Permalink
#108 - remove unused file read event handler methods
Browse files Browse the repository at this point in the history
  • Loading branch information
SoulKa committed Oct 31, 2024
1 parent c1bb14c commit 9f76669
Show file tree
Hide file tree
Showing 5 changed files with 7 additions and 95 deletions.
27 changes: 1 addition & 26 deletions src/main/event/main-event-service.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { MainEventService } from './main-event-service';
import path from 'node:path';
import { tmpdir } from 'node:os';
import { fs } from 'memfs';
Expand All @@ -12,7 +11,7 @@ jest.mock('electron', () => ({
},
}));

const eventService = MainEventService.instance;
jest.mock('./stream-events', () => ({}));

const TEST_STRING = 'Hello, World!';
const TEST_FILE_PATH = path.join(tmpdir(), 'test.txt');
Expand All @@ -25,28 +24,4 @@ describe('MainEventService', () => {
it('should register event functions on the backend', async () => {
expect((await import('electron')).ipcMain.handle).toHaveBeenCalled();
});

it('should read the file correctly providing no parameters', async () => {
// Act
const buffer = await eventService.readFile(TEST_FILE_PATH);

// Assert
expect(Buffer.from(buffer).toString()).toBe(TEST_STRING);
});

it('should read the file correctly with offset', async () => {
// Act
const buffer = await eventService.readFile(TEST_FILE_PATH, 1);

// Assert
expect(Buffer.from(buffer).toString()).toBe(TEST_STRING.substring(1));
});

it('should read the file correctly with offset and length', async () => {
// Act
const buffer = await eventService.readFile(TEST_FILE_PATH, 1, 2);

// Assert
expect(Buffer.from(buffer).toString()).toBe(TEST_STRING.substring(1, 3));
});
});
49 changes: 1 addition & 48 deletions src/main/event/main-event-service.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
import { IEventService } from 'shim/event-service';
import { HttpService } from 'main/network/service/http-service';
import { app, ipcMain } from 'electron';
import { FileHandle, open, stat } from 'node:fs/promises';
import { RequestBodyType, RufusRequest } from 'shim/objects/request';
import { Buffer } from 'node:buffer';
import { RufusRequest } from 'shim/objects/request';
import { PersistenceService } from '../persistence/service/persistence-service';
import { RufusObject } from 'shim/objects';
import * as console from 'node:console';
import { EnvironmentService } from 'main/environment/service/environment-service';
import './stream-events';

Expand Down Expand Up @@ -76,35 +73,6 @@ export class MainEventService implements IEventService {
return await HttpService.instance.fetchAsync(request);
}

async readFile(filePath: string, offset = 0, length?: number) {
console.debug(
'Reading file at',
filePath,
'with offset',
offset,
'and length limited to',
length ?? 'unlimited',
'bytes'
);

let file: FileHandle | null = null;
try {
// get file size if length is not provided
if (length === undefined) {
const stats = await stat(filePath);
length = Math.max(stats.size - offset, 0);
}

const buffer = Buffer.alloc(length);
file = await open(filePath);
const read = await file.read(buffer, 0, length, offset);
console.debug('Read', read.bytesRead, 'bytes from file');
return buffer.subarray(0, read.bytesRead).buffer;
} finally {
if (file !== null) await file.close();
}
}

async saveRequest(request: RufusRequest, textBody?: string) {
await persistenceService.saveRequest(request, textBody);
}
Expand All @@ -124,19 +92,4 @@ export class MainEventService implements IEventService {
async deleteObject(object: RufusObject) {
await persistenceService.delete(object);
}

async loadTextRequestBody(request: RufusRequest) {
let text = '';

// TODO: Do not load the entire body into memory. Use ITextSnapshot instead
if (request.body?.type === RequestBodyType.TEXT) {
const stream = await persistenceService.loadTextBodyOfRequest(request);
if (stream == null) return '';
for await (const chunk of stream) {
text += chunk;
}
}

return text;
}
}
10 changes: 5 additions & 5 deletions src/main/network/service/http-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { Readable } from 'stream';
import { EnvironmentService } from 'main/environment/service/environment-service';
import { RequestBodyType, RufusRequest } from 'shim/objects/request';
import { RufusResponse } from 'shim/objects/response';
import { PersistenceService } from '../../persistence/service/persistence-service';
import { PersistenceService } from 'main/persistence/service/persistence-service';
import { RufusHeader } from 'shim/objects/headers';
import { calculateResponseSize } from 'main/util/size-calculation';

Expand All @@ -33,7 +33,7 @@ export class HttpService {
* @returns response object
*/
public async fetchAsync(request: RufusRequest) {
console.info('Sending request: ', request);
console.info('Sending request:', request);

const now = getSteadyTimestamp();
const body = await this.readBody(request);
Expand All @@ -49,12 +49,12 @@ export class HttpService {
});

const duration = getDurationFromNow(now);
console.info(`Received response in ${duration} milliseconds:`, responseData);
console.info(`Received response in ${duration} milliseconds`);

// write the response body to a temporary file
const bodyFile = fileSystemService.temporaryFile();
if (responseData.body != null) {
console.debug('Writing response body to temporary file: ', bodyFile.name);
console.debug('Writing response body to temporary file:', bodyFile.name);
await pipeline(responseData.body, fs.createWriteStream('', { fd: bodyFile.fd }));
console.debug('Successfully written response body');
}
Expand All @@ -73,7 +73,7 @@ export class HttpService {
bodyFilePath: responseData.body != null ? bodyFile.name : null,
};

console.debug('Returning response: ', response);
console.debug('Returning response:', response);
return response;
}

Expand Down
2 changes: 0 additions & 2 deletions src/renderer/services/event/renderer-event-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,12 @@ import { MainProcessError } from '@/error/MainProcessError';

const METHOD_NAMES = new Set<keyof IEventService>([
'saveRequest',
'readFile',
'sendRequest',
'getAppVersion',
'loadCollection',
'saveChanges',
'discardChanges',
'deleteObject',
'loadTextRequestBody',
]);

const INSTANCE = {} as IEventService;
Expand Down
14 changes: 0 additions & 14 deletions src/shim/event-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,6 @@ export interface IEventService {
*/
sendRequest(request: RufusRequest): Promise<RufusResponse>;

/**
* Read a file from the file system.
* @param filePath The path to the file.
* @param offset The offset in the file to start reading from.
* @param length The number of bytes to read.
*/
readFile(filePath: string, offset?: number, length?: number): Promise<ArrayBufferLike>;

/**
* Saves the request to the file system. The draft flag is respected. If a
* body is provided, it is saved as well.
Expand Down Expand Up @@ -59,10 +51,4 @@ export interface IEventService {
* @returns The version of the app
*/
getAppVersion(): Promise<string>;

/**
* Load the text body of the request. The body type must be "text".
* @param request The request to load the text body of.
*/
loadTextRequestBody(request: RufusRequest): Promise<string>;
}

0 comments on commit 9f76669

Please sign in to comment.