mirror of
https://github.com/CommunitySolidServer/CommunitySolidServer.git
synced 2024-10-03 14:55:10 +00:00

* feat: implemented SizeReporter and FileSizeReporter * test: FileSizeReporter tests * feat: added QuotedDataAccessor * test: added extra test to check recursiveness of filesizereporter * feat: added QuotaStrategy interface * feat: further progress in different files * feat: wrote doc, tests and improved code * feat: fixed bugs and code is now runnable and buildable * feat: finished implementation * fix: revert accidental chanegs * fix: fileSizeReported did not count container size * fix: bug calculating container sizes fixed * test: FileSizeReporter tests * test: QuotaDataValidator tests * test: QuotaError tests * fix: removed console.log * doc: added doc to several files * doc: changed doc for QuotaStrategy to new implementation * fix: improved content length regex * feat: improved GlobalQuotaStrategy code * fix: made FileSizeReported readonly * feat: added comments to quota-file.json * fix: changed default tempFilePath variable * test: included new tempFilePath variable in testing * chore: created seperate command for start:file:quota to pass tests * feat: removed all sync fs calls from FileSizeReporter * feat: minor changes in multple files * fix: changed function signatures to be in line with others * feat: optimized quota data validation * feat: improved FileSizeReporter code * fix: corrected calculation of containersizes and fixed erroring edgecase * feat: save content-length as number in metadata * feat: added comments and changed GlobalQuotaStrategy constructor * feat: changed file names and added small comment * test: AtomicFileDataAccessor tests * test: completed FileSizeReporter tests * fix: content-length is now saved correctly in RepresentationMetadata * feat: adapted content length metadata + tests * fix: removed tempFilePath variable * fix: reverted .gitignore * fix: forgot to remove tempFilePath variable from componentsjs config * test: GlobalQuotaStrategy tests * feat: replaced DataValidator with Validator * feat: reworked DataValidator * feat: added calcultateChunkSize() to SizeReporter * test: updated FileSizeReporter tests * fix: tempFile location now relative to rootFilePath * test: QuotaDataValidator tests * fix: corrected FileSizeReporter tests * fix: adapted FileSizeReporter tests * fix: FileSizeReporter bug on Windows * fix: regex linting error * feat: changed Validator class * feat: added PodQuotaStrategy to enable suota on a per pod basis * chore: bump context versions * fix: Capitalized comments in json file * chore: renamed ValidatorArgs to ValidatorInput * chore: order all exports * fix: made TODO comment clearer * chore: added seperated config files for global and pod based quota + fixed comments * chore: made minor changes to comments * feat: added PassthroughDataAccessor * feat: added PasstroughtDataAccessor + tests * fix: added invalid header check to ContentLengthParser * chore: improved mocks * chore: move quota limit higher up in config * fix: atomicity issue in AtomicFileDataAccessor * chore: moved .internal folder to config from FileSizeReporter * fix: improved algorithm to ignore folders while calculating file size in FileSizeReporter * fix: changes to support containers in the future * fix: added error handling to prevent reading of unexistent files * feat: added generic type to SizeReporter to calculate chunk sizes * test: use mocked DataAccessor * chore: added some comments to test and made minor improvement * fix: fs mock rename * chore: QuotaStrategy.estimateSize refactor * chore: move trackAvailableSpace to abstract class QuotaStrategy * fix: improved test case * test: quota integration tests * chore: edited some comments * chore: change lstat to stat * feat: moved estimateSize to SizeReporter to be consistent with calcultateChunkSize * test: finish up tests to reach coverage * fix: basic config * fix: minor changes to test CI run * fix: small fix for windows * fix: improved writing to file * chore: linting errors * chore: rename trackAvailableSpace * test: improved integration tests * test: logging info for test debugging * test: extra logging for debugging * test: logging for debugging * test: logging for debugging * test: logging for debugging * test: improved Quota integration test setup * test: improve quota tests for CI run * test: debugging Quota test * test: uncommented global quota test * test: changed global quota parameters * test: logging for debugging * test: logging cleanup * chore: minor changes, mostly typo fixes * chore: remove console.log * fix: getting inconsistent results * chore: try fix index.ts CI error * chore: try fix CI error * chore: try fix CI error * chore: revert last commits * chore: fix inconsistent files with origin * test: minor test improvements * chore: minor refactors and improvements * fix: added extra try catch for breaking bug * chore: improve config * chore: minor code improvements * test: use mockFs * feat: add extra check in podQuotaStrategy * chore: replace handle by handleSafe in ValidatingDataAccessor * chore: typo * test: improved Quota integration tests * test: made comment in test more correct * fix: rm -> rmdir for backwards compatibility * fix: fsPromises issue * chore: leave out irrelevant config * chore: removed start script from package.json * fix: Small fixes Co-authored-by: Joachim Van Herwegen <joachimvh@gmail.com>
223 lines
7.9 KiB
TypeScript
223 lines
7.9 KiB
TypeScript
import { promises as fsPromises } from 'fs';
|
|
import type { Stats } from 'fs';
|
|
import fetch from 'cross-fetch';
|
|
import type { Response } from 'cross-fetch';
|
|
import { joinFilePath, joinUrl } from '../../src';
|
|
import type { App } from '../../src';
|
|
import { getPort } from '../util/Util';
|
|
import { getDefaultVariables, getTestConfigPath, getTestFolder, instantiateFromConfig, removeFolder } from './Config';
|
|
|
|
/** Performs a simple PUT request to the given 'path' with a body containing 'length' amount of characters */
|
|
async function performSimplePutWithLength(path: string, length: number): Promise<Response> {
|
|
return fetch(
|
|
path,
|
|
{
|
|
method: 'PUT',
|
|
headers: {
|
|
'content-type': 'text/plain',
|
|
},
|
|
body: 'A'.repeat(length),
|
|
},
|
|
);
|
|
}
|
|
|
|
/** Registers two test pods on the server matching the 'baseUrl' */
|
|
async function registerTestPods(baseUrl: string, pods: string[]): Promise<void> {
|
|
for (const pod of pods) {
|
|
await fetch(`${baseUrl}idp/register/`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'content-type': 'application/json',
|
|
},
|
|
body: JSON.stringify({
|
|
createWebId: 'on',
|
|
webId: '',
|
|
register: 'on',
|
|
createPod: 'on',
|
|
podName: pod,
|
|
email: `${pod}@example.ai`,
|
|
password: 't',
|
|
confirmPassword: 't',
|
|
submit: '',
|
|
}),
|
|
});
|
|
}
|
|
}
|
|
|
|
/* We just want a container with the correct metadata, everything else can be removed */
|
|
async function clearInitialFiles(rootFilePath: string, pods: string[]): Promise<void> {
|
|
for (const pod of pods) {
|
|
const fileList = await fsPromises.readdir(joinFilePath(rootFilePath, pod));
|
|
for (const file of fileList) {
|
|
if (file !== '.meta') {
|
|
const path = joinFilePath(rootFilePath, pod, file);
|
|
if ((await fsPromises.stat(path)).isDirectory()) {
|
|
await fsPromises.rmdir(path, { recursive: true });
|
|
} else {
|
|
await fsPromises.unlink(path);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
describe('A quota server', (): void => {
|
|
// The allowed quota depends on what filesystem/OS you are using.
|
|
// For example: an empty folder is reported as
|
|
// - 0KB on NTFS (most of the time, mileage may vary)
|
|
// - 0-...KB on APFS (depending on its contents and settings)
|
|
// - 4O96KB on FAT
|
|
// This is why we need to determine the size of a folder on the current system.
|
|
let folderSizeTest: Stats;
|
|
beforeAll(async(): Promise<void> => {
|
|
// We want to use an empty folder as on APFS/Mac folder sizes vary a lot
|
|
const tempFolder = getTestFolder('quota-temp');
|
|
await fsPromises.mkdir(tempFolder);
|
|
folderSizeTest = await fsPromises.stat(tempFolder);
|
|
await removeFolder(tempFolder);
|
|
});
|
|
const podName1 = 'arthur';
|
|
const podName2 = 'abel';
|
|
|
|
/** Test the general functionality of the server using pod quota */
|
|
describe('with pod quota enabled', (): void => {
|
|
const port = getPort('PodQuota');
|
|
const baseUrl = `http://localhost:${port}/`;
|
|
const pod1 = joinUrl(baseUrl, podName1);
|
|
const pod2 = joinUrl(baseUrl, podName2);
|
|
const rootFilePath = getTestFolder('quota-pod');
|
|
|
|
let app: App;
|
|
|
|
beforeAll(async(): Promise<void> => {
|
|
// Calculate the allowed quota depending on file system used
|
|
const size = folderSizeTest.size + 4000;
|
|
|
|
const instances = await instantiateFromConfig(
|
|
'urn:solid-server:test:Instances',
|
|
getTestConfigPath('quota-pod.json'),
|
|
{
|
|
...getDefaultVariables(port, baseUrl),
|
|
'urn:solid-server:default:variable:rootFilePath': rootFilePath,
|
|
'urn:solid-server:default:variable:PodQuota': size,
|
|
},
|
|
) as Record<string, any>;
|
|
({ app } = instances);
|
|
await app.start();
|
|
|
|
// Initialize 2 pods
|
|
await registerTestPods(baseUrl, [ podName1, podName2 ]);
|
|
await clearInitialFiles(rootFilePath, [ podName1, podName2 ]);
|
|
});
|
|
|
|
afterAll(async(): Promise<void> => {
|
|
await app.stop();
|
|
await removeFolder(rootFilePath);
|
|
});
|
|
|
|
// Test quota in the first pod
|
|
it('should return a 413 when the quota is exceeded during write.', async(): Promise<void> => {
|
|
const testFile1 = `${pod1}/test1.txt`;
|
|
const testFile2 = `${pod1}/test2.txt`;
|
|
|
|
const response1 = performSimplePutWithLength(testFile1, 2000);
|
|
await expect(response1).resolves.toBeDefined();
|
|
expect((await response1).status).toEqual(201);
|
|
|
|
const response2 = performSimplePutWithLength(testFile2, 2500);
|
|
await expect(response2).resolves.toBeDefined();
|
|
expect((await response2).status).toEqual(413);
|
|
});
|
|
|
|
// Test if writing in another pod is still possible
|
|
it('should allow writing in a pod that is not full yet.', async(): Promise<void> => {
|
|
const testFile1 = `${pod2}/test1.txt`;
|
|
|
|
const response1 = performSimplePutWithLength(testFile1, 2000);
|
|
await expect(response1).resolves.toBeDefined();
|
|
expect((await response1).status).toEqual(201);
|
|
});
|
|
|
|
// Both pods should not accept this request anymore
|
|
it('should block PUT requests to different pods if their quota is exceeded.', async(): Promise<void> => {
|
|
const testFile1 = `${pod1}/test2.txt`;
|
|
const testFile2 = `${pod2}/test2.txt`;
|
|
|
|
const response1 = performSimplePutWithLength(testFile1, 2500);
|
|
await expect(response1).resolves.toBeDefined();
|
|
expect((await response1).status).toEqual(413);
|
|
|
|
const response2 = performSimplePutWithLength(testFile2, 2500);
|
|
await expect(response2).resolves.toBeDefined();
|
|
expect((await response2).status).toEqual(413);
|
|
});
|
|
});
|
|
|
|
/** Test the general functionality of the server using global quota */
|
|
describe('with global quota enabled', (): void => {
|
|
const port = getPort('GlobalQuota');
|
|
const baseUrl = `http://localhost:${port}/`;
|
|
const pod1 = `${baseUrl}${podName1}`;
|
|
const pod2 = `${baseUrl}${podName2}`;
|
|
const rootFilePath = getTestFolder('quota-global');
|
|
|
|
let app: App;
|
|
|
|
beforeAll(async(): Promise<void> => {
|
|
// Calculate the allowed quota depending on file system used
|
|
const size = (folderSizeTest.size * 3) + 4000;
|
|
|
|
const instances = await instantiateFromConfig(
|
|
'urn:solid-server:test:Instances',
|
|
getTestConfigPath('quota-global.json'),
|
|
{
|
|
...getDefaultVariables(port, baseUrl),
|
|
'urn:solid-server:default:variable:rootFilePath': rootFilePath,
|
|
'urn:solid-server:default:variable:GlobalQuota': size,
|
|
},
|
|
) as Record<string, any>;
|
|
({ app } = instances);
|
|
await app.start();
|
|
|
|
// Initialize 2 pods
|
|
await registerTestPods(baseUrl, [ podName1, podName2 ]);
|
|
await clearInitialFiles(rootFilePath, [ podName1, podName2 ]);
|
|
});
|
|
|
|
afterAll(async(): Promise<void> => {
|
|
await app.stop();
|
|
await removeFolder(rootFilePath);
|
|
});
|
|
|
|
it('should return 413 when global quota is exceeded.', async(): Promise<void> => {
|
|
const testFile1 = `${baseUrl}test1.txt`;
|
|
const testFile2 = `${baseUrl}test2.txt`;
|
|
|
|
const response1 = performSimplePutWithLength(testFile1, 2000);
|
|
await expect(response1).resolves.toBeDefined();
|
|
const awaitedRes1 = await response1;
|
|
expect(awaitedRes1.status).toEqual(201);
|
|
|
|
const response2 = performSimplePutWithLength(testFile2, 2500);
|
|
await expect(response2).resolves.toBeDefined();
|
|
const awaitedRes2 = await response2;
|
|
expect(awaitedRes2.status).toEqual(413);
|
|
});
|
|
|
|
it('should return 413 when trying to write to any pod when global quota is exceeded.', async(): Promise<void> => {
|
|
const testFile1 = `${pod1}/test3.txt`;
|
|
const testFile2 = `${pod2}/test4.txt`;
|
|
|
|
const response1 = performSimplePutWithLength(testFile1, 2500);
|
|
await expect(response1).resolves.toBeDefined();
|
|
const awaitedRes1 = await response1;
|
|
expect(awaitedRes1.status).toEqual(413);
|
|
|
|
const response2 = performSimplePutWithLength(testFile2, 2500);
|
|
await expect(response2).resolves.toBeDefined();
|
|
const awaitedRes2 = await response2;
|
|
expect(awaitedRes2.status).toEqual(413);
|
|
});
|
|
});
|
|
});
|