aspera-cli 4.29.1 → 4.30.0

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 (264) hide show
  1. checksums.yaml +4 -4
  2. checksums.yaml.gz.sig +4 -4
  3. data/CHANGELOG.md +119 -0
  4. data/CONTRIBUTING.md +8 -1
  5. data/README.md +2 -0
  6. data/TODO.md +4 -5
  7. data/bin/asession +2 -2
  8. data/docs/README.md +616 -86
  9. data/docs/test-mcp-with-ai.md +4 -0
  10. data/lib/aspera/agent/base.rb +62 -6
  11. data/lib/aspera/agent/factory.rb +127 -20
  12. data/lib/aspera/ascp/data_repository.rb +71 -0
  13. data/lib/aspera/ascp/installation.rb +16 -11
  14. data/lib/aspera/ascp/log_analyzer/lines.rb +4 -4
  15. data/lib/aspera/ascp/log_analyzer/log_file.rb +5 -3
  16. data/lib/aspera/ascp/log_analyzer/records.rb +11 -6
  17. data/lib/aspera/ascp/log_analyzer.rb +43 -18
  18. data/lib/aspera/ascp/log_locations.rb +2 -2
  19. data/lib/aspera/assert.rb +8 -0
  20. data/lib/aspera/bundle_registry.rb +528 -0
  21. data/lib/aspera/cli/argument.rb +110 -0
  22. data/lib/aspera/cli/bool_value.rb +41 -0
  23. data/lib/aspera/cli/bootstrapper.rb +31 -24
  24. data/lib/aspera/cli/command/mount.rb +53 -0
  25. data/lib/aspera/cli/command/registry.rb +434 -0
  26. data/lib/aspera/cli/command.rb +95 -0
  27. data/lib/aspera/cli/command_line.rb +91 -91
  28. data/lib/aspera/cli/complete.rb +22 -0
  29. data/lib/aspera/cli/completion_actions.rb +28 -26
  30. data/lib/aspera/cli/context.rb +29 -6
  31. data/lib/aspera/cli/error.rb +39 -0
  32. data/lib/aspera/cli/extended_value.rb +25 -4
  33. data/lib/aspera/cli/formatter.rb +8 -8
  34. data/lib/aspera/cli/hints.rb +17 -52
  35. data/lib/aspera/cli/http.rb +17 -12
  36. data/lib/aspera/cli/mailer.rb +7 -24
  37. data/lib/aspera/cli/mcp/tool.rb +10 -2
  38. data/lib/aspera/cli/option/declarator.rb +80 -0
  39. data/lib/aspera/cli/option/registry.rb +74 -0
  40. data/lib/aspera/cli/option/source.rb +38 -0
  41. data/lib/aspera/cli/option/type.rb +37 -0
  42. data/lib/aspera/cli/option/value.rb +376 -0
  43. data/lib/aspera/cli/option.rb +78 -0
  44. data/lib/aspera/cli/options.schema.yaml +28 -783
  45. data/lib/aspera/cli/parser.rb +73 -41
  46. data/lib/aspera/cli/plugins/base.rb +122 -42
  47. data/lib/aspera/cli/plugins/basic_auth.rb +13 -2
  48. data/lib/aspera/cli/plugins/config.rb +101 -167
  49. data/lib/aspera/cli/plugins/factory.rb +139 -43
  50. data/lib/aspera/cli/plugins/mcp.rb +61 -54
  51. data/lib/aspera/cli/plugins/oauth.rb +19 -6
  52. data/lib/aspera/cli/poll.rb +14 -20
  53. data/lib/aspera/cli/preset_actions.rb +11 -3
  54. data/lib/aspera/cli/preset_manager.rb +16 -6
  55. data/lib/aspera/cli/result.rb +2 -2
  56. data/lib/aspera/cli/runner.rb +71 -99
  57. data/lib/aspera/cli/secret_finder.rb +1 -1
  58. data/lib/aspera/cli/security.rb +102 -4
  59. data/lib/aspera/{preview/terminal.rb → cli/terminal_image.rb} +93 -94
  60. data/lib/aspera/cli/vault_manager.rb +3 -3
  61. data/lib/aspera/cli/version.rb +1 -1
  62. data/lib/aspera/cli/wizard.rb +9 -3
  63. data/lib/aspera/coverage.rb +1 -2
  64. data/lib/aspera/line_logger.rb +35 -6
  65. data/lib/aspera/log.rb +3 -2
  66. data/lib/aspera/oauth/client/base.rb +19 -1
  67. data/lib/aspera/oauth/client/factory.rb +1 -7
  68. data/lib/aspera/plugin.schema.yaml +178 -0
  69. data/lib/aspera/plugins/alee/api.rb +25 -0
  70. data/lib/aspera/{cli/plugins/alee.rb → plugins/alee/commands.rb} +10 -8
  71. data/lib/aspera/plugins/alee/plugin.yaml +3 -0
  72. data/lib/aspera/plugins/aoc/admin_resources.rb +148 -0
  73. data/lib/aspera/plugins/aoc/api.rb +783 -0
  74. data/lib/aspera/{cli/plugins/aoc.rb → plugins/aoc/commands.rb} +404 -330
  75. data/lib/aspera/plugins/aoc/graphql.rb +45 -0
  76. data/lib/aspera/plugins/aoc/plugin.yaml +31 -0
  77. data/lib/aspera/{schema → plugins/aoc/schemas}/IBM Aspera on Cloud API-0.2.6-enhanced.yaml +15042 -7076
  78. data/lib/aspera/plugins/aoc/schemas/options.yaml +47 -0
  79. data/lib/aspera/plugins/ats/api.rb +51 -0
  80. data/lib/aspera/{cli/plugins/ats.rb → plugins/ats/commands.rb} +33 -33
  81. data/lib/aspera/plugins/ats/plugin.yaml +6 -0
  82. data/lib/aspera/plugins/connect/agent.rb +199 -0
  83. data/lib/aspera/plugins/connect/plugin.yaml +11 -0
  84. data/lib/aspera/plugins/connect/schemas/agent_options.yaml +6 -0
  85. data/lib/aspera/{cli/plugins/console.rb → plugins/console/commands.rb} +41 -33
  86. data/lib/aspera/plugins/console/plugin.yaml +8 -0
  87. data/lib/aspera/plugins/cos/api.rb +114 -0
  88. data/lib/aspera/{cli/plugins/cos.rb → plugins/cos/commands.rb} +19 -16
  89. data/lib/aspera/plugins/cos/plugin.yaml +9 -0
  90. data/lib/aspera/plugins/cos/schemas/options.yaml +30 -0
  91. data/lib/aspera/plugins/desktop/agent.rb +165 -0
  92. data/lib/aspera/plugins/desktop/plugin.yaml +11 -0
  93. data/lib/aspera/plugins/desktop/schemas/agent_options.yaml +6 -0
  94. data/lib/aspera/plugins/direct/agent.rb +518 -0
  95. data/lib/aspera/plugins/direct/plugin.yaml +11 -0
  96. data/lib/aspera/plugins/direct/schemas/agent_options.yaml +86 -0
  97. data/lib/aspera/plugins/faspex4/gateway_options.rb +18 -0
  98. data/lib/aspera/plugins/faspex4/gw_servlet.rb +122 -0
  99. data/lib/aspera/plugins/faspex4/plugin.yaml +7 -0
  100. data/lib/aspera/plugins/faspex4/schemas/options.yaml +57 -0
  101. data/lib/aspera/plugins/faspex5/api.rb +269 -0
  102. data/lib/aspera/{cli/plugins/faspex5.rb → plugins/faspex5/commands.rb} +152 -114
  103. data/lib/aspera/plugins/faspex5/faspex4_post_proc_servlet.rb +241 -0
  104. data/lib/aspera/plugins/faspex5/plugin.yaml +14 -0
  105. data/lib/aspera/{schema → plugins/faspex5/schemas}/IBM Aspera Faspex API-5.0-enhanced.yaml +279 -76
  106. data/lib/aspera/plugins/faspex5/schemas/options.yaml +87 -0
  107. data/lib/aspera/{cli/plugins/faspio.rb → plugins/faspio/commands.rb} +11 -7
  108. data/lib/aspera/plugins/faspio/plugin.yaml +8 -0
  109. data/lib/aspera/{schema → plugins/faspio/schemas}/IBM Aspera faspio Gateway API-1.0.0-enhanced.yaml +4 -2
  110. data/lib/aspera/plugins/httpgw/agent.rb +126 -0
  111. data/lib/aspera/plugins/httpgw/api.rb +411 -0
  112. data/lib/aspera/{cli/plugins/httpgw.rb → plugins/httpgw/commands.rb} +9 -9
  113. data/lib/aspera/plugins/httpgw/plugin.yaml +12 -0
  114. data/lib/aspera/plugins/httpgw/schemas/agent_options.yaml +24 -0
  115. data/lib/aspera/plugins/node/agent.rb +184 -0
  116. data/lib/aspera/plugins/node/api.rb +699 -0
  117. data/lib/aspera/{cli/plugins/node.rb → plugins/node/commands.rb} +166 -141
  118. data/lib/aspera/plugins/node/emulator.rb +774 -0
  119. data/lib/aspera/plugins/node/plugin.yaml +20 -0
  120. data/lib/aspera/plugins/node/schemas/agent_options.yaml +20 -0
  121. data/lib/aspera/plugins/node/schemas/options.yaml +190 -0
  122. data/lib/aspera/{cli/plugins/orchestrator.rb → plugins/orchestrator/commands.rb} +139 -110
  123. data/lib/aspera/plugins/orchestrator/plugin.yaml +34 -0
  124. data/lib/aspera/{schema → plugins/orchestrator/schemas}/IBM Aspera Orchestrator API-v1-enhanced.yaml +486 -16
  125. data/lib/aspera/plugins/orchestrator/schemas/options.yaml +143 -0
  126. data/lib/aspera/plugins/orchestrator/workflow_checker.rb +692 -0
  127. data/lib/aspera/{cli/plugins/preview.rb → plugins/preview/commands.rb} +53 -51
  128. data/lib/aspera/plugins/preview/file_types.rb +121 -0
  129. data/lib/aspera/plugins/preview/generator.rb +350 -0
  130. data/lib/aspera/plugins/preview/plugin.yaml +12 -0
  131. data/lib/aspera/{preview/options.schema.yaml → plugins/preview/schemas/options.yaml} +1 -1
  132. data/lib/aspera/plugins/preview/utils.rb +213 -0
  133. data/lib/aspera/plugins/server/ascmd.rb +374 -0
  134. data/lib/aspera/{cli/plugins/server.rb → plugins/server/commands.rb} +48 -32
  135. data/lib/aspera/plugins/server/plugin.yaml +9 -0
  136. data/lib/aspera/plugins/server/schemas/options.yaml +30 -0
  137. data/lib/aspera/{cli/plugins/shares.rb → plugins/shares/commands.rb} +29 -21
  138. data/lib/aspera/plugins/shares/plugin.yaml +10 -0
  139. data/lib/aspera/plugins/shares/shares_web.rb +97 -0
  140. data/lib/aspera/plugins/transferd/agent.rb +258 -0
  141. data/lib/aspera/plugins/transferd/api.rb +180 -0
  142. data/lib/aspera/plugins/transferd/client.rb +67 -0
  143. data/lib/aspera/{cli/plugins/transferd.rb → plugins/transferd/commands.rb} +43 -42
  144. data/lib/aspera/plugins/transferd/config_commands.rb +38 -0
  145. data/lib/aspera/plugins/transferd/plugin.yaml +27 -0
  146. data/lib/aspera/plugins/transferd/product.rb +146 -0
  147. data/lib/aspera/plugins/transferd/schemas/agent_options.yaml +31 -0
  148. data/lib/aspera/plugins/transferd/schemas/options.yaml +80 -0
  149. data/lib/aspera/plugins/transferd/service.rb +617 -0
  150. data/lib/aspera/plugins/xfer/ascp_actions.rb +131 -0
  151. data/lib/aspera/plugins/xfer/ascp_logs_actions.rb +198 -0
  152. data/lib/aspera/plugins/xfer/async_transfer_store.rb +131 -0
  153. data/lib/aspera/plugins/xfer/config_commands.rb +119 -0
  154. data/lib/aspera/plugins/xfer/helper.rb +19 -0
  155. data/lib/aspera/plugins/xfer/plugin.yaml +42 -0
  156. data/lib/aspera/plugins/xfer/schemas/agent_extension.schema.yaml +26 -0
  157. data/lib/aspera/plugins/xfer/schemas/options.yaml +125 -0
  158. data/lib/aspera/plugins/xfer/sync_actions.rb +253 -0
  159. data/lib/aspera/plugins/xfer/transfer_actions.rb +176 -0
  160. data/lib/aspera/plugins/xfer/transfer_agent.rb +505 -0
  161. data/lib/aspera/products/cli_v3.rb +34 -0
  162. data/lib/aspera/products/connect.rb +1 -1
  163. data/lib/aspera/products/drive.rb +29 -0
  164. data/lib/aspera/products/hsts.rb +34 -0
  165. data/lib/aspera/products/transferd.rb +25 -3
  166. data/lib/aspera/products.rb +54 -0
  167. data/lib/aspera/prompt.rb +184 -0
  168. data/lib/aspera/proxy_auto_config.rb +3 -3
  169. data/lib/aspera/rest/aspera_errors.rb +4 -38
  170. data/lib/aspera/rest/error_analyzer.rb +6 -2
  171. data/lib/aspera/rest/list.rb +4 -5
  172. data/lib/aspera/schema/reader.rb +15 -0
  173. data/lib/aspera/schema/registry.rb +239 -45
  174. data/lib/aspera/schema/validator.rb +63 -17
  175. data/lib/aspera/sealed_hash.rb +4 -0
  176. data/lib/aspera/secret/hider.rb +159 -24
  177. data/lib/aspera/secret/reference.rb +8 -0
  178. data/lib/aspera/secret/resolver.rb +8 -4
  179. data/lib/aspera/secret/store/base.rb +10 -9
  180. data/lib/aspera/secret/store/encrypted_hash.rb +6 -6
  181. data/lib/aspera/secret/store/hashicorp_vault.rb +3 -3
  182. data/lib/aspera/secret/store/keeper.rb +2 -2
  183. data/lib/aspera/secret/store/macos_security.rb +2 -3
  184. data/lib/aspera/secret/store/one_password_api.rb +2 -2
  185. data/lib/aspera/secret/store/one_password_cli.rb +3 -3
  186. data/lib/aspera/secret/store/secret_service.rb +2 -2
  187. data/lib/aspera/ssl.rb +3 -3
  188. data/lib/aspera/standard_input.rb +20 -0
  189. data/lib/aspera/{schema → sync}/async_tables.yaml +1 -1
  190. data/lib/aspera/sync/database.rb +7 -0
  191. data/lib/aspera/sync/log_parser.rb +138 -0
  192. data/lib/aspera/sync/operations.rb +59 -34
  193. data/lib/aspera/transfer/command_line_builder.rb +248 -0
  194. data/lib/aspera/transfer/command_line_converter.rb +37 -0
  195. data/lib/aspera/transfer/faux_file.rb +2 -2
  196. data/lib/aspera/transfer/parameters.rb +9 -10
  197. data/lib/aspera/transfer/spec.rb +28 -1
  198. data/lib/aspera/transfer/spec.schema.yaml +30 -5
  199. data/lib/aspera/units/decimal.rb +1 -1
  200. data/lib/aspera/units/timestamp.rb +84 -0
  201. data/lib/aspera/uri_reader.rb +2 -2
  202. data/lib/aspera/web_auth/paste.rb +2 -2
  203. data/lib/aspera/web_server_simple.rb +10 -4
  204. data.tar.gz.sig +0 -0
  205. metadata +137 -80
  206. metadata.gz.sig +0 -0
  207. data/lib/aspera/agent/connect.rb +0 -188
  208. data/lib/aspera/agent/desktop.rb +0 -154
  209. data/lib/aspera/agent/direct.rb +0 -496
  210. data/lib/aspera/agent/httpgw.rb +0 -100
  211. data/lib/aspera/agent/node.rb +0 -166
  212. data/lib/aspera/agent/transferd.rb +0 -341
  213. data/lib/aspera/api/alee.rb +0 -19
  214. data/lib/aspera/api/aoc.rb +0 -776
  215. data/lib/aspera/api/ats.rb +0 -49
  216. data/lib/aspera/api/cos_node.rb +0 -107
  217. data/lib/aspera/api/faspex.rb +0 -258
  218. data/lib/aspera/api/httpgw.rb +0 -409
  219. data/lib/aspera/api/node.rb +0 -684
  220. data/lib/aspera/ascmd.rb +0 -248
  221. data/lib/aspera/cli/ascp_actions.rb +0 -113
  222. data/lib/aspera/cli/ascp_logs_actions.rb +0 -188
  223. data/lib/aspera/cli/async_transfer_store.rb +0 -129
  224. data/lib/aspera/cli/command_registry.rb +0 -371
  225. data/lib/aspera/cli/command_spec.rb +0 -273
  226. data/lib/aspera/cli/option_declarator.rb +0 -74
  227. data/lib/aspera/cli/option_registry.rb +0 -72
  228. data/lib/aspera/cli/option_types.rb +0 -120
  229. data/lib/aspera/cli/option_value.rb +0 -345
  230. data/lib/aspera/cli/prompt.rb +0 -186
  231. data/lib/aspera/cli/sync_actions.rb +0 -181
  232. data/lib/aspera/cli/transfer_actions.rb +0 -98
  233. data/lib/aspera/cli/transfer_agent.rb +0 -348
  234. data/lib/aspera/command_line_builder.rb +0 -244
  235. data/lib/aspera/command_line_converter.rb +0 -35
  236. data/lib/aspera/data_repository.rb +0 -69
  237. data/lib/aspera/faspex_gw.rb +0 -172
  238. data/lib/aspera/faspex_postproc.rb +0 -237
  239. data/lib/aspera/graphql.rb +0 -41
  240. data/lib/aspera/node_emulator.rb +0 -758
  241. data/lib/aspera/oauth/client/shares_web.rb +0 -94
  242. data/lib/aspera/orchestrator_workflow_checker.rb +0 -688
  243. data/lib/aspera/preview/file_types.rb +0 -119
  244. data/lib/aspera/preview/generator.rb +0 -345
  245. data/lib/aspera/preview/utils.rb +0 -211
  246. data/lib/aspera/products/other.rb +0 -92
  247. data/lib/aspera/products/transferd_service.rb +0 -610
  248. /data/lib/aspera/{data → ascp/data}/1 +0 -0
  249. /data/lib/aspera/{data → ascp/data}/2 +0 -0
  250. /data/lib/aspera/{data → ascp/data}/3 +0 -0
  251. /data/lib/aspera/{data → ascp/data}/4 +0 -0
  252. /data/lib/aspera/{data → ascp/data}/5 +0 -0
  253. /data/lib/aspera/{data → ascp/data}/6 +0 -0
  254. /data/lib/aspera/{api → plugins/aoc}/queries/bss_subscription_account.graphql +0 -0
  255. /data/lib/aspera/{api → plugins/aoc}/queries/bss_subscription_usage.graphql +0 -0
  256. /data/lib/aspera/{schema → plugins/aoc/schemas}/IBM Aspera on Cloud Automation API-1.0.5-enhanced.yaml +0 -0
  257. /data/lib/aspera/{schema → plugins/console/schemas}/IBM Aspera Console-enhanced.yaml +0 -0
  258. /data/lib/aspera/{schema → plugins/node/schemas}/IBM Aspera Node API-4.4.6.yaml +0 -0
  259. /data/lib/aspera/{preview → plugins/preview}/image_error.png +0 -0
  260. /data/lib/aspera/{preview → plugins/preview}/video_error.png +0 -0
  261. /data/lib/aspera/{schema → plugins/shares/schemas}/IBM_Aspera_Shares.yaml +0 -0
  262. /data/lib/{transferd_pb.rb → aspera/plugins/transferd/grpc/transferd_pb.rb} +0 -0
  263. /data/lib/{transferd_services_pb.rb → aspera/plugins/transferd/grpc/transferd_services_pb.rb} +0 -0
  264. /data/lib/aspera/{schema → plugins/transferd/schemas}/transferd-config.schema.json +0 -0
@@ -0,0 +1,774 @@
1
+ # frozen_string_literal: true
2
+
3
+ # SPDX-FileCopyrightText: IBM Corp.
4
+ # SPDX-License-Identifier: Apache-2.0
5
+
6
+ require_relative '../../assert'
7
+ require_relative '../../ascp/installation'
8
+ require_relative '../../agent/factory'
9
+ require_relative '../../transfer/spec'
10
+ require_relative '../../transfer/error'
11
+ require_relative '../../secret/hider'
12
+ require_relative '../../string_ext'
13
+ require_relative '../../log'
14
+ require_relative '../../servlet_helpers'
15
+ require 'webrick'
16
+ require 'etc'
17
+ require 'securerandom'
18
+ require 'json'
19
+ require 'time'
20
+
21
+ module Aspera
22
+ module Plugins
23
+ module Node
24
+ # Node API transfers executed by transferd.
25
+ # Only transfers started through the emulator are known (kept in memory).
26
+ class Emulator
27
+ # transferd status → Node API transfer status
28
+ STATUS = {
29
+ UNKNOWN_STATUS: 'waiting',
30
+ QUEUED: 'waiting',
31
+ RUNNING: 'running',
32
+ COMPLETED: 'completed',
33
+ FAILED: 'failed',
34
+ ORPHANED: 'failed',
35
+ CANCELED: 'canceled',
36
+ PAUSED: 'paused'
37
+ }.freeze
38
+ # transferd statuses after which no event is received
39
+ TERMINAL = %i[COMPLETED FAILED CANCELED ORPHANED].freeze
40
+ # Node API statuses of active transfers and sessions
41
+ ACTIVE = %w[waiting running].freeze
42
+ # transferd session status (lowercase) → Node API, others are only lowercased
43
+ SESSION_STATUS = {'draft' => 'waiting'}.freeze
44
+ # transferd file status (lowercase) → Node API, others are only lowercased
45
+ FILE_STATUS = {'transferring' => 'running', 'finished' => 'completed'}.freeze
46
+ # transferd field → Node API field, when not the snake case of it (`nil`: ignored)
47
+ TRANSFER_OVERRIDES = {'averageRateKbps' => 'avg_rate_kbps', 'errorDescription' => 'error_desc'}.freeze
48
+ SESSION_OVERRIDES = {'id' => nil, 'sessionId' => 'id'}.freeze
49
+ FILE_OVERRIDES = {'fileId' => 'id', 'errorDescription' => 'error_desc', 'fileType' => 'type', 'fileChecksumType' => 'checksum_type'}.freeze
50
+ # Node API fields taken as is from transferd (after renaming)
51
+ TRANSFER_FIELDS = %w[bytes_transferred bytes_written bytes_lost avg_rate_kbps files_completed directories_completed elapsed_usec].freeze
52
+ SESSION_FIELDS = %w[
53
+ id client_node_id server_node_id client_ip_address server_ip_address start_time_usec end_time_usec elapsed_usec
54
+ bytes_transferred bytes_written bytes_lost files_completed directories_completed
55
+ target_rate_kbps min_rate_kbps calc_rate_kbps network_delay_usec error_code error_desc
56
+ ].freeze
57
+ FILE_FIELDS = %w[id path start_time_usec elapsed_usec error_code error_desc size type checksum_type checksum start_byte bytes_written session_id].freeze
58
+ # Node API session `source_statistics` field → transferd session field
59
+ SOURCE_STATISTICS = {
60
+ 'args_scan_attempted' => 'arg_scans_attempted',
61
+ 'args_scan_completed' => 'arg_scans_completed',
62
+ 'paths_scan_attempted' => 'source_paths_scan_attempted',
63
+ 'paths_scan_failed' => 'source_paths_scan_failed',
64
+ 'paths_scan_excluded' => 'source_paths_scan_excluded',
65
+ 'files_scan_completed' => 'source_paths_scan_completed',
66
+ 'dirs_scan_completed' => 'dir_scans_completed',
67
+ 'dirs_xfer_attempted' => 'dir_creates_attempted',
68
+ 'dirs_xfer_fail' => 'dir_creates_failed',
69
+ 'files_xfer_attempted' => 'transfers_attempted',
70
+ 'files_xfer_fail' => 'transfers_failed',
71
+ 'files_xfer_noxfer' => 'transfers_skipped'
72
+ }.freeze
73
+ # Node API `precalc` field → transferd session field
74
+ PRECALC = {
75
+ 'bytes_expected' => 'pre_transfer_bytes',
76
+ 'files_expected' => 'pre_transfer_files',
77
+ 'directories_expected' => 'pre_transfer_dirs',
78
+ 'files_special' => 'pre_transfer_special'
79
+ }.freeze
80
+ # transferd fills fields `*TimeUsec` (except `elapsedUsec`) with milliseconds: values below are not microseconds
81
+ MAX_MSEC = 10**14
82
+ # Max wait for the first event of a new transfer
83
+ START_TIMEOUT_SEC = 10
84
+ # `File.ftype` → Node API item type, others are unchanged
85
+ FILE_TYPES = {'link' => 'symbolic_link'}.freeze
86
+ # Node API node information not provided by transferd
87
+ # The emulator has no access key, AEJ, watch folder, sync, file id API (gen4), `files/page` or file operations
88
+ INFO_STATIC = {
89
+ 'aej_status' => 'disconnected',
90
+ 'async_reporting' => 'no',
91
+ 'transfer_activity_reporting' => 'no',
92
+ 'acls' => [],
93
+ 'access_key_configuration_capabilities' => {'transfer' => [], 'server' => []},
94
+ 'capabilities' => [
95
+ {'name' => 'sync', 'value' => false},
96
+ {'name' => 'watchfolder', 'value' => false},
97
+ {'name' => 'symbolic_links', 'value' => false},
98
+ {'name' => 'move_file', 'value' => false},
99
+ {'name' => 'move_directory', 'value' => false},
100
+ {'name' => 'filelock', 'value' => false},
101
+ {'name' => 'ssh_fingerprint', 'value' => false},
102
+ {'name' => 'page', 'value' => false},
103
+ {'name' => 'auto_delete', 'value' => false}
104
+ ],
105
+ 'settings' => [
106
+ {'name' => 'content_protection_required', 'value' => false},
107
+ {'name' => 'content_protection_strong_pass_required', 'value' => false},
108
+ {'name' => 'filelock_restriction', 'value' => 'none'},
109
+ {'name' => 'ssh_fingerprint', 'value' => nil},
110
+ {'name' => 'wss_enabled', 'value' => false},
111
+ {'name' => 'wss_port', 'value' => 443}
112
+ ]
113
+ }.freeze
114
+ private_constant :STATUS, :TERMINAL, :ACTIVE, :SESSION_STATUS, :FILE_STATUS,
115
+ :TRANSFER_OVERRIDES, :SESSION_OVERRIDES, :FILE_OVERRIDES, :TRANSFER_FIELDS, :SESSION_FIELDS, :FILE_FIELDS,
116
+ :SOURCE_STATISTICS, :PRECALC, :MAX_MSEC, :START_TIMEOUT_SEC, :FILE_TYPES, :INFO_STATIC
117
+
118
+ class << self
119
+ # Convert a transferd transfer status to a Node API status
120
+ # @param status [Symbol] transferd `TransferStatus`
121
+ # @return [String] Node API transfer status
122
+ def node_status(status)
123
+ STATUS.fetch(status, 'waiting')
124
+ end
125
+
126
+ # Convert a transferd message to a hash with Node API field names
127
+ # @param message [Google::Protobuf::AbstractMessage] transferd message
128
+ # @param overrides [Hash] field name → Node API name (`nil`: ignored)
129
+ # @return [Hash] all fields (including default values), keys in snake case, time stamps in microseconds
130
+ def message_to_hash(message, overrides)
131
+ message.class.descriptor.each_with_object({}) do |field, hash|
132
+ key = overrides.fetch(field.name) { field.name.capital_to_snake }
133
+ next if key.nil?
134
+ value = message[field.name]
135
+ value *= 1000 if key.end_with?('_time_usec') && value.positive? && value < MAX_MSEC
136
+ hash[key] = value
137
+ end
138
+ end
139
+
140
+ # Update a store entry with a transferd event
141
+ # @param entry [Hash] store entry
142
+ # @param response [Transferd::Api::TransferResponse] transferd event
143
+ def update_entry(entry, response)
144
+ entry[:status] = response.status
145
+ entry[:info] = response.transferInfo unless response.transferInfo.nil?
146
+ session = response.sessionInfo
147
+ entry[:sessions][session.sessionId] = session unless session.nil? || session.sessionId.empty?
148
+ # event ARG_STOP has a file without id
149
+ file = response.fileInfo
150
+ entry[:files][file.fileId] = file unless file.nil? || file.fileId.empty?
151
+ entry[:error] = response.error.description unless response.error.nil? || response.error.description.empty?
152
+ # session information keeps the initial rates, the ascp management message has the current ones
153
+ entry[:rates][session.sessionId] = management_rates(response.message) if response.transferEvent.eql?(:RATE_MODIFICATION) && entry[:sessions].key?(session&.sessionId)
154
+ end
155
+
156
+ # Build a Node API transfer from a store entry
157
+ # @param id [String] transfer id
158
+ # @param entry [Hash] store entry
159
+ # @param node_id [String] node id of the emulator
160
+ # @return [Hash] Node API transfer (`transferResponseSessionSpec`)
161
+ def transfer_to_node(id, entry, node_id: '')
162
+ info = message_to_hash(entry[:info] || transferd_agent_class.empty_message(:transfer_info), TRANSFER_OVERRIDES)
163
+ terminal = TERMINAL.include?(entry[:status])
164
+ retry_timeout = xfer_retry(entry[:start_spec])
165
+ sessions = entry[:sessions].map { |session_id, session| session_to_node(session, retry_timeout: retry_timeout, node_id: node_id).merge(entry[:rates].fetch(session_id, {})) }
166
+ error_desc = info['error_desc'].strip
167
+ error_desc = entry[:error].to_s if error_desc.empty?
168
+ precalc = PRECALC.keys.to_h { |field| [field, sessions.sum { |session| session['precalc'][field] }] }
169
+ info.slice(*TRANSFER_FIELDS).merge(
170
+ 'id' => id,
171
+ 'status' => node_status(entry[:status]),
172
+ 'start_spec' => entry[:start_spec],
173
+ 'sessions' => sessions,
174
+ # transferd does not provide the start time of the transfer
175
+ 'start_time_usec' => sessions.map { |session| session['start_time_usec'] }.select(&:positive?).min || 0,
176
+ 'end_time_usec' => terminal ? info['end_time_usec'] : 0,
177
+ 'error_code' => info['error_code'].to_i,
178
+ 'error_desc' => error_desc,
179
+ 'precalc' => precalc.merge(
180
+ 'enabled' => sessions.any? { |session| session['precalc']['enabled'] },
181
+ 'status' => precalc_status(precalc['bytes_expected'], terminal)
182
+ ),
183
+ 'files' => entry[:files].values.map { |file| file_to_node(file) }
184
+ )
185
+ end
186
+
187
+ # Convert a transferd session to a Node API session
188
+ # @param session [Transferd::Api::SessionTransferInformation]
189
+ # @param retry_timeout [Integer] from the transfer spec
190
+ # @param node_id [String] node id of the emulator
191
+ # @return [Hash] Node API session (`transferResponseSessions`)
192
+ def session_to_node(session, retry_timeout: 0, node_id: '')
193
+ source = message_to_hash(session, SESSION_OVERRIDES)
194
+ status = session.status.downcase
195
+ status = SESSION_STATUS.fetch(status, status)
196
+ result = source.slice(*SESSION_FIELDS)
197
+ # transferd provides the address of the remote side only: the server
198
+ result['server_ip_address'] = source['remote_address'] if result['server_ip_address'].empty?
199
+ # transferd provides the node id of the remote side only: the local side is the emulator
200
+ result['client_node_id'] = node_id if result['client_node_id'].empty?
201
+ precalc = PRECALC.transform_values { |field| source[field] }
202
+ result.merge(
203
+ 'status' => status,
204
+ 'retry_count' => 0,
205
+ 'retry_timeout' => retry_timeout,
206
+ 'stalled' => false,
207
+ 'avg_rate_kbps' => source['elapsed_usec'].positive? ? (source['bytes_transferred'] * 8000.0 / source['elapsed_usec']).round(2) : 0,
208
+ 'source_statistics' => SOURCE_STATISTICS.transform_values { |field| source[field] },
209
+ 'precalc' => precalc.merge(
210
+ 'enabled' => session.precalc.casecmp?('yes'),
211
+ 'status' => precalc_status(precalc['bytes_expected'], !ACTIVE.include?(status))
212
+ )
213
+ )
214
+ end
215
+
216
+ # Convert a transferd file to a Node API file
217
+ # @param file [Transferd::Api::FileTransferInformation]
218
+ # @return [Hash] Node API file (`fileMetadata`)
219
+ def file_to_node(file)
220
+ result = message_to_hash(file, FILE_OVERRIDES).slice(*FILE_FIELDS)
221
+ status = file.status.downcase
222
+ result['status'] = FILE_STATUS.fetch(status, status)
223
+ terminal = !result['status'].eql?('running') && result['start_time_usec'].positive?
224
+ result['end_time_usec'] = terminal ? result['start_time_usec'] + result['elapsed_usec'] : 0
225
+ result
226
+ end
227
+
228
+ # Build Node API node information from transferd instance information
229
+ # @param info [Transferd::Api::InstanceInfo]
230
+ # @param node_id [String] node id of the emulator
231
+ # @param cluster_id [String] cluster id of the emulator
232
+ # @param docroot [String] real path of the docroot
233
+ # @param transfer_user [String] system user executing transfers
234
+ # @return [Hash] Node API node information (`info-get-200`)
235
+ def info_to_node(info, node_id:, cluster_id:, docroot:, transfer_user:)
236
+ ascp = info.asperaInfo.find { |binary| binary.asperaBinary.eql?('ascp') } || transferd_agent_class.empty_message(:aspera_info)
237
+ license = info.licenseInfo || transferd_agent_class.empty_message(:license_info)
238
+ {
239
+ 'application' => 'node',
240
+ # without build id
241
+ 'version' => ascp.asperaVersion.sub(/ .*$/, ''),
242
+ 'current_time' => Time.now.utc.iso8601(0),
243
+ 'license_expiration_date' => license.license[%r{<expiration_date>([^<]*)</expiration_date>}, 1].to_s,
244
+ 'license_max_rate' => license.maxRate,
245
+ 'os' => ascp.operatingSystem,
246
+ 'node_id' => node_id,
247
+ 'cluster_id' => cluster_id,
248
+ 'transfer_user' => transfer_user,
249
+ 'docroot' => "file:///#{docroot}"
250
+ }.merge(INFO_STATIC)
251
+ end
252
+
253
+ private
254
+
255
+ # The transferd agent is resolved when needed, so that the bundle `node` does not depend on the bundle `transferd`.
256
+ # Resolved once, then reused.
257
+ # @param refresh [Boolean] true to resolve again (when an emulator starts), so that an unavailable bundle is always detected then
258
+ # @return [Class] class of the agent `transferd`
259
+ # @raise [BundleRegistry::Unavailable] if the bundle `transferd` is unavailable
260
+ def transferd_agent_class(refresh: false)
261
+ @transferd_agent_class = nil if refresh
262
+ @transferd_agent_class ||= Aspera::Agent::Factory.instance.agent_class(:transferd)
263
+ end
264
+
265
+ # Extract the current rates from an ascp management message
266
+ # @param message [String] ascp management message of event `RATE_MODIFICATION` (JSON)
267
+ # @return [Hash] Node API session rates found in the message
268
+ def management_rates(message)
269
+ management = JSON.parse(message)
270
+ {'target_rate_kbps' => management['Rate'], 'min_rate_kbps' => management['MinRate']}.compact.transform_values(&:to_i)
271
+ rescue JSON::ParserError
272
+ {}
273
+ end
274
+
275
+ # Compute the status of the pre-calculation of the transfer size
276
+ # @param bytes_expected [Integer] size of the transfer, 0 if not known yet
277
+ # @param terminal [Boolean] `true` if the transfer or session has ended
278
+ # @return [String] `ready` when the size is known, else `pending`
279
+ def precalc_status(bytes_expected, terminal)
280
+ bytes_expected.positive? || terminal ? 'ready' : 'pending'
281
+ end
282
+
283
+ # Get the retry timeout from the tags of the transfer spec
284
+ # @param start_spec [Hash] transfer spec
285
+ # @return [Integer] retry timeout set by the agent `node`, or 0
286
+ def xfer_retry(start_spec)
287
+ reserved = start_spec['tags'][Aspera::Transfer::Spec::TAG_RESERVED] if start_spec['tags'].is_a?(Hash)
288
+ reserved.is_a?(Hash) ? reserved['xfer_retry'].to_i : 0
289
+ end
290
+ end
291
+
292
+ # Create an emulator, start a transferd daemon if no client is given
293
+ # @param docroot [String, nil] folder of the node files, default: current folder
294
+ # @param transfer_client [Transferd::Api::TransferService::Stub, nil] gRPC client (wrapped by the agent `transferd`), default: start a transferd daemon
295
+ # @param retention_sec [Integer] time a transfer is kept after it ended (CLI default in schema)
296
+ def initialize(retention_sec:, docroot: nil, transfer_client: nil)
297
+ Aspera.assert(retention_sec.is_a?(Integer) && retention_sec.positive?) { "retention_sec must be a positive integer: #{retention_sec.inspect}" }
298
+ # paths of browse and local paths of transfers are relative to it
299
+ @docroot = File.realpath(docroot || Dir.pwd)
300
+ # the daemon is stopped at exit by the agent
301
+ agent_class = self.class.send(:transferd_agent_class, refresh: true)
302
+ @transfer_client =
303
+ if transfer_client.nil?
304
+ Aspera::Agent::Factory.instance.create(:transferd, {}).client
305
+ else
306
+ agent_class.wrap_client(transfer_client)
307
+ end
308
+ @retention_sec = retention_sec
309
+ # transfer id → store entry: `start_spec` (secrets hidden), last `status`, last `info`, `sessions` by id, `files` by id, current `rates` by session id, `error`,
310
+ # `ended` (monotonic time of the end), accessed with `store`
311
+ @transfers = {}
312
+ # WEBrick serves each request in a thread, monitoring runs in threads
313
+ @mutex = Mutex.new
314
+ # identifiers of the simulated node, in node information and in sessions
315
+ @node_id = SecureRandom.uuid
316
+ @cluster_id = SecureRandom.uuid
317
+ # transferd runs as the user of the emulator
318
+ @transfer_user = Etc.getpwuid(::Process.euid)&.name || Etc.getlogin.to_s
319
+ end
320
+
321
+ # Get the node information
322
+ # @return [Hash] Node API node information, from transferd
323
+ def info
324
+ response = @transfer_client.instance_info
325
+ Log.dump(:get_info_response, response.to_h, level: :trace2)
326
+ Aspera.assert(response.error.nil? || response.error.description.empty?, type: RuntimeError) { response.error.description }
327
+ self.class.info_to_node(response.info || self.class.send(:transferd_agent_class).empty_message(:instance_info), node_id: @node_id, cluster_id: @cluster_id, docroot: @docroot, transfer_user: @transfer_user)
328
+ end
329
+
330
+ # List a folder of the docroot
331
+ # @param path [String] folder to list, relative to the docroot
332
+ # @param skip [Integer] number of items to skip (paging)
333
+ # @param count [Integer] max number of items returned (paging)
334
+ # @return [Hash] Node API folder content, paths relative to the docroot
335
+ def browse(path, skip: 0, count: nil)
336
+ folder_path = real_path(path)
337
+ # symbolic links shall not lead out of the docroot
338
+ Aspera.assert(in_docroot?(File.realpath(folder_path))) { "Path outside docroot: #{path}" }
339
+ Aspera.assert(File.directory?(folder_path)) { "Not a folder: #{path}" }
340
+ folder_virtual = virtual_path(folder_path)
341
+ # stable order for paging: only the items of the page are read
342
+ names = Dir.children(folder_path).sort
343
+ items = names.drop(skip).first(count || names.length).map do |name|
344
+ item_path = File.join(folder_path, name)
345
+ # a symbolic link is not followed
346
+ item = item_info(item_path, File.join(folder_virtual, name), File.lstat(item_path))
347
+ case item['type']
348
+ when 'file' then item['partial_file'] = false
349
+ when 'symbolic_link' then item['target'] = link_target(item_path)
350
+ when 'unknown' then item['note'] = 'File type could not be determined'
351
+ end
352
+ item
353
+ end
354
+ {
355
+ 'self' => item_info(folder_path, folder_virtual, File.stat(folder_path)),
356
+ 'items' => items,
357
+ 'item_count' => items.length,
358
+ 'total_count' => names.length
359
+ }
360
+ end
361
+
362
+ # Start a transfer, and monitor it in a thread until terminated
363
+ # @param transfer_spec [Hash] transfer spec, local paths relative to the docroot (modified)
364
+ # @return [String] transfer id
365
+ def start(transfer_spec)
366
+ Aspera::Transfer::Spec.fix_transferd_resume_policy(transfer_spec)
367
+ # copy without secrets, returned in transfer `start_spec`
368
+ start_spec = Secret::Hider.instance.hidden_copy(transfer_spec)
369
+ Log.dump(:start_spec, start_spec)
370
+ request = apply_docroot(transfer_spec).to_json
371
+ first_event = Thread::Queue.new
372
+ Thread.new { monitor(request, start_spec, first_event) }
373
+ result = first_event.pop(timeout: START_TIMEOUT_SEC)
374
+ raise Aspera::Transfer::Error, "No event from transferd after #{START_TIMEOUT_SEC}s" if result.nil?
375
+ raise result if result.is_a?(Exception)
376
+ return result
377
+ end
378
+
379
+ # Get a transfer started by the emulator
380
+ # @param id [String] transfer id
381
+ # @return [Hash, nil] Node API transfer, `nil` if unknown
382
+ def transfer(id)
383
+ entry = store do |transfers|
384
+ found = transfers[id]
385
+ found&.merge(sessions: found[:sessions].dup, files: found[:files].dup, rates: found[:rates].dup)
386
+ end
387
+ return if entry.nil?
388
+ result = self.class.transfer_to_node(id, entry, node_id: @node_id)
389
+ # transferd gives real paths of local files
390
+ result['files'].each { |file| file['path'] = virtual_path(file['path']) if in_docroot?(file['path']) }
391
+ result
392
+ end
393
+
394
+ # List the transfers started by the emulator
395
+ # @param active_only [Boolean, nil] `true`: only waiting or running, `false`: only terminated, `nil`: all
396
+ # @param direction [String, nil] `send` or `receive`
397
+ # @param count [Integer, nil] max number of transfers, oldest first
398
+ # @return [Array<Hash>] Node API transfers
399
+ def transfers(active_only: nil, direction: nil, count: nil)
400
+ # a transfer may expire between the two calls
401
+ result = store(&:keys).filter_map { |id| transfer(id) }
402
+ result.select! { |transfer| ACTIVE.include?(transfer['status']).eql?(active_only) } unless active_only.nil?
403
+ result.select! { |transfer| transfer['start_spec']['direction'].eql?(direction) } unless direction.nil?
404
+ count.nil? ? result : result.first(count)
405
+ end
406
+
407
+ # Stop a transfer: its status becomes `canceled` when transferd notifies it
408
+ # @param id [String] transfer id
409
+ # @return [Boolean] `false` if unknown
410
+ def cancel(id)
411
+ return false unless known?(id)
412
+ response = @transfer_client.stop(id)
413
+ Log.dump(:stop_response, response.to_h, level: :trace2)
414
+ result = response.stopResult.find { |info| info.transferId.eql?(id) }
415
+ Aspera.assert(result&.stopped, type: Aspera::Transfer::Error) { result&.error&.description || 'Transfer not stopped by transferd' }
416
+ true
417
+ end
418
+
419
+ # Modify the rates or the policy of a transfer
420
+ # @param id [String] transfer id
421
+ # @param changes [Hash] new values of transfer spec fields: `target_rate_kbps`, `min_rate_kbps`, `rate_policy`
422
+ # @return [Boolean] `false` if unknown
423
+ def modify(id, changes)
424
+ return false unless known?(id)
425
+ response = @transfer_client.modify(id, changes.to_json)
426
+ Log.dump(:modify_response, response.to_h, level: :trace2)
427
+ Aspera.assert(response.error.nil? || response.error.description.empty?, type: Aspera::Transfer::Error) { response.error.description }
428
+ true
429
+ end
430
+
431
+ private
432
+
433
+ # Check if a transfer is known
434
+ # @param id [String] transfer id
435
+ # @return [Boolean] `true` if the transfer was started by the emulator
436
+ def known?(id)
437
+ store { |transfers| transfers.key?(id) }
438
+ end
439
+
440
+ # Lock the store, and remove the transfers ended for longer than the retention time
441
+ # @yieldparam transfers [Hash] transfer id → store entry
442
+ # @return [Object] result of the block
443
+ def store
444
+ @mutex.synchronize do
445
+ now = monotonic_time
446
+ @transfers.delete_if { |_, entry| entry.key?(:ended) && now - entry[:ended] >= @retention_sec }
447
+ yield(@transfers)
448
+ end
449
+ end
450
+
451
+ # @return [Float] current time in seconds, for durations
452
+ def monotonic_time
453
+ ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
454
+ end
455
+
456
+ # Convert a Node API path to a real path
457
+ # @param path [String] path relative to the docroot, leading `/` optional
458
+ # @return [String] real path, within the docroot
459
+ def real_path(path)
460
+ # `./` prevents expansion of `~`
461
+ real = File.expand_path("./#{path.to_s.sub(%r{\A/+}, '')}", @docroot)
462
+ # symbolic links shall not lead out of the docroot
463
+ resolved = resolved_path(real) if in_docroot?(real)
464
+ Aspera.assert(!resolved.nil? && in_docroot?(resolved)) { "Path outside docroot: #{path}" }
465
+ real
466
+ end
467
+
468
+ # Resolve symbolic links of the existing part of a path: a destination may not exist yet
469
+ # @param real [String] absolute path, without `..`, within the docroot
470
+ # @return [String, nil] real path of the longest existing part of `real`, `nil` if it is a dangling symbolic link
471
+ def resolved_path(real)
472
+ # stops at the docroot, which exists
473
+ real = File.dirname(real) until File.exist?(real) || File.symlink?(real)
474
+ File.realpath(real)
475
+ rescue Errno::ENOENT, Errno::ELOOP
476
+ nil
477
+ end
478
+
479
+ # Convert a real path to a Node API path
480
+ # @param real [String] real path within the docroot
481
+ # @return [String] path relative to the docroot, with leading `/`
482
+ def virtual_path(real)
483
+ "/#{real.delete_prefix(@docroot).delete_prefix('/')}"
484
+ end
485
+
486
+ # Check if a real path is within the docroot
487
+ # @param real [String] real path
488
+ # @return [Boolean] `true` if the path is the docroot or inside it
489
+ def in_docroot?(real)
490
+ real.eql?(@docroot) || real.start_with?(@docroot.end_with?('/') ? @docroot : "#{@docroot}/")
491
+ end
492
+
493
+ # Get the Node API fields of a folder or of an item of a folder
494
+ # @param real [String] real path within the docroot
495
+ # @param virtual [String] Node API path
496
+ # @param stat [File::Stat] information on the item
497
+ # @return [Hash] Node API fields common to a folder and its items
498
+ def item_info(real, virtual, stat)
499
+ {
500
+ 'path' => virtual,
501
+ 'basename' => File.basename(real),
502
+ 'type' => FILE_TYPES.fetch(stat.ftype, stat.ftype),
503
+ # Node API reports 0 for folders
504
+ 'size' => stat.directory? ? 0 : stat.size,
505
+ 'mtime' => stat.mtime.utc.iso8601,
506
+ 'permissions' => permissions(real)
507
+ }
508
+ end
509
+
510
+ # Get the Node API permissions of an item
511
+ # @param real [String] real path within the docroot
512
+ # @return [Array<Hash>] Node API permissions, from the access of the emulator on the item
513
+ def permissions(real)
514
+ names = []
515
+ names.push('view') if File.readable?(real)
516
+ names.push('edit') if File.writable?(real)
517
+ # the docroot itself cannot be deleted
518
+ names.push('delete') if !real.eql?(@docroot) && File.writable?(File.dirname(real))
519
+ names.map { |name| {'name' => name} }
520
+ end
521
+
522
+ # Get the Node API target of a symbolic link
523
+ # @param link [String] real path of a symbolic link within the docroot
524
+ # @return [Hash] Node API target of the link: only the content of the link if it is dangling or leads out of the docroot
525
+ def link_target(link)
526
+ target = File.realpath(link) rescue nil
527
+ unless target && in_docroot?(target)
528
+ content = File.readlink(link)
529
+ return {'path' => content, 'basename' => File.basename(content)}
530
+ end
531
+ stat = File.stat(target)
532
+ {
533
+ 'path' => virtual_path(target),
534
+ 'basename' => File.basename(target),
535
+ 'type' => File.ftype(target),
536
+ 'size' => stat.directory? ? 0 : stat.size
537
+ }
538
+ end
539
+
540
+ # Local paths of the transfer spec (sources for `send`, destination for `receive`) are relative to the docroot
541
+ # @param transfer_spec [Hash] modified: local paths are replaced with real paths
542
+ # @return [Hash] the transfer spec
543
+ def apply_docroot(transfer_spec)
544
+ receive = transfer_spec['direction'].eql?(Aspera::Transfer::Spec::DIRECTION_RECEIVE)
545
+ root_field, path_field = receive ? %w[destination_root destination] : %w[source_root source]
546
+ # a download without destination goes to the docroot
547
+ root = transfer_spec[root_field] || ('/' if receive)
548
+ if root.nil?
549
+ transfer_spec['paths']&.each { |item| item[path_field] = real_path(item[path_field]) if item.key?(path_field) }
550
+ else
551
+ transfer_spec[root_field] = real_path(root)
552
+ # paths are relative to the root: they shall not lead out of the docroot
553
+ transfer_spec['paths']&.each { |item| real_path(File.join(root, item[path_field])) if item.key?(path_field) }
554
+ end
555
+ transfer_spec
556
+ end
557
+
558
+ # Start the transfer and update the store with its events, until terminated.
559
+ # Runs in a thread.
560
+ # @param request [String] transfer spec, as JSON
561
+ # @param start_spec [Hash] transfer spec without secrets
562
+ # @param first_event [Thread::Queue] receives the transfer id, or the exception if the transfer could not start
563
+ def monitor(request, start_spec, first_event)
564
+ id = nil
565
+ @transfer_client.start_with_monitor(request) do |response|
566
+ Log.dump(:transferd_event, response.to_h, level: :trace2)
567
+ new_transfer = id.nil?
568
+ if new_transfer
569
+ Aspera.assert(!response.transferId.empty?, type: Aspera::Transfer::Error) { response.error&.description || 'No transfer id from transferd' }
570
+ id = response.transferId
571
+ end
572
+ store do |transfers|
573
+ entry = (transfers[id] ||= {start_spec: start_spec, sessions: {}, files: {}, rates: {}})
574
+ self.class.update_entry(entry, response)
575
+ # no more event, and so no more retry: retention starts
576
+ entry[:ended] = monotonic_time if TERMINAL.include?(entry[:status])
577
+ end
578
+ first_event.push(id) if new_transfer
579
+ break if TERMINAL.include?(response.status)
580
+ end
581
+ first_event.push(Aspera::Transfer::Error.new('transferd closed the stream without event')) if id.nil?
582
+ rescue StandardError => e
583
+ if id.nil?
584
+ first_event.push(e)
585
+ else
586
+ Log.log.error { "Transfer #{id}: #{e.message}" }
587
+ store { |transfers| transfers[id].merge!(status: :FAILED, error: e.message, ended: monotonic_time) }
588
+ end
589
+ end
590
+ end
591
+
592
+ # Answers a subset of the Node API, transfers are delegated to an Emulator
593
+ # a new instance is created for each request
594
+ class NodeEmulatorServlet < WEBrick::HTTPServlet::AbstractServlet
595
+ include ServletHelpers
596
+
597
+ PATH_TRANSFERS = '/ops/transfers'
598
+ PATH_ONE_TRANSFER = %r{/ops/transfers/(.+)$}
599
+ PATH_BROWSE = '/files/browse'
600
+ REALM = 'Aspera Node Emulator'
601
+ # `PUT` values of `status` that cancel the transfer (pause and resume are not supported)
602
+ CANCEL_STATUSES = %w[canceled cancelled stopped].freeze
603
+ # `PUT` fields modified by transferd
604
+ MODIFIABLE = %w[target_rate_kbps min_rate_kbps rate_policy].freeze
605
+ # HTTP methods with a JSON body
606
+ JSON_METHODS = %w[POST PUT].freeze
607
+ # Create the servlet, with optional Basic authentication
608
+ # @param server [WEBrick::HTTPServer]
609
+ # @param config [Hash] `username` and `password` (Basic authentication expected from clients, optional)
610
+ # @param simulator [Emulator]
611
+ def initialize(server, config, simulator)
612
+ super(server)
613
+ @simulator = simulator
614
+ @expected_auth = "#{config[:username]}:#{config[:password]}" unless config[:username].nil?
615
+ end
616
+
617
+ # Refuse requests of web pages, check authentication, dispatch to `do_<verb>`, and send errors in Node API format
618
+ # @param request [WEBrick::HTTPRequest]
619
+ # @param response [WEBrick::HTTPResponse]
620
+ def service(request, response)
621
+ check_request(request, json: JSON_METHODS.include?(request.request_method))
622
+ return set_error(request, response, 401, 'Invalid or missing credentials', headers: {'WWW-Authenticate' => %Q(Basic realm="#{REALM}")}) unless authorized?(request)
623
+ super
624
+ rescue WEBrick::HTTPStatus::Error => e
625
+ set_error(request, response, e.code, e.message)
626
+ rescue JSON::ParserError, AssertError, Aspera::Transfer::Error => e
627
+ set_error(request, response, 400, e.message)
628
+ rescue Errno::ENOENT => e
629
+ set_error(request, response, 404, e.message)
630
+ rescue StandardError => e
631
+ Log.log.error { "#{request.request_method} #{request.path}: #{e.class}: #{e.message}" }
632
+ set_error(request, response, 500, e.message)
633
+ end
634
+
635
+ # Start a transfer, or list a folder
636
+ # @param request [WEBrick::HTTPRequest]
637
+ # @param response [WEBrick::HTTPResponse]
638
+ def do_POST(request, response)
639
+ json =
640
+ case request.path
641
+ when PATH_TRANSFERS
642
+ @simulator.transfer(@simulator.start(JSON.parse(request.body.to_s)))
643
+ when PATH_BROWSE
644
+ req = JSON.parse(request.body.to_s)
645
+ @simulator.browse(req['path'] || '/', skip: req['skip'].to_i, count: req['count']&.to_i)
646
+ else raise WEBrick::HTTPStatus::NotFound, "Unknown path: #{request.path}"
647
+ end
648
+ set_json_response(request, response, json)
649
+ end
650
+
651
+ # Get the node information, the list of transfers, or one transfer
652
+ # @param request [WEBrick::HTTPRequest]
653
+ # @param response [WEBrick::HTTPResponse]
654
+ def do_GET(request, response)
655
+ json =
656
+ case request.path
657
+ when '/info' then @simulator.info
658
+ when PATH_TRANSFERS
659
+ @simulator.transfers(
660
+ active_only: query_boolean(request, 'active_only'),
661
+ direction: request.query['direction']&.to_s,
662
+ count: query_positive(request, 'count')
663
+ )
664
+ when PATH_ONE_TRANSFER then known_transfer(@simulator.transfer(transfer_id(request)))
665
+ else raise WEBrick::HTTPStatus::NotFound, "Unknown path: #{request.path}"
666
+ end
667
+ set_json_response(request, response, json)
668
+ end
669
+
670
+ # Modify a transfer, or cancel it with `status`
671
+ # @param request [WEBrick::HTTPRequest]
672
+ # @param response [WEBrick::HTTPResponse]
673
+ def do_PUT(request, response)
674
+ id = transfer_id(request)
675
+ changes = JSON.parse(request.body.to_s)
676
+ raise WEBrick::HTTPStatus::BadRequest, 'Body must be a JSON object' unless changes.is_a?(Hash)
677
+ status = changes.delete('status')
678
+ if status.nil?
679
+ unsupported = changes.keys - MODIFIABLE
680
+ raise WEBrick::HTTPStatus::BadRequest, "Cannot modify: #{unsupported.join(', ')}" unless unsupported.empty?
681
+ raise WEBrick::HTTPStatus::BadRequest, 'Nothing to modify' if changes.empty?
682
+ found = @simulator.modify(id, changes)
683
+ else
684
+ raise WEBrick::HTTPStatus::BadRequest, "Unsupported status: #{status}" unless CANCEL_STATUSES.include?(status)
685
+ found = @simulator.cancel(id)
686
+ end
687
+ known_transfer(found)
688
+ set_json_response(request, response, @simulator.transfer(id))
689
+ end
690
+
691
+ # Node API cancels a transfer with HTTP verb `CANCEL`
692
+ # @param request [WEBrick::HTTPRequest]
693
+ # @param response [WEBrick::HTTPResponse]
694
+ def do_CANCEL(request, response)
695
+ known_transfer(@simulator.cancel(transfer_id(request)))
696
+ response.status = 204
697
+ end
698
+
699
+ private
700
+
701
+ # Extract the transfer id from the path of the request
702
+ # @param request [WEBrick::HTTPRequest]
703
+ # @return [String] transfer id
704
+ # @raise [WEBrick::HTTPStatus::NotFound] if the path is not the one of a transfer
705
+ def transfer_id(request)
706
+ match = request.path.match(PATH_ONE_TRANSFER)
707
+ raise WEBrick::HTTPStatus::NotFound, "Unknown path: #{request.path}" if match.nil?
708
+ match[1]
709
+ end
710
+
711
+ # @param found [Object] Result of the emulator for a transfer: `nil` or `false` if unknown
712
+ # @return [Object] found
713
+ # @raise [WEBrick::HTTPStatus::NotFound] if the transfer is unknown
714
+ def known_transfer(found)
715
+ raise WEBrick::HTTPStatus::NotFound, 'Unknown transfer' unless found
716
+ found
717
+ end
718
+
719
+ # Read a boolean query parameter
720
+ # @param request [WEBrick::HTTPRequest]
721
+ # @param name [String] name of the query parameter
722
+ # @return [Boolean, nil] value, `nil` if absent
723
+ # @raise [WEBrick::HTTPStatus::BadRequest] if the value is not `true` or `false`
724
+ def query_boolean(request, name)
725
+ value = request.query[name]&.to_s
726
+ return if value.nil?
727
+ raise WEBrick::HTTPStatus::BadRequest, "Query #{name} must be true or false: #{value}" unless %w[true false].include?(value)
728
+ value.eql?('true')
729
+ end
730
+
731
+ # Read a positive integer query parameter
732
+ # @param request [WEBrick::HTTPRequest]
733
+ # @param name [String] name of the query parameter
734
+ # @return [Integer, nil] value, `nil` if absent
735
+ # @raise [WEBrick::HTTPStatus::BadRequest] if the value is not a positive integer
736
+ def query_positive(request, name)
737
+ value = request.query[name]&.to_s
738
+ return if value.nil?
739
+ number = Integer(value, exception: false)
740
+ raise WEBrick::HTTPStatus::BadRequest, "Query #{name} must be a positive integer: #{value}" unless number&.positive?
741
+ number
742
+ end
743
+
744
+ # Set error body in Node API format
745
+ # @param request [WEBrick::HTTPRequest]
746
+ # @param response [WEBrick::HTTPResponse]
747
+ # @param code [Integer] HTTP status code
748
+ # @param message [String] message for the user
749
+ # @param headers [Hash{String => String}] Other headers of the response
750
+ def set_error(request, response, code, message, headers: {})
751
+ set_json_response(request, response, {error: {code: code, reason: WEBrick::HTTPStatus.reason_phrase(code), user_message: message}}, code: code, headers: headers)
752
+ end
753
+
754
+ # Check the Basic credentials of the request
755
+ # @param request [WEBrick::HTTPRequest]
756
+ # @return [Boolean] `true` if the request has the expected Basic credentials, or if none are expected
757
+ def authorized?(request)
758
+ @expected_auth.nil? || basic_authorized?(request, @expected_auth)
759
+ end
760
+
761
+ # Set the status and the JSON body of the response
762
+ # @param request [WEBrick::HTTPRequest] for the log
763
+ # @param response [WEBrick::HTTPResponse]
764
+ # @param json [Hash, Array] body of the response
765
+ # @param code [Integer] HTTP status code
766
+ # @param headers [Hash{String => String}] Other headers of the response
767
+ def set_json_response(request, response, json, code: 200, headers: {})
768
+ json_response(response, code, json, headers: headers)
769
+ Log.dump("response for #{request.request_method} #{request.path}", json, level: :trace1)
770
+ end
771
+ end
772
+ end
773
+ end
774
+ end