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,692 @@
1
+ # frozen_string_literal: true
2
+
3
+ # SPDX-FileCopyrightText: IBM Corp.
4
+ # SPDX-License-Identifier: Apache-2.0
5
+
6
+ require 'psych'
7
+ require 'rexml/document'
8
+ require 'stringio'
9
+ require 'zlib'
10
+ require 'rubygems/package'
11
+
12
+ module Aspera
13
+ module Plugins
14
+ module Orchestrator
15
+ # Check of an Orchestrator workflow file (`.yml`) or package (`.wkf`), before import.
16
+ #
17
+ # Orchestrator 4.1.6 does not validate the graph on import (`import_workflow`, `import_with_constraints`): an invalid workflow is imported,
18
+ # then fails to publish, or at run time. These checks follow the rules of the designer (`Whiteboard#parse_workflow`).
19
+ # With the specifications of plugins (`plugins.yml` of the plugin documentation), action templates and inputs of steps are also checked:
20
+ # attributes and their values, required inputs, inputs and outputs that the plugin does not have with its template.
21
+ # Not checked: availability of plugins on the server.
22
+ #
23
+ # The interface is that of a REST operation, so that it can be replaced by a call to Orchestrator when one exists:
24
+ # - request: the fields of `import_workflow`: `file_name` (`import_file_name`) and `content` (`import_file`, bytes),
25
+ # and the specifications of plugins (`specs`), that Orchestrator would not need
26
+ # - response: a Hash (JSON compatible)
27
+ # `valid`: `true` if there is no issue with severity `error`
28
+ # `file_name`: name of the checked file
29
+ # `issues`: list of Hash
30
+ # `severity`: `error` (the workflow will not import, publish or run correctly) or `warning`
31
+ # `code`: stable identifier of the rule, for programs, e.g. `graph.step_orphan`
32
+ # `file`: file of the package where the issue is (absent for a single `.yml` file)
33
+ # `path`: where in the file, e.g. `graph/Step[Say hello]`
34
+ # `message`: description for humans
35
+ #
36
+ # The file is parsed without instantiating Ruby objects.
37
+ class WorkflowChecker
38
+ ERROR = 'error'
39
+ WARNING = 'warning'
40
+ # Columns of tables `workflows` and `whiteboards` (Orchestrator 4.1.6), and attributes ignored by the import
41
+ WORKFLOW_ATTRIBUTES = %w[
42
+ id name portable_id created_by folder_id generated_from revision_id label run_as source_revision comments description tags templates
43
+ max_running cleanup_after_days purge_after_days user_lock locked_by created_at updated_at global_variables hide_workflow
44
+ ].freeze
45
+ WHITEBOARD_ATTRIBUTES = %w[id created_by revision_id workflow_id error_free revisions_log xml_export created_at updated_at].freeze
46
+ VALUE_TYPES = %w[string int float flag date array hash object pwd attachment].freeze
47
+ # Element 6 (plugin versions) is informational: Orchestrator 4.1.6 only reads elements 1 to 5
48
+ ELEMENT_COUNTS = [5, 6].freeze
49
+ TRUE_VALUES = %w[true 1 t].freeze
50
+ # SimpleParameterLookup: separator of the columns of the table, input that returns the table indexed by a column
51
+ LOOKUP_DELIMITER = ':::'
52
+ LOOKUP_INDEX_INPUT = 'KeyForTableIndexing'
53
+ UNNAMED = ['', 'undefined', 'null'].freeze
54
+ SUCCESS_STATUSES = %w[complete true].freeze
55
+ BOOLEAN_TEXT = %w[true false].freeze
56
+ STEP_CHILDREN = %w[Inputs Outputs].freeze
57
+ PARAMETER_MAPPINGS = %w[parameter global].freeze
58
+ # Columns of every action template, besides those of the plugin
59
+ TEMPLATE_COLUMNS = %w[id name comments created_at updated_at].freeze
60
+ # Texts that the database layer (ActiveRecord) reads as false
61
+ FALSE_VALUES = %w[false 0 f off].freeze
62
+ INTEGER_TYPES = %w[integer bigint].freeze
63
+ # Template attribute with Ruby code that computes the inputs or the outputs: they are then unknown
64
+ SPEC_CODE = {inputs: 'inputs_spec_code', outputs: 'outputs_spec_code'}.freeze
65
+ # Note of a plugin specification: some inputs or outputs come from the template, other than through declared lists
66
+ PARTLY_DEFINED = {inputs: /\AInputs are partly defined/, outputs: /\AOutputs are partly defined/}.freeze
67
+ # Placeholder that creates a required input: <%= variable %>
68
+ PLACEHOLDER = /<%=\s*([A-Za-z_]\w*)\s*%>/
69
+ # Value of a template attribute that is a single name (of an input or an output): no line break, no structure (type map, list)
70
+ SINGLE_NAME = /\A[^\r\n{}\[\],:=]+\z/
71
+ # Column separator of a table (attribute `parameters_associations` of `SimpleParameterLookup`), whose first line holds the column names
72
+ TABLE_SEPARATOR = ':::'
73
+ # Elements of a step that a `Map_to` of type `output` gives as attributes (in lower case)
74
+ STEP_IDENTITY = %w[Step_name Step_type Action_id].freeze
75
+ # Maximum size of the entries of a package once decompressed: a small package can decompress to gigabytes (decompression bomb)
76
+ PACKAGE_MAX_SIZE = 256 * 1024 * 1024
77
+ private_constant :PACKAGE_MAX_SIZE
78
+ private_constant :WORKFLOW_ATTRIBUTES, :WHITEBOARD_ATTRIBUTES, :VALUE_TYPES, :ELEMENT_COUNTS, :TRUE_VALUES, :UNNAMED, :SUCCESS_STATUSES,
79
+ :BOOLEAN_TEXT, :STEP_CHILDREN, :PARAMETER_MAPPINGS, :TEMPLATE_COLUMNS, :FALSE_VALUES, :INTEGER_TYPES, :SPEC_CODE, :PARTLY_DEFINED, :PLACEHOLDER,
80
+ :STEP_IDENTITY, :SINGLE_NAME, :TABLE_SEPARATOR, :LOOKUP_DELIMITER, :LOOKUP_INDEX_INPUT
81
+
82
+ class << self
83
+ # @param file_name [String] Name of the file, ending with `yml` or `wkf`
84
+ # @param content [String] Bytes of the file
85
+ # @param specs [Hash, nil] Specifications of plugins (`plugins.yml`), to check templates and inputs of steps, or nil
86
+ # @return [Hash] Response, see class description
87
+ def check(file_name:, content:, specs: nil)
88
+ checker = new(file_name, specs)
89
+ checker.run(content)
90
+ {
91
+ 'valid' => checker.issues.none? { |issue| issue['severity'].eql?(ERROR) },
92
+ 'file_name' => file_name,
93
+ 'issues' => checker.issues
94
+ }
95
+ end
96
+ end
97
+
98
+ attr_reader :issues
99
+
100
+ # @param file_name [String] Name of the file
101
+ # @param specs [Hash, nil] Specifications of plugins: class name => attributes, inputs, outputs
102
+ def initialize(file_name, specs = nil)
103
+ @file_name = file_name
104
+ @specs = specs
105
+ @issues = []
106
+ # file of the package being checked
107
+ @member = nil
108
+ # attributes of the action templates of the workflow being checked, by key <StepType>__<N>
109
+ @template_attributes = {}
110
+ end
111
+
112
+ # @param content [String] Bytes of the file
113
+ def run(content)
114
+ case File.extname(@file_name)
115
+ when '.yml' then check_yaml(content)
116
+ when '.wkf' then check_package(content)
117
+ else add(ERROR, 'file.extension', 'file', "extension must be yml or wkf: #{@file_name}")
118
+ end
119
+ end
120
+
121
+ private
122
+
123
+ def add(severity, code, path, message)
124
+ @issues.push({'severity' => severity, 'code' => code, 'file' => @member, 'path' => path, 'message' => message}.compact)
125
+ end
126
+
127
+ # @param content [String] Bytes of a `.wkf` file: gzipped tar with a manifest (list of files, the first one is the main workflow)
128
+ def check_package(content)
129
+ files = {}
130
+ size = 0
131
+ begin
132
+ Zlib::GzipReader.wrap(StringIO.new(content)) do |gzip|
133
+ Gem::Package::TarReader.new(gzip) do |tar|
134
+ tar.each do |entry|
135
+ # Size declared in the header: checked before the entry is decompressed (read, or skipped)
136
+ size += entry.header.size
137
+ return add(ERROR, 'package.too_large', 'file', "package is too large when decompressed: more than #{PACKAGE_MAX_SIZE} bytes") if size > PACKAGE_MAX_SIZE
138
+ files[entry.full_name] = entry.read if entry.file?
139
+ end
140
+ end
141
+ end
142
+ rescue Zlib::Error, Gem::Package::Error => e
143
+ return add(ERROR, 'package.archive', 'file', "not a gzipped tar archive: #{e.message}")
144
+ end
145
+ manifest = files.keys.find { |name| File.basename(name).match?(/\AWorkflow_.*\.txt\z/) }
146
+ return add(ERROR, 'package.manifest_missing', 'file', 'no manifest file (Workflow_*.txt) in package') if manifest.nil?
147
+ list = Psych.safe_load(files[manifest])
148
+ return add(ERROR, 'package.manifest_invalid', manifest, 'manifest must be a list of file names') unless list.is_a?(Array) && !list.empty? && list.all?(String)
149
+ list.each_with_index do |name, index|
150
+ member = files.find { |key, _| File.basename(key).eql?(File.basename(name)) }&.last
151
+ next add(ERROR, 'package.file_missing', manifest, "file listed but not in package: #{name}") if member.nil?
152
+ # sub-workflows are checked as the main workflow; remote nodes and nested packages are not
153
+ next unless name.end_with?('.yml') && (index.zero? || File.basename(name).start_with?('Workflow_'))
154
+ @member = File.basename(name)
155
+ check_yaml(member)
156
+ end
157
+ @member = nil
158
+ rescue Psych::Exception => e
159
+ add(ERROR, 'package.manifest_invalid', manifest.to_s, "invalid manifest: #{e.message}")
160
+ end
161
+
162
+ # @param content [String] Bytes of a workflow file
163
+ def check_yaml(content)
164
+ text = content.dup.force_encoding(Encoding::UTF_8)
165
+ return add(ERROR, 'yaml.encoding', 'file', 'file is not UTF-8') unless text.valid_encoding?
166
+ begin
167
+ root = Psych.parse_stream(text).children.first&.root
168
+ rescue Psych::SyntaxError => e
169
+ return add(ERROR, 'yaml.invalid', 'file', "invalid YAML: #{e.message}")
170
+ end
171
+ return add(ERROR, 'yaml.empty', 'file', 'empty file') if root.nil?
172
+ return add(ERROR, 'yaml.not_list', 'file', 'a workflow file is a YAML list of elements') unless root.is_a?(Psych::Nodes::Sequence)
173
+ @plain = text.lines.none? { |line| line.match?(/^ *concise_attributes:/) }
174
+ @template_attributes = {}
175
+ check_layout(text) if @plain
176
+ elements = root.children
177
+ add(ERROR, 'yaml.element_count', 'file', "expected #{ELEMENT_COUNTS.join(' or ')} elements (workflow, whiteboard, templates, dependencies, packed dependencies, plugin versions), found #{elements.size}") unless ELEMENT_COUNTS.include?(elements.size)
178
+ return if elements.size < 2
179
+ workflow = check_attributes(elements[0], 'Workflow', 'workflow', WORKFLOW_ATTRIBUTES)
180
+ add(ERROR, 'workflow.name_missing', 'workflow', 'attribute name is missing') if workflow['name'].to_s.strip.empty?
181
+ whiteboard = check_attributes(elements[1], 'Whiteboard', 'whiteboard', WHITEBOARD_ATTRIBUTES)
182
+ add(ERROR, 'whiteboard.error_free', 'whiteboard', 'error_free is not true: the workflow cannot be published') unless TRUE_VALUES.include?(whiteboard['error_free'].to_s.downcase)
183
+ templates = elements.size > 2 ? check_templates(elements[2]) : []
184
+ elements[3..4]&.each_with_index do |element, index|
185
+ add(ERROR, 'dependencies.not_map', "element #{index + 4}", 'must be a map') unless element.is_a?(Psych::Nodes::Mapping)
186
+ end
187
+ if whiteboard['xml_export'].to_s.strip.empty?
188
+ add(ERROR, 'whiteboard.xml_missing', 'whiteboard', 'attribute xml_export is missing')
189
+ else
190
+ check_graph(whiteboard['xml_export'], templates)
191
+ end
192
+ check_dependencies(elements[3], elements[4]) if elements.size > 4
193
+ end
194
+
195
+ # Plain format is converted by Orchestrator line by line: each element starts with a dash at column 0
196
+ def check_layout(text)
197
+ count = text.lines.count { |line| line.match?(/^- /) }
198
+ return if ELEMENT_COUNTS.include?(count)
199
+ add(ERROR, 'yaml.layout', 'file', "plain format: each element must start with '- ' at column 0 (#{ELEMENT_COUNTS.join(' or ')} expected), found #{count} such lines")
200
+ end
201
+
202
+ # @return [Hash{String=>Psych::Nodes::Node}] Keys and values of a mapping
203
+ def pairs(node)
204
+ return {} unless node.is_a?(Psych::Nodes::Mapping)
205
+ node.children.each_slice(2).to_h { |key, value| [key.respond_to?(:value) ? key.value : nil, value] }
206
+ end
207
+
208
+ def scalar(node)
209
+ node.is_a?(Psych::Nodes::Scalar) ? node.value : nil
210
+ end
211
+
212
+ # @return [Hash{String=>String}] Attributes of a workflow, a whiteboard or a template, in plain or Rails format
213
+ def attributes(node)
214
+ content = pairs(node)
215
+ if content.key?('concise_attributes')
216
+ content['concise_attributes'].children.to_h do |item|
217
+ item_pairs = pairs(item)
218
+ [scalar(item_pairs['name']), scalar(item_pairs['value_before_type_cast'])]
219
+ end
220
+ else
221
+ inner = content['attributes']
222
+ (inner.is_a?(Psych::Nodes::Mapping) ? pairs(inner) : content.except('attributes', 'new_record', 'active_record_yaml_version')).transform_values { |value| scalar(value) }
223
+ end
224
+ end
225
+
226
+ def check_attributes(node, klass, path, known)
227
+ unless node.is_a?(Psych::Nodes::Mapping) && node.tag.eql?("!ruby/object:#{klass}")
228
+ add(ERROR, "#{path}.type", path, "element must be a map tagged !ruby/object:#{klass}")
229
+ return {}
230
+ end
231
+ attributes(node).tap do |attrs|
232
+ attrs.each_key { |name| add(WARNING, "#{path}.attribute_unknown", path, "unknown attribute: #{name} (the import may fail)") unless known.include?(name) }
233
+ end
234
+ end
235
+
236
+ # @return [Array<String>] Keys of the action templates
237
+ def check_templates(node)
238
+ return [] unless node.is_a?(Psych::Nodes::Mapping)
239
+ pairs(node).filter_map do |key, template|
240
+ path = "templates/#{key}"
241
+ match = key.to_s.match(/\A(.+)__(\d+)\z/)
242
+ if match.nil?
243
+ add(ERROR, 'template.key', path, "key must be <StepType>__<N>: #{key}")
244
+ elsif !template.respond_to?(:tag) || !template.tag.eql?("!ruby/object:#{match[1]}")
245
+ add(ERROR, 'template.tag', path, "value must be tagged !ruby/object:#{match[1]}")
246
+ else
247
+ check_boolean_values(path, template) if @plain
248
+ @template_attributes[key] = attributes(template)
249
+ check_template_attributes(path, match[1], @template_attributes[key]) unless @specs.nil?
250
+ end
251
+ key
252
+ end
253
+ end
254
+
255
+ # In plain format, a blank attribute is dropped, and false is blank
256
+ def check_boolean_values(path, template)
257
+ attributes(template).each do |name, value|
258
+ add(WARNING, 'template.boolean', path, "#{name} is #{value}: write 1 or 0, false is dropped in plain format") if BOOLEAN_TEXT.include?(value)
259
+ end
260
+ end
261
+
262
+ def check_dependencies(listed, packed)
263
+ return unless listed.is_a?(Psych::Nodes::Mapping) && packed.is_a?(Psych::Nodes::Mapping)
264
+ external = pairs(listed).values.flat_map { |list| list.is_a?(Psych::Nodes::Sequence) ? list.children : [] }
265
+ return if external.empty? || !packed.children.empty?
266
+ names = external.map do |dep|
267
+ fields = pairs(dep)
268
+ "#{scalar(fields[':entity'] || fields['entity'])} #{scalar(fields[':id_value'] || fields['id_value'])}".strip
269
+ end
270
+ add(WARNING, 'dependencies.external', 'dependencies', "uses entities not included in the file, they must exist on the server: #{names.uniq.join(', ')}")
271
+ end
272
+
273
+ def text_of(element, name)
274
+ element.elements[name]&.text&.strip
275
+ end
276
+
277
+ def check_graph(xml, templates)
278
+ begin
279
+ root = REXML::Document.new(xml).root
280
+ rescue REXML::ParseException => e
281
+ return add(ERROR, 'graph.xml_invalid', 'xml_export', "invalid XML: #{e.message.lines.first&.strip}")
282
+ end
283
+ return add(ERROR, 'graph.xml_invalid', 'xml_export', 'no XML root element') if root.nil?
284
+ terminals = %w[Start End Fail Error].to_h { |name| [name, root.get_elements(name)] }
285
+ terminals.each do |name, nodes|
286
+ add(ERROR, 'graph.terminal_count', "graph/#{name}", "#{name} must be present once, found #{nodes.size}") unless nodes.size.eql?(1)
287
+ end
288
+ steps = root.get_elements('Steps/Step')
289
+ add(ERROR, 'graph.no_step', 'graph', 'at least one Step is required') if steps.empty?
290
+ ids = (terminals.values.flatten + steps).map { |node| node.attributes['id'] }
291
+ (ids.tally.select { |_, count| count > 1 }.keys + ids.compact.select(&:empty?)).each do |id|
292
+ add(ERROR, 'graph.id_not_unique', 'graph', "node id must be unique and not empty: '#{id}'")
293
+ end
294
+ check_steps(steps, templates)
295
+ closing = terminals.values_at('End', 'Fail', 'Error').flatten
296
+ (closing + steps).each { |node| check_node(node, ids) }
297
+ check_branches(closing, steps)
298
+ # starvation is computed on a graph without loop
299
+ check_starvation(terminals['Start'].first&.attributes&.[]('id'), closing, steps) unless check_loops(closing, steps)
300
+ check_parameters(root, steps)
301
+ check_routers(root)
302
+ check_lookups(steps)
303
+ check_step_interfaces(steps) unless @specs.nil?
304
+ end
305
+
306
+ # SimpleParameterLookup returns a row only if an input selects it: an input named as a column of the header of the table.
307
+ # Without one, no row matches and the step ends with Failed (No configuration match), unless it returns the array of rows
308
+ # (SimpleParameterLookup#execute). The header of a table in a file (param_file_name) is not known.
309
+ def check_lookups(steps)
310
+ steps.each do |step|
311
+ next unless text_of(step, 'Step_type').eql?('SimpleParameterLookup')
312
+ values = @template_attributes["SimpleParameterLookup__#{text_of(step, 'Action_id')}"]
313
+ next if values.nil? || blank?(values['parameters_associations']) || !blank?(values['param_file_name'])
314
+ next if TRUE_VALUES.include?(values['return_array_of_rows'].to_s.downcase)
315
+ header = values['parameters_associations'].lines.first.to_s.strip.split(LOOKUP_DELIMITER, -1).map(&:strip)
316
+ # a carried variable is also given to the step under its name
317
+ provided = step.get_elements('Inputs/Input').map { |input| input.attributes['name'] } + step.get_elements('Outputs/Carry_thru').map { |carry| carry.attributes['name'] }
318
+ next if provided.include?(LOOKUP_INDEX_INPUT) || provided.intersect?(header)
319
+ add(
320
+ ERROR, 'step.lookup_without_key', node_path(step),
321
+ "no input is mapped to a column of the table (#{header.join(', ')}): no row matches and the step ends with Failed, unless return_array_of_rows is set"
322
+ )
323
+ end
324
+ end
325
+
326
+ # Line styles of links in the designer: it writes `new <router>()` in the page to draw each link (WhiteboardsHelper#connect_xmlsteps)
327
+ ROUTERS = %w[Manhattan Bezier Null Fan].map { |name| "draw2d.#{name}ConnectionRouter" }.freeze
328
+
329
+ # Links: prerequisites of nodes and links of parameters (Parameter in Start or Step); absent router: Manhattan
330
+ def check_routers(root)
331
+ root.each_element('//Prerequisite[@router] | //Start/Parameters/Parameter[@router] | //Step/Parameters/Parameter[@router]') do |link|
332
+ router = link.attributes['router']
333
+ next if ROUTERS.include?(router)
334
+ add(
335
+ ERROR, 'graph.router', node_path(link.parent.parent),
336
+ "router '#{router}' of the link from '#{link.attributes['id']}' is not one of #{ROUTERS.join(', ')}: the designer cannot draw the workflow"
337
+ )
338
+ end
339
+ end
340
+
341
+ def node_path(node)
342
+ node.name.eql?('Step') ? "graph/Step[#{text_of(node, 'Step_name')}]" : "graph/#{node.name}"
343
+ end
344
+
345
+ def check_node(node, ids)
346
+ path = node_path(node)
347
+ factor = text_of(node, 'Synch_factor')
348
+ if factor.nil? || !factor.match?(/\A-?\d+\z/)
349
+ add(ERROR, 'graph.synch_factor', path, 'Synch_factor is missing or not an integer')
350
+ elsif factor.to_i.negative?
351
+ add(ERROR, 'graph.synch_factor_negative', path, 'negative Synch_factor is never met')
352
+ elsif factor.to_i.positive? && %w[x y].any? { |name| node.elements['Synch_factor'].attributes[name].to_s.empty? }
353
+ # the designer writes the position of the join symbol, and draws the workflow with it (WhiteboardsHelper#draw_operator)
354
+ add(WARNING, 'graph.synch_factor_position', path, 'Synch_factor is not 0 and has no attributes x and y (position of the join symbol): the designer shows an empty canvas')
355
+ end
356
+ node.get_elements('Prerequisites/Prerequisite').each do |pre|
357
+ add(ERROR, 'graph.prerequisite_unknown', path, "prerequisite refers to unknown node '#{pre.attributes['id']}'") unless ids.include?(pre.attributes['id'])
358
+ end
359
+ end
360
+
361
+ def check_steps(steps, templates)
362
+ names = []
363
+ steps.each do |step|
364
+ name = text_of(step, 'Step_name')
365
+ type = text_of(step, 'Step_type')
366
+ action_id = text_of(step, 'Action_id')
367
+ path = node_path(step)
368
+ if UNNAMED.include?(name.to_s)
369
+ add(ERROR, 'graph.step_unnamed', "graph/Step[#{step.attributes['id']}]", 'step is not named')
370
+ elsif names.include?(name)
371
+ add(ERROR, 'graph.step_name_not_unique', path, 'step name is not unique')
372
+ end
373
+ names.push(name)
374
+ if UNNAMED.include?(type.to_s)
375
+ add(ERROR, 'graph.step_type_missing', path, 'Step_type is not defined')
376
+ elsif action_id.to_s.empty?
377
+ add(ERROR, 'graph.action_id_missing', path, 'Action_id is missing')
378
+ elsif !templates.include?("#{type}__#{action_id}")
379
+ add(ERROR, 'graph.template_missing', path, "no action template #{type}__#{action_id} in element 3")
380
+ end
381
+ STEP_CHILDREN.each do |child|
382
+ add(ERROR, 'graph.step_element_missing', path, "#{child} is missing (may be empty)") if step.elements[child].nil?
383
+ end
384
+ add(ERROR, 'graph.step_orphan', path, 'no prerequisite, the step never runs (orphaned)') if step.get_elements('Prerequisites/Prerequisite').empty?
385
+ check_output_references(step, steps, path)
386
+ end
387
+ end
388
+
389
+ def check_output_references(step, steps, path)
390
+ step.get_elements('Inputs/Input/Map_to').each do |map|
391
+ next unless map.attributes['type'].eql?('output')
392
+ source = steps.find { |other| text_of(other, 'Step_name').eql?(map.attributes['step_name']) }
393
+ next unless source.nil? || !text_of(source, 'Step_type').eql?(map.attributes['step_type']) || !text_of(source, 'Action_id').eql?(map.attributes['action_id'])
394
+ add(ERROR, 'graph.output_unknown', path, "input #{map.parent.attributes['name']} refers to unknown output of step '#{map.attributes['step_name']}' (step_name, step_type, action_id must match)")
395
+ end
396
+ end
397
+
398
+ def check_branches(closing, steps)
399
+ success = ->(pre) { SUCCESS_STATUSES.include?(pre.attributes['status'].to_s.downcase) }
400
+ consumers = (closing + steps).flat_map { |node| node.get_elements('Prerequisites/Prerequisite').select(&success).map { |pre| pre.attributes['id'] } }
401
+ steps.each do |step|
402
+ next if consumers.include?(step.attributes['id'])
403
+ add(ERROR, 'graph.step_no_output', node_path(step), 'no node follows it with status Complete (step does not have output)')
404
+ end
405
+ return unless closing.all? { |node| node.get_elements('Prerequisites/Prerequisite').empty? }
406
+ add(ERROR, 'graph.no_termination', 'graph', 'workflow does not terminate: End, Fail and Error have no prerequisite')
407
+ end
408
+
409
+ # Starvation: a node that waits for exclusive conditions never starts, and the work order never ends.
410
+ # Conditions of a node: pairs [step id, status] that must all be true for the node to start.
411
+ # With Synch_factor 0 (AND), those of all its prerequisites; otherwise (OR), those common to all its prerequisites.
412
+ # A prerequisite on a step adds its status to the conditions of that step.
413
+ # A step ends with one status: two statuses of the same step in the conditions of a node are exclusive,
414
+ # for example the Complete and Failed exits of a step, or an if and an else branch joined without OR.
415
+ # Not checked: steps after an ArrayFanout (one execution per element, with different statuses).
416
+ def check_starvation(start_id, closing, steps)
417
+ nodes = (closing + steps).to_h { |node| [node.attributes['id'], node] }
418
+ fanned = steps.select do |step|
419
+ step.get_elements('Prerequisites/Prerequisite').any? { |pre| text_of(nodes[pre.attributes['id']] || step, 'Step_type').eql?('ArrayFanout') }
420
+ end.map { |step| step.attributes['id'] }
421
+ memo = {}
422
+ conditions = lambda do |id, visiting|
423
+ return [] if id.eql?(start_id) || !nodes.key?(id) || visiting.include?(id)
424
+ return memo[id] if memo.key?(id)
425
+ node = nodes[id]
426
+ branches = node.get_elements('Prerequisites/Prerequisite').map do |pre|
427
+ source = pre.attributes['id']
428
+ own = source.eql?(start_id) || fanned.include?(source) ? [] : [[source, pre.attributes['status'].to_s.downcase]]
429
+ (own + conditions.call(source, visiting + [id])).uniq
430
+ end
431
+ memo[id] = if branches.empty? then []
432
+ elsif text_of(node, 'Synch_factor').to_i.zero? then branches.reduce(:|)
433
+ else branches.reduce(:&)
434
+ end
435
+ end
436
+ exclusive = ->(list) { list.group_by(&:first).select { |_, pairs| pairs.size > 1 }.transform_values { |pairs| pairs.map(&:last) } }
437
+ nodes.each do |id, node|
438
+ conflicts = exclusive.call(conditions.call(id, []))
439
+ # report where the conflict starts, not on the nodes that follow
440
+ inherited = node.get_elements('Prerequisites/Prerequisite').flat_map { |pre| exclusive.call(conditions.call(pre.attributes['id'], [])).keys }
441
+ conflicts.except(*inherited).each do |step_id, statuses|
442
+ step_name = text_of(nodes[step_id], 'Step_name')
443
+ add(
444
+ ERROR, 'graph.starvation', node_path(node),
445
+ "never starts: it waits for step '#{step_name}' to end with #{statuses.map(&:capitalize).join(' and ')}, which are exclusive; " \
446
+ 'join exclusive branches with an OR (Synch_factor 1), otherwise the work order never ends'
447
+ )
448
+ end
449
+ end
450
+ end
451
+
452
+ # Loop: a link back to a node it comes from. A step runs once in a work order: it does not run again.
453
+ # @return [Boolean] true if a loop was found
454
+ def check_loops(closing, steps)
455
+ found = false
456
+ nodes = (closing + steps).to_h { |node| [node.attributes['id'], node] }
457
+ sources = nodes.transform_values { |node| node.get_elements('Prerequisites/Prerequisite').map { |pre| pre.attributes['id'] }.uniq & nodes.keys }
458
+ state = {}
459
+ visit = lambda do |id|
460
+ state[id] = :visiting
461
+ sources[id].each do |source|
462
+ if state[source].eql?(:visiting)
463
+ found = true
464
+ add(
465
+ ERROR, 'graph.loop', node_path(nodes[source]),
466
+ "link back to '#{text_of(nodes[id], 'Step_name') || nodes[id].name}' (loop): a step runs only once in a work order; " \
467
+ 'to repeat, use a sub-workflow with retries, or an ArrayFanout'
468
+ )
469
+ elsif state[source].nil?
470
+ visit.call(source)
471
+ end
472
+ end
473
+ state[id] = :done
474
+ end
475
+ nodes.each_key { |id| visit.call(id) if state[id].nil? }
476
+ found
477
+ end
478
+
479
+ def check_parameters(root, steps)
480
+ linked = (root.get_elements('Start/Parameters/Parameter') + steps.flat_map { |step| step.get_elements('Parameters/Parameter') }).map { |link| link.attributes['id'] }
481
+ defined = {}
482
+ root.get_elements('Parameters/Parameter').each do |parameter|
483
+ name = text_of(parameter, 'Name')
484
+ type = text_of(parameter, 'Value_type')
485
+ path = "graph/Parameter[#{name || parameter.attributes['id']}]"
486
+ add(ERROR, 'graph.parameter_name', path, 'Name is missing') if name.to_s.empty?
487
+ add(ERROR, 'graph.parameter_type', path, "Value_type must be one of #{VALUE_TYPES.join(', ')}") unless VALUE_TYPES.include?(type)
488
+ mandatory_at_runtime = text_of(parameter, 'Runtime_override').eql?('true') && !text_of(parameter, 'Runtime_optional').eql?('true')
489
+ add(WARNING, 'graph.parameter_value', path, 'Value is missing') if !mandatory_at_runtime && parameter.elements['Value'].nil?
490
+ defined[name] = parameter.attributes['id']
491
+ end
492
+ steps.each do |step|
493
+ step.get_elements('Inputs/Input/Map_to').each do |map|
494
+ next unless PARAMETER_MAPPINGS.include?(map.attributes['type'])
495
+ id = defined[map.attributes['name']]
496
+ if id.nil?
497
+ add(ERROR, 'graph.parameter_undefined', node_path(step), "input refers to undefined parameter '#{map.attributes['name']}'")
498
+ elsif !linked.include?(id)
499
+ add(ERROR, 'graph.parameter_not_linked', node_path(step), "parameter '#{map.attributes['name']}' is not linked to Start or to a step: inputs mapped to it are not created")
500
+ end
501
+ end
502
+ end
503
+ end
504
+
505
+ # --- Checks with the specifications of plugins ---
506
+
507
+ def blank?(value)
508
+ value.nil? || value.to_s.strip.empty?
509
+ end
510
+
511
+ # @param values [Hash{String=>String}] Attributes of the template
512
+ def check_template_attributes(path, type, values)
513
+ spec = @specs[type]
514
+ if spec.nil?
515
+ similar = @specs.keys.find { |name| name.casecmp?(type) }
516
+ return add(ERROR, 'template.plugin_case', path, "plugin #{type} does not exist, class names are case sensitive: #{similar}") if similar
517
+ return add(WARNING, 'template.plugin_unknown', path, "plugin #{type} is not in the specifications: its template and the inputs of its steps are not checked")
518
+ end
519
+ columns = spec['attributes'] || {}
520
+ values.each do |name, value|
521
+ attribute = columns[name]
522
+ if attribute.nil?
523
+ next if TEMPLATE_COLUMNS.include?(name)
524
+ next add(ERROR, 'template.attribute_unknown', path, "#{type} has no attribute #{name}: the import fails") if @plain
525
+ next add(WARNING, 'template.attribute_unknown', path, "#{type} has no attribute #{name}: the import may fail")
526
+ end
527
+ # a placeholder is replaced at run time
528
+ next if blank?(value) || value.include?('<%')
529
+ check_value(path, name, attribute, value)
530
+ end
531
+ end
532
+
533
+ # Values are cast by the database layer (ActiveRecord): a text that is not false is true, a text that is not a number is 0
534
+ def check_value(path, name, attribute, value)
535
+ case attribute['type']
536
+ when 'boolean'
537
+ return if (TRUE_VALUES + FALSE_VALUES).include?(value.downcase)
538
+ return add(WARNING, 'template.attribute_value', path, "#{name}: #{value} is read as true: write 1 or 0")
539
+ when *INTEGER_TYPES
540
+ return add(WARNING, 'template.attribute_value', path, "#{name}: #{value} is not an integer, it is read as #{value.to_i}") unless value.match?(/\A-?\d+\z/)
541
+ end
542
+ allowed = attribute['values']
543
+ return if allowed.nil? || allowed.map(&:to_s).include?(value)
544
+ add(ERROR, 'template.attribute_value', path, "#{name}: #{value} is not an allowed value: #{allowed.join(', ')}")
545
+ end
546
+
547
+ # Value of an attribute as the plugin sees it: typed for booleans and integers
548
+ def typed(value, type)
549
+ return value unless value.is_a?(String)
550
+ case type
551
+ when 'boolean' then !FALSE_VALUES.include?(value.downcase)
552
+ when *INTEGER_TYPES then value.to_i
553
+ else value
554
+ end
555
+ end
556
+
557
+ # Values of the attributes of a template as the plugin sees them: nil when blank
558
+ # An attribute not in the template takes its database default; in plain format, so does a blank one (and false is blank)
559
+ # @return [Hash{String=>Object}]
560
+ def effective_values(spec, values)
561
+ (spec['attributes'] || {}).to_h do |name, attribute|
562
+ value = values[name]
563
+ value = nil if blank?(value) || (@plain && value.eql?('false'))
564
+ value = attribute['default'] if value.nil? && (@plain || !values.key?(name))
565
+ [name, typed(value, attribute['type'])]
566
+ end
567
+ end
568
+
569
+ # @param conditions [Hash] `if_blank`, `if_set`, `when` and `conditional` of an input or output of the specifications
570
+ # @return [Boolean, nil] true if the conditions are met, nil if unknown
571
+ def met(conditions, values)
572
+ return if conditions['conditional']
573
+ Array(conditions['if_blank']).all? { |name| values[name].nil? } &&
574
+ Array(conditions['if_set']).all? { |name| !values[name].nil? } &&
575
+ (conditions['when'] || {}).all? do |name, condition|
576
+ value = values[name]
577
+ if condition.key?('in')
578
+ condition['in'].any? { |item| item.nil? ? value.nil? : item.to_s.eql?(value.to_s) }
579
+ else
580
+ !value.nil? && condition['not_in'].none? { |item| item.to_s.eql?(value.to_s) }
581
+ end
582
+ end
583
+ end
584
+
585
+ # @return [Array<String>] Names declared by a type map `{'name'=>'type'}` (Ruby or JSON syntax) or a list `['name']`
586
+ def declared_names(value)
587
+ text = value.strip
588
+ return text.scan(/['"]([^'"]+)['"]\s*(?:=>|:)/).flatten if text.start_with?('{')
589
+ return text.scan(/['"]([^'"]+)['"]/).flatten if text.start_with?('[')
590
+ []
591
+ end
592
+
593
+ # Names given by the value of a template attribute, for a name in angle brackets (`<attribute>`) in the specification
594
+ # @return [Array<String>, nil] The names, or `nil` if they cannot be found in the value
595
+ def names_in_value(value)
596
+ text = value.to_s.strip
597
+ return [] if text.empty?
598
+ return [text] if text.match?(SINGLE_NAME)
599
+ header = text.lines.first.strip
600
+ return header.split(TABLE_SEPARATOR).map(&:strip) if header.include?(TABLE_SEPARATOR)
601
+ nil
602
+ end
603
+
604
+ # Inputs and outputs of a step, for the attributes of its template
605
+ # @return [Hash] `:inputs` and `:outputs`: name => {`exists`, `required`} (true, false or nil if unknown),
606
+ # and `:complete`: kind => true if all inputs (or outputs) are known, so that an other one does not exist
607
+ def step_interface(spec, attributes)
608
+ values = effective_values(spec, attributes)
609
+ interface = {inputs: {}, outputs: {}, complete: {}}
610
+ %i[inputs outputs].each do |kind|
611
+ # false when names come from an attribute value whose format is not known
612
+ names_known = true
613
+ (spec[kind.to_s] || {}).each do |name, info|
614
+ exists = met(info, values)
615
+ next if exists.eql?(false)
616
+ names = [name]
617
+ # a name in angle brackets comes from the value of that attribute
618
+ if name =~ /\A<(\w+)>\z/
619
+ names = names_in_value(values[Regexp.last_match(1)])
620
+ names_known = false if names.nil?
621
+ end
622
+ required = info['required'].is_a?(Hash) ? met(info['required'], values) : info['required']
623
+ Array(names).each do |each_name|
624
+ interface[kind][each_name] = {'exists' => exists, 'required' => required.eql?('depends') ? nil : required}
625
+ end
626
+ end
627
+ declared = (spec['attributes'] || {}).values.any? { |attribute| attribute['declares'].to_s.end_with?(kind.to_s) }
628
+ partly = Array(spec['notes']).any? { |note| note.match?(PARTLY_DEFINED[kind]) }
629
+ interface[:complete][kind] = names_known && (declared || !partly) && blank?(attributes[SPEC_CODE[kind]])
630
+ end
631
+ (spec['attributes'] || {}).each do |name, attribute|
632
+ value = attributes[name]
633
+ next if blank?(value)
634
+ case attribute['declares']
635
+ when 'required_inputs', 'optional_inputs'
636
+ required = attribute['declares'].eql?('required_inputs')
637
+ declared_names(value).each { |input| interface[:inputs][input] ||= {'exists' => true, 'required' => required} }
638
+ when 'outputs'
639
+ declared_names(value).each { |output| interface[:outputs][output] ||= {'exists' => true} }
640
+ end
641
+ next unless attribute['placeholders']
642
+ value.scan(PLACEHOLDER).flatten.each { |input| interface[:inputs][input] ||= {'exists' => true, 'required' => true} }
643
+ # inputs of other placeholders (functions of variables) are not known
644
+ interface[:complete][:inputs] = false if value.scan('<%').size > value.scan(PLACEHOLDER).size
645
+ end
646
+ interface
647
+ end
648
+
649
+ def check_step_interfaces(steps)
650
+ interfaces = {}
651
+ interface_of = lambda do |step|
652
+ type = text_of(step, 'Step_type')
653
+ key = "#{type}__#{text_of(step, 'Action_id')}"
654
+ next if @specs[type].nil? || !@template_attributes.key?(key)
655
+ interfaces[key] ||= step_interface(@specs[type], @template_attributes[key])
656
+ end
657
+ steps.each do |step|
658
+ path = node_path(step)
659
+ type = text_of(step, 'Step_type')
660
+ interface = interface_of.call(step)
661
+ unless interface.nil?
662
+ inputs = step.get_elements('Inputs/Input').map { |input| input.attributes['name'] }
663
+ # a carried variable is also given to the step under its name
664
+ provided = inputs + step.get_elements('Outputs/Carry_thru').map { |carry| carry.attributes['name'] }
665
+ unknown = interface[:complete][:inputs] ? inputs - interface[:inputs].keys : []
666
+ unknown.each { |name| add(WARNING, 'step.input_unknown', path, "#{type} has no input #{name} with this template: Orchestrator ignores it") }
667
+ interface[:inputs].each do |name, input|
668
+ next unless input['exists'].eql?(true) && input['required'].eql?(true) && !provided.include?(name)
669
+ add(ERROR, 'step.input_missing', path, "required input #{name} is not mapped")
670
+ end
671
+ if interface[:complete][:outputs]
672
+ (step.get_elements('Outputs/Output').map { |output| output.attributes['name'] } - interface[:outputs].keys).each do |name|
673
+ add(WARNING, 'step.output_unknown', path, "#{type} has no output #{name} with this template: its settings are ignored")
674
+ end
675
+ end
676
+ end
677
+ step.get_elements('Inputs/Input/Map_to').each do |map|
678
+ next unless map.attributes['type'].eql?('output')
679
+ source = steps.find { |other| STEP_IDENTITY.all? { |name| text_of(other, name).eql?(map.attributes[name.downcase]) } }
680
+ source_interface = source && interface_of.call(source)
681
+ next if source_interface.nil? || !source_interface[:complete][:outputs] || source_interface[:outputs].key?(map.attributes['name'])
682
+ add(
683
+ WARNING, 'step.output_not_produced', path,
684
+ "input #{map.parent.attributes['name']} maps output #{map.attributes['name']} of step '#{map.attributes['step_name']}', which #{map.attributes['step_type']} does not produce with its template"
685
+ )
686
+ end
687
+ end
688
+ end
689
+ end
690
+ end
691
+ end
692
+ end