GithubHelp home page GithubHelp logo

howprogrammingworks / nodejsstarterkit Goto Github PK

View Code? Open in Web Editor NEW
459.0 68.0 104.0 549 KB

Starter Kit for Node.js 16 or later, minimum dependencies ๐Ÿš€

Home Page: http://metarhia.com

License: MIT License

JavaScript 92.43% HTML 3.03% CSS 4.15% Shell 0.39%
nodejs node starter-kit server api project boilerplate threads cloud cluster

nodejsstarterkit's Issues

Request execution queue

  • Configuration parameters: { size: Number, timeout: Number }
  • Wait in queue implementation (N requests)
  • Error message on queue overflow
  • Integrate with execution timeout #15
  • Add to feature list

Note: execution timeout and queue timeout are not the same timeouts

Don't forget to test queue in end-to-end tests #11

Simple query builder

  • async select(table, fields, where)
  • async insert(table, record)
  • async update(table, delta, where)
  • async delete(table, where)

Server initialization order

  1. Load core layer modules
  2. Load internal node.js dependencies
  3. Load external dependencies (installed from npm)
  4. Create Application instance
  5. Create Config instance
  6. Create Logger instance and wait for open event
  7. Load lib layer modules
  8. Connect to database
  9. Load domain layer, api methods and init scripts
  10. Open server ports for listening

Sandbox pool

We can prepare N sandboxes in pool to speed up session starting

Potential semaphore queue overflow of expired tasks

If getting 'Semaphore timeout' exception in those 2 methods(Client.apiws and Client.api) we don't reach semaphore.leave. Therefore request which was added to the queue, it wouldn't be removed from the queue. And soon the queue will be busy with tasks with an expired timer

  async api() {
    const { semaphore } = this.application.server;
    await semaphore.enter();
    // ....
  /* Lets assume, we getting 'Simaphore timeout' and this error won't be handled by this method
  So we won't be able to reach semaphore.leave()
  */    
    try {
    // ...
      const proc = this.application.runScript(method, sandbox);
      const result = await proc(context)(args);
   // ...
    } catch (err) {
      this.application.logger.error(err.stack);
      this.error(this.res, err.message === 'Not found' ? 404 : 500);
    }
    semaphore.leave();
  }
}

Simple logger

Support logging from sandboxes with console interface wrapped and injected.
No logs rotation support.

Session-level sandboxes

After session started all requests should be sandboxed in a session sandbox.
Now we have shared sandbox for all API methods in application, see: #3
This shared sandbox will be used just for requests without sessions.

Decompose Server class

Here are following options:

  • Class Server and two subclasses: HttpServer and WsServer
  • Rewrite without classes just functions
  • Extract almost all functions but use outer classes to preserve interfaces
  • Use strategy pattern
  • Implement Client class

Implement dependency injection in core

We need to pass application to all core modules not with aggregation (as we implemented this in v1) but with dependency injection, so we can use either global or sandbox context.

Config structure

Use ({ field: 'value' }); instead of module.exports = { field: 'value' };

Layered architecture

Layer Description Directory
core loader, multi-threading, sandboxing, general purpose tools ./lib
domain layer for domain model and processes ./domain
api external network interface ./api
client browser api to wrap websocket and hide rpc calls ./static

Path separator in Windows

In Windows, the fs.reader method gets paths like '\index.html' while the static() method waits '/index.html'

./lib/application.js

...
  async cacheDirectory(directoryPath) {
    const files = await fsp.readdir(directoryPath, { withFileTypes: true });
    for (const file of files) {
      const filePath = path.join(directoryPath, file.name);
      if (file.isDirectory()) await this.cacheDirectory(filePath);
      else await this.cacheFile(filePath);
    }
    fs.watch(directoryPath, (event, fileName) => {
      const filePath = path.join(directoryPath, fileName);
      this.cacheFile(filePath);
    });
  }
...

./lib/server.js

...
class Client {
  constructor(req, res, application) {
    this.req = req;
    this.res = res;
    this.application = application;
  }

  static() {
    const { url } = this.req;
    const filePath = url === '/' ? '/index.html' : url;
    const fileExt = path.extname(filePath).substring(1);
    const mimeType = MIME_TYPES[fileExt] || MIME_TYPES.html;
    this.res.writeHead(200, { 'Content-Type': mimeType });
    const data = this.application.cache.get(filePath);
    if (data) this.res.end(data);
    else this.error(404);
  }

...

Request execution timeout

  • Configuration parameters: { timeout: Number }
  • Timeout implementation
  • Add to feature list

Don't forget to test timeout in end-to-end tests #11

Improve ws API handler

We need everything we have in lib/server.js/Client.api in lib/server.js/apiws: sessions, context passing.

Prepare contract specifications

All parts of this kit will be described as a contract to be implemented and replaced easily even by third-party developers. We will prepare tests for contracts and integration tests to be sure parts will work together.

Graceful shutdown

For following:

  • Changing system code layer (domain code will autoreloaded)
  • Update dependencies
  • Restart hardware server

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.