feat: replace iot adapter with mqtt command pipeline

This commit is contained in:
2026-08-03 13:18:11 +08:00
parent 6ed417c8c1
commit fefdba470a
48 changed files with 1620 additions and 338 deletions

View File

@@ -1,3 +1,3 @@
# Platform Worker
# Worker
独立 Worker 进程沿用仓库统一的 BSM 配置与基础设施创建方式。首期只提供 Mock 事件循环,真实 Redis Streams 消费将在 Outbox、死信、幂等消费与积压监控契约确定后接入
独立 Worker 负责支付超时任务,并通过 API 的锁定认领接口投递 IoT Outbox。数据库事实仍由 API 维护Worker 不复制同步领域事务;后续可在保持 Outbox 状态契约的前提下用 Redis Streams 唤醒替代短轮询

View File

@@ -1,18 +1,18 @@
// Worker 进程入口;保留独立扩缩和 Redis Streams 消费边界。
package main
import (
"bytes"
"context"
"encoding/json"
"git.apinb.com/bsm-sdk/core/printer"
"git.apinb.com/heqiapp/platforms/backend/worker/internal/config"
"git.apinb.com/heqiapp/platforms/backend/worker/internal/impl"
"io"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"git.apinb.com/bsm-sdk/core/printer"
"git.apinb.com/heqiapp/platforms/backend/worker/internal/config"
"git.apinb.com/heqiapp/platforms/backend/worker/internal/impl"
)
func main() {
@@ -21,18 +21,115 @@ func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go closeExpiredPayments(ctx)
printer.Info("[BSM - PlatformWorker] payment timeout scheduler started")
go dispatchIoTOutbox(ctx)
printer.Info("[BSM - PlatformWorker] payment scheduler and IoT Outbox dispatcher started")
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
cancel()
}
func closeExpiredPayments(ctx context.Context) {
ticker := time.NewTicker(time.Duration(config.Spec.PaymentAPI.IntervalSeconds) * time.Second); defer ticker.Stop()
for { select { case <-ctx.Done(): return; case <-ticker.C:
request, err := http.NewRequestWithContext(ctx, http.MethodPost, config.Spec.PaymentAPI.BaseURL+"/heqi/internal/v1/payment/close-expired", bytes.NewReader(nil)); if err != nil { continue }
request.Header.Set("X-Heqi-Worker-Token", config.Spec.PaymentAPI.Token)
response, err := http.DefaultClient.Do(request); if err == nil { _ = response.Body.Close() }
} }
ticker := time.NewTicker(time.Duration(config.Spec.PaymentAPI.IntervalSeconds) * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
request, err := http.NewRequestWithContext(ctx, http.MethodPost, config.Spec.PaymentAPI.BaseURL+"/heqi/internal/v1/payment/close-expired", bytes.NewReader(nil))
if err != nil {
continue
}
request.Header.Set("X-Heqi-Worker-Token", config.Spec.PaymentAPI.Token)
response, err := http.DefaultClient.Do(request)
if err == nil {
_ = response.Body.Close()
}
}
}
}
type iotOutbox struct {
Identity string `json:"identity"`
CommandIdentity string `json:"command_identity"`
Payload string `json:"payload"`
}
func dispatchIoTOutbox(ctx context.Context) {
ticker := time.NewTicker(time.Duration(config.Spec.IoTAPI.IntervalMilliseconds) * time.Millisecond)
defer ticker.Stop()
client := &http.Client{Timeout: 15 * time.Second}
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
request, err := http.NewRequestWithContext(ctx, http.MethodGet, config.Spec.IoTAPI.PlatformBaseURL+"/heqi/internal/v1/iot/outbox/next", nil)
if err != nil {
continue
}
request.Header.Set("X-Heqi-Iot-Token", config.Spec.IoTAPI.Token)
response, err := client.Do(request)
if err != nil {
continue
}
if response.StatusCode == http.StatusNoContent {
_ = response.Body.Close()
continue
}
if response.StatusCode != http.StatusOK {
_ = response.Body.Close()
continue
}
var outbox iotOutbox
err = json.NewDecoder(io.LimitReader(response.Body, 1<<20)).Decode(&outbox)
_ = response.Body.Close()
if err != nil {
continue
}
var payload map[string]any
if json.Unmarshal([]byte(outbox.Payload), &payload) != nil {
completeIoTOutbox(ctx, client, outbox.Identity, false, 0, "IOT_OUTBOX_PAYLOAD_INVALID")
continue
}
payload["identity"] = outbox.CommandIdentity
body, _ := json.Marshal(payload)
dispatch, err := http.NewRequestWithContext(ctx, http.MethodPost, config.Spec.IoTAPI.ClientBaseURL+"/v1/device-commands", bytes.NewReader(body))
if err != nil {
continue
}
dispatch.Header.Set("Content-Type", "application/json")
dispatch.Header.Set("X-Heqi-Iot-Token", config.Spec.IoTAPI.Token)
dispatchResponse, err := client.Do(dispatch)
if err != nil {
completeIoTOutbox(ctx, client, outbox.Identity, false, 0, "IOT_CLIENT_UNAVAILABLE")
continue
}
var result struct {
PacketNumber uint16 `json:"packet_number"`
}
decodeErr := json.NewDecoder(io.LimitReader(dispatchResponse.Body, 1<<20)).Decode(&result)
status := dispatchResponse.StatusCode
_ = dispatchResponse.Body.Close()
success := (status == http.StatusAccepted || status == http.StatusOK) && decodeErr == nil
errorCode := ""
if !success {
errorCode = "IOT_CLIENT_REJECTED"
}
completeIoTOutbox(ctx, client, outbox.Identity, success, result.PacketNumber, errorCode)
}
}
}
func completeIoTOutbox(ctx context.Context, client *http.Client, identity string, success bool, packet uint16, errorCode string) {
body, _ := json.Marshal(map[string]any{"success": success, "packet_number": packet, "error_code": errorCode})
request, err := http.NewRequestWithContext(ctx, http.MethodPost, config.Spec.IoTAPI.PlatformBaseURL+"/heqi/internal/v1/iot/outbox/"+identity+"/result", bytes.NewReader(body))
if err != nil {
return
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("X-Heqi-Iot-Token", config.Spec.IoTAPI.Token)
response, err := client.Do(request)
if err == nil {
_ = response.Body.Close()
}
}

View File

@@ -11,4 +11,9 @@ PaymentAPI:
BaseURL: http://localhost:12426
Token: change-me-payment-worker-token
IntervalSeconds: 60
IoTAPI:
PlatformBaseURL: http://127.0.0.1:12426
ClientBaseURL: http://127.0.0.1:12429
Token: change-me-iot-internal-token
IntervalMilliseconds: 500
SecretKey: change-me-to-a-random-string

View File

@@ -2,31 +2,32 @@
package config
import (
"net"
"git.apinb.com/bsm-sdk/core/conf"
"net"
)
// Spec 是 Worker 运行配置。
var Spec SrvConfig
// SrvConfig 保持与 API 进程相同的 BSM 配置结构。
type SrvConfig struct {
conf.Base `yaml:",inline"`
Databases *conf.DBConf `yaml:"Databases"`
Rpc map[string]conf.RpcConf `yaml:"Rpc"`
Apm *conf.ApmConf `yaml:"APM"`
PaymentAPI PaymentAPIConfig `yaml:"PaymentAPI"`
IoTAPI IoTAPIConfig `yaml:"IoTAPI"`
}
// PaymentAPIConfig 保存 Worker 调用支付内部动作所需的最小配置。
type PaymentAPIConfig struct {
BaseURL string `yaml:"BaseURL"`
Token string `yaml:"Token"`
IntervalSeconds int `yaml:"IntervalSeconds"`
}
type IoTAPIConfig struct {
PlatformBaseURL string `yaml:"PlatformBaseURL"`
ClientBaseURL string `yaml:"ClientBaseURL"`
Token string `yaml:"Token"`
IntervalMilliseconds int `yaml:"IntervalMilliseconds"`
}
// New 初始化 Worker 配置。
func New(srvKey string) {
conf.New(srvKey, &Spec)
Spec.Port = conf.CheckPort(Spec.Port)
@@ -36,5 +37,8 @@ func New(srvKey string) {
if Spec.PaymentAPI.BaseURL == "" || Spec.PaymentAPI.Token == "" || Spec.PaymentAPI.IntervalSeconds <= 0 {
panic("PaymentAPI configuration is required")
}
if Spec.IoTAPI.PlatformBaseURL == "" || Spec.IoTAPI.ClientBaseURL == "" || Spec.IoTAPI.Token == "" || Spec.IoTAPI.IntervalMilliseconds <= 0 {
panic("IoTAPI configuration is required")
}
conf.PrintInfo(Spec.Addr)
}