Skip to content

Commit

Permalink
WIP: todo revert
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrew Omondi committed Oct 30, 2024
1 parent 0536e6b commit 3d34eca
Show file tree
Hide file tree
Showing 36 changed files with 258 additions and 298 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import { type ObservabilityOptions, ObservabilityOptionsImpl } from "./observabi
/** Access token provider that leverages the Azure Identity library to retrieve an access token. */
export class AzureIdentityAccessTokenProvider implements AccessTokenProvider {
/**
*@constructor
*@param credentials The tokenCredential implementation to use for authentication.
*@param scopes The scopes to use for authentication.
*@param options The options to use for authentication.
Expand Down Expand Up @@ -55,15 +54,15 @@ export class AzureIdentityAccessTokenProvider implements AccessTokenProvider {
}
});
};
private getAuthorizationTokenInternal = async (url?: string, additionalAuthenticationContext?: Record<string, unknown>, span?: Span): Promise<string> => {
private readonly getAuthorizationTokenInternal = async (url?: string, additionalAuthenticationContext?: Record<string, unknown>, span?: Span): Promise<string> => {
if (!url || !this.allowedHostsValidator.isUrlHostValid(url)) {
span?.setAttribute("com.microsoft.kiota.authentication.is_url_valid", false);
return "";
}
validateProtocol(url);
span?.setAttribute("com.microsoft.kiota.authentication.is_url_valid", true);
let decodedClaims = "";
if (additionalAuthenticationContext && additionalAuthenticationContext[AzureIdentityAccessTokenProvider.claimsKey]) {
if (additionalAuthenticationContext?.[AzureIdentityAccessTokenProvider.claimsKey]) {
const rawClaims = additionalAuthenticationContext[AzureIdentityAccessTokenProvider.claimsKey] as string;
decodedClaims = inNodeEnv() ? Buffer.from(rawClaims, "base64").toString() : atob(rawClaims);
}
Expand All @@ -81,7 +80,7 @@ export class AzureIdentityAccessTokenProvider implements AccessTokenProvider {
const result = await this.credentials.getToken(this.scopes, localOptions);
return result?.token ?? "";
};
private getSchemeAndHostFromUrl = (url: string): string[] => {
private readonly getSchemeAndHostFromUrl = (url: string): string[] => {
const urlParts = url.split("://");
if (urlParts.length === 0) {
// relative url
Expand All @@ -96,13 +95,13 @@ export class AzureIdentityAccessTokenProvider implements AccessTokenProvider {
throw new Error("invalid url");
}
};
private getSchemeFromLocation = (): string => {
private readonly getSchemeFromLocation = (): string => {
if (!inNodeEnv()) {
return window.location.protocol.replace(":", "");
}
return "";
};
private getHostFromLocation = (): string => {
private readonly getHostFromLocation = (): string => {
if (!inNodeEnv()) {
return window.location.host;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ export class AzureAdSpfxAccessTokenProvider implements AccessTokenProvider {
private readonly allowedHostsValidator: AllowedHostsValidator;

/**
*@constructor
*@param tokenProvider The tokenProvider provided by the SharePoint framework
*@param applicationIdUri The application ID URI of the Azure AD App that we want to Authenticate
*@param allowedHosts The allowed hosts to use for authentication.
* @param observabilityOptions
*@param useCachedToken Allows the developer to specify if cached tokens should be returned.
*/
public constructor(
Expand Down Expand Up @@ -52,9 +52,9 @@ export class AzureAdSpfxAccessTokenProvider implements AccessTokenProvider {
}
});
};
private getAuthorizationTokenInternal = async (
private readonly getAuthorizationTokenInternal = async (
url?: string,
// eslint-disable-next-line @typescript-eslint/no-unused-vars

additionalAuthenticationContext?: Record<string, unknown>,
span?: Span,
): Promise<string> => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ import { type ObservabilityOptions, ObservabilityOptionsImpl } from "./observabi

export class AzureAdSpfxAuthenticationProvider extends BaseBearerTokenAuthenticationProvider {
/**
*@constructor
*@param tokenProvider The tokenProvider provided by the SharePoint framework
*@param applicationIdUri The application ID URI of the Azure AD App that we want to Authenticate
*@param allowedHosts The allowed hosts to use for authentication.
* @param observabilityOptions
*@param useCachedToken Allows the developer to specify if cached tokens should be returned.
*/
public constructor(tokenProvider: AadTokenProvider, applicationIdUri: string, allowedHosts: Set<string> = new Set<string>(["graph.microsoft.com", "graph.microsoft.us", "dod-graph.microsoft.us", "graph.microsoft.de", "microsoftgraph.chinacloudapi.cn", "canary.graph.microsoft.com"]), useCachedToken?: boolean, observabilityOptions: ObservabilityOptions = new ObservabilityOptionsImpl()) {
Expand Down
45 changes: 24 additions & 21 deletions packages/http/fetch/src/fetchRequestAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,14 @@ export class FetchRequestAdapter implements RequestAdapter {
this.observabilityOptions = new ObservabilityOptionsImpl(observabilityOptions);
}
}
private getResponseContentType = (response: Response): string | undefined => {
private readonly getResponseContentType = (response: Response): string | undefined => {
const header = response.headers.get("content-type")?.toLowerCase();
if (!header) return undefined;
const segments = header.split(";");
if (segments.length === 0) return undefined;
else return segments[0];
};
private getResponseHandler = (response: RequestInformation): ResponseHandler | undefined => {
private readonly getResponseHandler = (response: RequestInformation): ResponseHandler | undefined => {
const options = response.getRequestOptions();
const responseHandlerOption = options[ResponseHandlerOptionKey] as ResponseHandlerOption;
return responseHandlerOption?.responseHandler;
Expand Down Expand Up @@ -157,7 +157,7 @@ export class FetchRequestAdapter implements RequestAdapter {
}
});
};
private startTracingSpan = <T>(requestInfo: RequestInformation, methodName: string, callback: (arg0: Span) => Promise<T>): Promise<T> => {
private readonly startTracingSpan = <T>(requestInfo: RequestInformation, methodName: string, callback: (arg0: Span) => Promise<T>): Promise<T> => {
const urlTemplate = decodeURIComponent(requestInfo.urlTemplate ?? "");
const telemetryPathValue = urlTemplate.replace(/\{\?[^}]+\}/gi, "");
return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan(`${methodName} - ${telemetryPathValue}`, async (span) => {
Expand Down Expand Up @@ -221,7 +221,7 @@ export class FetchRequestAdapter implements RequestAdapter {
if (this.shouldReturnUndefined(response)) return undefined;
switch (responseType) {
case "ArrayBuffer":
// eslint-disable-next-line no-case-declarations

if (!response.body) {
return undefined;
}
Expand Down Expand Up @@ -264,7 +264,7 @@ export class FetchRequestAdapter implements RequestAdapter {
} finally {
span.end();
}
}) as Promise<ResponseType | undefined>;
});
};
public sendNoResponseContent = (requestInfo: RequestInformation, errorMappings: ErrorMappings | undefined): Promise<void> => {
if (!requestInfo) {
Expand Down Expand Up @@ -308,7 +308,7 @@ export class FetchRequestAdapter implements RequestAdapter {
try {
span.setAttribute(FetchRequestAdapter.responseTypeAttributeKey, "enum");
const result = rootNode.getEnumValue(enumObject);
return result as unknown as EnumObject[keyof EnumObject];
return result as EnumObject[keyof EnumObject];
} finally {
deserializeSpan.end();
}
Expand Down Expand Up @@ -356,15 +356,15 @@ export class FetchRequestAdapter implements RequestAdapter {
}
});
};
public enableBackingStore = (backingStoreFactory?: BackingStoreFactory | undefined): void => {
public enableBackingStore = (backingStoreFactory?: BackingStoreFactory ): void => {
this.parseNodeFactory = enableBackingStoreForParseNodeFactory(this.parseNodeFactory);
this.serializationWriterFactory = enableBackingStoreForSerializationWriterFactory(this.serializationWriterFactory);
if (!this.serializationWriterFactory || !this.parseNodeFactory) throw new Error("unable to enable backing store");
if (backingStoreFactory) {
BackingStoreFactorySingleton.instance = backingStoreFactory;
}
};
private getRootParseNode = (response: Response): Promise<ParseNode> => {
private readonly getRootParseNode = (response: Response): Promise<ParseNode> => {
return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("getRootParseNode", async (span) => {
try {
const payload = await response.arrayBuffer();
Expand All @@ -377,18 +377,21 @@ export class FetchRequestAdapter implements RequestAdapter {
}
});
};
private shouldReturnUndefined = (response: Response): boolean => {
private readonly shouldReturnUndefined = (response: Response): boolean => {
return response.status === 204 || !response.body;
};
/** purges the response body if it hasn't been read to release the connection to the server */
private purgeResponseBody = async (response: Response): Promise<void> => {
/**
* purges the response body if it hasn't been read to release the connection to the server
* @param response
*/
private readonly purgeResponseBody = async (response: Response): Promise<void> => {
if (!response.bodyUsed && response.body) {
await response.arrayBuffer();
}
};
public static readonly errorMappingFoundAttributeName = "com.microsoft.kiota.error.mapping_found";
public static readonly errorBodyFoundAttributeName = "com.microsoft.kiota.error.body_found";
private throwIfFailedResponse = (response: Response, errorMappings: ErrorMappings | undefined, spanForAttributes: Span): Promise<void> => {
private readonly throwIfFailedResponse = (response: Response, errorMappings: ErrorMappings | undefined, spanForAttributes: Span): Promise<void> => {
return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("throwIfFailedResponse", async (span) => {
try {
if (response.ok) return;
Expand Down Expand Up @@ -435,7 +438,7 @@ export class FetchRequestAdapter implements RequestAdapter {
}
});
};
private getHttpResponseMessage = (requestInfo: RequestInformation, spanForAttributes: Span, claims?: string): Promise<Response> => {
private readonly getHttpResponseMessage = (requestInfo: RequestInformation, spanForAttributes: Span, claims?: string): Promise<Response> => {
return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("getHttpResponseMessage", async (span) => {
try {
if (!requestInfo) {
Expand All @@ -444,7 +447,7 @@ export class FetchRequestAdapter implements RequestAdapter {
this.setBaseUrlForRequestInformation(requestInfo);
const additionalContext = {} as Record<string, unknown>;
if (claims) {
additionalContext["claims"] = claims;
additionalContext.claims = claims;
}
await this.authenticationProvider.authenticateRequest(requestInfo, additionalContext);
const request = await this.getRequestFromRequestInformation(requestInfo, spanForAttributes);
Expand Down Expand Up @@ -473,7 +476,7 @@ export class FetchRequestAdapter implements RequestAdapter {
});
};
public static readonly authenticateChallengedEventKey = "com.microsoft.kiota.authenticate_challenge_received";
private retryCAEResponseIfRequired = async (requestInfo: RequestInformation, response: Response, spanForAttributes: Span, claims?: string) => {
private readonly retryCAEResponseIfRequired = async (requestInfo: RequestInformation, response: Response, spanForAttributes: Span, claims?: string) => {
return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("retryCAEResponseIfRequired", async (span) => {
try {
const responseClaims = this.getClaimsFromResponse(response, claims);
Expand All @@ -489,7 +492,7 @@ export class FetchRequestAdapter implements RequestAdapter {
}
});
};
private getClaimsFromResponse = (response: Response, claims?: string) => {
private readonly getClaimsFromResponse = (response: Response, claims?: string) => {
if (response.status === 401 && !claims) {
// avoid infinite loop, we only retry once
// no need to check for the content since it's an array and it doesn't need to be rewound
Expand All @@ -506,16 +509,16 @@ export class FetchRequestAdapter implements RequestAdapter {
}
return undefined;
};
private setBaseUrlForRequestInformation = (requestInfo: RequestInformation): void => {
requestInfo.pathParameters["baseurl"] = this.baseUrl;
private readonly setBaseUrlForRequestInformation = (requestInfo: RequestInformation): void => {
requestInfo.pathParameters.baseurl = this.baseUrl;
};
private getRequestFromRequestInformation = (requestInfo: RequestInformation, spanForAttributes: Span): Promise<RequestInit> => {
private readonly getRequestFromRequestInformation = (requestInfo: RequestInformation, spanForAttributes: Span): Promise<RequestInit> => {
return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("getRequestFromRequestInformation", async (span) => {
try {
const method = requestInfo.httpMethod?.toString();
const uri = requestInfo.URL;
spanForAttributes.setAttribute("http.request.method", method ?? "");
const uriContainsScheme = uri.indexOf("://") > -1;
const uriContainsScheme = uri.includes("://");
const schemeSplatUri = uri.split("://");
if (uriContainsScheme) {
spanForAttributes.setAttribute("server.address", schemeSplatUri[0]);
Expand Down Expand Up @@ -548,7 +551,7 @@ export class FetchRequestAdapter implements RequestAdapter {
}
});
};
private foldHeaderValue = (value: string[] | null): string => {
private readonly foldHeaderValue = (value: string[] | null): string => {
if (!value || value.length < 1) {
return "";
} else if (value.length === 1) {
Expand Down
18 changes: 10 additions & 8 deletions packages/http/fetch/src/httpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,18 @@ import { MiddlewareFactory } from "./";
export class HttpClient {
private middleware: Middleware | undefined;
/**
* @public
* @constructor
*
* Creates an instance of a HttpClient which contains the middlewares and fetch implementation for request execution.
* @param {...Middleware} middleware - The first middleware of the middleware chain or a sequence of all the Middleware handlers
* @param middleware - The first middleware of the middleware chain or a sequence of all the Middleware handlers
* If middlewares param is undefined, the httpClient instance will use the default array of middlewares.
* Set middlewares to `null` if you do not wish to use middlewares.
* @param customFetch
* @param middlewares
* If custom fetch is undefined, the httpClient instance uses the `DefaultFetchHandler`
* @param {(request: string, init?: RequestInit) => Promise < Response >} custom fetch function - a Fetch API implementation
*
* @param custom fetch function - a Fetch API implementation
*/
public constructor(
private customFetch?: (request: string, init: RequestInit) => Promise<Response>,
private readonly customFetch?: (request: string, init: RequestInit) => Promise<Response>,
...middlewares: Middleware[]
) {
// If no middlewares are provided, use the default ones
Expand All @@ -41,10 +41,10 @@ export class HttpClient {
}

/**
* @private
*
* Processes the middleware parameter passed to set this.middleware property
* The calling function should validate if middleware is not undefined or not empty.
* @param {...Middleware} middleware - The middleware passed
* @param middleware - The middleware passed
* @returns Nothing
*/
private setMiddleware(...middleware: Middleware[]): void {
Expand All @@ -58,6 +58,8 @@ export class HttpClient {
* Executes a request and returns a promise resolving the response.
* @param url the request url.
* @param options request options.
* @param requestInit
* @param requestOptions
* @returns the promise resolving the response.
*/
public async executeFetch(url: string, requestInit: RequestInit, requestOptions?: Record<string, RequestOption>): Promise<Response> {
Expand Down
3 changes: 1 addition & 2 deletions packages/http/fetch/src/kiotaClientFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,11 @@ import { Middleware, MiddlewareFactory } from ".";
import { HttpClient } from "./httpClient";

/**
* @class
*
* Class containing function(s) related to the middleware pipelines.
*/
export class KiotaClientFactory {
/**
* @public
* @static
* Returns an instance of HttpClient with the provided middlewares and custom fetch implementation both parameters are optional.
* if not provided, the default fetch implementation and middlewares will be used.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ import { UserAgentHandler } from "../userAgentHandler";
import { CompressionHandler } from "../compressionHandler";

/**
* @class
*
* Class containing function(s) related to the middleware pipelines.
*/
export class MiddlewareFactory {
/**
* @public
* @param customFetch
* @static
* Returns the default middleware chain an array with the middleware handlers
* @returns an array of the middleware handlers of the default middleware chain
Expand Down
Loading

0 comments on commit 3d34eca

Please sign in to comment.