mirror of
https://github.com/sasjs/adapter.git
synced 2025-12-11 09:24:35 +00:00
Compare commits
164 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7cb2a43f95 | ||
|
|
6e85c7a588 | ||
|
|
a68f6962fd | ||
|
|
a650ba15dd | ||
|
|
6ca1b489fc | ||
|
|
a5c9f11c75 | ||
|
|
d4ebef4290 | ||
| 89590f9a37 | |||
| 5d61bebc9e | |||
| 99afa6e7e4 | |||
| b590a9f41b | |||
| 4466ee30d2 | |||
| db372950b4 | |||
| 46f5e07f11 | |||
|
|
a00cb1ebec | ||
|
|
7b1264d140 | ||
|
|
369b9fb023 | ||
|
|
76487b00e9 | ||
|
|
2d0515e25b | ||
|
|
b132b99586 | ||
|
|
5a7b4a1de4 | ||
|
|
6cac008b61 | ||
|
|
929ec6eb1c | ||
|
|
5a35237de5 | ||
|
|
5d77bbba8b | ||
|
|
eda021b6a5 | ||
|
|
259c479ef0 | ||
|
|
a962b8e7cf | ||
|
|
eb0e7247a6 | ||
| ccc77cb9d1 | |||
|
|
5cb5bbdb55 | ||
|
|
ac6cd7be82 | ||
|
|
63f5f4d03d | ||
|
|
a164fb7df9 | ||
|
|
336ba207cf | ||
|
|
3cfd45cc62 | ||
|
|
f7fb917282 | ||
|
|
a182037883 | ||
|
|
f9e79fb756 | ||
|
|
aaf0eef62b | ||
|
|
fafa0c3567 | ||
|
|
4a6845ad6a | ||
|
|
61d66c6f82 | ||
| 123fbc7235 | |||
|
|
eae8694a29 | ||
|
|
2b16be3aef | ||
|
|
d8d4da9c9a | ||
|
|
0b755b7304 | ||
|
|
0816b7b1f9 | ||
|
|
97d45e87ec | ||
|
|
57ef0647b5 | ||
|
|
a34eebba44 | ||
| 857e39eb33 | |||
| 9bd7d84975 | |||
| 731e38bce3 | |||
|
|
2ee6c45d16 | ||
|
|
b80283f8af | ||
|
|
291e23e40a | ||
| d53d1e1e6a | |||
| 8cf249e8fd | |||
| 5d7cfe1e6c | |||
| abc15fb3ab | |||
| 8cc4270e48 | |||
|
|
56b2ba026a | ||
|
|
8beda1ad6c | ||
|
|
b18b471549 | ||
| 93c9a34591 | |||
|
|
9493492dea | ||
|
|
9b976d48ca | ||
|
|
00b19de497 | ||
|
|
f4cdd2d607 | ||
|
|
cdc0c12ec4 | ||
|
|
bc6f109c48 | ||
|
|
cfab64cfa0 | ||
|
|
d4c8c58552 | ||
|
|
2b8cb51a50 | ||
|
|
e068d3263c | ||
| 630f2e9c37 | |||
| 51ac6b052b | |||
| c32258eb3c | |||
|
|
88f50e3c74 | ||
|
|
bfe5ac0ff7 | ||
|
|
d50f5a030a | ||
|
|
c320caec99 | ||
|
|
16a5b2b012 | ||
|
|
2951e0cc2d | ||
|
|
6bb4a7ea18 | ||
|
|
2827978fe5 | ||
|
|
541c19c1a4 | ||
|
|
c5e995f8d6 | ||
|
|
8bf36da566 | ||
| ccb4ec6e03 | |||
| 06ebb52bc9 | |||
|
|
6e23a0362f | ||
| a59d78bcf7 | |||
| 33d4ee92a7 | |||
| dadce3d4c9 | |||
|
|
b61cf34723 | ||
|
|
22445d1268 | ||
|
|
cba9dacb37 | ||
|
|
a055b36c5c | ||
| 06895cc9f8 | |||
| 24496a997a | |||
| 6419686269 | |||
|
|
4554c9100c | ||
| 919c83c143 | |||
| 00ba2957fb | |||
| 5beda6547a | |||
| bd49b3757a | |||
|
|
b32352a369 | ||
| b306f11148 | |||
|
|
8c4955cb65 | ||
|
|
155f2bb0e8 | ||
| 3ca971134a | |||
| 488d8b9316 | |||
| c20bdba4ae | |||
| 0be2d69aee | |||
| a6e67c3478 | |||
| 5968988984 | |||
| 31cd01610a | |||
| a67824762c | |||
|
|
0336541d40 | ||
|
|
01de3836d7 | ||
|
|
c571bb8490 | ||
|
|
5b4d354ea2 | ||
|
|
b0ce0dc40a | ||
| 88f70a7966 | |||
| 89ff323206 | |||
| d4357d939e | |||
|
|
6cb76f0b5c | ||
|
|
ba2baa36c0 | ||
|
|
e36cd785e8 | ||
| 2fa3a353fa | |||
|
|
bdb1ffb2ef | ||
|
|
84090661cf | ||
|
|
68e14bbf05 | ||
|
|
e4f23334d3 | ||
|
|
5593963b89 | ||
|
|
81c9138b93 | ||
|
|
83fa82108b | ||
|
|
76039c3ec7 | ||
|
|
9b57c9ca1c | ||
|
|
4018cf95ba | ||
|
|
173b6e3e8d | ||
|
|
0ed5447aff | ||
|
|
6344a906d8 | ||
|
|
b2c135ae61 | ||
|
|
2032aacba3 | ||
|
|
fadccfc94c | ||
|
|
551e4e43c1 | ||
|
|
1867658cde | ||
| 0b18fddc3e | |||
| 19503e0b31 | |||
| d8bdc02f09 | |||
| 2d0833061f | |||
|
|
5dfc4e4086 | ||
|
|
c5824a8a8d | ||
|
|
56a1960fff | ||
| b8c9522a55 | |||
| b461cff731 | |||
| 728167fd71 | |||
| 460575b462 | |||
|
|
55e64ae9d6 | ||
|
|
9b32b28aa7 |
@@ -6,7 +6,7 @@ GREEN="\033[1;32m"
|
||||
# temporary file which holds the message).
|
||||
commit_message=$(cat "$1")
|
||||
|
||||
if (echo "$commit_message" | grep -Eq "^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)(\([a-z0-9 \-]+\))?!?: .+$") then
|
||||
if (echo "$commit_message" | grep -Eq "^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)(\([a-z0-9 \-\*]+\))?!?: .+$") then
|
||||
echo "${GREEN} ✔ Commit message meets Conventional Commit standards"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
7
.github/dependabot.yml
vendored
Normal file
7
.github/dependabot.yml
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: npm
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: daily
|
||||
open-pull-requests-limit: 10
|
||||
5
.github/reviewer-lottery.yml
vendored
5
.github/reviewer-lottery.yml
vendored
@@ -7,3 +7,8 @@ groups:
|
||||
- saadjutt01
|
||||
- medjedovicm
|
||||
- allanbowe
|
||||
- sabhas
|
||||
- name: SASjs QA
|
||||
reviewers: 1
|
||||
usernames:
|
||||
- VladislavParhomchik
|
||||
|
||||
@@ -12,6 +12,8 @@ What code changes have been made to achieve the intent.
|
||||
|
||||
## Checks
|
||||
|
||||
No PR (that involves a non-trivial code change) should be merged, unless all four of the items below are confirmed! If an urgent fix is needed - use a tar file.
|
||||
|
||||
- [ ] Code is formatted correctly (`npm run lint:fix`).
|
||||
- [ ] All unit tests are passing (`npm test`).
|
||||
- [ ] All `sasjs-cli` unit tests are passing (`npm test`).
|
||||
|
||||
40
README.md
40
README.md
@@ -172,35 +172,43 @@ Configuration on the client side involves passing an object on startup, which ca
|
||||
* `serverType` - either `SAS9` or `SASVIYA`.
|
||||
* `serverUrl` - the location (including http protocol and port) of the SAS Server. Can be omitted, eg if serving directly from the SAS Web Server, or in streaming mode.
|
||||
* `debug` - if `true` then SAS Logs and extra debug information is returned.
|
||||
* `useComputeApi` - if `true` and the serverType is `SASVIYA` then the REST APIs will be called directly (rather than using the JES web service).
|
||||
* `contextName` - if missing or blank, and `useComputeApi` is `true` and `serverType` is `SASVIYA` then the JES API will be used.
|
||||
* `useComputeApi` - Only relevant when the serverType is `SASVIYA`. If `true` the [Compute API](#using-the-compute-api) is used. If `false` the [JES API](#using-the-jes-api) is used. If `null` or `undefined` the [Web](#using-jes-web-app) approach is used.
|
||||
* `contextName` - Compute context on which the requests will be called. If missing or not provided, defaults to `Job Execution Compute context`.
|
||||
|
||||
The adapter supports a number of approaches for interfacing with Viya (`serverType` is `SASVIYA`). For maximum performance, be sure to [configure your compute context](https://sasjs.io/guide-viya/#shared-account-and-server-re-use) with `reuseServerProcesses` as `true` and a system account in `runServerAs`. This functionality is available since Viya 3.5. This configuration is supported when [creating contexts using the CLI](https://sasjs.io/sasjs-cli-context/#sasjs-context-create).
|
||||
|
||||
### Using JES Web App
|
||||
|
||||
In this setup, all requests are routed through the JES web app, at `YOURSERVER/SASJobExecution`. This is the most reliable method, and also the slowest. One request is made to the JES app, and remaining requests (getting job uri, session spawning, passing parameters, running the program, fetching the log) are made on the SAS server by the JES app.
|
||||
|
||||
```
|
||||
{
|
||||
appLoc:"/Your/Path",
|
||||
serverType:"SASVIYA"
|
||||
}
|
||||
```
|
||||
|
||||
### Using the JES API
|
||||
Here we are running Jobs using the Job Execution Service except this time we are making the requests directly using the REST API instead of through the JES Web App. This is helpful when we need to call web services outside of a browser (eg with the SASjs CLI or other commandline tools). To save one network request, the adapter prefetches the JOB URIs and passes them in the `__job` parameter.
|
||||
In this setup, all requests are routed through the JES web app, at `YOURSERVER/SASJobExecution?_program=/your/program`. This is the most reliable method, and also the slowest. One request is made to the JES app, and remaining requests (getting job uri, session spawning, passing parameters, running the program, fetching the log) are handled by the SAS server inside the JES app.
|
||||
|
||||
```
|
||||
{
|
||||
appLoc:"/Your/Path",
|
||||
serverType:"SASVIYA",
|
||||
useComputeApi: true
|
||||
contextName: 'yourComputeContext'
|
||||
}
|
||||
```
|
||||
|
||||
Note - to use the web approach, the `useComputeApi` property must be `undefined` or `null`.
|
||||
|
||||
### Using the JES API
|
||||
Here we are running Jobs using the Job Execution Service except this time we are making the requests directly using the REST API instead of through the JES Web App. This is helpful when we need to call web services outside of a browser (eg with the SASjs CLI or other commandline tools). To save one network request, the adapter prefetches the JOB URIs and passes them in the `__job` parameter. Depending on your network bandwidth, it may or may not be faster than the JES Web approach.
|
||||
|
||||
This approach (`useComputeApi: false`) also ensures that jobs are displayed in Environment Manager.
|
||||
|
||||
```
|
||||
{
|
||||
appLoc:"/Your/Path",
|
||||
serverType:"SASVIYA",
|
||||
useComputeApi: false,
|
||||
contextName: 'yourComputeContext'
|
||||
}
|
||||
```
|
||||
|
||||
### Using the Compute API
|
||||
This approach is by far the fastest, as a result of the optimisations we have built into the adapter. With this configuration, in the first sasjs request, we take a URI map of the services in the target folder, and create a session manager - which spawns an extra session. The next time a request is made, the adapter will use the 'hot' session. Sessions are deleted after every use, which actually makes this _less_ resource intensive than a typical JES web app, in which all sessions are kept alive by default for 15 minutes.
|
||||
This approach is by far the fastest, as a result of the optimisations we have built into the adapter. With this configuration, in the first sasjs request, we take a URI map of the services in the target folder, and create a session manager. This manager will spawn a additional session every time a request is made. Subsequent requests will use the existing 'hot' session, if it exists. Sessions are always deleted after every use, which actually makes this _less_ resource intensive than a typical JES web app, in which all sessions are kept alive by default for 15 minutes.
|
||||
|
||||
With this approach (`useComputeApi: true`), the requests/logs will _not_ appear in the list in Environment manager.
|
||||
|
||||
```
|
||||
{
|
||||
@@ -225,4 +233,4 @@ If you are a SAS 9 or SAS Viya customer you can also request a copy of [Data Con
|
||||
|
||||
If you find this library useful, help us grow our star graph!
|
||||
|
||||

|
||||

|
||||
|
||||
19055
package-lock.json
generated
19055
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
41
package.json
41
package.json
@@ -3,17 +3,17 @@
|
||||
"description": "JavaScript adapter for SAS",
|
||||
"homepage": "https://adapter.sasjs.io",
|
||||
"scripts": {
|
||||
"build": "rimraf build && rimraf node && mkdir node && cp -r src/* node && webpack && rimraf build/src && rimraf node",
|
||||
"package:lib": "npm run build && cp ./package.json build && cd build && npm version \"5.0.0\" && npm pack",
|
||||
"build": "rimraf build && rimraf node && mkdir node && copyfiles -u 1 \"./src/**/*\" ./node && webpack && rimraf build/src && rimraf node",
|
||||
"package:lib": "npm run build && copyfiles ./package.json build && cd build && npm version \"5.0.0\" && npm pack",
|
||||
"publish:lib": "npm run build && cd build && npm publish",
|
||||
"lint:fix": "npx prettier --write 'src/**/*.{ts,tsx,js,jsx,html,css,sass,less,json,yml,md,graphql}' && npx prettier --write 'sasjs-tests/src/**/*.{ts,tsx,js,jsx,html,css,sass,less,json,yml,md,graphql}'",
|
||||
"lint": "npx prettier --check 'src/**/*.{ts,tsx,js,jsx,html,css,sass,less,json,yml,md,graphql}' && npx prettier --check 'sasjs-tests/src/**/*.{ts,tsx,js,jsx,html,css,sass,less,json,yml,md,graphql}'",
|
||||
"lint:fix": "npx prettier --write \"src/**/*.{ts,tsx,js,jsx,html,css,sass,less,json,yml,md,graphql}\" && npx prettier --write \"sasjs-tests/src/**/*.{ts,tsx,js,jsx,html,css,sass,less,json,yml,md,graphql}\"",
|
||||
"lint": "npx prettier --check \"src/**/*.{ts,tsx,js,jsx,html,css,sass,less,json,yml,md,graphql}\" && npx prettier --check \"sasjs-tests/src/**/*.{ts,tsx,js,jsx,html,css,sass,less,json,yml,md,graphql}\"",
|
||||
"test": "jest --silent --coverage",
|
||||
"prepublishOnly": "cp -r ./build/* . && rm -rf ./build",
|
||||
"postpublish": "git clean -fd",
|
||||
"semantic-release": "semantic-release",
|
||||
"typedoc": "typedoc",
|
||||
"postinstall": "[ -d .git ] && git config core.hooksPath ./.git-hooks || true"
|
||||
"prepare": "git rev-parse --git-dir && git config core.hooksPath ./.git-hooks && git config core.autocrlf false || true"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
@@ -38,30 +38,35 @@
|
||||
},
|
||||
"license": "ISC",
|
||||
"devDependencies": {
|
||||
"@types/jest": "^26.0.22",
|
||||
"@types/jest": "^26.0.23",
|
||||
"@types/mime": "^2.0.3",
|
||||
"@types/tough-cookie": "^4.0.0",
|
||||
"copyfiles": "^2.4.1",
|
||||
"cp": "^0.2.0",
|
||||
"dotenv": "^8.2.0",
|
||||
"jest": "^26.6.3",
|
||||
"dotenv": "^10.0.0",
|
||||
"jest": "^27.0.6",
|
||||
"jest-extended": "^0.11.5",
|
||||
"mime": "^2.5.2",
|
||||
"node-polyfill-webpack-plugin": "^1.1.4",
|
||||
"path": "^0.12.7",
|
||||
"process": "^0.11.10",
|
||||
"rimraf": "^3.0.2",
|
||||
"semantic-release": "^17.4.2",
|
||||
"terser-webpack-plugin": "^4.2.3",
|
||||
"ts-jest": "^25.5.1",
|
||||
"ts-loader": "^9.1.2",
|
||||
"semantic-release": "^17.4.4",
|
||||
"terser-webpack-plugin": "^5.1.4",
|
||||
"ts-jest": "^27.0.3",
|
||||
"ts-loader": "^9.2.2",
|
||||
"tslint": "^6.1.3",
|
||||
"tslint-config-prettier": "^1.18.0",
|
||||
"typedoc": "^0.20.36",
|
||||
"typedoc-neo-theme": "^1.1.0",
|
||||
"typedoc": "^0.21.2",
|
||||
"typedoc-neo-theme": "^1.1.1",
|
||||
"typedoc-plugin-external-module-name": "^4.0.6",
|
||||
"typescript": "^3.9.9",
|
||||
"webpack": "^5.33.2",
|
||||
"webpack-cli": "^4.7.0"
|
||||
"typescript": "^4.3.4",
|
||||
"webpack": "^5.41.1",
|
||||
"webpack-cli": "^4.7.2"
|
||||
},
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"@sasjs/utils": "^2.14.0",
|
||||
"@sasjs/utils": "^2.23.2",
|
||||
"axios": "^0.21.1",
|
||||
"axios-cookiejar-support": "^1.0.1",
|
||||
"form-data": "^4.0.0",
|
||||
|
||||
@@ -6,7 +6,7 @@ When developing on `@sasjs/adapter`, it's good practice to run the test suite ag
|
||||
|
||||
You can use the provided `update:adapter` NPM script for this.
|
||||
|
||||
```
|
||||
```bash
|
||||
npm run update:adapter
|
||||
```
|
||||
|
||||
@@ -37,7 +37,7 @@ To be able to run the `deploy` script, two environment variables need to be set:
|
||||
|
||||
So you can run the script like so:
|
||||
|
||||
```
|
||||
```bash
|
||||
SSH_ACCOUNT=me@my-sas-server.com DEPLOY_PATH=/var/www/html/my-folder/sasjs-tests npm run deploy
|
||||
```
|
||||
|
||||
@@ -49,8 +49,7 @@ The below services need to be created on your SAS server, at the location specif
|
||||
|
||||
### SAS 9
|
||||
|
||||
```
|
||||
|
||||
```sas
|
||||
filename mc url "https://raw.githubusercontent.com/sasjs/core/main/all.sas";
|
||||
%inc mc;
|
||||
filename ft15f001 temp;
|
||||
@@ -76,11 +75,20 @@ parmcards4;
|
||||
let he who hath understanding, reckon the number of the beast
|
||||
;;;;
|
||||
%mm_createwebservice(path=/Public/app/common,name=makeErr)
|
||||
parmcards4;
|
||||
%webout(OPEN)
|
||||
data _null_;
|
||||
file _webout;
|
||||
put ' the discovery channel ';
|
||||
run;
|
||||
%webout(CLOSE)
|
||||
;;;;
|
||||
%mm_createwebservice(path=/Public/app/common,name=invalidJSON)
|
||||
```
|
||||
|
||||
### SAS Viya
|
||||
|
||||
```
|
||||
```sas
|
||||
filename mc url "https://raw.githubusercontent.com/sasjs/core/main/all.sas";
|
||||
%inc mc;
|
||||
filename ft15f001 temp;
|
||||
@@ -119,6 +127,15 @@ If you can trust yourself when all men doubt you,
|
||||
But make allowance for their doubting too;
|
||||
;;;;
|
||||
%mp_createwebservice(path=/Public/app/common,name=makeErr)
|
||||
parmcards4;
|
||||
%webout(OPEN)
|
||||
data _null_;
|
||||
file _webout;
|
||||
put ' the discovery channel ';
|
||||
run;
|
||||
%webout(CLOSE)
|
||||
;;;;
|
||||
%mp_createwebservice(path=/Public/app/common,name=invalidJSON)
|
||||
```
|
||||
|
||||
You should now be able to access the tests in your browser at the deployed path on your server.
|
||||
|
||||
22184
sasjs-tests/package-lock.json
generated
22184
sasjs-tests/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -7,7 +7,7 @@
|
||||
"@sasjs/adapter": "file:../build/sasjs-adapter-5.0.0.tgz",
|
||||
"@sasjs/test-framework": "^1.4.0",
|
||||
"@types/jest": "^26.0.20",
|
||||
"@types/node": "^14.14.25",
|
||||
"@types/node": "^14.14.41",
|
||||
"@types/react": "^17.0.1",
|
||||
"@types/react-dom": "^17.0.0",
|
||||
"@types/react-router-dom": "^5.1.7",
|
||||
|
||||
@@ -13,14 +13,19 @@ const App = (): ReactElement<{}> => {
|
||||
|
||||
useEffect(() => {
|
||||
if (adapter) {
|
||||
setTestSuites([
|
||||
const testSuites = [
|
||||
basicTests(adapter, config.userName, config.password),
|
||||
sendArrTests(adapter),
|
||||
sendObjTests(adapter),
|
||||
specialCaseTests(adapter),
|
||||
sasjsRequestTests(adapter),
|
||||
computeTests(adapter)
|
||||
])
|
||||
sasjsRequestTests(adapter)
|
||||
]
|
||||
|
||||
if (adapter.getSasjsConfig().serverType === 'SASVIYA') {
|
||||
testSuites.push(computeTests(adapter))
|
||||
}
|
||||
|
||||
setTestSuites(testSuites)
|
||||
}
|
||||
}, [adapter, config])
|
||||
|
||||
|
||||
@@ -145,6 +145,29 @@ export const basicTests = (
|
||||
sasjsConfig.debug === false
|
||||
)
|
||||
}
|
||||
},
|
||||
{
|
||||
title: 'Request with extra attributes on JES approach',
|
||||
description:
|
||||
'Should complete successful request with extra attributes present in response',
|
||||
test: async () => {
|
||||
const config = {
|
||||
useComputeApi: false
|
||||
}
|
||||
|
||||
return await adapter.request(
|
||||
'common/sendArr',
|
||||
stringData,
|
||||
config,
|
||||
undefined,
|
||||
undefined,
|
||||
['file', 'data']
|
||||
)
|
||||
},
|
||||
assertion: (response: any) => {
|
||||
const responseKeys: any = Object.keys(response)
|
||||
return responseKeys.includes('file') && responseKeys.includes('data')
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
@@ -25,7 +25,7 @@ export const computeTests = (adapter: SASjs): TestSuite => ({
|
||||
'/Public/app/common/sendArr',
|
||||
data,
|
||||
{},
|
||||
'',
|
||||
undefined,
|
||||
true
|
||||
)
|
||||
},
|
||||
|
||||
@@ -176,11 +176,59 @@ export const sendObjTests = (adapter: SASjs): TestSuite => ({
|
||||
name: 'sendObj',
|
||||
tests: [
|
||||
{
|
||||
title: 'Invalid column name',
|
||||
title: 'Table name starts with numeric',
|
||||
description: 'Should throw an error',
|
||||
test: async () => {
|
||||
const invalidData: any = {
|
||||
'1 invalid table': [{ col1: 42 }]
|
||||
'1InvalidTable': [{ col1: 42 }]
|
||||
}
|
||||
return adapter.request('common/sendObj', invalidData).catch((e) => e)
|
||||
},
|
||||
assertion: (error: any) =>
|
||||
!!error && !!error.error && !!error.error.message
|
||||
},
|
||||
{
|
||||
title: 'Table name contains a space',
|
||||
description: 'Should throw an error',
|
||||
test: async () => {
|
||||
const invalidData: any = {
|
||||
'an invalidTable': [{ col1: 42 }]
|
||||
}
|
||||
return adapter.request('common/sendObj', invalidData).catch((e) => e)
|
||||
},
|
||||
assertion: (error: any) =>
|
||||
!!error && !!error.error && !!error.error.message
|
||||
},
|
||||
{
|
||||
title: 'Table name contains a special character',
|
||||
description: 'Should throw an error',
|
||||
test: async () => {
|
||||
const invalidData: any = {
|
||||
'anInvalidTable#': [{ col1: 42 }]
|
||||
}
|
||||
return adapter.request('common/sendObj', invalidData).catch((e) => e)
|
||||
},
|
||||
assertion: (error: any) =>
|
||||
!!error && !!error.error && !!error.error.message
|
||||
},
|
||||
{
|
||||
title: 'Table name exceeds max length of 32 characters',
|
||||
description: 'Should throw an error',
|
||||
test: async () => {
|
||||
const invalidData: any = {
|
||||
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: [{ col1: 42 }]
|
||||
}
|
||||
return adapter.request('common/sendObj', invalidData).catch((e) => e)
|
||||
},
|
||||
assertion: (error: any) =>
|
||||
!!error && !!error.error && !!error.error.message
|
||||
},
|
||||
{
|
||||
title: "Invalid data object's structure",
|
||||
description: 'Should throw an error',
|
||||
test: async () => {
|
||||
const invalidData: any = {
|
||||
inData: [[{ data: 'value' }]]
|
||||
}
|
||||
return adapter.request('common/sendObj', invalidData).catch((e) => e)
|
||||
},
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Context, EditContextInput, ContextAllAttributes } from './types'
|
||||
import { isUrl } from './utils'
|
||||
import { prefixMessage } from '@sasjs/utils/error'
|
||||
import { RequestClient } from './request/RequestClient'
|
||||
import { AuthConfig } from '@sasjs/utils/types'
|
||||
|
||||
export class ContextManager {
|
||||
private defaultComputeContexts = [
|
||||
@@ -328,12 +329,12 @@ export class ContextManager {
|
||||
|
||||
public async getExecutableContexts(
|
||||
executeScript: Function,
|
||||
accessToken?: string
|
||||
authConfig?: AuthConfig
|
||||
) {
|
||||
const { result: contexts } = await this.requestClient
|
||||
.get<{ items: Context[] }>(
|
||||
`${this.serverUrl}/compute/contexts?limit=10000`,
|
||||
accessToken
|
||||
authConfig?.access_token
|
||||
)
|
||||
.catch((err) => {
|
||||
throw prefixMessage(err, 'Error while fetching compute contexts.')
|
||||
@@ -350,7 +351,7 @@ export class ContextManager {
|
||||
`test-${context.name}`,
|
||||
linesOfCode,
|
||||
context.name,
|
||||
accessToken,
|
||||
authConfig,
|
||||
null,
|
||||
false,
|
||||
true,
|
||||
|
||||
@@ -2,15 +2,19 @@ import { isUrl } from './utils'
|
||||
import { UploadFile } from './types/UploadFile'
|
||||
import { ErrorResponse, LoginRequiredError } from './types/errors'
|
||||
import { RequestClient } from './request/RequestClient'
|
||||
import { ServerType } from '@sasjs/utils/types'
|
||||
import SASjs from './SASjs'
|
||||
import { Server } from 'https'
|
||||
import { SASjsConfig } from './types'
|
||||
import { config } from 'process'
|
||||
|
||||
export class FileUploader {
|
||||
constructor(
|
||||
private appLoc: string,
|
||||
serverUrl: string,
|
||||
private sasjsConfig: SASjsConfig,
|
||||
private jobsPath: string,
|
||||
private requestClient: RequestClient
|
||||
) {
|
||||
if (serverUrl) isUrl(serverUrl)
|
||||
if (this.sasjsConfig.serverUrl) isUrl(this.sasjsConfig.serverUrl)
|
||||
}
|
||||
|
||||
public uploadFile(sasJob: string, files: UploadFile[], params: any) {
|
||||
@@ -29,8 +33,8 @@ export class FileUploader {
|
||||
}
|
||||
}
|
||||
|
||||
const program = this.appLoc
|
||||
? this.appLoc.replace(/\/?$/, '/') + sasJob.replace(/^\//, '')
|
||||
const program = this.sasjsConfig.appLoc
|
||||
? this.sasjsConfig.appLoc.replace(/\/?$/, '/') + sasJob.replace(/^\//, '')
|
||||
: sasJob
|
||||
const uploadUrl = `${this.jobsPath}/?${
|
||||
'_program=' + program
|
||||
@@ -44,6 +48,12 @@ export class FileUploader {
|
||||
|
||||
const csrfToken = this.requestClient.getCsrfToken('file')
|
||||
if (csrfToken) formData.append('_csrf', csrfToken.value)
|
||||
if (this.sasjsConfig.debug) formData.append('_debug', '131')
|
||||
if (
|
||||
this.sasjsConfig.serverType === ServerType.SasViya &&
|
||||
this.sasjsConfig.contextName
|
||||
)
|
||||
formData.append('_contextname', this.sasjsConfig.contextName)
|
||||
|
||||
const headers = {
|
||||
'cache-control': 'no-cache',
|
||||
@@ -53,9 +63,15 @@ export class FileUploader {
|
||||
|
||||
return this.requestClient
|
||||
.post(uploadUrl, formData, undefined, 'application/json', headers)
|
||||
.then((res) =>
|
||||
typeof res.result === 'string' ? JSON.parse(res.result) : res.result
|
||||
)
|
||||
.then((res) => {
|
||||
let result
|
||||
|
||||
result =
|
||||
typeof res.result === 'string' ? JSON.parse(res.result) : res.result
|
||||
|
||||
return result
|
||||
//TODO: append to SASjs requests
|
||||
})
|
||||
.catch((err: Error) => {
|
||||
if (err instanceof LoginRequiredError) {
|
||||
return Promise.reject(
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import axios, { AxiosInstance } from 'axios'
|
||||
import { generateTimestamp } from '@sasjs/utils/time'
|
||||
import * as NodeFormData from 'form-data'
|
||||
import { Sas9RequestClient } from './request/Sas9RequestClient'
|
||||
import { isUrl } from './utils'
|
||||
|
||||
/**
|
||||
@@ -6,11 +8,11 @@ import { isUrl } from './utils'
|
||||
*
|
||||
*/
|
||||
export class SAS9ApiClient {
|
||||
private httpClient: AxiosInstance
|
||||
private requestClient: Sas9RequestClient
|
||||
|
||||
constructor(private serverUrl: string) {
|
||||
constructor(private serverUrl: string, private jobsPath: string) {
|
||||
if (serverUrl) isUrl(serverUrl)
|
||||
this.httpClient = axios.create({ baseURL: this.serverUrl })
|
||||
this.requestClient = new Sas9RequestClient(serverUrl, false)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -33,27 +35,61 @@ export class SAS9ApiClient {
|
||||
/**
|
||||
* Executes code on a SAS9 server.
|
||||
* @param linesOfCode - an array of code lines to execute.
|
||||
* @param serverName - the server to execute the code on.
|
||||
* @param repositoryName - the repository to execute the code in.
|
||||
* @param userName - the user name to log into the current SAS server.
|
||||
* @param password - the password to log into the current SAS server.
|
||||
*/
|
||||
public async executeScript(
|
||||
linesOfCode: string[],
|
||||
serverName: string,
|
||||
repositoryName: string
|
||||
userName: string,
|
||||
password: string
|
||||
) {
|
||||
const requestPayload = linesOfCode.join('\n')
|
||||
await this.requestClient.login(userName, password, this.jobsPath)
|
||||
|
||||
const executeScriptResponse = await this.httpClient.put(
|
||||
`/sas/servers/${serverName}/cmd?repositoryName=${repositoryName}`,
|
||||
`command=${requestPayload}`,
|
||||
{
|
||||
headers: {
|
||||
Accept: 'application/json'
|
||||
},
|
||||
responseType: 'text'
|
||||
}
|
||||
// This piece of code forces a webout to prevent Stored Process Errors.
|
||||
const forceOutputCode = [
|
||||
'data _null_;',
|
||||
'file _webout;',
|
||||
`put 'Executed sasjs run';`,
|
||||
'run;'
|
||||
]
|
||||
const formData = generateFileUploadForm(
|
||||
[...linesOfCode, ...forceOutputCode].join('\n')
|
||||
)
|
||||
|
||||
return executeScriptResponse.data
|
||||
const codeInjectorPath = `/User Folders/${userName}/My Folder/sasjs/runner`
|
||||
const contentType =
|
||||
'multipart/form-data; boundary=' + formData.getBoundary()
|
||||
const contentLength = formData.getLengthSync()
|
||||
|
||||
const headers = {
|
||||
'cache-control': 'no-cache',
|
||||
Accept: '*/*',
|
||||
'Content-Type': contentType,
|
||||
'Content-Length': contentLength,
|
||||
Connection: 'keep-alive'
|
||||
}
|
||||
const storedProcessUrl = `${this.jobsPath}/?${
|
||||
'_program=' + codeInjectorPath + '&_debug=log'
|
||||
}`
|
||||
const response = await this.requestClient.post(
|
||||
storedProcessUrl,
|
||||
formData,
|
||||
undefined,
|
||||
contentType,
|
||||
headers
|
||||
)
|
||||
|
||||
return response.result as string
|
||||
}
|
||||
}
|
||||
|
||||
const generateFileUploadForm = (data: any): NodeFormData => {
|
||||
const formData = new NodeFormData()
|
||||
const filename = `sasjs-execute-sas9-${generateTimestamp('')}.sas`
|
||||
formData.append(filename, data, {
|
||||
filename,
|
||||
contentType: 'text/plain'
|
||||
})
|
||||
|
||||
return formData
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
Context,
|
||||
ContextAllAttributes,
|
||||
Folder,
|
||||
File,
|
||||
EditContextInput,
|
||||
JobDefinition,
|
||||
PollOptions
|
||||
@@ -25,11 +26,16 @@ import { formatDataForRequest } from './utils/formatDataForRequest'
|
||||
import { SessionManager } from './SessionManager'
|
||||
import { ContextManager } from './ContextManager'
|
||||
import { timestampToYYYYMMDDHHMMSS } from '@sasjs/utils/time'
|
||||
import {
|
||||
isAccessTokenExpiring,
|
||||
isRefreshTokenExpiring
|
||||
} from '@sasjs/utils/auth'
|
||||
import { Logger, LogLevel } from '@sasjs/utils/logger'
|
||||
import { SasAuthResponse, MacroVar, AuthConfig } from '@sasjs/utils/types'
|
||||
import { isAuthorizeFormRequired } from './auth/isAuthorizeFormRequired'
|
||||
import { RequestClient } from './request/RequestClient'
|
||||
import { SasAuthResponse } from '@sasjs/utils/types'
|
||||
import { prefixMessage } from '@sasjs/utils/error'
|
||||
import * as mime from 'mime'
|
||||
|
||||
/**
|
||||
* A client for interfacing with the SAS Viya REST API.
|
||||
@@ -128,14 +134,14 @@ export class SASViyaApiClient {
|
||||
|
||||
/**
|
||||
* Returns all compute contexts on this server that the user has access to.
|
||||
* @param accessToken - an access token for an authorized user.
|
||||
* @param authConfig - an access token, refresh token, client and secret for an authorized user.
|
||||
*/
|
||||
public async getExecutableContexts(accessToken?: string) {
|
||||
public async getExecutableContexts(authConfig?: AuthConfig) {
|
||||
const bindedExecuteScript = this.executeScript.bind(this)
|
||||
|
||||
return await this.contextManager.getExecutableContexts(
|
||||
bindedExecuteScript,
|
||||
accessToken
|
||||
authConfig
|
||||
)
|
||||
}
|
||||
|
||||
@@ -264,37 +270,40 @@ export class SASViyaApiClient {
|
||||
* @param jobPath - the path to the file being submitted for execution.
|
||||
* @param linesOfCode - an array of code lines to execute.
|
||||
* @param contextName - the context to execute the code in.
|
||||
* @param accessToken - an access token for an authorized user.
|
||||
* @param authConfig - an object containing an access token, refresh token, client ID and secret.
|
||||
* @param data - execution data.
|
||||
* @param debug - when set to true, the log will be returned.
|
||||
* @param expectWebout - when set to true, the automatic _webout fileref will be checked for content, and that content returned. This fileref is used when the Job contains a SASjs web request (as opposed to executing arbitrary SAS code).
|
||||
* @param waitForResult - when set to true, function will return the session
|
||||
* @param pollOptions - an object that represents poll interval(milliseconds) and maximum amount of attempts. Object example: { MAX_POLL_COUNT: 24 * 60 * 60, POLL_INTERVAL: 1000 }.
|
||||
* @param printPid - a boolean that indicates whether the function should print (PID) of the started job.
|
||||
* @param variables - an object that represents macro variables.
|
||||
*/
|
||||
public async executeScript(
|
||||
jobPath: string,
|
||||
linesOfCode: string[],
|
||||
contextName: string,
|
||||
accessToken?: string,
|
||||
authConfig?: AuthConfig,
|
||||
data = null,
|
||||
debug: boolean = false,
|
||||
expectWebout = false,
|
||||
waitForResult = true,
|
||||
pollOptions?: PollOptions,
|
||||
printPid = false
|
||||
printPid = false,
|
||||
variables?: MacroVar
|
||||
): Promise<any> {
|
||||
let access_token = (authConfig || {}).access_token
|
||||
if (authConfig) {
|
||||
;({ access_token } = await this.getTokens(authConfig))
|
||||
}
|
||||
|
||||
const logger = process.logger || console
|
||||
|
||||
try {
|
||||
const headers: any = {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
|
||||
if (accessToken) headers.Authorization = `Bearer ${accessToken}`
|
||||
|
||||
let executionSessionId: string
|
||||
|
||||
const session = await this.sessionManager
|
||||
.getSession(accessToken)
|
||||
.getSession(access_token)
|
||||
.catch((err) => {
|
||||
throw prefixMessage(err, 'Error while getting session. ')
|
||||
})
|
||||
@@ -303,7 +312,7 @@ export class SASViyaApiClient {
|
||||
|
||||
if (printPid) {
|
||||
const { result: jobIdVariable } = await this.sessionManager
|
||||
.getVariable(executionSessionId, 'SYSJOBID', accessToken)
|
||||
.getVariable(executionSessionId, 'SYSJOBID', access_token)
|
||||
.catch((err) => {
|
||||
throw prefixMessage(err, 'Error while getting session variable. ')
|
||||
})
|
||||
@@ -335,7 +344,6 @@ export class SASViyaApiClient {
|
||||
if (debug) {
|
||||
jobArguments['_OMITTEXTLOG'] = false
|
||||
jobArguments['_OMITSESSIONRESULTS'] = false
|
||||
jobArguments['_DEBUG'] = 131
|
||||
}
|
||||
|
||||
let fileName
|
||||
@@ -356,11 +364,15 @@ export class SASViyaApiClient {
|
||||
: jobPath
|
||||
}
|
||||
|
||||
if (variables) jobVariables = { ...jobVariables, ...variables }
|
||||
|
||||
if (debug) jobVariables = { ...jobVariables, _DEBUG: 131 }
|
||||
|
||||
let files: any[] = []
|
||||
|
||||
if (data) {
|
||||
if (JSON.stringify(data).includes(';')) {
|
||||
files = await this.uploadTables(data, accessToken).catch((err) => {
|
||||
files = await this.uploadTables(data, access_token).catch((err) => {
|
||||
throw prefixMessage(err, 'Error while uploading tables. ')
|
||||
})
|
||||
|
||||
@@ -390,7 +402,7 @@ export class SASViyaApiClient {
|
||||
.post<Job>(
|
||||
`/compute/sessions/${executionSessionId}/jobs`,
|
||||
jobRequestBody,
|
||||
accessToken
|
||||
access_token
|
||||
)
|
||||
.catch((err) => {
|
||||
throw prefixMessage(err, 'Error while posting job. ')
|
||||
@@ -399,8 +411,8 @@ export class SASViyaApiClient {
|
||||
if (!waitForResult) return session
|
||||
|
||||
if (debug) {
|
||||
console.log(`Job has been submitted for '${fileName}'.`)
|
||||
console.log(
|
||||
logger.info(`Job has been submitted for '${fileName}'.`)
|
||||
logger.info(
|
||||
`You can monitor the job progress at '${this.serverUrl}${
|
||||
postedJob.links.find((l: any) => l.rel === 'state')!.href
|
||||
}'.`
|
||||
@@ -410,7 +422,7 @@ export class SASViyaApiClient {
|
||||
const jobStatus = await this.pollJobState(
|
||||
postedJob,
|
||||
etag,
|
||||
accessToken,
|
||||
authConfig,
|
||||
pollOptions
|
||||
).catch(async (err) => {
|
||||
const error = err?.response?.data
|
||||
@@ -423,7 +435,7 @@ export class SASViyaApiClient {
|
||||
const logCount = 1000000
|
||||
err.log = await fetchLogByChunks(
|
||||
this.requestClient,
|
||||
accessToken!,
|
||||
access_token!,
|
||||
sessionLogUrl,
|
||||
logCount
|
||||
)
|
||||
@@ -431,10 +443,14 @@ export class SASViyaApiClient {
|
||||
throw prefixMessage(err, 'Error while polling job status. ')
|
||||
})
|
||||
|
||||
if (authConfig) {
|
||||
;({ access_token } = await this.getTokens(authConfig))
|
||||
}
|
||||
|
||||
const { result: currentJob } = await this.requestClient
|
||||
.get<Job>(
|
||||
`/compute/sessions/${executionSessionId}/jobs/${postedJob.id}`,
|
||||
accessToken
|
||||
access_token
|
||||
)
|
||||
.catch((err) => {
|
||||
throw prefixMessage(err, 'Error while getting job. ')
|
||||
@@ -450,7 +466,7 @@ export class SASViyaApiClient {
|
||||
const logCount = currentJob.logStatistics?.lineCount ?? 1000000
|
||||
log = await fetchLogByChunks(
|
||||
this.requestClient,
|
||||
accessToken!,
|
||||
access_token!,
|
||||
logUrl,
|
||||
logCount
|
||||
)
|
||||
@@ -470,7 +486,7 @@ export class SASViyaApiClient {
|
||||
|
||||
if (resultLink) {
|
||||
jobResult = await this.requestClient
|
||||
.get<any>(resultLink, accessToken, 'text/plain')
|
||||
.get<any>(resultLink, access_token, 'text/plain')
|
||||
.catch(async (e) => {
|
||||
if (e instanceof NotFoundError) {
|
||||
if (logLink) {
|
||||
@@ -478,7 +494,7 @@ export class SASViyaApiClient {
|
||||
const logCount = currentJob.logStatistics?.lineCount ?? 1000000
|
||||
log = await fetchLogByChunks(
|
||||
this.requestClient,
|
||||
accessToken!,
|
||||
access_token!,
|
||||
logUrl,
|
||||
logCount
|
||||
)
|
||||
@@ -497,7 +513,7 @@ export class SASViyaApiClient {
|
||||
}
|
||||
|
||||
await this.sessionManager
|
||||
.clearSession(executionSessionId, accessToken)
|
||||
.clearSession(executionSessionId, access_token)
|
||||
.catch((err) => {
|
||||
throw prefixMessage(err, 'Error while clearing session. ')
|
||||
})
|
||||
@@ -509,7 +525,7 @@ export class SASViyaApiClient {
|
||||
jobPath,
|
||||
linesOfCode,
|
||||
contextName,
|
||||
accessToken,
|
||||
authConfig,
|
||||
data,
|
||||
debug,
|
||||
false,
|
||||
@@ -532,6 +548,53 @@ export class SASViyaApiClient {
|
||||
.then((res) => res.result)
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a file. Path to or URI of the parent folder is required.
|
||||
* @param fileName - the name of the new file.
|
||||
* @param contentBuffer - the content of the new file in Buffer.
|
||||
* @param parentFolderPath - the full path to the parent folder. If not
|
||||
* provided, the parentFolderUri must be provided.
|
||||
* @param parentFolderUri - the URI (eg /folders/folders/UUID) of the parent
|
||||
* folder. If not provided, the parentFolderPath must be provided.
|
||||
* @param accessToken - an access token for authorizing the request.
|
||||
*/
|
||||
public async createFile(
|
||||
fileName: string,
|
||||
contentBuffer: Buffer,
|
||||
parentFolderPath?: string,
|
||||
parentFolderUri?: string,
|
||||
accessToken?: string
|
||||
): Promise<File> {
|
||||
if (!parentFolderPath && !parentFolderUri) {
|
||||
throw new Error('Path or URI of the parent folder is required.')
|
||||
}
|
||||
|
||||
if (!parentFolderUri && parentFolderPath) {
|
||||
parentFolderUri = await this.getFolderUri(parentFolderPath, accessToken)
|
||||
}
|
||||
|
||||
const headers = {
|
||||
Accept: 'application/vnd.sas.file+json',
|
||||
'Content-Disposition': `filename="${fileName}";`
|
||||
}
|
||||
|
||||
const formData = new NodeFormData()
|
||||
formData.append('file', contentBuffer, fileName)
|
||||
|
||||
const mimeType =
|
||||
mime.getType(fileName.match(/\.[0-9a-z]+$/i)?.[0] || '') ?? 'text/plain'
|
||||
|
||||
return (
|
||||
await this.requestClient.post<File>(
|
||||
`/files/files?parentFolderUri=${parentFolderUri}&typeDefName=file#rawUpload`,
|
||||
formData,
|
||||
accessToken,
|
||||
'multipart/form-data; boundary=' + (formData as any)._boundary,
|
||||
headers
|
||||
)
|
||||
).result
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a folder. Path to or URI of the parent folder is required.
|
||||
* @param folderName - the name of the new folder.
|
||||
@@ -549,6 +612,7 @@ export class SASViyaApiClient {
|
||||
accessToken?: string,
|
||||
isForced?: boolean
|
||||
): Promise<Folder> {
|
||||
const logger = process.logger || console
|
||||
if (!parentFolderPath && !parentFolderUri) {
|
||||
throw new Error('Path or URI of the parent folder is required.')
|
||||
}
|
||||
@@ -556,7 +620,7 @@ export class SASViyaApiClient {
|
||||
if (!parentFolderUri && parentFolderPath) {
|
||||
parentFolderUri = await this.getFolderUri(parentFolderPath, accessToken)
|
||||
if (!parentFolderUri) {
|
||||
console.log(
|
||||
logger.info(
|
||||
`Parent folder at path '${parentFolderPath}' is not present.`
|
||||
)
|
||||
|
||||
@@ -568,7 +632,7 @@ export class SASViyaApiClient {
|
||||
if (newParentFolderPath === '') {
|
||||
throw new Error('Root folder has to be present on the server.')
|
||||
}
|
||||
console.log(
|
||||
logger.info(
|
||||
`Creating parent folder:\n'${newFolderName}' in '${newParentFolderPath}'`
|
||||
)
|
||||
const parentFolder = await this.createFolder(
|
||||
@@ -577,7 +641,7 @@ export class SASViyaApiClient {
|
||||
undefined,
|
||||
accessToken
|
||||
)
|
||||
console.log(
|
||||
logger.info(
|
||||
`Parent folder '${newFolderName}' has been successfully created.`
|
||||
)
|
||||
parentFolderUri = `/folders/folders/${parentFolder.id}`
|
||||
@@ -719,13 +783,11 @@ export class SASViyaApiClient {
|
||||
let formData
|
||||
if (typeof FormData === 'undefined') {
|
||||
formData = new NodeFormData()
|
||||
formData.append('grant_type', 'authorization_code')
|
||||
formData.append('code', authCode)
|
||||
} else {
|
||||
formData = new FormData()
|
||||
formData.append('grant_type', 'authorization_code')
|
||||
formData.append('code', authCode)
|
||||
}
|
||||
formData.append('grant_type', 'authorization_code')
|
||||
formData.append('code', authCode)
|
||||
|
||||
const authResponse = await this.requestClient
|
||||
.post(
|
||||
@@ -814,18 +876,25 @@ export class SASViyaApiClient {
|
||||
* @param expectWebout - a boolean indicating whether to expect a _webout response.
|
||||
* @param pollOptions - an object that represents poll interval(milliseconds) and maximum amount of attempts. Object example: { MAX_POLL_COUNT: 24 * 60 * 60, POLL_INTERVAL: 1000 }.
|
||||
* @param printPid - a boolean that indicates whether the function should print (PID) of the started job.
|
||||
* @param variables - an object that represents macro variables.
|
||||
*/
|
||||
public async executeComputeJob(
|
||||
sasJob: string,
|
||||
contextName: string,
|
||||
debug?: boolean,
|
||||
data?: any,
|
||||
accessToken?: string,
|
||||
authConfig?: AuthConfig,
|
||||
waitForResult = true,
|
||||
expectWebout = false,
|
||||
pollOptions?: PollOptions,
|
||||
printPid = false
|
||||
printPid = false,
|
||||
variables?: MacroVar
|
||||
) {
|
||||
let access_token = (authConfig || {}).access_token
|
||||
if (authConfig) {
|
||||
;({ access_token } = await this.getTokens(authConfig))
|
||||
}
|
||||
|
||||
if (isRelativePath(sasJob) && !this.rootFolderName) {
|
||||
throw new Error(
|
||||
'Relative paths cannot be used without specifying a root folder name'
|
||||
@@ -839,7 +908,7 @@ export class SASViyaApiClient {
|
||||
? `${this.rootFolderName}/${folderPath}`
|
||||
: folderPath
|
||||
|
||||
await this.populateFolderMap(fullFolderPath, accessToken).catch((err) => {
|
||||
await this.populateFolderMap(fullFolderPath, access_token).catch((err) => {
|
||||
throw prefixMessage(err, 'Error while populating folder map. ')
|
||||
})
|
||||
|
||||
@@ -851,12 +920,6 @@ export class SASViyaApiClient {
|
||||
)
|
||||
}
|
||||
|
||||
const headers: any = { 'Content-Type': 'application/json' }
|
||||
|
||||
if (!!accessToken) {
|
||||
headers.Authorization = `Bearer ${accessToken}`
|
||||
}
|
||||
|
||||
const jobToExecute = jobFolder?.find((item) => item.name === jobName)
|
||||
|
||||
if (!jobToExecute) {
|
||||
@@ -877,7 +940,7 @@ export class SASViyaApiClient {
|
||||
const { result: jobDefinition } = await this.requestClient
|
||||
.get<JobDefinition>(
|
||||
`${this.serverUrl}${jobDefinitionLink.href}`,
|
||||
accessToken
|
||||
access_token
|
||||
)
|
||||
.catch((err) => {
|
||||
throw prefixMessage(err, 'Error while getting job definition. ')
|
||||
@@ -897,13 +960,14 @@ export class SASViyaApiClient {
|
||||
sasJob,
|
||||
linesToExecute,
|
||||
contextName,
|
||||
accessToken,
|
||||
authConfig,
|
||||
data,
|
||||
debug,
|
||||
expectWebout,
|
||||
waitForResult,
|
||||
pollOptions,
|
||||
printPid
|
||||
printPid,
|
||||
variables
|
||||
)
|
||||
}
|
||||
|
||||
@@ -920,8 +984,12 @@ export class SASViyaApiClient {
|
||||
contextName: string,
|
||||
debug: boolean,
|
||||
data?: any,
|
||||
accessToken?: string
|
||||
authConfig?: AuthConfig
|
||||
) {
|
||||
let access_token = (authConfig || {}).access_token
|
||||
if (authConfig) {
|
||||
;({ access_token } = await this.getTokens(authConfig))
|
||||
}
|
||||
if (isRelativePath(sasJob) && !this.rootFolderName) {
|
||||
throw new Error(
|
||||
'Relative paths cannot be used without specifying a root folder name.'
|
||||
@@ -934,7 +1002,7 @@ export class SASViyaApiClient {
|
||||
const fullFolderPath = isRelativePath(sasJob)
|
||||
? `${this.rootFolderName}/${folderPath}`
|
||||
: folderPath
|
||||
await this.populateFolderMap(fullFolderPath, accessToken)
|
||||
await this.populateFolderMap(fullFolderPath, access_token)
|
||||
|
||||
const jobFolder = this.folderMap.get(fullFolderPath)
|
||||
if (!jobFolder) {
|
||||
@@ -947,7 +1015,7 @@ export class SASViyaApiClient {
|
||||
|
||||
let files: any[] = []
|
||||
if (data && Object.keys(data).length) {
|
||||
files = await this.uploadTables(data, accessToken)
|
||||
files = await this.uploadTables(data, access_token)
|
||||
}
|
||||
|
||||
if (!jobToExecute) {
|
||||
@@ -959,7 +1027,7 @@ export class SASViyaApiClient {
|
||||
|
||||
const { result: jobDefinition } = await this.requestClient.get<Job>(
|
||||
`${this.serverUrl}${jobDefinitionLink}`,
|
||||
accessToken
|
||||
access_token
|
||||
)
|
||||
|
||||
const jobArguments: { [key: string]: any } = {
|
||||
@@ -995,18 +1063,18 @@ export class SASViyaApiClient {
|
||||
const { result: postedJob, etag } = await this.requestClient.post<Job>(
|
||||
`${this.serverUrl}/jobExecution/jobs?_action=wait`,
|
||||
postJobRequestBody,
|
||||
accessToken
|
||||
access_token
|
||||
)
|
||||
const jobStatus = await this.pollJobState(
|
||||
postedJob,
|
||||
etag,
|
||||
accessToken
|
||||
authConfig
|
||||
).catch((err) => {
|
||||
throw prefixMessage(err, 'Error while polling job status. ')
|
||||
})
|
||||
const { result: currentJob } = await this.requestClient.get<Job>(
|
||||
`${this.serverUrl}/jobExecution/jobs/${postedJob.id}`,
|
||||
accessToken
|
||||
access_token
|
||||
)
|
||||
|
||||
let jobResult
|
||||
@@ -1017,13 +1085,13 @@ export class SASViyaApiClient {
|
||||
if (resultLink) {
|
||||
jobResult = await this.requestClient.get<any>(
|
||||
`${this.serverUrl}${resultLink}/content`,
|
||||
accessToken,
|
||||
access_token,
|
||||
'text/plain'
|
||||
)
|
||||
}
|
||||
if (debug && logLink) {
|
||||
log = await this.requestClient
|
||||
.get<any>(`${this.serverUrl}${logLink.href}/content`, accessToken)
|
||||
.get<any>(`${this.serverUrl}${logLink.href}/content`, access_token)
|
||||
.then((res: any) => res.result.items.map((i: any) => i.line).join('\n'))
|
||||
}
|
||||
if (jobStatus === 'failed') {
|
||||
@@ -1073,12 +1141,18 @@ export class SASViyaApiClient {
|
||||
private async pollJobState(
|
||||
postedJob: any,
|
||||
etag: string | null,
|
||||
accessToken?: string,
|
||||
authConfig?: AuthConfig,
|
||||
pollOptions?: PollOptions
|
||||
) {
|
||||
const logger = process.logger || console
|
||||
|
||||
let POLL_INTERVAL = 300
|
||||
let MAX_POLL_COUNT = 1000
|
||||
let MAX_ERROR_COUNT = 5
|
||||
let access_token = (authConfig || {}).access_token
|
||||
if (authConfig) {
|
||||
;({ access_token } = await this.getTokens(authConfig))
|
||||
}
|
||||
|
||||
if (pollOptions) {
|
||||
POLL_INTERVAL = pollOptions.POLL_INTERVAL || POLL_INTERVAL
|
||||
@@ -1092,8 +1166,8 @@ export class SASViyaApiClient {
|
||||
'Content-Type': 'application/json',
|
||||
'If-None-Match': etag
|
||||
}
|
||||
if (accessToken) {
|
||||
headers.Authorization = `Bearer ${accessToken}`
|
||||
if (access_token) {
|
||||
headers.Authorization = `Bearer ${access_token}`
|
||||
}
|
||||
const stateLink = postedJob.links.find((l: any) => l.rel === 'state')
|
||||
if (!stateLink) {
|
||||
@@ -1103,7 +1177,7 @@ export class SASViyaApiClient {
|
||||
const { result: state } = await this.requestClient
|
||||
.get<string>(
|
||||
`${this.serverUrl}${stateLink.href}?_action=wait&wait=300`,
|
||||
accessToken,
|
||||
access_token,
|
||||
'text/plain',
|
||||
{},
|
||||
this.debug
|
||||
@@ -1131,11 +1205,15 @@ export class SASViyaApiClient {
|
||||
postedJobState === 'pending' ||
|
||||
postedJobState === 'unavailable'
|
||||
) {
|
||||
if (authConfig) {
|
||||
;({ access_token } = await this.getTokens(authConfig))
|
||||
}
|
||||
|
||||
if (stateLink) {
|
||||
const { result: jobState } = await this.requestClient
|
||||
.get<string>(
|
||||
`${this.serverUrl}${stateLink.href}?_action=wait&wait=300`,
|
||||
accessToken,
|
||||
access_token,
|
||||
'text/plain',
|
||||
{},
|
||||
this.debug
|
||||
@@ -1164,8 +1242,8 @@ export class SASViyaApiClient {
|
||||
}
|
||||
|
||||
if (this.debug && printedState !== postedJobState) {
|
||||
console.log('Polling job status...')
|
||||
console.log(`Current job state: ${postedJobState}`)
|
||||
logger.info('Polling job status...')
|
||||
logger.info(`Current job state: ${postedJobState}`)
|
||||
|
||||
printedState = postedJobState
|
||||
}
|
||||
@@ -1355,6 +1433,9 @@ export class SASViyaApiClient {
|
||||
accessToken
|
||||
)
|
||||
|
||||
if (!sourceFolderUri) {
|
||||
return undefined
|
||||
}
|
||||
const sourceFolderId = sourceFolderUri?.split('/').pop()
|
||||
|
||||
const { result: folder } = await this.requestClient
|
||||
@@ -1409,4 +1490,21 @@ export class SASViyaApiClient {
|
||||
|
||||
return movedFolder
|
||||
}
|
||||
|
||||
private async getTokens(authConfig: AuthConfig): Promise<AuthConfig> {
|
||||
const logger = process.logger || console
|
||||
let { access_token, refresh_token, client, secret } = authConfig
|
||||
if (
|
||||
isAccessTokenExpiring(access_token) ||
|
||||
isRefreshTokenExpiring(refresh_token)
|
||||
) {
|
||||
logger.info('Refreshing access and refresh tokens.')
|
||||
;({ access_token, refresh_token } = await this.refreshTokens(
|
||||
client,
|
||||
secret,
|
||||
refresh_token
|
||||
))
|
||||
}
|
||||
return { access_token, refresh_token, client, secret }
|
||||
}
|
||||
}
|
||||
|
||||
232
src/SASjs.ts
232
src/SASjs.ts
@@ -4,7 +4,7 @@ import { SASViyaApiClient } from './SASViyaApiClient'
|
||||
import { SAS9ApiClient } from './SAS9ApiClient'
|
||||
import { FileUploader } from './FileUploader'
|
||||
import { AuthManager } from './auth'
|
||||
import { ServerType } from '@sasjs/utils/types'
|
||||
import { ServerType, MacroVar, AuthConfig } from '@sasjs/utils/types'
|
||||
import { RequestClient } from './request/RequestClient'
|
||||
import {
|
||||
JobExecutor,
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
Sas9JobExecutor
|
||||
} from './job-execution'
|
||||
import { ErrorResponse } from './types/errors'
|
||||
import { ExtraResponseAttributes } from '@sasjs/utils/types'
|
||||
|
||||
const defaultConfig: SASjsConfig = {
|
||||
serverUrl: '',
|
||||
@@ -23,7 +24,7 @@ const defaultConfig: SASjsConfig = {
|
||||
serverType: ServerType.SasViya,
|
||||
debug: false,
|
||||
contextName: 'SAS Job Execution compute context',
|
||||
useComputeApi: false,
|
||||
useComputeApi: null,
|
||||
allowInsecureRequests: false
|
||||
}
|
||||
|
||||
@@ -59,15 +60,15 @@ export default class SASjs {
|
||||
|
||||
public async executeScriptSAS9(
|
||||
linesOfCode: string[],
|
||||
serverName: string,
|
||||
repositoryName: string
|
||||
userName: string,
|
||||
password: string
|
||||
) {
|
||||
this.isMethodSupported('executeScriptSAS9', ServerType.Sas9)
|
||||
|
||||
return await this.sas9ApiClient?.executeScript(
|
||||
linesOfCode,
|
||||
serverName,
|
||||
repositoryName
|
||||
userName,
|
||||
password
|
||||
)
|
||||
}
|
||||
|
||||
@@ -102,12 +103,12 @@ export default class SASjs {
|
||||
|
||||
/**
|
||||
* Gets executable compute contexts.
|
||||
* @param accessToken - an access token for an authorized user.
|
||||
* @param authConfig - an access token, refresh token, client and secret for an authorized user.
|
||||
*/
|
||||
public async getExecutableContexts(accessToken: string) {
|
||||
public async getExecutableContexts(authConfig: AuthConfig) {
|
||||
this.isMethodSupported('getExecutableContexts', ServerType.SasViya)
|
||||
|
||||
return await this.sasViyaApiClient!.getExecutableContexts(accessToken)
|
||||
return await this.sasViyaApiClient!.getExecutableContexts(authConfig)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -239,14 +240,14 @@ export default class SASjs {
|
||||
* @param fileName - name of the file to run. It will be converted to path to the file being submitted for execution.
|
||||
* @param linesOfCode - lines of sas code from the file to run.
|
||||
* @param contextName - context name on which code will be run on the server.
|
||||
* @param accessToken - (optional) the access token for authorizing the request.
|
||||
* @param authConfig - (optional) the access token, refresh token, client and secret for authorizing the request.
|
||||
* @param debug - (optional) if true, global debug config will be overriden
|
||||
*/
|
||||
public async executeScriptSASViya(
|
||||
fileName: string,
|
||||
linesOfCode: string[],
|
||||
contextName: string,
|
||||
accessToken?: string,
|
||||
authConfig?: AuthConfig,
|
||||
debug?: boolean
|
||||
) {
|
||||
this.isMethodSupported('executeScriptSASViya', ServerType.SasViya)
|
||||
@@ -260,14 +261,14 @@ export default class SASjs {
|
||||
fileName,
|
||||
linesOfCode,
|
||||
contextName,
|
||||
accessToken,
|
||||
authConfig,
|
||||
null,
|
||||
debug ? debug : this.sasjsConfig.debug
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a folder at SAS file system.
|
||||
* Creates a folder in the logical SAS folder tree
|
||||
* @param folderName - name of the folder to be created.
|
||||
* @param parentFolderPath - the full path (eg `/Public/example/myFolder`) of the parent folder.
|
||||
* @param parentFolderUri - the URI of the parent folder.
|
||||
@@ -299,6 +300,40 @@ export default class SASjs {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a file in the logical SAS folder tree
|
||||
* @param fileName - name of the file to be created.
|
||||
* @param content - content of the file to be created.
|
||||
* @param parentFolderPath - the full path (eg `/Public/example/myFolder`) of the parent folder.
|
||||
* @param parentFolderUri - the URI of the parent folder.
|
||||
* @param accessToken - the access token to authorizing the request.
|
||||
* @param sasApiClient - a client for interfacing with SAS API.
|
||||
*/
|
||||
public async createFile(
|
||||
fileName: string,
|
||||
content: Buffer,
|
||||
parentFolderPath: string,
|
||||
parentFolderUri?: string,
|
||||
accessToken?: string,
|
||||
sasApiClient?: SASViyaApiClient
|
||||
) {
|
||||
if (sasApiClient)
|
||||
return await sasApiClient.createFile(
|
||||
fileName,
|
||||
content,
|
||||
parentFolderPath,
|
||||
parentFolderUri,
|
||||
accessToken
|
||||
)
|
||||
return await this.sasViyaApiClient!.createFile(
|
||||
fileName,
|
||||
content,
|
||||
parentFolderPath,
|
||||
parentFolderUri,
|
||||
accessToken
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches a folder from the SAS file system.
|
||||
* @param folderPath - path of the folder to be fetched.
|
||||
@@ -509,12 +544,7 @@ export default class SASjs {
|
||||
public uploadFile(sasJob: string, files: UploadFile[], params: any) {
|
||||
const fileUploader =
|
||||
this.fileUploader ||
|
||||
new FileUploader(
|
||||
this.sasjsConfig.appLoc,
|
||||
this.sasjsConfig.serverUrl,
|
||||
this.jobsPath,
|
||||
this.requestClient!
|
||||
)
|
||||
new FileUploader(this.sasjsConfig, this.jobsPath, this.requestClient!)
|
||||
|
||||
return fileUploader.uploadFile(sasJob, files, params)
|
||||
}
|
||||
@@ -540,50 +570,130 @@ export default class SASjs {
|
||||
* `await request(sasJobPath, data, config, () => setIsLoggedIn(false))`
|
||||
* If you are not passing in any data and configuration, it will look like so:
|
||||
* `await request(sasJobPath, {}, {}, () => setIsLoggedIn(false))`
|
||||
* @param extraResponseAttributes - a array of predefined values that are used
|
||||
* to provide extra attributes (same names as those values) to be added in response
|
||||
* Supported values are declared in ExtraResponseAttributes type.
|
||||
*/
|
||||
public async request(
|
||||
sasJob: string,
|
||||
data: { [key: string]: any },
|
||||
data: { [key: string]: any } | null,
|
||||
config: { [key: string]: any } = {},
|
||||
loginRequiredCallback?: () => any,
|
||||
accessToken?: string
|
||||
authConfig?: AuthConfig,
|
||||
extraResponseAttributes: ExtraResponseAttributes[] = []
|
||||
) {
|
||||
config = {
|
||||
...this.sasjsConfig,
|
||||
...config
|
||||
}
|
||||
|
||||
if (config.serverType === ServerType.SasViya && config.contextName) {
|
||||
if (config.useComputeApi) {
|
||||
return await this.computeJobExecutor!.execute(
|
||||
sasJob,
|
||||
data,
|
||||
config,
|
||||
loginRequiredCallback,
|
||||
accessToken
|
||||
)
|
||||
const validationResult = this.validateInput(data)
|
||||
|
||||
if (validationResult.status) {
|
||||
if (
|
||||
config.serverType !== ServerType.Sas9 &&
|
||||
config.useComputeApi !== undefined &&
|
||||
config.useComputeApi !== null
|
||||
) {
|
||||
if (config.useComputeApi) {
|
||||
return await this.computeJobExecutor!.execute(
|
||||
sasJob,
|
||||
data,
|
||||
config,
|
||||
loginRequiredCallback,
|
||||
authConfig
|
||||
)
|
||||
} else {
|
||||
return await this.jesJobExecutor!.execute(
|
||||
sasJob,
|
||||
data,
|
||||
config,
|
||||
loginRequiredCallback,
|
||||
authConfig,
|
||||
extraResponseAttributes
|
||||
)
|
||||
}
|
||||
} else if (
|
||||
config.serverType === ServerType.Sas9 &&
|
||||
config.username &&
|
||||
config.password
|
||||
) {
|
||||
return await this.sas9JobExecutor!.execute(sasJob, data, config)
|
||||
} else {
|
||||
return await this.jesJobExecutor!.execute(
|
||||
return await this.webJobExecutor!.execute(
|
||||
sasJob,
|
||||
data,
|
||||
config,
|
||||
loginRequiredCallback,
|
||||
accessToken
|
||||
authConfig,
|
||||
extraResponseAttributes
|
||||
)
|
||||
}
|
||||
} else if (
|
||||
config.serverType === ServerType.Sas9 &&
|
||||
config.username &&
|
||||
config.password
|
||||
) {
|
||||
return await this.sas9JobExecutor!.execute(sasJob, data, config)
|
||||
} else {
|
||||
return await this.webJobExecutor!.execute(
|
||||
sasJob,
|
||||
data,
|
||||
config,
|
||||
loginRequiredCallback
|
||||
)
|
||||
return Promise.reject(new ErrorResponse(validationResult.msg))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This function validates the input data structure and table naming convention
|
||||
*
|
||||
* @param data A json object that contains one or more tables, it can also be null
|
||||
* @returns An object which contains two attributes: 1) status: boolean, 2) msg: string
|
||||
*/
|
||||
private validateInput(data: { [key: string]: any } | null): {
|
||||
status: boolean
|
||||
msg: string
|
||||
} {
|
||||
if (data === null) return { status: true, msg: '' }
|
||||
for (const key in data) {
|
||||
if (!key.match(/^[a-zA-Z_]/)) {
|
||||
return {
|
||||
status: false,
|
||||
msg: 'First letter of table should be alphabet or underscore.'
|
||||
}
|
||||
}
|
||||
|
||||
if (!key.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/)) {
|
||||
return { status: false, msg: 'Table name should be alphanumeric.' }
|
||||
}
|
||||
|
||||
if (key.length > 32) {
|
||||
return {
|
||||
status: false,
|
||||
msg: 'Maximum length for table name could be 32 characters.'
|
||||
}
|
||||
}
|
||||
|
||||
if (this.getType(data[key]) !== 'Array') {
|
||||
return {
|
||||
status: false,
|
||||
msg: 'Parameter data contains invalid table structure.'
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < data[key].length; i++) {
|
||||
if (this.getType(data[key][i]) !== 'object') {
|
||||
return {
|
||||
status: false,
|
||||
msg: `Table ${key} contains invalid structure.`
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return { status: true, msg: '' }
|
||||
}
|
||||
|
||||
/**
|
||||
* this function returns the type of variable
|
||||
*
|
||||
* @param data it could be anything, like string, array, object etc.
|
||||
* @returns a string which tells the type of input parameter
|
||||
*/
|
||||
private getType(data: any): string {
|
||||
if (Array.isArray(data)) {
|
||||
return 'Array'
|
||||
} else {
|
||||
return typeof data
|
||||
}
|
||||
}
|
||||
|
||||
@@ -624,7 +734,7 @@ export default class SASjs {
|
||||
)
|
||||
sasApiClient.debug = this.sasjsConfig.debug
|
||||
} else if (this.sasjsConfig.serverType === ServerType.Sas9) {
|
||||
sasApiClient = new SAS9ApiClient(serverUrl)
|
||||
sasApiClient = new SAS9ApiClient(serverUrl, this.jobsPath)
|
||||
}
|
||||
} else {
|
||||
let sasClientConfig: any = null
|
||||
@@ -666,20 +776,22 @@ export default class SASjs {
|
||||
* @param config - provide any changes to the config here, for instance to
|
||||
* enable/disable `debug`. Any change provided will override the global config,
|
||||
* for that particular function call.
|
||||
* @param accessToken - a valid access token that is authorised to execute compute jobs.
|
||||
* @param authConfig - a valid client, secret, refresh and access tokens that are authorised to execute compute jobs.
|
||||
* The access token is not required when the user is authenticated via the browser.
|
||||
* @param waitForResult - a boolean that indicates whether the function needs to wait for execution to complete.
|
||||
* @param pollOptions - an object that represents poll interval(milliseconds) and maximum amount of attempts. Object example: { MAX_POLL_COUNT: 24 * 60 * 60, POLL_INTERVAL: 1000 }.
|
||||
* @param printPid - a boolean that indicates whether the function should print (PID) of the started job.
|
||||
* @param variables - an object that represents macro variables.
|
||||
*/
|
||||
public async startComputeJob(
|
||||
sasJob: string,
|
||||
data: any,
|
||||
config: any = {},
|
||||
accessToken?: string,
|
||||
authConfig?: AuthConfig,
|
||||
waitForResult?: boolean,
|
||||
pollOptions?: PollOptions,
|
||||
printPid = false
|
||||
printPid = false,
|
||||
variables?: MacroVar
|
||||
) {
|
||||
config = {
|
||||
...this.sasjsConfig,
|
||||
@@ -698,11 +810,12 @@ export default class SASjs {
|
||||
config.contextName,
|
||||
config.debug,
|
||||
data,
|
||||
accessToken,
|
||||
authConfig,
|
||||
!!waitForResult,
|
||||
false,
|
||||
pollOptions,
|
||||
printPid
|
||||
printPid,
|
||||
variables
|
||||
)
|
||||
}
|
||||
|
||||
@@ -813,12 +926,15 @@ export default class SASjs {
|
||||
if (this.sasjsConfig.serverType === ServerType.Sas9) {
|
||||
if (this.sas9ApiClient)
|
||||
this.sas9ApiClient!.setConfig(this.sasjsConfig.serverUrl)
|
||||
else this.sas9ApiClient = new SAS9ApiClient(this.sasjsConfig.serverUrl)
|
||||
else
|
||||
this.sas9ApiClient = new SAS9ApiClient(
|
||||
this.sasjsConfig.serverUrl,
|
||||
this.jobsPath
|
||||
)
|
||||
}
|
||||
|
||||
this.fileUploader = new FileUploader(
|
||||
this.sasjsConfig.appLoc,
|
||||
this.sasjsConfig.serverUrl,
|
||||
this.sasjsConfig,
|
||||
this.jobsPath,
|
||||
this.requestClient
|
||||
)
|
||||
@@ -867,6 +983,16 @@ export default class SASjs {
|
||||
isForced
|
||||
)
|
||||
break
|
||||
case 'file':
|
||||
await this.createFile(
|
||||
member.name,
|
||||
member.code,
|
||||
parentFolder,
|
||||
undefined,
|
||||
accessToken,
|
||||
sasApiClient
|
||||
)
|
||||
break
|
||||
case 'service':
|
||||
await this.createJobDefinition(
|
||||
member.name,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Session, Context, CsrfToken, SessionVariable } from './types'
|
||||
import { Session, Context, SessionVariable } from './types'
|
||||
import { NoSessionStateError } from './types/errors'
|
||||
import { asyncForEach, isUrl } from './utils'
|
||||
import { prefixMessage } from '@sasjs/utils/error'
|
||||
import { RequestClient } from './request/RequestClient'
|
||||
@@ -6,10 +7,6 @@ import { RequestClient } from './request/RequestClient'
|
||||
const MAX_SESSION_COUNT = 1
|
||||
const RETRY_LIMIT: number = 3
|
||||
let RETRY_COUNT: number = 0
|
||||
const INTERNAL_SAS_ERROR = {
|
||||
status: 304,
|
||||
message: 'Not Modified'
|
||||
}
|
||||
|
||||
export class SessionManager {
|
||||
constructor(
|
||||
@@ -158,11 +155,13 @@ export class SessionManager {
|
||||
etag: string | null,
|
||||
accessToken?: string
|
||||
) {
|
||||
const logger = process.logger || console
|
||||
|
||||
let sessionState = session.state
|
||||
|
||||
const stateLink = session.links.find((l: any) => l.rel === 'state')
|
||||
|
||||
return new Promise(async (resolve, _) => {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
if (
|
||||
sessionState === 'pending' ||
|
||||
sessionState === 'running' ||
|
||||
@@ -170,23 +169,24 @@ export class SessionManager {
|
||||
) {
|
||||
if (stateLink) {
|
||||
if (this.debug && !this.printedSessionState.printed) {
|
||||
console.log('Polling session status...')
|
||||
logger.info('Polling session status...')
|
||||
|
||||
this.printedSessionState.printed = true
|
||||
}
|
||||
|
||||
const state = await this.getSessionState(
|
||||
`${this.serverUrl}${stateLink.href}?wait=30`,
|
||||
etag!,
|
||||
accessToken
|
||||
).catch((err) => {
|
||||
throw err
|
||||
})
|
||||
const { result: state, responseStatus: responseStatus } =
|
||||
await this.getSessionState(
|
||||
`${this.serverUrl}${stateLink.href}?wait=30`,
|
||||
etag!,
|
||||
accessToken
|
||||
).catch((err) => {
|
||||
throw prefixMessage(err, 'Error while getting session state.')
|
||||
})
|
||||
|
||||
sessionState = state.trim()
|
||||
|
||||
if (this.debug && this.printedSessionState.state !== sessionState) {
|
||||
console.log(`Current session state is '${sessionState}'`)
|
||||
logger.info(`Current session state is '${sessionState}'`)
|
||||
|
||||
this.printedSessionState.state = sessionState
|
||||
this.printedSessionState.printed = false
|
||||
@@ -194,13 +194,21 @@ export class SessionManager {
|
||||
|
||||
// There is an internal error present in SAS Viya 3.5
|
||||
// Retry to wait for a session status in such case of SAS internal error
|
||||
if (
|
||||
sessionState === INTERNAL_SAS_ERROR.message &&
|
||||
RETRY_COUNT < RETRY_LIMIT
|
||||
) {
|
||||
RETRY_COUNT++
|
||||
if (!sessionState) {
|
||||
if (RETRY_COUNT < RETRY_LIMIT) {
|
||||
RETRY_COUNT++
|
||||
|
||||
resolve(this.waitForSession(session, etag, accessToken))
|
||||
resolve(this.waitForSession(session, etag, accessToken))
|
||||
} else {
|
||||
reject(
|
||||
new NoSessionStateError(
|
||||
responseStatus,
|
||||
this.serverUrl + stateLink.href,
|
||||
session.links.find((l: any) => l.rel === 'log')
|
||||
?.href as string
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
resolve(sessionState)
|
||||
@@ -218,11 +226,11 @@ export class SessionManager {
|
||||
) {
|
||||
return await this.requestClient
|
||||
.get(url, accessToken, 'text/plain', { 'If-None-Match': etag })
|
||||
.then((res) => res.result as string)
|
||||
.then((res) => ({
|
||||
result: res.result as string,
|
||||
responseStatus: res.status
|
||||
}))
|
||||
.catch((err) => {
|
||||
if (err.status === INTERNAL_SAS_ERROR.status)
|
||||
return INTERNAL_SAS_ERROR.message
|
||||
|
||||
throw err
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { ServerType } from '@sasjs/utils/types'
|
||||
import { isAuthorizeFormRequired } from '.'
|
||||
import { RequestClient } from '../request/RequestClient'
|
||||
import { serialize } from '../utils'
|
||||
|
||||
@@ -35,6 +34,7 @@ export class AuthManager {
|
||||
this.userName = loginParams.username
|
||||
|
||||
const { isLoggedIn, loginForm } = await this.checkSession()
|
||||
|
||||
if (isLoggedIn) {
|
||||
await this.loginCallback()
|
||||
|
||||
@@ -44,6 +44,44 @@ export class AuthManager {
|
||||
}
|
||||
}
|
||||
|
||||
let loginResponse = await this.sendLoginRequest(loginForm, loginParams)
|
||||
|
||||
let loggedIn = isLogInSuccess(loginResponse)
|
||||
|
||||
if (!loggedIn) {
|
||||
if (isCredentialsVerifyError(loginResponse)) {
|
||||
const newLoginForm = await this.getLoginForm(loginResponse)
|
||||
|
||||
loginResponse = await this.sendLoginRequest(newLoginForm, loginParams)
|
||||
}
|
||||
|
||||
const currentSession = await this.checkSession()
|
||||
loggedIn = currentSession.isLoggedIn
|
||||
}
|
||||
|
||||
if (loggedIn) {
|
||||
if (this.serverType === ServerType.Sas9) {
|
||||
const casAuthenticationUrl = `${this.serverUrl}/SASStoredProcess/j_spring_cas_security_check`
|
||||
|
||||
await this.requestClient.get<string>(
|
||||
`/SASLogon/login?service=${casAuthenticationUrl}`,
|
||||
undefined
|
||||
)
|
||||
}
|
||||
|
||||
this.loginCallback()
|
||||
}
|
||||
|
||||
return {
|
||||
isLoggedIn: !!loggedIn,
|
||||
userName: this.userName
|
||||
}
|
||||
}
|
||||
|
||||
private async sendLoginRequest(
|
||||
loginForm: { [key: string]: any },
|
||||
loginParams: { [key: string]: any }
|
||||
) {
|
||||
for (const key in loginForm) {
|
||||
loginParams[key] = loginForm[key]
|
||||
}
|
||||
@@ -60,21 +98,7 @@ export class AuthManager {
|
||||
}
|
||||
)
|
||||
|
||||
let loggedIn = isLogInSuccess(loginResponse)
|
||||
|
||||
if (!loggedIn) {
|
||||
const currentSession = await this.checkSession()
|
||||
loggedIn = currentSession.isLoggedIn
|
||||
}
|
||||
|
||||
if (loggedIn) {
|
||||
this.loginCallback()
|
||||
}
|
||||
|
||||
return {
|
||||
isLoggedIn: !!loggedIn,
|
||||
userName: this.userName
|
||||
}
|
||||
return loginResponse
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -168,5 +192,10 @@ export class AuthManager {
|
||||
}
|
||||
}
|
||||
|
||||
const isCredentialsVerifyError = (response: string): boolean =>
|
||||
/An error occurred while the system was verifying your credentials. Please enter your credentials again./gm.test(
|
||||
response
|
||||
)
|
||||
|
||||
const isLogInSuccess = (response: string): boolean =>
|
||||
/You have signed in/gm.test(response)
|
||||
|
||||
@@ -57,7 +57,7 @@ describe('AuthManager', () => {
|
||||
expect((authManager as any).logoutUrl).toEqual('/SASLogon/logout?')
|
||||
})
|
||||
|
||||
it('should call the auth callback and return when already logged in', async (done) => {
|
||||
it('should call the auth callback and return when already logged in', async () => {
|
||||
const authManager = new AuthManager(
|
||||
serverUrl,
|
||||
serverType,
|
||||
@@ -77,10 +77,9 @@ describe('AuthManager', () => {
|
||||
expect(loginResponse.isLoggedIn).toBeTruthy()
|
||||
expect(loginResponse.userName).toEqual(userName)
|
||||
expect(authCallback).toHaveBeenCalledTimes(1)
|
||||
done()
|
||||
})
|
||||
|
||||
it('should post a login request to the server if not logged in', async (done) => {
|
||||
it('should post a login request to the server if not logged in', async () => {
|
||||
const authManager = new AuthManager(
|
||||
serverUrl,
|
||||
serverType,
|
||||
@@ -121,10 +120,9 @@ describe('AuthManager', () => {
|
||||
}
|
||||
)
|
||||
expect(authCallback).toHaveBeenCalledTimes(1)
|
||||
done()
|
||||
})
|
||||
|
||||
it('should parse and submit the authorisation form when necessary', async (done) => {
|
||||
it('should parse and submit the authorisation form when necessary', async () => {
|
||||
const authManager = new AuthManager(
|
||||
serverUrl,
|
||||
serverType,
|
||||
@@ -160,10 +158,9 @@ describe('AuthManager', () => {
|
||||
expect(requestClient.authorize).toHaveBeenCalledWith(
|
||||
mockLoginAuthoriseRequiredResponse
|
||||
)
|
||||
done()
|
||||
})
|
||||
|
||||
it('should check and return session information if logged in', async (done) => {
|
||||
it('should check and return session information if logged in', async () => {
|
||||
const authManager = new AuthManager(
|
||||
serverUrl,
|
||||
serverType,
|
||||
@@ -189,7 +186,5 @@ describe('AuthManager', () => {
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ServerType } from '@sasjs/utils/types'
|
||||
import { AuthConfig, ServerType } from '@sasjs/utils/types'
|
||||
import { SASViyaApiClient } from '../SASViyaApiClient'
|
||||
import {
|
||||
ErrorResponse,
|
||||
@@ -17,7 +17,7 @@ export class ComputeJobExecutor extends BaseJobExecutor {
|
||||
data: any,
|
||||
config: any,
|
||||
loginRequiredCallback?: any,
|
||||
accessToken?: string
|
||||
authConfig?: AuthConfig
|
||||
) {
|
||||
const loginCallback = loginRequiredCallback || (() => Promise.resolve())
|
||||
const waitForResult = true
|
||||
@@ -30,7 +30,7 @@ export class ComputeJobExecutor extends BaseJobExecutor {
|
||||
config.contextName,
|
||||
config.debug,
|
||||
data,
|
||||
accessToken,
|
||||
authConfig,
|
||||
waitForResult,
|
||||
expectWebout
|
||||
)
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { ServerType } from '@sasjs/utils/types'
|
||||
import { AuthConfig, ServerType } from '@sasjs/utils/types'
|
||||
import { SASViyaApiClient } from '../SASViyaApiClient'
|
||||
import {
|
||||
ErrorResponse,
|
||||
JobExecutionError,
|
||||
LoginRequiredError
|
||||
} from '../types/errors'
|
||||
import { ExtraResponseAttributes } from '@sasjs/utils/types'
|
||||
import { BaseJobExecutor } from './JobExecutor'
|
||||
|
||||
export class JesJobExecutor extends BaseJobExecutor {
|
||||
@@ -17,23 +18,34 @@ export class JesJobExecutor extends BaseJobExecutor {
|
||||
data: any,
|
||||
config: any,
|
||||
loginRequiredCallback?: any,
|
||||
accessToken?: string
|
||||
authConfig?: AuthConfig,
|
||||
extraResponseAttributes: ExtraResponseAttributes[] = []
|
||||
) {
|
||||
const loginCallback = loginRequiredCallback || (() => Promise.resolve())
|
||||
|
||||
const requestPromise = new Promise((resolve, reject) => {
|
||||
this.sasViyaApiClient
|
||||
?.executeJob(
|
||||
sasJob,
|
||||
config.contextName,
|
||||
config.debug,
|
||||
data,
|
||||
accessToken
|
||||
)
|
||||
.then((response) => {
|
||||
?.executeJob(sasJob, config.contextName, config.debug, data, authConfig)
|
||||
.then((response: any) => {
|
||||
this.appendRequest(response, sasJob, config.debug)
|
||||
|
||||
resolve(response)
|
||||
let responseObject = {}
|
||||
|
||||
if (extraResponseAttributes && extraResponseAttributes.length > 0) {
|
||||
const extraAttributes = extraResponseAttributes.reduce(
|
||||
(map: any, obj: any) => ((map[obj] = response[obj]), map),
|
||||
{}
|
||||
)
|
||||
|
||||
responseObject = {
|
||||
result: response.result,
|
||||
...extraAttributes
|
||||
}
|
||||
} else {
|
||||
responseObject = response.result
|
||||
}
|
||||
|
||||
resolve(responseObject)
|
||||
})
|
||||
.catch(async (e: Error) => {
|
||||
if (e instanceof JobExecutionError) {
|
||||
@@ -50,7 +62,9 @@ export class JesJobExecutor extends BaseJobExecutor {
|
||||
sasJob,
|
||||
data,
|
||||
config,
|
||||
loginRequiredCallback
|
||||
loginRequiredCallback,
|
||||
authConfig,
|
||||
extraResponseAttributes
|
||||
).then(
|
||||
(res: any) => {
|
||||
resolve(res)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ServerType } from '@sasjs/utils/types'
|
||||
import { AuthConfig, ServerType } from '@sasjs/utils/types'
|
||||
import { SASjsRequest } from '../types'
|
||||
import { ExtraResponseAttributes } from '@sasjs/utils/types'
|
||||
import { asyncForEach, parseGeneratedCode, parseSourceCode } from '../utils'
|
||||
|
||||
export type ExecuteFunction = () => Promise<any>
|
||||
@@ -10,7 +11,8 @@ export interface JobExecutor {
|
||||
data: any,
|
||||
config: any,
|
||||
loginRequiredCallback?: any,
|
||||
accessToken?: string
|
||||
authConfig?: AuthConfig,
|
||||
extraResponseAttributes?: ExtraResponseAttributes[]
|
||||
) => Promise<any>
|
||||
resendWaitingRequests: () => Promise<void>
|
||||
getRequests: () => SASjsRequest[]
|
||||
@@ -28,7 +30,8 @@ export abstract class BaseJobExecutor implements JobExecutor {
|
||||
data: any,
|
||||
config: any,
|
||||
loginRequiredCallback?: any,
|
||||
accessToken?: string | undefined
|
||||
authConfig?: AuthConfig | undefined,
|
||||
extraResponseAttributes?: ExtraResponseAttributes[]
|
||||
): Promise<any>
|
||||
|
||||
resendWaitingRequests = async () => {
|
||||
@@ -59,14 +62,14 @@ export abstract class BaseJobExecutor implements JobExecutor {
|
||||
let sasWork = null
|
||||
|
||||
if (debug) {
|
||||
if (response?.result && response?.log) {
|
||||
if (response?.log) {
|
||||
sourceCode = parseSourceCode(response.log)
|
||||
generatedCode = parseGeneratedCode(response.log)
|
||||
|
||||
if (response.log) {
|
||||
sasWork = response.log
|
||||
} else {
|
||||
if (response?.result) {
|
||||
sasWork = response.result.WORK
|
||||
} else {
|
||||
sasWork = response.log
|
||||
}
|
||||
} else if (response?.result) {
|
||||
sourceCode = parseSourceCode(response.result)
|
||||
|
||||
@@ -8,8 +8,9 @@ import { generateFileUploadForm } from '../file/generateFileUploadForm'
|
||||
import { generateTableUploadForm } from '../file/generateTableUploadForm'
|
||||
import { RequestClient } from '../request/RequestClient'
|
||||
import { SASViyaApiClient } from '../SASViyaApiClient'
|
||||
import { isRelativePath } from '../utils'
|
||||
import { isRelativePath, isValidJson } from '../utils'
|
||||
import { BaseJobExecutor } from './JobExecutor'
|
||||
import { parseWeboutResponse } from '../utils/parseWeboutResponse'
|
||||
|
||||
export interface WaitingRequstPromise {
|
||||
promise: Promise<any> | null
|
||||
@@ -39,15 +40,18 @@ export class WebJobExecutor extends BaseJobExecutor {
|
||||
? config.appLoc.replace(/\/?$/, '/') + sasJob.replace(/^\//, '')
|
||||
: sasJob
|
||||
: sasJob
|
||||
const jobUri =
|
||||
config.serverType === ServerType.SasViya
|
||||
? await this.getJobUri(sasJob)
|
||||
: ''
|
||||
const apiUrl = `${config.serverUrl}${this.jobsPath}/?${
|
||||
jobUri.length > 0
|
||||
? '__program=' + program + '&_job=' + jobUri
|
||||
: '_program=' + program
|
||||
}`
|
||||
let apiUrl = `${config.serverUrl}${this.jobsPath}/?${'_program=' + program}`
|
||||
|
||||
if (config.serverType === ServerType.SasViya) {
|
||||
const jobUri =
|
||||
config.serverType === ServerType.SasViya
|
||||
? await this.getJobUri(sasJob)
|
||||
: ''
|
||||
|
||||
apiUrl += jobUri.length > 0 ? '&_job=' + jobUri : ''
|
||||
|
||||
apiUrl += config.contextName ? `&_contextname=${config.contextName}` : ''
|
||||
}
|
||||
|
||||
let requestParams = {
|
||||
...this.getRequestParams(config)
|
||||
@@ -97,6 +101,19 @@ export class WebJobExecutor extends BaseJobExecutor {
|
||||
this.appendRequest(res, sasJob, config.debug)
|
||||
resolve(jsonResponse)
|
||||
}
|
||||
if (this.serverType === ServerType.Sas9 && config.debug) {
|
||||
const jsonResponse = parseWeboutResponse(res.result as string)
|
||||
if (jsonResponse === '') {
|
||||
throw new Error(
|
||||
'Valid JSON could not be extracted from response.'
|
||||
)
|
||||
}
|
||||
|
||||
isValidJson(jsonResponse)
|
||||
this.appendRequest(res, sasJob, config.debug)
|
||||
resolve(res.result)
|
||||
}
|
||||
isValidJson(res.result as string)
|
||||
this.appendRequest(res, sasJob, config.debug)
|
||||
resolve(res.result)
|
||||
})
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
import { parseWeboutResponse } from '../utils/parseWeboutResponse'
|
||||
import { prefixMessage } from '@sasjs/utils/error'
|
||||
import { SAS9AuthError } from '../types/errors/SAS9AuthError'
|
||||
import { isValidJson } from '../utils'
|
||||
|
||||
export interface HttpClient {
|
||||
get<T>(
|
||||
@@ -63,6 +64,9 @@ export class RequestClient implements HttpClient {
|
||||
baseURL: baseUrl
|
||||
})
|
||||
}
|
||||
|
||||
this.httpClient.defaults.validateStatus = (status) =>
|
||||
status >= 200 && status < 305
|
||||
}
|
||||
|
||||
public getCsrfToken(type: 'general' | 'file' = 'general') {
|
||||
@@ -80,7 +84,7 @@ export class RequestClient implements HttpClient {
|
||||
contentType: string = 'application/json',
|
||||
overrideHeaders: { [key: string]: string | number } = {},
|
||||
debug: boolean = false
|
||||
): Promise<{ result: T; etag: string }> {
|
||||
): Promise<{ result: T; etag: string; status: number }> {
|
||||
const headers = {
|
||||
...this.getHeaders(accessToken, contentType),
|
||||
...overrideHeaders
|
||||
@@ -287,7 +291,8 @@ export class RequestClient implements HttpClient {
|
||||
})
|
||||
.then((res) => res.data)
|
||||
.catch((error) => {
|
||||
console.log(error)
|
||||
const logger = process.logger || console
|
||||
logger.error(error)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -419,7 +424,13 @@ export class RequestClient implements HttpClient {
|
||||
}
|
||||
} catch {
|
||||
try {
|
||||
parsedResponse = JSON.parse(parseWeboutResponse(response.data))
|
||||
const weboutResponse = parseWeboutResponse(response.data)
|
||||
if (weboutResponse === '') {
|
||||
throw new Error('Valid JSON could not be extracted from response.')
|
||||
}
|
||||
|
||||
const jsonResponse = isValidJson(weboutResponse)
|
||||
parsedResponse = jsonResponse
|
||||
} catch {
|
||||
parsedResponse = response.data
|
||||
}
|
||||
@@ -427,9 +438,15 @@ export class RequestClient implements HttpClient {
|
||||
includeSAS9Log = true
|
||||
}
|
||||
|
||||
let responseToReturn: { result: T; etag: any; log?: string } = {
|
||||
let responseToReturn: {
|
||||
result: T
|
||||
etag: any
|
||||
log?: string
|
||||
status: number
|
||||
} = {
|
||||
result: parsedResponse as T,
|
||||
etag
|
||||
etag,
|
||||
status: response.status
|
||||
}
|
||||
|
||||
if (includeSAS9Log) {
|
||||
|
||||
@@ -39,7 +39,7 @@ export class Sas9RequestClient extends RequestClient {
|
||||
contentType: string = 'application/json',
|
||||
overrideHeaders: { [key: string]: string | number } = {},
|
||||
debug: boolean = false
|
||||
): Promise<{ result: T; etag: string }> {
|
||||
): Promise<{ result: T; etag: string; status: number }> {
|
||||
const headers = {
|
||||
...this.getHeaders(accessToken, contentType),
|
||||
...overrideHeaders
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
/**
|
||||
* @jest-environment jsdom
|
||||
*/
|
||||
|
||||
import { FileUploader } from '../FileUploader'
|
||||
import { UploadFile } from '../types'
|
||||
import { SASjsConfig, UploadFile } from '../types'
|
||||
import { RequestClient } from '../request/RequestClient'
|
||||
import axios from 'axios'
|
||||
jest.mock('axios')
|
||||
@@ -28,48 +32,51 @@ const prepareFilesAndParams = () => {
|
||||
}
|
||||
|
||||
describe('FileUploader', () => {
|
||||
const config: SASjsConfig = {
|
||||
...new SASjsConfig(),
|
||||
appLoc: '/sample/apploc'
|
||||
}
|
||||
|
||||
const fileUploader = new FileUploader(
|
||||
'/sample/apploc',
|
||||
'https://sample.server.com',
|
||||
config,
|
||||
'/jobs/path',
|
||||
new RequestClient('https://sample.server.com')
|
||||
)
|
||||
|
||||
it('should upload successfully', async (done) => {
|
||||
it('should upload successfully', async () => {
|
||||
const sasJob = 'test/upload'
|
||||
const { files, params } = prepareFilesAndParams()
|
||||
mockedAxios.post.mockImplementation(() =>
|
||||
Promise.resolve({ data: sampleResponse })
|
||||
)
|
||||
|
||||
fileUploader.uploadFile(sasJob, files, params).then((res: any) => {
|
||||
expect(res).toEqual(JSON.parse(sampleResponse))
|
||||
done()
|
||||
})
|
||||
const res = await fileUploader.uploadFile(sasJob, files, params)
|
||||
|
||||
expect(res).toEqual(JSON.parse(sampleResponse))
|
||||
})
|
||||
|
||||
it('should an error when no files are provided', async (done) => {
|
||||
it('should an error when no files are provided', async () => {
|
||||
const sasJob = 'test/upload'
|
||||
const files: UploadFile[] = []
|
||||
const params = { table: 'libtable' }
|
||||
|
||||
fileUploader.uploadFile(sasJob, files, params).catch((err: any) => {
|
||||
expect(err.error.message).toEqual('At least one file must be provided.')
|
||||
done()
|
||||
})
|
||||
const err = await fileUploader
|
||||
.uploadFile(sasJob, files, params)
|
||||
.catch((err: any) => err)
|
||||
expect(err.error.message).toEqual('At least one file must be provided.')
|
||||
})
|
||||
|
||||
it('should throw an error when no sasJob is provided', async (done) => {
|
||||
it('should throw an error when no sasJob is provided', async () => {
|
||||
const sasJob = ''
|
||||
const { files, params } = prepareFilesAndParams()
|
||||
|
||||
fileUploader.uploadFile(sasJob, files, params).catch((err: any) => {
|
||||
expect(err.error.message).toEqual('sasJob must be provided.')
|
||||
done()
|
||||
})
|
||||
const err = await fileUploader
|
||||
.uploadFile(sasJob, files, params)
|
||||
.catch((err: any) => err)
|
||||
expect(err.error.message).toEqual('sasJob must be provided.')
|
||||
})
|
||||
|
||||
it('should throw an error when login is required', async (done) => {
|
||||
it('should throw an error when login is required', async () => {
|
||||
mockedAxios.post.mockImplementation(() =>
|
||||
Promise.resolve({ data: '<form action="Logon">' })
|
||||
)
|
||||
@@ -77,15 +84,13 @@ describe('FileUploader', () => {
|
||||
const sasJob = 'test'
|
||||
const { files, params } = prepareFilesAndParams()
|
||||
|
||||
fileUploader.uploadFile(sasJob, files, params).catch((err: any) => {
|
||||
expect(err.error.message).toEqual(
|
||||
'You must be logged in to upload a file.'
|
||||
)
|
||||
done()
|
||||
})
|
||||
const err = await fileUploader
|
||||
.uploadFile(sasJob, files, params)
|
||||
.catch((err: any) => err)
|
||||
expect(err.error.message).toEqual('You must be logged in to upload a file.')
|
||||
})
|
||||
|
||||
it('should throw an error when invalid JSON is returned by the server', async (done) => {
|
||||
it('should throw an error when invalid JSON is returned by the server', async () => {
|
||||
mockedAxios.post.mockImplementation(() =>
|
||||
Promise.resolve({ data: '{invalid: "json"' })
|
||||
)
|
||||
@@ -93,13 +98,13 @@ describe('FileUploader', () => {
|
||||
const sasJob = 'test'
|
||||
const { files, params } = prepareFilesAndParams()
|
||||
|
||||
fileUploader.uploadFile(sasJob, files, params).catch((err: any) => {
|
||||
expect(err.error.message).toEqual('File upload request failed.')
|
||||
done()
|
||||
})
|
||||
const err = await fileUploader
|
||||
.uploadFile(sasJob, files, params)
|
||||
.catch((err: any) => err)
|
||||
expect(err.error.message).toEqual('File upload request failed.')
|
||||
})
|
||||
|
||||
it('should throw an error when the server request fails', async (done) => {
|
||||
it('should throw an error when the server request fails', async () => {
|
||||
mockedAxios.post.mockImplementation(() =>
|
||||
Promise.reject({ data: '{message: "Server error"}' })
|
||||
)
|
||||
@@ -107,10 +112,9 @@ describe('FileUploader', () => {
|
||||
const sasJob = 'test'
|
||||
const { files, params } = prepareFilesAndParams()
|
||||
|
||||
fileUploader.uploadFile(sasJob, files, params).catch((err: any) => {
|
||||
expect(err.error.message).toEqual('File upload request failed.')
|
||||
|
||||
done()
|
||||
})
|
||||
const err = await fileUploader
|
||||
.uploadFile(sasJob, files, params)
|
||||
.catch((err: any) => err)
|
||||
expect(err.error.message).toEqual('File upload request failed.')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -14,7 +14,7 @@ describe('FolderOperations', () => {
|
||||
|
||||
beforeEach(() => {})
|
||||
|
||||
it('should move and rename folder', async (done) => {
|
||||
it('should move and rename folder', async () => {
|
||||
mockFetchResponse(false)
|
||||
|
||||
let res: any = await sasViyaApiClient.moveFolder(
|
||||
@@ -26,11 +26,9 @@ describe('FolderOperations', () => {
|
||||
|
||||
expect(res.folder.name).toEqual('newName')
|
||||
expect(res.folder.parentFolderUri.split('=')[1]).toEqual('/Test/toFolder')
|
||||
|
||||
done()
|
||||
})
|
||||
|
||||
it('should move and keep the name of folder', async (done) => {
|
||||
it('should move and keep the name of folder', async () => {
|
||||
mockFetchResponse(true)
|
||||
|
||||
let res: any = await sasViyaApiClient.moveFolder(
|
||||
@@ -42,11 +40,9 @@ describe('FolderOperations', () => {
|
||||
|
||||
expect(res.folder.name).toEqual('oldName')
|
||||
expect(res.folder.parentFolderUri.split('=')[1]).toEqual('/Test/toFolder')
|
||||
|
||||
done()
|
||||
})
|
||||
|
||||
it('should only rename folder', async (done) => {
|
||||
it('should only rename folder', async () => {
|
||||
mockFetchResponse(false)
|
||||
|
||||
let res: any = await sasViyaApiClient.moveFolder(
|
||||
@@ -58,8 +54,6 @@ describe('FolderOperations', () => {
|
||||
|
||||
expect(res.folder.name).toEqual('newName')
|
||||
expect(res.folder.parentFolderUri.split('=')[1]).toEqual('/Test/toFolder')
|
||||
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { SessionManager } from '../SessionManager'
|
||||
import * as dotenv from 'dotenv'
|
||||
import { RequestClient } from '../request/RequestClient'
|
||||
import { NoSessionStateError } from '../types/errors'
|
||||
import * as dotenv from 'dotenv'
|
||||
import axios from 'axios'
|
||||
|
||||
jest.mock('axios')
|
||||
const mockedAxios = axios as jest.Mocked<typeof axios>
|
||||
|
||||
@@ -43,4 +45,38 @@ describe('SessionManager', () => {
|
||||
).resolves.toEqual(expectedResponse)
|
||||
})
|
||||
})
|
||||
|
||||
describe('waitForSession', () => {
|
||||
it('should reject with NoSessionStateError if SAS server did not provide session state', async () => {
|
||||
const responseStatus = 304
|
||||
|
||||
mockedAxios.get.mockImplementation(() =>
|
||||
Promise.resolve({ data: '', status: responseStatus })
|
||||
)
|
||||
|
||||
await expect(
|
||||
sessionManager['waitForSession'](
|
||||
{
|
||||
id: 'id',
|
||||
state: '',
|
||||
links: [
|
||||
{ rel: 'state', href: '', uri: '', type: '', method: 'GET' }
|
||||
],
|
||||
attributes: {
|
||||
sessionInactiveTimeout: 0
|
||||
},
|
||||
creationTimeStamp: ''
|
||||
},
|
||||
null,
|
||||
'access_token'
|
||||
)
|
||||
).rejects.toEqual(
|
||||
new NoSessionStateError(
|
||||
responseStatus,
|
||||
process.env.SERVER_URL as string,
|
||||
'logUrl'
|
||||
)
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
31
src/test/utils/isValidJson.spec.ts
Normal file
31
src/test/utils/isValidJson.spec.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { isValidJson } from '../../utils'
|
||||
|
||||
describe('jsonValidator', () => {
|
||||
it('should not throw an error with an valid json', () => {
|
||||
const json = {
|
||||
test: 'test'
|
||||
}
|
||||
|
||||
expect(isValidJson(json)).toBe(json)
|
||||
})
|
||||
|
||||
it('should not throw an error with an valid json string', () => {
|
||||
const json = {
|
||||
test: 'test'
|
||||
}
|
||||
|
||||
expect(isValidJson(JSON.stringify(json))).toStrictEqual(json)
|
||||
})
|
||||
|
||||
it('should throw an error with an invalid json', () => {
|
||||
const json = `{\"test\":\"test\"\"test2\":\"test\"}`
|
||||
|
||||
expect(() => {
|
||||
try {
|
||||
isValidJson(json)
|
||||
} catch (err) {
|
||||
throw new Error()
|
||||
}
|
||||
}).toThrowError
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
import { parseGeneratedCode } from '../../utils/index'
|
||||
|
||||
it('should parse generated code', async (done) => {
|
||||
it('should parse generated code', () => {
|
||||
expect(sampleResponse).toBeTruthy()
|
||||
|
||||
const parsedGeneratedCode = parseGeneratedCode(sampleResponse)
|
||||
@@ -15,8 +15,6 @@ it('should parse generated code', async (done) => {
|
||||
expect(generatedCodeLines[2].startsWith('MPRINT(MM_WEBOUT)')).toBeTruthy()
|
||||
expect(generatedCodeLines[3].startsWith('MPRINT(MM_WEBRIGHT)')).toBeTruthy()
|
||||
expect(generatedCodeLines[4].startsWith('MPRINT(MM_WEBOUT)')).toBeTruthy()
|
||||
|
||||
done()
|
||||
})
|
||||
|
||||
/* tslint:disable */
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { parseSourceCode } from '../../utils/index'
|
||||
|
||||
it('should parse SAS9 source code', async (done) => {
|
||||
it('should parse SAS9 source code', async () => {
|
||||
expect(sampleResponse).toBeTruthy()
|
||||
|
||||
const parsedSourceCode = parseSourceCode(sampleResponse)
|
||||
@@ -15,8 +15,6 @@ it('should parse SAS9 source code', async (done) => {
|
||||
expect(sourceCodeLines[2].startsWith('8')).toBeTruthy()
|
||||
expect(sourceCodeLines[3].startsWith('9')).toBeTruthy()
|
||||
expect(sourceCodeLines[4].startsWith('10')).toBeTruthy()
|
||||
|
||||
done()
|
||||
})
|
||||
|
||||
/* tslint:disable */
|
||||
|
||||
8
src/types/File.ts
Normal file
8
src/types/File.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { Link } from './Link'
|
||||
|
||||
export interface File {
|
||||
id: string
|
||||
name: string
|
||||
parentUri: string
|
||||
links: Link[]
|
||||
}
|
||||
5
src/types/Process.d.ts
vendored
Normal file
5
src/types/Process.d.ts
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
declare namespace NodeJS {
|
||||
export interface Process {
|
||||
logger?: import('@sasjs/utils/logger').Logger
|
||||
}
|
||||
}
|
||||
@@ -40,23 +40,19 @@ export class SASjsConfig {
|
||||
*/
|
||||
debug: boolean = true
|
||||
/**
|
||||
* The name of the compute context to use when calling the Viya APIs directly.
|
||||
* The name of the compute context to use when calling the Viya services directly.
|
||||
* Example value: 'SAS Job Execution compute context'
|
||||
* If set to missing or empty, and useComputeApi is true, the adapter will use
|
||||
* the JES APIs. If provided, the Job Code will be executed in pooled
|
||||
* compute sessions on this named context.
|
||||
*/
|
||||
contextName: string = ''
|
||||
/**
|
||||
* Set to `false` to use the Job Execution Web Service. To enhance VIYA
|
||||
* If it's `false` adapter will use the JES API as connection approach. To enhance VIYA
|
||||
* performance, set to `true` and provide a `contextName` on which to run
|
||||
* the code. When running on a named context, the code executes under the
|
||||
* user identity. When running as a Job Execution service, the code runs
|
||||
* under the identity in the JES context. If no `contextName` is provided,
|
||||
* and `useComputeApi` is `true`, then the service will run as a Job, except
|
||||
* under the identity in the JES context. If `useComputeApi` is `null` or `undefined`, the service will run as a Job, except
|
||||
* triggered using the APIs instead of the Job Execution Web Service broker.
|
||||
*/
|
||||
useComputeApi = false
|
||||
useComputeApi: boolean | null = null
|
||||
/**
|
||||
* Defaults to `false`.
|
||||
* When set to `true`, the adapter will allow requests to SAS servers that use a self-signed SSL certificate.
|
||||
|
||||
15
src/types/errors/NoSessionStateError.ts
Normal file
15
src/types/errors/NoSessionStateError.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
export class NoSessionStateError extends Error {
|
||||
constructor(
|
||||
public serverResponseStatus: number,
|
||||
public sessionStateUrl: string,
|
||||
public logUrl: string
|
||||
) {
|
||||
super(
|
||||
`Could not get session state. Server responded with ${serverResponseStatus} whilst checking state: ${sessionStateUrl}`
|
||||
)
|
||||
|
||||
this.name = 'NoSessionStatus'
|
||||
|
||||
Object.setPrototypeOf(this, NoSessionStateError.prototype)
|
||||
}
|
||||
}
|
||||
@@ -5,3 +5,4 @@ export * from './JobExecutionError'
|
||||
export * from './LoginRequiredError'
|
||||
export * from './NotFoundError'
|
||||
export * from './ErrorResponse'
|
||||
export * from './NoSessionStateError'
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
export * from './Context'
|
||||
export * from './CsrfToken'
|
||||
export * from './Folder'
|
||||
export * from './File'
|
||||
export * from './Job'
|
||||
export * from './JobDefinition'
|
||||
export * from './JobResult'
|
||||
|
||||
@@ -15,12 +15,14 @@ export const fetchLogByChunks = async (
|
||||
logUrl: string,
|
||||
logCount: number
|
||||
): Promise<string> => {
|
||||
const logger = process.logger || console
|
||||
|
||||
let log: string = ''
|
||||
|
||||
const loglimit = logCount < 10000 ? logCount : 10000
|
||||
let start = 0
|
||||
do {
|
||||
console.log(
|
||||
logger.info(
|
||||
`Fetching logs from line no: ${start + 1} to ${
|
||||
start + loglimit
|
||||
} of ${logCount}.`
|
||||
|
||||
@@ -12,3 +12,4 @@ export * from './serialize'
|
||||
export * from './splitChunks'
|
||||
export * from './parseWeboutResponse'
|
||||
export * from './fetchLogByChunks'
|
||||
export * from './isValidJson'
|
||||
|
||||
13
src/utils/isValidJson.ts
Normal file
13
src/utils/isValidJson.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Checks if string is in valid JSON format else throw error.
|
||||
* @param str - string to check.
|
||||
*/
|
||||
export const isValidJson = (str: string | object) => {
|
||||
try {
|
||||
if (typeof str === 'object') return str
|
||||
|
||||
return JSON.parse(str)
|
||||
} catch (e) {
|
||||
throw new Error('Invalid JSON response.')
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,32 @@
|
||||
const path = require('path')
|
||||
const webpack = require('webpack')
|
||||
const terserPlugin = require('terser-webpack-plugin')
|
||||
const nodePolyfillPlugin = require('node-polyfill-webpack-plugin')
|
||||
|
||||
const defaultPlugins = [
|
||||
new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en/),
|
||||
new webpack.SourceMapDevToolPlugin({
|
||||
filename: null,
|
||||
exclude: [/node_modules/],
|
||||
test: /\.ts($|\?)/i
|
||||
})
|
||||
]
|
||||
|
||||
const optimization = {
|
||||
minimize: true,
|
||||
minimizer: [
|
||||
new terserPlugin({
|
||||
parallel: true,
|
||||
terserOptions: {}
|
||||
})
|
||||
]
|
||||
}
|
||||
|
||||
const browserConfig = {
|
||||
entry: './src/index.ts',
|
||||
devtool: 'inline-source-map',
|
||||
mode: 'production',
|
||||
optimization: {
|
||||
minimizer: [
|
||||
new terserPlugin({
|
||||
cache: true,
|
||||
parallel: true,
|
||||
sourceMap: true,
|
||||
terserOptions: {}
|
||||
})
|
||||
]
|
||||
},
|
||||
optimization: optimization,
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
@@ -27,7 +38,7 @@ const browserConfig = {
|
||||
},
|
||||
resolve: {
|
||||
extensions: ['.ts', '.js'],
|
||||
fallback: { https: false }
|
||||
fallback: { https: false, fs: false, readline: false }
|
||||
},
|
||||
output: {
|
||||
filename: 'index.js',
|
||||
@@ -36,17 +47,27 @@ const browserConfig = {
|
||||
library: 'SASjs'
|
||||
},
|
||||
plugins: [
|
||||
new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en/),
|
||||
new webpack.SourceMapDevToolPlugin({
|
||||
filename: null,
|
||||
exclude: [/node_modules/],
|
||||
test: /\.ts($|\?)/i
|
||||
})
|
||||
...defaultPlugins,
|
||||
new webpack.ProvidePlugin({
|
||||
process: 'process/browser'
|
||||
}),
|
||||
new nodePolyfillPlugin()
|
||||
]
|
||||
}
|
||||
|
||||
const browserConfigWithoutProcessPlugin = {
|
||||
entry: browserConfig.entry,
|
||||
devtool: browserConfig.devtool,
|
||||
mode: browserConfig.mode,
|
||||
optimization: optimization,
|
||||
module: browserConfig.module,
|
||||
resolve: browserConfig.resolve,
|
||||
output: browserConfig.output,
|
||||
plugins: defaultPlugins
|
||||
}
|
||||
|
||||
const nodeConfig = {
|
||||
...browserConfig,
|
||||
...browserConfigWithoutProcessPlugin,
|
||||
target: 'node',
|
||||
entry: './node/index.ts',
|
||||
output: {
|
||||
|
||||
Reference in New Issue
Block a user