36 lines
1.2 KiB
Go
36 lines
1.2 KiB
Go
// processor.go — разбор envelope телеметрии и запись в per-tenant PostgreSQL.
|
|
package consumer
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"log/slog"
|
|
|
|
"gitea.services.ngcloud.ru/Nail/IoT/internal/service/bridge"
|
|
"gitea.services.ngcloud.ru/Nail/IoT/internal/storage/iotpg"
|
|
)
|
|
|
|
// processTelemetry десериализует envelope и пишет в tenant DB.
|
|
// Битый JSON — пропускаем (не блокируем очередь).
|
|
func processTelemetry(ctx context.Context, body string, store *iotpg.IoTPostgresStore, log *slog.Logger) error {
|
|
var envelope bridge.TelemetryEnvelope
|
|
if err := json.Unmarshal([]byte(body), &envelope); err != nil {
|
|
log.Warn("consumer: failed to unmarshal envelope, skipping", "err", err)
|
|
return nil
|
|
}
|
|
|
|
// EnsureTenantDB идемпотентен, кэшируется после первого вызова.
|
|
if err := store.EnsureTenantDB(ctx, envelope.Namespace); err != nil {
|
|
return err
|
|
}
|
|
if err := store.InsertTelemetry(ctx, envelope.Namespace, envelope.DeviceID, envelope.Payload); err != nil {
|
|
return err
|
|
}
|
|
|
|
log.Info("consumer: telemetry saved",
|
|
"namespace", envelope.Namespace,
|
|
"device", envelope.DeviceID,
|
|
)
|
|
return nil
|
|
}
|