Files
platforms/backend/worker/cmd/main/main.go

136 lines
4.3 KiB
Go

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"
)
func main() {
config.New("PlatformWorker")
impl.NewImpl()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go closeExpiredPayments(ctx)
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()
}
}
}
}
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()
}
}