zcatalyst-cli 1.17.6 → 1.18.0-beta.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.
Files changed (124) hide show
  1. package/docs/commands/event/generate/job.toml +7 -0
  2. package/docs/commands/functions/shell.toml +4 -0
  3. package/docs/endpoints/lib/job-scheduling.toml +3 -0
  4. package/docs/internal/command.toml +5 -0
  5. package/docs/shell/dependencies/tunnel-server.toml +4 -0
  6. package/docs/shell/index.toml +7 -0
  7. package/lib/appsail-utils.js +3 -3
  8. package/lib/authentication/index.js +1 -0
  9. package/lib/command_needs/rc.js +1 -1
  10. package/lib/commands/appsail/add.js +1 -0
  11. package/lib/commands/client/setup.js +1 -0
  12. package/lib/commands/event/generate/job.js +82 -0
  13. package/lib/commands/functions/add.js +1 -0
  14. package/lib/commands/functions/delete.js +2 -4
  15. package/lib/commands/functions/setup.js +1 -0
  16. package/lib/commands/functions/shell.js +98 -1
  17. package/lib/commands/index.js +1 -0
  18. package/lib/commands/init.js +2 -6
  19. package/lib/commands/login.js +1 -0
  20. package/lib/commands/logout.js +1 -0
  21. package/lib/commands/pull.js +1 -0
  22. package/lib/commands/serve.js +2 -8
  23. package/lib/commands/whoami.js +1 -0
  24. package/lib/deploy/features/appsail/index.js +19 -17
  25. package/lib/deploy/features/appsail/utils.js +4 -5
  26. package/lib/endpoints/index.js +15 -1
  27. package/lib/endpoints/lib/appsail.js +7 -1
  28. package/lib/endpoints/lib/job-scheduling.js +61 -0
  29. package/lib/endpoints/lib/sdk.js +2 -2
  30. package/lib/endpoints/lib/tunnel.js +66 -0
  31. package/lib/express_middlewares/logger.js +2 -4
  32. package/lib/fn-utils/lib/common.js +2 -3
  33. package/lib/fn-utils/lib/java.js +1 -1
  34. package/lib/fn-utils/lib/python.js +2 -2
  35. package/lib/fn-watcher.js +1 -1
  36. package/lib/init/dependencies/python/ensure-python.js +6 -8
  37. package/lib/init/features/appsail/index.js +14 -10
  38. package/lib/init/features/functions/index.js +4 -0
  39. package/lib/init/features/functions/languages/python.js +21 -5
  40. package/lib/internal/api.js +17 -1
  41. package/lib/internal/command.js +28 -5
  42. package/lib/port-resolver.js +1 -1
  43. package/lib/repl-server.js +9 -0
  44. package/lib/serve/features/appsail.js +2 -3
  45. package/lib/serve/index.js +1 -2
  46. package/lib/serve/server/index.js +8 -9
  47. package/lib/serve/server/lib/appsail/index.js +24 -34
  48. package/lib/serve/server/lib/java/aio_server/lib/catalyst-cli-java-runtime-1.0.0.jar +0 -0
  49. package/lib/serve/server/lib/java/aio_server/lib/catalyst-function-sdk-1.0.0.jar +0 -0
  50. package/lib/serve/server/lib/java/aio_server/lib/catalyst-java-runtime-1.0.0.jar +0 -0
  51. package/lib/serve/server/lib/java/index.js +2 -2
  52. package/lib/serve/server/lib/master/appsail.js +53 -0
  53. package/lib/serve/server/lib/master/functions.js +34 -0
  54. package/lib/serve/server/lib/master/index.js +155 -0
  55. package/lib/{express_middlewares/unknownReqProxy.js → serve/server/lib/master/unknown-req-proxy.js} +4 -7
  56. package/lib/serve/server/lib/master/utils.js +130 -0
  57. package/lib/serve/server/lib/master/web-client.js +39 -0
  58. package/lib/serve/server/lib/node/index.js +3 -3
  59. package/lib/serve/server/lib/python/index.js +6 -3
  60. package/lib/shell/dependencies/http-functions.js +21 -8
  61. package/lib/shell/dependencies/invoker/bio/java/JavabioInvoker.java +28 -32
  62. package/lib/shell/dependencies/invoker/bio/java/lib/catalyst-function-sdk-1.0.0.jar +0 -0
  63. package/lib/shell/dependencies/invoker/bio/node.mjs +2 -2
  64. package/lib/shell/dependencies/invoker/cron/java/JavacronInvoker.java +62 -13
  65. package/lib/shell/dependencies/invoker/cron/java/lib/catalyst-function-sdk-1.0.0.jar +0 -0
  66. package/lib/shell/dependencies/invoker/cron/node.mjs +28 -24
  67. package/lib/shell/dependencies/invoker/event/java/JavaeventInvoker.java +41 -6
  68. package/lib/shell/dependencies/invoker/event/java/lib/catalyst-function-sdk-1.0.0.jar +0 -0
  69. package/lib/shell/dependencies/invoker/event/node.mjs +23 -9
  70. package/lib/shell/dependencies/invoker/integ/java/JavaintegInvoker.java +3 -3
  71. package/lib/shell/dependencies/invoker/integ/java/lib/catalyst-function-sdk-1.0.0.jar +0 -0
  72. package/lib/shell/dependencies/invoker/integ/node.mjs +6 -6
  73. package/lib/shell/dependencies/invoker/job/java/JavajobInvoker.java +254 -0
  74. package/lib/shell/dependencies/invoker/job/java/lib/catalyst-function-sdk-1.0.0.jar +0 -0
  75. package/lib/shell/dependencies/invoker/job/java/lib/org.json.jar +0 -0
  76. package/lib/shell/dependencies/invoker/job/node.mjs +93 -0
  77. package/lib/shell/dependencies/local-function.js +399 -200
  78. package/lib/shell/dependencies/tunnel-server.js +173 -0
  79. package/lib/shell/index.js +62 -2
  80. package/lib/shell/prepare/languages/index.js +4 -4
  81. package/lib/shell/prepare/languages/java.js +1 -2
  82. package/lib/shell/prepare/languages/python.js +10 -16
  83. package/lib/throbber/index.js +6 -1
  84. package/lib/userConfig.js +7 -1
  85. package/lib/util_modules/config/index.js +1 -1
  86. package/lib/util_modules/config/lib/{appSail.js → appsail.js} +61 -9
  87. package/lib/util_modules/config/lib/client.js +6 -8
  88. package/lib/util_modules/config/lib/functions.js +6 -8
  89. package/lib/util_modules/constants/index.js +3 -1
  90. package/lib/util_modules/constants/lib/default.js +1 -1
  91. package/lib/util_modules/constants/lib/fn-type.js +2 -1
  92. package/lib/util_modules/constants/lib/needed-scopes.js +61 -0
  93. package/lib/util_modules/constants/lib/placeholders.js +6 -0
  94. package/lib/util_modules/constants/lib/ref-mapping.js +2 -1
  95. package/lib/util_modules/constants/lib/remote-mapping.js +2 -1
  96. package/lib/util_modules/constants/lib/scopes.js +9 -1
  97. package/lib/util_modules/constants/lib/template.js +9 -4
  98. package/lib/util_modules/constants/lib/urls.js +16 -0
  99. package/lib/util_modules/fs/lib/async.js +7 -2
  100. package/lib/util_modules/fs/lib/sync.js +12 -1
  101. package/lib/util_modules/server.js +2 -4
  102. package/lib/winston.js +17 -11
  103. package/package.json +1 -1
  104. package/templates/event/job.json +30 -0
  105. package/templates/init/functions/java/job/.classpath +6 -0
  106. package/templates/init/functions/java/job/.project +17 -0
  107. package/templates/init/functions/java/job/catalyst-config.json +11 -0
  108. package/templates/init/functions/java/job/sample.java +34 -0
  109. package/templates/init/functions/node/aio/package.json +1 -1
  110. package/templates/init/functions/node/bio/package.json +1 -1
  111. package/templates/init/functions/node/cron/package.json +1 -1
  112. package/templates/init/functions/node/event/package.json +1 -1
  113. package/templates/init/functions/node/integ/cliq/package.json +1 -1
  114. package/templates/init/functions/node/integ/convokraft/package.json +1 -1
  115. package/templates/init/functions/node/{stream → job}/catalyst-config.json +3 -2
  116. package/templates/init/functions/node/{stream → job}/package.json +1 -1
  117. package/templates/init/functions/node/job/sample.js +28 -0
  118. package/templates/init/functions/node/job/types/job.d.ts +66 -0
  119. package/templates/init/functions/python/job/catalyst-config.json +11 -0
  120. package/templates/init/functions/python/job/requirements.txt +1 -0
  121. package/templates/init/functions/python/job/sample.py +23 -0
  122. package/templates/init.txt +13 -0
  123. package/lib/serve/server/lib/master.js +0 -317
  124. package/templates/init/functions/node/stream/sample.js +0 -15
@@ -0,0 +1,254 @@
1
+ import java.io.BufferedWriter;
2
+ import java.io.File;
3
+ import java.io.FileWriter;
4
+ import java.io.FilenameFilter;
5
+ import java.io.PrintWriter;
6
+ import java.io.StringWriter;
7
+ import java.lang.reflect.Method;
8
+ import java.net.URL;
9
+ import java.net.URLClassLoader;
10
+ import java.nio.file.Paths;
11
+ import java.util.HashMap;
12
+ import java.util.Iterator;
13
+ import java.util.logging.Handler;
14
+ import java.util.logging.LogManager;
15
+ import java.util.logging.LogRecord;
16
+ import java.util.logging.Logger;
17
+ import java.util.logging.SimpleFormatter;
18
+
19
+ import org.json.JSONObject;
20
+
21
+ import com.catalyst.Context;
22
+ import com.catalyst.config.ZCThreadLocal;
23
+ import com.catalyst.job.CapacityAttributes;
24
+ import com.catalyst.job.JOB_STATUS;
25
+ import com.catalyst.impl.DefaultContext;
26
+ import com.catalyst.job.JobRequest;
27
+ import com.catalyst.job.impl.DefaultJobRequest;
28
+
29
+ public class JavajobInvoker {
30
+
31
+ private static final Integer MESSAGE_LENGTH = 1500;
32
+
33
+ public class LogHandler extends Handler {
34
+
35
+ @Override
36
+ public void publish(LogRecord record) {
37
+ try {
38
+ String exceptionMessage = "";
39
+ if (record.getThrown() != null) {
40
+ exceptionMessage = getStackTraceAsString(record.getThrown());
41
+ }
42
+ String message = new SimpleFormatter().format(record) + " " + exceptionMessage;
43
+ if (message.length() > MESSAGE_LENGTH) {
44
+ message = message.substring(0, MESSAGE_LENGTH);
45
+ }
46
+
47
+ System.out.println("[" + record.getLevel().getName() + "] : " + message);
48
+
49
+ } catch (Exception e) {
50
+ System.out.println(getStackTraceAsString(e));
51
+ }
52
+
53
+ }
54
+
55
+ @Override
56
+ public void flush() {
57
+ // TODO Auto-generated method stub
58
+
59
+ }
60
+
61
+ @Override
62
+ public void close() throws SecurityException {
63
+ // TODO Auto-generated method stub
64
+
65
+ }
66
+
67
+ }
68
+
69
+ private static String getStackTraceAsString(Throwable throwable) {
70
+ StringWriter stringWriter = new StringWriter();
71
+ throwable.printStackTrace(new PrintWriter(stringWriter));
72
+ return stringWriter.toString();
73
+ }
74
+
75
+ private static <T> HashMap<String, T> jsonToMap(String t) throws Exception {
76
+
77
+ HashMap<String, T> map = new HashMap<String, T>();
78
+ JSONObject jObject = new JSONObject(t);
79
+ Iterator<?> keys = jObject.keys();
80
+
81
+ while (keys.hasNext()) {
82
+ String key = (String) keys.next();
83
+ Object value = jObject.get(key);
84
+ map.put(key, (T) value);
85
+
86
+ }
87
+ return map;
88
+ }
89
+
90
+ private static void writeResponse(String response, Integer status, String invokerDir) throws Exception {
91
+ // write response data
92
+ String responseFilePath = Paths.get(invokerDir, "../user_res_body").toString();
93
+
94
+ BufferedWriter responseWriter = new BufferedWriter(new FileWriter(responseFilePath));
95
+ responseWriter.write(response);
96
+ responseWriter.close();
97
+
98
+ // write response meta
99
+ String metaFilePath = Paths.get(invokerDir, "../user_meta.json").toString();
100
+
101
+ BufferedWriter metaWriter = new BufferedWriter(new FileWriter(metaFilePath));
102
+ JSONObject metaJson = new JSONObject();
103
+ metaJson.put("statusCode", status);
104
+ metaWriter.write(new JSONObject().put("response", metaJson).toString());
105
+ metaWriter.close();
106
+ }
107
+
108
+ private static void throwAndExit(Exception err, int exitCode, String invokerDir) {
109
+ try {
110
+ String sStackTrace = getStackTraceAsString(err); // stack trace as a string
111
+ if (exitCode == 532) {
112
+ writeResponse("CODE_EXCEPTION", exitCode, invokerDir);
113
+ } else if (exitCode == 500) {
114
+ writeResponse("INTERNAL_SERVER_ERROR", 500, invokerDir);
115
+ } else if (exitCode == 408) {
116
+ writeResponse("TIMEOUT", exitCode, invokerDir);
117
+ }
118
+ System.out.println(sStackTrace);
119
+ } catch (Exception e) {
120
+ System.out.println(e);
121
+ }
122
+ System.exit(exitCode);
123
+ }
124
+
125
+ private static void setZCThreadLocalProject(HashMap<String, Object> project) throws Exception {
126
+
127
+ JSONObject catalystConfig = new JSONObject();
128
+ catalystConfig.put("project_id", project.get("x-zc-projectid").toString());
129
+ catalystConfig.put("project_key", project.get("x-zc-project-key").toString());
130
+ catalystConfig.put("project_domain", project.get("x-zc-project-domain").toString());
131
+ catalystConfig.put("environment", project.get("x-zc-environment").toString());
132
+
133
+ ZCThreadLocal.putValue("CATALYST_CONFIG", catalystConfig.toString());
134
+ }
135
+
136
+ private static void setZCThreadLocalAuth(HashMap<String, Object> auth) throws Exception {
137
+ JSONObject catalystAuth = new JSONObject();
138
+
139
+ String adminAuthHeaderType = auth.get("x-zc-admin-cred-type").toString();
140
+ String adminAuthToken = auth.get("x-zc-admin-cred-token").toString();
141
+
142
+ JSONObject adminAuth = new JSONObject();
143
+ adminAuth.put((adminAuthHeaderType.equals("token")) ? "access_token" : "ticket", adminAuthToken); // No I18N
144
+ catalystAuth.put("admin_cred", adminAuth);
145
+
146
+ JSONObject clientAuth = new JSONObject();
147
+ if(auth.containsKey("x-zc-user-cred-type") && auth.containsKey("x-zc-user-cred-token")) {
148
+ String userAuthHeaderType = auth.get("x-zc-user-cred-type").toString();
149
+ String userAuthToken = auth.get("x-zc-user-cred-token").toString();
150
+
151
+ clientAuth.put((userAuthHeaderType.equals("token")) ? "access_token" : "ticket", userAuthToken); // No I18N
152
+ }
153
+ if(auth.containsKey("x-zc-user-type")) { // No I18N
154
+ String userType = auth.get("x-zc-user-type").toString(); // No I18N
155
+ clientAuth.put("user_type", userType); // No I18N
156
+ }
157
+ if (auth.containsKey("x-zc-cookie")) {
158
+ String cookie = auth.get("x-zc-cookie").toString();
159
+ clientAuth.put("cookie", cookie);
160
+ }
161
+ catalystAuth.put("client_cred", clientAuth);
162
+ ZCThreadLocal.putValue("CATALYST_AUTH", catalystAuth.toString()); // No I18N
163
+
164
+ // For backward compatibility, to be remove in future.
165
+ if(auth.containsKey("x-zc-cookie")) {
166
+ String cookie = auth.get("x-zc-cookie").toString();
167
+ ZCThreadLocal.putValue("client_cookie", cookie); // No I18N
168
+ }
169
+ // to be removed in future
170
+ }
171
+
172
+ public static void main(String[] args) {
173
+ String invokerDir = args[0];
174
+ try {
175
+ LogManager manager = LogManager.getLogManager();
176
+ manager.reset();
177
+ Logger rootLogger = manager.getLogger("");
178
+ LogHandler handler = new JavajobInvoker().new LogHandler();
179
+ rootLogger.addHandler(handler);
180
+
181
+ HashMap<String, Object> target = jsonToMap(args[1]);
182
+ String fnExeName = (String) target.get("index");
183
+ String fnName = (String) target.get("name");
184
+ String fnExePath = Paths.get(invokerDir, "../../", "functions", fnName).normalize().toString();
185
+
186
+ JSONObject userData = new JSONObject(args[2]);
187
+ HashMap<String, Object> projectData = jsonToMap(args[3]);
188
+ HashMap<String, Object> authData = jsonToMap(args[4]);
189
+
190
+ File[] jarFiles = new File(fnExePath).listFiles(new FilenameFilter() {
191
+ @Override
192
+ public boolean accept(File dir, String name) {
193
+ if(name.endsWith(".jar")) {
194
+ return true;
195
+ }
196
+ return false;
197
+ }
198
+ });
199
+ int jarCount = jarFiles.length;
200
+ URL[] URLs = new URL[jarCount + 1];
201
+ URLs[0] = new File(Paths.get(fnExePath).toString()).toURI().toURL();
202
+ for (int i = 1; i <= jarCount; i++) {
203
+ URLs[i] = jarFiles[i - 1].toURI().toURL();
204
+ }
205
+ URLClassLoader child = new URLClassLoader(URLs, JavajobInvoker.class.getClassLoader());
206
+ Class<?> cls = Class.forName(fnExeName, true, child);
207
+
208
+ setZCThreadLocalProject(projectData);
209
+ setZCThreadLocalAuth(authData);
210
+
211
+ DefaultJobRequest defaultJob = new DefaultJobRequest();
212
+
213
+ JSONObject jobDetails = userData.getJSONObject("job_details");
214
+ JSONObject jobMetaDetails = jobDetails.getJSONObject("job_meta_details");
215
+ JSONObject jobpoolDetails = jobMetaDetails.getJSONObject("jobpool_details");
216
+ JSONObject projectDetails = jobpoolDetails.getJSONObject("project_details");
217
+ JSONObject capacity = jobDetails.getJSONObject("capacity");
218
+ JSONObject params = jobMetaDetails.getJSONObject("params");
219
+
220
+ defaultJob.setJobDetails(jobDetails != null ? (JSONObject) jobDetails : new JSONObject());
221
+ defaultJob.setJobMetaDetails(jobMetaDetails != null ? (JSONObject) jobDetails : new JSONObject());
222
+ defaultJob.setJobpoolDetails(jobpoolDetails != null ? (JSONObject) jobpoolDetails : new JSONObject());
223
+ defaultJob.setProjectDetails(projectDetails);
224
+ CapacityAttributes capacityAttributes = CapacityAttributes.getInstance();
225
+ capacityAttributes.setMemory(capacity.getLong("memory"));
226
+ defaultJob.setJobCapacity(capacityAttributes);
227
+ defaultJob.setJobParams(jsonToMap(params != null ? params.toString() : new JSONObject().toString()));
228
+
229
+ JobRequest jobRequest = defaultJob;
230
+
231
+ DefaultContext defaultContext = new DefaultContext(cls.getName(), 900000L);
232
+ Context context = defaultContext;
233
+
234
+ Method runner = cls.getMethod("handleJobExecute", JobRequest.class, Context.class);
235
+ JOB_STATUS jobStatus = null;
236
+ try {
237
+ jobStatus = (JOB_STATUS) runner.invoke(cls.getDeclaredConstructor().newInstance(), jobRequest, context);
238
+ } catch (Exception e) {
239
+ throwAndExit(e, 532, invokerDir);
240
+ }
241
+
242
+ if(jobStatus == null) {
243
+ writeResponse("UNINTENTIONAL_TERMINATION", 531, invokerDir);
244
+ } else {
245
+ int status = jobStatus.getStatus();
246
+ writeResponse(jobStatus.name(), status == 500 ? 530 : status, invokerDir);
247
+ }
248
+
249
+ System.exit(0);
250
+ } catch (Exception e) {
251
+ throwAndExit(e, 500, invokerDir);
252
+ }
253
+ }
254
+ }
@@ -0,0 +1,93 @@
1
+ 'use strict';
2
+
3
+ import * as path from 'path';
4
+ import * as fs from 'fs';
5
+ import { pathToFileURL } from 'url';
6
+
7
+ const args = process.argv.slice(2);
8
+ const target = JSON.parse(args[0]);
9
+ const userData = JSON.parse(args[1]);
10
+ const projectJson = JSON.parse(args[2]);
11
+ const authJson = JSON.parse(args[3]);
12
+ const buildDir = JSON.parse(args[4]);
13
+
14
+ const requestFile = path.join(buildDir, '.catalyst', 'user_req_body');
15
+ const responseFile = path.join(buildDir, '.catalyst', 'user_res_body');
16
+ const metaFile = path.join(buildDir, '.catalyst', 'user_meta.json');
17
+
18
+ const writeToFile = (resp, status) => {
19
+ fs.writeFileSync(responseFile, resp);
20
+ fs.writeFileSync(metaFile, JSON.stringify({ response: { statusCode: status } }));
21
+ };
22
+
23
+ let body = {};
24
+
25
+ if (fs.existsSync(requestFile)) {
26
+ const content = fs.readFileSync(requestFile);
27
+ try {
28
+ body = JSON.parse(content.toString());
29
+ } catch (err) {
30
+ body = {};
31
+ }
32
+ }
33
+
34
+ /**
35
+ * execution timeout 15 minutes
36
+ */
37
+ const timeout = 15 * 60 * 1000;
38
+ const endTime = timeout + Date.now();
39
+
40
+ // exit on timeout
41
+ process.env.DEBUG === 'false' &&
42
+ setTimeout(() => {
43
+ writeToFile('TIMEOUT', 408);
44
+ process.exit(0);
45
+ }, timeout);
46
+
47
+ const context = {
48
+ catalystHeaders: Object.assign(projectJson, authJson),
49
+ getMaxExecutionTimeMs: () => timeout,
50
+ getRemainingExecutionTimeMs: () => endTime - Date.now(),
51
+ closeWithSuccess: () => {
52
+ writeToFile('SUCCESS', 200);
53
+ process.exit(0);
54
+ },
55
+ closeWithFailure: () => {
56
+ writeToFile('FAILURE', 530);
57
+ process.exit(0);
58
+ }
59
+ };
60
+
61
+ const jobReq = {
62
+ getJobDetails: () => ('job_details' in userData ? userData.job_details : {}),
63
+ getJobMetaDetails: () => jobReq.getJobDetails()?.job_meta_details || {},
64
+ getJobpoolDetails: () => jobReq.getJobMetaDetails()?.jobpool_details || {},
65
+ getProjectDetails: () => jobReq.getJobpoolDetails()?.project_details || {},
66
+ getJobCapacityAttributes: () => jobReq.getJobDetails()?.capacity || {},
67
+ getAllJobParams: () => jobReq.getJobMetaDetails()?.params || {},
68
+ getJobParam: (key) => (jobReq.getAllJobParams() || {})[key]
69
+ };
70
+
71
+ import(pathToFileURL(target.index))
72
+ .then((module) => {
73
+ try {
74
+ if (!('default' in module)) {
75
+ throw new Error('Could not find any default export');
76
+ }
77
+ if (typeof module.default !== 'function') {
78
+ throw new Error('The default export is not a function');
79
+ }
80
+ module.default(jobReq, context);
81
+ } catch (e) {
82
+ // eslint-disable-next-line no-console
83
+ console.error(e);
84
+ writeToFile('CODE_EXCEPTION', 532);
85
+ process.exit(0);
86
+ }
87
+ })
88
+ .catch((e) => {
89
+ // eslint-disable-next-line no-console
90
+ console.error(e);
91
+ writeToFile('INTERNAL_SERVER_ERROR', 500);
92
+ process.exit(0);
93
+ });