package node // Physical uplinks are independent of the private-network provider. The root // adapter owns the timed rollback even if this process or Core disappears. import ( "bufio" "context" "encoding/json" "errors" "net" "net/url" "sync" "time" ) type uplinkState map[string]any type uplinkWork struct { body map[string]any id string lease map[string]any received time.Time } type uplinkController struct { mu sync.Mutex value uplinkState observed time.Time busy bool receipt map[string]any commands chan uplinkWork call func(map[string]any) (uplinkState, error) } func uplinkHelper(body map[string]any) (uplinkState, error) { c, err := net.DialTimeout("unix", "/run/mission-core-uplink/control.sock", time.Second) if err != nil { return nil, errors.New("Для выбора подключения обновите Node на борту.") } defer c.Close() _ = c.SetDeadline(time.Now().Add(35 * time.Second)) if err = json.NewEncoder(c).Encode(body); err != nil { return nil, err } raw, err := bufio.NewReaderSize(c, 32769).ReadSlice('\n') var result struct { OK bool `json:"ok"` Result uplinkState `json:"result"` Error string `json:"error"` } if err != nil || len(raw) > 32768 || json.Unmarshal(raw, &result) != nil { return nil, errors.New("Нет подтверждения сетевой службы.") } if !result.OK { return nil, errors.New(result.Error) } return result.Result, nil } func newUplink(ctx context.Context) *uplinkController { u := &uplinkController{commands: make(chan uplinkWork, 1), call: uplinkHelper} go u.run(ctx) return u } func (u *uplinkController) run(ctx context.Context) { timer := time.NewTicker(5 * time.Second) defer timer.Stop() work := uplinkWork{body: map[string]any{"action": "status"}} for { value, err := u.execute(work) u.mu.Lock() if err == nil { u.value = value u.observed = time.Now() } else if work.id != "" { u.receipt = map[string]any{"id": work.id, "phase": "failed", "message": err.Error()} } else { u.value = uplinkState{"supported": false, "reason": "Сетевая служба недоступна. Обновите Node или проверьте состояние борта.", "candidates": []any{}, "operation": u.value["operation"]} u.observed = time.Now() } u.busy = false u.mu.Unlock() select { case <-ctx.Done(): return case work = <-u.commands: u.mu.Lock() u.busy = true u.mu.Unlock() case <-timer.C: work = uplinkWork{body: map[string]any{"action": "status"}} } } } // The authenticated reply carrying a command is itself a Core lease. Renew it // in the same serialized work item before staging; a command must not suppress // the heartbeat whose freshness the helper requires. Never renew queued old data. func (u *uplinkController) execute(work uplinkWork) (uplinkState, error) { fresh := func() bool { return work.received.IsZero() || time.Since(work.received) <= 20*time.Second } if !fresh() { return nil, errors.New("Ответ Core устарел до выполнения команды. Повторите выбор подключения.") } if work.lease != nil { if _, err := u.call(work.lease); err != nil { return nil, err } if !fresh() { return nil, errors.New("Подтверждение Core устарело. Подключение не изменено.") } } return u.call(work.body) } func (u *uplinkController) snapshot() uplinkState { if u == nil { return uplinkState{"supported": false, "candidates": []any{}} } u.mu.Lock() defer u.mu.Unlock() result := uplinkState{} for k, v := range u.value { if k != "diagnostic" { // Local DEV evidence must not increase the heartbeat payload. result[k] = v } } if time.Since(u.observed) > 20*time.Second { result["supported"] = false result["reason"] = "Нет свежего подтверждения сетевой службы." } result["receipt"] = u.receipt return result } func (u *uplinkController) pending() bool { if u == nil { return false } u.mu.Lock() defer u.mu.Unlock() op, _ := u.value["operation"].(map[string]any) return u.busy || len(u.commands) > 0 || op["phase"] == "applying" || op["phase"] == "verifying" || op["phase"] == "rolling_back" || op["phase"] == "recovering" } func (u *uplinkController) submit(body map[string]any, id string) { u.submitCore(body, id, nil, time.Time{}) } func (u *uplinkController) submitCore(body map[string]any, id string, lease map[string]any, received time.Time) { u.mu.Lock() defer u.mu.Unlock() if u.busy { return } select { case u.commands <- uplinkWork{body: body, id: id, lease: lease, received: received}: u.busy = true u.receipt = nil default: } } func (p *Pairing) acceptUplink(binding CoreBinding, instance string, raw, ack json.RawMessage, received time.Time) { if p.uplink == nil { return } p.mu.Lock() valid := p.state.Phase == "paired" && p.state.Binding != nil && p.state.Binding.BindingID == binding.BindingID && p.state.Binding.Endpoint == binding.Endpoint && p.state.Binding.EndpointRevision == binding.EndpointRevision _ = p.loadNetworkLocked() overlayBusy := p.network != nil && p.network.Pending != nil provider := "" if p.network != nil { provider = p.network.Provider } p.mu.Unlock() if !valid { return } scope := binding.BindingID + ":" + instance endpoint, err := url.Parse(binding.Endpoint) if err != nil || net.ParseIP(endpoint.Hostname()) == nil { return } lease := map[string]any{"action": "heartbeat", "binding": scope, "provider": provider, "peer": endpoint.Hostname()} var confirm struct { ID string `json:"id"` Nonce string `json:"nonce"` } if json.Unmarshal(ack, &confirm) == nil && networkOperationID.MatchString(confirm.ID) && networkOperationID.MatchString(confirm.Nonce) { p.uplink.submitCore(map[string]any{"action": "confirm", "id": confirm.ID, "binding": scope, "nonce": confirm.Nonce}, confirm.ID, lease, received) return } var command struct { ID string `json:"id"` Runtime string `json:"runtime"` Target string `json:"target"` Revision json.RawMessage `json:"revision"` ExpiresAt int64 `json:"expires_at"` Kind string `json:"kind"` Enabled *bool `json:"enabled"` } if overlayBusy || json.Unmarshal(raw, &command) != nil || !networkOperationID.MatchString(command.ID) || command.Runtime != instance || command.ExpiresAt <= time.Now().Unix() || command.ExpiresAt > time.Now().Unix()+60 { // Only this authenticated response path renews the onboard Core lease. p.uplink.submitCore(lease, "", nil, received) return } if command.Kind == "fallback" { var revision int if command.Enabled == nil || json.Unmarshal(command.Revision, &revision) != nil || revision < 0 { return } p.uplink.submitCore(map[string]any{"action": "fallback", "id": command.ID, "binding": scope, "enabled": *command.Enabled, "revision": revision, "expires_at": command.ExpiresAt}, command.ID, lease, received) return } var revision string if command.Kind != "" || json.Unmarshal(command.Revision, &revision) != nil { return } p.uplink.submitCore(map[string]any{"action": "stage", "id": command.ID, "binding": scope, "target": command.Target, "revision": revision, "expires_at": command.ExpiresAt}, command.ID, lease, received) }