@sasjs/api 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +3 -2
  2. package/build/browser.js +668 -87
  3. package/build/cjs/corpus/runner.js +19 -2
  4. package/build/cjs/corpus/runtime.js +238 -0
  5. package/build/cjs/corpus/session.js +1 -1
  6. package/build/cjs/host/dispatch.js +115 -1
  7. package/build/cjs/index.js +9 -1
  8. package/build/cjs/routes/generated.js +40 -0
  9. package/build/cjs/routes/overlay.js +18 -6
  10. package/build/cjs/runtime/memory-runner.js +59 -0
  11. package/build/cjs/runtime/service.js +303 -0
  12. package/build/cjs/session/memory-host.js +22 -5
  13. package/build/esm/corpus/drive.d.ts +13 -0
  14. package/build/esm/corpus/drive.d.ts.map +1 -1
  15. package/build/esm/corpus/runner.d.ts.map +1 -1
  16. package/build/esm/corpus/runner.js +19 -2
  17. package/build/esm/corpus/runtime.d.ts +17 -0
  18. package/build/esm/corpus/runtime.d.ts.map +1 -0
  19. package/build/esm/corpus/runtime.js +235 -0
  20. package/build/esm/corpus/session.js +1 -1
  21. package/build/esm/host/dispatch.d.ts +15 -0
  22. package/build/esm/host/dispatch.d.ts.map +1 -1
  23. package/build/esm/host/dispatch.js +115 -1
  24. package/build/esm/index.d.ts +5 -0
  25. package/build/esm/index.d.ts.map +1 -1
  26. package/build/esm/index.js +3 -0
  27. package/build/esm/routes/generated.d.ts.map +1 -1
  28. package/build/esm/routes/generated.js +40 -0
  29. package/build/esm/routes/overlay.d.ts.map +1 -1
  30. package/build/esm/routes/overlay.js +18 -6
  31. package/build/esm/runtime/memory-runner.d.ts +38 -0
  32. package/build/esm/runtime/memory-runner.d.ts.map +1 -0
  33. package/build/esm/runtime/memory-runner.js +55 -0
  34. package/build/esm/runtime/service.d.ts +185 -0
  35. package/build/esm/runtime/service.d.ts.map +1 -0
  36. package/build/esm/runtime/service.js +298 -0
  37. package/build/esm/session/memory-host.d.ts +13 -2
  38. package/build/esm/session/memory-host.d.ts.map +1 -1
  39. package/build/esm/session/memory-host.js +22 -5
  40. package/build/esm/session/service.d.ts +12 -1
  41. package/build/esm/session/service.d.ts.map +1 -1
  42. package/package.json +1 -1
@@ -0,0 +1,55 @@
1
+ /**
2
+ * A runner that needs no process, and the sessions it creates.
3
+ *
4
+ * The corpus and a browser build have the same problem: nothing to hand a
5
+ * program to. A memory runner answers it the way a mock should - it holds the
6
+ * record, the state, the log and the output of a session, and it finishes
7
+ * synchronously - which is why "the same API" can be checked without a SAS
8
+ * binary on the box. The one thing it cannot supply is a `pid`, and every
9
+ * response that would carry one carries it as optional.
10
+ *
11
+ * It is also a `SessionHost`, because a session a trigger created has to be one
12
+ * the session routes can read: two maps behind two ports would let a trigger
13
+ * write a record nothing can poll, which is the class of mistake the package
14
+ * exists to end.
15
+ */
16
+ import { MemorySessionHost } from '../session/memory-host.js';
17
+ export class MemorySessionRunner extends MemorySessionHost {
18
+ constructor(options = {}) {
19
+ super();
20
+ this.options = options;
21
+ }
22
+ async run(request) {
23
+ if (this.options.fail)
24
+ throw new Error('the mock run failed');
25
+ const key = 'code' in request.program ? request.program.code : request.program.path;
26
+ const output = this.options.outputs?.[key] || { contents: '' };
27
+ const pid = this.options.pid;
28
+ // a session is recorded before the work is reported done, because the id in
29
+ // the trigger's response is what a client polls with
30
+ if (request.session) {
31
+ const { sessionId, owner, expiresAfterMins } = request.session;
32
+ const started = new Date().toISOString();
33
+ const summary = {
34
+ sessionId,
35
+ // the work is finished by the time this returns: a memory runner has
36
+ // nothing to wait for, and the session routes report what it did
37
+ state: 'completed',
38
+ creationTimeStamp: started,
39
+ deathTimeStamp: started
40
+ };
41
+ if (pid !== undefined)
42
+ summary.pid = pid;
43
+ if (expiresAfterMins !== undefined)
44
+ // the record answers `{mins, used}`, not the number the caller sent: an
45
+ // interactive client reads this straight off the summary route
46
+ summary.expiresAfterMins = { mins: expiresAfterMins, used: false };
47
+ this.sessions[sessionId] = { owner, summary };
48
+ this.states[sessionId] =
49
+ pid === undefined ? { state: 'completed' } : { state: 'completed', pid };
50
+ this.logs[sessionId] = '';
51
+ this.outputs[sessionId] = output;
52
+ }
53
+ return pid === undefined ? { output } : { output, pid };
54
+ }
55
+ }
@@ -0,0 +1,185 @@
1
+ import type { Subject } from '../identity/types.js';
2
+ import type { CallerDirectory, SessionArtifact } from '../session/service.js';
3
+ /**
4
+ * The value that asks for the session log.
5
+ *
6
+ * `_debug` follows the SAS Application Broker's convention, where the value is a
7
+ * set of bit flags - 128 returns the log, 2 prints timing, 1 echoes the fields -
8
+ * so 131 is LOG + TIME + FIELDS, which is what @sasjs/core's `ms_runstp`
9
+ * defaults to and what the generated services test with `%if &_debug ge 131`.
10
+ *
11
+ * The two code routes force it on, because their documented response body is
12
+ * assembled from the webout, the log and the listing: a client that runs code
13
+ * and receives only the webout would be told nothing about a program that failed
14
+ * with an empty `_webout`. The stored-program routes leave it to the caller, so
15
+ * `GET /stp/execute` without `_debug` answers the program's output and nothing
16
+ * else.
17
+ */
18
+ export declare const CODE_DEBUG = 131;
19
+ /** The run times the published document states, and a host may hold fewer. */
20
+ export declare const DOCUMENTED_RUN_TIMES: string[];
21
+ /**
22
+ * `_debug`, normalised the way sasjs/server's `parseDebugValue` normalises it.
23
+ *
24
+ * The parameter's one effect is whether the log comes back, and the macros test
25
+ * it numerically (`%if &_debug ge 131`), so a keyword cannot be handed to a
26
+ * program as text: `_debug=log` would arrive as the string `log`, the comparison
27
+ * would fail, and the caller would receive a body without the log section the
28
+ * same request gets from a server. Integer text is a level; any other non-empty
29
+ * value means "the log, please"; absent or empty means it was not asked for.
30
+ *
31
+ * `1e3` and `0x10` are text, not levels - `Number()` would read them as 1000 and
32
+ * 16, neither of which the macros' comparison treats as the log.
33
+ */
34
+ export declare const parseDebugValue: (value: unknown) => number | undefined;
35
+ /**
36
+ * A session a trigger created.
37
+ *
38
+ * The package mints the id, because the document defines it as the name of the
39
+ * temporary folder and a client polls the session routes by it; the host records
40
+ * the session under that id before it runs anything, which is what makes the
41
+ * session routes answer afterwards.
42
+ *
43
+ * `owner` is the caller's **uid**, for the same reason the session routes
44
+ * compare uids first: a username is mutable client data - an account can be
45
+ * renamed, two accounts can exchange names - and a name-keyed record hands a
46
+ * session to whoever holds the name later.
47
+ */
48
+ export interface RunnerSession {
49
+ sessionId: string;
50
+ owner: string;
51
+ /** The run time the caller named, when they named one. */
52
+ runTime?: string;
53
+ /** Minutes after completion at which the session must be destroyed. */
54
+ expiresAfterMins?: number;
55
+ }
56
+ /**
57
+ * The program to run: its source, or the drive path that names it.
58
+ *
59
+ * A union rather than two optional fields, so a host cannot be handed a request
60
+ * with neither and quietly run nothing.
61
+ *
62
+ * A path arrives normalised and contained, and the package has already taken the
63
+ * run time from its extension when it carries a recognised one. What it cannot
64
+ * do is *find* the file: a path with no extension is the form every document
65
+ * example uses, and the server answers it by probing `<path>.<runTime>` for each
66
+ * run time it holds - a filesystem question, so the runner resolves the file and
67
+ * the run time that goes with it, exactly as `getRunTimeAndFilePath` does
68
+ * upstream. That is the one thing a runner must do beyond opening what it is
69
+ * given.
70
+ */
71
+ export type ProgramSource = {
72
+ code: string;
73
+ } | {
74
+ path: string;
75
+ };
76
+ /** One request to run something. */
77
+ export interface RunRequest {
78
+ program: ProgramSource;
79
+ /**
80
+ * The variables the program sees: the request's query and body as the caller
81
+ * sent them, with `_debug` normalised the way the server's own handlers
82
+ * normalise it - a number stays one, integer text becomes a number, and any
83
+ * other non-empty value means "return the log" (131). Everything else is the
84
+ * caller's, untouched: a session variable is whatever a client named it.
85
+ */
86
+ vars: Record<string, unknown>;
87
+ /**
88
+ * The run time to use: the one the caller named, or the one a stored
89
+ * program's extension names (`/app/run.js` is JavaScript). Absent when nothing
90
+ * names one, and then the run time is the host's own choice.
91
+ */
92
+ runTime?: string;
93
+ /**
94
+ * The session this run belongs to. Present for a trigger, absent for an
95
+ * execute: an execute waits for the program and answers its output, and the
96
+ * caller never sees a session.
97
+ */
98
+ session?: RunnerSession;
99
+ /** Multipart files the request carried, by field name. */
100
+ files?: Record<string, string | Uint8Array>;
101
+ }
102
+ /** What a run produced, as far as the host can tell. */
103
+ export interface RunOutcome {
104
+ /**
105
+ * The program's output: `_webout`, with the session log when the run was
106
+ * asked to return it. Absent when the program wrote nothing.
107
+ */
108
+ output?: SessionArtifact;
109
+ /** The OS process, where the host runs one and knows its id. */
110
+ pid?: number;
111
+ }
112
+ /**
113
+ * A host's run time, as the package sees it.
114
+ *
115
+ * One method, because performing work is the only thing the package cannot
116
+ * compute. Everything a client observes around it - the id, the record, who may
117
+ * read it, the refusals - is decided here.
118
+ */
119
+ export interface SessionRunner {
120
+ run(request: RunRequest): Promise<RunOutcome>;
121
+ }
122
+ /** What a trigger answers: the session to poll, and the process when there is one. */
123
+ export interface TriggerResponse {
124
+ sessionId: string;
125
+ pid?: number;
126
+ }
127
+ /**
128
+ * One run, in the shape a caller of the service states it.
129
+ *
130
+ * `program` and `code` are the two sources the document names - a drive path on
131
+ * the stored-program routes, a buffer on the code routes - and `source` says
132
+ * which one the route promised. It is not derivable from the payload: a request
133
+ * with neither field still has to name the right parameter in its refusal, and
134
+ * the stored-program and code schemas disagree about what is required
135
+ * (`runTime` is required on the code routes, and resolved from the file's
136
+ * extension on the stored-program ones).
137
+ */
138
+ export interface RuntimeRequest {
139
+ /** Which source the route promised. */
140
+ source: 'program' | 'code';
141
+ /** The drive path of a stored program. */
142
+ program?: string;
143
+ /** The code to run, instead of a stored program. */
144
+ code?: string;
145
+ /** The run time the caller named. */
146
+ runTime?: string;
147
+ /** The request's own parameters, which the program sees as session variables. */
148
+ vars?: Record<string, unknown>;
149
+ /** Multipart files the request carried, by field name. */
150
+ files?: Record<string, string | Uint8Array>;
151
+ /**
152
+ * Minutes after completion at which the session must be destroyed.
153
+ *
154
+ * A query parameter carries this as text, so both forms are accepted and the
155
+ * schema's coercion is the service's job.
156
+ */
157
+ expiresAfterMins?: number | string;
158
+ }
159
+ export interface RuntimeServiceOptions {
160
+ /**
161
+ * The run times the host holds.
162
+ *
163
+ * A host decides which languages it holds - the browser build runs JavaScript,
164
+ * a server runs JavaScript and SAS - and the document's `RunTimeType` names the
165
+ * five that exist. A name outside this list is the caller's mistake, which is
166
+ * the server's `400` ("`runTime` must be one of [sas, js]") rather than the
167
+ * `501` a capability answers: the route exists, the request cannot be served.
168
+ */
169
+ runTimes?: string[];
170
+ }
171
+ export interface RuntimeService {
172
+ /** Run a program to completion and answer what it produced. */
173
+ execute(caller: Subject | undefined, request: RuntimeRequest): Promise<SessionArtifact>;
174
+ /** Start a program in a new session and answer the session to poll. */
175
+ trigger(caller: Subject | undefined, request: RuntimeRequest): Promise<TriggerResponse>;
176
+ }
177
+ /**
178
+ * The five runtime routes, over a host's runner.
179
+ *
180
+ * The caller passes a `Subject` and nothing else: which account that is, whether
181
+ * it is still active, and what it is allowed to run are resolved here, against
182
+ * the same directory the session routes read. A host never states a role.
183
+ */
184
+ export declare const createRuntimeService: (directory: CallerDirectory, runner: SessionRunner, options?: RuntimeServiceOptions) => RuntimeService;
185
+ //# sourceMappingURL=service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../../src/runtime/service.ts"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EAAsB,OAAO,EAAE,MAAM,sBAAsB,CAAA;AACvE,OAAO,KAAK,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAA;AAG7E;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,UAAU,MAAM,CAAA;AAE7B,8EAA8E;AAC9E,eAAO,MAAM,oBAAoB,UAAsC,CAAA;AAEvE;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,eAAe,GAAI,OAAO,OAAO,KAAG,MAAM,GAAG,SAUzD,CAAA;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,aAAa;IAC5B,SAAS,EAAE,MAAM,CAAA;IACjB,KAAK,EAAE,MAAM,CAAA;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,iFAAiF;IACjF,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC9B,0DAA0D;IAC1D,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,UAAU,CAAC,CAAA;IAC3C;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;CACnC;AAED,MAAM,WAAW,qBAAqB;IACpC;;;;;;;;OAQG;IACH,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAA;CACpB;AAED,MAAM,WAAW,cAAc;IAC7B,+DAA+D;IAC/D,OAAO,CACL,MAAM,EAAE,OAAO,GAAG,SAAS,EAC3B,OAAO,EAAE,cAAc,GACtB,OAAO,CAAC,eAAe,CAAC,CAAA;IAC3B,uEAAuE;IACvE,OAAO,CACL,MAAM,EAAE,OAAO,GAAG,SAAS,EAC3B,OAAO,EAAE,cAAc,GACtB,OAAO,CAAC,eAAe,CAAC,CAAA;CAC5B;AAyDD;;;;;;GAMG;AACH,eAAO,MAAM,oBAAoB,GAC/B,WAAW,eAAe,EAC1B,QAAQ,aAAa,EACrB,UAAS,qBAA0B,KAClC,cA0NF,CAAA"}
@@ -0,0 +1,298 @@
1
+ /**
2
+ * The runtime routes: running a program, and starting one.
3
+ *
4
+ * Five operations run work - `code/execute`, `code/trigger`, both `stp/execute`
5
+ * and `stp/trigger` - and what they have in common is the part this package can
6
+ * decide: who may ask, what a valid request is, the session record a trigger
7
+ * creates, its ownership and its retention, and what a refusal says. What it
8
+ * cannot decide is whether there is a SAS binary, a JavaScript worker or
9
+ * anything at all to hand the program to, so that is one port: `SessionRunner`.
10
+ *
11
+ * A session is a transient run - a temporary folder plus a process, producing a
12
+ * log and an `_webout`, then destroyed. The routes expose the record and the
13
+ * artefacts, never the process, which is why a mock can carry them too: it holds
14
+ * records and bytes as well as a host does, and it can even do the work for a
15
+ * run time it has. The one thing it cannot supply is a `pid`, and every response
16
+ * that would carry one carries it as optional.
17
+ */
18
+ import { ApiError } from '../types.js';
19
+ import { normaliseDrivePath } from '../drive/paths.js';
20
+ /**
21
+ * The value that asks for the session log.
22
+ *
23
+ * `_debug` follows the SAS Application Broker's convention, where the value is a
24
+ * set of bit flags - 128 returns the log, 2 prints timing, 1 echoes the fields -
25
+ * so 131 is LOG + TIME + FIELDS, which is what @sasjs/core's `ms_runstp`
26
+ * defaults to and what the generated services test with `%if &_debug ge 131`.
27
+ *
28
+ * The two code routes force it on, because their documented response body is
29
+ * assembled from the webout, the log and the listing: a client that runs code
30
+ * and receives only the webout would be told nothing about a program that failed
31
+ * with an empty `_webout`. The stored-program routes leave it to the caller, so
32
+ * `GET /stp/execute` without `_debug` answers the program's output and nothing
33
+ * else.
34
+ */
35
+ export const CODE_DEBUG = 131;
36
+ /** The run times the published document states, and a host may hold fewer. */
37
+ export const DOCUMENTED_RUN_TIMES = ['sas', 'js', 'py', 'r', 'sasviya'];
38
+ /**
39
+ * `_debug`, normalised the way sasjs/server's `parseDebugValue` normalises it.
40
+ *
41
+ * The parameter's one effect is whether the log comes back, and the macros test
42
+ * it numerically (`%if &_debug ge 131`), so a keyword cannot be handed to a
43
+ * program as text: `_debug=log` would arrive as the string `log`, the comparison
44
+ * would fail, and the caller would receive a body without the log section the
45
+ * same request gets from a server. Integer text is a level; any other non-empty
46
+ * value means "the log, please"; absent or empty means it was not asked for.
47
+ *
48
+ * `1e3` and `0x10` are text, not levels - `Number()` would read them as 1000 and
49
+ * 16, neither of which the macros' comparison treats as the log.
50
+ */
51
+ export const parseDebugValue = (value) => {
52
+ if (value === undefined || value === null || value === '')
53
+ return undefined;
54
+ if (typeof value === 'number')
55
+ return Number.isFinite(value) ? value : undefined;
56
+ const text = String(value).trim();
57
+ if (!text)
58
+ return undefined;
59
+ return /^[+-]?\d+$/.test(text) ? Number(text) : CODE_DEBUG;
60
+ };
61
+ /** Two digits, for the timestamp a session id starts with. */
62
+ const pad = (value) => String(value).padStart(2, '0');
63
+ /**
64
+ * The timestamp a session id starts with: `YYYYMMDDHHMMSS`.
65
+ *
66
+ * Local time, which is what sasjs/server's `generateTimestamp` writes and what
67
+ * makes the id read as a SAS work folder name. Nothing derives from it - the id
68
+ * is opaque to a client - so a host in another time zone minting another string
69
+ * is not a divergence.
70
+ */
71
+ const timestamp = (now) => [
72
+ now.getFullYear(),
73
+ pad(now.getMonth() + 1),
74
+ pad(now.getDate()),
75
+ pad(now.getHours()),
76
+ pad(now.getMinutes()),
77
+ pad(now.getSeconds())
78
+ ].join('');
79
+ /**
80
+ * A session id in the shape the document shows: `20241028074744-54132-1730101664824`.
81
+ *
82
+ * The trailing milliseconds make two triggers in the same second distinct even
83
+ * when the random part collides, which matters because the id names a folder: a
84
+ * collision would put two runs in one session.
85
+ */
86
+ const newSessionId = (now) => `${timestamp(now)}-${Math.round(Math.random() * 100000)}-${now.getTime()}`;
87
+ /** The refusal a program that cannot be found answers, as the server words it. */
88
+ const notThere = (programPath) => `The Program at (${programPath}) does not exist.`;
89
+ /**
90
+ * The failure a run that could not be performed answers.
91
+ *
92
+ * The message is sasjs/server's, verbatim, because a client keys on it: the
93
+ * response body is `{status: 'failure', message, error}`, where `error` is the
94
+ * runner's own text. A host's bug must not become a `500` here - a `500` says
95
+ * the API happened to break, and this says the program did not run.
96
+ */
97
+ const failedRun = (error) => {
98
+ const message = 'Job execution failed.';
99
+ // `String(error)` keeps the prefix an Error carries (`Error: ...`), which is
100
+ // what the server sends: it stringifies the rejection rather than reading
101
+ // `.message` off it
102
+ throw new ApiError(400, message, {
103
+ status: 'failure',
104
+ message,
105
+ error: String(error)
106
+ });
107
+ };
108
+ /**
109
+ * The five runtime routes, over a host's runner.
110
+ *
111
+ * The caller passes a `Subject` and nothing else: which account that is, whether
112
+ * it is still active, and what it is allowed to run are resolved here, against
113
+ * the same directory the session routes read. A host never states a role.
114
+ */
115
+ export const createRuntimeService = (directory, runner, options = {}) => {
116
+ const runTimes = options.runTimes || DOCUMENTED_RUN_TIMES;
117
+ /** The caller, refused the way the middleware refuses one. */
118
+ const callerOf = async (caller) => {
119
+ if (!caller)
120
+ throw new ApiError(401, 'Unauthorized');
121
+ const reader = await directory.userById(caller.userId);
122
+ // a deactivated account keeps a token the sign-in flow issued before it was
123
+ // deactivated, and the server's middleware refuses it on every route
124
+ if (!reader || !reader.isActive)
125
+ throw new ApiError(401, 'Unauthorized');
126
+ return reader;
127
+ };
128
+ /**
129
+ * The program a request names, refused in the schema's own words.
130
+ *
131
+ * `_program` is caller-controlled and names a file under the host's drive, so
132
+ * it is resolved against the drive root before a runner sees it: a path that
133
+ * climbs out with `..` would otherwise let a caller run any file the service
134
+ * account can read, which is why sasjs/server resolves it with
135
+ * `resolveWithinDrive` before looking for the program. A path that leaves the
136
+ * drive is refused the way a program that is not there is refused - the same
137
+ * `400`, because saying "your path was rejected but existed" would say
138
+ * something about the host's filesystem.
139
+ */
140
+ const programOf = (request) => {
141
+ // a refusal names the parameter its own route declared: a code route told
142
+ // its caller that "_program" is missing is answering about a field the
143
+ // route never had
144
+ if (request.source === 'code') {
145
+ if (request.code === undefined)
146
+ throw new ApiError(400, '"code" is required');
147
+ if (typeof request.code !== 'string')
148
+ throw new ApiError(400, '"code" must be a string');
149
+ if (request.code === '')
150
+ throw new ApiError(400, '"code" is not allowed to be empty');
151
+ return { code: request.code };
152
+ }
153
+ if (request.program === undefined)
154
+ throw new ApiError(400, '"_program" is required');
155
+ if (typeof request.program !== 'string')
156
+ throw new ApiError(400, '"_program" must be a string');
157
+ if (request.program === '')
158
+ throw new ApiError(400, '"_program" is not allowed to be empty');
159
+ const resolved = normaliseDrivePath(request.program);
160
+ if (resolved === null)
161
+ return failedRun(notThere(request.program));
162
+ return { path: resolved };
163
+ };
164
+ /**
165
+ * The run time a stored program's path names, if it names one.
166
+ *
167
+ * `_program=/app/run.js` is JavaScript, and the server treats it that way
168
+ * before it looks for the file (`getRunTimeAndFilePath` reads the extension).
169
+ * Only the extension vocabulary the document states is read, so `run.sas7bdat`
170
+ * or `run.backup` name no run time and are left to the host.
171
+ */
172
+ const runTimeForPath = (path, request) => {
173
+ const file = path.split('/').pop() || '';
174
+ const dot = file.lastIndexOf('.');
175
+ const extension = dot > 0 ? file.slice(dot + 1).toLowerCase() : '';
176
+ if (DOCUMENTED_RUN_TIMES.includes(extension))
177
+ return extension;
178
+ return runTimeOf(request);
179
+ };
180
+ /** The run time, refused when it is absent where the document requires it, or unheld. */
181
+ const runTimeOf = (request) => {
182
+ if (request.runTime === undefined) {
183
+ // the code routes document `runTime` as required; a stored program's run
184
+ // time is the host's to resolve from the path, so absent is normal there
185
+ if (request.source === 'code')
186
+ throw new ApiError(400, '"runTime" is required');
187
+ return undefined;
188
+ }
189
+ if (typeof request.runTime !== 'string')
190
+ throw new ApiError(400, '"runTime" must be a string');
191
+ if (!runTimes.includes(request.runTime))
192
+ throw new ApiError(400, `"runTime" must be one of [${runTimes.join(', ')}]`);
193
+ return request.runTime;
194
+ };
195
+ /**
196
+ * Retention, refused when it is not a positive number of minutes.
197
+ *
198
+ * A query string carries text, and the server's schema coerces it -
199
+ * `?expiresAfterMins=15` is the same request as `"expiresAfterMins": 15` - so
200
+ * the coercion is part of the contract rather than a convenience. Only a
201
+ * number, or text shaped like one, is read: `15abc` and `1e3` are refused (the
202
+ * first is not a number to Joi either, the second is not the shape a client
203
+ * sends), while `1.5` is accepted because `number().greater(0)` takes decimals.
204
+ *
205
+ * Retention belongs to a trigger and only to a trigger: an execute waits for
206
+ * the program, so an `expiresAfterMins` on its request is a session variable
207
+ * like any other, and validating one would refuse a request the server answers.
208
+ */
209
+ const expiryOf = (request) => {
210
+ const value = request.expiresAfterMins;
211
+ if (value === undefined)
212
+ return undefined;
213
+ const minutes = typeof value === 'number'
214
+ ? value
215
+ : typeof value === 'string' && /^\s*[+-]?\d+(\.\d+)?\s*$/.test(value)
216
+ ? Number(value)
217
+ : NaN;
218
+ if (Number.isNaN(minutes))
219
+ throw new ApiError(400, '"expiresAfterMins" must be a number');
220
+ if (minutes <= 0)
221
+ throw new ApiError(400, '"expiresAfterMins" must be greater than 0');
222
+ return minutes;
223
+ };
224
+ /** The request, validated and normalised, with its caller resolved. */
225
+ const prepare = async (caller, request) => {
226
+ const reader = await callerOf(caller);
227
+ const program = programOf(request);
228
+ const vars = { ...(request.vars || {}) };
229
+ // the code routes force the log on, because their documented body is
230
+ // assembled from it; a stored program's caller decides, and a keyword there
231
+ // means the same thing a number does. A caller who did not ask for the log
232
+ // keeps no `_debug` key at all: a host that walks the entries to build a
233
+ // query string or a header map would otherwise emit `_debug=undefined`.
234
+ const debug = 'code' in program ? CODE_DEBUG : parseDebugValue(vars._debug);
235
+ if (debug === undefined)
236
+ delete vars._debug;
237
+ else
238
+ vars._debug = debug;
239
+ return {
240
+ reader,
241
+ program,
242
+ vars,
243
+ // a code route's run time is the one it named; a stored program's is the
244
+ // one its extension names, when it names one at all
245
+ runTime: 'code' in program
246
+ ? runTimeOf(request)
247
+ : runTimeForPath(program.path, request)
248
+ };
249
+ };
250
+ return {
251
+ async execute(caller, request) {
252
+ const prepared = await prepare(caller, request);
253
+ let outcome;
254
+ try {
255
+ outcome = await runner.run({
256
+ program: prepared.program,
257
+ vars: prepared.vars,
258
+ runTime: prepared.runTime,
259
+ files: request.files
260
+ });
261
+ }
262
+ catch (error) {
263
+ return failedRun(error);
264
+ }
265
+ // a program that wrote nothing is an empty body, not a missing one: the
266
+ // route answered, and "no output" is the answer
267
+ return outcome.output || { contents: '' };
268
+ },
269
+ async trigger(caller, request) {
270
+ const prepared = await prepare(caller, request);
271
+ const expiresAfterMins = expiryOf(request);
272
+ const session = {
273
+ sessionId: newSessionId(new Date()),
274
+ owner: prepared.reader.uid,
275
+ ...(prepared.runTime === undefined
276
+ ? {}
277
+ : { runTime: prepared.runTime }),
278
+ ...(expiresAfterMins === undefined ? {} : { expiresAfterMins })
279
+ };
280
+ let outcome;
281
+ try {
282
+ outcome = await runner.run({
283
+ program: prepared.program,
284
+ vars: prepared.vars,
285
+ runTime: prepared.runTime,
286
+ session,
287
+ files: request.files
288
+ });
289
+ }
290
+ catch (error) {
291
+ return failedRun(error);
292
+ }
293
+ return outcome.pid === undefined
294
+ ? { sessionId: session.sessionId }
295
+ : { sessionId: session.sessionId, pid: outcome.pid };
296
+ }
297
+ };
298
+ };
@@ -8,9 +8,20 @@ import type { HostSession, SessionArtifact, SessionHost, SessionStateResponse }
8
8
  * because an empty log is a 200 and not a 404.
9
9
  */
10
10
  export declare const DEFAULT_SESSIONS: Record<string, HostSession>;
11
+ /**
12
+ * Sessions held in maps.
13
+ *
14
+ * The four maps are `protected` rather than `private`, because a trigger creates
15
+ * a session and the same object has to be able to record it - a runner that
16
+ * wrote a record into a second map would leave the session routes answering 404
17
+ * for a session that exists.
18
+ */
11
19
  export declare class MemorySessionHost implements SessionHost {
12
- private readonly sessions;
13
- constructor(sessions?: Record<string, HostSession>);
20
+ protected readonly sessions: Record<string, HostSession>;
21
+ protected readonly states: Record<string, SessionStateResponse>;
22
+ protected readonly logs: Record<string, string>;
23
+ protected readonly outputs: Record<string, SessionArtifact>;
24
+ constructor(sessions?: Record<string, HostSession>, states?: Record<string, SessionStateResponse>, logs?: Record<string, string>, outputs?: Record<string, SessionArtifact>);
14
25
  session(id: string): Promise<HostSession>;
15
26
  state(id: string): Promise<SessionStateResponse | undefined>;
16
27
  log(id: string): Promise<string | undefined>;
@@ -1 +1 @@
1
- {"version":3,"file":"memory-host.d.ts","sourceRoot":"","sources":["../../../src/session/memory-host.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,eAAe,EACf,WAAW,EACX,oBAAoB,EACrB,MAAM,cAAc,CAAA;AAErB;;;;;;;GAOG;AACH,eAAO,MAAM,gBAAgB,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CA8BxD,CAAA;AAsBD,qBAAa,iBAAkB,YAAW,WAAW;IACvC,OAAO,CAAC,QAAQ,CAAC,QAAQ;gBAAR,QAAQ,8BAAmB;IAElD,OAAO,CAAC,EAAE,EAAE,MA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CAAC;IAI5D,GAAG,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;IAI5C,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC;CAG/D"}
@@ -15,7 +15,7 @@ export const DEFAULT_SESSIONS = {
15
15
  pid: 4242,
16
16
  creationTimeStamp: '2026-11-07T09:00:00.000Z',
17
17
  deathTimeStamp: '2026-11-07T09:00:04.000Z',
18
- expiresAfterMins: 60
18
+ expiresAfterMins: { mins: 60, used: false }
19
19
  }
20
20
  },
21
21
  'sess-restricted': {
@@ -54,20 +54,37 @@ const OUTPUTS = {
54
54
  'sess-restricted': { contents: '' },
55
55
  'sess-silent': { contents: '' }
56
56
  };
57
+ /**
58
+ * Sessions held in maps.
59
+ *
60
+ * The four maps are `protected` rather than `private`, because a trigger creates
61
+ * a session and the same object has to be able to record it - a runner that
62
+ * wrote a record into a second map would leave the session routes answering 404
63
+ * for a session that exists.
64
+ */
57
65
  export class MemorySessionHost {
58
- constructor(sessions = DEFAULT_SESSIONS) {
66
+ constructor(sessions = {
67
+ ...DEFAULT_SESSIONS
68
+ }, states = {
69
+ ...STATES
70
+ }, logs = { ...LOGS }, outputs = {
71
+ ...OUTPUTS
72
+ }) {
59
73
  this.sessions = sessions;
74
+ this.states = states;
75
+ this.logs = logs;
76
+ this.outputs = outputs;
60
77
  }
61
78
  async session(id) {
62
79
  return this.sessions[id];
63
80
  }
64
81
  async state(id) {
65
- return STATES[id];
82
+ return this.states[id];
66
83
  }
67
84
  async log(id) {
68
- return LOGS[id];
85
+ return this.logs[id];
69
86
  }
70
87
  async output(id) {
71
- return OUTPUTS[id];
88
+ return this.outputs[id];
72
89
  }
73
90
  }
@@ -8,7 +8,18 @@ export interface SessionSummary {
8
8
  creationTimeStamp?: string;
9
9
  deathTimeStamp?: string;
10
10
  failureReason?: string;
11
- expiresAfterMins?: number;
11
+ /**
12
+ * The retention the session was triggered with, as the document states it: the
13
+ * minutes, and whether the retention has already been applied.
14
+ *
15
+ * The pair is the host's record, not a duration on its own - `used` marks the
16
+ * sweep that destroys the session as spent, and a client reading the summary
17
+ * expects both fields, so the number alone would be a shape nobody documented.
18
+ */
19
+ expiresAfterMins?: {
20
+ mins: number;
21
+ used: boolean;
22
+ };
12
23
  }
13
24
  /**
14
25
  * An artefact a session left behind.
@@ -1 +1 @@
1
- {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../../src/session/service.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAA;AACnD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAA;AAE9D,kDAAkD;AAClD,MAAM,WAAW,cAAc;IAC7B,SAAS,EAAE,MAAM,CAAA;IACjB,KAAK,EAAE,MAAM,CAAA;IACb,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAC1B;AAED;;;;;;GAMG;AACH,MAAM,WAAW,eAAe;IAC9B,QAAQ,EAAE,MAAM,GAAG,UAAU,CAAA;IAC7B,WAAW,CAAC,EAAE,MAAM,CAAA;CACrB;AAED,iFAAiF;AACjF,MAAM,MAAM,oBAAoB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;AAE1D;;;;;;;;;GASG;AACH,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,MAAM,CAAA;IACb,OAAO,EAAE,cAAc,CAAA;CACxB;AAED;;;;;;GAMG;AACH,MAAM,WAAW,WAAW;IAC1B,OAAO,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,GAAG,SAAS,CAAC,CAAA;IACrD,KAAK,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO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AC,CAAA;IACzE,KAAK,CAAC,MAAM,EAAE,OAAO,GAAG,SAAS,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAA;IAC7E,GAAG,CAAC,MAAM,EAAE,OAAO,GAAG,SAAS,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAA;IAC7D,MAAM,CAAC,MAAM,EAAE,OAAO,GAAG,SAAS,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC,CAAA;CAC1E;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,oBAAoB,GAC/B,WAAW,eAAe,EAC1B,MAAM,WAAW,KAChB,cAsDF,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sasjs/api",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
4
4
  "description": "The SASjs Server API, described once - a generated route table, the services behind it, and the conformance corpus both hosts run",
5
5
  "license": "MIT",
6
6
  "author": "SASjs",