Code Monkey home page Code Monkey logo

kong-js-pdk's Issues

Add some insights in the docs about the performance impact of using JS plugins

Adding some insights in the docs (README and Kong official docs) about the expected impact on performance when using JS plugins would be nice even though they are slower than plugins written in Lua.

Also adding some tips, recommendations or even samples on how to perform automated load testing for JS plugins would be very useful.

Problem reading gzipped kong.service.response.get_raw_body()

I have been trying to read the kong.service.response.get_raw_body() in a kong js plugin.
I'm able to read the data fine when it's not gzipped.
However, when the response is gzipped, I'm unable to gunzip.

const rawBodyCompressed = await kong.service.response.getRawBody();
const rawBodyUncompressed = zlib.gunzipSync(rawBodyCompressed);

I wrote a version of the plugin in lua and was able to perform the task successfully.

local rawBodyCompressed = kong.service.response.get_raw_body()
local rawBodyUncompressed = zlib.inflate()(rawBodyCompressed)

When I compared the base64 encodings of both the js and lua responses from kong.service.response.get_raw_body() I found they did not match. Which to me points to an issue with the pdk, but I'm not 100% sure.

If any assistance can be provided in trying to rectify this problem I'm experiencing, it would be greatly appreciated.

Add "Version" as named property in "GetPluginInfo"

Hey folks, great work here! We're encountering a problem when a js-pdk plugin is pushed out to data planes over the clustering connection. Not sure if this is a new problem or not, but the Data Planes each report the LUA error:

Kong: Attempt to index field 'version' (a nil value)

Digging into it I can see that the version of the plugin is not provided as part of the GetPluginInfo method. The following fix addresses this (I've got a branch ready if you're taking PRs!)

  async GetPluginInfo(name) {
    if (this.plugins[name] === undefined) {
      return Promise.reject(new PluginServerError(name + " not initialized"))
    }

    let plugin = this.plugins[name]

    return {
      Name: name,
      + Version: plugin.getVersion(),
      Phases: plugin.getPhases(),
      Priority: plugin.getPriority(),
      Schema: {
        name: name,
        fields: [{
          config: {
            type: "record",
            fields: plugin.getSchema(),
          }
        }],
      },
    }
  }

Kong unable to load js plugin

Trying to load a simple plugin as an experiment, but kong is always crashing when trying to introspect the plug and isn't apparently obvious as to why

ingress-kong-8f894f697-8g5qb kong-proxy nginx: [error] init_by_lua error: ...al/share/lua/5.1/kong/runloop/plugin_servers/process.lua:159: Not a plugin info table: 
ingress-kong-8f894f697-8g5qb kong-proxy /usr/local/bin/kong-js-pluginserver --plugins-directory /home/kong/plugins --dump-all-plugins
ingress-kong-8f894f697-8g5qb kong-proxy plugin loaded
ingress-kong-8f894f697-8g5qb kong-proxy [{"Name":"fake","Version":"1.0.0","Phases":["access"],"Priority":0,"Schema":{"name":"fake","fields":[{"config":{"type":"record","fields":[{"header":{"type":"string"}}]}}]}}]
ingress-kong-8f894f697-8g5qb kong-proxy 
ingress-kong-8f894f697-8g5qb kong-proxy stack traceback:
ingress-kong-8f894f697-8g5qb kong-proxy         [C]: in function 'error'
ingress-kong-8f894f697-8g5qb kong-proxy         ...al/share/lua/5.1/kong/runloop/plugin_servers/process.lua:159: in function 'ask_info'
ingress-kong-8f894f697-8g5qb kong-proxy         ...al/share/lua/5.1/kong/runloop/plugin_servers/process.lua:195: in function 'get_plugin_info'
ingress-kong-8f894f697-8g5qb kong-proxy         ...local/share/lua/5.1/kong/runloop/plugin_servers/init.lua:262: in function 'get_plugin'
ingress-kong-8f894f697-8g5qb kong-proxy         ...local/share/lua/5.1/kong/runloop/plugin_servers/init.lua:270: in function 'load_plugin'
ingress-kong-8f894f697-8g5qb kong-proxy         /usr/local/share/lua/5.1/kong/db/dao/plugins.lua:136: in function 'load_plugin_handler'
ingress-kong-8f894f697-8g5qb kong-proxy         /usr/local/share/lua/5.1/kong/db/dao/plugins.lua:221: in function 'load_plugin'
ingress-kong-8f894f697-8g5qb kong-proxy         /usr/local/share/lua/5.1/kong/db/dao/plugins.lua:273: in function 'load_plugin_schemas'
ingress-kong-8f894f697-8g5qb kong-proxy         /usr/local/share/lua/5.1/kong/init.lua:515: in function 'init'
ingress-kong-8f894f697-8g5qb kong-proxy         init_by_lua:3: in main chunk

Kong Config

 - name: KONG_PLUGINS
   value: bundled,fake
 - name: KONG_PLUGINSERVER_NAMES
   value: js
 - name: KONG_PLUGINSERVER_JS_SOCKET
   value: /usr/local/kong/js_pluginserver.sock
 - name: KONG_PLUGINSERVER_JS_START_CMD
   value: /usr/local/bin/kong-js-pluginserver --plugins-directory /home/kong/plugins
 - name: KONG_PLUGINSERVER_JS_QUERY_CMD
   value: /usr/local/bin/kong-js-pluginserver --plugins-directory /home/kong/plugins --dump-all-plugins

Plugin Directory

plugins/
├── fake.js
├── package.json
└── package-lock.json

Plugin Code

'use strict'

const uuid = require('uuid')
const {version: Version} = require('./package.json')

class Plugin {
  constructor(config = {}) {
    this.config = config
    this.header = config.header || 'X-Request-ID'
  }

  async access(kong) {
    await kong.response.set_header(this.header, uuid())
  }
}
console.log('plugin loaded')
module.exports = {
  Plugin
, Version
, Priority: 0
, Schema: [
    {header: { type: "string" }}
  ]
}

Plugin Config

apiVersion: configuration.konghq.com/v1
kind: KongPlugin
plugin: fake
metadata:
  name: fake-id
config:
  header: 'X-Fake-ID-1'

Issues running tests

I'm trying to run tests for my plugin but I'm facing several issues that prevents having working tests:

  • ReferenceError: Headers is not defined -> I had to polyfill Headers with global.Headers = global.Headers || require('fetch-headers');
  • function kong.response.error is not a valid PDK function even if it works when I actually try the plugin, and is a documented function
  • .useURL('http://example.com') throws a Exceeded timeout of 5000 ms for a test error

This is the test I'm trying to run:

const { PluginTest, Request } = require('kong-pdk/plugin_test');
global.Headers = global.Headers || require('fetch-headers');

const plugin = require('./api-key-auth');

test('Set headers in response', async () => {
  const request = new Request();

  request
    .useURL('http://example.com')
    .useMethod('GET')
    .useHeaders({
      'x-api-key': 'abcde',
    })
    .useBody('OK');

  const pluginTest = new PluginTest(request);

  await pluginTest.Run(plugin, {});

  expect(pluginTest.response.status)
    .toBe(200);
});

Question: How to wrote Unit tests using plugin_test.js

from the docs

kong-js-pdk provides a mock framework to test plugin code correctness through jest.

there are examples in the repo - https://github.com/Kong/kong-js-pdk/blob/master/__tests__/js-hello.test.js

however when I try to setup something simple myself I seem to fall over at the first hurdle

Kong = require('kong-pdk');
Uncaught:
Error: Cannot find module '/Users/....../node_modules/kong-pdk/app.js'. Please verify that the package.json has a valid "main" entry

and I think this is actually a valid error because the current package.json shows app.js as the main entry point https://github.com/Kong/kong-js-pdk/blob/master/package.json#L5 and there are no app.js files in the repo.

Before I make a pull request to try and clean things up a little I just wanted to check im not missing something basic.

Create consumer in real-time

I'm building a custom authentication plugin based on api keys, and I was wondering if there's a way to create consumers once I get an 'OK' from my internal authentication system. This would allow me avoiding syncing Kong db with my auth system.

One idea was to use the kong.db and create consumers manually, but there's no api for db on kong-js-pdk.
A possible solution would be to add a postgreSQL client like https://node-postgres.com/ to my plugin and do queries directly.

Is there a more elegant solution for this?

Thanks

Unable to access environment variables from a plugin using `process.env`

I am unable to access environment variables in my plugin using process.env.<var_name>.

Logging process.env returns table: 0x7f3bb3b346f0, and JSON.stringify(process.env returns {"SHLVL":"1","PWD":"/"}.

execing into the Kong container and running printenv I can see the full list of environment variables that were set when Kong was deployed.

I was hoping to use environment variables to retrieve the password for an external Redis cache used by a plugin.

Reference to a incorrect module functions

on version 0.4.2 of the pdk, there seems to be a reference to the wrong msgpack module

ps.GetPluginInfo(opts.DumpPluginInfo)
.then((v) => {
process.stdout.write(msgpack.pack(v))
})

The pack function is a member of the top level msgpack module, but this is using the @msgpack/msgpack which only has encode / decode functions

/usr/local/bin/kong-js-pluginserver --dump-plugin-info fake -d /home/kong/plugins

UnhandledPromiseRejectionWarning: TypeError: msgpack.pack is not a function
    at /usr/local/lib/node_modules/kong-pdk/bin/kong-js-pluginserver:23:36
    at processTicksAndRejections (internal/process/task_queues.js:95:5)

loadConsumer returns undefined

I'm trying to retrieve a consumer both with const consumer = await kong.client.loadConsumer('<uuid>'); and const consumer = await kong.client.loadConsumer('<username>', true); but consumer is always undefined (the uuid and username I'm trying are on db obviously).
What am I doing wrong?

cannot serialize object to string

When I call get Object from API then I want to log Obj by kong.log.debug()
here is my code

async access(kong) {
await kong.response.setHeader("Cache-access", new Date().toISOString());
await axios
.get("https://microsoftedge.github.io/Demos/json-dummy-data/64KB.json")
.then(function (response) {
kong.log.debug("axios.get", " Success");
kong.log.debug("axios.get", JSON.stringify(response));
})
.catch(function (error) {
kong.log.err("axios.get ", " err");
// handle error
})
.finally(function () {
// always executed
kong.log.debug("axios.get ", " finally");
});
}

check it shows log "axios.get Success" but the next line is "axios.get err"
I try to use another lib from npm example JSON5 but it always shows an error
Can you help me how to serialize the object to string to trace log

Simplify Module Loading

There is a chunk of code that is trying to distinguish between a file, and a module (a plugin interface) and I think it is all a bit more complicated than it needs to be. Additionally the complexity actually forces plug-in implementors to organize their code in a specific way that is restrictive and not very intuitive from a Node.js perspective. A file is a module.

kong-js-pdk/server.js

Lines 45 to 69 in c3f9921

fs.readdirSync(this.pluginDir).forEach(file => {
let p = path.join(this.pluginDir, file)
if (fs.statSync(p).isDirectory()) {
return
}
let f = /(.+)\.([^.]+)$/.exec(file)
let name = f && f[1]
let ext = f && f[2]
if (!f || name === undefined || (ext !== 'js' && ext != 'ts') || name.endsWith(".test")) {
return
}
if (this.plugins[name]) {
this.logger.warn("plugin \"" + name + "\" is already imported from " + this.plugins[name].path +
", trying to reimport from " + p)
return
}
try {
let m = new Module(name, p)
this.logger.debug("loaded plugin \"" + name + "\" from " + p)
this.plugins[name] = m
} catch (ex) {
this.logger.warn("error loading plugin \"" + name + "\" from " + p + ": " + ex.stack)
}

There are a couple of issues that seem overly restrictive.

it ignores directories.

That mean my code must be organized as such

plugins/
├─ lib/
│  └─ index.js
├─ plugin-one.js
├─ plugin-two.js
├─ plugin-three.js
└─ package.json

The downside to this is that all of these plugins have to share the same dependency space and in all likelihood implementation code. As these plugins become more complex and the number of plugins grows, this becomes difficult to maintain. What I want is a logical separation

plugins/
├─ plugin-one/
│  ├─ lib/
│  │  └─ index.js
│  ├─ index.js
│  └─ package.json
├─ plugin-two/
│  ├─ lib/
│  │  └─ index.js
│  ├─ index.js
│  └─ package.json
└─ plugin-three/
   ├─ lib/
   │  └─ index.js
   ├─ index.js
   └─ package.json

One level is sufficient. I don't think it needs to be any more complicated or clever than that

It ignores Native Add on code

   if (!f || name === undefined || (ext !== 'js' && ext != 'ts') || name.endsWith(".test")) { 
     return 
   } 

This tries to load specifically .js and .ts file extensions. Additionally tries to bain if there is a .test in it.
From my perspective this is making too many assumptions about how I may or may not organize my code base. I may have test code in files that don't have a .test in the file name. To the point, this project uses _test. I personally put tests in a directory called test.

It also prohibits me from building Native Addons w/ C/C++, rust, etc. Those typically have a file extension.

  • Just let require load the files. If it can load it, it will. if it can, it'll error.

It doesn't allow for globally installed modules

kong-js-pdk/lib/mod.js

Lines 14 to 28 in c3f9921

if (path !== undefined) {
let f = /(.+)\.([^.]+)$/.exec(path)
if (f[1] === undefined) {
throw new Error(path + " doesn't contain a split")
}
mod = require(f[2].toLowerCase() == "js" ? f[1]: path)
this.mod = mod
this.mtime = fs.statSync(path).mtime.getTime() / 1000
} else if (module !== undefined) {
mod = module
// use mtime of current script instead
this.mtime = fs.statSync(__filename).mtime.getTime() / 1000
} else {
throw new Error("either path or module needs to be passed in")
}

There is a lot of restrictive code here trying to take a string or plugin interface object, but its assuming if it is a string its a file path. It could also be a module name. The require function does a lot of heavy lifting, I think much of this should just be delegated to require. The logic should really validate that the object being loaded is of the right shape / data types rather than restrict file extension.

if string:
  require(string)
  validate loaded object

else if object:
  validate object

else:
  error

This would allow me to install a plugin globally, or even locally in package.json and reference it by name rather than having to discover its actual file path location.

npm install -g @kong/pdk @my-org/kong-plugin-one @my-org/kong-plugin-two
pluginserver_names = js_one,js_two
pluginserver_js_one_socket = /usr/local/kong/js_pluginserver.sock
pluginserver_js_one_start_cmd = /usr/local/bin/kong-js-pluginserver --plugins @my-org/kong-plugin-one
pluginserver_js_one_query_cmd = /usr/local/bin/kong-js-pluginserver --plugins @my-org/kong-plugin-one --dump-all-plugins

pluginserver_js_two_socket = /usr/local/kong/js_pluginserver.sock
pluginserver_js_two_start_cmd = /usr/local/bin/kong-js-pluginserver --plugins @my-org/kong-plugin-two
pluginserver_js_two_query_cmd = /usr/local/bin/kong-js-pluginserver --plugins @my-org/kong-plugin-two --dump-all-plugins

Plugin loading is very disk intensive

  1. Check if the plugin path exists
  2. Try to read the path, and all the files in it
  3. Stat each file
  4. require each file
  5. Stat each file again (to get mtime)

its a bit expensive and slow. Much of the checking for existence and stat calls can be removed. The readdir call won't return file paths that don't exist. if you pass the withFileTypes option, you'll get back dirint objects which can tell you if it is a file or directory. But I'm still not sure you need to know if you lean on require more.

I think the mtime lookups could probably come out - Unless the kong server requires this, I'm not seeing it to be very useful.

Server tries to load all files in the folder as a plugin and fails to start

I'm trying to upgrade to the latest version 0.5.3 but I'm facing this issue.
I have a bunch of files like .nyc_output .gitignore and some tests, but when I try to start Kong it now errors out with this error:
Error: Cannot find module '/usr/local/kong/plugins/.nyc_output'
I tried eliminating some of these files, but for example it then tries to load the tests folder as a plugin :(
Error: Cannot find module '/usr/local/kong/plugins/__tests__'

I'm launching the server with these two configs:

pluginserver_js_start_cmd = /usr/local/kong/plugins/node_modules/kong-pdk/bin/kong-js-pluginserver -v --plugins-directory /usr/local/kong/plugins

pluginserver_js_query_cmd = /usr/local/kong/plugins/node_modules/kong-pdk/bin/kong-js-pluginserver --plugins-directory /usr/local/kong/plugins --dump-all-plugins

What should I do to fix this?

It worked correctly on version 0.4.4

Modifying response body (no body_filter phase?)

Hi, I would like to check if it is currently possible to modify the response body with a Javascript plugin? The body_filter phase does not appear to be available and calling getRawBody in response does not work (in the docs it says it is a replacement for both header_filter and body_filter so I expected it to work there).

Question: How to see plugin error inside docker container logs

Hi all, just a question from my side. I am running Kong with a custom js plugin in a Docker container. For some reason, Docker is failing to start, I only see this log output in my console. Side info, I am using RancherDesktop with nerdctl.

kong-with-js-plugin |2023/04/12 16:47:15 [debug] 1#0: [lua] globalpatches.lua:306: randomseed(): seeding PRNG from OpenSSL RAND_bytes()
INFO[0002] Container "kong-with-js-plugin" exited       
INFO[0002] All the containers have exited               
INFO[0002] Stopping containers (forcibly)               
INFO[0002] Stopping container kong-with-js-plugin 

Any tips from your side on how can I debug what is actually failing in my plugin? It would be really helpful for my further development.

I tested my setup with the small js plugin and it works, which confirms that my plugin paths are ok. Currently what I am trying to do is to build a ts plugin and compile it to js using tsc. So far worked. A problem occurred when I created an additional ts file with helper functions inside. Importing those functions inside my-plugin.ts brakes my setup.

Here is how it looks like

/usr/local/kong/js-plugins/
  node_modules
  package.json
  my-plugin.js
  libs/
     helpers.ts
# my-plugin.js
import { sayItOutloud } from "./lib/helpers";

async access(kong: any) {
  const test = new sayItOutloud();
  console.log(test.sayHello("Max"));
}
# helpers.ts
export class sayItOutloud {
  sayHello(user) {
    return "Hello " + user + "!";
  }
}

Any tip would be appreciated! Thank you

Critical severity alert on msgpack dependency

Hello!

Just started using this project and I got a critical severity alert for the msgpack dependency that this project is using.
Not sure if it has been reported yet, but I can't find any issues opened or closed about it, so I thought I would point that out to you guys.
Here is a screenshot of the issue:
image

How to cache stuff?

Is there a clean way to cache things with js plugins in Kong? Or I should use some npm package + redis or something?

Thanks

Incorrect assignment of mocked log functions in plugin_test.js

I was writing tests for a Kong JS Plugin, and encountered Error: function kong.log.err is not a valid PDK function whenever the plugin tried to interact with await kong.log.err("insert-error-here");.

After looking into the code, I found the mockFunctions in plugin_test.js where assigned under the index not the value of the elements in logFunctions.

I traced the issue to the for-in loop the returning the index not the value of the elements of logFunctions.

I have raised a PR which to the best of my knowledge fixes the assignment to use the name and not the index by using a basic for loop.

I hope these changes are good enough to be merged into the mainline.
If not the feedback would be appreciated.

#143

package.json no longer includes files for plugin_test.js

On version 0.5.0 the package.json has been modified to include only specific files, from this list the plugin_test.js has been left out. Meaning it is no longer possible for users of the repo to construct their own unit tests utilising the plugin_test functionality.

Adding samples of unit tests and integration tests for JS plugins examples

Adding samples of unit tests and integration tests for JS plugins examples would be nice to promote the development of well tested plugins, including coverage checking and SonarQube support in the examples. Considering that the Lua plugins from Kong template have Pongo (busted) configured in it, i think the JS samples could follow a similar path.

Missing plugin socket

I'm not sure if this is the right place, But recently after updating to kong 3.2.2, I started seeing ciritical errors at start up

2023/05/18 15:33:19 [notice] 1206#0: *148 [kong] process.lua:252 Starting js, context: ngx.timer
2023/05/18 15:33:19 [crit] 1206#0: *149 connect() to unix:/usr/local/kong/js_pluginserver.sock failed (2: No such file or directory), context: ngx.timer
2023/05/18 15:33:19 [crit] 1206#0: *149 connect() to unix:/usr/local/kong/js_pluginserver.sock failed (2: No such file or directory), context: ngx.timer
2023/05/18 15:33:19 [crit] 1206#0: *149 connect() to unix:/usr/local/kong/js_pluginserver.sock failed (2: No such file or directory), context: ngx.timer
2023/05/18 15:33:19 [crit] 1206#0: *149 connect() to unix:/usr/local/kong/js_pluginserver.sock failed (2: No such file or directory), context: ngx.timer
2023/05/18 15:33:19 [crit] 1206#0: *149 connect() to unix:/usr/local/kong/js_pluginserver.sock failed (2: No such file or directory), context: ngx.timer
2023/05/18 15:33:19 [crit] 1206#0: *149 connect() to unix:/usr/local/kong/js_pluginserver.sock failed (2: No such file or directory), context: ngx.timer
2023/05/18 15:33:19 [crit] 1206#0: *149 connect() to unix:/usr/local/kong/js_pluginserver.sock failed (2: No such file or directory), context: ngx.timer

2023/05/18 15:33:28 [warn] 1206#0: *160 [kong] plugins.lua:125 /plugins/schema/:name endpoint is deprecated, please use /schemas/plugins/:name instead (deprecated after 1.2.0, scheduled for removal in 3.0.0), client: 127.0.0.1, server: kong_admin, request: "GET /plugins/schema/prometheus HTTP/1.1", host: "127.0.0.1:8444"

Things seem to have a real hard time connecting to kong when this happens.

Here are the env vars used to set this up

KONG_PLUGINSERVER_JS_QUERY_CMD=node /usr/local/bin/kong-js-pluginserver --plugins-directory /opt/plugins/js --dump-all-plugins
KONG_PLUGINSERVER_JS_SOCKET=/usr/local/kong/js_pluginserver.sock
KONG_PLUGINSERVER_JS_START_CMD=node /usr/local/bin/kong-js-pluginserver --plugins-directory /opt/plugins/js
KONG_PLUGINSERVER_NAMES=js

table.d.ts contains imports with missing types

import type clear from "./table/clear"

It appears the generated TS type definitions from Lua are including a table definition that does not have have a matching import. Looking at the documentation I would assume that typescript doesn't have any use for the Lua tables but it is causing an issue with typescript transpilation.

kong.client.loadConsumer(UUID) throws error in custom js Plugin

It appears an RPC error is being thrown when trying to load a consumer by UUID.

We have verified our configurations and verified we are correctly passing in the UUID for our anonymous consumer, but continue to receive the following error:

[ERROR] rpc: #13 method "StepConsumer" not implemented

This is for a custom authorizer plugin. Using references to the lua plugins for authorization, we are attempting to call kong.client.loadConsumer(UUID) inside the access method.

Plugin Test Case - Cannot use import statement outside a module error

Hi team,

I am trying to add unit test case as per given example only. But it seems not working for me. I am not able find how can i resolve this

please find below code snippet

`const plugin = require('./js-transform');

const { PluginTest, Request } = require('kong-pdk/plugin_test');

test('Set headers in response', async () => {
let r = new Request();

r.useURL('http://example.com')
.useMethod('GET')
.useHeaders({
Host: 'example.com'
})
.useBody('all lower case');

let t = new PluginTest(r);

await t.Run(plugin, {});

expect(t.serviceRequest.body).toBe('ALL LOWER CASE');

expect(t.serviceRequest.url.search).toBe('?js-transform=v0.1.0');

expect(t.response.status).toBe(200);

expect(t.serviceResponse.body).toBe('OK');

expect(t.response.body).toBe(
Response body from upstream: OK Body size: 2
);
});
`

I installed

"devDependencies": { "@babel/core": "^7.16.0", "@babel/preset-env": "^7.16.0", "jest": "^27.3.1", "kong-pdk": "^0.4.3", "node-fetch": "^3.0.0", "uuid": "^8.3.2" }

code is same as example file
/examples/js-transform.js
/examples/js-transform.test.js

Can you please help me with this.

Accessing Binary Files in plugin

I am writing a custom js plugin for kong where I need to access the binary files that are coming with request as multipart form data
Currently I am using the getRawBody function provided by kong-pdk, but I am getting following error

2024/02/19 11:41:36 [warn] 1293#0: *2580 a client request body is buffered to a temporary file /var/run/kong/client_body_temp/0000000002" 2024/02/19 11:41:36 [error] 1293#0: *2580 [kong] init.lua:405 [clacks] /usr/local/share/lua/5.1/MessagePack.lua:126: attempt to get length of local 'str' (a nil value)

Is there a way to resolve it
Basically I want to access the number of files uploaded, size of files and the file extension

How to add X-Kong-Upstream-Status header to response

Trying to understand using the JavaScript PDK and I've written a simple plugin which converts XML from a legacy web service to JSON. It seems to be working for the most part, but I'm seeing a message in the Kong logs after the plugin executes:

2021/09/04 09:23:31 [error] 34#0: *66 [lua] handler.lua:1487: before(): failed to set X-Kong-Upstream-Status header while sending to client, client: 172.21.0.1, server: kong, request: "POST /vsedws/FindUser HTTP/1.1", host: "localhost:8000"

I've noted that the other X-Kong-* headers like X-Kong-Upstream-Latency and X-Kong-Proxy-Latency are still passing thru to the client, but not X-Kong-Upstream-Status. I've tried adding it myself in the response(kong) method:

kong.response.addHeader("X-Kong-Upstream-Status", await kong.service.response.getStatus());

But this doesn't seem to work. I can add other headers, e.g.:

kong.response.addHeader("foo", "bar");

I was even able to add it if I change the name to "Kong-Upstream-Status" and also added a header called "X-Kong-foo", so it seems that it's the fact that it's X-Kong-Upstream-Status. Also, don't understand why other X-Kong-* headers seem to be passing thru unmolested, but this one is stripped out by the existence of this plugin.

Is that just a limitation of the PDK, or am I missing something?

Add samples of JS plugins extending or reusing code from other plugins

Adding samples of JS plugins extending or reusing code from other plugins would be nice to promote the idea of code reuse and extensibility in the same way we see in some of the Lua plugins with ":extend()" from Lua.

Considering that the JS plugins probably will not be able to extend the Kong core plugins (given they are written in Lua) , at least promoting code reuse and extensibility between the JS plugins would be a welcome idea.

Share Data between Plugins in Kong JS PDK

Hi team,
Consider Scenario in which let's consider

  1. Parent Plugin Holding All common Configurations and having Highest Priority
  2. Child Plugin will get those common configurations from Parent and do action as per business logic

I tried with Custom nginx directive environment concept too which is https://docs.konghq.com/enterprise/2.5.x/property-reference/#injecting-nginx-directives , but it is not working for me.

docker run -it --name jskong \ --network=kong-net \ -e "KONG_DATABASE=postgres" \ -e "KONG_PG_HOST=kong-database" \ -e "KONG_PG_USER=kong" \ -e "KONG_PG_PASSWORD=kong" \ -e "KONG_CASSANDRA_CONTACT_POINTS=kong-database" \ -e "KONG_PROXY_ACCESS_LOG=/dev/stdout" \ -e "KONG_ADMIN_ACCESS_LOG=/dev/stdout" \ -e "KONG_PROXY_ERROR_LOG=/dev/stderr" \ -e "KONG_ADMIN_ERROR_LOG=/dev/stderr" \ -e "KONG_ADMIN_LISTEN=0.0.0.0:8001 reuseport backlog=16384, 0.0.0.0:8444 http2 ssl reuseport backlog=16384" \ -e "KONG_PLUGINSERVER_NAMES=js" \ -e "KONG_PLUGINSERVER_JS_SOCKET=/usr/local/kong/js_pluginserver.sock" \ -e "KONG_PLUGINSERVER_JS_START_CMD=/usr/local/bin/kong-js-pluginserver -v --plugins-directory /usr/local/kong/js-plugins" \ -e "KONG_PLUGINSERVER_JS_QUERY_CMD=/usr/local/bin/kong-js-pluginserver --plugins-directory /usr/local/kong/js-plugins --dump-all-plugins" \ -e "KONG_PLUGINS=bundled,global-config" \ -e "KONG_NGINX_MAIN_ENV=DATABASE_HOST; env DATABASE_PASSWORD; env DATABASE_USER; env DATABASE_NAME" \ -p 8000:8000 \ -p 8443:8443 \ -p 127.0.0.1:8001:8001 \ -p 127.0.0.1:8002:8002 \ -p 127.0.0.1:8444:8444 \ kong:1.0
but in my plugin with process.env it's not getting

It will be better if Parent => Child Plugin Data Shareable

Can you please guide how to do or access.

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.