Skip to content

Commit

Permalink
feat: added settings for send statics file and fix cork write
Browse files Browse the repository at this point in the history
feat: remove cache realisation for route (reason: more errors)
feat: set version 1.1.7
  • Loading branch information
sanchezzzhak committed Aug 29, 2024
1 parent 6d9b6af commit ddbd1d9
Show file tree
Hide file tree
Showing 9 changed files with 99 additions and 60 deletions.
15 changes: 12 additions & 3 deletions demo/controllers/home.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,13 @@ class HomeController extends AbstractController {

async index() {
this.initRequest();
this.cookieData.set('server-test-cookie', '1', {

let cookieValue = this.cookieData.get('server-test-cookie', 0);

this.cookieData.set('server-test-cookie', parseInt(cookieValue)+1, {
expires: new Date() + 36000
})

return this.renderRaw({
view: `<!DOCTYPE html>
<html>
Expand All @@ -15,8 +19,13 @@ class HomeController extends AbstractController {
</head>
<body>
<h1>Heading</h1>
<a href="/test/redirect">redirect to about page</a>
<a href="/about">about page</a>
<ul>
<li> <a href="/index1.html">get static file</a></li>
<li> <a href="/test/redirect">redirect to about page</a></li>
<li> <a href="/about">about page</a></li>
</ul>
current cookie incr ${cookieValue}
</body>
</html>
`,
Expand Down
8 changes: 5 additions & 3 deletions demo/services/app.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ class AppService extends Service {
name: 'app',
settings: {
port: process.env.SERVER_PORT ?? 3101,
ip: process.env.SERVER_IP ?? '127.0.0.1',
ip: process.env.SERVER_IP ?? 'localhost',
portSchema: process.env.SERVER_SCHEMA ?? 'none',
publicDir: __dirname + '/../statics',
publicIndex: 'index.html',
staticCompress: true,
controllers: {
home: HomeController
}
Expand All @@ -28,8 +30,8 @@ class AppService extends Service {

createService() {
this.createRoute('get /about #c:home.about')
this.createRoute('get / #c:home.index')
this.createRoute('get /test/redirect #c:home.test')
this.createRoute('get / #c:home.index', {})
this.createRoute('get /test/redirect #c:home.test', {})

this.bindRoutes();
}
Expand Down
1 change: 1 addition & 0 deletions demo/statics/index1.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
<head>
<meta charset="UTF-8">
<title>Title</title>
<link href="main.css" rel="stylesheet" />
</head>
<body>
the file static
Expand Down
3 changes: 3 additions & 0 deletions demo/statics/main.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
body {
background: #ccc;
}
11 changes: 11 additions & 0 deletions demo/statics/sub/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link href="/main.css" rel="stylesheet" />
</head>
<body>
the file static for sub
</body>
</html>
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "node-moleculer-web",
"version": "1.1.6",
"version": "1.1.7",
"description": "Fast web app service for moleculer.js + uWebSockets.js",
"main": "src/index.js",
"repository": {
Expand Down
1 change: 1 addition & 0 deletions src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export interface UwsServerSettings {
ip: string;
publicDir: null | string;
publicIndex: boolean | string;
staticCompress: boolean;
portSchema: null | PortSchemaOption;
routes: Array<RouteOptions>;
controllers: {
Expand Down
94 changes: 48 additions & 46 deletions src/utils/uws-send-file.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
const {createBrotliCompress, createGzip, createDeflate} = require('zlib');
const {existsSync, statSync, createReadStream} = require('fs');
const {existsSync, statSync, createReadStream} = require('fs');
const {getMime} = require("./mime");


const compressions = {
br: createBrotliCompress,
gzip: createGzip,
Expand All @@ -14,14 +13,15 @@ const defaultOptions = {
compress: true,
compressionOptions: {
priority: ['gzip', 'br', 'deflate']
}
},
publicIndex: 'index.html'
};

const BYTES = 'bytes=';

function writeHeaders(res, headers) {
for (const n in headers) {
res.writeHeader(n, headers[n].toString());
res.writeHeader(n, headers[n].toString());
}
}

Expand Down Expand Up @@ -50,9 +50,13 @@ async function uwsSendFile(res, req, options = {}) {
let {mtime, size} = stat;

if (!stat.isFile()) {
res.writeStatus('404 Not Found');
res.end();
return false;
if (options.publicIndex && stat.isDirectory() && existsSync(path + '/' + options.publicIndex)) {
path = path + '/' + options.publicIndex
} else {
res.writeStatus('404 Not Found');
res.end();
return false;
}
}

let headers = options.headers;
Expand All @@ -72,11 +76,10 @@ async function uwsSendFile(res, req, options = {}) {
headers['last-modified'] = mtimeutc;
}
headers['content-type'] = getMime(path);


let compressed = options.compress;
let start = 0, end = size - 1;
if (range) {
options.compress = false;
compressed = false;
const parts = range.replace(BYTES, '').split('-');
start = parseInt(parts[0], 10);
end = parts[1] ? parseInt(parts[1], 10) : end;
Expand All @@ -87,9 +90,9 @@ async function uwsSendFile(res, req, options = {}) {

if (end < 0) end = 0;
let readStream = createReadStream(path, {start, end});
let compressed = false;
options.compress = false;
if (options.compress) {


if (compressed) {
const l = options.compressionOptions.priority.length;
for (let i = 0; i < l; i++) {
const type = options.compressionOptions.priority[i];
Expand All @@ -103,39 +106,40 @@ async function uwsSendFile(res, req, options = {}) {
}
}
}

res.onAborted(() => readStream.destroy());

res.cork(() => {
writeHeaders(res, headers);
range && res.writeStatus('206 Partial Content');
})


if (compressed) {
readStream.on('data', buffer => {
res.cork(() => {
res.write(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength));
})
});
} else {

readStream.on('data', buffer => {
const chunk = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength),
lastOffset = res.getWriteOffset();
const chunk = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);

// First try
const [ok, done] = res.tryEnd(chunk, size);
res.cork(() => {
const lastOffset = res.getWriteOffset();
const [ok, done] = res.tryEnd(chunk, size);

if (done) {
readStream.destroy();
} else if (!ok) {
// pause because backpressure
readStream.pause();
if (done) {
readStream.destroy();
return;
}

// Save unsent chunk for later
res.ab = chunk;
res.abOffset = lastOffset;
if (!ok && !done) {
// pause because backpressure
readStream.pause();
// Save unsent chunk for later
res.ab = chunk;
res.abOffset = lastOffset;

res.cork(() => {
// Register async handlers for drainage
res.onWritable(offset => {
const [ok, done] = res.tryEnd(res.ab.slice(offset - res.abOffset), size);
Expand All @@ -146,30 +150,28 @@ async function uwsSendFile(res, req, options = {}) {
}
return ok;
});
})
}

}
})
});
}
readStream
.on('error', e => {
res.cork(() => {
res.writeStatus('500 Internal server error');
res.end();
});
readStream.destroy();
// throw e;
})
.on('end', () => {
res.cork(() => {
res.end();
});
});

readStream
.on('error', e => {
res.cork(() => {
res.writeStatus('500 Internal server error');
res.end();
});
!readStream.destroyed && readStream.destroy();
// throw e;
})
.on('end', () => {
res.cork(() => {
res.end();
});
});

return true;

}


module.exports = uwsSendFile;
24 changes: 17 additions & 7 deletions src/uws-server.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const Uws = require('uWebSockets.js');

const fsPath = require('node:path');
const getNextOpenPort = require('./utils/get-next-open-port');
const uwsSendFile = require('./utils/uws-send-file');
Expand Down Expand Up @@ -41,9 +42,11 @@ const UwsServer = {
settings: {
port: 3000,
ssl: {},
ip: '127.0.0.1',
ip: 'localhost',
publicDir: null,
publicIndex: false, //'index.html'
publicIndex: false, // or 'index.html'
staticCompress: true,
staticLastModified: true,
portSchema: 'node',
routes: [],
controllers: {}
Expand Down Expand Up @@ -115,7 +118,7 @@ const UwsServer = {
const type = match[3] ?? '';
const controller = match[4] ?? '';
const action = match[5] ?? '';
const cache = options.cache ?? 0;
const cache = options.cache ?? -1;
const onBefore = options.onBefore ?? null;
const onAfter = options.onAfter ?? null;

Expand Down Expand Up @@ -149,7 +152,11 @@ const UwsServer = {

if (rootDir) {
this.getServerUws().get('/*', (res, req) => {
const options = {};
const options = {
publicIndex: this.settings.publicIndex,
compress: this.settings.staticCompress,
lastModified: this.settings.staticLastModified,
};
const path = req.getUrl();
if (path === '/' && indexFile) {
options.path = indexFile
Expand All @@ -166,10 +173,13 @@ const UwsServer = {
*/
bindRoutes() {
this.settings.routes.forEach((route) => {

this.getServerUws()[route.method](route.path, async (res, req) => {
res.onAborted(() => {

res.onAborted && res.onAborted(() => {
res.aborted = true;
});

// run before promise
if (route.onBefore) {
await this.Promise.method(route.onBefore, {route, res, req})
Expand Down Expand Up @@ -204,7 +214,7 @@ const UwsServer = {
res.end(result);
});
}
}, route.cache ?? 0);
});
});

this.bindRoutesStatic();
Expand Down Expand Up @@ -277,7 +287,7 @@ const UwsServer = {
this.server = Uws.SSLApp({
key_file_name: this.settings.ssl.keyPath,
cert_file_name: this.settings.ssl.certPath,
ssl_prefer_low_memory_usage: this.server.ssl.prefer_low_memory_usage || faslse
ssl_prefer_low_memory_usage: this.server.ssl.prefer_low_memory_usage || false
});
return;
}
Expand Down

0 comments on commit ddbd1d9

Please sign in to comment.