grpc_uds_test.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. package tests
  2. import (
  3. "context"
  4. "os"
  5. "path/filepath"
  6. "testing"
  7. "time"
  8. "google.golang.org/grpc/health/grpc_health_v1"
  9. "google.golang.org/protobuf/types/known/durationpb"
  10. "google.golang.org/protobuf/types/known/timestamppb"
  11. "hth/internal/app"
  12. "hth/internal/backend"
  13. "hth/internal/capture"
  14. "hth/internal/config"
  15. hthv1 "hth/internal/gen/hth/api/v1"
  16. "hth/internal/grpcserver"
  17. "hth/internal/ids"
  18. "hth/internal/profile"
  19. "hth/internal/testutil"
  20. )
  21. func startMockApp(t *testing.T) (*app.App, string, string) {
  22. t.Helper()
  23. dir := t.TempDir()
  24. obs := filepath.Join(dir, "observe.sock")
  25. ctl := filepath.Join(dir, "control.sock")
  26. prof := testutil.ProfilePath(t)
  27. yaml := `
  28. api_version: hth.api.v1
  29. device_id: prod2u-0
  30. backend: mock
  31. profile: ` + prof + `
  32. runtime_root: ` + dir + `
  33. sockets:
  34. observe: ` + obs + `
  35. control: ` + ctl + `
  36. observe_perm: "0660"
  37. control_perm: "0660"
  38. poll:
  39. temperature_ms: 50
  40. motor_status_ms: 40
  41. watchdog:
  42. heartbeat_period_ms: 80
  43. lease:
  44. min_ttl_ms: 50
  45. max_ttl_ms: 20000
  46. safety:
  47. fan: 10
  48. ptc: 0
  49. door_close_percent: 0
  50. ring_buffer_size: 32
  51. subscriber_buffer_size: 2
  52. grpc:
  53. reflection: true
  54. mock:
  55. seed: 1
  56. startup_complete: true
  57. first_order_thermal: true
  58. allow_unbound_actions: true
  59. `
  60. cfgPath := filepath.Join(dir, "hthd.yaml")
  61. if err := os.WriteFile(cfgPath, []byte(yaml), 0o644); err != nil {
  62. t.Fatal(err)
  63. }
  64. a, err := app.New(cfgPath, "", nil)
  65. if err != nil {
  66. t.Fatal(err)
  67. }
  68. ctx, cancel := context.WithCancel(context.Background())
  69. errCh := make(chan error, 1)
  70. go func() { errCh <- a.Run(ctx) }()
  71. t.Cleanup(func() {
  72. cancel()
  73. a.Stop()
  74. <-errCh
  75. })
  76. deadline := time.Now().Add(3 * time.Second)
  77. for time.Now().Before(deadline) {
  78. if _, err := os.Stat(obs); err == nil {
  79. conn, err := grpcserver.DialUnix(obs, 200*time.Millisecond)
  80. if err == nil {
  81. conn.Close()
  82. waitSlewBudget()
  83. return a, obs, ctl
  84. }
  85. }
  86. time.Sleep(20 * time.Millisecond)
  87. }
  88. t.Fatal("daemon sockets not ready")
  89. return a, obs, ctl
  90. }
  91. func TestUDSObserveAndControl(t *testing.T) {
  92. _, obs, ctl := startMockApp(t)
  93. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  94. defer cancel()
  95. oconn, err := grpcserver.DialUnix(obs, time.Second)
  96. if err != nil {
  97. t.Fatal(err)
  98. }
  99. defer oconn.Close()
  100. cconn, err := grpcserver.DialUnix(ctl, time.Second)
  101. if err != nil {
  102. t.Fatal(err)
  103. }
  104. defer cconn.Close()
  105. hc := grpc_health_v1.NewHealthClient(oconn)
  106. st, err := hc.Check(ctx, &grpc_health_v1.HealthCheckRequest{})
  107. if err != nil || st.Status != grpc_health_v1.HealthCheckResponse_SERVING {
  108. t.Fatalf("health %v %v", st, err)
  109. }
  110. obsHealth, err := hc.Check(ctx, &grpc_health_v1.HealthCheckRequest{Service: grpcserver.ObserveHealthService})
  111. if err != nil || obsHealth.Status != grpc_health_v1.HealthCheckResponse_SERVING {
  112. t.Fatalf("observe service health %v %v", obsHealth, err)
  113. }
  114. if _, err := hc.Check(ctx, &grpc_health_v1.HealthCheckRequest{Service: grpcserver.ControlHealthService}); err == nil {
  115. t.Fatal("observe socket must not advertise ControlService as serving")
  116. }
  117. ctlHealth := grpc_health_v1.NewHealthClient(cconn)
  118. cst, err := ctlHealth.Check(ctx, &grpc_health_v1.HealthCheckRequest{Service: grpcserver.ControlHealthService})
  119. if err != nil || cst.Status != grpc_health_v1.HealthCheckResponse_SERVING {
  120. t.Fatalf("control service health %v %v", cst, err)
  121. }
  122. obsCli := hthv1.NewObserveServiceClient(oconn)
  123. devs, err := obsCli.ListDevices(ctx, &hthv1.ListDevicesRequest{})
  124. if err != nil || len(devs.Devices) != 1 {
  125. t.Fatal(err, devs)
  126. }
  127. snap, err := obsCli.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"})
  128. if err != nil {
  129. t.Fatal(err)
  130. }
  131. if snap.Snapshot.SnapshotSeq == 0 {
  132. t.Fatal("seq")
  133. }
  134. ctrl := hthv1.NewControlServiceClient(cconn)
  135. lease, err := ctrl.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
  136. DeviceId: "prod2u-0", Holder: "itest", Ttl: durationpb.New(15 * time.Second),
  137. })
  138. if err != nil {
  139. t.Fatal(err)
  140. }
  141. res, err := ctrl.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: &hthv1.ActionBatch{
  142. DeviceId: "prod2u-0", CommandId: "uds-1", LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch,
  143. ClientId: "itest",
  144. ValidUntil: timestamppb.New(time.Now().Add(15 * time.Second)),
  145. AllowClamp: true,
  146. ContinuousTargets: []*hthv1.ContinuousTarget{{Id: ids.Fan1, Value: 15}},
  147. }})
  148. if err != nil {
  149. t.Fatal(err)
  150. }
  151. if !res.Accepted || res.Confirmation == hthv1.ConfirmationStatus_CONFIRMATION_STATUS_CONFIRMED {
  152. t.Fatalf("%+v", res)
  153. }
  154. }
  155. func TestSlowSubscriberDoesNotBlockControl(t *testing.T) {
  156. _, obs, ctl := startMockApp(t)
  157. ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
  158. defer cancel()
  159. oconn, err := grpcserver.DialUnix(obs, time.Second)
  160. if err != nil {
  161. t.Fatal(err)
  162. }
  163. defer oconn.Close()
  164. cconn, err := grpcserver.DialUnix(ctl, time.Second)
  165. if err != nil {
  166. t.Fatal(err)
  167. }
  168. defer cconn.Close()
  169. obsCli := hthv1.NewObserveServiceClient(oconn)
  170. st, err := obsCli.SubscribeTelemetry(ctx, &hthv1.SubscribeTelemetryRequest{DeviceId: "prod2u-0"})
  171. if err != nil {
  172. t.Fatal(err)
  173. }
  174. ctrl := hthv1.NewControlServiceClient(cconn)
  175. lease, err := ctrl.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{DeviceId: "prod2u-0", Holder: "slow", Ttl: durationpb.New(15 * time.Second)})
  176. if err != nil {
  177. t.Fatal(err)
  178. }
  179. start := time.Now()
  180. res, err := ctrl.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: &hthv1.ActionBatch{
  181. DeviceId: "prod2u-0", CommandId: "while-slow", LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch,
  182. ValidUntil: timestamppb.New(time.Now().Add(20 * time.Second)),
  183. ContinuousTargets: []*hthv1.ContinuousTarget{{Id: ids.Fan2, Value: 12}},
  184. }})
  185. if err != nil || !res.Accepted {
  186. t.Fatal(err, res)
  187. }
  188. if time.Since(start) > 500*time.Millisecond {
  189. t.Fatal("control blocked by unread telemetry stream")
  190. }
  191. _, _ = st.Recv()
  192. }
  193. func TestCaptureAndReplayRefuseSerial(t *testing.T) {
  194. _, obs, _ := startMockApp(t)
  195. dir := t.TempDir()
  196. conn, err := grpcserver.DialUnix(obs, time.Second)
  197. if err != nil {
  198. t.Fatal(err)
  199. }
  200. defer conn.Close()
  201. cli := hthv1.NewObserveServiceClient(conn)
  202. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  203. defer cancel()
  204. tel, err := cli.SubscribeTelemetry(ctx, &hthv1.SubscribeTelemetryRequest{DeviceId: "prod2u-0"})
  205. if err != nil {
  206. t.Fatal(err)
  207. }
  208. f, err := os.Create(capture.RecordsPath(dir))
  209. if err != nil {
  210. t.Fatal(err)
  211. }
  212. n := 0
  213. for n < 3 {
  214. s, err := tel.Recv()
  215. if err != nil {
  216. break
  217. }
  218. rec, err := capture.SnapshotRecord(s)
  219. if err != nil {
  220. t.Fatal(err)
  221. }
  222. if err := capture.AppendRecord(f, rec); err != nil {
  223. t.Fatal(err)
  224. }
  225. n++
  226. }
  227. f.Close()
  228. if n == 0 {
  229. t.Fatal("no records")
  230. }
  231. _ = capture.Seal(dir, capture.Manifest{
  232. APIVersion: app.APIVersion, DeviceID: "prod2u-0", StartedAt: time.Now(),
  233. Status: capture.StatusComplete, ProfileHash: "profile-test", CapabilityHash: "cap-test",
  234. })
  235. r := backend.NewReplay(dir, 1000, true, 0)
  236. if err := r.Open(context.Background()); err != nil {
  237. t.Fatal(err)
  238. }
  239. item, err := r.Next(context.Background())
  240. if err != nil || item.EventID == 0 {
  241. t.Fatal(err, item)
  242. }
  243. if err := backend.NewReplay("/dev/ttyUSB0", 1, true, 0).Open(context.Background()); err == nil {
  244. t.Fatal("replay must refuse serial")
  245. }
  246. _ = config.BackendReplay
  247. _ = profile.SchemaID
  248. }
  249. func TestEmptyApplyAndValidateDoNotCrash(t *testing.T) {
  250. _, _, ctl := startMockApp(t)
  251. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  252. defer cancel()
  253. cconn, err := grpcserver.DialUnix(ctl, time.Second)
  254. if err != nil {
  255. t.Fatal(err)
  256. }
  257. defer cconn.Close()
  258. cli := hthv1.NewControlServiceClient(cconn)
  259. res, err := cli.ApplyAction(ctx, &hthv1.ApplyActionRequest{})
  260. if err != nil {
  261. t.Fatal(err)
  262. }
  263. if res.RejectReason != hthv1.RejectReason_REJECT_REASON_INVALID_ARGUMENT {
  264. t.Fatalf("empty apply: %+v", res)
  265. }
  266. res, err = cli.ValidateAction(ctx, &hthv1.ValidateActionRequest{})
  267. if err != nil {
  268. t.Fatal(err)
  269. }
  270. if res.RejectReason != hthv1.RejectReason_REJECT_REASON_INVALID_ARGUMENT {
  271. t.Fatalf("empty validate: %+v", res)
  272. }
  273. }
  274. func TestCheckConfigExample(t *testing.T) {
  275. path := filepath.Join(testutil.HostRoot(t), "deploy", "examples", "hthd.mock.yaml")
  276. if err := app.CheckConfig(path, ""); err != nil {
  277. t.Fatal(err)
  278. }
  279. }