Coder Social home page Coder Social logo

howprogrammingworks / nodejsstarterkit Goto Github PK

View Code? Open in Web Editor NEW
455.0 67.0 104.0 629 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 sandboxing metarhia

nodejsstarterkit's Introduction

Node.js Starter Kit

Concept

You can begin development from this Starter Kit, but it is not for production usage. The purpose of this Starter Kit is to show simplicity, basic concepts, give structure and architecture examples. All parts of this implementation are optimized for readability and understanding, but not for performance and scalability.

So it is good for development and education. However, for production deployment, you may need the Metarhia Example App an open-source application server on the top of Node.js.

Feature list

  • Pure node.js and framework-agnostic approach
  • Minimum code size and dependencies
  • Layered architecture: core, domain, API, client
  • Protocol-agnostic API with auto-routing, HTTP(S), WS(S)
  • Graceful shutdown
  • Code sandboxing for security, dependency injection and context isolation
  • Serve multiple ports
  • Serve static files with memory cache
  • Application configuration
  • Simple logger
  • Database access layer (Postgresql)
  • Persistent sessions
  • Unit-tests and API tests example
  • Request queue with timeout and size
  • Execution timeout and error handling

Requirements

  • Node.js v16 or later
  • Linux (tested on Fedora, Ubuntu, and CentOS)
  • Postgresql 9.5 or later (v12 preferred)
  • OpenSSL v1.1.1 or later
  • certbot (recommended but optional)

Usage

  1. Fork and clone this repository (optionally subscribe to repo changes)
  2. Remove unneeded dependencies if your project doesn't require them
  3. Run npm ci --production to install dependencies and generate certificate
  4. Add your license to LICENSE file but don't remove starter kit license
  5. Start your project by modifying this starter kit
  6. Run project with node server.js and stop with Ctrl+C

Help

Ask questions at https://t.me/nodeua and post issues on github.

License

Copyright (c) 2020-2023 How.Programming.Works contributors. This starter kit is MIT licensed.

nodejsstarterkit's People

Contributors

amelnik92f avatar belochub avatar lundibundi avatar mihmul83 avatar murka avatar sarnakov avatar tshemsedinov avatar tyanas avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

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

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

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

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.

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();
  }
}

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.

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

Graceful shutdown

For following:

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

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);
  }

...

Simple logger

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

Sandbox pool

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

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.

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

Improve ws API handler

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

Config structure

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

Simple query builder

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

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.