@mondaydotcomorg/monday-authorization 3.5.1 → 3.5.2-feat-shaime-support-entity-attributes-3-6202ab7

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 (111) hide show
  1. package/dist/authorization-attributes-ms-service.d.ts +72 -0
  2. package/dist/authorization-attributes-ms-service.d.ts.map +1 -0
  3. package/dist/authorization-attributes-ms-service.js +279 -0
  4. package/dist/authorization-attributes-service.d.ts +25 -47
  5. package/dist/authorization-attributes-service.d.ts.map +1 -1
  6. package/dist/authorization-attributes-service.js +32 -171
  7. package/dist/authorization-attributes-sns-service.d.ts +70 -0
  8. package/dist/authorization-attributes-sns-service.d.ts.map +1 -0
  9. package/dist/authorization-attributes-sns-service.js +179 -0
  10. package/dist/base-attribute-assignment.d.ts +19 -0
  11. package/dist/base-attribute-assignment.d.ts.map +1 -0
  12. package/dist/base-attribute-assignment.js +34 -0
  13. package/dist/constants/sns.d.ts +12 -2
  14. package/dist/constants/sns.d.ts.map +1 -1
  15. package/dist/constants/sns.js +22 -2
  16. package/dist/entity-attribute-assignment.d.ts +16 -0
  17. package/dist/entity-attribute-assignment.d.ts.map +1 -0
  18. package/dist/entity-attribute-assignment.js +33 -0
  19. package/dist/entity-attributes-constants.d.ts +7 -0
  20. package/dist/entity-attributes-constants.d.ts.map +1 -0
  21. package/dist/entity-attributes-constants.js +11 -0
  22. package/dist/errors/argument-error.d.ts +4 -0
  23. package/dist/errors/argument-error.d.ts.map +1 -0
  24. package/dist/errors/argument-error.js +10 -0
  25. package/dist/esm/authorization-attributes-ms-service.d.ts +72 -0
  26. package/dist/esm/authorization-attributes-ms-service.d.ts.map +1 -0
  27. package/dist/esm/authorization-attributes-ms-service.mjs +277 -0
  28. package/dist/esm/authorization-attributes-service.d.ts +25 -47
  29. package/dist/esm/authorization-attributes-service.d.ts.map +1 -1
  30. package/dist/esm/authorization-attributes-service.mjs +32 -167
  31. package/dist/esm/authorization-attributes-sns-service.d.ts +70 -0
  32. package/dist/esm/authorization-attributes-sns-service.d.ts.map +1 -0
  33. package/dist/esm/authorization-attributes-sns-service.mjs +173 -0
  34. package/dist/esm/base-attribute-assignment.d.ts +19 -0
  35. package/dist/esm/base-attribute-assignment.d.ts.map +1 -0
  36. package/dist/esm/base-attribute-assignment.mjs +28 -0
  37. package/dist/esm/constants/sns.d.ts +12 -2
  38. package/dist/esm/constants/sns.d.ts.map +1 -1
  39. package/dist/esm/constants/sns.mjs +17 -3
  40. package/dist/esm/entity-attribute-assignment.d.ts +16 -0
  41. package/dist/esm/entity-attribute-assignment.d.ts.map +1 -0
  42. package/dist/esm/entity-attribute-assignment.mjs +31 -0
  43. package/dist/esm/entity-attributes-constants.d.ts +7 -0
  44. package/dist/esm/entity-attributes-constants.d.ts.map +1 -0
  45. package/dist/esm/entity-attributes-constants.mjs +9 -0
  46. package/dist/esm/errors/argument-error.d.ts +4 -0
  47. package/dist/esm/errors/argument-error.d.ts.map +1 -0
  48. package/dist/esm/errors/argument-error.mjs +8 -0
  49. package/dist/esm/resource-attribute-assignment.d.ts +16 -0
  50. package/dist/esm/resource-attribute-assignment.d.ts.map +1 -0
  51. package/dist/esm/resource-attribute-assignment.mjs +31 -0
  52. package/dist/esm/resource-attributes-constants.d.ts +25 -0
  53. package/dist/esm/resource-attributes-constants.d.ts.map +1 -0
  54. package/dist/esm/resource-attributes-constants.mjs +28 -0
  55. package/dist/esm/types/authorization-attributes-contracts.d.ts +26 -12
  56. package/dist/esm/types/authorization-attributes-contracts.d.ts.map +1 -1
  57. package/dist/esm/types/authorization-attributes-contracts.mjs +6 -6
  58. package/dist/esm/types/authorization-attributes-service.interface.d.ts +43 -0
  59. package/dist/esm/types/authorization-attributes-service.interface.d.ts.map +1 -0
  60. package/dist/esm/types/authorization-attributes-service.interface.mjs +1 -0
  61. package/dist/esm/types/general.d.ts +1 -1
  62. package/dist/esm/types/general.d.ts.map +1 -1
  63. package/dist/esm/utils/assigment-schema.d.ts +23 -0
  64. package/dist/esm/utils/assigment-schema.d.ts.map +1 -0
  65. package/dist/esm/utils/assigment-schema.mjs +29 -0
  66. package/dist/esm/utils/resource-schema.d.ts +17 -0
  67. package/dist/esm/utils/resource-schema.d.ts.map +1 -0
  68. package/dist/esm/utils/resource-schema.mjs +16 -0
  69. package/dist/esm/utils/validation.d.ts +26 -0
  70. package/dist/esm/utils/validation.d.ts.map +1 -0
  71. package/dist/esm/utils/validation.mjs +70 -0
  72. package/dist/resource-attribute-assignment.d.ts +16 -0
  73. package/dist/resource-attribute-assignment.d.ts.map +1 -0
  74. package/dist/resource-attribute-assignment.js +33 -0
  75. package/dist/resource-attributes-constants.d.ts +25 -0
  76. package/dist/resource-attributes-constants.d.ts.map +1 -0
  77. package/dist/resource-attributes-constants.js +31 -0
  78. package/dist/types/authorization-attributes-contracts.d.ts +26 -12
  79. package/dist/types/authorization-attributes-contracts.d.ts.map +1 -1
  80. package/dist/types/authorization-attributes-contracts.js +5 -5
  81. package/dist/types/authorization-attributes-service.interface.d.ts +43 -0
  82. package/dist/types/authorization-attributes-service.interface.d.ts.map +1 -0
  83. package/dist/types/authorization-attributes-service.interface.js +1 -0
  84. package/dist/types/general.d.ts +1 -1
  85. package/dist/types/general.d.ts.map +1 -1
  86. package/dist/utils/assigment-schema.d.ts +23 -0
  87. package/dist/utils/assigment-schema.d.ts.map +1 -0
  88. package/dist/utils/assigment-schema.js +36 -0
  89. package/dist/utils/resource-schema.d.ts +17 -0
  90. package/dist/utils/resource-schema.d.ts.map +1 -0
  91. package/dist/utils/resource-schema.js +22 -0
  92. package/dist/utils/validation.d.ts +26 -0
  93. package/dist/utils/validation.d.ts.map +1 -0
  94. package/dist/utils/validation.js +76 -0
  95. package/package.json +3 -1
  96. package/src/authorization-attributes-ms-service.ts +414 -0
  97. package/src/authorization-attributes-service.ts +34 -222
  98. package/src/authorization-attributes-sns-service.ts +257 -0
  99. package/src/base-attribute-assignment.ts +30 -0
  100. package/src/constants/sns.ts +19 -2
  101. package/src/entity-attribute-assignment.ts +33 -0
  102. package/src/entity-attributes-constants.ts +7 -0
  103. package/src/errors/argument-error.ts +6 -0
  104. package/src/resource-attribute-assignment.ts +36 -0
  105. package/src/resource-attributes-constants.ts +27 -0
  106. package/src/types/authorization-attributes-contracts.ts +34 -11
  107. package/src/types/authorization-attributes-service.interface.ts +70 -0
  108. package/src/types/general.ts +1 -1
  109. package/src/utils/assigment-schema.ts +29 -0
  110. package/src/utils/resource-schema.ts +21 -0
  111. package/src/utils/validation.ts +82 -0
@@ -0,0 +1,414 @@
1
+ import { Api, HttpClient } from '@mondaydotcomorg/trident-backend-api';
2
+ import { signAuthorizationHeader } from '@mondaydotcomorg/monday-jwt';
3
+ import { ResourceAttributeAssignment } from './resource-attribute-assignment';
4
+ import { EntityAttributeAssignment } from './entity-attribute-assignment';
5
+ import {
6
+ AttributeOperation,
7
+ ResourceAttributeOperation,
8
+ EntityAttributeOperation,
9
+ ResourceAttributeResponse,
10
+ } from './types/authorization-attributes-contracts';
11
+ import { EntityType } from './entity-attributes-constants';
12
+ import { AuthorizationInternalService, logger } from './authorization-internal-service';
13
+ import { getAttributionsFromApi } from './attributions-service';
14
+ import { APP_NAME } from './constants';
15
+ import { ValidationUtils } from './utils/validation';
16
+ import { AuthorizationAttributesService } from './types/authorization-attributes-service.interface';
17
+ import { Resource } from './types/general';
18
+
19
+ const INTERNAL_APP_NAME = 'internal_ms';
20
+ const UPSERT_RESOURCE_ATTRIBUTES_PATH = '/attributes/{accountId}/resource';
21
+ const DELETE_RESOURCE_ATTRIBUTES_PATH = '/attributes/{accountId}/resource/{resourceType}/{resourceId}';
22
+ const UPSERT_ENTITY_ATTRIBUTES_PATH = '/attributes/{accountId}/entity';
23
+ const DELETE_ENTITY_ATTRIBUTES_PATH = '/attributes/{accountId}/entity/{entityType}/{entityId}';
24
+
25
+ interface DeleteRequestBody {
26
+ keys: string[];
27
+ }
28
+
29
+ /**
30
+ * Service class for managing resource attributes in the authorization microservice.
31
+ * Provides synchronous HTTP operations to create/update and delete attributes on resources.
32
+ */
33
+ export class AuthorizationAttributesMsService implements AuthorizationAttributesService {
34
+ private static LOG_TAG = 'authorization_attributes_ms';
35
+ private static httpClient: HttpClient | undefined = Api.getPart('httpClient');
36
+
37
+ /**
38
+ * Deletes specific attributes from a resource synchronously.
39
+ * @param accountId The account ID
40
+ * @param resource Object with resourceType (string) and resourceId (number)
41
+ * @param attributeKeys Array of attribute key strings to delete
42
+ * @returns Promise<void>
43
+ */
44
+ async deleteResourceAttributes(
45
+ accountId: number,
46
+ resource: Resource,
47
+ attributeKeys: string[],
48
+ _appName?: string,
49
+ _callerActionIdentifier?: string
50
+ ): Promise<void> {
51
+ ValidationUtils.validateResource(resource);
52
+ return AuthorizationAttributesMsService.executeDeleteRequest(
53
+ accountId,
54
+ DELETE_RESOURCE_ATTRIBUTES_PATH,
55
+ {
56
+ resourceType: resource.type,
57
+ resourceId: resource.id,
58
+ },
59
+ attributeKeys,
60
+ 'resource',
61
+ 'deleteResourceAttributesSync'
62
+ );
63
+ }
64
+
65
+ /**
66
+ * Deletes specific attributes from an entity synchronously.
67
+ * @param accountId The account ID
68
+ * @param entityType The entity type
69
+ * @param entityId The entity ID
70
+ * @param attributeKeys Array of attribute key strings to delete
71
+ * @returns Promise<void>
72
+ */
73
+ async deleteEntityAttributes(
74
+ accountId: number,
75
+ entityType: EntityType,
76
+ entityId: number,
77
+ attributeKeys: string[],
78
+ _appName?: string,
79
+ _callerActionIdentifier?: string
80
+ ): Promise<void> {
81
+ ValidationUtils.validateInteger(accountId);
82
+ return AuthorizationAttributesMsService.executeDeleteRequest(
83
+ accountId,
84
+ DELETE_ENTITY_ATTRIBUTES_PATH,
85
+ {
86
+ entityType,
87
+ entityId,
88
+ },
89
+ attributeKeys,
90
+ 'entity',
91
+ 'deleteEntityAttributesSync'
92
+ );
93
+ }
94
+
95
+ /**
96
+ * Updates resource attributes (batch operations).
97
+ * Note: MS service does not support batch operations directly.
98
+ * This method processes operations sequentially using upsert/delete methods.
99
+ * @param accountId The account ID
100
+ * @param appName App name (required for interface compatibility, but not used in MS service)
101
+ * @param callerActionIdentifier Action identifier (required for interface compatibility, but not used in MS service)
102
+ * @param resourceAttributeOperations Array of operations to perform
103
+ * @returns Promise<ResourceAttributesOperation[]> Array of processed operations
104
+ */
105
+ async updateResourceAttributes(
106
+ accountId: number,
107
+ _appName: string,
108
+ _callerActionIdentifier: string,
109
+ resourceAttributeOperations: ResourceAttributeOperation[]
110
+ ): Promise<ResourceAttributeOperation[]> {
111
+ // Process all operations in parallel using Promise.all
112
+ await Promise.all(
113
+ resourceAttributeOperations.map(async operation => {
114
+ ValidationUtils.validateResourceAssignment({
115
+ resourceId: operation.resourceId,
116
+ resourceType: operation.resourceType,
117
+ key: operation.key,
118
+ value: operation.value || '',
119
+ });
120
+ if (operation.operationType === AttributeOperation.UPSERT) {
121
+ await this.upsertResourceAttributes(accountId, [
122
+ new ResourceAttributeAssignment(
123
+ operation.resourceId,
124
+ operation.resourceType,
125
+ operation.key,
126
+ operation.value || ''
127
+ ),
128
+ ]);
129
+ } else if (operation.operationType === AttributeOperation.DELETE) {
130
+ await this.deleteResourceAttributes(
131
+ accountId,
132
+ {
133
+ type: operation.resourceType,
134
+ id: operation.resourceId,
135
+ },
136
+ [operation.key]
137
+ );
138
+ }
139
+ })
140
+ );
141
+
142
+ return resourceAttributeOperations;
143
+ }
144
+
145
+ /**
146
+ * Updates entity attributes (batch operations).
147
+ * Note: MS service does not support batch operations directly.
148
+ * This method processes operations sequentially using upsert/delete methods.
149
+ * @param accountId The account ID
150
+ * @param appName App name (required for interface compatibility, but not used in MS service)
151
+ * @param callerActionIdentifier Action identifier (required for interface compatibility, but not used in MS service)
152
+ * @param entityAttributeOperations Array of operations to perform
153
+ * @returns Promise<EntityAttributesOperation[]> Array of processed operations
154
+ */
155
+ async updateEntityAttributes(
156
+ accountId: number,
157
+ _appName: string,
158
+ _callerActionIdentifier: string,
159
+ entityAttributeOperations: EntityAttributeOperation[]
160
+ ): Promise<EntityAttributeOperation[]> {
161
+ // Process all operations in parallel using Promise.all
162
+ await Promise.all(
163
+ entityAttributeOperations.map(async operation => {
164
+ // Validate before processing
165
+ ValidationUtils.validateEntityAssignment({
166
+ entityId: operation.entityId,
167
+ entityType: operation.entityType,
168
+ key: operation.key,
169
+ value: operation.value || '',
170
+ });
171
+
172
+ if (operation.operationType === 'upsert') {
173
+ await AuthorizationAttributesMsService.executeUpsertRequest(
174
+ accountId,
175
+ [
176
+ new EntityAttributeAssignment(
177
+ operation.entityId,
178
+ operation.entityType,
179
+ operation.key,
180
+ operation.value || ''
181
+ ),
182
+ ],
183
+ UPSERT_ENTITY_ATTRIBUTES_PATH,
184
+ 'entityAttributeAssignments',
185
+ 'entity',
186
+ 'upsertEntityAttributesSync'
187
+ );
188
+ } else if (operation.operationType === 'delete') {
189
+ await this.deleteEntityAttributes(accountId, operation.entityType, operation.entityId, [operation.key]);
190
+ }
191
+ })
192
+ );
193
+
194
+ return entityAttributeOperations;
195
+ }
196
+
197
+ /**
198
+ * Replaces path template parameters with actual values
199
+ * @param template Path template with placeholders like {accountId}
200
+ * @param params Object with parameter names and values
201
+ * @returns Path with all placeholders replaced
202
+ */
203
+ private static replacePathParams(template: string, params: Record<string, string | number>): string {
204
+ let path = template;
205
+ for (const [key, value] of Object.entries(params)) {
206
+ path = path.replace(`{${key}}`, String(value));
207
+ }
208
+ return path;
209
+ }
210
+
211
+ /**
212
+ * Generic helper for executing delete requests
213
+ */
214
+ private static async executeDeleteRequest(
215
+ accountId: number,
216
+ pathTemplate: string,
217
+ pathParams: Record<string, string | number>,
218
+ keys: string[],
219
+ logPrefix: string,
220
+ methodName: string
221
+ ): Promise<void> {
222
+ // Validate inputs
223
+ ValidationUtils.validateInteger(accountId);
224
+ ValidationUtils.validateStringArray(keys);
225
+
226
+ if (!keys.length) {
227
+ logger.warn({ tag: this.LOG_TAG, accountId, ...pathParams }, `${methodName} called with empty keys array`);
228
+ return;
229
+ }
230
+ const requestBody: DeleteRequestBody = { keys };
231
+
232
+ if (!AuthorizationAttributesMsService.httpClient) {
233
+ throw new Error('AuthorizationAttributesMsService: HTTP client is not initialized');
234
+ }
235
+ const path = AuthorizationAttributesMsService.replacePathParams(pathTemplate, { accountId, ...pathParams });
236
+ const headers = AuthorizationAttributesMsService.getRequestHeaders(accountId);
237
+
238
+ try {
239
+ logger.info(
240
+ { tag: AuthorizationAttributesMsService.LOG_TAG, accountId, ...pathParams, keys },
241
+ `Deleting ${logPrefix} attributes`
242
+ );
243
+
244
+ await AuthorizationAttributesMsService.httpClient.fetch(
245
+ {
246
+ url: {
247
+ appName: APP_NAME,
248
+ path,
249
+ },
250
+ method: 'DELETE',
251
+ headers,
252
+ body: JSON.stringify(requestBody),
253
+ },
254
+ {
255
+ timeout: AuthorizationInternalService.getRequestTimeout(),
256
+ retryPolicy: AuthorizationInternalService.getRetriesPolicy(),
257
+ }
258
+ );
259
+
260
+ logger.debug(
261
+ { tag: AuthorizationAttributesMsService.LOG_TAG, accountId, ...pathParams, keys },
262
+ `Successfully deleted ${logPrefix} attributes`
263
+ );
264
+ } catch (err) {
265
+ logger.error(
266
+ {
267
+ tag: AuthorizationAttributesMsService.LOG_TAG,
268
+ method: methodName,
269
+ accountId,
270
+ ...pathParams,
271
+ error: err instanceof Error ? err.message : String(err),
272
+ },
273
+ `Failed in ${methodName}`
274
+ );
275
+ throw err;
276
+ }
277
+ }
278
+
279
+ /**
280
+ * Gets request headers including Authorization, Content-Type, and optional attribution headers
281
+ */
282
+ private static getRequestHeaders(accountId: number, userId?: number): Record<string, string> {
283
+ const headers: Record<string, string> = {
284
+ 'Content-Type': 'application/json',
285
+ };
286
+
287
+ // Generate Authorization token
288
+ const authToken = signAuthorizationHeader({
289
+ appName: INTERNAL_APP_NAME,
290
+ accountId,
291
+ userId,
292
+ });
293
+ headers.Authorization = authToken;
294
+
295
+ // Add attribution headers if available
296
+ const attributionHeaders = getAttributionsFromApi();
297
+ for (const key in attributionHeaders) {
298
+ if (Object.prototype.hasOwnProperty.call(attributionHeaders, key)) {
299
+ headers[key] = attributionHeaders[key];
300
+ }
301
+ }
302
+
303
+ // Add X-REQUEST-ID if available from context
304
+ try {
305
+ const tridentContext = Api.getPart('context');
306
+ if (tridentContext?.runtimeAttributions) {
307
+ const outgoingHeaders = tridentContext.runtimeAttributions.buildOutgoingHeaders('HTTP_INTERNAL');
308
+ if (outgoingHeaders) {
309
+ const attributionHeadersMap: Record<string, string> = {};
310
+ for (const [key, value] of outgoingHeaders) {
311
+ attributionHeadersMap[key] = value;
312
+ }
313
+ if (attributionHeadersMap['x-request-id']) {
314
+ headers['X-REQUEST-ID'] = attributionHeadersMap['x-request-id'];
315
+ }
316
+ }
317
+ }
318
+ } catch (error) {
319
+ // Silently fail if context is not available
320
+ logger.debug({ tag: AuthorizationAttributesMsService.LOG_TAG, error }, 'Failed to get request ID from context');
321
+ }
322
+
323
+ // Add X-REQUEST-START timestamp
324
+ headers['X-REQUEST-START'] = Math.floor(Date.now() / 1000).toString();
325
+
326
+ return headers;
327
+ }
328
+
329
+ /**
330
+ * Generic helper for executing upsert requests
331
+ */
332
+ private static async executeUpsertRequest<T extends ResourceAttributeAssignment | EntityAttributeAssignment>(
333
+ accountId: number,
334
+ assignments: T[],
335
+ pathTemplate: string,
336
+ requestBodyKey: 'resourceAttributeAssignments' | 'entityAttributeAssignments',
337
+ logPrefix: string,
338
+ methodName: string
339
+ ): Promise<void> {
340
+ const assignmentDto = assignments.map(assignment => assignment.toDataTransferObject());
341
+
342
+ const requestBody =
343
+ requestBodyKey === 'resourceAttributeAssignments'
344
+ ? { resourceAttributeAssignments: assignmentDto }
345
+ : { entityAttributeAssignments: assignmentDto };
346
+
347
+ if (!AuthorizationAttributesMsService.httpClient) {
348
+ throw new Error('AuthorizationAttributesMsService: HTTP client is not initialized');
349
+ }
350
+ const path = AuthorizationAttributesMsService.replacePathParams(pathTemplate, { accountId });
351
+ const headers = AuthorizationAttributesMsService.getRequestHeaders(accountId);
352
+
353
+ try {
354
+ logger.info(
355
+ { tag: AuthorizationAttributesMsService.LOG_TAG, accountId, count: assignments.length },
356
+ `Upserting ${logPrefix} attributes`
357
+ );
358
+
359
+ await AuthorizationAttributesMsService.httpClient.fetch(
360
+ {
361
+ url: {
362
+ appName: APP_NAME,
363
+ path,
364
+ },
365
+ method: 'POST',
366
+ headers,
367
+ body: JSON.stringify(requestBody),
368
+ },
369
+ {
370
+ timeout: AuthorizationInternalService.getRequestTimeout(),
371
+ retryPolicy: AuthorizationInternalService.getRetriesPolicy(),
372
+ }
373
+ );
374
+
375
+ logger.debug(
376
+ { tag: AuthorizationAttributesMsService.LOG_TAG, accountId, count: assignments.length },
377
+ `Successfully upserted ${logPrefix} attributes`
378
+ );
379
+ } catch (err) {
380
+ logger.error(
381
+ {
382
+ tag: AuthorizationAttributesMsService.LOG_TAG,
383
+ method: methodName,
384
+ accountId,
385
+ error: err instanceof Error ? err.message : String(err),
386
+ },
387
+ `Failed in ${methodName}`
388
+ );
389
+ throw err;
390
+ }
391
+ }
392
+
393
+ private async upsertResourceAttributes(
394
+ accountId: number,
395
+ resourceAttributeAssignments: ResourceAttributeAssignment[]
396
+ ): Promise<ResourceAttributeResponse> {
397
+ const attributionHeaders = getAttributionsFromApi();
398
+ if (!AuthorizationAttributesMsService.httpClient) {
399
+ throw new Error('AuthorizationAttributesMsService: HTTP client is not initialized');
400
+ }
401
+ return await AuthorizationAttributesMsService.httpClient.fetch<ResourceAttributeResponse>({
402
+ url: {
403
+ appName: APP_NAME,
404
+ path: UPSERT_RESOURCE_ATTRIBUTES_PATH.replace('{accountId}', accountId.toString()),
405
+ },
406
+ method: 'POST',
407
+ headers: {
408
+ 'Content-Type': 'application/json',
409
+ ...attributionHeaders,
410
+ },
411
+ body: JSON.stringify({ resourceAttributeAssignments }),
412
+ });
413
+ }
414
+ }
@@ -1,234 +1,46 @@
1
- import chunk from 'lodash/chunk.js';
2
- import { Api, FetcherConfig, HttpClient } from '@mondaydotcomorg/trident-backend-api';
3
- import { getTopicAttributes, sendToSns } from '@mondaydotcomorg/monday-sns';
4
- import { HttpFetcherError, RecursivePartial } from '@mondaydotcomorg/monday-fetch-api';
5
- import {
6
- ResourceAttributeAssignment,
7
- ResourceAttributeResponse,
8
- ResourceAttributesOperation,
9
- } from './types/authorization-attributes-contracts';
10
- import { Resource } from './types/general';
11
- import { logger } from './authorization-internal-service';
12
- import { getAttributionsFromApi } from './attributions-service';
13
- import {
14
- ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE,
15
- RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND,
16
- SNS_ARN_ENV_VAR_NAME,
17
- SNS_DEV_TEST_NAME,
18
- } from './constants/sns';
19
- import { APP_NAME, DEFAULT_FETCH_OPTIONS, ERROR_MESSAGES } from './constants';
20
- import type { TopicAttributesMap } from 'aws-sdk/clients/sns';
21
-
1
+ import { AuthorizationAttributesMsService } from './authorization-attributes-ms-service';
2
+ import { AuthorizationAttributesSnsService } from './authorization-attributes-sns-service';
3
+ import { AuthorizationAttributesService as IAuthorizationAttributesService } from './types/authorization-attributes-service.interface';
4
+
5
+ /**
6
+ * Main service class for managing resource and entity attributes.
7
+ * Provides access to both direct (MS) and SNS operations.
8
+ *
9
+ * @example
10
+ * const service = new AuthorizationAttributesService();
11
+ *
12
+ * // Use direct operations
13
+ * await service.direct().upsertResourceAttributes(accountId, assignments);
14
+ *
15
+ * // Use SNS operations
16
+ * await service.sns().upsertResourceAttributes(accountId, assignments, appName, actionId);
17
+ * ```
18
+ */
22
19
  export class AuthorizationAttributesService {
23
- private static LOG_TAG = 'authorization_attributes';
24
- private static API_PATHS = {
25
- UPSERT_RESOURCE_ATTRIBUTES: '/attributes/{accountId}/resource',
26
- DELETE_RESOURCE_ATTRIBUTES: '/attributes/{accountId}/resource/{resourceType}/{resourceId}',
27
- } as const;
28
- private httpClient: HttpClient;
29
- private fetchOptions: RecursivePartial<FetcherConfig>;
30
- private snsArn: string;
31
-
32
- /**
33
- * Public constructor to create the AuthorizationAttributesService instance.
34
- * @param httpClient The HTTP client to use for API requests, if not provided, the default HTTP client from Api will be used.
35
- * @param fetchOptions The fetch options to use for API requests, if not provided, the default fetch options will be used.
36
- */
37
- constructor(httpClient?: HttpClient, fetchOptions?: RecursivePartial<FetcherConfig>) {
38
- if (!httpClient) {
39
- httpClient = Api.getPart('httpClient');
40
- if (!httpClient) {
41
- throw new Error(ERROR_MESSAGES.HTTP_CLIENT_NOT_INITIALIZED);
42
- }
43
- }
44
-
45
- if (!fetchOptions) {
46
- fetchOptions = DEFAULT_FETCH_OPTIONS;
47
- } else {
48
- fetchOptions = {
49
- ...DEFAULT_FETCH_OPTIONS,
50
- ...fetchOptions,
51
- };
52
- }
53
- this.httpClient = httpClient;
54
- this.fetchOptions = fetchOptions;
55
- this.snsArn = AuthorizationAttributesService.getSnsTopicArn();
56
- }
57
-
58
- /**
59
- * Upsert resource attributes synchronously, performing http call to the authorization MS to assign the given attributes to the given resource.
60
- * @param accountId
61
- * @param resourceAttributeAssignments - Array of resource (resourceType, resourceId) and attribute (key, value) pairs to upsert in the authorization MS.
62
- * e.g. [{ resourceType: 'board', resourceId: 123, key: 'board_kind', value: 'private' }]
63
- * @returns ResourceAttributeResponse - The affected (created and updated_ resource attributes assignments in the `attributes` field.
64
- */
65
- async upsertResourceAttributes(
66
- accountId: number,
67
- resourceAttributeAssignments: ResourceAttributeAssignment[]
68
- ): Promise<ResourceAttributeResponse> {
69
- const attributionHeaders = getAttributionsFromApi();
70
- try {
71
- return await this.httpClient.fetch<ResourceAttributeResponse>(
72
- {
73
- url: {
74
- appName: APP_NAME,
75
- path: AuthorizationAttributesService.API_PATHS.UPSERT_RESOURCE_ATTRIBUTES.replace(
76
- '{accountId}',
77
- accountId.toString()
78
- ),
79
- },
80
- method: 'POST',
81
- headers: {
82
- 'Content-Type': 'application/json',
83
- ...attributionHeaders,
84
- },
85
- body: JSON.stringify({ resourceAttributeAssignments }),
86
- },
87
- this.fetchOptions
88
- );
89
- } catch (err) {
90
- if (err instanceof HttpFetcherError) {
91
- throw new Error(ERROR_MESSAGES.REQUEST_FAILED('upsertResourceAttributes', err.status, err.message));
92
- }
93
- throw err;
94
- }
95
- }
20
+ private _directService: AuthorizationAttributesMsService | null = null;
21
+ private _snsService: AuthorizationAttributesSnsService | null = null;
96
22
 
97
23
  /**
98
- * Delete resource attributes assignments synchronously, performing http call to the authorization MS to delete the given attributes from the given singular resource.
99
- * @param accountId
100
- * @param resource - The resource (resourceType, resourceId) to delete the attributes for.
101
- * @param attributeKeys - Array of attribute keys to delete for the resource.
102
- * @returns ResourceAttributeResponse - The affected (deleted) resource attributes assignments in the `attributes` field.
24
+ * Gets the direct (MS) service instance.
25
+ * Initializes the service on first access (lazy initialization).
26
+ * @returns IAuthorizationAttributesService instance
103
27
  */
104
- async deleteResourceAttributes(
105
- accountId: number,
106
- resource: Resource,
107
- attributeKeys: string[]
108
- ): Promise<ResourceAttributeResponse> {
109
- const attributionHeaders = getAttributionsFromApi();
110
- if (!resource.id) {
111
- throw new Error('Resource ID is required');
112
- }
113
- try {
114
- return await this.httpClient.fetch<ResourceAttributeResponse>(
115
- {
116
- url: {
117
- appName: APP_NAME,
118
- path: AuthorizationAttributesService.API_PATHS.DELETE_RESOURCE_ATTRIBUTES.replace(
119
- '{accountId}',
120
- accountId.toString()
121
- )
122
- .replace('{resourceType}', resource.type)
123
- .replace('{resourceId}', resource.id.toString()),
124
- },
125
- method: 'DELETE',
126
- headers: {
127
- 'Content-Type': 'application/json',
128
- ...attributionHeaders,
129
- },
130
- body: JSON.stringify({ keys: attributeKeys }),
131
- },
132
- this.fetchOptions
133
- );
134
- } catch (err) {
135
- if (err instanceof HttpFetcherError) {
136
- throw new Error(ERROR_MESSAGES.REQUEST_FAILED('deleteResourceAttributes', err.status, err.message));
137
- }
138
- throw err;
139
- }
140
- }
141
-
142
- /**
143
- * Async function, this function only send the updates request to SNS and return before the change actually took place
144
- * @param accountId
145
- * @param appName - App name of the calling app
146
- * @param callerActionIdentifier - action identifier
147
- * @param resourceAttributeOperations - Array of operations to do on resource attributes.
148
- * @return {Promise<ResourceAttributesOperation[]>} Array of sent operations
149
- * */
150
- async updateResourceAttributesAsync(
151
- accountId: number,
152
- appName: string,
153
- callerActionIdentifier: string,
154
- resourceAttributeOperations: ResourceAttributesOperation[]
155
- ): Promise<ResourceAttributesOperation[]> {
156
- const topicArn: string = this.snsArn;
157
- const sendToSnsPromises: Promise<ResourceAttributesOperation[]>[] = [];
158
- const operationChucks = chunk(resourceAttributeOperations, ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE);
159
- for (const operationsChunk of operationChucks) {
160
- sendToSnsPromises.push(
161
- this.sendSingleSnsMessage(topicArn, accountId, appName, callerActionIdentifier, operationsChunk)
162
- );
163
- }
164
- return (await Promise.all(sendToSnsPromises)).flat();
165
- }
166
-
167
- private async sendSingleSnsMessage(
168
- topicArn: string,
169
- accountId: number,
170
- appName: string,
171
- callerActionIdentifier: string,
172
- operations: ResourceAttributesOperation[]
173
- ): Promise<ResourceAttributesOperation[]> {
174
- const payload = {
175
- kind: RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND,
176
- payload: {
177
- accountId: accountId,
178
- callerAppName: appName,
179
- callerActionIdentifier: callerActionIdentifier,
180
- operations: operations,
181
- },
182
- };
183
- try {
184
- await sendToSns(payload, topicArn);
185
- return operations;
186
- } catch (error) {
187
- logger.error(
188
- { error, tag: AuthorizationAttributesService.LOG_TAG },
189
- 'Authorization resource attributes async update: failed to send operations to SNS'
190
- );
191
- return [];
192
- }
193
- }
194
-
195
- private static getSnsTopicArn(): string {
196
- const arnFromEnv: string | undefined = process.env[SNS_ARN_ENV_VAR_NAME];
197
- if (arnFromEnv) {
198
- return arnFromEnv;
199
- }
200
- if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
201
- return SNS_DEV_TEST_NAME;
28
+ direct(): IAuthorizationAttributesService {
29
+ if (this._directService === null) {
30
+ this._directService = new AuthorizationAttributesMsService();
202
31
  }
203
- throw new Error('Unable to get sns topic arn from env variable');
32
+ return this._directService;
204
33
  }
205
34
 
206
35
  /**
207
- * Checks we can contact the required SNS topic that used to send attribute updates to Authorization MS.
208
- * This function can be used as health check for services that updating resource attributes in async is crucial.
209
- * Note this function only verify the POD can contact AWS SDK and the topic exists, but the user still might get
210
- * errors when pushing for the SNS (e.g: in case the AWS role of the POD don't have permissions to push messages).
211
- * However, this is the best we can do without actually push dummy messages to the SNS.
212
- * @return {Promise<boolean>} - true if succeeded
36
+ * Gets the SNS service instance.
37
+ * Initializes the service on first access (lazy initialization).
38
+ * @returns IAuthorizationAttributesService instance
213
39
  */
214
- async asyncResourceAttributesHealthCheck(): Promise<boolean> {
215
- try {
216
- const requestedTopicArn: string = this.snsArn;
217
- const attributes: TopicAttributesMap = await getTopicAttributes(requestedTopicArn);
218
- const isHealthy = !(!attributes || !('TopicArn' in attributes) || attributes.TopicArn !== requestedTopicArn);
219
- if (!isHealthy) {
220
- logger.error(
221
- { requestedTopicArn, snsReturnedAttributes: attributes, tag: AuthorizationAttributesService.LOG_TAG },
222
- 'authorization-attributes-service failed in health check'
223
- );
224
- }
225
- return isHealthy;
226
- } catch (error) {
227
- logger.error(
228
- { error, tag: AuthorizationAttributesService.LOG_TAG },
229
- 'authorization-attributes-service got error during health check'
230
- );
231
- return false;
40
+ sns(): IAuthorizationAttributesService {
41
+ if (this._snsService === null) {
42
+ this._snsService = new AuthorizationAttributesSnsService();
232
43
  }
44
+ return this._snsService;
233
45
  }
234
46
  }