⚡️ limit to avoid max msg size with socketio

This commit is contained in:
Nate Sesti 2023-10-31 17:30:03 -07:00
parent 3eec4bacdc
commit 85ea710f40
10 changed files with 708 additions and 723 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -65,26 +65,28 @@ class IdeProtocolClient {
transports: ["websocket", "polling", "flashsocket"],
});
this.socket.on("message", (message) => {
this.socket.on("message", (message, callback) => {
const {
message_type: messageType,
data,
message_id: messageId,
} = message;
this.handleMessage(messageType, data, messageId).catch((err) => {
console.log("Error handling message: ", err);
vscode.window
.showErrorMessage(
`Error handling message (${messageType}) from Continue server: ` +
err,
"View Logs"
)
.then((selection) => {
if (selection === "View Logs") {
vscode.commands.executeCommand("continue.viewLogs");
}
});
});
this.handleMessage(messageType, data, messageId, callback).catch(
(err) => {
console.log("Error handling message: ", err);
vscode.window
.showErrorMessage(
`Error handling message (${messageType}) from Continue server: ` +
err,
"View Logs"
)
.then((selection) => {
if (selection === "View Logs") {
vscode.commands.executeCommand("continue.viewLogs");
}
});
}
);
});
// Listen for new file creation
@ -197,57 +199,69 @@ class IdeProtocolClient {
visibleMessages: Set<string> = new Set();
async handleMessage(messageType: string, data: any, messageId: string) {
async handleMessage(
messageType: string,
data: any,
messageId: string,
callback: (data: any) => void
) {
const respond = (messageType: string, responseData: any) => {
callback({
message_type: messageType,
data: responseData,
message_id: messageId,
});
};
switch (messageType) {
case "highlightedCode":
this.send("highlightedCode", messageId, {
respond("highlightedCode", {
highlightedCode: this.getHighlightedCode(),
});
break;
case "workspaceDirectory":
this.send("workspaceDirectory", messageId, {
respond("workspaceDirectory", {
workspaceDirectory: this.getWorkspaceDirectory(),
});
break;
case "uniqueId":
this.send("uniqueId", messageId, {
respond("uniqueId", {
uniqueId: this.getUniqueId(),
});
break;
case "ide":
this.send("ide", messageId, {
respond("ide", {
name: "vscode",
version: vscode.version,
remoteName: vscode.env.remoteName,
});
break;
case "fileExists":
this.send("fileExists", messageId, {
respond("fileExists", {
exists: await this.fileExists(data.filepath),
});
break;
case "getUserSecret":
this.send("getUserSecret", messageId, {
respond("getUserSecret", {
value: await this.getUserSecret(data.key),
});
break;
case "openFiles":
this.send("openFiles", messageId, {
respond("openFiles", {
openFiles: this.getOpenFiles(),
});
break;
case "visibleFiles":
this.send("visibleFiles", messageId, {
respond("visibleFiles", {
visibleFiles: this.getVisibleFiles(),
});
break;
case "readFile":
this.send("readFile", messageId, {
respond("readFile", {
contents: await this.readFile(data.filepath),
});
break;
case "getTerminalContents":
this.send("getTerminalContents", messageId, {
respond("getTerminalContents", {
contents: await this.getTerminalContents(data.commands),
});
break;
@ -262,13 +276,13 @@ class IdeProtocolClient {
console.log("Error listing directory contents: ", e);
contents = [];
}
this.send("listDirectoryContents", messageId, {
respond("listDirectoryContents", {
contents,
});
break;
case "editFile":
const fileEdit = await this.editFile(data.edit);
this.send("editFile", messageId, {
respond("editFile", {
fileEdit,
});
break;
@ -276,7 +290,7 @@ class IdeProtocolClient {
this.highlightCode(data.rangeInFile, data.color);
break;
case "runCommand":
this.send("runCommand", messageId, {
respond("runCommand", {
output: await this.runCommand(data.command),
});
break;
@ -556,19 +570,24 @@ class IdeProtocolClient {
}
async readFile(filepath: string): Promise<string> {
const MAX_BYTES = 500000; // 0.5MB - socket.io has a 1MB limit, but seems to die a bit above 0.5MB
let contents: string | undefined;
if (typeof contents === "undefined") {
try {
const fileStats = await vscode.workspace.fs.stat(
uriFromFilePath(filepath)
);
if (fileStats.size > 1000000) {
if (fileStats.size > 10 * MAX_BYTES) {
return "";
}
contents = await vscode.workspace.fs
.readFile(uriFromFilePath(filepath))
.then((bytes) => new TextDecoder().decode(bytes));
const bytes = await vscode.workspace.fs.readFile(
uriFromFilePath(filepath)
);
// Truncate the buffer to the first MAX_BYTES
const truncatedBytes = bytes.slice(0, MAX_BYTES);
contents = new TextDecoder().decode(truncatedBytes);
} catch {
contents = "";
}

View file

@ -343,18 +343,19 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
>(undefined);
const availableSlashCommands = useSelector(
(state: RootStore) => state.serverState.slashCommands
).map((cmd) => {
return {
name: `/${cmd.name}`,
description: cmd.description,
};
});
(state: RootStore) =>
state.serverState.slashCommands?.map((cmd) => {
return {
name: `/${cmd.name}`,
description: cmd.description,
};
}) || []
);
const selectedContextItems = useSelector((state: RootStore) => {
if (typeof props.index !== "undefined") {
return state.sessionState.contextItemsAtIndex[props.index] || [];
} else {
return state.sessionState.context_items;
return state.sessionState.context_items || [];
}
});

View file

@ -49,6 +49,7 @@ function useSetup(
!requestedTitle &&
!active &&
title === "New Session" &&
history &&
history.filter((step) => !step.hide).length >= 2
) {
setRequestedTitle(true);

View file

@ -555,7 +555,7 @@ function GUI(props: GUIProps) {
}}
/>
<div className="flex gap-2">
{sessionState.history.filter((n) => !n.hide).length > 0 && (
{sessionState?.history?.filter((n) => !n.hide).length > 0 && (
<HeaderButtonWithText
onClick={() => {
client?.stopSession();
@ -650,7 +650,7 @@ function GUI(props: GUIProps) {
)}
<br />
<StepsDiv>
{sessionState.history.map((step: StepDescription, index: number) => {
{sessionState?.history?.map((step: StepDescription, index: number) => {
if (step.hide) return null;
return (
<Fragment key={index}>

View file

@ -72,9 +72,9 @@ const windowIDTransform = (windowID) =>
const persistConfig = {
key: "root",
storage,
transforms: [
windowIDTransform((window as any).windowId || "undefinedWindowId"),
],
// transforms: [
// windowIDTransform((window as any).windowId || "undefinedWindowId"),
// ],
};
const persistedReducer = persistReducer(persistConfig, rootReducer);

View file

@ -96,9 +96,10 @@ class FileContextProvider(ContextProvider):
)
async def get_context_item_for_filepath(
self, absolute_filepath: str
self, absolute_filepath: str, content: Optional[str] = None
) -> Optional[ContextItem]:
content = await get_file_contents(absolute_filepath, self.ide)
if content is None:
content = await get_file_contents(absolute_filepath, self.ide)
if content is None:
return None
@ -143,7 +144,8 @@ class FileContextProvider(ContextProvider):
items = []
i = 0
delta = 1
timeout = 0.1
delta = 100
while i < len(absolute_filepaths):
# Don't want to flood with too many requests
items += await asyncio.gather(
@ -154,7 +156,7 @@ class FileContextProvider(ContextProvider):
)
i += delta
await asyncio.sleep(0.1)
await asyncio.sleep(timeout)
items = list(filter(lambda item: item is not None, items))

View file

@ -173,19 +173,20 @@ class IdeProtocolServer(AbstractIdeProtocolServer):
self.onAcceptRejectDiff(data["accepted"], data["stepIndex"])
elif msg.message_type == "mainUserInput":
self.onMainUserInput(data["input"])
elif msg.message_type in [
"highlightedCode",
"openFiles",
"visibleFiles",
"readFile",
"editFile",
"getUserSecret",
"runCommand",
"getTerminalContents",
"listDirectoryContents",
"fileExists",
]:
self.messenger.post(msg)
# elif msg.message_type in [
# "highlightedCode",
# "openFiles",
# "visibleFiles",
# "readFile",
# "readFiles",
# "editFile",
# "getUserSecret",
# "runCommand",
# "getTerminalContents",
# "listDirectoryContents",
# "fileExists",
# ]:
# self.messenger.post(msg)
elif msg.message_type == "workspaceDirectory":
self.workspace_directory = data["workspaceDirectory"]
elif msg.message_type == "uniqueId":

View file

@ -25,14 +25,18 @@ class SocketIOMessenger:
self.sid = sid
async def send(
self, message_type: str, data: Dict[str, Any], message_id: Optional[str] = None
self,
message_type: str,
data: Dict[str, Any],
message_id: Optional[str] = None,
callback=None,
):
msg = WebsocketsMessage(
message_type=message_type,
data=data,
message_id=message_id or uuid.uuid4().hex,
)
await self.sio.send(msg.dict(), to=self.sid)
await self.sio.send(msg.dict(), to=self.sid, callback=callback)
async def receive(self, message_id: str) -> WebsocketsMessage:
if message_id not in self.futures:
@ -46,9 +50,20 @@ class SocketIOMessenger:
message_id = uuid.uuid4().hex
async def try_with_timeout(timeout: int):
await self.send(message_type, data, message_id=message_id)
resp = await asyncio.wait_for(self.receive(message_id), timeout=timeout)
return resp_model.parse_obj(resp.data)
fut = asyncio.Future()
def callback(ack_data):
fut.set_result(ack_data)
await self.send(
message_type, data, message_id=message_id, callback=callback
)
response = await fut
return resp_model.parse_obj(response["data"])
# await self.send(message_type, data, message_id=message_id)
# resp = await asyncio.wait_for(self.receive(message_id), timeout=timeout)
# return resp_model.parse_obj(resp.data)
timeout = 1.0
while True:
@ -62,7 +77,7 @@ class SocketIOMessenger:
message=f"Timed out waiting for response to '{message_type}'. The message sent was: {data or ''}",
)
except asyncio.exceptions.CancelledError:
print("Cancelled")
print(f"Cancelled task {message_type}")
def post(self, msg: WebsocketsMessage):
if msg.message_id in self.futures: