Skip to content

Commit

Permalink
refactor(lsp proxy): don't. expose all routes to the web
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcMcIntosh authored and mitya52 committed Jan 18, 2024
1 parent e44956f commit f43d3a3
Showing 1 changed file with 26 additions and 10 deletions.
36 changes: 26 additions & 10 deletions self_hosting_machinery/webgui/selfhost_lsp_proxy.py
Original file line number Diff line number Diff line change
@@ -1,37 +1,53 @@
from fastapi import FastAPI, HTTPException, APIRouter
from fastapi import APIRouter
from starlette.requests import Request
from starlette.responses import StreamingResponse
from starlette.background import BackgroundTask
from fastapi import APIRouter, HTTPException

from fastapi import APIRouter
from self_hosting_machinery import env
import os
import json
import httpx

# TODO: can this be configured?
lsp_address = "http://127.0.0.1:8001"

__all__ = ["LspProxy"]


client = httpx.AsyncClient(base_url=lsp_address)
def get_lsp_url() -> str:
lsp_cfg = json.load(open(os.path.join(env.DIR_WATCHDOG_TEMPLATES, "lsp.cfg")))
lsp_cmdline = lsp_cfg["command_line"]
lsp_port = "8001"

if "--port" in lsp_cmdline:
maybe_port:str = lsp_cmdline[lsp_cmdline.index("--port") + 1]
if maybe_port.isnumeric():
lsp_port = maybe_port

return "http://127.0.0.1:" + lsp_port


class LspProxy(APIRouter):

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
super().add_route("/lsp/v1/{path:path}", self._reverse_proxy, methods=["GET", "POST"])
super().add_route("/lsp/v1/caps", self._reverse_proxy, methods=["GET"])
super().add_route("/lsp/v1/chat", self._reverse_proxy, methods=["POST"])
lsp_address = get_lsp_url()
self._client = httpx.AsyncClient(base_url=lsp_address)

async def _reverse_proxy(self, request: Request):
## TODO: handle errors
path = request.url.path.replace("/lsp", "")
url = httpx.URL(path=path, query=request.url.query.encode("utf-8"))

rp_req = client.build_request(
rp_req = self._client.build_request(
request.method, url, headers=request.headers.raw, content=await request.body()
)
rp_resp = await client.send(rp_req, stream=True)
rp_resp = await self._client.send(rp_req, stream=True)
return StreamingResponse(
rp_resp.aiter_raw(),
status_code=rp_resp.status_code,
headers=rp_resp.headers,
background=BackgroundTask(rp_resp.aclose),
)



0 comments on commit f43d3a3

Please sign in to comment.