| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287 |
- package tests
- import (
- "context"
- "os"
- "path/filepath"
- "testing"
- "time"
- "google.golang.org/grpc/health/grpc_health_v1"
- "google.golang.org/protobuf/types/known/durationpb"
- "google.golang.org/protobuf/types/known/timestamppb"
- "hth/internal/app"
- "hth/internal/backend"
- "hth/internal/capture"
- "hth/internal/config"
- hthv1 "hth/internal/gen/hth/api/v1"
- "hth/internal/grpcserver"
- "hth/internal/ids"
- "hth/internal/profile"
- "hth/internal/testutil"
- )
- func startMockApp(t *testing.T) (*app.App, string, string) {
- t.Helper()
- dir := t.TempDir()
- obs := filepath.Join(dir, "observe.sock")
- ctl := filepath.Join(dir, "control.sock")
- prof := testutil.ProfilePath(t)
- yaml := `
- api_version: hth.api.v1
- device_id: prod2u-0
- backend: mock
- profile: ` + prof + `
- runtime_root: ` + dir + `
- sockets:
- observe: ` + obs + `
- control: ` + ctl + `
- observe_perm: "0660"
- control_perm: "0660"
- poll:
- temperature_ms: 50
- motor_status_ms: 40
- watchdog:
- heartbeat_period_ms: 80
- lease:
- min_ttl_ms: 50
- max_ttl_ms: 20000
- safety:
- fan: 10
- ptc: 0
- door_close_percent: 0
- ring_buffer_size: 32
- subscriber_buffer_size: 2
- grpc:
- reflection: true
- mock:
- seed: 1
- startup_complete: true
- first_order_thermal: true
- allow_unbound_actions: true
- `
- cfgPath := filepath.Join(dir, "hthd.yaml")
- if err := os.WriteFile(cfgPath, []byte(yaml), 0o644); err != nil {
- t.Fatal(err)
- }
- a, err := app.New(cfgPath, "", nil)
- if err != nil {
- t.Fatal(err)
- }
- ctx, cancel := context.WithCancel(context.Background())
- errCh := make(chan error, 1)
- go func() { errCh <- a.Run(ctx) }()
- t.Cleanup(func() {
- cancel()
- a.Stop()
- <-errCh
- })
- deadline := time.Now().Add(3 * time.Second)
- for time.Now().Before(deadline) {
- if _, err := os.Stat(obs); err == nil {
- conn, err := grpcserver.DialUnix(obs, 200*time.Millisecond)
- if err == nil {
- conn.Close()
- waitSlewBudget()
- return a, obs, ctl
- }
- }
- time.Sleep(20 * time.Millisecond)
- }
- t.Fatal("daemon sockets not ready")
- return a, obs, ctl
- }
- func TestUDSObserveAndControl(t *testing.T) {
- _, obs, ctl := startMockApp(t)
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- oconn, err := grpcserver.DialUnix(obs, time.Second)
- if err != nil {
- t.Fatal(err)
- }
- defer oconn.Close()
- cconn, err := grpcserver.DialUnix(ctl, time.Second)
- if err != nil {
- t.Fatal(err)
- }
- defer cconn.Close()
- hc := grpc_health_v1.NewHealthClient(oconn)
- st, err := hc.Check(ctx, &grpc_health_v1.HealthCheckRequest{})
- if err != nil || st.Status != grpc_health_v1.HealthCheckResponse_SERVING {
- t.Fatalf("health %v %v", st, err)
- }
- obsHealth, err := hc.Check(ctx, &grpc_health_v1.HealthCheckRequest{Service: grpcserver.ObserveHealthService})
- if err != nil || obsHealth.Status != grpc_health_v1.HealthCheckResponse_SERVING {
- t.Fatalf("observe service health %v %v", obsHealth, err)
- }
- if _, err := hc.Check(ctx, &grpc_health_v1.HealthCheckRequest{Service: grpcserver.ControlHealthService}); err == nil {
- t.Fatal("observe socket must not advertise ControlService as serving")
- }
- ctlHealth := grpc_health_v1.NewHealthClient(cconn)
- cst, err := ctlHealth.Check(ctx, &grpc_health_v1.HealthCheckRequest{Service: grpcserver.ControlHealthService})
- if err != nil || cst.Status != grpc_health_v1.HealthCheckResponse_SERVING {
- t.Fatalf("control service health %v %v", cst, err)
- }
- obsCli := hthv1.NewObserveServiceClient(oconn)
- devs, err := obsCli.ListDevices(ctx, &hthv1.ListDevicesRequest{})
- if err != nil || len(devs.Devices) != 1 {
- t.Fatal(err, devs)
- }
- snap, err := obsCli.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"})
- if err != nil {
- t.Fatal(err)
- }
- if snap.Snapshot.SnapshotSeq == 0 {
- t.Fatal("seq")
- }
- ctrl := hthv1.NewControlServiceClient(cconn)
- lease, err := ctrl.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
- DeviceId: "prod2u-0", Holder: "itest", Ttl: durationpb.New(15 * time.Second),
- })
- if err != nil {
- t.Fatal(err)
- }
- res, err := ctrl.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: &hthv1.ActionBatch{
- DeviceId: "prod2u-0", CommandId: "uds-1", LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch,
- ClientId: "itest",
- ValidUntil: timestamppb.New(time.Now().Add(15 * time.Second)),
- AllowClamp: true,
- ContinuousTargets: []*hthv1.ContinuousTarget{{Id: ids.Fan1, Value: 15}},
- }})
- if err != nil {
- t.Fatal(err)
- }
- if !res.Accepted || res.Confirmation == hthv1.ConfirmationStatus_CONFIRMATION_STATUS_CONFIRMED {
- t.Fatalf("%+v", res)
- }
- }
- func TestSlowSubscriberDoesNotBlockControl(t *testing.T) {
- _, obs, ctl := startMockApp(t)
- ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
- defer cancel()
- oconn, err := grpcserver.DialUnix(obs, time.Second)
- if err != nil {
- t.Fatal(err)
- }
- defer oconn.Close()
- cconn, err := grpcserver.DialUnix(ctl, time.Second)
- if err != nil {
- t.Fatal(err)
- }
- defer cconn.Close()
- obsCli := hthv1.NewObserveServiceClient(oconn)
- st, err := obsCli.SubscribeTelemetry(ctx, &hthv1.SubscribeTelemetryRequest{DeviceId: "prod2u-0"})
- if err != nil {
- t.Fatal(err)
- }
- ctrl := hthv1.NewControlServiceClient(cconn)
- lease, err := ctrl.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{DeviceId: "prod2u-0", Holder: "slow", Ttl: durationpb.New(15 * time.Second)})
- if err != nil {
- t.Fatal(err)
- }
- start := time.Now()
- res, err := ctrl.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: &hthv1.ActionBatch{
- DeviceId: "prod2u-0", CommandId: "while-slow", LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch,
- ValidUntil: timestamppb.New(time.Now().Add(20 * time.Second)),
- ContinuousTargets: []*hthv1.ContinuousTarget{{Id: ids.Fan2, Value: 12}},
- }})
- if err != nil || !res.Accepted {
- t.Fatal(err, res)
- }
- if time.Since(start) > 500*time.Millisecond {
- t.Fatal("control blocked by unread telemetry stream")
- }
- _, _ = st.Recv()
- }
- func TestCaptureAndReplayRefuseSerial(t *testing.T) {
- _, obs, _ := startMockApp(t)
- dir := t.TempDir()
- conn, err := grpcserver.DialUnix(obs, time.Second)
- if err != nil {
- t.Fatal(err)
- }
- defer conn.Close()
- cli := hthv1.NewObserveServiceClient(conn)
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
- defer cancel()
- tel, err := cli.SubscribeTelemetry(ctx, &hthv1.SubscribeTelemetryRequest{DeviceId: "prod2u-0"})
- if err != nil {
- t.Fatal(err)
- }
- f, err := os.Create(capture.RecordsPath(dir))
- if err != nil {
- t.Fatal(err)
- }
- n := 0
- for n < 3 {
- s, err := tel.Recv()
- if err != nil {
- break
- }
- rec, err := capture.SnapshotRecord(s)
- if err != nil {
- t.Fatal(err)
- }
- if err := capture.AppendRecord(f, rec); err != nil {
- t.Fatal(err)
- }
- n++
- }
- f.Close()
- if n == 0 {
- t.Fatal("no records")
- }
- _ = capture.Seal(dir, capture.Manifest{
- APIVersion: app.APIVersion, DeviceID: "prod2u-0", StartedAt: time.Now(),
- Status: capture.StatusComplete, ProfileHash: "profile-test", CapabilityHash: "cap-test",
- })
- r := backend.NewReplay(dir, 1000, true, 0)
- if err := r.Open(context.Background()); err != nil {
- t.Fatal(err)
- }
- item, err := r.Next(context.Background())
- if err != nil || item.EventID == 0 {
- t.Fatal(err, item)
- }
- if err := backend.NewReplay("/dev/ttyUSB0", 1, true, 0).Open(context.Background()); err == nil {
- t.Fatal("replay must refuse serial")
- }
- _ = config.BackendReplay
- _ = profile.SchemaID
- }
- func TestEmptyApplyAndValidateDoNotCrash(t *testing.T) {
- _, _, ctl := startMockApp(t)
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- cconn, err := grpcserver.DialUnix(ctl, time.Second)
- if err != nil {
- t.Fatal(err)
- }
- defer cconn.Close()
- cli := hthv1.NewControlServiceClient(cconn)
- res, err := cli.ApplyAction(ctx, &hthv1.ApplyActionRequest{})
- if err != nil {
- t.Fatal(err)
- }
- if res.RejectReason != hthv1.RejectReason_REJECT_REASON_INVALID_ARGUMENT {
- t.Fatalf("empty apply: %+v", res)
- }
- res, err = cli.ValidateAction(ctx, &hthv1.ValidateActionRequest{})
- if err != nil {
- t.Fatal(err)
- }
- if res.RejectReason != hthv1.RejectReason_REJECT_REASON_INVALID_ARGUMENT {
- t.Fatalf("empty validate: %+v", res)
- }
- }
- func TestCheckConfigExample(t *testing.T) {
- path := filepath.Join(testutil.HostRoot(t), "deploy", "examples", "hthd.mock.yaml")
- if err := app.CheckConfig(path, ""); err != nil {
- t.Fatal(err)
- }
- }
|