@contrail/flexplm 1.7.7-alpha.a0d86c7 → 1.7.7-alpha.c59ab5b
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.
- package/lib/interfaces/interfaces.d.ts +0 -4
- package/lib/publish/base-process-publish-assortment.js +4 -2
- package/lib/publish/base-process-publish-assortment.spec.js +106 -0
- package/lib/util/flexplm-connect.d.ts +4 -20
- package/lib/util/flexplm-connect.js +10 -286
- package/lib/util/flexplm-connect.spec.js +0 -532
- package/package.json +1 -1
|
@@ -6,10 +6,6 @@ export interface FCConfig {
|
|
|
6
6
|
eventObjectClassParam?: string;
|
|
7
7
|
eventFlexTypePathParam?: string;
|
|
8
8
|
flexplmConnect?: any;
|
|
9
|
-
'flexplmConnect.sessionReuse.enabled'?: boolean | string;
|
|
10
|
-
'flexplmConnect.sessionReuse.ttlSeconds'?: number | string;
|
|
11
|
-
'flexplmConnect.sessionReuse.cookieName'?: string;
|
|
12
|
-
'flexplmConnect.sessionReuse.retryStatuses'?: number | number[] | string;
|
|
13
9
|
taskId?: string;
|
|
14
10
|
apiHost: string;
|
|
15
11
|
userName(): string;
|
|
@@ -909,7 +909,8 @@ class BaseProcessPublishAssortment {
|
|
|
909
909
|
? itemFamilyChanges.assortmentItemFullChangeMap.get(entityReference)?.item
|
|
910
910
|
: itemFamilyChanges.itemFamilyObject;
|
|
911
911
|
let seasonalData = await this.getSeasonalData(projectItem);
|
|
912
|
-
|
|
912
|
+
const productSeasonMapKey = (await type_conversion_utils_1.TypeConversionUtils.getMapKey(this.transformMapFile, this.mapFileUtil, projectItem, type_conversion_utils_1.TypeConversionUtils.VIBE2FLEX_DIRECTION)) || 'LCSProductSeasonLink';
|
|
913
|
+
seasonalData = await map_utils_1.MapUtil.applyTransformMap(this.transformMapFile, this.mapFileUtil, seasonalData, productSeasonMapKey, 'vibe2flex');
|
|
913
914
|
const LCSProduct = await this.getProductFederation(entityReference, itemToFederatedIdMapping, prodEntityData);
|
|
914
915
|
const isCreatable = await type_conversion_utils_1.TypeConversionUtils.isOutboundCreatableFromEntity(this.transformMapFile, this.mapFileUtil, projectItem, { item: prodEntityData, assortment });
|
|
915
916
|
const eventType = isCreatable ? 'UPSERT_ON_SEASON' : 'UPDATE_ON_SEASON';
|
|
@@ -944,7 +945,8 @@ class BaseProcessPublishAssortment {
|
|
|
944
945
|
}
|
|
945
946
|
const projectItem = this.getProjectItem(itemFamilyChanges, entityReference);
|
|
946
947
|
let seasonalData = await this.getSeasonalData(projectItem);
|
|
947
|
-
|
|
948
|
+
const skuSeasonMapKey = (await type_conversion_utils_1.TypeConversionUtils.getMapKey(this.transformMapFile, this.mapFileUtil, projectItem, type_conversion_utils_1.TypeConversionUtils.VIBE2FLEX_DIRECTION)) || 'LCSSKUSeasonLink';
|
|
949
|
+
seasonalData = await map_utils_1.MapUtil.applyTransformMap(this.transformMapFile, this.mapFileUtil, seasonalData, skuSeasonMapKey, 'vibe2flex');
|
|
948
950
|
const LCSSKU = await this.getSKUFederation(entityReference, itemToFederatedIdMapping, item);
|
|
949
951
|
const isCreatable = await type_conversion_utils_1.TypeConversionUtils.isOutboundCreatableFromEntity(this.transformMapFile, this.mapFileUtil, projectItem, { item, assortment });
|
|
950
952
|
const eventType = isCreatable ? 'UPSERT_ON_SEASON' : 'UPDATE_ON_SEASON';
|
|
@@ -1509,6 +1509,9 @@ describe('getEventsForItemFamilyChanges - conditional eventType', () => {
|
|
|
1509
1509
|
};
|
|
1510
1510
|
const mapFileUtil = new transform_data_1.MapFileUtil(new sdk_1.Entities());
|
|
1511
1511
|
const dc = new data_converter_1.DataConverter(config, mapFileUtil);
|
|
1512
|
+
beforeEach(() => {
|
|
1513
|
+
jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'getMapKey').mockResolvedValue(null);
|
|
1514
|
+
});
|
|
1512
1515
|
afterEach(() => {
|
|
1513
1516
|
jest.restoreAllMocks();
|
|
1514
1517
|
});
|
|
@@ -1705,6 +1708,108 @@ describe('getEventsForItemFamilyChanges - conditional eventType', () => {
|
|
|
1705
1708
|
// Verify SKU event called with assortment entity
|
|
1706
1709
|
expect(type_conversion_utils_1.TypeConversionUtils.isOutboundCreatableFromEntity).toHaveBeenNthCalledWith(2, undefined, mapFileUtil, colorProjectItem, { item: itemData, assortment });
|
|
1707
1710
|
});
|
|
1711
|
+
it('should use dynamic map key for LCSSKUSeasonLink when getMapKey returns a custom key', async () => {
|
|
1712
|
+
const bppa = new base_process_publish_assortment_1.BaseProcessPublishAssortment(config, dc, mapFileUtil);
|
|
1713
|
+
const itemFamilyId = 'family123';
|
|
1714
|
+
const colorId = 'color456';
|
|
1715
|
+
const familyItemData = { id: itemFamilyId, identifier: 'FAM-123', itemNumber: 'FAM-123' };
|
|
1716
|
+
const familyProjectItem = { id: 'proj0', updatedOn: '2023-01-15T00:00:00.000Z' };
|
|
1717
|
+
const colorProjectItem = { id: 'proj1', updatedOn: '2023-01-15T00:00:00.000Z' };
|
|
1718
|
+
const assortment = { id: 'assort123', name: 'Fall 2023 Assortment', publishToFlexPLM: true };
|
|
1719
|
+
const seasonFed = { entityReference: 'assortment:assort123', objectClass: 'LCSSeason', flexPLMSeasonName: 'Fall 2023' };
|
|
1720
|
+
const seasonalData = { someData: 'value' };
|
|
1721
|
+
const itemFamilyChanges = new item_family_changes_1.ItemFamilyChanges(itemFamilyId, new Date('2023-01-01T00:00:00.000Z'));
|
|
1722
|
+
itemFamilyChanges.colorUpdates.push(colorId);
|
|
1723
|
+
itemFamilyChanges.assortmentItemFullChangeMap.set(itemFamilyId, { item: familyItemData, projectItem: familyProjectItem });
|
|
1724
|
+
itemFamilyChanges.assortmentItemFullChangeMap.set(colorId, { item: { id: colorId, identifier: 'COLOR-456' }, projectItem: colorProjectItem });
|
|
1725
|
+
jest.spyOn(bppa, 'getAssortment').mockResolvedValue(assortment);
|
|
1726
|
+
jest.spyOn(bppa, 'getProjectItem')
|
|
1727
|
+
.mockReturnValueOnce(familyProjectItem)
|
|
1728
|
+
.mockReturnValueOnce(colorProjectItem);
|
|
1729
|
+
jest.spyOn(bppa, 'getSeasonalData').mockResolvedValue(seasonalData);
|
|
1730
|
+
jest.spyOn(map_utils_1.MapUtil, 'applyTransformMap').mockResolvedValue({ transformedData: 'value' });
|
|
1731
|
+
jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'getIdentifierProperties').mockResolvedValue(['identifier']);
|
|
1732
|
+
jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'getInformationalProperties').mockResolvedValue([]);
|
|
1733
|
+
jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'isOutboundCreatableFromEntity').mockResolvedValue(false);
|
|
1734
|
+
// First call: product path (return null → falls back to default)
|
|
1735
|
+
// Second call: SKU path (return custom key)
|
|
1736
|
+
jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'getMapKey')
|
|
1737
|
+
.mockResolvedValueOnce(null)
|
|
1738
|
+
.mockResolvedValueOnce('LCSSKUSeasonLinkFlexOwned');
|
|
1739
|
+
await bppa.getEventsForItemFamilyChanges(itemFamilyChanges, 'assort123', seasonFed, new Map());
|
|
1740
|
+
expect(map_utils_1.MapUtil.applyTransformMap).toHaveBeenCalledWith(undefined, mapFileUtil, seasonalData, 'LCSSKUSeasonLinkFlexOwned', 'vibe2flex');
|
|
1741
|
+
});
|
|
1742
|
+
it('should fall back to LCSSKUSeasonLink when getMapKey returns null', async () => {
|
|
1743
|
+
const bppa = new base_process_publish_assortment_1.BaseProcessPublishAssortment(config, dc, mapFileUtil);
|
|
1744
|
+
const itemFamilyId = 'family123';
|
|
1745
|
+
const colorId = 'color456';
|
|
1746
|
+
const familyItemData = { id: itemFamilyId, identifier: 'FAM-123', itemNumber: 'FAM-123' };
|
|
1747
|
+
const familyProjectItem = { id: 'proj0', updatedOn: '2023-01-15T00:00:00.000Z' };
|
|
1748
|
+
const colorProjectItem = { id: 'proj1', updatedOn: '2023-01-15T00:00:00.000Z' };
|
|
1749
|
+
const assortment = { id: 'assort123', name: 'Fall 2023 Assortment', publishToFlexPLM: true };
|
|
1750
|
+
const seasonFed = { entityReference: 'assortment:assort123', objectClass: 'LCSSeason', flexPLMSeasonName: 'Fall 2023' };
|
|
1751
|
+
const seasonalData = { someData: 'value' };
|
|
1752
|
+
const itemFamilyChanges = new item_family_changes_1.ItemFamilyChanges(itemFamilyId, new Date('2023-01-01T00:00:00.000Z'));
|
|
1753
|
+
itemFamilyChanges.colorUpdates.push(colorId);
|
|
1754
|
+
itemFamilyChanges.assortmentItemFullChangeMap.set(itemFamilyId, { item: familyItemData, projectItem: familyProjectItem });
|
|
1755
|
+
itemFamilyChanges.assortmentItemFullChangeMap.set(colorId, { item: { id: colorId, identifier: 'COLOR-456' }, projectItem: colorProjectItem });
|
|
1756
|
+
jest.spyOn(bppa, 'getAssortment').mockResolvedValue(assortment);
|
|
1757
|
+
jest.spyOn(bppa, 'getProjectItem')
|
|
1758
|
+
.mockReturnValueOnce(familyProjectItem)
|
|
1759
|
+
.mockReturnValueOnce(colorProjectItem);
|
|
1760
|
+
jest.spyOn(bppa, 'getSeasonalData').mockResolvedValue(seasonalData);
|
|
1761
|
+
jest.spyOn(map_utils_1.MapUtil, 'applyTransformMap').mockResolvedValue({ transformedData: 'value' });
|
|
1762
|
+
jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'getIdentifierProperties').mockResolvedValue(['identifier']);
|
|
1763
|
+
jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'getInformationalProperties').mockResolvedValue([]);
|
|
1764
|
+
jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'isOutboundCreatableFromEntity').mockResolvedValue(false);
|
|
1765
|
+
jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'getMapKey').mockResolvedValue(null);
|
|
1766
|
+
await bppa.getEventsForItemFamilyChanges(itemFamilyChanges, 'assort123', seasonFed, new Map());
|
|
1767
|
+
expect(map_utils_1.MapUtil.applyTransformMap).toHaveBeenCalledWith(undefined, mapFileUtil, seasonalData, 'LCSSKUSeasonLink', 'vibe2flex');
|
|
1768
|
+
});
|
|
1769
|
+
it('should use dynamic map key for LCSProductSeasonLink when getMapKey returns a custom key', async () => {
|
|
1770
|
+
const bppa = new base_process_publish_assortment_1.BaseProcessPublishAssortment(config, dc, mapFileUtil);
|
|
1771
|
+
const itemFamilyId = 'family123';
|
|
1772
|
+
const prodEntityData = { id: itemFamilyId, identifier: 'FAM-123', itemNumber: 'FAM-123' };
|
|
1773
|
+
const projectItem = { id: 'proj1', updatedOn: '2023-01-15T00:00:00.000Z' };
|
|
1774
|
+
const assortment = { id: 'assort123', name: 'Fall 2023 Assortment', publishToFlexPLM: true };
|
|
1775
|
+
const seasonFed = { entityReference: 'assortment:assort123', objectClass: 'LCSSeason', flexPLMSeasonName: 'Fall 2023' };
|
|
1776
|
+
const seasonalData = { someData: 'value' };
|
|
1777
|
+
const itemFamilyChanges = new item_family_changes_1.ItemFamilyChanges(itemFamilyId, new Date('2023-01-01T00:00:00.000Z'));
|
|
1778
|
+
itemFamilyChanges.familyUpdate = true;
|
|
1779
|
+
itemFamilyChanges.assortmentItemFullChangeMap.set(itemFamilyId, { item: prodEntityData, projectItem });
|
|
1780
|
+
jest.spyOn(bppa, 'getAssortment').mockResolvedValue(assortment);
|
|
1781
|
+
jest.spyOn(bppa, 'getProjectItem').mockReturnValue(projectItem);
|
|
1782
|
+
jest.spyOn(bppa, 'getSeasonalData').mockResolvedValue(seasonalData);
|
|
1783
|
+
jest.spyOn(map_utils_1.MapUtil, 'applyTransformMap').mockResolvedValue({ transformedData: 'value' });
|
|
1784
|
+
jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'getIdentifierProperties').mockResolvedValue(['identifier']);
|
|
1785
|
+
jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'getInformationalProperties').mockResolvedValue([]);
|
|
1786
|
+
jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'isOutboundCreatableFromEntity').mockResolvedValue(false);
|
|
1787
|
+
jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'getMapKey').mockResolvedValue('LCSProductSeasonLinkCustom');
|
|
1788
|
+
await bppa.getEventsForItemFamilyChanges(itemFamilyChanges, 'assort123', seasonFed, new Map());
|
|
1789
|
+
expect(map_utils_1.MapUtil.applyTransformMap).toHaveBeenCalledWith(undefined, mapFileUtil, seasonalData, 'LCSProductSeasonLinkCustom', 'vibe2flex');
|
|
1790
|
+
});
|
|
1791
|
+
it('should fall back to LCSProductSeasonLink when getMapKey returns null', async () => {
|
|
1792
|
+
const bppa = new base_process_publish_assortment_1.BaseProcessPublishAssortment(config, dc, mapFileUtil);
|
|
1793
|
+
const itemFamilyId = 'family123';
|
|
1794
|
+
const prodEntityData = { id: itemFamilyId, identifier: 'FAM-123', itemNumber: 'FAM-123' };
|
|
1795
|
+
const projectItem = { id: 'proj1', updatedOn: '2023-01-15T00:00:00.000Z' };
|
|
1796
|
+
const assortment = { id: 'assort123', name: 'Fall 2023 Assortment', publishToFlexPLM: true };
|
|
1797
|
+
const seasonFed = { entityReference: 'assortment:assort123', objectClass: 'LCSSeason', flexPLMSeasonName: 'Fall 2023' };
|
|
1798
|
+
const seasonalData = { someData: 'value' };
|
|
1799
|
+
const itemFamilyChanges = new item_family_changes_1.ItemFamilyChanges(itemFamilyId, new Date('2023-01-01T00:00:00.000Z'));
|
|
1800
|
+
itemFamilyChanges.familyUpdate = true;
|
|
1801
|
+
itemFamilyChanges.assortmentItemFullChangeMap.set(itemFamilyId, { item: prodEntityData, projectItem });
|
|
1802
|
+
jest.spyOn(bppa, 'getAssortment').mockResolvedValue(assortment);
|
|
1803
|
+
jest.spyOn(bppa, 'getProjectItem').mockReturnValue(projectItem);
|
|
1804
|
+
jest.spyOn(bppa, 'getSeasonalData').mockResolvedValue(seasonalData);
|
|
1805
|
+
jest.spyOn(map_utils_1.MapUtil, 'applyTransformMap').mockResolvedValue({ transformedData: 'value' });
|
|
1806
|
+
jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'getIdentifierProperties').mockResolvedValue(['identifier']);
|
|
1807
|
+
jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'getInformationalProperties').mockResolvedValue([]);
|
|
1808
|
+
jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'isOutboundCreatableFromEntity').mockResolvedValue(false);
|
|
1809
|
+
jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'getMapKey').mockResolvedValue(null);
|
|
1810
|
+
await bppa.getEventsForItemFamilyChanges(itemFamilyChanges, 'assort123', seasonFed, new Map());
|
|
1811
|
+
expect(map_utils_1.MapUtil.applyTransformMap).toHaveBeenCalledWith(undefined, mapFileUtil, seasonalData, 'LCSProductSeasonLink', 'vibe2flex');
|
|
1812
|
+
});
|
|
1708
1813
|
});
|
|
1709
1814
|
describe('sendToFlexPLM / handleVibeIQFile / sendPublishPayloadEvent', () => {
|
|
1710
1815
|
const config = {
|
|
@@ -1932,6 +2037,7 @@ describe('released family with pre-development options', () => {
|
|
|
1932
2037
|
jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'getIdentifierProperties').mockResolvedValue(['itemNumber']);
|
|
1933
2038
|
jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'getInformationalProperties').mockResolvedValue([]);
|
|
1934
2039
|
jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'isOutboundCreatableFromEntity').mockResolvedValue(true);
|
|
2040
|
+
jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'getMapKey').mockResolvedValue(null);
|
|
1935
2041
|
};
|
|
1936
2042
|
afterEach(() => { jest.restoreAllMocks(); });
|
|
1937
2043
|
/////////////////////////////////////////////////////////////////////////////
|
|
@@ -5,27 +5,11 @@ export declare class FlexPLMConnect {
|
|
|
5
5
|
private staticHeaders;
|
|
6
6
|
payloadSendAsArray: boolean;
|
|
7
7
|
constructor(_config: FCConfig, endPoint?: any, payloadAsArray?: any);
|
|
8
|
-
private get sessionOptions();
|
|
9
|
-
/**
|
|
10
|
-
* Waits until no cold session acquisition is running for this key.
|
|
11
|
-
* Callers must `await` this only when it returns a promise: awaiting even a resolved promise yields,
|
|
12
|
-
* and the check-then-register in runColdAcquisition has to stay synchronous to be race free.
|
|
13
|
-
*/
|
|
14
|
-
private waitForInFlightAcquisition;
|
|
15
|
-
/** Runs a cold acquisition and registers it so concurrent callers wait for it instead of opening their own session. */
|
|
16
|
-
private runColdAcquisition;
|
|
17
|
-
private getSessionKey;
|
|
18
|
-
/** Releases the connection of a rejected response before it is replaced by a retry. */
|
|
19
|
-
private discardBody;
|
|
20
|
-
private getCachedSession;
|
|
21
|
-
private storeSession;
|
|
22
|
-
private clearSession;
|
|
23
|
-
/** Returns the session cookie value Windchill issued on this response, if any (last one wins). */
|
|
24
|
-
private extractSessionCookie;
|
|
25
|
-
private cookieHeader;
|
|
26
8
|
private getRequestOptions;
|
|
27
|
-
getCSRF(
|
|
28
|
-
|
|
9
|
+
getCSRF(): Promise<{
|
|
10
|
+
nonce_key: any;
|
|
11
|
+
nonce: any;
|
|
12
|
+
}>;
|
|
29
13
|
sendRequest(csrf: any, payload: any): Promise<Response>;
|
|
30
14
|
protected processRequest(payload: any): Promise<FlexPLMResponseData>;
|
|
31
15
|
sendToFlexPLM(payload: PayloadType): Promise<FlexPLMResponseData>;
|
|
@@ -2,56 +2,6 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.FlexPLMConnect = void 0;
|
|
4
4
|
const app_framework_1 = require("@contrail/app-framework");
|
|
5
|
-
// Module-level on purpose: a new FlexPLMConnect is constructed for every event. Declaring for Session reusing use case.
|
|
6
|
-
const sessionCache = new Map();
|
|
7
|
-
// Upper bound so users/option combinations that are never requested again cannot accumulate cookies forever.
|
|
8
|
-
const MAX_CACHED_SESSIONS = 100;
|
|
9
|
-
const pruneSessionCache = () => {
|
|
10
|
-
const now = Date.now();
|
|
11
|
-
for (const [key, session] of sessionCache) {
|
|
12
|
-
if (session.expiresAt <= now)
|
|
13
|
-
sessionCache.delete(key);
|
|
14
|
-
}
|
|
15
|
-
// Still full: drop the oldest entries (Map keeps insertion order).
|
|
16
|
-
while (sessionCache.size >= MAX_CACHED_SESSIONS) {
|
|
17
|
-
sessionCache.delete(sessionCache.keys().next().value);
|
|
18
|
-
}
|
|
19
|
-
};
|
|
20
|
-
// In-flight cold session acquisitions per key, so concurrent events share one FlexPLM session instead of each creating their own.
|
|
21
|
-
const inFlightAcquisitions = new Map();
|
|
22
|
-
const DEFAULT_SESSION_COOKIE_NAME = 'JSESSIONID';
|
|
23
|
-
const DEFAULT_SESSION_TTL_SECONDS = 900;
|
|
24
|
-
const DEFAULT_RETRY_STATUSES = [401, 403];
|
|
25
|
-
const COOKIE_NAME_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
26
|
-
// Thrown internally when a cached cookie was rejected, so the caller can re-acquire under the lock.
|
|
27
|
-
class SessionRejectedError extends Error {
|
|
28
|
-
}
|
|
29
|
-
const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
30
|
-
const parseRetryStatuses = (value) => {
|
|
31
|
-
let list = [];
|
|
32
|
-
if (Array.isArray(value))
|
|
33
|
-
list = value;
|
|
34
|
-
else if (typeof value === 'string')
|
|
35
|
-
list = value.split(',');
|
|
36
|
-
else if (value !== undefined && value !== null)
|
|
37
|
-
list = [value];
|
|
38
|
-
const statuses = list
|
|
39
|
-
.map(status => (typeof status === 'string' ? status.trim() : status))
|
|
40
|
-
.filter(status => status !== '' && status !== null && status !== undefined)
|
|
41
|
-
.map(Number)
|
|
42
|
-
// Only client-error statuses can mean "session rejected". 2xx/5xx would resend events the server already processed.
|
|
43
|
-
.filter(status => Number.isInteger(status) && status >= 400 && status <= 499);
|
|
44
|
-
return statuses.length ? statuses : DEFAULT_RETRY_STATUSES;
|
|
45
|
-
};
|
|
46
|
-
const parseTtlSeconds = (value) => {
|
|
47
|
-
const ttl = Number(value);
|
|
48
|
-
return Number.isFinite(ttl) && ttl > 0 ? ttl : DEFAULT_SESSION_TTL_SECONDS;
|
|
49
|
-
};
|
|
50
|
-
const parseCookieName = (value) => {
|
|
51
|
-
const name = typeof value === 'string' ? value.trim() : '';
|
|
52
|
-
return COOKIE_NAME_TOKEN.test(name) ? name : DEFAULT_SESSION_COOKIE_NAME;
|
|
53
|
-
};
|
|
54
|
-
// Added for Session reuse - ET-390 - Ends
|
|
55
5
|
class FlexPLMConnect {
|
|
56
6
|
constructor(_config, endPoint = undefined, payloadAsArray = undefined) {
|
|
57
7
|
this.vibeEventEndpoint = '';
|
|
@@ -69,138 +19,9 @@ class FlexPLMConnect {
|
|
|
69
19
|
}
|
|
70
20
|
}
|
|
71
21
|
/////////////////////////////////////////////////////////////////////////////
|
|
72
|
-
///////// ET-390 - Session reuse: start
|
|
73
|
-
/////////////////////////////////////////////////////////////////////////////
|
|
74
|
-
/*
|
|
75
|
-
private get sessionOptions() {
|
|
76
|
-
const sessReuseBool = this.config?.flexplmConnect?.sessionReuse;
|
|
77
|
-
console.info('sessReuseBool value is --> ' + sessReuseBool);
|
|
78
|
-
console.info('enabled value is --> ' + sessReuseBool?.enabled);
|
|
79
|
-
return {
|
|
80
|
-
enabled: sessReuseBool?.enabled === true || String(sessReuseBool?.enabled).toLowerCase() === 'true',
|
|
81
|
-
ttlMs: (sessReuseBool?.ttlSeconds ?? 900) * 1000,
|
|
82
|
-
cookieName: sessReuseBool?.cookieName ?? 'JSESSIONID',
|
|
83
|
-
retryStatuses: (sessReuseBool?.retryStatuses ?? [401, 403]) as number[],
|
|
84
|
-
};
|
|
85
|
-
}
|
|
86
|
-
*/
|
|
87
|
-
get sessionOptions() {
|
|
88
|
-
const cfg = this.config ?? {};
|
|
89
|
-
const sessReuseEntries = (name) => cfg[`flexplmConnect.sessionReuse.${name}`];
|
|
90
|
-
const enabled = sessReuseEntries('enabled');
|
|
91
|
-
return {
|
|
92
|
-
enabled: enabled === true || String(enabled).toLowerCase() === 'true',
|
|
93
|
-
ttlMs: parseTtlSeconds(sessReuseEntries('ttlSeconds')) * 1000,
|
|
94
|
-
cookieName: parseCookieName(sessReuseEntries('cookieName')),
|
|
95
|
-
retryStatuses: parseRetryStatuses(sessReuseEntries('retryStatuses')),
|
|
96
|
-
};
|
|
97
|
-
}
|
|
98
|
-
/**
|
|
99
|
-
* Waits until no cold session acquisition is running for this key.
|
|
100
|
-
* Callers must `await` this only when it returns a promise: awaiting even a resolved promise yields,
|
|
101
|
-
* and the check-then-register in runColdAcquisition has to stay synchronous to be race free.
|
|
102
|
-
*/
|
|
103
|
-
waitForInFlightAcquisition() {
|
|
104
|
-
const key = this.getSessionKey();
|
|
105
|
-
if (!inFlightAcquisitions.has(key))
|
|
106
|
-
return undefined;
|
|
107
|
-
return (async () => {
|
|
108
|
-
let pending = inFlightAcquisitions.get(key);
|
|
109
|
-
while (pending) {
|
|
110
|
-
await pending.catch(() => undefined);
|
|
111
|
-
pending = inFlightAcquisitions.get(key);
|
|
112
|
-
}
|
|
113
|
-
})();
|
|
114
|
-
}
|
|
115
|
-
/** Runs a cold acquisition and registers it so concurrent callers wait for it instead of opening their own session. */
|
|
116
|
-
async runColdAcquisition(acquire) {
|
|
117
|
-
const key = this.getSessionKey();
|
|
118
|
-
const acquisition = acquire();
|
|
119
|
-
inFlightAcquisitions.set(key, acquisition);
|
|
120
|
-
try {
|
|
121
|
-
return await acquisition;
|
|
122
|
-
}
|
|
123
|
-
finally {
|
|
124
|
-
if (inFlightAcquisitions.get(key) === acquisition)
|
|
125
|
-
inFlightAcquisitions.delete(key);
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
getSessionKey() {
|
|
129
|
-
// Options that change the cached value are part of the key; JSON avoids '|' collisions between fields.
|
|
130
|
-
const { cookieName, ttlMs } = this.sessionOptions;
|
|
131
|
-
return JSON.stringify([
|
|
132
|
-
this.config.apiHost, this.config.urlContext, this.config.userName(), this.config.plmEnviornment, cookieName, ttlMs,
|
|
133
|
-
]);
|
|
134
|
-
}
|
|
135
|
-
/** Releases the connection of a rejected response before it is replaced by a retry. */
|
|
136
|
-
async discardBody(response) {
|
|
137
|
-
try {
|
|
138
|
-
if (typeof response?.body?.cancel === 'function')
|
|
139
|
-
await response.body.cancel();
|
|
140
|
-
}
|
|
141
|
-
catch (e) {
|
|
142
|
-
// best effort: nothing to do if the body is already consumed or locked
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
getCachedSession() {
|
|
146
|
-
if (!this.sessionOptions.enabled)
|
|
147
|
-
return undefined;
|
|
148
|
-
const key = this.getSessionKey();
|
|
149
|
-
const cachedSessValue = sessionCache.get(key);
|
|
150
|
-
if (!cachedSessValue)
|
|
151
|
-
return undefined;
|
|
152
|
-
if (cachedSessValue.expiresAt <= Date.now()) {
|
|
153
|
-
sessionCache.delete(key);
|
|
154
|
-
return undefined;
|
|
155
|
-
}
|
|
156
|
-
return cachedSessValue.cookie;
|
|
157
|
-
}
|
|
158
|
-
storeSession(cookie) {
|
|
159
|
-
// sliding expiry: Windchill's session timeout is also sliding
|
|
160
|
-
const key = this.getSessionKey();
|
|
161
|
-
// delete first so a refreshed entry moves to the newest position (oldest-first eviction then acts as LRU)
|
|
162
|
-
sessionCache.delete(key);
|
|
163
|
-
pruneSessionCache();
|
|
164
|
-
sessionCache.set(key, { cookie, expiresAt: Date.now() + this.sessionOptions.ttlMs });
|
|
165
|
-
}
|
|
166
|
-
clearSession() {
|
|
167
|
-
sessionCache.delete(this.getSessionKey());
|
|
168
|
-
}
|
|
169
|
-
/** Returns the session cookie value Windchill issued on this response, if any (last one wins). */
|
|
170
|
-
extractSessionCookie(response) {
|
|
171
|
-
const respHeader = response?.headers;
|
|
172
|
-
if (!respHeader)
|
|
173
|
-
return undefined;
|
|
174
|
-
let raw = [];
|
|
175
|
-
if (typeof respHeader.getSetCookie === 'function') {
|
|
176
|
-
raw = respHeader.getSetCookie();
|
|
177
|
-
}
|
|
178
|
-
else if (typeof respHeader.get === 'function' && respHeader.get('set-cookie')) {
|
|
179
|
-
raw = [respHeader.get('set-cookie')];
|
|
180
|
-
}
|
|
181
|
-
const name = this.sessionOptions.cookieName;
|
|
182
|
-
const regexFilter = new RegExp('(?:^|[,\\s])' + escapeRegExp(name) + '=([^;,\\s]+)', 'g');
|
|
183
|
-
let jSession;
|
|
184
|
-
for (const line of raw) {
|
|
185
|
-
let cookieNameMatcher = regexFilter.exec(line);
|
|
186
|
-
while (cookieNameMatcher !== null) {
|
|
187
|
-
jSession = cookieNameMatcher[1];
|
|
188
|
-
cookieNameMatcher = regexFilter.exec(line);
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
return jSession;
|
|
192
|
-
}
|
|
193
|
-
cookieHeader(sessionCookie) {
|
|
194
|
-
return sessionCookie ? `${this.sessionOptions.cookieName}=${sessionCookie}` : undefined;
|
|
195
|
-
}
|
|
196
|
-
/////////////////////////////////////////////////////////////////////////////
|
|
197
|
-
///////// ET-390 - Session reuse: end
|
|
198
|
-
/////////////////////////////////////////////////////////////////////////////
|
|
199
|
-
/////////////////////////////////////////////////////////////////////////////
|
|
200
22
|
///////// Custom getRequestOptions: start
|
|
201
23
|
/////////////////////////////////////////////////////////////////////////////
|
|
202
|
-
|
|
203
|
-
getRequestOptions(method, sessionCookie) {
|
|
24
|
+
getRequestOptions(method) {
|
|
204
25
|
const csrfOptions = {
|
|
205
26
|
method,
|
|
206
27
|
headers: {
|
|
@@ -212,19 +33,9 @@ class FlexPLMConnect {
|
|
|
212
33
|
if (this.staticHeaders) {
|
|
213
34
|
Object.assign(csrfOptions.headers, this.staticHeaders);
|
|
214
35
|
}
|
|
215
|
-
// Added for Session reuse - ET-390 - Starts
|
|
216
|
-
const cookie = this.cookieHeader(sessionCookie);
|
|
217
|
-
if (cookie) {
|
|
218
|
-
csrfOptions.headers['Cookie'] = cookie;
|
|
219
|
-
}
|
|
220
|
-
// Added for Session reuse - ET-390 - Ends
|
|
221
36
|
if (app_framework_1.Logger.isInfoOn()) {
|
|
222
37
|
const logOptions = JSON.parse(JSON.stringify(csrfOptions));
|
|
223
38
|
logOptions['headers']['Authorization'] = logOptions?.headers?.Authorization.substring(0, 9);
|
|
224
|
-
// Added for Session reuse - ET-390 - Starts
|
|
225
|
-
if (logOptions.headers['Cookie'])
|
|
226
|
-
logOptions.headers['Cookie'] = '***masked***';
|
|
227
|
-
// Added for Session reuse - ET-390 - Ends
|
|
228
39
|
console.info('csrfOptions: ' + JSON.stringify(logOptions));
|
|
229
40
|
}
|
|
230
41
|
return csrfOptions;
|
|
@@ -232,52 +43,13 @@ class FlexPLMConnect {
|
|
|
232
43
|
/////////////////////////////////////////////////////////////////////////////
|
|
233
44
|
///////// Custom getRequestOptions: end
|
|
234
45
|
/////////////////////////////////////////////////////////////////////////////
|
|
235
|
-
|
|
236
|
-
// Whenever a getCSRF is called without getNewSession, the default value of false will be used
|
|
237
|
-
// rejectedCookie: the cookie that was rejected by the caller, so a refresh already done by a concurrent event is not thrown away
|
|
238
|
-
async getCSRF(getNewSession = false, rejectedCookie) {
|
|
239
|
-
// Added for Session reuse - ET-390 - Starts
|
|
240
|
-
if (!this.sessionOptions.enabled)
|
|
241
|
-
return this.fetchCSRF(undefined);
|
|
242
|
-
for (let wait = this.waitForInFlightAcquisition(); wait; wait = this.waitForInFlightAcquisition())
|
|
243
|
-
await wait;
|
|
244
|
-
if (getNewSession) {
|
|
245
|
-
const current = this.getCachedSession();
|
|
246
|
-
if (rejectedCookie === undefined || !current || current === rejectedCookie)
|
|
247
|
-
this.clearSession();
|
|
248
|
-
}
|
|
249
|
-
const cached = this.getCachedSession();
|
|
250
|
-
if (cached) {
|
|
251
|
-
try {
|
|
252
|
-
return await this.fetchCSRF(cached);
|
|
253
|
-
}
|
|
254
|
-
catch (e) {
|
|
255
|
-
if (!(e instanceof SessionRejectedError))
|
|
256
|
-
throw e;
|
|
257
|
-
// if the cached cookie is rejected (401/403), drop it and acquire a new session (serialized)
|
|
258
|
-
if (this.getCachedSession() === cached)
|
|
259
|
-
this.clearSession();
|
|
260
|
-
return this.getCSRF();
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
return this.runColdAcquisition(() => this.fetchCSRF(undefined));
|
|
264
|
-
// Added for Session reuse - ET-390 - Ends
|
|
265
|
-
}
|
|
266
|
-
async fetchCSRF(sentCookie) {
|
|
46
|
+
async getCSRF() {
|
|
267
47
|
const urlContext = this.config.urlContext;
|
|
268
48
|
const csrfEndpoint = this.config.csrfEndpoint;
|
|
269
49
|
const csrfURL = this.config.apiHost + urlContext + csrfEndpoint;
|
|
270
50
|
console.info('csrfURL: ' + csrfURL);
|
|
271
|
-
|
|
272
|
-
const csrfOptions = this.getRequestOptions('GET', sentCookie);
|
|
51
|
+
const csrfOptions = this.getRequestOptions('GET');
|
|
273
52
|
const response = await fetch(csrfURL, csrfOptions);
|
|
274
|
-
// Added for Session reuse - ET-390 - Starts
|
|
275
|
-
if (sentCookie && this.sessionOptions.retryStatuses.includes(response.status)) {
|
|
276
|
-
console.warn('Cached FlexPLM session rejected on csrf call (status ' + response.status + '). Retrying with a new session.');
|
|
277
|
-
await this.discardBody(response);
|
|
278
|
-
throw new SessionRejectedError();
|
|
279
|
-
}
|
|
280
|
-
// Added for Session reuse - ET-390 - Ends
|
|
281
53
|
if (response.status >= 300) {
|
|
282
54
|
const message = 'Error connecting to FlexPLM:status: ' + response.status;
|
|
283
55
|
console.error(message);
|
|
@@ -286,24 +58,14 @@ class FlexPLMConnect {
|
|
|
286
58
|
e['httpResponseStatus'] = response.status;
|
|
287
59
|
throw e;
|
|
288
60
|
}
|
|
289
|
-
// Added for Session reuse - ET-390 - Starts
|
|
290
|
-
// If the cookie we sent was invalid, Windchill answers with a fresh Set-Cookie --> replace the cache.
|
|
291
|
-
let sessionCookie = sentCookie;
|
|
292
|
-
if (this.sessionOptions.enabled) {
|
|
293
|
-
sessionCookie = this.extractSessionCookie(response) ?? sentCookie;
|
|
294
|
-
if (sessionCookie)
|
|
295
|
-
this.storeSession(sessionCookie);
|
|
296
|
-
}
|
|
297
|
-
// Added for Session reuse - ET-390 - Ends
|
|
298
61
|
try {
|
|
299
62
|
const body = await response.json();
|
|
300
63
|
const nonce_key = body.items[0].attributes.nonce_key;
|
|
301
64
|
const nonce = body.items[0].attributes.nonce;
|
|
302
|
-
|
|
65
|
+
console.info('nonce_key: ' + nonce_key);
|
|
303
66
|
return {
|
|
304
67
|
nonce_key,
|
|
305
|
-
nonce
|
|
306
|
-
sessionCookie,
|
|
68
|
+
nonce
|
|
307
69
|
};
|
|
308
70
|
}
|
|
309
71
|
catch (e) {
|
|
@@ -317,7 +79,7 @@ class FlexPLMConnect {
|
|
|
317
79
|
if (this.payloadSendAsArray && !Array.isArray(payload)) {
|
|
318
80
|
payload = [payload];
|
|
319
81
|
}
|
|
320
|
-
const xferOptions = this.getRequestOptions('POST'
|
|
82
|
+
const xferOptions = this.getRequestOptions('POST');
|
|
321
83
|
xferOptions['body'] = JSON.stringify(payload);
|
|
322
84
|
xferOptions.headers[csrf.nonce_key] = csrf.nonce;
|
|
323
85
|
const urlContext = this.config.urlContext;
|
|
@@ -328,8 +90,6 @@ class FlexPLMConnect {
|
|
|
328
90
|
const logOptions = JSON.parse(JSON.stringify(xferOptions));
|
|
329
91
|
if (logOptions?.headers?.Authorization)
|
|
330
92
|
logOptions.headers.Authorization = logOptions?.headers?.Authorization.substring(0, 9);
|
|
331
|
-
if (logOptions?.headers?.Cookie)
|
|
332
|
-
logOptions.headers.Cookie = '***masked***';
|
|
333
93
|
if (csrf?.nonce_key)
|
|
334
94
|
logOptions.headers[csrf.nonce_key] = csrf.nonce ? `***masked(length:${csrf.nonce.length})***` : '***masked(empty)***';
|
|
335
95
|
console.info('csrfOptions: ' + JSON.stringify(logOptions));
|
|
@@ -347,22 +107,13 @@ class FlexPLMConnect {
|
|
|
347
107
|
if (app_framework_1.Logger.isInfoOn()) {
|
|
348
108
|
console.info('payload: ' + JSON.stringify(payload));
|
|
349
109
|
}
|
|
350
|
-
|
|
110
|
+
const csrf = await this.getCSRF();
|
|
351
111
|
if (!csrf) {
|
|
352
112
|
const message = 'Failed to get CSRF nonce';
|
|
353
113
|
console.error(message);
|
|
354
114
|
throw new Error(message);
|
|
355
115
|
}
|
|
356
|
-
|
|
357
|
-
// const response = await this.sendRequest(csrf, payload);
|
|
358
|
-
let response = await this.sendRequest(csrf, payload);
|
|
359
|
-
if (csrf.sessionCookie && this.sessionOptions.retryStatuses.includes(response.status)) {
|
|
360
|
-
console.warn('FlexPLM rejected session/nonce (status ' + response.status + '). Getting a new session and retrying once.');
|
|
361
|
-
await this.discardBody(response);
|
|
362
|
-
csrf = await this.getCSRF(true, csrf.sessionCookie);
|
|
363
|
-
response = await this.sendRequest(csrf, payload);
|
|
364
|
-
}
|
|
365
|
-
// Added for Session reuse - ET-390 - Ends
|
|
116
|
+
const response = await this.sendRequest(csrf, payload);
|
|
366
117
|
const status = response.status;
|
|
367
118
|
if (status >= 300) {
|
|
368
119
|
const message = 'Error sending data to FlexPLM:status: ' + response.status;
|
|
@@ -415,35 +166,8 @@ class FlexPLMConnect {
|
|
|
415
166
|
const urlContext = includeUrlContext ? this.config.urlContext : '';
|
|
416
167
|
const path = urlPath || ('/servlet/rest' + this.vibeEventEndpoint);
|
|
417
168
|
const vibeEventsURL = this.config.apiHost + urlContext + path;
|
|
418
|
-
|
|
419
|
-
const
|
|
420
|
-
if (!this.sessionOptions.enabled) {
|
|
421
|
-
return { response: await fetch(vibeEventsURL, this.getRequestOptions('GET')), sent: undefined };
|
|
422
|
-
}
|
|
423
|
-
for (let wait = this.waitForInFlightAcquisition(); wait; wait = this.waitForInFlightAcquisition())
|
|
424
|
-
await wait;
|
|
425
|
-
const sent = this.getCachedSession();
|
|
426
|
-
const call = async () => {
|
|
427
|
-
const res = await fetch(vibeEventsURL, this.getRequestOptions('GET', sent));
|
|
428
|
-
// A rejected cookie must not be stored again; only keep a cookie that was accepted or newly issued.
|
|
429
|
-
if (!(sent && this.sessionOptions.retryStatuses.includes(res.status))) {
|
|
430
|
-
const cookie = this.extractSessionCookie(res) ?? sent;
|
|
431
|
-
if (cookie)
|
|
432
|
-
this.storeSession(cookie);
|
|
433
|
-
}
|
|
434
|
-
return { response: res, sent };
|
|
435
|
-
};
|
|
436
|
-
return sent ? call() : this.runColdAcquisition(call);
|
|
437
|
-
};
|
|
438
|
-
const first = await attempt();
|
|
439
|
-
let response = first.response;
|
|
440
|
-
if (first.sent && this.sessionOptions.retryStatuses.includes(response.status)) {
|
|
441
|
-
await this.discardBody(response);
|
|
442
|
-
if (this.getCachedSession() === first.sent)
|
|
443
|
-
this.clearSession();
|
|
444
|
-
response = (await attempt()).response;
|
|
445
|
-
}
|
|
446
|
-
// Added for Session reuse - ET-390 - Ends
|
|
169
|
+
const csrfOptions = this.getRequestOptions('GET');
|
|
170
|
+
const response = await fetch(vibeEventsURL, csrfOptions);
|
|
447
171
|
if (response.status >= 300) {
|
|
448
172
|
const message = 'Error connecting to FlexPLM:status: ' + response.status;
|
|
449
173
|
console.error(message);
|
|
@@ -28,27 +28,6 @@ const createConfig = (overrides) => ({
|
|
|
28
28
|
useDistinctRestEndPointForImages: false,
|
|
29
29
|
...overrides,
|
|
30
30
|
});
|
|
31
|
-
// Added for Session reuse - ET-390 - Starts
|
|
32
|
-
const csrfBody = { items: [{ attributes: { nonce_key: 'CSRF_NONCE', nonce: 'n1' } }] };
|
|
33
|
-
// Response with Set-Cookie support. setCookie = list of raw Set-Cookie header lines.
|
|
34
|
-
const resp = (status, setCookie = [], json = csrfBody) => ({
|
|
35
|
-
status,
|
|
36
|
-
json: jest.fn().mockResolvedValue(json),
|
|
37
|
-
text: jest.fn().mockResolvedValue('error text'),
|
|
38
|
-
headers: { getSetCookie: () => setCookie, get: () => null },
|
|
39
|
-
});
|
|
40
|
-
let userCounter = 0;
|
|
41
|
-
const uniqueUser = () => 'sess-user-' + (++userCounter);
|
|
42
|
-
// The connector config is flat: keys look like 'flexplmConnect.sessionReuse.enabled'
|
|
43
|
-
const sessionConfig = (user, sessionReuse = { enabled: true }) => {
|
|
44
|
-
const flat = {};
|
|
45
|
-
Object.entries(sessionReuse).forEach(([k, v]) => { flat[`flexplmConnect.sessionReuse.${k}`] = v; });
|
|
46
|
-
return createConfig({ userName: () => user, ...flat });
|
|
47
|
-
};
|
|
48
|
-
const fetchMock = () => global.fetch;
|
|
49
|
-
const callHeaders = (i) => fetchMock().mock.calls[i][1].headers;
|
|
50
|
-
const callMethod = (i) => fetchMock().mock.calls[i][1].method;
|
|
51
|
-
// Added for Session reuse - ET-390 - Ends
|
|
52
31
|
describe('FlexPLMConnect.getRequest', () => {
|
|
53
32
|
it('should call default URL with urlContext when no params provided', async () => {
|
|
54
33
|
const connect = new flexplm_connect_1.FlexPLMConnect(createConfig());
|
|
@@ -142,514 +121,3 @@ describe('FlexPLMConnect.sendRequest', () => {
|
|
|
142
121
|
consoleInfoSpy.mockRestore();
|
|
143
122
|
});
|
|
144
123
|
});
|
|
145
|
-
// Added for Session reuse - ET-390 - Starts
|
|
146
|
-
describe('FlexPLMConnect session reuse', () => {
|
|
147
|
-
const payload = { id: '123' };
|
|
148
|
-
it('should capture JSESSIONID from the CSRF GET and send it on the POST', async () => {
|
|
149
|
-
const u = uniqueUser();
|
|
150
|
-
fetchMock()
|
|
151
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1; Path=/; HttpOnly']))
|
|
152
|
-
.mockResolvedValueOnce(resp(200, [], {}));
|
|
153
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
|
|
154
|
-
expect(fetchMock()).toHaveBeenCalledTimes(2);
|
|
155
|
-
expect(callHeaders(0).Cookie).toBeUndefined(); // first ever call: no cached session
|
|
156
|
-
expect(callHeaders(1).Cookie).toBe('JSESSIONID=abc.tomcat1');
|
|
157
|
-
expect(callHeaders(1).CSRF_NONCE).toBe('n1');
|
|
158
|
-
});
|
|
159
|
-
it('should reuse the cached session on the next event (new FlexPLMConnect instance)', async () => {
|
|
160
|
-
const u = uniqueUser();
|
|
161
|
-
fetchMock()
|
|
162
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1; Path=/'])) // event 1 GET
|
|
163
|
-
.mockResolvedValueOnce(resp(200, [], {})) // event 1 POST
|
|
164
|
-
.mockResolvedValueOnce(resp(200, [])) // event 2 GET (valid session -> no Set-Cookie)
|
|
165
|
-
.mockResolvedValueOnce(resp(200, [], {})); // event 2 POST
|
|
166
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
|
|
167
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
|
|
168
|
-
expect(callHeaders(2).Cookie).toBe('JSESSIONID=abc.tomcat1'); // GET reuses it
|
|
169
|
-
expect(callHeaders(3).Cookie).toBe('JSESSIONID=abc.tomcat1'); // POST reuses it
|
|
170
|
-
});
|
|
171
|
-
it('should replace the cached session when Windchill answers the GET with a new Set-Cookie', async () => {
|
|
172
|
-
const u = uniqueUser();
|
|
173
|
-
fetchMock()
|
|
174
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1; Path=/']))
|
|
175
|
-
.mockResolvedValueOnce(resp(200, [], {}))
|
|
176
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1; Path=/'])) // old one was stale -> new issued
|
|
177
|
-
.mockResolvedValueOnce(resp(200, [], {}))
|
|
178
|
-
.mockResolvedValueOnce(resp(200, []))
|
|
179
|
-
.mockResolvedValueOnce(resp(200, [], {}));
|
|
180
|
-
const connect = () => new flexplm_connect_1.FlexPLMConnect(sessionConfig(u));
|
|
181
|
-
await connect().sendToFlexPLM(payload);
|
|
182
|
-
await connect().sendToFlexPLM(payload);
|
|
183
|
-
await connect().sendToFlexPLM(payload);
|
|
184
|
-
expect(callHeaders(2).Cookie).toBe('JSESSIONID=old.tomcat1'); // event 2 GET sent the old one
|
|
185
|
-
expect(callHeaders(3).Cookie).toBe('JSESSIONID=new.tomcat1'); // POST uses the replacement
|
|
186
|
-
expect(callHeaders(4).Cookie).toBe('JSESSIONID=new.tomcat1'); // event 3 GET sends the replacement
|
|
187
|
-
});
|
|
188
|
-
it('should retry once with a new session when the POST is rejected with 403', async () => {
|
|
189
|
-
const u = uniqueUser();
|
|
190
|
-
fetchMock()
|
|
191
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1; Path=/'])) // GET
|
|
192
|
-
.mockResolvedValueOnce(resp(403, [], {})) // POST rejected
|
|
193
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1; Path=/'])) // GET again, fresh session
|
|
194
|
-
.mockResolvedValueOnce(resp(200, [], { ok: true })); // POST succeeds
|
|
195
|
-
const result = await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
|
|
196
|
-
expect(fetchMock()).toHaveBeenCalledTimes(4);
|
|
197
|
-
expect(callHeaders(2).Cookie).toBeUndefined(); // retry GET must NOT send the stale cookie
|
|
198
|
-
expect(callHeaders(3).Cookie).toBe('JSESSIONID=new.tomcat1');
|
|
199
|
-
expect(result.status).toBe(200);
|
|
200
|
-
expect(result.data).toEqual({ ok: true });
|
|
201
|
-
});
|
|
202
|
-
it('should also retry on 401', async () => {
|
|
203
|
-
const u = uniqueUser();
|
|
204
|
-
fetchMock()
|
|
205
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1']))
|
|
206
|
-
.mockResolvedValueOnce(resp(401, [], {}))
|
|
207
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1']))
|
|
208
|
-
.mockResolvedValueOnce(resp(200, [], {}));
|
|
209
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
|
|
210
|
-
expect(fetchMock()).toHaveBeenCalledTimes(4);
|
|
211
|
-
});
|
|
212
|
-
it('should not loop: a second 403 after the retry is surfaced as an error', async () => {
|
|
213
|
-
const u = uniqueUser();
|
|
214
|
-
fetchMock()
|
|
215
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1']))
|
|
216
|
-
.mockResolvedValueOnce(resp(403, [], {}))
|
|
217
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1']))
|
|
218
|
-
.mockResolvedValueOnce(resp(403, [], {}));
|
|
219
|
-
await expect(new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload))
|
|
220
|
-
.rejects.toThrow('Error sending data to FlexPLM:status: 403');
|
|
221
|
-
expect(fetchMock()).toHaveBeenCalledTimes(4);
|
|
222
|
-
});
|
|
223
|
-
it('should not retry on non-auth errors such as 500 (event may already be processed)', async () => {
|
|
224
|
-
const u = uniqueUser();
|
|
225
|
-
fetchMock()
|
|
226
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']))
|
|
227
|
-
.mockResolvedValueOnce(resp(500, [], {}));
|
|
228
|
-
await expect(new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload))
|
|
229
|
-
.rejects.toThrow('Error sending data to FlexPLM:status: 500');
|
|
230
|
-
expect(fetchMock()).toHaveBeenCalledTimes(2);
|
|
231
|
-
});
|
|
232
|
-
it('should retry the csrf GET without a cookie when the cached session is rejected there', async () => {
|
|
233
|
-
const u = uniqueUser();
|
|
234
|
-
fetchMock()
|
|
235
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1'])) // event 1 GET
|
|
236
|
-
.mockResolvedValueOnce(resp(200, [], {})) // event 1 POST
|
|
237
|
-
.mockResolvedValueOnce(resp(401, [])) // event 2 GET with cached cookie rejected
|
|
238
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1'])) // event 2 GET retry, no cookie
|
|
239
|
-
.mockResolvedValueOnce(resp(200, [], {})); // event 2 POST
|
|
240
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
|
|
241
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
|
|
242
|
-
expect(callHeaders(2).Cookie).toBe('JSESSIONID=old.tomcat1');
|
|
243
|
-
expect(callHeaders(3).Cookie).toBeUndefined();
|
|
244
|
-
expect(callHeaders(4).Cookie).toBe('JSESSIONID=new.tomcat1');
|
|
245
|
-
});
|
|
246
|
-
it('should expire the cached session after ttlSeconds', async () => {
|
|
247
|
-
const u = uniqueUser();
|
|
248
|
-
const realNow = Date.now();
|
|
249
|
-
const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(realNow);
|
|
250
|
-
fetchMock()
|
|
251
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']))
|
|
252
|
-
.mockResolvedValueOnce(resp(200, [], {}))
|
|
253
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=def.tomcat1']))
|
|
254
|
-
.mockResolvedValueOnce(resp(200, [], {}));
|
|
255
|
-
const cfg = sessionConfig(u, { enabled: true, ttlSeconds: 1 });
|
|
256
|
-
await new flexplm_connect_1.FlexPLMConnect(cfg).sendToFlexPLM(payload);
|
|
257
|
-
nowSpy.mockReturnValue(realNow + 2000); // 2s later > 1s ttl
|
|
258
|
-
await new flexplm_connect_1.FlexPLMConnect(cfg).sendToFlexPLM(payload);
|
|
259
|
-
expect(callHeaders(2).Cookie).toBeUndefined(); // expired -> GET sends no cookie
|
|
260
|
-
expect(callHeaders(3).Cookie).toBe('JSESSIONID=def.tomcat1');
|
|
261
|
-
nowSpy.mockRestore();
|
|
262
|
-
});
|
|
263
|
-
it('should use the last JSESSIONID when several Set-Cookie lines are returned', async () => {
|
|
264
|
-
const u = uniqueUser();
|
|
265
|
-
fetchMock()
|
|
266
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=first.tomcat1; Path=/', 'OTHER=x; Path=/', 'JSESSIONID=second.tomcat1; Path=/']))
|
|
267
|
-
.mockResolvedValueOnce(resp(200, [], {}));
|
|
268
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
|
|
269
|
-
expect(callHeaders(1).Cookie).toBe('JSESSIONID=second.tomcat1');
|
|
270
|
-
});
|
|
271
|
-
it('should fall back to headers.get("set-cookie") when getSetCookie is not available', async () => {
|
|
272
|
-
const u = uniqueUser();
|
|
273
|
-
const legacy = {
|
|
274
|
-
status: 200,
|
|
275
|
-
json: jest.fn().mockResolvedValue(csrfBody),
|
|
276
|
-
text: jest.fn(),
|
|
277
|
-
headers: { get: (k) => (k.toLowerCase() === 'set-cookie' ? 'JSESSIONID=legacy.tomcat1; Path=/' : null) },
|
|
278
|
-
};
|
|
279
|
-
fetchMock().mockResolvedValueOnce(legacy).mockResolvedValueOnce(resp(200, [], {}));
|
|
280
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
|
|
281
|
-
expect(callHeaders(1).Cookie).toBe('JSESSIONID=legacy.tomcat1');
|
|
282
|
-
});
|
|
283
|
-
it('should honour a custom cookieName', async () => {
|
|
284
|
-
const u = uniqueUser();
|
|
285
|
-
fetchMock()
|
|
286
|
-
.mockResolvedValueOnce(resp(200, ['MYSESSION=zzz; Path=/', 'JSESSIONID=ignored; Path=/']))
|
|
287
|
-
.mockResolvedValueOnce(resp(200, [], {}));
|
|
288
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: true, cookieName: 'MYSESSION' })).sendToFlexPLM(payload);
|
|
289
|
-
expect(callHeaders(1).Cookie).toBe('MYSESSION=zzz');
|
|
290
|
-
});
|
|
291
|
-
it('should accept enabled as the string "true"', async () => {
|
|
292
|
-
const u = uniqueUser();
|
|
293
|
-
fetchMock()
|
|
294
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']))
|
|
295
|
-
.mockResolvedValueOnce(resp(200, [], {}));
|
|
296
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: 'true' })).sendToFlexPLM(payload);
|
|
297
|
-
expect(callHeaders(1).Cookie).toBe('JSESSIONID=abc.tomcat1');
|
|
298
|
-
});
|
|
299
|
-
it('should evict expired sessions of other users when a new session is stored', async () => {
|
|
300
|
-
const userA = uniqueUser();
|
|
301
|
-
const userB = uniqueUser();
|
|
302
|
-
const realNow = Date.now();
|
|
303
|
-
const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(realNow);
|
|
304
|
-
fetchMock()
|
|
305
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=a.tomcat1'])) // A GET
|
|
306
|
-
.mockResolvedValueOnce(resp(200, [], {})) // A POST
|
|
307
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=b.tomcat1'])) // B GET
|
|
308
|
-
.mockResolvedValueOnce(resp(200, [], {})) // B POST
|
|
309
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=a2.tomcat1'])) // A GET again
|
|
310
|
-
.mockResolvedValueOnce(resp(200, [], {}));
|
|
311
|
-
const cfg = (u) => sessionConfig(u, { enabled: true, ttlSeconds: 1 });
|
|
312
|
-
await new flexplm_connect_1.FlexPLMConnect(cfg(userA)).sendToFlexPLM(payload);
|
|
313
|
-
nowSpy.mockReturnValue(realNow + 2000); // A has expired
|
|
314
|
-
await new flexplm_connect_1.FlexPLMConnect(cfg(userB)).sendToFlexPLM(payload); // storing B sweeps A
|
|
315
|
-
nowSpy.mockReturnValue(realNow); // rewind: only a swept A has no entry left
|
|
316
|
-
await new flexplm_connect_1.FlexPLMConnect(cfg(userA)).sendToFlexPLM(payload);
|
|
317
|
-
expect(callHeaders(4).Cookie).toBeUndefined();
|
|
318
|
-
nowSpy.mockRestore();
|
|
319
|
-
});
|
|
320
|
-
it('should not hold more than the maximum number of cached sessions', async () => {
|
|
321
|
-
const first = uniqueUser();
|
|
322
|
-
fetchMock().mockImplementation(async () => resp(200, ['JSESSIONID=s.tomcat1']));
|
|
323
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(first)).sendToFlexPLM(payload);
|
|
324
|
-
for (let i = 0; i < 100; i++) {
|
|
325
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(uniqueUser())).sendToFlexPLM(payload);
|
|
326
|
-
}
|
|
327
|
-
fetchMock().mockClear();
|
|
328
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(first)).sendToFlexPLM(payload);
|
|
329
|
-
expect(callHeaders(0).Cookie).toBeUndefined(); // oldest entry was evicted
|
|
330
|
-
});
|
|
331
|
-
it('should keep separate sessions per user', async () => {
|
|
332
|
-
const a = uniqueUser();
|
|
333
|
-
const b = uniqueUser();
|
|
334
|
-
fetchMock()
|
|
335
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=aaa.tomcat1']))
|
|
336
|
-
.mockResolvedValueOnce(resp(200, [], {}))
|
|
337
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=bbb.tomcat1']))
|
|
338
|
-
.mockResolvedValueOnce(resp(200, [], {}));
|
|
339
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(a)).sendToFlexPLM(payload);
|
|
340
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(b)).sendToFlexPLM(payload);
|
|
341
|
-
expect(callHeaders(2).Cookie).toBeUndefined(); // user b must not see user a's cookie
|
|
342
|
-
expect(callHeaders(3).Cookie).toBe('JSESSIONID=bbb.tomcat1');
|
|
343
|
-
});
|
|
344
|
-
it('should never log the cookie value', async () => {
|
|
345
|
-
const isInfoOn = jest.spyOn(app_framework_1.Logger, 'isInfoOn').mockReturnValue(true);
|
|
346
|
-
const info = jest.spyOn(console, 'info').mockImplementation();
|
|
347
|
-
const u = uniqueUser();
|
|
348
|
-
fetchMock()
|
|
349
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=supersecret.tomcat1']))
|
|
350
|
-
.mockResolvedValueOnce(resp(200, [], {}))
|
|
351
|
-
.mockResolvedValueOnce(resp(200, []))
|
|
352
|
-
.mockResolvedValueOnce(resp(200, [], {}));
|
|
353
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
|
|
354
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload); // 2nd event sends Cookie on GET and POST
|
|
355
|
-
const logged = info.mock.calls.map(c => String(c[0] ?? '')).join('\n');
|
|
356
|
-
expect(logged).toContain('"Cookie":"***masked***"');
|
|
357
|
-
expect(logged).not.toContain('supersecret');
|
|
358
|
-
isInfoOn.mockRestore();
|
|
359
|
-
info.mockRestore();
|
|
360
|
-
});
|
|
361
|
-
describe('option normalisation', () => {
|
|
362
|
-
const rejectedOnceThenOk = (u, opts) => {
|
|
363
|
-
fetchMock()
|
|
364
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1']))
|
|
365
|
-
.mockResolvedValueOnce(resp(403, [], {}))
|
|
366
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1']))
|
|
367
|
-
.mockResolvedValueOnce(resp(200, [], {}));
|
|
368
|
-
return new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: true, ...opts })).sendToFlexPLM(payload);
|
|
369
|
-
};
|
|
370
|
-
it.each([
|
|
371
|
-
['a scalar number', 403],
|
|
372
|
-
['a comma separated string', '401, 403'],
|
|
373
|
-
['garbage (falls back to 401/403)', 'abc'],
|
|
374
|
-
['an empty array (falls back to 401/403)', []],
|
|
375
|
-
])('should not throw and still retry on 403 when retryStatuses is %s', async (_label, retryStatuses) => {
|
|
376
|
-
await rejectedOnceThenOk(uniqueUser(), { retryStatuses });
|
|
377
|
-
expect(fetchMock()).toHaveBeenCalledTimes(4);
|
|
378
|
-
});
|
|
379
|
-
it.each([['abc'], [0], [-5]])('should fall back to the 900s default when ttlSeconds is invalid (%p)', async (ttlSeconds) => {
|
|
380
|
-
const u = uniqueUser();
|
|
381
|
-
const realNow = Date.now();
|
|
382
|
-
const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(realNow);
|
|
383
|
-
fetchMock()
|
|
384
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']))
|
|
385
|
-
.mockResolvedValueOnce(resp(200, [], {}))
|
|
386
|
-
.mockResolvedValueOnce(resp(200, []))
|
|
387
|
-
.mockResolvedValueOnce(resp(200, [], {}));
|
|
388
|
-
const cfg = sessionConfig(u, { enabled: true, ttlSeconds });
|
|
389
|
-
await new flexplm_connect_1.FlexPLMConnect(cfg).sendToFlexPLM(payload);
|
|
390
|
-
nowSpy.mockReturnValue(realNow + 2000);
|
|
391
|
-
await new flexplm_connect_1.FlexPLMConnect(cfg).sendToFlexPLM(payload);
|
|
392
|
-
expect(callHeaders(2).Cookie).toBe('JSESSIONID=abc.tomcat1');
|
|
393
|
-
nowSpy.mockRestore();
|
|
394
|
-
});
|
|
395
|
-
it('should fall back to JSESSIONID when cookieName is blank', async () => {
|
|
396
|
-
const u = uniqueUser();
|
|
397
|
-
fetchMock()
|
|
398
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']))
|
|
399
|
-
.mockResolvedValueOnce(resp(200, [], {}));
|
|
400
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: true, cookieName: ' ' })).sendToFlexPLM(payload);
|
|
401
|
-
expect(callHeaders(1).Cookie).toBe('JSESSIONID=abc.tomcat1');
|
|
402
|
-
});
|
|
403
|
-
});
|
|
404
|
-
describe('retryStatuses restricted to client-error statuses', () => {
|
|
405
|
-
const postFailsWith = async (status, retryStatuses) => {
|
|
406
|
-
const u = uniqueUser();
|
|
407
|
-
fetchMock()
|
|
408
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']))
|
|
409
|
-
.mockResolvedValueOnce(resp(status, [], {}));
|
|
410
|
-
await expect(new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: true, retryStatuses })).sendToFlexPLM({ id: '1' }))
|
|
411
|
-
.rejects.toThrow('Error sending data to FlexPLM:status: ' + status);
|
|
412
|
-
expect(fetchMock()).toHaveBeenCalledTimes(2); // no retry
|
|
413
|
-
};
|
|
414
|
-
it.each([[500], ['500'], [[200, 500]]])('should ignore non-4xx retryStatuses (%p) and not retry a 500', async (retryStatuses) => {
|
|
415
|
-
await postFailsWith(500, retryStatuses);
|
|
416
|
-
});
|
|
417
|
-
it('should keep 4xx entries and drop others from a mixed retryStatuses list', async () => {
|
|
418
|
-
await postFailsWith(500, [401, 500]);
|
|
419
|
-
});
|
|
420
|
-
it('should not resend a successful event when retryStatuses is configured as 200', async () => {
|
|
421
|
-
const u = uniqueUser();
|
|
422
|
-
fetchMock()
|
|
423
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']))
|
|
424
|
-
.mockResolvedValueOnce(resp(200, [], {}));
|
|
425
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: true, retryStatuses: 200 })).sendToFlexPLM({ id: '1' });
|
|
426
|
-
expect(fetchMock()).toHaveBeenCalledTimes(2);
|
|
427
|
-
});
|
|
428
|
-
});
|
|
429
|
-
describe('session cache key includes session options', () => {
|
|
430
|
-
it('should not share a cached cookie between different cookieNames for the same user', async () => {
|
|
431
|
-
const u = uniqueUser();
|
|
432
|
-
fetchMock()
|
|
433
|
-
.mockResolvedValueOnce(resp(200, ['AAA=a1; Path=/']))
|
|
434
|
-
.mockResolvedValueOnce(resp(200, [], {}))
|
|
435
|
-
.mockResolvedValueOnce(resp(200, ['BBB=b1; Path=/']))
|
|
436
|
-
.mockResolvedValueOnce(resp(200, [], {}));
|
|
437
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: true, cookieName: 'AAA' })).sendToFlexPLM({ id: '1' });
|
|
438
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: true, cookieName: 'BBB' })).sendToFlexPLM({ id: '1' });
|
|
439
|
-
expect(callHeaders(2).Cookie).toBeUndefined(); // BBB config must not pick up the AAA session
|
|
440
|
-
expect(callHeaders(3).Cookie).toBe('BBB=b1');
|
|
441
|
-
});
|
|
442
|
-
it('should not share a cached session between different ttlSeconds for the same user', async () => {
|
|
443
|
-
const u = uniqueUser();
|
|
444
|
-
fetchMock()
|
|
445
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=short.tomcat1']))
|
|
446
|
-
.mockResolvedValueOnce(resp(200, [], {}))
|
|
447
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=long.tomcat1']))
|
|
448
|
-
.mockResolvedValueOnce(resp(200, [], {}));
|
|
449
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: true, ttlSeconds: 1 })).sendToFlexPLM({ id: '1' });
|
|
450
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: true, ttlSeconds: 900 })).sendToFlexPLM({ id: '1' });
|
|
451
|
-
expect(callHeaders(2).Cookie).toBeUndefined();
|
|
452
|
-
expect(callHeaders(3).Cookie).toBe('JSESSIONID=long.tomcat1');
|
|
453
|
-
});
|
|
454
|
-
});
|
|
455
|
-
describe('rejected response disposal', () => {
|
|
456
|
-
const withBody = (r) => Object.assign(r, { body: { cancel: jest.fn().mockResolvedValue(undefined) } });
|
|
457
|
-
it('should cancel the body of a POST rejected with 403 before retrying', async () => {
|
|
458
|
-
const u = uniqueUser();
|
|
459
|
-
const rejected = withBody(resp(403, [], {}));
|
|
460
|
-
fetchMock()
|
|
461
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1']))
|
|
462
|
-
.mockResolvedValueOnce(rejected)
|
|
463
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1']))
|
|
464
|
-
.mockResolvedValueOnce(resp(200, [], {}));
|
|
465
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM({ id: '1' });
|
|
466
|
-
expect(rejected.body.cancel).toHaveBeenCalledTimes(1);
|
|
467
|
-
});
|
|
468
|
-
it('should cancel the body of a CSRF GET rejected with the cached cookie before retrying', async () => {
|
|
469
|
-
const u = uniqueUser();
|
|
470
|
-
const rejected = withBody(resp(401, []));
|
|
471
|
-
fetchMock()
|
|
472
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1']))
|
|
473
|
-
.mockResolvedValueOnce(resp(200, [], {}))
|
|
474
|
-
.mockResolvedValueOnce(rejected)
|
|
475
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1']))
|
|
476
|
-
.mockResolvedValueOnce(resp(200, [], {}));
|
|
477
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM({ id: '1' });
|
|
478
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM({ id: '1' });
|
|
479
|
-
expect(rejected.body.cancel).toHaveBeenCalledTimes(1);
|
|
480
|
-
});
|
|
481
|
-
it('should cancel the body of a getRequest rejected with the cached cookie before retrying', async () => {
|
|
482
|
-
const u = uniqueUser();
|
|
483
|
-
const rejected = withBody(resp(401, []));
|
|
484
|
-
fetchMock()
|
|
485
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1']))
|
|
486
|
-
.mockResolvedValueOnce(resp(200, [], {}))
|
|
487
|
-
.mockResolvedValueOnce(rejected)
|
|
488
|
-
.mockResolvedValueOnce(resp(200, [], { items: [] }));
|
|
489
|
-
const connect = new flexplm_connect_1.FlexPLMConnect(sessionConfig(u));
|
|
490
|
-
await connect.sendToFlexPLM({ id: '1' });
|
|
491
|
-
await connect.getRequest();
|
|
492
|
-
expect(rejected.body.cancel).toHaveBeenCalledTimes(1);
|
|
493
|
-
});
|
|
494
|
-
it('should still retry when cancelling the body throws', async () => {
|
|
495
|
-
const u = uniqueUser();
|
|
496
|
-
const rejected = resp(403, [], {});
|
|
497
|
-
rejected.body = { cancel: jest.fn().mockRejectedValue(new Error('locked')) };
|
|
498
|
-
fetchMock()
|
|
499
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1']))
|
|
500
|
-
.mockResolvedValueOnce(rejected)
|
|
501
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1']))
|
|
502
|
-
.mockResolvedValueOnce(resp(200, [], {}));
|
|
503
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM({ id: '1' });
|
|
504
|
-
expect(fetchMock()).toHaveBeenCalledTimes(4);
|
|
505
|
-
});
|
|
506
|
-
});
|
|
507
|
-
describe('cookie names containing regex metacharacters', () => {
|
|
508
|
-
it('should extract a cookie whose name contains "+"', async () => {
|
|
509
|
-
const u = uniqueUser();
|
|
510
|
-
fetchMock()
|
|
511
|
-
.mockResolvedValueOnce(resp(200, ['SID+=abc; Path=/']))
|
|
512
|
-
.mockResolvedValueOnce(resp(200, [], {}));
|
|
513
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: true, cookieName: 'SID+' })).sendToFlexPLM(payload);
|
|
514
|
-
expect(callHeaders(1).Cookie).toBe('SID+=abc');
|
|
515
|
-
});
|
|
516
|
-
it('should treat "." literally and not match a look-alike cookie', async () => {
|
|
517
|
-
const u = uniqueUser();
|
|
518
|
-
fetchMock()
|
|
519
|
-
.mockResolvedValueOnce(resp(200, ['AxB=wrong; Path=/']))
|
|
520
|
-
.mockResolvedValueOnce(resp(200, [], {}));
|
|
521
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: true, cookieName: 'A.B' })).sendToFlexPLM(payload);
|
|
522
|
-
expect(callHeaders(1).Cookie).toBeUndefined();
|
|
523
|
-
});
|
|
524
|
-
});
|
|
525
|
-
describe('concurrent session acquisition', () => {
|
|
526
|
-
const flush = () => new Promise(r => setImmediate(r));
|
|
527
|
-
const isColdGet = (call) => call[1].method === 'GET' && !call[1].headers.Cookie;
|
|
528
|
-
it('should share one session across concurrent events on a cold cache', async () => {
|
|
529
|
-
const u = uniqueUser();
|
|
530
|
-
let release;
|
|
531
|
-
const gate = new Promise(r => { release = r; });
|
|
532
|
-
fetchMock().mockImplementation(async (_url, opts) => {
|
|
533
|
-
if (opts.method === 'GET' && !opts.headers.Cookie) {
|
|
534
|
-
await gate;
|
|
535
|
-
return resp(200, ['JSESSIONID=abc.tomcat1']);
|
|
536
|
-
}
|
|
537
|
-
return resp(200, []);
|
|
538
|
-
});
|
|
539
|
-
const all = Promise.all([1, 2, 3].map(() => new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).getCSRF()));
|
|
540
|
-
await flush();
|
|
541
|
-
expect(fetchMock()).toHaveBeenCalledTimes(1); // the other two are waiting for the first acquisition
|
|
542
|
-
release();
|
|
543
|
-
const results = await all;
|
|
544
|
-
expect(fetchMock().mock.calls.filter(isColdGet)).toHaveLength(1);
|
|
545
|
-
results.forEach(r => expect(r.sessionCookie).toBe('abc.tomcat1'));
|
|
546
|
-
});
|
|
547
|
-
it('should not make a waiter inherit the failure of the first acquisition', async () => {
|
|
548
|
-
const u = uniqueUser();
|
|
549
|
-
let release;
|
|
550
|
-
const gate = new Promise(r => { release = r; });
|
|
551
|
-
fetchMock()
|
|
552
|
-
.mockImplementationOnce(async () => { await gate; return resp(500, []); })
|
|
553
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']));
|
|
554
|
-
const first = new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).getCSRF();
|
|
555
|
-
const firstResult = first.catch(e => e);
|
|
556
|
-
const second = new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).getCSRF();
|
|
557
|
-
await flush();
|
|
558
|
-
release();
|
|
559
|
-
expect(await firstResult).toBeInstanceOf(Error);
|
|
560
|
-
expect((await second).sessionCookie).toBe('abc.tomcat1');
|
|
561
|
-
});
|
|
562
|
-
it('should create only one replacement session for parallel events rejected with 403', async () => {
|
|
563
|
-
const u = uniqueUser();
|
|
564
|
-
fetchMock().mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1']));
|
|
565
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).getCSRF(); // prime the cache with the old session
|
|
566
|
-
fetchMock().mockReset();
|
|
567
|
-
fetchMock().mockImplementation(async (_url, opts) => {
|
|
568
|
-
const cookie = opts.headers.Cookie;
|
|
569
|
-
if (opts.method === 'POST')
|
|
570
|
-
return cookie === 'JSESSIONID=new.tomcat1' ? resp(200, [], {}) : resp(403, [], {});
|
|
571
|
-
if (!cookie)
|
|
572
|
-
return resp(200, ['JSESSIONID=new.tomcat1']);
|
|
573
|
-
return resp(200, []);
|
|
574
|
-
});
|
|
575
|
-
await Promise.all([1, 2, 3].map(() => new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload)));
|
|
576
|
-
expect(fetchMock().mock.calls.filter(isColdGet)).toHaveLength(1);
|
|
577
|
-
});
|
|
578
|
-
});
|
|
579
|
-
});
|
|
580
|
-
describe('FlexPLMConnect session reuse - feature disabled (default)', () => {
|
|
581
|
-
const payload = { id: '123' };
|
|
582
|
-
it('should send no Cookie header and make exactly one GET + one POST', async () => {
|
|
583
|
-
const u = uniqueUser();
|
|
584
|
-
fetchMock()
|
|
585
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1'])) // Set-Cookie present but must be ignored
|
|
586
|
-
.mockResolvedValueOnce(resp(200, [], {}))
|
|
587
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=def.tomcat1']))
|
|
588
|
-
.mockResolvedValueOnce(resp(200, [], {}));
|
|
589
|
-
const cfg = createConfig({ userName: () => u }); // no flexplmConnect at all
|
|
590
|
-
await new flexplm_connect_1.FlexPLMConnect(cfg).sendToFlexPLM(payload);
|
|
591
|
-
await new flexplm_connect_1.FlexPLMConnect(cfg).sendToFlexPLM(payload);
|
|
592
|
-
for (let i = 0; i < 4; i++) {
|
|
593
|
-
expect(callHeaders(i).Cookie).toBeUndefined();
|
|
594
|
-
}
|
|
595
|
-
});
|
|
596
|
-
it('should not retry on 403 (behaves exactly as before)', async () => {
|
|
597
|
-
const u = uniqueUser();
|
|
598
|
-
fetchMock()
|
|
599
|
-
.mockResolvedValueOnce(resp(200))
|
|
600
|
-
.mockResolvedValueOnce(resp(403, [], {}));
|
|
601
|
-
await expect(new flexplm_connect_1.FlexPLMConnect(createConfig({ userName: () => u })).sendToFlexPLM(payload))
|
|
602
|
-
.rejects.toThrow('Error sending data to FlexPLM:status: 403');
|
|
603
|
-
expect(fetchMock()).toHaveBeenCalledTimes(2);
|
|
604
|
-
});
|
|
605
|
-
it('should behave the same as not configured when enabled is false', async () => {
|
|
606
|
-
const u = uniqueUser();
|
|
607
|
-
fetchMock()
|
|
608
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']))
|
|
609
|
-
.mockResolvedValueOnce(resp(200, [], {}));
|
|
610
|
-
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: false })).sendToFlexPLM(payload);
|
|
611
|
-
expect(callHeaders(1).Cookie).toBeUndefined();
|
|
612
|
-
});
|
|
613
|
-
});
|
|
614
|
-
describe('FlexPLMConnect.getRequest session reuse', () => {
|
|
615
|
-
it('should send the cached cookie on image/GET requests', async () => {
|
|
616
|
-
const u = uniqueUser();
|
|
617
|
-
fetchMock()
|
|
618
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1'])) // csrf GET primes the cache
|
|
619
|
-
.mockResolvedValueOnce(resp(200, [], {})) // POST
|
|
620
|
-
.mockResolvedValueOnce(resp(200, [], { items: [] })); // getRequest
|
|
621
|
-
const connect = new flexplm_connect_1.FlexPLMConnect(sessionConfig(u));
|
|
622
|
-
await connect.sendToFlexPLM({ id: '1' });
|
|
623
|
-
await connect.getRequest();
|
|
624
|
-
expect(callHeaders(2).Cookie).toBe('JSESSIONID=abc.tomcat1');
|
|
625
|
-
});
|
|
626
|
-
it('should retry once without the cookie when the cached session is rejected on getRequest', async () => {
|
|
627
|
-
const u = uniqueUser();
|
|
628
|
-
fetchMock()
|
|
629
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']))
|
|
630
|
-
.mockResolvedValueOnce(resp(200, [], {}))
|
|
631
|
-
.mockResolvedValueOnce(resp(401, [])) // getRequest with cached cookie
|
|
632
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1'], { items: [] })); // retry, no cookie
|
|
633
|
-
const connect = new flexplm_connect_1.FlexPLMConnect(sessionConfig(u));
|
|
634
|
-
await connect.sendToFlexPLM({ id: '1' });
|
|
635
|
-
await connect.getRequest();
|
|
636
|
-
expect(callHeaders(2).Cookie).toBe('JSESSIONID=abc.tomcat1');
|
|
637
|
-
expect(callHeaders(3).Cookie).toBeUndefined();
|
|
638
|
-
});
|
|
639
|
-
it('should not re-store the rejected cookie when the retry issues no Set-Cookie', async () => {
|
|
640
|
-
const u = uniqueUser();
|
|
641
|
-
fetchMock()
|
|
642
|
-
.mockResolvedValueOnce(resp(200, ['JSESSIONID=stale.tomcat1']))
|
|
643
|
-
.mockResolvedValueOnce(resp(200, [], {}))
|
|
644
|
-
.mockResolvedValueOnce(resp(401, [])) // getRequest with the cached cookie
|
|
645
|
-
.mockResolvedValueOnce(resp(200, [], { items: [] })) // retry succeeds, no Set-Cookie
|
|
646
|
-
.mockResolvedValueOnce(resp(200, [], { items: [] })); // next getRequest
|
|
647
|
-
const connect = new flexplm_connect_1.FlexPLMConnect(sessionConfig(u));
|
|
648
|
-
await connect.sendToFlexPLM({ id: '1' });
|
|
649
|
-
await connect.getRequest();
|
|
650
|
-
await connect.getRequest();
|
|
651
|
-
expect(callHeaders(3).Cookie).toBeUndefined();
|
|
652
|
-
expect(callHeaders(4).Cookie).toBeUndefined(); // stale cookie must not be sent again
|
|
653
|
-
});
|
|
654
|
-
});
|
|
655
|
-
// Added for Session reuse - ET-390 - Ends
|