@mondaydotcomorg/monday-authorization 3.6.0-feat-shaime-support-entity-attributes-1-4c8e283 → 3.6.0-feat-shaime-support-entity-attributes-3-78dca48

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 (96) hide show
  1. package/dist/authorization-attributes-ms-service.d.ts +68 -0
  2. package/dist/authorization-attributes-ms-service.d.ts.map +1 -0
  3. package/dist/authorization-attributes-ms-service.js +263 -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 -172
  7. package/dist/authorization-attributes-sns-service.d.ts +84 -0
  8. package/dist/authorization-attributes-sns-service.d.ts.map +1 -0
  9. package/dist/authorization-attributes-sns-service.js +196 -0
  10. package/dist/constants/sns.d.ts +12 -2
  11. package/dist/constants/sns.d.ts.map +1 -1
  12. package/dist/constants/sns.js +22 -2
  13. package/dist/entity-attribute-assignment.d.ts.map +1 -1
  14. package/dist/entity-attribute-assignment.js +0 -2
  15. package/dist/esm/authorization-attributes-ms-service.d.ts +68 -0
  16. package/dist/esm/authorization-attributes-ms-service.d.ts.map +1 -0
  17. package/dist/esm/authorization-attributes-ms-service.mjs +261 -0
  18. package/dist/esm/authorization-attributes-service.d.ts +25 -47
  19. package/dist/esm/authorization-attributes-service.d.ts.map +1 -1
  20. package/dist/esm/authorization-attributes-service.mjs +32 -168
  21. package/dist/esm/authorization-attributes-sns-service.d.ts +84 -0
  22. package/dist/esm/authorization-attributes-sns-service.d.ts.map +1 -0
  23. package/dist/esm/authorization-attributes-sns-service.mjs +190 -0
  24. package/dist/esm/constants/sns.d.ts +12 -2
  25. package/dist/esm/constants/sns.d.ts.map +1 -1
  26. package/dist/esm/constants/sns.mjs +17 -3
  27. package/dist/esm/entity-attribute-assignment.d.ts.map +1 -1
  28. package/dist/esm/entity-attribute-assignment.mjs +0 -2
  29. package/dist/esm/index.d.ts +2 -0
  30. package/dist/esm/index.d.ts.map +1 -1
  31. package/dist/esm/index.mjs +2 -0
  32. package/dist/esm/resource-attribute-assignment.d.ts.map +1 -1
  33. package/dist/esm/resource-attribute-assignment.mjs +0 -2
  34. package/dist/esm/resource-attributes-constants.d.ts +2 -1
  35. package/dist/esm/resource-attributes-constants.d.ts.map +1 -1
  36. package/dist/esm/resource-attributes-constants.mjs +1 -0
  37. package/dist/esm/types/authorization-attributes-contracts.d.ts +2 -0
  38. package/dist/esm/types/authorization-attributes-contracts.d.ts.map +1 -1
  39. package/dist/esm/types/authorization-attributes-service.interface.d.ts +14 -25
  40. package/dist/esm/types/authorization-attributes-service.interface.d.ts.map +1 -1
  41. package/dist/esm/types/general.d.ts +4 -3
  42. package/dist/esm/types/general.d.ts.map +1 -1
  43. package/dist/esm/utils/assignment-schema.d.ts +51 -0
  44. package/dist/esm/utils/assignment-schema.d.ts.map +1 -0
  45. package/dist/esm/utils/assignment-schema.mjs +49 -0
  46. package/dist/esm/utils/resource-schema.d.ts +9 -0
  47. package/dist/esm/utils/resource-schema.d.ts.map +1 -0
  48. package/dist/esm/utils/resource-schema.mjs +16 -0
  49. package/dist/esm/utils/validation.d.ts +11 -3
  50. package/dist/esm/utils/validation.d.ts.map +1 -1
  51. package/dist/esm/utils/validation.mjs +50 -13
  52. package/dist/index.d.ts +2 -0
  53. package/dist/index.d.ts.map +1 -1
  54. package/dist/index.js +13 -0
  55. package/dist/resource-attribute-assignment.d.ts.map +1 -1
  56. package/dist/resource-attribute-assignment.js +0 -2
  57. package/dist/resource-attributes-constants.d.ts +2 -1
  58. package/dist/resource-attributes-constants.d.ts.map +1 -1
  59. package/dist/resource-attributes-constants.js +1 -0
  60. package/dist/types/authorization-attributes-contracts.d.ts +2 -0
  61. package/dist/types/authorization-attributes-contracts.d.ts.map +1 -1
  62. package/dist/types/authorization-attributes-service.interface.d.ts +14 -25
  63. package/dist/types/authorization-attributes-service.interface.d.ts.map +1 -1
  64. package/dist/types/general.d.ts +4 -3
  65. package/dist/types/general.d.ts.map +1 -1
  66. package/dist/utils/assignment-schema.d.ts +51 -0
  67. package/dist/utils/assignment-schema.d.ts.map +1 -0
  68. package/dist/utils/assignment-schema.js +58 -0
  69. package/dist/utils/resource-schema.d.ts +9 -0
  70. package/dist/utils/resource-schema.d.ts.map +1 -0
  71. package/dist/utils/resource-schema.js +22 -0
  72. package/dist/utils/validation.d.ts +11 -3
  73. package/dist/utils/validation.d.ts.map +1 -1
  74. package/dist/utils/validation.js +50 -13
  75. package/package.json +1 -1
  76. package/src/authorization-attributes-ms-service.ts +397 -0
  77. package/src/authorization-attributes-service.ts +34 -223
  78. package/src/authorization-attributes-sns-service.ts +321 -0
  79. package/src/constants/sns.ts +19 -2
  80. package/src/entity-attribute-assignment.ts +0 -2
  81. package/src/index.ts +2 -0
  82. package/src/resource-attribute-assignment.ts +0 -2
  83. package/src/resource-attributes-constants.ts +1 -0
  84. package/src/types/authorization-attributes-contracts.ts +2 -0
  85. package/src/types/authorization-attributes-service.interface.ts +19 -31
  86. package/src/types/general.ts +4 -3
  87. package/src/utils/assignment-schema.ts +51 -0
  88. package/src/utils/resource-schema.ts +16 -0
  89. package/src/utils/validation.ts +76 -15
  90. package/dist/esm/utils/assigment-schema.d.ts +0 -29
  91. package/dist/esm/utils/assigment-schema.d.ts.map +0 -1
  92. package/dist/esm/utils/assigment-schema.mjs +0 -29
  93. package/dist/utils/assigment-schema.d.ts +0 -29
  94. package/dist/utils/assigment-schema.d.ts.map +0 -1
  95. package/dist/utils/assigment-schema.js +0 -36
  96. package/src/utils/assigment-schema.ts +0 -29
@@ -0,0 +1,261 @@
1
+ import { Api } from '@mondaydotcomorg/trident-backend-api';
2
+ import { signAuthorizationHeader } from '@mondaydotcomorg/monday-jwt';
3
+ import { ResourceAttributeAssignment } from './resource-attribute-assignment.mjs';
4
+ import { EntityAttributeAssignment } from './entity-attribute-assignment.mjs';
5
+ import { AttributeOperation } from './types/authorization-attributes-contracts.mjs';
6
+ import { logger, AuthorizationInternalService } from './authorization-internal-service.mjs';
7
+ import { getAttributionsFromApi } from './attributions-service.mjs';
8
+ import { APP_NAME } from './constants.mjs';
9
+ import { ValidationUtils } from './utils/validation.mjs';
10
+
11
+ const INTERNAL_APP_NAME = 'internal_ms';
12
+ const UPSERT_RESOURCE_ATTRIBUTES_PATH = '/attributes/{accountId}/resource';
13
+ const DELETE_RESOURCE_ATTRIBUTES_PATH = '/attributes/{accountId}/resource/{resourceType}/{resourceId}';
14
+ const UPSERT_ENTITY_ATTRIBUTES_PATH = '/attributes/{accountId}/entity';
15
+ const DELETE_ENTITY_ATTRIBUTES_PATH = '/attributes/{accountId}/entity/{entityType}/{entityId}';
16
+ /**
17
+ * Service class for managing resource attributes in the authorization microservice.
18
+ * Provides synchronous HTTP operations to create/update and delete attributes on resources.
19
+ */
20
+ class AuthorizationAttributesMsService {
21
+ static LOG_TAG = 'authorization_attributes_ms';
22
+ static httpClient = Api.getPart('httpClient');
23
+ constructor() {
24
+ if (!AuthorizationAttributesMsService.httpClient) {
25
+ AuthorizationAttributesMsService.httpClient = Api.getPart('httpClient');
26
+ if (!AuthorizationAttributesMsService.httpClient) {
27
+ throw new Error('HTTP client is not initialized');
28
+ }
29
+ }
30
+ }
31
+ /**
32
+ * Deletes a specific attribute from a resource synchronously.
33
+ * @param accountId The account ID
34
+ * @param resource Object with resourceType (string) and resourceId (number)
35
+ * @param attributeKey Attribute key string to delete
36
+ * @returns Promise<ResourceAttributeDeleteOperation>
37
+ */
38
+ async deleteResourceAttributes(accountId, resource, attributeKey, _appName, _callerActionIdentifier) {
39
+ ValidationUtils.validateResource(resource);
40
+ ValidationUtils.validatDeleteResourceAssignment({
41
+ resourceType: resource.type,
42
+ resourceId: resource.id,
43
+ key: attributeKey,
44
+ });
45
+ await AuthorizationAttributesMsService.executeDeleteRequest(accountId, DELETE_RESOURCE_ATTRIBUTES_PATH, {
46
+ resourceType: resource.type,
47
+ resourceId: resource.id,
48
+ }, [attributeKey], 'resource', 'deleteResourceAttributesSync');
49
+ return {
50
+ resourceType: resource.type,
51
+ resourceId: resource.id,
52
+ key: attributeKey,
53
+ operationType: AttributeOperation.DELETE,
54
+ };
55
+ }
56
+ /**
57
+ * Deletes a specific attribute from an entity synchronously.
58
+ * @param accountId The account ID
59
+ * @param entityType The entity type
60
+ * @param entityId The entity ID
61
+ * @param attributeKey Attribute key string to delete
62
+ * @returns Promise<EntityAttributeDeleteOperation>
63
+ */
64
+ async deleteEntityAttributes(accountId, entityType, entityId, attributeKey, _appName, _callerActionIdentifier) {
65
+ ValidationUtils.validateInteger(accountId);
66
+ await AuthorizationAttributesMsService.executeDeleteRequest(accountId, DELETE_ENTITY_ATTRIBUTES_PATH, {
67
+ entityType,
68
+ entityId,
69
+ }, [attributeKey], 'entity', 'deleteEntityAttributesSync');
70
+ return {
71
+ entityType,
72
+ entityId,
73
+ key: attributeKey,
74
+ operationType: AttributeOperation.DELETE,
75
+ };
76
+ }
77
+ /**
78
+ * Updates a resource attribute (single operation - upsert only).
79
+ * @param accountId The account ID
80
+ * @param appName App name (required for interface compatibility, but not used in MS service)
81
+ * @param callerActionIdentifier Action identifier (required for interface compatibility, but not used in MS service)
82
+ * @param resourceAttributeOperation Operation to perform (must be UPSERT)
83
+ * @returns Promise<ResourceAttributeUpsertOperation> Processed operation
84
+ */
85
+ async updateResourceAttributes(accountId, _appName, _callerActionIdentifier, resourceAttributeOperation) {
86
+ ValidationUtils.validatUpsertResourceAssignment({
87
+ resourceId: resourceAttributeOperation.resourceId,
88
+ resourceType: resourceAttributeOperation.resourceType,
89
+ key: resourceAttributeOperation.key,
90
+ value: resourceAttributeOperation.value,
91
+ });
92
+ await AuthorizationAttributesMsService.executeUpsertRequest(accountId, [
93
+ new ResourceAttributeAssignment(resourceAttributeOperation.resourceId, resourceAttributeOperation.resourceType, resourceAttributeOperation.key, resourceAttributeOperation.value || ''),
94
+ ], UPSERT_RESOURCE_ATTRIBUTES_PATH, 'resourceAttributeAssignments', 'resource', 'updateResourceAttributesSync');
95
+ return resourceAttributeOperation;
96
+ }
97
+ /**
98
+ * Updates an entity attribute (single operation - upsert only).
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 entityAttributeOperation Operation to perform (must be UPSERT)
103
+ * @returns Promise<EntityAttributeUpsertOperation> Processed operation
104
+ */
105
+ async updateEntityAttributes(accountId, _appName, _callerActionIdentifier, entityAttributeOperation) {
106
+ // Validate before processing
107
+ ValidationUtils.validatUpsertEntityAssignment({
108
+ entityId: entityAttributeOperation.entityId,
109
+ entityType: entityAttributeOperation.entityType,
110
+ key: entityAttributeOperation.key,
111
+ value: entityAttributeOperation.value,
112
+ });
113
+ await AuthorizationAttributesMsService.executeUpsertRequest(accountId, [
114
+ new EntityAttributeAssignment(entityAttributeOperation.entityId, entityAttributeOperation.entityType, entityAttributeOperation.key, entityAttributeOperation.value),
115
+ ], UPSERT_ENTITY_ATTRIBUTES_PATH, 'entityAttributeAssignments', 'entity', 'upsertEntityAttributesSync');
116
+ return entityAttributeOperation;
117
+ }
118
+ /**
119
+ * Replaces path template parameters with actual values
120
+ * @param template Path template with placeholders like {accountId}
121
+ * @param params Object with parameter names and values
122
+ * @returns Path with all placeholders replaced
123
+ */
124
+ static replacePathParams(template, params) {
125
+ let path = template;
126
+ for (const [key, value] of Object.entries(params)) {
127
+ path = path.replace(`{${key}}`, String(value));
128
+ }
129
+ return path;
130
+ }
131
+ /**
132
+ * Generic helper for executing delete requests
133
+ */
134
+ static async executeDeleteRequest(accountId, pathTemplate, pathParams, keys, logPrefix, methodName) {
135
+ // Validate inputs
136
+ ValidationUtils.validateInteger(accountId);
137
+ ValidationUtils.validateStringArray(keys);
138
+ if (!keys.length) {
139
+ logger.warn({ tag: this.LOG_TAG, accountId, ...pathParams }, `${methodName} called with empty keys array`);
140
+ return;
141
+ }
142
+ const requestBody = { keys };
143
+ if (!AuthorizationAttributesMsService.httpClient) {
144
+ throw new Error('AuthorizationAttributesMsService: HTTP client is not initialized');
145
+ }
146
+ const path = AuthorizationAttributesMsService.replacePathParams(pathTemplate, { accountId, ...pathParams });
147
+ const headers = AuthorizationAttributesMsService.getRequestHeaders(accountId);
148
+ try {
149
+ logger.info({ tag: AuthorizationAttributesMsService.LOG_TAG, accountId, ...pathParams, keys }, `Deleting ${logPrefix} attributes`);
150
+ await AuthorizationAttributesMsService.httpClient.fetch({
151
+ url: {
152
+ appName: APP_NAME,
153
+ path,
154
+ },
155
+ method: 'DELETE',
156
+ headers,
157
+ body: JSON.stringify(requestBody),
158
+ }, {
159
+ timeout: AuthorizationInternalService.getRequestTimeout(),
160
+ retryPolicy: AuthorizationInternalService.getRetriesPolicy(),
161
+ });
162
+ logger.debug({ tag: AuthorizationAttributesMsService.LOG_TAG, accountId, ...pathParams, keys }, `Successfully deleted ${logPrefix} attributes`);
163
+ }
164
+ catch (err) {
165
+ logger.error({
166
+ tag: AuthorizationAttributesMsService.LOG_TAG,
167
+ method: methodName,
168
+ accountId,
169
+ ...pathParams,
170
+ error: err instanceof Error ? err.message : String(err),
171
+ }, `Failed in ${methodName}`);
172
+ throw err;
173
+ }
174
+ }
175
+ /**
176
+ * Gets request headers including Authorization, Content-Type, and optional attribution headers
177
+ */
178
+ static getRequestHeaders(accountId, userId) {
179
+ const headers = {
180
+ 'Content-Type': 'application/json',
181
+ };
182
+ // Generate Authorization token
183
+ const authToken = signAuthorizationHeader({
184
+ appName: INTERNAL_APP_NAME,
185
+ accountId,
186
+ userId,
187
+ });
188
+ headers.Authorization = authToken;
189
+ // Add attribution headers if available
190
+ const attributionHeaders = getAttributionsFromApi();
191
+ for (const key in attributionHeaders) {
192
+ if (Object.prototype.hasOwnProperty.call(attributionHeaders, key)) {
193
+ headers[key] = attributionHeaders[key];
194
+ }
195
+ }
196
+ // Add X-REQUEST-ID if available from context
197
+ try {
198
+ const tridentContext = Api.getPart('context');
199
+ if (tridentContext?.runtimeAttributions) {
200
+ const outgoingHeaders = tridentContext.runtimeAttributions.buildOutgoingHeaders('HTTP_INTERNAL');
201
+ if (outgoingHeaders) {
202
+ const attributionHeadersMap = {};
203
+ for (const [key, value] of outgoingHeaders) {
204
+ attributionHeadersMap[key] = value;
205
+ }
206
+ if (attributionHeadersMap['x-request-id']) {
207
+ headers['X-REQUEST-ID'] = attributionHeadersMap['x-request-id'];
208
+ }
209
+ }
210
+ }
211
+ }
212
+ catch (error) {
213
+ // Silently fail if context is not available
214
+ logger.debug({ tag: AuthorizationAttributesMsService.LOG_TAG, error }, 'Failed to get request ID from context');
215
+ }
216
+ // Add X-REQUEST-START timestamp
217
+ headers['X-REQUEST-START'] = Math.floor(Date.now() / 1000).toString();
218
+ return headers;
219
+ }
220
+ /**
221
+ * Generic helper for executing upsert requests
222
+ */
223
+ static async executeUpsertRequest(accountId, assignments, pathTemplate, requestBodyKey, logPrefix, methodName) {
224
+ const assignmentDto = assignments.map(assignment => assignment.toDataTransferObject());
225
+ const requestBody = requestBodyKey === 'resourceAttributeAssignments'
226
+ ? { resourceAttributeAssignments: assignmentDto }
227
+ : { entityAttributeAssignments: assignmentDto };
228
+ if (!AuthorizationAttributesMsService.httpClient) {
229
+ throw new Error('AuthorizationAttributesMsService: HTTP client is not initialized');
230
+ }
231
+ const path = AuthorizationAttributesMsService.replacePathParams(pathTemplate, { accountId });
232
+ const headers = AuthorizationAttributesMsService.getRequestHeaders(accountId);
233
+ try {
234
+ logger.info({ tag: AuthorizationAttributesMsService.LOG_TAG, accountId, count: assignments.length }, `Upserting ${logPrefix} attributes`);
235
+ await AuthorizationAttributesMsService.httpClient.fetch({
236
+ url: {
237
+ appName: APP_NAME,
238
+ path,
239
+ },
240
+ method: 'POST',
241
+ headers,
242
+ body: JSON.stringify(requestBody),
243
+ }, {
244
+ timeout: AuthorizationInternalService.getRequestTimeout(),
245
+ retryPolicy: AuthorizationInternalService.getRetriesPolicy(),
246
+ });
247
+ logger.debug({ tag: AuthorizationAttributesMsService.LOG_TAG, accountId, count: assignments.length }, `Successfully upserted ${logPrefix} attributes`);
248
+ }
249
+ catch (err) {
250
+ logger.error({
251
+ tag: AuthorizationAttributesMsService.LOG_TAG,
252
+ method: methodName,
253
+ accountId,
254
+ error: err instanceof Error ? err.message : String(err),
255
+ }, `Failed in ${methodName}`);
256
+ throw err;
257
+ }
258
+ }
259
+ }
260
+
261
+ export { AuthorizationAttributesMsService };
@@ -1,54 +1,32 @@
1
- import { FetcherConfig, HttpClient } from '@mondaydotcomorg/trident-backend-api';
2
- import { RecursivePartial } from '@mondaydotcomorg/monday-fetch-api';
3
- import { ResourceAttributeAssignment, ResourceAttributeResponse, ResourceAttributeUpsertOperation } from './types/authorization-attributes-contracts';
4
- import { Resource } from './types/general';
1
+ import { AuthorizationAttributesService as IAuthorizationAttributesService } from './types/authorization-attributes-service.interface';
2
+ /**
3
+ * Main service class for managing resource and entity attributes.
4
+ * Provides access to both direct (MS) and SNS operations.
5
+ *
6
+ * @example
7
+ * const service = new AuthorizationAttributesService();
8
+ *
9
+ * // Use direct operations
10
+ * await service.direct().upsertResourceAttributes(accountId, assignments);
11
+ *
12
+ * // Use SNS operations
13
+ * await service.sns().upsertResourceAttributes(accountId, assignments, appName, actionId);
14
+ * ```
15
+ */
5
16
  export declare class AuthorizationAttributesService {
6
- private static LOG_TAG;
7
- private static API_PATHS;
8
- private httpClient;
9
- private fetchOptions;
10
- private snsArn;
17
+ private _directService;
18
+ private _snsService;
11
19
  /**
12
- * Public constructor to create the AuthorizationAttributesService instance.
13
- * @param httpClient The HTTP client to use for API requests, if not provided, the default HTTP client from Api will be used.
14
- * @param fetchOptions The fetch options to use for API requests, if not provided, the default fetch options will be used.
20
+ * Gets the direct (MS) service instance.
21
+ * Initializes the service on first access (lazy initialization).
22
+ * @returns IAuthorizationAttributesService instance
15
23
  */
16
- constructor(httpClient?: HttpClient, fetchOptions?: RecursivePartial<FetcherConfig>);
24
+ direct(): IAuthorizationAttributesService;
17
25
  /**
18
- * Upsert resource attributes synchronously, performing http call to the authorization MS to assign the given attributes to the given resource.
19
- * @param accountId
20
- * @param resourceAttributeAssignments - Array of resource (resourceType, resourceId) and attribute (key, value) pairs to upsert in the authorization MS.
21
- * e.g. [{ resourceType: 'board', resourceId: 123, key: 'board_kind', value: 'private' }]
22
- * @returns ResourceAttributeResponse - The affected (created and updated_ resource attributes assignments in the `attributes` field.
26
+ * Gets the SNS service instance.
27
+ * Initializes the service on first access (lazy initialization).
28
+ * @returns IAuthorizationAttributesService instance
23
29
  */
24
- upsertResourceAttributes(accountId: number, resourceAttributeAssignments: ResourceAttributeAssignment[]): Promise<ResourceAttributeResponse>;
25
- /**
26
- * Delete resource attributes assignments synchronously, performing http call to the authorization MS to delete the given attributes from the given singular resource.
27
- * @param accountId
28
- * @param resource - The resource (resourceType, resourceId) to delete the attributes for.
29
- * @param attributeKeys - Array of attribute keys to delete for the resource.
30
- * @returns ResourceAttributeResponse - The affected (deleted) resource attributes assignments in the `attributes` field.
31
- */
32
- deleteResourceAttributes(accountId: number, resource: Resource, attributeKeys: string[]): Promise<ResourceAttributeResponse>;
33
- /**
34
- * Async function, this function only send the updates request to SNS and return before the change actually took place
35
- * @param accountId
36
- * @param appName - App name of the calling app
37
- * @param callerActionIdentifier - action identifier
38
- * @param resourceAttributeOperations - Array of operations to do on resource attributes.
39
- * @return {Promise<ResourceAttributesOperation[]>} Array of sent operations
40
- * */
41
- updateResourceAttributesAsync(accountId: number, appName: string, callerActionIdentifier: string, resourceAttributeOperations: ResourceAttributeUpsertOperation[]): Promise<ResourceAttributeUpsertOperation[]>;
42
- private sendSingleSnsMessage;
43
- private static getSnsTopicArn;
44
- /**
45
- * Checks we can contact the required SNS topic that used to send attribute updates to Authorization MS.
46
- * This function can be used as health check for services that updating resource attributes in async is crucial.
47
- * Note this function only verify the POD can contact AWS SDK and the topic exists, but the user still might get
48
- * errors when pushing for the SNS (e.g: in case the AWS role of the POD don't have permissions to push messages).
49
- * However, this is the best we can do without actually push dummy messages to the SNS.
50
- * @return {Promise<boolean>} - true if succeeded
51
- */
52
- asyncResourceAttributesHealthCheck(): Promise<boolean>;
30
+ sns(): IAuthorizationAttributesService;
53
31
  }
54
32
  //# sourceMappingURL=authorization-attributes-service.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"authorization-attributes-service.d.ts","sourceRoot":"","sources":["../../src/authorization-attributes-service.ts"],"names":[],"mappings":"AACA,OAAO,EAAO,aAAa,EAAE,UAAU,EAAE,MAAM,sCAAsC,CAAC;AAEtF,OAAO,EAAoB,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;AACvF,OAAO,EACL,2BAA2B,EAC3B,yBAAyB,EACzB,gCAAgC,EACjC,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAY3C,qBAAa,8BAA8B;IACzC,OAAO,CAAC,MAAM,CAAC,OAAO,CAA8B;IACpD,OAAO,CAAC,MAAM,CAAC,SAAS,CAGb;IACX,OAAO,CAAC,UAAU,CAAa;IAC/B,OAAO,CAAC,YAAY,CAAkC;IACtD,OAAO,CAAC,MAAM,CAAS;IAEvB;;;;OAIG;gBACS,UAAU,CAAC,EAAE,UAAU,EAAE,YAAY,CAAC,EAAE,gBAAgB,CAAC,aAAa,CAAC;IAsBnF;;;;;;OAMG;IACG,wBAAwB,CAC5B,SAAS,EAAE,MAAM,EACjB,4BAA4B,EAAE,2BAA2B,EAAE,GAC1D,OAAO,CAAC,yBAAyB,CAAC;IA6BrC;;;;;;OAMG;IACG,wBAAwB,CAC5B,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,QAAQ,EAClB,aAAa,EAAE,MAAM,EAAE,GACtB,OAAO,CAAC,yBAAyB,CAAC;IAkCrC;;;;;;;UAOM;IACA,6BAA6B,CACjC,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,MAAM,EACf,sBAAsB,EAAE,MAAM,EAC9B,2BAA2B,EAAE,gCAAgC,EAAE,GAC9D,OAAO,CAAC,gCAAgC,EAAE,CAAC;YAYhC,oBAAoB;IA4BlC,OAAO,CAAC,MAAM,CAAC,cAAc;IAW7B;;;;;;;OAOG;IACG,kCAAkC,IAAI,OAAO,CAAC,OAAO,CAAC;CAoB7D"}
1
+ {"version":3,"file":"authorization-attributes-service.d.ts","sourceRoot":"","sources":["../../src/authorization-attributes-service.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,8BAA8B,IAAI,+BAA+B,EAAE,MAAM,oDAAoD,CAAC;AAEvI;;;;;;;;;;;;;GAaG;AACH,qBAAa,8BAA8B;IACzC,OAAO,CAAC,cAAc,CAAiD;IACvE,OAAO,CAAC,WAAW,CAAkD;IAErE;;;;OAIG;IACH,MAAM,IAAI,+BAA+B;IAOzC;;;;OAIG;IACH,GAAG,IAAI,+BAA+B;CAMvC"}
@@ -1,180 +1,44 @@
1
- import chunk from 'lodash/chunk.js';
2
- import { Api } from '@mondaydotcomorg/trident-backend-api';
3
- import { sendToSns, getTopicAttributes } from '@mondaydotcomorg/monday-sns';
4
- import { HttpFetcherError } from '@mondaydotcomorg/monday-fetch-api';
5
- import { logger } from './authorization-internal-service.mjs';
6
- import { getAttributionsFromApi } from './attributions-service.mjs';
7
- import { ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE, SNS_ARN_ENV_VAR_NAME, SNS_DEV_TEST_NAME, RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND } from './constants/sns.mjs';
8
- import { ERROR_MESSAGES, DEFAULT_FETCH_OPTIONS, APP_NAME } from './constants.mjs';
1
+ import { AuthorizationAttributesMsService } from './authorization-attributes-ms-service.mjs';
2
+ import { AuthorizationAttributesSnsService } from './authorization-attributes-sns-service.mjs';
9
3
 
4
+ /**
5
+ * Main service class for managing resource and entity attributes.
6
+ * Provides access to both direct (MS) and SNS operations.
7
+ *
8
+ * @example
9
+ * const service = new AuthorizationAttributesService();
10
+ *
11
+ * // Use direct operations
12
+ * await service.direct().upsertResourceAttributes(accountId, assignments);
13
+ *
14
+ * // Use SNS operations
15
+ * await service.sns().upsertResourceAttributes(accountId, assignments, appName, actionId);
16
+ * ```
17
+ */
10
18
  class AuthorizationAttributesService {
11
- static LOG_TAG = 'authorization_attributes';
12
- static API_PATHS = {
13
- UPSERT_RESOURCE_ATTRIBUTES: '/attributes/{accountId}/resource',
14
- DELETE_RESOURCE_ATTRIBUTES: '/attributes/{accountId}/resource/{resourceType}/{resourceId}',
15
- };
16
- httpClient;
17
- fetchOptions;
18
- snsArn;
19
+ _directService = null;
20
+ _snsService = null;
19
21
  /**
20
- * Public constructor to create the AuthorizationAttributesService instance.
21
- * @param httpClient The HTTP client to use for API requests, if not provided, the default HTTP client from Api will be used.
22
- * @param fetchOptions The fetch options to use for API requests, if not provided, the default fetch options will be used.
22
+ * Gets the direct (MS) service instance.
23
+ * Initializes the service on first access (lazy initialization).
24
+ * @returns IAuthorizationAttributesService instance
23
25
  */
24
- constructor(httpClient, fetchOptions) {
25
- console.log(1);
26
- if (!httpClient) {
27
- httpClient = Api.getPart('httpClient');
28
- if (!httpClient) {
29
- throw new Error(ERROR_MESSAGES.HTTP_CLIENT_NOT_INITIALIZED);
30
- }
31
- }
32
- if (!fetchOptions) {
33
- fetchOptions = DEFAULT_FETCH_OPTIONS;
34
- }
35
- else {
36
- fetchOptions = {
37
- ...DEFAULT_FETCH_OPTIONS,
38
- ...fetchOptions,
39
- };
40
- }
41
- this.httpClient = httpClient;
42
- this.fetchOptions = fetchOptions;
43
- this.snsArn = AuthorizationAttributesService.getSnsTopicArn();
44
- }
45
- /**
46
- * Upsert resource attributes synchronously, performing http call to the authorization MS to assign the given attributes to the given resource.
47
- * @param accountId
48
- * @param resourceAttributeAssignments - Array of resource (resourceType, resourceId) and attribute (key, value) pairs to upsert in the authorization MS.
49
- * e.g. [{ resourceType: 'board', resourceId: 123, key: 'board_kind', value: 'private' }]
50
- * @returns ResourceAttributeResponse - The affected (created and updated_ resource attributes assignments in the `attributes` field.
51
- */
52
- async upsertResourceAttributes(accountId, resourceAttributeAssignments) {
53
- const attributionHeaders = getAttributionsFromApi();
54
- try {
55
- return await this.httpClient.fetch({
56
- url: {
57
- appName: APP_NAME,
58
- path: AuthorizationAttributesService.API_PATHS.UPSERT_RESOURCE_ATTRIBUTES.replace('{accountId}', accountId.toString()),
59
- },
60
- method: 'POST',
61
- headers: {
62
- 'Content-Type': 'application/json',
63
- ...attributionHeaders,
64
- },
65
- body: JSON.stringify({ resourceAttributeAssignments }),
66
- }, this.fetchOptions);
67
- }
68
- catch (err) {
69
- if (err instanceof HttpFetcherError) {
70
- throw new Error(ERROR_MESSAGES.REQUEST_FAILED('upsertResourceAttributes', err.status, err.message));
71
- }
72
- throw err;
26
+ direct() {
27
+ if (this._directService === null) {
28
+ this._directService = new AuthorizationAttributesMsService();
73
29
  }
30
+ return this._directService;
74
31
  }
75
32
  /**
76
- * Delete resource attributes assignments synchronously, performing http call to the authorization MS to delete the given attributes from the given singular resource.
77
- * @param accountId
78
- * @param resource - The resource (resourceType, resourceId) to delete the attributes for.
79
- * @param attributeKeys - Array of attribute keys to delete for the resource.
80
- * @returns ResourceAttributeResponse - The affected (deleted) resource attributes assignments in the `attributes` field.
33
+ * Gets the SNS service instance.
34
+ * Initializes the service on first access (lazy initialization).
35
+ * @returns IAuthorizationAttributesService instance
81
36
  */
82
- async deleteResourceAttributes(accountId, resource, attributeKeys) {
83
- const attributionHeaders = getAttributionsFromApi();
84
- if (!resource.id) {
85
- throw new Error('Resource ID is required');
86
- }
87
- try {
88
- return await this.httpClient.fetch({
89
- url: {
90
- appName: APP_NAME,
91
- path: AuthorizationAttributesService.API_PATHS.DELETE_RESOURCE_ATTRIBUTES.replace('{accountId}', accountId.toString())
92
- .replace('{resourceType}', resource.type)
93
- .replace('{resourceId}', resource.id.toString()),
94
- },
95
- method: 'DELETE',
96
- headers: {
97
- 'Content-Type': 'application/json',
98
- ...attributionHeaders,
99
- },
100
- body: JSON.stringify({ keys: attributeKeys }),
101
- }, this.fetchOptions);
102
- }
103
- catch (err) {
104
- if (err instanceof HttpFetcherError) {
105
- throw new Error(ERROR_MESSAGES.REQUEST_FAILED('deleteResourceAttributes', err.status, err.message));
106
- }
107
- throw err;
108
- }
109
- }
110
- /**
111
- * Async function, this function only send the updates request to SNS and return before the change actually took place
112
- * @param accountId
113
- * @param appName - App name of the calling app
114
- * @param callerActionIdentifier - action identifier
115
- * @param resourceAttributeOperations - Array of operations to do on resource attributes.
116
- * @return {Promise<ResourceAttributesOperation[]>} Array of sent operations
117
- * */
118
- async updateResourceAttributesAsync(accountId, appName, callerActionIdentifier, resourceAttributeOperations) {
119
- const topicArn = this.snsArn;
120
- const sendToSnsPromises = [];
121
- const operationChucks = chunk(resourceAttributeOperations, ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE);
122
- for (const operationsChunk of operationChucks) {
123
- sendToSnsPromises.push(this.sendSingleSnsMessage(topicArn, accountId, appName, callerActionIdentifier, operationsChunk));
124
- }
125
- return (await Promise.all(sendToSnsPromises)).flat();
126
- }
127
- async sendSingleSnsMessage(topicArn, accountId, appName, callerActionIdentifier, operations) {
128
- const payload = {
129
- kind: RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND,
130
- payload: {
131
- accountId: accountId,
132
- callerAppName: appName,
133
- callerActionIdentifier: callerActionIdentifier,
134
- operations: operations,
135
- },
136
- };
137
- try {
138
- await sendToSns(payload, topicArn);
139
- return operations;
140
- }
141
- catch (error) {
142
- logger.error({ error, tag: AuthorizationAttributesService.LOG_TAG }, 'Authorization resource attributes async update: failed to send operations to SNS');
143
- return [];
144
- }
145
- }
146
- static getSnsTopicArn() {
147
- const arnFromEnv = process.env[SNS_ARN_ENV_VAR_NAME];
148
- if (arnFromEnv) {
149
- return arnFromEnv;
150
- }
151
- if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
152
- return SNS_DEV_TEST_NAME;
153
- }
154
- throw new Error('Unable to get sns topic arn from env variable');
155
- }
156
- /**
157
- * Checks we can contact the required SNS topic that used to send attribute updates to Authorization MS.
158
- * This function can be used as health check for services that updating resource attributes in async is crucial.
159
- * Note this function only verify the POD can contact AWS SDK and the topic exists, but the user still might get
160
- * errors when pushing for the SNS (e.g: in case the AWS role of the POD don't have permissions to push messages).
161
- * However, this is the best we can do without actually push dummy messages to the SNS.
162
- * @return {Promise<boolean>} - true if succeeded
163
- */
164
- async asyncResourceAttributesHealthCheck() {
165
- try {
166
- const requestedTopicArn = this.snsArn;
167
- const attributes = await getTopicAttributes(requestedTopicArn);
168
- const isHealthy = !(!attributes || !('TopicArn' in attributes) || attributes.TopicArn !== requestedTopicArn);
169
- if (!isHealthy) {
170
- logger.error({ requestedTopicArn, snsReturnedAttributes: attributes, tag: AuthorizationAttributesService.LOG_TAG }, 'authorization-attributes-service failed in health check');
171
- }
172
- return isHealthy;
173
- }
174
- catch (error) {
175
- logger.error({ error, tag: AuthorizationAttributesService.LOG_TAG }, 'authorization-attributes-service got error during health check');
176
- return false;
37
+ sns() {
38
+ if (this._snsService === null) {
39
+ this._snsService = new AuthorizationAttributesSnsService();
177
40
  }
41
+ return this._snsService;
178
42
  }
179
43
  }
180
44
 
@@ -0,0 +1,84 @@
1
+ import { ResourceAttributeUpsertOperation, EntityAttributeUpsertOperation, EntityAttributeDeleteOperation, ResourceAttributeDeleteOperation } from './types/authorization-attributes-contracts';
2
+ import { Resource } from './types/general';
3
+ import { AuthorizationAttributesService } from './types/authorization-attributes-service.interface';
4
+ import { EntityType } from './entity-attributes-constants';
5
+ /**
6
+ * Service class for managing resource attributes asynchronously via SNS.
7
+ * Provides asynchronous operations to create/update and delete attributes on resources.
8
+ */
9
+ export declare class AuthorizationAttributesSnsService implements AuthorizationAttributesService {
10
+ private static LOG_TAG;
11
+ private resourceSnsArn;
12
+ private entitySnsArn;
13
+ /**
14
+ * Public constructor to create the AuthorizationAttributesSnsService instance.
15
+ */
16
+ constructor();
17
+ /**
18
+ * Async function to delete a resource attribute using SNS.
19
+ * Sends the delete request to SNS and returns before the change actually took place.
20
+ * @param accountId The account ID
21
+ * @param resource The resource (resourceType, resourceId)
22
+ * @param attributeKey Attribute key to delete
23
+ * @param appName App name of the calling app
24
+ * @param callerActionIdentifier Action identifier
25
+ * @return Promise with sent operation
26
+ */
27
+ deleteResourceAttributes(accountId: number, resource: Resource, attributeKey: string, appName?: string, callerActionIdentifier?: string): Promise<ResourceAttributeDeleteOperation>;
28
+ /**
29
+ * Async function to delete an entity attribute using SNS.
30
+ * Sends the delete request to SNS and returns before the change actually took place.
31
+ * @param accountId The account ID
32
+ * @param entityType The entity type
33
+ * @param entityId The entity ID
34
+ * @param attributeKey Attribute key to delete
35
+ * @param appName App name of the calling app
36
+ * @param callerActionIdentifier Action identifier
37
+ * @return Promise with sent operation
38
+ */
39
+ deleteEntityAttributes(accountId: number, entityType: EntityType, entityId: number, attributeKey: string, appName?: string, callerActionIdentifier?: string): Promise<EntityAttributeDeleteOperation>;
40
+ /**
41
+ * Async function, this function only send the update request to SNS and return before the change actually took place
42
+ * @param accountId
43
+ * @param appName - App name of the calling app
44
+ * @param callerActionIdentifier - action identifier
45
+ * @param resourceAttributeOperation - Operation to do on resource attribute.
46
+ * @return {Promise<ResourceAttributeUpsertOperation>} Sent operation
47
+ * */
48
+ updateResourceAttributes(accountId: number, appName: string, callerActionIdentifier: string, resourceAttributeOperation: ResourceAttributeUpsertOperation): Promise<ResourceAttributeUpsertOperation>;
49
+ /**
50
+ * Async function, this function only send the update request to SNS and return before the change actually took place
51
+ * @param accountId
52
+ * @param appName - App name of the calling app
53
+ * @param callerActionIdentifier - action identifier
54
+ * @param entityAttributeOperation - Operation to do on entity attribute.
55
+ * @return {Promise<EntityAttributeUpsertOperation>} Sent operation
56
+ * */
57
+ updateEntityAttributes(accountId: number, appName: string, callerActionIdentifier: string, entityAttributeOperation: EntityAttributeUpsertOperation): Promise<EntityAttributeUpsertOperation>;
58
+ /**
59
+ * Base function to send attribute operations to SNS.
60
+ * Chunks operations and sends them in parallel.
61
+ * @param topicArn The SNS topic ARN to send messages to
62
+ * @param accountId The account ID
63
+ * @param appName App name of the calling app
64
+ * @param callerActionIdentifier Action identifier
65
+ * @param operations Array of operations to send
66
+ * @param chunkSize Maximum number of operations per message
67
+ * @param messageKind The kind of message being sent
68
+ * @param errorLogMessage Error message to log if sending fails
69
+ * @return Promise with array of sent operations
70
+ */
71
+ private sendOperationsToSns;
72
+ private sendSingleSnsMessage;
73
+ private static getSnsTopicArn;
74
+ /**
75
+ * Checks we can contact the required SNS topic that used to send attribute updates to Authorization MS.
76
+ * This function can be used as health check for services that updating resource attributes in async is crucial.
77
+ * Note this function only verify the POD can contact AWS SDK and the topic exists, but the user still might get
78
+ * errors when pushing for the SNS (e.g: in case the AWS role of the POD don't have permissions to push messages).
79
+ * However, this is the best we can do without actually push dummy messages to the SNS.
80
+ * @return {Promise<boolean>} - true if succeeded
81
+ */
82
+ asyncResourceAttributesHealthCheck(): Promise<boolean>;
83
+ }
84
+ //# sourceMappingURL=authorization-attributes-sns-service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authorization-attributes-sns-service.d.ts","sourceRoot":"","sources":["../../src/authorization-attributes-sns-service.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,gCAAgC,EAChC,8BAA8B,EAC9B,8BAA8B,EAC9B,gCAAgC,EACjC,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAa3C,OAAO,EAAE,8BAA8B,EAAE,MAAM,oDAAoD,CAAC;AACpG,OAAO,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAI3D;;;GAGG;AACH,qBAAa,iCAAkC,YAAW,8BAA8B;IACtF,OAAO,CAAC,MAAM,CAAC,OAAO,CAA8B;IACpD,OAAO,CAAC,cAAc,CAAS;IAC/B,OAAO,CAAC,YAAY,CAAS;IAE7B;;OAEG;;IAMH;;;;;;;;;OASG;IACG,wBAAwB,CAC5B,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,QAAQ,EAClB,YAAY,EAAE,MAAM,EACpB,OAAO,CAAC,EAAE,MAAM,EAChB,sBAAsB,CAAC,EAAE,MAAM,GAC9B,OAAO,CAAC,gCAAgC,CAAC;IA4B5C;;;;;;;;;;OAUG;IACG,sBAAsB,CAC1B,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,UAAU,EACtB,QAAQ,EAAE,MAAM,EAChB,YAAY,EAAE,MAAM,EACpB,OAAO,CAAC,EAAE,MAAM,EAChB,sBAAsB,CAAC,EAAE,MAAM,GAC9B,OAAO,CAAC,8BAA8B,CAAC;IAwB1C;;;;;;;UAOM;IACA,wBAAwB,CAC5B,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,MAAM,EACf,sBAAsB,EAAE,MAAM,EAC9B,0BAA0B,EAAE,gCAAgC,GAC3D,OAAO,CAAC,gCAAgC,CAAC;IAe5C;;;;;;;UAOM;IACA,sBAAsB,CAC1B,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,MAAM,EACf,sBAAsB,EAAE,MAAM,EAC9B,wBAAwB,EAAE,8BAA8B,GACvD,OAAO,CAAC,8BAA8B,CAAC;IAe1C;;;;;;;;;;;;OAYG;YACW,mBAAmB;YAkCnB,oBAAoB;IAiClC,OAAO,CAAC,MAAM,CAAC,cAAc;IA0B7B;;;;;;;OAOG;IACG,kCAAkC,IAAI,OAAO,CAAC,OAAO,CAAC;CAoB7D"}