@lango-project/lango-server 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +283 -4
- package/dist/builder.mjs +16 -1
- package/dist/builder.mjs.map +1 -1
- package/dist/cli/endpoint.mjs +6 -0
- package/dist/cli/endpoint.mjs.map +1 -1
- package/dist/cli/longpoll_broker.mjs +214 -0
- package/dist/cli/longpoll_broker.mjs.map +1 -0
- package/dist/cli/longpoll_options.mjs +102 -0
- package/dist/cli/longpoll_options.mjs.map +1 -0
- package/dist/cli/longpoll_session.mjs +135 -0
- package/dist/cli/longpoll_session.mjs.map +1 -0
- package/dist/cli/middleware.mjs +25 -0
- package/dist/cli/middleware.mjs.map +1 -0
- package/dist/cli/options.mjs +14 -2
- package/dist/cli/options.mjs.map +1 -1
- package/dist/cli/routes.mjs +66 -2
- package/dist/cli/routes.mjs.map +1 -1
- package/dist/cli/server.mjs +243 -23
- package/dist/cli/server.mjs.map +1 -1
- package/dist/cli/static_files.mjs +125 -0
- package/dist/cli/static_files.mjs.map +1 -0
- package/dist/endpoint.mjs +6 -0
- package/dist/endpoint.mjs.map +1 -1
- package/dist/group.mjs +17 -1
- package/dist/group.mjs.map +1 -1
- package/dist/longpoll_broker.mjs +214 -0
- package/dist/longpoll_broker.mjs.map +1 -0
- package/dist/longpoll_options.mjs +102 -0
- package/dist/longpoll_options.mjs.map +1 -0
- package/dist/longpoll_session.mjs +135 -0
- package/dist/longpoll_session.mjs.map +1 -0
- package/dist/middleware.mjs +25 -0
- package/dist/middleware.mjs.map +1 -0
- package/dist/options.mjs +14 -2
- package/dist/options.mjs.map +1 -1
- package/dist/routes.mjs +66 -2
- package/dist/routes.mjs.map +1 -1
- package/dist/runtime.mjs +118 -44
- package/dist/runtime.mjs.map +1 -1
- package/dist/server.mjs +243 -23
- package/dist/server.mjs.map +1 -1
- package/dist/server_context.mjs +78 -0
- package/dist/server_context.mjs.map +1 -0
- package/dist/static_files.mjs +125 -0
- package/dist/static_files.mjs.map +1 -0
- package/package.json +9 -4
- package/src/builder.lango +11 -0
- package/src/endpoint.lango +7 -0
- package/src/group.lango +14 -0
- package/src/longpoll.lua +61 -0
- package/src/longpoll_broker.lango +161 -0
- package/src/longpoll_options.lango +79 -0
- package/src/longpoll_session.lango +90 -0
- package/src/middleware.lango +10 -0
- package/src/options.lango +16 -0
- package/src/routes.lango +65 -1
- package/src/runtime.lango +62 -0
- package/src/server.lango +182 -17
- package/src/server_context.lango +58 -0
- package/src/static_files.lango +90 -0
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import * as files from "serve-static";
|
|
4
|
+
import {
|
|
5
|
+
hostGlobal as __hostGlobal,
|
|
6
|
+
isNumber as __isNumber,
|
|
7
|
+
isString as __isString,
|
|
8
|
+
isBool as __isBool,
|
|
9
|
+
isObject as __isObject,
|
|
10
|
+
isArray as __isArray,
|
|
11
|
+
entries as __entries,
|
|
12
|
+
requireBoolean as __requireBoolean,
|
|
13
|
+
normalize as __normalize,
|
|
14
|
+
finite as __finite,
|
|
15
|
+
call as __call,
|
|
16
|
+
boundary as __boundary,
|
|
17
|
+
requireArity as __requireArity,
|
|
18
|
+
withArity as __withArity,
|
|
19
|
+
} from "./.lango/runtime.mjs";
|
|
20
|
+
|
|
21
|
+
export class StaticFiles {
|
|
22
|
+
#settings;
|
|
23
|
+
#serve;
|
|
24
|
+
constructor(settings) {
|
|
25
|
+
__requireArity(arguments.length, [0], "constructor");
|
|
26
|
+
settings = __boundary(settings);
|
|
27
|
+
this.#settings = settings;
|
|
28
|
+
if (__requireBoolean(!__requireBoolean(__normalize(__normalize(fs.statSync(__normalize(settings.directory))).isDirectory())))) {
|
|
29
|
+
throw "Static directory must be a directory";
|
|
30
|
+
}
|
|
31
|
+
this.#serve = __normalize(files.default(__normalize(settings.directory), { index: __normalize(settings.index), dotfiles: "deny", fallthrough: false, redirect: false }));
|
|
32
|
+
}
|
|
33
|
+
receive(req, res, failed) {
|
|
34
|
+
__requireArity(arguments.length, [0, 1, 2], "receive");
|
|
35
|
+
req = __boundary(req);
|
|
36
|
+
res = __boundary(res);
|
|
37
|
+
failed = __boundary(failed);
|
|
38
|
+
let mount = __normalize(this.#settings.path);
|
|
39
|
+
let url = __normalize(req.url);
|
|
40
|
+
let pathname = __normalize(__normalize(url.split("?"))[0]);
|
|
41
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(mount !== "/") && __requireBoolean(pathname !== mount)) && __requireBoolean(!__requireBoolean(__normalize(pathname.startsWith(`${mount}/`)))))) {
|
|
42
|
+
__call(failed, 404, "NotFound");
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
if (__requireBoolean(mount !== "/")) {
|
|
46
|
+
req.url = __normalize(url.slice(__normalize(mount.length)));
|
|
47
|
+
if (__requireBoolean(__requireBoolean(__normalize(req.url) === "") || __requireBoolean(__normalize(req.url.startsWith("?"))))) {
|
|
48
|
+
req.url = `/${__normalize(req.url)}`;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
let done = __withArity((error) => {
|
|
52
|
+
error = __boundary(error);
|
|
53
|
+
if (__requireBoolean(__normalize(res.headersSent))) {
|
|
54
|
+
__normalize(res.destroy());
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
let status = 404;
|
|
58
|
+
let code = "NotFound";
|
|
59
|
+
if (__requireBoolean(error !== null)) {
|
|
60
|
+
if (__normalize(error.status) === 400) {
|
|
61
|
+
status = 400;
|
|
62
|
+
code = "InvalidPath";
|
|
63
|
+
} else if (__normalize(error.status) === 403) {
|
|
64
|
+
status = 403;
|
|
65
|
+
code = "Forbidden";
|
|
66
|
+
} else if (__normalize(error.status) === 416) {
|
|
67
|
+
status = 416;
|
|
68
|
+
code = "RangeNotSatisfiable";
|
|
69
|
+
} else if (__normalize(error.status) === 404) {
|
|
70
|
+
status = 404;
|
|
71
|
+
} else {
|
|
72
|
+
status = 500;
|
|
73
|
+
code = "InternalServerError";
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
__call(failed, status, code);
|
|
77
|
+
return null;
|
|
78
|
+
}, [0], "closure");
|
|
79
|
+
let serve = __normalize(this.#serve);
|
|
80
|
+
__call(serve, req, res, done);
|
|
81
|
+
return null;
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
export function staticOptions(root, spec) {
|
|
86
|
+
__requireArity(arguments.length, [0, 1], "staticOptions");
|
|
87
|
+
root = __boundary(root);
|
|
88
|
+
spec = __boundary(spec);
|
|
89
|
+
if (__requireBoolean(spec === null)) {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
if (__requireBoolean(__requireBoolean(!__requireBoolean(__isObject(spec))) || __requireBoolean(__isArray(spec)))) {
|
|
93
|
+
throw "static must be a map";
|
|
94
|
+
}
|
|
95
|
+
let allowed = ["path", "directory", "index"];
|
|
96
|
+
for (const [key, value] of __entries(spec)) {
|
|
97
|
+
if (__requireBoolean(!__requireBoolean(__normalize(allowed.includes(key))))) {
|
|
98
|
+
throw `Unknown static option: ${key}`;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
let mount = __normalize(spec.path);
|
|
102
|
+
if (__requireBoolean(mount === null)) {
|
|
103
|
+
mount = "/";
|
|
104
|
+
}
|
|
105
|
+
let pattern = new (__hostGlobal(["RegExp"]))("^/(?:[A-Za-z0-9_-]+/)*[A-Za-z0-9_-]*$");
|
|
106
|
+
if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(mount))) || __requireBoolean(!__requireBoolean(__normalize(pattern.test(mount)))))) {
|
|
107
|
+
throw "Static path must be an absolute URL prefix";
|
|
108
|
+
}
|
|
109
|
+
if (__requireBoolean(__requireBoolean(mount !== "/") && __requireBoolean(__normalize(mount.endsWith("/"))))) {
|
|
110
|
+
mount = __normalize(mount.slice(0, __finite(-1)));
|
|
111
|
+
}
|
|
112
|
+
if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(__normalize(spec.directory)))) || __requireBoolean(__normalize(spec.directory.trim()) === ""))) {
|
|
113
|
+
throw "Static directory is required";
|
|
114
|
+
}
|
|
115
|
+
let index = __normalize(spec.index);
|
|
116
|
+
if (__requireBoolean(index === null)) {
|
|
117
|
+
index = "index.html";
|
|
118
|
+
}
|
|
119
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(index))) || __requireBoolean(index === "")) || __requireBoolean(__normalize(index.startsWith(".")))) || __requireBoolean(__normalize(index.includes("/")))) || __requireBoolean(__normalize(index.includes("\\"))))) {
|
|
120
|
+
throw "Static index must be a file name";
|
|
121
|
+
}
|
|
122
|
+
return { path: mount, directory: __normalize(path.resolve(root, __normalize(spec.directory))), index: index };
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
//# sourceMappingURL=static_files.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"static_files.mjs","sources":["static_files.lango"],"sourcesContent":["import js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"serve-static\" as files\nimport js global RegExp\n\nexport staticOptions(root, spec)\nexport class StaticFiles(settings)\n methods\n receive(req, res, failed)\n\nstaticOptions(root, spec)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"static must be a map\"\n allowed = [\"path\", \"directory\", \"index\"]\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown static option: ${key}\"\n mount = spec.path\n if mount == null\n mount = \"/\"\n pattern = new RegExp(\"^/(?:[A-Za-z0-9_-]+/)*[A-Za-z0-9_-]*$\")\n if !is_string(mount) or !pattern.test(mount)\n throw \"Static path must be an absolute URL prefix\"\n if mount != \"/\" and mount.endsWith(\"/\")\n mount = mount.slice(0, -1)\n if !is_string(spec.directory) or spec.directory.trim() == \"\"\n throw \"Static directory is required\"\n index = spec.index\n if index == null\n index = \"index.html\"\n if !is_string(index) or index == \"\" or index.startsWith(\".\") or index.includes(\"/\") or index.includes(\"\\\\\")\n throw \"Static index must be a file name\"\n return {\n path: mount\n directory: path/resolve(root, spec.directory)\n index: index\n }\n\nStaticFiles(settings)\n @settings = settings\n if !fs/statSync(settings.directory).isDirectory()\n throw \"Static directory must be a directory\"\n @serve = files/default(settings.directory, {\n index: settings.index\n dotfiles: \"deny\"\n fallthrough: false\n redirect: false\n })\n\nStaticFiles:receive(req, res, failed)\n mount = @settings.path\n url = req.url\n pathname = url.split(\"?\")[0]\n if mount != \"/\" and pathname != mount and !pathname.startsWith(\"${mount}/\")\n failed(404, \"NotFound\")\n return null\n if mount != \"/\"\n req.url = url.slice(mount.length)\n if req.url == \"\" or req.url.startsWith(\"?\")\n req.url = \"/${req.url}\"\n done = (error)\n capture res\n capture failed\n if res.headersSent\n res.destroy()\n return null\n status = 404\n code = \"NotFound\"\n if error != null\n switch error.status\n case 400\n status = 400\n code = \"InvalidPath\"\n case 403\n status = 403\n code = \"Forbidden\"\n case 416\n status = 416\n code = \"RangeNotSatisfiable\"\n case 404\n status = 404\n else\n status = 500\n code = \"InternalServerError\"\n failed(status, code)\n serve = @serve\n serve(req, res, done)\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lango-project/lango-server",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "A small JSON HTTP server for Lango applications.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -19,21 +19,26 @@
|
|
|
19
19
|
"files": [
|
|
20
20
|
"dist/**",
|
|
21
21
|
"src/*.lango",
|
|
22
|
+
"src/*.lua",
|
|
22
23
|
"README.md",
|
|
23
24
|
"LICENSE",
|
|
24
25
|
"NOTICE"
|
|
25
26
|
],
|
|
26
27
|
"scripts": {
|
|
27
28
|
"build": "lango run tools/clean.lango && lango build src/library.lango --out dist/library.mjs && lango build src/server.lango --out dist/cli/server.mjs --executable && lango build src/worker.lango --out dist/worker.mjs && lango build examples/application/handlers.lango --out examples/application/dist/handlers.mjs && lango build src/postgres_worker.lango --out dist/postgres_worker.mjs && lango build examples/database/handlers.lango --out examples/database/dist/handlers.mjs",
|
|
28
|
-
"test": "npm run build && lango build src/test/handlers.lango --out .test-output/handlers.mjs && lango build src/test/sql_handlers.lango --out .test-output/sql_handlers.mjs && lango test src/test/database.lango --build-dir .test-output/database && lango test src/test/unit.lango --build-dir .test-output/unit && lango test src/test/http.lango --build-dir .test-output/http && lango test src/test/standalone.lango --build-dir .test-output/standalone",
|
|
29
|
+
"test": "npm run build && lango build src/test/handlers.lango --out .test-output/handlers.mjs && lango build src/test/sql_handlers.lango --out .test-output/sql_handlers.mjs && lango build src/test/middleware_handlers.lango --out .test-output/middleware_handlers.mjs && lango test src/test/database.lango --build-dir .test-output/database && lango test src/test/unit.lango --build-dir .test-output/unit && lango test src/test/http.lango --build-dir .test-output/http && lango test src/test/middleware.lango --build-dir .test-output/middleware && lango test src/test/static.lango --build-dir .test-output/static && lango test src/test/standalone.lango --build-dir .test-output/standalone",
|
|
29
30
|
"start": "node dist/cli/server.mjs examples/application",
|
|
30
31
|
"prepack": "npm run build",
|
|
31
|
-
"test:postgres": "lango build src/test/sql_handlers.lango --out .test-output/sql_handlers.mjs && lango test src/test/database.lango --build-dir .test-output/database-postgres"
|
|
32
|
+
"test:postgres": "lango build src/test/sql_handlers.lango --out .test-output/sql_handlers.mjs && lango test src/test/database.lango --build-dir .test-output/database-postgres",
|
|
33
|
+
"test:longpoll": "lango build src/test/longpoll_handlers.lango --out .test-output/longpoll_handlers.mjs && lango test src/test/longpoll.lango --build-dir .test-output/longpoll && lango build src/test/middleware_handlers.lango --out .test-output/middleware_handlers.mjs && lango test src/test/standalone.lango --build-dir .test-output/standalone-longpoll",
|
|
34
|
+
"test:middleware": "lango build src/test/handlers.lango --out .test-output/handlers.mjs && lango build src/test/middleware_handlers.lango --out .test-output/middleware_handlers.mjs && lango test src/test/middleware.lango --build-dir .test-output/middleware"
|
|
32
35
|
},
|
|
33
36
|
"dependencies": {
|
|
34
37
|
"jsonwebtoken": "^9.0.3",
|
|
35
38
|
"pg": "^8.23.1",
|
|
36
|
-
"piscina": "^5.3.2"
|
|
39
|
+
"piscina": "^5.3.2",
|
|
40
|
+
"redis": "^5.12.1",
|
|
41
|
+
"serve-static": "^2.2.1"
|
|
37
42
|
},
|
|
38
43
|
"devDependencies": {
|
|
39
44
|
"@lango-project/lango-js": "^0.1.13"
|
package/src/builder.lango
CHANGED
|
@@ -12,7 +12,9 @@ import "./server"
|
|
|
12
12
|
export class Builder(root = null)
|
|
13
13
|
methods
|
|
14
14
|
configure(settings)
|
|
15
|
+
addMiddleware(name, spec)
|
|
15
16
|
endpoint(spec)
|
|
17
|
+
longpoll(spec)
|
|
16
18
|
group(spec)
|
|
17
19
|
include(spec)
|
|
18
20
|
event(spec)
|
|
@@ -30,10 +32,18 @@ Builder:configure(settings)
|
|
|
30
32
|
@settings[key] = value
|
|
31
33
|
return @this
|
|
32
34
|
|
|
35
|
+
Builder:addMiddleware(name, spec)
|
|
36
|
+
@routes.addMiddleware(name, spec)
|
|
37
|
+
return @this
|
|
38
|
+
|
|
33
39
|
Builder:endpoint(spec)
|
|
34
40
|
@routes.endpoint(spec)
|
|
35
41
|
return @this
|
|
36
42
|
|
|
43
|
+
Builder:longpoll(spec)
|
|
44
|
+
@routes.longpoll(spec)
|
|
45
|
+
return @this
|
|
46
|
+
|
|
37
47
|
Builder:group(spec)
|
|
38
48
|
return new Group(@routes, spec)
|
|
39
49
|
|
|
@@ -50,4 +60,5 @@ Builder:build()
|
|
|
50
60
|
settings: options(@root, @settings)
|
|
51
61
|
routes: @routes.definitions()
|
|
52
62
|
events: @routes.events()
|
|
63
|
+
middlewares: @routes.middlewares()
|
|
53
64
|
})
|
package/src/endpoint.lango
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
|
+
import "./middleware"
|
|
2
|
+
middlewareName(name)
|
|
3
|
+
|
|
1
4
|
export class Endpoint(spec)
|
|
2
5
|
properties
|
|
3
6
|
path
|
|
4
7
|
module
|
|
5
8
|
handler
|
|
6
9
|
auth
|
|
10
|
+
middleware
|
|
7
11
|
|
|
8
12
|
Endpoint(spec)
|
|
9
13
|
if !is_string(spec.path) or !spec.path.startsWith("/") or spec.path.includes("?") or spec.path.includes("#") or spec.path.includes("\\") or spec.path.includes("//")
|
|
@@ -16,6 +20,9 @@ Endpoint(spec)
|
|
|
16
20
|
@path = spec.path
|
|
17
21
|
@module = spec.module
|
|
18
22
|
@handler = spec.handler
|
|
23
|
+
@middleware = spec.middleware
|
|
24
|
+
if @middleware != null
|
|
25
|
+
middlewareName(@middleware)
|
|
19
26
|
@auth = spec.auth
|
|
20
27
|
if @auth == null
|
|
21
28
|
@auth = "login"
|
package/src/group.lango
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
|
+
import js global Object
|
|
2
|
+
|
|
1
3
|
export class Group(routes, spec, prefix = "", inheritedModule = null, inheritedAuth = null)
|
|
2
4
|
methods
|
|
3
5
|
endpoint(spec)
|
|
6
|
+
longpoll(spec)
|
|
4
7
|
group(spec)
|
|
5
8
|
include(spec)
|
|
6
9
|
|
|
@@ -30,9 +33,20 @@ Group:endpoint(spec)
|
|
|
30
33
|
module: mod
|
|
31
34
|
handler: spec.handler
|
|
32
35
|
auth: auth
|
|
36
|
+
middleware: spec.middleware
|
|
33
37
|
})
|
|
34
38
|
return @this
|
|
35
39
|
|
|
40
|
+
Group:longpoll(spec)
|
|
41
|
+
item = Object/assign({}, spec)
|
|
42
|
+
item.path = "${@prefix}${spec.path}"
|
|
43
|
+
if item.auth == null
|
|
44
|
+
item.auth = @auth
|
|
45
|
+
if item.fallback != null
|
|
46
|
+
item.fallback = "${@prefix}${item.fallback}"
|
|
47
|
+
@routes.longpoll(item)
|
|
48
|
+
return @this
|
|
49
|
+
|
|
36
50
|
Group:group(spec)
|
|
37
51
|
return new Group(@routes, spec, @prefix, @module, @auth)
|
|
38
52
|
|
package/src/longpoll.lua
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
-- Atomic channel generation, trimming, publication and cursor validation.
|
|
2
|
+
local stream, meta = KEYS[1], KEYS[2]
|
|
3
|
+
local operation, candidate = ARGV[1], ARGV[2]
|
|
4
|
+
local retention, maximum = tonumber(ARGV[3]), tonumber(ARGV[4])
|
|
5
|
+
local now = redis.call('TIME')
|
|
6
|
+
local milliseconds = tonumber(now[1]) * 1000 + math.floor(tonumber(now[2]) / 1000)
|
|
7
|
+
local generation = redis.call('HGET', meta, 'generation')
|
|
8
|
+
if not generation then
|
|
9
|
+
redis.call('DEL', stream)
|
|
10
|
+
generation = candidate
|
|
11
|
+
redis.call('HSET', meta, 'generation', generation, 'floor', '0-0', 'last', '0-0')
|
|
12
|
+
redis.call('PEXPIRE', meta, retention)
|
|
13
|
+
end
|
|
14
|
+
local function compare(a, b)
|
|
15
|
+
local am, as = string.match(a, '^(%d+)%-(%d+)$')
|
|
16
|
+
local bm, bs = string.match(b, '^(%d+)%-(%d+)$')
|
|
17
|
+
if #am ~= #bm then return #am < #bm end
|
|
18
|
+
if am ~= bm then return am < bm end
|
|
19
|
+
if #as ~= #bs then return #as < #bs end
|
|
20
|
+
return as < bs
|
|
21
|
+
end
|
|
22
|
+
local floor = redis.call('HGET', meta, 'floor')
|
|
23
|
+
local cutoff = tostring(math.max(0, milliseconds - retention)) .. '-0'
|
|
24
|
+
local removed = redis.call('XREVRANGE', stream, '(' .. cutoff, '-', 'COUNT', 1)
|
|
25
|
+
if #removed > 0 and compare(floor, removed[1][1]) then floor = removed[1][1] end
|
|
26
|
+
redis.call('XTRIM', stream, 'MINID', cutoff)
|
|
27
|
+
if operation == 'publish' then
|
|
28
|
+
local id = redis.call('XADD', stream, '*', 'data', ARGV[7])
|
|
29
|
+
redis.call('HSET', meta, 'last', id)
|
|
30
|
+
local excess = redis.call('XLEN', stream) - maximum
|
|
31
|
+
if excess > 0 then
|
|
32
|
+
local old = redis.call('XRANGE', stream, '-', '+', 'COUNT', excess)
|
|
33
|
+
floor = old[#old][1]
|
|
34
|
+
redis.call('XTRIM', stream, 'MAXLEN', maximum)
|
|
35
|
+
end
|
|
36
|
+
redis.call('HSET', meta, 'floor', floor)
|
|
37
|
+
redis.call('PEXPIRE', stream, retention)
|
|
38
|
+
redis.call('PEXPIRE', meta, retention)
|
|
39
|
+
return cjson.encode({generation=generation, id=id})
|
|
40
|
+
end
|
|
41
|
+
redis.call('HSET', meta, 'floor', floor)
|
|
42
|
+
local last = redis.call('HGET', meta, 'last')
|
|
43
|
+
if operation == 'cursor' then
|
|
44
|
+
return cjson.encode({generation=generation, id=last})
|
|
45
|
+
end
|
|
46
|
+
local epoch, position = ARGV[5], ARGV[6]
|
|
47
|
+
if epoch ~= '' and (epoch ~= generation or compare(position, floor) or compare(last, position)) then
|
|
48
|
+
return cjson.encode({resyncRequired=true})
|
|
49
|
+
end
|
|
50
|
+
local entries = redis.call('XRANGE', stream, '(' .. position, '+', 'COUNT', 16)
|
|
51
|
+
local messages = {}
|
|
52
|
+
local bytes = 0
|
|
53
|
+
local id = position
|
|
54
|
+
for _, entry in ipairs(entries) do
|
|
55
|
+
local data = entry[2][2]
|
|
56
|
+
if bytes + string.len(data) > 1048576 then break end
|
|
57
|
+
bytes = bytes + string.len(data)
|
|
58
|
+
id = entry[1]
|
|
59
|
+
table.insert(messages, {id=id, data=data})
|
|
60
|
+
end
|
|
61
|
+
return cjson.encode({generation=generation, id=id, messages=messages})
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import js "redis" as redis
|
|
2
|
+
import js "node:crypto" as crypto
|
|
3
|
+
import js "node:fs" as fs
|
|
4
|
+
import js "node:path" as path
|
|
5
|
+
import js "node:module" as modules
|
|
6
|
+
import js global Buffer
|
|
7
|
+
import js global Promise
|
|
8
|
+
import js global process
|
|
9
|
+
import js global JSON
|
|
10
|
+
import js global RegExp
|
|
11
|
+
import js global Object
|
|
12
|
+
import js global setTimeout
|
|
13
|
+
import js global clearTimeout
|
|
14
|
+
|
|
15
|
+
export class LongpollBroker(settings, routes)
|
|
16
|
+
methods
|
|
17
|
+
open()
|
|
18
|
+
close()
|
|
19
|
+
route(path)
|
|
20
|
+
publish(path, key, data)
|
|
21
|
+
cursor(path, key)
|
|
22
|
+
read(path, key, cursor)
|
|
23
|
+
|
|
24
|
+
LongpollBroker(settings, routes)
|
|
25
|
+
@routes = Object/create(null)
|
|
26
|
+
for routes as item
|
|
27
|
+
if item.kind == "longpoll"
|
|
28
|
+
@routes[item.path] = item
|
|
29
|
+
@settings = settings.redis
|
|
30
|
+
@client = null
|
|
31
|
+
@script = null
|
|
32
|
+
if Object/keys(@routes).length > 0 and @settings == null
|
|
33
|
+
throw "Longpoll routes require Redis configuration"
|
|
34
|
+
@root = settings.root
|
|
35
|
+
|
|
36
|
+
LongpollBroker:route(path)
|
|
37
|
+
if Object/hasOwn(@routes, path)
|
|
38
|
+
return @routes[path]
|
|
39
|
+
return null
|
|
40
|
+
|
|
41
|
+
LongpollBroker:open()
|
|
42
|
+
if Object/keys(@routes).length == 0
|
|
43
|
+
return Promise/resolve(null)
|
|
44
|
+
resolver = modules/createRequire(path/join(@root, "package.json"))
|
|
45
|
+
entry = resolver.resolve("@lango-project/lango-server")
|
|
46
|
+
@script = fs/readFileSync(path/join(path/dirname(entry), "../src/longpoll.lua"), "utf8")
|
|
47
|
+
config = @settings
|
|
48
|
+
name = config.connectionEnv
|
|
49
|
+
@client = redis/createClient({
|
|
50
|
+
url: process.env[name]
|
|
51
|
+
disableOfflineQueue: true
|
|
52
|
+
commandsQueueMaxLength: 2048
|
|
53
|
+
socket: {
|
|
54
|
+
connectTimeout: 2000
|
|
55
|
+
reconnectStrategy: 500
|
|
56
|
+
}
|
|
57
|
+
})
|
|
58
|
+
client = @client
|
|
59
|
+
client.on("error", (error)
|
|
60
|
+
return null
|
|
61
|
+
)
|
|
62
|
+
return bounded(client.connect(), 3000)
|
|
63
|
+
|
|
64
|
+
LongpollBroker:close()
|
|
65
|
+
if @client != null and @client.isOpen
|
|
66
|
+
@client.destroy()
|
|
67
|
+
return null
|
|
68
|
+
|
|
69
|
+
LongpollBroker:publish(path, key, data)
|
|
70
|
+
body = JSON/stringify(data)
|
|
71
|
+
if !is_string(body) or Buffer/byteLength(body) > 262144
|
|
72
|
+
return Promise/reject("Longpoll message must be JSON within 262144 bytes")
|
|
73
|
+
return execute("publish", path, key, null, body)
|
|
74
|
+
|
|
75
|
+
LongpollBroker:cursor(path, key)
|
|
76
|
+
return execute("cursor", path, key, null, "")
|
|
77
|
+
|
|
78
|
+
LongpollBroker:read(path, key, cursor)
|
|
79
|
+
return execute("read", path, key, cursor, "")
|
|
80
|
+
|
|
81
|
+
LongpollBroker:execute(operation, path, key, cursor, body)
|
|
82
|
+
item = route(path)
|
|
83
|
+
if item == null
|
|
84
|
+
return Promise/reject("Unknown longpoll path")
|
|
85
|
+
if !is_string(key) or key == "" or Buffer/byteLength(key) > 1024
|
|
86
|
+
return Promise/reject("Longpoll key must contain 1 to 1024 bytes")
|
|
87
|
+
if @client == null or !@client.isReady
|
|
88
|
+
return Promise/reject("RedisUnavailable")
|
|
89
|
+
hash = crypto/createHash("sha256")
|
|
90
|
+
hash.update(to_json([@settings.namespace, path, key]))
|
|
91
|
+
channel = hash.digest("hex")
|
|
92
|
+
prefix = "lango:longpoll:{${channel}}"
|
|
93
|
+
position = {
|
|
94
|
+
generation: ""
|
|
95
|
+
id: "0-0"
|
|
96
|
+
}
|
|
97
|
+
if cursor != null
|
|
98
|
+
position = decode(cursor, channel)
|
|
99
|
+
if position == null
|
|
100
|
+
return Promise/resolve({
|
|
101
|
+
resyncRequired: true
|
|
102
|
+
})
|
|
103
|
+
pending = @client.eval(@script, {
|
|
104
|
+
keys: ["${prefix}:stream", "${prefix}:meta"]
|
|
105
|
+
arguments: [operation, crypto/randomUUID(), "${item.retentionMs}", "${item.maxMessages}", position.generation, position.id, body]
|
|
106
|
+
})
|
|
107
|
+
return chain bounded(pending, 3000)
|
|
108
|
+
then(raw)
|
|
109
|
+
capture channel
|
|
110
|
+
capture operation
|
|
111
|
+
result = JSON/parse(raw)
|
|
112
|
+
if result.resyncRequired == true
|
|
113
|
+
return result
|
|
114
|
+
result.cursor = encode(channel, result.generation, result.id)
|
|
115
|
+
if operation != "read"
|
|
116
|
+
return result.cursor
|
|
117
|
+
messages = []
|
|
118
|
+
if is_array(result.messages)
|
|
119
|
+
for result.messages as message
|
|
120
|
+
messages.add({
|
|
121
|
+
id: encode(channel, result.generation, message.id)
|
|
122
|
+
data: JSON/parse(message.data)
|
|
123
|
+
})
|
|
124
|
+
return {
|
|
125
|
+
messages: messages
|
|
126
|
+
cursor: result.cursor
|
|
127
|
+
resyncRequired: false
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
encode(channel, generation, id)
|
|
131
|
+
buffer = Buffer/from(to_json([channel, generation, id]))
|
|
132
|
+
return buffer.toString("base64url")
|
|
133
|
+
|
|
134
|
+
decode(cursor, channel)
|
|
135
|
+
if !is_string(cursor) or cursor.length > 512
|
|
136
|
+
return null
|
|
137
|
+
try
|
|
138
|
+
buffer = Buffer/from(cursor, "base64url")
|
|
139
|
+
parts = from_json(buffer.toString("utf8"))
|
|
140
|
+
if !is_array(parts) or parts.length != 3 or parts[0] != channel or !is_string(parts[1]) or !is_string(parts[2])
|
|
141
|
+
return null
|
|
142
|
+
pattern = new RegExp("^(0|[1-9][0-9]{0,18})-(0|[1-9][0-9]{0,18})$")
|
|
143
|
+
if !pattern.test(parts[2]) or parts[2].length > 40
|
|
144
|
+
return null
|
|
145
|
+
return {
|
|
146
|
+
generation: parts[1]
|
|
147
|
+
id: parts[2]
|
|
148
|
+
}
|
|
149
|
+
catch error
|
|
150
|
+
return null
|
|
151
|
+
|
|
152
|
+
bounded(pending, ms)
|
|
153
|
+
expired = Promise/withResolvers()
|
|
154
|
+
fail = ()
|
|
155
|
+
capture expired
|
|
156
|
+
expired.reject("RedisUnavailable")
|
|
157
|
+
timer = setTimeout(fail, ms)
|
|
158
|
+
return chain Promise/race([pending, expired.promise])
|
|
159
|
+
finally
|
|
160
|
+
capture timer
|
|
161
|
+
clearTimeout(timer)
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import js global Number
|
|
2
|
+
import js global Object
|
|
3
|
+
import js global process
|
|
4
|
+
import js global URL
|
|
5
|
+
|
|
6
|
+
export longpollOptions(spec)
|
|
7
|
+
export redisOptions(spec)
|
|
8
|
+
|
|
9
|
+
longpollOptions(spec)
|
|
10
|
+
result = {
|
|
11
|
+
kind: "longpoll"
|
|
12
|
+
path: spec.path
|
|
13
|
+
auth: "login"
|
|
14
|
+
waitTimeoutMs: 20000
|
|
15
|
+
retentionMs: 300000
|
|
16
|
+
maxMessages: 1000
|
|
17
|
+
fallback: null
|
|
18
|
+
}
|
|
19
|
+
for spec as key: value
|
|
20
|
+
if !Object/hasOwn(result, key) or key == "kind"
|
|
21
|
+
throw "Unknown longpoll option: ${key}"
|
|
22
|
+
result[key] = value
|
|
23
|
+
if result.auth == null
|
|
24
|
+
result.auth = "login"
|
|
25
|
+
validPath(result.path)
|
|
26
|
+
if !is_string(result.auth) or result.auth == "" or result.auth.includes(",")
|
|
27
|
+
throw "Longpoll auth must name one permission"
|
|
28
|
+
if result.fallback != null
|
|
29
|
+
validPath(result.fallback)
|
|
30
|
+
limits = {
|
|
31
|
+
waitTimeoutMs: 60000
|
|
32
|
+
retentionMs: 86400000
|
|
33
|
+
maxMessages: 10000
|
|
34
|
+
}
|
|
35
|
+
for limits as key: limit
|
|
36
|
+
if !is_number(result[key]) and !is_string(result[key])
|
|
37
|
+
throw "Invalid longpoll option: ${key}"
|
|
38
|
+
value = Number(result[key])
|
|
39
|
+
if !Number/isSafeInteger(value) or value < 1 or value > limit
|
|
40
|
+
throw "Invalid longpoll option: ${key}"
|
|
41
|
+
result[key] = value
|
|
42
|
+
return result
|
|
43
|
+
|
|
44
|
+
validPath(value)
|
|
45
|
+
if !is_string(value) or !value.startsWith("/") or value.includes("*") or value.includes("?") or value.includes("#") or value.includes("\\") or value.includes("//")
|
|
46
|
+
throw "Longpoll requires an exact absolute URL path"
|
|
47
|
+
return null
|
|
48
|
+
|
|
49
|
+
redisOptions(spec)
|
|
50
|
+
if spec == null
|
|
51
|
+
return null
|
|
52
|
+
if !is_object(spec) or is_array(spec)
|
|
53
|
+
throw "Redis configuration must be a map"
|
|
54
|
+
allowed = ["connectionEnv", "namespace", "maxPendingPolls"]
|
|
55
|
+
for spec as key: value
|
|
56
|
+
if !allowed.includes(key)
|
|
57
|
+
throw "Unknown Redis option: ${key}"
|
|
58
|
+
if !is_string(spec.connectionEnv) or spec.connectionEnv == "" or !is_string(spec.namespace) or spec.namespace == "" or spec.namespace.length > 128
|
|
59
|
+
throw "Redis requires connectionEnv and namespace"
|
|
60
|
+
name = spec.connectionEnv
|
|
61
|
+
value = process.env[name]
|
|
62
|
+
if !is_string(value) or value == ""
|
|
63
|
+
throw "Redis connection environment variable is missing"
|
|
64
|
+
url = new URL(value)
|
|
65
|
+
protocols = ["redis:", "rediss:"]
|
|
66
|
+
if !protocols.includes(url.protocol)
|
|
67
|
+
throw "Redis requires a redis:// or rediss:// URL"
|
|
68
|
+
maximum = 1024
|
|
69
|
+
if spec.maxPendingPolls != null
|
|
70
|
+
if !is_number(spec.maxPendingPolls) and !is_string(spec.maxPendingPolls)
|
|
71
|
+
throw "Invalid Redis maxPendingPolls"
|
|
72
|
+
maximum = Number(spec.maxPendingPolls)
|
|
73
|
+
if !Number/isSafeInteger(maximum) or maximum < 1 or maximum > 10000
|
|
74
|
+
throw "Invalid Redis maxPendingPolls"
|
|
75
|
+
return {
|
|
76
|
+
connectionEnv: spec.connectionEnv
|
|
77
|
+
namespace: spec.namespace
|
|
78
|
+
maxPendingPolls: maximum
|
|
79
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import js global Promise
|
|
2
|
+
import js global Buffer
|
|
3
|
+
import js global Date
|
|
4
|
+
import js global Math
|
|
5
|
+
import js global setTimeout
|
|
6
|
+
import js global clearTimeout
|
|
7
|
+
|
|
8
|
+
export class LongpollSession(broker, route, authorize, body)
|
|
9
|
+
methods
|
|
10
|
+
run()
|
|
11
|
+
cancel()
|
|
12
|
+
|
|
13
|
+
LongpollSession(broker, route, authorize, body)
|
|
14
|
+
@broker = broker
|
|
15
|
+
@route = route
|
|
16
|
+
@authorize = authorize
|
|
17
|
+
@body = body
|
|
18
|
+
@cancelled = false
|
|
19
|
+
@timer = null
|
|
20
|
+
@sleep = null
|
|
21
|
+
@token = null
|
|
22
|
+
@deadline = 0
|
|
23
|
+
@input = null
|
|
24
|
+
@cursor = null
|
|
25
|
+
|
|
26
|
+
LongpollSession:cancel()
|
|
27
|
+
@cancelled = true
|
|
28
|
+
clearTimeout(@timer)
|
|
29
|
+
if @sleep != null
|
|
30
|
+
@sleep.resolve(null)
|
|
31
|
+
return null
|
|
32
|
+
|
|
33
|
+
LongpollSession:run()
|
|
34
|
+
try
|
|
35
|
+
@input = from_json(@body)
|
|
36
|
+
input = @input
|
|
37
|
+
if !is_object(input) or is_array(input) or !is_string(input.key) or input.key == "" or Buffer/byteLength(input.key) > 1024
|
|
38
|
+
return Promise/resolve(failure(400, "InvalidLongpollInput"))
|
|
39
|
+
if input.cursor != null and (!is_string(input.cursor) or input.cursor.length > 512)
|
|
40
|
+
return Promise/resolve(failure(400, "InvalidLongpollInput"))
|
|
41
|
+
@cursor = input.cursor
|
|
42
|
+
catch error
|
|
43
|
+
return Promise/resolve(failure(400, "InvalidJson"))
|
|
44
|
+
auth = @authorize
|
|
45
|
+
return chain auth(null, null)
|
|
46
|
+
then(result)
|
|
47
|
+
if result.status != 200
|
|
48
|
+
return result
|
|
49
|
+
@token = result.authorization
|
|
50
|
+
@deadline = Date/now() + @route.waitTimeoutMs
|
|
51
|
+
return poll()
|
|
52
|
+
catch(error)
|
|
53
|
+
return failure(503, "LongpollUnavailable")
|
|
54
|
+
finally
|
|
55
|
+
cancel()
|
|
56
|
+
|
|
57
|
+
LongpollSession:poll()
|
|
58
|
+
if @cancelled
|
|
59
|
+
return Promise/resolve(failure(503, "Unavailable"))
|
|
60
|
+
return chain @broker.read(@route.path, @input.key, @cursor)
|
|
61
|
+
then(batch)
|
|
62
|
+
if @cancelled
|
|
63
|
+
return failure(503, "Unavailable")
|
|
64
|
+
if batch.resyncRequired or batch.messages.length > 0 or Date/now() >= @deadline
|
|
65
|
+
if batch.resyncRequired
|
|
66
|
+
batch.fallback = @route.fallback
|
|
67
|
+
auth = @authorize
|
|
68
|
+
return auth(@token, batch)
|
|
69
|
+
@cursor = batch.cursor
|
|
70
|
+
@sleep = Promise/withResolvers()
|
|
71
|
+
sleep = @sleep
|
|
72
|
+
wake = ()
|
|
73
|
+
capture sleep
|
|
74
|
+
sleep.resolve(null)
|
|
75
|
+
@timer = setTimeout(wake, Math/min(250, Math/max(1, @deadline - Date/now())))
|
|
76
|
+
return chain sleep.promise
|
|
77
|
+
then(ignored)
|
|
78
|
+
return poll()
|
|
79
|
+
|
|
80
|
+
failure(status, code)
|
|
81
|
+
return {
|
|
82
|
+
status: status
|
|
83
|
+
headers: {
|
|
84
|
+
"content-type": "application/json; charset=utf-8"
|
|
85
|
+
"cache-control": "no-store"
|
|
86
|
+
}
|
|
87
|
+
body: to_json({
|
|
88
|
+
error: code
|
|
89
|
+
})
|
|
90
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import js global RegExp
|
|
2
|
+
|
|
3
|
+
export middlewareName(name)
|
|
4
|
+
|
|
5
|
+
middlewareName(name)
|
|
6
|
+
reserved = ["routes", "endpoint", "longpoll", "group", "include", "event", "middleware"]
|
|
7
|
+
pattern = new RegExp("^[A-Za-z_][A-Za-z0-9_-]*$")
|
|
8
|
+
if !is_string(name) or !pattern.test(name) or reserved.includes(name)
|
|
9
|
+
throw "Invalid or reserved middleware name: ${name}"
|
|
10
|
+
return name
|