Skip to content

Commit

Permalink
ENG-0000 - More Tweaks/Bug Fixes/Refinements
Browse files Browse the repository at this point in the history
Lots of little things, mostly related to API usage
  • Loading branch information
mcnielsen committed May 9, 2023
1 parent 85e2d75 commit 914aefe
Show file tree
Hide file tree
Showing 6 changed files with 63 additions and 31 deletions.
74 changes: 48 additions & 26 deletions lib/nucleus/src/client/al-base-api-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,18 +112,12 @@ export class AlBaseAPIClient extends AlAbstractClient {
*/
public async resolveDefaultEndpoints( accountId:string, serviceList:string[] ) {
try {
const endpointsRequest:AlNetworkRequestDescriptor = {
method: "POST",
endpoint: {
stack: AlLocation.GlobalAPI,
noAutoResolution: true,
service: "endpoints",
version: 1,
accountId: accountId,
},
let response = await this.context.handleRequest<any>( {
method: 'POST',
url: this.context.resolveURL( AlLocation.GlobalAPI, `/endpoints/v1/${accountId}/residency/default/endpoints` ),
data: serviceList,
};
let response = await this.context.handleRequest( endpointsRequest );
headers: { 'x-aims-auth-token': this.context.getAIMSToken() }
} );
Object.entries( response.data ).forEach( ( [ serviceName, endpointHost ] ) => {
let host = endpointHost as string;
if ( host.startsWith("async.") ) { // naming convention for WebSocket services
Expand All @@ -143,18 +137,12 @@ export class AlBaseAPIClient extends AlAbstractClient {

public async resolveResidencyAwareEndpoints( accountId:string, serviceList:string[] ) {
try {
const endpointsRequest:AlNetworkRequestDescriptor = {
method: "POST",
endpoint: {
stack: AlLocation.GlobalAPI,
service: "endpoints",
version: 1,
accountId: accountId,
path: `/endpoints`,
},
let response = await this.context.handleRequest<any>( {
method: 'POST',
url: this.context.resolveURL( AlLocation.GlobalAPI, `/endpoints/v1/${accountId}/endpoints` ),
data: serviceList,
};
let response = await this.context.handleRequest<any>( endpointsRequest );
headers: { 'x-aims-auth-token': this.context.getAIMSToken() }
} );
Object.entries( response.data ).forEach( ( [ serviceName, residencyLocations ] ) => {
Object.entries(residencyLocations).forEach(([residencyName, residencyHost]) => {
Object.entries(residencyHost).forEach(([datacenterId, endpointHost]) => {
Expand Down Expand Up @@ -301,7 +289,7 @@ export class AlBaseAPIClient extends AlAbstractClient {
// If we are using endpoints resolution to determine our calculated URL, merge globalServiceParams into our descriptoruration
if ( ! descriptor.noAutoResolution
&& ! this.context.getOption<boolean>( ConfigOption.DisableEndpointsResolution, false )
&& ( descriptor.targetEndpoint || ( descriptor.service && AlBaseAPIClient.endpointsStackWhitelist.includes( descriptor.service ) ) ) ) {
&& ( descriptor.targetEndpoint || ( descriptor.service && AlBaseAPIClient.endpointsStackWhitelist.includes( descriptor.stack ) ) ) ) {
// Utilize the endpoints service to determine which location to use for this service/account pair
request.url = await this.prepare( descriptor );
}
Expand Down Expand Up @@ -336,6 +324,9 @@ export class AlBaseAPIClient extends AlAbstractClient {
if ( 'path' in descriptor && descriptor.path.length > 0 ) {
request.url += `${descriptor.path[0] === '/' ? '' : '/'}${descriptor.path}`;
}
if ( 'params' in request ) {
request.url += this.normalizeQueryParams( request.params );
}
return request;
} else {
console.error(`Invalid endpoint descriptor`, descriptor );
Expand All @@ -349,11 +340,12 @@ export class AlBaseAPIClient extends AlAbstractClient {
protected importLegacyRequestConfig( config:APIRequestParams ):AlNetworkRequestDescriptor {
return {
endpoint: {
stack: config.service_stack || undefined,
stack: 'service_stack' in config ? config.service_stack : AlLocation.InsightAPI,
service: config.service_name || undefined,
version: config.version || undefined,
version: 'version' in config ? config.version : 'v1',
path: config.path || undefined,
accountId: config.account_id || undefined,
residency: 'residency' in config ? config.residency : 'default',
noAutoResolution: config.noEndpointsResolution || undefined,
aimsAuthHeader: config.aimsAuthHeader || undefined,
targetEndpoint: config.target_endpoint || undefined
Expand All @@ -362,7 +354,8 @@ export class AlBaseAPIClient extends AlAbstractClient {
headers: config.headers || undefined,
params: config.params || undefined,
credentialed: typeof( config.withCredentials ) === 'boolean' ? config.withCredentials : undefined,
responseType: config.responseType
responseType: config.responseType,
debug: config.debug || undefined
};
}

Expand Down Expand Up @@ -440,5 +433,34 @@ export class AlBaseAPIClient extends AlAbstractClient {
caches.delete( url );
} catch( e ) {}
}

/**
* Normalize query parameters from config api request.
*/
private normalizeQueryParams(params: any):string {
if ( typeof( params ) !== 'object' || ! params ) {
return '';
}
try {
let normalized = Object.entries( params )
.map( ( [ p, v ] ) => {
if ( typeof( v ) === 'undefined' ) {
return null;
}
if( Array.isArray(v) ) {
return v.map( ( arrayValue ) => {
return `${p}=${encodeURIComponent( typeof( arrayValue ) === 'string' ? arrayValue : arrayValue.toString() )}`;
}).join("&");
}
return `${p}=${encodeURIComponent( typeof( v ) === 'string' ? v : v.toString() )}`;
})
.filter( p => p )
.join("&");
return normalized.length > 0 ? `?${normalized}` : '';
} catch( e ) {
console.error( e );
return '';
}
}
}

1 change: 1 addition & 0 deletions lib/nucleus/src/common/types/context.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ export interface AlContextProvider {
defaultAccountId?:string;

resolveURL: (locationId:string, path?:string, queryParams?:{[paramerId:string]:string|number|boolean|null}, context?:any ) => string;
getAIMSToken: () => string | undefined;
getDataItem<Type>( itemName:string, defaultValue?:any|{():any} ):Type;
setDataItem<Type>( itemName:string, value:Type, persistFor?:number );
setOption<Type>( option:ConfigOption, value:Type ):void;
Expand Down
1 change: 1 addition & 0 deletions lib/nucleus/src/common/types/network.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ export interface APIRequestParams {
rawResponse?:boolean; // If set and truthy, the entire response object (not just its data payload) will be emitted as the result of a successful request.

validation?: any;
debug?: boolean;
}

export type ValidRequestSpecifier = AlEndpointDescriptor | AlNetworkRequestDescriptor | APIRequestParams;
15 changes: 11 additions & 4 deletions lib/nucleus/src/context/al-execution-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ export abstract class AlExecutionContext
{
protected static defaultContext?:AlExecutionContext;

public get environment() { return this.locatorService.environment; }
public get residency() { return this.locatorService.residency; }
public get locationId() { return this.locatorService.locationId; }
public get accessibleLocationIds() { return this.locatorService.accessibleLocationIds; }
public get environment() { return this.locatorService?.environment ?? 'production'; }
public get residency() { return this.locatorService?.residency ?? 'US' ; }
public get locationId() { return this.locatorService?.locationId ?? 'unspecified'; }
public get accessibleLocationIds() { return this.locatorService?.accessibleLocationIds ?? []; }
public defaultAccountId?:string;

protected defaultOptions:{[optionKey:string]:string|number|boolean|unknown} = {
Expand Down Expand Up @@ -173,6 +173,13 @@ export abstract class AlExecutionContext
return uri;
}

public getAIMSToken():string|undefined {
if ( this.sessionInstance && this.sessionInstance.isActive() ) {
return this.sessionInstance.getToken();
}
return undefined;
}

public get locator():AlLocatorMatrix {
if ( ! this.locatorService ) {
this.locatorService = new AlLocatorMatrix( AlLocationDictionary, true );
Expand Down
1 change: 1 addition & 0 deletions lib/nucleus/src/session/al-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ export class AlSessionInstance
this.storage.set("session", this.session );
return result;
} catch( e ) {
console.error( e );
AlErrorHandler.log( e, `AlSession.setAuthentication() failed` );
this.deactivateSession();
throw e;
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@al/core",
"version": "2.0.0-beta.4",
"version": "2.0.0-beta.5",
"description": "Node Enterprise Packages for Alert Logic (NEPAL) Core Library",
"main": "./bundles/al-core-nucleus.es5.js",
"types": "./types/al-core-nucleus.d.ts",
Expand Down

0 comments on commit 914aefe

Please sign in to comment.