Skip to content

Commit f541e0e

Browse files
committed
implemented connect and run
1 parent 7a5c24e commit f541e0e

File tree

6 files changed

+100
-266
lines changed

6 files changed

+100
-266
lines changed

src/classes/localConnection.ts

Lines changed: 63 additions & 174 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ import { commands } from "vscode";
1919
import { ext } from "../extensionVariables";
2020
import { QueryResult, QueryResultType } from "../models/queryResult";
2121
import { ServerObject } from "../models/serverObject";
22-
import { delay } from "../utils/core";
2322
import { convertStringToArray, handleQueryResults } from "../utils/execution";
2423
import { MessageKind, notify } from "../utils/notifications";
2524
import { queryWrapper } from "../utils/queryUtils";
@@ -32,8 +31,6 @@ export class LocalConnection {
3231
public labels: string[];
3332
private options: nodeq.ConnectionParameters;
3433
private connection?: nodeq.Connection;
35-
private isError: boolean = false;
36-
private result?: string;
3734

3835
constructor(
3936
connectionString: string,
@@ -80,35 +77,30 @@ export class LocalConnection {
8077
return this.connection;
8178
}
8279

83-
public async connect(
84-
callback: nodeq.AsyncValueCallback<LocalConnection>,
85-
): Promise<void> {
86-
if (this.connection && this.connected) return;
87-
80+
public async connect() {
8881
const options = await this.getCustomAuthOptions();
89-
90-
nodeq.connect(options, (err, conn) => {
91-
if (err || !conn) {
92-
ext.serverProvider.reload();
93-
this.connection = undefined;
94-
this.connected = false;
95-
callback(err, this);
96-
return;
97-
}
98-
99-
conn.addListener("close", () => {
100-
commands.executeCommand("kdb.connections.disconnect", this.connLabel);
101-
notify(
102-
`Connection closed: ${this.options.host}:${this.options.port}`,
103-
MessageKind.DEBUG,
104-
{ logger },
105-
);
82+
return new Promise<nodeq.Connection>((resolve, reject) => {
83+
nodeq.connect(options, (err, conn) => {
84+
if (err || !conn) {
85+
ext.serverProvider.reload();
86+
this.connection = undefined;
87+
this.connected = false;
88+
reject(err);
89+
return;
90+
}
91+
conn.addListener("close", () => {
92+
commands.executeCommand("kdb.connections.disconnect", this.connLabel);
93+
notify(
94+
`Connection closed: ${this.options.host}:${this.options.port}`,
95+
MessageKind.DEBUG,
96+
{ logger },
97+
);
98+
});
99+
this.connection = conn;
100+
this.connected = true;
101+
this.update();
102+
resolve(conn);
106103
});
107-
108-
this.connection = conn;
109-
this.connected = true;
110-
this.update();
111-
callback(err, this);
112104
});
113105
}
114106

@@ -125,131 +117,60 @@ export class LocalConnection {
125117
this.updateReservedKeywords();
126118
}
127119

128-
public async execute(query: string): Promise<string | Error> {
129-
let result;
130-
let error;
131-
let retryCount = 0;
132-
while (this.connection === undefined) {
133-
if (retryCount > ext.maxRetryCount) {
134-
return "timeout";
135-
}
136-
await delay(500);
137-
retryCount++;
138-
}
139-
140-
this.connection.k(query, function (err: Error, res: string) {
141-
if (err) {
142-
error = err;
143-
result = "";
144-
return;
145-
}
146-
result = res;
147-
});
148-
149-
// wait for result (lack of await using callbacks)
150-
while (result === undefined || result === null) {
151-
await delay(500);
152-
}
153-
154-
if (error) {
155-
throw error;
156-
}
157-
158-
return result;
159-
}
160-
161120
public async executeQuery(
162121
command: string,
163122
context?: string,
164123
stringify?: boolean,
165124
isPython?: boolean,
166125
): Promise<any> {
167-
let result;
168-
await this.waitForConnection();
169-
170-
if (!this.connection) {
171-
return "timeout";
172-
}
173-
const args: any[] = [];
174-
const wrapper = queryWrapper(!!isPython);
175-
176-
if (isPython) {
177-
args.push(stringify ? "text" : "serialized", command, "first", 10000);
178-
} else {
179-
args.push(context ?? ".", command, stringify ? "text" : "structuredText");
180-
}
181-
182-
args.push((err: Error, res: QueryResult) => {
183-
if (err) {
184-
this.isError = true;
185-
result = handleQueryResults(err.toString(), QueryResultType.Error);
186-
}
187-
if (res) {
188-
if (res.errored) {
189-
this.isError = true;
190-
result = handleQueryResults(
191-
res.error + (res.backtrace ? "\n" + res.backtrace : ""),
192-
QueryResultType.Error,
193-
);
126+
return new Promise((resolve, reject) => {
127+
if (this.connection) {
128+
const args: any[] = [];
129+
const wrapper = queryWrapper(!!isPython);
130+
if (isPython) {
131+
args.push(stringify ? "text" : "serialized", command, "first", 10000);
194132
} else {
195-
result = res.result === null ? "" : res.result;
133+
args.push(
134+
context ?? ".",
135+
command,
136+
stringify ? "text" : "structuredText",
137+
);
196138
}
197-
}
139+
this.connection.k(wrapper, ...args, (err: Error, res: QueryResult) => {
140+
if (err) {
141+
reject(handleQueryResults(err.toString(), QueryResultType.Error));
142+
} else if (res.errored) {
143+
resolve(
144+
handleQueryResults(
145+
res.error + (res.backtrace ? "\n" + res.backtrace : ""),
146+
QueryResultType.Error,
147+
),
148+
);
149+
} else {
150+
const result = res.result === null ? "" : res.result;
151+
if (!stringify && !isPython) {
152+
resolve(JSON.parse(result));
153+
} else if (ext.isResultsTabVisible && stringify) {
154+
resolve(convertStringToArray(result ? result : ""));
155+
} else {
156+
resolve(result);
157+
}
158+
}
159+
this.updateGlobal();
160+
});
161+
} else reject(new Error("Not connected."));
198162
});
199-
200-
this.connection.k(wrapper, ...args);
201-
202-
while (result === undefined || result === null) {
203-
await delay(50);
204-
}
205-
206-
this.updateGlobal();
207-
208-
if (this.isError) {
209-
this.isError = false;
210-
return result;
211-
}
212-
213-
if (!stringify && !isPython) {
214-
return JSON.parse(result);
215-
}
216-
217-
if (ext.isResultsTabVisible && stringify) {
218-
return convertStringToArray(result ? result : "");
219-
}
220-
221-
return result;
222163
}
223164

224165
public async executeQueryRaw(command: string): Promise<any> {
225-
let result;
226-
let retryCount = 0;
227-
let error;
228-
while (this.connection === undefined) {
229-
if (retryCount > ext.maxRetryCount) {
230-
return "timeout";
231-
}
232-
await delay(500);
233-
retryCount++;
234-
}
235-
this.connection.k(command, (err: Error, res: any) => {
236-
if (err) {
237-
error = err;
238-
result = "";
239-
return;
240-
}
241-
result = res;
166+
return new Promise((resolve, reject) => {
167+
if (this.connection) {
168+
this.connection.k(command, (err: Error, res: any) => {
169+
if (err) reject(err);
170+
else resolve(res || "");
171+
});
172+
} else reject(new Error("Not connected."));
242173
});
243-
244-
while (result === undefined || result === null) {
245-
await delay(500);
246-
}
247-
248-
if (error) {
249-
throw error;
250-
}
251-
252-
return result;
253174
}
254175

255176
public async loadServerObjects(): Promise<ServerObject[]> {
@@ -276,38 +197,6 @@ export class LocalConnection {
276197
}
277198
}
278199

279-
private async waitForConnection(): Promise<void> {
280-
let retryCount = 0;
281-
while (this.connection === undefined) {
282-
if (retryCount > ext.maxRetryCount) {
283-
throw new Error("timeout");
284-
}
285-
await delay(500);
286-
retryCount++;
287-
}
288-
}
289-
290-
private handleQueryResult(res: QueryResult): void {
291-
if (res.errored) {
292-
this.isError = true;
293-
this.result = handleQueryResults(
294-
res.error + (res.backtrace ? "\n" + res.backtrace : ""),
295-
QueryResultType.Error,
296-
);
297-
} else {
298-
this.result = res.result;
299-
}
300-
}
301-
302-
private async waitForResult(): Promise<any> {
303-
while (this.result === undefined || this.result === null) {
304-
await delay(500);
305-
}
306-
const result = this.result;
307-
this.result = undefined;
308-
return result;
309-
}
310-
311200
private updateGlobal() {
312201
const globalQuery =
313202
'{[q] t:system"T";tm:@[{$[x>0;[system"T ",string x;1b];0b]};0;{0b}];r:$[tm;@[0;(q;::);{[tm; t; msgs] if[tm;system"T ",string t];\'msgs}[tm;t]];@[q;::;{\'x}]];if[tm;system"T ",string t];r}{do[1000;2+2];{@[{.z.ide.ns.r1:x;:.z.ide.ns.r1};x;{r:y;:r}[;x]]}({:x!{![sv[`;] each x cross `Tables`Functions`Variables; system each "afv" cross enlist[" "] cross enlist string x]} each x} [{raze x,.z.s\'[{x where{@[{1#get x};x;`]~1#.q}\'[x]}` sv\'x,\'key x]}`]),(enlist `.z)!flip (`.z.Tables`.z.Functions`.z.Variables)!(enlist 0#`;enlist `ac`bm`exit`pc`pd`pg`ph`pi`pm`po`pp`ps`pw`vs`ts`s`wc`wo`ws;enlist `a`b`e`f`h`i`k`K`l`o`q`u`w`W`x`X`n`N`p`P`z`Z`t`T`d`D`c`zd)}';

src/commands/workspaceCommand.ts

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -726,20 +726,18 @@ export async function findConnection(uri: Uri) {
726726
server = node.label;
727727
conn = connMngService.retrieveConnectedConnection(server);
728728
if (conn === undefined) {
729-
offerConnectAction(server);
730-
return;
729+
const res = await offerConnectAction(server);
730+
if (res) {
731+
conn = connMngService.retrieveConnectedConnection(server);
732+
}
731733
}
732734
} else {
733735
notify(`Connection ${server} not found.`, MessageKind.ERROR, {
734736
logger,
735737
});
736-
return;
737738
}
738-
} else if (ext.activeConnection) {
739-
conn = ext.activeConnection;
740739
} else {
741-
offerConnectAction();
742-
return;
740+
await offerConnectAction();
743741
}
744742
return conn;
745743
/* c8 ignore stop */

src/services/connectionManagerService.ts

Lines changed: 18 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -146,28 +146,23 @@ export class ConnectionManagementService {
146146
authCredentials ? authCredentials.split(":") : undefined,
147147
connection.details.tls,
148148
);
149-
await localConnection.connect((err, conn) => {
150-
if (err) {
151-
this.connectFailBehaviour(connLabel, err);
152-
return;
153-
}
154-
if (conn) {
155-
notify(
156-
`Connection established successfully to: ${connLabel}`,
157-
MessageKind.DEBUG,
158-
{
159-
logger,
160-
telemetry:
161-
"Connection.Connected" +
162-
this.getTelemetryConnectionType(connLabel),
163-
},
164-
);
165-
166-
ext.connectedConnectionList.push(localConnection);
167-
168-
this.connectSuccessBehaviour(connection);
169-
}
170-
});
149+
const conn = await localConnection.connect();
150+
if (conn) {
151+
notify(
152+
`Connection established successfully to: ${connLabel}`,
153+
MessageKind.DEBUG,
154+
{
155+
logger,
156+
telemetry:
157+
"Connection.Connected" +
158+
this.getTelemetryConnectionType(connLabel),
159+
},
160+
);
161+
162+
ext.connectedConnectionList.push(localConnection);
163+
164+
this.connectSuccessBehaviour(connection);
165+
}
171166
} else {
172167
ext.context.secrets.delete(connection.details.alias);
173168
const insightsConn: InsightsConnection = new InsightsConnection(
@@ -212,22 +207,8 @@ export class ConnectionManagementService {
212207
logger,
213208
telemetry: "Connection.Connected.Active",
214209
});
210+
commands.executeCommand("setContext", "kdb.pythonEnabled", true);
215211
ext.activeConnection = connection;
216-
217-
if (node instanceof InsightsNode) {
218-
commands.executeCommand("setContext", "kdb.pythonEnabled", true);
219-
} else if (connection instanceof LocalConnection) {
220-
// check if pykx namespace is defined
221-
connection
222-
.execute("`pykx in key`")
223-
.then((res) => {
224-
commands.executeCommand("setContext", "kdb.pythonEnabled", !!res);
225-
})
226-
.catch(() => {
227-
commands.executeCommand("setContext", "kdb.pythonEnabled", false);
228-
});
229-
}
230-
231212
ext.connectionNode = node;
232213
ext.serverProvider.reload();
233214
}

0 commit comments

Comments
 (0)