tspace-nfs
Version:
tspace-nfs is a Network File System (NFS) and provides both server and client capabilities for accessing files over a network.
198 lines • 9.82 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.NfsServer = void 0;
const xml_1 = __importDefault(require("xml"));
const node_cron_1 = __importDefault(require("node-cron"));
const os_1 = __importDefault(require("os"));
const tspace_spear_1 = require("tspace-spear");
const server_studio_1 = require("./server.studio");
/**
* The 'NfsServer' class is a created the server for nfs
*
* @example
* import { NfsServer } from "tspace-nfs";
*
* new NfsServer()
* .listen(8000 , ({ port }) => console.log(`Server is running on port http://localhost:${port}`))
*/
class NfsServer extends server_studio_1.NfsStudio {
/**
* The 'listen' method is used to bind and start a server to a particular port and optionally a hostname.
*
* @param {number} port
* @param {function} callback
* @returns
*/
listen(port, callback) {
this._app = new tspace_spear_1.Spear({
cluster: this._cluster
});
this._app.cors({
origins: ['*'],
credentials: true
});
this._app.useLogger({
exceptPath: /\/benchmark(\/|$)|\/favicon\.ico(\/|$)/
});
this._app.useBodyParser();
this._app.useCookiesParser();
this._app.useFileUpload({
limit: Infinity,
tempFileDir: 'tmp',
removeTempFile: {
remove: true,
ms: 1000 * 60 * 60 * 2
}
});
this._router = new tspace_spear_1.Router();
this._router.get('/', this._default);
this._router.get('/benchmark', this._benchmark);
this._router.groups('/api', (router) => {
router.post('/connect', this._apiConnect);
router.post('/health-check', this._apiHealthCheck);
router.post('/storage', this._authMiddleware, this._apiStorage);
router.post('/file', this._authMiddleware, this._apiFile);
router.post('/folders', this._authMiddleware, this._apiFolders);
router.post('/base64', this._authMiddleware, this._apiBase64);
router.post('/stream', this._authMiddleware, this._apiStream);
router.post('/remove', this._authMiddleware, this._apiRemove);
router.post('/upload', this._authMiddleware, this._apiUpload);
router.post('/upload/merge', this._authMiddleware, this._apiMerge);
router.post('/upload/base64', this._authMiddleware, this._apiUploadBase64);
return router;
});
if (this._onStudioCredentials != null) {
this._router.groups('/studio', (router) => {
router.get('/', this.studio);
router.post('/api/login', this.studioLogin);
router.get('/api/storage', this._authStudioMiddleware, this.studioStorage);
router.get('/preview/*', this._authStudioMiddleware, this.studioPreview);
router.get('/api/preview/*', this._authStudioMiddleware, this.studioPreviewText);
router.patch('/api/preview/*', this._authStudioMiddleware, this.studioPreviewTextEdit);
router.delete('/api/logout', this._authStudioMiddleware, this.studioLogout);
router.get('/api/buckets', this._authStudioMiddleware, this.studioBucket);
router.post('/api/buckets', this._authStudioMiddleware, this.studioBucketCreate);
router.get('/api/files/*', this._authStudioMiddleware, this.studioFiles);
router.put('/api/files/*', this._authStudioMiddleware, this.studioEdit);
router.delete('/api/files/*', this._authStudioMiddleware, this.studioRemove);
router.post('/api/upload', this._authStudioMiddleware, this.studioUpload);
router.post('/api/download', this._authStudioMiddleware, this.studioDownload);
router.get('/shared/*', this.studioShared);
router.get('/api/shared/*', this._authStudioMiddleware, this.studioGetPathShared);
return router;
});
}
else {
this._router.get('/studio', ({ req, res }) => {
res.writeHead(403, { 'Content-Type': 'text/xml' });
const error = {
Error: [
{ Code: 'Forbidden' },
{ Message: 'The request was denied by service, Please enable to use studio mode' },
{ Resource: req.url },
]
};
return res.end((0, xml_1.default)([error], { declaration: true }));
});
}
this._router.get('/:bucket/*', this._media);
this._app.useRouter(this._router);
this._app.notfound(({ req, res }) => {
res.writeHead(404, { 'Content-Type': 'text/xml' });
const error = {
Error: [
{ Code: 'Not found' },
{ Message: 'The request was invalid' },
{ Resource: req.url },
]
};
return res.end((0, xml_1.default)([error], { declaration: true }));
});
this._app.response((results, statusCode) => {
if (typeof results === 'string')
return results;
return Object.assign(Object.assign({ success: statusCode < 400 }, results), { statusCode });
});
this._app
.catch((err, { req, res }) => {
if (this._debug) {
console.log(err);
}
return res.status(400)
.json({
success: false,
message: err.message,
statusCode: 400,
});
});
this._app.listen(port, ({ port, server }) => {
if (this._buckets != null) {
node_cron_1.default.schedule('0 0 0 * * *', () => __awaiter(this, void 0, void 0, function* () {
console.clear();
const buckets = this._buckets == null ? [] : yield this._buckets();
for (const bucket of buckets) {
this._queue.add(() => this._utils.removeOldDirInTrash(bucket));
}
}));
}
if (this._monitors != null) {
try {
const logCpuAndMemoryUsage = () => {
var _a, _b;
const memoryUsage = process.memoryUsage();
const totalMemory = os_1.default.totalmem();
const cpus = os_1.default.cpus();
const usageData = cpus.map(cpu => {
const total = Object.values(cpu.times).reduce((acc, time) => acc + time, 0);
const active = total - cpu.times.idle;
return (active / total) * 100;
});
const overallMax = Number(Number(Math.max(...usageData)).toFixed(4));
const overallMin = Number(Number(Math.min(...usageData)).toFixed(4));
const overallAvg = Number(Number(usageData.reduce((acc, usage) => acc + usage, 0) / usageData.length).toFixed(4));
if (this._monitors != null) {
const toMB = (v) => Number(Number(v / 1024 / 1024).toFixed(4));
this._monitors({
host: ((_a = process.env) === null || _a === void 0 ? void 0 : _a.HOSTNAME) == null ? null : String((_b = process.env) === null || _b === void 0 ? void 0 : _b.HOSTNAME),
memory: {
total: toMB(totalMemory),
heapTotal: toMB(memoryUsage.heapTotal),
heapUsed: toMB(memoryUsage.heapUsed),
external: toMB(memoryUsage.external),
rss: toMB(memoryUsage.rss)
},
cpu: {
total: cpus.length,
max: overallMax,
min: overallMin,
avg: overallAvg,
speed: cpus
.map((cpu) => cpu.speed / 1000)
.reduce((acc, usage) => acc + usage, 0) / cpus.length
}
});
}
};
setInterval(logCpuAndMemoryUsage, 5000);
}
catch (e) { }
}
return callback == null ? null : callback({ port, server });
});
}
}
exports.NfsServer = NfsServer;
exports.default = NfsServer;
//# sourceMappingURL=index.js.map