snapshot before legacy cleanup

This commit is contained in:
Naeel
2026-04-27 07:36:06 +03:00
parent 9461026546
commit 7cfe20bf76
25 changed files with 1430 additions and 261 deletions
+1 -2
View File
@@ -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 в процессе
}
+21 -21
View File
@@ -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)
+168 -62
View File
@@ -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
}
}
+2 -2
View File
@@ -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) {
+1
View File
@@ -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))
-1
View File
@@ -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)
+1 -6
View File
@@ -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},
}
-3
View File
@@ -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"
+1 -1
View File
@@ -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
+9 -1
View File
@@ -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
+50
View File
@@ -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 -1
View File
@@ -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: