@alwaysai/device-agent 1.5.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (305) hide show
  1. package/lib/application-control/config.d.ts.map +1 -1
  2. package/lib/application-control/config.js +8 -3
  3. package/lib/application-control/config.js.map +1 -1
  4. package/lib/application-control/environment-variables.d.ts +5 -5
  5. package/lib/application-control/environment-variables.d.ts.map +1 -1
  6. package/lib/application-control/environment-variables.js +25 -38
  7. package/lib/application-control/environment-variables.js.map +1 -1
  8. package/lib/application-control/environment-variables.test.js +27 -7
  9. package/lib/application-control/environment-variables.test.js.map +1 -1
  10. package/lib/application-control/index.d.ts +4 -4
  11. package/lib/application-control/index.d.ts.map +1 -1
  12. package/lib/application-control/index.js +1 -4
  13. package/lib/application-control/index.js.map +1 -1
  14. package/lib/application-control/install.d.ts +4 -1
  15. package/lib/application-control/install.d.ts.map +1 -1
  16. package/lib/application-control/install.js +24 -8
  17. package/lib/application-control/install.js.map +1 -1
  18. package/lib/application-control/models.d.ts +0 -11
  19. package/lib/application-control/models.d.ts.map +1 -1
  20. package/lib/application-control/models.js +5 -54
  21. package/lib/application-control/models.js.map +1 -1
  22. package/lib/application-control/utils.d.ts +0 -4
  23. package/lib/application-control/utils.d.ts.map +1 -1
  24. package/lib/application-control/utils.js +12 -22
  25. package/lib/application-control/utils.js.map +1 -1
  26. package/lib/cloud-connection/base-message-handler.d.ts +27 -0
  27. package/lib/cloud-connection/base-message-handler.d.ts.map +1 -0
  28. package/lib/cloud-connection/base-message-handler.js +72 -0
  29. package/lib/cloud-connection/base-message-handler.js.map +1 -0
  30. package/lib/cloud-connection/bootstrap-provision.js +3 -2
  31. package/lib/cloud-connection/bootstrap-provision.js.map +1 -1
  32. package/lib/cloud-connection/connection-manager.d.ts +21 -0
  33. package/lib/cloud-connection/connection-manager.d.ts.map +1 -0
  34. package/lib/cloud-connection/connection-manager.js +158 -0
  35. package/lib/cloud-connection/connection-manager.js.map +1 -0
  36. package/lib/cloud-connection/device-agent-cloud-connection.d.ts +9 -30
  37. package/lib/cloud-connection/device-agent-cloud-connection.d.ts.map +1 -1
  38. package/lib/cloud-connection/device-agent-cloud-connection.js +69 -508
  39. package/lib/cloud-connection/device-agent-cloud-connection.js.map +1 -1
  40. package/lib/cloud-connection/device-agent-message-handler.d.ts +22 -0
  41. package/lib/cloud-connection/device-agent-message-handler.d.ts.map +1 -0
  42. package/lib/cloud-connection/device-agent-message-handler.js +357 -0
  43. package/lib/cloud-connection/device-agent-message-handler.js.map +1 -0
  44. package/lib/cloud-connection/device-agent.d.ts.map +1 -1
  45. package/lib/cloud-connection/device-agent.js +11 -9
  46. package/lib/cloud-connection/device-agent.js.map +1 -1
  47. package/lib/cloud-connection/live-updates-handler.d.ts +19 -28
  48. package/lib/cloud-connection/live-updates-handler.d.ts.map +1 -1
  49. package/lib/cloud-connection/live-updates-handler.js +60 -172
  50. package/lib/cloud-connection/live-updates-handler.js.map +1 -1
  51. package/lib/cloud-connection/live-updates-handler.test.js +71 -165
  52. package/lib/cloud-connection/live-updates-handler.test.js.map +1 -1
  53. package/lib/cloud-connection/message-dispatcher.d.ts +10 -0
  54. package/lib/cloud-connection/message-dispatcher.d.ts.map +1 -0
  55. package/lib/cloud-connection/message-dispatcher.js +27 -0
  56. package/lib/cloud-connection/message-dispatcher.js.map +1 -0
  57. package/lib/cloud-connection/passthrough-handler.d.ts +4 -1
  58. package/lib/cloud-connection/passthrough-handler.d.ts.map +1 -1
  59. package/lib/cloud-connection/passthrough-handler.js +30 -11
  60. package/lib/cloud-connection/passthrough-handler.js.map +1 -1
  61. package/lib/cloud-connection/shadow-handler.d.ts +11 -3
  62. package/lib/cloud-connection/shadow-handler.d.ts.map +1 -1
  63. package/lib/cloud-connection/shadow-handler.js +133 -28
  64. package/lib/cloud-connection/shadow-handler.js.map +1 -1
  65. package/lib/cloud-connection/shadow-handler.test.js +45 -57
  66. package/lib/cloud-connection/shadow-handler.test.js.map +1 -1
  67. package/lib/cloud-connection/shadow.d.ts.map +1 -1
  68. package/lib/cloud-connection/shadow.js +2 -1
  69. package/lib/cloud-connection/shadow.js.map +1 -1
  70. package/lib/cloud-connection/transaction-manager.d.ts +12 -3
  71. package/lib/cloud-connection/transaction-manager.d.ts.map +1 -1
  72. package/lib/cloud-connection/transaction-manager.js +29 -28
  73. package/lib/cloud-connection/transaction-manager.js.map +1 -1
  74. package/lib/cloud-connection/transaction-manager.test.js +46 -5
  75. package/lib/cloud-connection/transaction-manager.test.js.map +1 -1
  76. package/lib/device-control/device-control.d.ts +8 -8
  77. package/lib/device-control/device-control.d.ts.map +1 -1
  78. package/lib/device-control/device-control.js +95 -71
  79. package/lib/device-control/device-control.js.map +1 -1
  80. package/lib/docker/docker-compose.d.ts.map +1 -1
  81. package/lib/docker/docker-compose.js +2 -1
  82. package/lib/docker/docker-compose.js.map +1 -1
  83. package/lib/infrastructure/agent-config.d.ts +2 -1
  84. package/lib/infrastructure/agent-config.d.ts.map +1 -1
  85. package/lib/infrastructure/agent-config.js +7 -7
  86. package/lib/infrastructure/agent-config.js.map +1 -1
  87. package/lib/infrastructure/agent-config.test.js +3 -1
  88. package/lib/infrastructure/agent-config.test.js.map +1 -1
  89. package/lib/infrastructure/config-check-utility.d.ts +6 -0
  90. package/lib/infrastructure/config-check-utility.d.ts.map +1 -0
  91. package/lib/infrastructure/config-check-utility.js +67 -0
  92. package/lib/infrastructure/config-check-utility.js.map +1 -0
  93. package/lib/infrastructure/config-check-utility.test.d.ts +2 -0
  94. package/lib/infrastructure/config-check-utility.test.d.ts.map +1 -0
  95. package/lib/infrastructure/config-check-utility.test.js +109 -0
  96. package/lib/infrastructure/config-check-utility.test.js.map +1 -0
  97. package/lib/infrastructure/device-certificate.d.ts +10 -0
  98. package/lib/infrastructure/device-certificate.d.ts.map +1 -0
  99. package/lib/infrastructure/device-certificate.js +47 -0
  100. package/lib/infrastructure/device-certificate.js.map +1 -0
  101. package/lib/infrastructure/device-certificate.test.d.ts +2 -0
  102. package/lib/infrastructure/device-certificate.test.d.ts.map +1 -0
  103. package/lib/infrastructure/device-certificate.test.js +24 -0
  104. package/lib/infrastructure/device-certificate.test.js.map +1 -0
  105. package/lib/infrastructure/legacy-migration/legacy-file.test.d.ts +2 -0
  106. package/lib/infrastructure/legacy-migration/legacy-file.test.d.ts.map +1 -0
  107. package/lib/infrastructure/legacy-migration/legacy-file.test.js +61 -0
  108. package/lib/infrastructure/legacy-migration/legacy-file.test.js.map +1 -0
  109. package/lib/infrastructure/legacy-migration/legacy-files.d.ts +75 -0
  110. package/lib/infrastructure/legacy-migration/legacy-files.d.ts.map +1 -0
  111. package/lib/infrastructure/legacy-migration/legacy-files.js +75 -0
  112. package/lib/infrastructure/legacy-migration/legacy-files.js.map +1 -0
  113. package/lib/infrastructure/legacy-migration/legacy-migration.d.ts +6 -0
  114. package/lib/infrastructure/legacy-migration/legacy-migration.d.ts.map +1 -0
  115. package/lib/infrastructure/legacy-migration/legacy-migration.js +149 -0
  116. package/lib/infrastructure/legacy-migration/legacy-migration.js.map +1 -0
  117. package/lib/infrastructure/legacy-migration/legacy-migration.test.d.ts +2 -0
  118. package/lib/infrastructure/legacy-migration/legacy-migration.test.d.ts.map +1 -0
  119. package/lib/infrastructure/legacy-migration/legacy-migration.test.js +226 -0
  120. package/lib/infrastructure/legacy-migration/legacy-migration.test.js.map +1 -0
  121. package/lib/infrastructure/require-files-present-ready.test.d.ts +2 -0
  122. package/lib/infrastructure/require-files-present-ready.test.d.ts.map +1 -0
  123. package/lib/infrastructure/require-files-present-ready.test.js +44 -0
  124. package/lib/infrastructure/require-files-present-ready.test.js.map +1 -0
  125. package/lib/infrastructure/required-config-checks.d.ts +2 -0
  126. package/lib/infrastructure/required-config-checks.d.ts.map +1 -0
  127. package/lib/infrastructure/required-config-checks.js +30 -0
  128. package/lib/infrastructure/required-config-checks.js.map +1 -0
  129. package/lib/infrastructure/tokens-and-device-cfg.d.ts.map +1 -1
  130. package/lib/infrastructure/tokens-and-device-cfg.js +11 -8
  131. package/lib/infrastructure/tokens-and-device-cfg.js.map +1 -1
  132. package/lib/jobs/job-handler.d.ts +23 -0
  133. package/lib/jobs/job-handler.d.ts.map +1 -0
  134. package/lib/jobs/job-handler.js +131 -0
  135. package/lib/jobs/job-handler.js.map +1 -0
  136. package/lib/local-connection/rabbitmq-connection.d.ts.map +1 -1
  137. package/lib/local-connection/rabbitmq-connection.js +14 -14
  138. package/lib/local-connection/rabbitmq-connection.js.map +1 -1
  139. package/lib/secure-tunneling/secure-tunnel-message-handler.d.ts +8 -0
  140. package/lib/secure-tunneling/secure-tunnel-message-handler.d.ts.map +1 -0
  141. package/lib/secure-tunneling/secure-tunnel-message-handler.js +42 -0
  142. package/lib/secure-tunneling/secure-tunnel-message-handler.js.map +1 -0
  143. package/lib/secure-tunneling/secure-tunneling.d.ts +9 -9
  144. package/lib/secure-tunneling/secure-tunneling.d.ts.map +1 -1
  145. package/lib/secure-tunneling/secure-tunneling.js +21 -16
  146. package/lib/secure-tunneling/secure-tunneling.js.map +1 -1
  147. package/lib/secure-tunneling/secure-tunneling.test.js +11 -13
  148. package/lib/secure-tunneling/secure-tunneling.test.js.map +1 -1
  149. package/lib/subcommands/app/analytics.d.ts.map +1 -1
  150. package/lib/subcommands/app/analytics.js +1 -2
  151. package/lib/subcommands/app/analytics.js.map +1 -1
  152. package/lib/subcommands/app/env-vars.d.ts +4 -0
  153. package/lib/subcommands/app/env-vars.d.ts.map +1 -1
  154. package/lib/subcommands/app/env-vars.js +52 -6
  155. package/lib/subcommands/app/env-vars.js.map +1 -1
  156. package/lib/subcommands/app/index.d.ts.map +1 -1
  157. package/lib/subcommands/app/index.js +1 -3
  158. package/lib/subcommands/app/index.js.map +1 -1
  159. package/lib/subcommands/app/models.d.ts +0 -11
  160. package/lib/subcommands/app/models.d.ts.map +1 -1
  161. package/lib/subcommands/app/models.js +2 -58
  162. package/lib/subcommands/app/models.js.map +1 -1
  163. package/lib/subcommands/app/shadow.d.ts.map +1 -1
  164. package/lib/subcommands/app/shadow.js +6 -5
  165. package/lib/subcommands/app/shadow.js.map +1 -1
  166. package/lib/subcommands/app/version.d.ts +2 -0
  167. package/lib/subcommands/app/version.d.ts.map +1 -1
  168. package/lib/subcommands/app/version.js +16 -6
  169. package/lib/subcommands/app/version.js.map +1 -1
  170. package/lib/subcommands/config.d.ts +2 -0
  171. package/lib/subcommands/config.d.ts.map +1 -0
  172. package/lib/subcommands/config.js +39 -0
  173. package/lib/subcommands/config.js.map +1 -0
  174. package/lib/subcommands/device/clean.d.ts +1 -1
  175. package/lib/subcommands/device/clean.d.ts.map +1 -1
  176. package/lib/subcommands/device/clean.js +23 -13
  177. package/lib/subcommands/device/clean.js.map +1 -1
  178. package/lib/subcommands/device/index.d.ts.map +1 -1
  179. package/lib/subcommands/device/index.js +3 -1
  180. package/lib/subcommands/device/index.js.map +1 -1
  181. package/lib/subcommands/device/init.js +8 -8
  182. package/lib/subcommands/device/init.js.map +1 -1
  183. package/lib/subcommands/device/migrate.d.ts +2 -0
  184. package/lib/subcommands/device/migrate.d.ts.map +1 -0
  185. package/lib/subcommands/device/migrate.js +24 -0
  186. package/lib/subcommands/device/migrate.js.map +1 -0
  187. package/lib/subcommands/device/refresh.d.ts.map +1 -1
  188. package/lib/subcommands/device/refresh.js +1 -0
  189. package/lib/subcommands/device/refresh.js.map +1 -1
  190. package/lib/subcommands/index.d.ts +1 -1
  191. package/lib/subcommands/index.d.ts.map +1 -1
  192. package/lib/subcommands/index.js +3 -1
  193. package/lib/subcommands/index.js.map +1 -1
  194. package/lib/subcommands/rabbitmq-connection.d.ts +1 -1
  195. package/lib/subcommands/rabbitmq-connection.d.ts.map +1 -1
  196. package/lib/util/aai-error.d.ts +12 -0
  197. package/lib/util/aai-error.d.ts.map +1 -0
  198. package/lib/util/aai-error.js +11 -0
  199. package/lib/util/aai-error.js.map +1 -0
  200. package/lib/util/aws-regions.d.ts +2 -0
  201. package/lib/util/aws-regions.d.ts.map +1 -0
  202. package/lib/util/{cloud-mode-ready.js → aws-regions.js} +2 -20
  203. package/lib/util/aws-regions.js.map +1 -0
  204. package/lib/util/check-for-updates.d.ts.map +1 -1
  205. package/lib/util/check-for-updates.js +5 -28
  206. package/lib/util/check-for-updates.js.map +1 -1
  207. package/lib/util/clean-certs.d.ts.map +1 -1
  208. package/lib/util/clean-certs.js +5 -4
  209. package/lib/util/clean-certs.js.map +1 -1
  210. package/lib/util/directories.d.ts +4 -18
  211. package/lib/util/directories.d.ts.map +1 -1
  212. package/lib/util/directories.js +18 -32
  213. package/lib/util/directories.js.map +1 -1
  214. package/lib/util/file.d.ts +4 -0
  215. package/lib/util/file.d.ts.map +1 -1
  216. package/lib/util/file.js +65 -4
  217. package/lib/util/file.js.map +1 -1
  218. package/lib/util/get-device-id.d.ts.map +1 -1
  219. package/lib/util/get-device-id.js +7 -1
  220. package/lib/util/get-device-id.js.map +1 -1
  221. package/lib/util/http-client.js +3 -3
  222. package/lib/util/http-client.js.map +1 -1
  223. package/package.json +19 -17
  224. package/readme.md +12 -32
  225. package/src/application-control/config.ts +9 -12
  226. package/src/application-control/environment-variables.test.ts +28 -7
  227. package/src/application-control/environment-variables.ts +42 -59
  228. package/src/application-control/index.ts +3 -16
  229. package/src/application-control/install.ts +39 -13
  230. package/src/application-control/models.ts +6 -87
  231. package/src/application-control/utils.ts +10 -25
  232. package/src/cloud-connection/base-message-handler.ts +118 -0
  233. package/src/cloud-connection/bootstrap-provision.ts +7 -7
  234. package/src/cloud-connection/connection-manager.ts +187 -0
  235. package/src/cloud-connection/device-agent-cloud-connection.ts +130 -723
  236. package/src/cloud-connection/device-agent-message-handler.ts +642 -0
  237. package/src/cloud-connection/device-agent.ts +16 -7
  238. package/src/cloud-connection/live-updates-handler.test.ts +121 -189
  239. package/src/cloud-connection/live-updates-handler.ts +105 -232
  240. package/src/cloud-connection/message-dispatcher.ts +33 -0
  241. package/src/cloud-connection/passthrough-handler.ts +55 -18
  242. package/src/cloud-connection/shadow-handler.test.ts +45 -57
  243. package/src/cloud-connection/shadow-handler.ts +224 -54
  244. package/src/cloud-connection/shadow.ts +4 -1
  245. package/src/cloud-connection/transaction-manager.test.ts +68 -6
  246. package/src/cloud-connection/transaction-manager.ts +69 -41
  247. package/src/device-control/device-control.ts +102 -70
  248. package/src/docker/docker-compose.ts +3 -2
  249. package/src/infrastructure/agent-config.test.ts +6 -2
  250. package/src/infrastructure/agent-config.ts +8 -7
  251. package/src/infrastructure/config-check-utility.test.ts +154 -0
  252. package/src/infrastructure/config-check-utility.ts +77 -0
  253. package/src/infrastructure/device-certificate.test.ts +40 -0
  254. package/src/infrastructure/device-certificate.ts +58 -0
  255. package/src/infrastructure/legacy-migration/legacy-file.test.ts +88 -0
  256. package/src/infrastructure/legacy-migration/legacy-files.ts +101 -0
  257. package/src/infrastructure/legacy-migration/legacy-migration.test.ts +396 -0
  258. package/src/infrastructure/legacy-migration/legacy-migration.ts +229 -0
  259. package/src/infrastructure/require-files-present-ready.test.ts +53 -0
  260. package/src/infrastructure/required-config-checks.ts +33 -0
  261. package/src/infrastructure/tokens-and-device-cfg.ts +12 -10
  262. package/src/jobs/job-handler.ts +146 -0
  263. package/src/local-connection/rabbitmq-connection.ts +22 -17
  264. package/src/secure-tunneling/secure-tunnel-message-handler.ts +56 -0
  265. package/src/secure-tunneling/secure-tunneling.test.ts +20 -22
  266. package/src/secure-tunneling/secure-tunneling.ts +41 -29
  267. package/src/subcommands/app/analytics.ts +2 -4
  268. package/src/subcommands/app/env-vars.ts +72 -9
  269. package/src/subcommands/app/index.ts +3 -11
  270. package/src/subcommands/app/models.ts +5 -81
  271. package/src/subcommands/app/shadow.ts +6 -5
  272. package/src/subcommands/app/version.ts +23 -6
  273. package/src/subcommands/config.ts +42 -0
  274. package/src/subcommands/device/clean.ts +31 -17
  275. package/src/subcommands/device/index.ts +3 -1
  276. package/src/subcommands/device/init.ts +11 -11
  277. package/src/subcommands/device/migrate.ts +20 -0
  278. package/src/subcommands/device/refresh.ts +1 -0
  279. package/src/subcommands/index.ts +3 -1
  280. package/src/util/aai-error.ts +20 -0
  281. package/src/util/{cloud-mode-ready.ts → aws-regions.ts} +0 -24
  282. package/src/util/check-for-updates.ts +14 -30
  283. package/src/util/clean-certs.ts +8 -4
  284. package/src/util/directories.ts +23 -67
  285. package/src/util/file.ts +83 -3
  286. package/src/util/get-device-id.ts +7 -7
  287. package/src/util/http-client.ts +2 -2
  288. package/lib/util/cloud-mode-ready.d.ts +0 -3
  289. package/lib/util/cloud-mode-ready.d.ts.map +0 -1
  290. package/lib/util/cloud-mode-ready.js.map +0 -1
  291. package/lib/util/download-file.d.ts +0 -6
  292. package/lib/util/download-file.d.ts.map +0 -1
  293. package/lib/util/download-file.js +0 -25
  294. package/lib/util/download-file.js.map +0 -1
  295. package/lib/util/fetch-with-timeout.d.ts +0 -4
  296. package/lib/util/fetch-with-timeout.d.ts.map +0 -1
  297. package/lib/util/fetch-with-timeout.js +0 -30
  298. package/lib/util/fetch-with-timeout.js.map +0 -1
  299. package/lib/util/parsing.d.ts +0 -2
  300. package/lib/util/parsing.d.ts.map +0 -1
  301. package/lib/util/parsing.js +0 -17
  302. package/lib/util/parsing.js.map +0 -1
  303. package/src/util/download-file.ts +0 -25
  304. package/src/util/fetch-with-timeout.ts +0 -35
  305. package/src/util/parsing.ts +0 -11
@@ -1,19 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.runDeviceAgentCloudInterface = exports.DeviceAgentCloudConnection = void 0;
4
- // eslint-disable-next-line
5
- const awsIot = require('aws-iot-device-sdk');
6
4
  const device_agent_schemas_1 = require("@alwaysai/device-agent-schemas");
7
5
  const fs_1 = require("fs");
8
- const application_control_1 = require("../application-control");
9
- const backup_1 = require("../application-control/backup");
10
- const device_control_1 = require("../device-control/device-control");
11
6
  const environment_1 = require("../environment");
12
- const agent_config_1 = require("../infrastructure/agent-config");
7
+ const device_certificate_1 = require("../infrastructure/device-certificate");
8
+ const legacy_migration_1 = require("../infrastructure/legacy-migration/legacy-migration");
9
+ const required_config_checks_1 = require("../infrastructure/required-config-checks");
13
10
  const urls_1 = require("../infrastructure/urls");
14
11
  const secure_tunneling_1 = require("../secure-tunneling/secure-tunneling");
15
- const cloud_mode_ready_1 = require("../util/cloud-mode-ready");
16
- const directories_1 = require("../util/directories");
12
+ const secure_tunnel_message_handler_1 = require("../secure-tunneling/secure-tunnel-message-handler");
13
+ const check_for_updates_1 = require("../util/check-for-updates");
17
14
  const get_device_id_1 = require("../util/get-device-id");
18
15
  const logger_1 = require("../util/logger");
19
16
  const sleep_1 = require("../util/sleep");
@@ -22,538 +19,102 @@ const live_updates_handler_1 = require("./live-updates-handler");
22
19
  const passthrough_handler_1 = require("./passthrough-handler");
23
20
  const publisher_1 = require("./publisher");
24
21
  const shadow_handler_1 = require("./shadow-handler");
22
+ const job_handler_1 = require("../jobs/job-handler");
25
23
  const transaction_manager_1 = require("./transaction-manager");
26
- const child_process_1 = require("child_process");
27
- const util_1 = require("util");
28
- const models_1 = require("../application-control/models");
29
- const check_for_updates_1 = require("../util/check-for-updates");
30
- const exec_promise = (0, util_1.promisify)(child_process_1.exec);
24
+ const connection_manager_1 = require("./connection-manager");
25
+ const device_agent_message_handler_1 = require("./device-agent-message-handler");
31
26
  class DeviceAgentCloudConnection {
32
- /*=================================================================
33
- Public interface
34
- =================================================================*/
35
27
  constructor() {
36
- this.device = awsIot.device;
37
28
  this.clientId = (0, get_device_id_1.getDeviceUuid)();
38
29
  this.host = (0, urls_1.getIoTCoreEndpointUrl)();
39
30
  this.port = 8883;
40
31
  this.toDeviceTopic = (0, device_agent_schemas_1.getToDeviceTopic)(this.clientId);
41
- this.secureTunnelNotifyTopic = `$aws/things/${this.clientId}/tunnels/notify`;
42
32
  this.secureTunnelHandler = secure_tunneling_1.SecureTunnelHandlerSingleton.getInstance();
43
- this.handleAppStateControl = async (payload) => {
44
- const { baseCommand, projectId } = payload;
45
- switch (baseCommand) {
46
- case device_agent_schemas_1.keyMirrors.appStateControl.start:
47
- await (0, application_control_1.startApp)({ projectId });
48
- break;
49
- case device_agent_schemas_1.keyMirrors.appStateControl.stop:
50
- await (0, application_control_1.stopApp)({ projectId });
51
- break;
52
- case device_agent_schemas_1.keyMirrors.appStateControl.restart:
53
- await (0, application_control_1.restartApp)({ projectId });
54
- break;
55
- }
56
- return true;
57
- };
58
- this.handleAppVersionControl = async (payload, txId) => {
59
- switch (payload.baseCommand) {
60
- case device_agent_schemas_1.keyMirrors.appVersionControl.install: {
61
- const { projectId, appReleaseHash } = payload;
62
- const signedUrlsRequestPayload = {
63
- signedUrlsRequest: {
64
- projectId,
65
- appReleaseHash
66
- }
67
- };
68
- const message = (0, device_agent_schemas_1.buildSignedUrlsRequestMessage)(this.clientId, signedUrlsRequestPayload, txId);
69
- await this.publishCloudRequest(message);
70
- return false;
71
- }
72
- case device_agent_schemas_1.keyMirrors.appVersionControl.uninstall: {
73
- const { projectId } = payload;
74
- await this.atomicApplicationUninstall(projectId);
75
- return true;
76
- }
77
- default:
78
- logger_1.logger.warn(`Ignore App Version Control packet: ${JSON.stringify(payload, null, 2)}`);
79
- return true;
80
- }
81
- };
82
- this.handleAppInstallCloudResponsePayload = async (payload) => {
83
- const { projectId, appReleaseHash, appInstallPayload, modelsInstallPayload } = payload.appInstallResponse;
84
- const signedUrlsPayload = {
85
- appInstallPayload,
86
- modelsInstallPayload
87
- };
88
- await this.atomicApplicationUpdate(async () => {
89
- this.shadowHandler.clearProjectShadow(projectId);
90
- await (0, application_control_1.installApp)({ projectId, appReleaseHash, signedUrlsPayload });
91
- }, projectId);
92
- return true;
93
- };
94
- this.handleModelsInstallCloudResponsePayload = async (payload, txId) => {
95
- const projectId = payload.modelsInstallResponse.projectId;
96
- const update = this.txnMgr.getAppCfgUpdateFromTxID(txId);
97
- if (update === undefined) {
98
- throw new Error('Unknown error while updating models via application config! No config present for model update.');
99
- }
100
- const { appCfgUpdate, envVarUpdate } = update;
101
- if (appCfgUpdate) {
102
- await this.atomicApplicationUpdate(async () => await (0, application_control_1.updateModelsWithPresignedUrls)({
103
- projectId,
104
- modelInstallPayloads: payload.modelsInstallResponse.newModels,
105
- newAppCfg: appCfgUpdate.newAppCfg
106
- }), projectId);
107
- }
108
- if (envVarUpdate) {
109
- await this.atomicApplicationUpdate(async () => await this.shadowHandler.updateProjectEnvVars({
110
- projectId,
111
- envVars: envVarUpdate.envVars
112
- }), projectId, true);
113
- }
114
- return true;
115
- };
116
- this.handleProjectShadowConfigUpdate = async (update, txId) => {
117
- const { projectId, appCfgUpdate, envVarUpdate } = update;
118
- if ((appCfgUpdate === null || appCfgUpdate === void 0 ? void 0 : appCfgUpdate.updatedModels) &&
119
- Object.keys(appCfgUpdate.updatedModels).length) {
120
- // When there are model updates request signed URLs and wait to apply config changes
121
- const { updatedModels } = appCfgUpdate;
122
- logger_1.logger.debug(`Requesting presigned urls from cloud for model versions: ${JSON.stringify(updatedModels)}`);
123
- const modelsOnlyUrlsRequestPayload = {
124
- modelsOnlyUrlsRequest: {
125
- projectId,
126
- models: updatedModels
127
- }
128
- };
129
- const message = (0, device_agent_schemas_1.buildSignedUrlsRequestMessage)(this.clientId, modelsOnlyUrlsRequestPayload, txId);
130
- this.publisher.publishToCloud(message);
131
- this.txnMgr.setAppCfgUpdateToTx(txId, update);
132
- return false;
133
- }
134
- if (appCfgUpdate) {
135
- await this.atomicApplicationUpdate(async () => {
136
- await (0, models_1.pruneModels)({
137
- projectId,
138
- appCfg: appCfgUpdate.newAppCfg
139
- });
140
- await (0, application_control_1.updateAppCfg)({
141
- projectId,
142
- newAppCfg: appCfgUpdate.newAppCfg
143
- });
144
- }, projectId);
145
- }
146
- if (envVarUpdate) {
147
- await this.atomicApplicationUpdate(async () => await this.shadowHandler.updateProjectEnvVars({
148
- projectId,
149
- envVars: envVarUpdate.envVars
150
- }), projectId, true);
151
- }
152
- return true;
153
- };
154
- this.device = awsIot.device({
155
- keyPath: directories_1.DEVICE_PRIVATE_KEY_FILE_PATH,
156
- certPath: directories_1.DEVICE_CERTIFICATE_FILE_PATH,
157
- caPath: directories_1.AWS_ROOT_CERTIFICATE_FILE_PATH,
158
- clientId: this.clientId,
159
- host: this.host,
160
- port: this.port,
161
- keepalive: 1 // time before re-connect attempt on dropped connection, default is 400 seconds
162
- });
163
- this.publisher = new publisher_1.Publisher(this.device, this.clientId);
33
+ this.liveUpdatesHandler = new live_updates_handler_1.LiveUpdatesHandler();
34
+ // Initialize & setup the connection
35
+ this.connectionManager = new connection_manager_1.ConnectionManager(this.clientId, this.host, this.port);
36
+ this.connectionManager.setupConnection();
37
+ // Initialize the Publisher, ShadowHandler & Transaction Manager
38
+ this.publisher = new publisher_1.Publisher(this.connectionManager.getIoTDevice(), this.clientId);
164
39
  this.shadowHandler = new shadow_handler_1.ShadowHandler(this.clientId, this.publisher);
165
- this.liveUpdatesHandler = new live_updates_handler_1.LiveUpdatesHandler(this.publisher, this.clientId);
166
- this.txnMgr = new transaction_manager_1.TransactionManager(this.publisher, this.liveUpdatesHandler);
167
- this.subscribe(this.toDeviceTopic);
168
- this.subscribe(this.secureTunnelNotifyTopic);
169
- for (const topic of this.shadowHandler.projectShadowTopics) {
170
- this.subscribe(topic);
171
- }
172
- this.subscribe(this.shadowHandler.shadowTopics.secureTunnel.updateDelta);
173
- this.subscribe(this.shadowHandler.shadowTopics.secureTunnel.deleteAccepted);
174
- }
175
- async handleDeviceAction(payload) {
176
- const { system_restart } = device_agent_schemas_1.keyMirrors.deviceAction;
177
- switch (payload.action) {
178
- case system_restart: {
179
- await (0, device_control_1.reboot)();
180
- break;
181
- }
182
- default: {
183
- logger_1.logger.info(`Unrecognized device action requested: '${payload.action}'.`);
184
- }
185
- }
186
- }
187
- async publishCloudRequest(message) {
188
- this.publisher.publishToCloud(message);
189
- }
190
- subscribe(topic) {
191
- logger_1.logger.info(`Subscribing to ${topic}`);
192
- this.device.subscribe(topic);
193
- }
194
- async atomicApplicationUninstall(projectId) {
195
- try {
196
- await (0, application_control_1.uninstallApp)({ projectId });
197
- this.shadowHandler.clearProjectShadow(projectId);
198
- }
199
- catch (e) {
200
- logger_1.logger.error(`Failed to uninstall ${projectId}: ${e.message}`);
201
- throw e;
202
- }
203
- }
204
- // eslint-disable-next-line
205
- async atomicApplicationUpdate(func, projectId, skipUpdateShadow) {
206
- // First try to create a backup, so that there is one available if something goes wrong in the next try:catch.
207
- if (await (0, agent_config_1.AgentConfigFile)().isAppPresent({ projectId })) {
208
- try {
209
- await (0, backup_1.createAppBackup)({ projectId });
210
- }
211
- catch (e) {
212
- logger_1.logger.error(`Could not create a backup for the project: ${projectId}:\n${e.message}\n${e.stack}`);
213
- }
214
- }
215
- try {
216
- const out = await func();
217
- if (!skipUpdateShadow)
218
- await this.shadowHandler.updateProjectShadow(projectId);
219
- return out;
220
- }
221
- catch (errorAppUpdate) {
222
- logger_1.logger.error(`Failed to update ${projectId}:\n${JSON.stringify(errorAppUpdate)}}`);
223
- // If something goes wrong, first try to rollback
224
- try {
225
- await (0, backup_1.rollbackApp)({ projectId });
226
- logger_1.logger.error(`Application update failed, rolled back to previous version: ${errorAppUpdate}`);
227
- }
228
- catch (errorRollbackApp) {
229
- // and if that fails, uninstall the app as a last resort.
230
- try {
231
- await this.atomicApplicationUninstall(projectId);
232
- }
233
- catch (_a) {
234
- // atomicApplicationUninstall handles failing, so there's nothing to handle here.
235
- }
236
- logger_1.logger.error(`Application update failed, rolled back to previous version: ${errorAppUpdate}`);
237
- throw new Error(`Application update and rollback failed, uninstalled the application: ${errorAppUpdate}`);
238
- }
239
- throw new Error(`Application update failed, rolled the application back: ${errorAppUpdate}`);
240
- }
241
- }
242
- async handleProjectShadowMessage(topic, message) {
243
- const shadowUpdates = await this.shadowHandler.handleProjectShadow({
244
- topic,
245
- payload: message,
246
- clientToken: message.clientToken
40
+ this.transactionManager = new transaction_manager_1.TransactionManager(this.publisher, this.liveUpdatesHandler);
41
+ // Construct a HandlerContext used by all the message handlers
42
+ const handlerContext = {
43
+ clientId: this.clientId,
44
+ txnMgr: this.transactionManager,
45
+ publisher: this.publisher,
46
+ shadowHandler: this.shadowHandler,
47
+ liveUpdatesHandler: this.liveUpdatesHandler,
48
+ secureTunnelHandler: this.secureTunnelHandler
49
+ };
50
+ // Instantiate & register message handlers for Project Shadow topics
51
+ const projectShadowMessageHandler = new shadow_handler_1.ProjectShadowMessageHandler(handlerContext);
52
+ this.shadowHandler.projectShadowTopics.forEach((topic) => {
53
+ this.connectionManager.registerHandler(topic, projectShadowMessageHandler);
247
54
  });
248
- if (shadowUpdates.length) {
249
- const shadowUpdatePromises = [];
250
- for (const shadowUpdate of shadowUpdates) {
251
- const projectId = shadowUpdate.projectId;
252
- const txId = shadowUpdate.txId;
253
- shadowUpdatePromises.push(this.txnMgr
254
- .runTransactionStep({
255
- func: () => this.handleProjectShadowConfigUpdate(shadowUpdate, txId),
256
- projectId,
257
- txId,
258
- start: true,
259
- stepName: topic
260
- })
261
- .catch((e) => {
262
- logger_1.logger.error(`There was an issue updating project shadow config: ${JSON.stringify(e)}`);
263
- }));
264
- }
265
- await Promise.all(shadowUpdatePromises);
266
- }
267
- }
268
- async handleSecureTunnelMessage(payload) {
269
- logger_1.logger.info(`Received secure tunnel update: ${JSON.stringify(payload)}`);
270
- const state = payload.state;
271
- if (!state) {
272
- logger_1.logger.debug(`No state found in message: ${JSON.stringify(payload)}`);
273
- return;
274
- }
275
- const valid = (0, device_agent_schemas_1.validateSecureTunnelShadowUpdate)(state);
276
- if (!valid) {
277
- logger_1.logger.error(`Error validating message: ${JSON.stringify({ payload, errors: device_agent_schemas_1.validateSecureTunnelShadowUpdate.errors }, null, 2)}`);
278
- return;
279
- }
280
- const secureTunnelUpdate = await this.secureTunnelHandler.syncShadowToDeviceState(payload);
281
- await this.shadowHandler.updateSecureTunnelShadow(secureTunnelUpdate);
282
- return;
55
+ // Instantiate & register message handlers for to-device and secureTunnel topics
56
+ this.connectionManager.registerHandler(this.toDeviceTopic, new device_agent_message_handler_1.DeviceAgentMessageHandler(handlerContext, (txId, errorMsg) => {
57
+ const msg = (0, device_agent_schemas_1.buildToClientStatusResponseMessage)(this.publisher.getClientId(), {
58
+ status: device_agent_schemas_1.keyMirrors.statusResponse.failure,
59
+ message: errorMsg
60
+ }, txId);
61
+ this.publisher.publishToClient(msg);
62
+ }, (txId) => {
63
+ const msg = (0, device_agent_schemas_1.buildToClientStatusResponseMessage)(this.publisher.getClientId(), { status: device_agent_schemas_1.keyMirrors.statusResponse.success }, txId);
64
+ this.publisher.publishToClient(msg);
65
+ }));
66
+ const secureTunnelMessageHandler = new secure_tunnel_message_handler_1.SecureTunnelMessageHandler(handlerContext);
67
+ this.connectionManager.registerHandler(secureTunnelMessageHandler.getNotifyTopic(), secureTunnelMessageHandler);
68
+ this.connectionManager.registerHandler(this.shadowHandler.shadowTopics.secureTunnel.updateDelta, secureTunnelMessageHandler);
69
+ this.connectionManager.registerHandler(this.shadowHandler.shadowTopics.secureTunnel.deleteAccepted, secureTunnelMessageHandler);
70
+ const jobHandler = new job_handler_1.JobHandler(handlerContext);
71
+ const JOB_HANDLER_TOPICS = jobHandler.getJobTopic();
72
+ this.connectionManager.registerHandler(JOB_HANDLER_TOPICS.NOTIFY_NEXT, jobHandler);
73
+ this.connectionManager.registerHandler(JOB_HANDLER_TOPICS.START_NEXT_ACCEPTED, jobHandler);
74
+ // Initialize job
75
+ this.publisher.publish(JOB_HANDLER_TOPICS.START_NEXT, JSON.stringify({}));
283
76
  }
77
+ /*=================================================================
78
+ Public interface
79
+ =================================================================*/
284
80
  getClientId() {
285
81
  return this.clientId;
286
82
  }
287
- getToDeviceTopic() {
288
- return this.toDeviceTopic;
289
- }
290
83
  isCmdInProgress(projectId) {
291
- return this.txnMgr.isOngoingTransactionForProjectID(projectId);
292
- }
293
- async updateProjectShadow(projectId) {
294
- await this.shadowHandler.updateProjectShadow(projectId);
295
- }
296
- async handleDeviceAgentMessage({ topic, message }) {
297
- const valid = (0, device_agent_schemas_1.validateToDeviceAgentMessage)(message);
298
- if (!valid) {
299
- logger_1.logger.error(`Error validating message: ${JSON.stringify({ topic, message, errors: device_agent_schemas_1.validateToDeviceAgentMessage.errors }, null, 2)}`);
300
- // TODO: Send generic error response
301
- return;
302
- }
303
- const txId = message.txId;
304
- const { app_state_control, app_version_control, live_state_updates, app_install_response, models_install_response, status_response, device_action } = device_agent_schemas_1.keyMirrors.toDeviceAgentMessageType;
305
- switch (message.messageType) {
306
- case app_state_control: {
307
- // txId sent from cloud, just need to continue it
308
- const payload = message.payload;
309
- const projectId = payload.projectId;
310
- try {
311
- await this.txnMgr.runTransactionStep({
312
- func: () => this.handleAppStateControl(message.payload),
313
- projectId,
314
- txId,
315
- start: true,
316
- stepName: payload.baseCommand
317
- });
318
- }
319
- catch (e) {
320
- logger_1.logger.error(`Error processing application state control request: ${e}!`);
321
- }
322
- break;
323
- }
324
- case app_version_control: {
325
- // txId sent from cloud, just need to continue it
326
- const payload = message.payload;
327
- const projectId = payload.projectId;
328
- try {
329
- await this.txnMgr.runTransactionStep({
330
- func: () => this.handleAppVersionControl(payload, txId),
331
- projectId,
332
- txId,
333
- start: true,
334
- stepName: payload.baseCommand
335
- });
336
- }
337
- catch (e) {
338
- logger_1.logger.error(`Error processing application install request: ${e}!`);
339
- }
340
- break;
341
- }
342
- case live_state_updates: {
343
- const payload = message.payload;
344
- // TODO: Send response?
345
- void this.liveUpdatesHandler.handleToggles(payload, txId);
346
- break;
347
- }
348
- case app_install_response: {
349
- const payload = message.payload;
350
- const { projectId } = payload.appInstallResponse;
351
- if (txId !== this.txnMgr.getTransactionFromProject(projectId)) {
352
- throw new Error(`App install response received a message for a transaction ID ${txId} that is not currently underway (${this.txnMgr.getTransactionFromProject(projectId)})!`);
353
- }
354
- await this.txnMgr.runTransactionStep({
355
- func: () => this.handleAppInstallCloudResponsePayload(payload),
356
- projectId,
357
- txId,
358
- start: false,
359
- stepName: message.messageType
360
- });
361
- break;
362
- }
363
- case models_install_response: {
364
- // This message doesn't have appReleaseHash in it's payload, but
365
- // atomicCmd should be able to read it from the installed app
366
- const payload = message.payload;
367
- const { projectId } = payload.modelsInstallResponse;
368
- if (txId !== this.txnMgr.getTransactionFromProject(projectId)) {
369
- throw new Error(`Model install response received a message for a transaction ID ${txId} that is not currently underway (${this.txnMgr.getTransactionFromProject(projectId)})!`);
370
- }
371
- await this.txnMgr.runTransactionStep({
372
- func: () => this.handleModelsInstallCloudResponsePayload(payload, txId),
373
- projectId,
374
- txId,
375
- start: false,
376
- stepName: message.messageType
377
- });
378
- break;
379
- }
380
- case status_response: {
381
- const { failure } = device_agent_schemas_1.keyMirrors.statusResponse;
382
- if (message.payload.status === failure) {
383
- this.txnMgr.completeTransaction(txId);
384
- const failureStatusResponsePayload = {
385
- status: device_agent_schemas_1.keyMirrors.statusResponse.failure,
386
- message: message.payload.message
387
- };
388
- // Send final status message
389
- const failureStatusResponseMessage = (0, device_agent_schemas_1.buildToClientStatusResponseMessage)(this.clientId, failureStatusResponsePayload, txId);
390
- this.publisher.publishToClient(failureStatusResponseMessage);
391
- }
392
- break;
393
- }
394
- case device_action: {
395
- try {
396
- const statusResponsePayload = {
397
- status: device_agent_schemas_1.keyMirrors.statusResponse.in_progress
398
- };
399
- const statusResponseMessage = (0, device_agent_schemas_1.buildToClientStatusResponseMessage)(this.clientId, statusResponsePayload, txId);
400
- this.publisher.publishToClient(statusResponseMessage);
401
- await this.handleDeviceAction(message.payload);
402
- const successStatusResponsePayload = {
403
- status: device_agent_schemas_1.keyMirrors.statusResponse.success
404
- };
405
- const successStatusResponseMessage = (0, device_agent_schemas_1.buildToClientStatusResponseMessage)(this.clientId, successStatusResponsePayload, txId);
406
- this.publisher.publishToClient(successStatusResponseMessage);
407
- }
408
- catch (e) {
409
- logger_1.logger.error(`There was a problem performing device action '${message.payload.action}': ${e.message}`);
410
- const failureStatusResponsePayload = {
411
- status: device_agent_schemas_1.keyMirrors.statusResponse.failure,
412
- message: e.message
413
- };
414
- const failureStatusResponseMessage = (0, device_agent_schemas_1.buildToClientStatusResponseMessage)(this.clientId, failureStatusResponsePayload, txId);
415
- this.publisher.publishToClient(failureStatusResponseMessage);
416
- }
417
- break;
418
- }
419
- default:
420
- logger_1.logger.error(`Invalid client message: '${JSON.stringify({ topic, message, txId }, null, 2)}'`);
421
- }
422
- }
423
- async handleMessage(topic, message) {
424
- logger_1.logger.debug(`Received message: ${JSON.stringify({ topic, message }, null, 2)}`);
425
- // ProjectShadow messages
426
- if (this.shadowHandler.projectShadowTopics.includes(topic)) {
427
- await this.handleProjectShadowMessage(topic, message);
428
- }
429
- else if (topic === this.toDeviceTopic) {
430
- await this.handleDeviceAgentMessage({
431
- topic,
432
- message
433
- });
434
- // SecureTunnelNotify messages
435
- }
436
- else if (topic === this.secureTunnelNotifyTopic) {
437
- await this.secureTunnelHandler.secureTunnelNotifyHandler(message);
438
- // SecureTunnel messages
439
- }
440
- else if (topic === this.shadowHandler.shadowTopics.secureTunnel.updateDelta) {
441
- await this.handleSecureTunnelMessage(message);
442
- }
443
- else if (topic === this.shadowHandler.shadowTopics.secureTunnel.deleteAccepted) {
444
- logger_1.logger.info(`Received secure tunnel deleteAccepted: ${message}`);
445
- await this.secureTunnelHandler.destroy();
446
- }
447
- else {
448
- logger_1.logger.error(`Unexpected topic, ignoring! ${topic}`);
449
- }
450
- }
451
- async setupHandlers() {
452
- this.device.on('connect', (connack) => {
453
- logger_1.logger.info('Device Agent has connected to the cloud');
454
- // FIXME: EI-709 Skip this request for now to prevent kicking off another
455
- // shadow update process if IoT Core disconnect occurs during app config update
456
- //this.shadowHandler.getShadowUpdates();
457
- void this.shadowHandler.updateSystemInfoShadow();
458
- });
459
- this.device.on('disconnect', () => {
460
- logger_1.logger.warn('Device Agent has been disconnected from the cloud');
461
- });
462
- this.device.on('reconnect', () => {
463
- logger_1.logger.info(`Device Agent attempting to re-connect ${new Date().toLocaleString()}`);
464
- });
465
- this.device.on('error', function (error) {
466
- const errorString = error.message.toString();
467
- logger_1.logger.error(`${errorString}`);
468
- });
469
- this.device.on('message', async (topic, payload) => {
470
- try {
471
- const jsonPacket = JSON.parse(payload);
472
- await this.handleMessage(topic, jsonPacket);
473
- }
474
- catch (e) {
475
- logger_1.logger.error(`Error parsing message: ${e.message}`);
476
- }
477
- });
478
- this.device.on('offline', () => {
479
- logger_1.logger.warn(`Device Agent is offline ${new Date().toLocaleString()}`);
480
- void this.logConnectionInfo();
481
- });
482
- }
483
- async logConnectionInfo() {
484
- try {
485
- /**
486
- * We're using the 'netcat' or 'nc' command to test the connection to the IoT Core endpoint.
487
- * This command doesn't always exit (see below), so
488
- * we use timeout to break out of the prompt
489
- * and catch the resulting error/parse the resulting stderr
490
- *
491
- * Sample command for current host and port:
492
- * nc -zv -w 1 a3tzi5g7sq5zsj-ats.iot.us-west-2.amazonaws.com 8883
493
- *
494
- * Sample output when port is not blocked and host is reachable:
495
- * $ nc -zv -w 1 a3tzi5g7sq5zsj-ats.iot.us-west-2.amazonaws.com 443
496
- * Connection to a3tzi5g7sq5zsj-ats.iot.us-west-2.amazonaws.com 443 port [tcp/https] succeeded!
497
- *
498
- *
499
- * Sample output when port is blocked (will repeatedly try until ctrl-C out):
500
- * $ nc -zv -w 1 a3tzi5g7sq5zsj-ats.iot.us-west-2.amazonaws.com 8883
501
- * nc: connect to a3tzi5g7sq5zsj-ats.iot.us-west-2.amazonaws.com port 8883 (tcp) timed out: Operation now in progress
502
- * nc: connect to a3tzi5g7sq5zsj-ats.iot.us-west-2.amazonaws.com port 8883 (tcp) timed out: Operation now in progress
503
- * nc: connect to a3tzi5g7sq5zsj-ats.iot.us-west-2.amazonaws.com port 8883 (tcp) timed out: Operation now in progress
504
- * ^C
505
- *
506
- *
507
- * Sample command/output when the port isn't enable on that host:
508
- * $ nc -zv -w 1 localhost 8883
509
- * nc: connect to localhost port 8883 (tcp) failed: Connection refused
510
- */
511
- await exec_promise(`nc -zv -w 1 ${this.host} ${this.port}`, {
512
- timeout: 2000
513
- });
514
- }
515
- catch (err) {
516
- const output = JSON.stringify(err['stderr']);
517
- if (output.indexOf('not known') !== -1) {
518
- logger_1.logger.warn('Iot Core endpoint appears to be unreachable, internet connection may be unstable or the host may be down.');
519
- }
520
- else if (output.indexOf('timed out') !== -1) {
521
- logger_1.logger.warn(`Internet connection appears fine, however the endpoint was not reachable on the current connection port: ${this.port}\nPlease check if a firewall is in place.`);
522
- }
523
- else if (output.indexOf('refused') !== -1) {
524
- logger_1.logger.warn(`The connection was refused, likely ${this.host} is not running a service on ${this.port}.`);
525
- }
526
- else {
527
- logger_1.logger.warn(`Output from checking connection to ${this.host} on ${this.port}: ${output}`);
528
- }
529
- }
84
+ return this.transactionManager.isOngoingTransactionForProjectID(projectId);
530
85
  }
531
86
  async stop() {
532
87
  // This method is currently only used by the CLI, and shadow messages can be
533
88
  // lost since we aren't waiting for responses so sleep for a short time to
534
89
  // receive them
535
90
  await (0, sleep_1.default)(1000);
536
- this.device.end();
91
+ this.connectionManager.disconnect();
92
+ }
93
+ async handleMessage(topic, message) {
94
+ this.connectionManager.dispatch(topic, message);
537
95
  }
538
96
  }
539
97
  exports.DeviceAgentCloudConnection = DeviceAgentCloudConnection;
540
98
  async function runDeviceAgentCloudInterface() {
541
99
  logger_1.logger.info(`Starting alwaysAI Device Agent v${await (0, check_for_updates_1.getDeviceAgentVersion)()}`);
542
- if ((0, cloud_mode_ready_1.cloudModeReady)()) {
100
+ if ((0, fs_1.existsSync)((0, device_certificate_1.getBootstrapPrivateKeyFilePath)())) {
101
+ await (0, bootstrap_provision_1.bootstrapProvision)();
102
+ return;
103
+ }
104
+ const filesAlreadyMigrated = await (0, required_config_checks_1.requiredConfigFilesPresentAndValid)();
105
+ if (!filesAlreadyMigrated) {
106
+ logger_1.logger.debug('Attempting configuration file migration.');
107
+ await (0, legacy_migration_1.migrateFromLegacyCertsAndTokens)();
108
+ }
109
+ if (await (0, required_config_checks_1.requiredConfigFilesPresentAndValid)()) {
543
110
  const deviceAgent = new DeviceAgentCloudConnection();
544
- await deviceAgent.setupHandlers();
545
111
  if (environment_1.ALWAYSAI_ANALYTICS_PASSTHROUGH === true) {
112
+ const shadowHandler = deviceAgent.shadowHandler;
546
113
  const publisher = deviceAgent.publisher;
547
- const passthroughHandler = new passthrough_handler_1.PassthroughHandler(publisher);
114
+ const passthroughHandler = new passthrough_handler_1.PassthroughHandler(publisher, shadowHandler);
548
115
  await passthroughHandler.setup();
549
116
  }
550
117
  }
551
- else if ((0, fs_1.existsSync)((0, directories_1.BOOTSTRAP_PRIVATE_KEY_FILE_PATH)())) {
552
- await (0, bootstrap_provision_1.bootstrapProvision)();
553
- }
554
- else if ((0, fs_1.existsSync)((0, directories_1.BOOTSTRAP_CERTIFICATES_DIR_PATH)())) {
555
- throw new Error("Device has not been created using 'aai-agent device init' or there has been an issue with device initialization");
556
- }
557
118
  else {
558
119
  throw new Error("Set device agent to local mode and retry the 'aai-agent device init' command");
559
120
  }