0z2i6v3u5t 1.0.0

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.
Files changed (211) hide show
  1. package/.devcontainer/devcontainer.json +4 -0
  2. package/.devcontainer/setup.sh +11 -0
  3. package/.dockerignore +2 -0
  4. package/.github/CONTRIBUTING.md +52 -0
  5. package/.github/FUNDING.yml +3 -0
  6. package/.github/ISSUE_TEMPLATE/bug_report.yml +59 -0
  7. package/.github/ISSUE_TEMPLATE/config.yml +5 -0
  8. package/.github/ISSUE_TEMPLATE/feature_request.yml +43 -0
  9. package/.github/dependabot.yml +17 -0
  10. package/.github/workflows/codeql.yml +76 -0
  11. package/.github/workflows/publish_docs.yml +25 -0
  12. package/.github/workflows/test.yml +78 -0
  13. package/.nvmrc +1 -0
  14. package/.prettierignore +1 -0
  15. package/.prettierrc +1 -0
  16. package/.vscode/launch.json +42 -0
  17. package/CODE_OF_CONDUCT.md +76 -0
  18. package/Dockerfile +17 -0
  19. package/LICENSE +21 -0
  20. package/README.md +3 -0
  21. package/SECURITY.md +5 -0
  22. package/__tests__/actions/cacheTest.ts +58 -0
  23. package/__tests__/actions/randomNumber.ts +26 -0
  24. package/__tests__/actions/recursiveAction.ts +16 -0
  25. package/__tests__/actions/sleepTest.ts +24 -0
  26. package/__tests__/actions/status.ts +17 -0
  27. package/__tests__/actions/swagger.ts +76 -0
  28. package/__tests__/actions/validationTest.ts +63 -0
  29. package/__tests__/cli/cli.ts +126 -0
  30. package/__tests__/core/api.ts +632 -0
  31. package/__tests__/core/cache.ts +400 -0
  32. package/__tests__/core/chatRoom.ts +589 -0
  33. package/__tests__/core/cli.ts +349 -0
  34. package/__tests__/core/cluster.ts +132 -0
  35. package/__tests__/core/config.ts +78 -0
  36. package/__tests__/core/errors.ts +112 -0
  37. package/__tests__/core/log.ts +23 -0
  38. package/__tests__/core/middleware.ts +427 -0
  39. package/__tests__/core/plugins/partialPlugin.ts +94 -0
  40. package/__tests__/core/plugins/withPlugin.ts +88 -0
  41. package/__tests__/core/plugins/withoutPlugin.ts +81 -0
  42. package/__tests__/core/process.ts +42 -0
  43. package/__tests__/core/specHelper.ts +330 -0
  44. package/__tests__/core/staticFile/compression.ts +99 -0
  45. package/__tests__/core/staticFile/staticFile.ts +180 -0
  46. package/__tests__/core/tasks/customQueueFunction.ts +67 -0
  47. package/__tests__/core/tasks/fullWorkerFlow.ts +199 -0
  48. package/__tests__/core/tasks/tasks.ts +605 -0
  49. package/__tests__/integration/browser.ts +133 -0
  50. package/__tests__/integration/ioredis-mock.ts +194 -0
  51. package/__tests__/integration/sendBuffer.ts +97 -0
  52. package/__tests__/integration/sendFile.ts +24 -0
  53. package/__tests__/integration/sharedFingerprint.ts +82 -0
  54. package/__tests__/integration/taskFlow.ts +110 -0
  55. package/__tests__/jest.ts +5 -0
  56. package/__tests__/modules/action.ts +103 -0
  57. package/__tests__/modules/config.ts +19 -0
  58. package/__tests__/modules/utils/ensureNoTsHeaderOrSpecFiles.ts +24 -0
  59. package/__tests__/servers/web/allowedRequestHosts.ts +88 -0
  60. package/__tests__/servers/web/enableMultiples.ts +83 -0
  61. package/__tests__/servers/web/fileUpload.ts +79 -0
  62. package/__tests__/servers/web/jsonp.ts +57 -0
  63. package/__tests__/servers/web/nonMultiples.ts +83 -0
  64. package/__tests__/servers/web/rawBody.ts +208 -0
  65. package/__tests__/servers/web/returnErrorCodes.ts +55 -0
  66. package/__tests__/servers/web/routes/deepRoutes.ts +96 -0
  67. package/__tests__/servers/web/routes/routes.ts +579 -0
  68. package/__tests__/servers/web/routes/veryDeepRoutes.ts +92 -0
  69. package/__tests__/servers/web/web.ts +1031 -0
  70. package/__tests__/servers/websocket.ts +795 -0
  71. package/__tests__/tasks/runAction.ts +37 -0
  72. package/__tests__/template.ts.example +20 -0
  73. package/__tests__/testCliCommands/hello.ts +44 -0
  74. package/__tests__/testPlugin/public/plugin.html +1 -0
  75. package/__tests__/testPlugin/src/actions/pluginAction.ts +14 -0
  76. package/__tests__/testPlugin/src/bin/hello.ts +22 -0
  77. package/__tests__/testPlugin/src/initializers/pluginInitializer.ts +17 -0
  78. package/__tests__/testPlugin/src/tasks/pluginTask.ts +15 -0
  79. package/__tests__/testPlugin/tsconfig.json +10 -0
  80. package/__tests__/utils/utils.ts +492 -0
  81. package/app.json +23 -0
  82. package/bin/deploy-docs +39 -0
  83. package/client/ActionheroWebsocketClient.js +277 -0
  84. package/docker-compose.yml +73 -0
  85. package/package.json +24 -0
  86. package/public/chat.html +194 -0
  87. package/public/css/cosmo.css +12 -0
  88. package/public/favicon.ico +0 -0
  89. package/public/index.html +115 -0
  90. package/public/javascript/.gitkeep +0 -0
  91. package/public/linkedSession.html +80 -0
  92. package/public/logo/actionhero-small.png +0 -0
  93. package/public/logo/actionhero.png +0 -0
  94. package/public/pixel.gif +0 -0
  95. package/public/simple.html +2 -0
  96. package/public/swagger.html +32 -0
  97. package/public/websocketLoadTest.html +322 -0
  98. package/src/actions/cacheTest.ts +58 -0
  99. package/src/actions/createChatRoom.ts +20 -0
  100. package/src/actions/randomNumber.ts +17 -0
  101. package/src/actions/recursiveAction.ts +13 -0
  102. package/src/actions/sendFile.ts +12 -0
  103. package/src/actions/sleepTest.ts +40 -0
  104. package/src/actions/status.ts +73 -0
  105. package/src/actions/swagger.ts +155 -0
  106. package/src/actions/validationTest.ts +36 -0
  107. package/src/bin/actionhero.ts +225 -0
  108. package/src/bin/methods/actions/list.ts +30 -0
  109. package/src/bin/methods/console.ts +26 -0
  110. package/src/bin/methods/generate/action.ts +58 -0
  111. package/src/bin/methods/generate/cli.ts +51 -0
  112. package/src/bin/methods/generate/initializer.ts +54 -0
  113. package/src/bin/methods/generate/plugin.ts +57 -0
  114. package/src/bin/methods/generate/server.ts +38 -0
  115. package/src/bin/methods/generate/task.ts +68 -0
  116. package/src/bin/methods/generate.ts +176 -0
  117. package/src/bin/methods/task/enqueue.ts +35 -0
  118. package/src/classes/action.ts +98 -0
  119. package/src/classes/actionProcessor.ts +463 -0
  120. package/src/classes/api.ts +51 -0
  121. package/src/classes/cli.ts +67 -0
  122. package/src/classes/config.ts +15 -0
  123. package/src/classes/connection.ts +321 -0
  124. package/src/classes/exceptionReporter.ts +9 -0
  125. package/src/classes/initializer.ts +59 -0
  126. package/src/classes/initializers.ts +5 -0
  127. package/src/classes/input.ts +9 -0
  128. package/src/classes/inputs.ts +34 -0
  129. package/src/classes/process/actionheroVersion.ts +15 -0
  130. package/src/classes/process/env.ts +16 -0
  131. package/src/classes/process/id.ts +34 -0
  132. package/src/classes/process/pid.ts +32 -0
  133. package/src/classes/process/projectRoot.ts +16 -0
  134. package/src/classes/process/typescript.ts +47 -0
  135. package/src/classes/process.ts +479 -0
  136. package/src/classes/server.ts +251 -0
  137. package/src/classes/task.ts +87 -0
  138. package/src/config/api.ts +107 -0
  139. package/src/config/errors.ts +162 -0
  140. package/src/config/logger.ts +113 -0
  141. package/src/config/plugins.ts +37 -0
  142. package/src/config/redis.ts +78 -0
  143. package/src/config/routes.ts +44 -0
  144. package/src/config/tasks.ts +84 -0
  145. package/src/config/web.ts +136 -0
  146. package/src/config/websocket.ts +62 -0
  147. package/src/index.ts +46 -0
  148. package/src/initializers/actions.ts +125 -0
  149. package/src/initializers/chatRoom.ts +214 -0
  150. package/src/initializers/connections.ts +124 -0
  151. package/src/initializers/exceptions.ts +155 -0
  152. package/src/initializers/params.ts +52 -0
  153. package/src/initializers/redis.ts +191 -0
  154. package/src/initializers/resque.ts +248 -0
  155. package/src/initializers/routes.ts +229 -0
  156. package/src/initializers/servers.ts +134 -0
  157. package/src/initializers/specHelper.ts +195 -0
  158. package/src/initializers/staticFile.ts +253 -0
  159. package/src/initializers/tasks.ts +188 -0
  160. package/src/modules/action.ts +89 -0
  161. package/src/modules/cache.ts +326 -0
  162. package/src/modules/chatRoom.ts +321 -0
  163. package/src/modules/config.ts +246 -0
  164. package/src/modules/log.ts +62 -0
  165. package/src/modules/redis.ts +93 -0
  166. package/src/modules/route.ts +59 -0
  167. package/src/modules/specHelper.ts +182 -0
  168. package/src/modules/task.ts +527 -0
  169. package/src/modules/utils/argv.ts +3 -0
  170. package/src/modules/utils/arrayStartingMatch.ts +21 -0
  171. package/src/modules/utils/arrayUnique.ts +15 -0
  172. package/src/modules/utils/collapseObjectToArray.ts +33 -0
  173. package/src/modules/utils/deepCopy.ts +3 -0
  174. package/src/modules/utils/ensureNoTsHeaderOrSpecFiles.ts +19 -0
  175. package/src/modules/utils/eventLoopDelay.ts +34 -0
  176. package/src/modules/utils/fileUtils.ts +119 -0
  177. package/src/modules/utils/filterObjectForLogging.ts +51 -0
  178. package/src/modules/utils/filterResponseForLogging.ts +53 -0
  179. package/src/modules/utils/getExternalIPAddress.ts +17 -0
  180. package/src/modules/utils/hashMerge.ts +63 -0
  181. package/src/modules/utils/isPlainObject.ts +45 -0
  182. package/src/modules/utils/isRunning.ts +7 -0
  183. package/src/modules/utils/parseCookies.ts +20 -0
  184. package/src/modules/utils/parseHeadersForClientAddress.ts +53 -0
  185. package/src/modules/utils/parseIPv6URI.ts +24 -0
  186. package/src/modules/utils/replaceDistWithSrc.ts +9 -0
  187. package/src/modules/utils/safeGlob.ts +6 -0
  188. package/src/modules/utils/sleep.ts +8 -0
  189. package/src/modules/utils/sortGlobalMiddleware.ts +17 -0
  190. package/src/modules/utils/sourceRelativeLinkPath.ts +29 -0
  191. package/src/modules/utils.ts +66 -0
  192. package/src/server.ts +20 -0
  193. package/src/servers/web.ts +894 -0
  194. package/src/servers/websocket.ts +304 -0
  195. package/src/tasks/runAction.ts +29 -0
  196. package/tea.yaml +9 -0
  197. package/templates/README.md.template +17 -0
  198. package/templates/action.ts.template +15 -0
  199. package/templates/boot.js.template +9 -0
  200. package/templates/cli.ts.template +15 -0
  201. package/templates/gitignore.template +23 -0
  202. package/templates/initializer.ts.template +17 -0
  203. package/templates/package-plugin.json.template +12 -0
  204. package/templates/package.json.template +45 -0
  205. package/templates/projectMap.txt +39 -0
  206. package/templates/projectServer.ts.template +20 -0
  207. package/templates/server.ts.template +37 -0
  208. package/templates/task.ts.template +16 -0
  209. package/templates/test/action.ts.template +13 -0
  210. package/templates/test/task.ts.template +20 -0
  211. package/tsconfig.json +11 -0
@@ -0,0 +1,125 @@
1
+ import * as path from "path";
2
+ import { api, config, log, utils, Initializer, Action } from "../index";
3
+ import { safeGlobSync } from "../modules/utils/safeGlob";
4
+ import * as ActionModule from "./../modules/action";
5
+
6
+ export interface ActionsApi {
7
+ actions: {
8
+ [key: string]: {
9
+ [key: string]: Action;
10
+ };
11
+ };
12
+ versions: {
13
+ [key: string]: Array<string | number>;
14
+ };
15
+ middleware: {
16
+ [key: string]: ActionModule.action.ActionMiddleware;
17
+ };
18
+ globalMiddleware: Array<string>;
19
+ loadFile?: Function;
20
+ }
21
+
22
+ export class ActionsInitializer extends Initializer {
23
+ constructor() {
24
+ super();
25
+ this.name = "actions";
26
+ this.loadPriority = 410;
27
+ }
28
+
29
+ async initialize() {
30
+ api.actions = {
31
+ actions: {},
32
+ versions: {},
33
+ middleware: {},
34
+ globalMiddleware: [],
35
+ };
36
+
37
+ api.actions.loadFile = async (
38
+ fullFilePath: string,
39
+ reload: boolean = false,
40
+ ) => {
41
+ const loadMessage = (action: Action) => {
42
+ if (reload) {
43
+ log(
44
+ `action reloaded: ${action.name} @ v${action.version}, ${fullFilePath}`,
45
+ "info",
46
+ );
47
+ } else {
48
+ log(
49
+ `action loaded: ${action.name} @ v${action.version}, ${fullFilePath}`,
50
+ "debug",
51
+ );
52
+ }
53
+ };
54
+
55
+ let action;
56
+
57
+ try {
58
+ let collection = await import(fullFilePath);
59
+ if (typeof collection === "function") {
60
+ collection = [collection];
61
+ }
62
+ for (const i in collection) {
63
+ action = new collection[i]();
64
+ await action.validate(api);
65
+ if (!api.actions.actions[action.name]) {
66
+ api.actions.actions[action.name] = {};
67
+ }
68
+
69
+ if (!api.actions.versions[action.name]) {
70
+ api.actions.versions[action.name] = [];
71
+ }
72
+
73
+ if (api.actions.actions[action.name][action.version] && !reload) {
74
+ log(
75
+ `an existing action with the same name \`${action.name}\` will be overridden by the file ${fullFilePath}`,
76
+ "warning",
77
+ );
78
+ }
79
+
80
+ api.actions.actions[action.name][action.version] = action;
81
+ api.actions.versions[action.name].push(action.version);
82
+ api.actions.versions[action.name].sort();
83
+ loadMessage(action);
84
+ }
85
+ } catch (error) {
86
+ try {
87
+ api.exceptionHandlers.initializer(error, fullFilePath);
88
+ delete api.actions.actions[action.name][action.version];
89
+ } catch (_error) {
90
+ throw error;
91
+ }
92
+ }
93
+ };
94
+
95
+ for (const p of config.general.paths.action) {
96
+ let files = safeGlobSync(path.join(p, "**", "**/*(*.js|*.ts)"));
97
+ files = utils.ensureNoTsHeaderOrSpecFiles(files);
98
+ for (const j in files) {
99
+ await api.actions.loadFile(files[j]);
100
+ }
101
+ }
102
+
103
+ for (const plugin of Object.values(config.plugins)) {
104
+ if (plugin.actions !== false) {
105
+ const pluginPath: string = path.normalize(plugin.path);
106
+
107
+ // old style at the root of the project
108
+ let files = safeGlobSync(
109
+ path.join(pluginPath, "actions", "**", "*.js"),
110
+ );
111
+
112
+ files = files.concat(
113
+ safeGlobSync(path.join(pluginPath, "dist", "actions", "**", "*.js")),
114
+ );
115
+
116
+ utils
117
+ .ensureNoTsHeaderOrSpecFiles(files)
118
+ .forEach((f) => api.actions.loadFile(f));
119
+ }
120
+ }
121
+
122
+ // now that the actions are loaded, we can add all the inputs to api.params
123
+ api.params.buildPostVariables();
124
+ }
125
+ }
@@ -0,0 +1,214 @@
1
+ import { api, config, id, log, chatRoom, redis, Initializer } from "../index";
2
+ import { Connection } from "../classes/connection";
3
+ import * as ChatModule from "./../modules/chatRoom";
4
+
5
+ export interface ChatRoomApi {
6
+ middleware: {
7
+ [key: string]: ChatModule.chatRoom.ChatMiddleware;
8
+ };
9
+ globalMiddleware: Array<string>;
10
+ keys: { [keys: string]: string };
11
+ messageChannel: string;
12
+ broadcast: ChatRoomInitializer["broadcast"];
13
+ generateMessagePayload: ChatRoomInitializer["generateMessagePayload"];
14
+ incomingMessage: ChatRoomInitializer["incomingMessage"];
15
+ incomingMessagePerConnection?: ChatRoomInitializer["incomingMessagePerConnection"];
16
+ runMiddleware: ChatRoomInitializer["runMiddleware"];
17
+ removeMember: ChatRoomInitializer["removeMember"];
18
+ }
19
+
20
+ export type ChatMiddlewareDirections =
21
+ | "join"
22
+ | "leave"
23
+ | "onSayReceive"
24
+ | "say";
25
+
26
+ export type MessagePayloadType = ReturnType<
27
+ typeof api.chatRoom.generateMessagePayload
28
+ >;
29
+
30
+ /**
31
+ * Chat & Realtime Communication Methods
32
+ */
33
+ export class ChatRoomInitializer extends Initializer {
34
+ constructor() {
35
+ super();
36
+ this.name = "chatRoom";
37
+ this.loadPriority = 520;
38
+ this.startPriority = 200;
39
+ }
40
+
41
+ broadcast = async (
42
+ connection: Partial<Connection>,
43
+ room: string,
44
+ message: object | Array<any> | string,
45
+ ) => {
46
+ if (!connection) connection = {};
47
+
48
+ if (!room || !message) {
49
+ throw new Error(
50
+ config.errors.connectionRoomAndMessage(connection as Connection),
51
+ );
52
+ } else if (
53
+ connection.rooms === undefined ||
54
+ connection.rooms.indexOf(room) > -1
55
+ ) {
56
+ const payload: ChatModule.chatRoom.ChatPubSubMessage = {
57
+ messageType: "chat",
58
+ serverToken: config.general.serverToken,
59
+ serverId: id,
60
+ message: message,
61
+ sentAt: new Date().getTime(),
62
+ connection: {
63
+ id: connection.id || "0",
64
+ room: room,
65
+ },
66
+ };
67
+
68
+ const messagePayload = api.chatRoom.generateMessagePayload(payload);
69
+ const newPayload = await api.chatRoom.runMiddleware(
70
+ connection,
71
+ messagePayload.room,
72
+ "onSayReceive",
73
+ messagePayload,
74
+ );
75
+
76
+ if (newPayload !== null && newPayload !== undefined) {
77
+ const payloadToSend: ChatModule.chatRoom.ChatPubSubMessage = {
78
+ messageType: "chat",
79
+ serverToken: config.general.serverToken,
80
+ serverId: id,
81
+ message: newPayload.message,
82
+ sentAt: newPayload.sentAt,
83
+ connection: {
84
+ id: newPayload.from,
85
+ room: newPayload.room,
86
+ },
87
+ };
88
+
89
+ await redis.publish(payloadToSend);
90
+ }
91
+ } else {
92
+ throw new Error(
93
+ config.errors.connectionNotInRoom(connection as Connection, room),
94
+ );
95
+ }
96
+ };
97
+
98
+ generateMessagePayload = (message: chatRoom.ChatPubSubMessage) => {
99
+ return {
100
+ message: message.message,
101
+ room: message.connection.room,
102
+ from: message.connection.id,
103
+ context: "user",
104
+ sentAt: message.sentAt,
105
+ } as Record<string, any>; // we want to relax the return type to a Record so that this method can be modified by users
106
+ };
107
+
108
+ incomingMessage = (message: ChatModule.chatRoom.ChatPubSubMessage) => {
109
+ const messagePayload = api.chatRoom.generateMessagePayload(message);
110
+ Object.keys(api.connections.connections).forEach((connectionId) => {
111
+ const connection = api.connections.connections[connectionId];
112
+ // we can parallelize this, no need to await
113
+ api.chatRoom.incomingMessagePerConnection(connection, messagePayload);
114
+ });
115
+ };
116
+
117
+ incomingMessagePerConnection = async (
118
+ connection: Connection,
119
+ messagePayload: MessagePayloadType,
120
+ ) => {
121
+ if (
122
+ connection.canChat === true &&
123
+ connection.rooms.indexOf(messagePayload.room) > -1
124
+ ) {
125
+ try {
126
+ const newMessagePayload = await api.chatRoom.runMiddleware(
127
+ connection,
128
+ messagePayload.room,
129
+ "say",
130
+ messagePayload,
131
+ );
132
+ if (newMessagePayload !== null) {
133
+ connection.sendMessage(newMessagePayload, "say");
134
+ }
135
+ } catch (error) {
136
+ log(error, "warning", { messagePayload, connection });
137
+ }
138
+ }
139
+ };
140
+
141
+ runMiddleware = async (
142
+ connection: Partial<Connection>,
143
+ room: string,
144
+ direction: ChatMiddlewareDirections,
145
+ messagePayload?: MessagePayloadType,
146
+ ) => {
147
+ let newMessagePayload: MessagePayloadType;
148
+ if (messagePayload) newMessagePayload = Object.assign({}, messagePayload);
149
+
150
+ for (const name of api.chatRoom.globalMiddleware) {
151
+ const m = api.chatRoom.middleware[name];
152
+ if (typeof m[direction] === "function") {
153
+ if (messagePayload) {
154
+ newMessagePayload =
155
+ (await m[direction](connection, room, newMessagePayload)) ?? null;
156
+ } else {
157
+ await m[direction](connection, room);
158
+ }
159
+ }
160
+ }
161
+ return newMessagePayload;
162
+ };
163
+
164
+ removeMember = (
165
+ connectionId: string,
166
+ room: string,
167
+ toWaitRemote: boolean = true,
168
+ ) => chatRoom.removeMember(connectionId, room, toWaitRemote);
169
+
170
+ async initialize() {
171
+ api.chatRoom = {
172
+ middleware: {},
173
+ globalMiddleware: [],
174
+ messageChannel: "/actionhero/chat/chat",
175
+ keys: {
176
+ rooms: "actionhero:chatRoom:rooms",
177
+ members: "actionhero:chatRoom:members:",
178
+ },
179
+ broadcast: this.broadcast,
180
+ generateMessagePayload: this.generateMessagePayload,
181
+ incomingMessage: this.incomingMessage,
182
+ incomingMessagePerConnection: this.incomingMessagePerConnection,
183
+ runMiddleware: this.runMiddleware,
184
+ removeMember: this.removeMember,
185
+ };
186
+ }
187
+
188
+ async start() {
189
+ api.redis.subscriptionHandlers.chat = (
190
+ message: ChatModule.chatRoom.ChatPubSubMessage,
191
+ ) => {
192
+ if (api.chatRoom) {
193
+ api.chatRoom.incomingMessage(message);
194
+ }
195
+ };
196
+
197
+ for (const [room, options] of Object.entries(
198
+ config.general.startingChatRooms,
199
+ )) {
200
+ log(`ensuring the existence of the chatRoom: ${room}`, "debug");
201
+ try {
202
+ await chatRoom.add(room);
203
+ } catch (error) {
204
+ if (
205
+ !error
206
+ .toString()
207
+ .match(await config.errors.connectionRoomExists(room))
208
+ ) {
209
+ throw error;
210
+ }
211
+ }
212
+ }
213
+ }
214
+ }
@@ -0,0 +1,124 @@
1
+ import { api, config, redis, Initializer, Connection } from "../index";
2
+
3
+ /**
4
+ * ```js
5
+ *var connectionMiddleware = {
6
+ *name: 'connection middleware',
7
+ *priority: 1000,
8
+ *create: (connection) => {
9
+ * // do stuff
10
+ *},
11
+ *destroy:(connection) => {
12
+ * // do stuff
13
+ *}
14
+ *}
15
+ * ```
16
+ */
17
+ export interface ConnectionMiddleware {
18
+ /**Unique name for the middleware. */
19
+ name: string;
20
+ /**Module load order. Defaults to `api.config.general.defaultMiddlewarePriority`. */
21
+ priority?: number;
22
+ /**Called for each new connection when it is created. Connection is passed to the event handler*/
23
+ create?: Function;
24
+ /**Called for each connection before it is destroyed. Connection is passed to the event handler*/
25
+ destroy?: Function;
26
+ }
27
+
28
+ export interface ConnectionsApi {
29
+ connections: {
30
+ [key: string]: Connection;
31
+ };
32
+ middleware: {
33
+ [key: string]: ConnectionMiddleware;
34
+ };
35
+ globalMiddleware: Array<string>;
36
+ apply: ConnectionsInitializer["apply"];
37
+ applyResponder: ConnectionsInitializer["applyResponder"];
38
+ addMiddleware: ConnectionsInitializer["addMiddleware"];
39
+ cleanConnection: ConnectionsInitializer["cleanConnection"];
40
+ }
41
+
42
+ export class ConnectionsInitializer extends Initializer {
43
+ constructor() {
44
+ super();
45
+ this.name = "connections";
46
+ this.loadPriority = 400;
47
+ }
48
+
49
+ apply = async (
50
+ connectionId: string,
51
+ method?: string,
52
+ args?: any[] | Record<string, any>,
53
+ ) => {
54
+ return redis.doCluster<Connection>(
55
+ "api.connections.applyResponder",
56
+ [connectionId, method, args],
57
+ connectionId,
58
+ true,
59
+ );
60
+ };
61
+
62
+ applyResponder = async (
63
+ connectionId: string,
64
+ method: keyof InstanceType<typeof Connection>,
65
+ args: any,
66
+ ) => {
67
+ const connection = api.connections.connections[connectionId];
68
+ if (!connection) return;
69
+
70
+ if (method && args) {
71
+ if (method === "sendMessage" || method === "sendFile") {
72
+ await connection[method](args);
73
+ } else {
74
+ //@ts-ignore
75
+ await connection[method].apply(connection, args);
76
+ }
77
+ }
78
+ return api.connections.cleanConnection(connection);
79
+ };
80
+
81
+ addMiddleware = (data: ConnectionMiddleware) => {
82
+ if (!data.name) {
83
+ throw new Error("middleware.name is required");
84
+ }
85
+ if (!data.priority) {
86
+ data.priority = config.general.defaultMiddlewarePriority;
87
+ }
88
+ data.priority = Number(data.priority);
89
+ api.connections.middleware[data.name] = data;
90
+
91
+ api.connections.globalMiddleware.push(data.name);
92
+ api.connections.globalMiddleware.sort(
93
+ (a, b) =>
94
+ api.connections.middleware[a].priority -
95
+ api.connections.middleware[b].priority,
96
+ );
97
+ };
98
+
99
+ cleanConnection = (connection: Connection) => {
100
+ const clean: { [key: string]: any } = {};
101
+ for (const [key, value] of Object.entries(connection)) {
102
+ if (key !== "rawConnection" && key !== "api") {
103
+ try {
104
+ JSON.stringify(value);
105
+ clean[key] = value;
106
+ } catch (error) {}
107
+ }
108
+ }
109
+
110
+ return clean;
111
+ };
112
+
113
+ async initialize() {
114
+ api.connections = {
115
+ connections: {},
116
+ middleware: {},
117
+ globalMiddleware: [],
118
+ apply: this.apply,
119
+ applyResponder: this.applyResponder,
120
+ addMiddleware: this.addMiddleware,
121
+ cleanConnection: this.cleanConnection,
122
+ };
123
+ }
124
+ }
@@ -0,0 +1,155 @@
1
+ import { api, config, log, Initializer, Action } from "../index";
2
+ import { ExceptionReporter } from "../classes/exceptionReporter";
3
+ import { ParsedJob } from "node-resque";
4
+ import { ActionheroLogLevel } from "../modules/log";
5
+
6
+ export interface ExceptionHandlerAPI {
7
+ reporters: Array<ExceptionReporter>;
8
+ report: ExceptionsInitializer["report"];
9
+ initializer: ExceptionsInitializer["initializer"];
10
+ action: ExceptionsInitializer["action"];
11
+ task: ExceptionsInitializer["task"];
12
+ }
13
+
14
+ /**
15
+ * Handlers for when things go wrong.
16
+ */
17
+ export class ExceptionsInitializer extends Initializer {
18
+ constructor() {
19
+ super();
20
+ this.name = "exceptions";
21
+ this.loadPriority = 1;
22
+ }
23
+
24
+ report = (
25
+ error: NodeJS.ErrnoException,
26
+ type: string,
27
+ name: string,
28
+ objects?: any,
29
+ severity?: ActionheroLogLevel,
30
+ ) => {
31
+ if (!severity) severity = "error";
32
+
33
+ for (const reporter of api.exceptionHandlers.reporters) {
34
+ reporter(error, type, name, objects, severity);
35
+ }
36
+ };
37
+
38
+ initializer = (error: NodeJS.ErrnoException, fullFilePath: string) => {
39
+ const name = "initializer:" + fullFilePath;
40
+ api.exceptionHandlers.report(
41
+ error,
42
+ "initializer",
43
+ name,
44
+ { fullFilePath: fullFilePath },
45
+ "alert",
46
+ );
47
+ };
48
+
49
+ action = (
50
+ error: NodeJS.ErrnoException,
51
+ {
52
+ to,
53
+ action,
54
+ params,
55
+ duration,
56
+ response,
57
+ }: {
58
+ to: string;
59
+ action: Action["name"];
60
+ params: string;
61
+ duration: number;
62
+ response: string;
63
+ },
64
+ ) => {
65
+ api.exceptionHandlers.report(
66
+ error,
67
+ "action",
68
+ `action: ${action}`,
69
+ { to, action, params, duration, error, response },
70
+ "alert",
71
+ );
72
+ };
73
+
74
+ task = (
75
+ error: NodeJS.ErrnoException,
76
+ queue: string,
77
+ task: ParsedJob,
78
+ workerId: string | number,
79
+ ) => {
80
+ let simpleName;
81
+ try {
82
+ simpleName = task["class"];
83
+ } catch (e) {
84
+ simpleName = error.message;
85
+ }
86
+ const name = "task:" + simpleName;
87
+ api.exceptionHandlers.report(
88
+ error,
89
+ "task",
90
+ name,
91
+ { task: task, queue: queue, workerId: workerId },
92
+ config.tasks.workerLogging.failure,
93
+ );
94
+ };
95
+
96
+ async initialize() {
97
+ api.exceptionHandlers = {
98
+ reporters: [],
99
+ report: this.report,
100
+ initializer: this.initializer,
101
+ action: this.action,
102
+ task: this.task,
103
+ };
104
+
105
+ api.exceptionHandlers.reporters.push(consoleReporter);
106
+ }
107
+ }
108
+
109
+ const consoleReporter: ExceptionReporter = (
110
+ error: NodeJS.ErrnoException & { [key: string]: any },
111
+ type,
112
+ name,
113
+ objects,
114
+ severity,
115
+ ) => {
116
+ let message = "";
117
+ const data = error["data"] ?? {};
118
+
119
+ if (type === "uncaught") {
120
+ message = `Uncaught ${name}`;
121
+ } else if (type === "action") {
122
+ // no need to log anything, it was handled already by the actionProcessor
123
+ } else if (type === "initializer") {
124
+ message = `Error from Initializer`;
125
+ } else if (type === "task") {
126
+ message = `Error from Task`;
127
+ data["name"] = name;
128
+ data["queue"] = objects.queue;
129
+ data["worker"] = objects.workerId;
130
+ data["arguments"] = objects?.task?.args
131
+ ? JSON.stringify(objects.task.args[0])
132
+ : undefined;
133
+ } else {
134
+ message = `Error: ${error?.message || error.toString()}`;
135
+ Object.getOwnPropertyNames(error)
136
+ .filter((prop) => prop !== "message")
137
+ .sort((a, b) => (a === "stack" || b === "stack" ? -1 : 1))
138
+ .forEach((prop) => (data[prop] = error[prop]));
139
+ data["type"] = type;
140
+ data["name"] = name;
141
+ data["data"] = objects;
142
+ }
143
+
144
+ if (error["stack"]) {
145
+ data["stack"] = error.stack;
146
+ } else {
147
+ data["stack"] = error.message ?? error.toString();
148
+ }
149
+
150
+ try {
151
+ if (message) log(message, severity, data);
152
+ } catch (e) {
153
+ console.log(message, data);
154
+ }
155
+ };
@@ -0,0 +1,52 @@
1
+ import { api, utils, Initializer } from "../index";
2
+
3
+ export interface ParamsApi {
4
+ globalSafeParams?: Array<string>;
5
+ postVariables: Array<string>;
6
+ buildPostVariables: ParamsInitializer["buildPostVariables"];
7
+ }
8
+
9
+ /**
10
+ * Collects and formats allowed params for this server.
11
+ */
12
+ export class ParamsInitializer extends Initializer {
13
+ constructor() {
14
+ super();
15
+ this.name = "params";
16
+ this.loadPriority = 400;
17
+ }
18
+
19
+ buildPostVariables = () => {
20
+ const postVariables = [];
21
+ let i: string;
22
+ let j: string | number;
23
+
24
+ api.params.globalSafeParams.forEach((p) => {
25
+ postVariables.push(p);
26
+ });
27
+
28
+ for (i in api.actions.actions) {
29
+ for (j in api.actions.actions[i]) {
30
+ const action = api.actions.actions[i][j];
31
+ for (const key in action.inputs) postVariables.push(key);
32
+ }
33
+ }
34
+
35
+ api.params.postVariables = utils.arrayUnique(postVariables);
36
+ return api.params.postVariables;
37
+ };
38
+
39
+ async initialize() {
40
+ api.params = {
41
+ postVariables: [],
42
+ buildPostVariables: this.buildPostVariables,
43
+ globalSafeParams: [
44
+ "file",
45
+ "apiVersion",
46
+ "callback",
47
+ "action",
48
+ "messageId",
49
+ ],
50
+ };
51
+ }
52
+ }