snapshot before legacy cleanup
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 ./cmd/server/
|
||||
|
||||
FROM alpine:3.20
|
||||
RUN apk add --no-cache ca-certificates nodejs python3 ruby perl php83
|
||||
RUN apk add --no-cache ca-certificates nodejs python3 ruby php83
|
||||
COPY --from=builder /build/fission-console /fission-console
|
||||
EXPOSE 8090
|
||||
ENTRYPOINT ["/fission-console"]
|
||||
|
||||
@@ -22,7 +22,7 @@ import (
|
||||
//
|
||||
// Почему реальные линтеры, а не LLM:
|
||||
// LLM часто "исправляет" валидный код и врёт о наличии ошибок.
|
||||
// node --check / python3 -m py_compile / ruby -c / php -l / perl -c — детерминированы и надёжны.
|
||||
// node --check / python3 -m py_compile / ruby -c / php -l — детерминированы и надёжны.
|
||||
// Go использует go/parser прямо в процессе — без внешних команд, быстро.
|
||||
func (s *Server) handleAICheck(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
@@ -54,7 +54,6 @@ func (s *Server) handleAICheck(w http.ResponseWriter, r *http.Request) {
|
||||
"python": {ext: ".py", cmd: []string{"python3", "-m", "py_compile"}},
|
||||
"ruby": {ext: ".rb", cmd: []string{"ruby", "-c"}},
|
||||
"php": {ext: ".php", cmd: []string{"php", "-l"}},
|
||||
"perl": {ext: ".pl", cmd: []string{"perl", "-c"}},
|
||||
"go": {ext: ".go", cmd: nil}, // go проверяется через go/parser в процессе
|
||||
}
|
||||
|
||||
|
||||
@@ -35,6 +35,19 @@ var validFuncName = regexp.MustCompile(`^[a-z0-9]([a-z0-9-]*[a-z0-9])?$`)
|
||||
// Выше — не имеет смысла для inline функции; лучше использовать Package с URL.
|
||||
const maxCodeSize = 1 << 20
|
||||
|
||||
func buildDeployArchive(lang, code string) ([]byte, error) {
|
||||
switch lang {
|
||||
case "nodejs":
|
||||
return runtime.BuildJSDeployZip(code)
|
||||
case "php":
|
||||
return runtime.BuildScriptZip(code, "main.php")
|
||||
case "ruby":
|
||||
return runtime.BuildScriptZip(code, "handler.rb")
|
||||
default:
|
||||
return []byte(code), nil
|
||||
}
|
||||
}
|
||||
|
||||
// handleFunctionsRoot обрабатывает запросы к /console/api/functions без имени функции.
|
||||
// GET → список всех функций, POST → создать новую.
|
||||
func (s *Server) handleFunctionsRoot(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -212,17 +225,10 @@ func (s *Server) handleCreateFunction(w http.ResponseWriter, r *http.Request) {
|
||||
"buildcommand": "build",
|
||||
}
|
||||
} else {
|
||||
var deployBytes []byte
|
||||
if req.Language == "nodejs" {
|
||||
zipBytes, zipErr := runtime.BuildJSDeployZip(req.Code)
|
||||
if zipErr != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, fmt.Sprintf("build nodejs archive: %v", zipErr))
|
||||
return
|
||||
}
|
||||
deployBytes = zipBytes
|
||||
} else {
|
||||
// Python, PHP, Ruby, Perl — код передаётся как есть в deployment.literal
|
||||
deployBytes = []byte(req.Code)
|
||||
deployBytes, archiveErr := buildDeployArchive(req.Language, req.Code)
|
||||
if archiveErr != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, fmt.Sprintf("build %s archive: %v", req.Language, archiveErr))
|
||||
return
|
||||
}
|
||||
pkgSpec = map[string]any{
|
||||
"deployment": map[string]any{"type": "literal", "literal": base64.StdEncoding.EncodeToString(deployBytes)},
|
||||
@@ -429,16 +435,10 @@ func (s *Server) handleUpdateFunctionCode(w http.ResponseWriter, r *http.Request
|
||||
|
||||
// Определяем язык из аннотации — нужен для правильной упаковки
|
||||
lang, _, _ := unstructured.NestedString(fn.Object, "metadata", "annotations", "fission-console/language")
|
||||
var deployBytes []byte
|
||||
if lang == "nodejs" {
|
||||
zipBytes, zipErr := runtime.BuildJSDeployZip(req.Code)
|
||||
if zipErr != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, fmt.Sprintf("build nodejs archive: %v", zipErr))
|
||||
return
|
||||
}
|
||||
deployBytes = zipBytes
|
||||
} else {
|
||||
deployBytes = []byte(req.Code)
|
||||
deployBytes, archiveErr := buildDeployArchive(lang, req.Code)
|
||||
if archiveErr != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, fmt.Sprintf("build %s archive: %v", lang, archiveErr))
|
||||
return
|
||||
}
|
||||
|
||||
literal := base64.StdEncoding.EncodeToString(deployBytes)
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"fission-console/internal/fission"
|
||||
@@ -14,72 +13,95 @@ import (
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
)
|
||||
|
||||
var requiredBootstrapServiceAccounts = []string{"fission-fetcher", "fission-builder"}
|
||||
|
||||
var requiredBootstrapRoleBindings = []string{
|
||||
"fission-executor-user-ns",
|
||||
"fission-router-user-ns",
|
||||
"fission-buildermgr-user-ns",
|
||||
"fission-kubewatcher-user-ns",
|
||||
"fission-timer-user-ns",
|
||||
"fission-fetcher-system-user-ns",
|
||||
"fission-builder-system-user-ns",
|
||||
"fission-fetcher-local-user-ns",
|
||||
"fission-builder-local-user-ns",
|
||||
}
|
||||
|
||||
type namespacePreparationStatus struct {
|
||||
ManagedByConsole bool `json:"managedByConsole"`
|
||||
WatcherLabel bool `json:"watcherLabel"`
|
||||
ServiceAccounts map[string]bool `json:"serviceAccounts"`
|
||||
RoleBindings map[string]bool `json:"roleBindings"`
|
||||
}
|
||||
|
||||
func (s namespacePreparationStatus) Ready() bool {
|
||||
if !s.ManagedByConsole || !s.WatcherLabel {
|
||||
return false
|
||||
}
|
||||
for _, ok := range s.ServiceAccounts {
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
for _, ok := range s.RoleBindings {
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type controlPlaneServiceStatus struct {
|
||||
Ready bool `json:"ready"`
|
||||
PodCount int `json:"podCount"`
|
||||
ReadyPods []string `json:"readyPods"`
|
||||
}
|
||||
|
||||
type controlPlaneStatus struct {
|
||||
Namespace string `json:"namespace"`
|
||||
Ready bool `json:"ready"`
|
||||
Executor controlPlaneServiceStatus `json:"executor"`
|
||||
Router controlPlaneServiceStatus `json:"router"`
|
||||
}
|
||||
|
||||
// handleNSStatus возвращает статус инициализации пользовательского namespace.
|
||||
// Используется UI для отображения прогресса при первом входе нового пользователя.
|
||||
//
|
||||
// Три стадии:
|
||||
// 1. Namespace существует и Active
|
||||
// 2. Namespace добавлен в FISSION_RESOURCE_NAMESPACES executor deployment
|
||||
// 3. Executor pod Running + Ready (готов принимать функции)
|
||||
// 2. Namespace подготовлен для Layer 1 NSWatcher: label + bootstrap RBAC/SA
|
||||
// 3. Fission control-plane готов: executor и router Running + Ready
|
||||
func (s *Server) handleNSStatus(w http.ResponseWriter, r *http.Request) {
|
||||
ns := s.userNS(r)
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
|
||||
defer cancel()
|
||||
|
||||
fissionNS := os.Getenv("FISSION_SYSTEM_NAMESPACE")
|
||||
if fissionNS == "" {
|
||||
fissionNS = "fission"
|
||||
}
|
||||
|
||||
type stageInfo struct {
|
||||
Name string `json:"name"`
|
||||
Done bool `json:"done"`
|
||||
}
|
||||
stages := []stageInfo{
|
||||
{Name: "Создание пространства имён"},
|
||||
{Name: "Регистрация в Fission"},
|
||||
{Name: "Прогрев окружений"},
|
||||
{Name: "Подготовка namespace для Fission"},
|
||||
{Name: "Готовность control-plane"},
|
||||
}
|
||||
|
||||
// Stage 1: namespace существует и Active
|
||||
nsObj, err := s.dyn.Resource(fission.NamespaceGVR).Get(ctx, ns, metav1.GetOptions{})
|
||||
var preparation namespacePreparationStatus
|
||||
control := controlPlaneStatus{Namespace: fissionSystemNamespace()}
|
||||
if err == nil {
|
||||
phase, _, _ := unstructured.NestedString(nsObj.Object, "status", "phase")
|
||||
stages[0].Done = phase == "Active"
|
||||
}
|
||||
|
||||
// Stage 2: namespace в FISSION_RESOURCE_NAMESPACES executor deployment
|
||||
if stages[0].Done {
|
||||
execDep, err2 := s.dyn.Resource(fission.DeploymentGVR).Namespace(fissionNS).Get(ctx, "executor", metav1.GetOptions{})
|
||||
if err2 == nil {
|
||||
stages[1].Done = nsInFissionEnv(execDep, ns)
|
||||
}
|
||||
preparation = s.namespacePreparationStatus(ctx, ns, nsObj)
|
||||
stages[1].Done = preparation.Ready()
|
||||
}
|
||||
|
||||
// Stage 3: executor pod Running + Ready
|
||||
if stages[1].Done {
|
||||
podGVR := schema.GroupVersionResource{Group: "", Version: "v1", Resource: "pods"}
|
||||
podList, err3 := s.dyn.Resource(podGVR).Namespace(fissionNS).List(ctx, metav1.ListOptions{
|
||||
LabelSelector: "svc=executor",
|
||||
})
|
||||
if err3 == nil {
|
||||
for _, pod := range podList.Items {
|
||||
phase, _, _ := unstructured.NestedString(pod.Object, "status", "phase")
|
||||
if phase != "Running" {
|
||||
continue
|
||||
}
|
||||
conditions, _, _ := unstructured.NestedSlice(pod.Object, "status", "conditions")
|
||||
for _, c := range conditions {
|
||||
cond, ok := c.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if cond["type"] == "Ready" && cond["status"] == "True" {
|
||||
stages[2].Done = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
control = s.controlPlaneStatus(ctx)
|
||||
stages[2].Done = control.Ready
|
||||
}
|
||||
|
||||
ready := stages[0].Done && stages[1].Done && stages[2].Done
|
||||
@@ -89,32 +111,116 @@ func (s *Server) handleNSStatus(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
}
|
||||
|
||||
// nsInFissionEnv проверяет что namespace ns содержится в FISSION_RESOURCE_NAMESPACES
|
||||
// первого контейнера данного deployment.
|
||||
func nsInFissionEnv(dep *unstructured.Unstructured, ns string) bool {
|
||||
containers, _, _ := unstructured.NestedSlice(dep.Object, "spec", "template", "spec", "containers")
|
||||
for _, c := range containers {
|
||||
cont, ok := c.(map[string]any)
|
||||
func (s *Server) handleNSDebug(w http.ResponseWriter, r *http.Request) {
|
||||
ns := s.userNS(r)
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
|
||||
defer cancel()
|
||||
|
||||
nsObj, err := s.dyn.Resource(fission.NamespaceGVR).Get(ctx, ns, metav1.GetOptions{})
|
||||
labels := map[string]string{}
|
||||
phase := ""
|
||||
exists := err == nil
|
||||
active := false
|
||||
preparation := namespacePreparationStatus{}
|
||||
if exists {
|
||||
labels, _, _ = unstructured.NestedStringMap(nsObj.Object, "metadata", "labels")
|
||||
phase, _, _ = unstructured.NestedString(nsObj.Object, "status", "phase")
|
||||
active = phase == "Active"
|
||||
preparation = s.namespacePreparationStatus(ctx, ns, nsObj)
|
||||
}
|
||||
control := s.controlPlaneStatus(ctx)
|
||||
|
||||
writeAnyJSON(w, http.StatusOK, map[string]any{
|
||||
"namespace": ns,
|
||||
"exists": exists,
|
||||
"active": active,
|
||||
"phase": phase,
|
||||
"labels": labels,
|
||||
"prepared": preparation.Ready(),
|
||||
"preparation": preparation,
|
||||
"controlPlane": control,
|
||||
"namespaceReady": active && preparation.Ready() && control.Ready,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) namespacePreparationStatus(ctx context.Context, ns string, nsObj *unstructured.Unstructured) namespacePreparationStatus {
|
||||
status := namespacePreparationStatus{
|
||||
ServiceAccounts: make(map[string]bool, len(requiredBootstrapServiceAccounts)),
|
||||
RoleBindings: make(map[string]bool, len(requiredBootstrapRoleBindings)),
|
||||
}
|
||||
if nsObj != nil {
|
||||
labels, _, _ := unstructured.NestedStringMap(nsObj.Object, "metadata", "labels")
|
||||
status.ManagedByConsole = labels["managed-by"] == "fission-console"
|
||||
status.WatcherLabel = labels["fission.io/managed"] == "true"
|
||||
}
|
||||
|
||||
saGVR := schema.GroupVersionResource{Group: "", Version: "v1", Resource: "serviceaccounts"}
|
||||
for _, name := range requiredBootstrapServiceAccounts {
|
||||
_, err := s.dyn.Resource(saGVR).Namespace(ns).Get(ctx, name, metav1.GetOptions{})
|
||||
status.ServiceAccounts[name] = err == nil
|
||||
}
|
||||
|
||||
rbGVR := schema.GroupVersionResource{Group: "rbac.authorization.k8s.io", Version: "v1", Resource: "rolebindings"}
|
||||
for _, name := range requiredBootstrapRoleBindings {
|
||||
_, err := s.dyn.Resource(rbGVR).Namespace(ns).Get(ctx, name, metav1.GetOptions{})
|
||||
status.RoleBindings[name] = err == nil
|
||||
}
|
||||
|
||||
return status
|
||||
}
|
||||
|
||||
func (s *Server) controlPlaneStatus(ctx context.Context) controlPlaneStatus {
|
||||
status := controlPlaneStatus{Namespace: fissionSystemNamespace()}
|
||||
status.Executor = s.serviceStatus(ctx, status.Namespace, "executor")
|
||||
status.Router = s.serviceStatus(ctx, status.Namespace, "router")
|
||||
status.Ready = status.Executor.Ready && status.Router.Ready
|
||||
return status
|
||||
}
|
||||
|
||||
func (s *Server) serviceStatus(ctx context.Context, namespace, service string) controlPlaneServiceStatus {
|
||||
podGVR := schema.GroupVersionResource{Group: "", Version: "v1", Resource: "pods"}
|
||||
podList, err := s.dyn.Resource(podGVR).Namespace(namespace).List(ctx, metav1.ListOptions{
|
||||
LabelSelector: "svc=" + service,
|
||||
})
|
||||
if err != nil {
|
||||
return controlPlaneServiceStatus{}
|
||||
}
|
||||
|
||||
status := controlPlaneServiceStatus{PodCount: len(podList.Items)}
|
||||
for _, pod := range podList.Items {
|
||||
if podReady(&pod) {
|
||||
status.Ready = true
|
||||
status.ReadyPods = append(status.ReadyPods, pod.GetName())
|
||||
}
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
func fissionSystemNamespace() string {
|
||||
ns := os.Getenv("FISSION_SYSTEM_NAMESPACE")
|
||||
if ns == "" {
|
||||
return "fission"
|
||||
}
|
||||
return ns
|
||||
}
|
||||
|
||||
func podReady(pod *unstructured.Unstructured) bool {
|
||||
if pod == nil {
|
||||
return false
|
||||
}
|
||||
phase, _, _ := unstructured.NestedString(pod.Object, "status", "phase")
|
||||
if phase != "Running" {
|
||||
return false
|
||||
}
|
||||
conditions, _, _ := unstructured.NestedSlice(pod.Object, "status", "conditions")
|
||||
for _, c := range conditions {
|
||||
cond, ok := c.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
envs, _, _ := unstructured.NestedSlice(cont, "env")
|
||||
for _, e := range envs {
|
||||
env, ok := e.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if env["name"] == "FISSION_RESOURCE_NAMESPACES" {
|
||||
if v, ok := env["value"].(string); ok {
|
||||
for _, p := range strings.Split(v, ",") {
|
||||
if strings.TrimSpace(p) == ns {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if cond["type"] == "Ready" && cond["status"] == "True" {
|
||||
return true
|
||||
}
|
||||
break // только первый контейнер
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -90,7 +90,7 @@ func decodeArchiveBytesToSource(decoded []byte) (string, error) {
|
||||
if len(decoded) == 0 {
|
||||
return "", io.ErrUnexpectedEOF
|
||||
}
|
||||
// Если байты — валидный UTF-8, возвращаем напрямую (python, ruby, perl, php)
|
||||
// Если байты — валидный UTF-8, возвращаем напрямую (python, ruby, php)
|
||||
if utf8.Valid(decoded) {
|
||||
return string(decoded), nil
|
||||
}
|
||||
@@ -112,7 +112,7 @@ func decodeZipSource(zipBytes []byte) (string, error) {
|
||||
}
|
||||
|
||||
// Сначала ищем по приоритетным именам
|
||||
preferred := []string{"main.py", "main.js", "main.go", "handler.go", "handler.js", "handler.py"}
|
||||
preferred := []string{"main.py", "main.js", "main.go", "main.php", "handler.rb", "handler.pl", "handler.go", "handler.js", "handler.py"}
|
||||
for _, name := range preferred {
|
||||
for _, file := range reader.File {
|
||||
if strings.EqualFold(file.Name, name) {
|
||||
|
||||
@@ -140,6 +140,7 @@ func (s *Server) RegisterRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("/console/api/httptriggers", auth(s.handleList(fission.HTTPTrigGVR)))
|
||||
mux.HandleFunc("/console/api/timetriggers", auth(s.handleList(fission.TimeTrigGVR)))
|
||||
mux.HandleFunc("/console/api/ns/status", auth(s.handleNSStatus))
|
||||
mux.HandleFunc("/console/api/ns/debug", auth(s.handleNSDebug))
|
||||
mux.HandleFunc("/console/api/ai/check", auth(s.handleAICheck))
|
||||
// --- ai/ask feature (удалить строку чтобы выкосить роут) ---
|
||||
mux.HandleFunc("/console/api/ai/ask", auth(s.handleAIAsk))
|
||||
|
||||
@@ -82,7 +82,6 @@ func CleanupEnvironmentIfUnused(ctx context.Context, dyn dynamic.Interface, ns,
|
||||
// Вся Fission-специфичная схема изолирована здесь — при обновлении Fission меняем только тут.
|
||||
func buildLangEnvironment(name, ns string, def model.LangEnvDef) *unstructured.Unstructured {
|
||||
// Version по умолчанию 3 (V2 protocol с async entrypoint).
|
||||
// Исключение: perl-env поддерживает только V1 protocol → version=1.
|
||||
envVersion := int64(3)
|
||||
if def.Version != 0 {
|
||||
envVersion = int64(def.Version)
|
||||
|
||||
@@ -23,7 +23,7 @@ type UpdateCodeRequest struct {
|
||||
|
||||
// LangEnvDef описывает Docker-образы для конкретного языка.
|
||||
// BuilderImage заполнен только для языков которым нужна компиляция (Go).
|
||||
// Version: версия среды Fission (по умолчанию 3; perl использует 1 — нет поддержки async entrypoint).
|
||||
// Version: версия среды Fission (по умолчанию 3).
|
||||
type LangEnvDef struct {
|
||||
Image string
|
||||
BuilderImage string
|
||||
@@ -32,15 +32,10 @@ type LangEnvDef struct {
|
||||
|
||||
// LangEnvMap сопоставляет идентификатор языка (string) с описанием среды выполнения.
|
||||
// Ключ используется в createFunctionRequest.Language и как суффикс имени Environment.
|
||||
//
|
||||
// Почему perl Version=1:
|
||||
// Fission Environment v3 требует поддержки async entrypoint (V2 protocol).
|
||||
// ghcr.io/fission/perl-env поддерживает только V1 protocol → version=1.
|
||||
var LangEnvMap = map[string]LangEnvDef{
|
||||
"python": {Image: "ghcr.io/fission/python-env"},
|
||||
"nodejs": {Image: "ghcr.io/fission/node-env"},
|
||||
"go": {Image: "ghcr.io/fission/go-env", BuilderImage: "naeel/go-builder-fast:v1"},
|
||||
"php": {Image: "ghcr.io/fission/php-env"},
|
||||
"ruby": {Image: "ghcr.io/fission/ruby-env"},
|
||||
"perl": {Image: "ghcr.io/fission/perl-env", Version: 1},
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ package runtime
|
||||
// - nodejs: "main" → имя экспортированной default-функции в main.js
|
||||
// - php: "main.php::handler" → имя файла + "::" + имя функции
|
||||
// - ruby: "handler" → имя метода в загруженном файле
|
||||
// - perl: "handler" → имя функции в загруженном файле
|
||||
// - go: "Handler" → экспортированная Go-функция (с большой буквы)
|
||||
func DefaultEntrypoint(lang string) string {
|
||||
switch lang {
|
||||
@@ -18,8 +17,6 @@ func DefaultEntrypoint(lang string) string {
|
||||
return "main.php::handler"
|
||||
case "ruby":
|
||||
return "handler"
|
||||
case "perl":
|
||||
return "handler"
|
||||
case "go":
|
||||
// Go: экспортированная функция (заглавная) — go/plugin требует экспорт
|
||||
return "Handler"
|
||||
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
)
|
||||
|
||||
// buildZip создаёт zip-архив с одним файлом fileName и содержимым content.
|
||||
// Вспомогательная функция: используется в buildScriptZip (PHP/Ruby/Perl),
|
||||
// Вспомогательная функция: используется в buildScriptZip (PHP/Ruby),
|
||||
// а также как основа для buildGoSourceZip и buildJSDeployZip.
|
||||
func buildZip(fileName string, content []byte) ([]byte, error) {
|
||||
var buf bytes.Buffer
|
||||
|
||||
@@ -22,6 +22,11 @@ import (
|
||||
// Результат: zip с двумя файлами:
|
||||
// - package.json: {"type":"module"}
|
||||
// - main.js: ESM wrapper + инлайн пользовательский код через new Function
|
||||
//
|
||||
// Совместимость entrypoint:
|
||||
// UI исторически отправлял entrypoint="handler", а backend по умолчанию использует
|
||||
// entrypoint="main". Чтобы specialization не ломался из-за несовпадения,
|
||||
// wrapper экспортирует обе точки входа: named exports main и handler, а также default.
|
||||
func BuildJSDeployZip(code string) ([]byte, error) {
|
||||
// Сериализуем пользовательский код в JSON строку чтобы безопасно инлайнить
|
||||
// в JavaScript-литерал — экранирует кавычки, переводы строк, спецсимволы.
|
||||
@@ -38,7 +43,7 @@ func BuildJSDeployZip(code string) ([]byte, error) {
|
||||
(new Function('module', 'exports', %s))(__mod, __mod.exports);
|
||||
const _fn = __mod.exports;
|
||||
|
||||
export default async function(ctx) {
|
||||
async function __invoke(ctx) {
|
||||
const fn = typeof _fn === 'function' ? _fn : (_fn.default || _fn.handler || _fn.main);
|
||||
if (!fn) throw new Error('no exported function found in user code');
|
||||
const result = await fn(ctx);
|
||||
@@ -46,6 +51,9 @@ export default async function(ctx) {
|
||||
if (typeof result.status !== 'undefined') return result;
|
||||
return { status: 200, ...result };
|
||||
}
|
||||
|
||||
export { __invoke as main, __invoke as handler };
|
||||
export default __invoke;
|
||||
`, string(codeJSON))
|
||||
|
||||
var buf bytes.Buffer
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBuildJSDeployZipExportsMainAndHandler(t *testing.T) {
|
||||
zipBytes, err := BuildJSDeployZip(`module.exports = async function () { return { status: 200, body: "ok" }; }`)
|
||||
if err != nil {
|
||||
t.Fatalf("BuildJSDeployZip() error = %v", err)
|
||||
}
|
||||
|
||||
zr, err := zip.NewReader(bytes.NewReader(zipBytes), int64(len(zipBytes)))
|
||||
if err != nil {
|
||||
t.Fatalf("zip.NewReader() error = %v", err)
|
||||
}
|
||||
|
||||
files := map[string]string{}
|
||||
for _, file := range zr.File {
|
||||
rc, openErr := file.Open()
|
||||
if openErr != nil {
|
||||
t.Fatalf("open %q: %v", file.Name, openErr)
|
||||
}
|
||||
content, readErr := io.ReadAll(rc)
|
||||
_ = rc.Close()
|
||||
if readErr != nil {
|
||||
t.Fatalf("read %q: %v", file.Name, readErr)
|
||||
}
|
||||
files[file.Name] = string(content)
|
||||
}
|
||||
|
||||
if files["package.json"] != `{"type":"module"}` {
|
||||
t.Fatalf("package.json = %q, want ESM marker", files["package.json"])
|
||||
}
|
||||
|
||||
mainJS := files["main.js"]
|
||||
if !strings.Contains(mainJS, `export { __invoke as main, __invoke as handler };`) {
|
||||
t.Fatalf("main.js does not export both main and handler: %s", mainJS)
|
||||
}
|
||||
if !strings.Contains(mainJS, `export default __invoke;`) {
|
||||
t.Fatalf("main.js does not export default invoke: %s", mainJS)
|
||||
}
|
||||
if !strings.Contains(mainJS, `_fn.default || _fn.handler || _fn.main`) {
|
||||
t.Fatalf("main.js lost user export resolution: %s", mainJS)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package runtime
|
||||
|
||||
// BuildScriptZip создаёт zip-архив с одним файлом fileName и содержимым code.
|
||||
// Используется для PHP, Ruby, Perl — языков где среда Fission ожидает
|
||||
// Используется для PHP и Ruby — языков где среда Fission ожидает
|
||||
// именованный файл (handler.rb, handler.pl, main.php и т.д.) внутри архива.
|
||||
//
|
||||
// Почему zip, а не просто literal:
|
||||
|
||||
+1
-5
@@ -125,7 +125,6 @@ var langEnvMap = map[string]langEnvDef{
|
||||
"go": {Image: "ghcr.io/fission/go-env", BuilderImage: "naeel/go-builder-fast:v1"},
|
||||
"php": {Image: "ghcr.io/fission/php-env"},
|
||||
"ruby": {Image: "ghcr.io/fission/ruby-env"},
|
||||
"perl": {Image: "ghcr.io/fission/perl-env", Version: 1},
|
||||
}
|
||||
|
||||
type updateCodeRequest struct {
|
||||
@@ -862,7 +861,7 @@ export default async function(ctx) {
|
||||
}
|
||||
|
||||
// buildScriptZip wraps code into a zip file with the given filename.
|
||||
// Used for PHP, Ruby, Perl where the environment requires a named source file.
|
||||
// Used for PHP and Ruby where the environment requires a named source file.
|
||||
func buildScriptZip(code, filename string) ([]byte, error) {
|
||||
var buf bytes.Buffer
|
||||
zw := zip.NewWriter(&buf)
|
||||
@@ -887,8 +886,6 @@ func defaultEntrypoint(lang string) string {
|
||||
return "main.php::handler"
|
||||
case "ruby":
|
||||
return "handler"
|
||||
case "perl":
|
||||
return "handler"
|
||||
case "go":
|
||||
return "Handler"
|
||||
default:
|
||||
@@ -2266,7 +2263,6 @@ func (s *server) handleAICheck(w http.ResponseWriter, r *http.Request) {
|
||||
"python": {ext: ".py", cmd: []string{"python3", "-m", "py_compile"}},
|
||||
"ruby": {ext: ".rb", cmd: []string{"ruby", "-c"}},
|
||||
"php": {ext: ".php", cmd: []string{"php", "-l"}},
|
||||
"perl": {ext: ".pl", cmd: []string{"perl", "-c"}},
|
||||
"go": {ext: ".go", cmd: nil}, // go проверяем через go/parser
|
||||
}
|
||||
|
||||
|
||||
+305
-88
@@ -1,10 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>NUBES Fission Console</title>
|
||||
<link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAACXBIWXMAAA7DAAAOwwHHb6hkAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAA4ZJREFUeJztm8+Lm0UYxz/fySZUoWIrVtbmXfyBP05Fa3e3rogsglJRK0p7E2svnrz6B3gQ8eRJFooXET14KKJ4FUQo3UQQ9CRC6W4WQW0VXZduTd7HQ9c22bzbTCY/ZpO8n0syb56Z+c437zPvhMzIzJhkXGwBsckNiC0gNrkBsQXEZsonSJLj4GNPgb2ACo9j9gDOvrSV6qkB6+sJ6WSJ5MIxUo4h5sDuI9U7tlZ57/+YTAN0zyOPUi+9jOxJxMOUj9wJOBBg117QvqGMwhNpcQ/J+rOkPIc0j+xeytyGsaWXa2+kvc312gxQMleHYgFtrQ9GYJmgmSfup3z15xuDNW/dGXOAjd680NgshlYdvcH2mfEwQIU0tOp4GNADuQGxBcRmPAyQgh/W42FAD+QGxBYQm/EwIF8HhJMbEFtAX3DreQqEkhsQW0BsxsMAlz8Gg8kNiC0gNuNhgJvK54BQcgNiC+gLhUlPgcuTbkAP5AbEFhCbcAOM4LyLitIW3eEGyP7qWUwMHFdaixNO1v4Av5pG8H/yfWfvesk7tq5GczHDAHnmtu727nTQbJYe8o51+qOl2BYgNv1a0iHvTgeNGq94x6buYnOx3YCU3/1asn06ePQZ744HiXTCO3a6/m1zsd0Ax/f+HTc+kU76598AUDL/LpjfjjWxYdXqRvOljDvAfezfO3dQvvCDtLjHu04f0czsaSx9y7uC8eP2S20GWO38Z+A7DwDwIOX135TMvylpKI9VJQv7lcx+hfEhurELsCPOfdDWVtZ5ASWzZ4GXArQ1QJfA/kTW6BhtLgX+7qL9IqTTmKa7GjgAumKry7dsv5q9Vfbfq29QLL1I9wulAtgB4ADmoy9kY4fodugAODuT2dpOJ0aUzH8E6asBXe0+zP5h7bvbzay+/aOdv+Ha8mnE5YEKGxqF17MGDzcxwMzqTBUWgc65vKuxT7cm9kx2TIHrATOzxzHOEpZ5sanYamXuZgEdJzlbqXyOmzrO6N0J56hVj3YK8prl7eK5L6g3DmFc6l3XEDCWbLWyYGYdf9h1TIGWYMmRHDlDaqcY0qKnO/Qr4oStLH/jXSPk4KSShf2ovoTZ80Db4iICv2D2ttWqS91WDDKgpYHy4adR8TWww8BdmN2KrOg5Zwoo+PV0">
|
||||
<link rel="icon" type="image/png"
|
||||
href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAACXBIWXMAAA7DAAAOwwHHb6hkAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAA4ZJREFUeJztm8+Lm0UYxz/fySZUoWIrVtbmXfyBP05Fa3e3rogsglJRK0p7E2svnrz6B3gQ8eRJFooXET14KKJ4FUQo3UQQ9CRC6W4WQW0VXZduTd7HQ9c22bzbTCY/ZpO8n0syb56Z+c437zPvhMzIzJhkXGwBsckNiC0gNrkBsQXEZsonSJLj4GNPgb2ACo9j9gDOvrSV6qkB6+sJ6WSJ5MIxUo4h5sDuI9U7tlZ57/+YTAN0zyOPUi+9jOxJxMOUj9wJOBBg117QvqGMwhNpcQ/J+rOkPIc0j+xeytyGsaWXa2+kvc312gxQMleHYgFtrQ9GYJmgmSfup3z15xuDNW/dGXOAjd680NgshlYdvcH2mfEwQIU0tOp4GNADuQGxBcRmPAyQgh/W42FAD+QGxBYQm/EwIF8HhJMbEFtAX3DreQqEkhsQW0BsxsMAlz8Gg8kNiC0gNuNhgJvK54BQcgNiC+gLhUlPgcuTbkAP5AbEFhCbcAOM4LyLitIW3eEGyP7qWUwMHFdaixNO1v4Av5pG8H/yfWfvesk7tq5GczHDAHnmtu727nTQbJYe8o51+qOl2BYgNv1a0iHvTgeNGq94x6buYnOx3YCU3/1asn06ePQZ744HiXTCO3a6/m1zsd0Ax/f+HTc+kU76598AUDL/LpjfjjWxYdXqRvOljDvAfezfO3dQvvCDtLjHu04f0czsaSx9y7uC8eP2S20GWO38Z+A7DwDwIOX135TMvylpKI9VJQv7lcx+hfEhurELsCPOfdDWVtZ5ASWzZ4GXArQ1QJfA/kTW6BhtLgX+7qL9IqTTmKa7GjgAumKry7dsv5q9Vfbfq29QLL1I9wulAtgB4ADmoy9kY4fodugAODuT2dpOJ0aUzH8E6asBXe0+zP5h7bvbzay+/aOdv+Ha8mnE5YEKGxqF17MGDzcxwMzqTBUWgc65vKuxT7cm9kx2TIHrATOzxzHOEpZ5sanYamXuZgEdJzlbqXyOmzrO6N0J56hVj3YK8prl7eK5L6g3DmFc6l3XEDCWbLWyYGYdf9h1TIGWYMmRHDlDaqcY0qKnO/Qr4oStLH/jXSPk4KSShf2ovoTZ80Db4iICv2D2ttWqS91WDDKgpYHy4adR8TWww8BdmN2KrOg5Zwoo+PV0">
|
||||
<script>
|
||||
if (window.location.protocol !== 'https:' && window.location.hostname !== 'localhost' && window.location.hostname !== '127.0.0.1') {
|
||||
window.location.replace('https://' + window.location.host + window.location.pathname + window.location.search + window.location.hash);
|
||||
@@ -21,7 +23,11 @@
|
||||
--text-secondary: #6b8eaa;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
|
||||
@@ -164,7 +170,8 @@
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
th, td {
|
||||
th,
|
||||
td {
|
||||
text-align: left;
|
||||
padding: 8px;
|
||||
border-bottom: 1px solid #0b2a48;
|
||||
@@ -214,14 +221,16 @@
|
||||
.modal {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0,0,0,.45);
|
||||
background: rgba(0, 0, 0, .45);
|
||||
display: none;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.modal.open { display: flex; }
|
||||
.modal.open {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.panel {
|
||||
width: min(820px, 100%);
|
||||
@@ -257,7 +266,9 @@
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
input, select, textarea {
|
||||
input,
|
||||
select,
|
||||
textarea {
|
||||
width: 100%;
|
||||
border: 1px solid #1d486d;
|
||||
background: #03192c;
|
||||
@@ -286,8 +297,10 @@
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="login-overlay" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,.85); z-index:999; align-items:center; justify-content:center; padding:16px;">
|
||||
<div id="login-overlay"
|
||||
style="display:none; position:fixed; inset:0; background:rgba(0,0,0,.85); z-index:999; align-items:center; justify-content:center; padding:16px;">
|
||||
<div class="panel" style="width:min(440px,100%);">
|
||||
<div class="brand" style="margin-bottom:24px;">
|
||||
<div class="brand-mark">N</div>
|
||||
@@ -298,7 +311,8 @@
|
||||
</div>
|
||||
<div class="row" style="flex-direction:column; gap:6px; margin-bottom:12px;">
|
||||
<label style="font-size:12px; color:#999;">Стенд</label>
|
||||
<select id="l-env" style="background:var(--bg-base); border:1px solid var(--border); color:var(--fg); padding:8px 10px; border-radius:6px;">
|
||||
<select id="l-env"
|
||||
style="background:var(--bg-base); border:1px solid var(--border); color:var(--fg); padding:8px 10px; border-radius:6px;">
|
||||
<option value="dev">Dev</option>
|
||||
<option value="test" selected>Test</option>
|
||||
<option value="prod">Prod</option>
|
||||
@@ -306,47 +320,89 @@
|
||||
</div>
|
||||
<div class="row" style="flex-direction:column; gap:6px; margin-bottom:12px;">
|
||||
<label style="font-size:12px; color:#999;">Токен</label>
|
||||
<textarea id="l-token" rows="5" style="background:var(--bg-base); border:1px solid var(--border); color:var(--fg); padding:8px 10px; border-radius:6px; font-family:monospace; font-size:12px; resize:vertical; width:100%; box-sizing:border-box;" placeholder="Введите токен..."></textarea>
|
||||
<div style="font-size:11px; color:var(--text-secondary); margin-top:4px;">Токен: <strong style="color:#8bc7ff;">Личный кабинет → Профиль пользователя → Токены</strong></div>
|
||||
<textarea id="l-token" rows="5"
|
||||
style="background:var(--bg-base); border:1px solid var(--border); color:var(--fg); padding:8px 10px; border-radius:6px; font-family:monospace; font-size:12px; resize:vertical; width:100%; box-sizing:border-box;"
|
||||
placeholder="Введите токен..."></textarea>
|
||||
<div style="font-size:11px; color:var(--text-secondary); margin-top:4px;">Токен: <strong
|
||||
style="color:#8bc7ff;">Личный кабинет → Профиль пользователя → Токены</strong></div>
|
||||
</div>
|
||||
<div id="l-error" style="display:none; color:#ff6b6b; font-size:13px; margin-bottom:10px;"></div>
|
||||
<button id="l-btn" class="btn" style="width:100%;" onclick="doLogin()">Войти</button>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Overlay: инициализация нового окружения -->
|
||||
<div id="init-overlay" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,.88); z-index:1000; align-items:center; justify-content:center; padding:16px;">
|
||||
<div id="init-overlay"
|
||||
style="display:none; position:fixed; inset:0; background:rgba(0,0,0,.88); z-index:1000; align-items:center; justify-content:center; padding:16px;">
|
||||
<div class="panel" style="width:min(520px,100%);">
|
||||
<div style="margin-bottom:16px;">
|
||||
<div style="font-size:16px; font-weight:700; margin-bottom:6px;">⚙️ Инициализация окружения</div>
|
||||
<div style="font-size:13px; color:var(--text-secondary);">Первый вход. Настраиваем ваше окружение — это займёт ~5 минут.</div>
|
||||
<div style="font-size:13px; color:var(--text-secondary);">Первый вход. Настраиваем ваше окружение — это займёт
|
||||
~5 минут.</div>
|
||||
</div>
|
||||
<div style="display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:10px; margin-bottom:12px;">
|
||||
<div style="background:#0d1827; border:1px solid var(--border); border-radius:6px; padding:10px;">
|
||||
<div style="font-size:11px; color:var(--text-secondary); margin-bottom:4px;">Время настройки</div>
|
||||
<div id="init-elapsed" style="font-size:18px; font-weight:700; color:#8bc7ff;">0с</div>
|
||||
</div>
|
||||
<div style="background:#0d1827; border:1px solid var(--border); border-radius:6px; padding:10px;">
|
||||
<div style="font-size:11px; color:var(--text-secondary); margin-bottom:4px;">Текущий этап</div>
|
||||
<div id="init-current-stage" style="font-size:14px; font-weight:600; color:#f4f7fb;">Ожидание старта</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="init-summary"
|
||||
style="display:none; margin-bottom:10px; background:#101c2b; border:1px solid var(--border); border-radius:6px; padding:10px 12px; font-size:13px; color:#d8e5f2;">
|
||||
</div>
|
||||
<div id="init-reason"
|
||||
style="display:none; margin-bottom:10px; background:#2d2310; border:1px solid #6a5427; border-radius:6px; padding:10px 12px; font-size:13px; color:#ffd98a;">
|
||||
</div>
|
||||
<div id="init-error"
|
||||
style="display:none; margin-bottom:10px; background:#2a1416; border:1px solid #7d3138; border-radius:6px; padding:10px 12px; font-size:13px; color:#ff9da5;">
|
||||
</div>
|
||||
<div id="init-log"
|
||||
style="background:#000d1a; border:1px solid var(--border); border-radius:6px; padding:12px; font-family:monospace; font-size:12px; height:160px; overflow-y:auto; color:#4fc3f7; white-space:pre-wrap; line-height:1.6;">
|
||||
</div>
|
||||
<div id="init-log" style="background:#000d1a; border:1px solid var(--border); border-radius:6px; padding:12px; font-family:monospace; font-size:12px; height:160px; overflow-y:auto; color:#4fc3f7; white-space:pre-wrap; line-height:1.6;"></div>
|
||||
<div id="init-stages" style="margin-top:14px; display:flex; flex-direction:column; gap:8px;"></div>
|
||||
<div style="margin-top:14px; font-size:12px; color:var(--text-secondary);">Страница обновится автоматически когда всё будет готово.</div>
|
||||
<div style="margin-top:14px; font-size:12px; color:var(--text-secondary);">Страница обновится автоматически когда
|
||||
всё будет готово.</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="navbar">
|
||||
<div class="brand-mark">N</div>
|
||||
<div class="brand-text">
|
||||
<div class="nubes">NUBES</div>
|
||||
<div class="product">FISSION CONSOLE</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row" style="margin:0;">
|
||||
<button class="btn ghost" onclick="reloadAll()">Refresh</button>
|
||||
<button class="btn" onclick="openCreate()">+ Создать функцию</button>
|
||||
<button class="btn ghost" onclick="doLogout()" style="margin-left:8px;">Выход</button>
|
||||
<div class="brand-mark">N</div>
|
||||
<div class="brand-text">
|
||||
<div class="nubes">NUBES</div>
|
||||
<div class="product">FISSION CONSOLE</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row" style="margin:0;">
|
||||
<button class="btn ghost" onclick="reloadAll()">Refresh</button>
|
||||
<button class="btn" onclick="openCreate()">+ Создать функцию</button>
|
||||
<button class="btn ghost" onclick="doLogout()" style="margin-left:8px;">Выход</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="wrap">
|
||||
<div class="grid">
|
||||
<div class="card"><div class="k">Окружения</div><div id="env-count" class="v">-</div></div>
|
||||
<div class="card"><div class="k">Пакеты</div><div id="pkg-count" class="v">-</div></div>
|
||||
<div class="card"><div class="k">Функции</div><div id="fn-count" class="v">-</div></div>
|
||||
<div class="card"><div class="k">HTTP-триггеры</div><div id="http-count" class="v">-</div></div>
|
||||
<div class="card"><div class="k">Тайм-триггеры</div><div id="time-count" class="v">-</div></div>
|
||||
<div class="card">
|
||||
<div class="k">Окружения</div>
|
||||
<div id="env-count" class="v">-</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="k">Пакеты</div>
|
||||
<div id="pkg-count" class="v">-</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="k">Функции</div>
|
||||
<div id="fn-count" class="v">-</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="k">HTTP-триггеры</div>
|
||||
<div id="http-count" class="v">-</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="k">Тайм-триггеры</div>
|
||||
<div id="time-count" class="v">-</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="box">
|
||||
@@ -356,7 +412,14 @@
|
||||
</div>
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>Имя</th><th>Окружение</th><th>Пакет</th><th>Маршрут</th><th>Методы</th><th class="nowrap">Действия</th></tr>
|
||||
<tr>
|
||||
<th>Имя</th>
|
||||
<th>Окружение</th>
|
||||
<th>Пакет</th>
|
||||
<th>Маршрут</th>
|
||||
<th>Методы</th>
|
||||
<th class="nowrap">Действия</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="fn-rows"></tbody>
|
||||
</table>
|
||||
@@ -380,7 +443,6 @@
|
||||
<option value="nodejs">Node.js</option>
|
||||
<option value="php">PHP</option>
|
||||
<option value="ruby">Ruby</option>
|
||||
<option value="perl">Perl</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="field">
|
||||
@@ -404,18 +466,22 @@
|
||||
return {"ok": True, "msg": "hello from fission console"}
|
||||
</textarea>
|
||||
<div style="margin-top:6px; display:flex; gap:6px; flex-wrap:wrap;">
|
||||
<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>
|
||||
<button class="btn ghost" id="c-gen-btn" onclick="showGenPrompt()">✨ Сгенерировать код</button>
|
||||
<button class="btn ghost" id="c-exp-btn" onclick="aiExplain('c-code','c-lang','c-ai-result')">📖 Что делает?</button>
|
||||
<button class="btn ghost" id="c-exp-btn" onclick="aiExplain('c-code','c-lang','c-ai-result')">📖 Что
|
||||
делает?</button>
|
||||
</div>
|
||||
<div id="c-gen-prompt" style="display:none; margin-top:8px; display:none; gap:6px; align-items:center;">
|
||||
<input id="c-gen-desc" type="text" placeholder="Что должна делать функция? (напр: принять JSON, вернуть сумму чисел)"
|
||||
style="flex:1; background:#2a2a42; border:1px solid #3a3a5c; border-radius:4px;
|
||||
<input id="c-gen-desc" type="text"
|
||||
placeholder="Что должна делать функция? (напр: принять JSON, вернуть сумму чисел)" style="flex:1; background:#2a2a42; border:1px solid #3a3a5c; border-radius:4px;
|
||||
color:#cdd6f4; padding:6px 8px; font-size:.82rem; outline:none; width:100%;"
|
||||
onkeydown="if(event.key==='Enter')aiGenerate()" />
|
||||
<button class="btn" onclick="aiGenerate()" style="white-space:nowrap;">▶ Генерировать</button>
|
||||
</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 class="actions">
|
||||
<button class="btn ghost" onclick="closeCreate()">Отмена</button>
|
||||
@@ -427,7 +493,11 @@
|
||||
<div id="edit-modal" class="modal">
|
||||
<div class="panel">
|
||||
<h3 id="e-title">Редактирование кода</h3>
|
||||
<div id="e-tf-warn" style="display:none;background:#553300;color:#ffa;padding:8px 12px;border-radius:6px;margin-bottom:10px;font-size:13px;">⚠️ Эта функция управляется Terraform. Изменения могут быть перезаписаны при следующем <code>terraform apply</code>.</div>
|
||||
<div id="e-tf-warn"
|
||||
style="display:none;background:#553300;color:#ffa;padding:8px 12px;border-radius:6px;margin-bottom:10px;font-size:13px;">
|
||||
⚠️ Эта функция управляется Terraform. Изменения могут быть перезаписаны при следующем
|
||||
<code>terraform apply</code>.
|
||||
</div>
|
||||
<input type="hidden" id="e-lang-hidden" value="">
|
||||
<div class="row">
|
||||
<div class="field">
|
||||
@@ -447,10 +517,14 @@
|
||||
<label>Код</label>
|
||||
<textarea id="e-code"></textarea>
|
||||
<div style="margin-top:6px; display:flex; gap:6px; flex-wrap:wrap;">
|
||||
<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-exp-btn" onclick="aiExplain('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>
|
||||
<button class="btn ghost" id="e-exp-btn" onclick="aiExplain('e-code','e-lang-hidden','e-ai-result')">📖
|
||||
Что делает?</button>
|
||||
</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 class="actions">
|
||||
<button class="btn ghost" onclick="closeEdit()">Отмена</button>
|
||||
@@ -471,6 +545,9 @@
|
||||
<button id="i-submit" class="btn" onclick="submitInvoke()">Вызвать</button>
|
||||
</div>
|
||||
<div id="i-status" style="margin-top:8px;font-size:13px;color:var(--text-secondary);min-height:20px;"></div>
|
||||
<div id="i-meta"
|
||||
style="display:none;margin-top:8px;background:#101c2b;border:1px solid var(--border);border-radius:6px;padding:10px 12px;font-size:13px;color:#d8e5f2;white-space:pre-wrap;">
|
||||
</div>
|
||||
<div style="margin-top:6px;">
|
||||
<label>Response</label>
|
||||
<textarea id="i-resp" readonly style="min-height:160px;"></textarea>
|
||||
@@ -497,7 +574,7 @@
|
||||
}
|
||||
|
||||
async function getJSON(url) {
|
||||
const r = await fetch(url, {headers: authHeaders()});
|
||||
const r = await fetch(url, { headers: authHeaders() });
|
||||
if (r.status === 401) { doLogout(); throw new Error('Сессия истекла'); }
|
||||
if (!r.ok) {
|
||||
let msg = '';
|
||||
@@ -515,12 +592,12 @@
|
||||
async function requestJSON(url, method, body) {
|
||||
const r = await fetch(url, {
|
||||
method: method,
|
||||
headers: Object.assign({'Content-Type': 'application/json'}, authHeaders()),
|
||||
headers: Object.assign({ 'Content-Type': 'application/json' }, authHeaders()),
|
||||
body: body ? JSON.stringify(body) : undefined
|
||||
});
|
||||
if (r.status === 401) { doLogout(); throw new Error('Сессия истекла'); }
|
||||
let data = {};
|
||||
try { data = await r.json(); } catch (_) {}
|
||||
try { data = await r.json(); } catch (_) { }
|
||||
if (!r.ok) {
|
||||
throw new Error(data.error || (url + ': ' + r.status));
|
||||
}
|
||||
@@ -571,13 +648,9 @@
|
||||
code: 'def main():\n return "hello from fission"'
|
||||
},
|
||||
nodejs: {
|
||||
entrypoint: 'handler',
|
||||
entrypoint: 'main',
|
||||
code: 'module.exports = async function(context) {\n return {\n status: 200,\n body: "hello from fission"\n };\n}'
|
||||
},
|
||||
go: {
|
||||
entrypoint: 'Handler',
|
||||
code: 'package main\n\nimport (\n "fmt"\n "net/http"\n)\n\nfunc Handler(w http.ResponseWriter, r *http.Request) {\n fmt.Fprintf(w, "hello from fission")\n}'
|
||||
},
|
||||
php: {
|
||||
entrypoint: 'main.php::handler',
|
||||
code: '<?php\nfunction handler($context)\n{\n $response = $context["response"];\n $response->getBody()->write("hello from fission");\n}'
|
||||
@@ -585,10 +658,6 @@
|
||||
ruby: {
|
||||
entrypoint: 'handler',
|
||||
code: '# frozen_string_literal: true\n\ndef handler\n "hello from fission"\nend'
|
||||
},
|
||||
perl: {
|
||||
entrypoint: 'handler',
|
||||
code: 'sub {\n return "hello from fission";\n}'
|
||||
}
|
||||
};
|
||||
|
||||
@@ -615,6 +684,7 @@
|
||||
async function submitCreate() {
|
||||
const btn = document.getElementById('c-submit');
|
||||
btn.disabled = true;
|
||||
const progress = startTimedStatus('Создаём функцию...', 'Создание функции...', explainDelay);
|
||||
try {
|
||||
const name = document.getElementById('c-name').value.trim();
|
||||
if (!name) throw new Error('name is required');
|
||||
@@ -631,10 +701,10 @@
|
||||
});
|
||||
|
||||
closeCreate();
|
||||
showStatus('\u0424\u0443\u043d\u043a\u0446\u0438\u044f \u0441\u043e\u0437\u0434\u0430\u043d\u0430: ' + name, 'ok');
|
||||
progress.stop('\u0424\u0443\u043d\u043a\u0446\u0438\u044f \u0441\u043e\u0437\u0434\u0430\u043d\u0430: ' + name, 'ok');
|
||||
await reloadAll();
|
||||
} catch (e) {
|
||||
showStatus('\u041e\u0448\u0438\u0431\u043a\u0430 \u0441\u043e\u0437\u0434\u0430\u043d\u0438\u044f: ' + e.message, 'err');
|
||||
progress.stop('\u041e\u0448\u0438\u0431\u043a\u0430 \u0441\u043e\u0437\u0434\u0430\u043d\u0438\u044f: ' + e.message, 'err');
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
@@ -656,7 +726,6 @@
|
||||
else if (envName.includes('go')) lang = 'go';
|
||||
else if (envName.includes('ruby')) lang = 'ruby';
|
||||
else if (envName.includes('php')) lang = 'php';
|
||||
else if (envName.includes('perl')) lang = 'perl';
|
||||
document.getElementById('e-lang-hidden').value = lang;
|
||||
// сбросить предыдущий AI-результат
|
||||
var aiRes = document.getElementById('e-ai-result');
|
||||
@@ -681,15 +750,16 @@
|
||||
if (!S.currentEdit) return;
|
||||
const btn = document.getElementById('e-submit');
|
||||
btn.disabled = true;
|
||||
const progress = startTimedStatus('Сохраняем код...', 'Сохранение кода...', explainDelay);
|
||||
try {
|
||||
const name = S.currentEdit.name;
|
||||
await requestJSON(API_BASE + '/functions/' + encodeURIComponent(name) + '/code', 'PUT', {
|
||||
code: document.getElementById('e-code').value
|
||||
});
|
||||
closeEdit();
|
||||
showStatus('\u041a\u043e\u0434 \u043e\u0431\u043d\u043e\u0432\u043b\u0451\u043d: ' + name, 'ok');
|
||||
progress.stop('\u041a\u043e\u0434 \u043e\u0431\u043d\u043e\u0432\u043b\u0451\u043d: ' + name, 'ok');
|
||||
} catch (e) {
|
||||
showStatus('\u041e\u0448\u0438\u0431\u043a\u0430 \u043e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0438\u044f: ' + e.message, 'err');
|
||||
progress.stop('\u041e\u0448\u0438\u0431\u043a\u0430 \u043e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0438\u044f: ' + e.message, 'err');
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
@@ -699,6 +769,9 @@
|
||||
S.currentInvoke = name;
|
||||
document.getElementById('i-title').textContent = '\u0412\u044b\u0437\u043e\u0432: ' + name;
|
||||
document.getElementById('i-resp').value = '';
|
||||
document.getElementById('i-status').textContent = '';
|
||||
document.getElementById('i-meta').style.display = 'none';
|
||||
document.getElementById('i-meta').textContent = '';
|
||||
document.getElementById('invoke-modal').classList.add('open');
|
||||
}
|
||||
|
||||
@@ -711,9 +784,12 @@
|
||||
if (!S.currentInvoke) return;
|
||||
const btn = document.getElementById('i-submit');
|
||||
const statusEl = document.getElementById('i-status');
|
||||
const metaEl = document.getElementById('i-meta');
|
||||
const respEl = document.getElementById('i-resp');
|
||||
btn.disabled = true;
|
||||
respEl.value = '';
|
||||
metaEl.style.display = 'none';
|
||||
metaEl.textContent = '';
|
||||
let elapsed = 0;
|
||||
statusEl.textContent = 'Вызов...';
|
||||
const timer = setInterval(() => {
|
||||
@@ -721,9 +797,9 @@
|
||||
if (elapsed < 5) {
|
||||
statusEl.textContent = 'Вызов... ' + elapsed + 'с';
|
||||
} else if (elapsed < 10) {
|
||||
statusEl.textContent = '⏳ Холодный старт — прогрев пула... ' + elapsed + 'с';
|
||||
statusEl.textContent = '⏳ Возможен cold start — прогрев пула... ' + elapsed + 'с';
|
||||
} else {
|
||||
statusEl.textContent = '⏳ Холодный старт — ещё немного... ' + elapsed + 'с';
|
||||
statusEl.textContent = '⏳ Возможны cold start или specialization... ' + elapsed + 'с';
|
||||
}
|
||||
}, 1000);
|
||||
try {
|
||||
@@ -731,10 +807,24 @@
|
||||
let parsed = {};
|
||||
if (raw) parsed = JSON.parse(raw);
|
||||
const result = await requestJSON(API_BASE + '/functions/' + encodeURIComponent(S.currentInvoke) + '/invoke', 'POST', parsed);
|
||||
statusEl.textContent = '✓ Выполнено за ' + elapsed + 'с';
|
||||
var latencyMs = Number(result.latency_ms || 0);
|
||||
var measuredSeconds = latencyMs > 0 ? Math.max(1, Math.round(latencyMs / 1000)) : elapsed;
|
||||
statusEl.textContent = '✓ Выполнено за ' + formatSeconds(measuredSeconds);
|
||||
metaEl.style.display = 'block';
|
||||
metaEl.textContent = [
|
||||
'HTTP status: ' + (result.status || 'n/a'),
|
||||
'Latency: ' + (latencyMs || 'n/a') + ' ms',
|
||||
'Причина задержки: ' + explainDelay(measuredSeconds),
|
||||
'Invoke URL: ' + (result.invoke_url || 'n/a')
|
||||
].join('\n');
|
||||
respEl.value = JSON.stringify(result, null, 2);
|
||||
} catch (e) {
|
||||
statusEl.textContent = '✗ Ошибка после ' + elapsed + 'с';
|
||||
statusEl.textContent = '✗ Ошибка после ' + formatSeconds(elapsed);
|
||||
metaEl.style.display = 'block';
|
||||
metaEl.textContent = [
|
||||
'Последняя ошибка: ' + e.message,
|
||||
'Вероятная причина задержки: ' + explainDelay(elapsed)
|
||||
].join('\n');
|
||||
respEl.value = 'Ошибка вызова: ' + e.message;
|
||||
} finally {
|
||||
clearInterval(timer);
|
||||
@@ -745,12 +835,13 @@
|
||||
async function removeFn(name) {
|
||||
var tfWarn = (/^tf-/.test(name)) ? '\n\n\u26a0\ufe0f \u042d\u0442\u0430 \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0443\u043f\u0440\u0430\u0432\u043b\u044f\u0435\u0442\u0441\u044f Terraform. \u0423\u0434\u0430\u043b\u0435\u043d\u0438\u0435 \u043f\u0440\u0438\u0432\u0435\u0434\u0451\u0442 \u043a \u0440\u0430\u0441\u0441\u0438\u043d\u0445\u0440\u043e\u043d\u0438\u0437\u0430\u0446\u0438\u0438 state!' : '';
|
||||
if (!confirm('\u0423\u0434\u0430\u043b\u0438\u0442\u044c \u0444\u0443\u043d\u043a\u0446\u0438\u044e ' + name + '?' + tfWarn)) return;
|
||||
var progress = startTimedStatus('\u0423\u0434\u0430\u043b\u044f\u0435\u043c \u0444\u0443\u043d\u043a\u0446\u0438\u044e...', '\u0423\u0434\u0430\u043b\u0435\u043d\u0438\u0435 \u0444\u0443\u043d\u043a\u0446\u0438\u0438...', explainDelay);
|
||||
try {
|
||||
await requestJSON(API_BASE + '/functions/' + encodeURIComponent(name), 'DELETE');
|
||||
showStatus('\u0424\u0443\u043d\u043a\u0446\u0438\u044f \u0443\u0434\u0430\u043b\u0435\u043d\u0430: ' + name, 'ok');
|
||||
progress.stop('\u0424\u0443\u043d\u043a\u0446\u0438\u044f \u0443\u0434\u0430\u043b\u0435\u043d\u0430: ' + name, 'ok');
|
||||
await reloadAll();
|
||||
} catch (e) {
|
||||
showStatus('\u041e\u0448\u0438\u0431\u043a\u0430 \u0443\u0434\u0430\u043b\u0435\u043d\u0438\u044f: ' + e.message, 'err');
|
||||
progress.stop('\u041e\u0448\u0438\u0431\u043a\u0430 \u0443\u0434\u0430\u043b\u0435\u043d\u0438\u044f: ' + e.message, 'err');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -797,7 +888,7 @@
|
||||
'<td class="mono">' + h(route) + '</td>' +
|
||||
'<td>' + chips + '</td>' +
|
||||
'<td class="nowrap">' + actions + '</td>' +
|
||||
'</tr>';
|
||||
'</tr>';
|
||||
}).join('');
|
||||
|
||||
document.getElementById('fn-rows').innerHTML = rows || '<tr><td colspan="3">\u041d\u0435\u0442 \u0444\u0443\u043d\u043a\u0446\u0438\u0439</td></tr>';
|
||||
@@ -829,11 +920,11 @@
|
||||
try {
|
||||
const res = await fetch(API_BASE + '/auth', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({token: token, env: env})
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token: token, env: env })
|
||||
});
|
||||
if (!res.ok) {
|
||||
const d = await res.json().catch(function() { return {}; });
|
||||
const d = await res.json().catch(function () { return {}; });
|
||||
throw new Error(d.error || 'Ошибка входа');
|
||||
}
|
||||
localStorage.setItem('auth_token', token);
|
||||
@@ -841,15 +932,15 @@
|
||||
hideLoginOverlay();
|
||||
// Проверяем статус NS — если не ready, показываем init overlay
|
||||
try {
|
||||
var sr = await fetch(API_BASE + '/ns/status', {headers: {'X-Auth-Token': token, 'X-Auth-Env': env}});
|
||||
var sr = await fetch(API_BASE + '/ns/status', { headers: { 'X-Auth-Token': token, 'X-Auth-Env': env } });
|
||||
var sd = await sr.json();
|
||||
if (!sd.ready) {
|
||||
pollNSStatus();
|
||||
return;
|
||||
}
|
||||
} catch(_) {}
|
||||
} catch (_) { }
|
||||
reloadAll();
|
||||
} catch(e) {
|
||||
} catch (e) {
|
||||
errEl.textContent = e.message;
|
||||
errEl.style.display = 'block';
|
||||
} finally {
|
||||
@@ -860,7 +951,7 @@
|
||||
function doLogout() {
|
||||
localStorage.removeItem('auth_token');
|
||||
localStorage.removeItem('auth_env');
|
||||
try { document.getElementById('l-token').value = ''; } catch(_) {}
|
||||
try { document.getElementById('l-token').value = ''; } catch (_) { }
|
||||
showLoginOverlay();
|
||||
}
|
||||
|
||||
@@ -878,11 +969,11 @@
|
||||
resEl.style.color = 'var(--fg)';
|
||||
resEl.textContent = 'Отправляю код в LLM...';
|
||||
try {
|
||||
var data = await requestJSON(API_BASE + '/ai/check', 'POST', {language: lang, code: code});
|
||||
var data = await requestJSON(API_BASE + '/ai/check', 'POST', { language: lang, code: code });
|
||||
resEl.style.background = data.ok ? '#1a3a1a' : '#3a1a1a';
|
||||
resEl.style.color = data.ok ? '#8f8' : '#f88';
|
||||
resEl.textContent = data.result || '(пустой ответ)';
|
||||
} catch(e) {
|
||||
} catch (e) {
|
||||
resEl.style.background = '#3a2a00';
|
||||
resEl.style.color = '#ffa';
|
||||
resEl.textContent = 'Ошибка: ' + e.message;
|
||||
@@ -893,6 +984,8 @@
|
||||
}
|
||||
|
||||
var _initPolling = false;
|
||||
var _initTickBusy = false;
|
||||
var _initStartedAt = 0;
|
||||
|
||||
function initLog(msg) {
|
||||
var el = document.getElementById('init-log');
|
||||
@@ -901,9 +994,109 @@
|
||||
el.scrollTop = el.scrollHeight;
|
||||
}
|
||||
|
||||
function formatSeconds(totalSeconds) {
|
||||
totalSeconds = Math.max(0, Number(totalSeconds) || 0);
|
||||
var minutes = Math.floor(totalSeconds / 60);
|
||||
var seconds = totalSeconds % 60;
|
||||
if (minutes <= 0) return seconds + 'с';
|
||||
return minutes + 'м ' + seconds + 'с';
|
||||
}
|
||||
|
||||
function setInitElapsed(seconds) {
|
||||
document.getElementById('init-elapsed').textContent = formatSeconds(seconds);
|
||||
}
|
||||
|
||||
function setInitCurrentStage(text) {
|
||||
document.getElementById('init-current-stage').textContent = text || 'Ожидание старта';
|
||||
}
|
||||
|
||||
function setBox(id, text) {
|
||||
var el = document.getElementById(id);
|
||||
if (!el) return;
|
||||
if (!text) {
|
||||
el.style.display = 'none';
|
||||
el.textContent = '';
|
||||
return;
|
||||
}
|
||||
el.style.display = 'block';
|
||||
el.textContent = text;
|
||||
}
|
||||
|
||||
function missingKeys(obj) {
|
||||
return Object.keys(obj || {}).filter(function (key) {
|
||||
return !obj[key];
|
||||
});
|
||||
}
|
||||
|
||||
function firstPendingStage(stages) {
|
||||
var list = stages || [];
|
||||
for (var i = 0; i < list.length; i++) {
|
||||
if (!list[i].done) return list[i].name;
|
||||
}
|
||||
return list.length ? list[list.length - 1].name : 'Ожидание старта';
|
||||
}
|
||||
|
||||
function describeInitReason(debug) {
|
||||
if (!debug) return 'Собираем диагностические данные по namespace и control-plane...';
|
||||
if (!debug.exists) return 'Ещё не создан Kubernetes namespace пользователя.';
|
||||
if (!debug.active) return 'Namespace создан, но Kubernetes ещё не перевёл его в состояние Active.';
|
||||
|
||||
var preparation = debug.preparation || {};
|
||||
if (!preparation.managedByConsole) return 'Namespace существует, но ещё не помечен как managed-by=fission-console.';
|
||||
if (!preparation.watcherLabel) return 'Namespace ещё не помечен label fission.io/managed=true для NSWatcher.';
|
||||
|
||||
var missingSAs = missingKeys(preparation.serviceAccounts);
|
||||
if (missingSAs.length) return 'Не готовы bootstrap service accounts: ' + missingSAs.join(', ') + '.';
|
||||
|
||||
var missingRBs = missingKeys(preparation.roleBindings);
|
||||
if (missingRBs.length) return 'Не готовы bootstrap role bindings: ' + missingRBs.join(', ') + '.';
|
||||
|
||||
var control = debug.controlPlane || {};
|
||||
if (!control.executor || !control.executor.ready) {
|
||||
return 'Executor ещё не ready. Возможна задержка из-за cold start, image pull или specialization.';
|
||||
}
|
||||
if (!control.router || !control.router.ready) {
|
||||
return 'Router ещё не ready. HTTP маршрутизация пока не активна.';
|
||||
}
|
||||
|
||||
return 'Ожидаем финальное подтверждение готовности control-plane.';
|
||||
}
|
||||
|
||||
function summarizeInit(status, debug) {
|
||||
var done = status && status.stages ? status.stages.filter(function (s) { return s.done; }).length : 0;
|
||||
var namespace = debug && debug.namespace ? debug.namespace : 'не определён';
|
||||
return 'Namespace: ' + namespace + '. Завершено шагов: ' + done + '/3.';
|
||||
}
|
||||
|
||||
function explainDelay(seconds) {
|
||||
if (seconds < 5) return 'Обычная операция без заметной задержки.';
|
||||
if (seconds < 10) return 'Вероятен cold start: прогрев пула, image pull или ожидание specialization.';
|
||||
return 'Задержка выше нормы: возможны cold start, specialization или ожидание готовности control-plane.';
|
||||
}
|
||||
|
||||
function startTimedStatus(startText, waitingPrefix, waitingHint) {
|
||||
var startedAt = Date.now();
|
||||
showStatus(startText, '');
|
||||
var timer = setInterval(function () {
|
||||
var elapsed = Math.max(1, Math.floor((Date.now() - startedAt) / 1000));
|
||||
var text = waitingPrefix + ' ' + formatSeconds(elapsed);
|
||||
if (waitingHint) text += ' · ' + waitingHint(elapsed);
|
||||
showStatus(text, '');
|
||||
}, 1000);
|
||||
return {
|
||||
stop: function (message, kind) {
|
||||
clearInterval(timer);
|
||||
var elapsed = Math.max(0, Math.round((Date.now() - startedAt) / 1000));
|
||||
var text = message;
|
||||
if (message) text += ' за ' + formatSeconds(elapsed);
|
||||
showStatus(text, kind || '');
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function renderInitStages(stages) {
|
||||
var el = document.getElementById('init-stages');
|
||||
el.innerHTML = stages.map(function(s) {
|
||||
el.innerHTML = stages.map(function (s) {
|
||||
var icon = s.done ? '✅' : '⏳';
|
||||
var color = s.done ? '#4caf50' : '#8bc7ff';
|
||||
return '<div style="font-size:13px; color:' + color + ';">' + icon + ' ' + s.name + '</div>';
|
||||
@@ -913,33 +1106,57 @@
|
||||
async function pollNSStatus() {
|
||||
if (_initPolling) return;
|
||||
_initPolling = true;
|
||||
_initTickBusy = false;
|
||||
_initStartedAt = Date.now();
|
||||
var overlay = document.getElementById('init-overlay');
|
||||
overlay.style.display = 'flex';
|
||||
document.getElementById('init-log').textContent = '';
|
||||
setInitElapsed(0);
|
||||
setInitCurrentStage('Подготовка запуска');
|
||||
setBox('init-summary', 'Проверяем состояние namespace и control-plane...');
|
||||
setBox('init-reason', 'Если пользователь новый, возможны cold start и создание bootstrap ресурсов.');
|
||||
setBox('init-error', '');
|
||||
initLog('Запуск инициализации...');
|
||||
var attempt = 0;
|
||||
var maxAttempts = 60; // 5 минут
|
||||
var interval = setInterval(async function() {
|
||||
var interval = setInterval(async function () {
|
||||
if (_initTickBusy) return;
|
||||
_initTickBusy = true;
|
||||
attempt++;
|
||||
try {
|
||||
var r = await fetch(API_BASE + '/ns/status', {headers: authHeaders()});
|
||||
var d = await r.json();
|
||||
var elapsed = Math.floor((Date.now() - _initStartedAt) / 1000);
|
||||
setInitElapsed(elapsed);
|
||||
var statusResp = await fetch(API_BASE + '/ns/status', { headers: authHeaders() });
|
||||
var debugResp = await fetch(API_BASE + '/ns/debug', { headers: authHeaders() });
|
||||
var d = await statusResp.json();
|
||||
var dbg = await debugResp.json().catch(function () { return null; });
|
||||
if (d.stages) renderInitStages(d.stages);
|
||||
var done = d.stages ? d.stages.filter(function(s){return s.done;}).length : 0;
|
||||
setInitCurrentStage(firstPendingStage(d.stages));
|
||||
setBox('init-summary', summarizeInit(d, dbg));
|
||||
setBox('init-reason', describeInitReason(dbg));
|
||||
setBox('init-error', '');
|
||||
var done = d.stages ? d.stages.filter(function (s) { return s.done; }).length : 0;
|
||||
initLog('Шагов завершено: ' + done + '/3');
|
||||
if (d.ready) {
|
||||
initLog('✅ Готово! Загружаем консоль...');
|
||||
clearInterval(interval);
|
||||
_initPolling = false;
|
||||
_initTickBusy = false;
|
||||
overlay.style.display = 'none';
|
||||
reloadAll();
|
||||
return;
|
||||
}
|
||||
} catch(e) {
|
||||
} catch (e) {
|
||||
setBox('init-error', 'Последняя ошибка: ' + e.message);
|
||||
initLog('Ошибка опроса: ' + e.message);
|
||||
} finally {
|
||||
_initTickBusy = false;
|
||||
}
|
||||
if (attempt >= maxAttempts) {
|
||||
clearInterval(interval);
|
||||
_initPolling = false;
|
||||
_initTickBusy = false;
|
||||
setBox('init-error', 'Превышено время ожидания. Чаще всего это bootstrap RBAC, control-plane readiness или холодный старт.');
|
||||
initLog('⚠️ Превышено время ожидания. Попробуйте обновить страницу.');
|
||||
}
|
||||
}, 5000);
|
||||
@@ -982,8 +1199,7 @@
|
||||
white-space:pre-wrap; word-break:break-word;
|
||||
">Чем могу помочь?</div>
|
||||
<div style="display:flex; gap:6px;">
|
||||
<input id="assistant-input" type="text" placeholder="Введи вопрос..."
|
||||
style="flex:1; background:#2a2a42; border:1px solid #3a3a5c; border-radius:4px;
|
||||
<input id="assistant-input" type="text" placeholder="Введи вопрос..." style="flex:1; background:#2a2a42; border:1px solid #3a3a5c; border-radius:4px;
|
||||
color:#cdd6f4; padding:6px 8px; font-size:.82rem; outline:none;"
|
||||
onkeydown="if(event.key==='Enter')askAssistant()" />
|
||||
<button onclick="askAssistant()" style="
|
||||
@@ -1017,7 +1233,7 @@
|
||||
});
|
||||
var d = await r.json();
|
||||
msgs.textContent = msgs.textContent.replace('⏳ ...', '🤖 ' + (d.answer || d.error || 'Нет ответа'));
|
||||
} catch(e) {
|
||||
} catch (e) {
|
||||
msgs.textContent = msgs.textContent.replace('⏳ ...', '❌ Ошибка: ' + e.message);
|
||||
}
|
||||
msgs.scrollTop = msgs.scrollHeight;
|
||||
@@ -1039,13 +1255,13 @@
|
||||
resEl.textContent = 'Запрашиваю у LLM...';
|
||||
try {
|
||||
var q = 'Напиши функцию Fission на ' + lang + ' с именем "' + name + '". Функция должна: ' + desc + '. Верни только чистый код без пояснений и без markdown-блоков.';
|
||||
var d = await requestJSON('/console/api/ai/ask', 'POST', {question: q});
|
||||
var d = await requestJSON('/console/api/ai/ask', 'POST', { question: q });
|
||||
var code = (d.answer || '').replace(/^```[\w]*\n?/, '').replace(/\n?```$/, '');
|
||||
document.getElementById('c-code').value = code;
|
||||
document.getElementById('c-gen-prompt').style.display = 'none';
|
||||
resEl.style.background = '#1a3a1a'; resEl.style.color = '#8f8';
|
||||
resEl.textContent = 'Код сгенерирован и вставлен.';
|
||||
} catch(e) {
|
||||
} catch (e) {
|
||||
resEl.style.background = '#3a2a00'; resEl.style.color = '#ffa';
|
||||
resEl.textContent = 'Ошибка: ' + e.message;
|
||||
} finally {
|
||||
@@ -1058,16 +1274,16 @@
|
||||
var resEl = document.getElementById(resultId);
|
||||
var btnId = codeId === 'c-code' ? 'c-exp-btn' : 'e-exp-btn';
|
||||
var btn = document.getElementById(btnId);
|
||||
if (!code) { resEl.style.display='block'; resEl.style.background='var(--bg-alt)'; resEl.textContent='Введите код.'; return; }
|
||||
if (!code) { resEl.style.display = 'block'; resEl.style.background = 'var(--bg-alt)'; resEl.textContent = 'Введите код.'; return; }
|
||||
btn.disabled = true; btn.textContent = '⏳ Объясняю...';
|
||||
resEl.style.display = 'block'; resEl.style.background = 'var(--bg-alt)'; resEl.style.color = 'var(--fg)';
|
||||
resEl.textContent = 'Запрашиваю у LLM...';
|
||||
try {
|
||||
var q = 'Кратко объясни что делает этот ' + lang + ' код:\n' + code;
|
||||
var d = await requestJSON('/console/api/ai/ask', 'POST', {question: q});
|
||||
var d = await requestJSON('/console/api/ai/ask', 'POST', { question: q });
|
||||
resEl.style.background = '#1a2a3a'; resEl.style.color = '#8cf';
|
||||
resEl.textContent = d.answer || '(пустой ответ)';
|
||||
} catch(e) {
|
||||
} catch (e) {
|
||||
resEl.style.background = '#3a2a00'; resEl.style.color = '#ffa';
|
||||
resEl.textContent = 'Ошибка: ' + e.message;
|
||||
} finally {
|
||||
@@ -1079,4 +1295,5 @@
|
||||
<!-- end ai/ask feature -->
|
||||
|
||||
</body>
|
||||
</html>
|
||||
|
||||
</html>
|
||||
Reference in New Issue
Block a user