Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lightspeed: rely on electron's fetch #1498

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion packages/ansible-language-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@
"dependencies": {
"@flatten-js/interval-tree": "^1.1.3",
"antsibull-docs": "^1.0.2",
"axios": "^1.7.2",
"glob": "^10.4.5",
"ini": "^4.1.3",
"lodash": "^4.17.21",
Expand Down
129 changes: 84 additions & 45 deletions packages/ansible-language-server/src/ansibleLanguageService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import { doValidate } from "./providers/validationProvider";
import { ValidationManager } from "./services/validationManager";
import { WorkspaceManager } from "./services/workspaceManager";
import { getAnsibleMetaData } from "./utils/getAnsibleMetaData";
import axios from "axios";
import { AxiosError } from "axios";
import { getBaseUri } from "./utils/webUtils";
import {
Expand All @@ -33,6 +32,15 @@ import {
} from "./interfaces/lightspeedApi";
import { mapError } from "./utils/handleApiError";

export function loadFetch(): typeof fetch | undefined {
try {
return require("electron")?.net?.fetch;
} catch (err) {
// Not available.
}
return undefined;
}

/**
* Initializes the connection and registers all lifecycle event handlers.
*
Expand Down Expand Up @@ -374,28 +382,37 @@ export class AnsibleLanguageService {
Authorization: `Bearer ${accessToken}`,
};

const axiosInstance = axios.create({
baseURL: `${getBaseUri(URL)}/api/v0`,
headers: headers,
const body = JSON.stringify({
content: content,
explanationId: explanationId,
});

const result: ExplanationResponse = await axiosInstance
.post(
"/ai/explanations/",
{
content: content,
explanationId: explanationId,
},
{ signal: AbortSignal.timeout(28000) },
)
.then((response) => {
return response.data;
})
.catch((error) => {
const err = error as AxiosError;
const mappedError: IError = mapError(err);
return mappedError;
});
const fetch = loadFetch();
if (!fetch) {
return { content: "Nothing" } as ExplanationResponse; // TODO
}
const result: ExplanationResponse = await fetch(
`${getBaseUri(URL)}/api/v0/ai/explanations/`,
{
method: "POST",
body,
headers,
},
).then((response) => {
console.log(response);
return response.json();
});
// .post(
// "/ai/explanations/",
// { signal: AbortSignal.timeout(28000) },
// )
//.then((response) => response.json());
// .catch((error) => {
// /* TODO */
// const err = error as AxiosError;
// const mappedError: IError = mapError(err);
// return mappedError;
// });

console.log(result);

Expand All @@ -419,37 +436,59 @@ export class AnsibleLanguageService {
Authorization: `Bearer ${accessToken}`,
};

const axiosInstance = axios.create({
baseURL: `${getBaseUri(URL)}/api/v0`,
headers: headers,
const body = JSON.stringify({
text,
createOutline,
outline,
generationId,
wizardId,
});

const result: GenerationResponse = await axiosInstance
.post(
"/ai/generations/",
{
text,
createOutline,
outline,
generationId,
wizardId,
},
{ signal: AbortSignal.timeout(28000) },
)
.then((response) => {
return response.data;
})
.catch((error) => {
const err = error as AxiosError;
const mappedError: IError = mapError(err);
return mappedError;
});
const fetch = loadFetch();
if (!fetch) {
return {} as GenerationResponse; // TODO
}

const result: GenerationResponse = await fetch(
`${getBaseUri(URL)}/api/v0/ai/generations/`,
{
method: "POST",
body,
headers,
},
).then((response) => {
return response.json();
});

console.log(result);

return result;

// const result: GenerationResponse = await axiosInstance
// .post(
// "/ai/generations/",
// {
// text,
// createOutline,
// outline,
// generationId,
// wizardId,
// },
// { signal: AbortSignal.timeout(28000) },
// )
// .then((response) => {
// return response.data;
// })
// .catch((error) => {
// const err = error as AxiosError;
// const mappedError: IError = mapError(err);
// return mappedError;
// });

// return result;
},
);
}

private handleError(error: unknown, contextName: string) {
const leadMessage = `An error occurred in '${contextName}' handler: `;
if (error instanceof Error) {
Expand Down
13 changes: 13 additions & 0 deletions src/features/lightspeed/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,3 +190,16 @@ export class LightSpeedManager {
);
}
}

// See:
// https://github.com/Microsoft/vscode/issues/12588#issuecomment-2111861237
// https://github.com/microsoft/vscode/pull/198408
// https://github.com/chrmarti/vscode-network-proxy-test/blob/main/src/extension.ts#L245-L252
export function loadFetch(): typeof fetch | undefined {
try {
return require("electron")?.net?.fetch;
} catch (err) {
// Not available.
}
return undefined;
}
90 changes: 49 additions & 41 deletions src/features/lightspeed/lightSpeedOAuthProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {
} from "../../definitions/lightspeed";
import { LightspeedAuthSession } from "../../interfaces/lightspeed";
import { lightSpeedManager } from "../../extension";
import { loadFetch } from "../lightspeed/base";

const CODE_VERIFIER = generateCodeVerifier();
const CODE_CHALLENGE = generateCodeChallengeFromVerifier(CODE_VERIFIER);
Expand Down Expand Up @@ -154,6 +155,8 @@ export class LightSpeedAuthenticationProvider
try {
lightSpeedManager.currentModelValue = undefined;
const account = await this.login(scopes);
console.log("account");
console.log(account);

if (!account) {
throw new Error(`Ansible Lightspeed login failure`);
Expand All @@ -162,6 +165,8 @@ export class LightSpeedAuthenticationProvider
const userinfo: LoggedInUserInfo = await this.getUserInfo(
account.accessToken,
);
console.log("userinfo");
console.log(userinfo);

const identifier = uuid();
const userName = userinfo.external_username || userinfo.username || "";
Expand Down Expand Up @@ -194,6 +199,7 @@ export class LightSpeedAuthenticationProvider
? userinfo.rh_user_is_org_admin
: false,
};
console.log(session);
await this.context.secrets.store(
SESSIONS_SECRET_KEY,
JSON.stringify([session]),
Expand Down Expand Up @@ -362,26 +368,36 @@ export class LightSpeedAuthenticationProvider
"Content-Type": "application/x-www-form-urlencoded",
};

const postData = {
const body = new URLSearchParams({
client_id: LIGHTSPEED_CLIENT_ID,
code: code,
code_verifier: CODE_VERIFIER,
redirect_uri: this._externalRedirectUri,
grant_type: "authorization_code",
};
});

console.log(
"[ansible-lightspeed-oauth] Sending request for access token...",
);

console.log(body);

const fetch = loadFetch();
if (!fetch) {
return;
}
try {
const { data } = await axios.post(
const response = await fetch(
`${getBaseUri(this.settingsManager)}/o/token/`,
postData,
{
headers: headers,
method: "POST",
body,
headers,
},
);
console.log(`requestOAuthAccountFromCode: ${response}`);
const data = await response.json();
console.log(data);

const account: OAuthAccount = {
type: "oauth",
Expand All @@ -395,6 +411,7 @@ export class LightSpeedAuthenticationProvider

return account;
} catch (error) {
/* TODO */
if (axios.isAxiosError(error)) {
console.error(
"[ansible-lightspeed-oauth] error message: ",
Expand Down Expand Up @@ -422,28 +439,33 @@ export class LightSpeedAuthenticationProvider
"Content-Type": "application/x-www-form-urlencoded",
};

const postData = {
const body = JSON.stringify({
client_id: LIGHTSPEED_CLIENT_ID,
refresh_token: currentAccount.refreshToken,
grant_type: "refresh_token",
};
});

console.log(
"[ansible-lightspeed-oauth] Sending request for a new access token...",
);

const fetch = loadFetch();
if (!fetch) {
return;
}
const account = await window.withProgress(
{
title: "Refreshing token",
location: ProgressLocation.Notification,
},
async () => {
return axios
.post(`${getBaseUri(this.settingsManager)}/o/token/`, postData, {
headers: headers,
})
.then((response) => {
const data = response.data;
return fetch(`${getBaseUri(this.settingsManager)}/o/token/`, {
method: "POST",
body,
headers,
})
.then((response) => response.json())
.then((data) => {
const account: OAuthAccount = {
...currentAccount,
accessToken: data.access_token,
Expand Down Expand Up @@ -559,36 +581,22 @@ export class LightSpeedAuthenticationProvider
/* Get the user info from server */
private async getUserInfo(token: string) {
console.log(
"[ansible-lightspeed-oauth] Sending request for logged-in user info...",
"[ansible-lightspeed-oauth] Sending request for logged-in user info1...",
);

try {
const { data } = await axios.get(
`${getBaseUri(this.settingsManager)}${LIGHTSPEED_ME_AUTH_URL}`,
{
headers: {
Authorization: `Bearer ${token}`,
},
},
);

return data;
} catch (error) {
if (axios.isAxiosError(error)) {
console.error(
"[ansible-lightspeed-oauth] error message: ",
error.message,
);
console.error(
"[ansible-lightspeed-oauth] error response data: ",
error.response?.data,
);
throw new Error(error.message);
} else {
console.error("[ansible-lightspeed-oauth] unexpected error: ", error);
throw new Error("An unexpected error occurred");
}
const headers = {
Authorization: `Bearer ${token}`,
};
const fetch = loadFetch();
if (!fetch) {
return;
}
const response = await fetch(
`${getBaseUri(this.settingsManager)}${LIGHTSPEED_ME_AUTH_URL}`,
{
headers,
},
);
return response.json();
}

/* Return session info if user is authenticated, else undefined */
Expand Down
Loading
Loading