feat(console): replace LLM with real linters (node/python/ruby/php/perl/go) v0.7.8
This commit is contained in:
+1
-1
@@ -6,7 +6,7 @@ COPY . .
|
|||||||
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o fission-console .
|
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o fission-console .
|
||||||
|
|
||||||
FROM alpine:3.20
|
FROM alpine:3.20
|
||||||
RUN apk add --no-cache ca-certificates
|
RUN apk add --no-cache ca-certificates nodejs python3 ruby perl php83
|
||||||
COPY --from=builder /build/fission-console /fission-console
|
COPY --from=builder /build/fission-console /fission-console
|
||||||
EXPOSE 8090
|
EXPOSE 8090
|
||||||
ENTRYPOINT ["/fission-console"]
|
ENTRYPOINT ["/fission-console"]
|
||||||
|
|||||||
+79
-72
@@ -14,7 +14,10 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"go/parser"
|
||||||
|
"go/token"
|
||||||
"os"
|
"os"
|
||||||
|
"os/exec"
|
||||||
"regexp"
|
"regexp"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
@@ -65,8 +68,7 @@ type server struct {
|
|||||||
authUser string
|
authUser string
|
||||||
authPass string
|
authPass string
|
||||||
|
|
||||||
llmURL string // FISSION_LLM_URL — базовый URL LLM API
|
|
||||||
llmKey string // FISSION_LLM_KEY — Bearer ключ
|
|
||||||
|
|
||||||
tokenMu sync.Mutex
|
tokenMu sync.Mutex
|
||||||
cachedJWT string
|
cachedJWT string
|
||||||
@@ -136,8 +138,6 @@ func main() {
|
|||||||
authUser: authUser,
|
authUser: authUser,
|
||||||
authPass: authPass,
|
authPass: authPass,
|
||||||
testMode: os.Getenv("FISSION_TEST_MODE") == "true",
|
testMode: os.Getenv("FISSION_TEST_MODE") == "true",
|
||||||
llmURL: envDefault("FISSION_LLM_URL", "https://api.aillm.ru"),
|
|
||||||
llmKey: os.Getenv("FISSION_LLM_KEY"),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
@@ -1776,7 +1776,17 @@ func readZipFile(file *zip.File) ([]byte, error) {
|
|||||||
return io.ReadAll(rc)
|
return io.ReadAll(rc)
|
||||||
}
|
}
|
||||||
|
|
||||||
// handleAICheck проксирует запрос проверки синтаксиса к LLM API.
|
// goParse проверяет синтаксис Go-кода через go/parser.
|
||||||
|
func goParse(code string) (*token.FileSet, error) {
|
||||||
|
fset := token.NewFileSet()
|
||||||
|
_, err := parser.ParseFile(fset, "code.go", code, parser.AllErrors)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return fset, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleAICheck проверяет синтаксис кода через реальный линтер языка.
|
||||||
// POST /console/api/ai/check
|
// POST /console/api/ai/check
|
||||||
// Body: {"language":"python","code":"..."}
|
// Body: {"language":"python","code":"..."}
|
||||||
// Response: {"ok":true,"result":"..."}
|
// Response: {"ok":true,"result":"..."}
|
||||||
@@ -1785,10 +1795,6 @@ func (s *server) handleAICheck(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeJSONError(w, http.StatusMethodNotAllowed, "method not allowed")
|
writeJSONError(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if s.llmKey == "" {
|
|
||||||
writeJSONError(w, http.StatusServiceUnavailable, "LLM не настроен (FISSION_LLM_KEY не задан)")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var req struct {
|
var req struct {
|
||||||
Language string `json:"language"`
|
Language string `json:"language"`
|
||||||
@@ -1799,79 +1805,80 @@ func (s *server) handleAICheck(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if strings.TrimSpace(req.Code) == "" {
|
if strings.TrimSpace(req.Code) == "" {
|
||||||
writeJSONError(w, http.StatusBadRequest, "code is required")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(map[string]any{"ok": false, "result": "Код пустой."})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
prompt := fmt.Sprintf(
|
// Определяем команду и расширение файла по языку
|
||||||
"Проверь синтаксис следующего кода на языке %s для serverless-функции Fission. "+
|
type linterCfg struct {
|
||||||
"Найди синтаксические ошибки, неправильные вызовы, проблемы с entrypoint. "+
|
ext string
|
||||||
"Если ошибок нет — ответь кратко: \"✅ Синтаксис корректен.\" "+
|
cmd []string
|
||||||
"Если есть — перечисли проблемы по пунктам, кратко, без лишних слов. "+
|
|
||||||
"Код:\n\n```%s\n%s\n```",
|
|
||||||
req.Language, req.Language, req.Code,
|
|
||||||
)
|
|
||||||
|
|
||||||
llmBody, _ := json.Marshal(map[string]any{
|
|
||||||
"model": "gpt-oss-120b",
|
|
||||||
"messages": []map[string]string{
|
|
||||||
{"role": "user", "content": prompt},
|
|
||||||
},
|
|
||||||
"max_tokens": 512,
|
|
||||||
})
|
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
llmReq, err := http.NewRequestWithContext(ctx, http.MethodPost,
|
|
||||||
strings.TrimRight(s.llmURL, "/")+"/chat/completions",
|
|
||||||
bytes.NewReader(llmBody),
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
writeJSONError(w, http.StatusInternalServerError, "build llm request: "+err.Error())
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
llmReq.Header.Set("Content-Type", "application/json")
|
langs := map[string]linterCfg{
|
||||||
llmReq.Header.Set("Authorization", "Bearer "+s.llmKey)
|
"nodejs": {ext: ".js", cmd: []string{"node", "--check"}},
|
||||||
|
"python": {ext: ".py", cmd: []string{"python3", "-m", "py_compile"}},
|
||||||
resp, err := s.http.Do(llmReq)
|
"ruby": {ext: ".rb", cmd: []string{"ruby", "-c"}},
|
||||||
if err != nil {
|
"php": {ext: ".php", cmd: []string{"php", "-l"}},
|
||||||
writeJSONError(w, http.StatusBadGateway, "llm request failed: "+err.Error())
|
"perl": {ext: ".pl", cmd: []string{"perl", "-c"}},
|
||||||
return
|
"go": {ext: ".go", cmd: nil}, // go проверяем через go/parser
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 64*1024))
|
cfg, ok := langs[req.Language]
|
||||||
if err != nil {
|
if !ok {
|
||||||
writeJSONError(w, http.StatusBadGateway, "read llm response: "+err.Error())
|
writeJSONError(w, http.StatusBadRequest, "unsupported language: "+req.Language)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var llmResp struct {
|
var isOK bool
|
||||||
Choices []struct {
|
var result string
|
||||||
Message struct {
|
|
||||||
Content string `json:"content"`
|
|
||||||
} `json:"message"`
|
|
||||||
} `json:"choices"`
|
|
||||||
Error *struct {
|
|
||||||
Message string `json:"message"`
|
|
||||||
} `json:"error"`
|
|
||||||
}
|
|
||||||
if err := json.Unmarshal(raw, &llmResp); err != nil {
|
|
||||||
writeJSONError(w, http.StatusBadGateway, "parse llm response: "+err.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if llmResp.Error != nil {
|
|
||||||
writeJSONError(w, http.StatusBadGateway, "llm error: "+llmResp.Error.Message)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if len(llmResp.Choices) == 0 {
|
|
||||||
writeJSONError(w, http.StatusBadGateway, "empty llm response")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
result := strings.TrimSpace(llmResp.Choices[0].Message.Content)
|
if req.Language == "go" {
|
||||||
isOK := strings.Contains(result, "✅") || strings.HasPrefix(strings.ToLower(result), "синтаксис корректен")
|
// Go: используем go/parser прямо в процессе — без внешних команд
|
||||||
|
_, parseErr := goParse(req.Code)
|
||||||
|
if parseErr == nil {
|
||||||
|
isOK = true
|
||||||
|
result = "✅ Синтаксис корректен."
|
||||||
|
} else {
|
||||||
|
isOK = false
|
||||||
|
result = parseErr.Error()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Записываем код во временный файл
|
||||||
|
tmpf, err := os.CreateTemp("", "fission-lint-*"+cfg.ext)
|
||||||
|
if err != nil {
|
||||||
|
writeJSONError(w, http.StatusInternalServerError, "tmp file: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer os.Remove(tmpf.Name())
|
||||||
|
if _, err := tmpf.WriteString(req.Code); err != nil {
|
||||||
|
tmpf.Close()
|
||||||
|
writeJSONError(w, http.StatusInternalServerError, "write tmp: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tmpf.Close()
|
||||||
|
|
||||||
|
args := append(cfg.cmd, tmpf.Name())
|
||||||
|
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
//nolint:gosec — cfg.cmd содержит только захардкоженные команды из langsMap
|
||||||
|
out, err := exec.CommandContext(ctx, args[0], args[1:]...).CombinedOutput()
|
||||||
|
outStr := strings.TrimSpace(string(out))
|
||||||
|
// Убираем путь к tmp-файлу из вывода — юзеру незачем его видеть
|
||||||
|
outStr = strings.ReplaceAll(outStr, tmpf.Name(), "<code>")
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
isOK = true
|
||||||
|
result = "✅ Синтаксис корректен."
|
||||||
|
} else {
|
||||||
|
isOK = false
|
||||||
|
if outStr != "" {
|
||||||
|
result = outStr
|
||||||
|
} else {
|
||||||
|
result = "Ошибка синтаксиса (линтер вернул код " + fmt.Sprintf("%v", err) + ")"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
json.NewEncoder(w).Encode(map[string]any{
|
json.NewEncoder(w).Encode(map[string]any{
|
||||||
|
|||||||
@@ -391,7 +391,7 @@
|
|||||||
return {"ok": True, "msg": "hello from fission console"}
|
return {"ok": True, "msg": "hello from fission console"}
|
||||||
</textarea>
|
</textarea>
|
||||||
<div style="margin-top:6px;">
|
<div style="margin-top:6px;">
|
||||||
<button class="btn ghost" id="c-ai-btn" onclick="aiCheck('c-code','c-lang','c-ai-result')">✨ Проверить синтаксис</button>
|
<button class="btn ghost" id="c-ai-btn" onclick="aiCheck('c-code','c-lang','c-ai-result')">🔍 Проверить синтаксис</button>
|
||||||
</div>
|
</div>
|
||||||
<div id="c-ai-result" style="display:none;margin-top:8px;padding:10px 12px;border-radius:6px;font-size:13px;line-height:1.5;white-space:pre-wrap;font-family:monospace;"></div>
|
<div id="c-ai-result" style="display:none;margin-top:8px;padding:10px 12px;border-radius:6px;font-size:13px;line-height:1.5;white-space:pre-wrap;font-family:monospace;"></div>
|
||||||
</div>
|
</div>
|
||||||
@@ -425,7 +425,7 @@
|
|||||||
<label>Код</label>
|
<label>Код</label>
|
||||||
<textarea id="e-code"></textarea>
|
<textarea id="e-code"></textarea>
|
||||||
<div style="margin-top:6px;">
|
<div style="margin-top:6px;">
|
||||||
<button class="btn ghost" id="e-ai-btn" onclick="aiCheck('e-code','e-lang-hidden','e-ai-result')">✨ Проверить синтаксис</button>
|
<button class="btn ghost" id="e-ai-btn" onclick="aiCheck('e-code','e-lang-hidden','e-ai-result')">🔍 Проверить синтаксис</button>
|
||||||
</div>
|
</div>
|
||||||
<div id="e-ai-result" style="display:none;margin-top:8px;padding:10px 12px;border-radius:6px;font-size:13px;line-height:1.5;white-space:pre-wrap;font-family:monospace;"></div>
|
<div id="e-ai-result" style="display:none;margin-top:8px;padding:10px 12px;border-radius:6px;font-size:13px;line-height:1.5;white-space:pre-wrap;font-family:monospace;"></div>
|
||||||
</div>
|
</div>
|
||||||
@@ -625,7 +625,7 @@
|
|||||||
document.getElementById('e-env').value = fn.environment || '';
|
document.getElementById('e-env').value = fn.environment || '';
|
||||||
document.getElementById('e-entry').value = fn.entrypoint || '';
|
document.getElementById('e-entry').value = fn.entrypoint || '';
|
||||||
document.getElementById('e-code').value = fn.code || '';
|
document.getElementById('e-code').value = fn.code || '';
|
||||||
// Определяем язык по имени environment для подсказки AI
|
// Определяем язык по имени environment для линтера
|
||||||
var envName = (fn.environment || '').toLowerCase();
|
var envName = (fn.environment || '').toLowerCase();
|
||||||
var lang = 'python';
|
var lang = 'python';
|
||||||
if (envName.includes('node')) lang = 'nodejs';
|
if (envName.includes('node')) lang = 'nodejs';
|
||||||
@@ -837,7 +837,7 @@
|
|||||||
resEl.textContent = 'Ошибка: ' + e.message;
|
resEl.textContent = 'Ошибка: ' + e.message;
|
||||||
} finally {
|
} finally {
|
||||||
btn.disabled = false;
|
btn.disabled = false;
|
||||||
btn.textContent = '✨ Проверить синтаксис';
|
btn.textContent = '🔍 Проверить синтаксис';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user