@sasjs/api 0.49.1 → 0.51.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.
@@ -1,7 +1,8 @@
1
1
  import { ApiError } from '../types.js';
2
2
  import { estateKeyOf, normaliseServerUrl, seedOf } from './seed.js';
3
3
  import { estateFor } from './sessions.js';
4
- import { idFor, callerId } from './ids.js';
4
+ import { idFor, callerId, EMULATED_NOW } from './ids.js';
5
+ import { SESSION_VARIABLE_REFUSAL } from './overlay.js';
5
6
  /**
6
7
  * The name the emulator answers when a client asks for no particular context.
7
8
  *
@@ -72,6 +73,31 @@ const contextBody = (name, caller) => ({
72
73
  version: 2,
73
74
  links: linksFor(`/compute/contexts/${EMULATED_CONTEXT_ID}`, 'application/vnd.sas.compute.context')
74
75
  });
76
+ /**
77
+ * The context in full, for the read a client makes of one it already holds.
78
+ *
79
+ * The list view Viya answers is deliberately minimal, so a client that needs a
80
+ * context's attributes reads the context itself - Data Controller's deploy
81
+ * screen fetches each one to pick up its batch identity. The attributes are the
82
+ * ones an emulated estate truthfully has: nothing runs as a batch identity here,
83
+ * and `reuseServerProcesses` is `false` for the same reason, which is what leaves
84
+ * a client's batch-id list empty rather than inventing an account to run as.
85
+ */
86
+ const contextDetailsBody = (caller) => ({
87
+ ...contextBody(DEFAULT_CONTEXT_NAME, caller),
88
+ description: 'The compute context an emulated estate answers for',
89
+ creationTimeStamp: EMULATED_NOW,
90
+ modifiedTimeStamp: EMULATED_NOW,
91
+ modifiedBy: caller,
92
+ launchType: 'service',
93
+ launchContext: { contextId: EMULATED_CONTEXT_ID },
94
+ environment: { autoExecLines: [] },
95
+ attributes: {
96
+ reuseServerProcesses: 'false',
97
+ allowXCMD: 'false',
98
+ serverMinAvailable: '1'
99
+ }
100
+ });
75
101
  const sessionBody = (services, session, autoExecLines, caller) => {
76
102
  const { id } = session;
77
103
  const uri = `/compute/sessions/${id}`;
@@ -112,7 +138,7 @@ const jobBody = (job) => {
112
138
  ...(job.completedTimeStamp
113
139
  ? { completedTimeStamp: job.completedTimeStamp }
114
140
  : {}),
115
- jobConditionCode: 0,
141
+ jobConditionCode: job.jobConditionCode ?? 0,
116
142
  stateElapsedTime: 1,
117
143
  listingStatistics: {
118
144
  lineCount: job.log.length,
@@ -168,6 +194,13 @@ const jobOf = (services, sessionId, jobId, subject) => {
168
194
  * no absent case to answer - a fallback here would be a branch nothing reaches.
169
195
  */
170
196
  const segmentsOf = (params) => params.segments;
197
+ // Visit every index, including holes in arrays supplied by direct dispatch.
198
+ const validCodeLines = (lines) => {
199
+ for (let i = 0; i < lines.length; i++)
200
+ if (typeof lines[i] !== 'string')
201
+ return false;
202
+ return true;
203
+ };
171
204
  export const COMPUTE_HANDLERS = {
172
205
  'GET /compute/contexts': async ({ request }) => {
173
206
  const limit = Number(request.query?.limit ?? 0) || 0;
@@ -187,6 +220,14 @@ export const COMPUTE_HANDLERS = {
187
220
  }
188
221
  };
189
222
  },
223
+ 'GET /compute/contexts/{}': async ({ request, params }) => {
224
+ // the estate has one context and its id does not move, so an id it is not is
225
+ // an id no context here ever had - the same refusal the drive makes for an
226
+ // unknown folder rather than a body about some other context
227
+ if (params.id !== EMULATED_CONTEXT_ID)
228
+ throw new ApiError(404, `No compute context matches the id ${params.id}. The emulated estate answers one context, and this is not its id.`);
229
+ return { status: 200, body: contextDetailsBody(callerId(request.subject)) };
230
+ },
190
231
  'POST /compute/contexts/{}/sessions': async ({ services, params, request }) => {
191
232
  if (params.id !== EMULATED_CONTEXT_ID)
192
233
  throw new ApiError(404, `Context with ID '${params.id}' was not found.`);
@@ -197,6 +238,31 @@ export const COMPUTE_HANDLERS = {
197
238
  body: sessionBody(services, session, body.environment?.autoExecLines ?? [], callerId(request.subject))
198
239
  };
199
240
  },
241
+ 'GET /compute/sessions/{}/variables/{}': async ({ services, params, request }) => {
242
+ if (services.viya?.mockSysjobid !== true)
243
+ throw new ApiError(501, SESSION_VARIABLE_REFUSAL, {
244
+ message: SESSION_VARIABLE_REFUSAL
245
+ });
246
+ if (request.subject === undefined && request.token !== undefined)
247
+ throw new ApiError(401, 'A valid caller is required.');
248
+ const [sessionId, name] = segmentsOf(params);
249
+ const session = sessionOf(services, sessionId, request.subject);
250
+ if (name !== 'SYSJOBID')
251
+ throw new ApiError(501, SESSION_VARIABLE_REFUSAL, {
252
+ message: SESSION_VARIABLE_REFUSAL
253
+ });
254
+ const uri = `/compute/sessions/${encodeURIComponent(session.id)}/variables/SYSJOBID`;
255
+ return {
256
+ status: 200,
257
+ body: {
258
+ name: 'SYSJOBID',
259
+ value: `mock-${session.id}`,
260
+ scope: 'AUTOMATIC',
261
+ version: 1,
262
+ links: linksFor(uri, 'application/vnd.sas.compute.session.variable')
263
+ }
264
+ };
265
+ },
200
266
  'GET /compute/sessions/{}/state': async ({ services, params, request }) => {
201
267
  sessionOf(services, params.id, request.subject);
202
268
  // a bare enum, not an object: the adapter calls `.trim()` on the answer, and
@@ -210,8 +276,17 @@ export const COMPUTE_HANDLERS = {
210
276
  },
211
277
  'POST /compute/sessions/{}/jobs': async ({ services, params, request }) => {
212
278
  const session = sessionOf(services, params.id, request.subject);
213
- const body = (request.body ?? {});
214
- const job = estateOf(services).submit(session, body);
279
+ const input = request.body === undefined ? {} : request.body;
280
+ if (!input || typeof input !== 'object' || Array.isArray(input))
281
+ throw new ApiError(400, 'Compute job code must be a string or an array of strings.');
282
+ const body = input;
283
+ const code = body.code;
284
+ if (code !== undefined &&
285
+ typeof code !== 'string' &&
286
+ (!Array.isArray(code) || !validCodeLines(code)))
287
+ throw new ApiError(400, 'Compute job code must be a string or an array of strings.');
288
+ const program = (code ?? '');
289
+ const job = estateOf(services).submit(session, { ...body, code: program });
215
290
  const execute = services.viya?.execute;
216
291
  // a host with no engine has nothing to run, so the job is finished at once
217
292
  if (!execute) {
@@ -227,7 +302,7 @@ export const COMPUTE_HANDLERS = {
227
302
  // not advertise them - the run writes the log when it has one
228
303
  job.log = [];
229
304
  void execute({
230
- program: body.code ?? '',
305
+ program,
231
306
  variables: body.variables,
232
307
  name: body.name,
233
308
  sessionId: session.id
@@ -235,6 +310,7 @@ export const COMPUTE_HANDLERS = {
235
310
  .then((ran) => {
236
311
  job.log = ran.log.split('\n');
237
312
  job.state = ran.state ?? 'completed';
313
+ job.jobConditionCode = ran.jobConditionCode;
238
314
  if (ran.webout !== undefined)
239
315
  job.webout = ran.webout;
240
316
  job.completedTimeStamp = new Date().toISOString();
@@ -282,6 +358,53 @@ export const COMPUTE_HANDLERS = {
282
358
  body: jobOf(services, sessionId, jobId, request.subject).state
283
359
  };
284
360
  },
361
+ // The collection is a separate CLI call from the adapter's /log/content.
362
+ 'GET /compute/sessions/{}/jobs/{}/log': async ({ services, params, request }) => {
363
+ const [sessionId, jobId] = segmentsOf(params);
364
+ const job = jobOf(services, sessionId, jobId, request.subject);
365
+ const start = request.query?.start;
366
+ const limit = request.query?.limit;
367
+ const startValue = start === undefined ? '0' : start;
368
+ const limitValue = limit === undefined ? '10' : limit;
369
+ if (typeof startValue !== 'string' ||
370
+ typeof limitValue !== 'string' ||
371
+ !/^\d+$/.test(startValue) ||
372
+ !/^\d+$/.test(limitValue) ||
373
+ !Number.isSafeInteger(Number(startValue)) ||
374
+ !Number.isSafeInteger(Number(limitValue)) ||
375
+ Number(limitValue) > 2147483647)
376
+ throw new ApiError(400, 'Unsupported job log pagination.');
377
+ if (request.query?.type !== undefined ||
378
+ request.query?.timeout !== undefined)
379
+ throw new ApiError(400, 'Job log type and timeout are not supported by the emulator.');
380
+ const offset = Number(startValue);
381
+ const pageSize = Number(limitValue);
382
+ const uri = `/compute/sessions/${job.sessionId}/jobs/${job.id}/log`;
383
+ return {
384
+ status: 200,
385
+ body: {
386
+ accept: 'application/json',
387
+ name: 'log',
388
+ start: offset,
389
+ limit: pageSize,
390
+ count: job.log.length,
391
+ version: 2,
392
+ items: job.log
393
+ .slice(offset, offset + pageSize)
394
+ .map((line) => ({ line, type: 'NOTE', version: 2 })),
395
+ links: [
396
+ {
397
+ href: uri,
398
+ uri,
399
+ rel: 'self',
400
+ method: 'GET',
401
+ type: 'application/vnd.sas.collection',
402
+ itemType: 'application/vnd.sas.compute.log.line'
403
+ }
404
+ ]
405
+ }
406
+ };
407
+ },
285
408
  'GET /compute/sessions/{}/jobs/{}/log/content': async ({ services, params, request }) => {
286
409
  const [sessionId, jobId] = segmentsOf(params);
287
410
  const job = jobOf(services, sessionId, jobId, request.subject);
@@ -1 +1 @@
1
- {"version":3,"file":"declared.d.ts","sourceRoot":"","sources":["../../../src/viya/declared.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAc,KAAK,aAAa,EAAE,MAAM,YAAY,CAAA;AAE3D,wDAAwD;AACxD,MAAM,WAAW,iBAAkB,SAAQ,aAAa;IACtD,qEAAqE;IACrE,QAAQ,EAAE,MAAM,CAAA;CACjB;AAED,eAAO,MAAM,QAAQ,EAAE,iBAAiB,EAiBvC,CAAA;AAED,mFAAmF;AACnF,eAAO,MAAM,eAAe,EAAE,aAAa,EAAiC,CAAA"}
1
+ {"version":3,"file":"declared.d.ts","sourceRoot":"","sources":["../../../src/viya/declared.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAc,KAAK,aAAa,EAAE,MAAM,YAAY,CAAA;AAE3D,wDAAwD;AACxD,MAAM,WAAW,iBAAkB,SAAQ,aAAa;IACtD,qEAAqE;IACrE,QAAQ,EAAE,MAAM,CAAA;CACjB;AAED,eAAO,MAAM,QAAQ,EAAE,iBAAiB,EAsIvC,CAAA;AAED,mFAAmF;AACnF,eAAO,MAAM,eAAe,EAAE,aAAa,EAAiC,CAAA"}
@@ -15,6 +15,17 @@
15
15
  */
16
16
  import { VIYA_TABLE } from './table.js';
17
17
  export const DECLARED = [
18
+ {
19
+ id: 'GET /compute/sessions/{}/jobs/{}/log',
20
+ method: 'GET',
21
+ path: '/compute/sessions/{}/jobs/{}/log',
22
+ steps: [],
23
+ statuses: [200, 400, 404],
24
+ queries: ['start', 'limit'],
25
+ request: { queries: ['start', 'limit'], body: undefined },
26
+ shape: undefined,
27
+ declared: 'The CLI follows the job log link directly and pages it; the adapter capture reads the different /log/content operation. SAS Compute documents this as a collection of log line objects.'
28
+ },
18
29
  {
19
30
  id: 'GET /compute/sessions/{}/filerefs/_webout/content',
20
31
  method: 'GET',
@@ -29,6 +40,102 @@ export const DECLARED = [
29
40
  // there is no JSON shape to record
30
41
  shape: undefined,
31
42
  declared: 'The adapter fetches this only when a run expects a webout (`expectWebout`), and the recording pass submits a `%put` and reads the log instead. Without it an application cannot receive the data its service returns, so the emulator answers it from the job it just ran.'
43
+ },
44
+ // The application's own identity reads. No capture describes these at all: the
45
+ // recorder drives the client the adapter is, and Data Controller's group, user
46
+ // and deploy screens call the identity service from the browser instead. That
47
+ // is why they are declared rather than recorded, and why the scope they belong
48
+ // to is stated in `src/viya/appSurface.ts`.
49
+ {
50
+ id: 'GET /identities/groups',
51
+ method: 'GET',
52
+ path: '/identities/groups',
53
+ steps: [],
54
+ statuses: [200],
55
+ queries: ['sortBy', 'limit', 'start'],
56
+ request: { queries: ['sortBy', 'limit', 'start'], body: undefined },
57
+ // a collection of groups, whose own shape Viya publishes rather than an
58
+ // estate recording supplying it
59
+ shape: undefined,
60
+ declared: 'The application fetches the group list twice on its deploy screen - for the admin-group dropdown and, filtered, for the caller own groups - and aborts the wizard when that read fails. The adapter never calls it, so no recording pass reaches it.'
61
+ },
62
+ {
63
+ id: 'GET /identities/groups/{}/members',
64
+ method: 'GET',
65
+ path: '/identities/groups/{}/members',
66
+ steps: [],
67
+ statuses: [200, 404],
68
+ queries: ['limit'],
69
+ request: { queries: ['limit'], body: undefined },
70
+ shape: undefined,
71
+ declared: 'The group screen lists the accounts that hold a group, following the members link the group list advertises. The adapter has no identity route beyond the caller, so a capture driven by it cannot reach this one.'
72
+ },
73
+ {
74
+ id: 'GET /identities/users',
75
+ method: 'GET',
76
+ path: '/identities/users',
77
+ steps: [],
78
+ statuses: [200],
79
+ queries: ['limit', 'start'],
80
+ request: { queries: ['limit', 'start'], body: undefined },
81
+ shape: undefined,
82
+ declared: 'The user screen lists the estate accounts. The adapter does not offer an account list and never requests one, so the recording pass has no way to observe it.'
83
+ },
84
+ {
85
+ id: 'GET /identities/users/{}',
86
+ method: 'GET',
87
+ path: '/identities/users/{}',
88
+ steps: [],
89
+ statuses: [200, 404],
90
+ queries: [],
91
+ request: { queries: [], body: undefined },
92
+ shape: undefined,
93
+ declared: 'The user screen reads one account from the id the list returned, for the profile above the memberships. The adapter asks only about the caller, which is a different operation with its own row.'
94
+ },
95
+ {
96
+ id: 'GET /identities/users/@currentUser/memberships',
97
+ method: 'GET',
98
+ path: '/identities/users/@currentUser/memberships',
99
+ steps: [],
100
+ statuses: [200],
101
+ queries: ['limit', 'start'],
102
+ request: { queries: ['limit', 'start'], body: undefined },
103
+ shape: undefined,
104
+ declared: 'The deploy screen filters the admin-group list to the groups the caller belongs to, and shows every group when this read fails. The adapter reads the caller itself but never the caller memberships.'
105
+ },
106
+ {
107
+ id: 'GET /identities/users/{}/memberships',
108
+ method: 'GET',
109
+ path: '/identities/users/{}/memberships',
110
+ steps: [],
111
+ statuses: [200, 401],
112
+ queries: ['limit', 'start'],
113
+ request: { queries: ['limit', 'start'], body: undefined },
114
+ shape: undefined,
115
+ declared: 'The user screen lists the groups any account holds, addressed by the id the list returned. It is the same answer as the caller own memberships for one id, and the adapter asks for neither.'
116
+ },
117
+ {
118
+ id: 'GET /identities/users/{}/avatar/content',
119
+ method: 'GET',
120
+ path: '/identities/users/{}/avatar/content',
121
+ steps: [],
122
+ statuses: [404],
123
+ queries: [],
124
+ request: { queries: [], body: undefined },
125
+ // the body is an image when an estate holds one: there is no JSON shape
126
+ shape: undefined,
127
+ declared: 'The header renders the caller avatar from this URL, and an estate whose identity carries no avatar answers 404 so the client falls back to its own image. The adapter has no avatar read.'
128
+ },
129
+ {
130
+ id: 'GET /compute/contexts/{}',
131
+ method: 'GET',
132
+ path: '/compute/contexts/{}',
133
+ steps: [],
134
+ statuses: [200, 404],
135
+ queries: [],
136
+ request: { queries: [], body: undefined },
137
+ shape: undefined,
138
+ declared: 'The deploy screen reads each context in full, because the list view carries neither the batch identity nor the reuse setting it filters on. The capture recorded the list only, so the read it follows with is stated here.'
32
139
  }
33
140
  ];
34
141
  /** Every operation the emulator answers: what an estate did, plus what it must. */
@@ -1 +1 @@
1
- {"version":3,"file":"dispatch.d.ts","sourceRoot":"","sources":["../../../src/viya/dispatch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,KAAK,EAAE,UAAU,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAA;AAE5E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAM/C,wDAAwD;AACxD,MAAM,WAAW,YAAa,SAAQ,WAAW;IAC/C,uEAAuE;IACvE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAChC;AAED,MAAM,WAAW,SAAS;IACxB,SAAS,EAAE,aAAa,CAAA;IACxB,sDAAsD;IACtD,QAAQ,EAAE,MAAM,EAAE,CAAA;CACnB;AA4BD,2EAA2E;AAC3E,eAAO,MAAM,iBAAiB,GAC5B,QAAQ,MAAM,EACd,MAAM,MAAM,KACX,SAAS,GAAG,SA0Bd,CAAA;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,YAAY,GACvB,UAAU,QAAQ,EAClB,QAAQ,MAAM,EACd,MAAM,MAAM,EACZ,UAAS,UAAe,KACvB,OAAO,CAAC,YAAY,CAkGtB,CAAA"}
1
+ {"version":3,"file":"dispatch.d.ts","sourceRoot":"","sources":["../../../src/viya/dispatch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,KAAK,EAAE,UAAU,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAA;AAE5E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAM/C,wDAAwD;AACxD,MAAM,WAAW,YAAa,SAAQ,WAAW;IAC/C,uEAAuE;IACvE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAChC;AAED,MAAM,WAAW,SAAS;IACxB,SAAS,EAAE,aAAa,CAAA;IACxB,sDAAsD;IACtD,QAAQ,EAAE,MAAM,EAAE,CAAA;CACnB;AA4BD,2EAA2E;AAC3E,eAAO,MAAM,iBAAiB,GAC5B,QAAQ,MAAM,EACd,MAAM,MAAM,KACX,SAAS,GAAG,SA0Bd,CAAA;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,YAAY,GACvB,UAAU,QAAQ,EAClB,QAAQ,MAAM,EACd,MAAM,MAAM,EACZ,UAAS,UAAe,KACvB,OAAO,CAAC,YAAY,CAwGtB,CAAA"}
@@ -1,6 +1,6 @@
1
1
  import { ApiError, isApiError } from '../types.js';
2
2
  import { VIYA_OPERATIONS } from './declared.js';
3
- import { VIYA_OVERLAY } from './overlay.js';
3
+ import { VIYA_OVERLAY, SESSION_VARIABLE_REFUSAL } from './overlay.js';
4
4
  import { VIYA_HANDLERS } from './service.js';
5
5
  import { emulatedHeaders } from './version.js';
6
6
  const escape = (segment) => segment.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
@@ -87,6 +87,9 @@ export const dispatchViya = async (services, method, path, request = {}) => {
87
87
  message: `${found.operation.id} is not emulated. ${entry.reason ?? ''}`.trim()
88
88
  }
89
89
  };
90
+ if (found.operation.id === 'GET /compute/sessions/{}/variables/{}' &&
91
+ services.viya?.mockSysjobid !== true)
92
+ return { status: 501, headers, body: { message: SESSION_VARIABLE_REFUSAL } };
90
93
  const handler = VIYA_HANDLERS[found.operation.id];
91
94
  if (!handler)
92
95
  return {
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The Viya identity answers an application reads for itself.
3
+ *
4
+ * The adapter asks Viya who the caller is and nothing else, so `/identities`
5
+ * used to be one operation here. An application asks more than that: Data
6
+ * Controller's group, user and deploy screens call the identity service
7
+ * directly - `GET /identities/groups` twice on the deploy screen alone - and on
8
+ * an emulated estate those calls answered 404, which is a screen a visitor
9
+ * cannot use. `src/viya/appSurface.ts` is where those calls are declared, and
10
+ * this is where they are answered.
11
+ *
12
+ * The estate has one identity: the store the package already serves the
13
+ * administration routes from. That store is the project's `mock-identity.json`
14
+ * on a mock site and the host's own records on a server, so a group named in the
15
+ * fixture is the group this answers - nothing here invents a population. The
16
+ * port is `RecordService` rather than `IdentityStore` because the administration
17
+ * routes' gates belong with them: a caller with no account gets the same 401
18
+ * here that it gets there.
19
+ */
20
+ import type { ApiResponse, Services } from '../host/dispatch.js';
21
+ import type { Subject } from '../identity/types.js';
22
+ import type { RecordService } from '../identity/records.js';
23
+ /** The port these handlers read, or the capability the host did not supply. */
24
+ export declare const requireRecords: (services: Services) => RecordService;
25
+ export declare const IDENTITY_HANDLERS: Record<string, (context: {
26
+ services: Services;
27
+ request: {
28
+ query?: Record<string, string | undefined>;
29
+ subject?: Subject;
30
+ token?: string;
31
+ };
32
+ params: Record<string, string>;
33
+ }) => Promise<ApiResponse>>;
34
+ //# sourceMappingURL=identity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity.d.ts","sourceRoot":"","sources":["../../../src/viya/identity.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAA;AAEhE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAA;AACnD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAA;AAG3D,+EAA+E;AAC/E,eAAO,MAAM,cAAc,GAAI,UAAU,QAAQ,KAAG,aAQnD,CAAA;AAqID,eAAO,MAAM,iBAAiB,EAAE,MAAM,CACpC,MAAM,EACN,CAAC,OAAO,EAAE;IACR,QAAQ,EAAE,QAAQ,CAAA;IAClB,OAAO,EAAE;QACP,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAA;QAC1C,OAAO,CAAC,EAAE,OAAO,CAAA;QACjB,KAAK,CAAC,EAAE,MAAM,CAAA;KACf,CAAA;IACD,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAC/B,KAAK,OAAO,CAAC,WAAW,CAAC,CAsJ3B,CAAA"}
@@ -0,0 +1,187 @@
1
+ import { ApiError } from '../types.js';
2
+ import { EMULATED_NOW } from './ids.js';
3
+ /** The port these handlers read, or the capability the host did not supply. */
4
+ export const requireRecords = (services) => {
5
+ if (!services.records)
6
+ throw new ApiError(501, 'The emulated identity answers from the records service, which this host does not supply.');
7
+ return services.records;
8
+ };
9
+ /**
10
+ * The caller, from the subject a host resolved or from the token it forwarded.
11
+ *
12
+ * A host that already knows its caller passes `subject`; one that hands the
13
+ * emulator a bearer token (the server's Viya router does) gets the token read
14
+ * here, exactly as `GET /identities/users/@currentUser` reads it. Neither is
15
+ * optional in effect: an unauthenticated caller has no identity to answer about.
16
+ */
17
+ const callerOf = async (services, request) => request.subject ?? (await services.identity?.authenticate(request.token));
18
+ /**
19
+ * The `{}` a membership or avatar read was addressed to, as a uid.
20
+ *
21
+ * `@currentUser` is where Viya puts the caller's own account, and a client asks
22
+ * for it by that spelling. It is resolved here rather than given its own row so
23
+ * the handler has one shape to answer.
24
+ */
25
+ const userIdFrom = (segment, caller) => {
26
+ if (segment.toLowerCase() !== '@currentuser')
27
+ return segment;
28
+ const id = caller?.userId;
29
+ if (!id)
30
+ throw new ApiError(401, 'No caller is signed in.');
31
+ return id;
32
+ };
33
+ /** The paging fields every collection answer carries, as the captured ones do. */
34
+ const collection = (name, items, limit, uri, type) => {
35
+ const page = limit > 0 ? items.slice(0, limit) : items;
36
+ return {
37
+ accept: 'application/json',
38
+ name,
39
+ start: 0,
40
+ // the value asked for is echoed, as the folder answers echo it: a caller
41
+ // that asked for five and is told zero cannot tell what happened
42
+ limit: limit || page.length,
43
+ count: page.length,
44
+ version: 2,
45
+ items: page,
46
+ links: [
47
+ {
48
+ href: uri,
49
+ uri,
50
+ rel: 'self',
51
+ method: 'GET',
52
+ type: 'application/vnd.sas.collection',
53
+ itemType: type
54
+ }
55
+ ]
56
+ };
57
+ };
58
+ const identityLinks = (uri, type) => [
59
+ { href: uri, uri, rel: 'self', method: 'GET', type }
60
+ ];
61
+ const GROUP_TYPE = 'application/vnd.sas.identity.group';
62
+ const USER_TYPE = 'application/vnd.sas.identity.user';
63
+ /** A group as Viya represents one, from the store's record. */
64
+ const groupBody = (group, memberCount) => ({
65
+ id: group.uid,
66
+ name: group.name,
67
+ description: group.description,
68
+ providerId: 'sas',
69
+ state: 'active',
70
+ memberCount,
71
+ creationTimeStamp: EMULATED_NOW,
72
+ modifiedTimeStamp: EMULATED_NOW,
73
+ version: 1,
74
+ links: identityLinks(`/identities/groups/${group.uid}`, GROUP_TYPE)
75
+ });
76
+ /** A user as Viya represents one. */
77
+ const userBody = (user) => ({
78
+ id: user.uid,
79
+ // Viya's `name` is the identifier a person signs in with; the display name is
80
+ // a separate field, and this is the one a member list shows
81
+ name: user.username,
82
+ displayName: user.displayName,
83
+ providerId: 'sas',
84
+ state: 'active',
85
+ version: 1,
86
+ links: identityLinks(`/identities/users/${user.uid}`, USER_TYPE)
87
+ });
88
+ /** The groups a user is a member of, as Viya's memberships route answers them. */
89
+ const membershipsOf = async (records, caller, uid) => {
90
+ const users = await records.listUsers(caller);
91
+ // Viya clients may address a user by login name; prefer an exact uid when a
92
+ // login happens to equal another user's uid.
93
+ const user = users.find((item) => item.uid === uid) ??
94
+ users.find((item) => item.username === uid);
95
+ const resolvedUid = user?.uid ?? uid;
96
+ const groups = await records.listGroups(caller);
97
+ const found = [];
98
+ for (const group of groups) {
99
+ const details = await records.getGroup(caller, { uid: group.uid });
100
+ if (details.users.some((member) => member.uid === resolvedUid))
101
+ found.push(groupBody(group, details.users.length));
102
+ }
103
+ return found;
104
+ };
105
+ export const IDENTITY_HANDLERS = {
106
+ 'GET /identities/groups': async ({ services, request }) => {
107
+ const records = requireRecords(services);
108
+ const caller = await callerOf(services, request);
109
+ const limit = Number(request.query?.limit ?? 0) || 0;
110
+ const sortBy = request.query?.sortBy;
111
+ const groups = await records.listGroups(caller);
112
+ const items = [];
113
+ for (const group of groups) {
114
+ const details = await records.getGroup(caller, { uid: group.uid });
115
+ items.push(groupBody(group, details.users.length));
116
+ }
117
+ // `sortBy=name` is what the application asks for, and the store's order is
118
+ // not one: a screen that lists groups alphabetically asks the service for it
119
+ const ordered = sortBy && sortBy.toLowerCase() === 'name'
120
+ ? [...items].sort((left, right) => left.name.localeCompare(right.name))
121
+ : items;
122
+ return {
123
+ status: 200,
124
+ body: collection('groups', ordered, limit, '/identities/groups', GROUP_TYPE)
125
+ };
126
+ },
127
+ 'GET /identities/groups/{}/members': async ({ services, request, params }) => {
128
+ const records = requireRecords(services);
129
+ const caller = await callerOf(services, request);
130
+ const limit = Number(request.query?.limit ?? 0) || 0;
131
+ const details = await records.getGroup(caller, { uid: params.id });
132
+ const items = details.users.map((user) => userBody(user));
133
+ return {
134
+ status: 200,
135
+ body: collection('members', items, limit, `/identities/groups/${details.uid}/members`, USER_TYPE)
136
+ };
137
+ },
138
+ 'GET /identities/users': async ({ services, request }) => {
139
+ const records = requireRecords(services);
140
+ const caller = await callerOf(services, request);
141
+ const limit = Number(request.query?.limit ?? 0) || 0;
142
+ const users = await records.listUsers(caller);
143
+ return {
144
+ status: 200,
145
+ body: collection('users', users.map((user) => userBody(user)), limit, '/identities/users', USER_TYPE)
146
+ };
147
+ },
148
+ 'GET /identities/users/{}': async ({ services, request, params }) => {
149
+ const records = requireRecords(services);
150
+ const caller = await callerOf(services, request);
151
+ const uid = userIdFrom(params.id, caller);
152
+ const user = await records.getUser(caller, { uid });
153
+ return { status: 200, body: userBody(user) };
154
+ },
155
+ 'GET /identities/users/@currentUser/memberships': async ({ services, request }) => {
156
+ const records = requireRecords(services);
157
+ const caller = await callerOf(services, request);
158
+ const limit = Number(request.query?.limit ?? 0) || 0;
159
+ const uid = userIdFrom('@currentUser', caller);
160
+ const items = await membershipsOf(records, caller, uid);
161
+ return {
162
+ status: 200,
163
+ body: collection('memberships', items, limit, '/identities/users/@currentUser/memberships', GROUP_TYPE)
164
+ };
165
+ },
166
+ 'GET /identities/users/{}/memberships': async ({ services, request, params }) => {
167
+ const records = requireRecords(services);
168
+ const caller = await callerOf(services, request);
169
+ const limit = Number(request.query?.limit ?? 0) || 0;
170
+ const uid = userIdFrom(params.id, caller);
171
+ // the address the client used is the address echoed back, as the other
172
+ // answers do: a client that followed a rel is never told about another one
173
+ const items = await membershipsOf(records, caller, uid);
174
+ return {
175
+ status: 200,
176
+ body: collection('memberships', items, limit, `/identities/users/${params.id}/memberships`, GROUP_TYPE)
177
+ };
178
+ },
179
+ 'GET /identities/users/{}/avatar/content': async ({ services, request, params }) => {
180
+ const caller = await callerOf(services, request);
181
+ const uid = userIdFrom(params.id, caller);
182
+ // the estate's identity carries no avatar, and Viya answers a 404 for an
183
+ // account that has none - so a client's fallback image is what a real
184
+ // estate with none would show it
185
+ throw new ApiError(404, `No avatar is recorded for the user ${uid}.`);
186
+ }
187
+ };
@@ -3,6 +3,7 @@ export interface ViyaOverlayEntry {
3
3
  /** Present when declined: what a caller is told, and why. */
4
4
  reason?: string;
5
5
  }
6
+ export declare const SESSION_VARIABLE_REFUSAL = "GET /compute/sessions/{}/variables/{} is not emulated. The emulator does not model session variables; the client reads these only to log the pid of a job it is about to submit (SYSJOBID), and any name it asks for is refused here rather than answered with a value the emulator did not run.";
6
7
  export declare const VIYA_OVERLAY: Record<string, ViyaOverlayEntry>;
7
8
  /**
8
9
  * Refuse an overlay and a table that do not describe the same operations.
@@ -1 +1 @@
1
- {"version":3,"file":"overlay.d.ts","sourceRoot":"","sources":["../../../src/viya/overlay.ts"],"names":[],"mappings":"AAeA,MAAM,WAAW,gBAAgB;IAC/B,WAAW,EAAE,OAAO,CAAA;IACpB,6DAA6D;IAC7D,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB;AAuBD,eAAO,MAAM,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAgEzD,CAAA;AAED;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,oBAAoB,GAC/B,SAAS,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,EACzC,aAAY,KAAK,CAAC;IAAE,EAAE,EAAE,MAAM,CAAA;CAAE,CAAmB,KAClD,IAcF,CAAA"}
1
+ {"version":3,"file":"overlay.d.ts","sourceRoot":"","sources":["../../../src/viya/overlay.ts"],"names":[],"mappings":"AAeA,MAAM,WAAW,gBAAgB;IAC/B,WAAW,EAAE,OAAO,CAAA;IACpB,6DAA6D;IAC7D,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB;AAuBD,eAAO,MAAM,wBAAwB,qSAC+P,CAAA;AAEpS,eAAO,MAAM,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAyEzD,CAAA;AAED;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,oBAAoB,GAC/B,SAAS,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,EACzC,aAAY,KAAK,CAAC;IAAE,EAAE,EAAE,MAAM,CAAA;CAAE,CAAmB,KAClD,IAcF,CAAA"}
@@ -29,6 +29,7 @@ const NEEDS_AUTH = 'The token endpoint is answered by the host that mounts the e
29
29
  * what is missing and a client learning nothing.
30
30
  */
31
31
  const NEEDS_JOBS = 'The emulator answers the compute and content families; the job definitions a deploy creates and the executions a run submits are not modelled yet.';
32
+ export const SESSION_VARIABLE_REFUSAL = 'GET /compute/sessions/{}/variables/{} is not emulated. The emulator does not model session variables; the client reads these only to log the pid of a job it is about to submit (SYSJOBID), and any name it asks for is refused here rather than answered with a value the emulator did not run.';
32
33
  export const VIYA_OVERLAY = {
33
34
  // answered here
34
35
  'POST /folders/folders': { implemented: true },
@@ -38,13 +39,24 @@ export const VIYA_OVERLAY = {
38
39
  'GET /folders/folders/@item': { implemented: true },
39
40
  'GET /folders/folders/@myRecycleBin': { implemented: true },
40
41
  'GET /identities/users/@currentUser': { implemented: true },
42
+ // answered here: the application's own identity reads, declared rather than
43
+ // captured - see src/viya/appSurface.ts for the scope they belong to
44
+ 'GET /identities/groups': { implemented: true },
45
+ 'GET /identities/groups/{}/members': { implemented: true },
46
+ 'GET /identities/users': { implemented: true },
47
+ 'GET /identities/users/{}': { implemented: true },
48
+ 'GET /identities/users/@currentUser/memberships': { implemented: true },
49
+ 'GET /identities/users/{}/memberships': { implemented: true },
50
+ 'GET /identities/users/{}/avatar/content': { implemented: true },
41
51
  'GET /types/types': { implemented: true },
42
52
  // answered here: compute
43
53
  'GET /compute/contexts': { implemented: true },
54
+ 'GET /compute/contexts/{}': { implemented: true },
44
55
  'POST /compute/contexts/{}/sessions': { implemented: true },
45
56
  'DELETE /compute/sessions/{}': { implemented: true },
46
57
  'POST /compute/sessions/{}/jobs': { implemented: true },
47
58
  'GET /compute/sessions/{}/jobs/{}': { implemented: true },
59
+ 'GET /compute/sessions/{}/jobs/{}/log': { implemented: true },
48
60
  'GET /compute/sessions/{}/jobs/{}/log/content': { implemented: true },
49
61
  'GET /compute/sessions/{}/jobs/{}/state': { implemented: true },
50
62
  'GET /compute/sessions/{}/state': { implemented: true },
@@ -75,11 +87,8 @@ export const VIYA_OVERLAY = {
75
87
  implemented: false,
76
88
  reason: 'The emulator answers compute contexts from its seed; the launcher list a client falls back to is not modelled, and nothing on the emulated path asks for it.'
77
89
  },
78
- // declined: session variables are not modelled
79
- 'GET /compute/sessions/{}/variables/{}': {
80
- implemented: false,
81
- reason: 'The emulator does not model session variables; the client reads these only to log the pid of a job it is about to submit (SYSJOBID), and any name it asks for is refused here rather than answered with a value the emulator did not run.'
82
- },
90
+ // Default refusal, with an explicit host opt-in for a synthetic SYSJOBID.
91
+ 'GET /compute/sessions/{}/variables/{}': { implemented: true },
83
92
  // declined: the host owns the token port
84
93
  'POST /SASLogon/oauth/token': { implemented: false, reason: NEEDS_AUTH },
85
94
  // declared, not captured: the webout an application's service returns