Code Monkey home page Code Monkey logo

egg-guardian's Introduction

egg-guardian

NPM version build status Test coverage David deps Known Vulnerabilities npm download

egg guardian plugin

Install

npm i egg-guardian

Usage

Simple - use default validator and interrupter

Use WorkerQpsJsonRule

Response 429 and JSON to client.

// config/config.default.js
module.exports = {
  guardian: {
    clients: {
      http: {
        rule: [ 'WorkerQpsJsonRule' ]
      },
    },
    rules: {
      WorkerQpsJsonRule: {
        thresholdMap: {
          // Define threshold one worker can handle
          // Format is `${method}-${path}`
          'POST-/foo/:id': 10,
          'GET-/foo': 10,
        },
        // Json interrupter response content
        responseContent: { msg: 'System is busy' },
        // Json interrupter response status code
        responseStatus: 429,
      },
    },
  },
};

Use WorkerQpsRedirectRule

Redirect to specified url.

// config.default.js
module.exports = {
  guardian: {
    clients: {
      http: {
        rule: [ 'WorkerQpsRedirectRule' ]
      },
    },
    rules: {
      WorkerQpsRedirectRule: {
        thresholdMap: {
          // Define threshold one worker can handle
          'POST-/foo/:id': 10,
          'GET-/foo': 10,
        },
        // Redirect interrupter redirect url
        redirectUrl: 'http://foo/server_busy',
      },
    },
  },
};

Use WorkerQpsLogRule.

Print guardian log.

// config.default.js
module.exports = {
  guardian: {
    clients: {
      http: {
        rule: [ 'WorkerQpsLogRule' ]
      },
    },
    rules: {
      WorkerQpsLogRule: {
        thresholdMap: {
          // Define threshold one worker can handle
          'POST-/foo/:id': 10,
          'GET-/foo': 10,
        },
      },
    },
  },
};

Advanced

GuardianLoader

egg-guardian will load app/guardian/interrupter to app.guardianInterrupters, load app/guardian/validator to app.guardianInterrupters. Loader case style is upper, json_interrupter will load to JsonInterrupter.

DefaultInterrupter

JsonInterrupter

Interrupt request, response with JSON content, should set responseStatus(default is 429), responseContent in rule config.

LogInterrupter

Not interrupt request, just print log.

RedirectInterrupter

Interrupt request, redirect to redirectUrl, should set redirectUrl in rule Config.

DefaultValidator

WorkerQpsValidator

If qps is over threshold, mark request should not paas. Should set thresholdMap in rule config.

  1. convert request to requestKey. GET /foo map to GET-/foo
  2. plus requestKey qps.
  3. compare qps with threshold

Define custom validator and interrupter.

  1. Define validator.
// guardian/validator/custom_validator.js
'use strict';

module.exports = app => {
  class CustomValidator extends app.GuardianValidator {
    /**
     * @constructor
     * @params {object} options -
     * @params {Application} options.app -
     * @params {object} config - rule config. `config.guardian.rules.rule`
     */
    constructor(options) {
      super(options);
      this.counter = 0;
      // ready(true) is required. Rule will wait to validator is ready.
      this.ready(true);
    }

    /**
     * validate before process request
     * @param {Context} ctx -
     * @return {Promise<Boolean>} request can be passed
     */
    async preValidate(ctx) {
      return true;
    }

    /**
     * validate after process request
     * @param {Context} ctx -
     * @return {Promise<Boolean>} request can be passed
     */
    async sufValidate() {
      return this.counter++ % 2 === 0;
    }
  }
};
  1. Define interrupter.
// guardian/interrupter/custom_interrupter.js
'use strict';

module.exports = app => {
  return class CustomInterrupter extends app.GuardianInterrupter {
    /**
     * @constructor
     * @params {object} options -
     * @params {Application} options.app -
     * @params {object} config - rule config. `config.guardian.rules.rule`
     */
    constructor(options) {
      super(options);
      // ready(true) is required. Rule will wait to interrupter is ready.
      this.ready(true);
    }

    /**
     * interrupt request
     * @param {Context} ctx -
     * @return {boolean} - should continue process
     */
    async interrupt(ctx) {
      ctx.status = 429;
      return false;
    }
  };
};
  1. Define rule.
// config/config.default.js
module.exports = {
  guardian: {
    clients: {
      http: {
        // Use custom rule
        rules: [ 'CustomRule' ],
      },
    },
    rules: {
      // Define custom rule
      CustomRule: {
        interrupter: 'CustomInterrupter',
        validator: 'CustomValidator',
      },
    },
  },
};

License

MIT

egg-guardian's People

Contributors

killagu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

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

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.