From 578e9c4cd21b77e088e55e4872a79208c38ce339 Mon Sep 17 00:00:00 2001 From: Michael Adler Date: Wed, 24 Jul 2024 15:25:36 +0200 Subject: [PATCH] feat!: Upgrade to OpenAPI v3 Upgrading from Swagger to OpenAPI v3 offers numerous benefits, including enhanced specification features, better support for modern use cases, improved developer experience, access to a richer ecosystem and tooling, future-proofing our API specifications, and ensuring compliance and interoperability. This change replaces the existing code generator, resulting in changes to the generated model. Users of the Go client library will need to make minor adjustments to their code. Signed-off-by: Michael Adler --- .ci/packages/versions.env | 1 + .gitignore | 1 - .golangci.yml | 22 +- .goreleaser.yml | 7 +- CHANGELOG.md | 30 +- Makefile | 2 +- README.md | 2 +- api/errors.go | 12 +- api/job_events_test.go | 6 +- api/job_id_test.go | 6 +- api/job_status_test.go | 4 +- api/job_tag_test.go | 16 +- api/jobs_test.go | 14 +- api/jq.go | 139 + api/jq_test.go | 66 + api/northbound.go | 347 +- api/northbound_test.go | 582 +- api/southbound.go | 285 +- api/southbound_test.go | 505 +- api/wfx.go | 457 ++ api/wfx_test.go | 55 + api/workflow_test.go | 31 +- cmd/wfx-loadtest/loadtest/loadtest.go | 15 +- cmd/wfx-loadtest/loadtest/write.go | 14 +- cmd/wfx-loadtest/main.go | 10 +- cmd/wfx-loadtest/root.go | 75 +- cmd/wfx-loadtest/wfx/workflow.go | 51 +- cmd/wfx-viewer/cmd.go | 7 +- cmd/wfx-viewer/colors/colors.go | 4 +- cmd/wfx-viewer/metadata/metadata.go | 2 +- cmd/wfx-viewer/output/all.go | 4 +- cmd/wfx-viewer/output/mermaid/mermaid.go | 4 +- cmd/wfx-viewer/output/plantuml/plantuml.go | 10 +- cmd/wfx-viewer/output/smcat/smcat.go | 4 +- cmd/wfx-viewer/output/svg/svg.go | 4 +- cmd/wfx/cmd/config/appconfig.go | 399 ++ cmd/wfx/cmd/config/appconfig_test.go | 80 + cmd/wfx/cmd/config/flags.go | 130 + cmd/wfx/cmd/config/flags_test.go | 20 + {internal => cmd/wfx/cmd}/config/main_test.go | 2 +- cmd/wfx/cmd/root/cmd.go | 291 - cmd/wfx/cmd/root/cmd_test.go | 227 - cmd/wfx/cmd/root/config.go | 31 - cmd/wfx/cmd/root/config_test.go | 27 - cmd/wfx/cmd/root/flags.go | 125 - cmd/wfx/cmd/root/northbound.go | 75 - cmd/wfx/cmd/root/plugins.go | 21 - cmd/wfx/cmd/root/plugins_disabled.go | 13 +- cmd/wfx/cmd/root/plugins_disabled_test.go | 29 +- cmd/wfx/cmd/root/plugins_enabled.go | 38 +- cmd/wfx/cmd/root/plugins_flag.go | 24 - cmd/wfx/cmd/root/plugins_test.go | 130 +- cmd/wfx/cmd/root/root.go | 151 + cmd/wfx/cmd/root/root_test.go | 460 ++ cmd/wfx/cmd/root/server.go | 157 - cmd/wfx/cmd/root/server_collection.go | 383 ++ cmd/wfx/cmd/root/server_collection_test.go | 95 + cmd/wfx/cmd/root/server_test.go | 93 - cmd/wfx/cmd/root/setup.go | 7 +- cmd/wfx/cmd/root/southbound.go | 75 - cmd/wfx/main.go | 10 +- cmd/wfx/metadata/config/config.go | 26 - .../health => cmd/wfx/metadata}/main_test.go | 4 +- cmd/wfx/metadata/metadata.go | 13 +- cmd/wfx/metadata/metadata_test.go | 20 + cmd/wfxctl/cmd/health/health.go | 214 +- cmd/wfxctl/cmd/health/health_test.go | 112 +- cmd/wfxctl/cmd/job/addtags/add_tags.go | 56 +- cmd/wfxctl/cmd/job/addtags/add_tags_test.go | 19 +- cmd/wfxctl/cmd/job/create/create.go | 137 +- cmd/wfxctl/cmd/job/create/create_test.go | 33 +- cmd/wfxctl/cmd/job/delete/delete.go | 50 +- cmd/wfxctl/cmd/job/delete/delete_test.go | 16 +- cmd/wfxctl/cmd/job/deltags/del_tags.go | 63 +- cmd/wfxctl/cmd/job/deltags/del_tags_test.go | 17 +- cmd/wfxctl/cmd/job/events/events.go | 157 +- cmd/wfxctl/cmd/job/events/events_test.go | 16 +- cmd/wfxctl/cmd/job/get/get.go | 74 +- cmd/wfxctl/cmd/job/get/get_test.go | 11 +- .../cmd/job/getdefinition/get_definition.go | 67 +- .../job/getdefinition/get_definition_test.go | 16 +- cmd/wfxctl/cmd/job/getstatus/get_status.go | 66 +- .../cmd/job/getstatus/get_status_test.go | 14 +- cmd/wfxctl/cmd/job/gettags/get_tags.go | 53 +- cmd/wfxctl/cmd/job/gettags/get_tags_test.go | 17 +- cmd/wfxctl/cmd/job/job.go | 42 +- cmd/wfxctl/cmd/job/job_test.go | 2 +- cmd/wfxctl/cmd/job/query/query.go | 118 +- cmd/wfxctl/cmd/job/query/query_test.go | 19 +- .../job/updatedefinition/update_definition.go | 76 +- .../update_definition_test.go | 18 +- .../cmd/job/updatestatus/update_status.go | 107 +- .../job/updatestatus/update_status_test.go | 28 +- cmd/wfxctl/cmd/man/wfxctl-completion-bash.1 | 124 + cmd/wfxctl/cmd/man/wfxctl-completion-fish.1 | 114 + .../cmd/man/wfxctl-completion-powershell.1 | 108 + cmd/wfxctl/cmd/man/wfxctl-completion-zsh.1 | 128 + cmd/wfxctl/cmd/man/wfxctl-completion.1 | 94 + cmd/wfxctl/cmd/man/wfxctl-health.1 | 97 + cmd/wfxctl/cmd/man/wfxctl-job-add-tags.1 | 103 + cmd/wfxctl/cmd/man/wfxctl-job-create.1 | 113 + cmd/wfxctl/cmd/man/wfxctl-job-del-tags.1 | 103 + cmd/wfxctl/cmd/man/wfxctl-job-delete.1 | 99 + cmd/wfxctl/cmd/man/wfxctl-job-events.1 | 117 + .../cmd/man/wfxctl-job-get-definition.1 | 105 + cmd/wfxctl/cmd/man/wfxctl-job-get-status.1 | 105 + cmd/wfxctl/cmd/man/wfxctl-job-get-tags.1 | 103 + cmd/wfxctl/cmd/man/wfxctl-job-get.1 | 109 + cmd/wfxctl/cmd/man/wfxctl-job-query.1 | 133 + .../cmd/man/wfxctl-job-update-definition.1 | 105 + cmd/wfxctl/cmd/man/wfxctl-job-update-status.1 | 125 + cmd/wfxctl/cmd/man/wfxctl-job.1 | 93 + cmd/wfxctl/cmd/man/wfxctl-man.1 | 97 + cmd/wfxctl/cmd/man/wfxctl-version.1 | 93 + cmd/wfxctl/cmd/man/wfxctl-workflow-create.1 | 126 + cmd/wfxctl/cmd/man/wfxctl-workflow-delete.1 | 99 + cmd/wfxctl/cmd/man/wfxctl-workflow-get.1 | 103 + cmd/wfxctl/cmd/man/wfxctl-workflow-query.1 | 113 + cmd/wfxctl/cmd/man/wfxctl-workflow-validate.1 | 101 + cmd/wfxctl/cmd/man/wfxctl-workflow.1 | 93 + cmd/wfxctl/cmd/man/wfxctl.1 | 94 + cmd/wfxctl/cmd/root.go | 112 +- cmd/wfxctl/cmd/root_test.go | 11 +- cmd/wfxctl/cmd/version/version.go | 61 +- cmd/wfxctl/cmd/version/version_test.go | 40 +- cmd/wfxctl/cmd/workflow/create/create.go | 81 +- cmd/wfxctl/cmd/workflow/create/create_test.go | 18 +- cmd/wfxctl/cmd/workflow/delete/delete.go | 49 +- cmd/wfxctl/cmd/workflow/delete/delete_test.go | 15 +- cmd/wfxctl/cmd/workflow/get/get.go | 64 +- cmd/wfxctl/cmd/workflow/get/get_test.go | 21 +- cmd/wfxctl/cmd/workflow/query/query.go | 78 +- cmd/wfxctl/cmd/workflow/query/query_test.go | 13 +- cmd/wfxctl/cmd/workflow/validate/validate.go | 91 +- .../cmd/workflow/validate/validate_test.go | 32 +- cmd/wfxctl/cmd/workflow/workflow.go | 28 +- cmd/wfxctl/cmd/workflow/workflow_test.go | 2 +- cmd/wfxctl/errutil/util.go | 41 +- cmd/wfxctl/errutil/util_test.go | 39 +- cmd/wfxctl/flags/basecmd.go | 326 +- cmd/wfxctl/flags/basecmd_test.go | 178 +- cmd/wfxctl/flags/flags.go | 37 - cmd/wfxctl/main.go | 9 +- cmd/wfxctl/metadata/metadata.go | 2 +- contrib/config-deployment/client/go.mod | 29 +- contrib/config-deployment/client/go.sum | 84 +- contrib/config-deployment/client/worker.go | 66 +- contrib/remote-access/client/go.mod | 29 +- contrib/remote-access/client/go.sum | 84 +- contrib/remote-access/client/main.go | 59 +- docs/operations.md | 4 +- docs/workflows.md | 6 +- generated/api/wfx.openapi.gen.go | 5916 +++++++++++++++++ .../client/jobs/delete_jobs_id_parameters.go | 156 - .../client/jobs/delete_jobs_id_responses.go | 238 - .../jobs/delete_jobs_id_tags_parameters.go | 178 - .../jobs/delete_jobs_id_tags_responses.go | 326 - .../client/jobs/get_jobs_events_parameters.go | 271 - .../client/jobs/get_jobs_events_responses.go | 314 - .../jobs/get_jobs_id_definition_parameters.go | 156 - .../jobs/get_jobs_id_definition_responses.go | 250 - .../client/jobs/get_jobs_id_parameters.go | 191 - .../client/jobs/get_jobs_id_responses.go | 328 - .../jobs/get_jobs_id_status_parameters.go | 156 - .../jobs/get_jobs_id_status_responses.go | 252 - .../jobs/get_jobs_id_tags_parameters.go | 156 - .../client/jobs/get_jobs_id_tags_responses.go | 250 - generated/client/jobs/get_jobs_parameters.go | 453 -- generated/client/jobs/get_jobs_responses.go | 252 - generated/client/jobs/jobs_client.go | 590 -- .../jobs/post_jobs_id_tags_parameters.go | 178 - .../jobs/post_jobs_id_tags_responses.go | 326 - generated/client/jobs/post_jobs_parameters.go | 157 - generated/client/jobs/post_jobs_responses.go | 252 - .../jobs/put_jobs_id_definition_parameters.go | 178 - .../jobs/put_jobs_id_definition_responses.go | 326 - .../jobs/put_jobs_id_status_parameters.go | 179 - .../jobs/put_jobs_id_status_responses.go | 328 - generated/client/workflow_executor_client.go | 122 - .../delete_workflows_name_parameters.go | 156 - .../delete_workflows_name_responses.go | 238 - .../get_workflows_name_parameters.go | 156 - .../workflows/get_workflows_name_responses.go | 328 - .../workflows/get_workflows_parameters.go | 261 - .../workflows/get_workflows_responses.go | 176 - .../workflows/post_workflows_parameters.go | 157 - .../workflows/post_workflows_responses.go | 252 - .../client/workflows/workflows_client.go | 232 - generated/ent/history.go | 4 +- generated/ent/history_create.go | 12 +- generated/ent/history_update.go | 22 +- generated/ent/job.go | 4 +- generated/ent/job_create.go | 6 +- generated/ent/job_update.go | 22 +- generated/ent/mutation.go | 92 +- generated/ent/schema/history.go | 4 +- generated/ent/schema/job.go | 4 +- generated/ent/schema/workflow.go | 8 +- generated/ent/workflow.go | 8 +- generated/ent/workflow_create.go | 14 +- generated/ent/workflow_update.go | 62 +- generated/model/action_enum.go | 83 - generated/model/eligible_enum.go | 83 - generated/model/error.go | 61 - generated/model/error_response.go | 134 - generated/model/group.go | 110 - generated/model/history.go | 153 - generated/model/job.go | 352 - generated/model/job_request.go | 121 - generated/model/job_status.go | 164 - generated/model/paginated_job_list.go | 223 - generated/model/paginated_workflow_list.go | 223 - generated/model/state.go | 81 - generated/model/transition.go | 196 - generated/model/workflow.go | 326 - .../restapi/configure_workflow_executor.go | 50 - generated/northbound/restapi/doc.go | 24 - generated/northbound/restapi/embedded_spec.go | 3415 ---------- .../operations/northbound/delete_jobs_id.go | 63 - .../northbound/delete_jobs_id_parameters.go | 76 - .../northbound/delete_jobs_id_responses.go | 127 - .../northbound/delete_jobs_id_tags.go | 63 - .../delete_jobs_id_tags_parameters.go | 123 - .../delete_jobs_id_tags_responses.go | 195 - .../delete_jobs_id_tags_urlbuilder.go | 104 - .../northbound/delete_jobs_id_urlbuilder.go | 104 - .../northbound/delete_workflows_name.go | 63 - .../delete_workflows_name_parameters.go | 76 - .../delete_workflows_name_responses.go | 127 - .../delete_workflows_name_urlbuilder.go | 104 - .../restapi/operations/northbound/get_jobs.go | 67 - .../operations/northbound/get_jobs_events.go | 65 - .../northbound/get_jobs_events_parameters.go | 164 - .../northbound/get_jobs_events_responses.go | 172 - .../northbound/get_jobs_events_urlbuilder.go | 135 - .../operations/northbound/get_jobs_id.go | 63 - .../northbound/get_jobs_id_definition.go | 63 - .../get_jobs_id_definition_parameters.go | 76 - .../get_jobs_id_definition_responses.go | 150 - .../get_jobs_id_definition_urlbuilder.go | 104 - .../northbound/get_jobs_id_parameters.go | 112 - .../northbound/get_jobs_id_responses.go | 192 - .../northbound/get_jobs_id_status.go | 63 - .../get_jobs_id_status_parameters.go | 76 - .../get_jobs_id_status_responses.go | 147 - .../get_jobs_id_status_urlbuilder.go | 104 - .../operations/northbound/get_jobs_id_tags.go | 63 - .../northbound/get_jobs_id_tags_parameters.go | 76 - .../northbound/get_jobs_id_tags_responses.go | 150 - .../northbound/get_jobs_id_tags_urlbuilder.go | 104 - .../northbound/get_jobs_id_urlbuilder.go | 120 - .../northbound/get_jobs_parameters.go | 334 - .../northbound/get_jobs_responses.go | 147 - .../northbound/get_jobs_urlbuilder.go | 191 - .../operations/northbound/get_workflows.go | 63 - .../northbound/get_workflows_name.go | 63 - .../get_workflows_name_parameters.go | 76 - .../get_workflows_name_responses.go | 192 - .../get_workflows_name_urlbuilder.go | 104 - .../northbound/get_workflows_parameters.go | 181 - .../northbound/get_workflows_responses.go | 102 - .../northbound/get_workflows_urlbuilder.go | 128 - .../operations/northbound/post_jobs.go | 63 - .../northbound/post_jobs_id_tags.go | 63 - .../post_jobs_id_tags_parameters.go | 123 - .../northbound/post_jobs_id_tags_responses.go | 195 - .../post_jobs_id_tags_urlbuilder.go | 104 - .../northbound/post_jobs_parameters.go | 88 - .../northbound/post_jobs_responses.go | 147 - .../northbound/post_jobs_urlbuilder.go | 92 - .../operations/northbound/post_workflows.go | 63 - .../northbound/post_workflows_parameters.go | 88 - .../northbound/post_workflows_responses.go | 147 - .../northbound/post_workflows_urlbuilder.go | 92 - .../northbound/put_jobs_id_definition.go | 63 - .../put_jobs_id_definition_parameters.go | 100 - .../put_jobs_id_definition_responses.go | 195 - .../put_jobs_id_definition_urlbuilder.go | 104 - .../northbound/put_jobs_id_status.go | 63 - .../put_jobs_id_status_parameters.go | 113 - .../put_jobs_id_status_responses.go | 192 - .../put_jobs_id_status_urlbuilder.go | 104 - .../operations/workflow_executor_api.go | 500 -- .../restapi/configure_workflow_executor.go | 50 - generated/southbound/restapi/doc.go | 24 - generated/southbound/restapi/embedded_spec.go | 3415 ---------- .../restapi/operations/southbound/get_jobs.go | 67 - .../operations/southbound/get_jobs_events.go | 65 - .../southbound/get_jobs_events_parameters.go | 164 - .../southbound/get_jobs_events_responses.go | 172 - .../southbound/get_jobs_events_urlbuilder.go | 135 - .../operations/southbound/get_jobs_id.go | 63 - .../southbound/get_jobs_id_definition.go | 63 - .../get_jobs_id_definition_parameters.go | 76 - .../get_jobs_id_definition_responses.go | 150 - .../get_jobs_id_definition_urlbuilder.go | 104 - .../southbound/get_jobs_id_parameters.go | 112 - .../southbound/get_jobs_id_responses.go | 192 - .../southbound/get_jobs_id_status.go | 63 - .../get_jobs_id_status_parameters.go | 76 - .../get_jobs_id_status_responses.go | 147 - .../get_jobs_id_status_urlbuilder.go | 104 - .../operations/southbound/get_jobs_id_tags.go | 63 - .../southbound/get_jobs_id_tags_parameters.go | 76 - .../southbound/get_jobs_id_tags_responses.go | 150 - .../southbound/get_jobs_id_tags_urlbuilder.go | 104 - .../southbound/get_jobs_id_urlbuilder.go | 120 - .../southbound/get_jobs_parameters.go | 334 - .../southbound/get_jobs_responses.go | 147 - .../southbound/get_jobs_urlbuilder.go | 191 - .../operations/southbound/get_workflows.go | 63 - .../southbound/get_workflows_name.go | 63 - .../get_workflows_name_parameters.go | 76 - .../get_workflows_name_responses.go | 192 - .../get_workflows_name_urlbuilder.go | 104 - .../southbound/get_workflows_parameters.go | 181 - .../southbound/get_workflows_responses.go | 102 - .../southbound/get_workflows_urlbuilder.go | 128 - .../southbound/put_jobs_id_definition.go | 63 - .../put_jobs_id_definition_parameters.go | 100 - .../put_jobs_id_definition_responses.go | 195 - .../put_jobs_id_definition_urlbuilder.go | 104 - .../southbound/put_jobs_id_status.go | 63 - .../put_jobs_id_status_parameters.go | 113 - .../put_jobs_id_status_responses.go | 192 - .../put_jobs_id_status_urlbuilder.go | 104 - .../operations/workflow_executor_api.go | 428 -- go.mod | 26 +- go.sum | 43 +- hugo/.gitignore | 2 +- hugo/content/docs/api.md | 2 +- internal/cmd/man/cmd.go | 13 +- internal/cmd/man/cmd_test.go | 2 +- internal/config/koanf.go | 41 - internal/config/koanf_test.go | 28 - internal/errutil/main_test.go | 19 - internal/errutil/wrap.go | 17 - internal/errutil/wrap_test.go | 44 - internal/handler/job/create.go | 19 +- internal/handler/job/create_test.go | 12 +- internal/handler/job/definition/get_test.go | 10 +- internal/handler/job/definition/update.go | 10 +- .../handler/job/definition/update_test.go | 6 +- internal/handler/job/delete.go | 6 +- internal/handler/job/delete_test.go | 6 +- internal/handler/job/events/events.go | 7 +- internal/handler/job/events/events_test.go | 6 +- internal/handler/job/get.go | 4 +- internal/handler/job/get_test.go | 4 +- internal/handler/job/query.go | 4 +- internal/handler/job/query_test.go | 13 +- internal/handler/job/status/get.go | 4 +- internal/handler/job/status/get_test.go | 10 +- internal/handler/job/status/update.go | 10 +- internal/handler/job/status/update_test.go | 72 +- internal/handler/job/tags/add.go | 4 +- internal/handler/job/tags/add_test.go | 26 +- internal/handler/job/tags/delete.go | 4 +- internal/handler/job/tags/delete_test.go | 12 +- internal/handler/job/tags/get_test.go | 10 +- internal/handler/workflow/create.go | 4 +- internal/handler/workflow/create_test.go | 2 +- internal/handler/workflow/get.go | 4 +- internal/handler/workflow/get_test.go | 12 +- internal/handler/workflow/query.go | 13 +- internal/handler/workflow/query_test.go | 2 +- internal/persistence/entgo/health.go | 4 +- internal/persistence/entgo/job_create.go | 30 +- internal/persistence/entgo/job_get.go | 39 +- internal/persistence/entgo/job_query.go | 17 +- internal/persistence/entgo/job_update.go | 19 +- internal/persistence/entgo/mysql.go | 5 +- internal/persistence/entgo/mysql_test.go | 7 +- internal/persistence/entgo/postgres.go | 5 +- internal/persistence/entgo/postgres_test.go | 5 +- internal/persistence/entgo/sqlite.go | 3 +- internal/persistence/entgo/sqlite_test.go | 17 +- internal/persistence/entgo/workflow_create.go | 13 +- internal/persistence/entgo/workflow_get.go | 11 +- internal/persistence/entgo/workflow_query.go | 34 +- internal/persistence/tests/all.go | 1 + internal/persistence/tests/job_get.go | 25 +- internal/persistence/tests/job_query.go | 64 +- .../persistence/tests/job_update_status.go | 14 +- internal/persistence/tests/workflow.go | 44 +- internal/producer/json.go | 67 - internal/producer/json_test.go | 121 - internal/producer/main_test.go | 19 - internal/producer/text_event_stream.go | 37 - internal/producer/text_event_stream_test.go | 34 - internal/server/http.go | 91 +- internal/server/http_test.go | 90 +- internal/server/tls.go | 82 - internal/server/tls_test.go | 78 - internal/workflow/workflow.go | 18 +- internal/workflow/workflow_test.go | 16 +- justfile | 38 +- middleware/fileserver/fileserver.go | 65 - middleware/fileserver/fileserver_test.go | 120 - middleware/fileserver/main_test.go | 19 - middleware/health/health.go | 82 - middleware/health/health_test.go | 49 - middleware/jq/gojq.go | 27 - middleware/jq/gojq_test.go | 33 - middleware/jq/main_test.go | 19 - middleware/logging/log.go | 92 +- middleware/logging/log_test.go | 9 +- middleware/plugin/fbplugin.go | 39 +- middleware/plugin/fbplugin_test.go | 46 +- middleware/plugin/middleware.go | 195 +- middleware/plugin/middleware_test.go | 35 +- middleware/plugin/plugin.go | 2 +- middleware/responder/sse/responder.go | 76 - middleware/responder/util/content_type.go | 29 - .../responder/util/content_type_test.go | 33 - middleware/responder/util/main_test.go | 19 - middleware/setup.go | 56 - middleware/{responder => }/sse/main_test.go | 0 middleware/sse/responder.go | 82 + .../{responder => }/sse/responder_test.go | 15 +- middleware/swagger/main_test.go | 19 - middleware/swagger/middleware.go | 45 - middleware/swagger/middleware_test.go | 47 - middleware/version/main_test.go | 19 - middleware/version/version.go | 47 - middleware/version/version_test.go | 35 - persistence/all_test.go | 4 +- persistence/mock.go | 22 + persistence/mock_Storage.go | 167 +- persistence/storage.go | 20 +- spec/cfg.yaml | 9 + spec/justfile | 19 - spec/middleware.go | 13 + spec/openapiv3.go | 48 + spec/spdx.txt | 3 - spec/swagger.go | 52 + spec/wfx.openapiv3.yml | 1330 ++++ test/01-api.bats | 39 - test/01-storage.bats | 52 + test/02-configuration.bats | 78 +- test/04-operations.bats | 56 +- test/05-workflows.bats | 2 +- test/06-plugins.bats | 53 + test/lib.sh | 129 +- workflow/dau/dau.go | 10 +- workflow/validate.go | 65 +- workflow/validate_test.go | 97 +- 447 files changed, 16524 insertions(+), 37918 deletions(-) create mode 100644 api/jq.go create mode 100644 api/jq_test.go create mode 100644 api/wfx.go create mode 100644 api/wfx_test.go create mode 100644 cmd/wfx/cmd/config/appconfig.go create mode 100644 cmd/wfx/cmd/config/appconfig_test.go create mode 100644 cmd/wfx/cmd/config/flags.go create mode 100644 cmd/wfx/cmd/config/flags_test.go rename {internal => cmd/wfx/cmd}/config/main_test.go (84%) delete mode 100644 cmd/wfx/cmd/root/cmd.go delete mode 100644 cmd/wfx/cmd/root/cmd_test.go delete mode 100644 cmd/wfx/cmd/root/config.go delete mode 100644 cmd/wfx/cmd/root/config_test.go delete mode 100644 cmd/wfx/cmd/root/flags.go delete mode 100644 cmd/wfx/cmd/root/northbound.go delete mode 100644 cmd/wfx/cmd/root/plugins.go delete mode 100644 cmd/wfx/cmd/root/plugins_flag.go create mode 100644 cmd/wfx/cmd/root/root.go create mode 100644 cmd/wfx/cmd/root/root_test.go delete mode 100644 cmd/wfx/cmd/root/server.go create mode 100644 cmd/wfx/cmd/root/server_collection.go create mode 100644 cmd/wfx/cmd/root/server_collection_test.go delete mode 100644 cmd/wfx/cmd/root/server_test.go delete mode 100644 cmd/wfx/cmd/root/southbound.go delete mode 100644 cmd/wfx/metadata/config/config.go rename {middleware/health => cmd/wfx/metadata}/main_test.go (77%) create mode 100644 cmd/wfx/metadata/metadata_test.go create mode 100644 cmd/wfxctl/cmd/man/wfxctl-completion-bash.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-completion-fish.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-completion-powershell.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-completion-zsh.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-completion.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-health.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-job-add-tags.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-job-create.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-job-del-tags.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-job-delete.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-job-events.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-job-get-definition.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-job-get-status.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-job-get-tags.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-job-get.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-job-query.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-job-update-definition.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-job-update-status.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-job.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-man.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-version.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-workflow-create.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-workflow-delete.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-workflow-get.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-workflow-query.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-workflow-validate.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl-workflow.1 create mode 100644 cmd/wfxctl/cmd/man/wfxctl.1 delete mode 100644 cmd/wfxctl/flags/flags.go create mode 100644 generated/api/wfx.openapi.gen.go delete mode 100644 generated/client/jobs/delete_jobs_id_parameters.go delete mode 100644 generated/client/jobs/delete_jobs_id_responses.go delete mode 100644 generated/client/jobs/delete_jobs_id_tags_parameters.go delete mode 100644 generated/client/jobs/delete_jobs_id_tags_responses.go delete mode 100644 generated/client/jobs/get_jobs_events_parameters.go delete mode 100644 generated/client/jobs/get_jobs_events_responses.go delete mode 100644 generated/client/jobs/get_jobs_id_definition_parameters.go delete mode 100644 generated/client/jobs/get_jobs_id_definition_responses.go delete mode 100644 generated/client/jobs/get_jobs_id_parameters.go delete mode 100644 generated/client/jobs/get_jobs_id_responses.go delete mode 100644 generated/client/jobs/get_jobs_id_status_parameters.go delete mode 100644 generated/client/jobs/get_jobs_id_status_responses.go delete mode 100644 generated/client/jobs/get_jobs_id_tags_parameters.go delete mode 100644 generated/client/jobs/get_jobs_id_tags_responses.go delete mode 100644 generated/client/jobs/get_jobs_parameters.go delete mode 100644 generated/client/jobs/get_jobs_responses.go delete mode 100644 generated/client/jobs/jobs_client.go delete mode 100644 generated/client/jobs/post_jobs_id_tags_parameters.go delete mode 100644 generated/client/jobs/post_jobs_id_tags_responses.go delete mode 100644 generated/client/jobs/post_jobs_parameters.go delete mode 100644 generated/client/jobs/post_jobs_responses.go delete mode 100644 generated/client/jobs/put_jobs_id_definition_parameters.go delete mode 100644 generated/client/jobs/put_jobs_id_definition_responses.go delete mode 100644 generated/client/jobs/put_jobs_id_status_parameters.go delete mode 100644 generated/client/jobs/put_jobs_id_status_responses.go delete mode 100644 generated/client/workflow_executor_client.go delete mode 100644 generated/client/workflows/delete_workflows_name_parameters.go delete mode 100644 generated/client/workflows/delete_workflows_name_responses.go delete mode 100644 generated/client/workflows/get_workflows_name_parameters.go delete mode 100644 generated/client/workflows/get_workflows_name_responses.go delete mode 100644 generated/client/workflows/get_workflows_parameters.go delete mode 100644 generated/client/workflows/get_workflows_responses.go delete mode 100644 generated/client/workflows/post_workflows_parameters.go delete mode 100644 generated/client/workflows/post_workflows_responses.go delete mode 100644 generated/client/workflows/workflows_client.go delete mode 100644 generated/model/action_enum.go delete mode 100644 generated/model/eligible_enum.go delete mode 100644 generated/model/error.go delete mode 100644 generated/model/error_response.go delete mode 100644 generated/model/group.go delete mode 100644 generated/model/history.go delete mode 100644 generated/model/job.go delete mode 100644 generated/model/job_request.go delete mode 100644 generated/model/job_status.go delete mode 100644 generated/model/paginated_job_list.go delete mode 100644 generated/model/paginated_workflow_list.go delete mode 100644 generated/model/state.go delete mode 100644 generated/model/transition.go delete mode 100644 generated/model/workflow.go delete mode 100644 generated/northbound/restapi/configure_workflow_executor.go delete mode 100644 generated/northbound/restapi/doc.go delete mode 100644 generated/northbound/restapi/embedded_spec.go delete mode 100644 generated/northbound/restapi/operations/northbound/delete_jobs_id.go delete mode 100644 generated/northbound/restapi/operations/northbound/delete_jobs_id_parameters.go delete mode 100644 generated/northbound/restapi/operations/northbound/delete_jobs_id_responses.go delete mode 100644 generated/northbound/restapi/operations/northbound/delete_jobs_id_tags.go delete mode 100644 generated/northbound/restapi/operations/northbound/delete_jobs_id_tags_parameters.go delete mode 100644 generated/northbound/restapi/operations/northbound/delete_jobs_id_tags_responses.go delete mode 100644 generated/northbound/restapi/operations/northbound/delete_jobs_id_tags_urlbuilder.go delete mode 100644 generated/northbound/restapi/operations/northbound/delete_jobs_id_urlbuilder.go delete mode 100644 generated/northbound/restapi/operations/northbound/delete_workflows_name.go delete mode 100644 generated/northbound/restapi/operations/northbound/delete_workflows_name_parameters.go delete mode 100644 generated/northbound/restapi/operations/northbound/delete_workflows_name_responses.go delete mode 100644 generated/northbound/restapi/operations/northbound/delete_workflows_name_urlbuilder.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_jobs.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_jobs_events.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_jobs_events_parameters.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_jobs_events_responses.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_jobs_events_urlbuilder.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_jobs_id.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_jobs_id_definition.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_jobs_id_definition_parameters.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_jobs_id_definition_responses.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_jobs_id_definition_urlbuilder.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_jobs_id_parameters.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_jobs_id_responses.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_jobs_id_status.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_jobs_id_status_parameters.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_jobs_id_status_responses.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_jobs_id_status_urlbuilder.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_jobs_id_tags.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_jobs_id_tags_parameters.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_jobs_id_tags_responses.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_jobs_id_tags_urlbuilder.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_jobs_id_urlbuilder.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_jobs_parameters.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_jobs_responses.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_jobs_urlbuilder.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_workflows.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_workflows_name.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_workflows_name_parameters.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_workflows_name_responses.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_workflows_name_urlbuilder.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_workflows_parameters.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_workflows_responses.go delete mode 100644 generated/northbound/restapi/operations/northbound/get_workflows_urlbuilder.go delete mode 100644 generated/northbound/restapi/operations/northbound/post_jobs.go delete mode 100644 generated/northbound/restapi/operations/northbound/post_jobs_id_tags.go delete mode 100644 generated/northbound/restapi/operations/northbound/post_jobs_id_tags_parameters.go delete mode 100644 generated/northbound/restapi/operations/northbound/post_jobs_id_tags_responses.go delete mode 100644 generated/northbound/restapi/operations/northbound/post_jobs_id_tags_urlbuilder.go delete mode 100644 generated/northbound/restapi/operations/northbound/post_jobs_parameters.go delete mode 100644 generated/northbound/restapi/operations/northbound/post_jobs_responses.go delete mode 100644 generated/northbound/restapi/operations/northbound/post_jobs_urlbuilder.go delete mode 100644 generated/northbound/restapi/operations/northbound/post_workflows.go delete mode 100644 generated/northbound/restapi/operations/northbound/post_workflows_parameters.go delete mode 100644 generated/northbound/restapi/operations/northbound/post_workflows_responses.go delete mode 100644 generated/northbound/restapi/operations/northbound/post_workflows_urlbuilder.go delete mode 100644 generated/northbound/restapi/operations/northbound/put_jobs_id_definition.go delete mode 100644 generated/northbound/restapi/operations/northbound/put_jobs_id_definition_parameters.go delete mode 100644 generated/northbound/restapi/operations/northbound/put_jobs_id_definition_responses.go delete mode 100644 generated/northbound/restapi/operations/northbound/put_jobs_id_definition_urlbuilder.go delete mode 100644 generated/northbound/restapi/operations/northbound/put_jobs_id_status.go delete mode 100644 generated/northbound/restapi/operations/northbound/put_jobs_id_status_parameters.go delete mode 100644 generated/northbound/restapi/operations/northbound/put_jobs_id_status_responses.go delete mode 100644 generated/northbound/restapi/operations/northbound/put_jobs_id_status_urlbuilder.go delete mode 100644 generated/northbound/restapi/operations/workflow_executor_api.go delete mode 100644 generated/southbound/restapi/configure_workflow_executor.go delete mode 100644 generated/southbound/restapi/doc.go delete mode 100644 generated/southbound/restapi/embedded_spec.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_jobs.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_jobs_events.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_jobs_events_parameters.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_jobs_events_responses.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_jobs_events_urlbuilder.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_jobs_id.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_jobs_id_definition.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_jobs_id_definition_parameters.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_jobs_id_definition_responses.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_jobs_id_definition_urlbuilder.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_jobs_id_parameters.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_jobs_id_responses.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_jobs_id_status.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_jobs_id_status_parameters.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_jobs_id_status_responses.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_jobs_id_status_urlbuilder.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_jobs_id_tags.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_jobs_id_tags_parameters.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_jobs_id_tags_responses.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_jobs_id_tags_urlbuilder.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_jobs_id_urlbuilder.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_jobs_parameters.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_jobs_responses.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_jobs_urlbuilder.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_workflows.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_workflows_name.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_workflows_name_parameters.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_workflows_name_responses.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_workflows_name_urlbuilder.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_workflows_parameters.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_workflows_responses.go delete mode 100644 generated/southbound/restapi/operations/southbound/get_workflows_urlbuilder.go delete mode 100644 generated/southbound/restapi/operations/southbound/put_jobs_id_definition.go delete mode 100644 generated/southbound/restapi/operations/southbound/put_jobs_id_definition_parameters.go delete mode 100644 generated/southbound/restapi/operations/southbound/put_jobs_id_definition_responses.go delete mode 100644 generated/southbound/restapi/operations/southbound/put_jobs_id_definition_urlbuilder.go delete mode 100644 generated/southbound/restapi/operations/southbound/put_jobs_id_status.go delete mode 100644 generated/southbound/restapi/operations/southbound/put_jobs_id_status_parameters.go delete mode 100644 generated/southbound/restapi/operations/southbound/put_jobs_id_status_responses.go delete mode 100644 generated/southbound/restapi/operations/southbound/put_jobs_id_status_urlbuilder.go delete mode 100644 generated/southbound/restapi/operations/workflow_executor_api.go delete mode 100644 internal/config/koanf.go delete mode 100644 internal/config/koanf_test.go delete mode 100644 internal/errutil/main_test.go delete mode 100644 internal/errutil/wrap.go delete mode 100644 internal/errutil/wrap_test.go delete mode 100644 internal/producer/json.go delete mode 100644 internal/producer/json_test.go delete mode 100644 internal/producer/main_test.go delete mode 100644 internal/producer/text_event_stream.go delete mode 100644 internal/producer/text_event_stream_test.go delete mode 100644 internal/server/tls.go delete mode 100644 internal/server/tls_test.go delete mode 100644 middleware/fileserver/fileserver.go delete mode 100644 middleware/fileserver/fileserver_test.go delete mode 100644 middleware/fileserver/main_test.go delete mode 100644 middleware/health/health.go delete mode 100644 middleware/health/health_test.go delete mode 100644 middleware/jq/gojq.go delete mode 100644 middleware/jq/gojq_test.go delete mode 100644 middleware/jq/main_test.go delete mode 100644 middleware/responder/sse/responder.go delete mode 100644 middleware/responder/util/content_type.go delete mode 100644 middleware/responder/util/content_type_test.go delete mode 100644 middleware/responder/util/main_test.go delete mode 100644 middleware/setup.go rename middleware/{responder => }/sse/main_test.go (100%) create mode 100644 middleware/sse/responder.go rename middleware/{responder => }/sse/responder_test.go (73%) delete mode 100644 middleware/swagger/main_test.go delete mode 100644 middleware/swagger/middleware.go delete mode 100644 middleware/swagger/middleware_test.go delete mode 100644 middleware/version/main_test.go delete mode 100644 middleware/version/version.go delete mode 100644 middleware/version/version_test.go create mode 100644 persistence/mock.go create mode 100644 spec/cfg.yaml delete mode 100644 spec/justfile create mode 100644 spec/middleware.go create mode 100644 spec/openapiv3.go delete mode 100644 spec/spdx.txt create mode 100644 spec/swagger.go create mode 100644 spec/wfx.openapiv3.yml delete mode 100755 test/01-api.bats create mode 100755 test/01-storage.bats create mode 100755 test/06-plugins.bats diff --git a/.ci/packages/versions.env b/.ci/packages/versions.env index ed9402b7..fd25c297 100644 --- a/.ci/packages/versions.env +++ b/.ci/packages/versions.env @@ -11,3 +11,4 @@ export SWAGGER_VERSION=0.31.0 # github-releases/go-swagger/go-swagger&versioning export ZIG_VERSION=0.13.0 # github-releases/ziglang/zig&versioning=semver export MARKDOWN_LINK_CHECK_VERSION=3.12.2 # github-releases/tcort/markdown-link-check&versioning=semver export SYFT_VERSION=1.17.0 # github-releases/anchore/syft&versioning=semver +export OAPI_CODEGEN_VERSION=2.3.0 # github-releases/oapi-codegen/oapi-codegen&versioning=semver diff --git a/.gitignore b/.gitignore index 14e9cef7..b0fa4ecb 100644 --- a/.gitignore +++ b/.gitignore @@ -15,7 +15,6 @@ cmd/wfx-viewer/wfx-viewer coverage* *.log /results -generated/wfx.swagger.yml /out *.cov /wfx.db* diff --git a/.golangci.yml b/.golangci.yml index 16193dd0..78991552 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -19,18 +19,6 @@ run: - postgres - mysql - # default is true. Enables skipping of directories: - # vendor$, third_party$, testdata$, examples$, Godeps$, builtin$ - skip-dirs-use-default: true - - # which files to skip: they will be analyzed, but issues from them - # won't be reported. Default value is empty list, but there is - # no need to include all autogenerated files, we confidently recognize - # autogenerated files. If it's not please let us know. - # "/" will be replaced by current OS file path separator to properly work - # on Windows. - skip-files: [] - # by default isn't set. If set we pass it to "go list -mod={option}". From "go help modules": # If invoked with -mod=readonly, the go command is disallowed from the implicit # automatic updating of go.mod described above. Instead, it fails when any changes @@ -47,10 +35,6 @@ run: # output configuration options output: - # colored-line-number|line-number|json|tab|checkstyle|code-climate|junit-xml|github-actions - # default is "colored-line-number" - format: colored-line-number - # print lines of code with issue, default is true print-issued-lines: true @@ -92,7 +76,6 @@ linters: linters-settings: staticcheck: - go: "1.21" # https://staticcheck.io/docs/options#checks checks: ["all", "-ST1000", "-SA1019"] misspell: @@ -107,3 +90,8 @@ linters-settings: dupword: keywords: - "INSTALLING" + stylecheck: + checks: [ + "all", + "-ST1003", # allow method names such as GetJobsIdTags + ] diff --git a/.goreleaser.yml b/.goreleaser.yml index 7ac8553b..94873ac3 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -21,6 +21,7 @@ builds: - postgres - mysql - plugin + - swagger flags: - -trimpath - -mod=readonly @@ -54,9 +55,9 @@ builds: - -mod=readonly ldflags: - -s -w -linkmode external -extldflags '-static' - - -X github.com/siemens/wfxctl/cmd/wfx/metadata.Version={{.Version}} - - -X github.com/siemens/wfxctl/cmd/wfx/metadata.Commit={{.Commit}} - - -X github.com/siemens/wfxctl/cmd/wfx/metadata.Date={{.CommitDate}} + - -X github.com/siemens/wfx/cmd/wfxctl/metadata.Version={{.Version}} + - -X github.com/siemens/wfx/cmd/wfxctl/metadata.Commit={{.Commit}} + - -X github.com/siemens/wfx/cmd/wfxctl/metadata.Date={{.CommitDate}} env: - CGO_ENABLED=1 goos: diff --git a/CHANGELOG.md b/CHANGELOG.md index f70d09bc..0d985485 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,20 +9,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- `wfxctl workflow query` now accepts a `sort` param +- Added (existing but undocumented) `/health` and `/version` endpoint to OpenAPI spec +- OpenAPI v3 spec is served at `/api/wfx/v1/openapiv3.json` + ### Fixed -- `wfx` would not start if it was built without plugins support +- `wfx`: implemented sort functionality for `/workflows` endpoint ### Changed -- Use zstd instead of xz to compress release tarballs - -## [0.3.1] - 2024-07-09 +- Migrated from Swagger to OpenAPI v3 +- The previous Swagger spec is still served at `/api/wfx/v1/swagger.json` (but no longer at the top level `/swagger.json`). + in order to *maintain compatibility* with older clients (e.g., SWUpdate <= 2024.12). The endpoint will be removed + in a future release. +- `wfxctl workflow get` uses southbound API by default +- `wfxctl health` validates the certificate chain when using TLS +- Forbbiden requests (e.g. job creation via southbound API) now return HTTP status code 403 instead of 405 +- System certificates will be loaded automatically for TLS communication -### Added +## [0.3.2] - 2024-09-03 ### Fixed +- `wfx` would not start if it was built without plugins support + +## [0.3.1] - 2024-07-09 + ### Changed - Use zstd instead of xz to compress release tarballs @@ -44,8 +57,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Log messages from automaxprocs/maxprocs are now seamlessly integrated into existing logging framework -### Removed - ## [0.2.0] - 2024-01-15 ### Added @@ -67,8 +78,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Empty or `null` arrays are omitted from JSON responses - Build requires Go >= 1.21 -### Removed - ## [0.1.0] - 2023-02-06 Initial release of wfx. @@ -77,4 +86,5 @@ Initial release of wfx. [0.2.0]: https://github.com/siemens/wfx/releases/tag/v0.2.0 [0.3.0]: https://github.com/siemens/wfx/releases/tag/v0.3.0 [0.3.1]: https://github.com/siemens/wfx/releases/tag/v0.3.1 -[unreleased]: https://github.com/siemens/wfx/compare/v0.3.1...HEAD +[0.3.2]: https://github.com/siemens/wfx/releases/tag/v0.3.2 +[unreleased]: https://github.com/siemens/wfx/compare/v0.3.2...HEAD diff --git a/Makefile b/Makefile index 82a0adb9..466ad2df 100644 --- a/Makefile +++ b/Makefile @@ -13,7 +13,7 @@ MAKEFLAGS += --jobs=$(shell nproc) DESTDIR ?= prefix ?= /usr/local -GO_TAGS = sqlite,postgres,mysql,plugin +GO_TAGS = sqlite,postgres,mysql,plugin,swagger export CGO_ENABLED=1 diff --git a/README.md b/README.md index 400fbcbc..202da9da 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ An exemplary [Kanban](https://en.wikipedia.org/wiki/Kanban)-inspired [workflow]( - Extendable modularized source code architecture - Lightweight, no dependencies (statically linked binaries) - Efficient, native code for a wide variety of platforms and operating systems (as supported by the [Go](https://golang.org/) Language) - - Fully documented REST API, see [wfx OpenAPI Specification](spec/wfx.swagger.yml) + - Fully documented REST API, see [wfx OpenAPI Specification](spec/wfx.openapiv3.yml) - Extensive test suite including load tests - Deployment / Usability - Load / Unload workflows at run-time diff --git a/api/errors.go b/api/errors.go index 9a7d9d68..0f5c4c05 100644 --- a/api/errors.go +++ b/api/errors.go @@ -8,35 +8,35 @@ package api * Author: Michael Adler */ -import "github.com/siemens/wfx/generated/model" +import "github.com/siemens/wfx/generated/api" /* these are defined in the swagger yaml */ -var InvalidRequest = model.Error{ +var InvalidRequest = api.Error{ Code: "wfx.invalidRequest", Message: "The request was invalid and/or could not be completed by the storage", Logref: "96a37ea1f7d205ffbfa12334c6812727", } -var JobNotFound = model.Error{ +var JobNotFound = api.Error{ Code: "wfx.jobNotFound", Logref: "11cc67762090e15b79a1387eca65ba65", Message: "Job ID was not found", } -var WorkflowNotFound = model.Error{ +var WorkflowNotFound = api.Error{ Code: "wfx.workflowNotFound", Logref: "c452719774086b6e803bb8f6ecea9899", Message: "Workflow not found for given name", } -var WorkflowNotUnique = model.Error{ +var WorkflowNotUnique = api.Error{ Code: "wfx.workflowNotUnique", Logref: "e1ee1f2aea859b9dd34579610e386da6", Message: "Workflow with name already exists", } -var WorkflowInvalid = model.Error{ +var WorkflowInvalid = api.Error{ Code: "wfx.workflowInvalid", Logref: "18f57adc70dd79c7fb4f1246be8a6e04", Message: "Workflow validation failed", diff --git a/api/job_events_test.go b/api/job_events_test.go index 7a2c1cca..31ec4c57 100644 --- a/api/job_events_test.go +++ b/api/job_events_test.go @@ -23,7 +23,7 @@ import ( "github.com/rs/zerolog" "github.com/rs/zerolog/log" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/internal/handler/job" "github.com/siemens/wfx/internal/handler/job/events" "github.com/siemens/wfx/internal/handler/job/status" @@ -74,7 +74,7 @@ func TestJobEventsSubscribe(t *testing.T) { events.ShutdownSubscribers() }() - _, err := job.CreateJob(context.Background(), db, &model.JobRequest{ClientID: clientID, Workflow: wf.Name}) + _, err := job.CreateJob(context.Background(), db, &api.JobRequest{ClientID: clientID, Workflow: wf.Name}) require.NoError(t, err) wg.Add(1) @@ -85,7 +85,7 @@ func TestJobEventsSubscribe(t *testing.T) { time.Sleep(20 * time.Millisecond) } // update job - _, err = status.Update(context.Background(), db, *jobID.Load(), &model.JobStatus{State: "INSTALLING"}, model.EligibleEnumCLIENT) + _, err = status.Update(context.Background(), db, *jobID.Load(), &api.JobStatus{State: "INSTALLING"}, api.CLIENT) require.NoError(t, err) }() diff --git a/api/job_id_test.go b/api/job_id_test.go index c033bb5c..5a787539 100644 --- a/api/job_id_test.go +++ b/api/job_id_test.go @@ -14,7 +14,6 @@ import ( "net/http" "testing" - "github.com/siemens/wfx/middleware/jq" "github.com/siemens/wfx/persistence" "github.com/steinfletcher/apitest" jsonpath "github.com/steinfletcher/apitest-jsonpath" @@ -47,9 +46,6 @@ func TestJobGetIdFilter(t *testing.T) { job := persistJob(t, db) jobPath := fmt.Sprintf("/api/wfx/v1/jobs/%s", job.ID) - north = jq.MW{}.Wrap(north) - south = jq.MW{}.Wrap(south) - // read job handlers := []http.Handler{north, south} for i, name := range allAPIs { @@ -94,7 +90,7 @@ func TestDeleteJob(t *testing.T) { Delete(jobPath). ContentType("application/json"). Expect(t). - Status(http.StatusMethodNotAllowed). + Status(http.StatusForbidden). End() // delete job shall succeed for north diff --git a/api/job_status_test.go b/api/job_status_test.go index 009e7c2b..cdd77ed8 100644 --- a/api/job_status_test.go +++ b/api/job_status_test.go @@ -14,7 +14,7 @@ import ( "net/http" "testing" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/internal/handler/job" "github.com/siemens/wfx/internal/handler/workflow" "github.com/siemens/wfx/workflow/dau" @@ -66,7 +66,7 @@ func TestJobStatusUpdate(t *testing.T) { wf, err := workflow.CreateWorkflow(context.Background(), db, dau.PhasedWorkflow()) require.NoError(t, err) - jobReq := model.JobRequest{ + jobReq := api.JobRequest{ ClientID: "foo", Workflow: wf.Name, } diff --git a/api/job_tag_test.go b/api/job_tag_test.go index 953b3867..66297bf1 100644 --- a/api/job_tag_test.go +++ b/api/job_tag_test.go @@ -14,7 +14,7 @@ import ( "net/http" "testing" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/internal/handler/job" "github.com/siemens/wfx/internal/handler/workflow" "github.com/siemens/wfx/workflow/dau" @@ -29,7 +29,7 @@ func TestJobTagGet(t *testing.T) { wf, err := workflow.CreateWorkflow(context.Background(), db, dau.DirectWorkflow()) require.NoError(t, err) - jobReq := model.JobRequest{ + jobReq := api.JobRequest{ ClientID: "foo", Workflow: wf.Name, Tags: []string{"foo", "bar"}, @@ -59,7 +59,7 @@ func TestJobTagPost(t *testing.T) { wf, err := workflow.CreateWorkflow(context.Background(), db, dau.DirectWorkflow()) require.NoError(t, err) - jobReq := model.JobRequest{ + jobReq := api.JobRequest{ ClientID: "foo", Workflow: wf.Name, Tags: []string{"tag1"}, @@ -85,8 +85,10 @@ func TestJobTagPost(t *testing.T) { apitest.New(). Handler(south). Post(jobPath). + ContentType("application/json"). + Body(`["bar", "foo"]`). Expect(t). - Status(http.StatusMethodNotAllowed). + Status(http.StatusForbidden). End() }) } @@ -98,7 +100,7 @@ func TestJobTagDelete(t *testing.T) { wf, err := workflow.CreateWorkflow(context.Background(), db, dau.DirectWorkflow()) require.NoError(t, err) - jobReq := model.JobRequest{ + jobReq := api.JobRequest{ ClientID: "foo", Workflow: wf.Name, Tags: []string{"foo", "bar"}, @@ -124,8 +126,10 @@ func TestJobTagDelete(t *testing.T) { apitest.New(). Handler(south). Delete(jobPath). + ContentType("application/json"). + Body(`["foo"]`). Expect(t). - Status(http.StatusMethodNotAllowed). + Status(http.StatusForbidden). End() }) } diff --git a/api/jobs_test.go b/api/jobs_test.go index cb8dd82a..e5f8a7c9 100644 --- a/api/jobs_test.go +++ b/api/jobs_test.go @@ -14,7 +14,7 @@ import ( "net/http" "testing" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/internal/handler/workflow" "github.com/siemens/wfx/persistence" "github.com/siemens/wfx/workflow/dau" @@ -30,14 +30,12 @@ func TestGetJobsHandler_Group(t *testing.T) { workflow, err := db.CreateWorkflow(context.Background(), dau.DirectWorkflow()) require.NoError(t, err) - _, err = db.CreateJob(context.Background(), &model.Job{ + _, err = db.CreateJob(context.Background(), &api.Job{ ClientID: "foo", - Status: &model.JobStatus{ - State: "INSTALL", - Progress: 0, - Message: "", + Status: &api.JobStatus{ + State: "INSTALL", }, - Workflow: &model.Workflow{Name: workflow.Name}, + Workflow: &api.Workflow{Name: workflow.Name}, }) assert.NoError(t, err) @@ -111,6 +109,6 @@ func TestCreateJob_SouthNotAllowed(t *testing.T) { Body(`{"clientId":"gotest","workflow":"wfx.workflow.kanban","tags":[]}`). ContentType("application/json"). Expect(t). - Status(http.StatusMethodNotAllowed). + Status(http.StatusForbidden). End() } diff --git a/api/jq.go b/api/jq.go new file mode 100644 index 00000000..77fc39c2 --- /dev/null +++ b/api/jq.go @@ -0,0 +1,139 @@ +package api + +/* + * SPDX-FileCopyrightText: 2024 Siemens AG + * + * SPDX-License-Identifier: Apache-2.0 + * + * Author: Michael Adler + */ + +import ( + "encoding/json" + "net/http" + + "github.com/Southclaws/fault" + "github.com/itchyny/gojq" + "github.com/rs/zerolog/log" +) + +// JQFilter applies a JQ filter to the response body. +type JQFilter struct { + filter string + body any +} + +func NewJQFilter(filter string, body any) JQFilter { + return JQFilter{filter: filter, body: body} +} + +func applyFilter(w http.ResponseWriter, body any, filter string) error { + contextLogger := log.With().Str("filter", filter).Logger() + contextLogger.Debug().Msg("Applying JQ filter") + + query, err := gojq.Parse(filter) + if err != nil { + contextLogger.Err(err).Msg("Failed to parse JQ filter") + return fault.Wrap(err) + } + + jsonData, err := json.Marshal(body) + if err != nil { + return fault.Wrap(err) + } + + var input any + // need to unmarshal again, but to type 'any'; this cannot fail + // because we own the local variable jsonData and know it's + // valid JSON + _ = json.Unmarshal(jsonData, &input) + + w.Header().Set("X-Response-Filter", filter) + iter := query.Run(input) + ok := true + encoder := json.NewEncoder(w) + for ok { + var v any + v, ok = iter.Next() + if ok { + // this cannot fail because we know the input + _ = encoder.Encode(v) + } + } + return nil +} + +// the below methods ensure we fulfill all the interfaces generated by oapi-codegen + +//revive:disable:var-naming +func (jq JQFilter) VisitGetHealthResponse(w http.ResponseWriter) error { + return applyFilter(w, jq.body, jq.filter) +} + +func (jq JQFilter) VisitGetJobsResponse(w http.ResponseWriter) error { + return applyFilter(w, jq.body, jq.filter) +} + +func (jq JQFilter) VisitPostJobsResponse(w http.ResponseWriter) error { + return applyFilter(w, jq.body, jq.filter) +} + +func (jq JQFilter) VisitGetJobsEventsResponse(w http.ResponseWriter) error { + return applyFilter(w, jq.body, jq.filter) +} + +func (jq JQFilter) VisitDeleteJobsIdResponse(w http.ResponseWriter) error { + return applyFilter(w, jq.body, jq.filter) +} + +func (jq JQFilter) VisitGetJobsIdResponse(w http.ResponseWriter) error { + return applyFilter(w, jq.body, jq.filter) +} + +func (jq JQFilter) VisitGetJobsIdDefinitionResponse(w http.ResponseWriter) error { + return applyFilter(w, jq.body, jq.filter) +} + +func (jq JQFilter) VisitPutJobsIdDefinitionResponse(w http.ResponseWriter) error { + return applyFilter(w, jq.body, jq.filter) +} + +func (jq JQFilter) VisitGetJobsIdStatusResponse(w http.ResponseWriter) error { + return applyFilter(w, jq.body, jq.filter) +} + +func (jq JQFilter) VisitPutJobsIdStatusResponse(w http.ResponseWriter) error { + return applyFilter(w, jq.body, jq.filter) +} + +func (jq JQFilter) VisitDeleteJobsIdTagsResponse(w http.ResponseWriter) error { + return applyFilter(w, jq.body, jq.filter) +} + +func (jq JQFilter) VisitGetJobsIdTagsResponse(w http.ResponseWriter) error { + return applyFilter(w, jq.body, jq.filter) +} + +func (jq JQFilter) VisitPostJobsIdTagsResponse(w http.ResponseWriter) error { + return applyFilter(w, jq.body, jq.filter) +} + +func (jq JQFilter) VisitGetVersionResponse(w http.ResponseWriter) error { + return applyFilter(w, jq.body, jq.filter) +} + +func (jq JQFilter) VisitGetWorkflowsResponse(w http.ResponseWriter) error { + return applyFilter(w, jq.body, jq.filter) +} + +func (jq JQFilter) VisitPostWorkflowsResponse(w http.ResponseWriter) error { + return applyFilter(w, jq.body, jq.filter) +} + +func (jq JQFilter) VisitDeleteWorkflowsNameResponse(w http.ResponseWriter) error { + return applyFilter(w, jq.body, jq.filter) +} + +func (jq JQFilter) VisitGetWorkflowsNameResponse(w http.ResponseWriter) error { + return applyFilter(w, jq.body, jq.filter) +} diff --git a/api/jq_test.go b/api/jq_test.go new file mode 100644 index 00000000..52d88b72 --- /dev/null +++ b/api/jq_test.go @@ -0,0 +1,66 @@ +package api + +/* + * SPDX-FileCopyrightText: 2024 Siemens AG + * + * SPDX-License-Identifier: Apache-2.0 + * + * Author: Michael Adler + */ + +import ( + "errors" + "io" + "net/http/httptest" + "reflect" + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestVisitMethod(t *testing.T) { + obj := map[string]string{"foo": "bar"} + filter := `.foo` + jqFilter := NewJQFilter(filter, obj) + + // Get the type and value of the struct + structType := reflect.TypeOf(jqFilter) + structValue := reflect.ValueOf(jqFilter) + + // Iterate through the methods of the struct + for i := 0; i < structType.NumMethod(); i++ { + method := structType.Method(i) + if strings.HasPrefix(method.Name, "Visit") { + t.Run(method.Name, func(t *testing.T) { + // Get the method by name + methodValue := structValue.MethodByName(method.Name) + + // Call the method + recorder := httptest.NewRecorder() + args := []reflect.Value{reflect.ValueOf(recorder)} + _ = methodValue.Call(args) + resp := recorder.Result() + assert.Equal(t, filter, resp.Header.Get("X-Response-Filter")) + body, _ := io.ReadAll(resp.Body) + assert.Equal(t, "\"bar\"\n", string(body)) + }) + } + } +} + +func TestApplyFilterInvalid(t *testing.T) { + err := applyFilter(nil, nil, "invalid filter") + assert.Error(t, err) +} + +type NoMarshal struct{} + +func (NoMarshal) MarshalJSON() ([]byte, error) { + return nil, errors.New("no marshal") +} + +func TestApplyFilterMarshalError(t *testing.T) { + err := applyFilter(nil, NoMarshal{}, "") + assert.Error(t, err) +} diff --git a/api/northbound.go b/api/northbound.go index 6629b989..312d581d 100644 --- a/api/northbound.go +++ b/api/northbound.go @@ -1,7 +1,7 @@ package api /* - * SPDX-FileCopyrightText: 2023 Siemens AG + * SPDX-FileCopyrightText: 2024 Siemens AG * * SPDX-License-Identifier: Apache-2.0 * @@ -9,296 +9,91 @@ package api */ import ( - "fmt" - "net/http" - "strings" + "context" - "github.com/Southclaws/fault/ftag" - "github.com/go-openapi/loads" - "github.com/go-openapi/runtime/middleware" - "github.com/siemens/wfx/generated/model" - "github.com/siemens/wfx/generated/northbound/restapi" - "github.com/siemens/wfx/generated/northbound/restapi/operations" - "github.com/siemens/wfx/generated/northbound/restapi/operations/northbound" - "github.com/siemens/wfx/internal/handler/job" - "github.com/siemens/wfx/internal/handler/job/definition" - "github.com/siemens/wfx/internal/handler/job/events" - "github.com/siemens/wfx/internal/handler/job/status" - "github.com/siemens/wfx/internal/handler/job/tags" - "github.com/siemens/wfx/internal/handler/workflow" - "github.com/siemens/wfx/middleware/logging" - "github.com/siemens/wfx/middleware/responder/sse" - "github.com/siemens/wfx/persistence" + "github.com/siemens/wfx/generated/api" ) -func NewNorthboundAPI(storage persistence.Storage) *operations.WorkflowExecutorAPI { - // NOTE: loads.Embedded only fails when given invalid JSON input; in our - // context, the JSON is always valid, so we may safely ignore the error. - swaggerSpec, _ := loads.Embedded(restapi.SwaggerJSON, restapi.FlatSwaggerJSON) - serverAPI := operations.NewWorkflowExecutorAPI(swaggerSpec) +// ensure that we fulfill the interface (compile-time check) +var _ api.StrictServerInterface = (*NorthboundServer)(nil) - serverAPI.NorthboundGetJobsHandler = northbound.GetJobsHandlerFunc( - func(params northbound.GetJobsParams) middleware.Responder { - filterParams := persistence.FilterParams{ - ClientID: params.ClientID, - Group: params.Group, - State: params.State, - Workflow: params.Workflow, - Tags: params.Tag, - } - paginationParams := persistence.PaginationParams{ - Offset: *params.Offset, - Limit: *params.Limit, - } - jobs, err := job.QueryJobs(params.HTTPRequest.Context(), storage, - filterParams, paginationParams, params.Sort) - if err != nil { - return northbound.NewGetJobsDefault(http.StatusInternalServerError) - } - return northbound.NewGetJobsOK().WithPayload(jobs) - }) +type NorthboundServer struct { + wfx *WfxServer +} - serverAPI.NorthboundGetJobsIDHandler = northbound.GetJobsIDHandlerFunc( - func(params northbound.GetJobsIDParams) middleware.Responder { - history := false - if params.History != nil { - history = *params.History - } - job, err := job.GetJob(params.HTTPRequest.Context(), storage, params.ID, history) - if ftag.Get(err) == ftag.NotFound { - return northbound.NewGetJobsIDNotFound().WithPayload(&model.ErrorResponse{ - Errors: []*model.Error{&JobNotFound}, - }) - } - if err != nil { - return northbound.NewGetJobsIDDefault(http.StatusInternalServerError) - } - return northbound.NewGetJobsIDOK().WithPayload(job) - }) +func NewNorthboundServer(wfx *WfxServer) NorthboundServer { + return NorthboundServer{wfx: wfx} +} - serverAPI.NorthboundGetJobsIDStatusHandler = northbound.GetJobsIDStatusHandlerFunc( - func(params northbound.GetJobsIDStatusParams) middleware.Responder { - status, err := status.Get(params.HTTPRequest.Context(), storage, params.ID) - if ftag.Get(err) == ftag.NotFound { - return northbound.NewGetJobsIDStatusNotFound().WithPayload(&model.ErrorResponse{ - Errors: []*model.Error{&JobNotFound}, - }) - } - if err != nil { - return northbound.NewGetJobsIDStatusDefault(http.StatusInternalServerError) - } - return northbound.NewGetJobsIDStatusOK().WithPayload(status) - }) +//revive:disable:var-naming +func (north NorthboundServer) GetJobs(ctx context.Context, request api.GetJobsRequestObject) (api.GetJobsResponseObject, error) { + return north.wfx.GetJobs(ctx, request) +} - serverAPI.NorthboundPutJobsIDStatusHandler = northbound.PutJobsIDStatusHandlerFunc( - func(params northbound.PutJobsIDStatusParams) middleware.Responder { - status, err := status.Update(params.HTTPRequest.Context(), storage, params.ID, params.NewJobStatus, model.EligibleEnumWFX) - if err != nil { - switch ftag.Get(err) { - case ftag.NotFound: - return northbound.NewPutJobsIDStatusNotFound().WithPayload(&model.ErrorResponse{ - Errors: []*model.Error{&JobNotFound}, - }) - case ftag.InvalidArgument: - err2 := InvalidRequest - err2.Message = err.Error() - return northbound.NewPutJobsIDStatusBadRequest().WithPayload(&model.ErrorResponse{Errors: []*model.Error{&err2}}) - default: - return northbound.NewPutJobsIDStatusDefault(http.StatusInternalServerError) - } - } - return northbound.NewPutJobsIDStatusOK().WithPayload(status) - }) +func (north NorthboundServer) PostJobs(ctx context.Context, request api.PostJobsRequestObject) (api.PostJobsResponseObject, error) { + return north.wfx.PostJobs(ctx, request) +} - serverAPI.NorthboundGetJobsIDDefinitionHandler = northbound.GetJobsIDDefinitionHandlerFunc( - func(params northbound.GetJobsIDDefinitionParams) middleware.Responder { - definition, err := definition.Get(params.HTTPRequest.Context(), storage, params.ID) - if ftag.Get(err) == ftag.NotFound { - return northbound.NewGetJobsIDDefinitionNotFound().WithPayload(&model.ErrorResponse{ - Errors: []*model.Error{&JobNotFound}, - }) - } - if err != nil { - return northbound.NewGetJobsIDDefinitionDefault(http.StatusInternalServerError) - } - return northbound.NewGetJobsIDDefinitionOK().WithPayload(definition) - }) - serverAPI.NorthboundPutJobsIDDefinitionHandler = northbound.PutJobsIDDefinitionHandlerFunc( - func(params northbound.PutJobsIDDefinitionParams) middleware.Responder { - definition, err := definition.Update(params.HTTPRequest.Context(), storage, params.ID, params.JobDefinition) - if ftag.Get(err) == ftag.NotFound { - return northbound.NewPutJobsIDDefinitionNotFound().WithPayload(&model.ErrorResponse{ - Errors: []*model.Error{&JobNotFound}, - }) - } - if err != nil { - return northbound.NewPutJobsIDDefinitionDefault(http.StatusInternalServerError) - } +func (north NorthboundServer) GetJobsEvents(ctx context.Context, request api.GetJobsEventsRequestObject) (api.GetJobsEventsResponseObject, error) { + return north.wfx.GetJobsEvents(ctx, request) +} - return northbound.NewPutJobsIDDefinitionOK().WithPayload(definition) - }) +func (north NorthboundServer) DeleteJobsId(ctx context.Context, request api.DeleteJobsIdRequestObject) (api.DeleteJobsIdResponseObject, error) { + return north.wfx.DeleteJobsId(ctx, request) +} - serverAPI.NorthboundGetWorkflowsNameHandler = northbound.GetWorkflowsNameHandlerFunc( - func(params northbound.GetWorkflowsNameParams) middleware.Responder { - workflow, err := workflow.GetWorkflow(params.HTTPRequest.Context(), storage, params.Name) - if ftag.Get(err) == ftag.NotFound { - return northbound.NewGetWorkflowsNameNotFound().WithPayload( - &model.ErrorResponse{ - Errors: []*model.Error{&WorkflowNotFound}, - }) - } - if err != nil { - return northbound.NewGetWorkflowsNameDefault(http.StatusInternalServerError) - } - return northbound.NewGetWorkflowsNameOK().WithPayload(workflow) - }) +func (north NorthboundServer) GetJobsId(ctx context.Context, request api.GetJobsIdRequestObject) (api.GetJobsIdResponseObject, error) { + return north.wfx.GetJobsId(ctx, request) +} - serverAPI.NorthboundGetWorkflowsHandler = northbound.GetWorkflowsHandlerFunc( - func(params northbound.GetWorkflowsParams) middleware.Responder { - pagination := persistence.PaginationParams{Offset: *params.Offset, Limit: *params.Limit} - ctx := params.HTTPRequest.Context() - log := logging.LoggerFromCtx(ctx) - workflows, err := workflow.QueryWorkflows(ctx, storage, pagination) - if err != nil { - log.Error().Err(err).Msg("Failed to query workflows") - return northbound.NewGetWorkflowsDefault(http.StatusInternalServerError) - } - return northbound.NewGetWorkflowsOK().WithPayload(workflows) - }) +func (north NorthboundServer) GetJobsIdDefinition(ctx context.Context, request api.GetJobsIdDefinitionRequestObject) (api.GetJobsIdDefinitionResponseObject, error) { + return north.wfx.GetJobsIdDefinition(ctx, request) +} + +func (north NorthboundServer) PutJobsIdDefinition(ctx context.Context, request api.PutJobsIdDefinitionRequestObject) (api.PutJobsIdDefinitionResponseObject, error) { + return north.wfx.PutJobsIdDefinition(ctx, request) +} - // not available southbound - serverAPI.NorthboundDeleteWorkflowsNameHandler = northbound.DeleteWorkflowsNameHandlerFunc( - func(params northbound.DeleteWorkflowsNameParams) middleware.Responder { - err := workflow.DeleteWorkflow(params.HTTPRequest.Context(), storage, params.Name) - if err != nil { - switch ftag.Get(err) { - case ftag.NotFound: - err2 := WorkflowNotFound - err2.Message = fmt.Sprintf("Workflow '%s' not found", params.Name) - return northbound.NewDeleteWorkflowsNameNotFound().WithPayload(&model.ErrorResponse{Errors: []*model.Error{&err2}}) - default: - return northbound.NewDeleteWorkflowsNameDefault(http.StatusInternalServerError) - } - } - return northbound.NewDeleteWorkflowsNameNoContent() - }) - serverAPI.NorthboundPostWorkflowsHandler = northbound.PostWorkflowsHandlerFunc( - func(params northbound.PostWorkflowsParams) middleware.Responder { - wf, err := workflow.CreateWorkflow(params.HTTPRequest.Context(), storage, params.Workflow) - if err != nil { - switch ftag.Get(err) { - case ftag.InvalidArgument: - err2 := WorkflowInvalid - err2.Message = err.Error() - return northbound.NewPostWorkflowsBadRequest().WithPayload(&model.ErrorResponse{Errors: []*model.Error{&err2}}) - case ftag.AlreadyExists: - err2 := WorkflowNotUnique - err2.Message = fmt.Sprintf("Workflow with name '%s' already exists", params.Workflow.Name) - return northbound.NewPostWorkflowsBadRequest().WithPayload(&model.ErrorResponse{Errors: []*model.Error{&err2}}) - default: - return northbound.NewPostWorkflowsDefault(http.StatusInternalServerError) - } - } - return northbound.NewPostWorkflowsCreated().WithPayload(wf) - }) - serverAPI.NorthboundPostJobsHandler = northbound.PostJobsHandlerFunc( - func(params northbound.PostJobsParams) middleware.Responder { - job, err := job.CreateJob(params.HTTPRequest.Context(), storage, params.Job) - if err != nil { - switch ftag.Get(err) { - case ftag.NotFound: - err2 := WorkflowNotFound - err2.Message = err.Error() - return northbound.NewPostJobsBadRequest().WithPayload(&model.ErrorResponse{Errors: []*model.Error{&err2}}) - default: - return northbound.NewPostJobsDefault(http.StatusInternalServerError) - } - } - return northbound.NewPostJobsCreated().WithPayload(job) - }) - serverAPI.NorthboundDeleteJobsIDHandler = northbound.DeleteJobsIDHandlerFunc( - func(params northbound.DeleteJobsIDParams) middleware.Responder { - err := job.DeleteJob(params.HTTPRequest.Context(), storage, params.ID) - if err != nil { - switch ftag.Get(err) { - case ftag.NotFound: - return northbound.NewDeleteJobsIDNotFound() - default: - return northbound.NewDeleteJobsIDDefault(http.StatusInternalServerError) - } - } - return northbound.NewDeleteJobsIDNoContent() - }) +func (north NorthboundServer) GetJobsIdStatus(ctx context.Context, request api.GetJobsIdStatusRequestObject) (api.GetJobsIdStatusResponseObject, error) { + return north.wfx.GetJobsIdStatus(ctx, request) +} - // tags - serverAPI.NorthboundGetJobsIDTagsHandler = northbound.GetJobsIDTagsHandlerFunc( - func(params northbound.GetJobsIDTagsParams) middleware.Responder { - tags, err := tags.Get(params.HTTPRequest.Context(), storage, params.ID) - if ftag.Get(err) == ftag.NotFound { - return northbound.NewGetJobsIDTagsNotFound().WithPayload(&model.ErrorResponse{ - Errors: []*model.Error{&JobNotFound}, - }) - } - if err != nil { - return northbound.NewGetJobsIDTagsDefault(http.StatusInternalServerError) - } - return northbound.NewGetJobsIDTagsOK().WithPayload(tags) - }) - serverAPI.NorthboundPostJobsIDTagsHandler = northbound.PostJobsIDTagsHandlerFunc( - func(params northbound.PostJobsIDTagsParams) middleware.Responder { - tags, err := tags.Add(params.HTTPRequest.Context(), storage, params.ID, params.Tags) - if ftag.Get(err) == ftag.NotFound { - return northbound.NewPostJobsIDTagsNotFound().WithPayload(&model.ErrorResponse{ - Errors: []*model.Error{&JobNotFound}, - }) - } - if err != nil { - return northbound.NewPostJobsIDTagsDefault(http.StatusInternalServerError) - } - return northbound.NewPostJobsIDTagsOK().WithPayload(tags) - }) - serverAPI.NorthboundDeleteJobsIDTagsHandler = northbound.DeleteJobsIDTagsHandlerFunc( - func(params northbound.DeleteJobsIDTagsParams) middleware.Responder { - tags, err := tags.Delete(params.HTTPRequest.Context(), storage, params.ID, params.Tags) - if ftag.Get(err) == ftag.NotFound { - return northbound.NewDeleteJobsIDTagsNotFound().WithPayload(&model.ErrorResponse{Errors: []*model.Error{&JobNotFound}}) - } - if err != nil { - return northbound.NewDeleteJobsIDTagsDefault(http.StatusInternalServerError) - } - return northbound.NewDeleteJobsIDTagsOK().WithPayload(tags) - }) +func (north NorthboundServer) PutJobsIdStatus(ctx context.Context, request api.PutJobsIdStatusRequestObject) (api.PutJobsIdStatusResponseObject, error) { + return north.wfx.PutJobsIdStatus(ctx, request, api.WFX) +} - serverAPI.NorthboundGetJobsEventsHandler = northbound.GetJobsEventsHandlerFunc( - func(params northbound.GetJobsEventsParams) middleware.Responder { - ctx := params.HTTPRequest.Context() - filter := parseFilterParamsNorth(params) - var tags []string - if s := params.Tags; s != nil { - tags = strings.Split(*s, ",") - } - eventChan, err := events.AddSubscriber(ctx, filter, tags) - if err != nil { - return northbound.NewGetJobsEventsDefault(http.StatusInternalServerError) - } - return sse.Responder(ctx, eventChan) - }) +func (north NorthboundServer) DeleteJobsIdTags(ctx context.Context, request api.DeleteJobsIdTagsRequestObject) (api.DeleteJobsIdTagsResponseObject, error) { + return north.wfx.DeleteJobsIdTags(ctx, request) +} + +func (north NorthboundServer) GetJobsIdTags(ctx context.Context, request api.GetJobsIdTagsRequestObject) (api.GetJobsIdTagsResponseObject, error) { + return north.wfx.GetJobsIdTags(ctx, request) +} + +func (north NorthboundServer) PostJobsIdTags(ctx context.Context, request api.PostJobsIdTagsRequestObject) (api.PostJobsIdTagsResponseObject, error) { + return north.wfx.PostJobsIdTags(ctx, request) +} + +func (north NorthboundServer) GetWorkflows(ctx context.Context, request api.GetWorkflowsRequestObject) (api.GetWorkflowsResponseObject, error) { + return north.wfx.GetWorkflows(ctx, request) +} + +func (north NorthboundServer) PostWorkflows(ctx context.Context, request api.PostWorkflowsRequestObject) (api.PostWorkflowsResponseObject, error) { + return north.wfx.PostWorkflows(ctx, request) +} + +func (north NorthboundServer) DeleteWorkflowsName(ctx context.Context, request api.DeleteWorkflowsNameRequestObject) (api.DeleteWorkflowsNameResponseObject, error) { + return north.wfx.DeleteWorkflowsName(ctx, request) +} + +func (north NorthboundServer) GetWorkflowsName(ctx context.Context, request api.GetWorkflowsNameRequestObject) (api.GetWorkflowsNameResponseObject, error) { + return north.wfx.GetWorkflowsName(ctx, request) +} - return serverAPI +func (north NorthboundServer) GetHealth(ctx context.Context, request api.GetHealthRequestObject) (api.GetHealthResponseObject, error) { + return north.wfx.GetHealth(ctx, request) } -func parseFilterParamsNorth(params northbound.GetJobsEventsParams) events.FilterParams { - // same code as parseFilterParamsSouth but params is from a different package; - // this isn't pretty (DRY) but we have a conceptually clear distinction - var filter events.FilterParams - if ids := params.JobIds; ids != nil { - filter.JobIDs = strings.Split(*ids, ",") - } - if ids := params.ClientIds; ids != nil { - filter.ClientIDs = strings.Split(*ids, ",") - } - if wfs := params.Workflows; wfs != nil { - filter.Workflows = strings.Split(*wfs, ",") - } - return filter +func (north NorthboundServer) GetVersion(ctx context.Context, request api.GetVersionRequestObject) (api.GetVersionResponseObject, error) { + return north.wfx.GetVersion(ctx, request) } diff --git a/api/northbound_test.go b/api/northbound_test.go index e8284127..1d11daf3 100644 --- a/api/northbound_test.go +++ b/api/northbound_test.go @@ -9,554 +9,246 @@ package api */ import ( - "bytes" + "context" "errors" - "fmt" "net/http" "net/http/httptest" "testing" "github.com/Southclaws/fault" "github.com/Southclaws/fault/ftag" - "github.com/siemens/wfx/generated/model" - "github.com/siemens/wfx/generated/northbound/restapi/operations/northbound" - "github.com/siemens/wfx/internal/producer" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/persistence" "github.com/siemens/wfx/workflow/dau" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) -func TestNorthboundGetJobsIDStatusHandler_NotFound(t *testing.T) { - params := northbound.NewGetJobsIDStatusParams() - jobID := "42" - params.ID = jobID - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, fault.Wrap(fmt.Errorf("job with id %s does not exist", jobID), ftag.With(ftag.NotFound))) - - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundGetJobsIDStatusHandler.Handle(params) - - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() - - assert.Equal(t, http.StatusNotFound, response.StatusCode) -} - -func TestNorthboundPutJobsIDStatusHandler_NotFound(t *testing.T) { - params := northbound.NewPutJobsIDStatusParams() - jobID := "42" - params.ID = jobID - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, fault.Wrap(fmt.Errorf("job with id %s does not exist", jobID), ftag.With(ftag.NotFound))) - - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundPutJobsIDStatusHandler.Handle(params) - - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() - - assert.Equal(t, http.StatusNotFound, response.StatusCode) -} - -func TestNorthboundGetJobsHandler_InternalError(t *testing.T) { - params := northbound.NewGetJobsParams() - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT(). - QueryJobs(params.HTTPRequest.Context(), persistence.FilterParams{}, persistence.SortParams{}, persistence.PaginationParams{Limit: 10}). - Return(nil, errors.New("something went wrong")) - - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundGetJobsHandler.Handle(params) - - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() - - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) -} - -func TestNorthboundGetJobsIDHandler_NotFound(t *testing.T) { - params := northbound.NewGetJobsIDParams() - - jobID := "42" - params.ID = jobID - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, fault.Wrap(fmt.Errorf("job with id %s does not exist", jobID), ftag.With(ftag.NotFound))) - - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundGetJobsIDHandler.Handle(params) - - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() - - assert.Equal(t, http.StatusNotFound, response.StatusCode) -} - -func TestNorthboundGetJobsIDHandler_InternalError(t *testing.T) { - params := northbound.NewGetJobsIDParams() - jobID := "42" - params.ID = jobID - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - history := true - params.History = &history - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{History: history}).Return(nil, errors.New("something went wrong")) - - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundGetJobsIDHandler.Handle(params) - - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() - - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) -} - -func TestNorthboundGetJobsIDStatusHandler_InternalError(t *testing.T) { - params := northbound.NewGetJobsIDStatusParams() - jobID := "42" - params.ID = jobID - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, errors.New("something went wrong")) - - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundGetJobsIDStatusHandler.Handle(params) - - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() - - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) -} - -func TestNorthboundPutJobsIDStatusHandler_InternalError(t *testing.T) { - params := northbound.NewPutJobsIDStatusParams() - jobID := "42" - params.ID = jobID - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, errors.New("something went wrong")) - - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundPutJobsIDStatusHandler.Handle(params) - - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() - - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) -} - -func TestNorthboundGetJobsIDDefinitionHandler_NotFound(t *testing.T) { - params := northbound.NewGetJobsIDDefinitionParams() - jobID := "42" - params.ID = jobID - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, fault.Wrap(fmt.Errorf("job with id %s does not exist", jobID), ftag.With(ftag.NotFound))) - - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundGetJobsIDDefinitionHandler.Handle(params) - - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() - - assert.Equal(t, http.StatusNotFound, response.StatusCode) -} - -func TestNorthboundGetJobsIDDefinitionHandler_InternalError(t *testing.T) { - params := northbound.NewGetJobsIDDefinitionParams() - jobID := "42" - params.ID = jobID - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, errors.New("something went wrong")) - - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundGetJobsIDDefinitionHandler.Handle(params) - - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() - - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) -} - -func TestNorthboundPutJobsIDDefinitionHandler_NotFound(t *testing.T) { - params := northbound.NewPutJobsIDDefinitionParams() - jobID := "42" - params.ID = jobID - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, fault.Wrap(fmt.Errorf("job with id %s does not exist", jobID), ftag.With(ftag.NotFound))) - - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundPutJobsIDDefinitionHandler.Handle(params) - - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() - - assert.Equal(t, http.StatusNotFound, response.StatusCode) -} - -func TestNorthboundPutJobsIDDefinitionHandler_InternalError(t *testing.T) { - params := northbound.NewPutJobsIDDefinitionParams() - jobID := "42" - params.ID = jobID - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, errors.New("something went wrong")) - - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundPutJobsIDDefinitionHandler.Handle(params) - - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() - - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) -} - -func TestNorthboundGetWorkflowsNameHandler_InternalError(t *testing.T) { - params := northbound.NewGetWorkflowsNameParams() - params.Name = "wfx.test.workflow" - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetWorkflow(params.HTTPRequest.Context(), params.Name).Return(nil, errors.New("something went wrong")) - - api := NewNorthboundAPI(dbMock) - - resp := api.NorthboundGetWorkflowsNameHandler.Handle(params) - - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() - - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) -} - -func TestNorthboundGetWorkflowsHandler_InternalError(t *testing.T) { - params := northbound.NewGetWorkflowsParams() - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().QueryWorkflows(params.HTTPRequest.Context(), persistence.PaginationParams{Limit: 10}).Return(nil, errors.New("something went wrong")) - - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundGetWorkflowsHandler.Handle(params) - - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() - - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) -} - -func TestNorthboundGetWorkflowsHandler_Empty(t *testing.T) { - params := northbound.NewGetWorkflowsParams() - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().QueryWorkflows(params.HTTPRequest.Context(), persistence.PaginationParams{Limit: 10}).Return(nil, nil) - - api := NewNorthboundAPI(dbMock) - - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - resp := api.NorthboundGetWorkflowsHandler.Handle(params) - - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() - - assert.Equal(t, http.StatusOK, response.StatusCode) -} - func TestNorthboundDeleteWorkflowsNameHandle_NotFound(t *testing.T) { - params := northbound.NewDeleteWorkflowsNameParams() - params.Name = "wfx.workflow.test" - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().DeleteWorkflow(params.HTTPRequest.Context(), params.Name).Return(fault.Wrap(errors.New("workflow not found"), ftag.With(ftag.NotFound))) + workflow := "wfx.workflow.test" - api := NewNorthboundAPI(dbMock) + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().DeleteWorkflow(context.Background(), workflow).Return(fault.Wrap(errors.New("workflow not found"), ftag.With(ftag.NotFound))) - resp := api.NorthboundDeleteWorkflowsNameHandler.Handle(params) + wfx := NewWfxServer(dbMock) + t.Cleanup(func() { wfx.Stop() }) + server := NewNorthboundServer(wfx) + resp, err := server.DeleteWorkflowsName(context.Background(), api.DeleteWorkflowsNameRequestObject{Name: workflow}) + assert.NoError(t, err) recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) + _ = resp.VisitDeleteWorkflowsNameResponse(recorder) response := recorder.Result() assert.Equal(t, http.StatusNotFound, response.StatusCode) } func TestNorthboundDeleteWorkflowsNameHandle_InternalError(t *testing.T) { - params := northbound.NewDeleteWorkflowsNameParams() - params.Name = "wfx.workflow.test" - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().DeleteWorkflow(params.HTTPRequest.Context(), params.Name).Return(errors.New("something went wrong")) + workflow := "wfx.workflow.test" - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundDeleteWorkflowsNameHandler.Handle(params) - - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().DeleteWorkflow(context.Background(), workflow).Return(errors.New("something went wrong")) - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) + wfx := NewWfxServer(dbMock) + t.Cleanup(func() { wfx.Stop() }) + server := NewNorthboundServer(wfx) + resp, err := server.DeleteWorkflowsName(context.Background(), api.DeleteWorkflowsNameRequestObject{Name: workflow}) + assert.Error(t, err) + assert.Nil(t, resp) } -func TestNorthboundPostWorkflowsHandler_InternalError(t *testing.T) { - params := northbound.NewPostWorkflowsParams() - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - params.Workflow = dau.DirectWorkflow() - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().CreateWorkflow(params.HTTPRequest.Context(), params.Workflow).Return(nil, errors.New("something went wrong")) +func TestNorthboundPostWorkflows_InternalError(t *testing.T) { + workflow := dau.DirectWorkflow() + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().CreateWorkflow(context.Background(), workflow).Return(nil, errors.New("something went wrong")) - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundPostWorkflowsHandler.Handle(params) + wfx := NewWfxServer(dbMock) + t.Cleanup(func() { wfx.Stop() }) + server := NewNorthboundServer(wfx) + resp, err := server.PostWorkflows(context.Background(), api.PostWorkflowsRequestObject{Body: workflow}) + assert.Error(t, err) + assert.Nil(t, resp) +} - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() +func TestNorthboundPostWorkflows_AlreadyExists(t *testing.T) { + workflow := dau.DirectWorkflow() - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) -} + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().CreateWorkflow(context.Background(), workflow).Return(nil, fault.Wrap(errors.New("already exists"), ftag.With(ftag.AlreadyExists))) -func TestNorthboundPostWorkflowsHandler_AlreadyExists(t *testing.T) { - params := northbound.NewPostWorkflowsParams() - params.Workflow = dau.DirectWorkflow() - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().CreateWorkflow(params.HTTPRequest.Context(), params.Workflow).Return(nil, fault.Wrap(errors.New("already exists"), ftag.With(ftag.AlreadyExists))) + wfx := NewWfxServer(dbMock) + t.Cleanup(func() { wfx.Stop() }) + server := NewNorthboundServer(wfx) - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundPostWorkflowsHandler.Handle(params) + resp, err := server.PostWorkflows(context.Background(), api.PostWorkflowsRequestObject{Body: workflow}) + assert.NoError(t, err) recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) + _ = resp.VisitPostWorkflowsResponse(recorder) response := recorder.Result() assert.Equal(t, http.StatusBadRequest, response.StatusCode) } -func TestNorthboundPostWorkflowsHandler_InvalidWorkflow(t *testing.T) { - params := northbound.NewPostWorkflowsParams() - params.Workflow = &model.Workflow{Name: "foo"} - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) +func TestNorthboundPostWorkflows_InvalidWorkflow(t *testing.T) { + workflow := &api.Workflow{Name: "foo"} - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundPostWorkflowsHandler.Handle(params) + dbMock := persistence.NewHealthyMockStorage(t) - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() - - assert.Equal(t, http.StatusBadRequest, response.StatusCode) -} + wfx := NewWfxServer(dbMock) + t.Cleanup(func() { wfx.Stop() }) + server := NewNorthboundServer(wfx) -func TestNorthboundPostJobsHandler_BadRequest(t *testing.T) { - params := northbound.NewPostJobsParams() - wf := dau.DirectWorkflow() - params.Job = &model.JobRequest{Workflow: wf.Name} - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetWorkflow(params.HTTPRequest.Context(), params.Job.Workflow).Return(nil, fault.Wrap(errors.New("invalid"), ftag.With(ftag.NotFound))) - - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundPostJobsHandler.Handle(params) + resp, err := server.PostWorkflows(context.Background(), api.PostWorkflowsRequestObject{Body: workflow}) + assert.NoError(t, err) recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) + _ = resp.VisitPostWorkflowsResponse(recorder) response := recorder.Result() assert.Equal(t, http.StatusBadRequest, response.StatusCode) } -func TestNorthboundPostJobsHandler_InternalError(t *testing.T) { +func TestNorthboundPostJobs_BadRequest(t *testing.T) { wf := dau.DirectWorkflow() - params := northbound.NewPostJobsParams() - params.Job = &model.JobRequest{Workflow: wf.Name} - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetWorkflow(params.HTTPRequest.Context(), params.Job.Workflow).Return(wf, nil) - dbMock.EXPECT().CreateJob(params.HTTPRequest.Context(), mock.Anything).Return(nil, errors.New("something went wrong")) - - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundPostJobsHandler.Handle(params) - - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() + jobRequest := api.JobRequest{Workflow: wf.Name} - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) -} + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().GetWorkflow(context.Background(), wf.Name).Return(nil, fault.Wrap(errors.New("invalid"), ftag.With(ftag.NotFound))) -func TestNorthboundDeleteJobsIDHandler_NotFound(t *testing.T) { - params := northbound.NewDeleteJobsIDParams() - params.ID = "42" - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) + wfx := NewWfxServer(dbMock) + t.Cleanup(func() { wfx.Stop() }) + server := NewNorthboundServer(wfx) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(&model.Job{}, nil) - dbMock.EXPECT().DeleteJob(params.HTTPRequest.Context(), params.ID).Return(fault.Wrap(errors.New("not found"), ftag.With(ftag.NotFound))) - - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundDeleteJobsIDHandler.Handle(params) + resp, err := server.PostJobs(context.Background(), api.PostJobsRequestObject{Body: &jobRequest}) + assert.NoError(t, err) recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) + _ = resp.VisitPostJobsResponse(recorder) response := recorder.Result() - assert.Equal(t, http.StatusNotFound, response.StatusCode) + assert.Equal(t, http.StatusBadRequest, response.StatusCode) } -func TestNorthboundDeleteJobsIDHandler_InternalError(t *testing.T) { - params := northbound.NewDeleteJobsIDParams() - params.ID = "42" - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(&model.Job{}, nil) - dbMock.EXPECT().DeleteJob(params.HTTPRequest.Context(), params.ID).Return(fault.Wrap(errors.New("something went wrong"), ftag.With(ftag.Internal))) +func TestNorthboundPostJobs_InternalError(t *testing.T) { + wf := dau.DirectWorkflow() + jobRequest := api.JobRequest{Workflow: wf.Name} - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundDeleteJobsIDHandler.Handle(params) + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().GetWorkflow(context.Background(), wf.Name).Return(wf, nil) + dbMock.EXPECT().CreateJob(context.Background(), mock.Anything).Return(nil, errors.New("something went wrong")) - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() + wfx := NewWfxServer(dbMock) + t.Cleanup(func() { wfx.Stop() }) + server := NewNorthboundServer(wfx) - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) + resp, err := server.PostJobs(context.Background(), api.PostJobsRequestObject{Body: &jobRequest}) + assert.Error(t, err) + assert.Nil(t, resp) } -func TestNorthboundGetJobsIDTagsHandler_NotFound(t *testing.T) { - params := northbound.NewGetJobsIDTagsParams() - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) +func TestNorthboundDeleteJobsID_NotFound(t *testing.T) { + jobID := "42" + + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().GetJob(context.Background(), jobID, persistence.FetchParams{}).Return(nil, fault.Wrap(errors.New("not found"), ftag.With(ftag.NotFound))) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, fault.Wrap(errors.New("not found"), ftag.With(ftag.NotFound))) + wfx := NewWfxServer(dbMock) + t.Cleanup(func() { wfx.Stop() }) + server := NewNorthboundServer(wfx) - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundGetJobsIDTagsHandler.Handle(params) + resp, err := server.DeleteJobsId(context.Background(), api.DeleteJobsIdRequestObject{Id: jobID}) + assert.NoError(t, err) recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) + _ = resp.VisitDeleteJobsIdResponse(recorder) response := recorder.Result() assert.Equal(t, http.StatusNotFound, response.StatusCode) } -func TestNorthboundGetJobsIDTagsHandler_InternalError(t *testing.T) { - params := northbound.NewGetJobsIDTagsParams() - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, fault.Wrap(errors.New("something went wrong"), ftag.With(ftag.Internal))) +func TestNorthboundDeleteJobsID_InternalError(t *testing.T) { + jobID := "42" - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundGetJobsIDTagsHandler.Handle(params) + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().GetJob(context.Background(), jobID, persistence.FetchParams{}).Return(&api.Job{ID: jobID}, nil) + dbMock.EXPECT().DeleteJob(context.Background(), jobID).Return(fault.Wrap(errors.New("something went wrong"), ftag.With(ftag.Internal))) - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() + wfx := NewWfxServer(dbMock) + t.Cleanup(func() { wfx.Stop() }) + server := NewNorthboundServer(wfx) - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) + resp, err := server.DeleteJobsId(context.Background(), api.DeleteJobsIdRequestObject{Id: jobID}) + assert.Error(t, err) + assert.Nil(t, resp) } -func TestNorthboundPostJobsIDTagsHandler_NotFound(t *testing.T) { - params := northbound.NewPostJobsIDTagsParams() - params.ID = "42" - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) +func TestNorthboundPostJobsIDTags_NotFound(t *testing.T) { + jobID := "42" + + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().GetJob(context.Background(), jobID, persistence.FetchParams{}).Return(nil, fault.Wrap(errors.New("not found"), ftag.With(ftag.NotFound))) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, fault.Wrap(errors.New("not found"), ftag.With(ftag.NotFound))) + wfx := NewWfxServer(dbMock) + t.Cleanup(func() { wfx.Stop() }) + server := NewNorthboundServer(wfx) - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundPostJobsIDTagsHandler.Handle(params) + resp, err := server.PostJobsIdTags(context.Background(), api.PostJobsIdTagsRequestObject{Id: jobID}) + assert.NoError(t, err) recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) + _ = resp.VisitPostJobsIdTagsResponse(recorder) response := recorder.Result() assert.Equal(t, http.StatusNotFound, response.StatusCode) } -func TestNorthboundPostJobsIDTagsHandler_InternalError(t *testing.T) { - params := northbound.NewPostJobsIDTagsParams() - params.ID = "42" - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, fault.Wrap(errors.New("something went wrong"), ftag.With(ftag.Internal))) +func TestNorthboundPostJobsIDTags_InternalError(t *testing.T) { + jobID := "42" - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundPostJobsIDTagsHandler.Handle(params) + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().GetJob(context.Background(), jobID, persistence.FetchParams{}).Return(nil, fault.Wrap(errors.New("something went wrong"), ftag.With(ftag.Internal))) - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() + wfx := NewWfxServer(dbMock) + t.Cleanup(func() { wfx.Stop() }) + server := NewNorthboundServer(wfx) - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) + resp, err := server.PostJobsIdTags(context.Background(), api.PostJobsIdTagsRequestObject{Id: jobID}) + assert.Error(t, err) + assert.Nil(t, resp) } -func TestNorthboundDeleteJobsIDTagsHandler_NotFound(t *testing.T) { - params := northbound.NewDeleteJobsIDTagsParams() - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) +func TestNorthboundDeleteJobsIDTags_NotFound(t *testing.T) { + jobID := "42" - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, fault.Wrap(errors.New("not found"), ftag.With(ftag.NotFound))) + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().GetJob(context.Background(), jobID, persistence.FetchParams{}).Return(nil, fault.Wrap(errors.New("not found"), ftag.With(ftag.NotFound))) - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundDeleteJobsIDTagsHandler.Handle(params) + wfx := NewWfxServer(dbMock) + t.Cleanup(func() { wfx.Stop() }) + server := NewNorthboundServer(wfx) + + resp, err := server.DeleteJobsIdTags(context.Background(), api.DeleteJobsIdTagsRequestObject{Id: jobID}) + assert.NoError(t, err) recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) + _ = resp.VisitDeleteJobsIdTagsResponse(recorder) response := recorder.Result() assert.Equal(t, http.StatusNotFound, response.StatusCode) } -func TestNorthboundDeleteJobsIDTagsHandler_InternalError(t *testing.T) { - params := northbound.NewDeleteJobsIDTagsParams() - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, fault.Wrap(errors.New("not found"), ftag.With(ftag.Internal))) +func TestNorthboundDeleteJobsIDTags_InternalError(t *testing.T) { + jobID := "42" - api := NewNorthboundAPI(dbMock) - resp := api.NorthboundDeleteJobsIDTagsHandler.Handle(params) + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().GetJob(context.Background(), jobID, persistence.FetchParams{}).Return(nil, fault.Wrap(errors.New("not found"), ftag.With(ftag.Internal))) - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() - - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) -} + wfx := NewWfxServer(dbMock) + t.Cleanup(func() { wfx.Stop() }) + server := NewNorthboundServer(wfx) -func TestParseFilterParamsNorth(t *testing.T) { - jobIDs := "abc,424-194-123" - clientIDs := "alpha,beta" - workflows := "wf1,wf2,wf3" - params := northbound.GetJobsEventsParams{ - HTTPRequest: &http.Request{}, - JobIds: &jobIDs, - ClientIds: &clientIDs, - Workflows: &workflows, - } - filter := parseFilterParamsNorth(params) - assert.Equal(t, []string{"abc", "424-194-123"}, filter.JobIDs) - assert.Equal(t, []string{"alpha", "beta"}, filter.ClientIDs) - assert.Equal(t, []string{"wf1", "wf2", "wf3"}, filter.Workflows) + resp, err := server.DeleteJobsIdTags(context.Background(), api.DeleteJobsIdTagsRequestObject{Id: jobID}) + assert.Error(t, err) + assert.Nil(t, resp) } diff --git a/api/southbound.go b/api/southbound.go index 26d5fb12..cf0f5027 100644 --- a/api/southbound.go +++ b/api/southbound.go @@ -1,7 +1,7 @@ package api /* - * SPDX-FileCopyrightText: 2023 Siemens AG + * SPDX-FileCopyrightText: 2024 Siemens AG * * SPDX-License-Identifier: Apache-2.0 * @@ -9,204 +9,91 @@ package api */ import ( - "net/http" - "strings" - - "github.com/Southclaws/fault/ftag" - "github.com/go-openapi/loads" - "github.com/go-openapi/runtime/middleware" - "github.com/siemens/wfx/generated/model" - "github.com/siemens/wfx/generated/southbound/restapi" - "github.com/siemens/wfx/generated/southbound/restapi/operations" - "github.com/siemens/wfx/generated/southbound/restapi/operations/southbound" - "github.com/siemens/wfx/internal/handler/job" - "github.com/siemens/wfx/internal/handler/job/definition" - "github.com/siemens/wfx/internal/handler/job/events" - "github.com/siemens/wfx/internal/handler/job/status" - "github.com/siemens/wfx/internal/handler/job/tags" - "github.com/siemens/wfx/internal/handler/workflow" - "github.com/siemens/wfx/middleware/logging" - "github.com/siemens/wfx/middleware/responder/sse" - "github.com/siemens/wfx/persistence" + "context" + + "github.com/siemens/wfx/generated/api" ) -func NewSouthboundAPI(storage persistence.Storage) *operations.WorkflowExecutorAPI { - // NOTE: loads.Embedded only fails when given invalid JSON input; in our - // context, the JSON is always valid, so we may safely ignore the error. - swaggerSpec, _ := loads.Embedded(restapi.SwaggerJSON, restapi.FlatSwaggerJSON) - serverAPI := operations.NewWorkflowExecutorAPI(swaggerSpec) - - serverAPI.SouthboundGetJobsHandler = southbound.GetJobsHandlerFunc( - func(params southbound.GetJobsParams) middleware.Responder { - filterParams := persistence.FilterParams{ - ClientID: params.ClientID, - Group: params.Group, - State: params.State, - Workflow: params.Workflow, - Tags: params.Tag, - } - paginationParams := persistence.PaginationParams{ - Offset: *params.Offset, - Limit: *params.Limit, - } - jobs, err := job.QueryJobs(params.HTTPRequest.Context(), storage, - filterParams, paginationParams, params.Sort) - if err != nil { - return southbound.NewGetJobsDefault(http.StatusInternalServerError) - } - return southbound.NewGetJobsOK().WithPayload(jobs) - }) - serverAPI.SouthboundGetJobsIDHandler = southbound.GetJobsIDHandlerFunc( - func(params southbound.GetJobsIDParams) middleware.Responder { - history := false - if params.History != nil { - history = *params.History - } - job, err := job.GetJob(params.HTTPRequest.Context(), storage, params.ID, history) - if ftag.Get(err) == ftag.NotFound { - return southbound.NewGetJobsIDNotFound().WithPayload(&model.ErrorResponse{ - Errors: []*model.Error{&JobNotFound}, - }) - } - if err != nil { - return southbound.NewGetJobsIDDefault(http.StatusInternalServerError) - } - return southbound.NewGetJobsIDOK().WithPayload(job) - }) - - serverAPI.SouthboundGetJobsIDStatusHandler = southbound.GetJobsIDStatusHandlerFunc( - func(params southbound.GetJobsIDStatusParams) middleware.Responder { - status, err := status.Get(params.HTTPRequest.Context(), storage, params.ID) - if ftag.Get(err) == ftag.NotFound { - return southbound.NewGetJobsIDStatusNotFound().WithPayload(&model.ErrorResponse{ - Errors: []*model.Error{&JobNotFound}, - }) - } - if err != nil { - return southbound.NewGetJobsIDStatusDefault(http.StatusInternalServerError) - } - return southbound.NewGetJobsIDStatusOK().WithPayload(status) - }) - - serverAPI.SouthboundPutJobsIDStatusHandler = southbound.PutJobsIDStatusHandlerFunc( - func(params southbound.PutJobsIDStatusParams) middleware.Responder { - status, err := status.Update(params.HTTPRequest.Context(), storage, params.ID, params.NewJobStatus, model.EligibleEnumCLIENT) - if err != nil { - switch ftag.Get(err) { - case ftag.NotFound: - return southbound.NewPutJobsIDStatusNotFound().WithPayload(&model.ErrorResponse{ - Errors: []*model.Error{&JobNotFound}, - }) - case ftag.InvalidArgument: - err2 := InvalidRequest - err2.Message = err.Error() - return southbound.NewPutJobsIDStatusBadRequest().WithPayload(&model.ErrorResponse{Errors: []*model.Error{&err2}}) - default: - return southbound.NewPutJobsIDStatusDefault(http.StatusInternalServerError) - } - } - return southbound.NewPutJobsIDStatusOK().WithPayload(status) - }) - - serverAPI.SouthboundGetJobsIDDefinitionHandler = southbound.GetJobsIDDefinitionHandlerFunc( - func(params southbound.GetJobsIDDefinitionParams) middleware.Responder { - definition, err := definition.Get(params.HTTPRequest.Context(), storage, params.ID) - if ftag.Get(err) == ftag.NotFound { - return southbound.NewGetJobsIDDefinitionNotFound().WithPayload(&model.ErrorResponse{ - Errors: []*model.Error{&JobNotFound}, - }) - } - if err != nil { - return southbound.NewGetJobsIDDefinitionDefault(http.StatusInternalServerError) - } - return southbound.NewGetJobsIDDefinitionOK().WithPayload(definition) - }) - serverAPI.SouthboundPutJobsIDDefinitionHandler = southbound.PutJobsIDDefinitionHandlerFunc( - func(params southbound.PutJobsIDDefinitionParams) middleware.Responder { - definition, err := definition.Update(params.HTTPRequest.Context(), storage, params.ID, params.JobDefinition) - if ftag.Get(err) == ftag.NotFound { - return southbound.NewPutJobsIDDefinitionNotFound().WithPayload(&model.ErrorResponse{ - Errors: []*model.Error{&JobNotFound}, - }) - } - if err != nil { - return southbound.NewPutJobsIDDefinitionDefault(http.StatusInternalServerError) - } - return southbound.NewPutJobsIDDefinitionOK().WithPayload(definition) - }) - - serverAPI.SouthboundGetWorkflowsNameHandler = southbound.GetWorkflowsNameHandlerFunc( - func(params southbound.GetWorkflowsNameParams) middleware.Responder { - workflow, err := workflow.GetWorkflow(params.HTTPRequest.Context(), storage, params.Name) - if ftag.Get(err) == ftag.NotFound { - return southbound.NewGetWorkflowsNameNotFound().WithPayload( - &model.ErrorResponse{ - Errors: []*model.Error{&WorkflowNotFound}, - }) - } - if err != nil { - return southbound.NewGetWorkflowsNameDefault(http.StatusInternalServerError) - } - return southbound.NewGetWorkflowsNameOK().WithPayload(workflow) - }) - - serverAPI.SouthboundGetWorkflowsHandler = southbound.GetWorkflowsHandlerFunc( - func(params southbound.GetWorkflowsParams) middleware.Responder { - pagination := persistence.PaginationParams{Offset: *params.Offset, Limit: *params.Limit} - ctx := params.HTTPRequest.Context() - log := logging.LoggerFromCtx(ctx) - workflows, err := workflow.QueryWorkflows(ctx, storage, pagination) - if err != nil { - log.Error().Err(err).Msg("Failed to query workflows") - return southbound.NewGetWorkflowsDefault(http.StatusInternalServerError) - } - return southbound.NewGetWorkflowsOK().WithPayload(workflows) - }) - - serverAPI.SouthboundGetJobsIDTagsHandler = southbound.GetJobsIDTagsHandlerFunc( - func(params southbound.GetJobsIDTagsParams) middleware.Responder { - tags, err := tags.Get(params.HTTPRequest.Context(), storage, params.ID) - if ftag.Get(err) == ftag.NotFound { - return southbound.NewGetJobsIDTagsNotFound().WithPayload(&model.ErrorResponse{ - Errors: []*model.Error{&JobNotFound}, - }) - } - if err != nil { - return southbound.NewGetJobsIDTagsDefault(http.StatusInternalServerError) - } - return southbound.NewGetJobsIDTagsOK().WithPayload(tags) - }) - - serverAPI.SouthboundGetJobsEventsHandler = southbound.GetJobsEventsHandlerFunc( - func(params southbound.GetJobsEventsParams) middleware.Responder { - ctx := params.HTTPRequest.Context() - filter := parseFilterParamsSouth(params) - var tags []string - if s := params.Tags; s != nil { - tags = strings.Split(*s, ",") - } - eventChan, err := events.AddSubscriber(ctx, filter, tags) - if err != nil { - return southbound.NewGetJobsEventsDefault(http.StatusInternalServerError) - } - return sse.Responder(ctx, eventChan) - }) - - return serverAPI -} - -func parseFilterParamsSouth(params southbound.GetJobsEventsParams) events.FilterParams { - // same code as parseFilterParamsNorth but params is from a different package; - // this isn't pretty (DRY) but we have a conceptually clear distinction - var filter events.FilterParams - if ids := params.JobIds; ids != nil { - filter.JobIDs = strings.Split(*ids, ",") - } - if ids := params.ClientIds; ids != nil { - filter.ClientIDs = strings.Split(*ids, ",") - } - if wfs := params.Workflows; wfs != nil { - filter.Workflows = strings.Split(*wfs, ",") - } - return filter +// ensure that we fulfill the interface (compile-time check) +var _ api.StrictServerInterface = (*SouthboundServer)(nil) + +type SouthboundServer struct { + wfx *WfxServer +} + +func NewSouthboundServer(wfx *WfxServer) SouthboundServer { + return SouthboundServer{wfx: wfx} +} + +//revive:disable:var-naming +func (south SouthboundServer) GetJobs(ctx context.Context, request api.GetJobsRequestObject) (api.GetJobsResponseObject, error) { + return south.wfx.GetJobs(ctx, request) +} + +func (south SouthboundServer) PostJobs(context.Context, api.PostJobsRequestObject) (api.PostJobsResponseObject, error) { + return api.PostJobs403Response{}, nil +} + +func (south SouthboundServer) GetJobsEvents(ctx context.Context, request api.GetJobsEventsRequestObject) (api.GetJobsEventsResponseObject, error) { + return south.wfx.GetJobsEvents(ctx, request) +} + +func (south SouthboundServer) DeleteJobsId(context.Context, api.DeleteJobsIdRequestObject) (api.DeleteJobsIdResponseObject, error) { + return api.DeleteJobsId403Response{}, nil +} + +func (south SouthboundServer) GetJobsId(ctx context.Context, request api.GetJobsIdRequestObject) (api.GetJobsIdResponseObject, error) { + return south.wfx.GetJobsId(ctx, request) +} + +func (south SouthboundServer) GetJobsIdDefinition(ctx context.Context, request api.GetJobsIdDefinitionRequestObject) (api.GetJobsIdDefinitionResponseObject, error) { + return south.wfx.GetJobsIdDefinition(ctx, request) +} + +func (south SouthboundServer) PutJobsIdDefinition(ctx context.Context, request api.PutJobsIdDefinitionRequestObject) (api.PutJobsIdDefinitionResponseObject, error) { + return south.wfx.PutJobsIdDefinition(ctx, request) +} + +func (south SouthboundServer) GetJobsIdStatus(ctx context.Context, request api.GetJobsIdStatusRequestObject) (api.GetJobsIdStatusResponseObject, error) { + return south.wfx.GetJobsIdStatus(ctx, request) +} + +func (south SouthboundServer) PutJobsIdStatus(ctx context.Context, request api.PutJobsIdStatusRequestObject) (api.PutJobsIdStatusResponseObject, error) { + return south.wfx.PutJobsIdStatus(ctx, request, api.CLIENT) +} + +func (south SouthboundServer) DeleteJobsIdTags(context.Context, api.DeleteJobsIdTagsRequestObject) (api.DeleteJobsIdTagsResponseObject, error) { + return api.DeleteJobsIdTags403Response{}, nil +} + +func (south SouthboundServer) GetJobsIdTags(ctx context.Context, request api.GetJobsIdTagsRequestObject) (api.GetJobsIdTagsResponseObject, error) { + return south.wfx.GetJobsIdTags(ctx, request) +} + +func (south SouthboundServer) PostJobsIdTags(context.Context, api.PostJobsIdTagsRequestObject) (api.PostJobsIdTagsResponseObject, error) { + return api.PostJobsIdTags403Response{}, nil +} + +func (south SouthboundServer) GetWorkflows(ctx context.Context, request api.GetWorkflowsRequestObject) (api.GetWorkflowsResponseObject, error) { + return south.wfx.GetWorkflows(ctx, request) +} + +func (south SouthboundServer) PostWorkflows(context.Context, api.PostWorkflowsRequestObject) (api.PostWorkflowsResponseObject, error) { + return api.PostWorkflows403Response{}, nil +} + +func (south SouthboundServer) DeleteWorkflowsName(context.Context, api.DeleteWorkflowsNameRequestObject) (api.DeleteWorkflowsNameResponseObject, error) { + return api.DeleteWorkflowsName403Response{}, nil +} + +func (south SouthboundServer) GetWorkflowsName(ctx context.Context, request api.GetWorkflowsNameRequestObject) (api.GetWorkflowsNameResponseObject, error) { + return south.wfx.GetWorkflowsName(ctx, request) +} + +func (south SouthboundServer) GetHealth(ctx context.Context, request api.GetHealthRequestObject) (api.GetHealthResponseObject, error) { + return south.wfx.GetHealth(ctx, request) +} + +func (south SouthboundServer) GetVersion(ctx context.Context, request api.GetVersionRequestObject) (api.GetVersionResponseObject, error) { + return south.wfx.GetVersion(ctx, request) } diff --git a/api/southbound_test.go b/api/southbound_test.go index d2b2e6a2..da5aae24 100644 --- a/api/southbound_test.go +++ b/api/southbound_test.go @@ -1,7 +1,7 @@ package api /* - * SPDX-FileCopyrightText: 2023 Siemens AG + * SPDX-FileCopyrightText: 2024 Siemens AG * * SPDX-License-Identifier: Apache-2.0 * @@ -9,320 +9,351 @@ package api */ import ( - "bytes" + "context" "errors" "fmt" "net/http" "net/http/httptest" "testing" + "time" "github.com/Southclaws/fault" "github.com/Southclaws/fault/ftag" - "github.com/siemens/wfx/generated/southbound/restapi/operations/southbound" - "github.com/siemens/wfx/internal/producer" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/persistence" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) -func TestSouthboundGetJobsIDStatusHandler_NotFound(t *testing.T) { - params := southbound.NewGetJobsIDStatusParams() - jobID := "42" - params.ID = jobID - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, fault.Wrap(fmt.Errorf("job with id %s does not exist", jobID), ftag.With(ftag.NotFound))) - - api := NewSouthboundAPI(dbMock) - resp := api.SouthboundGetJobsIDStatusHandler.Handle(params) +var allOrientations = []string{"north", "south"} - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() - - assert.Equal(t, http.StatusNotFound, response.StatusCode) +func createServerForTesting(t *testing.T, orientation string, db persistence.Storage) api.StrictServerInterface { + wfx := NewWfxServer(db) + wfx.Start() + t.Cleanup(func() { wfx.Stop() }) + if orientation == "north" { + return NewNorthboundServer(wfx) + } else if orientation == "south" { + return NewSouthboundServer(wfx) + } + panic("invalid orientation") } -func TestSouthboundPutJobsIDStatusHandler_NotFound(t *testing.T) { - params := southbound.NewPutJobsIDStatusParams() +func TestGetJobsIDStatus_NotFound(t *testing.T) { jobID := "42" - params.ID = jobID - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, fault.Wrap(fmt.Errorf("job with id %s does not exist", jobID), ftag.With(ftag.NotFound))) - api := NewSouthboundAPI(dbMock) - resp := api.SouthboundPutJobsIDStatusHandler.Handle(params) + for _, orientation := range allOrientations { + t.Run(orientation, func(t *testing.T) { + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().GetJob(context.Background(), jobID, persistence.FetchParams{}).Return(nil, fault.Wrap(fmt.Errorf("job with id %s does not exist", jobID), ftag.With(ftag.NotFound))) - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() + server := createServerForTesting(t, orientation, dbMock) + resp, err := server.GetJobsIdStatus(context.Background(), api.GetJobsIdStatusRequestObject{Id: jobID}) + assert.NoError(t, err) - assert.Equal(t, http.StatusNotFound, response.StatusCode) + recorder := httptest.NewRecorder() + _ = resp.VisitGetJobsIdStatusResponse(recorder) + response := recorder.Result() + assert.Equal(t, http.StatusNotFound, response.StatusCode) + }) + } } -func TestSouthboundGetJobsHandler_InternalError(t *testing.T) { - params := southbound.NewGetJobsParams() - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT(). - QueryJobs(params.HTTPRequest.Context(), persistence.FilterParams{}, persistence.SortParams{}, persistence.PaginationParams{Limit: 10}). - Return(nil, errors.New("something went wrong")) - - api := NewSouthboundAPI(dbMock) - resp := api.SouthboundGetJobsHandler.Handle(params) - - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() - - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) +func TestGetJobsIDStatus_InternalError(t *testing.T) { + jobID := "42" + for _, orientation := range allOrientations { + t.Run(orientation, func(t *testing.T) { + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().GetJob(context.Background(), jobID, persistence.FetchParams{}).Return(nil, errors.New("something went wrong")) + + server := createServerForTesting(t, orientation, dbMock) + resp, err := server.GetJobsIdStatus(context.Background(), api.GetJobsIdStatusRequestObject{Id: jobID}) + assert.Error(t, err) + assert.Nil(t, resp) + }) + } } -func TestSouthboundGetJobsIDHandler_NotFound(t *testing.T) { - params := southbound.NewGetJobsIDParams() - +func TestPutJobsIDStatus_NotFound(t *testing.T) { jobID := "42" - params.ID = jobID - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, fault.Wrap(fmt.Errorf("job with id %s does not exist", jobID), ftag.With(ftag.NotFound))) - api := NewSouthboundAPI(dbMock) - resp := api.SouthboundGetJobsIDHandler.Handle(params) + for _, orientation := range allOrientations { + t.Run(orientation, func(t *testing.T) { + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().GetJob(context.Background(), jobID, persistence.FetchParams{}).Return(nil, fault.Wrap(fmt.Errorf("job with id %s does not exist", jobID), ftag.With(ftag.NotFound))) + + server := createServerForTesting(t, orientation, dbMock) + resp, err := server.PutJobsIdStatus(context.Background(), api.PutJobsIdStatusRequestObject{ + Id: jobID, + Body: &api.JobStatus{}, + }) + assert.NoError(t, err) - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() + recorder := httptest.NewRecorder() + _ = resp.VisitPutJobsIdStatusResponse(recorder) + response := recorder.Result() - assert.Equal(t, http.StatusNotFound, response.StatusCode) + assert.Equal(t, http.StatusNotFound, response.StatusCode) + }) + } } -func TestSouthboundGetJobsIDHandler_InternalError(t *testing.T) { - params := southbound.NewGetJobsIDParams() +func TestPutJobsIDStatus_InternalError(t *testing.T) { jobID := "42" - params.ID = jobID - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - history := true - params.History = &history - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{History: history}).Return(nil, errors.New("something went wrong")) - api := NewSouthboundAPI(dbMock) - resp := api.SouthboundGetJobsIDHandler.Handle(params) + for _, orientation := range allOrientations { + t.Run(orientation, func(t *testing.T) { + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().GetJob(context.Background(), jobID, persistence.FetchParams{}).Return(nil, errors.New("something went wrong")) - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() + server := createServerForTesting(t, orientation, dbMock) + resp, err := server.PutJobsIdStatus(context.Background(), api.PutJobsIdStatusRequestObject{Id: jobID}) + assert.Error(t, err) + assert.Nil(t, resp) + }) + } +} - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) +func TestGetJobs_InternalError(t *testing.T) { + for _, orientation := range allOrientations { + t.Run(orientation, func(t *testing.T) { + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT(). + QueryJobs(context.Background(), persistence.FilterParams{}, persistence.SortParams{}, persistence.PaginationParams{Limit: 10}). + Return(nil, errors.New("something went wrong")) + + server := createServerForTesting(t, orientation, dbMock) + resp, err := server.GetJobs(context.Background(), api.GetJobsRequestObject{Params: api.GetJobsParams{}}) + assert.Error(t, err) + assert.Nil(t, resp) + }) + } } -func TestSouthboundGetJobsIDStatusHandler_InternalError(t *testing.T) { - params := southbound.NewGetJobsIDStatusParams() +func TestGetJobsID_NotFound(t *testing.T) { jobID := "42" - params.ID = jobID - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, errors.New("something went wrong")) + for _, orientation := range allOrientations { + t.Run(orientation, func(t *testing.T) { + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().GetJob(context.Background(), jobID, persistence.FetchParams{}).Return(nil, fault.Wrap(fmt.Errorf("job with id %s does not exist", jobID), ftag.With(ftag.NotFound))) - api := NewSouthboundAPI(dbMock) - resp := api.SouthboundGetJobsIDStatusHandler.Handle(params) + server := createServerForTesting(t, orientation, dbMock) + resp, err := server.GetJobsId(context.Background(), api.GetJobsIdRequestObject{Id: jobID}) + assert.NoError(t, err) - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() + recorder := httptest.NewRecorder() + _ = resp.VisitGetJobsIdResponse(recorder) + response := recorder.Result() - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) + assert.Equal(t, http.StatusNotFound, response.StatusCode) + }) + } } -func TestSouthboundPutJobsIDStatusHandler_InternalError(t *testing.T) { - params := southbound.NewPutJobsIDStatusParams() +func TestGetJobsID_InternalError(t *testing.T) { jobID := "42" - params.ID = jobID - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, errors.New("something went wrong")) - - api := NewSouthboundAPI(dbMock) - resp := api.SouthboundPutJobsIDStatusHandler.Handle(params) - - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() - - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) + for _, orientation := range allOrientations { + t.Run(orientation, func(t *testing.T) { + history := true + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().GetJob(context.Background(), jobID, persistence.FetchParams{History: history}).Return(nil, errors.New("something went wrong")) + + server := createServerForTesting(t, orientation, dbMock) + resp, err := server.GetJobsId(context.Background(), api.GetJobsIdRequestObject{Id: jobID, Params: api.GetJobsIdParams{ParamHistory: &history}}) + assert.Error(t, err) + assert.Nil(t, resp) + }) + } } -func TestSouthboundGetJobsIDDefinitionHandler_NotFound(t *testing.T) { - params := southbound.NewGetJobsIDDefinitionParams() +func TestGetJobsIDDefinition_NotFound(t *testing.T) { jobID := "42" - params.ID = jobID - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, fault.Wrap(fmt.Errorf("job with id %s does not exist", jobID), ftag.With(ftag.NotFound))) + for _, orientation := range allOrientations { + t.Run(orientation, func(t *testing.T) { + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().GetJob(context.Background(), jobID, persistence.FetchParams{}).Return(nil, fault.Wrap(fmt.Errorf("job with id %s does not exist", jobID), ftag.With(ftag.NotFound))) - api := NewSouthboundAPI(dbMock) - resp := api.SouthboundGetJobsIDDefinitionHandler.Handle(params) + server := createServerForTesting(t, orientation, dbMock) + resp, err := server.GetJobsIdDefinition(context.Background(), api.GetJobsIdDefinitionRequestObject{Id: jobID}) + assert.NoError(t, err) - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() + recorder := httptest.NewRecorder() + _ = resp.VisitGetJobsIdDefinitionResponse(recorder) + response := recorder.Result() - assert.Equal(t, http.StatusNotFound, response.StatusCode) + assert.Equal(t, http.StatusNotFound, response.StatusCode) + }) + } } -func TestSouthboundGetJobsIDDefinitionHandler_InternalError(t *testing.T) { - params := southbound.NewGetJobsIDDefinitionParams() +func TestGetJobsIDDefinition_InternalError(t *testing.T) { jobID := "42" - params.ID = jobID - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, errors.New("something went wrong")) - - api := NewSouthboundAPI(dbMock) - resp := api.SouthboundGetJobsIDDefinitionHandler.Handle(params) - - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() - - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) + for _, orientation := range allOrientations { + t.Run(orientation, func(t *testing.T) { + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().GetJob(context.Background(), jobID, persistence.FetchParams{}).Return(nil, errors.New("something went wrong")) + + server := createServerForTesting(t, orientation, dbMock) + resp, err := server.GetJobsIdDefinition(context.Background(), api.GetJobsIdDefinitionRequestObject{Id: jobID}) + assert.Error(t, err) + assert.Nil(t, resp) + }) + } } -func TestSouthboundPutJobsIDDefinitionHandler_NotFound(t *testing.T) { - params := southbound.NewPutJobsIDDefinitionParams() +func TestPutJobsIDDefinition_NotFound(t *testing.T) { jobID := "42" - params.ID = jobID - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, fault.Wrap(fmt.Errorf("job with id %s does not exist", jobID), ftag.With(ftag.NotFound))) + for _, orientation := range allOrientations { + t.Run(orientation, func(t *testing.T) { + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().GetJob(context.Background(), jobID, persistence.FetchParams{}).Return(nil, fault.Wrap(fmt.Errorf("job with id %s does not exist", jobID), ftag.With(ftag.NotFound))) - api := NewSouthboundAPI(dbMock) - resp := api.SouthboundPutJobsIDDefinitionHandler.Handle(params) + server := createServerForTesting(t, orientation, dbMock) + resp, err := server.PutJobsIdDefinition(context.Background(), api.PutJobsIdDefinitionRequestObject{Id: jobID}) + assert.NoError(t, err) - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() + recorder := httptest.NewRecorder() + _ = resp.VisitPutJobsIdDefinitionResponse(recorder) + response := recorder.Result() - assert.Equal(t, http.StatusNotFound, response.StatusCode) + assert.Equal(t, http.StatusNotFound, response.StatusCode) + }) + } } -func TestSouthboundPutJobsIDDefinitionHandler_InternalError(t *testing.T) { - params := southbound.NewPutJobsIDDefinitionParams() +func TestPutJobsIDDefinition_InternalError(t *testing.T) { jobID := "42" - params.ID = jobID - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, errors.New("something went wrong")) - - api := NewSouthboundAPI(dbMock) - resp := api.SouthboundPutJobsIDDefinitionHandler.Handle(params) - - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() - - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) + for _, orientation := range allOrientations { + t.Run(orientation, func(t *testing.T) { + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().GetJob(context.Background(), jobID, persistence.FetchParams{}).Return(nil, errors.New("something went wrong")) + + server := createServerForTesting(t, orientation, dbMock) + resp, err := server.PutJobsIdDefinition(context.Background(), api.PutJobsIdDefinitionRequestObject{Id: jobID}) + assert.Error(t, err) + assert.Nil(t, resp) + }) + } } -func TestSouthboundGetWorkflowsNameHandler_InternalError(t *testing.T) { - params := southbound.NewGetWorkflowsNameParams() - params.Name = "wfx.test.workflow" - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetWorkflow(params.HTTPRequest.Context(), params.Name).Return(nil, errors.New("something went wrong")) - - api := NewSouthboundAPI(dbMock) - - resp := api.SouthboundGetWorkflowsNameHandler.Handle(params) - - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() - - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) +func TestGetWorkflowsName_InternalError(t *testing.T) { + workflow := "wfx.test.workflow" + for _, orientation := range allOrientations { + t.Run(orientation, func(t *testing.T) { + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().GetWorkflow(context.Background(), workflow).Return(nil, errors.New("something went wrong")) + + server := createServerForTesting(t, orientation, dbMock) + resp, err := server.GetWorkflowsName(context.Background(), api.GetWorkflowsNameRequestObject{Name: workflow}) + assert.Error(t, err) + assert.Nil(t, resp) + }) + } } -func TestSouthboundGetWorkflowsHandler_InternalError(t *testing.T) { - params := southbound.NewGetWorkflowsParams() - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().QueryWorkflows(params.HTTPRequest.Context(), persistence.PaginationParams{Limit: 10}).Return(nil, errors.New("something went wrong")) - - api := NewSouthboundAPI(dbMock) - resp := api.SouthboundGetWorkflowsHandler.Handle(params) - - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() - - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) +func TestGetWorkflows_InternalError(t *testing.T) { + for _, orientation := range allOrientations { + t.Run(orientation, func(t *testing.T) { + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().QueryWorkflows(context.Background(), persistence.SortParams{}, persistence.PaginationParams{Limit: 10}).Return(nil, errors.New("something went wrong")) + + server := createServerForTesting(t, orientation, dbMock) + resp, err := server.GetWorkflows(context.Background(), api.GetWorkflowsRequestObject{Params: api.GetWorkflowsParams{}}) + assert.Error(t, err) + assert.Nil(t, resp) + }) + } } -func TestSouthboundGetWorkflowsHandler_Empty(t *testing.T) { - params := southbound.NewGetWorkflowsParams() - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().QueryWorkflows(params.HTTPRequest.Context(), persistence.PaginationParams{Limit: 10}).Return(nil, nil) - - api := NewSouthboundAPI(dbMock) +func TestGetWorkflows_Empty(t *testing.T) { + for _, orientation := range allOrientations { + t.Run(orientation, func(t *testing.T) { + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().QueryWorkflows(context.Background(), persistence.SortParams{Desc: false}, persistence.PaginationParams{Limit: 10}).Return(&api.PaginatedWorkflowList{}, nil) - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - resp := api.SouthboundGetWorkflowsHandler.Handle(params) + server := createServerForTesting(t, orientation, dbMock) + resp, err := server.GetWorkflows(context.Background(), api.GetWorkflowsRequestObject{Params: api.GetWorkflowsParams{}}) + assert.NoError(t, err) - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() + recorder := httptest.NewRecorder() + _ = resp.VisitGetWorkflowsResponse(recorder) + response := recorder.Result() - assert.Equal(t, http.StatusOK, response.StatusCode) + assert.Equal(t, http.StatusOK, response.StatusCode) + }) + } } -func TestSouthboundGetJobsIDTagsHandler_NotFound(t *testing.T) { - params := southbound.NewGetJobsIDTagsParams() - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, fault.Wrap(errors.New("not found"), ftag.With(ftag.NotFound))) +func TestGetJobsIDTags_NotFound(t *testing.T) { + jobID := "42" + for _, orientation := range allOrientations { + t.Run(orientation, func(t *testing.T) { + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().GetJob(context.Background(), jobID, persistence.FetchParams{}).Return(nil, fault.Wrap(errors.New("not found"), ftag.With(ftag.NotFound))) - api := NewSouthboundAPI(dbMock) - resp := api.SouthboundGetJobsIDTagsHandler.Handle(params) + server := createServerForTesting(t, orientation, dbMock) + resp, err := server.GetJobsIdTags(context.Background(), api.GetJobsIdTagsRequestObject{Id: jobID}) + assert.NoError(t, err) - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() + recorder := httptest.NewRecorder() + _ = resp.VisitGetJobsIdTagsResponse(recorder) + response := recorder.Result() - assert.Equal(t, http.StatusNotFound, response.StatusCode) + assert.Equal(t, http.StatusNotFound, response.StatusCode) + }) + } } -func TestSouthboundGetJobsIDTagsHandler_InternalError(t *testing.T) { - params := southbound.NewGetJobsIDTagsParams() - params.HTTPRequest = httptest.NewRequest(http.MethodGet, "http://localhost", new(bytes.Buffer)) - - dbMock := persistence.NewMockStorage(t) - dbMock.EXPECT().GetJob(params.HTTPRequest.Context(), params.ID, persistence.FetchParams{}).Return(nil, fault.Wrap(errors.New("something went wrong"), ftag.With(ftag.Internal))) - - api := NewSouthboundAPI(dbMock) - resp := api.SouthboundGetJobsIDTagsHandler.Handle(params) - - recorder := httptest.NewRecorder() - resp.WriteResponse(recorder, producer.JSONProducer()) - response := recorder.Result() +func TestGetJobsIDTags_InternalError(t *testing.T) { + jobID := "42" + for _, orientation := range allOrientations { + t.Run(orientation, func(t *testing.T) { + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().GetJob(context.Background(), jobID, persistence.FetchParams{}).Return(nil, fault.Wrap(errors.New("something went wrong"), ftag.With(ftag.Internal))) + + server := createServerForTesting(t, orientation, dbMock) + resp, err := server.GetJobsIdTags(context.Background(), api.GetJobsIdTagsRequestObject{Id: jobID}) + assert.Error(t, err) + assert.Nil(t, resp) + }) + } +} - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) +func TestHealth(t *testing.T) { + for _, orientation := range allOrientations { + t.Run(orientation, func(t *testing.T) { + dbMock := persistence.NewHealthyMockStorage(t) + server := createServerForTesting(t, orientation, dbMock) + ok := false + for i := 0; i < 10; i++ { + resp, err := server.GetHealth(context.Background(), api.GetHealthRequestObject{}) + require.NoError(t, err) + recorder := httptest.NewRecorder() + _ = resp.VisitGetHealthResponse(recorder) + response := recorder.Result() + if response.StatusCode == http.StatusOK { + ok = true + break + } + time.Sleep(200 * time.Millisecond) + } + assert.True(t, ok) + }) + } } -func TestParseFilterParamsSouth(t *testing.T) { - jobIDs := "abc,424-194-123" - clientIDs := "alpha,beta" - workflows := "wf1,wf2,wf3" - params := southbound.GetJobsEventsParams{ - HTTPRequest: &http.Request{}, - JobIds: &jobIDs, - ClientIds: &clientIDs, - Workflows: &workflows, +func TestVersion(t *testing.T) { + dbMock := persistence.NewHealthyMockStorage(t) + for _, orientation := range allOrientations { + t.Run(orientation, func(t *testing.T) { + server := createServerForTesting(t, orientation, dbMock) + resp, err := server.GetVersion(context.Background(), api.GetVersionRequestObject{}) + require.NoError(t, err) + + recorder := httptest.NewRecorder() + _ = resp.VisitGetVersionResponse(recorder) + response := recorder.Result() + assert.Equal(t, http.StatusOK, response.StatusCode) + }) } - filter := parseFilterParamsSouth(params) - assert.Equal(t, []string{"abc", "424-194-123"}, filter.JobIDs) - assert.Equal(t, []string{"alpha", "beta"}, filter.ClientIDs) - assert.Equal(t, []string{"wf1", "wf2", "wf3"}, filter.Workflows) } diff --git a/api/wfx.go b/api/wfx.go new file mode 100644 index 00000000..42c5d2cd --- /dev/null +++ b/api/wfx.go @@ -0,0 +1,457 @@ +package api + +/* + * SPDX-FileCopyrightText: 2024 Siemens AG + * + * SPDX-License-Identifier: Apache-2.0 + * + * Author: Michael Adler + */ + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/Southclaws/fault" + "github.com/Southclaws/fault/ftag" + "github.com/alexliesenfeld/health" + "github.com/rs/zerolog/log" + "github.com/siemens/wfx/cmd/wfx/metadata" + "github.com/siemens/wfx/generated/api" + "github.com/siemens/wfx/internal/handler/job" + "github.com/siemens/wfx/internal/handler/job/definition" + "github.com/siemens/wfx/internal/handler/job/events" + "github.com/siemens/wfx/internal/handler/job/status" + "github.com/siemens/wfx/internal/handler/job/tags" + "github.com/siemens/wfx/internal/handler/workflow" + "github.com/siemens/wfx/middleware/logging" + "github.com/siemens/wfx/middleware/sse" + "github.com/siemens/wfx/persistence" +) + +const ( + defaultPageLimit = 10 +) + +type WfxServer struct { + storage persistence.Storage + checker health.Checker +} + +func NewWfxServer(storage persistence.Storage) *WfxServer { + checker := health.NewChecker( + health.WithTimeout(10*time.Second), + health.WithPeriodicCheck(30*time.Second, 0, health.Check{ + Name: "persistence", + Check: func(ctx context.Context) error { + return fault.Wrap(storage.CheckHealth(ctx)) + }, + }), + health.WithStatusListener(healthStatusListener), + health.WithDisabledAutostart()) + wfx := &WfxServer{storage: storage, checker: checker} + return wfx +} + +func (server WfxServer) Start() { + server.checker.Start() +} + +func (server WfxServer) Stop() { + if server.checker.IsStarted() { + server.checker.Stop() + } +} + +func healthStatusListener(_ context.Context, state health.CheckerState) { + logFn := log.Warn + switch state.Status { + case health.StatusDown: + logFn = log.Error + case health.StatusUp: + logFn = log.Info + case health.StatusUnknown: + logFn = log.Warn + } + + childLog := logFn() + for k, v := range state.CheckState { + childLog.Str(k, string(v.Status)) + } + + childLog.Str("overall", string(state.Status)).Msg("Health status changed") +} + +//revive:disable:var-naming +func (server WfxServer) GetJobs(ctx context.Context, request api.GetJobsRequestObject) (api.GetJobsResponseObject, error) { + filter := persistence.FilterParams{ + ClientID: request.Params.ParamClientID, + State: request.Params.ParamState, + Workflow: request.Params.ParamWorkflow, + } + if request.Params.ParamGroup != nil { + filter.Group = *request.Params.ParamGroup + } + if request.Params.ParamTag != nil { + filter.Tags = *request.Params.ParamTag + } + + pagination := persistence.PaginationParams{Offset: 0, Limit: defaultPageLimit} + if request.Params.ParamOffset != nil { + pagination.Offset = *request.Params.ParamOffset + } + if request.Params.ParamLimit != nil { + pagination.Limit = *request.Params.ParamLimit + } + + jobs, err := job.QueryJobs(ctx, server.storage, filter, pagination, (*string)(request.Params.ParamSort)) + if err != nil { + return nil, fault.Wrap(err) + } + if request.Params.XResponseFilter != nil { + return NewJQFilter(*request.Params.XResponseFilter, *jobs), nil + } + return api.GetJobs200JSONResponse(*jobs), nil +} + +func (server WfxServer) PostJobs(ctx context.Context, request api.PostJobsRequestObject) (api.PostJobsResponseObject, error) { + job, err := job.CreateJob(ctx, server.storage, request.Body) + if err != nil { + switch ftag.Get(err) { + case ftag.NotFound: + err2 := WorkflowNotFound + err2.Message = err.Error() + return api.PostJobs400JSONResponse(api.ErrorResponse{ + Errors: &[]api.Error{err2}, + }), nil + default: + return nil, fault.Wrap(err) + } + } + if request.Params.XResponseFilter != nil { + return NewJQFilter(*request.Params.XResponseFilter, *job), nil + } + return api.PostJobs201JSONResponse(*job), nil +} + +func (server WfxServer) GetJobsEvents(ctx context.Context, request api.GetJobsEventsRequestObject) (api.GetJobsEventsResponseObject, error) { + var filter events.FilterParams + if ids := request.Params.JobIds; ids != nil { + filter.JobIDs = strings.Split(*ids, ",") + } + if ids := request.Params.ClientIDs; ids != nil { + filter.ClientIDs = strings.Split(*ids, ",") + } + if wfs := request.Params.Workflows; wfs != nil { + filter.Workflows = strings.Split(*wfs, ",") + } + + var tags []string + if s := request.Params.Tags; s != nil { + tags = strings.Split(*s, ",") + } + eventChan, err := events.AddSubscriber(ctx, filter, tags) + if err != nil { + return nil, fault.Wrap(err) + } + return sse.NewResponder(ctx, eventChan), nil +} + +func (server WfxServer) DeleteJobsId(ctx context.Context, request api.DeleteJobsIdRequestObject) (api.DeleteJobsIdResponseObject, error) { + if err := job.DeleteJob(ctx, server.storage, request.Id); err != nil { + if ftag.Get(err) == ftag.NotFound { + return api.DeleteJobsId404JSONResponse(api.ErrorResponse{}), nil + } + return nil, fault.Wrap(err) + } + return api.DeleteJobsId204Response{}, nil +} + +func (server WfxServer) GetJobsId(ctx context.Context, request api.GetJobsIdRequestObject) (api.GetJobsIdResponseObject, error) { + history := false + if request.Params.ParamHistory != nil { + history = *request.Params.ParamHistory + } + job, err := job.GetJob(ctx, server.storage, request.Id, history) + if err != nil { + if ftag.Get(err) == ftag.NotFound { + return api.GetJobsId404JSONResponse(api.ErrorResponse{ + Errors: &[]api.Error{JobNotFound}, + }), nil + } + return nil, fault.Wrap(err) + } + if request.Params.XResponseFilter != nil { + return NewJQFilter(*request.Params.XResponseFilter, *job), nil + } + return api.GetJobsId200JSONResponse(*job), nil +} + +func (server WfxServer) GetJobsIdDefinition(ctx context.Context, request api.GetJobsIdDefinitionRequestObject) (api.GetJobsIdDefinitionResponseObject, error) { + definition, err := definition.Get(ctx, server.storage, request.Id) + if err != nil { + if ftag.Get(err) == ftag.NotFound { + return api.GetJobsIdDefinition404JSONResponse(api.ErrorResponse{ + Errors: &[]api.Error{JobNotFound}, + }), nil + } + return nil, fault.Wrap(err) + } + if request.Params.XResponseFilter != nil { + return NewJQFilter(*request.Params.XResponseFilter, definition), nil + } + return api.GetJobsIdDefinition200JSONResponse(definition), nil +} + +func (server WfxServer) PutJobsIdDefinition(ctx context.Context, request api.PutJobsIdDefinitionRequestObject) (api.PutJobsIdDefinitionResponseObject, error) { + var def map[string]any + if request.Body != nil { + def = *request.Body + } + definition, err := definition.Update(ctx, server.storage, request.Id, def) + if err != nil { + if ftag.Get(err) == ftag.NotFound { + return api.PutJobsIdDefinition404JSONResponse(api.ErrorResponse{ + Errors: &[]api.Error{JobNotFound}, + }), nil + } + return nil, fault.Wrap(err) + } + if request.Params.XResponseFilter != nil { + return NewJQFilter(*request.Params.XResponseFilter, definition), nil + } + return api.PutJobsIdDefinition200JSONResponse(definition), nil +} + +func (server WfxServer) GetJobsIdStatus(ctx context.Context, request api.GetJobsIdStatusRequestObject) (api.GetJobsIdStatusResponseObject, error) { + status, err := status.Get(ctx, server.storage, request.Id) + if err != nil { + if ftag.Get(err) == ftag.NotFound { + return api.GetJobsIdStatus404JSONResponse(api.ErrorResponse{ + Errors: &[]api.Error{JobNotFound}, + }), nil + } + return nil, fault.Wrap(err) + } + if request.Params.XResponseFilter != nil { + return NewJQFilter(*request.Params.XResponseFilter, *status), nil + } + return api.GetJobsIdStatus200JSONResponse(*status), nil +} + +func (server WfxServer) PutJobsIdStatus(ctx context.Context, request api.PutJobsIdStatusRequestObject, eligible api.EligibleEnum) (api.PutJobsIdStatusResponseObject, error) { + status, err := status.Update(ctx, server.storage, request.Id, request.Body, eligible) + if err != nil { + switch ftag.Get(err) { + case ftag.NotFound: + return api.PutJobsIdStatus404JSONResponse(api.ErrorResponse{ + Errors: &[]api.Error{JobNotFound}, + }), nil + case ftag.InvalidArgument: + err2 := InvalidRequest + err2.Message = err.Error() + return api.PutJobsIdStatus400JSONResponse(api.ErrorResponse{ + Errors: &[]api.Error{err2}, + }), nil + default: + return nil, fault.Wrap(err) + } + } + if request.Params.XResponseFilter != nil { + return NewJQFilter(*request.Params.XResponseFilter, *status), nil + } + return api.PutJobsIdStatus200JSONResponse(*status), nil +} + +func (server WfxServer) DeleteJobsIdTags(ctx context.Context, request api.DeleteJobsIdTagsRequestObject) (api.DeleteJobsIdTagsResponseObject, error) { + var body []string + if request.Body != nil { + body = *request.Body + } + tags, err := tags.Delete(ctx, server.storage, request.Id, body) + if err != nil { + if ftag.Get(err) == ftag.NotFound { + return api.DeleteJobsIdTags404JSONResponse(api.ErrorResponse{ + Errors: &[]api.Error{JobNotFound}, + }), nil + } + return nil, fault.Wrap(err) + } + if request.Params.XResponseFilter != nil { + return NewJQFilter(*request.Params.XResponseFilter, tags), nil + } + return api.DeleteJobsIdTags200JSONResponse(tags), nil +} + +func (server WfxServer) GetJobsIdTags(ctx context.Context, request api.GetJobsIdTagsRequestObject) (api.GetJobsIdTagsResponseObject, error) { + tags, err := tags.Get(ctx, server.storage, request.Id) + if err != nil { + if ftag.Get(err) == ftag.NotFound { + return api.GetJobsIdTags404JSONResponse(api.ErrorResponse{ + Errors: &[]api.Error{JobNotFound}, + }), nil + } + return nil, fault.Wrap(err) + } + if request.Params.XResponseFilter != nil { + return NewJQFilter(*request.Params.XResponseFilter, tags), nil + } + return api.GetJobsIdTags200JSONResponse(tags), nil +} + +func (server WfxServer) PostJobsIdTags(ctx context.Context, request api.PostJobsIdTagsRequestObject) (api.PostJobsIdTagsResponseObject, error) { + var body []string + if request.Body != nil { + body = *request.Body + } + tags, err := tags.Add(ctx, server.storage, request.Id, body) + if err != nil { + if ftag.Get(err) == ftag.NotFound { + return api.PostJobsIdTags404JSONResponse(api.ErrorResponse{ + Errors: &[]api.Error{JobNotFound}, + }), nil + } + return nil, fault.Wrap(err) + } + if request.Params.XResponseFilter != nil { + return NewJQFilter(*request.Params.XResponseFilter, tags), nil + } + return api.PostJobsIdTags200JSONResponse(tags), nil +} + +func (server WfxServer) GetWorkflows(ctx context.Context, request api.GetWorkflowsRequestObject) (api.GetWorkflowsResponseObject, error) { + var offset int64 + if request.Params.ParamOffset != nil { + offset = *request.Params.ParamOffset + } + var limit int32 = defaultPageLimit + if request.Params.ParamLimit != nil { + limit = *request.Params.ParamLimit + } + pagination := persistence.PaginationParams{Offset: offset, Limit: limit} + log := logging.LoggerFromCtx(ctx) + workflows, err := workflow.QueryWorkflows(ctx, server.storage, pagination, (*string)(request.Params.ParamSort)) + if err != nil { + log.Error().Err(err).Msg("Failed to query workflows") + return nil, fault.Wrap(err) + } + if request.Params.XResponseFilter != nil { + return NewJQFilter(*request.Params.XResponseFilter, *workflows), nil + } + return api.GetWorkflows200JSONResponse(*workflows), nil +} + +func (server WfxServer) PostWorkflows(ctx context.Context, request api.PostWorkflowsRequestObject) (api.PostWorkflowsResponseObject, error) { + wf, err := workflow.CreateWorkflow(ctx, server.storage, request.Body) + if err != nil { + switch ftag.Get(err) { + case ftag.InvalidArgument: + err2 := WorkflowInvalid + err2.Message = err.Error() + return api.PostWorkflows400JSONResponse(api.ErrorResponse{ + Errors: &[]api.Error{err2}, + }), nil + case ftag.AlreadyExists: + err2 := WorkflowNotUnique + err2.Message = fmt.Sprintf("Workflow with name '%s' already exists", request.Body.Name) + return api.PostWorkflows400JSONResponse(api.ErrorResponse{ + Errors: &[]api.Error{err2}, + }), nil + default: + return nil, fault.Wrap(err) + } + } + if request.Params.XResponseFilter != nil { + return NewJQFilter(*request.Params.XResponseFilter, wf), nil + } + return api.PostWorkflows201JSONResponse(*wf), nil +} + +func (server WfxServer) DeleteWorkflowsName(ctx context.Context, request api.DeleteWorkflowsNameRequestObject) (api.DeleteWorkflowsNameResponseObject, error) { + err := workflow.DeleteWorkflow(ctx, server.storage, request.Name) + if err != nil { + if ftag.Get(err) == ftag.NotFound { + err2 := WorkflowNotFound + err2.Message = fmt.Sprintf("Workflow '%s' not found", request.Name) + return api.DeleteWorkflowsName404JSONResponse(api.ErrorResponse{ + Errors: &[]api.Error{err2}, + }), nil + } + return nil, fault.Wrap(err) + } + return api.DeleteWorkflowsName204Response{}, nil +} + +func (server WfxServer) GetWorkflowsName(ctx context.Context, request api.GetWorkflowsNameRequestObject) (api.GetWorkflowsNameResponseObject, error) { + workflow, err := workflow.GetWorkflow(ctx, server.storage, request.Name) + if err != nil { + if ftag.Get(err) == ftag.NotFound { + return api.GetWorkflowsName404JSONResponse(api.ErrorResponse{ + Errors: &[]api.Error{WorkflowNotFound}, + }), nil + } + return nil, fault.Wrap(err) + } + if request.Params.XResponseFilter != nil { + return NewJQFilter(*request.Params.XResponseFilter, *workflow), nil + } + return api.GetWorkflowsName200JSONResponse(*workflow), nil +} + +func (server WfxServer) GetHealth(ctx context.Context, _ api.GetHealthRequestObject) (api.GetHealthResponseObject, error) { + result := server.checker.Check(ctx) + details := make(map[string]api.CheckResult, len(result.Details)) + for component, result := range result.Details { + componentResult := api.CheckResult{ + Status: (api.AvailabilityStatus)(result.Status), + Timestamp: result.Timestamp, + } + if result.Error != nil { + componentResult.Error = result.Error.Error() + } + details[component] = componentResult + } + + checkerResult := api.CheckerResult{ + Status: api.AvailabilityStatus(result.Status), + } + if len(result.Info) > 0 { + checkerResult.Info = &result.Info + } + if len(result.Details) > 0 { + checkerResult.Details = &details + } + + if result.Status == health.StatusUp { + return api.GetHealth200JSONResponse{ + Headers: api.GetHealth200ResponseHeaders{ + // avoid caching + CacheControl: "no-cache", + Pragma: "no-cache", + Expires: "Thu, 01 Jan 1970 00:00:00 GMT", + }, + Body: checkerResult, + }, nil + } + return api.GetHealth503JSONResponse{ + Headers: api.GetHealth503ResponseHeaders{ + // avoid caching + CacheControl: "no-cache", + Pragma: "no-cache", + Expires: "Thu, 01 Jan 1970 00:00:00 GMT", + }, + Body: checkerResult, + }, nil +} + +func (server WfxServer) GetVersion(context.Context, api.GetVersionRequestObject) (api.GetVersionResponseObject, error) { + buildDate, _ := time.Parse("2006-01-02T15:04:05-07:00", metadata.Date) + return api.GetVersion200JSONResponse{ + Version: metadata.Version, + Commit: metadata.Commit, + BuildDate: buildDate, + ApiVersion: metadata.APIVersion, + }, nil +} diff --git a/api/wfx_test.go b/api/wfx_test.go new file mode 100644 index 00000000..472035a2 --- /dev/null +++ b/api/wfx_test.go @@ -0,0 +1,55 @@ +package api + +/* + * SPDX-FileCopyrightText: 2024 Siemens AG + * + * SPDX-License-Identifier: Apache-2.0 + * + * Author: Michael Adler + */ + +import ( + "context" + "testing" + + "github.com/alexliesenfeld/health" + "github.com/siemens/wfx/generated/api" + "github.com/siemens/wfx/persistence" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestStatusListener(*testing.T) { + healthStatusListener(context.Background(), health.CheckerState{Status: health.StatusUp}) + healthStatusListener(context.Background(), health.CheckerState{Status: health.StatusDown}) + healthStatusListener(context.Background(), health.CheckerState{Status: health.StatusUnknown}) + healthStatusListener(context.Background(), health.CheckerState{ + Status: health.StatusUp, + CheckState: map[string]health.CheckState{ + "db": {Status: health.StatusUp}, + }, + }) +} + +func TestGetJobsEvents(t *testing.T) { + jobIDs := "1,2,3" + clientIDs := "4,5,6" + workflows := "wf1,wf2" + tags := "tag1,tag2" + + request := api.GetJobsEventsRequestObject{ + Params: api.GetJobsEventsParams{ + JobIds: &jobIDs, + ClientIDs: &clientIDs, + Workflows: &workflows, + Tags: &tags, + }, + } + + wfx := NewWfxServer(persistence.NewHealthyMockStorage(t)) + ctx, cancel := context.WithCancel(context.TODO()) + defer cancel() + response, err := wfx.GetJobsEvents(ctx, request) + require.NoError(t, err) + assert.NotNil(t, response) +} diff --git a/api/workflow_test.go b/api/workflow_test.go index c1c19d59..9828216f 100644 --- a/api/workflow_test.go +++ b/api/workflow_test.go @@ -16,6 +16,7 @@ import ( "testing" "github.com/Southclaws/fault/ftag" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/internal/handler/job" "github.com/siemens/wfx/internal/handler/workflow" "github.com/siemens/wfx/internal/persistence/entgo" @@ -25,10 +26,6 @@ import ( jsonpath "github.com/steinfletcher/apitest-jsonpath" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - "github.com/siemens/wfx/generated/model" - northbound "github.com/siemens/wfx/generated/northbound/restapi" - southbound "github.com/siemens/wfx/generated/southbound/restapi" ) var allAPIs = []string{"north", "south"} @@ -101,7 +98,7 @@ func TestDeleteWorkflow(t *testing.T) { Handler(south). Delete(url). Expect(t). - Status(http.StatusMethodNotAllowed). + Status(http.StatusForbidden). End() // delete shall succeed for north @@ -136,7 +133,7 @@ func TestCreateWorkflow(t *testing.T) { Body(string(wfJSON)). Header("content-type", "application/json"). Expect(t). - Status(http.StatusMethodNotAllowed). + Status(http.StatusForbidden). End() // north is allowed @@ -178,7 +175,7 @@ func TestDeleteWorkflow_NotFound(t *testing.T) { func newInMemoryDB(t *testing.T) persistence.Storage { db := &entgo.SQLite{} - err := db.Initialize(context.Background(), "file:wfx?mode=memory&cache=shared&_fk=1") + err := db.Initialize("file:wfx?mode=memory&cache=shared&_fk=1") require.NoError(t, err) t.Cleanup(db.Shutdown) t.Cleanup(func() { @@ -189,7 +186,7 @@ func newInMemoryDB(t *testing.T) persistence.Storage { } } { - list, _ := db.QueryWorkflows(context.Background(), persistence.PaginationParams{Limit: 100}) + list, _ := db.QueryWorkflows(context.Background(), persistence.SortParams{Desc: false}, persistence.PaginationParams{Limit: 100}) for _, wf := range list.Content { _ = db.DeleteWorkflow(context.Background(), wf.Name) } @@ -199,25 +196,23 @@ func newInMemoryDB(t *testing.T) persistence.Storage { } func createNorthAndSouth(t *testing.T, db persistence.Storage) (http.Handler, http.Handler) { - northAPI := NewNorthboundAPI(db) - require.NoError(t, northAPI.Validate()) - north := northbound.ConfigureAPI(northAPI) - - southAPI := NewSouthboundAPI(db) - require.NoError(t, southAPI.Validate()) - south := southbound.ConfigureAPI(southAPI) - + wfx := NewWfxServer(db) + t.Cleanup(func() { wfx.Stop() }) + northAPI := NewNorthboundServer(wfx) + north := api.HandlerFromMuxWithBaseURL(api.NewStrictHandler(northAPI, nil), http.NewServeMux(), "/api/wfx/v1") + southAPI := NewSouthboundServer(wfx) + south := api.HandlerFromMuxWithBaseURL(api.NewStrictHandler(southAPI, nil), http.NewServeMux(), "/api/wfx/v1") return north, south } -func persistJob(t *testing.T, db persistence.Storage) *model.Job { +func persistJob(t *testing.T, db persistence.Storage) *api.Job { wf := dau.DirectWorkflow() if found, _ := workflow.GetWorkflow(context.Background(), db, wf.Name); found == nil { _, err := workflow.CreateWorkflow(context.Background(), db, wf) require.NoError(t, err) } - jobReq := model.JobRequest{ + jobReq := api.JobRequest{ ClientID: "foo", Workflow: wf.Name, } diff --git a/cmd/wfx-loadtest/loadtest/loadtest.go b/cmd/wfx-loadtest/loadtest/loadtest.go index 25002897..a5e4cfc8 100644 --- a/cmd/wfx-loadtest/loadtest/loadtest.go +++ b/cmd/wfx-loadtest/loadtest/loadtest.go @@ -20,7 +20,7 @@ import ( "github.com/knadh/koanf/v2" "github.com/rs/zerolog/log" "github.com/siemens/wfx/cmd/wfx-loadtest/wfx" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/workflow/dau" vegeta "github.com/tsenart/vegeta/v12/lib" "github.com/tsenart/vegeta/v12/lib/plot" @@ -43,7 +43,7 @@ var ( jobCounter uint64 workflow = dau.DirectWorkflow() - queue = make([]*model.JobStatus, 0, 10) + queue = make([]*api.JobStatus, 0, 10) queueMutex sync.RWMutex host string @@ -62,7 +62,7 @@ func Run(k *koanf.Koanf) error { return errors.New("host or mgmtHost not set") } - if err := wfx.CreateWorkflow(mgmtHost, mgmtPort, workflow); err != nil { + if err := wfx.CreateWorkflow(mgmtHost, mgmtPort, *workflow); err != nil { return fault.Wrap(err) } @@ -118,17 +118,18 @@ func Run(k *koanf.Koanf) error { if res.Code == http.StatusCreated { // we know it must be a job - var job model.Job + var job api.Job err := json.Unmarshal(res.Body, &job) if err != nil { log.Error().Err(err).Bytes("body", res.Body).Msg("Failed to unmarshal body") continue } + if job.Status.Context == nil { - job.Status.Context = make(map[string]any) + job.Status.Context = &map[string]any{} } // ensure job id is available - job.Status.Context["id"] = job.ID + (*job.Status.Context)["id"] = job.ID queueMutex.Lock() queue = append(queue, job.Status) @@ -136,7 +137,7 @@ func Run(k *koanf.Koanf) error { } else if res.Code == http.StatusOK { // status was updated - var status model.JobStatus + var status api.JobStatus err := json.Unmarshal(res.Body, &status) if err != nil { log.Error().Err(err).Bytes("body", res.Body).Msg("Failed to unmarshal body") diff --git a/cmd/wfx-loadtest/loadtest/write.go b/cmd/wfx-loadtest/loadtest/write.go index 13073cab..32f8310f 100644 --- a/cmd/wfx-loadtest/loadtest/write.go +++ b/cmd/wfx-loadtest/loadtest/write.go @@ -16,7 +16,7 @@ import ( "github.com/Southclaws/fault" "github.com/rs/zerolog/log" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" vegeta "github.com/tsenart/vegeta/v12/lib" ) @@ -28,7 +28,7 @@ func writeTargeter(tgt *vegeta.Target) error { // reset *tgt = vegeta.Target{} - var status *model.JobStatus + var status *api.JobStatus // pop queueMutex.RLock() n := len(queue) @@ -43,7 +43,7 @@ func writeTargeter(tgt *vegeta.Target) error { if status != nil { from := status.State var to string - var eligible model.EligibleEnum + var eligible api.EligibleEnum // choose a suitable transition for _, t := range workflow.Transitions { if t.From == from { @@ -53,10 +53,10 @@ func writeTargeter(tgt *vegeta.Target) error { } } if to != "" { - jobID := status.Context["id"].(string) + jobID := (*status.Context)["id"].(string) var url string - if eligible == model.EligibleEnumCLIENT { + if eligible == api.CLIENT { url = fmt.Sprintf("http://%s:%d/api/wfx/v1/jobs/%s/status", host, port, jobID) } else { url = fmt.Sprintf("http://%s:%d/api/wfx/v1/jobs/%s/status", mgmtHost, mgmtPort, jobID) @@ -71,7 +71,7 @@ func writeTargeter(tgt *vegeta.Target) error { return fault.Wrap(err) } log.Debug(). - Str("id", status.Context["id"].(string)). + Str("id", jobID). Str("from", from). Str("to", to). Str("url", url). @@ -91,7 +91,7 @@ func writeTargeter(tgt *vegeta.Target) error { } log.Debug().Msg("No job available, creating new one") - jobReq := model.JobRequest{ + jobReq := api.JobRequest{ ClientID: "vegeta", Workflow: workflow.Name, Definition: map[string]any{ diff --git a/cmd/wfx-loadtest/main.go b/cmd/wfx-loadtest/main.go index 5b453bc2..758b6329 100644 --- a/cmd/wfx-loadtest/main.go +++ b/cmd/wfx-loadtest/main.go @@ -8,10 +8,14 @@ package main * Author: Michael Adler */ -import "github.com/rs/zerolog/log" +import ( + "fmt" + "os" +) func main() { - if err := rootCmd.Execute(); err != nil { - log.Fatal().Err(err).Msg("Failed to execute") + if err := NewCommand().Execute(); err != nil { + fmt.Fprintf(os.Stderr, "error: %+v\n", err) + os.Exit(1) } } diff --git a/cmd/wfx-loadtest/root.go b/cmd/wfx-loadtest/root.go index 66773a58..3dd664d2 100644 --- a/cmd/wfx-loadtest/root.go +++ b/cmd/wfx-loadtest/root.go @@ -21,25 +21,52 @@ import ( "github.com/rs/zerolog" "github.com/rs/zerolog/log" "github.com/siemens/wfx/cmd/wfx-loadtest/loadtest" + "github.com/siemens/wfx/cmd/wfxctl/flags" "github.com/siemens/wfx/internal/cmd/man" "github.com/spf13/cobra" ) -const ( - logLevelFlag = "log-level" -) +func NewCommand() *cobra.Command { + k := koanf.New(".") + cmd := cobra.Command{ + Use: "wfx-loadtest", + Short: "Run a loadtest against wfx", + Example: "wfx-loadtest --duration 10s", + PreRun: func(cmd *cobra.Command, _ []string) { + if err := k.Load(env.Provider("WFX_", ".", func(s string) string { + result := strings.ReplaceAll( + strings.ToLower(strings.TrimPrefix(s, "WFX_")), "_", "-") + return result + }), nil); err != nil { + log.Err(err).Msg("Failed to env variables") + } -func init() { - rootCmd.AddCommand(man.Command) + // --log-level becomes log.level + if err := k.Load(posflag.Provider(cmd.Flags(), ".", k), nil); err != nil { + log.Fatal().Err(err).Msg("Failed to load pflags") + } - f := rootCmd.PersistentFlags() + log.Logger = zerolog.New(zerolog.ConsoleWriter{ + Out: os.Stderr, + TimeFormat: time.Stamp, + }).With().Timestamp().Logger() + if lvl, err := zerolog.ParseLevel(k.String(flags.LogLevelFlag)); err == nil { + zerolog.SetGlobalLevel(lvl) + } + }, + RunE: func(*cobra.Command, []string) error { + return fault.Wrap(loadtest.Run(k)) + }, + } + cmd.AddCommand(man.NewCommand()) + f := cmd.PersistentFlags() f.String(loadtest.HostFlag, "localhost", "host") f.Int(loadtest.PortFlag, 8080, "port") f.String(loadtest.MgmtHostFlag, "localhost", "management host") f.Int(loadtest.MgmtPortFlag, 8081, "management port") - f.String(logLevelFlag, "info", fmt.Sprintf("set log level. one of: %s,%s,%s,%s,%s,%s,%s", + f.String(flags.LogLevelFlag, "info", fmt.Sprintf("set log level. one of: %s,%s,%s,%s,%s,%s,%s", zerolog.TraceLevel.String(), zerolog.DebugLevel.String(), zerolog.InfoLevel.String(), @@ -51,37 +78,5 @@ func init() { f.Int(loadtest.ReadFreqFlag, 75, "number of read (GET) requests per second") f.Int(loadtest.WriteFreqFlag, 25, "number of write (POST) requests per second") f.Duration(loadtest.DurationFlag, time.Minute, "how long the benchmark shall run") -} - -var k = koanf.New(".") - -var rootCmd = &cobra.Command{ - Use: "wfx-loadtest", - Short: "Run a loadtest against wfx", - Example: "wfx-loadtest --duration 10s", - PreRun: func(cmd *cobra.Command, _ []string) { - if err := k.Load(env.Provider("WFX_", ".", func(s string) string { - result := strings.ReplaceAll( - strings.ToLower(strings.TrimPrefix(s, "WFX_")), "_", "-") - return result - }), nil); err != nil { - log.Err(err).Msg("Failed to env variables") - } - - // --log-level becomes log.level - if err := k.Load(posflag.Provider(cmd.Flags(), ".", k), nil); err != nil { - log.Fatal().Err(err).Msg("Failed to load pflags") - } - - log.Logger = zerolog.New(zerolog.ConsoleWriter{ - Out: os.Stderr, - TimeFormat: time.Stamp, - }).With().Timestamp().Logger() - if lvl, err := zerolog.ParseLevel(k.String(logLevelFlag)); err == nil { - zerolog.SetGlobalLevel(lvl) - } - }, - RunE: func(*cobra.Command, []string) error { - return fault.Wrap(loadtest.Run(k)) - }, + return &cmd } diff --git a/cmd/wfx-loadtest/wfx/workflow.go b/cmd/wfx-loadtest/wfx/workflow.go index 1184e180..e291337f 100644 --- a/cmd/wfx-loadtest/wfx/workflow.go +++ b/cmd/wfx-loadtest/wfx/workflow.go @@ -9,33 +9,46 @@ package wfx */ import ( + "context" "fmt" "net/http" "time" - "github.com/go-openapi/strfmt" + "github.com/Southclaws/fault" "github.com/rs/zerolog/log" - "github.com/siemens/wfx/generated/client" - "github.com/siemens/wfx/generated/client/workflows" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/cmd/wfxctl/errutil" + "github.com/siemens/wfx/generated/api" ) -func CreateWorkflow(host string, port int, workflow *model.Workflow) error { - log.Debug().Str("name", workflow.Name).Msg("Creating workflow") - - params := workflows.NewPostWorkflowsParams(). - WithHTTPClient(&http.Client{ - Timeout: time.Second * 10, - }). - WithWorkflow(workflow) - - cfg := client.DefaultTransportConfig().WithHost(fmt.Sprintf("%s:%d", host, port)) - client := client.NewHTTPClientWithConfig(strfmt.Default, cfg) - - _, err := client.Workflows.PostWorkflows(params) +func CreateWorkflow(host string, port int, workflow api.Workflow) error { + swagger := errutil.Must(api.GetSwagger()) + basePath := errutil.Must(swagger.Servers.BasePath()) + server := fmt.Sprintf("http://%s:%d%s", host, port, basePath) + log.Info().Str("server", server).Str("name", workflow.Name).Msg("Creating workflow") + client, err := api.NewClientWithResponses(server, api.WithHTTPClient(&http.Client{ + Timeout: time.Second * 10, + })) if err != nil { - log.Warn().Err(err).Msg("Failed to create workflow") + return fault.Wrap(err) + } + { + resp, err := client.GetWorkflowsNameWithResponse(context.Background(), workflow.Name, nil) + if err != nil { + return fault.Wrap(err) + } + if resp.JSON200 != nil { + return nil + } + } + resp, err := client.PostWorkflowsWithResponse(context.Background(), nil, api.PostWorkflowsJSONRequestBody(workflow)) + if err != nil { + return fault.Wrap(err) + } + if resp.JSON201 != nil { + log.Info().Str("name", workflow.Name).Msg("Created workflow") + return nil } - log.Info().Str("name", workflow.Name).Msg("Created workflow") + body := string(resp.Body) + log.Warn().Str("body", body).Msg("Failed to create workflow") return nil } diff --git a/cmd/wfx-viewer/cmd.go b/cmd/wfx-viewer/cmd.go index f6e33d83..8bf473f5 100644 --- a/cmd/wfx-viewer/cmd.go +++ b/cmd/wfx-viewer/cmd.go @@ -22,7 +22,7 @@ import ( "github.com/rs/zerolog/log" "github.com/siemens/wfx/cmd/wfx-viewer/output" "github.com/siemens/wfx/cmd/wfx/metadata" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/internal/cmd/man" "github.com/spf13/cobra" "gopkg.in/yaml.v3" @@ -35,8 +35,7 @@ const ( func init() { rootCmd.Version = metadata.Version - rootCmd.AddCommand(man.Command) - + rootCmd.AddCommand(man.NewCommand()) f := rootCmd.PersistentFlags() f.String("log-level", "info", fmt.Sprintf("set log level. one of: %s,%s,%s,%s,%s,%s,%s", zerolog.TraceLevel.String(), @@ -116,7 +115,7 @@ Do not use this for confidential information. cmd.SetOut(outFile) } - var workflow model.Workflow + var workflow api.Workflow { // parse workflow b, err := io.ReadAll(cmd.InOrStdin()) if err != nil { diff --git a/cmd/wfx-viewer/colors/colors.go b/cmd/wfx-viewer/colors/colors.go index 851277f7..6175504d 100644 --- a/cmd/wfx-viewer/colors/colors.go +++ b/cmd/wfx-viewer/colors/colors.go @@ -11,7 +11,7 @@ package colors import ( "image/color/palette" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "gopkg.in/go-playground/colors.v1" ) @@ -25,7 +25,7 @@ type ColorPalette struct { groupColor map[string]colors.RGBAColor } -func NewColorPalette(workflow *model.Workflow) ColorPalette { +func NewColorPalette(workflow *api.Workflow) ColorPalette { cp := ColorPalette{ stateToGroup: make(map[string]string, len(workflow.States)), groupColor: make(map[string]colors.RGBAColor), diff --git a/cmd/wfx-viewer/metadata/metadata.go b/cmd/wfx-viewer/metadata/metadata.go index 18e8530f..6dd703e5 100644 --- a/cmd/wfx-viewer/metadata/metadata.go +++ b/cmd/wfx-viewer/metadata/metadata.go @@ -12,5 +12,5 @@ var ( // values provided by linker Version = "dev" Commit = "unknown" - Date = "unknown" + Date = "1970-01-01T00:00:00+00:00" ) diff --git a/cmd/wfx-viewer/output/all.go b/cmd/wfx-viewer/output/all.go index c1241d7d..1210671c 100644 --- a/cmd/wfx-viewer/output/all.go +++ b/cmd/wfx-viewer/output/all.go @@ -15,13 +15,13 @@ import ( "github.com/siemens/wfx/cmd/wfx-viewer/output/plantuml" "github.com/siemens/wfx/cmd/wfx-viewer/output/smcat" "github.com/siemens/wfx/cmd/wfx-viewer/output/svg" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/spf13/pflag" ) type Generator interface { RegisterFlags(f *pflag.FlagSet) - Generate(out io.Writer, workflow *model.Workflow) error + Generate(out io.Writer, workflow *api.Workflow) error } var Generators = make(map[string]Generator) diff --git a/cmd/wfx-viewer/output/mermaid/mermaid.go b/cmd/wfx-viewer/output/mermaid/mermaid.go index bba5b24a..2300708f 100644 --- a/cmd/wfx-viewer/output/mermaid/mermaid.go +++ b/cmd/wfx-viewer/output/mermaid/mermaid.go @@ -14,7 +14,7 @@ import ( "strings" "github.com/siemens/wfx/cmd/wfx-viewer/colors" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/internal/workflow" "github.com/spf13/pflag" ) @@ -27,7 +27,7 @@ func NewGenerator() *Generator { func (g *Generator) RegisterFlags(_ *pflag.FlagSet) {} -func (g *Generator) Generate(out io.Writer, wf *model.Workflow) error { +func (g *Generator) Generate(out io.Writer, wf *api.Workflow) error { _, _ = out.Write([]byte("stateDiagram-v2\n")) initialState := *workflow.FindInitialState(wf) diff --git a/cmd/wfx-viewer/output/plantuml/plantuml.go b/cmd/wfx-viewer/output/plantuml/plantuml.go index 6005f693..fc2f578d 100644 --- a/cmd/wfx-viewer/output/plantuml/plantuml.go +++ b/cmd/wfx-viewer/output/plantuml/plantuml.go @@ -13,7 +13,7 @@ import ( "io" "github.com/siemens/wfx/cmd/wfx-viewer/colors" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/spf13/pflag" ) @@ -25,10 +25,10 @@ func NewGenerator() *Generator { func (g *Generator) RegisterFlags(_ *pflag.FlagSet) {} -func (g *Generator) Generate(out io.Writer, workflow *model.Workflow) error { +func (g *Generator) Generate(out io.Writer, workflow *api.Workflow) error { _, _ = out.Write([]byte("@startuml\n")) - allStates := make(map[string]*model.State, len(workflow.States)) + allStates := make(map[string]api.State, len(workflow.States)) for _, state := range workflow.States { allStates[state.Name] = state } @@ -43,8 +43,8 @@ func (g *Generator) Generate(out io.Writer, workflow *model.Workflow) error { // add transitions for _, transition := range workflow.Transitions { _, _ = out.Write([]byte((fmt.Sprintf("%s --> %s: %s", transition.From, transition.To, string(transition.Eligible))))) - if string(transition.Action) != "" { - _, _ = out.Write([]byte((fmt.Sprintf(" [%s]", string(transition.Action))))) + if transition.Action != nil { + _, _ = out.Write([]byte((fmt.Sprintf(" [%s]", string(*transition.Action))))) } _, _ = out.Write([]byte("\n")) } diff --git a/cmd/wfx-viewer/output/smcat/smcat.go b/cmd/wfx-viewer/output/smcat/smcat.go index e75c995c..5cbcca36 100644 --- a/cmd/wfx-viewer/output/smcat/smcat.go +++ b/cmd/wfx-viewer/output/smcat/smcat.go @@ -14,7 +14,7 @@ import ( "strings" "github.com/siemens/wfx/cmd/wfx-viewer/colors" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/internal/workflow" "github.com/spf13/pflag" ) @@ -27,7 +27,7 @@ func NewGenerator() *Generator { func (g *Generator) RegisterFlags(_ *pflag.FlagSet) {} -func (g *Generator) Generate(out io.Writer, wf *model.Workflow) error { +func (g *Generator) Generate(out io.Writer, wf *api.Workflow) error { cp := colors.NewColorPalette(wf) states := make([]string, 0, len(wf.States)) diff --git a/cmd/wfx-viewer/output/svg/svg.go b/cmd/wfx-viewer/output/svg/svg.go index c09323ff..50c2d14a 100644 --- a/cmd/wfx-viewer/output/svg/svg.go +++ b/cmd/wfx-viewer/output/svg/svg.go @@ -16,7 +16,7 @@ import ( "github.com/Southclaws/fault" "github.com/siemens/wfx/cmd/wfx-viewer/output/plantuml" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/spf13/pflag" ) @@ -35,7 +35,7 @@ func (s *Generator) RegisterFlags(f *pflag.FlagSet) { s.f = f } -func (s *Generator) Generate(out io.Writer, workflow *model.Workflow) error { +func (s *Generator) Generate(out io.Writer, workflow *api.Workflow) error { body := new(bytes.Buffer) writer := multipart.NewWriter(body) w, err := writer.CreateFormFile("file", "workflow") diff --git a/cmd/wfx/cmd/config/appconfig.go b/cmd/wfx/cmd/config/appconfig.go new file mode 100644 index 00000000..55e6556e --- /dev/null +++ b/cmd/wfx/cmd/config/appconfig.go @@ -0,0 +1,399 @@ +package config + +/* + * SPDX-FileCopyrightText: 2024 Siemens AG + * + * SPDX-License-Identifier: Apache-2.0 + * + * Author: Michael Adler + */ + +import ( + "errors" + "fmt" + "os" + "strings" + "sync" + "time" + + "github.com/Southclaws/fault" + "github.com/knadh/koanf/parsers/yaml" + "github.com/knadh/koanf/providers/env" + "github.com/knadh/koanf/providers/file" + "github.com/knadh/koanf/providers/posflag" + "github.com/knadh/koanf/v2" + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" + "github.com/spf13/pflag" +) + +type AppConfig struct { + mutex sync.RWMutex + k *koanf.Koanf + flags *pflag.FlagSet + fileProviders []*file.File + + // flags + logLevel zerolog.Level + logFormat string + storage string + storageOpts string + gracefulTimeout time.Duration + schemes []Scheme + simpleFileServer string + + maxHeaderSize int + readTimeout time.Duration + writeTimeout time.Duration + keepAlive bool + cleanupTimeout time.Duration + + tlsCACertificate string + tlsCertificate string + tlsKey string + + clientHost string + clientPort int + clientTLSHost string + clientTLSPort int + clientUnixSocket string + clientPluginsDir string + + mgmtHost string + mgmtPort int + mgmtTLSHost string + mgmtTLSPort int + mgmtUnixSocket string + mgmtPluginsDir string +} + +type Scheme int + +const ( + SchemeHTTP Scheme = iota + SchemeHTTPS + SchemeUnix +) + +func (scheme Scheme) String() string { + return []string{"http", "https", "unix"}[scheme] +} + +func NewAppConfig(flags *pflag.FlagSet) (*AppConfig, error) { + k := koanf.New(".") + knownOptions := make(map[string]bool, 64) + flags.VisitAll(func(flag *pflag.Flag) { + knownOptions[flag.Name] = true + }) + + mergeFn := koanf.WithMergeFunc(func(src, dest map[string]any) error { + // merge src into dest + for k, v := range src { + if _, exists := knownOptions[k]; !exists { + fmt.Fprintf(os.Stderr, "WARN: Ignoring unknown config option '%s'", k) + continue + } + dest[k] = v + } + return nil + }) + + // Load the config files provided in the commandline and set up file watches + cFiles, _ := flags.GetStringSlice(ConfigFlag) + fileProviders := make([]*file.File, 0, len(cFiles)) + for _, fname := range cFiles { + if _, err := os.Stat(fname); err == nil { + fp := file.Provider(fname) + if err := k.Load(fp, yaml.Parser(), mergeFn); err != nil { + return nil, fault.Wrap(err) + } + fileProviders = append(fileProviders, fp) + } + } + + envProvider := env.Provider("WFX_", ".", func(s string) string { + // WFX_LOG_LEVEL becomes log-level + return strings.ReplaceAll(strings.ToLower(strings.TrimPrefix(s, "WFX_")), "_", "-") + }) + if err := k.Load(envProvider, nil, mergeFn); err != nil { + fmt.Fprintln(os.Stderr, "ERROR: Could not load env variables") + } + if err := k.Load(posflag.Provider(flags, ".", k), nil); err != nil { + fmt.Fprintln(os.Stderr, "ERROR: Could not load CLI flags") + } + + cfg := new(AppConfig) + cfg.flags = flags + cfg.k = k + if ok := cfg.Reload(); !ok { + return nil, errors.New("configuration contains errors") + } + + // start watching config + for _, fp := range fileProviders { + if err := fp.Watch(func(_ interface{}, err error) { + if err != nil { + return + } + if err := k.Load(fp, yaml.Parser(), mergeFn); err == nil { + if ok := cfg.Reload(); !ok { + log.Error().Err(err).Msg("Failed to reload config") + } + } + }); err != nil { + log.Error().Err(err).Msg("Failed to set up config file watcher") + } + } + cfg.fileProviders = fileProviders + return cfg, nil +} + +func (cfg *AppConfig) Stop() { + for _, fp := range cfg.fileProviders { + _ = fp.Unwatch() + } +} + +func (cfg *AppConfig) LogLevel() zerolog.Level { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.logLevel +} + +func (cfg *AppConfig) LogFormat() string { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.logFormat +} + +func (cfg *AppConfig) Storage() string { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.storage +} + +func (cfg *AppConfig) StorageOptions() string { + name := cfg.Storage() + + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + + storageOpt := cfg.flags.Lookup(StorageOptFlag) + changed := storageOpt != nil && storageOpt.Changed + // do not return SQLite options for non-SQLite backends + if name != preferedStorage && (!changed || cfg.storageOpts == sqliteDefaultOpts) { + return "" + } + return cfg.storageOpts +} + +func (cfg *AppConfig) GracefulTimeout() time.Duration { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.gracefulTimeout +} + +func (cfg *AppConfig) Schemes() []Scheme { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.schemes +} + +func (cfg *AppConfig) SimpleFileserver() string { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.simpleFileServer +} + +func (cfg *AppConfig) Reload() bool { + ok := true + fmt.Fprintln(os.Stderr, "Reloading config") + + cfg.mutex.Lock() + defer cfg.mutex.Unlock() + + cfg.logFormat = cfg.k.String(LogFormatFlag) + cfg.storage = cfg.k.String(StorageFlag) + cfg.storageOpts = cfg.k.String(StorageOptFlag) + cfg.gracefulTimeout = cfg.k.Duration(GracefulTimeoutFlag) + if schemes := cfg.k.Strings(SchemeFlag); len(schemes) > 0 { + cfg.schemes = make([]Scheme, 0, len(schemes)) + for _, s := range schemes { + switch s { + case "http": + cfg.schemes = append(cfg.schemes, SchemeHTTP) + case "https": + cfg.schemes = append(cfg.schemes, SchemeHTTPS) + case "unix": + cfg.schemes = append(cfg.schemes, SchemeUnix) + default: + log.Error().Str("scheme", s).Msg("Unknown scheme") + ok = false + } + } + } + + cfg.tlsCACertificate = cfg.k.String(TLSCaFlag) + cfg.tlsCertificate = cfg.k.String(TLSCertificateFlag) + cfg.tlsKey = cfg.k.String(TLSKeyFlag) + + cfg.maxHeaderSize = cfg.k.Int(MaxHeaderSizeFlag) + cfg.readTimeout = cfg.k.Duration(ReadTimeoutFlag) + cfg.writeTimeout = cfg.k.Duration(WriteTimoutFlag) + cfg.cleanupTimeout = cfg.k.Duration(CleanupTimeoutFlag) + cfg.keepAlive = cfg.k.Bool(KeepAliveFlag) + + cfg.mgmtHost = cfg.k.String(MgmtHostFlag) + cfg.mgmtPort = cfg.k.Int(MgmtPortFlag) + cfg.mgmtTLSHost = cfg.k.String(MgmtTLSHostFlag) + cfg.mgmtTLSPort = cfg.k.Int(MgmtTLSPortFlag) + cfg.mgmtUnixSocket = cfg.k.String(MgmtUnixSocketFlag) + cfg.mgmtPluginsDir = cfg.k.String(MgmtPluginsDirFlag) + + cfg.clientHost = cfg.k.String(ClientHostFlag) + cfg.clientPort = cfg.k.Int(ClientPortFlag) + cfg.clientTLSHost = cfg.k.String(ClientTLSHostFlag) + cfg.clientTLSPort = cfg.k.Int(ClientTLSPortFlag) + cfg.clientUnixSocket = cfg.k.String(ClientUnixSocketFlag) + cfg.clientPluginsDir = cfg.k.String(ClientPluginsDirFlag) + + lvlString := cfg.k.String(LogLevelFlag) + if lvl, err := zerolog.ParseLevel(lvlString); err != nil { + fmt.Fprintln(os.Stderr, "Failed to parse log level:", lvlString) + ok = false + } else { + fmt.Fprintln(os.Stderr, "Setting global log level:", lvl) + cfg.logLevel = lvl + zerolog.SetGlobalLevel(lvl) + } + + cfg.simpleFileServer = cfg.k.String(SimpleFileServerFlag) + if cfg.simpleFileServer != "" { + info, err := os.Stat(cfg.simpleFileServer) + if err != nil || !info.IsDir() { + ok = false + fmt.Fprintf(os.Stderr, "%s is not a valid directory", cfg.simpleFileServer) + } + } + return ok +} + +func (cfg *AppConfig) MaxHeaderSize() int { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.maxHeaderSize +} + +func (cfg *AppConfig) ReadTimeout() time.Duration { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.readTimeout +} + +func (cfg *AppConfig) WriteTimeout() time.Duration { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.writeTimeout +} + +func (cfg *AppConfig) KeepAlive() bool { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.keepAlive +} + +func (cfg *AppConfig) CleanupTimeout() time.Duration { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.cleanupTimeout +} + +func (cfg *AppConfig) TLSCACertificate() string { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.tlsCACertificate +} + +func (cfg *AppConfig) TLSCertificate() string { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.tlsCertificate +} + +func (cfg *AppConfig) TLSKey() string { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.tlsKey +} + +func (cfg *AppConfig) ClientHost() string { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.clientHost +} + +func (cfg *AppConfig) ClientPort() int { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.clientPort +} + +func (cfg *AppConfig) ClientTLSHost() string { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.clientTLSHost +} + +func (cfg *AppConfig) ClientTLSPort() int { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.clientTLSPort +} + +func (cfg *AppConfig) ClientUnixSocket() string { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.clientUnixSocket +} + +func (cfg *AppConfig) ClientPluginsDir() string { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.clientPluginsDir +} + +func (cfg *AppConfig) MgmtHost() string { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.mgmtHost +} + +func (cfg *AppConfig) MgmtPort() int { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.mgmtPort +} + +func (cfg *AppConfig) MgmtTLSHost() string { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.mgmtTLSHost +} + +func (cfg *AppConfig) MgmtTLSPort() int { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.mgmtTLSPort +} + +func (cfg *AppConfig) MgmtUnixSocket() string { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.mgmtUnixSocket +} + +func (cfg *AppConfig) MgmtPluginsDir() string { + cfg.mutex.RLock() + defer cfg.mutex.RUnlock() + return cfg.mgmtPluginsDir +} diff --git a/cmd/wfx/cmd/config/appconfig_test.go b/cmd/wfx/cmd/config/appconfig_test.go new file mode 100644 index 00000000..05b91e6f --- /dev/null +++ b/cmd/wfx/cmd/config/appconfig_test.go @@ -0,0 +1,80 @@ +package config + +/* + * SPDX-FileCopyrightText: 2024 Siemens AG + * + * SPDX-License-Identifier: Apache-2.0 + * + * Author: Michael Adler + */ + +import ( + "os" + "reflect" + "testing" + "time" + + "github.com/rs/zerolog" + "github.com/spf13/pflag" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestNewAppConfig(t *testing.T) { + cfg, err := NewAppConfig(NewFlagset()) + defer cfg.Stop() + require.NoError(t, err) + + // call all methods which do not accept arguments + structValue := reflect.ValueOf(cfg) + for i := 0; i < structValue.NumMethod(); i++ { + method := structValue.Method(i) + methodType := method.Type() + if methodType.NumIn() == 0 { + t.Run(methodType.Name(), func(*testing.T) { + _ = method.Call([]reflect.Value{}) + }) + } + } +} + +func TestNewAppConfig_Invalid(t *testing.T) { + flags := pflag.NewFlagSet("TestNewAppConfig_Invalid", pflag.ContinueOnError) + _ = flags.String(LogLevelFlag, "info", "Log level") + _ = flags.Parse([]string{"--log-level", "foo"}) + + cfg, err := NewAppConfig(flags) + assert.Nil(t, cfg) + assert.Error(t, err) +} + +func TestReload(t *testing.T) { + dir, _ := os.MkdirTemp("", "TestReload") + cfgFile, _ := os.CreateTemp("", "config.yaml") + t.Cleanup(func() { + _ = cfgFile.Close() + _ = os.RemoveAll(dir) + }) + _, _ = cfgFile.Write([]byte("log-level: trace")) + + f := NewFlagset() + _ = f.Parse([]string{"--config", cfgFile.Name()}) + cfg, err := NewAppConfig(f) + defer cfg.Stop() + require.NoError(t, err) + + assert.Equal(t, zerolog.TraceLevel.String(), cfg.LogLevel().String()) + + { // modify config file + _, _ = cfgFile.Seek(0, 0) + _, _ = cfgFile.Write([]byte("log-level: error")) + } + + for i := 0; i < 500; i++ { + if zerolog.GlobalLevel() == zerolog.ErrorLevel { + break + } + time.Sleep(time.Millisecond * 10) + } + assert.Equal(t, zerolog.ErrorLevel.String(), zerolog.GlobalLevel().String()) +} diff --git a/cmd/wfx/cmd/config/flags.go b/cmd/wfx/cmd/config/flags.go new file mode 100644 index 00000000..b2255269 --- /dev/null +++ b/cmd/wfx/cmd/config/flags.go @@ -0,0 +1,130 @@ +package config + +/* + * SPDX-FileCopyrightText: 2024 Siemens AG + * + * SPDX-License-Identifier: Apache-2.0 + * + * Author: Michael Adler + */ + +import ( + "fmt" + "path" + "slices" + "strings" + "time" + + "github.com/OpenPeeDeeP/xdg" + "github.com/rs/zerolog" + "github.com/siemens/wfx/persistence" + "github.com/spf13/pflag" + + // import storages (must be here because we include them into the --help output) + _ "github.com/siemens/wfx/internal/persistence/entgo" +) + +// CLI flags +const ( + ConfigFlag = "config" + LogFormatFlag = "log-format" + LogLevelFlag = "log-level" + StorageFlag = "storage" + StorageOptFlag = "storage-opt" + SimpleFileServerFlag = "simple-fileserver" + + ClientHostFlag = "client-host" + ClientPortFlag = "client-port" + ClientTLSHostFlag = "client-tls-host" + ClientTLSPortFlag = "client-tls-port" + ClientUnixSocketFlag = "client-unix-socket" + ClientPluginsDirFlag = "client-plugins-dir" + + MgmtHostFlag = "mgmt-host" + MgmtPortFlag = "mgmt-port" + MgmtTLSHostFlag = "mgmt-tls-host" + MgmtTLSPortFlag = "mgmt-tls-port" + MgmtUnixSocketFlag = "mgmt-unix-socket" + MgmtPluginsDirFlag = "mgmt-plugins-dir" + + SchemeFlag = "scheme" + KeepAliveFlag = "keep-alive" + MaxHeaderSizeFlag = "max-header-size" + CleanupTimeoutFlag = "cleanup-timeout" + GracefulTimeoutFlag = "graceful-timeout" + ReadTimeoutFlag = "read-timeout" + WriteTimoutFlag = "write-timeout" + + TLSCaFlag = "tls-ca" + TLSCertificateFlag = "tls-certificate" + TLSKeyFlag = "tls-key" +) + +const ( + preferedStorage = "sqlite" + sqliteDefaultOpts = "file:wfx.db?_fk=1&_journal=WAL" +) + +func NewFlagset() *pflag.FlagSet { + f := pflag.NewFlagSet("wfx", pflag.ExitOnError) + + f.StringSlice(ConfigFlag, DefaultConfigFiles(), "path to one or more .yaml config files") + f.StringSlice(SchemeFlag, []string{"http"}, "the listeners to enable, this can be repeated and defaults to the schemes in the swagger spec") + f.Duration(CleanupTimeoutFlag, 10*time.Second, "grace period for which to wait before killing idle connections") + f.Duration(GracefulTimeoutFlag, 15*time.Second, "grace period for which to wait before shutting down the server") + f.Int(MaxHeaderSizeFlag, 1000000, "controls the maximum number of bytes the server will read parsing the request header's keys and values, including the request line. It does not limit the size of the request body") + f.Bool(KeepAliveFlag, true, "sets the TCP keep-alive timeouts on accepted connections. It prunes dead TCP connections ( e.g. closing laptop mid-download)") + f.Duration(ReadTimeoutFlag, 30*time.Second, "maximum duration before timing out read of the request") + f.Duration(WriteTimoutFlag, 10*time.Minute, "maximum duration before timing out write of the response") + f.String(SimpleFileServerFlag, "", "root directory for built-in fileserver (available under /download)") + + f.String(TLSCertificateFlag, "", "the certificate file to use for secure connections") + f.String(TLSKeyFlag, "", "the private key file to use for secure connections (without passphrase)") + f.String(TLSCaFlag, "", "the certificate authority certificate file to be used with mutual TLS auth") + + f.String(ClientHostFlag, "0.0.0.0", "the IP to listen on") + f.Int(ClientPortFlag, 8080, "the port to listen on for insecure connections") + f.String(ClientTLSHostFlag, "0.0.0.0", "the IP to listen on") + f.Int(ClientTLSPortFlag, 8443, "the port to listen on for secure connections, defaults to a random value") + f.String(ClientUnixSocketFlag, "/tmp/wfx-client.sock", "the unix domain socket to use") + f.String(ClientPluginsDirFlag, "", "directory containing client plugins") + + f.String(MgmtHostFlag, "127.0.0.1", "management host") + f.Int(MgmtPortFlag, 8081, "management port") + f.String(MgmtTLSHostFlag, "127.0.0.1", "management TLS host") + f.Int(MgmtTLSPortFlag, 8444, "TLS management port") + f.String(MgmtUnixSocketFlag, "/tmp/wfx-mgmt.sock", "the unix domain socket to use") + f.String(MgmtPluginsDirFlag, "", "directory containing management plugins") + + { + + supportedStorages := persistence.Storages() + defaultStorage := supportedStorages[0] + if slices.Index(supportedStorages, preferedStorage) != -1 { + defaultStorage = preferedStorage + } + f.String(StorageFlag, defaultStorage, fmt.Sprintf("persistence storage. one of: [%s]", strings.Join(supportedStorages, ", "))) + + var storageOpts string + if defaultStorage == preferedStorage { + storageOpts = sqliteDefaultOpts + } + f.String(StorageOptFlag, storageOpts, "storage options") + } + + allLevels := []string{zerolog.TraceLevel.String(), zerolog.DebugLevel.String(), zerolog.InfoLevel.String(), zerolog.WarnLevel.String(), zerolog.ErrorLevel.String(), zerolog.FatalLevel.String(), zerolog.PanicLevel.String()} + f.String(LogLevelFlag, "info", fmt.Sprintf("set log level. one of: [%s]", strings.Join(allLevels, ", "))) + f.String(LogFormatFlag, "auto", "log format; possible values: json, pretty, auto") + return f +} + +func DefaultConfigFiles() []string { + configFiles := []string{ + // current directory + "wfx.yml", + // user home + path.Join(xdg.ConfigHome(), "wfx", "config.yml"), + path.Join("/etc/wfx/wfx.yml"), + } + return configFiles +} diff --git a/cmd/wfx/cmd/config/flags_test.go b/cmd/wfx/cmd/config/flags_test.go new file mode 100644 index 00000000..2139e2b1 --- /dev/null +++ b/cmd/wfx/cmd/config/flags_test.go @@ -0,0 +1,20 @@ +package config + +/* + * SPDX-FileCopyrightText: 2024 Siemens AG + * + * SPDX-License-Identifier: Apache-2.0 + * + * Author: Michael Adler + */ + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestDefaultConfigFiles(t *testing.T) { + fnames := DefaultConfigFiles() + assert.NotEmpty(t, fnames) +} diff --git a/internal/config/main_test.go b/cmd/wfx/cmd/config/main_test.go similarity index 84% rename from internal/config/main_test.go rename to cmd/wfx/cmd/config/main_test.go index 26d91679..449961c1 100644 --- a/internal/config/main_test.go +++ b/cmd/wfx/cmd/config/main_test.go @@ -1,7 +1,7 @@ package config /* - * SPDX-FileCopyrightText: 2023 Siemens AG + * SPDX-FileCopyrightText: 2024 Siemens AG * * SPDX-License-Identifier: Apache-2.0 * diff --git a/cmd/wfx/cmd/root/cmd.go b/cmd/wfx/cmd/root/cmd.go deleted file mode 100644 index f7b7b68d..00000000 --- a/cmd/wfx/cmd/root/cmd.go +++ /dev/null @@ -1,291 +0,0 @@ -package root - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "context" - "errors" - "fmt" - "net" - "net/http" - "os" - "os/signal" - "os/user" - "strings" - "syscall" - "time" - - "github.com/Southclaws/fault" - "github.com/coreos/go-systemd/v22/activation" - "github.com/knadh/koanf/parsers/yaml" - "github.com/knadh/koanf/providers/env" - "github.com/knadh/koanf/providers/file" - "github.com/knadh/koanf/providers/posflag" - "github.com/knadh/koanf/v2" - "github.com/rs/zerolog/log" - "github.com/siemens/wfx/cmd/wfx/metadata" - "github.com/siemens/wfx/internal/config" - "github.com/siemens/wfx/internal/handler/job/events" - "github.com/siemens/wfx/persistence" - "github.com/spf13/cobra" - "github.com/spf13/pflag" - "go.uber.org/automaxprocs/maxprocs" -) - -var k = config.New() - -var signalChannel = make(chan os.Signal, 1) - -var Command = &cobra.Command{ - Use: "wfx", - Short: "wfx server", - Long: `This API allows to create and execute reusable workflows for clients. -Each workflow is modeled as a state machine running in the storage, with tasks to be executed by clients. - -Examples of tasks are installation of firmware or other types of commands issued to clients.`, - PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { - f := cmd.Flags() - knownOptions := make(map[string]bool, 64) - f.VisitAll(func(flag *pflag.Flag) { - knownOptions[flag.Name] = true - }) - - mergeFn := koanf.WithMergeFunc(func(src, dest map[string]any) error { - // merge src into dest - for k, v := range src { - if _, exists := knownOptions[k]; !exists { - fmt.Fprintf(os.Stderr, "ERROR: Unknown config option '%s'", k) - } - dest[k] = v - } - return nil - }) - - // Load the config files provided in the commandline. - cFiles, _ := f.GetStringSlice(configFlag) - var fileProvider *file.File - for _, fname := range cFiles { - if _, err := os.Stat(fname); err == nil { - fileProvider = file.Provider(fname) - k.Write(func(k *koanf.Koanf) { - if err := k.Load(fileProvider, yaml.Parser(), mergeFn); err != nil { - fmt.Fprintf(os.Stderr, "ERROR: Failed to load config file '%s'", fname) - } - }) - - } - } - - envProvider := env.Provider("WFX_", ".", func(s string) string { - // WFX_LOG_LEVEL becomes log-level - return strings.ReplaceAll(strings.ToLower(strings.TrimPrefix(s, "WFX_")), "_", "-") - }) - k.Write(func(k *koanf.Koanf) { - if err := k.Load(envProvider, nil, mergeFn); err != nil { - fmt.Fprintln(os.Stderr, "ERROR: Could not load env variables") - } - if err := k.Load(posflag.Provider(f, ".", k), nil); err != nil { - fmt.Fprintln(os.Stderr, "ERROR: Could not load CLI flags") - } - }) - - // now that we have merged all config sources, set up logger - var logLevel, logFormat string - k.Read(func(k *koanf.Koanf) { - logLevel = k.String(logLevelFlag) - logFormat = k.String(logFormatFlag) - }) - setupLogging(os.Stdout, logFormat, logLevel) - if _, err := maxprocs.Set(maxprocs.Logger(log.Printf)); err != nil { - log.Warn().Err(err).Msg("Failed to set GOMAXPROCS") - } - - // start watching config - if fileProvider != nil { - err := fileProvider.Watch(func(_ interface{}, err error) { - if err == nil { - k.Write(func(k *koanf.Koanf) { - if err := k.Load(fileProvider, yaml.Parser(), mergeFn); err == nil { - if err := reloadConfig(k); err != nil { - log.Error().Err(err).Msg("Failed to reload config") - } - } - }) - } - }) - if err != nil { - log.Error().Err(err).Msg("Failed to set up config file watcher") - } - } - - return nil - }, - RunE: func(*cobra.Command, []string) error { - var username string - if u, err := user.Current(); err == nil { - username = u.Username - } - - log.Info(). - Str("version", metadata.Version). - Str("date", metadata.Date). - Str("commit", metadata.Commit). - Str("user", username). - Msg("Starting wfx") - - var name, options string - k.Read(func(k *koanf.Koanf) { - name = k.String(storageFlag) - options = k.String(storageOptFlag) - }) - log.Debug().Str("name", name).Str("options", options).Msg("Setting up persistence storage") - if name != preferedStorage && options == defaultStorageOpts { - options = "" - } - - // note: storage is shared between north- and southbound API - storage := persistence.GetStorage(name) - if storage == nil { - return fmt.Errorf("unknown storage %s", name) - } - var err error - for i := 0; i < 300; i++ { - log.Debug().Str("name", name).Msg("Initializing storage") - err = storage.Initialize(context.Background(), options) - if err == nil { - log.Info().Str("name", name).Msg("Initialized storage") - break - } - dur := time.Second - log.Warn(). - Err(err). - Str("storage", name). - Msg("Failed to initialize persistent storage. Trying again in one second...") - time.Sleep(dur) - } - if err != nil { - return fault.Wrap(err) - } - defer storage.Shutdown() - - signal.Notify(signalChannel, os.Interrupt, syscall.SIGTERM) - - var schemes []string - k.Read(func(k *koanf.Koanf) { - schemes = k.Strings(schemeFlag) - }) - serverCollections := make([]*serverCollection, 0, 3) - chQuit := make(chan error) - { - collection, err := createNorthboundCollection(schemes, storage, chQuit) - if err != nil { - return fault.Wrap(err) - } - serverCollections = append(serverCollections, collection) - } - { - collection, err := createSouthboundCollection(schemes, storage, chQuit) - if err != nil { - return fault.Wrap(err) - } - serverCollections = append(serverCollections, collection) - } - - // check for socket-based activation (systemd) - listeners, _ := activation.Listeners() - serverCollections = append(serverCollections, adoptListeners(listeners, storage, chQuit)...) - - for _, collection := range serverCollections { - for i := range collection.servers { - // capture loop variables - // see https://go.dev/blog/loopvar-preview - // TODO: remove this once our go.mod targets Go 1.22 - name := collection.name - srv := collection.servers[i] - go func() { - if err := launchServer(name, srv); err != nil { - chQuit <- err - } - }() - } - } - - // wait for signal or an error - running := true - for running { - select { - case <-signalChannel: - running = false - case <-chQuit: - running = false - } - } - - // shut down (disconnect) subscribers otherwise we cannot stop the web server due to open connections - events.ShutdownSubscribers() - - // create a context with a timeout to allow outstanding requests to complete - var timeout time.Duration - k.Read(func(k *koanf.Koanf) { - timeout = k.Duration(gracefulTimeoutFlag) - }) - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() - - for _, collection := range serverCollections { - collection.Shutdown(ctx) - } - return nil - }, -} - -func adoptListeners(listeners []net.Listener, storage persistence.Storage, chQuit chan error) []*serverCollection { - if len(listeners) == 2 { - log.Debug().Msg("Adopting sockets provided by systemd") - south, err := createSouthboundCollection([]string{kindHTTP.String()}, storage, chQuit) - if err != nil { - log.Err(err).Msg("Failed to create southbound collection") - return nil - } - south.servers[0].Listener = func() (net.Listener, error) { - // use listener created by systemd - return listeners[0], nil - } - - north, err := createNorthboundCollection([]string{kindHTTP.String()}, storage, chQuit) - if err != nil { - log.Err(err).Msg("Failed to create northbound collection") - return nil - } - north.servers[0].Listener = func() (net.Listener, error) { - // use listener created by systemd - return listeners[1], nil - } - return []*serverCollection{south, north} - } - log.Debug().Msg("No sockets provided by systemd") - return nil -} - -func launchServer(name string, srv myServer) error { - ln, err := srv.Listener() - if err != nil { - return fault.Wrap(err) - } - log.Info().Str("name", name).Str("addr", ln.Addr().String()).Str("kind", srv.Kind.String()).Msg("Starting server") - if srv.Kind == kindHTTPS { - err = srv.Srv.ServeTLS(ln, "", "") - } else { - err = srv.Srv.Serve(ln) - } - if err != nil && !errors.Is(err, http.ErrServerClosed) { - return fault.Wrap(err) - } - return nil -} diff --git a/cmd/wfx/cmd/root/cmd_test.go b/cmd/wfx/cmd/root/cmd_test.go deleted file mode 100644 index 74834c2f..00000000 --- a/cmd/wfx/cmd/root/cmd_test.go +++ /dev/null @@ -1,227 +0,0 @@ -//go:build linux - -package root - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "context" - "errors" - "fmt" - "net" - "net/http" - "os" - "strings" - "sync" - "testing" - "time" - - "github.com/knadh/koanf/v2" - "github.com/rs/zerolog" - "github.com/siemens/wfx/cmd/wfxctl/flags" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestCommand_ReloadConfig(t *testing.T) { - dir, err := os.MkdirTemp("", "wfx-reload-test") - require.NoError(t, err) - - cfgFile, err := os.CreateTemp("", "wfxconfig") - require.NoError(t, err) - - var clientSocket, mgmtSocket string - k.Read(func(k *koanf.Koanf) { - clientSocket = k.String(flags.ClientUnixSocketFlag) - mgmtSocket = k.String(flags.MgmtUnixSocketFlag) - }) - - t.Cleanup(func() { - _ = cfgFile.Close() - _ = os.Remove(cfgFile.Name()) - _ = os.Remove(clientSocket) - _ = os.Remove(mgmtSocket) - _ = os.RemoveAll(dir) - }) - - _, err = cfgFile.Write([]byte("log-level: warn")) - require.NoError(t, err) - - Command.SetArgs([]string{ - "--config", cfgFile.Name(), - "--storage-opt=file:wfx?mode=memory&cache=shared&_fk=1", - "--scheme=unix", - }) - - err = errors.New("Should be set to nil by the goroutine") - - var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() - err = Command.Execute() - }() - - waitForLogLevel(t, zerolog.WarnLevel) - - // wait for inotify to be set up - foundInotify := false - for foundInotify { - fddir := fmt.Sprintf("/proc/%d/fd", os.Getpid()) - files, err := os.ReadDir(fddir) - require.NoError(t, err) - for _, f := range files { - fname, _ := os.Readlink(fmt.Sprintf("%s/%s", fddir, f.Name())) - if strings.HasPrefix(fname, "anon_inode") { - foundInotify = true - break - } - } - time.Sleep(10 * time.Millisecond) - } - - // modify config file - _, _ = cfgFile.Seek(0, 0) - _, err = cfgFile.Write([]byte("log-level: trace")) - require.NoError(t, err) - - waitForLogLevel(t, zerolog.TraceLevel) - - // tell go routine to stop - signalChannel <- os.Interrupt - - wg.Wait() - require.NoError(t, err) -} - -func TestAdoptListeners(t *testing.T) { - assert.Empty(t, adoptListeners(nil, nil, nil)) - assert.Empty(t, adoptListeners([]net.Listener{nil, nil, nil}, nil, nil)) - - sock1, _ := os.CreateTemp(os.TempDir(), "TestAdoptListeners*.sock") - sock2, _ := os.CreateTemp(os.TempDir(), "TestAdoptListeners*.sock") - t.Cleanup(func() { - _ = os.Remove(sock1.Name()) - _ = os.Remove(sock2.Name()) - }) - - ln1, _ := net.Listen("unix", sock1.Name()) - ln2, _ := net.Listen("unix", sock1.Name()) - - collection := adoptListeners([]net.Listener{ln1, ln2}, nil, nil) - t.Cleanup(func() { - for _, sc := range collection { - sc.Shutdown(context.Background()) - } - }) - assert.Len(t, collection, 2) - assert.Len(t, collection[0].servers, 1) - assert.Len(t, collection[1].servers, 1) - - actualLn1, err := collection[0].servers[0].Listener() - assert.Nil(t, err) - assert.Equal(t, ln1, actualLn1) - - actualLn2, err := collection[1].servers[0].Listener() - assert.Nil(t, err) - assert.Equal(t, ln2, actualLn2) -} - -func TestLaunchServer_ListenerError(t *testing.T) { - srv := myServer{ - Listener: func() (net.Listener, error) { - return nil, errors.New("something went wrong") - }, - } - err := launchServer("test", srv) - assert.NotNil(t, err) -} - -func TestLaunchServer_UDS(t *testing.T) { - f, _ := os.CreateTemp(os.TempDir(), "TestLaunchServer_UDS.*.sock") - f.Close() - _ = os.Remove(f.Name()) - ln, err := net.Listen("unix", f.Name()) - require.NoError(t, err) - - srv := myServer{ - Srv: &http.Server{Handler: http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { - rw.WriteHeader(http.StatusOK) - })}, - Listener: func() (net.Listener, error) { - return ln, nil - }, - Kind: kindUnix, - } - - var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() - err := launchServer("notls", srv) - assert.NoError(t, err) - }() - - for i := 0; i < 30; i++ { - time.Sleep(time.Millisecond * 10) - conn, err := net.Dial("unix", f.Name()) - if err != nil { - continue - } - defer conn.Close() - - req, err := http.NewRequest(http.MethodGet, "/", nil) - require.NoError(t, err) - client := &http.Client{ - Transport: &http.Transport{ - DialContext: func(_ context.Context, _, _ string) (net.Conn, error) { - return conn, nil - }, - }, - } - resp, err := client.Do(req) - if err == nil && resp.StatusCode == http.StatusOK { - break - } - } - - _ = srv.Srv.Shutdown(context.Background()) - wg.Wait() -} - -func TestLaunchServer_ListenerClosed(t *testing.T) { - f, _ := os.CreateTemp(os.TempDir(), "TestLaunchServer_UDS.*.sock") - f.Close() - _ = os.Remove(f.Name()) - ln, _ := net.Listen("unix", f.Name()) - _ = ln.Close() - - srv := myServer{ - Srv: &http.Server{Handler: http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { - rw.WriteHeader(http.StatusOK) - })}, - Listener: func() (net.Listener, error) { - return ln, nil - }, - Kind: kindUnix, - } - - err := launchServer("notls", srv) - assert.Error(t, err) -} - -func waitForLogLevel(t *testing.T, expected zerolog.Level) { - for i := 0; i < 500; i++ { - if zerolog.GlobalLevel() == expected { - break - } - time.Sleep(time.Millisecond * 10) - } - require.Equal(t, expected.String(), zerolog.GlobalLevel().String()) -} diff --git a/cmd/wfx/cmd/root/config.go b/cmd/wfx/cmd/root/config.go deleted file mode 100644 index b73a7e92..00000000 --- a/cmd/wfx/cmd/root/config.go +++ /dev/null @@ -1,31 +0,0 @@ -package root - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "fmt" - "os" - - "github.com/Southclaws/fault" - "github.com/knadh/koanf/v2" - "github.com/rs/zerolog" -) - -func reloadConfig(k *koanf.Koanf) error { - fmt.Fprintln(os.Stderr, "Reloading config") - - lvlString := k.String(logLevelFlag) - lvl, err := zerolog.ParseLevel(lvlString) - if err != nil { - return fault.Wrap(err) - } - fmt.Fprintln(os.Stderr, "Setting global log level:", lvl) - zerolog.SetGlobalLevel(lvl) - return nil -} diff --git a/cmd/wfx/cmd/root/config_test.go b/cmd/wfx/cmd/root/config_test.go deleted file mode 100644 index 795bd6d1..00000000 --- a/cmd/wfx/cmd/root/config_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package root - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "testing" - - "github.com/knadh/koanf/v2" - "github.com/stretchr/testify/require" -) - -func TestReloadConfig_Invalid(t *testing.T) { - var inner *koanf.Koanf - k.Write(func(k *koanf.Koanf) { - _ = k.Set(logLevelFlag, "foo") - // only do this in a test! - inner = k - }) - err := reloadConfig(inner) - require.Error(t, err) -} diff --git a/cmd/wfx/cmd/root/flags.go b/cmd/wfx/cmd/root/flags.go deleted file mode 100644 index 8e4da175..00000000 --- a/cmd/wfx/cmd/root/flags.go +++ /dev/null @@ -1,125 +0,0 @@ -package root - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "fmt" - "strings" - "time" - - "github.com/rs/zerolog" - "github.com/siemens/wfx/cmd/wfx/metadata/config" - "github.com/siemens/wfx/internal/cmd/man" - "github.com/siemens/wfx/middleware/fileserver" - "github.com/siemens/wfx/persistence" - - // import storages (must be here because we include them into the --help output - _ "github.com/siemens/wfx/internal/persistence/entgo" -) - -const ( - configFlag = "config" - storageFlag = "storage" - storageOptFlag = "storage-opt" - logFormatFlag = "log-format" - logLevelFlag = "log-level" - - clientHostFlag = "client-host" - clientPortFlag = "client-port" - clientTLSHostFlag = "client-tls-host" - clientTLSPortFlag = "client-tls-port" - clientUnixSocket = "client-unix-socket" - - mgmtHostFlag = "mgmt-host" - mgmtPortFlag = "mgmt-port" - mgmtTLSHostFlag = "mgmt-tls-host" - mgmtTLSPortFlag = "mgmt-tls-port" - mgmtUnixSocketFlag = "mgmt-unix-socket" - - schemeFlag = "scheme" - keepAliveFlag = "keep-alive" - maxHeaderSizeFlag = "max-header-size" - - cleanupTimeoutFlag = "cleanup-timeout" - gracefulTimeoutFlag = "graceful-timeout" - readTimeoutFlag = "read-timeout" - writeTimoutFlag = "write-timeout" - - tlsCaFlag = "tls-ca" - tlsCertificateFlag = "tls-certificate" - tlsKeyFlag = "tls-key" - - preferedStorage = "sqlite" - defaultStorageOpts = "file:wfx.db?_fk=1&_journal=WAL" -) - -func init() { - Command.AddCommand(man.Command) - - f := Command.PersistentFlags() - - f.StringSlice(schemeFlag, []string{"http"}, "the listeners to enable, this can be repeated and defaults to the schemes in the swagger spec") - f.Duration(cleanupTimeoutFlag, 10*time.Second, "grace period for which to wait before killing idle connections") - f.Duration(gracefulTimeoutFlag, 15*time.Second, "grace period for which to wait before shutting down the server") - f.Int(maxHeaderSizeFlag, 1000000, "controls the maximum number of bytes the server will read parsing the request header's keys and values, including the request line. It does not limit the size of the request body") - f.Duration(keepAliveFlag, 3*time.Minute, "sets the TCP keep-alive timeouts on accepted connections. It prunes dead TCP connections ( e.g. closing laptop mid-download)") - f.Duration(readTimeoutFlag, 30*time.Second, "maximum duration before timing out read of the request") - f.Duration(writeTimoutFlag, 10*time.Minute, "maximum duration before timing out write of the response") - - f.String(tlsCertificateFlag, "", "the certificate file to use for secure connections") - f.String(tlsKeyFlag, "", "the private key file to use for secure connections (without passphrase)") - f.String(tlsCaFlag, "", "the certificate authority certificate file to be used with mutual TLS auth") - - f.String(clientHostFlag, "0.0.0.0", "the IP to listen on") - f.Int(clientPortFlag, 8080, "the port to listen on for insecure connections") - f.String(clientTLSHostFlag, "0.0.0.0", "the IP to listen on") - f.Int(clientTLSPortFlag, 8443, "the port to listen on for secure connections, defaults to a random value") - f.String(clientUnixSocket, "/tmp/wfx-client.sock", "the unix domain socket to use") - - f.String(mgmtHostFlag, "0.0.0.0", "management host") - f.Int(mgmtPortFlag, 8081, "management port") - f.String(mgmtTLSHostFlag, "0.0.0.0", "management TLS host") - f.Int(mgmtTLSPortFlag, 8444, "TLS management port") - f.String(mgmtUnixSocketFlag, "/tmp/wfx-mgmt.sock", "the unix domain socket to use") - - _ = Command.MarkPersistentFlagDirname(fileserver.SimpleFileServerFlag) - f.String(fileserver.SimpleFileServerFlag, "", "root directory for built-in fileserver (available under /download)") - - f.StringSlice(configFlag, config.DefaultConfigFiles(), "path to one or more .yaml config files") - _ = Command.MarkPersistentFlagFilename(configFlag, "yml", "yaml") - - { - var defaultStorage string - supportedStorages := persistence.Storages() - for _, storage := range supportedStorages { - if storage == preferedStorage { - defaultStorage = preferedStorage - break - } - defaultStorage = storage - } - f.String(storageFlag, defaultStorage, fmt.Sprintf("persistence storage. one of: [%s]", strings.Join(supportedStorages, ", "))) - - if defaultStorage == preferedStorage { - f.String(storageOptFlag, defaultStorageOpts, "custom storage options") - } else { - f.String(storageOptFlag, "", "custom storage options") - } - } - - f.String(logLevelFlag, "info", fmt.Sprintf("set log level. one of: [%s,%s,%s,%s,%s,%s,%s]", - zerolog.TraceLevel.String(), - zerolog.DebugLevel.String(), - zerolog.InfoLevel.String(), - zerolog.WarnLevel.String(), - zerolog.ErrorLevel.String(), - zerolog.FatalLevel.String(), - zerolog.PanicLevel.String())) - f.String(logFormatFlag, "auto", "log format; possible values: json, pretty, auto") -} diff --git a/cmd/wfx/cmd/root/northbound.go b/cmd/wfx/cmd/root/northbound.go deleted file mode 100644 index f9d895da..00000000 --- a/cmd/wfx/cmd/root/northbound.go +++ /dev/null @@ -1,75 +0,0 @@ -package root - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "github.com/Southclaws/fault" - "github.com/knadh/koanf/v2" - "github.com/rs/cors" - "github.com/siemens/wfx/api" - "github.com/siemens/wfx/generated/northbound/restapi" - "github.com/siemens/wfx/internal/server" - "github.com/siemens/wfx/middleware" - "github.com/siemens/wfx/middleware/fileserver" - "github.com/siemens/wfx/middleware/health" - "github.com/siemens/wfx/middleware/jq" - "github.com/siemens/wfx/middleware/logging" - "github.com/siemens/wfx/middleware/swagger" - "github.com/siemens/wfx/middleware/version" - "github.com/siemens/wfx/persistence" -) - -func createNorthboundCollection(schemes []string, storage persistence.Storage, chQuit chan error) (*serverCollection, error) { - var settings server.HTTPSettings - k.Read(func(k *koanf.Koanf) { - settings.Host = k.String(mgmtHostFlag) - settings.TLSHost = k.String(mgmtTLSHostFlag) - settings.Port = k.Int(mgmtPortFlag) - settings.TLSPort = k.Int(mgmtTLSPortFlag) - settings.UDSPath = k.String(mgmtUnixSocketFlag) - }) - api := api.NewNorthboundAPI(storage) - - fsMW, err := fileserver.NewFileServerMiddleware(k) - if err != nil { - return nil, fault.Wrap(err) - } - - swaggerJSON, _ := restapi.SwaggerJSON.MarshalJSON() - - pluginMws, err := LoadNorthboundPlugins(chQuit) - if err != nil { - return nil, fault.Wrap(err) - } - - // LIFO, i.e. middlewares are applied in reverse order - intermdiateMws := []middleware.IntermediateMW{ - jq.MW{}, - fsMW, - swagger.NewSpecMiddleware(api.Context().BasePath(), swaggerJSON), - health.NewHealthMiddleware(storage), - version.MW{}, - middleware.PromoteWrapper(cors.AllowAll().Handler), - } - - intermdiateMws = append(intermdiateMws, pluginMws...) - intermdiateMws = append(intermdiateMws, logging.MW{}) - - mw := middleware.NewGlobalMiddleware(restapi.ConfigureAPI(api), intermdiateMws) - servers, err := createServers(schemes, mw, settings) - if err != nil { - mw.Shutdown() - return nil, fault.Wrap(err) - } - return &serverCollection{ - name: "northbound", - servers: servers, - middleware: mw, - }, nil -} diff --git a/cmd/wfx/cmd/root/plugins.go b/cmd/wfx/cmd/root/plugins.go deleted file mode 100644 index 611f6e7e..00000000 --- a/cmd/wfx/cmd/root/plugins.go +++ /dev/null @@ -1,21 +0,0 @@ -package root - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "github.com/siemens/wfx/middleware" -) - -func LoadNorthboundPlugins(chQuit chan error) ([]middleware.IntermediateMW, error) { - return loadPluginSet(mgmtPluginsDirFlag, chQuit) -} - -func LoadSouthboundPlugins(chQuit chan error) ([]middleware.IntermediateMW, error) { - return loadPluginSet(clientPluginsDirFlag, chQuit) -} diff --git a/cmd/wfx/cmd/root/plugins_disabled.go b/cmd/wfx/cmd/root/plugins_disabled.go index d6ee40fb..68f4f5fc 100644 --- a/cmd/wfx/cmd/root/plugins_disabled.go +++ b/cmd/wfx/cmd/root/plugins_disabled.go @@ -13,17 +13,12 @@ package root import ( "errors" - "github.com/knadh/koanf/v2" - "github.com/siemens/wfx/middleware" + "github.com/siemens/wfx/middleware/plugin" ) -func loadPluginSet(flag string, _ chan error) ([]middleware.IntermediateMW, error) { - var pluginsDir string - k.Read(func(k *koanf.Koanf) { - pluginsDir = k.String(flag) - }) - if pluginsDir != "" { +func loadPlugins(dir string) ([]plugin.Plugin, error) { + if dir != "" { return nil, errors.New("this binary was built without plugin support") } - return []middleware.IntermediateMW{}, nil + return []plugin.Plugin{}, nil } diff --git a/cmd/wfx/cmd/root/plugins_disabled_test.go b/cmd/wfx/cmd/root/plugins_disabled_test.go index d6a54922..91e7785f 100644 --- a/cmd/wfx/cmd/root/plugins_disabled_test.go +++ b/cmd/wfx/cmd/root/plugins_disabled_test.go @@ -13,36 +13,17 @@ package root import ( "testing" - "github.com/knadh/koanf/v2" "github.com/stretchr/testify/assert" ) -func TestLoadNorthboundPlugins(t *testing.T) { - k.Write(func(k *koanf.Koanf) { - _ = k.Set(mgmtPluginsDirFlag, "/plugins") - }) - mw, err := LoadNorthboundPlugins(nil) - assert.Nil(t, mw) +func TestLoadPlugins(t *testing.T) { + plugins, err := loadPlugins("/plugins") + assert.Nil(t, plugins) assert.ErrorContains(t, err, "this binary was built without plugin support") } func TestLoadNorthboundPlugins_None(t *testing.T) { - mw, err := LoadNorthboundPlugins(nil) + plugins, err := loadPlugins("") assert.NoError(t, err) - assert.Empty(t, mw) -} - -func TestLoadSouthboundPlugins(t *testing.T) { - k.Write(func(k *koanf.Koanf) { - _ = k.Set(clientPluginsDirFlag, "/plugins") - }) - mw, err := LoadSouthboundPlugins(nil) - assert.Nil(t, mw) - assert.ErrorContains(t, err, "this binary was built without plugin support") -} - -func TestLoadSouthboundPlugins_None(t *testing.T) { - mw, err := LoadSouthboundPlugins(nil) - assert.NoError(t, err) - assert.Empty(t, mw) + assert.Empty(t, plugins) } diff --git a/cmd/wfx/cmd/root/plugins_enabled.go b/cmd/wfx/cmd/root/plugins_enabled.go index 7396f299..121c86e6 100644 --- a/cmd/wfx/cmd/root/plugins_enabled.go +++ b/cmd/wfx/cmd/root/plugins_enabled.go @@ -17,42 +17,15 @@ import ( "sort" "github.com/Southclaws/fault" - "github.com/knadh/koanf/v2" "github.com/rs/zerolog/log" - "github.com/siemens/wfx/internal/errutil" - "github.com/siemens/wfx/middleware" "github.com/siemens/wfx/middleware/plugin" ) -func loadPluginSet(flag string, chQuit chan error) ([]middleware.IntermediateMW, error) { - var pluginsDir string - k.Read(func(k *koanf.Koanf) { - pluginsDir = k.String(flag) - }) - if pluginsDir == "" { - return []middleware.IntermediateMW{}, nil - } - return errutil.Wrap2(createPluginMiddlewares(pluginsDir, chQuit)) -} - -func createPluginMiddlewares(pluginsDir string, chQuit chan error) ([]middleware.IntermediateMW, error) { - pluginMws, err := loadPlugins(pluginsDir) - if err != nil { - return nil, fault.Wrap(err) - } - result := make([]middleware.IntermediateMW, 0, len(pluginMws)) - for _, p := range pluginMws { - mw, err := plugin.NewMiddleware(p, chQuit) - if err != nil { - return nil, fault.Wrap(err) - } - result = append(result, mw) - } - return result, nil -} - func loadPlugins(dir string) ([]plugin.Plugin, error) { - log.Debug().Msg("Loading plugins") + if dir == "" { + return []plugin.Plugin{}, nil + } + log.Debug().Str("dir", dir).Msg("Loading plugins") entries, err := os.ReadDir(dir) if err != nil { return nil, fault.Wrap(err) @@ -71,9 +44,10 @@ func loadPlugins(dir string) ([]plugin.Plugin, error) { } // check if file is executable if (info.Mode() & 0o111) != 0 { + log.Info().Str("dest", dest).Msg("Loading plugin") result = append(result, plugin.NewFBPlugin(dest)) } else { - log.Warn().Str("dest", dest).Msg("Ignoring non-executable file") + log.Debug().Str("dest", dest).Msg("Ignoring non-executable file") } } } diff --git a/cmd/wfx/cmd/root/plugins_flag.go b/cmd/wfx/cmd/root/plugins_flag.go deleted file mode 100644 index d959d14d..00000000 --- a/cmd/wfx/cmd/root/plugins_flag.go +++ /dev/null @@ -1,24 +0,0 @@ -package root - -/* - * SPDX-FileCopyrightText: 2024 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -const ( - clientPluginsDirFlag = "client-plugins-dir" - mgmtPluginsDirFlag = "mgmt-plugins-dir" -) - -func init() { - f := Command.PersistentFlags() - - _ = Command.MarkPersistentFlagDirname(clientPluginsDirFlag) - f.String(clientPluginsDirFlag, "", "directory containing client plugins") - - _ = Command.MarkPersistentFlagDirname(mgmtPluginsDirFlag) - f.String(mgmtPluginsDirFlag, "", "directory containing management plugins") -} diff --git a/cmd/wfx/cmd/root/plugins_test.go b/cmd/wfx/cmd/root/plugins_test.go index bc4f3370..b1cbe177 100644 --- a/cmd/wfx/cmd/root/plugins_test.go +++ b/cmd/wfx/cmd/root/plugins_test.go @@ -11,14 +11,10 @@ package root */ import ( - "context" - "io" "os" "path" "testing" - "github.com/knadh/koanf/v2" - "github.com/siemens/wfx/persistence" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -26,7 +22,7 @@ import ( func TestLoadPluginsEmpty(t *testing.T) { t.Parallel() - dir, _ := os.MkdirTemp("", "TestLoadPluginsEmpty") + dir, _ := os.MkdirTemp("", t.Name()) t.Cleanup(func() { _ = os.Remove(dir) }) @@ -38,7 +34,7 @@ func TestLoadPluginsEmpty(t *testing.T) { func TestLoadPlugins(t *testing.T) { t.Parallel() - dir, _ := os.MkdirTemp("", "TestLoadPlugins") + dir, _ := os.MkdirTemp("", t.Name()) t.Cleanup(func() { _ = os.RemoveAll(dir) }) @@ -56,7 +52,7 @@ func TestLoadPlugins(t *testing.T) { func TestLoadPluginsIgnoreNonExecutable(t *testing.T) { t.Parallel() - dir, _ := os.MkdirTemp("", "TestLoadPluginsIgnoreNonExecutable") + dir, _ := os.MkdirTemp("", t.Name()) t.Cleanup(func() { _ = os.RemoveAll(dir) }) @@ -72,7 +68,7 @@ func TestLoadPluginsIgnoreNonExecutable(t *testing.T) { func TestLoadPluginsSymlink(t *testing.T) { t.Parallel() - baseDir, _ := os.MkdirTemp("", "TestLoadPluginsSymlink") + baseDir, _ := os.MkdirTemp("", t.Name()) t.Cleanup(func() { _ = os.RemoveAll(baseDir) }) @@ -97,7 +93,7 @@ func TestLoadPluginsSymlink(t *testing.T) { func TestLoadPluginsSymlinkIgnoreNonExecutable(t *testing.T) { t.Parallel() - baseDir, _ := os.MkdirTemp("", "TestLoadPluginsSymlinkIgnoreNonExecutable") + baseDir, _ := os.MkdirTemp("", t.Name()) t.Cleanup(func() { _ = os.RemoveAll(baseDir) }) @@ -117,120 +113,30 @@ func TestLoadPluginsSymlinkIgnoreNonExecutable(t *testing.T) { assert.Len(t, plugins, 0) } -func TestCreatePluginMiddlewares_InvalidDir(t *testing.T) { - chQuit := make(chan error) - mws, err := createPluginMiddlewares("", chQuit) - assert.Nil(t, mws) - assert.NotNil(t, err) -} +func TestLoadPlugins_EmptyArg(t *testing.T) { + t.Parallel() -func TestCreatePluginMiddlewares_EmptyDir(t *testing.T) { - baseDir, _ := os.MkdirTemp("", "TestCreatePluginMiddlewares_EmptydDir") - t.Cleanup(func() { - _ = os.RemoveAll(baseDir) - }) - chQuit := make(chan error) - mws, err := createPluginMiddlewares(baseDir, chQuit) + mws, err := loadPlugins("") assert.Empty(t, mws) - assert.NoError(t, err) + assert.Nil(t, err) } -func TestCreatePluginMiddlewares_PluginFailure(t *testing.T) { - baseDir, _ := os.MkdirTemp("", "TestCreatePluginMiddlewares_PluginFailure") - t.Cleanup(func() { - _ = os.RemoveAll(baseDir) - }) - - f, err := os.CreateTemp(baseDir, "plugin*.sh") - require.NoError(t, err) - t.Cleanup(func() { - _ = os.Remove(f.Name()) - }) - _, _ = io.WriteString(f, "no shebang") - fname := f.Name() - _ = f.Close() - _ = os.Chmod(fname, os.FileMode(0o700)) - - chQuit := make(chan error) - mws, err := createPluginMiddlewares(baseDir, chQuit) - assert.Nil(t, mws) - assert.Error(t, err) -} +func TestLoadPlugins_EmptyDir(t *testing.T) { + t.Parallel() -func TestCreatePluginMiddlewares(t *testing.T) { - baseDir, _ := os.MkdirTemp("", "TestCreatePluginMiddlewares") + baseDir, _ := os.MkdirTemp("", t.Name()) t.Cleanup(func() { _ = os.RemoveAll(baseDir) }) - - f, err := os.CreateTemp(baseDir, "plugin*.sh") - require.NoError(t, err) - t.Cleanup(func() { - _ = os.Remove(f.Name()) - }) - _, _ = io.WriteString(f, `#!/bin/sh -while true; do - sleep 1 -done -`) - fname := f.Name() - _ = f.Close() - _ = os.Chmod(fname, os.FileMode(0o700)) - - chQuit := make(chan error) - mws, err := createPluginMiddlewares(baseDir, chQuit) - assert.Len(t, mws, 1) - assert.NoError(t, err) - mws[0].Shutdown() -} - -func TestCreateNorthboundCollection_PluginsDir(t *testing.T) { - dir, _ := os.MkdirTemp("", "TestCreateNorthboundCollection_PluginsDir.*") - t.Cleanup(func() { os.RemoveAll(dir) }) - k.Write(func(k *koanf.Koanf) { - _ = k.Set(mgmtPluginsDirFlag, dir) - }) - dbMock := persistence.NewMockStorage(t) - chQuit := make(chan error) - sc, err := createNorthboundCollection([]string{"http"}, dbMock, chQuit) - t.Cleanup(func() { sc.Shutdown(context.Background()) }) - assert.NoError(t, err) - assert.NotNil(t, sc) -} - -func TestCreateNorthboundCollection_PluginsDirError(t *testing.T) { - k.Write(func(k *koanf.Koanf) { - _ = k.Set(mgmtPluginsDirFlag, "/does/not/exist") - }) - dbMock := persistence.NewMockStorage(t) - chQuit := make(chan error) - sc, err := createNorthboundCollection([]string{"http"}, dbMock, chQuit) - assert.Error(t, err) - assert.Nil(t, sc) -} - -func TestCreateSouthboundCollection_PluginsDir(t *testing.T) { - dir, _ := os.MkdirTemp("", "TestCreateSouthboundCollection_PluginsDir.*") - t.Cleanup(func() { os.RemoveAll(dir) }) - k.Write(func(k *koanf.Koanf) { - _ = k.Set(clientPluginsDirFlag, dir) - }) - dbMock := persistence.NewMockStorage(t) - chQuit := make(chan error) - sc, err := createSouthboundCollection([]string{"http"}, dbMock, chQuit) - t.Cleanup(func() { sc.Shutdown(context.Background()) }) + mws, err := loadPlugins(baseDir) + assert.Empty(t, mws) assert.NoError(t, err) - assert.NotNil(t, sc) } -func TestCreateSouthboundCollection_PluginsDirError(t *testing.T) { - k.Write(func(k *koanf.Koanf) { - _ = k.Set(clientPluginsDirFlag, "/does/not/exist") - }) +func TestLoadPlugins_DirNotExist(t *testing.T) { + t.Parallel() - dbMock := persistence.NewMockStorage(t) - chQuit := make(chan error) - sc, err := createSouthboundCollection([]string{"http"}, dbMock, chQuit) + mws, err := loadPlugins("/does/not/exist") assert.Error(t, err) - assert.Nil(t, sc) + assert.Empty(t, mws) } diff --git a/cmd/wfx/cmd/root/root.go b/cmd/wfx/cmd/root/root.go new file mode 100644 index 00000000..e7ad0700 --- /dev/null +++ b/cmd/wfx/cmd/root/root.go @@ -0,0 +1,151 @@ +package root + +/* + * SPDX-FileCopyrightText: 2024 Siemens AG + * + * SPDX-License-Identifier: Apache-2.0 + * + * Author: Michael Adler + */ + +import ( + "fmt" + "os" + "os/signal" + "os/user" + "sync" + "syscall" + "time" + + "github.com/Southclaws/fault" + "github.com/rs/zerolog/log" + "github.com/siemens/wfx/cmd/wfx/cmd/config" + "github.com/siemens/wfx/cmd/wfx/metadata" + "github.com/siemens/wfx/internal/cmd/man" + "github.com/siemens/wfx/persistence" + "github.com/spf13/cobra" + "go.uber.org/automaxprocs/maxprocs" +) + +func NewCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "wfx", + Short: "wfx server", + Long: `wfx is a server that models workflows as finite-state machines and exposes a REST API to update the state machine. +It drives tasks in coordination with clients through jobs, with each job instantiation including metadata to guide the client. + +Examples of tasks are installation of firmware or other types of commands issued to clients.`, + Version: metadata.Version, + SilenceUsage: true, + RunE: func(cmd *cobra.Command, _ []string) error { + cfg, err := config.NewAppConfig(cmd.Flags()) + if err != nil { + return fault.Wrap(err) + } + defer cfg.Stop() + + setupLogging(os.Stdout, cfg.LogFormat(), cfg.LogLevel()) + + if _, err := maxprocs.Set(maxprocs.Logger(log.Printf)); err != nil { + log.Warn().Err(err).Msg("Failed to set GOMAXPROCS") + } + + var username string + if u, err := user.Current(); err == nil { + username = u.Username + } + + log.Info(). + Str("version", metadata.Version). + Str("date", metadata.Date). + Str("commit", metadata.Commit). + Str("user", username). + Msg("Starting wfx") + + storage, err := initStorage(cfg) + if err != nil { + return fault.Wrap(err) + } + defer storage.Shutdown() + + // channel to catch signals + chSignal := make(chan os.Signal, 1) + signal.Notify(chSignal, os.Interrupt, syscall.SIGTERM) + + chErr := make(chan error, 1) + collection, err := NewServerCollection(cfg, storage) + if err != nil { + return fault.Wrap(err) + } + + var g sync.WaitGroup + g.Add(1) + go func() { + defer g.Done() + err := collection.Start() + log.Debug().Msg("Server collection done") + if err != nil { + log.Debug().Msg("Sending error") + chErr <- err + } + close(chErr) + }() + + // reset error variable + err = nil + // wait for any shutdown event + select { + case sig := <-chSignal: + log.Info().Str("signal", sig.String()).Msg("Caught signal") + case err = <-chErr: + log.Err(err).Msg("Error in server collection") + case <-cmd.Context().Done(): + log.Info().Msg("Context done") + } + + collection.Stop() + log.Trace().Msg("Waiting for server collection goroutine") + g.Wait() + + log.Info().Msg("Exiting") + return fault.Wrap(err) + }, + } + cmd.AddCommand(man.NewCommand()) + cmd.PersistentFlags().AddFlagSet(config.NewFlagset()) + _ = cmd.MarkPersistentFlagDirname(config.SimpleFileServerFlag) + _ = cmd.MarkPersistentFlagFilename(config.ConfigFlag, "yml", "yaml") + _ = cmd.MarkPersistentFlagDirname(config.ClientPluginsDirFlag) + _ = cmd.MarkPersistentFlagDirname(config.MgmtPluginsDirFlag) + return cmd +} + +func initStorage(cfg *config.AppConfig) (persistence.Storage, error) { + name, options := cfg.Storage(), cfg.StorageOptions() + log.Debug().Str("name", name).Str("options", options).Msg("Setting up persistent storage") + + // note: storage is shared between north- and southbound API + storage := persistence.GetStorage(name) + if storage == nil { + return nil, fmt.Errorf("unknown storage %s", name) + } + var err error + for i := 0; i < 300; i++ { + log.Debug().Str("name", name).Msg("Initializing storage") + err = storage.Initialize(options) + if err == nil { + log.Info().Str("name", name).Msg("Initialized storage") + break + } + dur := time.Second + log.Warn(). + Err(err). + Str("storage", name). + Msg("Failed to initialize persistent storage. Trying again in one second...") + time.Sleep(dur) + } + if err != nil { + return nil, fault.Wrap(err) + } + return storage, nil +} diff --git a/cmd/wfx/cmd/root/root_test.go b/cmd/wfx/cmd/root/root_test.go new file mode 100644 index 00000000..07b87446 --- /dev/null +++ b/cmd/wfx/cmd/root/root_test.go @@ -0,0 +1,460 @@ +//go:build linux + +/* + * SPDX-FileCopyrightText: 2024 Siemens AG + * + * SPDX-License-Identifier: Apache-2.0 + * + * Author: Michael Adler + */ + +package root + +import ( + "bytes" + "context" + "crypto/rand" + "crypto/rsa" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/json" + "encoding/pem" + "fmt" + "io" + "math/big" + "net" + "net/http" + "os" + "path" + "strings" + "testing" + "time" + + "github.com/getkin/kin-openapi/openapi3" + "github.com/siemens/wfx/cmd/wfx/cmd/config" + "github.com/siemens/wfx/cmd/wfxctl/cmd" + "github.com/siemens/wfx/cmd/wfxctl/errutil" + "github.com/siemens/wfx/generated/api" + "github.com/siemens/wfx/workflow/dau" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/sync/errgroup" +) + +func TestUDS(t *testing.T) { + clientSocket, mgmtSocket := generateTempFilenames(t) + + cmd := NewCommand() + cmd.SetArgs([]string{ + "--log-level=debug", + "--storage-opt=file:wfx?mode=memory&cache=shared&_fk=1", + "--scheme=unix", + "--client-unix-socket", clientSocket, + "--mgmt-unix-socket", mgmtSocket, + }) + ctx, cancel := context.WithCancel(context.Background()) + cmd.SetContext(ctx) + + var g errgroup.Group + g.Go(cmd.Execute) + + for i := 0; i < 30; i++ { + conn, err := net.Dial("unix", clientSocket) + if err != nil { + time.Sleep(time.Millisecond * 10) + continue + } + defer conn.Close() + + req, err := http.NewRequest(http.MethodGet, "/version", nil) + require.NoError(t, err) + client := &http.Client{ + Transport: &http.Transport{ + DialContext: func(_ context.Context, _, _ string) (net.Conn, error) { + return conn, nil + }, + }, + } + resp, err := client.Do(req) + if err == nil && resp.StatusCode == http.StatusOK { + break + } + } + + // tell Command to stop + cancel() + + err := g.Wait() + require.NoError(t, err) +} + +func TestTLSOnly(t *testing.T) { + privkey, pubkey := createKeypair(t) + + cmd := NewCommand() + cmd.SetArgs([]string{ + "--log-level=debug", + "--storage-opt=file:wfx?mode=memory&cache=shared&_fk=1", + "--scheme=https", + "--tls-certificate", pubkey, + "--tls-key", privkey, + }) + ctx, cancel := context.WithCancel(context.Background()) + cmd.SetContext(ctx) + + var g errgroup.Group + g.Go(func() error { + return cmd.Execute() + }) + + httpClient := http.Client{ + Transport: &http.Transport{ + TLSClientConfig: &tls.Config{ + InsecureSkipVerify: true, + }, + TLSHandshakeTimeout: time.Second * 10, + }, + Timeout: time.Second * 10, + } + + f := config.NewFlagset() + + var upCount int + tlsEndpoints := []string{ + fmt.Sprintf("https://%s:%s", f.Lookup(config.ClientTLSHostFlag).DefValue, f.Lookup(config.ClientTLSPortFlag).DefValue), + fmt.Sprintf("https://%s:%s", f.Lookup(config.MgmtTLSHostFlag).DefValue, f.Lookup(config.MgmtTLSPortFlag).DefValue), + } + for i := 0; i < 30; i++ { + upCount = 0 + for _, endpoint := range tlsEndpoints { + client := errutil.Must(api.NewClientWithResponses(endpoint, api.WithHTTPClient(&httpClient))) + resp, _ := client.GetHealthWithResponse(ctx) + if resp != nil && resp.JSON200 != nil && resp.JSON200.Status == api.Up { + t.Log("Endpoint is up:", endpoint) + upCount++ + } else { + t.Log("Endpoint is down:", endpoint) + } + } + t.Log("Upcount:", upCount) + if upCount == len(tlsEndpoints) { + break + } + time.Sleep(100 * time.Millisecond) + } + + insecureEndpoints := []string{ + fmt.Sprintf("http://%s:%s", f.Lookup(config.ClientHostFlag).DefValue, f.Lookup(config.ClientPortFlag).DefValue), + fmt.Sprintf("http://%s:%s", f.Lookup(config.MgmtHostFlag).DefValue, f.Lookup(config.MgmtPortFlag).DefValue), + } + for _, endpoint := range insecureEndpoints { + resp, err := httpClient.Get(fmt.Sprintf("%s/health", endpoint)) + assert.Error(t, err) + assert.Nil(t, resp) + } + + // tell Command to stop + cancel() + + err := g.Wait() + require.NoError(t, err) + assert.Equal(t, len(tlsEndpoints), upCount) +} + +func TestTLSMixedMode(t *testing.T) { + privkey, pubkey := createKeypair(t) + + cmd := NewCommand() + cmd.SetArgs([]string{ + "--log-level=debug", + "--storage-opt=file:wfx?mode=memory&cache=shared&_fk=1", + "--scheme=http", + "--scheme=https", + "--tls-certificate", pubkey, + "--tls-key", privkey, + }) + ctx, cancel := context.WithCancel(context.Background()) + cmd.SetContext(ctx) + + var g errgroup.Group + g.Go(func() error { + return cmd.Execute() + }) + + httpClient := http.Client{ + Transport: &http.Transport{ + TLSClientConfig: &tls.Config{ + InsecureSkipVerify: true, + }, + TLSHandshakeTimeout: time.Second * 10, + }, + Timeout: time.Second * 10, + } + + f := config.NewFlagset() + + var upCount int + endpoints := []string{ + fmt.Sprintf("http://%s:%s", f.Lookup(config.ClientHostFlag).DefValue, f.Lookup(config.ClientPortFlag).DefValue), + fmt.Sprintf("https://%s:%s", f.Lookup(config.ClientTLSHostFlag).DefValue, f.Lookup(config.ClientTLSPortFlag).DefValue), + fmt.Sprintf("http://%s:%s", f.Lookup(config.MgmtHostFlag).DefValue, f.Lookup(config.MgmtPortFlag).DefValue), + fmt.Sprintf("https://%s:%s", f.Lookup(config.MgmtTLSHostFlag).DefValue, f.Lookup(config.MgmtTLSPortFlag).DefValue), + } + t.Logf("Endpoints: %v", endpoints) + for i := 0; i < 30; i++ { + upCount = 0 + for _, endpoint := range endpoints { + client := errutil.Must(api.NewClientWithResponses(endpoint, api.WithHTTPClient(&httpClient))) + resp, _ := client.GetHealthWithResponse(ctx) + if resp != nil && resp.JSON200 != nil && resp.JSON200.Status == api.Up { + t.Log("Endpoint is up:", endpoint) + upCount++ + } else { + t.Log("Endpoint is down:", endpoint) + } + } + t.Log("Upcount:", upCount) + if upCount == len(endpoints) { + break + } + time.Sleep(100 * time.Millisecond) + } + + // tell Command to stop + cancel() + + err := g.Wait() + require.NoError(t, err) + assert.Equal(t, len(endpoints), upCount) +} + +func TestAPI(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + var g errgroup.Group + g.Go(func() error { + cmd := NewCommand() + cmd.SetArgs([]string{ + "--log-level=debug", + "--storage-opt=file:wfx?mode=memory&cache=shared&_fk=1", + }) + cmd.SetContext(ctx) + return cmd.Execute() + }) + + t.Run("fetch openapiv3 spec", func(t *testing.T) { + httpClient := new(http.Client) + var spec openapi3.T + for i := 0; i < 100; i++ { + resp, err := httpClient.Get("http://localhost:8080/api/wfx/v1/openapiv3.json") + if err != nil { + time.Sleep(time.Millisecond * 10) + continue + } + defer resp.Body.Close() + // check valid json + err = json.NewDecoder(resp.Body).Decode(&spec) + require.NoError(t, err) + break + } + assert.Equal(t, "3.0.0", spec.OpenAPI) + }) + + t.Run("/health endpoint", func(t *testing.T) { + httpClient := new(http.Client) + var result api.CheckerResult + for i := 0; i < 100; i++ { + resp, err := httpClient.Get("http://localhost:8080/health") + if err != nil { + time.Sleep(time.Millisecond * 10) + continue + } + defer resp.Body.Close() + // check valid json + err = json.NewDecoder(resp.Body).Decode(&result) + require.NoError(t, err) + break + } + assert.Equal(t, api.Up, result.Status) + }) + + t.Run("/version endpoint", func(t *testing.T) { + httpClient := new(http.Client) + var result api.GetVersion200JSONResponse + for i := 0; i < 100; i++ { + resp, err := httpClient.Get("http://localhost:8080/version") + if err != nil { + time.Sleep(time.Millisecond * 10) + continue + } + defer resp.Body.Close() + // check valid json + err = json.NewDecoder(resp.Body).Decode(&result) + require.NoError(t, err) + break + } + assert.Equal(t, "v1", result.ApiVersion) + }) + + t.Run("Response Filters", func(t *testing.T) { + tmpFile, _ := os.CreateTemp("", "dau.yml.*") + wf := dau.DirectWorkflow() + _ = json.NewEncoder(tmpFile).Encode(wf) + _ = tmpFile.Close() + t.Cleanup(func() { _ = os.Remove(tmpFile.Name()) }) + + t.Setenv("WFX_CLIENT_HOST", "localhost") + t.Setenv("WFX_CLIENT_PORT", "8080") + t.Setenv("WFX_MGMT_HOST", "localhost") + t.Setenv("WFX_MGMT_PORT", "8081") + + wfxctl := cmd.NewCommand() + wfxctl.SetArgs([]string{"workflow", "create", tmpFile.Name()}) + err := wfxctl.Execute() + require.NoError(t, err) + + buf := new(bytes.Buffer) + wfxctl = cmd.NewCommand() + wfxctl.SetArgs([]string{ + "job", "create", "--workflow", wf.Name, + "--client-id=Dana", "--filter=.id", "--raw", + }) + wfxctl.SetOut(buf) + err = wfxctl.Execute() + require.NoError(t, err) + jobID := strings.TrimRight(buf.String(), "\n") + assert.NotEmpty(t, jobID) + t.Log("jobID", jobID) + + httpClient := new(http.Client) + var state string + for i := 0; i < 100; i++ { + url := fmt.Sprintf("http://localhost:8080/api/wfx/v1/jobs/%s/status", jobID) + req, err := http.NewRequest(http.MethodGet, url, nil) + require.NoError(t, err) + req.Header.Set("X-Response-Filter", ".state") + resp, err := httpClient.Do(req) + if err != nil { + time.Sleep(time.Millisecond * 10) + continue + } + defer resp.Body.Close() + b, _ := io.ReadAll(resp.Body) + state = strings.TrimSpace(string(b)) + break + } + assert.Equal(t, `"INSTALL"`, state) + }) + + t.Run("Fileserver Disabled", func(t *testing.T) { + httpClient := new(http.Client) + var statusCode int + var body []byte + for i := 0; i < 100; i++ { + resp, err := httpClient.Get("http://localhost:8080/download/") + if err != nil { + time.Sleep(time.Millisecond * 10) + continue + } + defer resp.Body.Close() + body, _ = io.ReadAll(resp.Body) + statusCode = resp.StatusCode + + } + assert.Equal(t, http.StatusNotFound, statusCode) + assert.Equal(t, `{"code":404,"message":"path /download is not served as simple file server is not enabled"}`, string(body)) + }) + + cancel() + err := g.Wait() + require.NoError(t, err) +} + +func TestSimpleFileServer(t *testing.T) { + dir, err := os.MkdirTemp("", "wfx-fileserver*") + require.NoError(t, err) + t.Cleanup(func() { os.RemoveAll(dir) }) + + testFile := path.Join(dir, "hello.txt") + err = os.WriteFile(testFile, []byte("Hello World!"), 0o644) + require.NoError(t, err) + + ctx, cancel := context.WithCancel(context.Background()) + + cmd := NewCommand() + cmd.SetContext(ctx) + cmd.SetArgs([]string{ + "--log-level=debug", + "--storage-opt=file:wfx?mode=memory&cache=shared&_fk=1", + "--" + config.SimpleFileServerFlag, dir, + }) + + var g errgroup.Group + g.Go(func() error { + return cmd.Execute() + }) + + httpClient := new(http.Client) + var statusCode int + var body []byte + for i := 0; i < 100; i++ { + resp, err := httpClient.Get("http://localhost:8080/download/hello.txt") + if err != nil { + time.Sleep(time.Millisecond * 10) + continue + } + defer resp.Body.Close() + body, _ = io.ReadAll(resp.Body) + statusCode = resp.StatusCode + } + + assert.Equal(t, http.StatusOK, statusCode) + assert.Equal(t, "Hello World!", string(body)) + + cancel() + + err = g.Wait() + require.NoError(t, err) +} + +func generateTempFilenames(t *testing.T) (string, string) { + fnames := make([]string, 0, 2) + for i := 0; i < 2; i++ { + f, _ := os.CreateTemp(os.TempDir(), fmt.Sprintf("%s.*.sock", t.Name())) + f.Close() + fname := f.Name() + _ = os.Remove(fname) + fnames = append(fnames, fname) + } + return fnames[0], fnames[1] +} + +func createKeypair(t *testing.T) (string, string) { + privateKey, _ := rsa.GenerateKey(rand.Reader, 2048) + template := x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: pkix.Name{CommonName: "My CA"}, + NotBefore: time.Now(), + NotAfter: time.Now().AddDate(0, 0, 1), // Valid for 1 day + KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, + BasicConstraintsValid: true, + IsCA: true, + } + derBytes, _ := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey) + + dir, _ := os.MkdirTemp("", "wfx-testkeys.*") + t.Cleanup(func() { os.RemoveAll(dir) }) + + privkey, pubkey := path.Join(dir, "test.key"), path.Join(dir, "test.crt") + certOut, _ := os.Create(pubkey) + defer certOut.Close() + + _ = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) + + keyOut, _ := os.OpenFile(privkey, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) + defer keyOut.Close() + + _ = pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}) + + return privkey, pubkey +} diff --git a/cmd/wfx/cmd/root/server.go b/cmd/wfx/cmd/root/server.go deleted file mode 100644 index 9d957b48..00000000 --- a/cmd/wfx/cmd/root/server.go +++ /dev/null @@ -1,157 +0,0 @@ -package root - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "context" - "errors" - "fmt" - "net" - "net/http" - "time" - - "github.com/Southclaws/fault" - "github.com/go-openapi/runtime/flagext" - "github.com/knadh/koanf/v2" - "github.com/rs/zerolog/log" - "github.com/siemens/wfx/internal/errutil" - "github.com/siemens/wfx/internal/server" - "github.com/siemens/wfx/middleware" -) - -type serverCollection struct { - // name of the collection - name string - // servers belonging to this collection - servers []myServer - // middleware shared between all servers - middleware *middleware.GlobalMW -} - -func (collection serverCollection) Shutdown(ctx context.Context) { - contextLogger := log.With().Str("name", collection.name).Logger() - for _, server := range collection.servers { - contextLogger.Info().Str("kind", server.Kind.String()).Msg("Shutting down server") - if err := server.Srv.Shutdown(ctx); err != nil { - log.Err(err).Msg("Shutdown error") - } - } - collection.middleware.Shutdown() - contextLogger.Info().Msg("Shutdown successful") -} - -type myServer struct { - Srv *http.Server - Listener func() (net.Listener, error) - Kind serverKind -} - -type serverKind int - -const ( - kindHTTP serverKind = iota - kindHTTPS - kindUnix -) - -func (k serverKind) String() string { - switch k { - case kindHTTP: - return "http" - case kindHTTPS: - return "https" - case kindUnix: - return "unix" - } - panic("unreachable") // non-exhaustive switch statement caught by linter -} - -func parseServerKind(scheme string) (*serverKind, error) { - var result serverKind - switch scheme { - case "http": - result = kindHTTP - case "https": - result = kindHTTPS - case "unix": - result = kindUnix - default: - return nil, fmt.Errorf("unknown scheme: %s", scheme) - } - return &result, nil -} - -func createServers(schemes []string, handler http.Handler, settings server.HTTPSettings) ([]myServer, error) { - result := make([]myServer, 0, 3) - - k.Read(func(k *koanf.Koanf) { - settings.MaxHeaderSize = flagext.ByteSize(k.Int(maxHeaderSizeFlag)) - settings.KeepAlive = k.Duration(keepAliveFlag) - settings.ReadTimeout = k.Duration(readTimeoutFlag) - settings.WriteTimeout = k.Duration(writeTimoutFlag) - settings.CleanupTimeout = k.Duration(cleanupTimeoutFlag) - }) - - for _, scheme := range schemes { - maybeKind, err := parseServerKind(scheme) - if err != nil { - return nil, fault.Wrap(err) - } - kind := *maybeKind - log.Debug().Str("kind", kind.String()).Msg("Creating server") - - switch kind { - case kindHTTP: - log.Debug().Msg("Creating http server") - srv := server.NewHTTPServer(&settings, handler) - - result = append(result, myServer{Srv: srv, Kind: kind, Listener: func() (net.Listener, error) { - return errutil.Wrap2(createListener("tcp", fmt.Sprintf("%s:%d", settings.Host, settings.Port))) - }}) - case kindHTTPS: - log.Debug().Msg("Creating https server") - srv := server.NewHTTPServer(&settings, handler) - var tlsSettings server.TLSSettings - k.Read(func(k *koanf.Koanf) { - tlsSettings.TLSCertificate = k.String(tlsCertificateFlag) - tlsSettings.TLSCertificateKey = k.String(tlsKeyFlag) - tlsSettings.TLSCACertificate = k.String(tlsCaFlag) - }) - err := server.ConfigureTLS(srv, &tlsSettings) - if err != nil { - return nil, fault.Wrap(err) - } - - result = append(result, myServer{Srv: srv, Kind: kind, Listener: func() (net.Listener, error) { - return errutil.Wrap2(createListener("tcp", fmt.Sprintf("%s:%d", settings.TLSHost, settings.TLSPort))) - }}) - - case kindUnix: - log.Debug().Msg("Creating unix-domain socket server") - srv := server.NewHTTPServer(&settings, handler) - result = append(result, myServer{Srv: srv, Kind: kind, Listener: func() (net.Listener, error) { - return errutil.Wrap2(createListener("unix", settings.UDSPath)) - }}) - } - } - return result, nil -} - -func createListener(network string, addr string) (net.Listener, error) { - maxAttempts := 30 - for attempt := 1; attempt <= maxAttempts; attempt++ { - ln, err := net.Listen(network, addr) - if err == nil { - return ln, nil - } - log.Err(err).Str("network", network).Str("addr", addr).Msg("Failed to create listener") - time.Sleep(time.Second) - } - return nil, errors.New("failed to create listener") -} diff --git a/cmd/wfx/cmd/root/server_collection.go b/cmd/wfx/cmd/root/server_collection.go new file mode 100644 index 00000000..d547bc85 --- /dev/null +++ b/cmd/wfx/cmd/root/server_collection.go @@ -0,0 +1,383 @@ +package root + +/* + * SPDX-FileCopyrightText: 2024 Siemens AG + * + * SPDX-License-Identifier: Apache-2.0 + * + * Author: Michael Adler + */ + +import ( + "context" + "errors" + "fmt" + "net" + "net/http" + "sync" + "time" + + "github.com/Southclaws/fault" + "github.com/coreos/go-systemd/v22/activation" + nethttpmiddleware "github.com/oapi-codegen/nethttp-middleware" + "github.com/rs/cors" + "github.com/rs/zerolog/log" + "github.com/siemens/wfx/api" + "github.com/siemens/wfx/cmd/wfx/cmd/config" + "github.com/siemens/wfx/cmd/wfxctl/errutil" + genApi "github.com/siemens/wfx/generated/api" + "github.com/siemens/wfx/internal/handler/job/events" + "github.com/siemens/wfx/internal/server" + "github.com/siemens/wfx/middleware/logging" + "github.com/siemens/wfx/middleware/plugin" + "github.com/siemens/wfx/persistence" + "github.com/siemens/wfx/spec" + "golang.org/x/sync/errgroup" +) + +type ServerCollection struct { + once sync.Once + cfg *config.AppConfig + storage persistence.Storage + north *http.Server + south *http.Server + wfx *api.WfxServer + + pluginMWs []*plugin.Middleware + pluginErrors []<-chan error +} + +func NewServerCollection(cfg *config.AppConfig, storage persistence.Storage) (*ServerCollection, error) { + wfx := api.NewWfxServer(storage) + + swag, _ := genApi.GetSwagger() + validator := nethttpmiddleware.OapiRequestValidatorWithOptions(swag, + &nethttpmiddleware.Options{SilenceServersWarning: true}) + corsMW := cors.AllowAll().Handler + logMW := logging.NewLoggingMiddleware() + + // LIFO + middlewares := []genApi.MiddlewareFunc{validator, corsMW, logMW} + + pluginMWs := make([]*plugin.Middleware, 0) + pluginErrors := make([]<-chan error, 0) + + northPluginMWs, err := createPluginMiddlewares(cfg.MgmtPluginsDir()) + if err != nil { + return nil, fault.Wrap(err) + } + + for _, mw := range northPluginMWs { + pluginMWs = append(pluginMWs, mw) + pluginErrors = append(pluginErrors, mw.Errors()) + } + + northServer, err := createServer(cfg, api.NewNorthboundServer(wfx), middlewares, northPluginMWs) + if err != nil { + return nil, fault.Wrap(err) + } + + southPluginMWs, err := createPluginMiddlewares(cfg.ClientPluginsDir()) + if err != nil { + return nil, fault.Wrap(err) + } + + for _, mw := range southPluginMWs { + pluginMWs = append(pluginMWs, mw) + pluginErrors = append(pluginErrors, mw.Errors()) + } + + southServer, err := createServer(cfg, api.NewSouthboundServer(wfx), middlewares, southPluginMWs) + if err != nil { + return nil, fault.Wrap(err) + } + + return &ServerCollection{ + cfg: cfg, + storage: storage, + pluginMWs: pluginMWs, + pluginErrors: pluginErrors, + wfx: wfx, + north: northServer, + south: southServer, + }, nil +} + +func (sc *ServerCollection) Start() error { + sc.wfx.Start() + + cfg := sc.cfg + schemes := cfg.Schemes() + // check for socket-based activation; order of sockets: south, north + systemdListeners, _ := activation.Listeners() + if len(systemdListeners) > 0 { + // perform sanity checks + if len(systemdListeners) != 2 { + return errors.New("systemd socket-based activation requires two sockets") + } + if len(schemes) != 1 || schemes[0] != config.SchemeUnix { + return errors.New("systemd socket-based activation only supports unix scheme") + } + } + + var g errgroup.Group + for _, scheme := range schemes { + var northListener, southListener net.Listener + if len(systemdListeners) > 0 { + log.Debug().Msg("Using sockets provided by systemd") + southListener, northListener = systemdListeners[0], systemdListeners[1] + } else { + var err error + northSettings := ListenerSettings{ + Host: cfg.MgmtHost(), + Port: cfg.MgmtPort(), + TLSHost: cfg.MgmtTLSHost(), + TLSPort: cfg.MgmtTLSPort(), + UDSPath: cfg.MgmtUnixSocket(), + } + northListener, err = createListener(scheme, northSettings) + if err != nil { + return fault.Wrap(err) + } + + southSettings := ListenerSettings{ + Host: cfg.ClientHost(), + Port: cfg.ClientPort(), + TLSHost: cfg.ClientTLSHost(), + TLSPort: cfg.ClientTLSPort(), + UDSPath: cfg.ClientUnixSocket(), + } + southListener, err = createListener(scheme, southSettings) + if err != nil { + return fault.Wrap(err) + } + } + + isTLS := scheme == config.SchemeHTTPS + g.Go(func() error { + defer func() { + log.Debug().Msg("Northbound goroutine finished") + }() + log.Info(). + Bool("tls", isTLS). + Str("scheme", scheme.String()). + Str("addr", northListener.Addr().String()). + Msg("Starting northbound server") + + var err error + if isTLS { + err = sc.north.ServeTLS(northListener, cfg.TLSCertificate(), cfg.TLSKey()) + } else { + err = sc.north.Serve(northListener) + } + if err != nil && !errors.Is(err, http.ErrServerClosed) { + log.Err(err).Msg("Northbound server encountered an error") + return fault.Wrap(err) + } + return nil + }) + + g.Go(func() error { + defer func() { + log.Debug().Msg("Southbound goroutine finished") + }() + log.Info(). + Bool("tls", isTLS). + Str("scheme", scheme.String()). + Str("addr", southListener.Addr().String()). + Msg("Starting southbound server") + var err error + if isTLS { + err = sc.south.ServeTLS(southListener, cfg.TLSCertificate(), cfg.TLSKey()) + } else { + err = sc.south.Serve(southListener) + } + if err != nil && !errors.Is(err, http.ErrServerClosed) { + log.Err(err).Msg("Southbound server encountered an error") + return fault.Wrap(err) + } + return nil + }) + } + + if len(sc.pluginErrors) > 0 { + g.Go(func() error { + defer func() { + log.Debug().Msg("Plugin reaper finished, triggering shutdown") + sc.Stop() + }() + + running := true + for running { + for _, chErr := range sc.pluginErrors { + select { + case err := <-chErr: + running = false + if err != nil { + log.Err(err).Msg("Received plugin error") + return err + } + default: + // no errors or channel was closed + } + } + time.Sleep(time.Millisecond * 300) + } + return nil + }) + } + + log.Debug().Msg("Waiting for goroutines to finish") + err := g.Wait() + log.Debug().Err(err).Msg("Goroutines finished") + + return fault.Wrap(err) +} + +// Stop the server collection and its associated listeners. It's safe to call this method multiple times. +func (sc *ServerCollection) Stop() { + sc.once.Do(func() { + timeout := sc.cfg.GracefulTimeout() + log.Info().Dur("timeout", timeout).Msg("Shutting down server collection") + + // shut down (disconnect) subscribers otherwise we cannot stop the web server due to open connections + events.ShutdownSubscribers() + + var shutdownGroup sync.WaitGroup + if sc.north != nil { + log.Debug().Msg("Shutting down northbound servers") + shutdownGroup.Add(1) + go func() { + defer shutdownGroup.Done() + + timeoutCtx, timeoutCancel := context.WithTimeout(context.Background(), timeout) + defer timeoutCancel() + + _ = sc.north.Shutdown(timeoutCtx) + log.Debug().Msg("Northbound server shut down complete") + }() + } + if sc.south != nil { + log.Debug().Msg("Shutting down southbound servers") + shutdownGroup.Add(1) + go func() { + defer shutdownGroup.Done() + + timeoutCtx, timeoutCancel := context.WithTimeout(context.Background(), timeout) + defer timeoutCancel() + + _ = sc.south.Shutdown(timeoutCtx) + log.Debug().Msg("Southbound server shut down complete") + }() + } + shutdownGroup.Wait() + + log.Debug().Msg("Shutting down plugin middlewares") + for _, mw := range sc.pluginMWs { + mw.Stop() + } + + log.Debug().Msg("Shutting down wfx") + sc.wfx.Stop() + log.Debug().Msg("Finished shutting down wfx") + + log.Info().Msg("Server collection shut down complete") + }) +} + +func createServer(cfg *config.AppConfig, ssi genApi.StrictServerInterface, baseMWs []genApi.MiddlewareFunc, pluginMWs []*plugin.Middleware) (*http.Server, error) { + combinedMWs := make([]genApi.MiddlewareFunc, 0, len(baseMWs)+len(pluginMWs)) + _ = copy(combinedMWs, baseMWs) + for _, mw := range pluginMWs { + combinedMWs = append(combinedMWs, mw.Middleware()) + } + + swag, _ := genApi.GetSwagger() + basePath := errutil.Must(swag.Servers.BasePath()) + strictHandler := genApi.NewStrictHandler(ssi, nil) + handler := genApi.HandlerWithOptions(strictHandler, genApi.StdHTTPServerOptions{ + BaseURL: basePath, + BaseRouter: createMux(cfg, strictHandler), + Middlewares: combinedMWs, + }) + server, err := server.NewHTTPServer(cfg, handler) + return server, fault.Wrap(err) +} + +func createPluginMiddlewares(pluginDir string) ([]*plugin.Middleware, error) { + plugins, err := loadPlugins(pluginDir) + if err != nil { + return nil, fault.Wrap(err) + } + + pluginMWs := make([]*plugin.Middleware, 0, len(plugins)) + for _, p := range plugins { + chErr := make(chan error, 1) + mw, err := plugin.NewMiddleware(p, chErr) + if err != nil { + return nil, fault.Wrap(err) + } + pluginMWs = append(pluginMWs, mw) + } + return pluginMWs, nil +} + +type ListenerSettings struct { + Host string + Port int + TLSHost string + TLSPort int + UDSPath string +} + +func createListener(scheme config.Scheme, settings ListenerSettings) (net.Listener, error) { + var network, addr string + switch scheme { + case config.SchemeUnix: + network = "unix" + addr = settings.UDSPath + case config.SchemeHTTP: + network = "tcp" + addr = fmt.Sprintf("%s:%d", settings.Host, settings.Port) + case config.SchemeHTTPS: + network = "tcp" + addr = fmt.Sprintf("%s:%d", settings.TLSHost, settings.TLSPort) + default: + return nil, fmt.Errorf("unsupported scheme: %s", scheme) + } + contextLogger := log.With().Str("network", network).Str("addr", addr).Str("scheme", scheme.String()).Logger() + for attempt := 0; attempt < 30; attempt++ { + ln, err := net.Listen(network, addr) + if err == nil { + contextLogger.Debug().Msg("Created new listener") + return ln, nil + } + contextLogger.Err(err).Msg("Failed to create listener") + time.Sleep(time.Second) + } + return nil, errors.New("failed to create listener") +} + +func createMux(cfg *config.AppConfig, server genApi.ServerInterface) *http.ServeMux { + mux := http.NewServeMux() + mux.HandleFunc("GET /version", func(w http.ResponseWriter, r *http.Request) { server.GetVersion(w, r) }) + mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) { server.GetHealth(w, r) }) + mux.HandleFunc("GET /download/", func(w http.ResponseWriter, r *http.Request) { + rootDir := cfg.SimpleFileserver() + enabled := rootDir != "" + log.Debug().Bool("enabled", enabled).Msg("Received download request") + if enabled { + http.StripPrefix("/download", http.FileServer(http.Dir(rootDir))).ServeHTTP(w, r) + } else { + w.WriteHeader(http.StatusNotFound) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"code":404,"message":"path /download is not served as simple file server is not enabled"}`)) + } + }) + + for pattern, handler := range spec.Handlers { + mux.Handle(pattern, handler) + } + + return mux +} diff --git a/cmd/wfx/cmd/root/server_collection_test.go b/cmd/wfx/cmd/root/server_collection_test.go new file mode 100644 index 00000000..e5a3e36c --- /dev/null +++ b/cmd/wfx/cmd/root/server_collection_test.go @@ -0,0 +1,95 @@ +package root + +/* + * SPDX-FileCopyrightText: 2024 Siemens AG + * + * SPDX-License-Identifier: Apache-2.0 + * + * Author: Michael Adler + */ + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path" + "testing" + + "github.com/siemens/wfx/cmd/wfx/cmd/config" + "github.com/siemens/wfx/persistence" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestNewServerCollection(t *testing.T) { + dbMock := persistence.NewHealthyMockStorage(t) + sc, err := NewServerCollection(new(config.AppConfig), dbMock) + assert.NotNil(t, sc) + assert.NoError(t, err) +} + +func TestOpenAPIJSON(t *testing.T) { + mux := createMux(new(config.AppConfig), nil) + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/wfx/v1/openapiv3.json", nil)) + result := rec.Result() + assert.Equal(t, http.StatusOK, result.StatusCode) +} + +func TestTopLevelNotFound(t *testing.T) { + mux := createMux(new(config.AppConfig), nil) + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil)) + result := rec.Result() + assert.Equal(t, http.StatusNotFound, result.StatusCode) + b, _ := io.ReadAll(result.Body) + assert.Equal(t, "The requested resource could not be found.\n\nHint: Check /api/wfx/v1/openapiv3.json to see available endpoints.\n", string(b)) +} + +func TestDownloadRedirect(t *testing.T) { + mux := createMux(new(config.AppConfig), nil) + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/download", nil)) + result := rec.Result() + assert.Equal(t, http.StatusMovedPermanently, result.StatusCode) + b, _ := io.ReadAll(result.Body) + assert.Contains(t, string(b), "/download/") +} + +func TestDownload(t *testing.T) { + tmp := os.TempDir() + tmpFile, _ := os.CreateTemp(tmp, "TestDownload.*") + _, _ = tmpFile.Write([]byte("hello world")) + _ = tmpFile.Close() + t.Cleanup(func() { _ = os.Remove(tmpFile.Name()) }) + + f := config.NewFlagset() + _ = f.Parse([]string{"--" + config.SimpleFileServerFlag, tmp}) + cfg, err := config.NewAppConfig(f) + require.NotEmpty(t, cfg.SimpleFileserver()) + require.NoError(t, err) + t.Cleanup(cfg.Stop) + + mux := createMux(cfg, nil) + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, fmt.Sprintf("/download/%s", path.Base(tmpFile.Name())), nil)) + result := rec.Result() + assert.Equal(t, http.StatusOK, result.StatusCode) + b, _ := io.ReadAll(result.Body) + assert.Contains(t, string(b), "hello world") +} + +func TestDownload_NotFound(t *testing.T) { + f := config.NewFlagset() + cfg, err := config.NewAppConfig(f) + t.Cleanup(cfg.Stop) + require.NoError(t, err) + mux := createMux(cfg, nil) + + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/download/", nil)) + result := rec.Result() + assert.Equal(t, http.StatusNotFound, result.StatusCode) +} diff --git a/cmd/wfx/cmd/root/server_test.go b/cmd/wfx/cmd/root/server_test.go deleted file mode 100644 index 6d894e98..00000000 --- a/cmd/wfx/cmd/root/server_test.go +++ /dev/null @@ -1,93 +0,0 @@ -package root - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "crypto/x509/pkix" - "encoding/pem" - "math/big" - "net/http" - "os" - "path" - "testing" - "time" - - "github.com/knadh/koanf/v2" - "github.com/siemens/wfx/internal/server" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestServerKind(t *testing.T) { - assert.Equal(t, "http", kindHTTP.String()) - assert.Equal(t, "https", kindHTTPS.String()) - assert.Equal(t, "unix", kindUnix.String()) -} - -func TestCreateServers_InvalidKind(t *testing.T) { - _, err := createServers([]string{"foo"}, nil, server.HTTPSettings{}) - assert.NotNil(t, err) - assert.ErrorContains(t, err, "unknown scheme: foo") -} - -func TestCreateServers_TLS(t *testing.T) { - privateKey, err := rsa.GenerateKey(rand.Reader, 2048) - require.NoError(t, err) - - template := x509.Certificate{ - SerialNumber: big.NewInt(1), - Subject: pkix.Name{CommonName: "My CA"}, - NotBefore: time.Now(), - NotAfter: time.Now().AddDate(0, 0, 1), // Valid for 1 day - KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, - BasicConstraintsValid: true, - IsCA: true, - } - - derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey) - require.NoError(t, err) - - dir, err := os.MkdirTemp(os.TempDir(), "wfx-tlsca") - require.NoError(t, err) - defer os.RemoveAll(dir) - - caCrtFile := path.Join(dir, "ca.crt") - caKeyFile := path.Join(dir, "ca.key") - { - certOut, err := os.Create(caCrtFile) - require.NoError(t, err) - defer certOut.Close() - - err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) - require.NoError(t, err) - - keyOut, err := os.OpenFile(caKeyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) - require.NoError(t, err) - defer keyOut.Close() - - err = pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}) - require.NoError(t, err) - } - - k.Write(func(k *koanf.Koanf) { - _ = k.Set(tlsCertificateFlag, caCrtFile) - _ = k.Set(tlsKeyFlag, caKeyFile) - _ = k.Set(tlsCaFlag, caCrtFile) - }) - - handler := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}) - servers, err := createServers([]string{kindHTTPS.String()}, handler, server.HTTPSettings{}) - require.Nil(t, err) - require.Len(t, servers, 1) - assert.Equal(t, kindHTTPS, servers[0].Kind) - assert.NotEmpty(t, servers[0].Srv.TLSConfig.Certificates) -} diff --git a/cmd/wfx/cmd/root/setup.go b/cmd/wfx/cmd/root/setup.go index ae104e04..c52daa39 100644 --- a/cmd/wfx/cmd/root/setup.go +++ b/cmd/wfx/cmd/root/setup.go @@ -18,12 +18,7 @@ import ( "golang.org/x/term" ) -func setupLogging(out *os.File, format string, level string) { - lvl, err := zerolog.ParseLevel(level) - if err != nil { - fmt.Fprintf(os.Stderr, "Invalid log level: %s\n", level) - lvl = zerolog.InfoLevel - } +func setupLogging(out *os.File, format string, lvl zerolog.Level) { zerolog.SetGlobalLevel(lvl) var logger zerolog.Logger diff --git a/cmd/wfx/cmd/root/southbound.go b/cmd/wfx/cmd/root/southbound.go deleted file mode 100644 index 3ad16b6a..00000000 --- a/cmd/wfx/cmd/root/southbound.go +++ /dev/null @@ -1,75 +0,0 @@ -package root - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "github.com/Southclaws/fault" - "github.com/knadh/koanf/v2" - "github.com/rs/cors" - "github.com/siemens/wfx/api" - "github.com/siemens/wfx/generated/southbound/restapi" - "github.com/siemens/wfx/internal/server" - "github.com/siemens/wfx/middleware" - "github.com/siemens/wfx/middleware/fileserver" - "github.com/siemens/wfx/middleware/health" - "github.com/siemens/wfx/middleware/jq" - "github.com/siemens/wfx/middleware/logging" - "github.com/siemens/wfx/middleware/swagger" - "github.com/siemens/wfx/middleware/version" - "github.com/siemens/wfx/persistence" -) - -func createSouthboundCollection(schemes []string, storage persistence.Storage, chQuit chan error) (*serverCollection, error) { - var settings server.HTTPSettings - k.Read(func(k *koanf.Koanf) { - settings.Host = k.String(clientHostFlag) - settings.TLSHost = k.String(clientTLSHostFlag) - settings.Port = k.Int(clientPortFlag) - settings.TLSPort = k.Int(clientTLSPortFlag) - settings.UDSPath = k.String(clientUnixSocket) - }) - api := api.NewSouthboundAPI(storage) - - fsMW, err := fileserver.NewFileServerMiddleware(k) - if err != nil { - return nil, fault.Wrap(err) - } - - swaggerJSON, _ := restapi.SwaggerJSON.MarshalJSON() - - pluginMws, err := LoadSouthboundPlugins(chQuit) - if err != nil { - return nil, fault.Wrap(err) - } - - // LIFO, i.e. middlewares are applied in reverse order - intermdiateMws := []middleware.IntermediateMW{ - jq.MW{}, - fsMW, - swagger.NewSpecMiddleware(api.Context().BasePath(), swaggerJSON), - health.NewHealthMiddleware(storage), - version.MW{}, - middleware.PromoteWrapper(cors.AllowAll().Handler), - } - - intermdiateMws = append(intermdiateMws, pluginMws...) - intermdiateMws = append(intermdiateMws, logging.MW{}) - - mw := middleware.NewGlobalMiddleware(restapi.ConfigureAPI(api), intermdiateMws) - servers, err := createServers(schemes, mw, settings) - if err != nil { - mw.Shutdown() - return nil, fault.Wrap(err) - } - return &serverCollection{ - name: "southbound", - servers: servers, - middleware: mw, - }, nil -} diff --git a/cmd/wfx/main.go b/cmd/wfx/main.go index 2f7775d7..95d9ab2b 100644 --- a/cmd/wfx/main.go +++ b/cmd/wfx/main.go @@ -9,15 +9,15 @@ package main */ import ( - "github.com/rs/zerolog/log" + "fmt" + "os" "github.com/siemens/wfx/cmd/wfx/cmd/root" - "github.com/siemens/wfx/cmd/wfx/metadata" ) func main() { - root.Command.Version = metadata.Version - if err := root.Command.Execute(); err != nil { - log.Fatal().Err(err).Msg("wfx encountered an error") + if err := root.NewCommand().Execute(); err != nil { + fmt.Fprintf(os.Stderr, "wfx encountered an error: %+v\n", err) + os.Exit(1) } } diff --git a/cmd/wfx/metadata/config/config.go b/cmd/wfx/metadata/config/config.go deleted file mode 100644 index cffceb3c..00000000 --- a/cmd/wfx/metadata/config/config.go +++ /dev/null @@ -1,26 +0,0 @@ -package config - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "path" - - "github.com/OpenPeeDeeP/xdg" -) - -func DefaultConfigFiles() []string { - configFiles := []string{ - // current directory - "wfx.yml", - // user home - path.Join(xdg.ConfigHome(), "wfx", "config.yml"), - path.Join("/etc/wfx/wfx.yml"), - } - return configFiles -} diff --git a/middleware/health/main_test.go b/cmd/wfx/metadata/main_test.go similarity index 77% rename from middleware/health/main_test.go rename to cmd/wfx/metadata/main_test.go index 082ecd07..ca44d49e 100644 --- a/middleware/health/main_test.go +++ b/cmd/wfx/metadata/main_test.go @@ -1,7 +1,7 @@ -package health +package metadata /* - * SPDX-FileCopyrightText: 2023 Siemens AG + * SPDX-FileCopyrightText: 2024 Siemens AG * * SPDX-License-Identifier: Apache-2.0 * diff --git a/cmd/wfx/metadata/metadata.go b/cmd/wfx/metadata/metadata.go index 0e0ef1bd..455de511 100644 --- a/cmd/wfx/metadata/metadata.go +++ b/cmd/wfx/metadata/metadata.go @@ -8,10 +8,21 @@ package metadata * Author: Michael Adler */ +import ( + "time" + + "github.com/Southclaws/fault" +) + var ( // values provided by linker Version = "dev" Commit = "unknown" - Date = "unknown" + Date = "1970-01-01T00:00:00+00:00" APIVersion = "v1" ) + +func BuildDate() (time.Time, error) { + buildDate, err := time.Parse("2006-01-02T15:04:05-07:00", Date) + return buildDate, fault.Wrap(err) +} diff --git a/cmd/wfx/metadata/metadata_test.go b/cmd/wfx/metadata/metadata_test.go new file mode 100644 index 00000000..2a984562 --- /dev/null +++ b/cmd/wfx/metadata/metadata_test.go @@ -0,0 +1,20 @@ +package metadata + +/* + * SPDX-FileCopyrightText: 2024 Siemens AG + * + * SPDX-License-Identifier: Apache-2.0 + * + * Author: Michael Adler + */ + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestBuildDate(t *testing.T) { + _, err := BuildDate() + require.NoError(t, err) +} diff --git a/cmd/wfxctl/cmd/health/health.go b/cmd/wfxctl/cmd/health/health.go index 69b26542..7f2035c9 100644 --- a/cmd/wfxctl/cmd/health/health.go +++ b/cmd/wfxctl/cmd/health/health.go @@ -10,161 +10,133 @@ package health import ( "bufio" - "crypto/tls" - "encoding/json" "fmt" "io" - "net/http" "os" - "time" + "sync" - "github.com/alexliesenfeld/health" + "github.com/Southclaws/fault" "github.com/gookit/color" "github.com/mattn/go-isatty" "github.com/rs/zerolog/log" "github.com/spf13/cobra" + "github.com/siemens/wfx/cmd/wfxctl/errutil" "github.com/siemens/wfx/cmd/wfxctl/flags" + "github.com/siemens/wfx/generated/api" ) -type endpoint struct { - Name string `json:"name"` - URL string `json:"url"` - Status health.AvailabilityStatus `json:"status"` +type Endpoint struct { + Name string + Server string + Response *api.GetHealthResponse } const ( colorNever = "never" colorAlways = "always" colorAuto = "auto" - colorFlag = "color" ) -func init() { - f := Command.Flags() - f.String(colorFlag, colorAuto, fmt.Sprintf("possible values: %s, %s, %s", colorNever, colorAlways, colorAuto)) -} - -var Command = &cobra.Command{ - Use: "health", - Short: "Check health of wfx", - Long: "Check health wfx", - TraverseChildren: true, - Run: func(cmd *cobra.Command, _ []string) { - tty := isatty.IsTerminal(os.Stdout.Fd()) - - colorMode := flags.Koanf.String(colorFlag) - var useColor bool - switch colorMode { - case colorAlways: - useColor = true - case colorAuto: - useColor = tty - case colorNever: - useColor = false - default: - log.Warn().Str("color", colorMode).Msg("Unsupported color mode") - } +func NewCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "health", + Short: "Check health of wfx", + Long: "Check health wfx", + TraverseChildren: true, + RunE: func(cmd *cobra.Command, _ []string) error { + b := flags.NewBaseCmd(cmd.Flags()) + + var useColor bool + switch b.ColorMode { + case colorAlways: + useColor = true + case colorAuto: + useColor = isatty.IsTerminal(os.Stdout.Fd()) + case colorNever: + useColor = false + default: + return fmt.Errorf("unsupported color mode: %s", b.ColorMode) + } - allEndpoints := []endpoint{ - { - Name: "northbound", - URL: fmt.Sprintf("http://%s:%d/health", flags.Koanf.String(flags.MgmtHostFlag), - flags.Koanf.Int(flags.MgmtPortFlag)), - Status: health.StatusUnknown, - }, - { - Name: "southbound", - URL: fmt.Sprintf("http://%s:%d/health", flags.Koanf.String(flags.ClientHostFlag), - flags.Koanf.Int(flags.ClientPortFlag)), - Status: health.StatusUnknown, - }, - { - Name: "northbound_tls", - URL: fmt.Sprintf("https://%s:%d/health", flags.Koanf.String(flags.MgmtTLSHostFlag), - flags.Koanf.Int(flags.MgmtTLSPortFlag)), - Status: health.StatusUnknown, - }, - { - Name: "southbound_tls", - URL: fmt.Sprintf("https://%s:%d/health", flags.Koanf.String(flags.ClientTLSHostFlag), - flags.Koanf.Int(flags.ClientTLSPortFlag)), - Status: health.StatusUnknown, - }, - } + swagger := errutil.Must(api.GetSwagger()) + basePath := errutil.Must(swagger.Servers.BasePath()) - client := http.Client{ - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{ - InsecureSkipVerify: true, + allEndpoints := []Endpoint{ + { + Name: "northbound", + Server: fmt.Sprintf("http://%s:%d%s", b.MgmtHost, b.MgmtPort, basePath), + Response: &api.GetHealthResponse{Body: []byte("{}")}, }, - TLSHandshakeTimeout: time.Second * 10, - }, - Timeout: time.Second * 10, - } - - for i := range allEndpoints { - updateStatus(&allEndpoints[i], &client) - } - - filter, rawOutput := flags.Koanf.String(flags.FilterFlag), - flags.Koanf.Bool(flags.RawFlag) - - if tty && filter == "" && !rawOutput { - prettyReport(cmd.OutOrStderr(), useColor, allEndpoints) - } else { - baseCmd := flags.NewBaseCmd() - _ = baseCmd.DumpResponse(cmd.OutOrStdout(), allEndpoints) - } - }, -} - -type simpleHTTPClient interface { - Get(url string) (resp *http.Response, err error) -} - -func updateStatus(ep *endpoint, client simpleHTTPClient) { - resp, err := client.Get(ep.URL) - if err != nil { - ep.Status = health.StatusDown - return - } - - defer resp.Body.Close() + { + Name: "southbound", + Server: fmt.Sprintf("http://%s:%d%s", b.Host, b.Port, basePath), + Response: &api.GetHealthResponse{Body: []byte("{}")}, + }, + { + Name: "northbound_tls", + Server: fmt.Sprintf("https://%s:%d%s", b.MgmtTLSHost, b.MgmtTLSPort, basePath), + Response: &api.GetHealthResponse{Body: []byte("{}")}, + }, + { + Name: "southbound_tls", + Server: fmt.Sprintf("https://%s:%d%s", b.TLSHost, b.TLSPort, basePath), + Response: &api.GetHealthResponse{Body: []byte("{}")}, + }, + } - body, err := io.ReadAll(resp.Body) - if err != nil { - ep.Status = health.StatusUnknown - return - } + httpClient, err := b.CreateHTTPClient() + if err != nil { + return fault.Wrap(err) + } - var result health.CheckerResult - err = json.Unmarshal(body, &result) - if err != nil { - ep.Status = health.StatusDown - return + var g sync.WaitGroup + for i, endpoint := range allEndpoints { + g.Add(1) + go func() { + defer g.Done() + client := errutil.Must(api.NewClientWithResponses(endpoint.Server, api.WithHTTPClient(httpClient))) + resp, err := client.GetHealthWithResponse(cmd.Context()) + if err != nil { + log.Warn().Err(err).Msg("Error while checking health") + } else { + allEndpoints[i].Response = resp + } + }() + } + g.Wait() + prettyReport(cmd.OutOrStdout(), useColor, allEndpoints) + return nil + }, } - ep.Status = health.StatusUp + f := cmd.Flags() + f.String(flags.ColorFlag, colorAuto, fmt.Sprintf("possible values: %s, %s, %s", colorNever, colorAlways, colorAuto)) + return cmd } -func prettyReport(w io.Writer, useColor bool, allEndpoints []endpoint) { +func prettyReport(w io.Writer, useColor bool, allEndpoints []Endpoint) { buf := bufio.NewWriter(w) + defer buf.Flush() _, _ = buf.WriteString("Health report:\n\n") for _, ep := range allEndpoints { - f := fmt.Sprint - if useColor { - switch ep.Status { - case health.StatusUp: - f = color.FgGreen.Render - - case health.StatusDown: - f = color.FgRed.Render + status := api.Down + if ep.Response.JSON200 != nil { + status = ep.Response.JSON200.Status + } else if ep.Response.JSON503 != nil { + status = ep.Response.JSON503.Status + } + formatter := fmt.Sprint + if useColor { + switch status { + case api.Up: + formatter = color.FgGreen.Render + case api.Down: + formatter = color.FgRed.Render default: - f = color.FgYellow.Render + formatter = color.FgYellow.Render } } - fmt.Fprintf(buf, "%s\t%s\t(%s)\n", ep.Name, f(ep.Status), ep.URL) + fmt.Fprintf(buf, "%s\t%s\t(%s)\n", ep.Name, formatter(status), ep.Server) } - buf.Flush() } diff --git a/cmd/wfxctl/cmd/health/health_test.go b/cmd/wfxctl/cmd/health/health_test.go index 2666bf71..64d1a0f9 100644 --- a/cmd/wfxctl/cmd/health/health_test.go +++ b/cmd/wfxctl/cmd/health/health_test.go @@ -1,32 +1,69 @@ package health +/* + * SPDX-FileCopyrightText: 2024 Siemens AG + * + * SPDX-License-Identifier: Apache-2.0 + * + * Author: Michael Adler + */ + import ( "bytes" "encoding/json" "net/http" "net/http/httptest" + "net/url" "testing" - "github.com/alexliesenfeld/health" - "github.com/siemens/wfx/cmd/wfxctl/flags" + "github.com/siemens/wfx/generated/api" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ +func TestNewCommand(t *testing.T) { + cmd := NewCommand() + err := cmd.Execute() + require.NoError(t, err) +} + +func TestNewCommand_Up(t *testing.T) { + var actualPath string + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + actualPath = r.URL.Path + + w.Header().Add("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + response := api.GetHealth200JSONResponse{ + Body: api.CheckerResult{ + Status: api.Up, + }, + } + _ = json.NewEncoder(w).Encode(response) + })) + defer ts.Close() -func TestCommand_Color(t *testing.T) { - for _, c := range []string{colorAlways, colorAuto, colorNever, "foo"} { - _ = flags.Koanf.Set(colorFlag, c) - err := Command.Execute() + u, _ := url.Parse(ts.URL) + t.Setenv("WFX_CLIENT_HOST", u.Hostname()) + t.Setenv("WFX_CLIENT_PORT", u.Port()) + + cmd := NewCommand() + err := cmd.Execute() + require.NoError(t, err) + assert.Equal(t, "/api/wfx/v1/health", actualPath) +} + +func TestNewCommand_ColorModes(t *testing.T) { + for _, mode := range []string{colorAlways, colorAuto, colorNever} { + cmd := NewCommand() + cmd.SetArgs([]string{"--color", mode}) + err := cmd.Execute() require.NoError(t, err) } + cmd := NewCommand() + cmd.SetArgs([]string{"--color", "foo"}) + err := cmd.Execute() + assert.ErrorContains(t, err, "unsupported color mode: foo") } func TestPrettyReport_Empty(t *testing.T) { @@ -39,54 +76,13 @@ func TestPrettyReport_Empty(t *testing.T) { func TestPrettyReport(t *testing.T) { buf := new(bytes.Buffer) - allEndpoints := []endpoint{ - {Name: "Foo", URL: "http://127.0.0.1", Status: health.StatusUp}, - {Name: "Foo", URL: "http://127.0.0.2", Status: health.StatusDown}, - {Name: "Foo", URL: "http://127.0.0.3", Status: health.StatusUnknown}, + allEndpoints := []Endpoint{ + {Name: "Foo", Server: "http://127.0.0.1", Response: &api.GetHealthResponse{JSON200: &api.CheckerResult{Status: api.Up}}}, + {Name: "Foo", Server: "http://127.0.0.2", Response: &api.GetHealthResponse{JSON503: &api.CheckerResult{Status: api.Down}}}, + {Name: "Foo", Server: "http://127.0.0.3", Response: &api.GetHealthResponse{JSON503: &api.CheckerResult{Status: api.Unknown}}}, } prettyReport(buf, false, allEndpoints) prettyReport(buf, true, allEndpoints) assert.NotEmpty(t, buf) } - -func TestUpdateStatus_Down(t *testing.T) { - ep := endpoint{Name: "Foo", URL: "http://127.0.0.1", Status: health.StatusUp} - updateStatus(&ep, &http.Client{}) - assert.Equal(t, health.StatusDown, ep.Status) -} - -type mockHTTPClient struct { - Status health.AvailabilityStatus - InvalidJSON bool -} - -func (m mockHTTPClient) Get(string) (resp *http.Response, err error) { - result := health.CheckerResult{ - Status: m.Status, - } - body, _ := json.Marshal(result) - - fakeResp := httptest.NewRecorder() - fakeResp.WriteHeader(http.StatusOK) - fakeResp.Header().Set("Content-Type", "application/json") - _, _ = fakeResp.Write(body) - if m.InvalidJSON { - _, _ = fakeResp.Write([]byte("invalid!!!")) - } - return fakeResp.Result(), nil -} - -func TestUpdateStatus_Up(t *testing.T) { - ep := endpoint{Name: "Foo", URL: "http://127.0.0.1", Status: health.StatusUnknown} - mock := mockHTTPClient{Status: health.StatusUp} - updateStatus(&ep, mock) - assert.Equal(t, health.StatusUp, ep.Status) -} - -func TestUpdateStatus_DownInvalidJSON(t *testing.T) { - ep := endpoint{Name: "Foo", URL: "http://127.0.0.1", Status: health.StatusUnknown} - mock := mockHTTPClient{Status: health.StatusUp, InvalidJSON: true} - updateStatus(&ep, mock) - assert.Equal(t, health.StatusDown, ep.Status) -} diff --git a/cmd/wfxctl/cmd/job/addtags/add_tags.go b/cmd/wfxctl/cmd/job/addtags/add_tags.go index 17ebba08..22aaafba 100644 --- a/cmd/wfxctl/cmd/job/addtags/add_tags.go +++ b/cmd/wfxctl/cmd/job/addtags/add_tags.go @@ -9,43 +9,33 @@ package addtags */ import ( - "fmt" - - "github.com/rs/zerolog/log" + "github.com/Southclaws/fault" "github.com/spf13/cobra" "github.com/siemens/wfx/cmd/wfxctl/errutil" "github.com/siemens/wfx/cmd/wfxctl/flags" - "github.com/siemens/wfx/generated/client/jobs" -) - -const ( - idFlag = "id" + "github.com/siemens/wfx/generated/api" ) -func init() { - f := Command.Flags() - f.String(idFlag, "", "job id") -} - -var Command = &cobra.Command{ - Use: "add-tags", - Short: "Add tags to a job", - Example: "wfxctl add-tags --id=1 tag1 tag2", - TraverseChildren: true, - Run: func(cmd *cobra.Command, args []string) { - if len(args) == 0 { - log.Fatal().Msg("No tags were provided") - } - - baseCmd := flags.NewBaseCmd() - client := errutil.Must(baseCmd.CreateHTTPClient()) - params := jobs.NewPostJobsIDTagsParams(). - WithHTTPClient(client). - WithID(flags.Koanf.String(idFlag)). - WithTags(args) - - resp := errutil.Must(baseCmd.CreateMgmtClient().Jobs.PostJobsIDTags(params)) - fmt.Fprintln(cmd.OutOrStdout(), resp.Payload) - }, +func NewCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "add-tags", + Short: "Add tags to a job", + Example: "wfxctl job add-tags --id=8ea1e9d7-28e6-4f1f-b444-a8d2d1ad7618 tag1 tag2", + TraverseChildren: true, + RunE: func(cmd *cobra.Command, args []string) error { + baseCmd := flags.NewBaseCmd(cmd.Flags()) + tags := args + + client := errutil.Must(baseCmd.CreateMgmtClient()) + resp, err := client.PostJobsIdTags(cmd.Context(), baseCmd.ID, nil, api.PostJobsIdTagsJSONRequestBody(tags)) + if err != nil { + return fault.Wrap(err) + } + return fault.Wrap(baseCmd.ProcessResponse(resp, cmd.OutOrStdout())) + }, + } + f := cmd.Flags() + f.String(flags.IDFlag, "", "job id") + return cmd } diff --git a/cmd/wfxctl/cmd/job/addtags/add_tags_test.go b/cmd/wfxctl/cmd/job/addtags/add_tags_test.go index 8aad0a96..5ab70643 100644 --- a/cmd/wfxctl/cmd/job/addtags/add_tags_test.go +++ b/cmd/wfxctl/cmd/job/addtags/add_tags_test.go @@ -9,15 +9,16 @@ package addtags */ import ( + "fmt" "io" "net/http" "net/http/httptest" "net/url" - "strconv" "testing" "github.com/siemens/wfx/cmd/wfxctl/flags" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAddTags(t *testing.T) { @@ -35,15 +36,17 @@ func TestAddTags(t *testing.T) { defer ts.Close() u, _ := url.Parse(ts.URL) - _ = flags.Koanf.Set(flags.MgmtHostFlag, u.Hostname()) - port, _ := strconv.Atoi(u.Port()) - _ = flags.Koanf.Set(flags.MgmtPortFlag, port) + t.Setenv("WFX_MGMT_HOST", u.Hostname()) + t.Setenv("WFX_MGMT_PORT", u.Port()) - _ = flags.Koanf.Set(idFlag, "1") - Command.SetArgs([]string{"foo", "bar"}) + cmd := NewCommand() + cmd.SetArgs([]string{ + fmt.Sprintf("--%s=%s", flags.IDFlag, "1"), + "foo", "bar", + }) - err := Command.Execute() - assert.NoError(t, err) + err := cmd.Execute() + require.NoError(t, err) assert.Equal(t, "/api/wfx/v1/jobs/1/tags", actualPath) assert.JSONEq(t, `["foo", "bar"]`, string(body)) diff --git a/cmd/wfxctl/cmd/job/create/create.go b/cmd/wfxctl/cmd/job/create/create.go index 901b9362..457b4451 100644 --- a/cmd/wfxctl/cmd/job/create/create.go +++ b/cmd/wfxctl/cmd/job/create/create.go @@ -13,100 +13,79 @@ import ( "io" "os" - "github.com/go-openapi/strfmt" + "github.com/Southclaws/fault" + "github.com/pkg/errors" "github.com/rs/zerolog/log" "github.com/spf13/cobra" "github.com/siemens/wfx/cmd/wfxctl/errutil" "github.com/siemens/wfx/cmd/wfxctl/flags" - "github.com/siemens/wfx/generated/client/jobs" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" ) -const ( - clientIDFlag = ("client-id") - workflowFlag = ("workflow") - tagFlag = ("tag") -) - -func init() { - f := Command.Flags() - f.String(clientIDFlag, "", "clientID for the job") - f.String(workflowFlag, "", "workflow for the job") - f.StringArray(tagFlag, []string{}, "Tags to apply to the job") -} - -var Command = &cobra.Command{ - Use: "create", - Short: "Create a new job", - Long: "Create a new job. You should provide the job definition (JSON) via stdin.", - Example: ` +func NewCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "create", + Short: "Create a new job", + Long: "Create a new job. You should provide the job definition (JSON) via stdin.", + Example: ` echo '{ "title": "Task 1" }' | wfxctl job create --client-id=my_client --workflow=wfx.workflow.kanban - `, - TraverseChildren: true, - Run: func(cmd *cobra.Command, args []string) { - clientID := flags.Koanf.String(clientIDFlag) - workflow := flags.Koanf.String(workflowFlag) - tags := flags.Koanf.Strings(tagFlag) - log.Debug(). - Str("clientID", clientID). - Str("workflow", workflow). - Strs("tags", tags). - Msg("Creating new job") + TraverseChildren: true, + RunE: func(cmd *cobra.Command, args []string) error { + baseCmd := flags.NewBaseCmd(cmd.Flags()) + clientID := baseCmd.ClientID + workflow := baseCmd.Workflow + tags := baseCmd.Tags + log.Debug(). + Str("clientID", clientID). + Str("workflow", workflow). + Strs("tags", tags). + Msg("Creating new job") - baseCmd := flags.NewBaseCmd() - client := errutil.Must(baseCmd.CreateHTTPClient()) - params := jobs.NewPostJobsParams(). - WithHTTPClient(client). - WithJob(&model.JobRequest{ + request := api.PostJobsJSONRequestBody{ ClientID: clientID, Workflow: workflow, Tags: tags, - Definition: map[string]any{}, - }) + Definition: make(map[string]any), + } - n := len(args) - switch n { - case 0: - log.Warn().Msg("No job definition supplied!") - case 1: - var b []byte - var err error - if args[0] == "-" { - // stdin is a pipe, so we shall read from it and attach it to the Data field - log.Debug().Msg("Reading job definition from stdin...") - b, err = io.ReadAll(cmd.InOrStdin()) - } else { - b, err = os.ReadFile(args[0]) + n := len(args) + switch n { + case 0: + log.Warn().Msg("No job definition supplied!") + case 1: + var b []byte + var err error + if args[0] == "-" { + // stdin is a pipe, so we shall read from it and attach it to the Data field + log.Debug().Msg("Reading job definition from stdin...") + b, err = io.ReadAll(cmd.InOrStdin()) + } else { + b, err = os.ReadFile(args[0]) + } + if err != nil { + return fault.Wrap(err) + } + if err := json.Unmarshal(b, &request.Definition); err != nil { + return fault.Wrap(err) + } + log.Debug().RawJSON("definition", b).Msg("Parsed job definition") + default: + return errors.New("Too many arguments") } + + client := errutil.Must(baseCmd.CreateMgmtClient()) + resp, err := client.PostJobs(cmd.Context(), nil, request) if err != nil { - log.Fatal().Err(err).Msg("Failed to read from stdin") - } - if err := json.Unmarshal(b, ¶ms.Job.Definition); err != nil { - log.Fatal().Err(err).Msg("Failed to unmarshal JSON") + return fault.Wrap(err) } - log.Debug().RawJSON("definition", b).Msg("Parsed job definition") - default: - log.Fatal().Int("n", n).Msg("Too many arguments") - } - - if err := params.Job.Validate(strfmt.Default); err != nil { - log.Fatal().Msg(err.Error()) - } - - resp, err := baseCmd.CreateMgmtClient().Jobs.PostJobs(params) - if err != nil { - errutil.ProcessErrorResponse(cmd.OutOrStderr(), err) - log.Fatal().Msg("Failed to create job") - } - job := resp.GetPayload() - var state string - if job.Status != nil { - state = job.Status.State - } - log.Info().Str("id", job.ID).Str("state", state).Msg("Created new job") - if err := baseCmd.DumpResponse(cmd.OutOrStdout(), resp.GetPayload()); err != nil { - log.Fatal().Err(err).Msg("Failed to print response") - } - }, + return fault.Wrap(baseCmd.ProcessResponse(resp, cmd.OutOrStdout())) + }, + } + f := cmd.Flags() + f.String(flags.ClientIDFlag, "", "clientID for the job") + f.String(flags.WorkflowFlag, "", "workflow for the job") + f.StringArray(flags.TagFlag, []string{}, "Tags to apply to the job") + return cmd } diff --git a/cmd/wfxctl/cmd/job/create/create_test.go b/cmd/wfxctl/cmd/job/create/create_test.go index 649d05fc..9813cafd 100644 --- a/cmd/wfxctl/cmd/job/create/create_test.go +++ b/cmd/wfxctl/cmd/job/create/create_test.go @@ -10,21 +10,23 @@ package create import ( "bytes" + "encoding/json" "fmt" "io" "net/http" "net/http/httptest" "net/url" - "strconv" "testing" "github.com/siemens/wfx/cmd/wfxctl/flags" + "github.com/siemens/wfx/generated/api" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCreateJob(t *testing.T) { const data = `{"artifacts":[{"name":"example.swu","uri":"http://localhost:8080/download/example.swu"}]}` - expected := fmt.Sprintf(`{"definition":%s,"clientId":"my_client","workflow":"wfx.workflow.dau.direct","tags":[]}`, data) + expected := fmt.Sprintf(`{"definition":%s,"clientId":"my_client","workflow":"wfx.workflow.dau.direct"}`, data) var body []byte @@ -33,25 +35,30 @@ func TestCreateJob(t *testing.T) { w.Header().Add("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) - _, _ = w.Write([]byte("{}")) + + id := "1" + clientID := "my_client" + job := api.Job{ + ID: id, + ClientID: clientID, + } + _ = json.NewEncoder(w).Encode(job) })) defer ts.Close() u, _ := url.Parse(ts.URL) - _ = flags.Koanf.Set(flags.MgmtHostFlag, u.Hostname()) - port, _ := strconv.Atoi(u.Port()) - _ = flags.Koanf.Set(flags.MgmtPortFlag, port) - - _ = flags.Koanf.Set(clientIDFlag, "my_client") - _ = flags.Koanf.Set(workflowFlag, "wfx.workflow.dau.direct") + t.Setenv("WFX_MGMT_HOST", u.Hostname()) + t.Setenv("WFX_MGMT_PORT", u.Port()) var stdin bytes.Buffer stdin.Write([]byte(data)) - Command.SetIn(&stdin) - Command.SetArgs([]string{"-"}) - err := Command.Execute() - assert.NoError(t, err) + cmd := NewCommand() + cmd.SetArgs([]string{"--" + flags.ClientIDFlag, "my_client", "--" + flags.WorkflowFlag, "wfx.workflow.dau.direct", "-"}) + cmd.SetIn(&stdin) + + err := cmd.Execute() + require.NoError(t, err) assert.JSONEq(t, expected, string(body)) } diff --git a/cmd/wfxctl/cmd/job/delete/delete.go b/cmd/wfxctl/cmd/job/delete/delete.go index 71c30c79..971aae13 100644 --- a/cmd/wfxctl/cmd/job/delete/delete.go +++ b/cmd/wfxctl/cmd/job/delete/delete.go @@ -9,39 +9,31 @@ package delete */ import ( - "github.com/rs/zerolog/log" + "github.com/Southclaws/fault" "github.com/spf13/cobra" "github.com/siemens/wfx/cmd/wfxctl/errutil" "github.com/siemens/wfx/cmd/wfxctl/flags" - "github.com/siemens/wfx/generated/client/jobs" ) -const ( - idFlag = "id" -) - -func init() { - f := Command.Flags() - f.String(idFlag, "", "id of the job which shall be deleted") -} - -var Command = &cobra.Command{ - Use: "delete", - Short: "Delete an existing job", - Long: `Delete an existing job`, - TraverseChildren: true, - Run: func(cmd *cobra.Command, _ []string) { - baseCmd := flags.NewBaseCmd() - client := errutil.Must(baseCmd.CreateHTTPClient()) - params := jobs.NewDeleteJobsIDParams(). - WithHTTPClient(client). - WithID(flags.Koanf.String(idFlag)) - - // no content - if _, err := baseCmd.CreateMgmtClient().Jobs.DeleteJobsID(params); err != nil { - errutil.ProcessErrorResponse(cmd.OutOrStderr(), err) - log.Fatal().Msg("Failed to delete job") - } - }, +func NewCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "delete", + Short: "Delete an existing job", + Long: `Delete an existing job`, + Example: `wfxctl job delete --id=8ea1e9d7-28e6-4f1f-b444-a8d2d1ad7618`, + TraverseChildren: true, + RunE: func(cmd *cobra.Command, _ []string) error { + baseCmd := flags.NewBaseCmd(cmd.Flags()) + client := errutil.Must(baseCmd.CreateMgmtClient()) + resp, err := client.DeleteJobsId(cmd.Context(), baseCmd.ID) + if err != nil { + return fault.Wrap(err) + } + return fault.Wrap(baseCmd.ProcessResponse(resp, cmd.OutOrStdout())) + }, + } + f := cmd.Flags() + f.String(flags.IDFlag, "", "job id") + return cmd } diff --git a/cmd/wfxctl/cmd/job/delete/delete_test.go b/cmd/wfxctl/cmd/job/delete/delete_test.go index 6db19a68..577d05fd 100644 --- a/cmd/wfxctl/cmd/job/delete/delete_test.go +++ b/cmd/wfxctl/cmd/job/delete/delete_test.go @@ -12,11 +12,10 @@ import ( "net/http" "net/http/httptest" "net/url" - "strconv" "testing" - "github.com/siemens/wfx/cmd/wfxctl/flags" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCreateJob(t *testing.T) { @@ -31,13 +30,14 @@ func TestCreateJob(t *testing.T) { defer ts.Close() u, _ := url.Parse(ts.URL) - _ = flags.Koanf.Set(flags.MgmtHostFlag, u.Hostname()) - port, _ := strconv.Atoi(u.Port()) - _ = flags.Koanf.Set(flags.MgmtPortFlag, port) - _ = flags.Koanf.Set(idFlag, "1") + t.Setenv("WFX_MGMT_HOST", u.Hostname()) + t.Setenv("WFX_MGMT_PORT", u.Port()) - err := Command.Execute() - assert.NoError(t, err) + cmd := NewCommand() + cmd.SetArgs([]string{"--id=1"}) + + err := cmd.Execute() + require.NoError(t, err) const expectedPath = "/api/wfx/v1/jobs/1" assert.Equal(t, expectedPath, actualPath) diff --git a/cmd/wfxctl/cmd/job/deltags/del_tags.go b/cmd/wfxctl/cmd/job/deltags/del_tags.go index 531b3cd9..cb8caee4 100644 --- a/cmd/wfxctl/cmd/job/deltags/del_tags.go +++ b/cmd/wfxctl/cmd/job/deltags/del_tags.go @@ -9,47 +9,38 @@ package deltags */ import ( - "fmt" + "errors" - "github.com/rs/zerolog/log" + "github.com/Southclaws/fault" "github.com/spf13/cobra" "github.com/siemens/wfx/cmd/wfxctl/errutil" "github.com/siemens/wfx/cmd/wfxctl/flags" - "github.com/siemens/wfx/generated/client/jobs" + "github.com/siemens/wfx/generated/api" ) -const ( - idFlag = "id" -) - -func init() { - f := Command.Flags() - f.String(idFlag, "", "job id") -} - -var Command = &cobra.Command{ - Use: "del-tags", - Short: "Delete tags from a job", - Example: "wfxctl del-tags --id=1 tag1 tag2", - TraverseChildren: true, - Run: func(cmd *cobra.Command, args []string) { - if len(args) == 0 { - log.Fatal().Msg("No tags were provided") - } - - baseCmd := flags.NewBaseCmd() - client := errutil.Must(baseCmd.CreateHTTPClient()) - params := jobs.NewDeleteJobsIDTagsParams(). - WithHTTPClient(client). - WithID(flags.Koanf.String(idFlag)). - WithTags(args) - - resp, err := baseCmd.CreateMgmtClient().Jobs.DeleteJobsIDTags(params) - if err != nil { - errutil.ProcessErrorResponse(cmd.OutOrStderr(), err) - log.Fatal().Msg("Failed to delete tags") - } - fmt.Fprintln(cmd.OutOrStdout(), resp.Payload) - }, +func NewCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "del-tags", + Short: "Delete tags from a job", + Example: "wfxctl job del-tags --id=8ea1e9d7-28e6-4f1f-b444-a8d2d1ad7618 tag1 tag2", + TraverseChildren: true, + RunE: func(cmd *cobra.Command, args []string) error { + if len(args) == 0 { + return errors.New("no tags provided") + } + baseCmd := flags.NewBaseCmd(cmd.Flags()) + tags := args + + client := errutil.Must(baseCmd.CreateMgmtClient()) + resp, err := client.DeleteJobsIdTags(cmd.Context(), baseCmd.ID, nil, api.DeleteJobsIdTagsJSONRequestBody(tags)) + if err != nil { + return fault.Wrap(err) + } + return fault.Wrap(baseCmd.ProcessResponse(resp, cmd.OutOrStdout())) + }, + } + f := cmd.Flags() + f.String(flags.IDFlag, "", "job id") + return cmd } diff --git a/cmd/wfxctl/cmd/job/deltags/del_tags_test.go b/cmd/wfxctl/cmd/job/deltags/del_tags_test.go index 1a65966f..1dac1db6 100644 --- a/cmd/wfxctl/cmd/job/deltags/del_tags_test.go +++ b/cmd/wfxctl/cmd/job/deltags/del_tags_test.go @@ -13,11 +13,11 @@ import ( "net/http" "net/http/httptest" "net/url" - "strconv" "testing" "github.com/siemens/wfx/cmd/wfxctl/flags" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestDelTags(t *testing.T) { @@ -35,16 +35,13 @@ func TestDelTags(t *testing.T) { defer ts.Close() u, _ := url.Parse(ts.URL) - _ = flags.Koanf.Set(flags.MgmtHostFlag, u.Hostname()) - port, _ := strconv.Atoi(u.Port()) - _ = flags.Koanf.Set(flags.MgmtPortFlag, port) - - _ = flags.Koanf.Set(idFlag, "1") - Command.SetArgs([]string{"bar"}) - - err := Command.Execute() - assert.NoError(t, err) + t.Setenv("WFX_MGMT_HOST", u.Hostname()) + t.Setenv("WFX_MGMT_PORT", u.Port()) + cmd := NewCommand() + cmd.SetArgs([]string{"--" + flags.IDFlag, "1", "bar"}) + err := cmd.Execute() + require.NoError(t, err) assert.Equal(t, "/api/wfx/v1/jobs/1/tags", actualPath) assert.JSONEq(t, `["bar"]`, string(body)) } diff --git a/cmd/wfxctl/cmd/job/events/events.go b/cmd/wfxctl/cmd/job/events/events.go index eb8b3f49..b549c969 100644 --- a/cmd/wfxctl/cmd/job/events/events.go +++ b/cmd/wfxctl/cmd/job/events/events.go @@ -14,30 +14,17 @@ import ( "fmt" "io" "net/http" - "os" "strings" "time" "github.com/Southclaws/fault" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/client" - "github.com/go-openapi/strfmt" "github.com/rs/zerolog/log" "github.com/spf13/cobra" "github.com/tmaxmax/go-sse" "github.com/siemens/wfx/cmd/wfxctl/errutil" "github.com/siemens/wfx/cmd/wfxctl/flags" - generatedClient "github.com/siemens/wfx/generated/client" - "github.com/siemens/wfx/generated/client/jobs" - "github.com/siemens/wfx/generated/model" -) - -const ( - jobIDFlag = "job-id" - clientIDFlag = "client-id" - workflowNameFlag = "workflow-name" - tagFlag = "tag" + "github.com/siemens/wfx/generated/api" ) var validator = func(out io.Writer) sse.ResponseValidator { @@ -53,12 +40,12 @@ var validator = func(out io.Writer) sse.ResponseValidator { return fault.Wrap(err) } - errResp := new(model.ErrorResponse) + errResp := new(api.ErrorResponse) if err := json.Unmarshal(b, errResp); err != nil { return fault.Wrap(err) } - if len(errResp.Errors) > 0 { - for _, msg := range errResp.Errors { + if errResp.Errors != nil { + for _, msg := range *errResp.Errors { fmt.Fprintf(out, "ERROR: %s (code=%s, logref=%s)\n", msg.Message, msg.Code, msg.Logref) } } @@ -67,45 +54,17 @@ var validator = func(out io.Writer) sse.ResponseValidator { } } -func init() { - f := Command.Flags() - f.StringSlice(jobIDFlag, nil, "job id filter") - f.StringSlice(clientIDFlag, nil, "client id filter") - f.StringSlice(workflowNameFlag, nil, "workflow name filter") - f.StringSlice(tagFlag, nil, "tag filter") -} - type SSETransport struct { - baseCmd *flags.BaseCmd - out io.Writer + sseClient *sse.Client + out io.Writer } // Submit implements the runtime.ClientTransport interface. -func (t SSETransport) Submit(op *runtime.ClientOperation) (interface{}, error) { - cfg := t.baseCmd.CreateTransportConfig() - rt := client.New(cfg.Host, generatedClient.DefaultBasePath, cfg.Schemes) - req := errutil.Must(rt.CreateHttpRequest(op)) - - httpClient := errutil.Must(t.baseCmd.CreateHTTPClient()) - httpClient.Timeout = 0 - - client := sse.Client{ - HTTPClient: httpClient, - Backoff: sse.Backoff{ - InitialInterval: 5 * time.Second, - Multiplier: 1.5, - Jitter: 0.5, - MaxInterval: 60 * time.Second, - MaxElapsedTime: 15 * time.Minute, - MaxRetries: -1, - }, - ResponseValidator: validator(t.out), - } - - conn := client.NewConnection(req) +func (t SSETransport) Do(req *http.Request) (*http.Response, error) { + conn := t.sseClient.NewConnection(req) unsubscribe := conn.SubscribeMessages(func(event sse.Event) { - _, _ = os.Stdout.WriteString(event.Data) - os.Stdout.Write([]byte("\n")) + _, _ = t.out.Write([]byte(event.Data)) + _, _ = t.out.Write([]byte("\n")) }) defer unsubscribe() @@ -114,42 +73,74 @@ func (t SSETransport) Submit(op *runtime.ClientOperation) (interface{}, error) { log.Error().Err(err).Msg("Failed to connect to remote server") return nil, fault.Wrap(err) } - - return jobs.NewGetJobsEventsOK(), nil + return &http.Response{StatusCode: http.StatusOK}, nil } -var Command = &cobra.Command{ - Use: "events", - Short: "Subscribe to job events", - Example: ` +func NewCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "events", + Short: "Subscribe to job events", + Example: ` wfxctl job events --job-id=1 --job-id=2 --client-id=foo `, - TraverseChildren: true, - Run: func(cmd *cobra.Command, _ []string) { - params := jobs.NewGetJobsEventsParams() + TraverseChildren: true, + RunE: func(cmd *cobra.Command, _ []string) error { + baseCmd := flags.NewBaseCmd(cmd.Flags()) + httpClient := errutil.Must(baseCmd.CreateHTTPClient()) + httpClient.Timeout = 0 + sseClient := &sse.Client{ + HTTPClient: httpClient, + Backoff: sse.Backoff{ + InitialInterval: 5 * time.Second, + Multiplier: 1.5, + Jitter: 0.5, + MaxInterval: 60 * time.Second, + MaxElapsedTime: 15 * time.Minute, + MaxRetries: -1, + }, + ResponseValidator: validator(cmd.ErrOrStderr()), + } + transport := SSETransport{sseClient: sseClient, out: cmd.OutOrStdout()} + + var server string + swagger := errutil.Must(api.GetSwagger()) + basePath := errutil.Must(swagger.Servers.BasePath()) + if baseCmd.EnableTLS { + server = fmt.Sprintf("https://%s:%d%s", baseCmd.TLSHost, baseCmd.TLSPort, basePath) + } else { + server = fmt.Sprintf("http://%s:%d%s", baseCmd.Host, baseCmd.Port, basePath) + } - if jobIDs := flags.Koanf.Strings(jobIDFlag); len(jobIDs) > 0 { - s := strings.Join(jobIDs, ",") - params.WithJobIds(&s) - } - if clientIDs := flags.Koanf.Strings(clientIDFlag); len(clientIDs) > 0 { - s := strings.Join(clientIDs, ",") - params.WithClientIds(&s) - } - if workflowNames := flags.Koanf.Strings(workflowNameFlag); len(workflowNames) > 0 { - s := strings.Join(workflowNames, ",") - params.WithWorkflows(&s) - } - if tags := flags.Koanf.Strings(tagFlag); len(tags) > 0 { - s := strings.Join(tags, ",") - params.WithTags(&s) - } + client, err := api.NewClient(server, api.WithHTTPClient(transport)) + if err != nil { + return fault.Wrap(err) + } - baseCmd := flags.NewBaseCmd() - transport := SSETransport{baseCmd: &baseCmd, out: cmd.OutOrStderr()} - executor := generatedClient.New(transport, strfmt.Default) - if _, err := executor.Jobs.GetJobsEvents(params); err != nil { - log.Fatal().Err(err).Msg("Failed to subscribe to job events") - } - }, + params := new(api.GetJobsEventsParams) + if jobIDs := baseCmd.JobIDs; len(jobIDs) > 0 { + s := strings.Join(jobIDs, ",") + params.JobIds = &s + } + if clientIDs := baseCmd.ClientIDs; len(clientIDs) > 0 { + s := strings.Join(clientIDs, ",") + params.ClientIDs = &s + } + if workflowNames := baseCmd.Workflows; len(workflowNames) > 0 { + s := strings.Join(workflowNames, ",") + params.Workflows = &s + } + if tags := baseCmd.Tags; len(tags) > 0 { + s := strings.Join(tags, ",") + params.Tags = &s + } + _, err = client.GetJobsEvents(cmd.Context(), params) + return fault.Wrap(err) + }, + } + f := cmd.Flags() + f.StringSlice(flags.JobIDFlag, nil, "job id filter") + f.StringSlice(flags.ClientIDFlag, nil, "client id filter") + f.StringSlice(flags.WorkflowFlag, nil, "workflow name filter") + f.StringSlice(flags.TagFlag, nil, "tag filter") + return cmd } diff --git a/cmd/wfxctl/cmd/job/events/events_test.go b/cmd/wfxctl/cmd/job/events/events_test.go index 8fd26270..c2faf7d4 100644 --- a/cmd/wfxctl/cmd/job/events/events_test.go +++ b/cmd/wfxctl/cmd/job/events/events_test.go @@ -13,11 +13,11 @@ import ( "net/http" "net/http/httptest" "net/url" - "strconv" "testing" "github.com/siemens/wfx/cmd/wfxctl/flags" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestSubscribeJobStatus(t *testing.T) { @@ -36,15 +36,13 @@ func TestSubscribeJobStatus(t *testing.T) { t.Cleanup(ts.Close) u, _ := url.Parse(ts.URL) - _ = flags.Koanf.Set(flags.ClientHostFlag, u.Hostname()) - port, _ := strconv.Atoi(u.Port()) - _ = flags.Koanf.Set(flags.ClientPortFlag, port) - - _ = flags.Koanf.Set(jobIDFlag, "1") - - err := Command.Execute() - assert.NoError(t, err) + t.Setenv("WFX_CLIENT_HOST", u.Hostname()) + t.Setenv("WFX_CLIENT_PORT", u.Port()) + cmd := NewCommand() + cmd.SetArgs([]string{"--" + flags.JobIDFlag, "1"}) + err := cmd.Execute() + require.NoError(t, err) assert.Equal(t, expectedPath, actualPath) } diff --git a/cmd/wfxctl/cmd/job/get/get.go b/cmd/wfxctl/cmd/job/get/get.go index 67cdb64b..0d2eae1c 100644 --- a/cmd/wfxctl/cmd/job/get/get.go +++ b/cmd/wfxctl/cmd/job/get/get.go @@ -9,53 +9,43 @@ package get */ import ( - "github.com/rs/zerolog/log" + "errors" + + "github.com/Southclaws/fault" "github.com/spf13/cobra" "github.com/siemens/wfx/cmd/wfxctl/errutil" "github.com/siemens/wfx/cmd/wfxctl/flags" - "github.com/siemens/wfx/generated/client/jobs" -) - -const ( - idFlag = "id" - historyFlag = "history" + "github.com/siemens/wfx/generated/api" ) -func init() { - f := Command.Flags() - f.String(idFlag, "", "id of the job to be fetched") - f.Bool(historyFlag, false, "whether to fetch the job history") -} - -var Command = &cobra.Command{ - Use: "get", - Short: "Get an existing job", - Long: `Get an existing job.`, - Example: ` -wfxctl job get --id=1 +func NewCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "get", + Short: "Get an existing job", + Long: `Get an existing job.`, + Example: ` +wfxctl job get --id=8ea1e9d7-28e6-4f1f-b444-a8d2d1ad7618 `, - TraverseChildren: true, - Run: func(cmd *cobra.Command, _ []string) { - baseCmd := flags.NewBaseCmd() - history := flags.Koanf.Bool(historyFlag) - client := errutil.Must(baseCmd.CreateHTTPClient()) - params := jobs.NewGetJobsIDParams(). - WithHTTPClient(client). - WithID(flags.Koanf.String(idFlag)). - WithHistory(&history) - - if params.ID == "" { - log.Fatal().Msg("Job ID missing") - } - - resp, err := baseCmd.CreateClient().Jobs.GetJobsID(params) - if err != nil { - errutil.ProcessErrorResponse(cmd.OutOrStderr(), err) - log.Fatal().Msg("Failed to get job") - } - if err := baseCmd.DumpResponse(cmd.OutOrStdout(), resp.GetPayload()); err != nil { - log.Fatal().Err(err).Msg("Failed to dump response") - } - }, + TraverseChildren: true, + RunE: func(cmd *cobra.Command, _ []string) error { + baseCmd := flags.NewBaseCmd(cmd.Flags()) + id := baseCmd.ID + if id == "" { + return errors.New("id missing") + } + history := baseCmd.History + client := errutil.Must(baseCmd.CreateClient()) + resp, err := client.GetJobsId(cmd.Context(), id, &api.GetJobsIdParams{ParamHistory: &history}) + if err != nil { + return fault.Wrap(err) + } + return fault.Wrap(baseCmd.ProcessResponse(resp, cmd.OutOrStdout())) + }, + } + + f := cmd.Flags() + f.String(flags.IDFlag, "", "id of the job to be fetched") + f.Bool(flags.HistoryFlag, false, "whether to fetch the job history") + return cmd } diff --git a/cmd/wfxctl/cmd/job/get/get_test.go b/cmd/wfxctl/cmd/job/get/get_test.go index 8692ffcb..4da80f55 100644 --- a/cmd/wfxctl/cmd/job/get/get_test.go +++ b/cmd/wfxctl/cmd/job/get/get_test.go @@ -12,7 +12,6 @@ import ( "net/http" "net/http/httptest" "net/url" - "strconv" "testing" "github.com/siemens/wfx/cmd/wfxctl/flags" @@ -33,12 +32,12 @@ func TestGetJob(t *testing.T) { defer ts.Close() u, _ := url.Parse(ts.URL) - _ = flags.Koanf.Set(flags.ClientHostFlag, u.Hostname()) - port, _ := strconv.Atoi(u.Port()) - _ = flags.Koanf.Set(flags.ClientPortFlag, port) + t.Setenv("WFX_CLIENT_HOST", u.Hostname()) + t.Setenv("WFX_CLIENT_PORT", u.Port()) - _ = flags.Koanf.Set(idFlag, "1") - err := Command.Execute() + cmd := NewCommand() + cmd.SetArgs([]string{"--" + flags.IDFlag, "1"}) + err := cmd.Execute() assert.NoError(t, err) assert.Equal(t, expectedPath, actualPath) } diff --git a/cmd/wfxctl/cmd/job/getdefinition/get_definition.go b/cmd/wfxctl/cmd/job/getdefinition/get_definition.go index 072442f4..8a23b170 100644 --- a/cmd/wfxctl/cmd/job/getdefinition/get_definition.go +++ b/cmd/wfxctl/cmd/job/getdefinition/get_definition.go @@ -9,49 +9,40 @@ package getdefinition */ import ( - "github.com/rs/zerolog/log" + "errors" + + "github.com/Southclaws/fault" "github.com/spf13/cobra" "github.com/siemens/wfx/cmd/wfxctl/errutil" "github.com/siemens/wfx/cmd/wfxctl/flags" - "github.com/siemens/wfx/generated/client/jobs" -) - -const ( - idFlag = "id" ) -func init() { - f := Command.Flags() - f.String(idFlag, "", "job id") -} - -var Command = &cobra.Command{ - Use: "get-definition", - Short: "Get definition of an existing job", - Long: "Get definition of an existing job", - Example: ` -wfxctl job get-definition --id=1 +func NewCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "get-definition", + Short: "Get definition of an existing job", + Long: "Get definition of an existing job", + Example: ` +wfxctl job get-definition --id=8ea1e9d7-28e6-4f1f-b444-a8d2d1ad7618 `, - TraverseChildren: true, - Run: func(cmd *cobra.Command, _ []string) { - baseCmd := flags.NewBaseCmd() - client := errutil.Must(baseCmd.CreateHTTPClient()) - params := jobs.NewGetJobsIDDefinitionParams(). - WithHTTPClient(client). - WithID(flags.Koanf.String(idFlag)) - - if params.ID == "" { - log.Fatal().Msg("Job ID missing") - } - - resp, err := baseCmd.CreateClient().Jobs.GetJobsIDDefinition(params) - if err != nil { - errutil.ProcessErrorResponse(cmd.OutOrStderr(), err) - log.Fatal().Msg("Failed to get job definition") - } - if err := baseCmd.DumpResponse(cmd.OutOrStdout(), resp.GetPayload()); err != nil { - log.Fatal().Err(err).Msg("Failed to dump response") - } - }, + TraverseChildren: true, + RunE: func(cmd *cobra.Command, _ []string) error { + baseCmd := flags.NewBaseCmd(cmd.Flags()) + id := baseCmd.ID + if id == "" { + return errors.New("id missing") + } + client := errutil.Must(baseCmd.CreateClient()) + resp, err := client.GetJobsIdDefinition(cmd.Context(), id, nil) + if err != nil { + return fault.Wrap(err) + } + return fault.Wrap(baseCmd.ProcessResponse(resp, cmd.OutOrStdout())) + }, + } + + f := cmd.Flags() + f.String(flags.IDFlag, "", "job id") + return cmd } diff --git a/cmd/wfxctl/cmd/job/getdefinition/get_definition_test.go b/cmd/wfxctl/cmd/job/getdefinition/get_definition_test.go index 670bd224..36c14d02 100644 --- a/cmd/wfxctl/cmd/job/getdefinition/get_definition_test.go +++ b/cmd/wfxctl/cmd/job/getdefinition/get_definition_test.go @@ -12,11 +12,11 @@ import ( "net/http" "net/http/httptest" "net/url" - "strconv" "testing" "github.com/siemens/wfx/cmd/wfxctl/flags" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetJobStatus(t *testing.T) { @@ -33,14 +33,12 @@ func TestGetJobStatus(t *testing.T) { defer ts.Close() u, _ := url.Parse(ts.URL) - _ = flags.Koanf.Set(flags.ClientHostFlag, u.Hostname()) - port, _ := strconv.Atoi(u.Port()) - _ = flags.Koanf.Set(flags.ClientPortFlag, port) - - _ = flags.Koanf.Set(idFlag, "1") - - err := Command.Execute() - assert.NoError(t, err) + t.Setenv("WFX_CLIENT_HOST", u.Hostname()) + t.Setenv("WFX_CLIENT_PORT", u.Port()) + cmd := NewCommand() + cmd.SetArgs([]string{"--" + flags.IDFlag, "1"}) + err := cmd.Execute() + require.NoError(t, err) assert.Equal(t, expectedPath, actualPath) } diff --git a/cmd/wfxctl/cmd/job/getstatus/get_status.go b/cmd/wfxctl/cmd/job/getstatus/get_status.go index c200d096..587e2a3b 100644 --- a/cmd/wfxctl/cmd/job/getstatus/get_status.go +++ b/cmd/wfxctl/cmd/job/getstatus/get_status.go @@ -9,49 +9,39 @@ package getstatus */ import ( - "github.com/rs/zerolog/log" + "errors" + + "github.com/Southclaws/fault" "github.com/spf13/cobra" "github.com/siemens/wfx/cmd/wfxctl/errutil" "github.com/siemens/wfx/cmd/wfxctl/flags" - "github.com/siemens/wfx/generated/client/jobs" -) - -const ( - idFlag = "id" ) -func init() { - f := Command.Flags() - f.String(idFlag, "", "job id") -} - -var Command = &cobra.Command{ - Use: "get-status", - Short: "Get status of an existing job", - Long: "Get status of an existing job", - Example: ` -wfxctl job get-status --id=1 +func NewCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "get-status", + Short: "Get status of an existing job", + Long: "Get status of an existing job", + Example: ` +wfxctl job get-status --id=8ea1e9d7-28e6-4f1f-b444-a8d2d1ad7618 `, - TraverseChildren: true, - Run: func(cmd *cobra.Command, _ []string) { - baseCmd := flags.NewBaseCmd() - client := errutil.Must(baseCmd.CreateHTTPClient()) - params := jobs.NewGetJobsIDStatusParams(). - WithHTTPClient(client). - WithID(flags.Koanf.String(idFlag)) - - if params.ID == "" { - log.Fatal().Msg("Job ID missing") - } - - resp, err := baseCmd.CreateClient().Jobs.GetJobsIDStatus(params) - if err != nil { - errutil.ProcessErrorResponse(cmd.OutOrStderr(), err) - log.Fatal().Msg("Failed to get job status") - } - if err := baseCmd.DumpResponse(cmd.OutOrStdout(), resp.GetPayload()); err != nil { - log.Fatal().Err(err).Msg("Failed to get job status") - } - }, + TraverseChildren: true, + RunE: func(cmd *cobra.Command, _ []string) error { + baseCmd := flags.NewBaseCmd(cmd.Flags()) + id := baseCmd.ID + if id == "" { + return errors.New("id missing") + } + client := errutil.Must(baseCmd.CreateClient()) + resp, err := client.GetJobsIdStatus(cmd.Context(), id, nil) + if err != nil { + return fault.Wrap(err) + } + return fault.Wrap(baseCmd.ProcessResponse(resp, cmd.OutOrStdout())) + }, + } + f := cmd.Flags() + f.String(flags.IDFlag, "", "job id") + return cmd } diff --git a/cmd/wfxctl/cmd/job/getstatus/get_status_test.go b/cmd/wfxctl/cmd/job/getstatus/get_status_test.go index 534008af..9fc194ae 100644 --- a/cmd/wfxctl/cmd/job/getstatus/get_status_test.go +++ b/cmd/wfxctl/cmd/job/getstatus/get_status_test.go @@ -12,11 +12,11 @@ import ( "net/http" "net/http/httptest" "net/url" - "strconv" "testing" "github.com/siemens/wfx/cmd/wfxctl/flags" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetJobStatus(t *testing.T) { @@ -33,14 +33,14 @@ func TestGetJobStatus(t *testing.T) { defer ts.Close() u, _ := url.Parse(ts.URL) - _ = flags.Koanf.Set(flags.ClientHostFlag, u.Hostname()) - port, _ := strconv.Atoi(u.Port()) - _ = flags.Koanf.Set(flags.ClientPortFlag, port) + t.Setenv("WFX_CLIENT_HOST", u.Hostname()) + t.Setenv("WFX_CLIENT_PORT", u.Port()) - _ = flags.Koanf.Set(idFlag, "1") + cmd := NewCommand() + cmd.SetArgs([]string{"--" + flags.IDFlag, "1"}) - err := Command.Execute() - assert.NoError(t, err) + err := cmd.Execute() + require.NoError(t, err) assert.Equal(t, expectedPath, actualPath) } diff --git a/cmd/wfxctl/cmd/job/gettags/get_tags.go b/cmd/wfxctl/cmd/job/gettags/get_tags.go index 1c3440a4..6d49ec7d 100644 --- a/cmd/wfxctl/cmd/job/gettags/get_tags.go +++ b/cmd/wfxctl/cmd/job/gettags/get_tags.go @@ -9,42 +9,31 @@ package gettags */ import ( - "fmt" - - "github.com/rs/zerolog/log" + "github.com/Southclaws/fault" "github.com/spf13/cobra" "github.com/siemens/wfx/cmd/wfxctl/errutil" "github.com/siemens/wfx/cmd/wfxctl/flags" - "github.com/siemens/wfx/generated/client/jobs" -) - -const ( - idFlag = "id" ) -func init() { - f := Command.Flags() - f.String(idFlag, "", "job id") -} - -var Command = &cobra.Command{ - Use: "get-tags", - Short: "Get tags of a job", - Example: "wfxctl get-tags --id=1", - TraverseChildren: true, - Run: func(cmd *cobra.Command, _ []string) { - baseCmd := flags.NewBaseCmd() - client := errutil.Must(baseCmd.CreateHTTPClient()) - params := jobs.NewGetJobsIDTagsParams(). - WithHTTPClient(client). - WithID(flags.Koanf.String(idFlag)) - - resp, err := baseCmd.CreateClient().Jobs.GetJobsIDTags(params) - if err != nil { - errutil.ProcessErrorResponse(cmd.OutOrStderr(), err) - log.Fatal().Msg("Failed to retrieve tags") - } - fmt.Fprintln(cmd.OutOrStdout(), resp.Payload) - }, +func NewCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "get-tags", + Short: "Get tags of a job", + Example: "wfxctl job get-tags --id=8ea1e9d7-28e6-4f1f-b444-a8d2d1ad7618", + TraverseChildren: true, + RunE: func(cmd *cobra.Command, _ []string) error { + baseCmd := flags.NewBaseCmd(cmd.Flags()) + id := baseCmd.ID + client := errutil.Must(baseCmd.CreateClient()) + resp, err := client.GetJobsIdTags(cmd.Context(), id, nil) + if err != nil { + return fault.Wrap(err) + } + return fault.Wrap(baseCmd.ProcessResponse(resp, cmd.OutOrStdout())) + }, + } + f := cmd.Flags() + f.String(flags.IDFlag, "", "job id") + return cmd } diff --git a/cmd/wfxctl/cmd/job/gettags/get_tags_test.go b/cmd/wfxctl/cmd/job/gettags/get_tags_test.go index d7377040..7c0f3d38 100644 --- a/cmd/wfxctl/cmd/job/gettags/get_tags_test.go +++ b/cmd/wfxctl/cmd/job/gettags/get_tags_test.go @@ -12,11 +12,11 @@ import ( "net/http" "net/http/httptest" "net/url" - "strconv" "testing" "github.com/siemens/wfx/cmd/wfxctl/flags" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAddTags(t *testing.T) { @@ -35,15 +35,12 @@ func TestAddTags(t *testing.T) { defer ts.Close() u, _ := url.Parse(ts.URL) - _ = flags.Koanf.Set(flags.ClientHostFlag, u.Hostname()) - port, _ := strconv.Atoi(u.Port()) - _ = flags.Koanf.Set(flags.ClientPortFlag, port) - - _ = flags.Koanf.Set(idFlag, "1") - - err := Command.Execute() - assert.NoError(t, err) - + t.Setenv("WFX_CLIENT_HOST", u.Hostname()) + t.Setenv("WFX_CLIENT_PORT", u.Port()) + cmd := NewCommand() + cmd.SetArgs([]string{"--" + flags.IDFlag, "1"}) + err := cmd.Execute() + require.NoError(t, err) assert.Equal(t, "/api/wfx/v1/jobs/1/tags", actualPath) assert.JSONEq(t, `["foo", "bar"]`, string(body)) } diff --git a/cmd/wfxctl/cmd/job/job.go b/cmd/wfxctl/cmd/job/job.go index 7ce13d0a..4c79c8a6 100644 --- a/cmd/wfxctl/cmd/job/job.go +++ b/cmd/wfxctl/cmd/job/job.go @@ -24,25 +24,25 @@ import ( "github.com/spf13/cobra" ) -var Command = &cobra.Command{ - Use: "job", - Short: "manage jobs", - Long: "subcommand to manage jobs (CRUD)", - TraverseChildren: true, - SilenceUsage: true, -} - -func init() { - Command.AddCommand(create.Command) - Command.AddCommand(delete.Command) - Command.AddCommand(get.Command) - Command.AddCommand(query.Command) - Command.AddCommand(updatestatus.Command) - Command.AddCommand(getstatus.Command) - Command.AddCommand(updatedefinition.Command) - Command.AddCommand(getdefinition.Command) - Command.AddCommand(addtags.Command) - Command.AddCommand(deltags.Command) - Command.AddCommand(gettags.Command) - Command.AddCommand(events.Command) +func NewCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "job", + Short: "manage jobs", + Long: "subcommand to manage jobs (CRUD)", + TraverseChildren: true, + SilenceUsage: true, + } + cmd.AddCommand(create.NewCommand()) + cmd.AddCommand(delete.NewCommand()) + cmd.AddCommand(get.NewCommand()) + cmd.AddCommand(query.NewCommand()) + cmd.AddCommand(updatestatus.NewCommand()) + cmd.AddCommand(getstatus.NewCommand()) + cmd.AddCommand(updatedefinition.NewCommand()) + cmd.AddCommand(getdefinition.NewCommand()) + cmd.AddCommand(addtags.NewCommand()) + cmd.AddCommand(deltags.NewCommand()) + cmd.AddCommand(gettags.NewCommand()) + cmd.AddCommand(events.NewCommand()) + return cmd } diff --git a/cmd/wfxctl/cmd/job/job_test.go b/cmd/wfxctl/cmd/job/job_test.go index 37d05f33..b76017bc 100644 --- a/cmd/wfxctl/cmd/job/job_test.go +++ b/cmd/wfxctl/cmd/job/job_test.go @@ -15,5 +15,5 @@ import ( ) func TestSubcommands(t *testing.T) { - assert.True(t, Command.HasSubCommands()) + assert.True(t, NewCommand().HasSubCommands()) } diff --git a/cmd/wfxctl/cmd/job/query/query.go b/cmd/wfxctl/cmd/job/query/query.go index 19e653aa..9a1e15be 100644 --- a/cmd/wfxctl/cmd/job/query/query.go +++ b/cmd/wfxctl/cmd/job/query/query.go @@ -9,81 +9,69 @@ package query */ import ( - "github.com/rs/zerolog/log" + "github.com/Southclaws/fault" "github.com/spf13/cobra" "github.com/siemens/wfx/cmd/wfxctl/errutil" "github.com/siemens/wfx/cmd/wfxctl/flags" - "github.com/siemens/wfx/generated/client/jobs" + "github.com/siemens/wfx/generated/api" ) -const ( - clientIDFlag = "client-id" - stateFlag = "state" - workflowFlag = "workflow" - sortFlag = "sort" - groupFlag = "group" - offsetFlag = "offset" - limitFlag = "limit" - tagFlag = "tag" -) - -func init() { - f := Command.Flags() - f.String(clientIDFlag, "", "Filter jobs belonging to a specific client with clientId") - f.StringSlice(groupFlag, []string{}, "Filter jobs based on the group they belong to") - f.String(stateFlag, "", "Filter jobs based on the current state value") - f.String(workflowFlag, "", "Filter jobs based on workflow name") - f.StringSlice(tagFlag, []string{}, "Filter jobs by tags") - f.Int32(offsetFlag, 0, "0-based index of the page") - f.Int32(limitFlag, 10, "maximum number of elements returned in one page ") - f.String(sortFlag, "", "sort order. possible values: asc, desc") -} - -var Command = &cobra.Command{ - Use: "query", - Short: "Query existing jobs", - Long: `Query existing jobs`, - Example: ` +func NewCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "query", + Short: "Query existing jobs", + Long: `Query existing jobs`, + Example: ` wfxctl job query --state=CREATED `, - TraverseChildren: true, - Run: func(cmd *cobra.Command, _ []string) { - baseCmd := flags.NewBaseCmd() - client := errutil.Must(baseCmd.CreateHTTPClient()) - params := jobs.NewGetJobsParams(). - WithHTTPClient(client) + TraverseChildren: true, + RunE: func(cmd *cobra.Command, _ []string) error { + baseCmd := flags.NewBaseCmd(cmd.Flags()) - if clientID := flags.Koanf.String(clientIDFlag); clientID != "" { - params = params.WithClientID(&clientID) - } - if state := flags.Koanf.String(stateFlag); state != "" { - params = params.WithState(&state) - } - if modelKey := flags.Koanf.String(workflowFlag); modelKey != "" { - params = params.WithWorkflow(&modelKey) - } - if sort := flags.Koanf.String(sortFlag); sort != "" { - params = params.WithSort(&sort) - } - groups := flags.Koanf.Strings(groupFlag) - tags := flags.Koanf.Strings(tagFlag) + params := new(api.GetJobsParams) + if clientID := baseCmd.ClientID; clientID != "" { + params.ParamClientID = &clientID + } + if state := baseCmd.State; state != "" { + params.ParamState = &state + } + if workflow := baseCmd.Workflow; workflow != "" { + params.ParamWorkflow = &workflow + } + { + var err error + params.ParamSort, err = baseCmd.SortParam() + if err != nil { + return fault.Wrap(err) + } + } + if groups := baseCmd.Groups; len(groups) > 0 { + params.ParamGroup = &groups + } + if tags := baseCmd.Tags; len(tags) > 0 { + params.ParamTag = &tags + } - offset := flags.Koanf.Int64(offsetFlag) - limit := int32(flags.Koanf.Int(limitFlag)) - params = params. - WithOffset(&offset). - WithLimit(&limit). - WithTag(tags). - WithGroup(groups) + params.ParamOffset = &baseCmd.Offset + params.ParamLimit = &baseCmd.Limit - resp, err := baseCmd.CreateClient().Jobs.GetJobs(params) - if err != nil { - errutil.ProcessErrorResponse(cmd.OutOrStderr(), err) - } else { - if err := baseCmd.DumpResponse(cmd.OutOrStdout(), resp.GetPayload()); err != nil { - log.Fatal().Err(err).Msg("Failed to dump response") + client := errutil.Must(baseCmd.CreateClient()) + resp, err := client.GetJobs(cmd.Context(), params) + if err != nil { + return fault.Wrap(err) } - } - }, + return fault.Wrap(baseCmd.ProcessResponse(resp, cmd.OutOrStdout())) + }, + } + f := cmd.Flags() + f.String(flags.ClientIDFlag, "", "Filter jobs belonging to a specific client with clientId") + f.StringSlice(flags.GroupFlag, []string{}, "Filter jobs based on the group they belong to") + f.String(flags.StateFlag, "", "Filter jobs based on the current state value") + f.String(flags.WorkflowFlag, "", "Filter jobs based on workflow name") + f.StringSlice(flags.TagFlag, []string{}, "Filter jobs by tags") + f.Int64(flags.OffsetFlag, 0, "0-based index of the page") + f.Int32(flags.LimitFlag, 10, "maximum number of elements returned in one page ") + f.String(flags.SortFlag, "", "sort order. possible values: asc, desc") + return cmd } diff --git a/cmd/wfxctl/cmd/job/query/query_test.go b/cmd/wfxctl/cmd/job/query/query_test.go index fbae0e9d..b5704dbf 100644 --- a/cmd/wfxctl/cmd/job/query/query_test.go +++ b/cmd/wfxctl/cmd/job/query/query_test.go @@ -12,11 +12,11 @@ import ( "net/http" "net/http/httptest" "net/url" - "strconv" "testing" "github.com/siemens/wfx/cmd/wfxctl/flags" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestQueryJobs(t *testing.T) { @@ -40,17 +40,12 @@ func TestQueryJobs(t *testing.T) { defer ts.Close() u, _ := url.Parse(ts.URL) - _ = flags.Koanf.Set(flags.ClientHostFlag, u.Hostname()) - port, _ := strconv.Atoi(u.Port()) - _ = flags.Koanf.Set(flags.ClientPortFlag, port) - - _ = flags.Koanf.Set(clientIDFlag, "my_client") - _ = flags.Koanf.Set(groupFlag, []string{"OPEN"}) - _ = flags.Koanf.Set(stateFlag, "DOWNLOAD") - _ = flags.Koanf.Set(workflowFlag, "wfx.workflow.dau.direct") - - err := Command.Execute() - assert.NoError(t, err) + t.Setenv("WFX_CLIENT_HOST", u.Hostname()) + t.Setenv("WFX_CLIENT_PORT", u.Port()) + cmd := NewCommand() + cmd.SetArgs([]string{"--" + flags.ClientIDFlag, "my_client", "--" + flags.GroupFlag, "OPEN", "--" + flags.StateFlag, "DOWNLOAD", "--" + flags.WorkflowFlag, "wfx.workflow.dau.direct"}) + err := cmd.Execute() + require.NoError(t, err) assert.Equal(t, expectedPath, actualPath) } diff --git a/cmd/wfxctl/cmd/job/updatedefinition/update_definition.go b/cmd/wfxctl/cmd/job/updatedefinition/update_definition.go index e7535c13..dcec5a0f 100644 --- a/cmd/wfxctl/cmd/job/updatedefinition/update_definition.go +++ b/cmd/wfxctl/cmd/job/updatedefinition/update_definition.go @@ -10,62 +10,40 @@ package updatedefinition import ( "bufio" - "encoding/json" - "io" + "errors" - "github.com/rs/zerolog/log" + "github.com/Southclaws/fault" "github.com/spf13/cobra" "github.com/siemens/wfx/cmd/wfxctl/errutil" "github.com/siemens/wfx/cmd/wfxctl/flags" - "github.com/siemens/wfx/generated/client/jobs" ) -const ( - idFlag = "id" -) - -func init() { - f := Command.Flags() - f.String(idFlag, "", "job id") -} - -var Command = &cobra.Command{ - Use: "update-definition", - Short: "Update job definition", - Long: `Update definition of an existing job using data provided via stdin`, - Example: ` +func NewCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "update-definition", + Short: "Update job definition", + Long: `Update definition of an existing job using data provided via stdin`, + Example: ` wfxctl job update-definition `, - TraverseChildren: true, - Run: func(cmd *cobra.Command, _ []string) { - baseCmd := flags.NewBaseCmd() - - b, err := io.ReadAll(bufio.NewReader(cmd.InOrStdin())) - if err != nil { - log.Fatal().Err(err).Msg("Failed to read from stdin") - } - - var definition map[string]any - err = json.Unmarshal(b, &definition) - if err != nil { - log.Fatal().Err(err).Msg("Failed to parse data from stdin") - } - client := errutil.Must(baseCmd.CreateHTTPClient()) - params := jobs.NewPutJobsIDDefinitionParams(). - WithHTTPClient(client). - WithID(flags.Koanf.String(idFlag)). - WithJobDefinition(definition) - - resp, err := baseCmd.CreateMgmtClient().Jobs.PutJobsIDDefinition(params) - if err != nil { - errutil.ProcessErrorResponse(cmd.OutOrStderr(), err) - log.Fatal().Msg("Failed to update job definition") - } - - log.Info().Str("id", params.ID).Msg("Updated job definition") - if err := baseCmd.DumpResponse(cmd.OutOrStdout(), resp.GetPayload()); err != nil { - log.Fatal().Err(err).Msg("Failed to print response") - } - }, + TraverseChildren: true, + RunE: func(cmd *cobra.Command, _ []string) error { + baseCmd := flags.NewBaseCmd(cmd.Flags()) + id := baseCmd.ID + if id == "" { + return errors.New("job id missing") + } + client := errutil.Must(baseCmd.CreateMgmtClient()) + resp, err := client.PutJobsIdDefinitionWithBody(cmd.Context(), id, nil, "application/json", bufio.NewReader(cmd.InOrStdin())) + if err != nil { + return fault.Wrap(err) + } + return fault.Wrap(baseCmd.ProcessResponse(resp, cmd.OutOrStdout())) + }, + } + + f := cmd.Flags() + f.String(flags.IDFlag, "", "job id") + return cmd } diff --git a/cmd/wfxctl/cmd/job/updatedefinition/update_definition_test.go b/cmd/wfxctl/cmd/job/updatedefinition/update_definition_test.go index 5e1ba1e3..75f6cd97 100644 --- a/cmd/wfxctl/cmd/job/updatedefinition/update_definition_test.go +++ b/cmd/wfxctl/cmd/job/updatedefinition/update_definition_test.go @@ -14,11 +14,11 @@ import ( "net/http" "net/http/httptest" "net/url" - "strconv" "testing" "github.com/siemens/wfx/cmd/wfxctl/flags" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestUpdateJobDefinition(t *testing.T) { @@ -36,19 +36,17 @@ func TestUpdateJobDefinition(t *testing.T) { defer ts.Close() u, _ := url.Parse(ts.URL) - _ = flags.Koanf.Set(flags.MgmtHostFlag, u.Hostname()) - port, _ := strconv.Atoi(u.Port()) - _ = flags.Koanf.Set(flags.MgmtPortFlag, port) - - _ = flags.Koanf.Set(idFlag, "1") + t.Setenv("WFX_MGMT_HOST", u.Hostname()) + t.Setenv("WFX_MGMT_PORT", u.Port()) var stdin bytes.Buffer stdin.Write([]byte("{}")) - Command.SetIn(&stdin) - err := Command.Execute() - assert.NoError(t, err) - + cmd := NewCommand() + cmd.SetArgs([]string{"--" + flags.IDFlag, "1"}) + cmd.SetIn(&stdin) + err := cmd.Execute() + require.NoError(t, err) assert.Equal(t, "/api/wfx/v1/jobs/1/definition", actualPath) assert.JSONEq(t, "{}", string(body)) } diff --git a/cmd/wfxctl/cmd/job/updatestatus/update_status.go b/cmd/wfxctl/cmd/job/updatestatus/update_status.go index 731fbfb1..dc785e66 100644 --- a/cmd/wfxctl/cmd/job/updatestatus/update_status.go +++ b/cmd/wfxctl/cmd/job/updatestatus/update_status.go @@ -9,75 +9,60 @@ package updatestatus */ import ( + "errors" "strings" - "github.com/rs/zerolog/log" + "github.com/Southclaws/fault" "github.com/spf13/cobra" "github.com/siemens/wfx/cmd/wfxctl/errutil" "github.com/siemens/wfx/cmd/wfxctl/flags" - "github.com/siemens/wfx/generated/client" - "github.com/siemens/wfx/generated/client/jobs" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" ) -const ( - idFlag = "id" - actorFlag = "actor" - clientIDFlag = "client-id" - stateFlag = "state" - progressFlag = "progress" - messageFlag = "message" -) - -func init() { - f := Command.Flags() - f.String(idFlag, "", "job which shall be updated") - f.String(actorFlag, string(model.EligibleEnumCLIENT), "actor to use (eligible)") - f.String(clientIDFlag, "", "client which sends the update") - f.String(stateFlag, "", "Name of the new state") - f.Int(progressFlag, 0, "progress value (0 <= progress <= 100)") - f.String(messageFlag, "", "status message / info, free text from client") -} - -var Command = &cobra.Command{ - Use: "update-status", - Short: "Update job status", - Long: `Update job status of an existing job`, - Example: ` -wfxctl job update-status --id=1 --client-id=client42 --state=DOWNLOAD +func NewCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "update-status", + Short: "Update job status", + Long: `Update job status of an existing job`, + Example: ` +wfxctl job update-status --id=8ea1e9d7-28e6-4f1f-b444-a8d2d1ad7618 --client-id=client42 --state=DOWNLOAD `, - Run: func(cmd *cobra.Command, _ []string) { - baseCmd := flags.NewBaseCmd() - req := model.JobStatus{ - ClientID: flags.Koanf.String(clientIDFlag), - State: flags.Koanf.String(stateFlag), - Progress: int32(flags.Koanf.Int(progressFlag)), - Message: flags.Koanf.String(messageFlag), - } - - cli := errutil.Must(baseCmd.CreateHTTPClient()) - - params := jobs.NewPutJobsIDStatusParams(). - WithHTTPClient(cli). - WithID(flags.Koanf.String(idFlag)). - WithNewJobStatus(&req) - - var c *client.WorkflowExecutor - if strings.ToUpper(flags.Koanf.String(actorFlag)) == string(model.EligibleEnumCLIENT) { - c = baseCmd.CreateClient() - } else { - c = baseCmd.CreateMgmtClient() - } - resp, err := c.Jobs.PutJobsIDStatus(params) - if err != nil { - errutil.ProcessErrorResponse(cmd.OutOrStderr(), err) - log.Fatal().Msg("Failed to update job") - } + RunE: func(cmd *cobra.Command, _ []string) error { + baseCmd := flags.NewBaseCmd(cmd.Flags()) + id := baseCmd.ID + if id == "" { + return errors.New("id missing") + } + clientID := baseCmd.ClientID + progress := int32(baseCmd.Progress) + message := baseCmd.Message + status := api.JobStatus{ + ClientID: clientID, + State: baseCmd.State, + Progress: &progress, + Message: message, + } - log.Info().Str("id", params.ID).Str("state", req.State).Msg("Updated job status") - if err := baseCmd.DumpResponse(cmd.OutOrStdout(), resp.GetPayload()); err != nil { - log.Fatal().Err(err).Msg("Failed to dump response") - } - }, + var client *api.Client + if strings.ToUpper(baseCmd.Actor) == string(api.CLIENT) { + client = errutil.Must(baseCmd.CreateClient()) + } else { + client = errutil.Must(baseCmd.CreateMgmtClient()) + } + resp, err := client.PutJobsIdStatus(cmd.Context(), id, nil, api.PutJobsIdStatusJSONRequestBody(status)) + if err != nil { + return fault.Wrap(err) + } + return fault.Wrap(baseCmd.ProcessResponse(resp, cmd.OutOrStdout())) + }, + } + f := cmd.Flags() + f.String(flags.IDFlag, "", "job which shall be updated") + f.String(flags.ActorFlag, string(api.CLIENT), "actor to use (eligible)") + f.String(flags.ClientIDFlag, "", "client which sends the update") + f.String(flags.StateFlag, "", "name of the new state") + f.Int(flags.ProgressFlag, 0, "progress value (0 <= progress <= 100)") + f.String(flags.MessageFlag, "", "status message / info, free text from client") + return cmd } diff --git a/cmd/wfxctl/cmd/job/updatestatus/update_status_test.go b/cmd/wfxctl/cmd/job/updatestatus/update_status_test.go index a3cd3479..05215cb0 100644 --- a/cmd/wfxctl/cmd/job/updatestatus/update_status_test.go +++ b/cmd/wfxctl/cmd/job/updatestatus/update_status_test.go @@ -13,11 +13,10 @@ import ( "net/http" "net/http/httptest" "net/url" - "strconv" "testing" "github.com/siemens/wfx/cmd/wfxctl/flags" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/stretchr/testify/assert" ) @@ -36,18 +35,19 @@ func TestUpdateJobStatus(t *testing.T) { defer ts.Close() u, _ := url.Parse(ts.URL) - _ = flags.Koanf.Set(flags.ClientHostFlag, u.Hostname()) - port, _ := strconv.Atoi(u.Port()) - _ = flags.Koanf.Set(flags.ClientPortFlag, port) - - _ = flags.Koanf.Set(clientIDFlag, "foo") - _ = flags.Koanf.Set(messageFlag, "this is a test") - _ = flags.Koanf.Set(progressFlag, int32(42)) - _ = flags.Koanf.Set(stateFlag, "DOWNLOADED") - _ = flags.Koanf.Set(idFlag, "1") - _ = flags.Koanf.Set(actorFlag, model.EligibleEnumCLIENT) - - err := Command.Execute() + t.Setenv("WFX_CLIENT_HOST", u.Hostname()) + t.Setenv("WFX_CLIENT_PORT", u.Port()) + + cmd := NewCommand() + cmd.SetArgs([]string{ + "--" + flags.ClientIDFlag, "foo", + "--" + flags.MessageFlag, "this is a test", + "--" + flags.ProgressFlag, "42", + "--" + flags.StateFlag, "DOWNLOADED", + "--" + flags.IDFlag, "1", + "--" + flags.ActorFlag, string(api.CLIENT), + }) + err := cmd.Execute() assert.NoError(t, err) assert.Equal(t, "/api/wfx/v1/jobs/1/status", actualPath) diff --git a/cmd/wfxctl/cmd/man/wfxctl-completion-bash.1 b/cmd/wfxctl/cmd/man/wfxctl-completion-bash.1 new file mode 100644 index 00000000..fbb7585a --- /dev/null +++ b/cmd/wfxctl/cmd/man/wfxctl-completion-bash.1 @@ -0,0 +1,124 @@ +.nh +.TH "WFXCTL-COMPLETION-BASH" "1" "Dec 2024" "" "" + +.SH NAME +.PP +wfxctl-completion-bash - Generate the autocompletion script for bash + + +.SH SYNOPSIS +.PP +\fBwfxctl completion bash\fP + + +.SH DESCRIPTION +.PP +Generate the autocompletion script for the bash shell. + +.PP +This script depends on the 'bash-completion' package. +If it is not installed already, you can install it via your OS's package manager. + +.PP +To load completions in your current shell session: + +.EX +source <(wfxctl completion bash) +.EE + +.PP +To load completions for every new session, execute once: + +.SS Linux: +.EX +wfxctl completion bash > /etc/bash_completion.d/wfxctl +.EE + +.SS macOS: +.EX +wfxctl completion bash > $(brew --prefix)/etc/bash_completion.d/wfxctl +.EE + +.PP +You will need to start a new shell for this setup to take effect. + + +.SH OPTIONS +.PP +\fB-h\fP, \fB--help\fP[=false] + help for bash + +.PP +\fB--no-descriptions\fP[=false] + disable completion descriptions + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB--client-host\fP="localhost" + host + +.PP +\fB--client-port\fP=8080 + port + +.PP +\fB--client-tls-host\fP="localhost" + TLS host + +.PP +\fB--client-tls-port\fP=8443 + TLS port + +.PP +\fB--client-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--config\fP=[wfx.yml,/home/adlerm/.config/wfx/config.yml,/etc/wfx/wfx.yml] + path to one or more .yaml config files; if this option is not set, then the default paths are tried + +.PP +\fB--enable-tls\fP[=false] + whether to enable TLS (https) + +.PP +\fB--filter\fP="" + output filter (jq-expression). example: '.id' + +.PP +\fB--log-level\fP="info" + set log level. one of: trace,debug,info,warn,error,fatal,panic + +.PP +\fB--mgmt-host\fP="localhost" + management host + +.PP +\fB--mgmt-port\fP=8081 + management port + +.PP +\fB--mgmt-tls-host\fP="localhost" + management TLS host + +.PP +\fB--mgmt-tls-port\fP=8444 + management TLS port + +.PP +\fB--mgmt-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--raw\fP[=false] + output raw strings, not JSON texts; use --filter to select a single entity + +.PP +\fB--tls-ca\fP="" + ca bundle (PEM) + + +.SH SEE ALSO +.PP +\fBwfxctl-completion(1)\fP diff --git a/cmd/wfxctl/cmd/man/wfxctl-completion-fish.1 b/cmd/wfxctl/cmd/man/wfxctl-completion-fish.1 new file mode 100644 index 00000000..818d7299 --- /dev/null +++ b/cmd/wfxctl/cmd/man/wfxctl-completion-fish.1 @@ -0,0 +1,114 @@ +.nh +.TH "WFXCTL-COMPLETION-FISH" "1" "Dec 2024" "" "" + +.SH NAME +.PP +wfxctl-completion-fish - Generate the autocompletion script for fish + + +.SH SYNOPSIS +.PP +\fBwfxctl completion fish [flags]\fP + + +.SH DESCRIPTION +.PP +Generate the autocompletion script for the fish shell. + +.PP +To load completions in your current shell session: + +.EX +wfxctl completion fish | source +.EE + +.PP +To load completions for every new session, execute once: + +.EX +wfxctl completion fish > ~/.config/fish/completions/wfxctl.fish +.EE + +.PP +You will need to start a new shell for this setup to take effect. + + +.SH OPTIONS +.PP +\fB-h\fP, \fB--help\fP[=false] + help for fish + +.PP +\fB--no-descriptions\fP[=false] + disable completion descriptions + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB--client-host\fP="localhost" + host + +.PP +\fB--client-port\fP=8080 + port + +.PP +\fB--client-tls-host\fP="localhost" + TLS host + +.PP +\fB--client-tls-port\fP=8443 + TLS port + +.PP +\fB--client-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--config\fP=[wfx.yml,/home/adlerm/.config/wfx/config.yml,/etc/wfx/wfx.yml] + path to one or more .yaml config files; if this option is not set, then the default paths are tried + +.PP +\fB--enable-tls\fP[=false] + whether to enable TLS (https) + +.PP +\fB--filter\fP="" + output filter (jq-expression). example: '.id' + +.PP +\fB--log-level\fP="info" + set log level. one of: trace,debug,info,warn,error,fatal,panic + +.PP +\fB--mgmt-host\fP="localhost" + management host + +.PP +\fB--mgmt-port\fP=8081 + management port + +.PP +\fB--mgmt-tls-host\fP="localhost" + management TLS host + +.PP +\fB--mgmt-tls-port\fP=8444 + management TLS port + +.PP +\fB--mgmt-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--raw\fP[=false] + output raw strings, not JSON texts; use --filter to select a single entity + +.PP +\fB--tls-ca\fP="" + ca bundle (PEM) + + +.SH SEE ALSO +.PP +\fBwfxctl-completion(1)\fP diff --git a/cmd/wfxctl/cmd/man/wfxctl-completion-powershell.1 b/cmd/wfxctl/cmd/man/wfxctl-completion-powershell.1 new file mode 100644 index 00000000..96f39b89 --- /dev/null +++ b/cmd/wfxctl/cmd/man/wfxctl-completion-powershell.1 @@ -0,0 +1,108 @@ +.nh +.TH "WFXCTL-COMPLETION-POWERSHELL" "1" "Dec 2024" "" "" + +.SH NAME +.PP +wfxctl-completion-powershell - Generate the autocompletion script for powershell + + +.SH SYNOPSIS +.PP +\fBwfxctl completion powershell [flags]\fP + + +.SH DESCRIPTION +.PP +Generate the autocompletion script for powershell. + +.PP +To load completions in your current shell session: + +.EX +wfxctl completion powershell | Out-String | Invoke-Expression +.EE + +.PP +To load completions for every new session, add the output of the above command +to your powershell profile. + + +.SH OPTIONS +.PP +\fB-h\fP, \fB--help\fP[=false] + help for powershell + +.PP +\fB--no-descriptions\fP[=false] + disable completion descriptions + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB--client-host\fP="localhost" + host + +.PP +\fB--client-port\fP=8080 + port + +.PP +\fB--client-tls-host\fP="localhost" + TLS host + +.PP +\fB--client-tls-port\fP=8443 + TLS port + +.PP +\fB--client-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--config\fP=[wfx.yml,/home/adlerm/.config/wfx/config.yml,/etc/wfx/wfx.yml] + path to one or more .yaml config files; if this option is not set, then the default paths are tried + +.PP +\fB--enable-tls\fP[=false] + whether to enable TLS (https) + +.PP +\fB--filter\fP="" + output filter (jq-expression). example: '.id' + +.PP +\fB--log-level\fP="info" + set log level. one of: trace,debug,info,warn,error,fatal,panic + +.PP +\fB--mgmt-host\fP="localhost" + management host + +.PP +\fB--mgmt-port\fP=8081 + management port + +.PP +\fB--mgmt-tls-host\fP="localhost" + management TLS host + +.PP +\fB--mgmt-tls-port\fP=8444 + management TLS port + +.PP +\fB--mgmt-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--raw\fP[=false] + output raw strings, not JSON texts; use --filter to select a single entity + +.PP +\fB--tls-ca\fP="" + ca bundle (PEM) + + +.SH SEE ALSO +.PP +\fBwfxctl-completion(1)\fP diff --git a/cmd/wfxctl/cmd/man/wfxctl-completion-zsh.1 b/cmd/wfxctl/cmd/man/wfxctl-completion-zsh.1 new file mode 100644 index 00000000..d6400bfe --- /dev/null +++ b/cmd/wfxctl/cmd/man/wfxctl-completion-zsh.1 @@ -0,0 +1,128 @@ +.nh +.TH "WFXCTL-COMPLETION-ZSH" "1" "Dec 2024" "" "" + +.SH NAME +.PP +wfxctl-completion-zsh - Generate the autocompletion script for zsh + + +.SH SYNOPSIS +.PP +\fBwfxctl completion zsh [flags]\fP + + +.SH DESCRIPTION +.PP +Generate the autocompletion script for the zsh shell. + +.PP +If shell completion is not already enabled in your environment you will need +to enable it. You can execute the following once: + +.EX +echo "autoload -U compinit; compinit" >> ~/.zshrc +.EE + +.PP +To load completions in your current shell session: + +.EX +source <(wfxctl completion zsh) +.EE + +.PP +To load completions for every new session, execute once: + +.SS Linux: +.EX +wfxctl completion zsh > "${fpath[1]}/_wfxctl" +.EE + +.SS macOS: +.EX +wfxctl completion zsh > $(brew --prefix)/share/zsh/site-functions/_wfxctl +.EE + +.PP +You will need to start a new shell for this setup to take effect. + + +.SH OPTIONS +.PP +\fB-h\fP, \fB--help\fP[=false] + help for zsh + +.PP +\fB--no-descriptions\fP[=false] + disable completion descriptions + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB--client-host\fP="localhost" + host + +.PP +\fB--client-port\fP=8080 + port + +.PP +\fB--client-tls-host\fP="localhost" + TLS host + +.PP +\fB--client-tls-port\fP=8443 + TLS port + +.PP +\fB--client-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--config\fP=[wfx.yml,/home/adlerm/.config/wfx/config.yml,/etc/wfx/wfx.yml] + path to one or more .yaml config files; if this option is not set, then the default paths are tried + +.PP +\fB--enable-tls\fP[=false] + whether to enable TLS (https) + +.PP +\fB--filter\fP="" + output filter (jq-expression). example: '.id' + +.PP +\fB--log-level\fP="info" + set log level. one of: trace,debug,info,warn,error,fatal,panic + +.PP +\fB--mgmt-host\fP="localhost" + management host + +.PP +\fB--mgmt-port\fP=8081 + management port + +.PP +\fB--mgmt-tls-host\fP="localhost" + management TLS host + +.PP +\fB--mgmt-tls-port\fP=8444 + management TLS port + +.PP +\fB--mgmt-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--raw\fP[=false] + output raw strings, not JSON texts; use --filter to select a single entity + +.PP +\fB--tls-ca\fP="" + ca bundle (PEM) + + +.SH SEE ALSO +.PP +\fBwfxctl-completion(1)\fP diff --git a/cmd/wfxctl/cmd/man/wfxctl-completion.1 b/cmd/wfxctl/cmd/man/wfxctl-completion.1 new file mode 100644 index 00000000..33fefc42 --- /dev/null +++ b/cmd/wfxctl/cmd/man/wfxctl-completion.1 @@ -0,0 +1,94 @@ +.nh +.TH "WFXCTL-COMPLETION" "1" "Dec 2024" "" "" + +.SH NAME +.PP +wfxctl-completion - Generate the autocompletion script for the specified shell + + +.SH SYNOPSIS +.PP +\fBwfxctl completion [flags]\fP + + +.SH DESCRIPTION +.PP +Generate the autocompletion script for wfxctl for the specified shell. +See each sub-command's help for details on how to use the generated script. + + +.SH OPTIONS +.PP +\fB-h\fP, \fB--help\fP[=false] + help for completion + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB--client-host\fP="localhost" + host + +.PP +\fB--client-port\fP=8080 + port + +.PP +\fB--client-tls-host\fP="localhost" + TLS host + +.PP +\fB--client-tls-port\fP=8443 + TLS port + +.PP +\fB--client-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--config\fP=[wfx.yml,/home/adlerm/.config/wfx/config.yml,/etc/wfx/wfx.yml] + path to one or more .yaml config files; if this option is not set, then the default paths are tried + +.PP +\fB--enable-tls\fP[=false] + whether to enable TLS (https) + +.PP +\fB--filter\fP="" + output filter (jq-expression). example: '.id' + +.PP +\fB--log-level\fP="info" + set log level. one of: trace,debug,info,warn,error,fatal,panic + +.PP +\fB--mgmt-host\fP="localhost" + management host + +.PP +\fB--mgmt-port\fP=8081 + management port + +.PP +\fB--mgmt-tls-host\fP="localhost" + management TLS host + +.PP +\fB--mgmt-tls-port\fP=8444 + management TLS port + +.PP +\fB--mgmt-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--raw\fP[=false] + output raw strings, not JSON texts; use --filter to select a single entity + +.PP +\fB--tls-ca\fP="" + ca bundle (PEM) + + +.SH SEE ALSO +.PP +\fBwfxctl(1)\fP, \fBwfxctl-completion-bash(1)\fP, \fBwfxctl-completion-fish(1)\fP, \fBwfxctl-completion-powershell(1)\fP, \fBwfxctl-completion-zsh(1)\fP diff --git a/cmd/wfxctl/cmd/man/wfxctl-health.1 b/cmd/wfxctl/cmd/man/wfxctl-health.1 new file mode 100644 index 00000000..fa1c8034 --- /dev/null +++ b/cmd/wfxctl/cmd/man/wfxctl-health.1 @@ -0,0 +1,97 @@ +.nh +.TH "WFXCTL-HEALTH" "1" "Dec 2024" "" "" + +.SH NAME +.PP +wfxctl-health - Check health of wfx + + +.SH SYNOPSIS +.PP +\fBwfxctl health [flags]\fP + + +.SH DESCRIPTION +.PP +Check health wfx + + +.SH OPTIONS +.PP +\fB--color\fP="auto" + possible values: never, always, auto + +.PP +\fB-h\fP, \fB--help\fP[=false] + help for health + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB--client-host\fP="localhost" + host + +.PP +\fB--client-port\fP=8080 + port + +.PP +\fB--client-tls-host\fP="localhost" + TLS host + +.PP +\fB--client-tls-port\fP=8443 + TLS port + +.PP +\fB--client-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--config\fP=[wfx.yml,/home/adlerm/.config/wfx/config.yml,/etc/wfx/wfx.yml] + path to one or more .yaml config files; if this option is not set, then the default paths are tried + +.PP +\fB--enable-tls\fP[=false] + whether to enable TLS (https) + +.PP +\fB--filter\fP="" + output filter (jq-expression). example: '.id' + +.PP +\fB--log-level\fP="info" + set log level. one of: trace,debug,info,warn,error,fatal,panic + +.PP +\fB--mgmt-host\fP="localhost" + management host + +.PP +\fB--mgmt-port\fP=8081 + management port + +.PP +\fB--mgmt-tls-host\fP="localhost" + management TLS host + +.PP +\fB--mgmt-tls-port\fP=8444 + management TLS port + +.PP +\fB--mgmt-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--raw\fP[=false] + output raw strings, not JSON texts; use --filter to select a single entity + +.PP +\fB--tls-ca\fP="" + ca bundle (PEM) + + +.SH SEE ALSO +.PP +\fBwfxctl(1)\fP diff --git a/cmd/wfxctl/cmd/man/wfxctl-job-add-tags.1 b/cmd/wfxctl/cmd/man/wfxctl-job-add-tags.1 new file mode 100644 index 00000000..9c536b1a --- /dev/null +++ b/cmd/wfxctl/cmd/man/wfxctl-job-add-tags.1 @@ -0,0 +1,103 @@ +.nh +.TH "WFXCTL-JOB-ADD-TAGS" "1" "Dec 2024" "" "" + +.SH NAME +.PP +wfxctl-job-add-tags - Add tags to a job + + +.SH SYNOPSIS +.PP +\fBwfxctl job add-tags [flags]\fP + + +.SH DESCRIPTION +.PP +Add tags to a job + + +.SH OPTIONS +.PP +\fB-h\fP, \fB--help\fP[=false] + help for add-tags + +.PP +\fB--id\fP="" + job id + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB--client-host\fP="localhost" + host + +.PP +\fB--client-port\fP=8080 + port + +.PP +\fB--client-tls-host\fP="localhost" + TLS host + +.PP +\fB--client-tls-port\fP=8443 + TLS port + +.PP +\fB--client-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--config\fP=[wfx.yml,/home/adlerm/.config/wfx/config.yml,/etc/wfx/wfx.yml] + path to one or more .yaml config files; if this option is not set, then the default paths are tried + +.PP +\fB--enable-tls\fP[=false] + whether to enable TLS (https) + +.PP +\fB--filter\fP="" + output filter (jq-expression). example: '.id' + +.PP +\fB--log-level\fP="info" + set log level. one of: trace,debug,info,warn,error,fatal,panic + +.PP +\fB--mgmt-host\fP="localhost" + management host + +.PP +\fB--mgmt-port\fP=8081 + management port + +.PP +\fB--mgmt-tls-host\fP="localhost" + management TLS host + +.PP +\fB--mgmt-tls-port\fP=8444 + management TLS port + +.PP +\fB--mgmt-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--raw\fP[=false] + output raw strings, not JSON texts; use --filter to select a single entity + +.PP +\fB--tls-ca\fP="" + ca bundle (PEM) + + +.SH EXAMPLE +.EX +wfxctl job add-tags --id=1 tag1 tag2 +.EE + + +.SH SEE ALSO +.PP +\fBwfxctl-job(1)\fP diff --git a/cmd/wfxctl/cmd/man/wfxctl-job-create.1 b/cmd/wfxctl/cmd/man/wfxctl-job-create.1 new file mode 100644 index 00000000..1f537330 --- /dev/null +++ b/cmd/wfxctl/cmd/man/wfxctl-job-create.1 @@ -0,0 +1,113 @@ +.nh +.TH "WFXCTL-JOB-CREATE" "1" "Dec 2024" "" "" + +.SH NAME +.PP +wfxctl-job-create - Create a new job + + +.SH SYNOPSIS +.PP +\fBwfxctl job create [flags]\fP + + +.SH DESCRIPTION +.PP +Create a new job. You should provide the job definition (JSON) via stdin. + + +.SH OPTIONS +.PP +\fB--client-id\fP="" + clientID for the job + +.PP +\fB-h\fP, \fB--help\fP[=false] + help for create + +.PP +\fB--tag\fP=[] + Tags to apply to the job + +.PP +\fB--workflow\fP="" + workflow for the job + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB--client-host\fP="localhost" + host + +.PP +\fB--client-port\fP=8080 + port + +.PP +\fB--client-tls-host\fP="localhost" + TLS host + +.PP +\fB--client-tls-port\fP=8443 + TLS port + +.PP +\fB--client-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--config\fP=[wfx.yml,/home/adlerm/.config/wfx/config.yml,/etc/wfx/wfx.yml] + path to one or more .yaml config files; if this option is not set, then the default paths are tried + +.PP +\fB--enable-tls\fP[=false] + whether to enable TLS (https) + +.PP +\fB--filter\fP="" + output filter (jq-expression). example: '.id' + +.PP +\fB--log-level\fP="info" + set log level. one of: trace,debug,info,warn,error,fatal,panic + +.PP +\fB--mgmt-host\fP="localhost" + management host + +.PP +\fB--mgmt-port\fP=8081 + management port + +.PP +\fB--mgmt-tls-host\fP="localhost" + management TLS host + +.PP +\fB--mgmt-tls-port\fP=8444 + management TLS port + +.PP +\fB--mgmt-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--raw\fP[=false] + output raw strings, not JSON texts; use --filter to select a single entity + +.PP +\fB--tls-ca\fP="" + ca bundle (PEM) + + +.SH EXAMPLE +.EX + +echo '{ "title": "Task 1" }' | wfxctl job create --client-id=my_client --workflow=wfx.workflow.kanban - + +.EE + + +.SH SEE ALSO +.PP +\fBwfxctl-job(1)\fP diff --git a/cmd/wfxctl/cmd/man/wfxctl-job-del-tags.1 b/cmd/wfxctl/cmd/man/wfxctl-job-del-tags.1 new file mode 100644 index 00000000..97d2f271 --- /dev/null +++ b/cmd/wfxctl/cmd/man/wfxctl-job-del-tags.1 @@ -0,0 +1,103 @@ +.nh +.TH "WFXCTL-JOB-DEL-TAGS" "1" "Dec 2024" "" "" + +.SH NAME +.PP +wfxctl-job-del-tags - Delete tags from a job + + +.SH SYNOPSIS +.PP +\fBwfxctl job del-tags [flags]\fP + + +.SH DESCRIPTION +.PP +Delete tags from a job + + +.SH OPTIONS +.PP +\fB-h\fP, \fB--help\fP[=false] + help for del-tags + +.PP +\fB--id\fP="" + job id + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB--client-host\fP="localhost" + host + +.PP +\fB--client-port\fP=8080 + port + +.PP +\fB--client-tls-host\fP="localhost" + TLS host + +.PP +\fB--client-tls-port\fP=8443 + TLS port + +.PP +\fB--client-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--config\fP=[wfx.yml,/home/adlerm/.config/wfx/config.yml,/etc/wfx/wfx.yml] + path to one or more .yaml config files; if this option is not set, then the default paths are tried + +.PP +\fB--enable-tls\fP[=false] + whether to enable TLS (https) + +.PP +\fB--filter\fP="" + output filter (jq-expression). example: '.id' + +.PP +\fB--log-level\fP="info" + set log level. one of: trace,debug,info,warn,error,fatal,panic + +.PP +\fB--mgmt-host\fP="localhost" + management host + +.PP +\fB--mgmt-port\fP=8081 + management port + +.PP +\fB--mgmt-tls-host\fP="localhost" + management TLS host + +.PP +\fB--mgmt-tls-port\fP=8444 + management TLS port + +.PP +\fB--mgmt-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--raw\fP[=false] + output raw strings, not JSON texts; use --filter to select a single entity + +.PP +\fB--tls-ca\fP="" + ca bundle (PEM) + + +.SH EXAMPLE +.EX +wfxctl job del-tags --id=1 tag1 tag2 +.EE + + +.SH SEE ALSO +.PP +\fBwfxctl-job(1)\fP diff --git a/cmd/wfxctl/cmd/man/wfxctl-job-delete.1 b/cmd/wfxctl/cmd/man/wfxctl-job-delete.1 new file mode 100644 index 00000000..6dd85501 --- /dev/null +++ b/cmd/wfxctl/cmd/man/wfxctl-job-delete.1 @@ -0,0 +1,99 @@ +.nh +.TH "WFXCTL-JOB-DELETE" "1" "Dec 2024" "" "" + +.SH NAME +.PP +wfxctl-job-delete - Delete an existing job + + +.SH SYNOPSIS +.PP +\fBwfxctl job delete [flags]\fP + + +.SH DESCRIPTION +.PP +Delete an existing job + + +.SH OPTIONS +.PP +\fB-h\fP, \fB--help\fP[=false] + help for delete + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB--client-host\fP="localhost" + host + +.PP +\fB--client-port\fP=8080 + port + +.PP +\fB--client-tls-host\fP="localhost" + TLS host + +.PP +\fB--client-tls-port\fP=8443 + TLS port + +.PP +\fB--client-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--config\fP=[wfx.yml,/home/adlerm/.config/wfx/config.yml,/etc/wfx/wfx.yml] + path to one or more .yaml config files; if this option is not set, then the default paths are tried + +.PP +\fB--enable-tls\fP[=false] + whether to enable TLS (https) + +.PP +\fB--filter\fP="" + output filter (jq-expression). example: '.id' + +.PP +\fB--log-level\fP="info" + set log level. one of: trace,debug,info,warn,error,fatal,panic + +.PP +\fB--mgmt-host\fP="localhost" + management host + +.PP +\fB--mgmt-port\fP=8081 + management port + +.PP +\fB--mgmt-tls-host\fP="localhost" + management TLS host + +.PP +\fB--mgmt-tls-port\fP=8444 + management TLS port + +.PP +\fB--mgmt-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--raw\fP[=false] + output raw strings, not JSON texts; use --filter to select a single entity + +.PP +\fB--tls-ca\fP="" + ca bundle (PEM) + + +.SH EXAMPLE +.EX +wfxctl job delete 8ea1e9d7-28e6-4f1f-b444-a8d2d1ad7618 +.EE + + +.SH SEE ALSO +.PP +\fBwfxctl-job(1)\fP diff --git a/cmd/wfxctl/cmd/man/wfxctl-job-events.1 b/cmd/wfxctl/cmd/man/wfxctl-job-events.1 new file mode 100644 index 00000000..6d85bd57 --- /dev/null +++ b/cmd/wfxctl/cmd/man/wfxctl-job-events.1 @@ -0,0 +1,117 @@ +.nh +.TH "WFXCTL-JOB-EVENTS" "1" "Dec 2024" "" "" + +.SH NAME +.PP +wfxctl-job-events - Subscribe to job events + + +.SH SYNOPSIS +.PP +\fBwfxctl job events [flags]\fP + + +.SH DESCRIPTION +.PP +Subscribe to job events + + +.SH OPTIONS +.PP +\fB--client-id\fP=[] + client id filter + +.PP +\fB-h\fP, \fB--help\fP[=false] + help for events + +.PP +\fB--job-id\fP=[] + job id filter + +.PP +\fB--tag\fP=[] + tag filter + +.PP +\fB--workflow\fP=[] + workflow name filter + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB--client-host\fP="localhost" + host + +.PP +\fB--client-port\fP=8080 + port + +.PP +\fB--client-tls-host\fP="localhost" + TLS host + +.PP +\fB--client-tls-port\fP=8443 + TLS port + +.PP +\fB--client-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--config\fP=[wfx.yml,/home/adlerm/.config/wfx/config.yml,/etc/wfx/wfx.yml] + path to one or more .yaml config files; if this option is not set, then the default paths are tried + +.PP +\fB--enable-tls\fP[=false] + whether to enable TLS (https) + +.PP +\fB--filter\fP="" + output filter (jq-expression). example: '.id' + +.PP +\fB--log-level\fP="info" + set log level. one of: trace,debug,info,warn,error,fatal,panic + +.PP +\fB--mgmt-host\fP="localhost" + management host + +.PP +\fB--mgmt-port\fP=8081 + management port + +.PP +\fB--mgmt-tls-host\fP="localhost" + management TLS host + +.PP +\fB--mgmt-tls-port\fP=8444 + management TLS port + +.PP +\fB--mgmt-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--raw\fP[=false] + output raw strings, not JSON texts; use --filter to select a single entity + +.PP +\fB--tls-ca\fP="" + ca bundle (PEM) + + +.SH EXAMPLE +.EX + +wfxctl job events --job-id=1 --job-id=2 --client-id=foo + +.EE + + +.SH SEE ALSO +.PP +\fBwfxctl-job(1)\fP diff --git a/cmd/wfxctl/cmd/man/wfxctl-job-get-definition.1 b/cmd/wfxctl/cmd/man/wfxctl-job-get-definition.1 new file mode 100644 index 00000000..ac0d6500 --- /dev/null +++ b/cmd/wfxctl/cmd/man/wfxctl-job-get-definition.1 @@ -0,0 +1,105 @@ +.nh +.TH "WFXCTL-JOB-GET-DEFINITION" "1" "Dec 2024" "" "" + +.SH NAME +.PP +wfxctl-job-get-definition - Get definition of an existing job + + +.SH SYNOPSIS +.PP +\fBwfxctl job get-definition [flags]\fP + + +.SH DESCRIPTION +.PP +Get definition of an existing job + + +.SH OPTIONS +.PP +\fB-h\fP, \fB--help\fP[=false] + help for get-definition + +.PP +\fB--id\fP="" + job id + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB--client-host\fP="localhost" + host + +.PP +\fB--client-port\fP=8080 + port + +.PP +\fB--client-tls-host\fP="localhost" + TLS host + +.PP +\fB--client-tls-port\fP=8443 + TLS port + +.PP +\fB--client-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--config\fP=[wfx.yml,/home/adlerm/.config/wfx/config.yml,/etc/wfx/wfx.yml] + path to one or more .yaml config files; if this option is not set, then the default paths are tried + +.PP +\fB--enable-tls\fP[=false] + whether to enable TLS (https) + +.PP +\fB--filter\fP="" + output filter (jq-expression). example: '.id' + +.PP +\fB--log-level\fP="info" + set log level. one of: trace,debug,info,warn,error,fatal,panic + +.PP +\fB--mgmt-host\fP="localhost" + management host + +.PP +\fB--mgmt-port\fP=8081 + management port + +.PP +\fB--mgmt-tls-host\fP="localhost" + management TLS host + +.PP +\fB--mgmt-tls-port\fP=8444 + management TLS port + +.PP +\fB--mgmt-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--raw\fP[=false] + output raw strings, not JSON texts; use --filter to select a single entity + +.PP +\fB--tls-ca\fP="" + ca bundle (PEM) + + +.SH EXAMPLE +.EX + +wfxctl job get-definition --id=1 + +.EE + + +.SH SEE ALSO +.PP +\fBwfxctl-job(1)\fP diff --git a/cmd/wfxctl/cmd/man/wfxctl-job-get-status.1 b/cmd/wfxctl/cmd/man/wfxctl-job-get-status.1 new file mode 100644 index 00000000..f6b269ab --- /dev/null +++ b/cmd/wfxctl/cmd/man/wfxctl-job-get-status.1 @@ -0,0 +1,105 @@ +.nh +.TH "WFXCTL-JOB-GET-STATUS" "1" "Dec 2024" "" "" + +.SH NAME +.PP +wfxctl-job-get-status - Get status of an existing job + + +.SH SYNOPSIS +.PP +\fBwfxctl job get-status [flags]\fP + + +.SH DESCRIPTION +.PP +Get status of an existing job + + +.SH OPTIONS +.PP +\fB-h\fP, \fB--help\fP[=false] + help for get-status + +.PP +\fB--id\fP="" + job id + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB--client-host\fP="localhost" + host + +.PP +\fB--client-port\fP=8080 + port + +.PP +\fB--client-tls-host\fP="localhost" + TLS host + +.PP +\fB--client-tls-port\fP=8443 + TLS port + +.PP +\fB--client-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--config\fP=[wfx.yml,/home/adlerm/.config/wfx/config.yml,/etc/wfx/wfx.yml] + path to one or more .yaml config files; if this option is not set, then the default paths are tried + +.PP +\fB--enable-tls\fP[=false] + whether to enable TLS (https) + +.PP +\fB--filter\fP="" + output filter (jq-expression). example: '.id' + +.PP +\fB--log-level\fP="info" + set log level. one of: trace,debug,info,warn,error,fatal,panic + +.PP +\fB--mgmt-host\fP="localhost" + management host + +.PP +\fB--mgmt-port\fP=8081 + management port + +.PP +\fB--mgmt-tls-host\fP="localhost" + management TLS host + +.PP +\fB--mgmt-tls-port\fP=8444 + management TLS port + +.PP +\fB--mgmt-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--raw\fP[=false] + output raw strings, not JSON texts; use --filter to select a single entity + +.PP +\fB--tls-ca\fP="" + ca bundle (PEM) + + +.SH EXAMPLE +.EX + +wfxctl job get-status --id=1 + +.EE + + +.SH SEE ALSO +.PP +\fBwfxctl-job(1)\fP diff --git a/cmd/wfxctl/cmd/man/wfxctl-job-get-tags.1 b/cmd/wfxctl/cmd/man/wfxctl-job-get-tags.1 new file mode 100644 index 00000000..f0f60be8 --- /dev/null +++ b/cmd/wfxctl/cmd/man/wfxctl-job-get-tags.1 @@ -0,0 +1,103 @@ +.nh +.TH "WFXCTL-JOB-GET-TAGS" "1" "Dec 2024" "" "" + +.SH NAME +.PP +wfxctl-job-get-tags - Get tags of a job + + +.SH SYNOPSIS +.PP +\fBwfxctl job get-tags [flags]\fP + + +.SH DESCRIPTION +.PP +Get tags of a job + + +.SH OPTIONS +.PP +\fB-h\fP, \fB--help\fP[=false] + help for get-tags + +.PP +\fB--id\fP="" + job id + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB--client-host\fP="localhost" + host + +.PP +\fB--client-port\fP=8080 + port + +.PP +\fB--client-tls-host\fP="localhost" + TLS host + +.PP +\fB--client-tls-port\fP=8443 + TLS port + +.PP +\fB--client-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--config\fP=[wfx.yml,/home/adlerm/.config/wfx/config.yml,/etc/wfx/wfx.yml] + path to one or more .yaml config files; if this option is not set, then the default paths are tried + +.PP +\fB--enable-tls\fP[=false] + whether to enable TLS (https) + +.PP +\fB--filter\fP="" + output filter (jq-expression). example: '.id' + +.PP +\fB--log-level\fP="info" + set log level. one of: trace,debug,info,warn,error,fatal,panic + +.PP +\fB--mgmt-host\fP="localhost" + management host + +.PP +\fB--mgmt-port\fP=8081 + management port + +.PP +\fB--mgmt-tls-host\fP="localhost" + management TLS host + +.PP +\fB--mgmt-tls-port\fP=8444 + management TLS port + +.PP +\fB--mgmt-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--raw\fP[=false] + output raw strings, not JSON texts; use --filter to select a single entity + +.PP +\fB--tls-ca\fP="" + ca bundle (PEM) + + +.SH EXAMPLE +.EX +wfxctl job get-tags --id=1 +.EE + + +.SH SEE ALSO +.PP +\fBwfxctl-job(1)\fP diff --git a/cmd/wfxctl/cmd/man/wfxctl-job-get.1 b/cmd/wfxctl/cmd/man/wfxctl-job-get.1 new file mode 100644 index 00000000..571fb027 --- /dev/null +++ b/cmd/wfxctl/cmd/man/wfxctl-job-get.1 @@ -0,0 +1,109 @@ +.nh +.TH "WFXCTL-JOB-GET" "1" "Dec 2024" "" "" + +.SH NAME +.PP +wfxctl-job-get - Get an existing job + + +.SH SYNOPSIS +.PP +\fBwfxctl job get [flags]\fP + + +.SH DESCRIPTION +.PP +Get an existing job. + + +.SH OPTIONS +.PP +\fB-h\fP, \fB--help\fP[=false] + help for get + +.PP +\fB--history\fP[=false] + whether to fetch the job history + +.PP +\fB--id\fP="" + id of the job to be fetched + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB--client-host\fP="localhost" + host + +.PP +\fB--client-port\fP=8080 + port + +.PP +\fB--client-tls-host\fP="localhost" + TLS host + +.PP +\fB--client-tls-port\fP=8443 + TLS port + +.PP +\fB--client-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--config\fP=[wfx.yml,/home/adlerm/.config/wfx/config.yml,/etc/wfx/wfx.yml] + path to one or more .yaml config files; if this option is not set, then the default paths are tried + +.PP +\fB--enable-tls\fP[=false] + whether to enable TLS (https) + +.PP +\fB--filter\fP="" + output filter (jq-expression). example: '.id' + +.PP +\fB--log-level\fP="info" + set log level. one of: trace,debug,info,warn,error,fatal,panic + +.PP +\fB--mgmt-host\fP="localhost" + management host + +.PP +\fB--mgmt-port\fP=8081 + management port + +.PP +\fB--mgmt-tls-host\fP="localhost" + management TLS host + +.PP +\fB--mgmt-tls-port\fP=8444 + management TLS port + +.PP +\fB--mgmt-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--raw\fP[=false] + output raw strings, not JSON texts; use --filter to select a single entity + +.PP +\fB--tls-ca\fP="" + ca bundle (PEM) + + +.SH EXAMPLE +.EX + +wfxctl job get --id=1 + +.EE + + +.SH SEE ALSO +.PP +\fBwfxctl-job(1)\fP diff --git a/cmd/wfxctl/cmd/man/wfxctl-job-query.1 b/cmd/wfxctl/cmd/man/wfxctl-job-query.1 new file mode 100644 index 00000000..35c8711b --- /dev/null +++ b/cmd/wfxctl/cmd/man/wfxctl-job-query.1 @@ -0,0 +1,133 @@ +.nh +.TH "WFXCTL-JOB-QUERY" "1" "Dec 2024" "" "" + +.SH NAME +.PP +wfxctl-job-query - Query existing jobs + + +.SH SYNOPSIS +.PP +\fBwfxctl job query [flags]\fP + + +.SH DESCRIPTION +.PP +Query existing jobs + + +.SH OPTIONS +.PP +\fB--client-id\fP="" + Filter jobs belonging to a specific client with clientId + +.PP +\fB--group\fP=[] + Filter jobs based on the group they belong to + +.PP +\fB-h\fP, \fB--help\fP[=false] + help for query + +.PP +\fB--limit\fP=10 + maximum number of elements returned in one page + +.PP +\fB--offset\fP=0 + 0-based index of the page + +.PP +\fB--sort\fP="" + sort order. possible values: asc, desc + +.PP +\fB--state\fP="" + Filter jobs based on the current state value + +.PP +\fB--tag\fP=[] + Filter jobs by tags + +.PP +\fB--workflow\fP="" + Filter jobs based on workflow name + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB--client-host\fP="localhost" + host + +.PP +\fB--client-port\fP=8080 + port + +.PP +\fB--client-tls-host\fP="localhost" + TLS host + +.PP +\fB--client-tls-port\fP=8443 + TLS port + +.PP +\fB--client-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--config\fP=[wfx.yml,/home/adlerm/.config/wfx/config.yml,/etc/wfx/wfx.yml] + path to one or more .yaml config files; if this option is not set, then the default paths are tried + +.PP +\fB--enable-tls\fP[=false] + whether to enable TLS (https) + +.PP +\fB--filter\fP="" + output filter (jq-expression). example: '.id' + +.PP +\fB--log-level\fP="info" + set log level. one of: trace,debug,info,warn,error,fatal,panic + +.PP +\fB--mgmt-host\fP="localhost" + management host + +.PP +\fB--mgmt-port\fP=8081 + management port + +.PP +\fB--mgmt-tls-host\fP="localhost" + management TLS host + +.PP +\fB--mgmt-tls-port\fP=8444 + management TLS port + +.PP +\fB--mgmt-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--raw\fP[=false] + output raw strings, not JSON texts; use --filter to select a single entity + +.PP +\fB--tls-ca\fP="" + ca bundle (PEM) + + +.SH EXAMPLE +.EX + +wfxctl job query --state=CREATED + +.EE + + +.SH SEE ALSO +.PP +\fBwfxctl-job(1)\fP diff --git a/cmd/wfxctl/cmd/man/wfxctl-job-update-definition.1 b/cmd/wfxctl/cmd/man/wfxctl-job-update-definition.1 new file mode 100644 index 00000000..a7c11393 --- /dev/null +++ b/cmd/wfxctl/cmd/man/wfxctl-job-update-definition.1 @@ -0,0 +1,105 @@ +.nh +.TH "WFXCTL-JOB-UPDATE-DEFINITION" "1" "Dec 2024" "" "" + +.SH NAME +.PP +wfxctl-job-update-definition - Update job definition + + +.SH SYNOPSIS +.PP +\fBwfxctl job update-definition [flags]\fP + + +.SH DESCRIPTION +.PP +Update definition of an existing job using data provided via stdin + + +.SH OPTIONS +.PP +\fB-h\fP, \fB--help\fP[=false] + help for update-definition + +.PP +\fB--id\fP="" + job id + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB--client-host\fP="localhost" + host + +.PP +\fB--client-port\fP=8080 + port + +.PP +\fB--client-tls-host\fP="localhost" + TLS host + +.PP +\fB--client-tls-port\fP=8443 + TLS port + +.PP +\fB--client-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--config\fP=[wfx.yml,/home/adlerm/.config/wfx/config.yml,/etc/wfx/wfx.yml] + path to one or more .yaml config files; if this option is not set, then the default paths are tried + +.PP +\fB--enable-tls\fP[=false] + whether to enable TLS (https) + +.PP +\fB--filter\fP="" + output filter (jq-expression). example: '.id' + +.PP +\fB--log-level\fP="info" + set log level. one of: trace,debug,info,warn,error,fatal,panic + +.PP +\fB--mgmt-host\fP="localhost" + management host + +.PP +\fB--mgmt-port\fP=8081 + management port + +.PP +\fB--mgmt-tls-host\fP="localhost" + management TLS host + +.PP +\fB--mgmt-tls-port\fP=8444 + management TLS port + +.PP +\fB--mgmt-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--raw\fP[=false] + output raw strings, not JSON texts; use --filter to select a single entity + +.PP +\fB--tls-ca\fP="" + ca bundle (PEM) + + +.SH EXAMPLE +.EX + +wfxctl job update-definition + +.EE + + +.SH SEE ALSO +.PP +\fBwfxctl-job(1)\fP diff --git a/cmd/wfxctl/cmd/man/wfxctl-job-update-status.1 b/cmd/wfxctl/cmd/man/wfxctl-job-update-status.1 new file mode 100644 index 00000000..7031d4a1 --- /dev/null +++ b/cmd/wfxctl/cmd/man/wfxctl-job-update-status.1 @@ -0,0 +1,125 @@ +.nh +.TH "WFXCTL-JOB-UPDATE-STATUS" "1" "Dec 2024" "" "" + +.SH NAME +.PP +wfxctl-job-update-status - Update job status + + +.SH SYNOPSIS +.PP +\fBwfxctl job update-status [flags]\fP + + +.SH DESCRIPTION +.PP +Update job status of an existing job + + +.SH OPTIONS +.PP +\fB--actor\fP="CLIENT" + actor to use (eligible) + +.PP +\fB--client-id\fP="" + client which sends the update + +.PP +\fB-h\fP, \fB--help\fP[=false] + help for update-status + +.PP +\fB--id\fP="" + job which shall be updated + +.PP +\fB--message\fP="" + status message / info, free text from client + +.PP +\fB--progress\fP=0 + progress value (0 <= progress <= 100) + +.PP +\fB--state\fP="" + Name of the new state + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB--client-host\fP="localhost" + host + +.PP +\fB--client-port\fP=8080 + port + +.PP +\fB--client-tls-host\fP="localhost" + TLS host + +.PP +\fB--client-tls-port\fP=8443 + TLS port + +.PP +\fB--client-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--config\fP=[wfx.yml,/home/adlerm/.config/wfx/config.yml,/etc/wfx/wfx.yml] + path to one or more .yaml config files; if this option is not set, then the default paths are tried + +.PP +\fB--enable-tls\fP[=false] + whether to enable TLS (https) + +.PP +\fB--filter\fP="" + output filter (jq-expression). example: '.id' + +.PP +\fB--log-level\fP="info" + set log level. one of: trace,debug,info,warn,error,fatal,panic + +.PP +\fB--mgmt-host\fP="localhost" + management host + +.PP +\fB--mgmt-port\fP=8081 + management port + +.PP +\fB--mgmt-tls-host\fP="localhost" + management TLS host + +.PP +\fB--mgmt-tls-port\fP=8444 + management TLS port + +.PP +\fB--mgmt-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--raw\fP[=false] + output raw strings, not JSON texts; use --filter to select a single entity + +.PP +\fB--tls-ca\fP="" + ca bundle (PEM) + + +.SH EXAMPLE +.EX + +wfxctl job update-status --id=1 --client-id=client42 --state=DOWNLOAD + +.EE + + +.SH SEE ALSO +.PP +\fBwfxctl-job(1)\fP diff --git a/cmd/wfxctl/cmd/man/wfxctl-job.1 b/cmd/wfxctl/cmd/man/wfxctl-job.1 new file mode 100644 index 00000000..1ddce0e0 --- /dev/null +++ b/cmd/wfxctl/cmd/man/wfxctl-job.1 @@ -0,0 +1,93 @@ +.nh +.TH "WFXCTL-JOB" "1" "Dec 2024" "" "" + +.SH NAME +.PP +wfxctl-job - manage jobs + + +.SH SYNOPSIS +.PP +\fBwfxctl job [flags]\fP + + +.SH DESCRIPTION +.PP +subcommand to manage jobs (CRUD) + + +.SH OPTIONS +.PP +\fB-h\fP, \fB--help\fP[=false] + help for job + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB--client-host\fP="localhost" + host + +.PP +\fB--client-port\fP=8080 + port + +.PP +\fB--client-tls-host\fP="localhost" + TLS host + +.PP +\fB--client-tls-port\fP=8443 + TLS port + +.PP +\fB--client-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--config\fP=[wfx.yml,/home/adlerm/.config/wfx/config.yml,/etc/wfx/wfx.yml] + path to one or more .yaml config files; if this option is not set, then the default paths are tried + +.PP +\fB--enable-tls\fP[=false] + whether to enable TLS (https) + +.PP +\fB--filter\fP="" + output filter (jq-expression). example: '.id' + +.PP +\fB--log-level\fP="info" + set log level. one of: trace,debug,info,warn,error,fatal,panic + +.PP +\fB--mgmt-host\fP="localhost" + management host + +.PP +\fB--mgmt-port\fP=8081 + management port + +.PP +\fB--mgmt-tls-host\fP="localhost" + management TLS host + +.PP +\fB--mgmt-tls-port\fP=8444 + management TLS port + +.PP +\fB--mgmt-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--raw\fP[=false] + output raw strings, not JSON texts; use --filter to select a single entity + +.PP +\fB--tls-ca\fP="" + ca bundle (PEM) + + +.SH SEE ALSO +.PP +\fBwfxctl(1)\fP, \fBwfxctl-job-add-tags(1)\fP, \fBwfxctl-job-create(1)\fP, \fBwfxctl-job-del-tags(1)\fP, \fBwfxctl-job-delete(1)\fP, \fBwfxctl-job-events(1)\fP, \fBwfxctl-job-get(1)\fP, \fBwfxctl-job-get-definition(1)\fP, \fBwfxctl-job-get-status(1)\fP, \fBwfxctl-job-get-tags(1)\fP, \fBwfxctl-job-query(1)\fP, \fBwfxctl-job-update-definition(1)\fP, \fBwfxctl-job-update-status(1)\fP diff --git a/cmd/wfxctl/cmd/man/wfxctl-man.1 b/cmd/wfxctl/cmd/man/wfxctl-man.1 new file mode 100644 index 00000000..d64e84f7 --- /dev/null +++ b/cmd/wfxctl/cmd/man/wfxctl-man.1 @@ -0,0 +1,97 @@ +.nh +.TH "WFXCTL-MAN" "1" "Dec 2024" "" "" + +.SH NAME +.PP +wfxctl-man - Generate man pages and exit + + +.SH SYNOPSIS +.PP +\fBwfxctl man [flags]\fP + + +.SH DESCRIPTION +.PP +Generate man pages and exit + + +.SH OPTIONS +.PP +\fB--dir\fP="man" + directory to store the man page files + +.PP +\fB-h\fP, \fB--help\fP[=false] + help for man + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB--client-host\fP="localhost" + host + +.PP +\fB--client-port\fP=8080 + port + +.PP +\fB--client-tls-host\fP="localhost" + TLS host + +.PP +\fB--client-tls-port\fP=8443 + TLS port + +.PP +\fB--client-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--config\fP=[wfx.yml,/home/adlerm/.config/wfx/config.yml,/etc/wfx/wfx.yml] + path to one or more .yaml config files; if this option is not set, then the default paths are tried + +.PP +\fB--enable-tls\fP[=false] + whether to enable TLS (https) + +.PP +\fB--filter\fP="" + output filter (jq-expression). example: '.id' + +.PP +\fB--log-level\fP="info" + set log level. one of: trace,debug,info,warn,error,fatal,panic + +.PP +\fB--mgmt-host\fP="localhost" + management host + +.PP +\fB--mgmt-port\fP=8081 + management port + +.PP +\fB--mgmt-tls-host\fP="localhost" + management TLS host + +.PP +\fB--mgmt-tls-port\fP=8444 + management TLS port + +.PP +\fB--mgmt-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--raw\fP[=false] + output raw strings, not JSON texts; use --filter to select a single entity + +.PP +\fB--tls-ca\fP="" + ca bundle (PEM) + + +.SH SEE ALSO +.PP +\fBwfxctl(1)\fP diff --git a/cmd/wfxctl/cmd/man/wfxctl-version.1 b/cmd/wfxctl/cmd/man/wfxctl-version.1 new file mode 100644 index 00000000..6199ac97 --- /dev/null +++ b/cmd/wfxctl/cmd/man/wfxctl-version.1 @@ -0,0 +1,93 @@ +.nh +.TH "WFXCTL-VERSION" "1" "Dec 2024" "" "" + +.SH NAME +.PP +wfxctl-version - Retrieve version of wfx + + +.SH SYNOPSIS +.PP +\fBwfxctl version [flags]\fP + + +.SH DESCRIPTION +.PP +Retrieve version of wfx + + +.SH OPTIONS +.PP +\fB-h\fP, \fB--help\fP[=false] + help for version + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB--client-host\fP="localhost" + host + +.PP +\fB--client-port\fP=8080 + port + +.PP +\fB--client-tls-host\fP="localhost" + TLS host + +.PP +\fB--client-tls-port\fP=8443 + TLS port + +.PP +\fB--client-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--config\fP=[wfx.yml,/home/adlerm/.config/wfx/config.yml,/etc/wfx/wfx.yml] + path to one or more .yaml config files; if this option is not set, then the default paths are tried + +.PP +\fB--enable-tls\fP[=false] + whether to enable TLS (https) + +.PP +\fB--filter\fP="" + output filter (jq-expression). example: '.id' + +.PP +\fB--log-level\fP="info" + set log level. one of: trace,debug,info,warn,error,fatal,panic + +.PP +\fB--mgmt-host\fP="localhost" + management host + +.PP +\fB--mgmt-port\fP=8081 + management port + +.PP +\fB--mgmt-tls-host\fP="localhost" + management TLS host + +.PP +\fB--mgmt-tls-port\fP=8444 + management TLS port + +.PP +\fB--mgmt-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--raw\fP[=false] + output raw strings, not JSON texts; use --filter to select a single entity + +.PP +\fB--tls-ca\fP="" + ca bundle (PEM) + + +.SH SEE ALSO +.PP +\fBwfxctl(1)\fP diff --git a/cmd/wfxctl/cmd/man/wfxctl-workflow-create.1 b/cmd/wfxctl/cmd/man/wfxctl-workflow-create.1 new file mode 100644 index 00000000..fadcaf55 --- /dev/null +++ b/cmd/wfxctl/cmd/man/wfxctl-workflow-create.1 @@ -0,0 +1,126 @@ +.nh +.TH "WFXCTL-WORKFLOW-CREATE" "1" "Dec 2024" "" "" + +.SH NAME +.PP +wfxctl-workflow-create - Create a new workflow + + +.SH SYNOPSIS +.PP +\fBwfxctl workflow create [flags]\fP + + +.SH DESCRIPTION +.PP +Create a new workflow. The workflow must be in YAML format. + + +.SH OPTIONS +.PP +\fB-h\fP, \fB--help\fP[=false] + help for create + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB--client-host\fP="localhost" + host + +.PP +\fB--client-port\fP=8080 + port + +.PP +\fB--client-tls-host\fP="localhost" + TLS host + +.PP +\fB--client-tls-port\fP=8443 + TLS port + +.PP +\fB--client-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--config\fP=[wfx.yml,/home/adlerm/.config/wfx/config.yml,/etc/wfx/wfx.yml] + path to one or more .yaml config files; if this option is not set, then the default paths are tried + +.PP +\fB--enable-tls\fP[=false] + whether to enable TLS (https) + +.PP +\fB--filter\fP="" + output filter (jq-expression). example: '.id' + +.PP +\fB--log-level\fP="info" + set log level. one of: trace,debug,info,warn,error,fatal,panic + +.PP +\fB--mgmt-host\fP="localhost" + management host + +.PP +\fB--mgmt-port\fP=8081 + management port + +.PP +\fB--mgmt-tls-host\fP="localhost" + management TLS host + +.PP +\fB--mgmt-tls-port\fP=8444 + management TLS port + +.PP +\fB--mgmt-unix-socket\fP="" + connect via the given unix-domain socket (if set, this overrides http/tls) + +.PP +\fB--raw\fP[=false] + output raw strings, not JSON texts; use --filter to select a single entity + +.PP +\fB--tls-ca\fP="" + ca bundle (PEM) + + +.SH EXAMPLE +.EX + +cat < 0 { - return fmt.Errorf("failed to delete workflows: %s", strings.Join(failedWfs, ",")) - } - return nil - }, + return nil + }, + } } diff --git a/cmd/wfxctl/cmd/workflow/delete/delete_test.go b/cmd/wfxctl/cmd/workflow/delete/delete_test.go index 8bce8d65..add50dd7 100644 --- a/cmd/wfxctl/cmd/workflow/delete/delete_test.go +++ b/cmd/wfxctl/cmd/workflow/delete/delete_test.go @@ -12,11 +12,10 @@ import ( "net/http" "net/http/httptest" "net/url" - "strconv" "testing" - "github.com/siemens/wfx/cmd/wfxctl/flags" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestDeleteWorkflow(t *testing.T) { @@ -32,14 +31,14 @@ func TestDeleteWorkflow(t *testing.T) { defer ts.Close() u, _ := url.Parse(ts.URL) - _ = flags.Koanf.Set(flags.MgmtHostFlag, u.Hostname()) - port, _ := strconv.Atoi(u.Port()) - _ = flags.Koanf.Set(flags.MgmtPortFlag, port) + t.Setenv("WFX_MGMT_HOST", u.Hostname()) + t.Setenv("WFX_MGMT_PORT", u.Port()) - Command.SetArgs([]string{"wfx.workflow.dau.direct"}) + cmd := NewCommand() + cmd.SetArgs([]string{"wfx.workflow.dau.direct"}) - err := Command.Execute() - assert.NoError(t, err) + err := cmd.Execute() + require.NoError(t, err) assert.Equal(t, expectedPath, actualPath) } diff --git a/cmd/wfxctl/cmd/workflow/get/get.go b/cmd/wfxctl/cmd/workflow/get/get.go index 92dc3052..d59959a4 100644 --- a/cmd/wfxctl/cmd/workflow/get/get.go +++ b/cmd/wfxctl/cmd/workflow/get/get.go @@ -9,47 +9,37 @@ package get */ import ( - "github.com/rs/zerolog/log" + "errors" + + "github.com/Southclaws/fault" "github.com/spf13/cobra" "github.com/siemens/wfx/cmd/wfxctl/errutil" "github.com/siemens/wfx/cmd/wfxctl/flags" - "github.com/siemens/wfx/generated/client/workflows" -) - -const ( - nameFlag = ("name") ) -func init() { - f := Command.PersistentFlags() - f.String(nameFlag, "", "workflow name") -} - -var Command = &cobra.Command{ - Use: "get", - Short: "Get an existing workflow", - Long: `Get an existing workflow`, - Example: "wfxctl workflow get --name=wfx.workflow.kanban", - TraverseChildren: true, - Run: func(cmd *cobra.Command, _ []string) { - baseCmd := flags.NewBaseCmd() - client := errutil.Must(baseCmd.CreateHTTPClient()) - params := workflows.NewGetWorkflowsNameParams(). - WithHTTPClient(client). - WithName(flags.Koanf.String(nameFlag)) - - if params.Name == "" { - log.Fatal().Msg("No workflow name provided") - } - - resp, err := baseCmd.CreateMgmtClient().Workflows.GetWorkflowsName(params) - if err != nil { - errutil.ProcessErrorResponse(cmd.OutOrStderr(), err) - log.Fatal().Msg("Failed to get workflow") - } - if err := baseCmd.DumpResponse(cmd.OutOrStdout(), resp.GetPayload()); err != nil { - log.Fatal().Err(err).Msg("Failed to dump response") - } - }, +func NewCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "get", + Short: "Get an existing workflow", + Long: `Get an existing workflow`, + Example: "wfxctl workflow get --name=wfx.workflow.kanban", + TraverseChildren: true, + RunE: func(cmd *cobra.Command, _ []string) error { + baseCmd := flags.NewBaseCmd(cmd.Flags()) + name := baseCmd.Name + if name == "" { + return errors.New("workflow name missing") + } + client := errutil.Must(baseCmd.CreateClient()) + resp, err := client.GetWorkflowsName(cmd.Context(), name, nil) + if err != nil { + return fault.Wrap(err) + } + return fault.Wrap(baseCmd.ProcessResponse(resp, cmd.OutOrStdout())) + }, + } + f := cmd.PersistentFlags() + f.String(flags.NameFlag, "", "workflow name") + return cmd } diff --git a/cmd/wfxctl/cmd/workflow/get/get_test.go b/cmd/wfxctl/cmd/workflow/get/get_test.go index bca215e3..f2d1382b 100644 --- a/cmd/wfxctl/cmd/workflow/get/get_test.go +++ b/cmd/wfxctl/cmd/workflow/get/get_test.go @@ -13,12 +13,12 @@ import ( "net/http" "net/http/httptest" "net/url" - "strconv" "testing" "github.com/siemens/wfx/cmd/wfxctl/flags" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetWorkflow(t *testing.T) { @@ -27,25 +27,24 @@ func TestGetWorkflow(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { name := "test" - wf := model.Workflow{Name: name} + wf := api.Workflow{Name: name} actualPath = r.URL.Path w.Header().Add("Content-Type", "application/json") w.WriteHeader(http.StatusOK) - model, _ := json.Marshal(wf) - _, _ = w.Write(model) + _ = json.NewEncoder(w).Encode(wf) })) defer ts.Close() u, _ := url.Parse(ts.URL) - _ = flags.Koanf.Set(flags.MgmtHostFlag, u.Hostname()) - port, _ := strconv.Atoi(u.Port()) + t.Setenv("WFX_CLIENT_HOST", u.Hostname()) + t.Setenv("WFX_CLIENT_PORT", u.Port()) - _ = flags.Koanf.Set(flags.MgmtPortFlag, port) - _ = flags.Koanf.Set(nameFlag, "test") + cmd := NewCommand() + cmd.SetArgs([]string{"--" + flags.NameFlag, "test"}) - err := Command.Execute() - assert.NoError(t, err) + err := cmd.Execute() + require.NoError(t, err) assert.Equal(t, expectedPath, actualPath) } diff --git a/cmd/wfxctl/cmd/workflow/query/query.go b/cmd/wfxctl/cmd/workflow/query/query.go index 6109f1e9..c543b9d5 100644 --- a/cmd/wfxctl/cmd/workflow/query/query.go +++ b/cmd/wfxctl/cmd/workflow/query/query.go @@ -9,53 +9,49 @@ package query */ import ( - "github.com/rs/zerolog/log" + "github.com/Southclaws/fault" "github.com/spf13/cobra" "github.com/siemens/wfx/cmd/wfxctl/errutil" "github.com/siemens/wfx/cmd/wfxctl/flags" - "github.com/siemens/wfx/generated/client/workflows" + "github.com/siemens/wfx/generated/api" ) -const ( - offsetFlag = "offset" - limitFlag = "limit" -) - -func init() { - flags := Command.PersistentFlags() - - flags.Int32(offsetFlag, 0, "the number of items to skip before starting to return results") - flags.Int32(limitFlag, 10, "the maximum number of items to return") -} - -var Command = &cobra.Command{ - Use: "query", - Short: "Query existing workflows", - Long: `Query existing workflows`, - Example: ` +func NewCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "query", + Short: "Query existing workflows", + Long: `Query existing workflows`, + Example: ` wfxctl workflow query `, - TraverseChildren: true, - Run: func(cmd *cobra.Command, _ []string) { - baseCmd := flags.NewBaseCmd() - - offset := flags.Koanf.Int64(offsetFlag) - limit := int32(flags.Koanf.Int(limitFlag)) - - client := errutil.Must(baseCmd.CreateHTTPClient()) - params := workflows.NewGetWorkflowsParams(). - WithHTTPClient(client). - WithOffset(&offset). - WithLimit(&limit) - - resp, err := baseCmd.CreateClient().Workflows.GetWorkflows(params) - if err != nil { - errutil.ProcessErrorResponse(cmd.OutOrStderr(), err) - log.Fatal().Msg("Failed to query workflows") - } - if err := baseCmd.DumpResponse(cmd.OutOrStdout(), resp.GetPayload()); err != nil { - log.Fatal().Err(err).Msg("Failed to dump response") - } - }, + TraverseChildren: true, + RunE: func(cmd *cobra.Command, _ []string) error { + baseCmd := flags.NewBaseCmd(cmd.Flags()) + + params := new(api.GetWorkflowsParams) + params.ParamOffset = &baseCmd.Offset + params.ParamLimit = &baseCmd.Limit + + { + var err error + params.ParamSort, err = baseCmd.SortParam() + if err != nil { + return fault.Wrap(err) + } + } + + client := errutil.Must(baseCmd.CreateClient()) + resp, err := client.GetWorkflows(cmd.Context(), params) + if err != nil { + return fault.Wrap(err) + } + return fault.Wrap(baseCmd.ProcessResponse(resp, cmd.OutOrStdout())) + }, + } + f := cmd.PersistentFlags() + f.Int64(flags.OffsetFlag, 0, "the number of items to skip before starting to return results") + f.Int32(flags.LimitFlag, 10, "the maximum number of items to return") + f.String(flags.SortFlag, "", "sort order. possible values: asc, desc") + return cmd } diff --git a/cmd/wfxctl/cmd/workflow/query/query_test.go b/cmd/wfxctl/cmd/workflow/query/query_test.go index 4b58da6d..d68c6209 100644 --- a/cmd/wfxctl/cmd/workflow/query/query_test.go +++ b/cmd/wfxctl/cmd/workflow/query/query_test.go @@ -12,7 +12,6 @@ import ( "net/http" "net/http/httptest" "net/url" - "strconv" "testing" "github.com/siemens/wfx/cmd/wfxctl/flags" @@ -35,14 +34,12 @@ func TestQueryWorkflows(t *testing.T) { defer ts.Close() u, _ := url.Parse(ts.URL) - _ = flags.Koanf.Set(flags.ClientHostFlag, u.Hostname()) - port, _ := strconv.Atoi(u.Port()) - _ = flags.Koanf.Set(flags.ClientPortFlag, port) + t.Setenv("WFX_CLIENT_HOST", u.Hostname()) + t.Setenv("WFX_CLIENT_PORT", u.Port()) - _ = flags.Koanf.Set(offsetFlag, 0) - _ = flags.Koanf.Set(limitFlag, 10) - - err := Command.Execute() + cmd := NewCommand() + cmd.SetArgs([]string{"--" + flags.OffsetFlag, "0", "--" + flags.LimitFlag, "10"}) + err := cmd.Execute() assert.NoError(t, err) assert.Equal(t, expectedPath, actualPath) diff --git a/cmd/wfxctl/cmd/workflow/validate/validate.go b/cmd/wfxctl/cmd/workflow/validate/validate.go index 7a635a4f..e75f9a02 100644 --- a/cmd/wfxctl/cmd/workflow/validate/validate.go +++ b/cmd/wfxctl/cmd/workflow/validate/validate.go @@ -19,42 +19,29 @@ import ( "github.com/spf13/cobra" "gopkg.in/yaml.v3" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/workflow" ) -var Command = &cobra.Command{ - Use: "validate", - Short: "Validate a workflow", - Long: "Offline validation of a workflow", - Example: ` +func NewCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "validate", + Short: "Validate a workflow", + Long: "Offline validation of a workflow", + Example: ` wfxctl workflow validate wfx.workflow.dau.direct.yml `, - TraverseChildren: true, - Args: cobra.OnlyValidArgs, - ValidArgsFunction: func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) { - return []string{"yaml", "yml"}, cobra.ShellCompDirectiveFilterFileExt - }, - RunE: func(cmd *cobra.Command, args []string) error { - allWorkflows := make([]*model.Workflow, 0, len(args)) - n := len(args) - if n == 1 && args[0] == "-" { - log.Debug().Msg("Reading workflow from stdin...") - b, err := io.ReadAll(cmd.InOrStdin()) - if err != nil { - return fault.Wrap(err) - } - wf, err := unmarshal(b) - if err != nil { - return fault.Wrap(err) - } - allWorkflows = append(allWorkflows, wf) - } else { - if n == 0 { - return errors.New("workflow must be provided either via file or stdin") - } - for _, fname := range args { - b, err := os.ReadFile(fname) + TraverseChildren: true, + Args: cobra.OnlyValidArgs, + ValidArgsFunction: func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) { + return []string{"yaml", "yml"}, cobra.ShellCompDirectiveFilterFileExt + }, + RunE: func(cmd *cobra.Command, args []string) error { + allWorkflows := make([]*api.Workflow, 0, len(args)) + n := len(args) + if n == 1 && args[0] == "-" { + log.Debug().Msg("Reading workflow from stdin...") + b, err := io.ReadAll(cmd.InOrStdin()) if err != nil { return fault.Wrap(err) } @@ -63,25 +50,41 @@ wfxctl workflow validate wfx.workflow.dau.direct.yml return fault.Wrap(err) } allWorkflows = append(allWorkflows, wf) + } else { + if n == 0 { + return errors.New("workflow must be provided either via file or stdin") + } + for _, fname := range args { + b, err := os.ReadFile(fname) + if err != nil { + return fault.Wrap(err) + } + wf, err := unmarshal(b) + if err != nil { + return fault.Wrap(err) + } + allWorkflows = append(allWorkflows, wf) + } } - } - out := cmd.OutOrStdout() - for _, wf := range allWorkflows { - err := workflow.ValidateWorkflow(wf) - if err != nil { - fmt.Fprintln(out, "ERROR:", err) - } else { - fmt.Fprintln(out, wf.Name, ": OK") + out := cmd.OutOrStdout() + for _, wf := range allWorkflows { + err := workflow.ValidateWorkflow(wf) + if err != nil { + fmt.Fprintln(out, "ERROR:", err) + } else { + fmt.Fprintln(out, wf.Name, ": OK") + } } - } - return nil - }, + return nil + }, + } + return cmd } -func unmarshal(raw []byte) (*model.Workflow, error) { +func unmarshal(raw []byte) (*api.Workflow, error) { // try YAML - var wf model.Workflow + var wf api.Workflow err := yaml.Unmarshal(raw, &wf) if err != nil { return nil, fault.Wrap(err) diff --git a/cmd/wfxctl/cmd/workflow/validate/validate_test.go b/cmd/wfxctl/cmd/workflow/validate/validate_test.go index b3429caf..822bbe41 100644 --- a/cmd/wfxctl/cmd/workflow/validate/validate_test.go +++ b/cmd/wfxctl/cmd/workflow/validate/validate_test.go @@ -1,5 +1,13 @@ package validate +/* + * SPDX-FileCopyrightText: 2023 Siemens AG + * + * SPDX-License-Identifier: Apache-2.0 + * + * Author: Michael Adler + */ + import ( "bytes" "os" @@ -10,16 +18,8 @@ import ( "github.com/stretchr/testify/require" ) -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - func TestCommand_NoWorkflowGiven(t *testing.T) { - err := Command.Execute() + err := NewCommand().Execute() require.Error(t, err) assert.ErrorContains(t, err, "workflow must be provided either via file or stdin") } @@ -27,10 +27,10 @@ func TestCommand_NoWorkflowGiven(t *testing.T) { func TestCommand_Stdin(t *testing.T) { buf := new(bytes.Buffer) _, _ = buf.WriteString(dau.DirectYAML) - Command.SetIn(buf) - Command.SetArgs([]string{"-"}) - - err := Command.Execute() + cmd := NewCommand() + cmd.SetIn(buf) + cmd.SetArgs([]string{"-"}) + err := cmd.Execute() require.NoError(t, err) } @@ -40,8 +40,8 @@ func TestCommand_Fname(t *testing.T) { _ = tmpFile.Close() defer os.Remove(tmpFile.Name()) - Command.SetArgs([]string{tmpFile.Name()}) - - err := Command.Execute() + cmd := NewCommand() + cmd.SetArgs([]string{tmpFile.Name()}) + err := cmd.Execute() require.NoError(t, err) } diff --git a/cmd/wfxctl/cmd/workflow/workflow.go b/cmd/wfxctl/cmd/workflow/workflow.go index 9395484d..1fb8daf1 100644 --- a/cmd/wfxctl/cmd/workflow/workflow.go +++ b/cmd/wfxctl/cmd/workflow/workflow.go @@ -17,18 +17,18 @@ import ( "github.com/spf13/cobra" ) -var Command = &cobra.Command{ - Use: "workflow", - Short: "manage workflows", - Long: "subcommand to manage workflows (CRUD)", - TraverseChildren: true, - SilenceUsage: true, -} - -func init() { - Command.AddCommand(create.Command) - Command.AddCommand(delete.Command) - Command.AddCommand(get.Command) - Command.AddCommand(query.Command) - Command.AddCommand(validate.Command) +func NewCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "workflow", + Short: "manage workflows", + Long: "subcommand to manage workflows (CRUD)", + TraverseChildren: true, + SilenceUsage: true, + } + cmd.AddCommand(create.NewCommand()) + cmd.AddCommand(delete.NewCommand()) + cmd.AddCommand(get.NewCommand()) + cmd.AddCommand(query.NewCommand()) + cmd.AddCommand(validate.NewCommand()) + return cmd } diff --git a/cmd/wfxctl/cmd/workflow/workflow_test.go b/cmd/wfxctl/cmd/workflow/workflow_test.go index 6c2824d8..4c2f29c6 100644 --- a/cmd/wfxctl/cmd/workflow/workflow_test.go +++ b/cmd/wfxctl/cmd/workflow/workflow_test.go @@ -15,5 +15,5 @@ import ( ) func TestSubcommands(t *testing.T) { - assert.True(t, Command.HasSubCommands()) + assert.True(t, NewCommand().HasSubCommands()) } diff --git a/cmd/wfxctl/errutil/util.go b/cmd/wfxctl/errutil/util.go index 1eaabbc5..ae500441 100644 --- a/cmd/wfxctl/errutil/util.go +++ b/cmd/wfxctl/errutil/util.go @@ -9,53 +9,20 @@ package errutil */ import ( - "errors" "fmt" "io" - "reflect" "github.com/rs/zerolog/log" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" ) -type codeFn interface { - Code() int -} - // ProcessErrorResponse extracts the Payload from an ErrorResponse. -func ProcessErrorResponse(w io.Writer, err error) { - if errors := extractErrors(err); len(errors) > 0 { - for _, msg := range errors { +func ProcessErrorResponse(w io.Writer, resp api.ErrorResponse) { + if resp.Errors != nil { + for _, msg := range *resp.Errors { fmt.Fprintf(w, "ERROR: %s (code=%s, logref=%s)\n", msg.Message, msg.Code, msg.Logref) } - return - } - var fn codeFn - if errors.As(err, &fn) { - fmt.Fprintf(w, "ERROR: HTTP status %d\n", fn.Code()) - return - } - fmt.Fprintf(w, "ERROR: %s\n", err) -} - -func extractErrors(val any) []*model.Error { - /* The below code is the generalization of the following snippet - * and works for _all_ returned errors, since they all share the same structure thanks to the - * ErrorType in the OpenAPI spec: - - if resp, ok := err.(*jobs.PostJobsBadRequest); ok { - return resp.Payload.Errors - } - */ - var zeroValue reflect.Value - if value := reflect.ValueOf(val); value.Kind() == reflect.Ptr { - if field := value.Elem().FieldByName("Payload"); field != zeroValue { - if resp, ok := field.Interface().(*model.ErrorResponse); ok { - return resp.Errors - } - } } - return nil } // Must is a utility function that takes a value and an error as parameters and returns the value if the error is nil. diff --git a/cmd/wfxctl/errutil/util_test.go b/cmd/wfxctl/errutil/util_test.go index ec46cde2..5eb7b638 100644 --- a/cmd/wfxctl/errutil/util_test.go +++ b/cmd/wfxctl/errutil/util_test.go @@ -12,42 +12,31 @@ import ( "bytes" "testing" - "github.com/siemens/wfx/generated/client/jobs" - "github.com/siemens/wfx/generated/model" - "github.com/siemens/wfx/generated/northbound/restapi/operations/northbound" + "github.com/siemens/wfx/generated/api" "github.com/stretchr/testify/assert" ) -var resp = model.ErrorResponse{ - Errors: []*model.Error{ - { - Code: "foo", - Message: "something went wrong", - }, - { - Code: "bar", - Message: "oops", - }, - }, -} - func TestProcessErrorResponse(t *testing.T) { - bad := jobs.NewPostJobsBadRequest() - bad.Payload = &resp + resp := api.ErrorResponse{ + Errors: &[]api.Error{ + { + Code: "foo", + Message: "something went wrong", + }, + { + Code: "bar", + Message: "oops", + }, + }, + } buf := new(bytes.Buffer) - ProcessErrorResponse(buf, bad) + ProcessErrorResponse(buf, resp) msg := buf.String() assert.Equal(t, `ERROR: something went wrong (code=foo, logref=) ERROR: oops (code=bar, logref=) `, msg) } -func TestExtractErrors(t *testing.T) { - err := northbound.NewPostJobsBadRequest().WithPayload(&resp) - messages := extractErrors(err) - assert.NotEmpty(t, messages) -} - func TestMust(t *testing.T) { s := "hello world" assert.Equal(t, s, Must(s, nil)) diff --git a/cmd/wfxctl/flags/basecmd.go b/cmd/wfxctl/flags/basecmd.go index d47bcc28..6b22c1ed 100644 --- a/cmd/wfxctl/flags/basecmd.go +++ b/cmd/wfxctl/flags/basecmd.go @@ -18,13 +18,57 @@ import ( "net" "net/http" "os" + "strings" "time" "github.com/Southclaws/fault" - "github.com/go-openapi/strfmt" "github.com/itchyny/gojq" + "github.com/knadh/koanf/parsers/yaml" + "github.com/knadh/koanf/providers/env" + "github.com/knadh/koanf/providers/file" + "github.com/knadh/koanf/providers/posflag" + "github.com/knadh/koanf/v2" + "github.com/rs/zerolog" "github.com/rs/zerolog/log" - "github.com/siemens/wfx/generated/client" + "github.com/siemens/wfx/cmd/wfxctl/errutil" + "github.com/siemens/wfx/generated/api" + "github.com/spf13/pflag" +) + +const ( + ActorFlag = "actor" + ClientHostFlag = "client-host" + ClientIDFlag = "client-id" + ClientPortFlag = "client-port" + ClientTLSHostFlag = "client-tls-host" + ClientTLSPortFlag = "client-tls-port" + ClientUnixSocketFlag = "client-unix-socket" + ColorFlag = "color" + ConfigFlag = "config" + EnableTLSFlag = "enable-tls" + FilterFlag = "filter" + GroupFlag = "group" + HistoryFlag = "history" + IDFlag = "id" + JobIDFlag = "job-id" + LimitFlag = "limit" + LogLevelFlag = "log-level" + MessageFlag = "message" + MgmtHostFlag = "mgmt-host" + MgmtPortFlag = "mgmt-port" + MgmtTLSHostFlag = "mgmt-tls-host" + MgmtTLSPortFlag = "mgmt-tls-port" + MgmtUnixSocketFlag = "mgmt-unix-socket" + OffsetFlag = "offset" + ProgressFlag = "progress" + RawFlag = "raw" + SortFlag = "sort" + StateFlag = "state" + TLSCaFlag = "tls-ca" + TagFlag = "tag" + WorkflowFlag = "workflow" + WorkflowNameFlag = "workflow-name" + NameFlag = "name" ) type BaseCmd struct { @@ -46,28 +90,120 @@ type BaseCmd struct { Filter string // Strip quotes to make output usable in shell scripts RawOutput bool + ColorMode string + + ID string + ClientID string + ClientIDs []string + Workflow string + Workflows []string + Tags []string + State string + Sort string + Groups []string + Offset int64 + JobIDs []string + History bool + Progress int + Message string + Actor string + Name string + Limit int32 } -func NewBaseCmd() BaseCmd { - return BaseCmd{ - EnableTLS: Koanf.Bool(EnableTLSFlag), - TLSCa: Koanf.String(TLSCaFlag), +func NewBaseCmd(f *pflag.FlagSet) BaseCmd { + k := koanf.New(".") + + if level, err := f.GetString(LogLevelFlag); err == nil { + if lvl, err := zerolog.ParseLevel(level); err == nil { + zerolog.SetGlobalLevel(lvl) + } + } + + // Load the config files provided in the commandline. + configFiles, _ := f.GetStringSlice(ConfigFlag) + log.Debug().Strs("configFiles", configFiles).Msg("Checking config files") + for _, fname := range configFiles { + if _, err := os.Stat(fname); err == nil { + log.Debug().Str("fname", fname).Msg("Loading config file") + prov := file.Provider(fname) + if err := k.Load(prov, yaml.Parser()); err != nil { + log.Fatal().Err(err).Msg("Failed to config file") + } + } + } - Host: Koanf.String(ClientHostFlag), - Port: Koanf.Int(ClientPortFlag), - TLSHost: Koanf.String(ClientTLSHostFlag), - TLSPort: Koanf.Int(ClientTLSPortFlag), - Socket: Koanf.String(ClientUnixSocketFlag), + if err := k.Load(env.Provider("WFX_", ".", func(s string) string { + result := strings.ReplaceAll( + strings.ToLower(strings.TrimPrefix(s, "WFX_")), "_", "-") + return result + }), nil); err != nil { + log.Err(err).Msg("Failed to env variables") + } + + // --log-level becomes log.level + if err := k.Load(posflag.Provider(f, ".", k), nil); err != nil { + log.Fatal().Err(err).Msg("Failed to load flags") + } - MgmtHost: Koanf.String(MgmtHostFlag), - MgmtPort: Koanf.Int(MgmtPortFlag), - MgmtTLSHost: Koanf.String(MgmtTLSHostFlag), - MgmtTLSPort: Koanf.Int(MgmtTLSPortFlag), - MgmtSocket: Koanf.String(MgmtUnixSocketFlag), + log.Logger = zerolog.New(zerolog.ConsoleWriter{ + Out: os.Stderr, + TimeFormat: time.Stamp, + }).With().Timestamp().Logger() + if lvl, err := zerolog.ParseLevel(k.String(LogLevelFlag)); err == nil { + zerolog.SetGlobalLevel(lvl) + } + + return BaseCmd{ + ClientID: k.String(ClientIDFlag), + ClientIDs: k.Strings(ClientIDFlag), + ColorMode: k.String(ColorFlag), + EnableTLS: k.Bool(EnableTLSFlag), + Filter: k.String(FilterFlag), + Groups: k.Strings(GroupFlag), + History: k.Bool(HistoryFlag), + Host: k.String(ClientHostFlag), + ID: k.String(IDFlag), + JobIDs: k.Strings(JobIDFlag), + MgmtHost: k.String(MgmtHostFlag), + MgmtPort: k.Int(MgmtPortFlag), + MgmtSocket: k.String(MgmtUnixSocketFlag), + MgmtTLSHost: k.String(MgmtTLSHostFlag), + MgmtTLSPort: k.Int(MgmtTLSPortFlag), + Offset: k.Int64(OffsetFlag), + Port: k.Int(ClientPortFlag), + RawOutput: k.Bool(RawFlag), + Socket: k.String(ClientUnixSocketFlag), + Sort: k.String(SortFlag), + TLSCa: k.String(TLSCaFlag), + TLSHost: k.String(ClientTLSHostFlag), + TLSPort: k.Int(ClientTLSPortFlag), + Tags: k.Strings(TagFlag), + Workflow: k.String(WorkflowFlag), + Workflows: k.Strings(WorkflowNameFlag), + Progress: k.Int(ProgressFlag), + Message: k.String(MessageFlag), + State: k.String(StateFlag), + Actor: k.String(ActorFlag), + Name: k.String(NameFlag), + Limit: int32(k.Int(LimitFlag)), + } +} - Filter: Koanf.String(FilterFlag), - RawOutput: Koanf.Bool(RawFlag), +func (b *BaseCmd) SortParam() (*api.SortEnum, error) { + sortRaw := strings.ToLower(b.Sort) + asc := api.Asc + desc := api.Desc + if sortRaw == "" { + return &asc, nil + } + if sortRaw == "asc" { + return &asc, nil + } + if sortRaw == "desc" { + return &desc, nil } + return nil, fmt.Errorf("invalid sort value: %s", sortRaw) } func (b *BaseCmd) CreateHTTPClient() (*http.Client, error) { @@ -99,96 +235,118 @@ func (b *BaseCmd) CreateHTTPClient() (*http.Client, error) { }, nil } - if !b.EnableTLS { - return &http.Client{ - Timeout: time.Second * 10, - }, nil - } - caCert, err := os.ReadFile(b.TLSCa) - if err != nil { - log.Error().Err(err).Str("tlsCA", b.TLSCa).Msg("Failed to read CA bundle") - return &http.Client{ - Timeout: time.Second * 10, - }, nil - } + tlsConfig := new(tls.Config) + if b.TLSCa != "" { + caCertPool, err := x509.SystemCertPool() + if err != nil { + log.Warn().Err(err).Msg("Failed to load system cert pool, starting with empty pool") + caCertPool = x509.NewCertPool() + } - caCertPool := x509.NewCertPool() - caCertPool.AppendCertsFromPEM(caCert) + log.Debug().Str("tlsCA", b.TLSCa).Msg("Reading CA bundle") + caCert, err := os.ReadFile(b.TLSCa) + if err != nil { + return nil, fault.Wrap(err) + } + caCertPool.AppendCertsFromPEM(caCert) + tlsConfig.RootCAs = caCertPool + } return &http.Client{ Transport: &http.Transport{ - TLSClientConfig: &tls.Config{ - RootCAs: caCertPool, - }, + TLSClientConfig: tlsConfig, + TLSHandshakeTimeout: time.Second * 10, }, Timeout: time.Second * 10, }, nil } -func (b *BaseCmd) CreateClient() *client.WorkflowExecutor { - return client.NewHTTPClientWithConfig(strfmt.Default, b.CreateTransportConfig()) -} - -func (b *BaseCmd) CreateTransportConfig() *client.TransportConfig { - var host string - var schemes []string +func (b *BaseCmd) CreateClient() (*api.Client, error) { + var server string + swagger := errutil.Must(api.GetSwagger()) + basePath := errutil.Must(swagger.Servers.BasePath()) if b.EnableTLS { - schemes = []string{"https"} - host = fmt.Sprintf("%s:%d", b.TLSHost, b.TLSPort) + server = fmt.Sprintf("https://%s:%d%s", b.TLSHost, b.TLSPort, basePath) } else { - schemes = []string{"http"} - host = fmt.Sprintf("%s:%d", b.Host, b.Port) + server = fmt.Sprintf("http://%s:%d%s", b.Host, b.Port, basePath) + } + log.Debug().Str("server", server).Msg("Creating client") + httpClient, err := b.CreateHTTPClient() + if err != nil { + return nil, fault.Wrap(err) } - return client.DefaultTransportConfig(). - WithHost(host). - WithSchemes(schemes) + client, err := api.NewClient(server, api.WithHTTPClient(httpClient)) + if err != nil { + return nil, fault.Wrap(err) + } + return client, nil } -func (b *BaseCmd) CreateMgmtClient() *client.WorkflowExecutor { - var host string - var schemes []string +func (b *BaseCmd) CreateMgmtClient() (*api.Client, error) { + var server string + swagger := errutil.Must(api.GetSwagger()) + basePath := errutil.Must(swagger.Servers.BasePath()) if b.EnableTLS { - schemes = []string{"https"} - host = fmt.Sprintf("%s:%d", b.MgmtTLSHost, b.MgmtTLSPort) + server = fmt.Sprintf("https://%s:%d%s", b.MgmtTLSHost, b.MgmtTLSPort, basePath) } else { - schemes = []string{"http"} - host = fmt.Sprintf("%s:%d", b.MgmtHost, b.MgmtPort) + server = fmt.Sprintf("http://%s:%d%s", b.MgmtHost, b.MgmtPort, basePath) + } + httpClient, err := b.CreateHTTPClient() + if err != nil { + return nil, fault.Wrap(err) } + client, err := api.NewClient(server, api.WithHTTPClient(httpClient)) + if err != nil { + return nil, fault.Wrap(err) + } + return client, nil +} - cfg := client.DefaultTransportConfig(). - WithHost(host). - WithSchemes(schemes) - return client.NewHTTPClientWithConfig(strfmt.Default, cfg) +func (b *BaseCmd) ProcessResponse(resp *http.Response, w io.Writer) error { + body, _ := io.ReadAll(resp.Body) + _ = resp.Body.Close() + statusCode := resp.StatusCode + switch statusCode { + case http.StatusOK, http.StatusCreated, http.StatusNoContent: + if err := b.dumpResponse(w, body); err != nil { + return fault.Wrap(err) + } + default: + var errorResponse api.ErrorResponse + if err := json.Unmarshal(body, &errorResponse); err == nil { + errutil.ProcessErrorResponse(w, errorResponse) + } + return fmt.Errorf("error: %s", string(body)) + } + return nil } -func (b *BaseCmd) DumpResponse(w io.Writer, payload any) error { +func (b *BaseCmd) dumpResponse(w io.Writer, payload []byte) error { + if len(payload) == 0 { + return nil + } if b.Filter != "" { return fault.Wrap(dumpFiltered(payload, b.Filter, b.RawOutput, w)) } - return fault.Wrap(dumpPlain(payload, w)) + var body any + if err := json.Unmarshal(payload, &body); err != nil { + return fault.Wrap(err) + } + encoder := json.NewEncoder(w) + encoder.SetIndent("", " ") + return fault.Wrap(encoder.Encode(body)) } -func dumpFiltered(payload any, filter string, rawOutput bool, w io.Writer) error { +func dumpFiltered(payload []byte, filter string, rawOutput bool, w io.Writer) error { query, err := gojq.Parse(filter) if err != nil { return fault.Wrap(err) } var input any - if payloadBytes, ok := payload.([]byte); ok { - if err := json.Unmarshal(payloadBytes, &input); err != nil { - return fault.Wrap(err) - } - } else { - data, err := json.Marshal(payload) - if err != nil { - return fault.Wrap(err) - } - if err := json.Unmarshal(data, &input); err != nil { - return fault.Wrap(err) - } + if err := json.Unmarshal(payload, &input); err != nil { + return fault.Wrap(err) } - iter := query.Run(input) for { v, ok := iter.Next() @@ -206,23 +364,13 @@ func dumpFiltered(payload any, filter string, rawOutput bool, w io.Writer) error return errors.New("value is not a string. try disabling raw output mode") } } else { - b, err := json.MarshalIndent(v, "", " ") - if err != nil { + encoder := json.NewEncoder(w) + encoder.SetIndent("", " ") + if err := encoder.Encode(v); err != nil { return fault.Wrap(err) } - fmt.Fprintln(w, string(b)) } } return nil } - -func dumpPlain(payload any, w io.Writer) error { - if payloadBytes, ok := payload.([]byte); ok { - fmt.Println(string(payloadBytes)) - return nil - } - enc := json.NewEncoder(w) - enc.SetIndent("", " ") - return fault.Wrap(enc.Encode(payload)) -} diff --git a/cmd/wfxctl/flags/basecmd_test.go b/cmd/wfxctl/flags/basecmd_test.go index fb1bd947..5f56b612 100644 --- a/cmd/wfxctl/flags/basecmd_test.go +++ b/cmd/wfxctl/flags/basecmd_test.go @@ -10,17 +10,20 @@ package flags import ( "bytes" + "encoding/json" "net/http" + "net/http/httptest" "os" "testing" + "github.com/rs/zerolog" + "github.com/siemens/wfx/generated/api" + "github.com/spf13/pflag" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestCreateHTTPClientTLS(t *testing.T) { - _ = Koanf.Set(EnableTLSFlag, true) - cert := []byte(` -----BEGIN CERTIFICATE----- MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh @@ -45,20 +48,21 @@ YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4= -----END CERTIFICATE----- `) - tmpFile, _ := os.CreateTemp(os.TempDir(), "wfx-cert-") + tmpFile, _ := os.CreateTemp("", "wfx-cert-") _, _ = tmpFile.Write(cert) defer os.Remove(tmpFile.Name()) - _ = Koanf.Set(TLSCaFlag, tmpFile.Name()) + b := NewBaseCmd(pflag.NewFlagSet("wfx", pflag.ExitOnError)) + b.EnableTLS = true + b.TLSCa = tmpFile.Name() - b := NewBaseCmd() client, _ := b.CreateHTTPClient() transport := client.Transport.(*http.Transport) assert.NotEmpty(t, transport.TLSClientConfig.RootCAs) } func TestCreateHTTPClient_AmbiguousSockets(t *testing.T) { - b := NewBaseCmd() + b := NewBaseCmd(pflag.NewFlagSet("wfx", pflag.ExitOnError)) b.Socket = "foo" b.MgmtSocket = "bar" _, err := b.CreateHTTPClient() @@ -66,80 +70,184 @@ func TestCreateHTTPClient_AmbiguousSockets(t *testing.T) { } func TestCreateHTTPClient_Socket(t *testing.T) { - b := NewBaseCmd() - b.Socket = "foo" + b := NewBaseCmd(pflag.NewFlagSet("wfx", pflag.ExitOnError)) + b.Socket = "/tmp/foo.sock" _, err := b.CreateHTTPClient() require.NoError(t, err) } -func TestCreateClient(t *testing.T) { - b := NewBaseCmd() +func TestCreateClient_TLS(t *testing.T) { + b := NewBaseCmd(pflag.NewFlagSet("wfx", pflag.ExitOnError)) b.EnableTLS = true - client := b.CreateClient() + client, err := b.CreateClient() assert.NotNil(t, client) + assert.NoError(t, err) } func TestCreateClient_NoTLS(t *testing.T) { - b := NewBaseCmd() + b := NewBaseCmd(pflag.NewFlagSet("wfx", pflag.ExitOnError)) b.EnableTLS = false - client := b.CreateClient() + client, err := b.CreateClient() assert.NotNil(t, client) + assert.NoError(t, err) } func TestCreateMgmtClient(t *testing.T) { - b := NewBaseCmd() + b := NewBaseCmd(pflag.NewFlagSet("wfx", pflag.ExitOnError)) b.EnableTLS = true - client := b.CreateMgmtClient() + client, err := b.CreateMgmtClient() assert.NotNil(t, client) + assert.NoError(t, err) } func TestCreateMgmtClient_NoTLS(t *testing.T) { - b := NewBaseCmd() + b := NewBaseCmd(pflag.NewFlagSet("wfx", pflag.ExitOnError)) b.EnableTLS = false - client := b.CreateMgmtClient() + client, err := b.CreateMgmtClient() assert.NotNil(t, client) + assert.NoError(t, err) } func TestDumpPlain(t *testing.T) { - payload := map[string]string{ - "id": "1", - "foo": "bar", - } - + payload := []byte("{\n \"foo\": \"bar\",\n \"id\": \"1\"\n}\n") var buf bytes.Buffer - b := NewBaseCmd() + b := NewBaseCmd(pflag.NewFlagSet("wfx", pflag.ExitOnError)) b.Filter = "" - err := b.DumpResponse(&buf, payload) + err := b.dumpResponse(&buf, payload) assert.NoError(t, err) assert.JSONEq(t, "{\n \"foo\": \"bar\",\n \"id\": \"1\"\n}\n", buf.String()) } func TestDumpFilter(t *testing.T) { - payload := map[string]string{ - "id": "1", - "foo": "bar", - } + payload := []byte("{\n \"foo\": \"bar\",\n \"id\": \"1\"\n}\n") var buf bytes.Buffer - b := NewBaseCmd() + b := NewBaseCmd(pflag.NewFlagSet("wfx", pflag.ExitOnError)) b.Filter = ".id" b.RawOutput = false - err := b.DumpResponse(&buf, payload) + err := b.dumpResponse(&buf, payload) assert.NoError(t, err) assert.JSONEq(t, "\"1\"", buf.String()) } func TestDumpFilterRaw(t *testing.T) { - payload := map[string]string{ - "id": "1", - "foo": "bar", - } - + payload := []byte("{\n \"foo\": \"bar\",\n \"id\": \"1\"\n}\n") var buf bytes.Buffer err := dumpFiltered(payload, ".id", true, &buf) assert.NoError(t, err) assert.JSONEq(t, "1", buf.String()) } + +func TestProcessResponse(t *testing.T) { + recorder := httptest.NewRecorder() + recorder.WriteHeader(http.StatusOK) + _, _ = recorder.WriteString(`{"foo": "bar"}`) + resp := recorder.Result() + buf := new(bytes.Buffer) + b := NewBaseCmd(pflag.NewFlagSet("wfx", pflag.ExitOnError)) + err := b.ProcessResponse(resp, buf) + assert.NoError(t, err) +} + +func TestProcessResponse_Empty(t *testing.T) { + recorder := httptest.NewRecorder() + recorder.WriteHeader(http.StatusNoContent) + resp := recorder.Result() + buf := new(bytes.Buffer) + b := NewBaseCmd(pflag.NewFlagSet("wfx", pflag.ExitOnError)) + err := b.ProcessResponse(resp, buf) + assert.NoError(t, err) +} + +func TestProcessResponse_Error(t *testing.T) { + recorder := httptest.NewRecorder() + recorder.WriteHeader(http.StatusInternalServerError) + resp := recorder.Result() + buf := new(bytes.Buffer) + b := NewBaseCmd(pflag.NewFlagSet("wfx", pflag.ExitOnError)) + err := b.ProcessResponse(resp, buf) + assert.Error(t, err) +} + +func TestProcessResponse_ErrorResponse(t *testing.T) { + recorder := httptest.NewRecorder() + recorder.WriteHeader(http.StatusInternalServerError) + errResp := api.ErrorResponse{ + Errors: &[]api.Error{ + {Code: "foo", Message: "bar", Logref: "baz"}, + }, + } + _ = json.NewEncoder(recorder).Encode(errResp) + resp := recorder.Result() + buf := new(bytes.Buffer) + b := NewBaseCmd(pflag.NewFlagSet("wfx", pflag.ExitOnError)) + err := b.ProcessResponse(resp, buf) + assert.Error(t, err) +} + +func TestSortParam_Asc(t *testing.T) { + b := NewBaseCmd(pflag.NewFlagSet("wfx", pflag.ExitOnError)) + b.Sort = "asc" + val, err := b.SortParam() + assert.NoError(t, err) + assert.Equal(t, api.Asc, *val) +} + +func TestSortParam_Desc(t *testing.T) { + b := NewBaseCmd(pflag.NewFlagSet("wfx", pflag.ExitOnError)) + b.Sort = "desc" + val, err := b.SortParam() + assert.NoError(t, err) + assert.Equal(t, api.Desc, *val) +} + +func TestSortParam_Empty(t *testing.T) { + b := NewBaseCmd(pflag.NewFlagSet("wfx", pflag.ExitOnError)) + b.Sort = "" + val, err := b.SortParam() + assert.NoError(t, err) + assert.Equal(t, api.Asc, *val) +} + +func TestSortParam_Invalid(t *testing.T) { + b := NewBaseCmd(pflag.NewFlagSet("wfx", pflag.ExitOnError)) + b.Sort = "foo" + val, err := b.SortParam() + assert.Error(t, err) + assert.Nil(t, val) +} + +func TestNewBaseCmd_LogLevel(t *testing.T) { + f := pflag.NewFlagSet("test", pflag.ContinueOnError) + f.String(LogLevelFlag, "trace", "log level") + _ = NewBaseCmd(f) + assert.Equal(t, zerolog.TraceLevel, zerolog.GlobalLevel()) +} + +func TestNewBaseCmd_ConfigFile(t *testing.T) { + tmpfile, err := os.CreateTemp("", "test-log-level-*.yaml") + require.NoError(t, err) + t.Log(tmpfile.Name()) + defer os.Remove(tmpfile.Name()) + + content := []byte("log-level: trace\n") + _, err = tmpfile.Write(content) + require.NoError(t, err) + err = tmpfile.Close() + require.NoError(t, err) + + f := pflag.NewFlagSet("test", pflag.ContinueOnError) + f.StringSlice(ConfigFlag, []string{tmpfile.Name()}, "config files") + _ = NewBaseCmd(f) + assert.Equal(t, zerolog.TraceLevel, zerolog.GlobalLevel()) +} + +func TestNewBaseCmd_EnvVariables(t *testing.T) { + t.Setenv("WFX_LOG_LEVEL", "trace") + f := pflag.NewFlagSet("test", pflag.ContinueOnError) + NewBaseCmd(f) + assert.Equal(t, zerolog.TraceLevel, zerolog.GlobalLevel()) +} diff --git a/cmd/wfxctl/flags/flags.go b/cmd/wfxctl/flags/flags.go deleted file mode 100644 index c2b97767..00000000 --- a/cmd/wfxctl/flags/flags.go +++ /dev/null @@ -1,37 +0,0 @@ -package flags - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "github.com/knadh/koanf/v2" -) - -const ( - ConfigFlag = "config" - - ClientHostFlag = "client-host" - ClientPortFlag = "client-port" - ClientUnixSocketFlag = "client-unix-socket" - ClientTLSHostFlag = "client-tls-host" - ClientTLSPortFlag = "client-tls-port" - - MgmtHostFlag = "mgmt-host" - MgmtPortFlag = "mgmt-port" - MgmtUnixSocketFlag = "mgmt-unix-socket" - MgmtTLSHostFlag = "mgmt-tls-host" - MgmtTLSPortFlag = "mgmt-tls-port" - - TLSCaFlag = "tls-ca" - - FilterFlag = "filter" - RawFlag = "raw" - EnableTLSFlag = "enable-tls" -) - -var Koanf = koanf.New(".") diff --git a/cmd/wfxctl/main.go b/cmd/wfxctl/main.go index b6c503d8..ba2070a4 100644 --- a/cmd/wfxctl/main.go +++ b/cmd/wfxctl/main.go @@ -9,14 +9,13 @@ package main */ import ( - "github.com/rs/zerolog/log" + "os" + "github.com/siemens/wfx/cmd/wfxctl/cmd" - "github.com/siemens/wfx/cmd/wfxctl/metadata" ) func main() { - cmd.RootCmd.Version = metadata.Version - if err := cmd.RootCmd.Execute(); err != nil { - log.Fatal().Err(err).Msg("wfxctl encountered an error") + if err := cmd.NewCommand().Execute(); err != nil { + os.Exit(1) } } diff --git a/cmd/wfxctl/metadata/metadata.go b/cmd/wfxctl/metadata/metadata.go index 18e8530f..6dd703e5 100644 --- a/cmd/wfxctl/metadata/metadata.go +++ b/cmd/wfxctl/metadata/metadata.go @@ -12,5 +12,5 @@ var ( // values provided by linker Version = "dev" Commit = "unknown" - Date = "unknown" + Date = "1970-01-01T00:00:00+00:00" ) diff --git a/contrib/config-deployment/client/go.mod b/contrib/config-deployment/client/go.mod index 3e81d7b3..0f34464b 100644 --- a/contrib/config-deployment/client/go.mod +++ b/contrib/config-deployment/client/go.mod @@ -6,34 +6,25 @@ go 1.23.0 require ( github.com/cavaliergopher/grab/v3 v3.0.1 - github.com/go-openapi/strfmt v0.23.0 github.com/siemens/wfx v0.3.2 github.com/spf13/pflag v1.0.5 ) require ( - github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect - github.com/go-logr/logr v1.4.2 // indirect - github.com/go-logr/stdr v1.2.2 // indirect - github.com/go-openapi/analysis v0.23.0 // indirect - github.com/go-openapi/errors v0.22.0 // indirect + github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect + github.com/getkin/kin-openapi v0.128.0 // indirect github.com/go-openapi/jsonpointer v0.21.0 // indirect - github.com/go-openapi/jsonreference v0.21.0 // indirect - github.com/go-openapi/loads v0.22.0 // indirect - github.com/go-openapi/runtime v0.28.0 // indirect - github.com/go-openapi/spec v0.21.0 // indirect github.com/go-openapi/swag v0.23.0 // indirect - github.com/go-openapi/validate v0.24.0 // indirect github.com/google/uuid v1.6.0 // indirect + github.com/invopop/yaml v0.3.1 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/mailru/easyjson v0.7.7 // indirect - github.com/mitchellh/mapstructure v1.5.0 // indirect - github.com/oklog/ulid v1.3.1 // indirect - github.com/opentracing/opentracing-go v1.2.0 // indirect - go.mongodb.org/mongo-driver v1.17.1 // indirect - go.opentelemetry.io/otel v1.32.0 // indirect - go.opentelemetry.io/otel/metric v1.32.0 // indirect - go.opentelemetry.io/otel/trace v1.32.0 // indirect - golang.org/x/sync v0.10.0 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect + github.com/oapi-codegen/runtime v1.1.1 // indirect + github.com/perimeterx/marshmallow v1.1.5 // indirect + github.com/rs/zerolog v1.33.0 // indirect + golang.org/x/sys v0.28.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/contrib/config-deployment/client/go.sum b/contrib/config-deployment/client/go.sum index ff59d5e5..351d0d87 100644 --- a/contrib/config-deployment/client/go.sum +++ b/contrib/config-deployment/client/go.sum @@ -1,75 +1,69 @@ -github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= -github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= +github.com/RaveNoX/go-jsoncommentstrip v1.0.0/go.mod h1:78ihd09MekBnJnxpICcwzCMzGrKSKYe4AqU6PDYYpjk= +github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7Dml6nw9rQ= +github.com/apapsch/go-jsonmerge/v2 v2.0.0/go.mod h1:lvDnEdqiQrp0O42VQGgmlKpxL1AP2+08jFMw88y4klk= +github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvFv1sNto9p6w= github.com/cavaliergopher/grab/v3 v3.0.1 h1:4z7TkBfmPjmLAAmkkAZNX/6QJ1nNFdv3SdIHXju0Fr4= github.com/cavaliergopher/grab/v3 v3.0.1/go.mod h1:1U/KNnD+Ft6JJiYoYBAimKH2XrYptb8Kl3DFGmsjpq4= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= -github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= -github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= -github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= -github.com/go-openapi/analysis v0.23.0 h1:aGday7OWupfMs+LbmLZG4k0MYXIANxcuBTYUC03zFCU= -github.com/go-openapi/analysis v0.23.0/go.mod h1:9mz9ZWaSlV8TvjQHLl2mUW2PbZtemkE8yA5v22ohupo= -github.com/go-openapi/errors v0.22.0 h1:c4xY/OLxUBSTiepAg3j/MHuAv5mJhnf53LLMWFB+u/w= -github.com/go-openapi/errors v0.22.0/go.mod h1:J3DmZScxCDufmIMsdOuDHxJbdOGC0xtUynjIx092vXE= +github.com/getkin/kin-openapi v0.128.0 h1:jqq3D9vC9pPq1dGcOCv7yOp1DaEe7c/T1vzcLbITSp4= +github.com/getkin/kin-openapi v0.128.0/go.mod h1:OZrfXzUfGrNbsKj+xmFBx6E5c6yH3At/tAKSc2UszXM= github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ= github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY= -github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ= -github.com/go-openapi/jsonreference v0.21.0/go.mod h1:LmZmgsrTkVg9LG4EaHeY8cBDslNPMo06cago5JNLkm4= -github.com/go-openapi/loads v0.22.0 h1:ECPGd4jX1U6NApCGG1We+uEozOAvXvJSF4nnwHZ8Aco= -github.com/go-openapi/loads v0.22.0/go.mod h1:yLsaTCS92mnSAZX5WWoxszLj0u+Ojl+Zs5Stn1oF+rs= -github.com/go-openapi/runtime v0.28.0 h1:gpPPmWSNGo214l6n8hzdXYhPuJcGtziTOgUpvsFWGIQ= -github.com/go-openapi/runtime v0.28.0/go.mod h1:QN7OzcS+XuYmkQLw05akXk0jRH/eZ3kb18+1KwW9gyc= -github.com/go-openapi/spec v0.21.0 h1:LTVzPc3p/RzRnkQqLRndbAzjY0d0BCL72A6j3CdL9ZY= -github.com/go-openapi/spec v0.21.0/go.mod h1:78u6VdPw81XU44qEWGhtr982gJ5BWg2c0I5XwVMotYk= -github.com/go-openapi/strfmt v0.23.0 h1:nlUS6BCqcnAk0pyhi9Y+kdDVZdZMHfEKQiS4HaMgO/c= -github.com/go-openapi/strfmt v0.23.0/go.mod h1:NrtIpfKtWIygRkKVsxh7XQMDQW5HKQl6S5ik2elW+K4= github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE= github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ= -github.com/go-openapi/validate v0.24.0 h1:LdfDKwNbpB6Vn40xhTdNZAnfLECL81w+VX3BumrGD58= -github.com/go-openapi/validate v0.24.0/go.mod h1:iyeX1sEufmv3nPbBdX3ieNviWnOZaJ1+zquzJEf2BAQ= -github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= -github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/go-test/deep v1.0.8 h1:TDsG77qcSprGbC6vTN8OuXp5g+J+b5Pcguhf7Zt61VM= +github.com/go-test/deep v1.0.8/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/invopop/yaml v0.3.1 h1:f0+ZpmhfBSS4MhG+4HYseMdJhoeeopbSKbq5Rpeelso= +github.com/invopop/yaml v0.3.1/go.mod h1:PMOp3nn4/12yEZUFfmOuNHJsZToEEOwoWsT+D81KkeA= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/juju/gnuflag v0.0.0-20171113085948-2ce1bb71843d/go.mod h1:2PavIy+JPciBPrBUjwbNvtwB6RQlve+hkpll6QSNmOE= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= -github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= -github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= -github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4= -github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= -github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs= -github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw= +github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8= +github.com/oapi-codegen/runtime v1.1.1 h1:EXLHh0DXIJnWhdRPN2w4MXAzFyE4CskzhNLUmtpMYro= +github.com/oapi-codegen/runtime v1.1.1/go.mod h1:SK9X900oXmPWilYR5/WKPzt3Kqxn/uS/+lbpREv+eCg= +github.com/perimeterx/marshmallow v1.1.5 h1:a2LALqQ1BlHM8PZblsDdidgv1mWi1DgC2UmX50IvK2s= +github.com/perimeterx/marshmallow v1.1.5/go.mod h1:dsXbUu8CRzfYP5a87xpp0xq9S3u0Vchtcl8we9tYaXw= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= -github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= +github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8= +github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spkg/bom v0.0.0-20160624110644-59b7046e48ad/go.mod h1:qLr4V1qq6nMqFKkMo8ZTx3f+BZEkzsRUY10Xsm2mwU0= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -go.mongodb.org/mongo-driver v1.17.1 h1:Wic5cJIwJgSpBhe3lx3+/RybR5PiYRMpVFgO7cOHyIM= -go.mongodb.org/mongo-driver v1.17.1/go.mod h1:wwWm/+BuOddhcq3n68LKRmgk2wXzmF6s0SFOa0GINL4= -go.opentelemetry.io/otel v1.32.0 h1:WnBN+Xjcteh0zdk01SVqV55d/m62NJLJdIyb4y/WO5U= -go.opentelemetry.io/otel v1.32.0/go.mod h1:00DCVSB0RQcnzlwyTfqtxSm+DRr9hpYrHjNGiBHVQIg= -go.opentelemetry.io/otel/metric v1.32.0 h1:xV2umtmNcThh2/a/aCP+h64Xx5wsj8qqnkYZktzNa0M= -go.opentelemetry.io/otel/metric v1.32.0/go.mod h1:jH7CIbbK6SH2V2wE16W05BHCtIDzauciCRLoc/SyMv8= -go.opentelemetry.io/otel/sdk v1.24.0 h1:YMPPDNymmQN3ZgczicBY3B6sf9n62Dlj9pWD3ucgoDw= -go.opentelemetry.io/otel/sdk v1.24.0/go.mod h1:KVrIYw6tEubO9E96HQpcmpTKDVn9gdv35HoYiQWGDFg= -go.opentelemetry.io/otel/trace v1.32.0 h1:WIC9mYrXf8TmY/EXuULKc8hR17vE+Hjv2cssQDe03fM= -go.opentelemetry.io/otel/trace v1.32.0/go.mod h1:+i4rkvCraA+tG6AzwloGaCtkx53Fa+L+V8e9a7YvhT8= -golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= -golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU= +github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/contrib/config-deployment/client/worker.go b/contrib/config-deployment/client/worker.go index f3a86a70..332dc91d 100644 --- a/contrib/config-deployment/client/worker.go +++ b/contrib/config-deployment/client/worker.go @@ -9,59 +9,66 @@ package main */ import ( + "context" "fmt" "io" "log" + "net/http" "os" "os/exec" "path" "time" - "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/client" - "github.com/siemens/wfx/generated/client/jobs" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/cmd/wfxctl/errutil" + "github.com/siemens/wfx/generated/api" ) func worker() { workflow := "wfx.workflow.config.deployment" initialState := "NEW" limit := int32(1) - queryParams := jobs.NewGetJobsParams(). - WithClientID(&clientID). - WithWorkflow(&workflow). - WithState(&initialState). - WithLimit(&limit) - cfg := client.DefaultTransportConfig() - cfg.Host = fmt.Sprintf("%s:%d", host, port) - c := client.NewHTTPClientWithConfig(strfmt.Default, cfg) + + params := new(api.GetJobsParams) + params.ParamClientID = &clientID + params.ParamWorkflow = &workflow + params.ParamState = &initialState + params.ParamLimit = &limit + + swagger := errutil.Must(api.GetSwagger()) + basePath := errutil.Must(swagger.Servers.BasePath()) + server := fmt.Sprintf("http://%s:%d%s", host, port, basePath) + httpClient := &http.Client{Timeout: time.Second * 10} + client, err := api.NewClientWithResponses(server, api.WithHTTPClient(httpClient)) + if err != nil { + log.Fatalf("Failed to create client: %s", err) + } for !done.Load() { log.Println("\n>> Waiting for new job") - var job *model.Job + var job *api.Job for { if done.Load() { break } - resp, err := c.Jobs.GetJobs(queryParams) - if err == nil && len(resp.Payload.Content) > 0 { - job = resp.Payload.Content[0] + resp, err := client.GetJobsWithResponse(context.Background(), params) + if err == nil && resp.JSON200 != nil && len(resp.JSON200.Content) > 0 { + job = &resp.JSON200.Content[0] break } time.Sleep(pollInterval) } log.Println("Got new job with ID", job.ID) - if err := processJob(c, job); err != nil { + if err := processJob(client, job); err != nil { log.Println("Failed to process job:", err) - updateJobStatus(c, job, "FAILED", nil) + updateJobStatus(client, job, "FAILED", nil) continue } log.Println("Successfully processed job") - updateJobStatus(c, job, "DONE", nil) + updateJobStatus(client, job, "DONE", nil) } } -func processJob(c *client.WorkflowExecutor, job *model.Job) error { +func processJob(client *api.ClientWithResponses, job *api.Job) error { tmpDir, err := os.MkdirTemp("", "config-deployer") if err != nil { return err @@ -70,7 +77,7 @@ func processJob(c *client.WorkflowExecutor, job *model.Job) error { _ = os.RemoveAll(tmpDir) }() - updateJobStatus(c, job, "DOWNLOADING", nil) + updateJobStatus(client, job, "DOWNLOADING", nil) url := job.Definition["url"].(string) log.Println("Downloading", url) @@ -80,7 +87,7 @@ func processJob(c *client.WorkflowExecutor, job *model.Job) error { } log.Println("Download successful, starting installation") - updateJobStatus(c, job, "INSTALLING", nil) + updateJobStatus(client, job, "INSTALLING", nil) // run preinstall script if preinstall, ok := job.Definition["preinstall"].(string); ok { @@ -125,22 +132,19 @@ func processJob(c *client.WorkflowExecutor, job *model.Job) error { return nil } -func updateJobStatus(c *client.WorkflowExecutor, job *model.Job, state string, err error) { +func updateJobStatus(client *api.ClientWithResponses, job *api.Job, state string, err error) { + job.Status = &api.JobStatus{State: state} if err == nil { log.Println("Setting job status to", state) } else { log.Printf("Setting job status to %s, err=%s\n", state, err) - } - job.Status = &model.JobStatus{State: state} - if err != nil { - job.Status.Context = map[string]any{ + job.Status.Context = &map[string]any{ "error": err.Error(), } } - _, err = c.Jobs.PutJobsIDStatus(jobs.NewPutJobsIDStatusParams(). - WithID(job.ID). - WithNewJobStatus(job.Status)) - if err != nil { + + resp, err := client.PutJobsIdStatus(context.Background(), job.ID, nil, *job.Status) + if err != nil || resp.StatusCode != http.StatusOK { log.Println("Failed to update job status:", err) } } diff --git a/contrib/remote-access/client/go.mod b/contrib/remote-access/client/go.mod index cfaf71ed..6ae024c8 100644 --- a/contrib/remote-access/client/go.mod +++ b/contrib/remote-access/client/go.mod @@ -5,34 +5,25 @@ replace github.com/siemens/wfx => ../../.. go 1.23.0 require ( - github.com/go-openapi/strfmt v0.23.0 github.com/siemens/wfx v0.3.2 github.com/spf13/pflag v1.0.5 ) require ( - github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect - github.com/go-logr/logr v1.4.2 // indirect - github.com/go-logr/stdr v1.2.2 // indirect - github.com/go-openapi/analysis v0.23.0 // indirect - github.com/go-openapi/errors v0.22.0 // indirect + github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect + github.com/getkin/kin-openapi v0.128.0 // indirect github.com/go-openapi/jsonpointer v0.21.0 // indirect - github.com/go-openapi/jsonreference v0.21.0 // indirect - github.com/go-openapi/loads v0.22.0 // indirect - github.com/go-openapi/runtime v0.28.0 // indirect - github.com/go-openapi/spec v0.21.0 // indirect github.com/go-openapi/swag v0.23.0 // indirect - github.com/go-openapi/validate v0.24.0 // indirect github.com/google/uuid v1.6.0 // indirect + github.com/invopop/yaml v0.3.1 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/mailru/easyjson v0.7.7 // indirect - github.com/mitchellh/mapstructure v1.5.0 // indirect - github.com/oklog/ulid v1.3.1 // indirect - github.com/opentracing/opentracing-go v1.2.0 // indirect - go.mongodb.org/mongo-driver v1.17.1 // indirect - go.opentelemetry.io/otel v1.32.0 // indirect - go.opentelemetry.io/otel/metric v1.32.0 // indirect - go.opentelemetry.io/otel/trace v1.32.0 // indirect - golang.org/x/sync v0.10.0 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect + github.com/oapi-codegen/runtime v1.1.1 // indirect + github.com/perimeterx/marshmallow v1.1.5 // indirect + github.com/rs/zerolog v1.33.0 // indirect + golang.org/x/sys v0.28.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/contrib/remote-access/client/go.sum b/contrib/remote-access/client/go.sum index 80d33d8c..ba9dbe3e 100644 --- a/contrib/remote-access/client/go.sum +++ b/contrib/remote-access/client/go.sum @@ -1,73 +1,67 @@ -github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= -github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= +github.com/RaveNoX/go-jsoncommentstrip v1.0.0/go.mod h1:78ihd09MekBnJnxpICcwzCMzGrKSKYe4AqU6PDYYpjk= +github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7Dml6nw9rQ= +github.com/apapsch/go-jsonmerge/v2 v2.0.0/go.mod h1:lvDnEdqiQrp0O42VQGgmlKpxL1AP2+08jFMw88y4klk= +github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvFv1sNto9p6w= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= -github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= -github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= -github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= -github.com/go-openapi/analysis v0.23.0 h1:aGday7OWupfMs+LbmLZG4k0MYXIANxcuBTYUC03zFCU= -github.com/go-openapi/analysis v0.23.0/go.mod h1:9mz9ZWaSlV8TvjQHLl2mUW2PbZtemkE8yA5v22ohupo= -github.com/go-openapi/errors v0.22.0 h1:c4xY/OLxUBSTiepAg3j/MHuAv5mJhnf53LLMWFB+u/w= -github.com/go-openapi/errors v0.22.0/go.mod h1:J3DmZScxCDufmIMsdOuDHxJbdOGC0xtUynjIx092vXE= +github.com/getkin/kin-openapi v0.128.0 h1:jqq3D9vC9pPq1dGcOCv7yOp1DaEe7c/T1vzcLbITSp4= +github.com/getkin/kin-openapi v0.128.0/go.mod h1:OZrfXzUfGrNbsKj+xmFBx6E5c6yH3At/tAKSc2UszXM= github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ= github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY= -github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ= -github.com/go-openapi/jsonreference v0.21.0/go.mod h1:LmZmgsrTkVg9LG4EaHeY8cBDslNPMo06cago5JNLkm4= -github.com/go-openapi/loads v0.22.0 h1:ECPGd4jX1U6NApCGG1We+uEozOAvXvJSF4nnwHZ8Aco= -github.com/go-openapi/loads v0.22.0/go.mod h1:yLsaTCS92mnSAZX5WWoxszLj0u+Ojl+Zs5Stn1oF+rs= -github.com/go-openapi/runtime v0.28.0 h1:gpPPmWSNGo214l6n8hzdXYhPuJcGtziTOgUpvsFWGIQ= -github.com/go-openapi/runtime v0.28.0/go.mod h1:QN7OzcS+XuYmkQLw05akXk0jRH/eZ3kb18+1KwW9gyc= -github.com/go-openapi/spec v0.21.0 h1:LTVzPc3p/RzRnkQqLRndbAzjY0d0BCL72A6j3CdL9ZY= -github.com/go-openapi/spec v0.21.0/go.mod h1:78u6VdPw81XU44qEWGhtr982gJ5BWg2c0I5XwVMotYk= -github.com/go-openapi/strfmt v0.23.0 h1:nlUS6BCqcnAk0pyhi9Y+kdDVZdZMHfEKQiS4HaMgO/c= -github.com/go-openapi/strfmt v0.23.0/go.mod h1:NrtIpfKtWIygRkKVsxh7XQMDQW5HKQl6S5ik2elW+K4= github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE= github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ= -github.com/go-openapi/validate v0.24.0 h1:LdfDKwNbpB6Vn40xhTdNZAnfLECL81w+VX3BumrGD58= -github.com/go-openapi/validate v0.24.0/go.mod h1:iyeX1sEufmv3nPbBdX3ieNviWnOZaJ1+zquzJEf2BAQ= -github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= -github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/go-test/deep v1.0.8 h1:TDsG77qcSprGbC6vTN8OuXp5g+J+b5Pcguhf7Zt61VM= +github.com/go-test/deep v1.0.8/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/invopop/yaml v0.3.1 h1:f0+ZpmhfBSS4MhG+4HYseMdJhoeeopbSKbq5Rpeelso= +github.com/invopop/yaml v0.3.1/go.mod h1:PMOp3nn4/12yEZUFfmOuNHJsZToEEOwoWsT+D81KkeA= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/juju/gnuflag v0.0.0-20171113085948-2ce1bb71843d/go.mod h1:2PavIy+JPciBPrBUjwbNvtwB6RQlve+hkpll6QSNmOE= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= -github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= -github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= -github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4= -github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= -github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs= -github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw= +github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8= +github.com/oapi-codegen/runtime v1.1.1 h1:EXLHh0DXIJnWhdRPN2w4MXAzFyE4CskzhNLUmtpMYro= +github.com/oapi-codegen/runtime v1.1.1/go.mod h1:SK9X900oXmPWilYR5/WKPzt3Kqxn/uS/+lbpREv+eCg= +github.com/perimeterx/marshmallow v1.1.5 h1:a2LALqQ1BlHM8PZblsDdidgv1mWi1DgC2UmX50IvK2s= +github.com/perimeterx/marshmallow v1.1.5/go.mod h1:dsXbUu8CRzfYP5a87xpp0xq9S3u0Vchtcl8we9tYaXw= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= -github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= +github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8= +github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spkg/bom v0.0.0-20160624110644-59b7046e48ad/go.mod h1:qLr4V1qq6nMqFKkMo8ZTx3f+BZEkzsRUY10Xsm2mwU0= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -go.mongodb.org/mongo-driver v1.17.1 h1:Wic5cJIwJgSpBhe3lx3+/RybR5PiYRMpVFgO7cOHyIM= -go.mongodb.org/mongo-driver v1.17.1/go.mod h1:wwWm/+BuOddhcq3n68LKRmgk2wXzmF6s0SFOa0GINL4= -go.opentelemetry.io/otel v1.32.0 h1:WnBN+Xjcteh0zdk01SVqV55d/m62NJLJdIyb4y/WO5U= -go.opentelemetry.io/otel v1.32.0/go.mod h1:00DCVSB0RQcnzlwyTfqtxSm+DRr9hpYrHjNGiBHVQIg= -go.opentelemetry.io/otel/metric v1.32.0 h1:xV2umtmNcThh2/a/aCP+h64Xx5wsj8qqnkYZktzNa0M= -go.opentelemetry.io/otel/metric v1.32.0/go.mod h1:jH7CIbbK6SH2V2wE16W05BHCtIDzauciCRLoc/SyMv8= -go.opentelemetry.io/otel/sdk v1.24.0 h1:YMPPDNymmQN3ZgczicBY3B6sf9n62Dlj9pWD3ucgoDw= -go.opentelemetry.io/otel/sdk v1.24.0/go.mod h1:KVrIYw6tEubO9E96HQpcmpTKDVn9gdv35HoYiQWGDFg= -go.opentelemetry.io/otel/trace v1.32.0 h1:WIC9mYrXf8TmY/EXuULKc8hR17vE+Hjv2cssQDe03fM= -go.opentelemetry.io/otel/trace v1.32.0/go.mod h1:+i4rkvCraA+tG6AzwloGaCtkx53Fa+L+V8e9a7YvhT8= -golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= -golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU= +github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/contrib/remote-access/client/main.go b/contrib/remote-access/client/main.go index fcb52293..013a7c43 100644 --- a/contrib/remote-access/client/main.go +++ b/contrib/remote-access/client/main.go @@ -9,8 +9,10 @@ package main */ import ( + "context" "fmt" "log" + "net/http" "os" "os/exec" "os/signal" @@ -18,10 +20,8 @@ import ( "syscall" "time" - "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/client" - "github.com/siemens/wfx/generated/client/jobs" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/cmd/wfxctl/errutil" + "github.com/siemens/wfx/generated/api" flag "github.com/spf13/pflag" ) @@ -74,20 +74,27 @@ func worker() { workflow := "wfx.workflow.remote.access" initialState := "OPEN" limit := int32(1) - queryParams := jobs.NewGetJobsParams(). - WithClientID(&clientID). - WithWorkflow(&workflow). - WithState(&initialState). - WithLimit(&limit) - cfg := client.DefaultTransportConfig() - cfg.Host = fmt.Sprintf("%s:%d", host, port) - c := client.NewHTTPClientWithConfig(strfmt.Default, cfg) + + swagger := errutil.Must(api.GetSwagger()) + basePath := errutil.Must(swagger.Servers.BasePath()) + server := fmt.Sprintf("http://%s:%d%s", host, port, basePath) + httpClient := &http.Client{Timeout: time.Second * 10} + client, err := api.NewClientWithResponses(server, api.WithHTTPClient(httpClient)) + if err != nil { + log.Fatalf("Failed to create client: %s", err) + } + + params := new(api.GetJobsParams) + params.ParamClientID = &clientID + params.ParamWorkflow = &workflow + params.ParamState = &initialState + params.ParamLimit = &limit for !done.Load() { log.Println("Polling for new jobs") - resp, err := c.Jobs.GetJobs(queryParams) - if err == nil && len(resp.Payload.Content) > 0 && !done.Load() { - job := resp.Payload.Content[0] + resp, err := client.GetJobsWithResponse(context.Background(), params) + if err == nil && resp.JSON200 != nil && len(resp.JSON200.Content) > 0 { + job := &resp.JSON200.Content[0] log.Println("Found new job with ID", job.ID) args := []string{ @@ -101,13 +108,13 @@ func worker() { ttydCmd := createTtyCmd(args) - updateJobStatus(c, job, "OPENING", nil) + updateJobStatus(client, job, "OPENING", nil) err := ttydCmd.Start() if err != nil { - updateJobStatus(c, job, "FAILED", err) + updateJobStatus(client, job, "FAILED", err) continue } - updateJobStatus(c, job, "OPENED", nil) + updateJobStatus(client, job, "OPENED", nil) if s := job.Definition["timeout"].(string); s != "" { if d, err := time.ParseDuration(s); err == nil { @@ -118,7 +125,7 @@ func worker() { } } _ = ttydCmd.Wait() - updateJobStatus(c, job, "CLOSED", nil) + updateJobStatus(client, job, "CLOSED", nil) } else { log.Println("Nothing to do") time.Sleep(pollInterval) @@ -126,22 +133,18 @@ func worker() { } } -func updateJobStatus(c *client.WorkflowExecutor, job *model.Job, state string, err error) { +func updateJobStatus(client *api.ClientWithResponses, job *api.Job, state string, err error) { + job.Status = &api.JobStatus{State: state} if err == nil { log.Println("Setting job status to", state) } else { log.Printf("Setting job status to %s, err=%s\n", state, err) - } - job.Status = &model.JobStatus{State: state} - if err != nil { - job.Status.Context = map[string]any{ + job.Status.Context = &map[string]any{ "error": err.Error(), } } - _, err = c.Jobs.PutJobsIDStatus(jobs.NewPutJobsIDStatusParams(). - WithID(job.ID). - WithNewJobStatus(job.Status)) - if err != nil { + resp, err := client.PutJobsIdStatus(context.Background(), job.ID, nil, *job.Status) + if err != nil || resp.StatusCode != http.StatusOK { log.Println("Failed to update job status:", err) } } diff --git a/docs/operations.md b/docs/operations.md index ad605ce5..631d3c72 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -23,11 +23,9 @@ wfx provides two RESTful APIs to interact with it: the northbound operator/manag The northbound API is used to create jobs and execute server-side state transitions, whereas the southbound API is used for client-side transitions. -The complete [wfx API specification](../spec/wfx.swagger.yml) is accessible at runtime via the `/swagger.json` endpoint. +The complete [wfx API specification](../spec/wfx.openapiv3.yml) is accessible at runtime via the `/api/wfx/v1/openapiv3.json` endpoint. Clients may inspect this specification at run-time so to obey the various limits imposed, e.g, for parameter value ranges and array lengths. -For convenience, wfx includes a built-in Swagger UI accessible at runtime via , assuming default listening host and port [configuration](configuration.md). - ### Job Events Job events provide a notification mechanism that informs clients about certain operations happening on jobs. diff --git a/docs/workflows.md b/docs/workflows.md index fa84ebf7..3af9745b 100644 --- a/docs/workflows.md +++ b/docs/workflows.md @@ -8,7 +8,7 @@ More precisely, a _workflow_ consists of - a non-empty finite set of `transitions` correlating states by their names, and - optionally, a set of `groups` collating states by their names, -see the [wfx OpenAPI Specification](../spec/wfx.swagger.yml)'s `Workflow` object for reference. +see the [wfx OpenAPI Specification](../spec/wfx.openapiv3.yml)'s `Workflow` object for reference. wfx supports dynamic loading and unloading of workflows at run-time; when a workflow is loaded into wfx, it is validated to ensure that it adheres to these rules and constraints. @@ -81,7 +81,7 @@ workflows to address them. ### Creating Jobs -A new job can be created by sending a `JobRequest` object (see [wfx OpenAPI Specification](../spec/wfx.swagger.yml)) to wfx's [northbound REST API](operations.md#API). +A new job can be created by sending a `JobRequest` object (see [wfx OpenAPI Specification](../spec/wfx.openapiv3.yml)) to wfx's [northbound REST API](operations.md#API). A JobRequest consists of the following: - a non-empty `clientId` to assign the job to a specific client @@ -269,7 +269,7 @@ echo '{ "title": "expose job api" }' | \ The Task is immediately transitioned to the "NEW" state (Kanban Lane) by wfx on behalf of the Product Owner Parker as the transition's `action` is `IMMEDIATE`. -Note that the piped-in JSON document is the _Job Definition_ (see [wfx OpenAPI Specification](../spec/wfx.swagger.yml)) which is the contract +Note that the piped-in JSON document is the _Job Definition_ (see [wfx OpenAPI Specification](../spec/wfx.openapiv3.yml)) which is the contract between the operator (Product Owner) creating jobs (Tasks) and the clients (Developers) executing those jobs so that they're actually able to process the job. diff --git a/generated/api/wfx.openapi.gen.go b/generated/api/wfx.openapi.gen.go new file mode 100644 index 00000000..e5212047 --- /dev/null +++ b/generated/api/wfx.openapi.gen.go @@ -0,0 +1,5916 @@ +//go:build go1.22 + +// Package api provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.3.0 DO NOT EDIT. +package api + +import ( + "bytes" + "compress/gzip" + "context" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "path" + "strings" + "time" + + "github.com/getkin/kin-openapi/openapi3" + "github.com/oapi-codegen/runtime" + strictnethttp "github.com/oapi-codegen/runtime/strictmiddleware/nethttp" +) + +// Defines values for ActionEnum. +const ( + IMMEDIATE ActionEnum = "IMMEDIATE" + WAIT ActionEnum = "WAIT" +) + +// Defines values for AvailabilityStatus. +const ( + Down AvailabilityStatus = "down" + Unknown AvailabilityStatus = "unknown" + Up AvailabilityStatus = "up" +) + +// Defines values for EligibleEnum. +const ( + CLIENT EligibleEnum = "CLIENT" + WFX EligibleEnum = "WFX" +) + +// Defines values for SortEnum. +const ( + Asc SortEnum = "asc" + Desc SortEnum = "desc" +) + +// ActionEnum defines model for ActionEnum. +type ActionEnum string + +// AvailabilityStatus Enumeration of possible availability statuses. +type AvailabilityStatus string + +// CheckResult Health information for a checked component. +type CheckResult struct { + // Error The check error message, if the check failed. + Error string `json:"error,omitempty"` + + // Status Enumeration of possible availability statuses. + Status AvailabilityStatus `json:"status,omitempty"` + + // Timestamp The time when the check was executed. + Timestamp time.Time `json:"timestamp,omitempty"` +} + +// CheckerResult defines model for CheckerResult. +type CheckerResult struct { + // Details Details contains health information for all checked components. + Details *map[string]CheckResult `json:"details,omitempty"` + + // Info Info contains additional information about this health result. + Info *map[string]interface{} `json:"info,omitempty"` + + // Status Enumeration of possible availability statuses. + Status AvailabilityStatus `json:"status,omitempty"` +} + +// EligibleEnum defines model for EligibleEnum. +type EligibleEnum string + +// Error defines model for Error. +type Error struct { + // Code Identifier code for the reason of the error + Code string `json:"code"` + + // Logref Log correlation ID + Logref string `json:"logref"` + + // Message Error message + Message string `json:"message"` +} + +// ErrorResponse defines model for ErrorResponse. +type ErrorResponse struct { + Errors *[]Error `json:"errors,omitempty"` +} + +// Group defines model for Group. +type Group struct { + Description string `json:"description,omitempty"` + Name string `json:"name"` + + // States A list of states belonging to this group + States []string `json:"states"` +} + +// History defines model for History. +type History struct { + Definition *map[string]interface{} `json:"definition,omitempty"` + + // Mtime Date and time (ISO8601) when the job was modified (set by wfx) + Mtime *time.Time `json:"mtime,omitempty"` + + // Status Job status information + Status *JobStatus `json:"status,omitempty"` +} + +// Job defines model for Job. +type Job struct { + ClientID string `json:"clientId,omitempty"` + Definition map[string]interface{} `json:"definition,omitempty"` + + // History The job's history. Last in, first out (LIFO). Array is truncated if its length exceeds the maximum allowed length. + // By default, the job history is omitted from responses unless explicitly requested by the client (see the `history` URL parameter). + History *[]History `json:"history,omitempty"` + + // ID Unique job ID (wfx-generated) + ID string `json:"id,omitempty"` + + // Mtime Date and time (ISO8601) when the job was last modified (set by wfx) + Mtime *time.Time `json:"mtime"` + + // Status Job status information + Status *JobStatus `json:"status,omitempty"` + + // Stime Date and time (ISO8601) when the job was created (set by wfx). Although stime conceptually always exists, it's nullable because we don't want to serialize stime in some cases (e.g. for job events). + Stime *time.Time `json:"stime"` + Tags TagList `json:"tags,omitempty"` + Workflow *Workflow `json:"workflow,omitempty"` +} + +// JobEvent defines model for JobEvent. +type JobEvent struct { + Action *string `json:"action,omitempty"` + Ctime *time.Time `json:"ctime"` + Job *Job `json:"job,omitempty"` + Tags *[]string `json:"tags,omitempty"` +} + +// JobRequest defines model for JobRequest. +type JobRequest struct { + // ClientID Create job for the given client ID + ClientID string `json:"clientId"` + + // Definition The existing job definition will be replaced with this if this property is not empty. + Definition map[string]interface{} `json:"definition,omitempty"` + Tags TagList `json:"tags,omitempty"` + + // Workflow Workflow name + Workflow string `json:"workflow"` +} + +// JobStatus Job status information +type JobStatus struct { + // ClientID Client which sent the status update + ClientID string `json:"clientId,omitempty"` + + // Context Client-specific JSON object to report additional context information such as error details, stack traces, etc + Context *map[string]interface{} `json:"context,omitempty"` + + // DefinitionHash Job definition hash + DefinitionHash string `json:"definitionHash,omitempty"` + + // Message Reason message/info, free text from client + Message string `json:"message,omitempty"` + + // Progress Current job progress percentage + Progress *int32 `json:"progress,omitempty"` + + // State Name of the new workflow state + State string `json:"state"` +} + +// PaginatedJobList Paginated list of jobs +type PaginatedJobList struct { + Content []Job `json:"content"` + Pagination Pagination `json:"pagination"` +} + +// PaginatedWorkflowList Paginated list of workflows +type PaginatedWorkflowList struct { + Content []Workflow `json:"content"` + Pagination Pagination `json:"pagination"` +} + +// Pagination defines model for Pagination. +type Pagination struct { + // Limit the maximum number of items to return + Limit int32 `json:"limit"` + + // Offset the number of items to skip before starting to return results + Offset int64 `json:"offset"` + + // Total the total number of items + Total int64 `json:"total"` +} + +// SortEnum defines model for SortEnum. +type SortEnum string + +// State defines model for State. +type State struct { + Description string `json:"description,omitempty"` + Name string `json:"name"` +} + +// TagList defines model for TagList. +type TagList = []string + +// Transition defines model for Transition. +type Transition struct { + Action *ActionEnum `json:"action,omitempty"` + Description string `json:"description,omitempty"` + Eligible EligibleEnum `json:"eligible"` + From string `json:"from"` + To string `json:"to"` +} + +// Workflow defines model for Workflow. +type Workflow struct { + // Description Description of the workflow + Description string `json:"description,omitempty"` + Groups []Group `json:"groups,omitempty"` + + // Name User provided unique workflow name + Name string `json:"name"` + States []State `json:"states,omitempty"` + Transitions []Transition `json:"transitions,omitempty"` +} + +// paramClientID defines model for clientId. +type paramClientID = string + +// paramGroup defines model for group. +type paramGroup = []string + +// paramHistory defines model for history. +type paramHistory = bool + +// paramLimit defines model for limit. +type paramLimit = int32 + +// paramOffset defines model for offset. +type paramOffset = int64 + +// ResponseFilter defines model for responseFilter. +type ResponseFilter = string + +// paramSort defines model for sort. +type paramSort = SortEnum + +// paramState defines model for state. +type paramState = string + +// paramTag defines model for tag. +type paramTag = TagList + +// GetJobsParams defines parameters for GetJobs. +type GetJobsParams struct { + // ParamLimit the maximum number of items to return + ParamLimit *paramLimit `form:"limit,omitempty" json:"limit,omitempty"` + + // ParamOffset the number of items to skip before starting to return results + ParamOffset *paramOffset `form:"offset,omitempty" json:"offset,omitempty"` + + // ParamSort the order of returned elements + ParamSort *paramSort `form:"sort,omitempty" json:"sort,omitempty"` + + // ParamState Filter jobs based on the current state value + ParamState *paramState `form:"state,omitempty" json:"state,omitempty"` + + // ParamGroup Filter jobs based on the group they are in + ParamGroup *paramGroup `form:"group,omitempty" json:"group,omitempty"` + + // ParamClientID Filter jobs belonging to a specific client with clientId + ParamClientID *paramClientID `form:"clientId,omitempty" json:"clientId,omitempty"` + + // ParamTag A list of tags + ParamTag *paramTag `form:"tag,omitempty" json:"tag,omitempty"` + + // ParamWorkflow Filter jobs matching by workflow + ParamWorkflow *string `form:"workflow,omitempty" json:"workflow,omitempty"` + + // XResponseFilter Apply a jq-like filter to the response + XResponseFilter *ResponseFilter `json:"X-Response-Filter,omitempty"` +} + +// PostJobsParams defines parameters for PostJobs. +type PostJobsParams struct { + // XResponseFilter Apply a jq-like filter to the response + XResponseFilter *ResponseFilter `json:"X-Response-Filter,omitempty"` +} + +// GetJobsEventsParams defines parameters for GetJobsEvents. +type GetJobsEventsParams struct { + // ClientIDs The job's clientId must be one of these clientIds (comma-separated). + ClientIDs *string `form:"clientIds,omitempty" json:"clientIds,omitempty"` + + // JobIds The job's id must be one of these ids (comma-separated). + JobIds *string `form:"jobIds,omitempty" json:"jobIds,omitempty"` + + // Workflows The job's workflow must be equal to one of the provided workflow names (comma-separated). + Workflows *string `form:"workflows,omitempty" json:"workflows,omitempty"` + + // Tags A (comma-separated) list of tags to include into each job event. This can be used to aggregrate events from multiple wfx instances. + Tags *string `form:"tags,omitempty" json:"tags,omitempty"` +} + +// GetJobsIdParams defines parameters for GetJobsId. +type GetJobsIdParams struct { + // ParamHistory Boolean flag to include the transition history of the job + ParamHistory *paramHistory `form:"history,omitempty" json:"history,omitempty"` + + // XResponseFilter Apply a jq-like filter to the response + XResponseFilter *ResponseFilter `json:"X-Response-Filter,omitempty"` +} + +// GetJobsIdDefinitionParams defines parameters for GetJobsIdDefinition. +type GetJobsIdDefinitionParams struct { + // XResponseFilter Apply a jq-like filter to the response + XResponseFilter *ResponseFilter `json:"X-Response-Filter,omitempty"` +} + +// PutJobsIdDefinitionJSONBody defines parameters for PutJobsIdDefinition. +type PutJobsIdDefinitionJSONBody = map[string]interface{} + +// PutJobsIdDefinitionParams defines parameters for PutJobsIdDefinition. +type PutJobsIdDefinitionParams struct { + // XResponseFilter Apply a jq-like filter to the response + XResponseFilter *ResponseFilter `json:"X-Response-Filter,omitempty"` +} + +// GetJobsIdStatusParams defines parameters for GetJobsIdStatus. +type GetJobsIdStatusParams struct { + // XResponseFilter Apply a jq-like filter to the response + XResponseFilter *ResponseFilter `json:"X-Response-Filter,omitempty"` +} + +// PutJobsIdStatusParams defines parameters for PutJobsIdStatus. +type PutJobsIdStatusParams struct { + // XResponseFilter Apply a jq-like filter to the response + XResponseFilter *ResponseFilter `json:"X-Response-Filter,omitempty"` +} + +// DeleteJobsIdTagsJSONBody defines parameters for DeleteJobsIdTags. +type DeleteJobsIdTagsJSONBody = []string + +// DeleteJobsIdTagsParams defines parameters for DeleteJobsIdTags. +type DeleteJobsIdTagsParams struct { + // XResponseFilter Apply a jq-like filter to the response + XResponseFilter *ResponseFilter `json:"X-Response-Filter,omitempty"` +} + +// GetJobsIdTagsParams defines parameters for GetJobsIdTags. +type GetJobsIdTagsParams struct { + // XResponseFilter Apply a jq-like filter to the response + XResponseFilter *ResponseFilter `json:"X-Response-Filter,omitempty"` +} + +// PostJobsIdTagsJSONBody defines parameters for PostJobsIdTags. +type PostJobsIdTagsJSONBody = []string + +// PostJobsIdTagsParams defines parameters for PostJobsIdTags. +type PostJobsIdTagsParams struct { + // XResponseFilter Apply a jq-like filter to the response + XResponseFilter *ResponseFilter `json:"X-Response-Filter,omitempty"` +} + +// GetWorkflowsParams defines parameters for GetWorkflows. +type GetWorkflowsParams struct { + // ParamLimit the maximum number of items to return + ParamLimit *paramLimit `form:"limit,omitempty" json:"limit,omitempty"` + + // ParamOffset the number of items to skip before starting to return results + ParamOffset *paramOffset `form:"offset,omitempty" json:"offset,omitempty"` + + // ParamSort the order of returned elements + ParamSort *paramSort `form:"sort,omitempty" json:"sort,omitempty"` + + // XResponseFilter Apply a jq-like filter to the response + XResponseFilter *ResponseFilter `json:"X-Response-Filter,omitempty"` +} + +// PostWorkflowsParams defines parameters for PostWorkflows. +type PostWorkflowsParams struct { + // XResponseFilter Apply a jq-like filter to the response + XResponseFilter *ResponseFilter `json:"X-Response-Filter,omitempty"` +} + +// GetWorkflowsNameParams defines parameters for GetWorkflowsName. +type GetWorkflowsNameParams struct { + // XResponseFilter Apply a jq-like filter to the response + XResponseFilter *ResponseFilter `json:"X-Response-Filter,omitempty"` +} + +// PostJobsJSONRequestBody defines body for PostJobs for application/json ContentType. +type PostJobsJSONRequestBody = JobRequest + +// PutJobsIdDefinitionJSONRequestBody defines body for PutJobsIdDefinition for application/json ContentType. +type PutJobsIdDefinitionJSONRequestBody = PutJobsIdDefinitionJSONBody + +// PutJobsIdStatusJSONRequestBody defines body for PutJobsIdStatus for application/json ContentType. +type PutJobsIdStatusJSONRequestBody = JobStatus + +// DeleteJobsIdTagsJSONRequestBody defines body for DeleteJobsIdTags for application/json ContentType. +type DeleteJobsIdTagsJSONRequestBody = DeleteJobsIdTagsJSONBody + +// PostJobsIdTagsJSONRequestBody defines body for PostJobsIdTags for application/json ContentType. +type PostJobsIdTagsJSONRequestBody = PostJobsIdTagsJSONBody + +// PostWorkflowsJSONRequestBody defines body for PostWorkflows for application/json ContentType. +type PostWorkflowsJSONRequestBody = Workflow + +// RequestEditorFn is the function signature for the RequestEditor callback function +type RequestEditorFn func(ctx context.Context, req *http.Request) error + +// Doer performs HTTP requests. +// +// The standard http.Client implements this interface. +type HttpRequestDoer interface { + Do(req *http.Request) (*http.Response, error) +} + +// Client which conforms to the OpenAPI3 specification for this service. +type Client struct { + // The endpoint of the server conforming to this interface, with scheme, + // https://api.deepmap.com for example. This can contain a path relative + // to the server, such as https://api.deepmap.com/dev-test, and all the + // paths in the swagger spec will be appended to the server. + Server string + + // Doer for performing requests, typically a *http.Client with any + // customized settings, such as certificate chains. + Client HttpRequestDoer + + // A list of callbacks for modifying requests which are generated before sending over + // the network. + RequestEditors []RequestEditorFn +} + +// ClientOption allows setting custom parameters during construction +type ClientOption func(*Client) error + +// Creates a new Client, with reasonable defaults +func NewClient(server string, opts ...ClientOption) (*Client, error) { + // create a client with sane default values + client := Client{ + Server: server, + } + // mutate client and add all optional params + for _, o := range opts { + if err := o(&client); err != nil { + return nil, err + } + } + // ensure the server URL always has a trailing slash + if !strings.HasSuffix(client.Server, "/") { + client.Server += "/" + } + // create httpClient, if not already present + if client.Client == nil { + client.Client = &http.Client{} + } + return &client, nil +} + +// WithHTTPClient allows overriding the default Doer, which is +// automatically created using http.Client. This is useful for tests. +func WithHTTPClient(doer HttpRequestDoer) ClientOption { + return func(c *Client) error { + c.Client = doer + return nil + } +} + +// WithRequestEditorFn allows setting up a callback function, which will be +// called right before sending the request. This can be used to mutate the request. +func WithRequestEditorFn(fn RequestEditorFn) ClientOption { + return func(c *Client) error { + c.RequestEditors = append(c.RequestEditors, fn) + return nil + } +} + +// The interface specification for the client above. +type ClientInterface interface { + // GetHealth request + GetHealth(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetJobs request + GetJobs(ctx context.Context, params *GetJobsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // PostJobsWithBody request with any body + PostJobsWithBody(ctx context.Context, params *PostJobsParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + PostJobs(ctx context.Context, params *PostJobsParams, body PostJobsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetJobsEvents request + GetJobsEvents(ctx context.Context, params *GetJobsEventsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // DeleteJobsId request + DeleteJobsId(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetJobsId request + GetJobsId(ctx context.Context, id string, params *GetJobsIdParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetJobsIdDefinition request + GetJobsIdDefinition(ctx context.Context, id string, params *GetJobsIdDefinitionParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // PutJobsIdDefinitionWithBody request with any body + PutJobsIdDefinitionWithBody(ctx context.Context, id string, params *PutJobsIdDefinitionParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + PutJobsIdDefinition(ctx context.Context, id string, params *PutJobsIdDefinitionParams, body PutJobsIdDefinitionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetJobsIdStatus request + GetJobsIdStatus(ctx context.Context, id string, params *GetJobsIdStatusParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // PutJobsIdStatusWithBody request with any body + PutJobsIdStatusWithBody(ctx context.Context, id string, params *PutJobsIdStatusParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + PutJobsIdStatus(ctx context.Context, id string, params *PutJobsIdStatusParams, body PutJobsIdStatusJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // DeleteJobsIdTagsWithBody request with any body + DeleteJobsIdTagsWithBody(ctx context.Context, id string, params *DeleteJobsIdTagsParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + DeleteJobsIdTags(ctx context.Context, id string, params *DeleteJobsIdTagsParams, body DeleteJobsIdTagsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetJobsIdTags request + GetJobsIdTags(ctx context.Context, id string, params *GetJobsIdTagsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // PostJobsIdTagsWithBody request with any body + PostJobsIdTagsWithBody(ctx context.Context, id string, params *PostJobsIdTagsParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + PostJobsIdTags(ctx context.Context, id string, params *PostJobsIdTagsParams, body PostJobsIdTagsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetVersion request + GetVersion(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetWorkflows request + GetWorkflows(ctx context.Context, params *GetWorkflowsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // PostWorkflowsWithBody request with any body + PostWorkflowsWithBody(ctx context.Context, params *PostWorkflowsParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + PostWorkflows(ctx context.Context, params *PostWorkflowsParams, body PostWorkflowsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // DeleteWorkflowsName request + DeleteWorkflowsName(ctx context.Context, name string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetWorkflowsName request + GetWorkflowsName(ctx context.Context, name string, params *GetWorkflowsNameParams, reqEditors ...RequestEditorFn) (*http.Response, error) +} + +func (c *Client) GetHealth(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetHealthRequest(c.Server) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetJobs(ctx context.Context, params *GetJobsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetJobsRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) PostJobsWithBody(ctx context.Context, params *PostJobsParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewPostJobsRequestWithBody(c.Server, params, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) PostJobs(ctx context.Context, params *PostJobsParams, body PostJobsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewPostJobsRequest(c.Server, params, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetJobsEvents(ctx context.Context, params *GetJobsEventsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetJobsEventsRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) DeleteJobsId(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewDeleteJobsIdRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetJobsId(ctx context.Context, id string, params *GetJobsIdParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetJobsIdRequest(c.Server, id, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetJobsIdDefinition(ctx context.Context, id string, params *GetJobsIdDefinitionParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetJobsIdDefinitionRequest(c.Server, id, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) PutJobsIdDefinitionWithBody(ctx context.Context, id string, params *PutJobsIdDefinitionParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewPutJobsIdDefinitionRequestWithBody(c.Server, id, params, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) PutJobsIdDefinition(ctx context.Context, id string, params *PutJobsIdDefinitionParams, body PutJobsIdDefinitionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewPutJobsIdDefinitionRequest(c.Server, id, params, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetJobsIdStatus(ctx context.Context, id string, params *GetJobsIdStatusParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetJobsIdStatusRequest(c.Server, id, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) PutJobsIdStatusWithBody(ctx context.Context, id string, params *PutJobsIdStatusParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewPutJobsIdStatusRequestWithBody(c.Server, id, params, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) PutJobsIdStatus(ctx context.Context, id string, params *PutJobsIdStatusParams, body PutJobsIdStatusJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewPutJobsIdStatusRequest(c.Server, id, params, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) DeleteJobsIdTagsWithBody(ctx context.Context, id string, params *DeleteJobsIdTagsParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewDeleteJobsIdTagsRequestWithBody(c.Server, id, params, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) DeleteJobsIdTags(ctx context.Context, id string, params *DeleteJobsIdTagsParams, body DeleteJobsIdTagsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewDeleteJobsIdTagsRequest(c.Server, id, params, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetJobsIdTags(ctx context.Context, id string, params *GetJobsIdTagsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetJobsIdTagsRequest(c.Server, id, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) PostJobsIdTagsWithBody(ctx context.Context, id string, params *PostJobsIdTagsParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewPostJobsIdTagsRequestWithBody(c.Server, id, params, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) PostJobsIdTags(ctx context.Context, id string, params *PostJobsIdTagsParams, body PostJobsIdTagsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewPostJobsIdTagsRequest(c.Server, id, params, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetVersion(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetVersionRequest(c.Server) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetWorkflows(ctx context.Context, params *GetWorkflowsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetWorkflowsRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) PostWorkflowsWithBody(ctx context.Context, params *PostWorkflowsParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewPostWorkflowsRequestWithBody(c.Server, params, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) PostWorkflows(ctx context.Context, params *PostWorkflowsParams, body PostWorkflowsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewPostWorkflowsRequest(c.Server, params, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) DeleteWorkflowsName(ctx context.Context, name string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewDeleteWorkflowsNameRequest(c.Server, name) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetWorkflowsName(ctx context.Context, name string, params *GetWorkflowsNameParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetWorkflowsNameRequest(c.Server, name, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// NewGetHealthRequest generates requests for GetHealth +func NewGetHealthRequest(server string) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/health") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetJobsRequest generates requests for GetJobs +func NewGetJobsRequest(server string, params *GetJobsParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/jobs") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + queryValues := queryURL.Query() + + if params.ParamLimit != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "limit", runtime.ParamLocationQuery, *params.ParamLimit); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + if params.ParamOffset != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "offset", runtime.ParamLocationQuery, *params.ParamOffset); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + if params.ParamSort != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "sort", runtime.ParamLocationQuery, *params.ParamSort); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + if params.ParamState != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "state", runtime.ParamLocationQuery, *params.ParamState); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + if params.ParamGroup != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", false, "group", runtime.ParamLocationQuery, *params.ParamGroup); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + if params.ParamClientID != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "clientId", runtime.ParamLocationQuery, *params.ParamClientID); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + if params.ParamTag != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", false, "tag", runtime.ParamLocationQuery, *params.ParamTag); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + if params.ParamWorkflow != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "workflow", runtime.ParamLocationQuery, *params.ParamWorkflow); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + queryURL.RawQuery = queryValues.Encode() + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + if params != nil { + + if params.XResponseFilter != nil { + var headerParam0 string + + headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Response-Filter", runtime.ParamLocationHeader, *params.XResponseFilter) + if err != nil { + return nil, err + } + + req.Header.Set("X-Response-Filter", headerParam0) + } + + } + + return req, nil +} + +// NewPostJobsRequest calls the generic PostJobs builder with application/json body +func NewPostJobsRequest(server string, params *PostJobsParams, body PostJobsJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewPostJobsRequestWithBody(server, params, "application/json", bodyReader) +} + +// NewPostJobsRequestWithBody generates requests for PostJobs with any type of body +func NewPostJobsRequestWithBody(server string, params *PostJobsParams, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/jobs") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("POST", queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + if params != nil { + + if params.XResponseFilter != nil { + var headerParam0 string + + headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Response-Filter", runtime.ParamLocationHeader, *params.XResponseFilter) + if err != nil { + return nil, err + } + + req.Header.Set("X-Response-Filter", headerParam0) + } + + } + + return req, nil +} + +// NewGetJobsEventsRequest generates requests for GetJobsEvents +func NewGetJobsEventsRequest(server string, params *GetJobsEventsParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/jobs/events") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + queryValues := queryURL.Query() + + if params.ClientIDs != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "clientIds", runtime.ParamLocationQuery, *params.ClientIDs); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + if params.JobIds != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "jobIds", runtime.ParamLocationQuery, *params.JobIds); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + if params.Workflows != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "workflows", runtime.ParamLocationQuery, *params.Workflows); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + if params.Tags != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "tags", runtime.ParamLocationQuery, *params.Tags); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + queryURL.RawQuery = queryValues.Encode() + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewDeleteJobsIdRequest generates requests for DeleteJobsId +func NewDeleteJobsIdRequest(server string, id string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "id", runtime.ParamLocationPath, id) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/jobs/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("DELETE", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetJobsIdRequest generates requests for GetJobsId +func NewGetJobsIdRequest(server string, id string, params *GetJobsIdParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "id", runtime.ParamLocationPath, id) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/jobs/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + queryValues := queryURL.Query() + + if params.ParamHistory != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "history", runtime.ParamLocationQuery, *params.ParamHistory); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + queryURL.RawQuery = queryValues.Encode() + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + if params != nil { + + if params.XResponseFilter != nil { + var headerParam0 string + + headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Response-Filter", runtime.ParamLocationHeader, *params.XResponseFilter) + if err != nil { + return nil, err + } + + req.Header.Set("X-Response-Filter", headerParam0) + } + + } + + return req, nil +} + +// NewGetJobsIdDefinitionRequest generates requests for GetJobsIdDefinition +func NewGetJobsIdDefinitionRequest(server string, id string, params *GetJobsIdDefinitionParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "id", runtime.ParamLocationPath, id) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/jobs/%s/definition", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + if params != nil { + + if params.XResponseFilter != nil { + var headerParam0 string + + headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Response-Filter", runtime.ParamLocationHeader, *params.XResponseFilter) + if err != nil { + return nil, err + } + + req.Header.Set("X-Response-Filter", headerParam0) + } + + } + + return req, nil +} + +// NewPutJobsIdDefinitionRequest calls the generic PutJobsIdDefinition builder with application/json body +func NewPutJobsIdDefinitionRequest(server string, id string, params *PutJobsIdDefinitionParams, body PutJobsIdDefinitionJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewPutJobsIdDefinitionRequestWithBody(server, id, params, "application/json", bodyReader) +} + +// NewPutJobsIdDefinitionRequestWithBody generates requests for PutJobsIdDefinition with any type of body +func NewPutJobsIdDefinitionRequestWithBody(server string, id string, params *PutJobsIdDefinitionParams, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "id", runtime.ParamLocationPath, id) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/jobs/%s/definition", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("PUT", queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + if params != nil { + + if params.XResponseFilter != nil { + var headerParam0 string + + headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Response-Filter", runtime.ParamLocationHeader, *params.XResponseFilter) + if err != nil { + return nil, err + } + + req.Header.Set("X-Response-Filter", headerParam0) + } + + } + + return req, nil +} + +// NewGetJobsIdStatusRequest generates requests for GetJobsIdStatus +func NewGetJobsIdStatusRequest(server string, id string, params *GetJobsIdStatusParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "id", runtime.ParamLocationPath, id) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/jobs/%s/status", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + if params != nil { + + if params.XResponseFilter != nil { + var headerParam0 string + + headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Response-Filter", runtime.ParamLocationHeader, *params.XResponseFilter) + if err != nil { + return nil, err + } + + req.Header.Set("X-Response-Filter", headerParam0) + } + + } + + return req, nil +} + +// NewPutJobsIdStatusRequest calls the generic PutJobsIdStatus builder with application/json body +func NewPutJobsIdStatusRequest(server string, id string, params *PutJobsIdStatusParams, body PutJobsIdStatusJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewPutJobsIdStatusRequestWithBody(server, id, params, "application/json", bodyReader) +} + +// NewPutJobsIdStatusRequestWithBody generates requests for PutJobsIdStatus with any type of body +func NewPutJobsIdStatusRequestWithBody(server string, id string, params *PutJobsIdStatusParams, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "id", runtime.ParamLocationPath, id) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/jobs/%s/status", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("PUT", queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + if params != nil { + + if params.XResponseFilter != nil { + var headerParam0 string + + headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Response-Filter", runtime.ParamLocationHeader, *params.XResponseFilter) + if err != nil { + return nil, err + } + + req.Header.Set("X-Response-Filter", headerParam0) + } + + } + + return req, nil +} + +// NewDeleteJobsIdTagsRequest calls the generic DeleteJobsIdTags builder with application/json body +func NewDeleteJobsIdTagsRequest(server string, id string, params *DeleteJobsIdTagsParams, body DeleteJobsIdTagsJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewDeleteJobsIdTagsRequestWithBody(server, id, params, "application/json", bodyReader) +} + +// NewDeleteJobsIdTagsRequestWithBody generates requests for DeleteJobsIdTags with any type of body +func NewDeleteJobsIdTagsRequestWithBody(server string, id string, params *DeleteJobsIdTagsParams, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "id", runtime.ParamLocationPath, id) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/jobs/%s/tags", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("DELETE", queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + if params != nil { + + if params.XResponseFilter != nil { + var headerParam0 string + + headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Response-Filter", runtime.ParamLocationHeader, *params.XResponseFilter) + if err != nil { + return nil, err + } + + req.Header.Set("X-Response-Filter", headerParam0) + } + + } + + return req, nil +} + +// NewGetJobsIdTagsRequest generates requests for GetJobsIdTags +func NewGetJobsIdTagsRequest(server string, id string, params *GetJobsIdTagsParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "id", runtime.ParamLocationPath, id) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/jobs/%s/tags", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + if params != nil { + + if params.XResponseFilter != nil { + var headerParam0 string + + headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Response-Filter", runtime.ParamLocationHeader, *params.XResponseFilter) + if err != nil { + return nil, err + } + + req.Header.Set("X-Response-Filter", headerParam0) + } + + } + + return req, nil +} + +// NewPostJobsIdTagsRequest calls the generic PostJobsIdTags builder with application/json body +func NewPostJobsIdTagsRequest(server string, id string, params *PostJobsIdTagsParams, body PostJobsIdTagsJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewPostJobsIdTagsRequestWithBody(server, id, params, "application/json", bodyReader) +} + +// NewPostJobsIdTagsRequestWithBody generates requests for PostJobsIdTags with any type of body +func NewPostJobsIdTagsRequestWithBody(server string, id string, params *PostJobsIdTagsParams, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "id", runtime.ParamLocationPath, id) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/jobs/%s/tags", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("POST", queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + if params != nil { + + if params.XResponseFilter != nil { + var headerParam0 string + + headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Response-Filter", runtime.ParamLocationHeader, *params.XResponseFilter) + if err != nil { + return nil, err + } + + req.Header.Set("X-Response-Filter", headerParam0) + } + + } + + return req, nil +} + +// NewGetVersionRequest generates requests for GetVersion +func NewGetVersionRequest(server string) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/version") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetWorkflowsRequest generates requests for GetWorkflows +func NewGetWorkflowsRequest(server string, params *GetWorkflowsParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/workflows") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + queryValues := queryURL.Query() + + if params.ParamLimit != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "limit", runtime.ParamLocationQuery, *params.ParamLimit); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + if params.ParamOffset != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "offset", runtime.ParamLocationQuery, *params.ParamOffset); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + if params.ParamSort != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "sort", runtime.ParamLocationQuery, *params.ParamSort); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + queryURL.RawQuery = queryValues.Encode() + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + if params != nil { + + if params.XResponseFilter != nil { + var headerParam0 string + + headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Response-Filter", runtime.ParamLocationHeader, *params.XResponseFilter) + if err != nil { + return nil, err + } + + req.Header.Set("X-Response-Filter", headerParam0) + } + + } + + return req, nil +} + +// NewPostWorkflowsRequest calls the generic PostWorkflows builder with application/json body +func NewPostWorkflowsRequest(server string, params *PostWorkflowsParams, body PostWorkflowsJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewPostWorkflowsRequestWithBody(server, params, "application/json", bodyReader) +} + +// NewPostWorkflowsRequestWithBody generates requests for PostWorkflows with any type of body +func NewPostWorkflowsRequestWithBody(server string, params *PostWorkflowsParams, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/workflows") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("POST", queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + if params != nil { + + if params.XResponseFilter != nil { + var headerParam0 string + + headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Response-Filter", runtime.ParamLocationHeader, *params.XResponseFilter) + if err != nil { + return nil, err + } + + req.Header.Set("X-Response-Filter", headerParam0) + } + + } + + return req, nil +} + +// NewDeleteWorkflowsNameRequest generates requests for DeleteWorkflowsName +func NewDeleteWorkflowsNameRequest(server string, name string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "name", runtime.ParamLocationPath, name) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/workflows/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("DELETE", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetWorkflowsNameRequest generates requests for GetWorkflowsName +func NewGetWorkflowsNameRequest(server string, name string, params *GetWorkflowsNameParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "name", runtime.ParamLocationPath, name) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/workflows/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + if params != nil { + + if params.XResponseFilter != nil { + var headerParam0 string + + headerParam0, err = runtime.StyleParamWithLocation("simple", false, "X-Response-Filter", runtime.ParamLocationHeader, *params.XResponseFilter) + if err != nil { + return nil, err + } + + req.Header.Set("X-Response-Filter", headerParam0) + } + + } + + return req, nil +} + +func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { + for _, r := range c.RequestEditors { + if err := r(ctx, req); err != nil { + return err + } + } + for _, r := range additionalEditors { + if err := r(ctx, req); err != nil { + return err + } + } + return nil +} + +// ClientWithResponses builds on ClientInterface to offer response payloads +type ClientWithResponses struct { + ClientInterface +} + +// NewClientWithResponses creates a new ClientWithResponses, which wraps +// Client with return type handling +func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { + client, err := NewClient(server, opts...) + if err != nil { + return nil, err + } + return &ClientWithResponses{client}, nil +} + +// WithBaseURL overrides the baseURL. +func WithBaseURL(baseURL string) ClientOption { + return func(c *Client) error { + newBaseURL, err := url.Parse(baseURL) + if err != nil { + return err + } + c.Server = newBaseURL.String() + return nil + } +} + +// ClientWithResponsesInterface is the interface specification for the client with responses above. +type ClientWithResponsesInterface interface { + // GetHealthWithResponse request + GetHealthWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetHealthResponse, error) + + // GetJobsWithResponse request + GetJobsWithResponse(ctx context.Context, params *GetJobsParams, reqEditors ...RequestEditorFn) (*GetJobsResponse, error) + + // PostJobsWithBodyWithResponse request with any body + PostJobsWithBodyWithResponse(ctx context.Context, params *PostJobsParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PostJobsResponse, error) + + PostJobsWithResponse(ctx context.Context, params *PostJobsParams, body PostJobsJSONRequestBody, reqEditors ...RequestEditorFn) (*PostJobsResponse, error) + + // GetJobsEventsWithResponse request + GetJobsEventsWithResponse(ctx context.Context, params *GetJobsEventsParams, reqEditors ...RequestEditorFn) (*GetJobsEventsResponse, error) + + // DeleteJobsIdWithResponse request + DeleteJobsIdWithResponse(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*DeleteJobsIdResponse, error) + + // GetJobsIdWithResponse request + GetJobsIdWithResponse(ctx context.Context, id string, params *GetJobsIdParams, reqEditors ...RequestEditorFn) (*GetJobsIdResponse, error) + + // GetJobsIdDefinitionWithResponse request + GetJobsIdDefinitionWithResponse(ctx context.Context, id string, params *GetJobsIdDefinitionParams, reqEditors ...RequestEditorFn) (*GetJobsIdDefinitionResponse, error) + + // PutJobsIdDefinitionWithBodyWithResponse request with any body + PutJobsIdDefinitionWithBodyWithResponse(ctx context.Context, id string, params *PutJobsIdDefinitionParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PutJobsIdDefinitionResponse, error) + + PutJobsIdDefinitionWithResponse(ctx context.Context, id string, params *PutJobsIdDefinitionParams, body PutJobsIdDefinitionJSONRequestBody, reqEditors ...RequestEditorFn) (*PutJobsIdDefinitionResponse, error) + + // GetJobsIdStatusWithResponse request + GetJobsIdStatusWithResponse(ctx context.Context, id string, params *GetJobsIdStatusParams, reqEditors ...RequestEditorFn) (*GetJobsIdStatusResponse, error) + + // PutJobsIdStatusWithBodyWithResponse request with any body + PutJobsIdStatusWithBodyWithResponse(ctx context.Context, id string, params *PutJobsIdStatusParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PutJobsIdStatusResponse, error) + + PutJobsIdStatusWithResponse(ctx context.Context, id string, params *PutJobsIdStatusParams, body PutJobsIdStatusJSONRequestBody, reqEditors ...RequestEditorFn) (*PutJobsIdStatusResponse, error) + + // DeleteJobsIdTagsWithBodyWithResponse request with any body + DeleteJobsIdTagsWithBodyWithResponse(ctx context.Context, id string, params *DeleteJobsIdTagsParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*DeleteJobsIdTagsResponse, error) + + DeleteJobsIdTagsWithResponse(ctx context.Context, id string, params *DeleteJobsIdTagsParams, body DeleteJobsIdTagsJSONRequestBody, reqEditors ...RequestEditorFn) (*DeleteJobsIdTagsResponse, error) + + // GetJobsIdTagsWithResponse request + GetJobsIdTagsWithResponse(ctx context.Context, id string, params *GetJobsIdTagsParams, reqEditors ...RequestEditorFn) (*GetJobsIdTagsResponse, error) + + // PostJobsIdTagsWithBodyWithResponse request with any body + PostJobsIdTagsWithBodyWithResponse(ctx context.Context, id string, params *PostJobsIdTagsParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PostJobsIdTagsResponse, error) + + PostJobsIdTagsWithResponse(ctx context.Context, id string, params *PostJobsIdTagsParams, body PostJobsIdTagsJSONRequestBody, reqEditors ...RequestEditorFn) (*PostJobsIdTagsResponse, error) + + // GetVersionWithResponse request + GetVersionWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetVersionResponse, error) + + // GetWorkflowsWithResponse request + GetWorkflowsWithResponse(ctx context.Context, params *GetWorkflowsParams, reqEditors ...RequestEditorFn) (*GetWorkflowsResponse, error) + + // PostWorkflowsWithBodyWithResponse request with any body + PostWorkflowsWithBodyWithResponse(ctx context.Context, params *PostWorkflowsParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PostWorkflowsResponse, error) + + PostWorkflowsWithResponse(ctx context.Context, params *PostWorkflowsParams, body PostWorkflowsJSONRequestBody, reqEditors ...RequestEditorFn) (*PostWorkflowsResponse, error) + + // DeleteWorkflowsNameWithResponse request + DeleteWorkflowsNameWithResponse(ctx context.Context, name string, reqEditors ...RequestEditorFn) (*DeleteWorkflowsNameResponse, error) + + // GetWorkflowsNameWithResponse request + GetWorkflowsNameWithResponse(ctx context.Context, name string, params *GetWorkflowsNameParams, reqEditors ...RequestEditorFn) (*GetWorkflowsNameResponse, error) +} + +type GetHealthResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *CheckerResult + JSON503 *CheckerResult +} + +// Status returns HTTPResponse.Status +func (r GetHealthResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetHealthResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetJobsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *PaginatedJobList + JSON400 *ErrorResponse + JSONDefault *ErrorResponse +} + +// Status returns HTTPResponse.Status +func (r GetJobsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetJobsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type PostJobsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *Job + JSON400 *ErrorResponse +} + +// Status returns HTTPResponse.Status +func (r PostJobsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r PostJobsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetJobsEventsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON400 *ErrorResponse + JSON404 *ErrorResponse +} + +// Status returns HTTPResponse.Status +func (r GetJobsEventsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetJobsEventsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type DeleteJobsIdResponse struct { + Body []byte + HTTPResponse *http.Response + JSON404 *ErrorResponse +} + +// Status returns HTTPResponse.Status +func (r DeleteJobsIdResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r DeleteJobsIdResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetJobsIdResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Job + JSON400 *ErrorResponse + JSON404 *ErrorResponse +} + +// Status returns HTTPResponse.Status +func (r GetJobsIdResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetJobsIdResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetJobsIdDefinitionResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *map[string]interface{} + JSON404 *ErrorResponse +} + +// Status returns HTTPResponse.Status +func (r GetJobsIdDefinitionResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetJobsIdDefinitionResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type PutJobsIdDefinitionResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *map[string]interface{} + JSON400 *ErrorResponse + JSON404 *ErrorResponse +} + +// Status returns HTTPResponse.Status +func (r PutJobsIdDefinitionResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r PutJobsIdDefinitionResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetJobsIdStatusResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *JobStatus + JSON404 *ErrorResponse +} + +// Status returns HTTPResponse.Status +func (r GetJobsIdStatusResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetJobsIdStatusResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type PutJobsIdStatusResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *JobStatus + JSON400 *ErrorResponse + JSON404 *ErrorResponse +} + +// Status returns HTTPResponse.Status +func (r PutJobsIdStatusResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r PutJobsIdStatusResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type DeleteJobsIdTagsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *TagList + JSON400 *ErrorResponse + JSON404 *ErrorResponse +} + +// Status returns HTTPResponse.Status +func (r DeleteJobsIdTagsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r DeleteJobsIdTagsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetJobsIdTagsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *TagList + JSON404 *ErrorResponse +} + +// Status returns HTTPResponse.Status +func (r GetJobsIdTagsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetJobsIdTagsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type PostJobsIdTagsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *TagList + JSON400 *ErrorResponse + JSON404 *ErrorResponse +} + +// Status returns HTTPResponse.Status +func (r PostJobsIdTagsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r PostJobsIdTagsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetVersionResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *struct { + ApiVersion string `json:"apiVersion,omitempty"` + BuildDate time.Time `json:"buildDate,omitempty"` + Commit string `json:"commit,omitempty"` + Version string `json:"version,omitempty"` + } +} + +// Status returns HTTPResponse.Status +func (r GetVersionResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetVersionResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetWorkflowsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *PaginatedWorkflowList +} + +// Status returns HTTPResponse.Status +func (r GetWorkflowsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetWorkflowsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type PostWorkflowsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *Workflow + JSON400 *ErrorResponse +} + +// Status returns HTTPResponse.Status +func (r PostWorkflowsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r PostWorkflowsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type DeleteWorkflowsNameResponse struct { + Body []byte + HTTPResponse *http.Response + JSON404 *ErrorResponse +} + +// Status returns HTTPResponse.Status +func (r DeleteWorkflowsNameResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r DeleteWorkflowsNameResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetWorkflowsNameResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Workflow + JSON400 *ErrorResponse + JSON404 *ErrorResponse +} + +// Status returns HTTPResponse.Status +func (r GetWorkflowsNameResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetWorkflowsNameResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// GetHealthWithResponse request returning *GetHealthResponse +func (c *ClientWithResponses) GetHealthWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetHealthResponse, error) { + rsp, err := c.GetHealth(ctx, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetHealthResponse(rsp) +} + +// GetJobsWithResponse request returning *GetJobsResponse +func (c *ClientWithResponses) GetJobsWithResponse(ctx context.Context, params *GetJobsParams, reqEditors ...RequestEditorFn) (*GetJobsResponse, error) { + rsp, err := c.GetJobs(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetJobsResponse(rsp) +} + +// PostJobsWithBodyWithResponse request with arbitrary body returning *PostJobsResponse +func (c *ClientWithResponses) PostJobsWithBodyWithResponse(ctx context.Context, params *PostJobsParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PostJobsResponse, error) { + rsp, err := c.PostJobsWithBody(ctx, params, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParsePostJobsResponse(rsp) +} + +func (c *ClientWithResponses) PostJobsWithResponse(ctx context.Context, params *PostJobsParams, body PostJobsJSONRequestBody, reqEditors ...RequestEditorFn) (*PostJobsResponse, error) { + rsp, err := c.PostJobs(ctx, params, body, reqEditors...) + if err != nil { + return nil, err + } + return ParsePostJobsResponse(rsp) +} + +// GetJobsEventsWithResponse request returning *GetJobsEventsResponse +func (c *ClientWithResponses) GetJobsEventsWithResponse(ctx context.Context, params *GetJobsEventsParams, reqEditors ...RequestEditorFn) (*GetJobsEventsResponse, error) { + rsp, err := c.GetJobsEvents(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetJobsEventsResponse(rsp) +} + +// DeleteJobsIdWithResponse request returning *DeleteJobsIdResponse +func (c *ClientWithResponses) DeleteJobsIdWithResponse(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*DeleteJobsIdResponse, error) { + rsp, err := c.DeleteJobsId(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParseDeleteJobsIdResponse(rsp) +} + +// GetJobsIdWithResponse request returning *GetJobsIdResponse +func (c *ClientWithResponses) GetJobsIdWithResponse(ctx context.Context, id string, params *GetJobsIdParams, reqEditors ...RequestEditorFn) (*GetJobsIdResponse, error) { + rsp, err := c.GetJobsId(ctx, id, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetJobsIdResponse(rsp) +} + +// GetJobsIdDefinitionWithResponse request returning *GetJobsIdDefinitionResponse +func (c *ClientWithResponses) GetJobsIdDefinitionWithResponse(ctx context.Context, id string, params *GetJobsIdDefinitionParams, reqEditors ...RequestEditorFn) (*GetJobsIdDefinitionResponse, error) { + rsp, err := c.GetJobsIdDefinition(ctx, id, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetJobsIdDefinitionResponse(rsp) +} + +// PutJobsIdDefinitionWithBodyWithResponse request with arbitrary body returning *PutJobsIdDefinitionResponse +func (c *ClientWithResponses) PutJobsIdDefinitionWithBodyWithResponse(ctx context.Context, id string, params *PutJobsIdDefinitionParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PutJobsIdDefinitionResponse, error) { + rsp, err := c.PutJobsIdDefinitionWithBody(ctx, id, params, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParsePutJobsIdDefinitionResponse(rsp) +} + +func (c *ClientWithResponses) PutJobsIdDefinitionWithResponse(ctx context.Context, id string, params *PutJobsIdDefinitionParams, body PutJobsIdDefinitionJSONRequestBody, reqEditors ...RequestEditorFn) (*PutJobsIdDefinitionResponse, error) { + rsp, err := c.PutJobsIdDefinition(ctx, id, params, body, reqEditors...) + if err != nil { + return nil, err + } + return ParsePutJobsIdDefinitionResponse(rsp) +} + +// GetJobsIdStatusWithResponse request returning *GetJobsIdStatusResponse +func (c *ClientWithResponses) GetJobsIdStatusWithResponse(ctx context.Context, id string, params *GetJobsIdStatusParams, reqEditors ...RequestEditorFn) (*GetJobsIdStatusResponse, error) { + rsp, err := c.GetJobsIdStatus(ctx, id, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetJobsIdStatusResponse(rsp) +} + +// PutJobsIdStatusWithBodyWithResponse request with arbitrary body returning *PutJobsIdStatusResponse +func (c *ClientWithResponses) PutJobsIdStatusWithBodyWithResponse(ctx context.Context, id string, params *PutJobsIdStatusParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PutJobsIdStatusResponse, error) { + rsp, err := c.PutJobsIdStatusWithBody(ctx, id, params, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParsePutJobsIdStatusResponse(rsp) +} + +func (c *ClientWithResponses) PutJobsIdStatusWithResponse(ctx context.Context, id string, params *PutJobsIdStatusParams, body PutJobsIdStatusJSONRequestBody, reqEditors ...RequestEditorFn) (*PutJobsIdStatusResponse, error) { + rsp, err := c.PutJobsIdStatus(ctx, id, params, body, reqEditors...) + if err != nil { + return nil, err + } + return ParsePutJobsIdStatusResponse(rsp) +} + +// DeleteJobsIdTagsWithBodyWithResponse request with arbitrary body returning *DeleteJobsIdTagsResponse +func (c *ClientWithResponses) DeleteJobsIdTagsWithBodyWithResponse(ctx context.Context, id string, params *DeleteJobsIdTagsParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*DeleteJobsIdTagsResponse, error) { + rsp, err := c.DeleteJobsIdTagsWithBody(ctx, id, params, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseDeleteJobsIdTagsResponse(rsp) +} + +func (c *ClientWithResponses) DeleteJobsIdTagsWithResponse(ctx context.Context, id string, params *DeleteJobsIdTagsParams, body DeleteJobsIdTagsJSONRequestBody, reqEditors ...RequestEditorFn) (*DeleteJobsIdTagsResponse, error) { + rsp, err := c.DeleteJobsIdTags(ctx, id, params, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseDeleteJobsIdTagsResponse(rsp) +} + +// GetJobsIdTagsWithResponse request returning *GetJobsIdTagsResponse +func (c *ClientWithResponses) GetJobsIdTagsWithResponse(ctx context.Context, id string, params *GetJobsIdTagsParams, reqEditors ...RequestEditorFn) (*GetJobsIdTagsResponse, error) { + rsp, err := c.GetJobsIdTags(ctx, id, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetJobsIdTagsResponse(rsp) +} + +// PostJobsIdTagsWithBodyWithResponse request with arbitrary body returning *PostJobsIdTagsResponse +func (c *ClientWithResponses) PostJobsIdTagsWithBodyWithResponse(ctx context.Context, id string, params *PostJobsIdTagsParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PostJobsIdTagsResponse, error) { + rsp, err := c.PostJobsIdTagsWithBody(ctx, id, params, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParsePostJobsIdTagsResponse(rsp) +} + +func (c *ClientWithResponses) PostJobsIdTagsWithResponse(ctx context.Context, id string, params *PostJobsIdTagsParams, body PostJobsIdTagsJSONRequestBody, reqEditors ...RequestEditorFn) (*PostJobsIdTagsResponse, error) { + rsp, err := c.PostJobsIdTags(ctx, id, params, body, reqEditors...) + if err != nil { + return nil, err + } + return ParsePostJobsIdTagsResponse(rsp) +} + +// GetVersionWithResponse request returning *GetVersionResponse +func (c *ClientWithResponses) GetVersionWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetVersionResponse, error) { + rsp, err := c.GetVersion(ctx, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetVersionResponse(rsp) +} + +// GetWorkflowsWithResponse request returning *GetWorkflowsResponse +func (c *ClientWithResponses) GetWorkflowsWithResponse(ctx context.Context, params *GetWorkflowsParams, reqEditors ...RequestEditorFn) (*GetWorkflowsResponse, error) { + rsp, err := c.GetWorkflows(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetWorkflowsResponse(rsp) +} + +// PostWorkflowsWithBodyWithResponse request with arbitrary body returning *PostWorkflowsResponse +func (c *ClientWithResponses) PostWorkflowsWithBodyWithResponse(ctx context.Context, params *PostWorkflowsParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PostWorkflowsResponse, error) { + rsp, err := c.PostWorkflowsWithBody(ctx, params, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParsePostWorkflowsResponse(rsp) +} + +func (c *ClientWithResponses) PostWorkflowsWithResponse(ctx context.Context, params *PostWorkflowsParams, body PostWorkflowsJSONRequestBody, reqEditors ...RequestEditorFn) (*PostWorkflowsResponse, error) { + rsp, err := c.PostWorkflows(ctx, params, body, reqEditors...) + if err != nil { + return nil, err + } + return ParsePostWorkflowsResponse(rsp) +} + +// DeleteWorkflowsNameWithResponse request returning *DeleteWorkflowsNameResponse +func (c *ClientWithResponses) DeleteWorkflowsNameWithResponse(ctx context.Context, name string, reqEditors ...RequestEditorFn) (*DeleteWorkflowsNameResponse, error) { + rsp, err := c.DeleteWorkflowsName(ctx, name, reqEditors...) + if err != nil { + return nil, err + } + return ParseDeleteWorkflowsNameResponse(rsp) +} + +// GetWorkflowsNameWithResponse request returning *GetWorkflowsNameResponse +func (c *ClientWithResponses) GetWorkflowsNameWithResponse(ctx context.Context, name string, params *GetWorkflowsNameParams, reqEditors ...RequestEditorFn) (*GetWorkflowsNameResponse, error) { + rsp, err := c.GetWorkflowsName(ctx, name, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetWorkflowsNameResponse(rsp) +} + +// ParseGetHealthResponse parses an HTTP response from a GetHealthWithResponse call +func ParseGetHealthResponse(rsp *http.Response) (*GetHealthResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetHealthResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest CheckerResult + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest CheckerResult + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON503 = &dest + + } + + return response, nil +} + +// ParseGetJobsResponse parses an HTTP response from a GetJobsWithResponse call +func ParseGetJobsResponse(rsp *http.Response) (*GetJobsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetJobsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest PaginatedJobList + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSONDefault = &dest + + } + + return response, nil +} + +// ParsePostJobsResponse parses an HTTP response from a PostJobsWithResponse call +func ParsePostJobsResponse(rsp *http.Response) (*PostJobsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &PostJobsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest Job + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + } + + return response, nil +} + +// ParseGetJobsEventsResponse parses an HTTP response from a GetJobsEventsWithResponse call +func ParseGetJobsEventsResponse(rsp *http.Response) (*GetJobsEventsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetJobsEventsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseDeleteJobsIdResponse parses an HTTP response from a DeleteJobsIdWithResponse call +func ParseDeleteJobsIdResponse(rsp *http.Response) (*DeleteJobsIdResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteJobsIdResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseGetJobsIdResponse parses an HTTP response from a GetJobsIdWithResponse call +func ParseGetJobsIdResponse(rsp *http.Response) (*GetJobsIdResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetJobsIdResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Job + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseGetJobsIdDefinitionResponse parses an HTTP response from a GetJobsIdDefinitionWithResponse call +func ParseGetJobsIdDefinitionResponse(rsp *http.Response) (*GetJobsIdDefinitionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetJobsIdDefinitionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest map[string]interface{} + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParsePutJobsIdDefinitionResponse parses an HTTP response from a PutJobsIdDefinitionWithResponse call +func ParsePutJobsIdDefinitionResponse(rsp *http.Response) (*PutJobsIdDefinitionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &PutJobsIdDefinitionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest map[string]interface{} + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseGetJobsIdStatusResponse parses an HTTP response from a GetJobsIdStatusWithResponse call +func ParseGetJobsIdStatusResponse(rsp *http.Response) (*GetJobsIdStatusResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetJobsIdStatusResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest JobStatus + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParsePutJobsIdStatusResponse parses an HTTP response from a PutJobsIdStatusWithResponse call +func ParsePutJobsIdStatusResponse(rsp *http.Response) (*PutJobsIdStatusResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &PutJobsIdStatusResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest JobStatus + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseDeleteJobsIdTagsResponse parses an HTTP response from a DeleteJobsIdTagsWithResponse call +func ParseDeleteJobsIdTagsResponse(rsp *http.Response) (*DeleteJobsIdTagsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteJobsIdTagsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest TagList + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseGetJobsIdTagsResponse parses an HTTP response from a GetJobsIdTagsWithResponse call +func ParseGetJobsIdTagsResponse(rsp *http.Response) (*GetJobsIdTagsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetJobsIdTagsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest TagList + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParsePostJobsIdTagsResponse parses an HTTP response from a PostJobsIdTagsWithResponse call +func ParsePostJobsIdTagsResponse(rsp *http.Response) (*PostJobsIdTagsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &PostJobsIdTagsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest TagList + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseGetVersionResponse parses an HTTP response from a GetVersionWithResponse call +func ParseGetVersionResponse(rsp *http.Response) (*GetVersionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetVersionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest struct { + ApiVersion string `json:"apiVersion,omitempty"` + BuildDate time.Time `json:"buildDate,omitempty"` + Commit string `json:"commit,omitempty"` + Version string `json:"version,omitempty"` + } + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + +// ParseGetWorkflowsResponse parses an HTTP response from a GetWorkflowsWithResponse call +func ParseGetWorkflowsResponse(rsp *http.Response) (*GetWorkflowsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetWorkflowsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest PaginatedWorkflowList + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + +// ParsePostWorkflowsResponse parses an HTTP response from a PostWorkflowsWithResponse call +func ParsePostWorkflowsResponse(rsp *http.Response) (*PostWorkflowsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &PostWorkflowsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest Workflow + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + } + + return response, nil +} + +// ParseDeleteWorkflowsNameResponse parses an HTTP response from a DeleteWorkflowsNameWithResponse call +func ParseDeleteWorkflowsNameResponse(rsp *http.Response) (*DeleteWorkflowsNameResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteWorkflowsNameResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseGetWorkflowsNameResponse parses an HTTP response from a GetWorkflowsNameWithResponse call +func ParseGetWorkflowsNameResponse(rsp *http.Response) (*GetWorkflowsNameResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetWorkflowsNameResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Workflow + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ServerInterface represents all server handlers. +type ServerInterface interface { + // Query health status + // (GET /health) + GetHealth(w http.ResponseWriter, r *http.Request) + // List of job descriptions + // (GET /jobs) + GetJobs(w http.ResponseWriter, r *http.Request, params GetJobsParams) + // Add a new job + // (POST /jobs) + PostJobs(w http.ResponseWriter, r *http.Request, params PostJobsParams) + // Subscribe to job-related events such as status updates + // (GET /jobs/events) + GetJobsEvents(w http.ResponseWriter, r *http.Request, params GetJobsEventsParams) + // Delete an existing job + // (DELETE /jobs/{id}) + DeleteJobsId(w http.ResponseWriter, r *http.Request, id string) + // Job description for a given ID + // (GET /jobs/{id}) + GetJobsId(w http.ResponseWriter, r *http.Request, id string, params GetJobsIdParams) + // Get job definition + // (GET /jobs/{id}/definition) + GetJobsIdDefinition(w http.ResponseWriter, r *http.Request, id string, params GetJobsIdDefinitionParams) + // Modify job definition + // (PUT /jobs/{id}/definition) + PutJobsIdDefinition(w http.ResponseWriter, r *http.Request, id string, params PutJobsIdDefinitionParams) + // Get job status + // (GET /jobs/{id}/status) + GetJobsIdStatus(w http.ResponseWriter, r *http.Request, id string, params GetJobsIdStatusParams) + // Modify status of an existing job + // (PUT /jobs/{id}/status) + PutJobsIdStatus(w http.ResponseWriter, r *http.Request, id string, params PutJobsIdStatusParams) + // Delete a tag + // (DELETE /jobs/{id}/tags) + DeleteJobsIdTags(w http.ResponseWriter, r *http.Request, id string, params DeleteJobsIdTagsParams) + // Get tags + // (GET /jobs/{id}/tags) + GetJobsIdTags(w http.ResponseWriter, r *http.Request, id string, params GetJobsIdTagsParams) + // Add a tag + // (POST /jobs/{id}/tags) + PostJobsIdTags(w http.ResponseWriter, r *http.Request, id string, params PostJobsIdTagsParams) + // Get version information + // (GET /version) + GetVersion(w http.ResponseWriter, r *http.Request) + // List of available workflows + // (GET /workflows) + GetWorkflows(w http.ResponseWriter, r *http.Request, params GetWorkflowsParams) + // Add a new workflow + // (POST /workflows) + PostWorkflows(w http.ResponseWriter, r *http.Request, params PostWorkflowsParams) + // Delete an existing workflow + // (DELETE /workflows/{name}) + DeleteWorkflowsName(w http.ResponseWriter, r *http.Request, name string) + // Workflow description for a given name + // (GET /workflows/{name}) + GetWorkflowsName(w http.ResponseWriter, r *http.Request, name string, params GetWorkflowsNameParams) +} + +// ServerInterfaceWrapper converts contexts to parameters. +type ServerInterfaceWrapper struct { + Handler ServerInterface + HandlerMiddlewares []MiddlewareFunc + ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) +} + +type MiddlewareFunc func(http.Handler) http.Handler + +// GetHealth operation middleware +func (siw *ServerInterfaceWrapper) GetHealth(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetHealth(w, r) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r.WithContext(ctx)) +} + +// GetJobs operation middleware +func (siw *ServerInterfaceWrapper) GetJobs(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params GetJobsParams + + // ------------- Optional query parameter "limit" ------------- + + err = runtime.BindQueryParameter("form", true, false, "limit", r.URL.Query(), ¶ms.ParamLimit) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "limit", Err: err}) + return + } + + // ------------- Optional query parameter "offset" ------------- + + err = runtime.BindQueryParameter("form", true, false, "offset", r.URL.Query(), ¶ms.ParamOffset) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "offset", Err: err}) + return + } + + // ------------- Optional query parameter "sort" ------------- + + err = runtime.BindQueryParameter("form", true, false, "sort", r.URL.Query(), ¶ms.ParamSort) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "sort", Err: err}) + return + } + + // ------------- Optional query parameter "state" ------------- + + err = runtime.BindQueryParameter("form", true, false, "state", r.URL.Query(), ¶ms.ParamState) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "state", Err: err}) + return + } + + // ------------- Optional query parameter "group" ------------- + + err = runtime.BindQueryParameter("form", false, false, "group", r.URL.Query(), ¶ms.ParamGroup) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "group", Err: err}) + return + } + + // ------------- Optional query parameter "clientId" ------------- + + err = runtime.BindQueryParameter("form", true, false, "clientId", r.URL.Query(), ¶ms.ParamClientID) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "clientId", Err: err}) + return + } + + // ------------- Optional query parameter "tag" ------------- + + err = runtime.BindQueryParameter("form", false, false, "tag", r.URL.Query(), ¶ms.ParamTag) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "tag", Err: err}) + return + } + + // ------------- Optional query parameter "workflow" ------------- + + err = runtime.BindQueryParameter("form", true, false, "workflow", r.URL.Query(), ¶ms.ParamWorkflow) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "workflow", Err: err}) + return + } + + headers := r.Header + + // ------------- Optional header parameter "X-Response-Filter" ------------- + if valueList, found := headers[http.CanonicalHeaderKey("X-Response-Filter")]; found { + var XResponseFilter ResponseFilter + n := len(valueList) + if n != 1 { + siw.ErrorHandlerFunc(w, r, &TooManyValuesForParamError{ParamName: "X-Response-Filter", Count: n}) + return + } + + err = runtime.BindStyledParameterWithOptions("simple", "X-Response-Filter", valueList[0], &XResponseFilter, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "X-Response-Filter", Err: err}) + return + } + + params.XResponseFilter = &XResponseFilter + + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetJobs(w, r, params) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r.WithContext(ctx)) +} + +// PostJobs operation middleware +func (siw *ServerInterfaceWrapper) PostJobs(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params PostJobsParams + + headers := r.Header + + // ------------- Optional header parameter "X-Response-Filter" ------------- + if valueList, found := headers[http.CanonicalHeaderKey("X-Response-Filter")]; found { + var XResponseFilter ResponseFilter + n := len(valueList) + if n != 1 { + siw.ErrorHandlerFunc(w, r, &TooManyValuesForParamError{ParamName: "X-Response-Filter", Count: n}) + return + } + + err = runtime.BindStyledParameterWithOptions("simple", "X-Response-Filter", valueList[0], &XResponseFilter, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "X-Response-Filter", Err: err}) + return + } + + params.XResponseFilter = &XResponseFilter + + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.PostJobs(w, r, params) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r.WithContext(ctx)) +} + +// GetJobsEvents operation middleware +func (siw *ServerInterfaceWrapper) GetJobsEvents(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params GetJobsEventsParams + + // ------------- Optional query parameter "clientIds" ------------- + + err = runtime.BindQueryParameter("form", true, false, "clientIds", r.URL.Query(), ¶ms.ClientIDs) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "clientIds", Err: err}) + return + } + + // ------------- Optional query parameter "jobIds" ------------- + + err = runtime.BindQueryParameter("form", true, false, "jobIds", r.URL.Query(), ¶ms.JobIds) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "jobIds", Err: err}) + return + } + + // ------------- Optional query parameter "workflows" ------------- + + err = runtime.BindQueryParameter("form", true, false, "workflows", r.URL.Query(), ¶ms.Workflows) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "workflows", Err: err}) + return + } + + // ------------- Optional query parameter "tags" ------------- + + err = runtime.BindQueryParameter("form", true, false, "tags", r.URL.Query(), ¶ms.Tags) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "tags", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetJobsEvents(w, r, params) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r.WithContext(ctx)) +} + +// DeleteJobsId operation middleware +func (siw *ServerInterfaceWrapper) DeleteJobsId(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + var err error + + // ------------- Path parameter "id" ------------- + var id string + + err = runtime.BindStyledParameterWithOptions("simple", "id", r.PathValue("id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.DeleteJobsId(w, r, id) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r.WithContext(ctx)) +} + +// GetJobsId operation middleware +func (siw *ServerInterfaceWrapper) GetJobsId(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + var err error + + // ------------- Path parameter "id" ------------- + var id string + + err = runtime.BindStyledParameterWithOptions("simple", "id", r.PathValue("id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params GetJobsIdParams + + // ------------- Optional query parameter "history" ------------- + + err = runtime.BindQueryParameter("form", true, false, "history", r.URL.Query(), ¶ms.ParamHistory) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "history", Err: err}) + return + } + + headers := r.Header + + // ------------- Optional header parameter "X-Response-Filter" ------------- + if valueList, found := headers[http.CanonicalHeaderKey("X-Response-Filter")]; found { + var XResponseFilter ResponseFilter + n := len(valueList) + if n != 1 { + siw.ErrorHandlerFunc(w, r, &TooManyValuesForParamError{ParamName: "X-Response-Filter", Count: n}) + return + } + + err = runtime.BindStyledParameterWithOptions("simple", "X-Response-Filter", valueList[0], &XResponseFilter, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "X-Response-Filter", Err: err}) + return + } + + params.XResponseFilter = &XResponseFilter + + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetJobsId(w, r, id, params) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r.WithContext(ctx)) +} + +// GetJobsIdDefinition operation middleware +func (siw *ServerInterfaceWrapper) GetJobsIdDefinition(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + var err error + + // ------------- Path parameter "id" ------------- + var id string + + err = runtime.BindStyledParameterWithOptions("simple", "id", r.PathValue("id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params GetJobsIdDefinitionParams + + headers := r.Header + + // ------------- Optional header parameter "X-Response-Filter" ------------- + if valueList, found := headers[http.CanonicalHeaderKey("X-Response-Filter")]; found { + var XResponseFilter ResponseFilter + n := len(valueList) + if n != 1 { + siw.ErrorHandlerFunc(w, r, &TooManyValuesForParamError{ParamName: "X-Response-Filter", Count: n}) + return + } + + err = runtime.BindStyledParameterWithOptions("simple", "X-Response-Filter", valueList[0], &XResponseFilter, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "X-Response-Filter", Err: err}) + return + } + + params.XResponseFilter = &XResponseFilter + + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetJobsIdDefinition(w, r, id, params) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r.WithContext(ctx)) +} + +// PutJobsIdDefinition operation middleware +func (siw *ServerInterfaceWrapper) PutJobsIdDefinition(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + var err error + + // ------------- Path parameter "id" ------------- + var id string + + err = runtime.BindStyledParameterWithOptions("simple", "id", r.PathValue("id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params PutJobsIdDefinitionParams + + headers := r.Header + + // ------------- Optional header parameter "X-Response-Filter" ------------- + if valueList, found := headers[http.CanonicalHeaderKey("X-Response-Filter")]; found { + var XResponseFilter ResponseFilter + n := len(valueList) + if n != 1 { + siw.ErrorHandlerFunc(w, r, &TooManyValuesForParamError{ParamName: "X-Response-Filter", Count: n}) + return + } + + err = runtime.BindStyledParameterWithOptions("simple", "X-Response-Filter", valueList[0], &XResponseFilter, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "X-Response-Filter", Err: err}) + return + } + + params.XResponseFilter = &XResponseFilter + + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.PutJobsIdDefinition(w, r, id, params) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r.WithContext(ctx)) +} + +// GetJobsIdStatus operation middleware +func (siw *ServerInterfaceWrapper) GetJobsIdStatus(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + var err error + + // ------------- Path parameter "id" ------------- + var id string + + err = runtime.BindStyledParameterWithOptions("simple", "id", r.PathValue("id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params GetJobsIdStatusParams + + headers := r.Header + + // ------------- Optional header parameter "X-Response-Filter" ------------- + if valueList, found := headers[http.CanonicalHeaderKey("X-Response-Filter")]; found { + var XResponseFilter ResponseFilter + n := len(valueList) + if n != 1 { + siw.ErrorHandlerFunc(w, r, &TooManyValuesForParamError{ParamName: "X-Response-Filter", Count: n}) + return + } + + err = runtime.BindStyledParameterWithOptions("simple", "X-Response-Filter", valueList[0], &XResponseFilter, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "X-Response-Filter", Err: err}) + return + } + + params.XResponseFilter = &XResponseFilter + + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetJobsIdStatus(w, r, id, params) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r.WithContext(ctx)) +} + +// PutJobsIdStatus operation middleware +func (siw *ServerInterfaceWrapper) PutJobsIdStatus(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + var err error + + // ------------- Path parameter "id" ------------- + var id string + + err = runtime.BindStyledParameterWithOptions("simple", "id", r.PathValue("id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params PutJobsIdStatusParams + + headers := r.Header + + // ------------- Optional header parameter "X-Response-Filter" ------------- + if valueList, found := headers[http.CanonicalHeaderKey("X-Response-Filter")]; found { + var XResponseFilter ResponseFilter + n := len(valueList) + if n != 1 { + siw.ErrorHandlerFunc(w, r, &TooManyValuesForParamError{ParamName: "X-Response-Filter", Count: n}) + return + } + + err = runtime.BindStyledParameterWithOptions("simple", "X-Response-Filter", valueList[0], &XResponseFilter, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "X-Response-Filter", Err: err}) + return + } + + params.XResponseFilter = &XResponseFilter + + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.PutJobsIdStatus(w, r, id, params) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r.WithContext(ctx)) +} + +// DeleteJobsIdTags operation middleware +func (siw *ServerInterfaceWrapper) DeleteJobsIdTags(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + var err error + + // ------------- Path parameter "id" ------------- + var id string + + err = runtime.BindStyledParameterWithOptions("simple", "id", r.PathValue("id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params DeleteJobsIdTagsParams + + headers := r.Header + + // ------------- Optional header parameter "X-Response-Filter" ------------- + if valueList, found := headers[http.CanonicalHeaderKey("X-Response-Filter")]; found { + var XResponseFilter ResponseFilter + n := len(valueList) + if n != 1 { + siw.ErrorHandlerFunc(w, r, &TooManyValuesForParamError{ParamName: "X-Response-Filter", Count: n}) + return + } + + err = runtime.BindStyledParameterWithOptions("simple", "X-Response-Filter", valueList[0], &XResponseFilter, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "X-Response-Filter", Err: err}) + return + } + + params.XResponseFilter = &XResponseFilter + + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.DeleteJobsIdTags(w, r, id, params) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r.WithContext(ctx)) +} + +// GetJobsIdTags operation middleware +func (siw *ServerInterfaceWrapper) GetJobsIdTags(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + var err error + + // ------------- Path parameter "id" ------------- + var id string + + err = runtime.BindStyledParameterWithOptions("simple", "id", r.PathValue("id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params GetJobsIdTagsParams + + headers := r.Header + + // ------------- Optional header parameter "X-Response-Filter" ------------- + if valueList, found := headers[http.CanonicalHeaderKey("X-Response-Filter")]; found { + var XResponseFilter ResponseFilter + n := len(valueList) + if n != 1 { + siw.ErrorHandlerFunc(w, r, &TooManyValuesForParamError{ParamName: "X-Response-Filter", Count: n}) + return + } + + err = runtime.BindStyledParameterWithOptions("simple", "X-Response-Filter", valueList[0], &XResponseFilter, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "X-Response-Filter", Err: err}) + return + } + + params.XResponseFilter = &XResponseFilter + + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetJobsIdTags(w, r, id, params) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r.WithContext(ctx)) +} + +// PostJobsIdTags operation middleware +func (siw *ServerInterfaceWrapper) PostJobsIdTags(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + var err error + + // ------------- Path parameter "id" ------------- + var id string + + err = runtime.BindStyledParameterWithOptions("simple", "id", r.PathValue("id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params PostJobsIdTagsParams + + headers := r.Header + + // ------------- Optional header parameter "X-Response-Filter" ------------- + if valueList, found := headers[http.CanonicalHeaderKey("X-Response-Filter")]; found { + var XResponseFilter ResponseFilter + n := len(valueList) + if n != 1 { + siw.ErrorHandlerFunc(w, r, &TooManyValuesForParamError{ParamName: "X-Response-Filter", Count: n}) + return + } + + err = runtime.BindStyledParameterWithOptions("simple", "X-Response-Filter", valueList[0], &XResponseFilter, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "X-Response-Filter", Err: err}) + return + } + + params.XResponseFilter = &XResponseFilter + + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.PostJobsIdTags(w, r, id, params) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r.WithContext(ctx)) +} + +// GetVersion operation middleware +func (siw *ServerInterfaceWrapper) GetVersion(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetVersion(w, r) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r.WithContext(ctx)) +} + +// GetWorkflows operation middleware +func (siw *ServerInterfaceWrapper) GetWorkflows(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params GetWorkflowsParams + + // ------------- Optional query parameter "limit" ------------- + + err = runtime.BindQueryParameter("form", true, false, "limit", r.URL.Query(), ¶ms.ParamLimit) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "limit", Err: err}) + return + } + + // ------------- Optional query parameter "offset" ------------- + + err = runtime.BindQueryParameter("form", true, false, "offset", r.URL.Query(), ¶ms.ParamOffset) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "offset", Err: err}) + return + } + + // ------------- Optional query parameter "sort" ------------- + + err = runtime.BindQueryParameter("form", true, false, "sort", r.URL.Query(), ¶ms.ParamSort) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "sort", Err: err}) + return + } + + headers := r.Header + + // ------------- Optional header parameter "X-Response-Filter" ------------- + if valueList, found := headers[http.CanonicalHeaderKey("X-Response-Filter")]; found { + var XResponseFilter ResponseFilter + n := len(valueList) + if n != 1 { + siw.ErrorHandlerFunc(w, r, &TooManyValuesForParamError{ParamName: "X-Response-Filter", Count: n}) + return + } + + err = runtime.BindStyledParameterWithOptions("simple", "X-Response-Filter", valueList[0], &XResponseFilter, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "X-Response-Filter", Err: err}) + return + } + + params.XResponseFilter = &XResponseFilter + + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetWorkflows(w, r, params) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r.WithContext(ctx)) +} + +// PostWorkflows operation middleware +func (siw *ServerInterfaceWrapper) PostWorkflows(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params PostWorkflowsParams + + headers := r.Header + + // ------------- Optional header parameter "X-Response-Filter" ------------- + if valueList, found := headers[http.CanonicalHeaderKey("X-Response-Filter")]; found { + var XResponseFilter ResponseFilter + n := len(valueList) + if n != 1 { + siw.ErrorHandlerFunc(w, r, &TooManyValuesForParamError{ParamName: "X-Response-Filter", Count: n}) + return + } + + err = runtime.BindStyledParameterWithOptions("simple", "X-Response-Filter", valueList[0], &XResponseFilter, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "X-Response-Filter", Err: err}) + return + } + + params.XResponseFilter = &XResponseFilter + + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.PostWorkflows(w, r, params) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r.WithContext(ctx)) +} + +// DeleteWorkflowsName operation middleware +func (siw *ServerInterfaceWrapper) DeleteWorkflowsName(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + var err error + + // ------------- Path parameter "name" ------------- + var name string + + err = runtime.BindStyledParameterWithOptions("simple", "name", r.PathValue("name"), &name, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "name", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.DeleteWorkflowsName(w, r, name) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r.WithContext(ctx)) +} + +// GetWorkflowsName operation middleware +func (siw *ServerInterfaceWrapper) GetWorkflowsName(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + var err error + + // ------------- Path parameter "name" ------------- + var name string + + err = runtime.BindStyledParameterWithOptions("simple", "name", r.PathValue("name"), &name, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "name", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params GetWorkflowsNameParams + + headers := r.Header + + // ------------- Optional header parameter "X-Response-Filter" ------------- + if valueList, found := headers[http.CanonicalHeaderKey("X-Response-Filter")]; found { + var XResponseFilter ResponseFilter + n := len(valueList) + if n != 1 { + siw.ErrorHandlerFunc(w, r, &TooManyValuesForParamError{ParamName: "X-Response-Filter", Count: n}) + return + } + + err = runtime.BindStyledParameterWithOptions("simple", "X-Response-Filter", valueList[0], &XResponseFilter, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationHeader, Explode: false, Required: false}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "X-Response-Filter", Err: err}) + return + } + + params.XResponseFilter = &XResponseFilter + + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetWorkflowsName(w, r, name, params) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r.WithContext(ctx)) +} + +type UnescapedCookieParamError struct { + ParamName string + Err error +} + +func (e *UnescapedCookieParamError) Error() string { + return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName) +} + +func (e *UnescapedCookieParamError) Unwrap() error { + return e.Err +} + +type UnmarshalingParamError struct { + ParamName string + Err error +} + +func (e *UnmarshalingParamError) Error() string { + return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error()) +} + +func (e *UnmarshalingParamError) Unwrap() error { + return e.Err +} + +type RequiredParamError struct { + ParamName string +} + +func (e *RequiredParamError) Error() string { + return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName) +} + +type RequiredHeaderError struct { + ParamName string + Err error +} + +func (e *RequiredHeaderError) Error() string { + return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName) +} + +func (e *RequiredHeaderError) Unwrap() error { + return e.Err +} + +type InvalidParamFormatError struct { + ParamName string + Err error +} + +func (e *InvalidParamFormatError) Error() string { + return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error()) +} + +func (e *InvalidParamFormatError) Unwrap() error { + return e.Err +} + +type TooManyValuesForParamError struct { + ParamName string + Count int +} + +func (e *TooManyValuesForParamError) Error() string { + return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count) +} + +// Handler creates http.Handler with routing matching OpenAPI spec. +func Handler(si ServerInterface) http.Handler { + return HandlerWithOptions(si, StdHTTPServerOptions{}) +} + +type StdHTTPServerOptions struct { + BaseURL string + BaseRouter *http.ServeMux + Middlewares []MiddlewareFunc + ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) +} + +// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux. +func HandlerFromMux(si ServerInterface, m *http.ServeMux) http.Handler { + return HandlerWithOptions(si, StdHTTPServerOptions{ + BaseRouter: m, + }) +} + +func HandlerFromMuxWithBaseURL(si ServerInterface, m *http.ServeMux, baseURL string) http.Handler { + return HandlerWithOptions(si, StdHTTPServerOptions{ + BaseURL: baseURL, + BaseRouter: m, + }) +} + +// HandlerWithOptions creates http.Handler with additional options +func HandlerWithOptions(si ServerInterface, options StdHTTPServerOptions) http.Handler { + m := options.BaseRouter + + if m == nil { + m = http.NewServeMux() + } + if options.ErrorHandlerFunc == nil { + options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { + http.Error(w, err.Error(), http.StatusBadRequest) + } + } + + wrapper := ServerInterfaceWrapper{ + Handler: si, + HandlerMiddlewares: options.Middlewares, + ErrorHandlerFunc: options.ErrorHandlerFunc, + } + + m.HandleFunc("GET "+options.BaseURL+"/health", wrapper.GetHealth) + m.HandleFunc("GET "+options.BaseURL+"/jobs", wrapper.GetJobs) + m.HandleFunc("POST "+options.BaseURL+"/jobs", wrapper.PostJobs) + m.HandleFunc("GET "+options.BaseURL+"/jobs/events", wrapper.GetJobsEvents) + m.HandleFunc("DELETE "+options.BaseURL+"/jobs/{id}", wrapper.DeleteJobsId) + m.HandleFunc("GET "+options.BaseURL+"/jobs/{id}", wrapper.GetJobsId) + m.HandleFunc("GET "+options.BaseURL+"/jobs/{id}/definition", wrapper.GetJobsIdDefinition) + m.HandleFunc("PUT "+options.BaseURL+"/jobs/{id}/definition", wrapper.PutJobsIdDefinition) + m.HandleFunc("GET "+options.BaseURL+"/jobs/{id}/status", wrapper.GetJobsIdStatus) + m.HandleFunc("PUT "+options.BaseURL+"/jobs/{id}/status", wrapper.PutJobsIdStatus) + m.HandleFunc("DELETE "+options.BaseURL+"/jobs/{id}/tags", wrapper.DeleteJobsIdTags) + m.HandleFunc("GET "+options.BaseURL+"/jobs/{id}/tags", wrapper.GetJobsIdTags) + m.HandleFunc("POST "+options.BaseURL+"/jobs/{id}/tags", wrapper.PostJobsIdTags) + m.HandleFunc("GET "+options.BaseURL+"/version", wrapper.GetVersion) + m.HandleFunc("GET "+options.BaseURL+"/workflows", wrapper.GetWorkflows) + m.HandleFunc("POST "+options.BaseURL+"/workflows", wrapper.PostWorkflows) + m.HandleFunc("DELETE "+options.BaseURL+"/workflows/{name}", wrapper.DeleteWorkflowsName) + m.HandleFunc("GET "+options.BaseURL+"/workflows/{name}", wrapper.GetWorkflowsName) + + return m +} + +type GetHealthRequestObject struct { +} + +type GetHealthResponseObject interface { + VisitGetHealthResponse(w http.ResponseWriter) error +} + +type GetHealth200ResponseHeaders struct { + CacheControl string + Expires string + Pragma string +} + +type GetHealth200JSONResponse struct { + Body CheckerResult + Headers GetHealth200ResponseHeaders +} + +func (response GetHealth200JSONResponse) VisitGetHealthResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", fmt.Sprint(response.Headers.CacheControl)) + w.Header().Set("Expires", fmt.Sprint(response.Headers.Expires)) + w.Header().Set("Pragma", fmt.Sprint(response.Headers.Pragma)) + w.WriteHeader(200) + + return json.NewEncoder(w).Encode(response.Body) +} + +type GetHealth503ResponseHeaders struct { + CacheControl string + Expires string + Pragma string +} + +type GetHealth503JSONResponse struct { + Body CheckerResult + Headers GetHealth503ResponseHeaders +} + +func (response GetHealth503JSONResponse) VisitGetHealthResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", fmt.Sprint(response.Headers.CacheControl)) + w.Header().Set("Expires", fmt.Sprint(response.Headers.Expires)) + w.Header().Set("Pragma", fmt.Sprint(response.Headers.Pragma)) + w.WriteHeader(503) + + return json.NewEncoder(w).Encode(response.Body) +} + +type GetHealthdefaultResponse struct { + StatusCode int +} + +func (response GetHealthdefaultResponse) VisitGetHealthResponse(w http.ResponseWriter) error { + w.WriteHeader(response.StatusCode) + return nil +} + +type GetJobsRequestObject struct { + Params GetJobsParams +} + +type GetJobsResponseObject interface { + VisitGetJobsResponse(w http.ResponseWriter) error +} + +type GetJobs200JSONResponse PaginatedJobList + +func (response GetJobs200JSONResponse) VisitGetJobsResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + + return json.NewEncoder(w).Encode(response) +} + +type GetJobs400JSONResponse ErrorResponse + +func (response GetJobs400JSONResponse) VisitGetJobsResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + + return json.NewEncoder(w).Encode(response) +} + +type GetJobsdefaultJSONResponse struct { + Body ErrorResponse + StatusCode int +} + +func (response GetJobsdefaultJSONResponse) VisitGetJobsResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(response.StatusCode) + + return json.NewEncoder(w).Encode(response.Body) +} + +type PostJobsRequestObject struct { + Params PostJobsParams + Body *PostJobsJSONRequestBody +} + +type PostJobsResponseObject interface { + VisitPostJobsResponse(w http.ResponseWriter) error +} + +type PostJobs201JSONResponse Job + +func (response PostJobs201JSONResponse) VisitPostJobsResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(201) + + return json.NewEncoder(w).Encode(response) +} + +type PostJobs400JSONResponse ErrorResponse + +func (response PostJobs400JSONResponse) VisitPostJobsResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + + return json.NewEncoder(w).Encode(response) +} + +type PostJobs403Response struct { +} + +func (response PostJobs403Response) VisitPostJobsResponse(w http.ResponseWriter) error { + w.WriteHeader(403) + return nil +} + +type PostJobsdefaultResponse struct { + StatusCode int +} + +func (response PostJobsdefaultResponse) VisitPostJobsResponse(w http.ResponseWriter) error { + w.WriteHeader(response.StatusCode) + return nil +} + +type GetJobsEventsRequestObject struct { + Params GetJobsEventsParams +} + +type GetJobsEventsResponseObject interface { + VisitGetJobsEventsResponse(w http.ResponseWriter) error +} + +type GetJobsEvents200TexteventStreamResponse struct { + Body io.Reader + ContentLength int64 +} + +func (response GetJobsEvents200TexteventStreamResponse) VisitGetJobsEventsResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "text/event-stream") + if response.ContentLength != 0 { + w.Header().Set("Content-Length", fmt.Sprint(response.ContentLength)) + } + w.WriteHeader(200) + + if closer, ok := response.Body.(io.ReadCloser); ok { + defer closer.Close() + } + _, err := io.Copy(w, response.Body) + return err +} + +type GetJobsEvents400JSONResponse ErrorResponse + +func (response GetJobsEvents400JSONResponse) VisitGetJobsEventsResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + + return json.NewEncoder(w).Encode(response) +} + +type GetJobsEvents404JSONResponse ErrorResponse + +func (response GetJobsEvents404JSONResponse) VisitGetJobsEventsResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(404) + + return json.NewEncoder(w).Encode(response) +} + +type GetJobsEventsdefaultResponse struct { + StatusCode int +} + +func (response GetJobsEventsdefaultResponse) VisitGetJobsEventsResponse(w http.ResponseWriter) error { + w.WriteHeader(response.StatusCode) + return nil +} + +type DeleteJobsIdRequestObject struct { + Id string `json:"id"` +} + +type DeleteJobsIdResponseObject interface { + VisitDeleteJobsIdResponse(w http.ResponseWriter) error +} + +type DeleteJobsId204Response struct { +} + +func (response DeleteJobsId204Response) VisitDeleteJobsIdResponse(w http.ResponseWriter) error { + w.WriteHeader(204) + return nil +} + +type DeleteJobsId403Response struct { +} + +func (response DeleteJobsId403Response) VisitDeleteJobsIdResponse(w http.ResponseWriter) error { + w.WriteHeader(403) + return nil +} + +type DeleteJobsId404JSONResponse ErrorResponse + +func (response DeleteJobsId404JSONResponse) VisitDeleteJobsIdResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(404) + + return json.NewEncoder(w).Encode(response) +} + +type DeleteJobsIddefaultResponse struct { + StatusCode int +} + +func (response DeleteJobsIddefaultResponse) VisitDeleteJobsIdResponse(w http.ResponseWriter) error { + w.WriteHeader(response.StatusCode) + return nil +} + +type GetJobsIdRequestObject struct { + Id string `json:"id"` + Params GetJobsIdParams +} + +type GetJobsIdResponseObject interface { + VisitGetJobsIdResponse(w http.ResponseWriter) error +} + +type GetJobsId200JSONResponse Job + +func (response GetJobsId200JSONResponse) VisitGetJobsIdResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + + return json.NewEncoder(w).Encode(response) +} + +type GetJobsId400JSONResponse ErrorResponse + +func (response GetJobsId400JSONResponse) VisitGetJobsIdResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + + return json.NewEncoder(w).Encode(response) +} + +type GetJobsId404JSONResponse ErrorResponse + +func (response GetJobsId404JSONResponse) VisitGetJobsIdResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(404) + + return json.NewEncoder(w).Encode(response) +} + +type GetJobsIddefaultResponse struct { + StatusCode int +} + +func (response GetJobsIddefaultResponse) VisitGetJobsIdResponse(w http.ResponseWriter) error { + w.WriteHeader(response.StatusCode) + return nil +} + +type GetJobsIdDefinitionRequestObject struct { + Id string `json:"id"` + Params GetJobsIdDefinitionParams +} + +type GetJobsIdDefinitionResponseObject interface { + VisitGetJobsIdDefinitionResponse(w http.ResponseWriter) error +} + +type GetJobsIdDefinition200JSONResponse map[string]interface{} + +func (response GetJobsIdDefinition200JSONResponse) VisitGetJobsIdDefinitionResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + + return json.NewEncoder(w).Encode(response) +} + +type GetJobsIdDefinition404JSONResponse ErrorResponse + +func (response GetJobsIdDefinition404JSONResponse) VisitGetJobsIdDefinitionResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(404) + + return json.NewEncoder(w).Encode(response) +} + +type GetJobsIdDefinitiondefaultResponse struct { + StatusCode int +} + +func (response GetJobsIdDefinitiondefaultResponse) VisitGetJobsIdDefinitionResponse(w http.ResponseWriter) error { + w.WriteHeader(response.StatusCode) + return nil +} + +type PutJobsIdDefinitionRequestObject struct { + Id string `json:"id"` + Params PutJobsIdDefinitionParams + Body *PutJobsIdDefinitionJSONRequestBody +} + +type PutJobsIdDefinitionResponseObject interface { + VisitPutJobsIdDefinitionResponse(w http.ResponseWriter) error +} + +type PutJobsIdDefinition200JSONResponse map[string]interface{} + +func (response PutJobsIdDefinition200JSONResponse) VisitPutJobsIdDefinitionResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + + return json.NewEncoder(w).Encode(response) +} + +type PutJobsIdDefinition400JSONResponse ErrorResponse + +func (response PutJobsIdDefinition400JSONResponse) VisitPutJobsIdDefinitionResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + + return json.NewEncoder(w).Encode(response) +} + +type PutJobsIdDefinition404JSONResponse ErrorResponse + +func (response PutJobsIdDefinition404JSONResponse) VisitPutJobsIdDefinitionResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(404) + + return json.NewEncoder(w).Encode(response) +} + +type PutJobsIdDefinitiondefaultResponse struct { + StatusCode int +} + +func (response PutJobsIdDefinitiondefaultResponse) VisitPutJobsIdDefinitionResponse(w http.ResponseWriter) error { + w.WriteHeader(response.StatusCode) + return nil +} + +type GetJobsIdStatusRequestObject struct { + Id string `json:"id"` + Params GetJobsIdStatusParams +} + +type GetJobsIdStatusResponseObject interface { + VisitGetJobsIdStatusResponse(w http.ResponseWriter) error +} + +type GetJobsIdStatus200JSONResponse JobStatus + +func (response GetJobsIdStatus200JSONResponse) VisitGetJobsIdStatusResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + + return json.NewEncoder(w).Encode(response) +} + +type GetJobsIdStatus404JSONResponse ErrorResponse + +func (response GetJobsIdStatus404JSONResponse) VisitGetJobsIdStatusResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(404) + + return json.NewEncoder(w).Encode(response) +} + +type GetJobsIdStatusdefaultResponse struct { + StatusCode int +} + +func (response GetJobsIdStatusdefaultResponse) VisitGetJobsIdStatusResponse(w http.ResponseWriter) error { + w.WriteHeader(response.StatusCode) + return nil +} + +type PutJobsIdStatusRequestObject struct { + Id string `json:"id"` + Params PutJobsIdStatusParams + Body *PutJobsIdStatusJSONRequestBody +} + +type PutJobsIdStatusResponseObject interface { + VisitPutJobsIdStatusResponse(w http.ResponseWriter) error +} + +type PutJobsIdStatus200JSONResponse JobStatus + +func (response PutJobsIdStatus200JSONResponse) VisitPutJobsIdStatusResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + + return json.NewEncoder(w).Encode(response) +} + +type PutJobsIdStatus400JSONResponse ErrorResponse + +func (response PutJobsIdStatus400JSONResponse) VisitPutJobsIdStatusResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + + return json.NewEncoder(w).Encode(response) +} + +type PutJobsIdStatus404JSONResponse ErrorResponse + +func (response PutJobsIdStatus404JSONResponse) VisitPutJobsIdStatusResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(404) + + return json.NewEncoder(w).Encode(response) +} + +type PutJobsIdStatusdefaultResponse struct { + StatusCode int +} + +func (response PutJobsIdStatusdefaultResponse) VisitPutJobsIdStatusResponse(w http.ResponseWriter) error { + w.WriteHeader(response.StatusCode) + return nil +} + +type DeleteJobsIdTagsRequestObject struct { + Id string `json:"id"` + Params DeleteJobsIdTagsParams + Body *DeleteJobsIdTagsJSONRequestBody +} + +type DeleteJobsIdTagsResponseObject interface { + VisitDeleteJobsIdTagsResponse(w http.ResponseWriter) error +} + +type DeleteJobsIdTags200JSONResponse TagList + +func (response DeleteJobsIdTags200JSONResponse) VisitDeleteJobsIdTagsResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + + return json.NewEncoder(w).Encode(response) +} + +type DeleteJobsIdTags400JSONResponse ErrorResponse + +func (response DeleteJobsIdTags400JSONResponse) VisitDeleteJobsIdTagsResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + + return json.NewEncoder(w).Encode(response) +} + +type DeleteJobsIdTags403Response struct { +} + +func (response DeleteJobsIdTags403Response) VisitDeleteJobsIdTagsResponse(w http.ResponseWriter) error { + w.WriteHeader(403) + return nil +} + +type DeleteJobsIdTags404JSONResponse ErrorResponse + +func (response DeleteJobsIdTags404JSONResponse) VisitDeleteJobsIdTagsResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(404) + + return json.NewEncoder(w).Encode(response) +} + +type DeleteJobsIdTagsdefaultResponse struct { + StatusCode int +} + +func (response DeleteJobsIdTagsdefaultResponse) VisitDeleteJobsIdTagsResponse(w http.ResponseWriter) error { + w.WriteHeader(response.StatusCode) + return nil +} + +type GetJobsIdTagsRequestObject struct { + Id string `json:"id"` + Params GetJobsIdTagsParams +} + +type GetJobsIdTagsResponseObject interface { + VisitGetJobsIdTagsResponse(w http.ResponseWriter) error +} + +type GetJobsIdTags200JSONResponse TagList + +func (response GetJobsIdTags200JSONResponse) VisitGetJobsIdTagsResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + + return json.NewEncoder(w).Encode(response) +} + +type GetJobsIdTags404JSONResponse ErrorResponse + +func (response GetJobsIdTags404JSONResponse) VisitGetJobsIdTagsResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(404) + + return json.NewEncoder(w).Encode(response) +} + +type GetJobsIdTagsdefaultResponse struct { + StatusCode int +} + +func (response GetJobsIdTagsdefaultResponse) VisitGetJobsIdTagsResponse(w http.ResponseWriter) error { + w.WriteHeader(response.StatusCode) + return nil +} + +type PostJobsIdTagsRequestObject struct { + Id string `json:"id"` + Params PostJobsIdTagsParams + Body *PostJobsIdTagsJSONRequestBody +} + +type PostJobsIdTagsResponseObject interface { + VisitPostJobsIdTagsResponse(w http.ResponseWriter) error +} + +type PostJobsIdTags200JSONResponse TagList + +func (response PostJobsIdTags200JSONResponse) VisitPostJobsIdTagsResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + + return json.NewEncoder(w).Encode(response) +} + +type PostJobsIdTags400JSONResponse ErrorResponse + +func (response PostJobsIdTags400JSONResponse) VisitPostJobsIdTagsResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + + return json.NewEncoder(w).Encode(response) +} + +type PostJobsIdTags403Response struct { +} + +func (response PostJobsIdTags403Response) VisitPostJobsIdTagsResponse(w http.ResponseWriter) error { + w.WriteHeader(403) + return nil +} + +type PostJobsIdTags404JSONResponse ErrorResponse + +func (response PostJobsIdTags404JSONResponse) VisitPostJobsIdTagsResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(404) + + return json.NewEncoder(w).Encode(response) +} + +type PostJobsIdTagsdefaultResponse struct { + StatusCode int +} + +func (response PostJobsIdTagsdefaultResponse) VisitPostJobsIdTagsResponse(w http.ResponseWriter) error { + w.WriteHeader(response.StatusCode) + return nil +} + +type GetVersionRequestObject struct { +} + +type GetVersionResponseObject interface { + VisitGetVersionResponse(w http.ResponseWriter) error +} + +type GetVersion200JSONResponse struct { + ApiVersion string `json:"apiVersion,omitempty"` + BuildDate time.Time `json:"buildDate,omitempty"` + Commit string `json:"commit,omitempty"` + Version string `json:"version,omitempty"` +} + +func (response GetVersion200JSONResponse) VisitGetVersionResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + + return json.NewEncoder(w).Encode(response) +} + +type GetVersiondefaultResponse struct { + StatusCode int +} + +func (response GetVersiondefaultResponse) VisitGetVersionResponse(w http.ResponseWriter) error { + w.WriteHeader(response.StatusCode) + return nil +} + +type GetWorkflowsRequestObject struct { + Params GetWorkflowsParams +} + +type GetWorkflowsResponseObject interface { + VisitGetWorkflowsResponse(w http.ResponseWriter) error +} + +type GetWorkflows200JSONResponse PaginatedWorkflowList + +func (response GetWorkflows200JSONResponse) VisitGetWorkflowsResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + + return json.NewEncoder(w).Encode(response) +} + +type GetWorkflowsdefaultResponse struct { + StatusCode int +} + +func (response GetWorkflowsdefaultResponse) VisitGetWorkflowsResponse(w http.ResponseWriter) error { + w.WriteHeader(response.StatusCode) + return nil +} + +type PostWorkflowsRequestObject struct { + Params PostWorkflowsParams + Body *PostWorkflowsJSONRequestBody +} + +type PostWorkflowsResponseObject interface { + VisitPostWorkflowsResponse(w http.ResponseWriter) error +} + +type PostWorkflows201JSONResponse Workflow + +func (response PostWorkflows201JSONResponse) VisitPostWorkflowsResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(201) + + return json.NewEncoder(w).Encode(response) +} + +type PostWorkflows400JSONResponse ErrorResponse + +func (response PostWorkflows400JSONResponse) VisitPostWorkflowsResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + + return json.NewEncoder(w).Encode(response) +} + +type PostWorkflows403Response struct { +} + +func (response PostWorkflows403Response) VisitPostWorkflowsResponse(w http.ResponseWriter) error { + w.WriteHeader(403) + return nil +} + +type PostWorkflowsdefaultResponse struct { + StatusCode int +} + +func (response PostWorkflowsdefaultResponse) VisitPostWorkflowsResponse(w http.ResponseWriter) error { + w.WriteHeader(response.StatusCode) + return nil +} + +type DeleteWorkflowsNameRequestObject struct { + Name string `json:"name"` +} + +type DeleteWorkflowsNameResponseObject interface { + VisitDeleteWorkflowsNameResponse(w http.ResponseWriter) error +} + +type DeleteWorkflowsName204Response struct { +} + +func (response DeleteWorkflowsName204Response) VisitDeleteWorkflowsNameResponse(w http.ResponseWriter) error { + w.WriteHeader(204) + return nil +} + +type DeleteWorkflowsName403Response struct { +} + +func (response DeleteWorkflowsName403Response) VisitDeleteWorkflowsNameResponse(w http.ResponseWriter) error { + w.WriteHeader(403) + return nil +} + +type DeleteWorkflowsName404JSONResponse ErrorResponse + +func (response DeleteWorkflowsName404JSONResponse) VisitDeleteWorkflowsNameResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(404) + + return json.NewEncoder(w).Encode(response) +} + +type DeleteWorkflowsNamedefaultResponse struct { + StatusCode int +} + +func (response DeleteWorkflowsNamedefaultResponse) VisitDeleteWorkflowsNameResponse(w http.ResponseWriter) error { + w.WriteHeader(response.StatusCode) + return nil +} + +type GetWorkflowsNameRequestObject struct { + Name string `json:"name"` + Params GetWorkflowsNameParams +} + +type GetWorkflowsNameResponseObject interface { + VisitGetWorkflowsNameResponse(w http.ResponseWriter) error +} + +type GetWorkflowsName200JSONResponse Workflow + +func (response GetWorkflowsName200JSONResponse) VisitGetWorkflowsNameResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + + return json.NewEncoder(w).Encode(response) +} + +type GetWorkflowsName400JSONResponse ErrorResponse + +func (response GetWorkflowsName400JSONResponse) VisitGetWorkflowsNameResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + + return json.NewEncoder(w).Encode(response) +} + +type GetWorkflowsName404JSONResponse ErrorResponse + +func (response GetWorkflowsName404JSONResponse) VisitGetWorkflowsNameResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(404) + + return json.NewEncoder(w).Encode(response) +} + +type GetWorkflowsNamedefaultResponse struct { + StatusCode int +} + +func (response GetWorkflowsNamedefaultResponse) VisitGetWorkflowsNameResponse(w http.ResponseWriter) error { + w.WriteHeader(response.StatusCode) + return nil +} + +// StrictServerInterface represents all server handlers. +type StrictServerInterface interface { + // Query health status + // (GET /health) + GetHealth(ctx context.Context, request GetHealthRequestObject) (GetHealthResponseObject, error) + // List of job descriptions + // (GET /jobs) + GetJobs(ctx context.Context, request GetJobsRequestObject) (GetJobsResponseObject, error) + // Add a new job + // (POST /jobs) + PostJobs(ctx context.Context, request PostJobsRequestObject) (PostJobsResponseObject, error) + // Subscribe to job-related events such as status updates + // (GET /jobs/events) + GetJobsEvents(ctx context.Context, request GetJobsEventsRequestObject) (GetJobsEventsResponseObject, error) + // Delete an existing job + // (DELETE /jobs/{id}) + DeleteJobsId(ctx context.Context, request DeleteJobsIdRequestObject) (DeleteJobsIdResponseObject, error) + // Job description for a given ID + // (GET /jobs/{id}) + GetJobsId(ctx context.Context, request GetJobsIdRequestObject) (GetJobsIdResponseObject, error) + // Get job definition + // (GET /jobs/{id}/definition) + GetJobsIdDefinition(ctx context.Context, request GetJobsIdDefinitionRequestObject) (GetJobsIdDefinitionResponseObject, error) + // Modify job definition + // (PUT /jobs/{id}/definition) + PutJobsIdDefinition(ctx context.Context, request PutJobsIdDefinitionRequestObject) (PutJobsIdDefinitionResponseObject, error) + // Get job status + // (GET /jobs/{id}/status) + GetJobsIdStatus(ctx context.Context, request GetJobsIdStatusRequestObject) (GetJobsIdStatusResponseObject, error) + // Modify status of an existing job + // (PUT /jobs/{id}/status) + PutJobsIdStatus(ctx context.Context, request PutJobsIdStatusRequestObject) (PutJobsIdStatusResponseObject, error) + // Delete a tag + // (DELETE /jobs/{id}/tags) + DeleteJobsIdTags(ctx context.Context, request DeleteJobsIdTagsRequestObject) (DeleteJobsIdTagsResponseObject, error) + // Get tags + // (GET /jobs/{id}/tags) + GetJobsIdTags(ctx context.Context, request GetJobsIdTagsRequestObject) (GetJobsIdTagsResponseObject, error) + // Add a tag + // (POST /jobs/{id}/tags) + PostJobsIdTags(ctx context.Context, request PostJobsIdTagsRequestObject) (PostJobsIdTagsResponseObject, error) + // Get version information + // (GET /version) + GetVersion(ctx context.Context, request GetVersionRequestObject) (GetVersionResponseObject, error) + // List of available workflows + // (GET /workflows) + GetWorkflows(ctx context.Context, request GetWorkflowsRequestObject) (GetWorkflowsResponseObject, error) + // Add a new workflow + // (POST /workflows) + PostWorkflows(ctx context.Context, request PostWorkflowsRequestObject) (PostWorkflowsResponseObject, error) + // Delete an existing workflow + // (DELETE /workflows/{name}) + DeleteWorkflowsName(ctx context.Context, request DeleteWorkflowsNameRequestObject) (DeleteWorkflowsNameResponseObject, error) + // Workflow description for a given name + // (GET /workflows/{name}) + GetWorkflowsName(ctx context.Context, request GetWorkflowsNameRequestObject) (GetWorkflowsNameResponseObject, error) +} + +type StrictHandlerFunc = strictnethttp.StrictHTTPHandlerFunc +type StrictMiddlewareFunc = strictnethttp.StrictHTTPMiddlewareFunc + +type StrictHTTPServerOptions struct { + RequestErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) + ResponseErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) +} + +func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { + return &strictHandler{ssi: ssi, middlewares: middlewares, options: StrictHTTPServerOptions{ + RequestErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { + http.Error(w, err.Error(), http.StatusBadRequest) + }, + ResponseErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { + http.Error(w, err.Error(), http.StatusInternalServerError) + }, + }} +} + +func NewStrictHandlerWithOptions(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc, options StrictHTTPServerOptions) ServerInterface { + return &strictHandler{ssi: ssi, middlewares: middlewares, options: options} +} + +type strictHandler struct { + ssi StrictServerInterface + middlewares []StrictMiddlewareFunc + options StrictHTTPServerOptions +} + +// GetHealth operation middleware +func (sh *strictHandler) GetHealth(w http.ResponseWriter, r *http.Request) { + var request GetHealthRequestObject + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.GetHealth(ctx, request.(GetHealthRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "GetHealth") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(GetHealthResponseObject); ok { + if err := validResponse.VisitGetHealthResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// GetJobs operation middleware +func (sh *strictHandler) GetJobs(w http.ResponseWriter, r *http.Request, params GetJobsParams) { + var request GetJobsRequestObject + + request.Params = params + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.GetJobs(ctx, request.(GetJobsRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "GetJobs") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(GetJobsResponseObject); ok { + if err := validResponse.VisitGetJobsResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// PostJobs operation middleware +func (sh *strictHandler) PostJobs(w http.ResponseWriter, r *http.Request, params PostJobsParams) { + var request PostJobsRequestObject + + request.Params = params + + var body PostJobsJSONRequestBody + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) + return + } + request.Body = &body + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.PostJobs(ctx, request.(PostJobsRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "PostJobs") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(PostJobsResponseObject); ok { + if err := validResponse.VisitPostJobsResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// GetJobsEvents operation middleware +func (sh *strictHandler) GetJobsEvents(w http.ResponseWriter, r *http.Request, params GetJobsEventsParams) { + var request GetJobsEventsRequestObject + + request.Params = params + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.GetJobsEvents(ctx, request.(GetJobsEventsRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "GetJobsEvents") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(GetJobsEventsResponseObject); ok { + if err := validResponse.VisitGetJobsEventsResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// DeleteJobsId operation middleware +func (sh *strictHandler) DeleteJobsId(w http.ResponseWriter, r *http.Request, id string) { + var request DeleteJobsIdRequestObject + + request.Id = id + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.DeleteJobsId(ctx, request.(DeleteJobsIdRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "DeleteJobsId") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(DeleteJobsIdResponseObject); ok { + if err := validResponse.VisitDeleteJobsIdResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// GetJobsId operation middleware +func (sh *strictHandler) GetJobsId(w http.ResponseWriter, r *http.Request, id string, params GetJobsIdParams) { + var request GetJobsIdRequestObject + + request.Id = id + request.Params = params + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.GetJobsId(ctx, request.(GetJobsIdRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "GetJobsId") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(GetJobsIdResponseObject); ok { + if err := validResponse.VisitGetJobsIdResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// GetJobsIdDefinition operation middleware +func (sh *strictHandler) GetJobsIdDefinition(w http.ResponseWriter, r *http.Request, id string, params GetJobsIdDefinitionParams) { + var request GetJobsIdDefinitionRequestObject + + request.Id = id + request.Params = params + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.GetJobsIdDefinition(ctx, request.(GetJobsIdDefinitionRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "GetJobsIdDefinition") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(GetJobsIdDefinitionResponseObject); ok { + if err := validResponse.VisitGetJobsIdDefinitionResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// PutJobsIdDefinition operation middleware +func (sh *strictHandler) PutJobsIdDefinition(w http.ResponseWriter, r *http.Request, id string, params PutJobsIdDefinitionParams) { + var request PutJobsIdDefinitionRequestObject + + request.Id = id + request.Params = params + + var body PutJobsIdDefinitionJSONRequestBody + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) + return + } + request.Body = &body + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.PutJobsIdDefinition(ctx, request.(PutJobsIdDefinitionRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "PutJobsIdDefinition") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(PutJobsIdDefinitionResponseObject); ok { + if err := validResponse.VisitPutJobsIdDefinitionResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// GetJobsIdStatus operation middleware +func (sh *strictHandler) GetJobsIdStatus(w http.ResponseWriter, r *http.Request, id string, params GetJobsIdStatusParams) { + var request GetJobsIdStatusRequestObject + + request.Id = id + request.Params = params + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.GetJobsIdStatus(ctx, request.(GetJobsIdStatusRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "GetJobsIdStatus") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(GetJobsIdStatusResponseObject); ok { + if err := validResponse.VisitGetJobsIdStatusResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// PutJobsIdStatus operation middleware +func (sh *strictHandler) PutJobsIdStatus(w http.ResponseWriter, r *http.Request, id string, params PutJobsIdStatusParams) { + var request PutJobsIdStatusRequestObject + + request.Id = id + request.Params = params + + var body PutJobsIdStatusJSONRequestBody + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) + return + } + request.Body = &body + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.PutJobsIdStatus(ctx, request.(PutJobsIdStatusRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "PutJobsIdStatus") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(PutJobsIdStatusResponseObject); ok { + if err := validResponse.VisitPutJobsIdStatusResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// DeleteJobsIdTags operation middleware +func (sh *strictHandler) DeleteJobsIdTags(w http.ResponseWriter, r *http.Request, id string, params DeleteJobsIdTagsParams) { + var request DeleteJobsIdTagsRequestObject + + request.Id = id + request.Params = params + + var body DeleteJobsIdTagsJSONRequestBody + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) + return + } + request.Body = &body + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.DeleteJobsIdTags(ctx, request.(DeleteJobsIdTagsRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "DeleteJobsIdTags") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(DeleteJobsIdTagsResponseObject); ok { + if err := validResponse.VisitDeleteJobsIdTagsResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// GetJobsIdTags operation middleware +func (sh *strictHandler) GetJobsIdTags(w http.ResponseWriter, r *http.Request, id string, params GetJobsIdTagsParams) { + var request GetJobsIdTagsRequestObject + + request.Id = id + request.Params = params + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.GetJobsIdTags(ctx, request.(GetJobsIdTagsRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "GetJobsIdTags") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(GetJobsIdTagsResponseObject); ok { + if err := validResponse.VisitGetJobsIdTagsResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// PostJobsIdTags operation middleware +func (sh *strictHandler) PostJobsIdTags(w http.ResponseWriter, r *http.Request, id string, params PostJobsIdTagsParams) { + var request PostJobsIdTagsRequestObject + + request.Id = id + request.Params = params + + var body PostJobsIdTagsJSONRequestBody + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) + return + } + request.Body = &body + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.PostJobsIdTags(ctx, request.(PostJobsIdTagsRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "PostJobsIdTags") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(PostJobsIdTagsResponseObject); ok { + if err := validResponse.VisitPostJobsIdTagsResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// GetVersion operation middleware +func (sh *strictHandler) GetVersion(w http.ResponseWriter, r *http.Request) { + var request GetVersionRequestObject + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.GetVersion(ctx, request.(GetVersionRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "GetVersion") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(GetVersionResponseObject); ok { + if err := validResponse.VisitGetVersionResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// GetWorkflows operation middleware +func (sh *strictHandler) GetWorkflows(w http.ResponseWriter, r *http.Request, params GetWorkflowsParams) { + var request GetWorkflowsRequestObject + + request.Params = params + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.GetWorkflows(ctx, request.(GetWorkflowsRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "GetWorkflows") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(GetWorkflowsResponseObject); ok { + if err := validResponse.VisitGetWorkflowsResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// PostWorkflows operation middleware +func (sh *strictHandler) PostWorkflows(w http.ResponseWriter, r *http.Request, params PostWorkflowsParams) { + var request PostWorkflowsRequestObject + + request.Params = params + + var body PostWorkflowsJSONRequestBody + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) + return + } + request.Body = &body + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.PostWorkflows(ctx, request.(PostWorkflowsRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "PostWorkflows") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(PostWorkflowsResponseObject); ok { + if err := validResponse.VisitPostWorkflowsResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// DeleteWorkflowsName operation middleware +func (sh *strictHandler) DeleteWorkflowsName(w http.ResponseWriter, r *http.Request, name string) { + var request DeleteWorkflowsNameRequestObject + + request.Name = name + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.DeleteWorkflowsName(ctx, request.(DeleteWorkflowsNameRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "DeleteWorkflowsName") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(DeleteWorkflowsNameResponseObject); ok { + if err := validResponse.VisitDeleteWorkflowsNameResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// GetWorkflowsName operation middleware +func (sh *strictHandler) GetWorkflowsName(w http.ResponseWriter, r *http.Request, name string, params GetWorkflowsNameParams) { + var request GetWorkflowsNameRequestObject + + request.Name = name + request.Params = params + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.GetWorkflowsName(ctx, request.(GetWorkflowsNameRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "GetWorkflowsName") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(GetWorkflowsNameResponseObject); ok { + if err := validResponse.VisitGetWorkflowsNameResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// Base64 encoded, gzipped, json marshaled Swagger object +var swaggerSpec = []string{ + + "H4sIAAAAAAAC/+w9a3PbNrZ/BcO7M01mJZl6WLL0zY3d1h7XyY3d7c5GubsgeSjBoQgWAC2rGf/3O3jw", + "JYKSbMvepvVMp5GE18HBeZ8D+Kvj00VCY4gFdyZfnQQzvAABTH3zIwKxOAvk5wC4z0giCI2difMDiQQw", + "dEM9jjyIaDwj8QwJijDiCfgkJD7So9GSiDnKZ2o5RI7/LQW2clpOjBfgTJxSM/fnsMByRbFKZBsXjMQz", + "577l3LVntG1GKEDf6WEnsnHGaJpsARRzCBCNkZgDUv3lpxXCDBCJnZYDd0lEA3AmIY442EHV65ThJAIW", + "3Aqw+QEzhlfyOxerSP4QUrZwLPv5Uc1933LmhAvKVvXtfE9pBDhGYYQVuknsR2kAakeC4ZgT2RGZ8YiG", + "quWGeg2Izxay4N3TS1kR/5MZdt9yIrIgog6oXHaB78giXaA4XXjAJDAKVRJuBiJlcQNQesoySAGEOI2E", + "M+m6LYU9LJyJQ2LR7zk5mkksYAbMCvCFmvK+5dAw5NAArwVO/oUkyIOQMkBcYCYMmWv4EQOeRoI37MOs", + "Zd3I2j6Gg9328V5Ped9yGPCExhw0gdc3dJwk0QphdPNbOyJfAIWaEQRVFJGNziCfAw6AFaD/s/3R9Gib", + "BTZwpqRsyhqQSlmgcapRBgGCCBZK3tixpqYqr/Y3BqEzcf7noBBVB7qVH1xRJk7jdGFFlmzUbIcFPEA0", + "+CljUnKpcegWRyk0wapmfpjQulJjpHTAM8uxoYhwoRgXz/iOMknOtCvGrvHsgnCxizi6xuZw9VA587Ev", + "4VQYn3x1QP37yTn7+efTk7Pj61On5fx6fHbtfG7VEXF8i0mEPRIRsZI4SHl993JiYFjJMBqihHJOvAgQ", + "Lo1Vx5Jy4B2JHQOBEskBXUqRksZfYvmpBoTZovyxLRm7TdW6OGonVDIdcyaCpSC70YUUAYlY6Z/uW867", + "OfhfPip+r8P9E+BIzBGJNU9L8EPKEEa+HAUByg9CAp0wmgATBBQGgDFq4d9rSYhyNFId0AI4xzNoIaJl", + "um4LMYkgUJi4w4tEHee7bC0UU4EYYH+OvQicvaKD5ye4idgsZy4JnyyAC7xI7LuWzWg5h7i0zyXmCO7A", + "T8X6bntur9/uum23f911J93DSd/9l1MSrgEW0JZT7nP/hW6n3g34ipsUgQArSKR6zAEITCL1EQcB0St9", + "qHTZhMky+d231rB2oudGPo0FJjFH8wZ6jKI6RSo+qu1GDq0fz1kc0mKVYh+VlbBHU4HEnORwaDVpXefx", + "dKR04G8pYRBICWAm+mxZ4zQiMylG1sXWu4uz08trKbN++KddWsRpFCne0dJXzpVxa/V0fSWia+gKIBYk", + "JMCQ7KDOQGtfzLWEk9+0ALBIzIjOFE7Wp72gM+RTxiDSCD87sY02AsMiZMvypD5yDa9qZzksxbRWRMuZ", + "M8OhjiS1UV4xmTcduka13Am+O9MDur2jdavaxoo/Zr7AOguW0PC1JENOiobsUDIz/1Ei4z7TzOVF3n84", + "vbSdk7Ih+CZLQPeo+lmKvTIgmz2QBYkz1FkQVz5nBXAOje10fyqcknW8hiQmdbR+RVMn5cBOZDsEU2eC", + "vt6j+2lsEwQLJaNrWDiRJhiOA60V3pxdvT8aut23hX64oZ7SDgsaSE4L0BsOAnkrtAzv3jYpAgY4eB9H", + "q0zCWw9lu1g6p15JGtW2dE49i6Qo+dQFqvSvg14TxRmzLHd4dyfEpx/O7ms1uq3X+qC+45ln2kEXmAtE", + "4hYKCZNkngr05uLsh/dvO+hYEigiHAmWxj4WEEijhwiOIohnYo7gzgcIOCo7mTiK6BIC06Uzjb9fIeNt", + "tXJCyfxiwpFU6XLmkNFF7g5xlMYRcGlrJBHxiYhWSDIJcNnVW2mLRMc13nDQfvd/zKz/Qb98vEB5BOVt", + "R+FyJ1FX8qcLYXfUHffWmNZuixFLgOaXmPyW6k2fnaA3y/CuPYNY2tYQvK0YUP2+O4JD32u7o4HfHoy9", + "UXs8DgbtQxh2j/pjPPB7gaPgulCodSb94TYOqlLtg+j1qXIgknT1IGFQKHm9lf0LBznkabvyGSg+KO+n", + "g44jMafpbI7U9NIw8yERKY6k5x8t8UoSMuGCtxAR33GU7RR54OOUA1oCCmj8nUBLHAsV7wBGcER+BzMl", + "iRGncmosmeMNdGYdZcVIuOBW7vdtZ294VR7v7u7rkrIvYUSX24b8mvVbV3kksOq5c+qdyq3VZTf2Mzla", + "g93PDngnVNSG32hVsYWeykjaNerYoJg+aqm2WT9VifWdokF19JkhOyO3EGcCUbH541VaTVfVVYgiZmkA", + "SRiKzmhJogh50q5OIuxDoGPOykRS3jLhyGxSiX7pFisJWvUkn0MjPoGkq9vPiBgZO60AexnedbJxnQCn", + "nYAwDeQWw76IuefLNrBDU7jmnHomGlN2AGsRjg0kZVIEc+LPEZcfJVWZKdMk0NG1ZzeT7GpV+rlwJ5qg", + "bueJjvOr95dII0zHhhPKRNk7NjNVvGSe+nOEuYnumOhAS+7d/4IEwz7wFgLhV0l0GiM0dSISA5f0+cl8", + "6U6dlvnYmzro8zRusLILpvkJ87n9REuMNZedKrp/ONhR9z8O541O60ftMpv2A4nJFgqZNMEkZpUVp6mj", + "Cm/X7Q32CmHCpCfMLdzwzoSNpXDKeqEEmA+x0J52LXNhjFcJpmuL/zdEri/xAjJHNYYlyvgXZfHogmJO", + "L0+2SgI9ysb7H/CMxNLwOKeeklE1UPIeubd6Qz1eFwGSA7RK3ckgzpTdWgIt0asZBbFpgg9Fz/XtliZp", + "5YBt3H0mfHdFQXYeT8dDYbv8QZBhVqvu6ok5wJxae+5mHimxcolJniull4O1W65OUIEjOxSqaR2W8gpd", + "191lkbWzy/KkeZ5Rg2A7vTxPVs5BOpj7pRyK/iaht+ZvrjJZ9PigWiae9hdUu7o+/ni9VcCpcTa0ZKZX", + "mR1LsvOXj+8/nP7719Ora2uAtQhLDi1++qM1zHWex9/kgWwMlxdZuvVcwZYTKmoInnBMYOLtWwO85bj8", + "fcuRSnyn45WUvnZUO6i5HCyzkprFRhW/lqzwjcS+noWpoTM3rMsq+Vr5JRzhcvN+TJasDmb3IHteclKi", + "5vL6e6DnjGvXAlQcmDSTbkkAAUp1uGr5CC9nzThdkDhHpNSRQgCT6/3fJ9z+/bj9L7c9nk7b02nn89//", + "tjkcvxP+8mx+gb+BOx7uFLcrmG339UrCYU0E9Y8GO6xqj/qXIdmQA7gvJQYj4oPJ8hiv6zjB/hxQr+M6", + "LSdlkTNx5kIkk4OD5XLZwaq1Q9nswAzlBxdn704vr07bvY7bmYtFpJPDQh147vCeqrSvypDdAuOaerqd", + "rlrmrn1LONGJQWfiwJ08bawmognEOCHOxOl3XNU5wWKuEHyg85Ly48xmOfxvCmyVJS9NtE9NqEsTpCfr", + "/AhCZ/2dohZHTd5z3TVLDydJRHw19OCGa9GxW7FGNaes8L+WJIoixFdc2TZpokKJLI1jLTJ0UY8C6p1E", + "fvsdjQWjUXX9utA8vUsI05vZ1O0DwzPd1txL9jt0+y+HkCu6APRG57rf5qjBDJCpDvmDICU3wtZp772Y", + "AzNRARXGwnFW8qKTyOqMDcEhjwYrpO3Gjq7VSRcLzFaNRKwDUp8cTlMx92gaB07LiSnLvnyWkxwoH66J", + "Oy4KRw+VWvh6yoVwBHGgFIQxrnXGpuwoIhKXS0Z1sZjcYcIgAAFsQWIIkPJSZqhQxp1pfD0HDtl66ogn", + "0xihNjrmPsSB7M8pE4jGOpatG7suglgwAso1lxODipTUmPvcuLGlgthPdtosuhysFeXdt7aOiExh4taO", + "NKv829qT67K37f2M6tracWZshK0d80DfDn0FnqluzTV5Cyz8uTxGb1W2lGwFcKXmh5TiFd7152cU4rUg", + "ik2OoySPIki+kjzSkTAPdgIkt5OKIotPX51p6rp9X/9fuZG3OCKBifyb6orP97sWDlaLOyx7OAuzXKm0", + "bs1qTlXW7QWhWyExe6uIwyaptZNMbDkJtYV+joMAYRWCu6GeRY58oHw/guSzNtuAi+9psNobJkuJIAsa", + "z6mXhebnWGdYTB7SKVuRxppd45/uPoFshK5IjX5jzPI9DlCOegl531KgTJlHggBi50UMhgoxl9jCah0c", + "6Oxvo5Hw3hOYxIjEXGBdiSoVvDoInqe3GSjLTLKkP8fxDEpCX1VaMCKAEdxB1xVrIhUkIr8DRxzYLbC2", + "yhxpgNCbq6vTty25BINSXYdcZ+r48zT+AsHU0ZgKaOpFKoQekRiQxwB/4R30A2XIEElLWicknkWg50cL", + "MpsLFFH6BamyemnmKLsjwAJP0Ndpnu2aOpNpRmv/1j9OndZUe1eq8ezy6vr44uLs8sepcz+dxvK/Rlvk", + "9NbUzK8JkqZCmwwMtEi5kKxL4yxnwCFv5eiNTxcL3OYg5xUQqHz+pjs6fHclm+XhuEXTF5CSBhjJQ6C7", + "od4W0DaBkMcdMkDgtxRHSNASREWwohKleACM5bTAA8A8rq9QuSRQvgdEYkERYH9eVGgY5vFxLDeWcgjU", + "Pa3ZjMFMzpYxjkqhLdJIkCQCtAzvDPP6ytp2Gm8ebN7NdsNKwJ3Q0qTNBQO8qGqGPCqyFonDYhfFoQs5", + "GmqkVEnBrS5d6NjD7Vk0QiobPZclXph1ulLSCF3JGXN2XavGsFh+eteq0LMmzvas1W6od618KhypwNUL", + "6LXBHmG/pOIHqYf2D/YlFUhN/Tyqdk3TXqWenNYDyYk31GurUm4IMlbMagMqhRAP894PvpLgXu8gAlsO", + "+UT9jnBcqaqx6B/dUaogVSuyUf2cq3LDTFYkWEXHjKggdavxYYJj0FhXiuaYIw8gRnq3QWc3m2qP1JnJ", + "9m+WRNetQTt9NJmFLbsVeF51tsylKF01dnbSbOzYKO3hoZdno83t0Y2sEvpZAwsbHKN1pFcR/637Sq86", + "xcKwm3nt4crjoFqNaeXvjyAYgVvIa5VLYxpZ+6Tc54/L5E/l3Efdg2ni5hxjr/TfRP8/gqiT4E6hvdQC", + "1s80IOHKQtfSTt9uNH1Iv0Fif1x8cU90fm1qGWtHuC3Q+F/jyvySCU99HzgP0yhavarWP6FoMcLg4dKl", + "5dy15UoziNuGv9pynSxAdk69koBY07/FNaPddG9zoYIWRVdZ+59X5+56WdPKzzy/rfXKBhs17AOKCTZr", + "VwPEwzTqt0LGz5Kta6ZgHeTNnmYQJW2aH9d+NemTeO1Vd/7FdGcjq+9DjV5WKX1Nj2Z38LZFQpHAM50F", + "eVhQ9FrnQP6U4uhxL0vUhZNJU5kjeElRlN+utNQKlmRPFjlGui7pT11K8CqpNka8kX5OzRbn3iaIlCho", + "CoZL80ndsZDMIAWhEX8N5vq3IVZenmvlDoTB8yslNxrqJjP/1No2od8Z3cE+N6Vur/rwAfoQB8EfUhni", + "INCq0CSoXzXiX1KO5CLgSepQWuP5zZ3mYFZ+P8D0rbyWYEqwSqdiU5z/MKs8kYPWrlwm5B8F9EX8+Lb7", + "hCuSXkqi4MRcqK08Zjlou6N2r3/dPZz0jiaHg7+7vYnr7vVFS/W2xcJc2S4tfhgOgqAfjo96R4eHfX8M", + "g/4I9wbhKMSDwy6GoTvuDsPeE5a9tSHS7fQ7j8fl/Q7R+kK2FWSvGMNCap2XU9GW1TW3FIWC2+7gmIdx", + "I6i8OVBjjF/LDxJ8qzdaXuSORuWpB2u5Xv2RhxchmM0nvo8rDKVLNHXTbn8U9EzB0dIrX7VDy++SFo/0", + "eKCNnBe9ybATjM93p6FUo6afB8xeWG3seaYNtb/Y9YcSIzTegciZ7+CrNHYeWmqZDW8MLeb8dqlvaG8s", + "u1x/HMziIpmWZ6i/zKvhX4swX6IIcxtxNgSfchJpKhEzBNJsOtgJ8aluvXmnVK6evyq4ftlz75TsvqxE", + "L6PcvExYuk3yBVZ/louer6zczMq7MuAOVZpyXnVTRGNOP7VxgBNysAzvDm67ysYy8zTJAZ7fBDJX9Ih5", + "25Pb7itZw3EcBcDIbfaGct5boST7Yw3IWyFcvMxX3NayTapes8j3jY4/nOV3/nj5D8TkmLFPUWCraYoS", + "Pu9VFEM9DdIWsEii7PmX0+K1egs/5W/+q5dpqj2K5/InzniI+yPA3XAU9NzDMPRC3O31+wN/eNTtjXqj", + "0ov6Wp1mnCXNQDOtQqhP0yhQT5d6oP54g05XmTepuaBMzqGfkq0yTRXUUnMZzm7X94ej0bDnjl3oHnqj", + "Me72j0bg4+Ghh4eHFTh1LFaBKAEKMy6yXy+qrV/pU0FWdxi6eNzt4z4M8GEPj4de0Bt1we2NfWmI74Ks", + "7G3jrCyKmEcmhFkVZe8e2K3cKrRrXSoYOwoPRzjwR24QjMb+KPQGYbc3GHpwhIfgDirA5tyvpjF/kUP9", + "7ZYyIJvObb1PGRR/cNgbdcej0cA9GnpDOHL7nncUDsEHPD4aj+2g5EenxFBJCFUhKrsKjSDpTmWYoAvQ", + "DXsY8NHh2BsHQX9wOBoPuy70j4YBHtphUiJWGQM4YoCDlXnAWr2a8v8BAAD//1TFzlatbgAA", +} + +// GetSwagger returns the content of the embedded swagger specification file +// or error if failed to decode +func decodeSpec() ([]byte, error) { + zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) + if err != nil { + return nil, fmt.Errorf("error base64 decoding spec: %w", err) + } + zr, err := gzip.NewReader(bytes.NewReader(zipped)) + if err != nil { + return nil, fmt.Errorf("error decompressing spec: %w", err) + } + var buf bytes.Buffer + _, err = buf.ReadFrom(zr) + if err != nil { + return nil, fmt.Errorf("error decompressing spec: %w", err) + } + + return buf.Bytes(), nil +} + +var rawSpec = decodeSpecCached() + +// a naive cached of a decoded swagger spec +func decodeSpecCached() func() ([]byte, error) { + data, err := decodeSpec() + return func() ([]byte, error) { + return data, err + } +} + +// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. +func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { + res := make(map[string]func() ([]byte, error)) + if len(pathToFile) > 0 { + res[pathToFile] = rawSpec + } + + return res +} + +// GetSwagger returns the Swagger specification corresponding to the generated code +// in this file. The external references of Swagger specification are resolved. +// The logic of resolving external references is tightly connected to "import-mapping" feature. +// Externally referenced files must be embedded in the corresponding golang packages. +// Urls can be supported but this task was out of the scope. +func GetSwagger() (swagger *openapi3.T, err error) { + resolvePath := PathToRawSpec("") + + loader := openapi3.NewLoader() + loader.IsExternalRefsAllowed = true + loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { + pathToFile := url.String() + pathToFile = path.Clean(pathToFile) + getSpec, ok := resolvePath[pathToFile] + if !ok { + err1 := fmt.Errorf("path not found: %s", pathToFile) + return nil, err1 + } + return getSpec() + } + var specData []byte + specData, err = rawSpec() + if err != nil { + return + } + swagger, err = loader.LoadFromData(specData) + if err != nil { + return + } + return +} diff --git a/generated/client/jobs/delete_jobs_id_parameters.go b/generated/client/jobs/delete_jobs_id_parameters.go deleted file mode 100644 index 72f57cbe..00000000 --- a/generated/client/jobs/delete_jobs_id_parameters.go +++ /dev/null @@ -1,156 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "net/http" - "time" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - "github.com/go-openapi/strfmt" -) - -// NewDeleteJobsIDParams creates a new DeleteJobsIDParams object, -// with the default timeout for this client. -// -// Default values are not hydrated, since defaults are normally applied by the API server side. -// -// To enforce default values in parameter, use SetDefaults or WithDefaults. -func NewDeleteJobsIDParams() *DeleteJobsIDParams { - return &DeleteJobsIDParams{ - timeout: cr.DefaultTimeout, - } -} - -// NewDeleteJobsIDParamsWithTimeout creates a new DeleteJobsIDParams object -// with the ability to set a timeout on a request. -func NewDeleteJobsIDParamsWithTimeout(timeout time.Duration) *DeleteJobsIDParams { - return &DeleteJobsIDParams{ - timeout: timeout, - } -} - -// NewDeleteJobsIDParamsWithContext creates a new DeleteJobsIDParams object -// with the ability to set a context for a request. -func NewDeleteJobsIDParamsWithContext(ctx context.Context) *DeleteJobsIDParams { - return &DeleteJobsIDParams{ - Context: ctx, - } -} - -// NewDeleteJobsIDParamsWithHTTPClient creates a new DeleteJobsIDParams object -// with the ability to set a custom HTTPClient for a request. -func NewDeleteJobsIDParamsWithHTTPClient(client *http.Client) *DeleteJobsIDParams { - return &DeleteJobsIDParams{ - HTTPClient: client, - } -} - -/* -DeleteJobsIDParams contains all the parameters to send to the API endpoint - - for the delete jobs ID operation. - - Typically these are written to a http.Request. -*/ -type DeleteJobsIDParams struct { - - /* ID. - - Job ID - */ - ID string - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithDefaults hydrates default values in the delete jobs ID params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *DeleteJobsIDParams) WithDefaults() *DeleteJobsIDParams { - o.SetDefaults() - return o -} - -// SetDefaults hydrates default values in the delete jobs ID params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *DeleteJobsIDParams) SetDefaults() { - // no default values defined for this parameter -} - -// WithTimeout adds the timeout to the delete jobs ID params -func (o *DeleteJobsIDParams) WithTimeout(timeout time.Duration) *DeleteJobsIDParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the delete jobs ID params -func (o *DeleteJobsIDParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the delete jobs ID params -func (o *DeleteJobsIDParams) WithContext(ctx context.Context) *DeleteJobsIDParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the delete jobs ID params -func (o *DeleteJobsIDParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the delete jobs ID params -func (o *DeleteJobsIDParams) WithHTTPClient(client *http.Client) *DeleteJobsIDParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the delete jobs ID params -func (o *DeleteJobsIDParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithID adds the id to the delete jobs ID params -func (o *DeleteJobsIDParams) WithID(id string) *DeleteJobsIDParams { - o.SetID(id) - return o -} - -// SetID adds the id to the delete jobs ID params -func (o *DeleteJobsIDParams) SetID(id string) { - o.ID = id -} - -// WriteToRequest writes these params to a swagger request -func (o *DeleteJobsIDParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - // path param id - if err := r.SetPathParam("id", o.ID); err != nil { - return err - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/generated/client/jobs/delete_jobs_id_responses.go b/generated/client/jobs/delete_jobs_id_responses.go deleted file mode 100644 index 4fc711c1..00000000 --- a/generated/client/jobs/delete_jobs_id_responses.go +++ /dev/null @@ -1,238 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "encoding/json" - "fmt" - "io" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" -) - -// DeleteJobsIDReader is a Reader for the DeleteJobsID structure. -type DeleteJobsIDReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *DeleteJobsIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - case 204: - result := NewDeleteJobsIDNoContent() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - case 404: - result := NewDeleteJobsIDNotFound() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - default: - result := NewDeleteJobsIDDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewDeleteJobsIDNoContent creates a DeleteJobsIDNoContent with default headers values -func NewDeleteJobsIDNoContent() *DeleteJobsIDNoContent { - return &DeleteJobsIDNoContent{} -} - -/* -DeleteJobsIDNoContent describes a response with status code 204, with default header values. - -The job has been deleted. -*/ -type DeleteJobsIDNoContent struct { -} - -// IsSuccess returns true when this delete jobs Id no content response has a 2xx status code -func (o *DeleteJobsIDNoContent) IsSuccess() bool { - return true -} - -// IsRedirect returns true when this delete jobs Id no content response has a 3xx status code -func (o *DeleteJobsIDNoContent) IsRedirect() bool { - return false -} - -// IsClientError returns true when this delete jobs Id no content response has a 4xx status code -func (o *DeleteJobsIDNoContent) IsClientError() bool { - return false -} - -// IsServerError returns true when this delete jobs Id no content response has a 5xx status code -func (o *DeleteJobsIDNoContent) IsServerError() bool { - return false -} - -// IsCode returns true when this delete jobs Id no content response a status code equal to that given -func (o *DeleteJobsIDNoContent) IsCode(code int) bool { - return code == 204 -} - -// Code gets the status code for the delete jobs Id no content response -func (o *DeleteJobsIDNoContent) Code() int { - return 204 -} - -func (o *DeleteJobsIDNoContent) Error() string { - return fmt.Sprintf("[DELETE /jobs/{id}][%d] deleteJobsIdNoContent", 204) -} - -func (o *DeleteJobsIDNoContent) String() string { - return fmt.Sprintf("[DELETE /jobs/{id}][%d] deleteJobsIdNoContent", 204) -} - -func (o *DeleteJobsIDNoContent) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - return nil -} - -// NewDeleteJobsIDNotFound creates a DeleteJobsIDNotFound with default headers values -func NewDeleteJobsIDNotFound() *DeleteJobsIDNotFound { - return &DeleteJobsIDNotFound{} -} - -/* -DeleteJobsIDNotFound describes a response with status code 404, with default header values. - -Not Found -*/ -type DeleteJobsIDNotFound struct { - Payload *model.ErrorResponse -} - -// IsSuccess returns true when this delete jobs Id not found response has a 2xx status code -func (o *DeleteJobsIDNotFound) IsSuccess() bool { - return false -} - -// IsRedirect returns true when this delete jobs Id not found response has a 3xx status code -func (o *DeleteJobsIDNotFound) IsRedirect() bool { - return false -} - -// IsClientError returns true when this delete jobs Id not found response has a 4xx status code -func (o *DeleteJobsIDNotFound) IsClientError() bool { - return true -} - -// IsServerError returns true when this delete jobs Id not found response has a 5xx status code -func (o *DeleteJobsIDNotFound) IsServerError() bool { - return false -} - -// IsCode returns true when this delete jobs Id not found response a status code equal to that given -func (o *DeleteJobsIDNotFound) IsCode(code int) bool { - return code == 404 -} - -// Code gets the status code for the delete jobs Id not found response -func (o *DeleteJobsIDNotFound) Code() int { - return 404 -} - -func (o *DeleteJobsIDNotFound) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[DELETE /jobs/{id}][%d] deleteJobsIdNotFound %s", 404, payload) -} - -func (o *DeleteJobsIDNotFound) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[DELETE /jobs/{id}][%d] deleteJobsIdNotFound %s", 404, payload) -} - -func (o *DeleteJobsIDNotFound) GetPayload() *model.ErrorResponse { - return o.Payload -} - -func (o *DeleteJobsIDNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.ErrorResponse) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewDeleteJobsIDDefault creates a DeleteJobsIDDefault with default headers values -func NewDeleteJobsIDDefault(code int) *DeleteJobsIDDefault { - return &DeleteJobsIDDefault{ - _statusCode: code, - } -} - -/* -DeleteJobsIDDefault describes a response with status code -1, with default header values. - -Other error with any status code and response body format. -*/ -type DeleteJobsIDDefault struct { - _statusCode int -} - -// IsSuccess returns true when this delete jobs ID default response has a 2xx status code -func (o *DeleteJobsIDDefault) IsSuccess() bool { - return o._statusCode/100 == 2 -} - -// IsRedirect returns true when this delete jobs ID default response has a 3xx status code -func (o *DeleteJobsIDDefault) IsRedirect() bool { - return o._statusCode/100 == 3 -} - -// IsClientError returns true when this delete jobs ID default response has a 4xx status code -func (o *DeleteJobsIDDefault) IsClientError() bool { - return o._statusCode/100 == 4 -} - -// IsServerError returns true when this delete jobs ID default response has a 5xx status code -func (o *DeleteJobsIDDefault) IsServerError() bool { - return o._statusCode/100 == 5 -} - -// IsCode returns true when this delete jobs ID default response a status code equal to that given -func (o *DeleteJobsIDDefault) IsCode(code int) bool { - return o._statusCode == code -} - -// Code gets the status code for the delete jobs ID default response -func (o *DeleteJobsIDDefault) Code() int { - return o._statusCode -} - -func (o *DeleteJobsIDDefault) Error() string { - return fmt.Sprintf("[DELETE /jobs/{id}][%d] DeleteJobsID default", o._statusCode) -} - -func (o *DeleteJobsIDDefault) String() string { - return fmt.Sprintf("[DELETE /jobs/{id}][%d] DeleteJobsID default", o._statusCode) -} - -func (o *DeleteJobsIDDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - return nil -} diff --git a/generated/client/jobs/delete_jobs_id_tags_parameters.go b/generated/client/jobs/delete_jobs_id_tags_parameters.go deleted file mode 100644 index d6ce3615..00000000 --- a/generated/client/jobs/delete_jobs_id_tags_parameters.go +++ /dev/null @@ -1,178 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "net/http" - "time" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - "github.com/go-openapi/strfmt" -) - -// NewDeleteJobsIDTagsParams creates a new DeleteJobsIDTagsParams object, -// with the default timeout for this client. -// -// Default values are not hydrated, since defaults are normally applied by the API server side. -// -// To enforce default values in parameter, use SetDefaults or WithDefaults. -func NewDeleteJobsIDTagsParams() *DeleteJobsIDTagsParams { - return &DeleteJobsIDTagsParams{ - timeout: cr.DefaultTimeout, - } -} - -// NewDeleteJobsIDTagsParamsWithTimeout creates a new DeleteJobsIDTagsParams object -// with the ability to set a timeout on a request. -func NewDeleteJobsIDTagsParamsWithTimeout(timeout time.Duration) *DeleteJobsIDTagsParams { - return &DeleteJobsIDTagsParams{ - timeout: timeout, - } -} - -// NewDeleteJobsIDTagsParamsWithContext creates a new DeleteJobsIDTagsParams object -// with the ability to set a context for a request. -func NewDeleteJobsIDTagsParamsWithContext(ctx context.Context) *DeleteJobsIDTagsParams { - return &DeleteJobsIDTagsParams{ - Context: ctx, - } -} - -// NewDeleteJobsIDTagsParamsWithHTTPClient creates a new DeleteJobsIDTagsParams object -// with the ability to set a custom HTTPClient for a request. -func NewDeleteJobsIDTagsParamsWithHTTPClient(client *http.Client) *DeleteJobsIDTagsParams { - return &DeleteJobsIDTagsParams{ - HTTPClient: client, - } -} - -/* -DeleteJobsIDTagsParams contains all the parameters to send to the API endpoint - - for the delete jobs ID tags operation. - - Typically these are written to a http.Request. -*/ -type DeleteJobsIDTagsParams struct { - - /* Tags. - - Tags to add - */ - Tags []string - - /* ID. - - Job ID - */ - ID string - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithDefaults hydrates default values in the delete jobs ID tags params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *DeleteJobsIDTagsParams) WithDefaults() *DeleteJobsIDTagsParams { - o.SetDefaults() - return o -} - -// SetDefaults hydrates default values in the delete jobs ID tags params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *DeleteJobsIDTagsParams) SetDefaults() { - // no default values defined for this parameter -} - -// WithTimeout adds the timeout to the delete jobs ID tags params -func (o *DeleteJobsIDTagsParams) WithTimeout(timeout time.Duration) *DeleteJobsIDTagsParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the delete jobs ID tags params -func (o *DeleteJobsIDTagsParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the delete jobs ID tags params -func (o *DeleteJobsIDTagsParams) WithContext(ctx context.Context) *DeleteJobsIDTagsParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the delete jobs ID tags params -func (o *DeleteJobsIDTagsParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the delete jobs ID tags params -func (o *DeleteJobsIDTagsParams) WithHTTPClient(client *http.Client) *DeleteJobsIDTagsParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the delete jobs ID tags params -func (o *DeleteJobsIDTagsParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithTags adds the tags to the delete jobs ID tags params -func (o *DeleteJobsIDTagsParams) WithTags(tags []string) *DeleteJobsIDTagsParams { - o.SetTags(tags) - return o -} - -// SetTags adds the tags to the delete jobs ID tags params -func (o *DeleteJobsIDTagsParams) SetTags(tags []string) { - o.Tags = tags -} - -// WithID adds the id to the delete jobs ID tags params -func (o *DeleteJobsIDTagsParams) WithID(id string) *DeleteJobsIDTagsParams { - o.SetID(id) - return o -} - -// SetID adds the id to the delete jobs ID tags params -func (o *DeleteJobsIDTagsParams) SetID(id string) { - o.ID = id -} - -// WriteToRequest writes these params to a swagger request -func (o *DeleteJobsIDTagsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - if o.Tags != nil { - if err := r.SetBodyParam(o.Tags); err != nil { - return err - } - } - - // path param id - if err := r.SetPathParam("id", o.ID); err != nil { - return err - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/generated/client/jobs/delete_jobs_id_tags_responses.go b/generated/client/jobs/delete_jobs_id_tags_responses.go deleted file mode 100644 index 8c8ab3c2..00000000 --- a/generated/client/jobs/delete_jobs_id_tags_responses.go +++ /dev/null @@ -1,326 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "encoding/json" - "fmt" - "io" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" -) - -// DeleteJobsIDTagsReader is a Reader for the DeleteJobsIDTags structure. -type DeleteJobsIDTagsReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *DeleteJobsIDTagsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - case 200: - result := NewDeleteJobsIDTagsOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - case 400: - result := NewDeleteJobsIDTagsBadRequest() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - case 404: - result := NewDeleteJobsIDTagsNotFound() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - default: - result := NewDeleteJobsIDTagsDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewDeleteJobsIDTagsOK creates a DeleteJobsIDTagsOK with default headers values -func NewDeleteJobsIDTagsOK() *DeleteJobsIDTagsOK { - return &DeleteJobsIDTagsOK{} -} - -/* -DeleteJobsIDTagsOK describes a response with status code 200, with default header values. - -Successfully deleted tag -*/ -type DeleteJobsIDTagsOK struct { - Payload []string -} - -// IsSuccess returns true when this delete jobs Id tags o k response has a 2xx status code -func (o *DeleteJobsIDTagsOK) IsSuccess() bool { - return true -} - -// IsRedirect returns true when this delete jobs Id tags o k response has a 3xx status code -func (o *DeleteJobsIDTagsOK) IsRedirect() bool { - return false -} - -// IsClientError returns true when this delete jobs Id tags o k response has a 4xx status code -func (o *DeleteJobsIDTagsOK) IsClientError() bool { - return false -} - -// IsServerError returns true when this delete jobs Id tags o k response has a 5xx status code -func (o *DeleteJobsIDTagsOK) IsServerError() bool { - return false -} - -// IsCode returns true when this delete jobs Id tags o k response a status code equal to that given -func (o *DeleteJobsIDTagsOK) IsCode(code int) bool { - return code == 200 -} - -// Code gets the status code for the delete jobs Id tags o k response -func (o *DeleteJobsIDTagsOK) Code() int { - return 200 -} - -func (o *DeleteJobsIDTagsOK) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[DELETE /jobs/{id}/tags][%d] deleteJobsIdTagsOK %s", 200, payload) -} - -func (o *DeleteJobsIDTagsOK) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[DELETE /jobs/{id}/tags][%d] deleteJobsIdTagsOK %s", 200, payload) -} - -func (o *DeleteJobsIDTagsOK) GetPayload() []string { - return o.Payload -} - -func (o *DeleteJobsIDTagsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - // response payload - if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewDeleteJobsIDTagsBadRequest creates a DeleteJobsIDTagsBadRequest with default headers values -func NewDeleteJobsIDTagsBadRequest() *DeleteJobsIDTagsBadRequest { - return &DeleteJobsIDTagsBadRequest{} -} - -/* -DeleteJobsIDTagsBadRequest describes a response with status code 400, with default header values. - -Bad Request -*/ -type DeleteJobsIDTagsBadRequest struct { - Payload *model.ErrorResponse -} - -// IsSuccess returns true when this delete jobs Id tags bad request response has a 2xx status code -func (o *DeleteJobsIDTagsBadRequest) IsSuccess() bool { - return false -} - -// IsRedirect returns true when this delete jobs Id tags bad request response has a 3xx status code -func (o *DeleteJobsIDTagsBadRequest) IsRedirect() bool { - return false -} - -// IsClientError returns true when this delete jobs Id tags bad request response has a 4xx status code -func (o *DeleteJobsIDTagsBadRequest) IsClientError() bool { - return true -} - -// IsServerError returns true when this delete jobs Id tags bad request response has a 5xx status code -func (o *DeleteJobsIDTagsBadRequest) IsServerError() bool { - return false -} - -// IsCode returns true when this delete jobs Id tags bad request response a status code equal to that given -func (o *DeleteJobsIDTagsBadRequest) IsCode(code int) bool { - return code == 400 -} - -// Code gets the status code for the delete jobs Id tags bad request response -func (o *DeleteJobsIDTagsBadRequest) Code() int { - return 400 -} - -func (o *DeleteJobsIDTagsBadRequest) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[DELETE /jobs/{id}/tags][%d] deleteJobsIdTagsBadRequest %s", 400, payload) -} - -func (o *DeleteJobsIDTagsBadRequest) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[DELETE /jobs/{id}/tags][%d] deleteJobsIdTagsBadRequest %s", 400, payload) -} - -func (o *DeleteJobsIDTagsBadRequest) GetPayload() *model.ErrorResponse { - return o.Payload -} - -func (o *DeleteJobsIDTagsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.ErrorResponse) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewDeleteJobsIDTagsNotFound creates a DeleteJobsIDTagsNotFound with default headers values -func NewDeleteJobsIDTagsNotFound() *DeleteJobsIDTagsNotFound { - return &DeleteJobsIDTagsNotFound{} -} - -/* -DeleteJobsIDTagsNotFound describes a response with status code 404, with default header values. - -Not Found -*/ -type DeleteJobsIDTagsNotFound struct { - Payload *model.ErrorResponse -} - -// IsSuccess returns true when this delete jobs Id tags not found response has a 2xx status code -func (o *DeleteJobsIDTagsNotFound) IsSuccess() bool { - return false -} - -// IsRedirect returns true when this delete jobs Id tags not found response has a 3xx status code -func (o *DeleteJobsIDTagsNotFound) IsRedirect() bool { - return false -} - -// IsClientError returns true when this delete jobs Id tags not found response has a 4xx status code -func (o *DeleteJobsIDTagsNotFound) IsClientError() bool { - return true -} - -// IsServerError returns true when this delete jobs Id tags not found response has a 5xx status code -func (o *DeleteJobsIDTagsNotFound) IsServerError() bool { - return false -} - -// IsCode returns true when this delete jobs Id tags not found response a status code equal to that given -func (o *DeleteJobsIDTagsNotFound) IsCode(code int) bool { - return code == 404 -} - -// Code gets the status code for the delete jobs Id tags not found response -func (o *DeleteJobsIDTagsNotFound) Code() int { - return 404 -} - -func (o *DeleteJobsIDTagsNotFound) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[DELETE /jobs/{id}/tags][%d] deleteJobsIdTagsNotFound %s", 404, payload) -} - -func (o *DeleteJobsIDTagsNotFound) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[DELETE /jobs/{id}/tags][%d] deleteJobsIdTagsNotFound %s", 404, payload) -} - -func (o *DeleteJobsIDTagsNotFound) GetPayload() *model.ErrorResponse { - return o.Payload -} - -func (o *DeleteJobsIDTagsNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.ErrorResponse) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewDeleteJobsIDTagsDefault creates a DeleteJobsIDTagsDefault with default headers values -func NewDeleteJobsIDTagsDefault(code int) *DeleteJobsIDTagsDefault { - return &DeleteJobsIDTagsDefault{ - _statusCode: code, - } -} - -/* -DeleteJobsIDTagsDefault describes a response with status code -1, with default header values. - -Other error with any status code and response body format. -*/ -type DeleteJobsIDTagsDefault struct { - _statusCode int -} - -// IsSuccess returns true when this delete jobs ID tags default response has a 2xx status code -func (o *DeleteJobsIDTagsDefault) IsSuccess() bool { - return o._statusCode/100 == 2 -} - -// IsRedirect returns true when this delete jobs ID tags default response has a 3xx status code -func (o *DeleteJobsIDTagsDefault) IsRedirect() bool { - return o._statusCode/100 == 3 -} - -// IsClientError returns true when this delete jobs ID tags default response has a 4xx status code -func (o *DeleteJobsIDTagsDefault) IsClientError() bool { - return o._statusCode/100 == 4 -} - -// IsServerError returns true when this delete jobs ID tags default response has a 5xx status code -func (o *DeleteJobsIDTagsDefault) IsServerError() bool { - return o._statusCode/100 == 5 -} - -// IsCode returns true when this delete jobs ID tags default response a status code equal to that given -func (o *DeleteJobsIDTagsDefault) IsCode(code int) bool { - return o._statusCode == code -} - -// Code gets the status code for the delete jobs ID tags default response -func (o *DeleteJobsIDTagsDefault) Code() int { - return o._statusCode -} - -func (o *DeleteJobsIDTagsDefault) Error() string { - return fmt.Sprintf("[DELETE /jobs/{id}/tags][%d] DeleteJobsIDTags default", o._statusCode) -} - -func (o *DeleteJobsIDTagsDefault) String() string { - return fmt.Sprintf("[DELETE /jobs/{id}/tags][%d] DeleteJobsIDTags default", o._statusCode) -} - -func (o *DeleteJobsIDTagsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - return nil -} diff --git a/generated/client/jobs/get_jobs_events_parameters.go b/generated/client/jobs/get_jobs_events_parameters.go deleted file mode 100644 index 6909594d..00000000 --- a/generated/client/jobs/get_jobs_events_parameters.go +++ /dev/null @@ -1,271 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "net/http" - "time" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - "github.com/go-openapi/strfmt" -) - -// NewGetJobsEventsParams creates a new GetJobsEventsParams object, -// with the default timeout for this client. -// -// Default values are not hydrated, since defaults are normally applied by the API server side. -// -// To enforce default values in parameter, use SetDefaults or WithDefaults. -func NewGetJobsEventsParams() *GetJobsEventsParams { - return &GetJobsEventsParams{ - timeout: cr.DefaultTimeout, - } -} - -// NewGetJobsEventsParamsWithTimeout creates a new GetJobsEventsParams object -// with the ability to set a timeout on a request. -func NewGetJobsEventsParamsWithTimeout(timeout time.Duration) *GetJobsEventsParams { - return &GetJobsEventsParams{ - timeout: timeout, - } -} - -// NewGetJobsEventsParamsWithContext creates a new GetJobsEventsParams object -// with the ability to set a context for a request. -func NewGetJobsEventsParamsWithContext(ctx context.Context) *GetJobsEventsParams { - return &GetJobsEventsParams{ - Context: ctx, - } -} - -// NewGetJobsEventsParamsWithHTTPClient creates a new GetJobsEventsParams object -// with the ability to set a custom HTTPClient for a request. -func NewGetJobsEventsParamsWithHTTPClient(client *http.Client) *GetJobsEventsParams { - return &GetJobsEventsParams{ - HTTPClient: client, - } -} - -/* -GetJobsEventsParams contains all the parameters to send to the API endpoint - - for the get jobs events operation. - - Typically these are written to a http.Request. -*/ -type GetJobsEventsParams struct { - - /* ClientIds. - - The job's clientId must be one of these clientIds (comma-separated). - */ - ClientIds *string - - /* JobIds. - - The job's id must be one of these ids (comma-separated). - */ - JobIds *string - - /* Tags. - - A (comma-separated) list of tags to include into each job event. This can be used to aggregrate events from multiple wfx instances. - - */ - Tags *string - - /* Workflows. - - The job's workflow must be equal to one of the provided workflow names (comma-separated). - */ - Workflows *string - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithDefaults hydrates default values in the get jobs events params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *GetJobsEventsParams) WithDefaults() *GetJobsEventsParams { - o.SetDefaults() - return o -} - -// SetDefaults hydrates default values in the get jobs events params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *GetJobsEventsParams) SetDefaults() { - // no default values defined for this parameter -} - -// WithTimeout adds the timeout to the get jobs events params -func (o *GetJobsEventsParams) WithTimeout(timeout time.Duration) *GetJobsEventsParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the get jobs events params -func (o *GetJobsEventsParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the get jobs events params -func (o *GetJobsEventsParams) WithContext(ctx context.Context) *GetJobsEventsParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the get jobs events params -func (o *GetJobsEventsParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the get jobs events params -func (o *GetJobsEventsParams) WithHTTPClient(client *http.Client) *GetJobsEventsParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the get jobs events params -func (o *GetJobsEventsParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithClientIds adds the clientIds to the get jobs events params -func (o *GetJobsEventsParams) WithClientIds(clientIds *string) *GetJobsEventsParams { - o.SetClientIds(clientIds) - return o -} - -// SetClientIds adds the clientIds to the get jobs events params -func (o *GetJobsEventsParams) SetClientIds(clientIds *string) { - o.ClientIds = clientIds -} - -// WithJobIds adds the jobIds to the get jobs events params -func (o *GetJobsEventsParams) WithJobIds(jobIds *string) *GetJobsEventsParams { - o.SetJobIds(jobIds) - return o -} - -// SetJobIds adds the jobIds to the get jobs events params -func (o *GetJobsEventsParams) SetJobIds(jobIds *string) { - o.JobIds = jobIds -} - -// WithTags adds the tags to the get jobs events params -func (o *GetJobsEventsParams) WithTags(tags *string) *GetJobsEventsParams { - o.SetTags(tags) - return o -} - -// SetTags adds the tags to the get jobs events params -func (o *GetJobsEventsParams) SetTags(tags *string) { - o.Tags = tags -} - -// WithWorkflows adds the workflows to the get jobs events params -func (o *GetJobsEventsParams) WithWorkflows(workflows *string) *GetJobsEventsParams { - o.SetWorkflows(workflows) - return o -} - -// SetWorkflows adds the workflows to the get jobs events params -func (o *GetJobsEventsParams) SetWorkflows(workflows *string) { - o.Workflows = workflows -} - -// WriteToRequest writes these params to a swagger request -func (o *GetJobsEventsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - if o.ClientIds != nil { - - // query param clientIds - var qrClientIds string - - if o.ClientIds != nil { - qrClientIds = *o.ClientIds - } - qClientIds := qrClientIds - if qClientIds != "" { - - if err := r.SetQueryParam("clientIds", qClientIds); err != nil { - return err - } - } - } - - if o.JobIds != nil { - - // query param jobIds - var qrJobIds string - - if o.JobIds != nil { - qrJobIds = *o.JobIds - } - qJobIds := qrJobIds - if qJobIds != "" { - - if err := r.SetQueryParam("jobIds", qJobIds); err != nil { - return err - } - } - } - - if o.Tags != nil { - - // query param tags - var qrTags string - - if o.Tags != nil { - qrTags = *o.Tags - } - qTags := qrTags - if qTags != "" { - - if err := r.SetQueryParam("tags", qTags); err != nil { - return err - } - } - } - - if o.Workflows != nil { - - // query param workflows - var qrWorkflows string - - if o.Workflows != nil { - qrWorkflows = *o.Workflows - } - qWorkflows := qrWorkflows - if qWorkflows != "" { - - if err := r.SetQueryParam("workflows", qWorkflows); err != nil { - return err - } - } - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/generated/client/jobs/get_jobs_events_responses.go b/generated/client/jobs/get_jobs_events_responses.go deleted file mode 100644 index 299b8997..00000000 --- a/generated/client/jobs/get_jobs_events_responses.go +++ /dev/null @@ -1,314 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "encoding/json" - "fmt" - "io" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" -) - -// GetJobsEventsReader is a Reader for the GetJobsEvents structure. -type GetJobsEventsReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *GetJobsEventsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - case 200: - result := NewGetJobsEventsOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - case 400: - result := NewGetJobsEventsBadRequest() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - case 404: - result := NewGetJobsEventsNotFound() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - default: - result := NewGetJobsEventsDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewGetJobsEventsOK creates a GetJobsEventsOK with default headers values -func NewGetJobsEventsOK() *GetJobsEventsOK { - return &GetJobsEventsOK{} -} - -/* -GetJobsEventsOK describes a response with status code 200, with default header values. - -A stream of server-sent events -*/ -type GetJobsEventsOK struct { -} - -// IsSuccess returns true when this get jobs events o k response has a 2xx status code -func (o *GetJobsEventsOK) IsSuccess() bool { - return true -} - -// IsRedirect returns true when this get jobs events o k response has a 3xx status code -func (o *GetJobsEventsOK) IsRedirect() bool { - return false -} - -// IsClientError returns true when this get jobs events o k response has a 4xx status code -func (o *GetJobsEventsOK) IsClientError() bool { - return false -} - -// IsServerError returns true when this get jobs events o k response has a 5xx status code -func (o *GetJobsEventsOK) IsServerError() bool { - return false -} - -// IsCode returns true when this get jobs events o k response a status code equal to that given -func (o *GetJobsEventsOK) IsCode(code int) bool { - return code == 200 -} - -// Code gets the status code for the get jobs events o k response -func (o *GetJobsEventsOK) Code() int { - return 200 -} - -func (o *GetJobsEventsOK) Error() string { - return fmt.Sprintf("[GET /jobs/events][%d] getJobsEventsOK", 200) -} - -func (o *GetJobsEventsOK) String() string { - return fmt.Sprintf("[GET /jobs/events][%d] getJobsEventsOK", 200) -} - -func (o *GetJobsEventsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - return nil -} - -// NewGetJobsEventsBadRequest creates a GetJobsEventsBadRequest with default headers values -func NewGetJobsEventsBadRequest() *GetJobsEventsBadRequest { - return &GetJobsEventsBadRequest{} -} - -/* -GetJobsEventsBadRequest describes a response with status code 400, with default header values. - -Bad Request -*/ -type GetJobsEventsBadRequest struct { - Payload *model.ErrorResponse -} - -// IsSuccess returns true when this get jobs events bad request response has a 2xx status code -func (o *GetJobsEventsBadRequest) IsSuccess() bool { - return false -} - -// IsRedirect returns true when this get jobs events bad request response has a 3xx status code -func (o *GetJobsEventsBadRequest) IsRedirect() bool { - return false -} - -// IsClientError returns true when this get jobs events bad request response has a 4xx status code -func (o *GetJobsEventsBadRequest) IsClientError() bool { - return true -} - -// IsServerError returns true when this get jobs events bad request response has a 5xx status code -func (o *GetJobsEventsBadRequest) IsServerError() bool { - return false -} - -// IsCode returns true when this get jobs events bad request response a status code equal to that given -func (o *GetJobsEventsBadRequest) IsCode(code int) bool { - return code == 400 -} - -// Code gets the status code for the get jobs events bad request response -func (o *GetJobsEventsBadRequest) Code() int { - return 400 -} - -func (o *GetJobsEventsBadRequest) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs/events][%d] getJobsEventsBadRequest %s", 400, payload) -} - -func (o *GetJobsEventsBadRequest) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs/events][%d] getJobsEventsBadRequest %s", 400, payload) -} - -func (o *GetJobsEventsBadRequest) GetPayload() *model.ErrorResponse { - return o.Payload -} - -func (o *GetJobsEventsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.ErrorResponse) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetJobsEventsNotFound creates a GetJobsEventsNotFound with default headers values -func NewGetJobsEventsNotFound() *GetJobsEventsNotFound { - return &GetJobsEventsNotFound{} -} - -/* -GetJobsEventsNotFound describes a response with status code 404, with default header values. - -Not Found -*/ -type GetJobsEventsNotFound struct { - Payload *model.ErrorResponse -} - -// IsSuccess returns true when this get jobs events not found response has a 2xx status code -func (o *GetJobsEventsNotFound) IsSuccess() bool { - return false -} - -// IsRedirect returns true when this get jobs events not found response has a 3xx status code -func (o *GetJobsEventsNotFound) IsRedirect() bool { - return false -} - -// IsClientError returns true when this get jobs events not found response has a 4xx status code -func (o *GetJobsEventsNotFound) IsClientError() bool { - return true -} - -// IsServerError returns true when this get jobs events not found response has a 5xx status code -func (o *GetJobsEventsNotFound) IsServerError() bool { - return false -} - -// IsCode returns true when this get jobs events not found response a status code equal to that given -func (o *GetJobsEventsNotFound) IsCode(code int) bool { - return code == 404 -} - -// Code gets the status code for the get jobs events not found response -func (o *GetJobsEventsNotFound) Code() int { - return 404 -} - -func (o *GetJobsEventsNotFound) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs/events][%d] getJobsEventsNotFound %s", 404, payload) -} - -func (o *GetJobsEventsNotFound) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs/events][%d] getJobsEventsNotFound %s", 404, payload) -} - -func (o *GetJobsEventsNotFound) GetPayload() *model.ErrorResponse { - return o.Payload -} - -func (o *GetJobsEventsNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.ErrorResponse) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetJobsEventsDefault creates a GetJobsEventsDefault with default headers values -func NewGetJobsEventsDefault(code int) *GetJobsEventsDefault { - return &GetJobsEventsDefault{ - _statusCode: code, - } -} - -/* -GetJobsEventsDefault describes a response with status code -1, with default header values. - -Other error with any status code and response body format -*/ -type GetJobsEventsDefault struct { - _statusCode int -} - -// IsSuccess returns true when this get jobs events default response has a 2xx status code -func (o *GetJobsEventsDefault) IsSuccess() bool { - return o._statusCode/100 == 2 -} - -// IsRedirect returns true when this get jobs events default response has a 3xx status code -func (o *GetJobsEventsDefault) IsRedirect() bool { - return o._statusCode/100 == 3 -} - -// IsClientError returns true when this get jobs events default response has a 4xx status code -func (o *GetJobsEventsDefault) IsClientError() bool { - return o._statusCode/100 == 4 -} - -// IsServerError returns true when this get jobs events default response has a 5xx status code -func (o *GetJobsEventsDefault) IsServerError() bool { - return o._statusCode/100 == 5 -} - -// IsCode returns true when this get jobs events default response a status code equal to that given -func (o *GetJobsEventsDefault) IsCode(code int) bool { - return o._statusCode == code -} - -// Code gets the status code for the get jobs events default response -func (o *GetJobsEventsDefault) Code() int { - return o._statusCode -} - -func (o *GetJobsEventsDefault) Error() string { - return fmt.Sprintf("[GET /jobs/events][%d] GetJobsEvents default", o._statusCode) -} - -func (o *GetJobsEventsDefault) String() string { - return fmt.Sprintf("[GET /jobs/events][%d] GetJobsEvents default", o._statusCode) -} - -func (o *GetJobsEventsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - return nil -} diff --git a/generated/client/jobs/get_jobs_id_definition_parameters.go b/generated/client/jobs/get_jobs_id_definition_parameters.go deleted file mode 100644 index 81597c7e..00000000 --- a/generated/client/jobs/get_jobs_id_definition_parameters.go +++ /dev/null @@ -1,156 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "net/http" - "time" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - "github.com/go-openapi/strfmt" -) - -// NewGetJobsIDDefinitionParams creates a new GetJobsIDDefinitionParams object, -// with the default timeout for this client. -// -// Default values are not hydrated, since defaults are normally applied by the API server side. -// -// To enforce default values in parameter, use SetDefaults or WithDefaults. -func NewGetJobsIDDefinitionParams() *GetJobsIDDefinitionParams { - return &GetJobsIDDefinitionParams{ - timeout: cr.DefaultTimeout, - } -} - -// NewGetJobsIDDefinitionParamsWithTimeout creates a new GetJobsIDDefinitionParams object -// with the ability to set a timeout on a request. -func NewGetJobsIDDefinitionParamsWithTimeout(timeout time.Duration) *GetJobsIDDefinitionParams { - return &GetJobsIDDefinitionParams{ - timeout: timeout, - } -} - -// NewGetJobsIDDefinitionParamsWithContext creates a new GetJobsIDDefinitionParams object -// with the ability to set a context for a request. -func NewGetJobsIDDefinitionParamsWithContext(ctx context.Context) *GetJobsIDDefinitionParams { - return &GetJobsIDDefinitionParams{ - Context: ctx, - } -} - -// NewGetJobsIDDefinitionParamsWithHTTPClient creates a new GetJobsIDDefinitionParams object -// with the ability to set a custom HTTPClient for a request. -func NewGetJobsIDDefinitionParamsWithHTTPClient(client *http.Client) *GetJobsIDDefinitionParams { - return &GetJobsIDDefinitionParams{ - HTTPClient: client, - } -} - -/* -GetJobsIDDefinitionParams contains all the parameters to send to the API endpoint - - for the get jobs ID definition operation. - - Typically these are written to a http.Request. -*/ -type GetJobsIDDefinitionParams struct { - - /* ID. - - Job ID - */ - ID string - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithDefaults hydrates default values in the get jobs ID definition params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *GetJobsIDDefinitionParams) WithDefaults() *GetJobsIDDefinitionParams { - o.SetDefaults() - return o -} - -// SetDefaults hydrates default values in the get jobs ID definition params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *GetJobsIDDefinitionParams) SetDefaults() { - // no default values defined for this parameter -} - -// WithTimeout adds the timeout to the get jobs ID definition params -func (o *GetJobsIDDefinitionParams) WithTimeout(timeout time.Duration) *GetJobsIDDefinitionParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the get jobs ID definition params -func (o *GetJobsIDDefinitionParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the get jobs ID definition params -func (o *GetJobsIDDefinitionParams) WithContext(ctx context.Context) *GetJobsIDDefinitionParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the get jobs ID definition params -func (o *GetJobsIDDefinitionParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the get jobs ID definition params -func (o *GetJobsIDDefinitionParams) WithHTTPClient(client *http.Client) *GetJobsIDDefinitionParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the get jobs ID definition params -func (o *GetJobsIDDefinitionParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithID adds the id to the get jobs ID definition params -func (o *GetJobsIDDefinitionParams) WithID(id string) *GetJobsIDDefinitionParams { - o.SetID(id) - return o -} - -// SetID adds the id to the get jobs ID definition params -func (o *GetJobsIDDefinitionParams) SetID(id string) { - o.ID = id -} - -// WriteToRequest writes these params to a swagger request -func (o *GetJobsIDDefinitionParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - // path param id - if err := r.SetPathParam("id", o.ID); err != nil { - return err - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/generated/client/jobs/get_jobs_id_definition_responses.go b/generated/client/jobs/get_jobs_id_definition_responses.go deleted file mode 100644 index 9a7b81cd..00000000 --- a/generated/client/jobs/get_jobs_id_definition_responses.go +++ /dev/null @@ -1,250 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "encoding/json" - "fmt" - "io" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" -) - -// GetJobsIDDefinitionReader is a Reader for the GetJobsIDDefinition structure. -type GetJobsIDDefinitionReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *GetJobsIDDefinitionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - case 200: - result := NewGetJobsIDDefinitionOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - case 404: - result := NewGetJobsIDDefinitionNotFound() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - default: - result := NewGetJobsIDDefinitionDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewGetJobsIDDefinitionOK creates a GetJobsIDDefinitionOK with default headers values -func NewGetJobsIDDefinitionOK() *GetJobsIDDefinitionOK { - return &GetJobsIDDefinitionOK{} -} - -/* -GetJobsIDDefinitionOK describes a response with status code 200, with default header values. - -Job definition -*/ -type GetJobsIDDefinitionOK struct { - Payload map[string]interface{} -} - -// IsSuccess returns true when this get jobs Id definition o k response has a 2xx status code -func (o *GetJobsIDDefinitionOK) IsSuccess() bool { - return true -} - -// IsRedirect returns true when this get jobs Id definition o k response has a 3xx status code -func (o *GetJobsIDDefinitionOK) IsRedirect() bool { - return false -} - -// IsClientError returns true when this get jobs Id definition o k response has a 4xx status code -func (o *GetJobsIDDefinitionOK) IsClientError() bool { - return false -} - -// IsServerError returns true when this get jobs Id definition o k response has a 5xx status code -func (o *GetJobsIDDefinitionOK) IsServerError() bool { - return false -} - -// IsCode returns true when this get jobs Id definition o k response a status code equal to that given -func (o *GetJobsIDDefinitionOK) IsCode(code int) bool { - return code == 200 -} - -// Code gets the status code for the get jobs Id definition o k response -func (o *GetJobsIDDefinitionOK) Code() int { - return 200 -} - -func (o *GetJobsIDDefinitionOK) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs/{id}/definition][%d] getJobsIdDefinitionOK %s", 200, payload) -} - -func (o *GetJobsIDDefinitionOK) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs/{id}/definition][%d] getJobsIdDefinitionOK %s", 200, payload) -} - -func (o *GetJobsIDDefinitionOK) GetPayload() map[string]interface{} { - return o.Payload -} - -func (o *GetJobsIDDefinitionOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - // response payload - if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetJobsIDDefinitionNotFound creates a GetJobsIDDefinitionNotFound with default headers values -func NewGetJobsIDDefinitionNotFound() *GetJobsIDDefinitionNotFound { - return &GetJobsIDDefinitionNotFound{} -} - -/* -GetJobsIDDefinitionNotFound describes a response with status code 404, with default header values. - -Not Found -*/ -type GetJobsIDDefinitionNotFound struct { - Payload *model.ErrorResponse -} - -// IsSuccess returns true when this get jobs Id definition not found response has a 2xx status code -func (o *GetJobsIDDefinitionNotFound) IsSuccess() bool { - return false -} - -// IsRedirect returns true when this get jobs Id definition not found response has a 3xx status code -func (o *GetJobsIDDefinitionNotFound) IsRedirect() bool { - return false -} - -// IsClientError returns true when this get jobs Id definition not found response has a 4xx status code -func (o *GetJobsIDDefinitionNotFound) IsClientError() bool { - return true -} - -// IsServerError returns true when this get jobs Id definition not found response has a 5xx status code -func (o *GetJobsIDDefinitionNotFound) IsServerError() bool { - return false -} - -// IsCode returns true when this get jobs Id definition not found response a status code equal to that given -func (o *GetJobsIDDefinitionNotFound) IsCode(code int) bool { - return code == 404 -} - -// Code gets the status code for the get jobs Id definition not found response -func (o *GetJobsIDDefinitionNotFound) Code() int { - return 404 -} - -func (o *GetJobsIDDefinitionNotFound) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs/{id}/definition][%d] getJobsIdDefinitionNotFound %s", 404, payload) -} - -func (o *GetJobsIDDefinitionNotFound) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs/{id}/definition][%d] getJobsIdDefinitionNotFound %s", 404, payload) -} - -func (o *GetJobsIDDefinitionNotFound) GetPayload() *model.ErrorResponse { - return o.Payload -} - -func (o *GetJobsIDDefinitionNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.ErrorResponse) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetJobsIDDefinitionDefault creates a GetJobsIDDefinitionDefault with default headers values -func NewGetJobsIDDefinitionDefault(code int) *GetJobsIDDefinitionDefault { - return &GetJobsIDDefinitionDefault{ - _statusCode: code, - } -} - -/* -GetJobsIDDefinitionDefault describes a response with status code -1, with default header values. - -Other error with any status code and response body format. -*/ -type GetJobsIDDefinitionDefault struct { - _statusCode int -} - -// IsSuccess returns true when this get jobs ID definition default response has a 2xx status code -func (o *GetJobsIDDefinitionDefault) IsSuccess() bool { - return o._statusCode/100 == 2 -} - -// IsRedirect returns true when this get jobs ID definition default response has a 3xx status code -func (o *GetJobsIDDefinitionDefault) IsRedirect() bool { - return o._statusCode/100 == 3 -} - -// IsClientError returns true when this get jobs ID definition default response has a 4xx status code -func (o *GetJobsIDDefinitionDefault) IsClientError() bool { - return o._statusCode/100 == 4 -} - -// IsServerError returns true when this get jobs ID definition default response has a 5xx status code -func (o *GetJobsIDDefinitionDefault) IsServerError() bool { - return o._statusCode/100 == 5 -} - -// IsCode returns true when this get jobs ID definition default response a status code equal to that given -func (o *GetJobsIDDefinitionDefault) IsCode(code int) bool { - return o._statusCode == code -} - -// Code gets the status code for the get jobs ID definition default response -func (o *GetJobsIDDefinitionDefault) Code() int { - return o._statusCode -} - -func (o *GetJobsIDDefinitionDefault) Error() string { - return fmt.Sprintf("[GET /jobs/{id}/definition][%d] GetJobsIDDefinition default", o._statusCode) -} - -func (o *GetJobsIDDefinitionDefault) String() string { - return fmt.Sprintf("[GET /jobs/{id}/definition][%d] GetJobsIDDefinition default", o._statusCode) -} - -func (o *GetJobsIDDefinitionDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - return nil -} diff --git a/generated/client/jobs/get_jobs_id_parameters.go b/generated/client/jobs/get_jobs_id_parameters.go deleted file mode 100644 index 735d6d9a..00000000 --- a/generated/client/jobs/get_jobs_id_parameters.go +++ /dev/null @@ -1,191 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "net/http" - "time" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// NewGetJobsIDParams creates a new GetJobsIDParams object, -// with the default timeout for this client. -// -// Default values are not hydrated, since defaults are normally applied by the API server side. -// -// To enforce default values in parameter, use SetDefaults or WithDefaults. -func NewGetJobsIDParams() *GetJobsIDParams { - return &GetJobsIDParams{ - timeout: cr.DefaultTimeout, - } -} - -// NewGetJobsIDParamsWithTimeout creates a new GetJobsIDParams object -// with the ability to set a timeout on a request. -func NewGetJobsIDParamsWithTimeout(timeout time.Duration) *GetJobsIDParams { - return &GetJobsIDParams{ - timeout: timeout, - } -} - -// NewGetJobsIDParamsWithContext creates a new GetJobsIDParams object -// with the ability to set a context for a request. -func NewGetJobsIDParamsWithContext(ctx context.Context) *GetJobsIDParams { - return &GetJobsIDParams{ - Context: ctx, - } -} - -// NewGetJobsIDParamsWithHTTPClient creates a new GetJobsIDParams object -// with the ability to set a custom HTTPClient for a request. -func NewGetJobsIDParamsWithHTTPClient(client *http.Client) *GetJobsIDParams { - return &GetJobsIDParams{ - HTTPClient: client, - } -} - -/* -GetJobsIDParams contains all the parameters to send to the API endpoint - - for the get jobs ID operation. - - Typically these are written to a http.Request. -*/ -type GetJobsIDParams struct { - - /* History. - - Boolean flag to include the transition history of the job - */ - History *bool - - /* ID. - - Job ID - */ - ID string - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithDefaults hydrates default values in the get jobs ID params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *GetJobsIDParams) WithDefaults() *GetJobsIDParams { - o.SetDefaults() - return o -} - -// SetDefaults hydrates default values in the get jobs ID params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *GetJobsIDParams) SetDefaults() { - // no default values defined for this parameter -} - -// WithTimeout adds the timeout to the get jobs ID params -func (o *GetJobsIDParams) WithTimeout(timeout time.Duration) *GetJobsIDParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the get jobs ID params -func (o *GetJobsIDParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the get jobs ID params -func (o *GetJobsIDParams) WithContext(ctx context.Context) *GetJobsIDParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the get jobs ID params -func (o *GetJobsIDParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the get jobs ID params -func (o *GetJobsIDParams) WithHTTPClient(client *http.Client) *GetJobsIDParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the get jobs ID params -func (o *GetJobsIDParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithHistory adds the history to the get jobs ID params -func (o *GetJobsIDParams) WithHistory(history *bool) *GetJobsIDParams { - o.SetHistory(history) - return o -} - -// SetHistory adds the history to the get jobs ID params -func (o *GetJobsIDParams) SetHistory(history *bool) { - o.History = history -} - -// WithID adds the id to the get jobs ID params -func (o *GetJobsIDParams) WithID(id string) *GetJobsIDParams { - o.SetID(id) - return o -} - -// SetID adds the id to the get jobs ID params -func (o *GetJobsIDParams) SetID(id string) { - o.ID = id -} - -// WriteToRequest writes these params to a swagger request -func (o *GetJobsIDParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - if o.History != nil { - - // query param history - var qrHistory bool - - if o.History != nil { - qrHistory = *o.History - } - qHistory := swag.FormatBool(qrHistory) - if qHistory != "" { - - if err := r.SetQueryParam("history", qHistory); err != nil { - return err - } - } - } - - // path param id - if err := r.SetPathParam("id", o.ID); err != nil { - return err - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/generated/client/jobs/get_jobs_id_responses.go b/generated/client/jobs/get_jobs_id_responses.go deleted file mode 100644 index b41c603e..00000000 --- a/generated/client/jobs/get_jobs_id_responses.go +++ /dev/null @@ -1,328 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "encoding/json" - "fmt" - "io" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" -) - -// GetJobsIDReader is a Reader for the GetJobsID structure. -type GetJobsIDReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *GetJobsIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - case 200: - result := NewGetJobsIDOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - case 400: - result := NewGetJobsIDBadRequest() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - case 404: - result := NewGetJobsIDNotFound() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - default: - result := NewGetJobsIDDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewGetJobsIDOK creates a GetJobsIDOK with default headers values -func NewGetJobsIDOK() *GetJobsIDOK { - return &GetJobsIDOK{} -} - -/* -GetJobsIDOK describes a response with status code 200, with default header values. - -Job description for for a given ID -*/ -type GetJobsIDOK struct { - Payload *model.Job -} - -// IsSuccess returns true when this get jobs Id o k response has a 2xx status code -func (o *GetJobsIDOK) IsSuccess() bool { - return true -} - -// IsRedirect returns true when this get jobs Id o k response has a 3xx status code -func (o *GetJobsIDOK) IsRedirect() bool { - return false -} - -// IsClientError returns true when this get jobs Id o k response has a 4xx status code -func (o *GetJobsIDOK) IsClientError() bool { - return false -} - -// IsServerError returns true when this get jobs Id o k response has a 5xx status code -func (o *GetJobsIDOK) IsServerError() bool { - return false -} - -// IsCode returns true when this get jobs Id o k response a status code equal to that given -func (o *GetJobsIDOK) IsCode(code int) bool { - return code == 200 -} - -// Code gets the status code for the get jobs Id o k response -func (o *GetJobsIDOK) Code() int { - return 200 -} - -func (o *GetJobsIDOK) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs/{id}][%d] getJobsIdOK %s", 200, payload) -} - -func (o *GetJobsIDOK) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs/{id}][%d] getJobsIdOK %s", 200, payload) -} - -func (o *GetJobsIDOK) GetPayload() *model.Job { - return o.Payload -} - -func (o *GetJobsIDOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.Job) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetJobsIDBadRequest creates a GetJobsIDBadRequest with default headers values -func NewGetJobsIDBadRequest() *GetJobsIDBadRequest { - return &GetJobsIDBadRequest{} -} - -/* -GetJobsIDBadRequest describes a response with status code 400, with default header values. - -Bad Request -*/ -type GetJobsIDBadRequest struct { - Payload *model.ErrorResponse -} - -// IsSuccess returns true when this get jobs Id bad request response has a 2xx status code -func (o *GetJobsIDBadRequest) IsSuccess() bool { - return false -} - -// IsRedirect returns true when this get jobs Id bad request response has a 3xx status code -func (o *GetJobsIDBadRequest) IsRedirect() bool { - return false -} - -// IsClientError returns true when this get jobs Id bad request response has a 4xx status code -func (o *GetJobsIDBadRequest) IsClientError() bool { - return true -} - -// IsServerError returns true when this get jobs Id bad request response has a 5xx status code -func (o *GetJobsIDBadRequest) IsServerError() bool { - return false -} - -// IsCode returns true when this get jobs Id bad request response a status code equal to that given -func (o *GetJobsIDBadRequest) IsCode(code int) bool { - return code == 400 -} - -// Code gets the status code for the get jobs Id bad request response -func (o *GetJobsIDBadRequest) Code() int { - return 400 -} - -func (o *GetJobsIDBadRequest) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs/{id}][%d] getJobsIdBadRequest %s", 400, payload) -} - -func (o *GetJobsIDBadRequest) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs/{id}][%d] getJobsIdBadRequest %s", 400, payload) -} - -func (o *GetJobsIDBadRequest) GetPayload() *model.ErrorResponse { - return o.Payload -} - -func (o *GetJobsIDBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.ErrorResponse) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetJobsIDNotFound creates a GetJobsIDNotFound with default headers values -func NewGetJobsIDNotFound() *GetJobsIDNotFound { - return &GetJobsIDNotFound{} -} - -/* -GetJobsIDNotFound describes a response with status code 404, with default header values. - -Not Found -*/ -type GetJobsIDNotFound struct { - Payload *model.ErrorResponse -} - -// IsSuccess returns true when this get jobs Id not found response has a 2xx status code -func (o *GetJobsIDNotFound) IsSuccess() bool { - return false -} - -// IsRedirect returns true when this get jobs Id not found response has a 3xx status code -func (o *GetJobsIDNotFound) IsRedirect() bool { - return false -} - -// IsClientError returns true when this get jobs Id not found response has a 4xx status code -func (o *GetJobsIDNotFound) IsClientError() bool { - return true -} - -// IsServerError returns true when this get jobs Id not found response has a 5xx status code -func (o *GetJobsIDNotFound) IsServerError() bool { - return false -} - -// IsCode returns true when this get jobs Id not found response a status code equal to that given -func (o *GetJobsIDNotFound) IsCode(code int) bool { - return code == 404 -} - -// Code gets the status code for the get jobs Id not found response -func (o *GetJobsIDNotFound) Code() int { - return 404 -} - -func (o *GetJobsIDNotFound) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs/{id}][%d] getJobsIdNotFound %s", 404, payload) -} - -func (o *GetJobsIDNotFound) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs/{id}][%d] getJobsIdNotFound %s", 404, payload) -} - -func (o *GetJobsIDNotFound) GetPayload() *model.ErrorResponse { - return o.Payload -} - -func (o *GetJobsIDNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.ErrorResponse) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetJobsIDDefault creates a GetJobsIDDefault with default headers values -func NewGetJobsIDDefault(code int) *GetJobsIDDefault { - return &GetJobsIDDefault{ - _statusCode: code, - } -} - -/* -GetJobsIDDefault describes a response with status code -1, with default header values. - -Other error with any status code and response body format. -*/ -type GetJobsIDDefault struct { - _statusCode int -} - -// IsSuccess returns true when this get jobs ID default response has a 2xx status code -func (o *GetJobsIDDefault) IsSuccess() bool { - return o._statusCode/100 == 2 -} - -// IsRedirect returns true when this get jobs ID default response has a 3xx status code -func (o *GetJobsIDDefault) IsRedirect() bool { - return o._statusCode/100 == 3 -} - -// IsClientError returns true when this get jobs ID default response has a 4xx status code -func (o *GetJobsIDDefault) IsClientError() bool { - return o._statusCode/100 == 4 -} - -// IsServerError returns true when this get jobs ID default response has a 5xx status code -func (o *GetJobsIDDefault) IsServerError() bool { - return o._statusCode/100 == 5 -} - -// IsCode returns true when this get jobs ID default response a status code equal to that given -func (o *GetJobsIDDefault) IsCode(code int) bool { - return o._statusCode == code -} - -// Code gets the status code for the get jobs ID default response -func (o *GetJobsIDDefault) Code() int { - return o._statusCode -} - -func (o *GetJobsIDDefault) Error() string { - return fmt.Sprintf("[GET /jobs/{id}][%d] GetJobsID default", o._statusCode) -} - -func (o *GetJobsIDDefault) String() string { - return fmt.Sprintf("[GET /jobs/{id}][%d] GetJobsID default", o._statusCode) -} - -func (o *GetJobsIDDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - return nil -} diff --git a/generated/client/jobs/get_jobs_id_status_parameters.go b/generated/client/jobs/get_jobs_id_status_parameters.go deleted file mode 100644 index 17ea8059..00000000 --- a/generated/client/jobs/get_jobs_id_status_parameters.go +++ /dev/null @@ -1,156 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "net/http" - "time" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - "github.com/go-openapi/strfmt" -) - -// NewGetJobsIDStatusParams creates a new GetJobsIDStatusParams object, -// with the default timeout for this client. -// -// Default values are not hydrated, since defaults are normally applied by the API server side. -// -// To enforce default values in parameter, use SetDefaults or WithDefaults. -func NewGetJobsIDStatusParams() *GetJobsIDStatusParams { - return &GetJobsIDStatusParams{ - timeout: cr.DefaultTimeout, - } -} - -// NewGetJobsIDStatusParamsWithTimeout creates a new GetJobsIDStatusParams object -// with the ability to set a timeout on a request. -func NewGetJobsIDStatusParamsWithTimeout(timeout time.Duration) *GetJobsIDStatusParams { - return &GetJobsIDStatusParams{ - timeout: timeout, - } -} - -// NewGetJobsIDStatusParamsWithContext creates a new GetJobsIDStatusParams object -// with the ability to set a context for a request. -func NewGetJobsIDStatusParamsWithContext(ctx context.Context) *GetJobsIDStatusParams { - return &GetJobsIDStatusParams{ - Context: ctx, - } -} - -// NewGetJobsIDStatusParamsWithHTTPClient creates a new GetJobsIDStatusParams object -// with the ability to set a custom HTTPClient for a request. -func NewGetJobsIDStatusParamsWithHTTPClient(client *http.Client) *GetJobsIDStatusParams { - return &GetJobsIDStatusParams{ - HTTPClient: client, - } -} - -/* -GetJobsIDStatusParams contains all the parameters to send to the API endpoint - - for the get jobs ID status operation. - - Typically these are written to a http.Request. -*/ -type GetJobsIDStatusParams struct { - - /* ID. - - Job ID - */ - ID string - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithDefaults hydrates default values in the get jobs ID status params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *GetJobsIDStatusParams) WithDefaults() *GetJobsIDStatusParams { - o.SetDefaults() - return o -} - -// SetDefaults hydrates default values in the get jobs ID status params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *GetJobsIDStatusParams) SetDefaults() { - // no default values defined for this parameter -} - -// WithTimeout adds the timeout to the get jobs ID status params -func (o *GetJobsIDStatusParams) WithTimeout(timeout time.Duration) *GetJobsIDStatusParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the get jobs ID status params -func (o *GetJobsIDStatusParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the get jobs ID status params -func (o *GetJobsIDStatusParams) WithContext(ctx context.Context) *GetJobsIDStatusParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the get jobs ID status params -func (o *GetJobsIDStatusParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the get jobs ID status params -func (o *GetJobsIDStatusParams) WithHTTPClient(client *http.Client) *GetJobsIDStatusParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the get jobs ID status params -func (o *GetJobsIDStatusParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithID adds the id to the get jobs ID status params -func (o *GetJobsIDStatusParams) WithID(id string) *GetJobsIDStatusParams { - o.SetID(id) - return o -} - -// SetID adds the id to the get jobs ID status params -func (o *GetJobsIDStatusParams) SetID(id string) { - o.ID = id -} - -// WriteToRequest writes these params to a swagger request -func (o *GetJobsIDStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - // path param id - if err := r.SetPathParam("id", o.ID); err != nil { - return err - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/generated/client/jobs/get_jobs_id_status_responses.go b/generated/client/jobs/get_jobs_id_status_responses.go deleted file mode 100644 index e1253b88..00000000 --- a/generated/client/jobs/get_jobs_id_status_responses.go +++ /dev/null @@ -1,252 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "encoding/json" - "fmt" - "io" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" -) - -// GetJobsIDStatusReader is a Reader for the GetJobsIDStatus structure. -type GetJobsIDStatusReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *GetJobsIDStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - case 200: - result := NewGetJobsIDStatusOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - case 404: - result := NewGetJobsIDStatusNotFound() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - default: - result := NewGetJobsIDStatusDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewGetJobsIDStatusOK creates a GetJobsIDStatusOK with default headers values -func NewGetJobsIDStatusOK() *GetJobsIDStatusOK { - return &GetJobsIDStatusOK{} -} - -/* -GetJobsIDStatusOK describes a response with status code 200, with default header values. - -Job status -*/ -type GetJobsIDStatusOK struct { - Payload *model.JobStatus -} - -// IsSuccess returns true when this get jobs Id status o k response has a 2xx status code -func (o *GetJobsIDStatusOK) IsSuccess() bool { - return true -} - -// IsRedirect returns true when this get jobs Id status o k response has a 3xx status code -func (o *GetJobsIDStatusOK) IsRedirect() bool { - return false -} - -// IsClientError returns true when this get jobs Id status o k response has a 4xx status code -func (o *GetJobsIDStatusOK) IsClientError() bool { - return false -} - -// IsServerError returns true when this get jobs Id status o k response has a 5xx status code -func (o *GetJobsIDStatusOK) IsServerError() bool { - return false -} - -// IsCode returns true when this get jobs Id status o k response a status code equal to that given -func (o *GetJobsIDStatusOK) IsCode(code int) bool { - return code == 200 -} - -// Code gets the status code for the get jobs Id status o k response -func (o *GetJobsIDStatusOK) Code() int { - return 200 -} - -func (o *GetJobsIDStatusOK) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs/{id}/status][%d] getJobsIdStatusOK %s", 200, payload) -} - -func (o *GetJobsIDStatusOK) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs/{id}/status][%d] getJobsIdStatusOK %s", 200, payload) -} - -func (o *GetJobsIDStatusOK) GetPayload() *model.JobStatus { - return o.Payload -} - -func (o *GetJobsIDStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.JobStatus) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetJobsIDStatusNotFound creates a GetJobsIDStatusNotFound with default headers values -func NewGetJobsIDStatusNotFound() *GetJobsIDStatusNotFound { - return &GetJobsIDStatusNotFound{} -} - -/* -GetJobsIDStatusNotFound describes a response with status code 404, with default header values. - -Not Found -*/ -type GetJobsIDStatusNotFound struct { - Payload *model.ErrorResponse -} - -// IsSuccess returns true when this get jobs Id status not found response has a 2xx status code -func (o *GetJobsIDStatusNotFound) IsSuccess() bool { - return false -} - -// IsRedirect returns true when this get jobs Id status not found response has a 3xx status code -func (o *GetJobsIDStatusNotFound) IsRedirect() bool { - return false -} - -// IsClientError returns true when this get jobs Id status not found response has a 4xx status code -func (o *GetJobsIDStatusNotFound) IsClientError() bool { - return true -} - -// IsServerError returns true when this get jobs Id status not found response has a 5xx status code -func (o *GetJobsIDStatusNotFound) IsServerError() bool { - return false -} - -// IsCode returns true when this get jobs Id status not found response a status code equal to that given -func (o *GetJobsIDStatusNotFound) IsCode(code int) bool { - return code == 404 -} - -// Code gets the status code for the get jobs Id status not found response -func (o *GetJobsIDStatusNotFound) Code() int { - return 404 -} - -func (o *GetJobsIDStatusNotFound) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs/{id}/status][%d] getJobsIdStatusNotFound %s", 404, payload) -} - -func (o *GetJobsIDStatusNotFound) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs/{id}/status][%d] getJobsIdStatusNotFound %s", 404, payload) -} - -func (o *GetJobsIDStatusNotFound) GetPayload() *model.ErrorResponse { - return o.Payload -} - -func (o *GetJobsIDStatusNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.ErrorResponse) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetJobsIDStatusDefault creates a GetJobsIDStatusDefault with default headers values -func NewGetJobsIDStatusDefault(code int) *GetJobsIDStatusDefault { - return &GetJobsIDStatusDefault{ - _statusCode: code, - } -} - -/* -GetJobsIDStatusDefault describes a response with status code -1, with default header values. - -Other error with any status code and response body format. -*/ -type GetJobsIDStatusDefault struct { - _statusCode int -} - -// IsSuccess returns true when this get jobs ID status default response has a 2xx status code -func (o *GetJobsIDStatusDefault) IsSuccess() bool { - return o._statusCode/100 == 2 -} - -// IsRedirect returns true when this get jobs ID status default response has a 3xx status code -func (o *GetJobsIDStatusDefault) IsRedirect() bool { - return o._statusCode/100 == 3 -} - -// IsClientError returns true when this get jobs ID status default response has a 4xx status code -func (o *GetJobsIDStatusDefault) IsClientError() bool { - return o._statusCode/100 == 4 -} - -// IsServerError returns true when this get jobs ID status default response has a 5xx status code -func (o *GetJobsIDStatusDefault) IsServerError() bool { - return o._statusCode/100 == 5 -} - -// IsCode returns true when this get jobs ID status default response a status code equal to that given -func (o *GetJobsIDStatusDefault) IsCode(code int) bool { - return o._statusCode == code -} - -// Code gets the status code for the get jobs ID status default response -func (o *GetJobsIDStatusDefault) Code() int { - return o._statusCode -} - -func (o *GetJobsIDStatusDefault) Error() string { - return fmt.Sprintf("[GET /jobs/{id}/status][%d] GetJobsIDStatus default", o._statusCode) -} - -func (o *GetJobsIDStatusDefault) String() string { - return fmt.Sprintf("[GET /jobs/{id}/status][%d] GetJobsIDStatus default", o._statusCode) -} - -func (o *GetJobsIDStatusDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - return nil -} diff --git a/generated/client/jobs/get_jobs_id_tags_parameters.go b/generated/client/jobs/get_jobs_id_tags_parameters.go deleted file mode 100644 index b5c5feb9..00000000 --- a/generated/client/jobs/get_jobs_id_tags_parameters.go +++ /dev/null @@ -1,156 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "net/http" - "time" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - "github.com/go-openapi/strfmt" -) - -// NewGetJobsIDTagsParams creates a new GetJobsIDTagsParams object, -// with the default timeout for this client. -// -// Default values are not hydrated, since defaults are normally applied by the API server side. -// -// To enforce default values in parameter, use SetDefaults or WithDefaults. -func NewGetJobsIDTagsParams() *GetJobsIDTagsParams { - return &GetJobsIDTagsParams{ - timeout: cr.DefaultTimeout, - } -} - -// NewGetJobsIDTagsParamsWithTimeout creates a new GetJobsIDTagsParams object -// with the ability to set a timeout on a request. -func NewGetJobsIDTagsParamsWithTimeout(timeout time.Duration) *GetJobsIDTagsParams { - return &GetJobsIDTagsParams{ - timeout: timeout, - } -} - -// NewGetJobsIDTagsParamsWithContext creates a new GetJobsIDTagsParams object -// with the ability to set a context for a request. -func NewGetJobsIDTagsParamsWithContext(ctx context.Context) *GetJobsIDTagsParams { - return &GetJobsIDTagsParams{ - Context: ctx, - } -} - -// NewGetJobsIDTagsParamsWithHTTPClient creates a new GetJobsIDTagsParams object -// with the ability to set a custom HTTPClient for a request. -func NewGetJobsIDTagsParamsWithHTTPClient(client *http.Client) *GetJobsIDTagsParams { - return &GetJobsIDTagsParams{ - HTTPClient: client, - } -} - -/* -GetJobsIDTagsParams contains all the parameters to send to the API endpoint - - for the get jobs ID tags operation. - - Typically these are written to a http.Request. -*/ -type GetJobsIDTagsParams struct { - - /* ID. - - Job ID - */ - ID string - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithDefaults hydrates default values in the get jobs ID tags params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *GetJobsIDTagsParams) WithDefaults() *GetJobsIDTagsParams { - o.SetDefaults() - return o -} - -// SetDefaults hydrates default values in the get jobs ID tags params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *GetJobsIDTagsParams) SetDefaults() { - // no default values defined for this parameter -} - -// WithTimeout adds the timeout to the get jobs ID tags params -func (o *GetJobsIDTagsParams) WithTimeout(timeout time.Duration) *GetJobsIDTagsParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the get jobs ID tags params -func (o *GetJobsIDTagsParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the get jobs ID tags params -func (o *GetJobsIDTagsParams) WithContext(ctx context.Context) *GetJobsIDTagsParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the get jobs ID tags params -func (o *GetJobsIDTagsParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the get jobs ID tags params -func (o *GetJobsIDTagsParams) WithHTTPClient(client *http.Client) *GetJobsIDTagsParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the get jobs ID tags params -func (o *GetJobsIDTagsParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithID adds the id to the get jobs ID tags params -func (o *GetJobsIDTagsParams) WithID(id string) *GetJobsIDTagsParams { - o.SetID(id) - return o -} - -// SetID adds the id to the get jobs ID tags params -func (o *GetJobsIDTagsParams) SetID(id string) { - o.ID = id -} - -// WriteToRequest writes these params to a swagger request -func (o *GetJobsIDTagsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - // path param id - if err := r.SetPathParam("id", o.ID); err != nil { - return err - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/generated/client/jobs/get_jobs_id_tags_responses.go b/generated/client/jobs/get_jobs_id_tags_responses.go deleted file mode 100644 index 29386e9a..00000000 --- a/generated/client/jobs/get_jobs_id_tags_responses.go +++ /dev/null @@ -1,250 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "encoding/json" - "fmt" - "io" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" -) - -// GetJobsIDTagsReader is a Reader for the GetJobsIDTags structure. -type GetJobsIDTagsReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *GetJobsIDTagsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - case 200: - result := NewGetJobsIDTagsOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - case 404: - result := NewGetJobsIDTagsNotFound() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - default: - result := NewGetJobsIDTagsDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewGetJobsIDTagsOK creates a GetJobsIDTagsOK with default headers values -func NewGetJobsIDTagsOK() *GetJobsIDTagsOK { - return &GetJobsIDTagsOK{} -} - -/* -GetJobsIDTagsOK describes a response with status code 200, with default header values. - -Job tags -*/ -type GetJobsIDTagsOK struct { - Payload []string -} - -// IsSuccess returns true when this get jobs Id tags o k response has a 2xx status code -func (o *GetJobsIDTagsOK) IsSuccess() bool { - return true -} - -// IsRedirect returns true when this get jobs Id tags o k response has a 3xx status code -func (o *GetJobsIDTagsOK) IsRedirect() bool { - return false -} - -// IsClientError returns true when this get jobs Id tags o k response has a 4xx status code -func (o *GetJobsIDTagsOK) IsClientError() bool { - return false -} - -// IsServerError returns true when this get jobs Id tags o k response has a 5xx status code -func (o *GetJobsIDTagsOK) IsServerError() bool { - return false -} - -// IsCode returns true when this get jobs Id tags o k response a status code equal to that given -func (o *GetJobsIDTagsOK) IsCode(code int) bool { - return code == 200 -} - -// Code gets the status code for the get jobs Id tags o k response -func (o *GetJobsIDTagsOK) Code() int { - return 200 -} - -func (o *GetJobsIDTagsOK) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs/{id}/tags][%d] getJobsIdTagsOK %s", 200, payload) -} - -func (o *GetJobsIDTagsOK) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs/{id}/tags][%d] getJobsIdTagsOK %s", 200, payload) -} - -func (o *GetJobsIDTagsOK) GetPayload() []string { - return o.Payload -} - -func (o *GetJobsIDTagsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - // response payload - if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetJobsIDTagsNotFound creates a GetJobsIDTagsNotFound with default headers values -func NewGetJobsIDTagsNotFound() *GetJobsIDTagsNotFound { - return &GetJobsIDTagsNotFound{} -} - -/* -GetJobsIDTagsNotFound describes a response with status code 404, with default header values. - -Not Found -*/ -type GetJobsIDTagsNotFound struct { - Payload *model.ErrorResponse -} - -// IsSuccess returns true when this get jobs Id tags not found response has a 2xx status code -func (o *GetJobsIDTagsNotFound) IsSuccess() bool { - return false -} - -// IsRedirect returns true when this get jobs Id tags not found response has a 3xx status code -func (o *GetJobsIDTagsNotFound) IsRedirect() bool { - return false -} - -// IsClientError returns true when this get jobs Id tags not found response has a 4xx status code -func (o *GetJobsIDTagsNotFound) IsClientError() bool { - return true -} - -// IsServerError returns true when this get jobs Id tags not found response has a 5xx status code -func (o *GetJobsIDTagsNotFound) IsServerError() bool { - return false -} - -// IsCode returns true when this get jobs Id tags not found response a status code equal to that given -func (o *GetJobsIDTagsNotFound) IsCode(code int) bool { - return code == 404 -} - -// Code gets the status code for the get jobs Id tags not found response -func (o *GetJobsIDTagsNotFound) Code() int { - return 404 -} - -func (o *GetJobsIDTagsNotFound) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs/{id}/tags][%d] getJobsIdTagsNotFound %s", 404, payload) -} - -func (o *GetJobsIDTagsNotFound) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs/{id}/tags][%d] getJobsIdTagsNotFound %s", 404, payload) -} - -func (o *GetJobsIDTagsNotFound) GetPayload() *model.ErrorResponse { - return o.Payload -} - -func (o *GetJobsIDTagsNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.ErrorResponse) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetJobsIDTagsDefault creates a GetJobsIDTagsDefault with default headers values -func NewGetJobsIDTagsDefault(code int) *GetJobsIDTagsDefault { - return &GetJobsIDTagsDefault{ - _statusCode: code, - } -} - -/* -GetJobsIDTagsDefault describes a response with status code -1, with default header values. - -Other error with any status code and response body format. -*/ -type GetJobsIDTagsDefault struct { - _statusCode int -} - -// IsSuccess returns true when this get jobs ID tags default response has a 2xx status code -func (o *GetJobsIDTagsDefault) IsSuccess() bool { - return o._statusCode/100 == 2 -} - -// IsRedirect returns true when this get jobs ID tags default response has a 3xx status code -func (o *GetJobsIDTagsDefault) IsRedirect() bool { - return o._statusCode/100 == 3 -} - -// IsClientError returns true when this get jobs ID tags default response has a 4xx status code -func (o *GetJobsIDTagsDefault) IsClientError() bool { - return o._statusCode/100 == 4 -} - -// IsServerError returns true when this get jobs ID tags default response has a 5xx status code -func (o *GetJobsIDTagsDefault) IsServerError() bool { - return o._statusCode/100 == 5 -} - -// IsCode returns true when this get jobs ID tags default response a status code equal to that given -func (o *GetJobsIDTagsDefault) IsCode(code int) bool { - return o._statusCode == code -} - -// Code gets the status code for the get jobs ID tags default response -func (o *GetJobsIDTagsDefault) Code() int { - return o._statusCode -} - -func (o *GetJobsIDTagsDefault) Error() string { - return fmt.Sprintf("[GET /jobs/{id}/tags][%d] GetJobsIDTags default", o._statusCode) -} - -func (o *GetJobsIDTagsDefault) String() string { - return fmt.Sprintf("[GET /jobs/{id}/tags][%d] GetJobsIDTags default", o._statusCode) -} - -func (o *GetJobsIDTagsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - return nil -} diff --git a/generated/client/jobs/get_jobs_parameters.go b/generated/client/jobs/get_jobs_parameters.go deleted file mode 100644 index d559cd5a..00000000 --- a/generated/client/jobs/get_jobs_parameters.go +++ /dev/null @@ -1,453 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "net/http" - "time" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// NewGetJobsParams creates a new GetJobsParams object, -// with the default timeout for this client. -// -// Default values are not hydrated, since defaults are normally applied by the API server side. -// -// To enforce default values in parameter, use SetDefaults or WithDefaults. -func NewGetJobsParams() *GetJobsParams { - return &GetJobsParams{ - timeout: cr.DefaultTimeout, - } -} - -// NewGetJobsParamsWithTimeout creates a new GetJobsParams object -// with the ability to set a timeout on a request. -func NewGetJobsParamsWithTimeout(timeout time.Duration) *GetJobsParams { - return &GetJobsParams{ - timeout: timeout, - } -} - -// NewGetJobsParamsWithContext creates a new GetJobsParams object -// with the ability to set a context for a request. -func NewGetJobsParamsWithContext(ctx context.Context) *GetJobsParams { - return &GetJobsParams{ - Context: ctx, - } -} - -// NewGetJobsParamsWithHTTPClient creates a new GetJobsParams object -// with the ability to set a custom HTTPClient for a request. -func NewGetJobsParamsWithHTTPClient(client *http.Client) *GetJobsParams { - return &GetJobsParams{ - HTTPClient: client, - } -} - -/* -GetJobsParams contains all the parameters to send to the API endpoint - - for the get jobs operation. - - Typically these are written to a http.Request. -*/ -type GetJobsParams struct { - - /* ClientID. - - Filter jobs belonging to a specific client with clientId - */ - ClientID *string - - /* Group. - - Filter jobs based on the group they are in - */ - Group []string - - /* Limit. - - the maximum number of items to return - - Format: int32 - Default: 10 - */ - Limit *int32 - - /* Offset. - - the number of items to skip before starting to return results - - Format: int64 - */ - Offset *int64 - - /* Sort. - - the order of returned elements - - Default: "asc" - */ - Sort *string - - /* State. - - Filter jobs based on the current state value - */ - State *string - - /* Tag. - - Filter jobs by tags - */ - Tag []string - - /* Workflow. - - Filter jobs matching by workflow - */ - Workflow *string - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithDefaults hydrates default values in the get jobs params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *GetJobsParams) WithDefaults() *GetJobsParams { - o.SetDefaults() - return o -} - -// SetDefaults hydrates default values in the get jobs params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *GetJobsParams) SetDefaults() { - var ( - limitDefault = int32(10) - - offsetDefault = int64(0) - - sortDefault = string("asc") - ) - - val := GetJobsParams{ - Limit: &limitDefault, - Offset: &offsetDefault, - Sort: &sortDefault, - } - - val.timeout = o.timeout - val.Context = o.Context - val.HTTPClient = o.HTTPClient - *o = val -} - -// WithTimeout adds the timeout to the get jobs params -func (o *GetJobsParams) WithTimeout(timeout time.Duration) *GetJobsParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the get jobs params -func (o *GetJobsParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the get jobs params -func (o *GetJobsParams) WithContext(ctx context.Context) *GetJobsParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the get jobs params -func (o *GetJobsParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the get jobs params -func (o *GetJobsParams) WithHTTPClient(client *http.Client) *GetJobsParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the get jobs params -func (o *GetJobsParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithClientID adds the clientID to the get jobs params -func (o *GetJobsParams) WithClientID(clientID *string) *GetJobsParams { - o.SetClientID(clientID) - return o -} - -// SetClientID adds the clientId to the get jobs params -func (o *GetJobsParams) SetClientID(clientID *string) { - o.ClientID = clientID -} - -// WithGroup adds the group to the get jobs params -func (o *GetJobsParams) WithGroup(group []string) *GetJobsParams { - o.SetGroup(group) - return o -} - -// SetGroup adds the group to the get jobs params -func (o *GetJobsParams) SetGroup(group []string) { - o.Group = group -} - -// WithLimit adds the limit to the get jobs params -func (o *GetJobsParams) WithLimit(limit *int32) *GetJobsParams { - o.SetLimit(limit) - return o -} - -// SetLimit adds the limit to the get jobs params -func (o *GetJobsParams) SetLimit(limit *int32) { - o.Limit = limit -} - -// WithOffset adds the offset to the get jobs params -func (o *GetJobsParams) WithOffset(offset *int64) *GetJobsParams { - o.SetOffset(offset) - return o -} - -// SetOffset adds the offset to the get jobs params -func (o *GetJobsParams) SetOffset(offset *int64) { - o.Offset = offset -} - -// WithSort adds the sort to the get jobs params -func (o *GetJobsParams) WithSort(sort *string) *GetJobsParams { - o.SetSort(sort) - return o -} - -// SetSort adds the sort to the get jobs params -func (o *GetJobsParams) SetSort(sort *string) { - o.Sort = sort -} - -// WithState adds the state to the get jobs params -func (o *GetJobsParams) WithState(state *string) *GetJobsParams { - o.SetState(state) - return o -} - -// SetState adds the state to the get jobs params -func (o *GetJobsParams) SetState(state *string) { - o.State = state -} - -// WithTag adds the tag to the get jobs params -func (o *GetJobsParams) WithTag(tag []string) *GetJobsParams { - o.SetTag(tag) - return o -} - -// SetTag adds the tag to the get jobs params -func (o *GetJobsParams) SetTag(tag []string) { - o.Tag = tag -} - -// WithWorkflow adds the workflow to the get jobs params -func (o *GetJobsParams) WithWorkflow(workflow *string) *GetJobsParams { - o.SetWorkflow(workflow) - return o -} - -// SetWorkflow adds the workflow to the get jobs params -func (o *GetJobsParams) SetWorkflow(workflow *string) { - o.Workflow = workflow -} - -// WriteToRequest writes these params to a swagger request -func (o *GetJobsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - if o.ClientID != nil { - - // query param clientId - var qrClientID string - - if o.ClientID != nil { - qrClientID = *o.ClientID - } - qClientID := qrClientID - if qClientID != "" { - - if err := r.SetQueryParam("clientId", qClientID); err != nil { - return err - } - } - } - - if o.Group != nil { - - // binding items for group - joinedGroup := o.bindParamGroup(reg) - - // query array param group - if err := r.SetQueryParam("group", joinedGroup...); err != nil { - return err - } - } - - if o.Limit != nil { - - // query param limit - var qrLimit int32 - - if o.Limit != nil { - qrLimit = *o.Limit - } - qLimit := swag.FormatInt32(qrLimit) - if qLimit != "" { - - if err := r.SetQueryParam("limit", qLimit); err != nil { - return err - } - } - } - - if o.Offset != nil { - - // query param offset - var qrOffset int64 - - if o.Offset != nil { - qrOffset = *o.Offset - } - qOffset := swag.FormatInt64(qrOffset) - if qOffset != "" { - - if err := r.SetQueryParam("offset", qOffset); err != nil { - return err - } - } - } - - if o.Sort != nil { - - // query param sort - var qrSort string - - if o.Sort != nil { - qrSort = *o.Sort - } - qSort := qrSort - if qSort != "" { - - if err := r.SetQueryParam("sort", qSort); err != nil { - return err - } - } - } - - if o.State != nil { - - // query param state - var qrState string - - if o.State != nil { - qrState = *o.State - } - qState := qrState - if qState != "" { - - if err := r.SetQueryParam("state", qState); err != nil { - return err - } - } - } - - if o.Tag != nil { - - // binding items for tag - joinedTag := o.bindParamTag(reg) - - // query array param tag - if err := r.SetQueryParam("tag", joinedTag...); err != nil { - return err - } - } - - if o.Workflow != nil { - - // query param workflow - var qrWorkflow string - - if o.Workflow != nil { - qrWorkflow = *o.Workflow - } - qWorkflow := qrWorkflow - if qWorkflow != "" { - - if err := r.SetQueryParam("workflow", qWorkflow); err != nil { - return err - } - } - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindParamGetJobs binds the parameter group -func (o *GetJobsParams) bindParamGroup(formats strfmt.Registry) []string { - groupIR := o.Group - - var groupIC []string - for _, groupIIR := range groupIR { // explode []string - - groupIIV := groupIIR // string as string - groupIC = append(groupIC, groupIIV) - } - - // items.CollectionFormat: "" - groupIS := swag.JoinByFormat(groupIC, "") - - return groupIS -} - -// bindParamGetJobs binds the parameter tag -func (o *GetJobsParams) bindParamTag(formats strfmt.Registry) []string { - tagIR := o.Tag - - var tagIC []string - for _, tagIIR := range tagIR { // explode []string - - tagIIV := tagIIR // string as string - tagIC = append(tagIC, tagIIV) - } - - // items.CollectionFormat: "" - tagIS := swag.JoinByFormat(tagIC, "") - - return tagIS -} diff --git a/generated/client/jobs/get_jobs_responses.go b/generated/client/jobs/get_jobs_responses.go deleted file mode 100644 index e2ae70a6..00000000 --- a/generated/client/jobs/get_jobs_responses.go +++ /dev/null @@ -1,252 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "encoding/json" - "fmt" - "io" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" -) - -// GetJobsReader is a Reader for the GetJobs structure. -type GetJobsReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *GetJobsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - case 200: - result := NewGetJobsOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - case 400: - result := NewGetJobsBadRequest() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - default: - result := NewGetJobsDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewGetJobsOK creates a GetJobsOK with default headers values -func NewGetJobsOK() *GetJobsOK { - return &GetJobsOK{} -} - -/* -GetJobsOK describes a response with status code 200, with default header values. - -A paginated job list. -*/ -type GetJobsOK struct { - Payload *model.PaginatedJobList -} - -// IsSuccess returns true when this get jobs o k response has a 2xx status code -func (o *GetJobsOK) IsSuccess() bool { - return true -} - -// IsRedirect returns true when this get jobs o k response has a 3xx status code -func (o *GetJobsOK) IsRedirect() bool { - return false -} - -// IsClientError returns true when this get jobs o k response has a 4xx status code -func (o *GetJobsOK) IsClientError() bool { - return false -} - -// IsServerError returns true when this get jobs o k response has a 5xx status code -func (o *GetJobsOK) IsServerError() bool { - return false -} - -// IsCode returns true when this get jobs o k response a status code equal to that given -func (o *GetJobsOK) IsCode(code int) bool { - return code == 200 -} - -// Code gets the status code for the get jobs o k response -func (o *GetJobsOK) Code() int { - return 200 -} - -func (o *GetJobsOK) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs][%d] getJobsOK %s", 200, payload) -} - -func (o *GetJobsOK) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs][%d] getJobsOK %s", 200, payload) -} - -func (o *GetJobsOK) GetPayload() *model.PaginatedJobList { - return o.Payload -} - -func (o *GetJobsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.PaginatedJobList) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetJobsBadRequest creates a GetJobsBadRequest with default headers values -func NewGetJobsBadRequest() *GetJobsBadRequest { - return &GetJobsBadRequest{} -} - -/* -GetJobsBadRequest describes a response with status code 400, with default header values. - -If request is invalid -*/ -type GetJobsBadRequest struct { - Payload *model.ErrorResponse -} - -// IsSuccess returns true when this get jobs bad request response has a 2xx status code -func (o *GetJobsBadRequest) IsSuccess() bool { - return false -} - -// IsRedirect returns true when this get jobs bad request response has a 3xx status code -func (o *GetJobsBadRequest) IsRedirect() bool { - return false -} - -// IsClientError returns true when this get jobs bad request response has a 4xx status code -func (o *GetJobsBadRequest) IsClientError() bool { - return true -} - -// IsServerError returns true when this get jobs bad request response has a 5xx status code -func (o *GetJobsBadRequest) IsServerError() bool { - return false -} - -// IsCode returns true when this get jobs bad request response a status code equal to that given -func (o *GetJobsBadRequest) IsCode(code int) bool { - return code == 400 -} - -// Code gets the status code for the get jobs bad request response -func (o *GetJobsBadRequest) Code() int { - return 400 -} - -func (o *GetJobsBadRequest) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs][%d] getJobsBadRequest %s", 400, payload) -} - -func (o *GetJobsBadRequest) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /jobs][%d] getJobsBadRequest %s", 400, payload) -} - -func (o *GetJobsBadRequest) GetPayload() *model.ErrorResponse { - return o.Payload -} - -func (o *GetJobsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.ErrorResponse) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetJobsDefault creates a GetJobsDefault with default headers values -func NewGetJobsDefault(code int) *GetJobsDefault { - return &GetJobsDefault{ - _statusCode: code, - } -} - -/* -GetJobsDefault describes a response with status code -1, with default header values. - -Other error with any status code and response body format. -*/ -type GetJobsDefault struct { - _statusCode int -} - -// IsSuccess returns true when this get jobs default response has a 2xx status code -func (o *GetJobsDefault) IsSuccess() bool { - return o._statusCode/100 == 2 -} - -// IsRedirect returns true when this get jobs default response has a 3xx status code -func (o *GetJobsDefault) IsRedirect() bool { - return o._statusCode/100 == 3 -} - -// IsClientError returns true when this get jobs default response has a 4xx status code -func (o *GetJobsDefault) IsClientError() bool { - return o._statusCode/100 == 4 -} - -// IsServerError returns true when this get jobs default response has a 5xx status code -func (o *GetJobsDefault) IsServerError() bool { - return o._statusCode/100 == 5 -} - -// IsCode returns true when this get jobs default response a status code equal to that given -func (o *GetJobsDefault) IsCode(code int) bool { - return o._statusCode == code -} - -// Code gets the status code for the get jobs default response -func (o *GetJobsDefault) Code() int { - return o._statusCode -} - -func (o *GetJobsDefault) Error() string { - return fmt.Sprintf("[GET /jobs][%d] GetJobs default", o._statusCode) -} - -func (o *GetJobsDefault) String() string { - return fmt.Sprintf("[GET /jobs][%d] GetJobs default", o._statusCode) -} - -func (o *GetJobsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - return nil -} diff --git a/generated/client/jobs/jobs_client.go b/generated/client/jobs/jobs_client.go deleted file mode 100644 index 9063cfed..00000000 --- a/generated/client/jobs/jobs_client.go +++ /dev/null @@ -1,590 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "github.com/go-openapi/runtime" - httptransport "github.com/go-openapi/runtime/client" - "github.com/go-openapi/strfmt" -) - -// New creates a new jobs API client. -func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { - return &Client{transport: transport, formats: formats} -} - -// New creates a new jobs API client with basic auth credentials. -// It takes the following parameters: -// - host: http host (github.com). -// - basePath: any base path for the API client ("/v1", "/v3"). -// - scheme: http scheme ("http", "https"). -// - user: user for basic authentication header. -// - password: password for basic authentication header. -func NewClientWithBasicAuth(host, basePath, scheme, user, password string) ClientService { - transport := httptransport.New(host, basePath, []string{scheme}) - transport.DefaultAuthentication = httptransport.BasicAuth(user, password) - return &Client{transport: transport, formats: strfmt.Default} -} - -// New creates a new jobs API client with a bearer token for authentication. -// It takes the following parameters: -// - host: http host (github.com). -// - basePath: any base path for the API client ("/v1", "/v3"). -// - scheme: http scheme ("http", "https"). -// - bearerToken: bearer token for Bearer authentication header. -func NewClientWithBearerToken(host, basePath, scheme, bearerToken string) ClientService { - transport := httptransport.New(host, basePath, []string{scheme}) - transport.DefaultAuthentication = httptransport.BearerToken(bearerToken) - return &Client{transport: transport, formats: strfmt.Default} -} - -/* -Client for jobs API -*/ -type Client struct { - transport runtime.ClientTransport - formats strfmt.Registry -} - -// ClientOption may be used to customize the behavior of Client methods. -type ClientOption func(*runtime.ClientOperation) - -// This client is generated with a few options you might find useful for your swagger spec. -// -// Feel free to add you own set of options. - -// WithAccept allows the client to force the Accept header -// to negotiate a specific Producer from the server. -// -// You may use this option to set arbitrary extensions to your MIME media type. -func WithAccept(mime string) ClientOption { - return func(r *runtime.ClientOperation) { - r.ProducesMediaTypes = []string{mime} - } -} - -// WithAcceptApplicationJSON sets the Accept header to "application/json". -func WithAcceptApplicationJSON(r *runtime.ClientOperation) { - r.ProducesMediaTypes = []string{"application/json"} -} - -// WithAcceptTextEventStream sets the Accept header to "text/event-stream". -func WithAcceptTextEventStream(r *runtime.ClientOperation) { - r.ProducesMediaTypes = []string{"text/event-stream"} -} - -// ClientService is the interface for Client methods -type ClientService interface { - DeleteJobsID(params *DeleteJobsIDParams, opts ...ClientOption) (*DeleteJobsIDNoContent, error) - - DeleteJobsIDTags(params *DeleteJobsIDTagsParams, opts ...ClientOption) (*DeleteJobsIDTagsOK, error) - - GetJobs(params *GetJobsParams, opts ...ClientOption) (*GetJobsOK, error) - - GetJobsEvents(params *GetJobsEventsParams, opts ...ClientOption) (*GetJobsEventsOK, error) - - GetJobsID(params *GetJobsIDParams, opts ...ClientOption) (*GetJobsIDOK, error) - - GetJobsIDDefinition(params *GetJobsIDDefinitionParams, opts ...ClientOption) (*GetJobsIDDefinitionOK, error) - - GetJobsIDStatus(params *GetJobsIDStatusParams, opts ...ClientOption) (*GetJobsIDStatusOK, error) - - GetJobsIDTags(params *GetJobsIDTagsParams, opts ...ClientOption) (*GetJobsIDTagsOK, error) - - PostJobs(params *PostJobsParams, opts ...ClientOption) (*PostJobsCreated, error) - - PostJobsIDTags(params *PostJobsIDTagsParams, opts ...ClientOption) (*PostJobsIDTagsOK, error) - - PutJobsIDDefinition(params *PutJobsIDDefinitionParams, opts ...ClientOption) (*PutJobsIDDefinitionOK, error) - - PutJobsIDStatus(params *PutJobsIDStatusParams, opts ...ClientOption) (*PutJobsIDStatusOK, error) - - SetTransport(transport runtime.ClientTransport) -} - -/* -DeleteJobsID deletes an existing job - -Delete an existing job -*/ -func (a *Client) DeleteJobsID(params *DeleteJobsIDParams, opts ...ClientOption) (*DeleteJobsIDNoContent, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewDeleteJobsIDParams() - } - op := &runtime.ClientOperation{ - ID: "DeleteJobsID", - Method: "DELETE", - PathPattern: "/jobs/{id}", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http"}, - Params: params, - Reader: &DeleteJobsIDReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - } - for _, opt := range opts { - opt(op) - } - - result, err := a.transport.Submit(op) - if err != nil { - return nil, err - } - success, ok := result.(*DeleteJobsIDNoContent) - if ok { - return success, nil - } - // unexpected success response - unexpectedSuccess := result.(*DeleteJobsIDDefault) - return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) -} - -/* -DeleteJobsIDTags deletes a tag - -Delete a tag from an existing job -*/ -func (a *Client) DeleteJobsIDTags(params *DeleteJobsIDTagsParams, opts ...ClientOption) (*DeleteJobsIDTagsOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewDeleteJobsIDTagsParams() - } - op := &runtime.ClientOperation{ - ID: "DeleteJobsIDTags", - Method: "DELETE", - PathPattern: "/jobs/{id}/tags", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http"}, - Params: params, - Reader: &DeleteJobsIDTagsReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - } - for _, opt := range opts { - opt(op) - } - - result, err := a.transport.Submit(op) - if err != nil { - return nil, err - } - success, ok := result.(*DeleteJobsIDTagsOK) - if ok { - return success, nil - } - // unexpected success response - unexpectedSuccess := result.(*DeleteJobsIDTagsDefault) - return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) -} - -/* - GetJobs lists of job descriptions - - List of job descriptions - -By default, this endpoint returns the list of jobs in a specific order and predetermined paging properties. -These defaults are: - - Ascending sort on stime - - 10 entries per page -*/ -func (a *Client) GetJobs(params *GetJobsParams, opts ...ClientOption) (*GetJobsOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewGetJobsParams() - } - op := &runtime.ClientOperation{ - ID: "GetJobs", - Method: "GET", - PathPattern: "/jobs", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http"}, - Params: params, - Reader: &GetJobsReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - } - for _, opt := range opts { - opt(op) - } - - result, err := a.transport.Submit(op) - if err != nil { - return nil, err - } - success, ok := result.(*GetJobsOK) - if ok { - return success, nil - } - // unexpected success response - unexpectedSuccess := result.(*GetJobsDefault) - return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) -} - -/* -GetJobsEvents subscribes to job related events such as status updates - -Obtain instant notifications when there are job changes matching the criteria. This endpoint utilizes server-sent events (SSE), where responses are "chunked" with double newline breaks. For example, a single event might look like this: -data: {"clientId":"example_client","state":"INSTALLING"}\n\n -*/ -func (a *Client) GetJobsEvents(params *GetJobsEventsParams, opts ...ClientOption) (*GetJobsEventsOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewGetJobsEventsParams() - } - op := &runtime.ClientOperation{ - ID: "GetJobsEvents", - Method: "GET", - PathPattern: "/jobs/events", - ProducesMediaTypes: []string{"application/json", "text/event-stream"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http"}, - Params: params, - Reader: &GetJobsEventsReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - } - for _, opt := range opts { - opt(op) - } - - result, err := a.transport.Submit(op) - if err != nil { - return nil, err - } - success, ok := result.(*GetJobsEventsOK) - if ok { - return success, nil - } - // unexpected success response - unexpectedSuccess := result.(*GetJobsEventsDefault) - return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) -} - -/* -GetJobsID jobs description for a given ID - -Job description for a given ID -*/ -func (a *Client) GetJobsID(params *GetJobsIDParams, opts ...ClientOption) (*GetJobsIDOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewGetJobsIDParams() - } - op := &runtime.ClientOperation{ - ID: "GetJobsID", - Method: "GET", - PathPattern: "/jobs/{id}", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http"}, - Params: params, - Reader: &GetJobsIDReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - } - for _, opt := range opts { - opt(op) - } - - result, err := a.transport.Submit(op) - if err != nil { - return nil, err - } - success, ok := result.(*GetJobsIDOK) - if ok { - return success, nil - } - // unexpected success response - unexpectedSuccess := result.(*GetJobsIDDefault) - return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) -} - -/* -GetJobsIDDefinition gets job definition - -Retrieve the job definition -*/ -func (a *Client) GetJobsIDDefinition(params *GetJobsIDDefinitionParams, opts ...ClientOption) (*GetJobsIDDefinitionOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewGetJobsIDDefinitionParams() - } - op := &runtime.ClientOperation{ - ID: "GetJobsIDDefinition", - Method: "GET", - PathPattern: "/jobs/{id}/definition", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http"}, - Params: params, - Reader: &GetJobsIDDefinitionReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - } - for _, opt := range opts { - opt(op) - } - - result, err := a.transport.Submit(op) - if err != nil { - return nil, err - } - success, ok := result.(*GetJobsIDDefinitionOK) - if ok { - return success, nil - } - // unexpected success response - unexpectedSuccess := result.(*GetJobsIDDefinitionDefault) - return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) -} - -/* -GetJobsIDStatus gets job status - -Retrieve the job status -*/ -func (a *Client) GetJobsIDStatus(params *GetJobsIDStatusParams, opts ...ClientOption) (*GetJobsIDStatusOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewGetJobsIDStatusParams() - } - op := &runtime.ClientOperation{ - ID: "GetJobsIDStatus", - Method: "GET", - PathPattern: "/jobs/{id}/status", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http"}, - Params: params, - Reader: &GetJobsIDStatusReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - } - for _, opt := range opts { - opt(op) - } - - result, err := a.transport.Submit(op) - if err != nil { - return nil, err - } - success, ok := result.(*GetJobsIDStatusOK) - if ok { - return success, nil - } - // unexpected success response - unexpectedSuccess := result.(*GetJobsIDStatusDefault) - return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) -} - -/* -GetJobsIDTags gets tags - -Get the tags of a job -*/ -func (a *Client) GetJobsIDTags(params *GetJobsIDTagsParams, opts ...ClientOption) (*GetJobsIDTagsOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewGetJobsIDTagsParams() - } - op := &runtime.ClientOperation{ - ID: "GetJobsIDTags", - Method: "GET", - PathPattern: "/jobs/{id}/tags", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http"}, - Params: params, - Reader: &GetJobsIDTagsReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - } - for _, opt := range opts { - opt(op) - } - - result, err := a.transport.Submit(op) - if err != nil { - return nil, err - } - success, ok := result.(*GetJobsIDTagsOK) - if ok { - return success, nil - } - // unexpected success response - unexpectedSuccess := result.(*GetJobsIDTagsDefault) - return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) -} - -/* -PostJobs adds a new job - -Add a new job -*/ -func (a *Client) PostJobs(params *PostJobsParams, opts ...ClientOption) (*PostJobsCreated, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewPostJobsParams() - } - op := &runtime.ClientOperation{ - ID: "PostJobs", - Method: "POST", - PathPattern: "/jobs", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http"}, - Params: params, - Reader: &PostJobsReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - } - for _, opt := range opts { - opt(op) - } - - result, err := a.transport.Submit(op) - if err != nil { - return nil, err - } - success, ok := result.(*PostJobsCreated) - if ok { - return success, nil - } - // unexpected success response - unexpectedSuccess := result.(*PostJobsDefault) - return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) -} - -/* -PostJobsIDTags adds a tag - -Add a tag to an existing job -*/ -func (a *Client) PostJobsIDTags(params *PostJobsIDTagsParams, opts ...ClientOption) (*PostJobsIDTagsOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewPostJobsIDTagsParams() - } - op := &runtime.ClientOperation{ - ID: "PostJobsIDTags", - Method: "POST", - PathPattern: "/jobs/{id}/tags", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http"}, - Params: params, - Reader: &PostJobsIDTagsReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - } - for _, opt := range opts { - opt(op) - } - - result, err := a.transport.Submit(op) - if err != nil { - return nil, err - } - success, ok := result.(*PostJobsIDTagsOK) - if ok { - return success, nil - } - // unexpected success response - unexpectedSuccess := result.(*PostJobsIDTagsDefault) - return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) -} - -/* -PutJobsIDDefinition modifies job definition - -Modify the job definition of an existing job -*/ -func (a *Client) PutJobsIDDefinition(params *PutJobsIDDefinitionParams, opts ...ClientOption) (*PutJobsIDDefinitionOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewPutJobsIDDefinitionParams() - } - op := &runtime.ClientOperation{ - ID: "PutJobsIDDefinition", - Method: "PUT", - PathPattern: "/jobs/{id}/definition", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http"}, - Params: params, - Reader: &PutJobsIDDefinitionReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - } - for _, opt := range opts { - opt(op) - } - - result, err := a.transport.Submit(op) - if err != nil { - return nil, err - } - success, ok := result.(*PutJobsIDDefinitionOK) - if ok { - return success, nil - } - // unexpected success response - unexpectedSuccess := result.(*PutJobsIDDefinitionDefault) - return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) -} - -/* -PutJobsIDStatus modifies status of an existing job - -Modify status of an existing job -*/ -func (a *Client) PutJobsIDStatus(params *PutJobsIDStatusParams, opts ...ClientOption) (*PutJobsIDStatusOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewPutJobsIDStatusParams() - } - op := &runtime.ClientOperation{ - ID: "PutJobsIDStatus", - Method: "PUT", - PathPattern: "/jobs/{id}/status", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http"}, - Params: params, - Reader: &PutJobsIDStatusReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - } - for _, opt := range opts { - opt(op) - } - - result, err := a.transport.Submit(op) - if err != nil { - return nil, err - } - success, ok := result.(*PutJobsIDStatusOK) - if ok { - return success, nil - } - // unexpected success response - unexpectedSuccess := result.(*PutJobsIDStatusDefault) - return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) -} - -// SetTransport changes the transport on the client -func (a *Client) SetTransport(transport runtime.ClientTransport) { - a.transport = transport -} diff --git a/generated/client/jobs/post_jobs_id_tags_parameters.go b/generated/client/jobs/post_jobs_id_tags_parameters.go deleted file mode 100644 index d593af0a..00000000 --- a/generated/client/jobs/post_jobs_id_tags_parameters.go +++ /dev/null @@ -1,178 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "net/http" - "time" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - "github.com/go-openapi/strfmt" -) - -// NewPostJobsIDTagsParams creates a new PostJobsIDTagsParams object, -// with the default timeout for this client. -// -// Default values are not hydrated, since defaults are normally applied by the API server side. -// -// To enforce default values in parameter, use SetDefaults or WithDefaults. -func NewPostJobsIDTagsParams() *PostJobsIDTagsParams { - return &PostJobsIDTagsParams{ - timeout: cr.DefaultTimeout, - } -} - -// NewPostJobsIDTagsParamsWithTimeout creates a new PostJobsIDTagsParams object -// with the ability to set a timeout on a request. -func NewPostJobsIDTagsParamsWithTimeout(timeout time.Duration) *PostJobsIDTagsParams { - return &PostJobsIDTagsParams{ - timeout: timeout, - } -} - -// NewPostJobsIDTagsParamsWithContext creates a new PostJobsIDTagsParams object -// with the ability to set a context for a request. -func NewPostJobsIDTagsParamsWithContext(ctx context.Context) *PostJobsIDTagsParams { - return &PostJobsIDTagsParams{ - Context: ctx, - } -} - -// NewPostJobsIDTagsParamsWithHTTPClient creates a new PostJobsIDTagsParams object -// with the ability to set a custom HTTPClient for a request. -func NewPostJobsIDTagsParamsWithHTTPClient(client *http.Client) *PostJobsIDTagsParams { - return &PostJobsIDTagsParams{ - HTTPClient: client, - } -} - -/* -PostJobsIDTagsParams contains all the parameters to send to the API endpoint - - for the post jobs ID tags operation. - - Typically these are written to a http.Request. -*/ -type PostJobsIDTagsParams struct { - - /* Tags. - - Tags to add - */ - Tags []string - - /* ID. - - Job ID - */ - ID string - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithDefaults hydrates default values in the post jobs ID tags params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *PostJobsIDTagsParams) WithDefaults() *PostJobsIDTagsParams { - o.SetDefaults() - return o -} - -// SetDefaults hydrates default values in the post jobs ID tags params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *PostJobsIDTagsParams) SetDefaults() { - // no default values defined for this parameter -} - -// WithTimeout adds the timeout to the post jobs ID tags params -func (o *PostJobsIDTagsParams) WithTimeout(timeout time.Duration) *PostJobsIDTagsParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the post jobs ID tags params -func (o *PostJobsIDTagsParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the post jobs ID tags params -func (o *PostJobsIDTagsParams) WithContext(ctx context.Context) *PostJobsIDTagsParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the post jobs ID tags params -func (o *PostJobsIDTagsParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the post jobs ID tags params -func (o *PostJobsIDTagsParams) WithHTTPClient(client *http.Client) *PostJobsIDTagsParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the post jobs ID tags params -func (o *PostJobsIDTagsParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithTags adds the tags to the post jobs ID tags params -func (o *PostJobsIDTagsParams) WithTags(tags []string) *PostJobsIDTagsParams { - o.SetTags(tags) - return o -} - -// SetTags adds the tags to the post jobs ID tags params -func (o *PostJobsIDTagsParams) SetTags(tags []string) { - o.Tags = tags -} - -// WithID adds the id to the post jobs ID tags params -func (o *PostJobsIDTagsParams) WithID(id string) *PostJobsIDTagsParams { - o.SetID(id) - return o -} - -// SetID adds the id to the post jobs ID tags params -func (o *PostJobsIDTagsParams) SetID(id string) { - o.ID = id -} - -// WriteToRequest writes these params to a swagger request -func (o *PostJobsIDTagsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - if o.Tags != nil { - if err := r.SetBodyParam(o.Tags); err != nil { - return err - } - } - - // path param id - if err := r.SetPathParam("id", o.ID); err != nil { - return err - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/generated/client/jobs/post_jobs_id_tags_responses.go b/generated/client/jobs/post_jobs_id_tags_responses.go deleted file mode 100644 index 6e5ce957..00000000 --- a/generated/client/jobs/post_jobs_id_tags_responses.go +++ /dev/null @@ -1,326 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "encoding/json" - "fmt" - "io" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" -) - -// PostJobsIDTagsReader is a Reader for the PostJobsIDTags structure. -type PostJobsIDTagsReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *PostJobsIDTagsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - case 200: - result := NewPostJobsIDTagsOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - case 400: - result := NewPostJobsIDTagsBadRequest() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - case 404: - result := NewPostJobsIDTagsNotFound() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - default: - result := NewPostJobsIDTagsDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewPostJobsIDTagsOK creates a PostJobsIDTagsOK with default headers values -func NewPostJobsIDTagsOK() *PostJobsIDTagsOK { - return &PostJobsIDTagsOK{} -} - -/* -PostJobsIDTagsOK describes a response with status code 200, with default header values. - -Successfully added tag to job -*/ -type PostJobsIDTagsOK struct { - Payload []string -} - -// IsSuccess returns true when this post jobs Id tags o k response has a 2xx status code -func (o *PostJobsIDTagsOK) IsSuccess() bool { - return true -} - -// IsRedirect returns true when this post jobs Id tags o k response has a 3xx status code -func (o *PostJobsIDTagsOK) IsRedirect() bool { - return false -} - -// IsClientError returns true when this post jobs Id tags o k response has a 4xx status code -func (o *PostJobsIDTagsOK) IsClientError() bool { - return false -} - -// IsServerError returns true when this post jobs Id tags o k response has a 5xx status code -func (o *PostJobsIDTagsOK) IsServerError() bool { - return false -} - -// IsCode returns true when this post jobs Id tags o k response a status code equal to that given -func (o *PostJobsIDTagsOK) IsCode(code int) bool { - return code == 200 -} - -// Code gets the status code for the post jobs Id tags o k response -func (o *PostJobsIDTagsOK) Code() int { - return 200 -} - -func (o *PostJobsIDTagsOK) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[POST /jobs/{id}/tags][%d] postJobsIdTagsOK %s", 200, payload) -} - -func (o *PostJobsIDTagsOK) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[POST /jobs/{id}/tags][%d] postJobsIdTagsOK %s", 200, payload) -} - -func (o *PostJobsIDTagsOK) GetPayload() []string { - return o.Payload -} - -func (o *PostJobsIDTagsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - // response payload - if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPostJobsIDTagsBadRequest creates a PostJobsIDTagsBadRequest with default headers values -func NewPostJobsIDTagsBadRequest() *PostJobsIDTagsBadRequest { - return &PostJobsIDTagsBadRequest{} -} - -/* -PostJobsIDTagsBadRequest describes a response with status code 400, with default header values. - -Bad Request -*/ -type PostJobsIDTagsBadRequest struct { - Payload *model.ErrorResponse -} - -// IsSuccess returns true when this post jobs Id tags bad request response has a 2xx status code -func (o *PostJobsIDTagsBadRequest) IsSuccess() bool { - return false -} - -// IsRedirect returns true when this post jobs Id tags bad request response has a 3xx status code -func (o *PostJobsIDTagsBadRequest) IsRedirect() bool { - return false -} - -// IsClientError returns true when this post jobs Id tags bad request response has a 4xx status code -func (o *PostJobsIDTagsBadRequest) IsClientError() bool { - return true -} - -// IsServerError returns true when this post jobs Id tags bad request response has a 5xx status code -func (o *PostJobsIDTagsBadRequest) IsServerError() bool { - return false -} - -// IsCode returns true when this post jobs Id tags bad request response a status code equal to that given -func (o *PostJobsIDTagsBadRequest) IsCode(code int) bool { - return code == 400 -} - -// Code gets the status code for the post jobs Id tags bad request response -func (o *PostJobsIDTagsBadRequest) Code() int { - return 400 -} - -func (o *PostJobsIDTagsBadRequest) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[POST /jobs/{id}/tags][%d] postJobsIdTagsBadRequest %s", 400, payload) -} - -func (o *PostJobsIDTagsBadRequest) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[POST /jobs/{id}/tags][%d] postJobsIdTagsBadRequest %s", 400, payload) -} - -func (o *PostJobsIDTagsBadRequest) GetPayload() *model.ErrorResponse { - return o.Payload -} - -func (o *PostJobsIDTagsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.ErrorResponse) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPostJobsIDTagsNotFound creates a PostJobsIDTagsNotFound with default headers values -func NewPostJobsIDTagsNotFound() *PostJobsIDTagsNotFound { - return &PostJobsIDTagsNotFound{} -} - -/* -PostJobsIDTagsNotFound describes a response with status code 404, with default header values. - -Not Found -*/ -type PostJobsIDTagsNotFound struct { - Payload *model.ErrorResponse -} - -// IsSuccess returns true when this post jobs Id tags not found response has a 2xx status code -func (o *PostJobsIDTagsNotFound) IsSuccess() bool { - return false -} - -// IsRedirect returns true when this post jobs Id tags not found response has a 3xx status code -func (o *PostJobsIDTagsNotFound) IsRedirect() bool { - return false -} - -// IsClientError returns true when this post jobs Id tags not found response has a 4xx status code -func (o *PostJobsIDTagsNotFound) IsClientError() bool { - return true -} - -// IsServerError returns true when this post jobs Id tags not found response has a 5xx status code -func (o *PostJobsIDTagsNotFound) IsServerError() bool { - return false -} - -// IsCode returns true when this post jobs Id tags not found response a status code equal to that given -func (o *PostJobsIDTagsNotFound) IsCode(code int) bool { - return code == 404 -} - -// Code gets the status code for the post jobs Id tags not found response -func (o *PostJobsIDTagsNotFound) Code() int { - return 404 -} - -func (o *PostJobsIDTagsNotFound) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[POST /jobs/{id}/tags][%d] postJobsIdTagsNotFound %s", 404, payload) -} - -func (o *PostJobsIDTagsNotFound) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[POST /jobs/{id}/tags][%d] postJobsIdTagsNotFound %s", 404, payload) -} - -func (o *PostJobsIDTagsNotFound) GetPayload() *model.ErrorResponse { - return o.Payload -} - -func (o *PostJobsIDTagsNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.ErrorResponse) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPostJobsIDTagsDefault creates a PostJobsIDTagsDefault with default headers values -func NewPostJobsIDTagsDefault(code int) *PostJobsIDTagsDefault { - return &PostJobsIDTagsDefault{ - _statusCode: code, - } -} - -/* -PostJobsIDTagsDefault describes a response with status code -1, with default header values. - -Other error with any status code and response body format. -*/ -type PostJobsIDTagsDefault struct { - _statusCode int -} - -// IsSuccess returns true when this post jobs ID tags default response has a 2xx status code -func (o *PostJobsIDTagsDefault) IsSuccess() bool { - return o._statusCode/100 == 2 -} - -// IsRedirect returns true when this post jobs ID tags default response has a 3xx status code -func (o *PostJobsIDTagsDefault) IsRedirect() bool { - return o._statusCode/100 == 3 -} - -// IsClientError returns true when this post jobs ID tags default response has a 4xx status code -func (o *PostJobsIDTagsDefault) IsClientError() bool { - return o._statusCode/100 == 4 -} - -// IsServerError returns true when this post jobs ID tags default response has a 5xx status code -func (o *PostJobsIDTagsDefault) IsServerError() bool { - return o._statusCode/100 == 5 -} - -// IsCode returns true when this post jobs ID tags default response a status code equal to that given -func (o *PostJobsIDTagsDefault) IsCode(code int) bool { - return o._statusCode == code -} - -// Code gets the status code for the post jobs ID tags default response -func (o *PostJobsIDTagsDefault) Code() int { - return o._statusCode -} - -func (o *PostJobsIDTagsDefault) Error() string { - return fmt.Sprintf("[POST /jobs/{id}/tags][%d] PostJobsIDTags default", o._statusCode) -} - -func (o *PostJobsIDTagsDefault) String() string { - return fmt.Sprintf("[POST /jobs/{id}/tags][%d] PostJobsIDTags default", o._statusCode) -} - -func (o *PostJobsIDTagsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - return nil -} diff --git a/generated/client/jobs/post_jobs_parameters.go b/generated/client/jobs/post_jobs_parameters.go deleted file mode 100644 index 694fb066..00000000 --- a/generated/client/jobs/post_jobs_parameters.go +++ /dev/null @@ -1,157 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "net/http" - "time" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" -) - -// NewPostJobsParams creates a new PostJobsParams object, -// with the default timeout for this client. -// -// Default values are not hydrated, since defaults are normally applied by the API server side. -// -// To enforce default values in parameter, use SetDefaults or WithDefaults. -func NewPostJobsParams() *PostJobsParams { - return &PostJobsParams{ - timeout: cr.DefaultTimeout, - } -} - -// NewPostJobsParamsWithTimeout creates a new PostJobsParams object -// with the ability to set a timeout on a request. -func NewPostJobsParamsWithTimeout(timeout time.Duration) *PostJobsParams { - return &PostJobsParams{ - timeout: timeout, - } -} - -// NewPostJobsParamsWithContext creates a new PostJobsParams object -// with the ability to set a context for a request. -func NewPostJobsParamsWithContext(ctx context.Context) *PostJobsParams { - return &PostJobsParams{ - Context: ctx, - } -} - -// NewPostJobsParamsWithHTTPClient creates a new PostJobsParams object -// with the ability to set a custom HTTPClient for a request. -func NewPostJobsParamsWithHTTPClient(client *http.Client) *PostJobsParams { - return &PostJobsParams{ - HTTPClient: client, - } -} - -/* -PostJobsParams contains all the parameters to send to the API endpoint - - for the post jobs operation. - - Typically these are written to a http.Request. -*/ -type PostJobsParams struct { - - /* Job. - - Job which shall be created - */ - Job *model.JobRequest - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithDefaults hydrates default values in the post jobs params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *PostJobsParams) WithDefaults() *PostJobsParams { - o.SetDefaults() - return o -} - -// SetDefaults hydrates default values in the post jobs params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *PostJobsParams) SetDefaults() { - // no default values defined for this parameter -} - -// WithTimeout adds the timeout to the post jobs params -func (o *PostJobsParams) WithTimeout(timeout time.Duration) *PostJobsParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the post jobs params -func (o *PostJobsParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the post jobs params -func (o *PostJobsParams) WithContext(ctx context.Context) *PostJobsParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the post jobs params -func (o *PostJobsParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the post jobs params -func (o *PostJobsParams) WithHTTPClient(client *http.Client) *PostJobsParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the post jobs params -func (o *PostJobsParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithJob adds the job to the post jobs params -func (o *PostJobsParams) WithJob(job *model.JobRequest) *PostJobsParams { - o.SetJob(job) - return o -} - -// SetJob adds the job to the post jobs params -func (o *PostJobsParams) SetJob(job *model.JobRequest) { - o.Job = job -} - -// WriteToRequest writes these params to a swagger request -func (o *PostJobsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - if o.Job != nil { - if err := r.SetBodyParam(o.Job); err != nil { - return err - } - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/generated/client/jobs/post_jobs_responses.go b/generated/client/jobs/post_jobs_responses.go deleted file mode 100644 index 07cf0798..00000000 --- a/generated/client/jobs/post_jobs_responses.go +++ /dev/null @@ -1,252 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "encoding/json" - "fmt" - "io" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" -) - -// PostJobsReader is a Reader for the PostJobs structure. -type PostJobsReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *PostJobsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - case 201: - result := NewPostJobsCreated() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - case 400: - result := NewPostJobsBadRequest() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - default: - result := NewPostJobsDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewPostJobsCreated creates a PostJobsCreated with default headers values -func NewPostJobsCreated() *PostJobsCreated { - return &PostJobsCreated{} -} - -/* -PostJobsCreated describes a response with status code 201, with default header values. - -Job was created -*/ -type PostJobsCreated struct { - Payload *model.Job -} - -// IsSuccess returns true when this post jobs created response has a 2xx status code -func (o *PostJobsCreated) IsSuccess() bool { - return true -} - -// IsRedirect returns true when this post jobs created response has a 3xx status code -func (o *PostJobsCreated) IsRedirect() bool { - return false -} - -// IsClientError returns true when this post jobs created response has a 4xx status code -func (o *PostJobsCreated) IsClientError() bool { - return false -} - -// IsServerError returns true when this post jobs created response has a 5xx status code -func (o *PostJobsCreated) IsServerError() bool { - return false -} - -// IsCode returns true when this post jobs created response a status code equal to that given -func (o *PostJobsCreated) IsCode(code int) bool { - return code == 201 -} - -// Code gets the status code for the post jobs created response -func (o *PostJobsCreated) Code() int { - return 201 -} - -func (o *PostJobsCreated) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[POST /jobs][%d] postJobsCreated %s", 201, payload) -} - -func (o *PostJobsCreated) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[POST /jobs][%d] postJobsCreated %s", 201, payload) -} - -func (o *PostJobsCreated) GetPayload() *model.Job { - return o.Payload -} - -func (o *PostJobsCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.Job) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPostJobsBadRequest creates a PostJobsBadRequest with default headers values -func NewPostJobsBadRequest() *PostJobsBadRequest { - return &PostJobsBadRequest{} -} - -/* -PostJobsBadRequest describes a response with status code 400, with default header values. - -Bad Request -*/ -type PostJobsBadRequest struct { - Payload *model.ErrorResponse -} - -// IsSuccess returns true when this post jobs bad request response has a 2xx status code -func (o *PostJobsBadRequest) IsSuccess() bool { - return false -} - -// IsRedirect returns true when this post jobs bad request response has a 3xx status code -func (o *PostJobsBadRequest) IsRedirect() bool { - return false -} - -// IsClientError returns true when this post jobs bad request response has a 4xx status code -func (o *PostJobsBadRequest) IsClientError() bool { - return true -} - -// IsServerError returns true when this post jobs bad request response has a 5xx status code -func (o *PostJobsBadRequest) IsServerError() bool { - return false -} - -// IsCode returns true when this post jobs bad request response a status code equal to that given -func (o *PostJobsBadRequest) IsCode(code int) bool { - return code == 400 -} - -// Code gets the status code for the post jobs bad request response -func (o *PostJobsBadRequest) Code() int { - return 400 -} - -func (o *PostJobsBadRequest) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[POST /jobs][%d] postJobsBadRequest %s", 400, payload) -} - -func (o *PostJobsBadRequest) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[POST /jobs][%d] postJobsBadRequest %s", 400, payload) -} - -func (o *PostJobsBadRequest) GetPayload() *model.ErrorResponse { - return o.Payload -} - -func (o *PostJobsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.ErrorResponse) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPostJobsDefault creates a PostJobsDefault with default headers values -func NewPostJobsDefault(code int) *PostJobsDefault { - return &PostJobsDefault{ - _statusCode: code, - } -} - -/* -PostJobsDefault describes a response with status code -1, with default header values. - -Other error with any status code and response body format. -*/ -type PostJobsDefault struct { - _statusCode int -} - -// IsSuccess returns true when this post jobs default response has a 2xx status code -func (o *PostJobsDefault) IsSuccess() bool { - return o._statusCode/100 == 2 -} - -// IsRedirect returns true when this post jobs default response has a 3xx status code -func (o *PostJobsDefault) IsRedirect() bool { - return o._statusCode/100 == 3 -} - -// IsClientError returns true when this post jobs default response has a 4xx status code -func (o *PostJobsDefault) IsClientError() bool { - return o._statusCode/100 == 4 -} - -// IsServerError returns true when this post jobs default response has a 5xx status code -func (o *PostJobsDefault) IsServerError() bool { - return o._statusCode/100 == 5 -} - -// IsCode returns true when this post jobs default response a status code equal to that given -func (o *PostJobsDefault) IsCode(code int) bool { - return o._statusCode == code -} - -// Code gets the status code for the post jobs default response -func (o *PostJobsDefault) Code() int { - return o._statusCode -} - -func (o *PostJobsDefault) Error() string { - return fmt.Sprintf("[POST /jobs][%d] PostJobs default", o._statusCode) -} - -func (o *PostJobsDefault) String() string { - return fmt.Sprintf("[POST /jobs][%d] PostJobs default", o._statusCode) -} - -func (o *PostJobsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - return nil -} diff --git a/generated/client/jobs/put_jobs_id_definition_parameters.go b/generated/client/jobs/put_jobs_id_definition_parameters.go deleted file mode 100644 index c2030955..00000000 --- a/generated/client/jobs/put_jobs_id_definition_parameters.go +++ /dev/null @@ -1,178 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "net/http" - "time" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - "github.com/go-openapi/strfmt" -) - -// NewPutJobsIDDefinitionParams creates a new PutJobsIDDefinitionParams object, -// with the default timeout for this client. -// -// Default values are not hydrated, since defaults are normally applied by the API server side. -// -// To enforce default values in parameter, use SetDefaults or WithDefaults. -func NewPutJobsIDDefinitionParams() *PutJobsIDDefinitionParams { - return &PutJobsIDDefinitionParams{ - timeout: cr.DefaultTimeout, - } -} - -// NewPutJobsIDDefinitionParamsWithTimeout creates a new PutJobsIDDefinitionParams object -// with the ability to set a timeout on a request. -func NewPutJobsIDDefinitionParamsWithTimeout(timeout time.Duration) *PutJobsIDDefinitionParams { - return &PutJobsIDDefinitionParams{ - timeout: timeout, - } -} - -// NewPutJobsIDDefinitionParamsWithContext creates a new PutJobsIDDefinitionParams object -// with the ability to set a context for a request. -func NewPutJobsIDDefinitionParamsWithContext(ctx context.Context) *PutJobsIDDefinitionParams { - return &PutJobsIDDefinitionParams{ - Context: ctx, - } -} - -// NewPutJobsIDDefinitionParamsWithHTTPClient creates a new PutJobsIDDefinitionParams object -// with the ability to set a custom HTTPClient for a request. -func NewPutJobsIDDefinitionParamsWithHTTPClient(client *http.Client) *PutJobsIDDefinitionParams { - return &PutJobsIDDefinitionParams{ - HTTPClient: client, - } -} - -/* -PutJobsIDDefinitionParams contains all the parameters to send to the API endpoint - - for the put jobs ID definition operation. - - Typically these are written to a http.Request. -*/ -type PutJobsIDDefinitionParams struct { - - /* JobDefinition. - - How to modify the job - */ - JobDefinition map[string]interface{} - - /* ID. - - Job ID - */ - ID string - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithDefaults hydrates default values in the put jobs ID definition params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *PutJobsIDDefinitionParams) WithDefaults() *PutJobsIDDefinitionParams { - o.SetDefaults() - return o -} - -// SetDefaults hydrates default values in the put jobs ID definition params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *PutJobsIDDefinitionParams) SetDefaults() { - // no default values defined for this parameter -} - -// WithTimeout adds the timeout to the put jobs ID definition params -func (o *PutJobsIDDefinitionParams) WithTimeout(timeout time.Duration) *PutJobsIDDefinitionParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the put jobs ID definition params -func (o *PutJobsIDDefinitionParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the put jobs ID definition params -func (o *PutJobsIDDefinitionParams) WithContext(ctx context.Context) *PutJobsIDDefinitionParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the put jobs ID definition params -func (o *PutJobsIDDefinitionParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the put jobs ID definition params -func (o *PutJobsIDDefinitionParams) WithHTTPClient(client *http.Client) *PutJobsIDDefinitionParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the put jobs ID definition params -func (o *PutJobsIDDefinitionParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithJobDefinition adds the jobDefinition to the put jobs ID definition params -func (o *PutJobsIDDefinitionParams) WithJobDefinition(jobDefinition map[string]interface{}) *PutJobsIDDefinitionParams { - o.SetJobDefinition(jobDefinition) - return o -} - -// SetJobDefinition adds the jobDefinition to the put jobs ID definition params -func (o *PutJobsIDDefinitionParams) SetJobDefinition(jobDefinition map[string]interface{}) { - o.JobDefinition = jobDefinition -} - -// WithID adds the id to the put jobs ID definition params -func (o *PutJobsIDDefinitionParams) WithID(id string) *PutJobsIDDefinitionParams { - o.SetID(id) - return o -} - -// SetID adds the id to the put jobs ID definition params -func (o *PutJobsIDDefinitionParams) SetID(id string) { - o.ID = id -} - -// WriteToRequest writes these params to a swagger request -func (o *PutJobsIDDefinitionParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - if o.JobDefinition != nil { - if err := r.SetBodyParam(o.JobDefinition); err != nil { - return err - } - } - - // path param id - if err := r.SetPathParam("id", o.ID); err != nil { - return err - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/generated/client/jobs/put_jobs_id_definition_responses.go b/generated/client/jobs/put_jobs_id_definition_responses.go deleted file mode 100644 index 0d59396d..00000000 --- a/generated/client/jobs/put_jobs_id_definition_responses.go +++ /dev/null @@ -1,326 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "encoding/json" - "fmt" - "io" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" -) - -// PutJobsIDDefinitionReader is a Reader for the PutJobsIDDefinition structure. -type PutJobsIDDefinitionReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *PutJobsIDDefinitionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - case 200: - result := NewPutJobsIDDefinitionOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - case 400: - result := NewPutJobsIDDefinitionBadRequest() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - case 404: - result := NewPutJobsIDDefinitionNotFound() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - default: - result := NewPutJobsIDDefinitionDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewPutJobsIDDefinitionOK creates a PutJobsIDDefinitionOK with default headers values -func NewPutJobsIDDefinitionOK() *PutJobsIDDefinitionOK { - return &PutJobsIDDefinitionOK{} -} - -/* -PutJobsIDDefinitionOK describes a response with status code 200, with default header values. - -Job modified successfully -*/ -type PutJobsIDDefinitionOK struct { - Payload map[string]interface{} -} - -// IsSuccess returns true when this put jobs Id definition o k response has a 2xx status code -func (o *PutJobsIDDefinitionOK) IsSuccess() bool { - return true -} - -// IsRedirect returns true when this put jobs Id definition o k response has a 3xx status code -func (o *PutJobsIDDefinitionOK) IsRedirect() bool { - return false -} - -// IsClientError returns true when this put jobs Id definition o k response has a 4xx status code -func (o *PutJobsIDDefinitionOK) IsClientError() bool { - return false -} - -// IsServerError returns true when this put jobs Id definition o k response has a 5xx status code -func (o *PutJobsIDDefinitionOK) IsServerError() bool { - return false -} - -// IsCode returns true when this put jobs Id definition o k response a status code equal to that given -func (o *PutJobsIDDefinitionOK) IsCode(code int) bool { - return code == 200 -} - -// Code gets the status code for the put jobs Id definition o k response -func (o *PutJobsIDDefinitionOK) Code() int { - return 200 -} - -func (o *PutJobsIDDefinitionOK) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[PUT /jobs/{id}/definition][%d] putJobsIdDefinitionOK %s", 200, payload) -} - -func (o *PutJobsIDDefinitionOK) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[PUT /jobs/{id}/definition][%d] putJobsIdDefinitionOK %s", 200, payload) -} - -func (o *PutJobsIDDefinitionOK) GetPayload() map[string]interface{} { - return o.Payload -} - -func (o *PutJobsIDDefinitionOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - // response payload - if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPutJobsIDDefinitionBadRequest creates a PutJobsIDDefinitionBadRequest with default headers values -func NewPutJobsIDDefinitionBadRequest() *PutJobsIDDefinitionBadRequest { - return &PutJobsIDDefinitionBadRequest{} -} - -/* -PutJobsIDDefinitionBadRequest describes a response with status code 400, with default header values. - -Bad Request -*/ -type PutJobsIDDefinitionBadRequest struct { - Payload *model.ErrorResponse -} - -// IsSuccess returns true when this put jobs Id definition bad request response has a 2xx status code -func (o *PutJobsIDDefinitionBadRequest) IsSuccess() bool { - return false -} - -// IsRedirect returns true when this put jobs Id definition bad request response has a 3xx status code -func (o *PutJobsIDDefinitionBadRequest) IsRedirect() bool { - return false -} - -// IsClientError returns true when this put jobs Id definition bad request response has a 4xx status code -func (o *PutJobsIDDefinitionBadRequest) IsClientError() bool { - return true -} - -// IsServerError returns true when this put jobs Id definition bad request response has a 5xx status code -func (o *PutJobsIDDefinitionBadRequest) IsServerError() bool { - return false -} - -// IsCode returns true when this put jobs Id definition bad request response a status code equal to that given -func (o *PutJobsIDDefinitionBadRequest) IsCode(code int) bool { - return code == 400 -} - -// Code gets the status code for the put jobs Id definition bad request response -func (o *PutJobsIDDefinitionBadRequest) Code() int { - return 400 -} - -func (o *PutJobsIDDefinitionBadRequest) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[PUT /jobs/{id}/definition][%d] putJobsIdDefinitionBadRequest %s", 400, payload) -} - -func (o *PutJobsIDDefinitionBadRequest) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[PUT /jobs/{id}/definition][%d] putJobsIdDefinitionBadRequest %s", 400, payload) -} - -func (o *PutJobsIDDefinitionBadRequest) GetPayload() *model.ErrorResponse { - return o.Payload -} - -func (o *PutJobsIDDefinitionBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.ErrorResponse) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPutJobsIDDefinitionNotFound creates a PutJobsIDDefinitionNotFound with default headers values -func NewPutJobsIDDefinitionNotFound() *PutJobsIDDefinitionNotFound { - return &PutJobsIDDefinitionNotFound{} -} - -/* -PutJobsIDDefinitionNotFound describes a response with status code 404, with default header values. - -Not Found -*/ -type PutJobsIDDefinitionNotFound struct { - Payload *model.ErrorResponse -} - -// IsSuccess returns true when this put jobs Id definition not found response has a 2xx status code -func (o *PutJobsIDDefinitionNotFound) IsSuccess() bool { - return false -} - -// IsRedirect returns true when this put jobs Id definition not found response has a 3xx status code -func (o *PutJobsIDDefinitionNotFound) IsRedirect() bool { - return false -} - -// IsClientError returns true when this put jobs Id definition not found response has a 4xx status code -func (o *PutJobsIDDefinitionNotFound) IsClientError() bool { - return true -} - -// IsServerError returns true when this put jobs Id definition not found response has a 5xx status code -func (o *PutJobsIDDefinitionNotFound) IsServerError() bool { - return false -} - -// IsCode returns true when this put jobs Id definition not found response a status code equal to that given -func (o *PutJobsIDDefinitionNotFound) IsCode(code int) bool { - return code == 404 -} - -// Code gets the status code for the put jobs Id definition not found response -func (o *PutJobsIDDefinitionNotFound) Code() int { - return 404 -} - -func (o *PutJobsIDDefinitionNotFound) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[PUT /jobs/{id}/definition][%d] putJobsIdDefinitionNotFound %s", 404, payload) -} - -func (o *PutJobsIDDefinitionNotFound) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[PUT /jobs/{id}/definition][%d] putJobsIdDefinitionNotFound %s", 404, payload) -} - -func (o *PutJobsIDDefinitionNotFound) GetPayload() *model.ErrorResponse { - return o.Payload -} - -func (o *PutJobsIDDefinitionNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.ErrorResponse) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPutJobsIDDefinitionDefault creates a PutJobsIDDefinitionDefault with default headers values -func NewPutJobsIDDefinitionDefault(code int) *PutJobsIDDefinitionDefault { - return &PutJobsIDDefinitionDefault{ - _statusCode: code, - } -} - -/* -PutJobsIDDefinitionDefault describes a response with status code -1, with default header values. - -Other error with any status code and response body format. -*/ -type PutJobsIDDefinitionDefault struct { - _statusCode int -} - -// IsSuccess returns true when this put jobs ID definition default response has a 2xx status code -func (o *PutJobsIDDefinitionDefault) IsSuccess() bool { - return o._statusCode/100 == 2 -} - -// IsRedirect returns true when this put jobs ID definition default response has a 3xx status code -func (o *PutJobsIDDefinitionDefault) IsRedirect() bool { - return o._statusCode/100 == 3 -} - -// IsClientError returns true when this put jobs ID definition default response has a 4xx status code -func (o *PutJobsIDDefinitionDefault) IsClientError() bool { - return o._statusCode/100 == 4 -} - -// IsServerError returns true when this put jobs ID definition default response has a 5xx status code -func (o *PutJobsIDDefinitionDefault) IsServerError() bool { - return o._statusCode/100 == 5 -} - -// IsCode returns true when this put jobs ID definition default response a status code equal to that given -func (o *PutJobsIDDefinitionDefault) IsCode(code int) bool { - return o._statusCode == code -} - -// Code gets the status code for the put jobs ID definition default response -func (o *PutJobsIDDefinitionDefault) Code() int { - return o._statusCode -} - -func (o *PutJobsIDDefinitionDefault) Error() string { - return fmt.Sprintf("[PUT /jobs/{id}/definition][%d] PutJobsIDDefinition default", o._statusCode) -} - -func (o *PutJobsIDDefinitionDefault) String() string { - return fmt.Sprintf("[PUT /jobs/{id}/definition][%d] PutJobsIDDefinition default", o._statusCode) -} - -func (o *PutJobsIDDefinitionDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - return nil -} diff --git a/generated/client/jobs/put_jobs_id_status_parameters.go b/generated/client/jobs/put_jobs_id_status_parameters.go deleted file mode 100644 index 4bf43d4c..00000000 --- a/generated/client/jobs/put_jobs_id_status_parameters.go +++ /dev/null @@ -1,179 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "net/http" - "time" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" -) - -// NewPutJobsIDStatusParams creates a new PutJobsIDStatusParams object, -// with the default timeout for this client. -// -// Default values are not hydrated, since defaults are normally applied by the API server side. -// -// To enforce default values in parameter, use SetDefaults or WithDefaults. -func NewPutJobsIDStatusParams() *PutJobsIDStatusParams { - return &PutJobsIDStatusParams{ - timeout: cr.DefaultTimeout, - } -} - -// NewPutJobsIDStatusParamsWithTimeout creates a new PutJobsIDStatusParams object -// with the ability to set a timeout on a request. -func NewPutJobsIDStatusParamsWithTimeout(timeout time.Duration) *PutJobsIDStatusParams { - return &PutJobsIDStatusParams{ - timeout: timeout, - } -} - -// NewPutJobsIDStatusParamsWithContext creates a new PutJobsIDStatusParams object -// with the ability to set a context for a request. -func NewPutJobsIDStatusParamsWithContext(ctx context.Context) *PutJobsIDStatusParams { - return &PutJobsIDStatusParams{ - Context: ctx, - } -} - -// NewPutJobsIDStatusParamsWithHTTPClient creates a new PutJobsIDStatusParams object -// with the ability to set a custom HTTPClient for a request. -func NewPutJobsIDStatusParamsWithHTTPClient(client *http.Client) *PutJobsIDStatusParams { - return &PutJobsIDStatusParams{ - HTTPClient: client, - } -} - -/* -PutJobsIDStatusParams contains all the parameters to send to the API endpoint - - for the put jobs ID status operation. - - Typically these are written to a http.Request. -*/ -type PutJobsIDStatusParams struct { - - /* NewJobStatus. - - This contains the new job status - */ - NewJobStatus *model.JobStatus - - /* ID. - - Job ID - */ - ID string - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithDefaults hydrates default values in the put jobs ID status params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *PutJobsIDStatusParams) WithDefaults() *PutJobsIDStatusParams { - o.SetDefaults() - return o -} - -// SetDefaults hydrates default values in the put jobs ID status params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *PutJobsIDStatusParams) SetDefaults() { - // no default values defined for this parameter -} - -// WithTimeout adds the timeout to the put jobs ID status params -func (o *PutJobsIDStatusParams) WithTimeout(timeout time.Duration) *PutJobsIDStatusParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the put jobs ID status params -func (o *PutJobsIDStatusParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the put jobs ID status params -func (o *PutJobsIDStatusParams) WithContext(ctx context.Context) *PutJobsIDStatusParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the put jobs ID status params -func (o *PutJobsIDStatusParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the put jobs ID status params -func (o *PutJobsIDStatusParams) WithHTTPClient(client *http.Client) *PutJobsIDStatusParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the put jobs ID status params -func (o *PutJobsIDStatusParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithNewJobStatus adds the newJobStatus to the put jobs ID status params -func (o *PutJobsIDStatusParams) WithNewJobStatus(newJobStatus *model.JobStatus) *PutJobsIDStatusParams { - o.SetNewJobStatus(newJobStatus) - return o -} - -// SetNewJobStatus adds the newJobStatus to the put jobs ID status params -func (o *PutJobsIDStatusParams) SetNewJobStatus(newJobStatus *model.JobStatus) { - o.NewJobStatus = newJobStatus -} - -// WithID adds the id to the put jobs ID status params -func (o *PutJobsIDStatusParams) WithID(id string) *PutJobsIDStatusParams { - o.SetID(id) - return o -} - -// SetID adds the id to the put jobs ID status params -func (o *PutJobsIDStatusParams) SetID(id string) { - o.ID = id -} - -// WriteToRequest writes these params to a swagger request -func (o *PutJobsIDStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - if o.NewJobStatus != nil { - if err := r.SetBodyParam(o.NewJobStatus); err != nil { - return err - } - } - - // path param id - if err := r.SetPathParam("id", o.ID); err != nil { - return err - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/generated/client/jobs/put_jobs_id_status_responses.go b/generated/client/jobs/put_jobs_id_status_responses.go deleted file mode 100644 index 27bdc4fe..00000000 --- a/generated/client/jobs/put_jobs_id_status_responses.go +++ /dev/null @@ -1,328 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package jobs - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "encoding/json" - "fmt" - "io" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" -) - -// PutJobsIDStatusReader is a Reader for the PutJobsIDStatus structure. -type PutJobsIDStatusReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *PutJobsIDStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - case 200: - result := NewPutJobsIDStatusOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - case 400: - result := NewPutJobsIDStatusBadRequest() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - case 404: - result := NewPutJobsIDStatusNotFound() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - default: - result := NewPutJobsIDStatusDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewPutJobsIDStatusOK creates a PutJobsIDStatusOK with default headers values -func NewPutJobsIDStatusOK() *PutJobsIDStatusOK { - return &PutJobsIDStatusOK{} -} - -/* -PutJobsIDStatusOK describes a response with status code 200, with default header values. - -Job modified successfully -*/ -type PutJobsIDStatusOK struct { - Payload *model.JobStatus -} - -// IsSuccess returns true when this put jobs Id status o k response has a 2xx status code -func (o *PutJobsIDStatusOK) IsSuccess() bool { - return true -} - -// IsRedirect returns true when this put jobs Id status o k response has a 3xx status code -func (o *PutJobsIDStatusOK) IsRedirect() bool { - return false -} - -// IsClientError returns true when this put jobs Id status o k response has a 4xx status code -func (o *PutJobsIDStatusOK) IsClientError() bool { - return false -} - -// IsServerError returns true when this put jobs Id status o k response has a 5xx status code -func (o *PutJobsIDStatusOK) IsServerError() bool { - return false -} - -// IsCode returns true when this put jobs Id status o k response a status code equal to that given -func (o *PutJobsIDStatusOK) IsCode(code int) bool { - return code == 200 -} - -// Code gets the status code for the put jobs Id status o k response -func (o *PutJobsIDStatusOK) Code() int { - return 200 -} - -func (o *PutJobsIDStatusOK) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[PUT /jobs/{id}/status][%d] putJobsIdStatusOK %s", 200, payload) -} - -func (o *PutJobsIDStatusOK) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[PUT /jobs/{id}/status][%d] putJobsIdStatusOK %s", 200, payload) -} - -func (o *PutJobsIDStatusOK) GetPayload() *model.JobStatus { - return o.Payload -} - -func (o *PutJobsIDStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.JobStatus) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPutJobsIDStatusBadRequest creates a PutJobsIDStatusBadRequest with default headers values -func NewPutJobsIDStatusBadRequest() *PutJobsIDStatusBadRequest { - return &PutJobsIDStatusBadRequest{} -} - -/* -PutJobsIDStatusBadRequest describes a response with status code 400, with default header values. - -Bad Request -*/ -type PutJobsIDStatusBadRequest struct { - Payload *model.ErrorResponse -} - -// IsSuccess returns true when this put jobs Id status bad request response has a 2xx status code -func (o *PutJobsIDStatusBadRequest) IsSuccess() bool { - return false -} - -// IsRedirect returns true when this put jobs Id status bad request response has a 3xx status code -func (o *PutJobsIDStatusBadRequest) IsRedirect() bool { - return false -} - -// IsClientError returns true when this put jobs Id status bad request response has a 4xx status code -func (o *PutJobsIDStatusBadRequest) IsClientError() bool { - return true -} - -// IsServerError returns true when this put jobs Id status bad request response has a 5xx status code -func (o *PutJobsIDStatusBadRequest) IsServerError() bool { - return false -} - -// IsCode returns true when this put jobs Id status bad request response a status code equal to that given -func (o *PutJobsIDStatusBadRequest) IsCode(code int) bool { - return code == 400 -} - -// Code gets the status code for the put jobs Id status bad request response -func (o *PutJobsIDStatusBadRequest) Code() int { - return 400 -} - -func (o *PutJobsIDStatusBadRequest) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[PUT /jobs/{id}/status][%d] putJobsIdStatusBadRequest %s", 400, payload) -} - -func (o *PutJobsIDStatusBadRequest) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[PUT /jobs/{id}/status][%d] putJobsIdStatusBadRequest %s", 400, payload) -} - -func (o *PutJobsIDStatusBadRequest) GetPayload() *model.ErrorResponse { - return o.Payload -} - -func (o *PutJobsIDStatusBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.ErrorResponse) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPutJobsIDStatusNotFound creates a PutJobsIDStatusNotFound with default headers values -func NewPutJobsIDStatusNotFound() *PutJobsIDStatusNotFound { - return &PutJobsIDStatusNotFound{} -} - -/* -PutJobsIDStatusNotFound describes a response with status code 404, with default header values. - -Not Found -*/ -type PutJobsIDStatusNotFound struct { - Payload *model.ErrorResponse -} - -// IsSuccess returns true when this put jobs Id status not found response has a 2xx status code -func (o *PutJobsIDStatusNotFound) IsSuccess() bool { - return false -} - -// IsRedirect returns true when this put jobs Id status not found response has a 3xx status code -func (o *PutJobsIDStatusNotFound) IsRedirect() bool { - return false -} - -// IsClientError returns true when this put jobs Id status not found response has a 4xx status code -func (o *PutJobsIDStatusNotFound) IsClientError() bool { - return true -} - -// IsServerError returns true when this put jobs Id status not found response has a 5xx status code -func (o *PutJobsIDStatusNotFound) IsServerError() bool { - return false -} - -// IsCode returns true when this put jobs Id status not found response a status code equal to that given -func (o *PutJobsIDStatusNotFound) IsCode(code int) bool { - return code == 404 -} - -// Code gets the status code for the put jobs Id status not found response -func (o *PutJobsIDStatusNotFound) Code() int { - return 404 -} - -func (o *PutJobsIDStatusNotFound) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[PUT /jobs/{id}/status][%d] putJobsIdStatusNotFound %s", 404, payload) -} - -func (o *PutJobsIDStatusNotFound) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[PUT /jobs/{id}/status][%d] putJobsIdStatusNotFound %s", 404, payload) -} - -func (o *PutJobsIDStatusNotFound) GetPayload() *model.ErrorResponse { - return o.Payload -} - -func (o *PutJobsIDStatusNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.ErrorResponse) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPutJobsIDStatusDefault creates a PutJobsIDStatusDefault with default headers values -func NewPutJobsIDStatusDefault(code int) *PutJobsIDStatusDefault { - return &PutJobsIDStatusDefault{ - _statusCode: code, - } -} - -/* -PutJobsIDStatusDefault describes a response with status code -1, with default header values. - -Other error with any status code and response body format. -*/ -type PutJobsIDStatusDefault struct { - _statusCode int -} - -// IsSuccess returns true when this put jobs ID status default response has a 2xx status code -func (o *PutJobsIDStatusDefault) IsSuccess() bool { - return o._statusCode/100 == 2 -} - -// IsRedirect returns true when this put jobs ID status default response has a 3xx status code -func (o *PutJobsIDStatusDefault) IsRedirect() bool { - return o._statusCode/100 == 3 -} - -// IsClientError returns true when this put jobs ID status default response has a 4xx status code -func (o *PutJobsIDStatusDefault) IsClientError() bool { - return o._statusCode/100 == 4 -} - -// IsServerError returns true when this put jobs ID status default response has a 5xx status code -func (o *PutJobsIDStatusDefault) IsServerError() bool { - return o._statusCode/100 == 5 -} - -// IsCode returns true when this put jobs ID status default response a status code equal to that given -func (o *PutJobsIDStatusDefault) IsCode(code int) bool { - return o._statusCode == code -} - -// Code gets the status code for the put jobs ID status default response -func (o *PutJobsIDStatusDefault) Code() int { - return o._statusCode -} - -func (o *PutJobsIDStatusDefault) Error() string { - return fmt.Sprintf("[PUT /jobs/{id}/status][%d] PutJobsIDStatus default", o._statusCode) -} - -func (o *PutJobsIDStatusDefault) String() string { - return fmt.Sprintf("[PUT /jobs/{id}/status][%d] PutJobsIDStatus default", o._statusCode) -} - -func (o *PutJobsIDStatusDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - return nil -} diff --git a/generated/client/workflow_executor_client.go b/generated/client/workflow_executor_client.go deleted file mode 100644 index 02807b21..00000000 --- a/generated/client/workflow_executor_client.go +++ /dev/null @@ -1,122 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package client - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "github.com/go-openapi/runtime" - httptransport "github.com/go-openapi/runtime/client" - "github.com/go-openapi/strfmt" - - "github.com/siemens/wfx/generated/client/jobs" - "github.com/siemens/wfx/generated/client/workflows" -) - -// Default workflow executor HTTP client. -var Default = NewHTTPClient(nil) - -const ( - // DefaultHost is the default Host - // found in Meta (info) section of spec file - DefaultHost string = "localhost" - // DefaultBasePath is the default BasePath - // found in Meta (info) section of spec file - DefaultBasePath string = "/api/wfx/v1" -) - -// DefaultSchemes are the default schemes found in Meta (info) section of spec file -var DefaultSchemes = []string{"http"} - -// NewHTTPClient creates a new workflow executor HTTP client. -func NewHTTPClient(formats strfmt.Registry) *WorkflowExecutor { - return NewHTTPClientWithConfig(formats, nil) -} - -// NewHTTPClientWithConfig creates a new workflow executor HTTP client, -// using a customizable transport config. -func NewHTTPClientWithConfig(formats strfmt.Registry, cfg *TransportConfig) *WorkflowExecutor { - // ensure nullable parameters have default - if cfg == nil { - cfg = DefaultTransportConfig() - } - - // create transport and client - transport := httptransport.New(cfg.Host, cfg.BasePath, cfg.Schemes) - return New(transport, formats) -} - -// New creates a new workflow executor client -func New(transport runtime.ClientTransport, formats strfmt.Registry) *WorkflowExecutor { - // ensure nullable parameters have default - if formats == nil { - formats = strfmt.Default - } - - cli := new(WorkflowExecutor) - cli.Transport = transport - cli.Jobs = jobs.New(transport, formats) - cli.Workflows = workflows.New(transport, formats) - return cli -} - -// DefaultTransportConfig creates a TransportConfig with the -// default settings taken from the meta section of the spec file. -func DefaultTransportConfig() *TransportConfig { - return &TransportConfig{ - Host: DefaultHost, - BasePath: DefaultBasePath, - Schemes: DefaultSchemes, - } -} - -// TransportConfig contains the transport related info, -// found in the meta section of the spec file. -type TransportConfig struct { - Host string - BasePath string - Schemes []string -} - -// WithHost overrides the default host, -// provided by the meta section of the spec file. -func (cfg *TransportConfig) WithHost(host string) *TransportConfig { - cfg.Host = host - return cfg -} - -// WithBasePath overrides the default basePath, -// provided by the meta section of the spec file. -func (cfg *TransportConfig) WithBasePath(basePath string) *TransportConfig { - cfg.BasePath = basePath - return cfg -} - -// WithSchemes overrides the default schemes, -// provided by the meta section of the spec file. -func (cfg *TransportConfig) WithSchemes(schemes []string) *TransportConfig { - cfg.Schemes = schemes - return cfg -} - -// WorkflowExecutor is a client for workflow executor -type WorkflowExecutor struct { - Jobs jobs.ClientService - - Workflows workflows.ClientService - - Transport runtime.ClientTransport -} - -// SetTransport changes the transport on the client and all its subresources -func (c *WorkflowExecutor) SetTransport(transport runtime.ClientTransport) { - c.Transport = transport - c.Jobs.SetTransport(transport) - c.Workflows.SetTransport(transport) -} diff --git a/generated/client/workflows/delete_workflows_name_parameters.go b/generated/client/workflows/delete_workflows_name_parameters.go deleted file mode 100644 index 2e030d76..00000000 --- a/generated/client/workflows/delete_workflows_name_parameters.go +++ /dev/null @@ -1,156 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package workflows - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "net/http" - "time" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - "github.com/go-openapi/strfmt" -) - -// NewDeleteWorkflowsNameParams creates a new DeleteWorkflowsNameParams object, -// with the default timeout for this client. -// -// Default values are not hydrated, since defaults are normally applied by the API server side. -// -// To enforce default values in parameter, use SetDefaults or WithDefaults. -func NewDeleteWorkflowsNameParams() *DeleteWorkflowsNameParams { - return &DeleteWorkflowsNameParams{ - timeout: cr.DefaultTimeout, - } -} - -// NewDeleteWorkflowsNameParamsWithTimeout creates a new DeleteWorkflowsNameParams object -// with the ability to set a timeout on a request. -func NewDeleteWorkflowsNameParamsWithTimeout(timeout time.Duration) *DeleteWorkflowsNameParams { - return &DeleteWorkflowsNameParams{ - timeout: timeout, - } -} - -// NewDeleteWorkflowsNameParamsWithContext creates a new DeleteWorkflowsNameParams object -// with the ability to set a context for a request. -func NewDeleteWorkflowsNameParamsWithContext(ctx context.Context) *DeleteWorkflowsNameParams { - return &DeleteWorkflowsNameParams{ - Context: ctx, - } -} - -// NewDeleteWorkflowsNameParamsWithHTTPClient creates a new DeleteWorkflowsNameParams object -// with the ability to set a custom HTTPClient for a request. -func NewDeleteWorkflowsNameParamsWithHTTPClient(client *http.Client) *DeleteWorkflowsNameParams { - return &DeleteWorkflowsNameParams{ - HTTPClient: client, - } -} - -/* -DeleteWorkflowsNameParams contains all the parameters to send to the API endpoint - - for the delete workflows name operation. - - Typically these are written to a http.Request. -*/ -type DeleteWorkflowsNameParams struct { - - /* Name. - - Workflow name - */ - Name string - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithDefaults hydrates default values in the delete workflows name params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *DeleteWorkflowsNameParams) WithDefaults() *DeleteWorkflowsNameParams { - o.SetDefaults() - return o -} - -// SetDefaults hydrates default values in the delete workflows name params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *DeleteWorkflowsNameParams) SetDefaults() { - // no default values defined for this parameter -} - -// WithTimeout adds the timeout to the delete workflows name params -func (o *DeleteWorkflowsNameParams) WithTimeout(timeout time.Duration) *DeleteWorkflowsNameParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the delete workflows name params -func (o *DeleteWorkflowsNameParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the delete workflows name params -func (o *DeleteWorkflowsNameParams) WithContext(ctx context.Context) *DeleteWorkflowsNameParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the delete workflows name params -func (o *DeleteWorkflowsNameParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the delete workflows name params -func (o *DeleteWorkflowsNameParams) WithHTTPClient(client *http.Client) *DeleteWorkflowsNameParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the delete workflows name params -func (o *DeleteWorkflowsNameParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithName adds the name to the delete workflows name params -func (o *DeleteWorkflowsNameParams) WithName(name string) *DeleteWorkflowsNameParams { - o.SetName(name) - return o -} - -// SetName adds the name to the delete workflows name params -func (o *DeleteWorkflowsNameParams) SetName(name string) { - o.Name = name -} - -// WriteToRequest writes these params to a swagger request -func (o *DeleteWorkflowsNameParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - // path param name - if err := r.SetPathParam("name", o.Name); err != nil { - return err - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/generated/client/workflows/delete_workflows_name_responses.go b/generated/client/workflows/delete_workflows_name_responses.go deleted file mode 100644 index 0e945f35..00000000 --- a/generated/client/workflows/delete_workflows_name_responses.go +++ /dev/null @@ -1,238 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package workflows - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "encoding/json" - "fmt" - "io" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" -) - -// DeleteWorkflowsNameReader is a Reader for the DeleteWorkflowsName structure. -type DeleteWorkflowsNameReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *DeleteWorkflowsNameReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - case 204: - result := NewDeleteWorkflowsNameNoContent() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - case 404: - result := NewDeleteWorkflowsNameNotFound() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - default: - result := NewDeleteWorkflowsNameDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewDeleteWorkflowsNameNoContent creates a DeleteWorkflowsNameNoContent with default headers values -func NewDeleteWorkflowsNameNoContent() *DeleteWorkflowsNameNoContent { - return &DeleteWorkflowsNameNoContent{} -} - -/* -DeleteWorkflowsNameNoContent describes a response with status code 204, with default header values. - -The workflow has been deleted. -*/ -type DeleteWorkflowsNameNoContent struct { -} - -// IsSuccess returns true when this delete workflows name no content response has a 2xx status code -func (o *DeleteWorkflowsNameNoContent) IsSuccess() bool { - return true -} - -// IsRedirect returns true when this delete workflows name no content response has a 3xx status code -func (o *DeleteWorkflowsNameNoContent) IsRedirect() bool { - return false -} - -// IsClientError returns true when this delete workflows name no content response has a 4xx status code -func (o *DeleteWorkflowsNameNoContent) IsClientError() bool { - return false -} - -// IsServerError returns true when this delete workflows name no content response has a 5xx status code -func (o *DeleteWorkflowsNameNoContent) IsServerError() bool { - return false -} - -// IsCode returns true when this delete workflows name no content response a status code equal to that given -func (o *DeleteWorkflowsNameNoContent) IsCode(code int) bool { - return code == 204 -} - -// Code gets the status code for the delete workflows name no content response -func (o *DeleteWorkflowsNameNoContent) Code() int { - return 204 -} - -func (o *DeleteWorkflowsNameNoContent) Error() string { - return fmt.Sprintf("[DELETE /workflows/{name}][%d] deleteWorkflowsNameNoContent", 204) -} - -func (o *DeleteWorkflowsNameNoContent) String() string { - return fmt.Sprintf("[DELETE /workflows/{name}][%d] deleteWorkflowsNameNoContent", 204) -} - -func (o *DeleteWorkflowsNameNoContent) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - return nil -} - -// NewDeleteWorkflowsNameNotFound creates a DeleteWorkflowsNameNotFound with default headers values -func NewDeleteWorkflowsNameNotFound() *DeleteWorkflowsNameNotFound { - return &DeleteWorkflowsNameNotFound{} -} - -/* -DeleteWorkflowsNameNotFound describes a response with status code 404, with default header values. - -Not Found -*/ -type DeleteWorkflowsNameNotFound struct { - Payload *model.ErrorResponse -} - -// IsSuccess returns true when this delete workflows name not found response has a 2xx status code -func (o *DeleteWorkflowsNameNotFound) IsSuccess() bool { - return false -} - -// IsRedirect returns true when this delete workflows name not found response has a 3xx status code -func (o *DeleteWorkflowsNameNotFound) IsRedirect() bool { - return false -} - -// IsClientError returns true when this delete workflows name not found response has a 4xx status code -func (o *DeleteWorkflowsNameNotFound) IsClientError() bool { - return true -} - -// IsServerError returns true when this delete workflows name not found response has a 5xx status code -func (o *DeleteWorkflowsNameNotFound) IsServerError() bool { - return false -} - -// IsCode returns true when this delete workflows name not found response a status code equal to that given -func (o *DeleteWorkflowsNameNotFound) IsCode(code int) bool { - return code == 404 -} - -// Code gets the status code for the delete workflows name not found response -func (o *DeleteWorkflowsNameNotFound) Code() int { - return 404 -} - -func (o *DeleteWorkflowsNameNotFound) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[DELETE /workflows/{name}][%d] deleteWorkflowsNameNotFound %s", 404, payload) -} - -func (o *DeleteWorkflowsNameNotFound) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[DELETE /workflows/{name}][%d] deleteWorkflowsNameNotFound %s", 404, payload) -} - -func (o *DeleteWorkflowsNameNotFound) GetPayload() *model.ErrorResponse { - return o.Payload -} - -func (o *DeleteWorkflowsNameNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.ErrorResponse) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewDeleteWorkflowsNameDefault creates a DeleteWorkflowsNameDefault with default headers values -func NewDeleteWorkflowsNameDefault(code int) *DeleteWorkflowsNameDefault { - return &DeleteWorkflowsNameDefault{ - _statusCode: code, - } -} - -/* -DeleteWorkflowsNameDefault describes a response with status code -1, with default header values. - -Other error with any status code and response body format. -*/ -type DeleteWorkflowsNameDefault struct { - _statusCode int -} - -// IsSuccess returns true when this delete workflows name default response has a 2xx status code -func (o *DeleteWorkflowsNameDefault) IsSuccess() bool { - return o._statusCode/100 == 2 -} - -// IsRedirect returns true when this delete workflows name default response has a 3xx status code -func (o *DeleteWorkflowsNameDefault) IsRedirect() bool { - return o._statusCode/100 == 3 -} - -// IsClientError returns true when this delete workflows name default response has a 4xx status code -func (o *DeleteWorkflowsNameDefault) IsClientError() bool { - return o._statusCode/100 == 4 -} - -// IsServerError returns true when this delete workflows name default response has a 5xx status code -func (o *DeleteWorkflowsNameDefault) IsServerError() bool { - return o._statusCode/100 == 5 -} - -// IsCode returns true when this delete workflows name default response a status code equal to that given -func (o *DeleteWorkflowsNameDefault) IsCode(code int) bool { - return o._statusCode == code -} - -// Code gets the status code for the delete workflows name default response -func (o *DeleteWorkflowsNameDefault) Code() int { - return o._statusCode -} - -func (o *DeleteWorkflowsNameDefault) Error() string { - return fmt.Sprintf("[DELETE /workflows/{name}][%d] DeleteWorkflowsName default", o._statusCode) -} - -func (o *DeleteWorkflowsNameDefault) String() string { - return fmt.Sprintf("[DELETE /workflows/{name}][%d] DeleteWorkflowsName default", o._statusCode) -} - -func (o *DeleteWorkflowsNameDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - return nil -} diff --git a/generated/client/workflows/get_workflows_name_parameters.go b/generated/client/workflows/get_workflows_name_parameters.go deleted file mode 100644 index 0c0626fb..00000000 --- a/generated/client/workflows/get_workflows_name_parameters.go +++ /dev/null @@ -1,156 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package workflows - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "net/http" - "time" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - "github.com/go-openapi/strfmt" -) - -// NewGetWorkflowsNameParams creates a new GetWorkflowsNameParams object, -// with the default timeout for this client. -// -// Default values are not hydrated, since defaults are normally applied by the API server side. -// -// To enforce default values in parameter, use SetDefaults or WithDefaults. -func NewGetWorkflowsNameParams() *GetWorkflowsNameParams { - return &GetWorkflowsNameParams{ - timeout: cr.DefaultTimeout, - } -} - -// NewGetWorkflowsNameParamsWithTimeout creates a new GetWorkflowsNameParams object -// with the ability to set a timeout on a request. -func NewGetWorkflowsNameParamsWithTimeout(timeout time.Duration) *GetWorkflowsNameParams { - return &GetWorkflowsNameParams{ - timeout: timeout, - } -} - -// NewGetWorkflowsNameParamsWithContext creates a new GetWorkflowsNameParams object -// with the ability to set a context for a request. -func NewGetWorkflowsNameParamsWithContext(ctx context.Context) *GetWorkflowsNameParams { - return &GetWorkflowsNameParams{ - Context: ctx, - } -} - -// NewGetWorkflowsNameParamsWithHTTPClient creates a new GetWorkflowsNameParams object -// with the ability to set a custom HTTPClient for a request. -func NewGetWorkflowsNameParamsWithHTTPClient(client *http.Client) *GetWorkflowsNameParams { - return &GetWorkflowsNameParams{ - HTTPClient: client, - } -} - -/* -GetWorkflowsNameParams contains all the parameters to send to the API endpoint - - for the get workflows name operation. - - Typically these are written to a http.Request. -*/ -type GetWorkflowsNameParams struct { - - /* Name. - - Unique name for the workflow - */ - Name string - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithDefaults hydrates default values in the get workflows name params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *GetWorkflowsNameParams) WithDefaults() *GetWorkflowsNameParams { - o.SetDefaults() - return o -} - -// SetDefaults hydrates default values in the get workflows name params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *GetWorkflowsNameParams) SetDefaults() { - // no default values defined for this parameter -} - -// WithTimeout adds the timeout to the get workflows name params -func (o *GetWorkflowsNameParams) WithTimeout(timeout time.Duration) *GetWorkflowsNameParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the get workflows name params -func (o *GetWorkflowsNameParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the get workflows name params -func (o *GetWorkflowsNameParams) WithContext(ctx context.Context) *GetWorkflowsNameParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the get workflows name params -func (o *GetWorkflowsNameParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the get workflows name params -func (o *GetWorkflowsNameParams) WithHTTPClient(client *http.Client) *GetWorkflowsNameParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the get workflows name params -func (o *GetWorkflowsNameParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithName adds the name to the get workflows name params -func (o *GetWorkflowsNameParams) WithName(name string) *GetWorkflowsNameParams { - o.SetName(name) - return o -} - -// SetName adds the name to the get workflows name params -func (o *GetWorkflowsNameParams) SetName(name string) { - o.Name = name -} - -// WriteToRequest writes these params to a swagger request -func (o *GetWorkflowsNameParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - // path param name - if err := r.SetPathParam("name", o.Name); err != nil { - return err - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/generated/client/workflows/get_workflows_name_responses.go b/generated/client/workflows/get_workflows_name_responses.go deleted file mode 100644 index 8d3ab3a0..00000000 --- a/generated/client/workflows/get_workflows_name_responses.go +++ /dev/null @@ -1,328 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package workflows - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "encoding/json" - "fmt" - "io" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" -) - -// GetWorkflowsNameReader is a Reader for the GetWorkflowsName structure. -type GetWorkflowsNameReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *GetWorkflowsNameReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - case 200: - result := NewGetWorkflowsNameOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - case 400: - result := NewGetWorkflowsNameBadRequest() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - case 404: - result := NewGetWorkflowsNameNotFound() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - default: - result := NewGetWorkflowsNameDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewGetWorkflowsNameOK creates a GetWorkflowsNameOK with default headers values -func NewGetWorkflowsNameOK() *GetWorkflowsNameOK { - return &GetWorkflowsNameOK{} -} - -/* -GetWorkflowsNameOK describes a response with status code 200, with default header values. - -Workflow description with the provided key -*/ -type GetWorkflowsNameOK struct { - Payload *model.Workflow -} - -// IsSuccess returns true when this get workflows name o k response has a 2xx status code -func (o *GetWorkflowsNameOK) IsSuccess() bool { - return true -} - -// IsRedirect returns true when this get workflows name o k response has a 3xx status code -func (o *GetWorkflowsNameOK) IsRedirect() bool { - return false -} - -// IsClientError returns true when this get workflows name o k response has a 4xx status code -func (o *GetWorkflowsNameOK) IsClientError() bool { - return false -} - -// IsServerError returns true when this get workflows name o k response has a 5xx status code -func (o *GetWorkflowsNameOK) IsServerError() bool { - return false -} - -// IsCode returns true when this get workflows name o k response a status code equal to that given -func (o *GetWorkflowsNameOK) IsCode(code int) bool { - return code == 200 -} - -// Code gets the status code for the get workflows name o k response -func (o *GetWorkflowsNameOK) Code() int { - return 200 -} - -func (o *GetWorkflowsNameOK) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /workflows/{name}][%d] getWorkflowsNameOK %s", 200, payload) -} - -func (o *GetWorkflowsNameOK) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /workflows/{name}][%d] getWorkflowsNameOK %s", 200, payload) -} - -func (o *GetWorkflowsNameOK) GetPayload() *model.Workflow { - return o.Payload -} - -func (o *GetWorkflowsNameOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.Workflow) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetWorkflowsNameBadRequest creates a GetWorkflowsNameBadRequest with default headers values -func NewGetWorkflowsNameBadRequest() *GetWorkflowsNameBadRequest { - return &GetWorkflowsNameBadRequest{} -} - -/* -GetWorkflowsNameBadRequest describes a response with status code 400, with default header values. - -If request is invalid -*/ -type GetWorkflowsNameBadRequest struct { - Payload *model.ErrorResponse -} - -// IsSuccess returns true when this get workflows name bad request response has a 2xx status code -func (o *GetWorkflowsNameBadRequest) IsSuccess() bool { - return false -} - -// IsRedirect returns true when this get workflows name bad request response has a 3xx status code -func (o *GetWorkflowsNameBadRequest) IsRedirect() bool { - return false -} - -// IsClientError returns true when this get workflows name bad request response has a 4xx status code -func (o *GetWorkflowsNameBadRequest) IsClientError() bool { - return true -} - -// IsServerError returns true when this get workflows name bad request response has a 5xx status code -func (o *GetWorkflowsNameBadRequest) IsServerError() bool { - return false -} - -// IsCode returns true when this get workflows name bad request response a status code equal to that given -func (o *GetWorkflowsNameBadRequest) IsCode(code int) bool { - return code == 400 -} - -// Code gets the status code for the get workflows name bad request response -func (o *GetWorkflowsNameBadRequest) Code() int { - return 400 -} - -func (o *GetWorkflowsNameBadRequest) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /workflows/{name}][%d] getWorkflowsNameBadRequest %s", 400, payload) -} - -func (o *GetWorkflowsNameBadRequest) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /workflows/{name}][%d] getWorkflowsNameBadRequest %s", 400, payload) -} - -func (o *GetWorkflowsNameBadRequest) GetPayload() *model.ErrorResponse { - return o.Payload -} - -func (o *GetWorkflowsNameBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.ErrorResponse) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetWorkflowsNameNotFound creates a GetWorkflowsNameNotFound with default headers values -func NewGetWorkflowsNameNotFound() *GetWorkflowsNameNotFound { - return &GetWorkflowsNameNotFound{} -} - -/* -GetWorkflowsNameNotFound describes a response with status code 404, with default header values. - -Not Found -*/ -type GetWorkflowsNameNotFound struct { - Payload *model.ErrorResponse -} - -// IsSuccess returns true when this get workflows name not found response has a 2xx status code -func (o *GetWorkflowsNameNotFound) IsSuccess() bool { - return false -} - -// IsRedirect returns true when this get workflows name not found response has a 3xx status code -func (o *GetWorkflowsNameNotFound) IsRedirect() bool { - return false -} - -// IsClientError returns true when this get workflows name not found response has a 4xx status code -func (o *GetWorkflowsNameNotFound) IsClientError() bool { - return true -} - -// IsServerError returns true when this get workflows name not found response has a 5xx status code -func (o *GetWorkflowsNameNotFound) IsServerError() bool { - return false -} - -// IsCode returns true when this get workflows name not found response a status code equal to that given -func (o *GetWorkflowsNameNotFound) IsCode(code int) bool { - return code == 404 -} - -// Code gets the status code for the get workflows name not found response -func (o *GetWorkflowsNameNotFound) Code() int { - return 404 -} - -func (o *GetWorkflowsNameNotFound) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /workflows/{name}][%d] getWorkflowsNameNotFound %s", 404, payload) -} - -func (o *GetWorkflowsNameNotFound) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /workflows/{name}][%d] getWorkflowsNameNotFound %s", 404, payload) -} - -func (o *GetWorkflowsNameNotFound) GetPayload() *model.ErrorResponse { - return o.Payload -} - -func (o *GetWorkflowsNameNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.ErrorResponse) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetWorkflowsNameDefault creates a GetWorkflowsNameDefault with default headers values -func NewGetWorkflowsNameDefault(code int) *GetWorkflowsNameDefault { - return &GetWorkflowsNameDefault{ - _statusCode: code, - } -} - -/* -GetWorkflowsNameDefault describes a response with status code -1, with default header values. - -Other error with any status code and response body format. -*/ -type GetWorkflowsNameDefault struct { - _statusCode int -} - -// IsSuccess returns true when this get workflows name default response has a 2xx status code -func (o *GetWorkflowsNameDefault) IsSuccess() bool { - return o._statusCode/100 == 2 -} - -// IsRedirect returns true when this get workflows name default response has a 3xx status code -func (o *GetWorkflowsNameDefault) IsRedirect() bool { - return o._statusCode/100 == 3 -} - -// IsClientError returns true when this get workflows name default response has a 4xx status code -func (o *GetWorkflowsNameDefault) IsClientError() bool { - return o._statusCode/100 == 4 -} - -// IsServerError returns true when this get workflows name default response has a 5xx status code -func (o *GetWorkflowsNameDefault) IsServerError() bool { - return o._statusCode/100 == 5 -} - -// IsCode returns true when this get workflows name default response a status code equal to that given -func (o *GetWorkflowsNameDefault) IsCode(code int) bool { - return o._statusCode == code -} - -// Code gets the status code for the get workflows name default response -func (o *GetWorkflowsNameDefault) Code() int { - return o._statusCode -} - -func (o *GetWorkflowsNameDefault) Error() string { - return fmt.Sprintf("[GET /workflows/{name}][%d] GetWorkflowsName default", o._statusCode) -} - -func (o *GetWorkflowsNameDefault) String() string { - return fmt.Sprintf("[GET /workflows/{name}][%d] GetWorkflowsName default", o._statusCode) -} - -func (o *GetWorkflowsNameDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - return nil -} diff --git a/generated/client/workflows/get_workflows_parameters.go b/generated/client/workflows/get_workflows_parameters.go deleted file mode 100644 index 19d669ff..00000000 --- a/generated/client/workflows/get_workflows_parameters.go +++ /dev/null @@ -1,261 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package workflows - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "net/http" - "time" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// NewGetWorkflowsParams creates a new GetWorkflowsParams object, -// with the default timeout for this client. -// -// Default values are not hydrated, since defaults are normally applied by the API server side. -// -// To enforce default values in parameter, use SetDefaults or WithDefaults. -func NewGetWorkflowsParams() *GetWorkflowsParams { - return &GetWorkflowsParams{ - timeout: cr.DefaultTimeout, - } -} - -// NewGetWorkflowsParamsWithTimeout creates a new GetWorkflowsParams object -// with the ability to set a timeout on a request. -func NewGetWorkflowsParamsWithTimeout(timeout time.Duration) *GetWorkflowsParams { - return &GetWorkflowsParams{ - timeout: timeout, - } -} - -// NewGetWorkflowsParamsWithContext creates a new GetWorkflowsParams object -// with the ability to set a context for a request. -func NewGetWorkflowsParamsWithContext(ctx context.Context) *GetWorkflowsParams { - return &GetWorkflowsParams{ - Context: ctx, - } -} - -// NewGetWorkflowsParamsWithHTTPClient creates a new GetWorkflowsParams object -// with the ability to set a custom HTTPClient for a request. -func NewGetWorkflowsParamsWithHTTPClient(client *http.Client) *GetWorkflowsParams { - return &GetWorkflowsParams{ - HTTPClient: client, - } -} - -/* -GetWorkflowsParams contains all the parameters to send to the API endpoint - - for the get workflows operation. - - Typically these are written to a http.Request. -*/ -type GetWorkflowsParams struct { - - /* Limit. - - the maximum number of items to return - - Format: int32 - Default: 10 - */ - Limit *int32 - - /* Offset. - - the number of items to skip before starting to return results - - Format: int64 - */ - Offset *int64 - - /* Sort. - - the order of returned elements - - Default: "asc" - */ - Sort *string - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithDefaults hydrates default values in the get workflows params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *GetWorkflowsParams) WithDefaults() *GetWorkflowsParams { - o.SetDefaults() - return o -} - -// SetDefaults hydrates default values in the get workflows params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *GetWorkflowsParams) SetDefaults() { - var ( - limitDefault = int32(10) - - offsetDefault = int64(0) - - sortDefault = string("asc") - ) - - val := GetWorkflowsParams{ - Limit: &limitDefault, - Offset: &offsetDefault, - Sort: &sortDefault, - } - - val.timeout = o.timeout - val.Context = o.Context - val.HTTPClient = o.HTTPClient - *o = val -} - -// WithTimeout adds the timeout to the get workflows params -func (o *GetWorkflowsParams) WithTimeout(timeout time.Duration) *GetWorkflowsParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the get workflows params -func (o *GetWorkflowsParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the get workflows params -func (o *GetWorkflowsParams) WithContext(ctx context.Context) *GetWorkflowsParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the get workflows params -func (o *GetWorkflowsParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the get workflows params -func (o *GetWorkflowsParams) WithHTTPClient(client *http.Client) *GetWorkflowsParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the get workflows params -func (o *GetWorkflowsParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithLimit adds the limit to the get workflows params -func (o *GetWorkflowsParams) WithLimit(limit *int32) *GetWorkflowsParams { - o.SetLimit(limit) - return o -} - -// SetLimit adds the limit to the get workflows params -func (o *GetWorkflowsParams) SetLimit(limit *int32) { - o.Limit = limit -} - -// WithOffset adds the offset to the get workflows params -func (o *GetWorkflowsParams) WithOffset(offset *int64) *GetWorkflowsParams { - o.SetOffset(offset) - return o -} - -// SetOffset adds the offset to the get workflows params -func (o *GetWorkflowsParams) SetOffset(offset *int64) { - o.Offset = offset -} - -// WithSort adds the sort to the get workflows params -func (o *GetWorkflowsParams) WithSort(sort *string) *GetWorkflowsParams { - o.SetSort(sort) - return o -} - -// SetSort adds the sort to the get workflows params -func (o *GetWorkflowsParams) SetSort(sort *string) { - o.Sort = sort -} - -// WriteToRequest writes these params to a swagger request -func (o *GetWorkflowsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - if o.Limit != nil { - - // query param limit - var qrLimit int32 - - if o.Limit != nil { - qrLimit = *o.Limit - } - qLimit := swag.FormatInt32(qrLimit) - if qLimit != "" { - - if err := r.SetQueryParam("limit", qLimit); err != nil { - return err - } - } - } - - if o.Offset != nil { - - // query param offset - var qrOffset int64 - - if o.Offset != nil { - qrOffset = *o.Offset - } - qOffset := swag.FormatInt64(qrOffset) - if qOffset != "" { - - if err := r.SetQueryParam("offset", qOffset); err != nil { - return err - } - } - } - - if o.Sort != nil { - - // query param sort - var qrSort string - - if o.Sort != nil { - qrSort = *o.Sort - } - qSort := qrSort - if qSort != "" { - - if err := r.SetQueryParam("sort", qSort); err != nil { - return err - } - } - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/generated/client/workflows/get_workflows_responses.go b/generated/client/workflows/get_workflows_responses.go deleted file mode 100644 index aa6d0e83..00000000 --- a/generated/client/workflows/get_workflows_responses.go +++ /dev/null @@ -1,176 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package workflows - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "encoding/json" - "fmt" - "io" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" -) - -// GetWorkflowsReader is a Reader for the GetWorkflows structure. -type GetWorkflowsReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *GetWorkflowsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - case 200: - result := NewGetWorkflowsOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - default: - result := NewGetWorkflowsDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewGetWorkflowsOK creates a GetWorkflowsOK with default headers values -func NewGetWorkflowsOK() *GetWorkflowsOK { - return &GetWorkflowsOK{} -} - -/* -GetWorkflowsOK describes a response with status code 200, with default header values. - -A list of workflows -*/ -type GetWorkflowsOK struct { - Payload *model.PaginatedWorkflowList -} - -// IsSuccess returns true when this get workflows o k response has a 2xx status code -func (o *GetWorkflowsOK) IsSuccess() bool { - return true -} - -// IsRedirect returns true when this get workflows o k response has a 3xx status code -func (o *GetWorkflowsOK) IsRedirect() bool { - return false -} - -// IsClientError returns true when this get workflows o k response has a 4xx status code -func (o *GetWorkflowsOK) IsClientError() bool { - return false -} - -// IsServerError returns true when this get workflows o k response has a 5xx status code -func (o *GetWorkflowsOK) IsServerError() bool { - return false -} - -// IsCode returns true when this get workflows o k response a status code equal to that given -func (o *GetWorkflowsOK) IsCode(code int) bool { - return code == 200 -} - -// Code gets the status code for the get workflows o k response -func (o *GetWorkflowsOK) Code() int { - return 200 -} - -func (o *GetWorkflowsOK) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /workflows][%d] getWorkflowsOK %s", 200, payload) -} - -func (o *GetWorkflowsOK) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[GET /workflows][%d] getWorkflowsOK %s", 200, payload) -} - -func (o *GetWorkflowsOK) GetPayload() *model.PaginatedWorkflowList { - return o.Payload -} - -func (o *GetWorkflowsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.PaginatedWorkflowList) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetWorkflowsDefault creates a GetWorkflowsDefault with default headers values -func NewGetWorkflowsDefault(code int) *GetWorkflowsDefault { - return &GetWorkflowsDefault{ - _statusCode: code, - } -} - -/* -GetWorkflowsDefault describes a response with status code -1, with default header values. - -Other error with any status code and response body format. -*/ -type GetWorkflowsDefault struct { - _statusCode int -} - -// IsSuccess returns true when this get workflows default response has a 2xx status code -func (o *GetWorkflowsDefault) IsSuccess() bool { - return o._statusCode/100 == 2 -} - -// IsRedirect returns true when this get workflows default response has a 3xx status code -func (o *GetWorkflowsDefault) IsRedirect() bool { - return o._statusCode/100 == 3 -} - -// IsClientError returns true when this get workflows default response has a 4xx status code -func (o *GetWorkflowsDefault) IsClientError() bool { - return o._statusCode/100 == 4 -} - -// IsServerError returns true when this get workflows default response has a 5xx status code -func (o *GetWorkflowsDefault) IsServerError() bool { - return o._statusCode/100 == 5 -} - -// IsCode returns true when this get workflows default response a status code equal to that given -func (o *GetWorkflowsDefault) IsCode(code int) bool { - return o._statusCode == code -} - -// Code gets the status code for the get workflows default response -func (o *GetWorkflowsDefault) Code() int { - return o._statusCode -} - -func (o *GetWorkflowsDefault) Error() string { - return fmt.Sprintf("[GET /workflows][%d] GetWorkflows default", o._statusCode) -} - -func (o *GetWorkflowsDefault) String() string { - return fmt.Sprintf("[GET /workflows][%d] GetWorkflows default", o._statusCode) -} - -func (o *GetWorkflowsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - return nil -} diff --git a/generated/client/workflows/post_workflows_parameters.go b/generated/client/workflows/post_workflows_parameters.go deleted file mode 100644 index 6e29f734..00000000 --- a/generated/client/workflows/post_workflows_parameters.go +++ /dev/null @@ -1,157 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package workflows - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "net/http" - "time" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" -) - -// NewPostWorkflowsParams creates a new PostWorkflowsParams object, -// with the default timeout for this client. -// -// Default values are not hydrated, since defaults are normally applied by the API server side. -// -// To enforce default values in parameter, use SetDefaults or WithDefaults. -func NewPostWorkflowsParams() *PostWorkflowsParams { - return &PostWorkflowsParams{ - timeout: cr.DefaultTimeout, - } -} - -// NewPostWorkflowsParamsWithTimeout creates a new PostWorkflowsParams object -// with the ability to set a timeout on a request. -func NewPostWorkflowsParamsWithTimeout(timeout time.Duration) *PostWorkflowsParams { - return &PostWorkflowsParams{ - timeout: timeout, - } -} - -// NewPostWorkflowsParamsWithContext creates a new PostWorkflowsParams object -// with the ability to set a context for a request. -func NewPostWorkflowsParamsWithContext(ctx context.Context) *PostWorkflowsParams { - return &PostWorkflowsParams{ - Context: ctx, - } -} - -// NewPostWorkflowsParamsWithHTTPClient creates a new PostWorkflowsParams object -// with the ability to set a custom HTTPClient for a request. -func NewPostWorkflowsParamsWithHTTPClient(client *http.Client) *PostWorkflowsParams { - return &PostWorkflowsParams{ - HTTPClient: client, - } -} - -/* -PostWorkflowsParams contains all the parameters to send to the API endpoint - - for the post workflows operation. - - Typically these are written to a http.Request. -*/ -type PostWorkflowsParams struct { - - /* Workflow. - - Workflow object to be added - */ - Workflow *model.Workflow - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithDefaults hydrates default values in the post workflows params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *PostWorkflowsParams) WithDefaults() *PostWorkflowsParams { - o.SetDefaults() - return o -} - -// SetDefaults hydrates default values in the post workflows params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *PostWorkflowsParams) SetDefaults() { - // no default values defined for this parameter -} - -// WithTimeout adds the timeout to the post workflows params -func (o *PostWorkflowsParams) WithTimeout(timeout time.Duration) *PostWorkflowsParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the post workflows params -func (o *PostWorkflowsParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the post workflows params -func (o *PostWorkflowsParams) WithContext(ctx context.Context) *PostWorkflowsParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the post workflows params -func (o *PostWorkflowsParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the post workflows params -func (o *PostWorkflowsParams) WithHTTPClient(client *http.Client) *PostWorkflowsParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the post workflows params -func (o *PostWorkflowsParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithWorkflow adds the workflow to the post workflows params -func (o *PostWorkflowsParams) WithWorkflow(workflow *model.Workflow) *PostWorkflowsParams { - o.SetWorkflow(workflow) - return o -} - -// SetWorkflow adds the workflow to the post workflows params -func (o *PostWorkflowsParams) SetWorkflow(workflow *model.Workflow) { - o.Workflow = workflow -} - -// WriteToRequest writes these params to a swagger request -func (o *PostWorkflowsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - if o.Workflow != nil { - if err := r.SetBodyParam(o.Workflow); err != nil { - return err - } - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/generated/client/workflows/post_workflows_responses.go b/generated/client/workflows/post_workflows_responses.go deleted file mode 100644 index c1cdc6d5..00000000 --- a/generated/client/workflows/post_workflows_responses.go +++ /dev/null @@ -1,252 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package workflows - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "encoding/json" - "fmt" - "io" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" -) - -// PostWorkflowsReader is a Reader for the PostWorkflows structure. -type PostWorkflowsReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *PostWorkflowsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - case 201: - result := NewPostWorkflowsCreated() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - case 400: - result := NewPostWorkflowsBadRequest() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - default: - result := NewPostWorkflowsDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewPostWorkflowsCreated creates a PostWorkflowsCreated with default headers values -func NewPostWorkflowsCreated() *PostWorkflowsCreated { - return &PostWorkflowsCreated{} -} - -/* -PostWorkflowsCreated describes a response with status code 201, with default header values. - -Workflow was created -*/ -type PostWorkflowsCreated struct { - Payload *model.Workflow -} - -// IsSuccess returns true when this post workflows created response has a 2xx status code -func (o *PostWorkflowsCreated) IsSuccess() bool { - return true -} - -// IsRedirect returns true when this post workflows created response has a 3xx status code -func (o *PostWorkflowsCreated) IsRedirect() bool { - return false -} - -// IsClientError returns true when this post workflows created response has a 4xx status code -func (o *PostWorkflowsCreated) IsClientError() bool { - return false -} - -// IsServerError returns true when this post workflows created response has a 5xx status code -func (o *PostWorkflowsCreated) IsServerError() bool { - return false -} - -// IsCode returns true when this post workflows created response a status code equal to that given -func (o *PostWorkflowsCreated) IsCode(code int) bool { - return code == 201 -} - -// Code gets the status code for the post workflows created response -func (o *PostWorkflowsCreated) Code() int { - return 201 -} - -func (o *PostWorkflowsCreated) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[POST /workflows][%d] postWorkflowsCreated %s", 201, payload) -} - -func (o *PostWorkflowsCreated) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[POST /workflows][%d] postWorkflowsCreated %s", 201, payload) -} - -func (o *PostWorkflowsCreated) GetPayload() *model.Workflow { - return o.Payload -} - -func (o *PostWorkflowsCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.Workflow) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPostWorkflowsBadRequest creates a PostWorkflowsBadRequest with default headers values -func NewPostWorkflowsBadRequest() *PostWorkflowsBadRequest { - return &PostWorkflowsBadRequest{} -} - -/* -PostWorkflowsBadRequest describes a response with status code 400, with default header values. - -Bad Request -*/ -type PostWorkflowsBadRequest struct { - Payload *model.ErrorResponse -} - -// IsSuccess returns true when this post workflows bad request response has a 2xx status code -func (o *PostWorkflowsBadRequest) IsSuccess() bool { - return false -} - -// IsRedirect returns true when this post workflows bad request response has a 3xx status code -func (o *PostWorkflowsBadRequest) IsRedirect() bool { - return false -} - -// IsClientError returns true when this post workflows bad request response has a 4xx status code -func (o *PostWorkflowsBadRequest) IsClientError() bool { - return true -} - -// IsServerError returns true when this post workflows bad request response has a 5xx status code -func (o *PostWorkflowsBadRequest) IsServerError() bool { - return false -} - -// IsCode returns true when this post workflows bad request response a status code equal to that given -func (o *PostWorkflowsBadRequest) IsCode(code int) bool { - return code == 400 -} - -// Code gets the status code for the post workflows bad request response -func (o *PostWorkflowsBadRequest) Code() int { - return 400 -} - -func (o *PostWorkflowsBadRequest) Error() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[POST /workflows][%d] postWorkflowsBadRequest %s", 400, payload) -} - -func (o *PostWorkflowsBadRequest) String() string { - payload, _ := json.Marshal(o.Payload) - return fmt.Sprintf("[POST /workflows][%d] postWorkflowsBadRequest %s", 400, payload) -} - -func (o *PostWorkflowsBadRequest) GetPayload() *model.ErrorResponse { - return o.Payload -} - -func (o *PostWorkflowsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(model.ErrorResponse) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPostWorkflowsDefault creates a PostWorkflowsDefault with default headers values -func NewPostWorkflowsDefault(code int) *PostWorkflowsDefault { - return &PostWorkflowsDefault{ - _statusCode: code, - } -} - -/* -PostWorkflowsDefault describes a response with status code -1, with default header values. - -Other error with any status code and response body format. -*/ -type PostWorkflowsDefault struct { - _statusCode int -} - -// IsSuccess returns true when this post workflows default response has a 2xx status code -func (o *PostWorkflowsDefault) IsSuccess() bool { - return o._statusCode/100 == 2 -} - -// IsRedirect returns true when this post workflows default response has a 3xx status code -func (o *PostWorkflowsDefault) IsRedirect() bool { - return o._statusCode/100 == 3 -} - -// IsClientError returns true when this post workflows default response has a 4xx status code -func (o *PostWorkflowsDefault) IsClientError() bool { - return o._statusCode/100 == 4 -} - -// IsServerError returns true when this post workflows default response has a 5xx status code -func (o *PostWorkflowsDefault) IsServerError() bool { - return o._statusCode/100 == 5 -} - -// IsCode returns true when this post workflows default response a status code equal to that given -func (o *PostWorkflowsDefault) IsCode(code int) bool { - return o._statusCode == code -} - -// Code gets the status code for the post workflows default response -func (o *PostWorkflowsDefault) Code() int { - return o._statusCode -} - -func (o *PostWorkflowsDefault) Error() string { - return fmt.Sprintf("[POST /workflows][%d] PostWorkflows default", o._statusCode) -} - -func (o *PostWorkflowsDefault) String() string { - return fmt.Sprintf("[POST /workflows][%d] PostWorkflows default", o._statusCode) -} - -func (o *PostWorkflowsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - return nil -} diff --git a/generated/client/workflows/workflows_client.go b/generated/client/workflows/workflows_client.go deleted file mode 100644 index d929086c..00000000 --- a/generated/client/workflows/workflows_client.go +++ /dev/null @@ -1,232 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package workflows - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "github.com/go-openapi/runtime" - httptransport "github.com/go-openapi/runtime/client" - "github.com/go-openapi/strfmt" -) - -// New creates a new workflows API client. -func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { - return &Client{transport: transport, formats: formats} -} - -// New creates a new workflows API client with basic auth credentials. -// It takes the following parameters: -// - host: http host (github.com). -// - basePath: any base path for the API client ("/v1", "/v3"). -// - scheme: http scheme ("http", "https"). -// - user: user for basic authentication header. -// - password: password for basic authentication header. -func NewClientWithBasicAuth(host, basePath, scheme, user, password string) ClientService { - transport := httptransport.New(host, basePath, []string{scheme}) - transport.DefaultAuthentication = httptransport.BasicAuth(user, password) - return &Client{transport: transport, formats: strfmt.Default} -} - -// New creates a new workflows API client with a bearer token for authentication. -// It takes the following parameters: -// - host: http host (github.com). -// - basePath: any base path for the API client ("/v1", "/v3"). -// - scheme: http scheme ("http", "https"). -// - bearerToken: bearer token for Bearer authentication header. -func NewClientWithBearerToken(host, basePath, scheme, bearerToken string) ClientService { - transport := httptransport.New(host, basePath, []string{scheme}) - transport.DefaultAuthentication = httptransport.BearerToken(bearerToken) - return &Client{transport: transport, formats: strfmt.Default} -} - -/* -Client for workflows API -*/ -type Client struct { - transport runtime.ClientTransport - formats strfmt.Registry -} - -// ClientOption may be used to customize the behavior of Client methods. -type ClientOption func(*runtime.ClientOperation) - -// ClientService is the interface for Client methods -type ClientService interface { - DeleteWorkflowsName(params *DeleteWorkflowsNameParams, opts ...ClientOption) (*DeleteWorkflowsNameNoContent, error) - - GetWorkflows(params *GetWorkflowsParams, opts ...ClientOption) (*GetWorkflowsOK, error) - - GetWorkflowsName(params *GetWorkflowsNameParams, opts ...ClientOption) (*GetWorkflowsNameOK, error) - - PostWorkflows(params *PostWorkflowsParams, opts ...ClientOption) (*PostWorkflowsCreated, error) - - SetTransport(transport runtime.ClientTransport) -} - -/* -DeleteWorkflowsName deletes an existing workflow - -Delete an existing workflow -*/ -func (a *Client) DeleteWorkflowsName(params *DeleteWorkflowsNameParams, opts ...ClientOption) (*DeleteWorkflowsNameNoContent, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewDeleteWorkflowsNameParams() - } - op := &runtime.ClientOperation{ - ID: "DeleteWorkflowsName", - Method: "DELETE", - PathPattern: "/workflows/{name}", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http"}, - Params: params, - Reader: &DeleteWorkflowsNameReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - } - for _, opt := range opts { - opt(op) - } - - result, err := a.transport.Submit(op) - if err != nil { - return nil, err - } - success, ok := result.(*DeleteWorkflowsNameNoContent) - if ok { - return success, nil - } - // unexpected success response - unexpectedSuccess := result.(*DeleteWorkflowsNameDefault) - return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) -} - -/* -GetWorkflows lists of available workflows - -List of available workflows -*/ -func (a *Client) GetWorkflows(params *GetWorkflowsParams, opts ...ClientOption) (*GetWorkflowsOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewGetWorkflowsParams() - } - op := &runtime.ClientOperation{ - ID: "GetWorkflows", - Method: "GET", - PathPattern: "/workflows", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http"}, - Params: params, - Reader: &GetWorkflowsReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - } - for _, opt := range opts { - opt(op) - } - - result, err := a.transport.Submit(op) - if err != nil { - return nil, err - } - success, ok := result.(*GetWorkflowsOK) - if ok { - return success, nil - } - // unexpected success response - unexpectedSuccess := result.(*GetWorkflowsDefault) - return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) -} - -/* -GetWorkflowsName workflows description for a given name - -Workflow description for a given name -*/ -func (a *Client) GetWorkflowsName(params *GetWorkflowsNameParams, opts ...ClientOption) (*GetWorkflowsNameOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewGetWorkflowsNameParams() - } - op := &runtime.ClientOperation{ - ID: "GetWorkflowsName", - Method: "GET", - PathPattern: "/workflows/{name}", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http"}, - Params: params, - Reader: &GetWorkflowsNameReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - } - for _, opt := range opts { - opt(op) - } - - result, err := a.transport.Submit(op) - if err != nil { - return nil, err - } - success, ok := result.(*GetWorkflowsNameOK) - if ok { - return success, nil - } - // unexpected success response - unexpectedSuccess := result.(*GetWorkflowsNameDefault) - return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) -} - -/* -PostWorkflows adds a new workflow - -Add a new workflow -*/ -func (a *Client) PostWorkflows(params *PostWorkflowsParams, opts ...ClientOption) (*PostWorkflowsCreated, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewPostWorkflowsParams() - } - op := &runtime.ClientOperation{ - ID: "PostWorkflows", - Method: "POST", - PathPattern: "/workflows", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http"}, - Params: params, - Reader: &PostWorkflowsReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - } - for _, opt := range opts { - opt(op) - } - - result, err := a.transport.Submit(op) - if err != nil { - return nil, err - } - success, ok := result.(*PostWorkflowsCreated) - if ok { - return success, nil - } - // unexpected success response - unexpectedSuccess := result.(*PostWorkflowsDefault) - return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) -} - -// SetTransport changes the transport on the client -func (a *Client) SetTransport(transport runtime.ClientTransport) { - a.transport = transport -} diff --git a/generated/ent/history.go b/generated/ent/history.go index 95683c5e..1785ee5a 100644 --- a/generated/ent/history.go +++ b/generated/ent/history.go @@ -13,9 +13,9 @@ import ( "entgo.io/ent" "entgo.io/ent/dialect/sql" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/generated/ent/history" "github.com/siemens/wfx/generated/ent/job" - "github.com/siemens/wfx/generated/model" ) // History is the model entity for the History schema. @@ -26,7 +26,7 @@ type History struct { // modification time Mtime time.Time `json:"mtime,omitempty"` // Status holds the value of the "status" field. - Status model.JobStatus `json:"status,omitempty"` + Status api.JobStatus `json:"status,omitempty"` // Definition holds the value of the "definition" field. Definition map[string]interface{} `json:"definition,omitempty"` // Edges holds the relations/edges for other nodes in the graph. diff --git a/generated/ent/history_create.go b/generated/ent/history_create.go index a3aa62e6..2eb262d4 100644 --- a/generated/ent/history_create.go +++ b/generated/ent/history_create.go @@ -13,9 +13,9 @@ import ( "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/generated/ent/history" "github.com/siemens/wfx/generated/ent/job" - "github.com/siemens/wfx/generated/model" ) // HistoryCreate is the builder for creating a History entity. @@ -32,15 +32,15 @@ func (hc *HistoryCreate) SetMtime(t time.Time) *HistoryCreate { } // SetStatus sets the "status" field. -func (hc *HistoryCreate) SetStatus(ms model.JobStatus) *HistoryCreate { - hc.mutation.SetStatus(ms) +func (hc *HistoryCreate) SetStatus(as api.JobStatus) *HistoryCreate { + hc.mutation.SetStatus(as) return hc } // SetNillableStatus sets the "status" field if the given value is not nil. -func (hc *HistoryCreate) SetNillableStatus(ms *model.JobStatus) *HistoryCreate { - if ms != nil { - hc.SetStatus(*ms) +func (hc *HistoryCreate) SetNillableStatus(as *api.JobStatus) *HistoryCreate { + if as != nil { + hc.SetStatus(*as) } return hc } diff --git a/generated/ent/history_update.go b/generated/ent/history_update.go index a8da1c40..efce00f4 100644 --- a/generated/ent/history_update.go +++ b/generated/ent/history_update.go @@ -14,10 +14,10 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/generated/ent/history" "github.com/siemens/wfx/generated/ent/job" "github.com/siemens/wfx/generated/ent/predicate" - "github.com/siemens/wfx/generated/model" ) // HistoryUpdate is the builder for updating History entities. @@ -48,15 +48,15 @@ func (hu *HistoryUpdate) SetNillableMtime(t *time.Time) *HistoryUpdate { } // SetStatus sets the "status" field. -func (hu *HistoryUpdate) SetStatus(ms model.JobStatus) *HistoryUpdate { - hu.mutation.SetStatus(ms) +func (hu *HistoryUpdate) SetStatus(as api.JobStatus) *HistoryUpdate { + hu.mutation.SetStatus(as) return hu } // SetNillableStatus sets the "status" field if the given value is not nil. -func (hu *HistoryUpdate) SetNillableStatus(ms *model.JobStatus) *HistoryUpdate { - if ms != nil { - hu.SetStatus(*ms) +func (hu *HistoryUpdate) SetNillableStatus(as *api.JobStatus) *HistoryUpdate { + if as != nil { + hu.SetStatus(*as) } return hu } @@ -224,15 +224,15 @@ func (huo *HistoryUpdateOne) SetNillableMtime(t *time.Time) *HistoryUpdateOne { } // SetStatus sets the "status" field. -func (huo *HistoryUpdateOne) SetStatus(ms model.JobStatus) *HistoryUpdateOne { - huo.mutation.SetStatus(ms) +func (huo *HistoryUpdateOne) SetStatus(as api.JobStatus) *HistoryUpdateOne { + huo.mutation.SetStatus(as) return huo } // SetNillableStatus sets the "status" field if the given value is not nil. -func (huo *HistoryUpdateOne) SetNillableStatus(ms *model.JobStatus) *HistoryUpdateOne { - if ms != nil { - huo.SetStatus(*ms) +func (huo *HistoryUpdateOne) SetNillableStatus(as *api.JobStatus) *HistoryUpdateOne { + if as != nil { + huo.SetStatus(*as) } return huo } diff --git a/generated/ent/job.go b/generated/ent/job.go index 8299859c..311bca0f 100644 --- a/generated/ent/job.go +++ b/generated/ent/job.go @@ -13,9 +13,9 @@ import ( "entgo.io/ent" "entgo.io/ent/dialect/sql" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/generated/ent/job" "github.com/siemens/wfx/generated/ent/workflow" - "github.com/siemens/wfx/generated/model" ) // Job is the model entity for the Job schema. @@ -32,7 +32,7 @@ type Job struct { // Definition holds the value of the "definition" field. Definition map[string]interface{} `json:"definition,omitempty"` // Status holds the value of the "status" field. - Status model.JobStatus `json:"status,omitempty"` + Status api.JobStatus `json:"status,omitempty"` // Group holds the value of the "group" field. Group string `json:"group,omitempty"` // Edges holds the relations/edges for other nodes in the graph. diff --git a/generated/ent/job_create.go b/generated/ent/job_create.go index 4c2f4d9c..bf8f131d 100644 --- a/generated/ent/job_create.go +++ b/generated/ent/job_create.go @@ -13,11 +13,11 @@ import ( "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/generated/ent/history" "github.com/siemens/wfx/generated/ent/job" "github.com/siemens/wfx/generated/ent/tag" "github.com/siemens/wfx/generated/ent/workflow" - "github.com/siemens/wfx/generated/model" ) // JobCreate is the builder for creating a Job entity. @@ -68,8 +68,8 @@ func (jc *JobCreate) SetDefinition(m map[string]interface{}) *JobCreate { } // SetStatus sets the "status" field. -func (jc *JobCreate) SetStatus(ms model.JobStatus) *JobCreate { - jc.mutation.SetStatus(ms) +func (jc *JobCreate) SetStatus(as api.JobStatus) *JobCreate { + jc.mutation.SetStatus(as) return jc } diff --git a/generated/ent/job_update.go b/generated/ent/job_update.go index c759a604..723d0401 100644 --- a/generated/ent/job_update.go +++ b/generated/ent/job_update.go @@ -14,12 +14,12 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/generated/ent/history" "github.com/siemens/wfx/generated/ent/job" "github.com/siemens/wfx/generated/ent/predicate" "github.com/siemens/wfx/generated/ent/tag" "github.com/siemens/wfx/generated/ent/workflow" - "github.com/siemens/wfx/generated/model" ) // JobUpdate is the builder for updating Job entities. @@ -82,15 +82,15 @@ func (ju *JobUpdate) ClearDefinition() *JobUpdate { } // SetStatus sets the "status" field. -func (ju *JobUpdate) SetStatus(ms model.JobStatus) *JobUpdate { - ju.mutation.SetStatus(ms) +func (ju *JobUpdate) SetStatus(as api.JobStatus) *JobUpdate { + ju.mutation.SetStatus(as) return ju } // SetNillableStatus sets the "status" field if the given value is not nil. -func (ju *JobUpdate) SetNillableStatus(ms *model.JobStatus) *JobUpdate { - if ms != nil { - ju.SetStatus(*ms) +func (ju *JobUpdate) SetNillableStatus(as *api.JobStatus) *JobUpdate { + if as != nil { + ju.SetStatus(*as) } return ju } @@ -472,15 +472,15 @@ func (juo *JobUpdateOne) ClearDefinition() *JobUpdateOne { } // SetStatus sets the "status" field. -func (juo *JobUpdateOne) SetStatus(ms model.JobStatus) *JobUpdateOne { - juo.mutation.SetStatus(ms) +func (juo *JobUpdateOne) SetStatus(as api.JobStatus) *JobUpdateOne { + juo.mutation.SetStatus(as) return juo } // SetNillableStatus sets the "status" field if the given value is not nil. -func (juo *JobUpdateOne) SetNillableStatus(ms *model.JobStatus) *JobUpdateOne { - if ms != nil { - juo.SetStatus(*ms) +func (juo *JobUpdateOne) SetNillableStatus(as *api.JobStatus) *JobUpdateOne { + if as != nil { + juo.SetStatus(*as) } return juo } diff --git a/generated/ent/mutation.go b/generated/ent/mutation.go index 99ebb08b..95cc125e 100644 --- a/generated/ent/mutation.go +++ b/generated/ent/mutation.go @@ -14,12 +14,12 @@ import ( "entgo.io/ent" "entgo.io/ent/dialect/sql" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/generated/ent/history" "github.com/siemens/wfx/generated/ent/job" "github.com/siemens/wfx/generated/ent/predicate" "github.com/siemens/wfx/generated/ent/tag" "github.com/siemens/wfx/generated/ent/workflow" - "github.com/siemens/wfx/generated/model" ) const ( @@ -44,7 +44,7 @@ type HistoryMutation struct { typ string id *int mtime *time.Time - status *model.JobStatus + status *api.JobStatus definition *map[string]interface{} clearedFields map[string]struct{} job *string @@ -189,12 +189,12 @@ func (m *HistoryMutation) ResetMtime() { } // SetStatus sets the "status" field. -func (m *HistoryMutation) SetStatus(ms model.JobStatus) { - m.status = &ms +func (m *HistoryMutation) SetStatus(as api.JobStatus) { + m.status = &as } // Status returns the value of the "status" field in the mutation. -func (m *HistoryMutation) Status() (r model.JobStatus, exists bool) { +func (m *HistoryMutation) Status() (r api.JobStatus, exists bool) { v := m.status if v == nil { return @@ -205,7 +205,7 @@ func (m *HistoryMutation) Status() (r model.JobStatus, exists bool) { // OldStatus returns the old "status" field's value of the History entity. // If the History object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *HistoryMutation) OldStatus(ctx context.Context) (v model.JobStatus, err error) { +func (m *HistoryMutation) OldStatus(ctx context.Context) (v api.JobStatus, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldStatus is only allowed on UpdateOne operations") } @@ -415,7 +415,7 @@ func (m *HistoryMutation) SetField(name string, value ent.Value) error { m.SetMtime(v) return nil case history.FieldStatus: - v, ok := value.(model.JobStatus) + v, ok := value.(api.JobStatus) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } @@ -589,7 +589,7 @@ type JobMutation struct { mtime *time.Time client_id *string definition *map[string]interface{} - status *model.JobStatus + status *api.JobStatus group *string clearedFields map[string]struct{} workflow *int @@ -867,12 +867,12 @@ func (m *JobMutation) ResetDefinition() { } // SetStatus sets the "status" field. -func (m *JobMutation) SetStatus(ms model.JobStatus) { - m.status = &ms +func (m *JobMutation) SetStatus(as api.JobStatus) { + m.status = &as } // Status returns the value of the "status" field in the mutation. -func (m *JobMutation) Status() (r model.JobStatus, exists bool) { +func (m *JobMutation) Status() (r api.JobStatus, exists bool) { v := m.status if v == nil { return @@ -883,7 +883,7 @@ func (m *JobMutation) Status() (r model.JobStatus, exists bool) { // OldStatus returns the old "status" field's value of the Job entity. // If the Job object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *JobMutation) OldStatus(ctx context.Context) (v model.JobStatus, err error) { +func (m *JobMutation) OldStatus(ctx context.Context) (v api.JobStatus, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldStatus is only allowed on UpdateOne operations") } @@ -1230,7 +1230,7 @@ func (m *JobMutation) SetField(name string, value ent.Value) error { m.SetDefinition(v) return nil case job.FieldStatus: - v, ok := value.(model.JobStatus) + v, ok := value.(api.JobStatus) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } @@ -1884,12 +1884,12 @@ type WorkflowMutation struct { id *int name *string description *string - states *[]*model.State - appendstates []*model.State - transitions *[]*model.Transition - appendtransitions []*model.Transition - groups *[]*model.Group - appendgroups []*model.Group + states *[]api.State + appendstates []api.State + transitions *[]api.Transition + appendtransitions []api.Transition + groups *[]api.Group + appendgroups []api.Group clearedFields map[string]struct{} jobs map[string]struct{} removedjobs map[string]struct{} @@ -2083,13 +2083,13 @@ func (m *WorkflowMutation) ResetDescription() { } // SetStates sets the "states" field. -func (m *WorkflowMutation) SetStates(value []*model.State) { - m.states = &value +func (m *WorkflowMutation) SetStates(a []api.State) { + m.states = &a m.appendstates = nil } // States returns the value of the "states" field in the mutation. -func (m *WorkflowMutation) States() (r []*model.State, exists bool) { +func (m *WorkflowMutation) States() (r []api.State, exists bool) { v := m.states if v == nil { return @@ -2100,7 +2100,7 @@ func (m *WorkflowMutation) States() (r []*model.State, exists bool) { // OldStates returns the old "states" field's value of the Workflow entity. // If the Workflow object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *WorkflowMutation) OldStates(ctx context.Context) (v []*model.State, err error) { +func (m *WorkflowMutation) OldStates(ctx context.Context) (v []api.State, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldStates is only allowed on UpdateOne operations") } @@ -2114,13 +2114,13 @@ func (m *WorkflowMutation) OldStates(ctx context.Context) (v []*model.State, err return oldValue.States, nil } -// AppendStates adds value to the "states" field. -func (m *WorkflowMutation) AppendStates(value []*model.State) { - m.appendstates = append(m.appendstates, value...) +// AppendStates adds a to the "states" field. +func (m *WorkflowMutation) AppendStates(a []api.State) { + m.appendstates = append(m.appendstates, a...) } // AppendedStates returns the list of values that were appended to the "states" field in this mutation. -func (m *WorkflowMutation) AppendedStates() ([]*model.State, bool) { +func (m *WorkflowMutation) AppendedStates() ([]api.State, bool) { if len(m.appendstates) == 0 { return nil, false } @@ -2134,13 +2134,13 @@ func (m *WorkflowMutation) ResetStates() { } // SetTransitions sets the "transitions" field. -func (m *WorkflowMutation) SetTransitions(value []*model.Transition) { - m.transitions = &value +func (m *WorkflowMutation) SetTransitions(a []api.Transition) { + m.transitions = &a m.appendtransitions = nil } // Transitions returns the value of the "transitions" field in the mutation. -func (m *WorkflowMutation) Transitions() (r []*model.Transition, exists bool) { +func (m *WorkflowMutation) Transitions() (r []api.Transition, exists bool) { v := m.transitions if v == nil { return @@ -2151,7 +2151,7 @@ func (m *WorkflowMutation) Transitions() (r []*model.Transition, exists bool) { // OldTransitions returns the old "transitions" field's value of the Workflow entity. // If the Workflow object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *WorkflowMutation) OldTransitions(ctx context.Context) (v []*model.Transition, err error) { +func (m *WorkflowMutation) OldTransitions(ctx context.Context) (v []api.Transition, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldTransitions is only allowed on UpdateOne operations") } @@ -2165,13 +2165,13 @@ func (m *WorkflowMutation) OldTransitions(ctx context.Context) (v []*model.Trans return oldValue.Transitions, nil } -// AppendTransitions adds value to the "transitions" field. -func (m *WorkflowMutation) AppendTransitions(value []*model.Transition) { - m.appendtransitions = append(m.appendtransitions, value...) +// AppendTransitions adds a to the "transitions" field. +func (m *WorkflowMutation) AppendTransitions(a []api.Transition) { + m.appendtransitions = append(m.appendtransitions, a...) } // AppendedTransitions returns the list of values that were appended to the "transitions" field in this mutation. -func (m *WorkflowMutation) AppendedTransitions() ([]*model.Transition, bool) { +func (m *WorkflowMutation) AppendedTransitions() ([]api.Transition, bool) { if len(m.appendtransitions) == 0 { return nil, false } @@ -2185,13 +2185,13 @@ func (m *WorkflowMutation) ResetTransitions() { } // SetGroups sets the "groups" field. -func (m *WorkflowMutation) SetGroups(value []*model.Group) { - m.groups = &value +func (m *WorkflowMutation) SetGroups(a []api.Group) { + m.groups = &a m.appendgroups = nil } // Groups returns the value of the "groups" field in the mutation. -func (m *WorkflowMutation) Groups() (r []*model.Group, exists bool) { +func (m *WorkflowMutation) Groups() (r []api.Group, exists bool) { v := m.groups if v == nil { return @@ -2202,7 +2202,7 @@ func (m *WorkflowMutation) Groups() (r []*model.Group, exists bool) { // OldGroups returns the old "groups" field's value of the Workflow entity. // If the Workflow object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *WorkflowMutation) OldGroups(ctx context.Context) (v []*model.Group, err error) { +func (m *WorkflowMutation) OldGroups(ctx context.Context) (v []api.Group, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldGroups is only allowed on UpdateOne operations") } @@ -2216,13 +2216,13 @@ func (m *WorkflowMutation) OldGroups(ctx context.Context) (v []*model.Group, err return oldValue.Groups, nil } -// AppendGroups adds value to the "groups" field. -func (m *WorkflowMutation) AppendGroups(value []*model.Group) { - m.appendgroups = append(m.appendgroups, value...) +// AppendGroups adds a to the "groups" field. +func (m *WorkflowMutation) AppendGroups(a []api.Group) { + m.appendgroups = append(m.appendgroups, a...) } // AppendedGroups returns the list of values that were appended to the "groups" field in this mutation. -func (m *WorkflowMutation) AppendedGroups() ([]*model.Group, bool) { +func (m *WorkflowMutation) AppendedGroups() ([]api.Group, bool) { if len(m.appendgroups) == 0 { return nil, false } @@ -2400,21 +2400,21 @@ func (m *WorkflowMutation) SetField(name string, value ent.Value) error { m.SetDescription(v) return nil case workflow.FieldStates: - v, ok := value.([]*model.State) + v, ok := value.([]api.State) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetStates(v) return nil case workflow.FieldTransitions: - v, ok := value.([]*model.Transition) + v, ok := value.([]api.Transition) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetTransitions(v) return nil case workflow.FieldGroups: - v, ok := value.([]*model.Group) + v, ok := value.([]api.Group) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } diff --git a/generated/ent/schema/history.go b/generated/ent/schema/history.go index 825294d5..ba2912d9 100644 --- a/generated/ent/schema/history.go +++ b/generated/ent/schema/history.go @@ -10,7 +10,7 @@ import ( "entgo.io/ent/schema" "entgo.io/ent/schema/edge" "entgo.io/ent/schema/field" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" ) // History holds the schema definition for the Job entity. @@ -32,7 +32,7 @@ func (History) Fields() []ent.Field { SchemaType(map[string]string{ dialect.MySQL: "TIMESTAMP(6)", // microsecond precision }), - field.JSON("status", model.JobStatus{}).Optional(), + field.JSON("status", api.JobStatus{}).Optional(), field.JSON("definition", map[string]any{}).Optional(), } } diff --git a/generated/ent/schema/job.go b/generated/ent/schema/job.go index 52086339..59d45166 100644 --- a/generated/ent/schema/job.go +++ b/generated/ent/schema/job.go @@ -14,7 +14,7 @@ import ( "entgo.io/ent/schema/field" "entgo.io/ent/schema/index" "github.com/google/uuid" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" ) // Job holds the schema definition for the Job entity. @@ -57,7 +57,7 @@ func (Job) Fields() []ent.Field { field.String("client_id"), field.JSON("definition", map[string]any{}).Optional(), // JobStatus - field.JSON("status", model.JobStatus{}), + field.JSON("status", api.JobStatus{}), field.String("group").Optional(), } } diff --git a/generated/ent/schema/workflow.go b/generated/ent/schema/workflow.go index 0ebf2c89..96b3327a 100644 --- a/generated/ent/schema/workflow.go +++ b/generated/ent/schema/workflow.go @@ -9,7 +9,7 @@ import ( "entgo.io/ent/schema" "entgo.io/ent/schema/edge" "entgo.io/ent/schema/field" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" ) // Workflow holds the schema definition for the Workflow entity. @@ -33,9 +33,9 @@ func (Workflow) Fields() []ent.Field { field.String("description"). Optional(). MaxLen(1024), - field.JSON("states", []*model.State{}), - field.JSON("transitions", []*model.Transition{}), - field.JSON("groups", []*model.Group{}), + field.JSON("states", []api.State{}), + field.JSON("transitions", []api.Transition{}), + field.JSON("groups", []api.Group{}), } } diff --git a/generated/ent/workflow.go b/generated/ent/workflow.go index d3a7db3d..75ea9ee6 100644 --- a/generated/ent/workflow.go +++ b/generated/ent/workflow.go @@ -12,8 +12,8 @@ import ( "entgo.io/ent" "entgo.io/ent/dialect/sql" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/generated/ent/workflow" - "github.com/siemens/wfx/generated/model" ) // Workflow is the model entity for the Workflow schema. @@ -26,11 +26,11 @@ type Workflow struct { // Description holds the value of the "description" field. Description string `json:"description,omitempty"` // States holds the value of the "states" field. - States []*model.State `json:"states,omitempty"` + States []api.State `json:"states,omitempty"` // Transitions holds the value of the "transitions" field. - Transitions []*model.Transition `json:"transitions,omitempty"` + Transitions []api.Transition `json:"transitions,omitempty"` // Groups holds the value of the "groups" field. - Groups []*model.Group `json:"groups,omitempty"` + Groups []api.Group `json:"groups,omitempty"` // Edges holds the relations/edges for other nodes in the graph. // The values are being populated by the WorkflowQuery when eager-loading is set. Edges WorkflowEdges `json:"edges"` diff --git a/generated/ent/workflow_create.go b/generated/ent/workflow_create.go index 360e7726..33c7998b 100644 --- a/generated/ent/workflow_create.go +++ b/generated/ent/workflow_create.go @@ -12,9 +12,9 @@ import ( "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/generated/ent/job" "github.com/siemens/wfx/generated/ent/workflow" - "github.com/siemens/wfx/generated/model" ) // WorkflowCreate is the builder for creating a Workflow entity. @@ -45,20 +45,20 @@ func (wc *WorkflowCreate) SetNillableDescription(s *string) *WorkflowCreate { } // SetStates sets the "states" field. -func (wc *WorkflowCreate) SetStates(m []*model.State) *WorkflowCreate { - wc.mutation.SetStates(m) +func (wc *WorkflowCreate) SetStates(a []api.State) *WorkflowCreate { + wc.mutation.SetStates(a) return wc } // SetTransitions sets the "transitions" field. -func (wc *WorkflowCreate) SetTransitions(m []*model.Transition) *WorkflowCreate { - wc.mutation.SetTransitions(m) +func (wc *WorkflowCreate) SetTransitions(a []api.Transition) *WorkflowCreate { + wc.mutation.SetTransitions(a) return wc } // SetGroups sets the "groups" field. -func (wc *WorkflowCreate) SetGroups(m []*model.Group) *WorkflowCreate { - wc.mutation.SetGroups(m) +func (wc *WorkflowCreate) SetGroups(a []api.Group) *WorkflowCreate { + wc.mutation.SetGroups(a) return wc } diff --git a/generated/ent/workflow_update.go b/generated/ent/workflow_update.go index eb934edb..d117eab9 100644 --- a/generated/ent/workflow_update.go +++ b/generated/ent/workflow_update.go @@ -14,10 +14,10 @@ import ( "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/dialect/sql/sqljson" "entgo.io/ent/schema/field" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/generated/ent/job" "github.com/siemens/wfx/generated/ent/predicate" "github.com/siemens/wfx/generated/ent/workflow" - "github.com/siemens/wfx/generated/model" ) // WorkflowUpdate is the builder for updating Workflow entities. @@ -68,38 +68,38 @@ func (wu *WorkflowUpdate) ClearDescription() *WorkflowUpdate { } // SetStates sets the "states" field. -func (wu *WorkflowUpdate) SetStates(m []*model.State) *WorkflowUpdate { - wu.mutation.SetStates(m) +func (wu *WorkflowUpdate) SetStates(a []api.State) *WorkflowUpdate { + wu.mutation.SetStates(a) return wu } -// AppendStates appends m to the "states" field. -func (wu *WorkflowUpdate) AppendStates(m []*model.State) *WorkflowUpdate { - wu.mutation.AppendStates(m) +// AppendStates appends a to the "states" field. +func (wu *WorkflowUpdate) AppendStates(a []api.State) *WorkflowUpdate { + wu.mutation.AppendStates(a) return wu } // SetTransitions sets the "transitions" field. -func (wu *WorkflowUpdate) SetTransitions(m []*model.Transition) *WorkflowUpdate { - wu.mutation.SetTransitions(m) +func (wu *WorkflowUpdate) SetTransitions(a []api.Transition) *WorkflowUpdate { + wu.mutation.SetTransitions(a) return wu } -// AppendTransitions appends m to the "transitions" field. -func (wu *WorkflowUpdate) AppendTransitions(m []*model.Transition) *WorkflowUpdate { - wu.mutation.AppendTransitions(m) +// AppendTransitions appends a to the "transitions" field. +func (wu *WorkflowUpdate) AppendTransitions(a []api.Transition) *WorkflowUpdate { + wu.mutation.AppendTransitions(a) return wu } // SetGroups sets the "groups" field. -func (wu *WorkflowUpdate) SetGroups(m []*model.Group) *WorkflowUpdate { - wu.mutation.SetGroups(m) +func (wu *WorkflowUpdate) SetGroups(a []api.Group) *WorkflowUpdate { + wu.mutation.SetGroups(a) return wu } -// AppendGroups appends m to the "groups" field. -func (wu *WorkflowUpdate) AppendGroups(m []*model.Group) *WorkflowUpdate { - wu.mutation.AppendGroups(m) +// AppendGroups appends a to the "groups" field. +func (wu *WorkflowUpdate) AppendGroups(a []api.Group) *WorkflowUpdate { + wu.mutation.AppendGroups(a) return wu } @@ -331,38 +331,38 @@ func (wuo *WorkflowUpdateOne) ClearDescription() *WorkflowUpdateOne { } // SetStates sets the "states" field. -func (wuo *WorkflowUpdateOne) SetStates(m []*model.State) *WorkflowUpdateOne { - wuo.mutation.SetStates(m) +func (wuo *WorkflowUpdateOne) SetStates(a []api.State) *WorkflowUpdateOne { + wuo.mutation.SetStates(a) return wuo } -// AppendStates appends m to the "states" field. -func (wuo *WorkflowUpdateOne) AppendStates(m []*model.State) *WorkflowUpdateOne { - wuo.mutation.AppendStates(m) +// AppendStates appends a to the "states" field. +func (wuo *WorkflowUpdateOne) AppendStates(a []api.State) *WorkflowUpdateOne { + wuo.mutation.AppendStates(a) return wuo } // SetTransitions sets the "transitions" field. -func (wuo *WorkflowUpdateOne) SetTransitions(m []*model.Transition) *WorkflowUpdateOne { - wuo.mutation.SetTransitions(m) +func (wuo *WorkflowUpdateOne) SetTransitions(a []api.Transition) *WorkflowUpdateOne { + wuo.mutation.SetTransitions(a) return wuo } -// AppendTransitions appends m to the "transitions" field. -func (wuo *WorkflowUpdateOne) AppendTransitions(m []*model.Transition) *WorkflowUpdateOne { - wuo.mutation.AppendTransitions(m) +// AppendTransitions appends a to the "transitions" field. +func (wuo *WorkflowUpdateOne) AppendTransitions(a []api.Transition) *WorkflowUpdateOne { + wuo.mutation.AppendTransitions(a) return wuo } // SetGroups sets the "groups" field. -func (wuo *WorkflowUpdateOne) SetGroups(m []*model.Group) *WorkflowUpdateOne { - wuo.mutation.SetGroups(m) +func (wuo *WorkflowUpdateOne) SetGroups(a []api.Group) *WorkflowUpdateOne { + wuo.mutation.SetGroups(a) return wuo } -// AppendGroups appends m to the "groups" field. -func (wuo *WorkflowUpdateOne) AppendGroups(m []*model.Group) *WorkflowUpdateOne { - wuo.mutation.AppendGroups(m) +// AppendGroups appends a to the "groups" field. +func (wuo *WorkflowUpdateOne) AppendGroups(a []api.Group) *WorkflowUpdateOne { + wuo.mutation.AppendGroups(a) return wuo } diff --git a/generated/model/action_enum.go b/generated/model/action_enum.go deleted file mode 100644 index e7e5611b..00000000 --- a/generated/model/action_enum.go +++ /dev/null @@ -1,83 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package model - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/validate" -) - -// ActionEnum action enum -// -// swagger:model ActionEnum -type ActionEnum string - -func NewActionEnum(value ActionEnum) *ActionEnum { - return &value -} - -// Pointer returns a pointer to a freshly-allocated ActionEnum. -func (m ActionEnum) Pointer() *ActionEnum { - return &m -} - -const ( - - // ActionEnumIMMEDIATE captures enum value "IMMEDIATE" - ActionEnumIMMEDIATE ActionEnum = "IMMEDIATE" - - // ActionEnumWAIT captures enum value "WAIT" - ActionEnumWAIT ActionEnum = "WAIT" -) - -// for schema -var actionEnumEnum []interface{} - -func init() { - var res []ActionEnum - if err := json.Unmarshal([]byte(`["IMMEDIATE","WAIT"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - actionEnumEnum = append(actionEnumEnum, v) - } -} - -func (m ActionEnum) validateActionEnumEnum(path, location string, value ActionEnum) error { - if err := validate.EnumCase(path, location, value, actionEnumEnum, true); err != nil { - return err - } - return nil -} - -// Validate validates this action enum -func (m ActionEnum) Validate(formats strfmt.Registry) error { - var res []error - - // value enum - if err := m.validateActionEnumEnum("", "body", m); err != nil { - return err - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// ContextValidate validates this action enum based on context it is used -func (m ActionEnum) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} diff --git a/generated/model/eligible_enum.go b/generated/model/eligible_enum.go deleted file mode 100644 index 0f98b501..00000000 --- a/generated/model/eligible_enum.go +++ /dev/null @@ -1,83 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package model - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/validate" -) - -// EligibleEnum eligible enum -// -// swagger:model EligibleEnum -type EligibleEnum string - -func NewEligibleEnum(value EligibleEnum) *EligibleEnum { - return &value -} - -// Pointer returns a pointer to a freshly-allocated EligibleEnum. -func (m EligibleEnum) Pointer() *EligibleEnum { - return &m -} - -const ( - - // EligibleEnumCLIENT captures enum value "CLIENT" - EligibleEnumCLIENT EligibleEnum = "CLIENT" - - // EligibleEnumWFX captures enum value "WFX" - EligibleEnumWFX EligibleEnum = "WFX" -) - -// for schema -var eligibleEnumEnum []interface{} - -func init() { - var res []EligibleEnum - if err := json.Unmarshal([]byte(`["CLIENT","WFX"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - eligibleEnumEnum = append(eligibleEnumEnum, v) - } -} - -func (m EligibleEnum) validateEligibleEnumEnum(path, location string, value EligibleEnum) error { - if err := validate.EnumCase(path, location, value, eligibleEnumEnum, true); err != nil { - return err - } - return nil -} - -// Validate validates this eligible enum -func (m EligibleEnum) Validate(formats strfmt.Registry) error { - var res []error - - // value enum - if err := m.validateEligibleEnumEnum("", "body", m); err != nil { - return err - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// ContextValidate validates this eligible enum based on context it is used -func (m EligibleEnum) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} diff --git a/generated/model/error.go b/generated/model/error.go deleted file mode 100644 index 45b30201..00000000 --- a/generated/model/error.go +++ /dev/null @@ -1,61 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package model - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// Error error -// -// swagger:model Error -type Error struct { - - // Identifier code for the reason of the error - Code string `json:"code,omitempty"` - - // Log correlation ID - Logref string `json:"logref,omitempty"` - - // Error message - Message string `json:"message,omitempty"` -} - -// Validate validates this error -func (m *Error) Validate(formats strfmt.Registry) error { - return nil -} - -// ContextValidate validates this error based on context it is used -func (m *Error) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *Error) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Error) UnmarshalBinary(b []byte) error { - var res Error - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/generated/model/error_response.go b/generated/model/error_response.go deleted file mode 100644 index 6562c2c1..00000000 --- a/generated/model/error_response.go +++ /dev/null @@ -1,134 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package model - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// ErrorResponse error response -// -// swagger:model ErrorResponse -type ErrorResponse struct { - - // errors - // Max Items: 128 - Errors []*Error `json:"errors"` -} - -// Validate validates this error response -func (m *ErrorResponse) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateErrors(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ErrorResponse) validateErrors(formats strfmt.Registry) error { - if swag.IsZero(m.Errors) { // not required - return nil - } - - iErrorsSize := int64(len(m.Errors)) - - if err := validate.MaxItems("errors", "body", iErrorsSize, 128); err != nil { - return err - } - - for i := 0; i < len(m.Errors); i++ { - if swag.IsZero(m.Errors[i]) { // not required - continue - } - - if m.Errors[i] != nil { - if err := m.Errors[i].Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("errors" + "." + strconv.Itoa(i)) - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("errors" + "." + strconv.Itoa(i)) - } - return err - } - } - - } - - return nil -} - -// ContextValidate validate this error response based on the context it is used -func (m *ErrorResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateErrors(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ErrorResponse) contextValidateErrors(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Errors); i++ { - - if m.Errors[i] != nil { - - if swag.IsZero(m.Errors[i]) { // not required - return nil - } - - if err := m.Errors[i].ContextValidate(ctx, formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("errors" + "." + strconv.Itoa(i)) - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("errors" + "." + strconv.Itoa(i)) - } - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *ErrorResponse) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ErrorResponse) UnmarshalBinary(b []byte) error { - var res ErrorResponse - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/generated/model/group.go b/generated/model/group.go deleted file mode 100644 index e021698f..00000000 --- a/generated/model/group.go +++ /dev/null @@ -1,110 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package model - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Group group -// -// swagger:model Group -type Group struct { - - // description - // Example: Description of the group - Description string `json:"description,omitempty"` - - // name - // Example: OPEN - // Required: true - Name string `json:"name"` - - // A list of states belonging to this group - // Required: true - // Max Items: 4096 - // Min Items: 1 - States []string `json:"states"` -} - -// Validate validates this group -func (m *Group) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStates(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Group) validateName(formats strfmt.Registry) error { - - if err := validate.RequiredString("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *Group) validateStates(formats strfmt.Registry) error { - - if err := validate.Required("states", "body", m.States); err != nil { - return err - } - - iStatesSize := int64(len(m.States)) - - if err := validate.MinItems("states", "body", iStatesSize, 1); err != nil { - return err - } - - if err := validate.MaxItems("states", "body", iStatesSize, 4096); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this group based on context it is used -func (m *Group) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *Group) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Group) UnmarshalBinary(b []byte) error { - var res Group - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/generated/model/history.go b/generated/model/history.go deleted file mode 100644 index 5a04ff3f..00000000 --- a/generated/model/history.go +++ /dev/null @@ -1,153 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package model - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// History history -// -// swagger:model History -type History struct { - - // definition - // Example: { \"userDefined\": {} }\n - Definition map[string]interface{} `json:"definition,omitempty"` - - // Date and time (ISO8601) when the job was modified (set by wfx) - // Read Only: true - // Format: date-time - Mtime strfmt.DateTime `json:"mtime,omitempty"` - - // A previous job status - Status *JobStatus `json:"status,omitempty"` -} - -// Validate validates this history -func (m *History) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateMtime(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStatus(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *History) validateMtime(formats strfmt.Registry) error { - if swag.IsZero(m.Mtime) { // not required - return nil - } - - if err := validate.FormatOf("mtime", "body", "date-time", m.Mtime.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *History) validateStatus(formats strfmt.Registry) error { - if swag.IsZero(m.Status) { // not required - return nil - } - - if m.Status != nil { - if err := m.Status.Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("status") - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("status") - } - return err - } - } - - return nil -} - -// ContextValidate validate this history based on the context it is used -func (m *History) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateMtime(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateStatus(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *History) contextValidateMtime(ctx context.Context, formats strfmt.Registry) error { - - if err := validate.ReadOnly(ctx, "mtime", "body", strfmt.DateTime(m.Mtime)); err != nil { - return err - } - - return nil -} - -func (m *History) contextValidateStatus(ctx context.Context, formats strfmt.Registry) error { - - if m.Status != nil { - - if swag.IsZero(m.Status) { // not required - return nil - } - - if err := m.Status.ContextValidate(ctx, formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("status") - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("status") - } - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *History) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *History) UnmarshalBinary(b []byte) error { - var res History - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/generated/model/job.go b/generated/model/job.go deleted file mode 100644 index 586fcbb5..00000000 --- a/generated/model/job.go +++ /dev/null @@ -1,352 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package model - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Job job -// -// swagger:model Job -type Job struct { - - // client Id - // Example: client42 - ClientID string `json:"clientId,omitempty"` - - // definition - // Example: { \"userDefined\": {} }\n - Definition map[string]interface{} `json:"definition,omitempty"` - - // The job's history. Last in, first out (LIFO). Array is truncated if its length exceeds the maximum allowed length. - // By default, the job history is omitted from responses unless explicitly requested by the client (see the `history` URL parameter). - // - // Max Items: 8192 - History []*History `json:"history,omitempty"` - - // Unique job ID (wfx-generated) - // Example: 3307e5cb-074c-49b7-99d4-5e61839a4c2d - // Read Only: true - // Max Length: 36 - ID string `json:"id,omitempty"` - - // Date and time (ISO8601) when the job was last modified (set by wfx) - // Read Only: true - // Format: date-time - Mtime *strfmt.DateTime `json:"mtime,omitempty"` - - // status - Status *JobStatus `json:"status,omitempty"` - - // Date and time (ISO8601) when the job was created (set by wfx). Although stime conceptually always exists, it's nullable because we don't want to serialize stime in some cases (e.g. for job events). - // Read Only: true - // Format: date-time - Stime *strfmt.DateTime `json:"stime,omitempty"` - - // tags - Tags []string `json:"tags,omitempty"` - - // workflow - Workflow *Workflow `json:"workflow,omitempty"` -} - -// Validate validates this job -func (m *Job) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateHistory(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMtime(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStatus(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStime(formats); err != nil { - res = append(res, err) - } - - if err := m.validateWorkflow(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Job) validateHistory(formats strfmt.Registry) error { - if swag.IsZero(m.History) { // not required - return nil - } - - iHistorySize := int64(len(m.History)) - - if err := validate.MaxItems("history", "body", iHistorySize, 8192); err != nil { - return err - } - - for i := 0; i < len(m.History); i++ { - if swag.IsZero(m.History[i]) { // not required - continue - } - - if m.History[i] != nil { - if err := m.History[i].Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("history" + "." + strconv.Itoa(i)) - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("history" + "." + strconv.Itoa(i)) - } - return err - } - } - - } - - return nil -} - -func (m *Job) validateID(formats strfmt.Registry) error { - if swag.IsZero(m.ID) { // not required - return nil - } - - if err := validate.MaxLength("id", "body", m.ID, 36); err != nil { - return err - } - - return nil -} - -func (m *Job) validateMtime(formats strfmt.Registry) error { - if swag.IsZero(m.Mtime) { // not required - return nil - } - - if err := validate.FormatOf("mtime", "body", "date-time", m.Mtime.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *Job) validateStatus(formats strfmt.Registry) error { - if swag.IsZero(m.Status) { // not required - return nil - } - - if m.Status != nil { - if err := m.Status.Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("status") - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("status") - } - return err - } - } - - return nil -} - -func (m *Job) validateStime(formats strfmt.Registry) error { - if swag.IsZero(m.Stime) { // not required - return nil - } - - if err := validate.FormatOf("stime", "body", "date-time", m.Stime.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *Job) validateWorkflow(formats strfmt.Registry) error { - if swag.IsZero(m.Workflow) { // not required - return nil - } - - if m.Workflow != nil { - if err := m.Workflow.Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("workflow") - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("workflow") - } - return err - } - } - - return nil -} - -// ContextValidate validate this job based on the context it is used -func (m *Job) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateHistory(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateID(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateMtime(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateStatus(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateStime(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateWorkflow(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Job) contextValidateHistory(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.History); i++ { - - if m.History[i] != nil { - - if swag.IsZero(m.History[i]) { // not required - return nil - } - - if err := m.History[i].ContextValidate(ctx, formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("history" + "." + strconv.Itoa(i)) - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("history" + "." + strconv.Itoa(i)) - } - return err - } - } - - } - - return nil -} - -func (m *Job) contextValidateID(ctx context.Context, formats strfmt.Registry) error { - - if err := validate.ReadOnly(ctx, "id", "body", string(m.ID)); err != nil { - return err - } - - return nil -} - -func (m *Job) contextValidateMtime(ctx context.Context, formats strfmt.Registry) error { - - if err := validate.ReadOnly(ctx, "mtime", "body", m.Mtime); err != nil { - return err - } - - return nil -} - -func (m *Job) contextValidateStatus(ctx context.Context, formats strfmt.Registry) error { - - if m.Status != nil { - - if swag.IsZero(m.Status) { // not required - return nil - } - - if err := m.Status.ContextValidate(ctx, formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("status") - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("status") - } - return err - } - } - - return nil -} - -func (m *Job) contextValidateStime(ctx context.Context, formats strfmt.Registry) error { - - if err := validate.ReadOnly(ctx, "stime", "body", m.Stime); err != nil { - return err - } - - return nil -} - -func (m *Job) contextValidateWorkflow(ctx context.Context, formats strfmt.Registry) error { - - if m.Workflow != nil { - - if swag.IsZero(m.Workflow) { // not required - return nil - } - - if err := m.Workflow.ContextValidate(ctx, formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("workflow") - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("workflow") - } - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Job) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Job) UnmarshalBinary(b []byte) error { - var res Job - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/generated/model/job_request.go b/generated/model/job_request.go deleted file mode 100644 index d73e9d28..00000000 --- a/generated/model/job_request.go +++ /dev/null @@ -1,121 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package model - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// JobRequest job request -// -// swagger:model JobRequest -type JobRequest struct { - - // Create job for the given client ID - // Example: client42 - // Required: true - ClientID string `json:"clientId"` - - // The existing job definition will be replaced with this if this property is not empty. - // Example: { \"userDefined\": {} }\n - Definition map[string]interface{} `json:"definition,omitempty"` - - // tags - // Max Items: 16 - Tags []string `json:"tags"` - - // Workflow name - // Example: wfx.workflow.dau.direct - // Required: true - Workflow string `json:"workflow"` -} - -// Validate validates this job request -func (m *JobRequest) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateClientID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTags(formats); err != nil { - res = append(res, err) - } - - if err := m.validateWorkflow(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *JobRequest) validateClientID(formats strfmt.Registry) error { - - if err := validate.RequiredString("clientId", "body", m.ClientID); err != nil { - return err - } - - return nil -} - -func (m *JobRequest) validateTags(formats strfmt.Registry) error { - if swag.IsZero(m.Tags) { // not required - return nil - } - - iTagsSize := int64(len(m.Tags)) - - if err := validate.MaxItems("tags", "body", iTagsSize, 16); err != nil { - return err - } - - return nil -} - -func (m *JobRequest) validateWorkflow(formats strfmt.Registry) error { - - if err := validate.RequiredString("workflow", "body", m.Workflow); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this job request based on context it is used -func (m *JobRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *JobRequest) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *JobRequest) UnmarshalBinary(b []byte) error { - var res JobRequest - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/generated/model/job_status.go b/generated/model/job_status.go deleted file mode 100644 index c0fa7f2d..00000000 --- a/generated/model/job_status.go +++ /dev/null @@ -1,164 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package model - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// JobStatus Job status information -// -// swagger:model JobStatus -type JobStatus struct { - - // Client which sent the status update - // Example: client42 - ClientID string `json:"clientId,omitempty"` - - // Client-specific JSON object to report additional context information such as error details, stack traces, etc - // Example: {\n \"lines\": [ \"line1\", \"line2\" ]\n}\n - Context map[string]interface{} `json:"context,omitempty"` - - // Job definition hash - // Read Only: true - // Max Length: 64 - DefinitionHash string `json:"definitionHash,omitempty"` - - // Reason message/info, free text from client - // Max Length: 1024 - Message string `json:"message,omitempty"` - - // Current job progress percentage - // Maximum: 100 - Progress int32 `json:"progress,omitempty"` - - // Name of the new workflow state - // Example: END - // Required: true - State string `json:"state"` -} - -// Validate validates this job status -func (m *JobStatus) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateDefinitionHash(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMessage(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProgress(formats); err != nil { - res = append(res, err) - } - - if err := m.validateState(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *JobStatus) validateDefinitionHash(formats strfmt.Registry) error { - if swag.IsZero(m.DefinitionHash) { // not required - return nil - } - - if err := validate.MaxLength("definitionHash", "body", m.DefinitionHash, 64); err != nil { - return err - } - - return nil -} - -func (m *JobStatus) validateMessage(formats strfmt.Registry) error { - if swag.IsZero(m.Message) { // not required - return nil - } - - if err := validate.MaxLength("message", "body", m.Message, 1024); err != nil { - return err - } - - return nil -} - -func (m *JobStatus) validateProgress(formats strfmt.Registry) error { - if swag.IsZero(m.Progress) { // not required - return nil - } - - if err := validate.MaximumInt("progress", "body", int64(m.Progress), 100, false); err != nil { - return err - } - - return nil -} - -func (m *JobStatus) validateState(formats strfmt.Registry) error { - - if err := validate.RequiredString("state", "body", m.State); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this job status based on the context it is used -func (m *JobStatus) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateDefinitionHash(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *JobStatus) contextValidateDefinitionHash(ctx context.Context, formats strfmt.Registry) error { - - if err := validate.ReadOnly(ctx, "definitionHash", "body", string(m.DefinitionHash)); err != nil { - return err - } - - return nil -} - -// MarshalBinary interface implementation -func (m *JobStatus) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *JobStatus) UnmarshalBinary(b []byte) error { - var res JobStatus - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/generated/model/paginated_job_list.go b/generated/model/paginated_job_list.go deleted file mode 100644 index 14efd70e..00000000 --- a/generated/model/paginated_job_list.go +++ /dev/null @@ -1,223 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package model - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// PaginatedJobList Paginated list of jobs -// -// swagger:model PaginatedJobList -type PaginatedJobList struct { - - // content - Content []*Job `json:"content"` - - // pagination - Pagination *PaginatedJobListPagination `json:"pagination,omitempty"` -} - -// Validate validates this paginated job list -func (m *PaginatedJobList) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateContent(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePagination(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PaginatedJobList) validateContent(formats strfmt.Registry) error { - if swag.IsZero(m.Content) { // not required - return nil - } - - for i := 0; i < len(m.Content); i++ { - if swag.IsZero(m.Content[i]) { // not required - continue - } - - if m.Content[i] != nil { - if err := m.Content[i].Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("content" + "." + strconv.Itoa(i)) - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("content" + "." + strconv.Itoa(i)) - } - return err - } - } - - } - - return nil -} - -func (m *PaginatedJobList) validatePagination(formats strfmt.Registry) error { - if swag.IsZero(m.Pagination) { // not required - return nil - } - - if m.Pagination != nil { - if err := m.Pagination.Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("pagination") - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("pagination") - } - return err - } - } - - return nil -} - -// ContextValidate validate this paginated job list based on the context it is used -func (m *PaginatedJobList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateContent(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidatePagination(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PaginatedJobList) contextValidateContent(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Content); i++ { - - if m.Content[i] != nil { - - if swag.IsZero(m.Content[i]) { // not required - return nil - } - - if err := m.Content[i].ContextValidate(ctx, formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("content" + "." + strconv.Itoa(i)) - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("content" + "." + strconv.Itoa(i)) - } - return err - } - } - - } - - return nil -} - -func (m *PaginatedJobList) contextValidatePagination(ctx context.Context, formats strfmt.Registry) error { - - if m.Pagination != nil { - - if swag.IsZero(m.Pagination) { // not required - return nil - } - - if err := m.Pagination.ContextValidate(ctx, formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("pagination") - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("pagination") - } - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *PaginatedJobList) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PaginatedJobList) UnmarshalBinary(b []byte) error { - var res PaginatedJobList - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} - -// PaginatedJobListPagination paginated job list pagination -// -// swagger:model PaginatedJobListPagination -type PaginatedJobListPagination struct { - - // the maximum number of items to return - // Example: 20 - Limit int32 `json:"limit,omitempty"` - - // the number of items to skip before starting to return results - // Example: 0 - Offset int64 `json:"offset,omitempty"` - - // the total number of items - // Example: 1000 - Total int64 `json:"total,omitempty"` -} - -// Validate validates this paginated job list pagination -func (m *PaginatedJobListPagination) Validate(formats strfmt.Registry) error { - return nil -} - -// ContextValidate validates this paginated job list pagination based on context it is used -func (m *PaginatedJobListPagination) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *PaginatedJobListPagination) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PaginatedJobListPagination) UnmarshalBinary(b []byte) error { - var res PaginatedJobListPagination - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/generated/model/paginated_workflow_list.go b/generated/model/paginated_workflow_list.go deleted file mode 100644 index 7d1d9de5..00000000 --- a/generated/model/paginated_workflow_list.go +++ /dev/null @@ -1,223 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package model - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// PaginatedWorkflowList Paginated list of workflows -// -// swagger:model PaginatedWorkflowList -type PaginatedWorkflowList struct { - - // content - Content []*Workflow `json:"content"` - - // pagination - Pagination *PaginatedWorkflowListPagination `json:"pagination,omitempty"` -} - -// Validate validates this paginated workflow list -func (m *PaginatedWorkflowList) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateContent(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePagination(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PaginatedWorkflowList) validateContent(formats strfmt.Registry) error { - if swag.IsZero(m.Content) { // not required - return nil - } - - for i := 0; i < len(m.Content); i++ { - if swag.IsZero(m.Content[i]) { // not required - continue - } - - if m.Content[i] != nil { - if err := m.Content[i].Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("content" + "." + strconv.Itoa(i)) - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("content" + "." + strconv.Itoa(i)) - } - return err - } - } - - } - - return nil -} - -func (m *PaginatedWorkflowList) validatePagination(formats strfmt.Registry) error { - if swag.IsZero(m.Pagination) { // not required - return nil - } - - if m.Pagination != nil { - if err := m.Pagination.Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("pagination") - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("pagination") - } - return err - } - } - - return nil -} - -// ContextValidate validate this paginated workflow list based on the context it is used -func (m *PaginatedWorkflowList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateContent(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidatePagination(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PaginatedWorkflowList) contextValidateContent(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Content); i++ { - - if m.Content[i] != nil { - - if swag.IsZero(m.Content[i]) { // not required - return nil - } - - if err := m.Content[i].ContextValidate(ctx, formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("content" + "." + strconv.Itoa(i)) - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("content" + "." + strconv.Itoa(i)) - } - return err - } - } - - } - - return nil -} - -func (m *PaginatedWorkflowList) contextValidatePagination(ctx context.Context, formats strfmt.Registry) error { - - if m.Pagination != nil { - - if swag.IsZero(m.Pagination) { // not required - return nil - } - - if err := m.Pagination.ContextValidate(ctx, formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("pagination") - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("pagination") - } - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *PaginatedWorkflowList) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PaginatedWorkflowList) UnmarshalBinary(b []byte) error { - var res PaginatedWorkflowList - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} - -// PaginatedWorkflowListPagination paginated workflow list pagination -// -// swagger:model PaginatedWorkflowListPagination -type PaginatedWorkflowListPagination struct { - - // the maximum number of items to return - // Example: 20 - Limit int32 `json:"limit,omitempty"` - - // the number of items to skip before starting to return results - // Example: 0 - Offset int64 `json:"offset,omitempty"` - - // the total number of items - // Example: 1000 - Total int64 `json:"total,omitempty"` -} - -// Validate validates this paginated workflow list pagination -func (m *PaginatedWorkflowListPagination) Validate(formats strfmt.Registry) error { - return nil -} - -// ContextValidate validates this paginated workflow list pagination based on context it is used -func (m *PaginatedWorkflowListPagination) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *PaginatedWorkflowListPagination) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PaginatedWorkflowListPagination) UnmarshalBinary(b []byte) error { - var res PaginatedWorkflowListPagination - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/generated/model/state.go b/generated/model/state.go deleted file mode 100644 index 6d4880ee..00000000 --- a/generated/model/state.go +++ /dev/null @@ -1,81 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package model - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// State state -// -// swagger:model State -type State struct { - - // description - // Example: Description of the state - Description string `json:"description,omitempty"` - - // name - // Example: START - // Required: true - Name string `json:"name"` -} - -// Validate validates this state -func (m *State) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *State) validateName(formats strfmt.Registry) error { - - if err := validate.RequiredString("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this state based on context it is used -func (m *State) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *State) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *State) UnmarshalBinary(b []byte) error { - var res State - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/generated/model/transition.go b/generated/model/transition.go deleted file mode 100644 index 7b86d478..00000000 --- a/generated/model/transition.go +++ /dev/null @@ -1,196 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package model - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Transition transition -// -// swagger:model Transition -type Transition struct { - - // The transition execution action (default: WAIT) - // Example: WAIT - Action ActionEnum `json:"action,omitempty"` - - // description - // Example: Description of the transition - Description string `json:"description,omitempty"` - - // The entity that may execute the transition - // Example: CLIENT - // Required: true - Eligible EligibleEnum `json:"eligible"` - - // from - // Example: START - // Required: true - From string `json:"from"` - - // to - // Example: END - // Required: true - To string `json:"to"` -} - -// Validate validates this transition -func (m *Transition) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateAction(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEligible(formats); err != nil { - res = append(res, err) - } - - if err := m.validateFrom(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTo(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Transition) validateAction(formats strfmt.Registry) error { - if swag.IsZero(m.Action) { // not required - return nil - } - - if err := m.Action.Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("action") - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("action") - } - return err - } - - return nil -} - -func (m *Transition) validateEligible(formats strfmt.Registry) error { - - if err := validate.Required("eligible", "body", EligibleEnum(m.Eligible)); err != nil { - return err - } - - if err := m.Eligible.Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("eligible") - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("eligible") - } - return err - } - - return nil -} - -func (m *Transition) validateFrom(formats strfmt.Registry) error { - - if err := validate.RequiredString("from", "body", m.From); err != nil { - return err - } - - return nil -} - -func (m *Transition) validateTo(formats strfmt.Registry) error { - - if err := validate.RequiredString("to", "body", m.To); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this transition based on the context it is used -func (m *Transition) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateAction(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateEligible(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Transition) contextValidateAction(ctx context.Context, formats strfmt.Registry) error { - - if swag.IsZero(m.Action) { // not required - return nil - } - - if err := m.Action.ContextValidate(ctx, formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("action") - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("action") - } - return err - } - - return nil -} - -func (m *Transition) contextValidateEligible(ctx context.Context, formats strfmt.Registry) error { - - if err := m.Eligible.ContextValidate(ctx, formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("eligible") - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("eligible") - } - return err - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Transition) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Transition) UnmarshalBinary(b []byte) error { - var res Transition - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/generated/model/workflow.go b/generated/model/workflow.go deleted file mode 100644 index 2650a760..00000000 --- a/generated/model/workflow.go +++ /dev/null @@ -1,326 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package model - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Workflow workflow -// -// swagger:model Workflow -type Workflow struct { - - // Description of the workflow - // Example: This is a workflow - // Max Length: 1024 - Description string `json:"description,omitempty"` - - // groups - // Max Items: 1024 - Groups []*Group `json:"groups,omitempty"` - - // User provided unique workflow name - // Example: wfx.workflow.dau.direct - // Required: true - // Max Length: 64 - // Min Length: 1 - // Pattern: ^[a-zA-Z0-9\-\.]+$ - Name string `json:"name"` - - // states - // Max Items: 4096 - States []*State `json:"states,omitempty"` - - // transitions - // Max Items: 16384 - Transitions []*Transition `json:"transitions,omitempty"` -} - -// Validate validates this workflow -func (m *Workflow) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateDescription(formats); err != nil { - res = append(res, err) - } - - if err := m.validateGroups(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStates(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTransitions(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Workflow) validateDescription(formats strfmt.Registry) error { - if swag.IsZero(m.Description) { // not required - return nil - } - - if err := validate.MaxLength("description", "body", m.Description, 1024); err != nil { - return err - } - - return nil -} - -func (m *Workflow) validateGroups(formats strfmt.Registry) error { - if swag.IsZero(m.Groups) { // not required - return nil - } - - iGroupsSize := int64(len(m.Groups)) - - if err := validate.MaxItems("groups", "body", iGroupsSize, 1024); err != nil { - return err - } - - for i := 0; i < len(m.Groups); i++ { - if swag.IsZero(m.Groups[i]) { // not required - continue - } - - if m.Groups[i] != nil { - if err := m.Groups[i].Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("groups" + "." + strconv.Itoa(i)) - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("groups" + "." + strconv.Itoa(i)) - } - return err - } - } - - } - - return nil -} - -func (m *Workflow) validateName(formats strfmt.Registry) error { - - if err := validate.RequiredString("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", m.Name, 1); err != nil { - return err - } - - if err := validate.MaxLength("name", "body", m.Name, 64); err != nil { - return err - } - - if err := validate.Pattern("name", "body", m.Name, `^[a-zA-Z0-9\-\.]+$`); err != nil { - return err - } - - return nil -} - -func (m *Workflow) validateStates(formats strfmt.Registry) error { - if swag.IsZero(m.States) { // not required - return nil - } - - iStatesSize := int64(len(m.States)) - - if err := validate.MaxItems("states", "body", iStatesSize, 4096); err != nil { - return err - } - - for i := 0; i < len(m.States); i++ { - if swag.IsZero(m.States[i]) { // not required - continue - } - - if m.States[i] != nil { - if err := m.States[i].Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("states" + "." + strconv.Itoa(i)) - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("states" + "." + strconv.Itoa(i)) - } - return err - } - } - - } - - return nil -} - -func (m *Workflow) validateTransitions(formats strfmt.Registry) error { - if swag.IsZero(m.Transitions) { // not required - return nil - } - - iTransitionsSize := int64(len(m.Transitions)) - - if err := validate.MaxItems("transitions", "body", iTransitionsSize, 16384); err != nil { - return err - } - - for i := 0; i < len(m.Transitions); i++ { - if swag.IsZero(m.Transitions[i]) { // not required - continue - } - - if m.Transitions[i] != nil { - if err := m.Transitions[i].Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("transitions" + "." + strconv.Itoa(i)) - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("transitions" + "." + strconv.Itoa(i)) - } - return err - } - } - - } - - return nil -} - -// ContextValidate validate this workflow based on the context it is used -func (m *Workflow) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateGroups(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateStates(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateTransitions(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Workflow) contextValidateGroups(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Groups); i++ { - - if m.Groups[i] != nil { - - if swag.IsZero(m.Groups[i]) { // not required - return nil - } - - if err := m.Groups[i].ContextValidate(ctx, formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("groups" + "." + strconv.Itoa(i)) - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("groups" + "." + strconv.Itoa(i)) - } - return err - } - } - - } - - return nil -} - -func (m *Workflow) contextValidateStates(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.States); i++ { - - if m.States[i] != nil { - - if swag.IsZero(m.States[i]) { // not required - return nil - } - - if err := m.States[i].ContextValidate(ctx, formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("states" + "." + strconv.Itoa(i)) - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("states" + "." + strconv.Itoa(i)) - } - return err - } - } - - } - - return nil -} - -func (m *Workflow) contextValidateTransitions(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Transitions); i++ { - - if m.Transitions[i] != nil { - - if swag.IsZero(m.Transitions[i]) { // not required - return nil - } - - if err := m.Transitions[i].ContextValidate(ctx, formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("transitions" + "." + strconv.Itoa(i)) - } else if ce, ok := err.(*errors.CompositeError); ok { - return ce.ValidateName("transitions" + "." + strconv.Itoa(i)) - } - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Workflow) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Workflow) UnmarshalBinary(b []byte) error { - var res Workflow - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/generated/northbound/restapi/configure_workflow_executor.go b/generated/northbound/restapi/configure_workflow_executor.go deleted file mode 100644 index c10e7837..00000000 --- a/generated/northbound/restapi/configure_workflow_executor.go +++ /dev/null @@ -1,50 +0,0 @@ -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 - -package restapi - -import ( - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/rs/zerolog/log" - - "github.com/siemens/wfx/generated/northbound/restapi/operations" - "github.com/siemens/wfx/internal/producer" -) - -func ConfigureAPI(api *operations.WorkflowExecutorAPI) http.Handler { - // configure the api here - api.ServeError = func(rw http.ResponseWriter, r *http.Request, err error) { - log.Err(err).Msg("Serve error") - errors.ServeError(rw, r, err) - } - - api.Logger = log.Printf - - api.UseSwaggerUI() - - api.JSONConsumer = runtime.JSONConsumer() - - api.JSONProducer = producer.JSONProducer() - - api.TextEventStreamProducer = producer.TextEventStreamProducer() - - api.PreServerShutdown = func() {} - - return setupGlobalMiddleware(api.Serve(setupMiddlewares)) -} - -// The middleware configuration is for the handler executors. These do not apply to the swagger.json document. -// The middleware executes after routing but before authentication, binding and validation. -func setupMiddlewares(handler http.Handler) http.Handler { - return handler -} - -// The middleware configuration happens before anything, this middleware also applies to serving the swagger.json document. -// So this is a good place to plug in a panic handling middleware, logging and metrics -func setupGlobalMiddleware(handler http.Handler) http.Handler { - return handler -} diff --git a/generated/northbound/restapi/doc.go b/generated/northbound/restapi/doc.go deleted file mode 100644 index 5876cb2b..00000000 --- a/generated/northbound/restapi/doc.go +++ /dev/null @@ -1,24 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -// Package restapi Workflow Executor -// -// Schemes: -// http -// Host: localhost -// BasePath: /api/wfx/v1 -// Version: 1.0.0 -// License: Apache 2.0 http://www.apache.org/licenses/LICENSE-2.0.html -// -// Consumes: -// - application/json -// -// Produces: -// - application/json -// - text/event-stream -// -// swagger:meta -package restapi diff --git a/generated/northbound/restapi/embedded_spec.go b/generated/northbound/restapi/embedded_spec.go deleted file mode 100644 index edc8f3af..00000000 --- a/generated/northbound/restapi/embedded_spec.go +++ /dev/null @@ -1,3415 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package restapi - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "encoding/json" -) - -var ( - // SwaggerJSON embedded version of the swagger document used at generation time - SwaggerJSON json.RawMessage - // FlatSwaggerJSON embedded flattened version of the swagger document used at generation time - FlatSwaggerJSON json.RawMessage -) - -func init() { - SwaggerJSON = json.RawMessage([]byte(`{ - "schemes": [ - "http" - ], - "swagger": "2.0", - "info": { - "title": "Workflow Executor", - "license": { - "name": "Apache 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0.html" - }, - "version": "1.0.0", - "x-visibility": "external" - }, - "basePath": "/api/wfx/v1", - "paths": { - "/jobs": { - "get": { - "description": "List of job descriptions\nBy default, this endpoint returns the list of jobs in a specific order and predetermined paging properties.\nThese defaults are:\n - Ascending sort on stime\n - 10 entries per page\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "southbound", - "northbound" - ], - "summary": "List of job descriptions", - "parameters": [ - { - "$ref": "#/parameters/offset" - }, - { - "$ref": "#/parameters/limit" - }, - { - "$ref": "#/parameters/sort" - }, - { - "$ref": "#/parameters/state" - }, - { - "$ref": "#/parameters/group" - }, - { - "$ref": "#/parameters/clientId" - }, - { - "$ref": "#/parameters/workflow" - }, - { - "$ref": "#/parameters/tag" - } - ], - "responses": { - "200": { - "description": "A paginated job list.", - "schema": { - "$ref": "#/definitions/PaginatedJobList" - } - }, - "400": { - "description": "If request is invalid", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "post": { - "description": "Add a new job\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound" - ], - "summary": "Add a new job", - "parameters": [ - { - "description": "Job which shall be created", - "name": "Job", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/JobRequest" - } - } - ], - "responses": { - "201": { - "description": "Job was created", - "schema": { - "$ref": "#/definitions/Job" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - }, - "/jobs/events": { - "get": { - "description": "Obtain instant notifications when there are job changes matching the criteria. This endpoint utilizes server-sent events (SSE), where responses are \"chunked\" with double newline breaks. For example, a single event might look like this:\n data: {\"clientId\":\"example_client\",\"state\":\"INSTALLING\"}\\n\\n\n", - "produces": [ - "application/json", - "text/event-stream" - ], - "tags": [ - "jobs", - "northbound", - "southbound" - ], - "summary": "Subscribe to job-related events such as status updates", - "parameters": [ - { - "type": "string", - "description": "The job's clientId must be one of these clientIds (comma-separated).", - "name": "clientIds", - "in": "query" - }, - { - "type": "string", - "description": "The job's id must be one of these ids (comma-separated).", - "name": "jobIds", - "in": "query" - }, - { - "type": "string", - "description": "The job's workflow must be equal to one of the provided workflow names (comma-separated).", - "name": "workflows", - "in": "query" - }, - { - "type": "string", - "description": "A (comma-separated) list of tags to include into each job event. This can be used to aggregrate events from multiple wfx instances.\n", - "name": "tags", - "in": "query" - } - ], - "responses": { - "200": { - "description": "A stream of server-sent events" - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.jobTerminalState", - "logref": "916f0a913a3e4a52a96bd271e029c201", - "message": "The request was invalid because the job is in a terminal state" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format" - } - } - } - }, - "/jobs/{id}": { - "get": { - "description": "Job description for a given ID\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "southbound", - "northbound" - ], - "summary": "Job description for a given ID", - "parameters": [ - { - "$ref": "#/parameters/jobId" - }, - { - "$ref": "#/parameters/history" - } - ], - "responses": { - "200": { - "description": "Job description for for a given ID", - "schema": { - "$ref": "#/definitions/Job" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while querying a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "delete": { - "description": "Delete an existing job\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound" - ], - "summary": "Delete an existing job", - "parameters": [ - { - "$ref": "#/parameters/jobId" - } - ], - "responses": { - "204": { - "description": "The job has been deleted." - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while querying a non-existent workflow": { - "errors": [ - { - "code": "wfx.workflowNotFound", - "logref": "c452719774086b6e803bb8f6ecea9899", - "message": "Workflow not found for given name" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - }, - "/jobs/{id}/definition": { - "get": { - "description": "Retrieve the job definition", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound", - "southbound" - ], - "summary": "Get job definition", - "parameters": [ - { - "$ref": "#/parameters/jobId" - } - ], - "responses": { - "200": { - "description": "Job definition", - "schema": { - "type": "object", - "additionalProperties": { - "type": "object" - }, - "example": "{ \"userDefined\": {} }\n" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "put": { - "description": "Modify the job definition of an existing job\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "southbound", - "northbound" - ], - "summary": "Modify job definition", - "parameters": [ - { - "$ref": "#/parameters/jobId" - }, - { - "description": "How to modify the job", - "name": "JobDefinition", - "in": "body", - "required": true, - "schema": { - "type": "object", - "additionalProperties": { - "type": "object" - }, - "example": "{ \"userDefined\": {} }\n" - } - } - ], - "responses": { - "200": { - "description": "Job modified successfully", - "schema": { - "type": "object", - "additionalProperties": { - "type": "object" - }, - "example": "{ \"userDefined\": {} }\n" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - }, - "/jobs/{id}/status": { - "get": { - "description": "Retrieve the job status", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound", - "southbound" - ], - "summary": "Get job status", - "parameters": [ - { - "$ref": "#/parameters/jobId" - } - ], - "responses": { - "200": { - "description": "Job status", - "schema": { - "$ref": "#/definitions/JobStatus" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "put": { - "description": "Modify status of an existing job\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "southbound", - "northbound" - ], - "summary": "Modify status of an existing job", - "parameters": [ - { - "$ref": "#/parameters/jobId" - }, - { - "description": "This contains the new job status", - "name": "New job status", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/JobStatus" - } - } - ], - "responses": { - "200": { - "description": "Job modified successfully", - "schema": { - "$ref": "#/definitions/JobStatus" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - }, - "/jobs/{id}/tags": { - "get": { - "description": "Get the tags of a job", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound", - "southbound" - ], - "summary": "Get tags", - "parameters": [ - { - "$ref": "#/parameters/jobId" - } - ], - "responses": { - "200": { - "description": "Job tags", - "schema": { - "type": "array", - "items": { - "type": "string", - "example": "EUROPE_WEST" - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "post": { - "description": "Add a tag to an existing job\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound" - ], - "summary": "Add a tag", - "parameters": [ - { - "$ref": "#/parameters/jobId" - }, - { - "description": "Tags to add", - "name": "Tags", - "in": "body", - "required": true, - "schema": { - "type": "array", - "maxItems": 16, - "minItems": 1, - "items": { - "type": "string" - } - } - } - ], - "responses": { - "200": { - "description": "Successfully added tag to job", - "schema": { - "type": "array", - "items": { - "type": "string", - "example": "EUROPE_WEST" - } - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "delete": { - "description": "Delete a tag from an existing job\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound" - ], - "summary": "Delete a tag", - "parameters": [ - { - "$ref": "#/parameters/jobId" - }, - { - "description": "Tags to add", - "name": "Tags", - "in": "body", - "required": true, - "schema": { - "type": "array", - "maxItems": 16, - "minItems": 1, - "items": { - "type": "string" - } - } - } - ], - "responses": { - "200": { - "description": "Successfully deleted tag", - "schema": { - "type": "array", - "items": { - "type": "string", - "example": "EUROPE_WEST" - } - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - }, - "/workflows": { - "get": { - "description": "List of available workflows", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "workflows", - "northbound", - "southbound" - ], - "summary": "List of available workflows", - "parameters": [ - { - "$ref": "#/parameters/limit" - }, - { - "$ref": "#/parameters/offset" - }, - { - "$ref": "#/parameters/sort" - } - ], - "responses": { - "200": { - "description": "A list of workflows", - "schema": { - "$ref": "#/definitions/PaginatedWorkflowList" - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "post": { - "description": "Add a new workflow", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "workflows", - "northbound" - ], - "summary": "Add a new workflow", - "parameters": [ - { - "description": "Workflow object to be added", - "name": "Workflow", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/Workflow" - } - } - ], - "responses": { - "201": { - "description": "Workflow was created", - "schema": { - "$ref": "#/definitions/Workflow" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.workflowNotUnique", - "logref": "e1ee1f2aea859b9dd34579610e386da6", - "message": "Workflow with name already exists" - }, - { - "code": "wfx.workflowInvalid", - "logref": "18f57adc70dd79c7fb4f1246be8a6e04", - "message": "Workflow validation failed" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - }, - "/workflows/{name}": { - "get": { - "description": "Workflow description for a given name", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "workflows", - "northbound", - "southbound" - ], - "summary": "Workflow description for a given name", - "parameters": [ - { - "type": "string", - "description": "Unique name for the workflow", - "name": "name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Workflow description with the provided key", - "schema": { - "$ref": "#/definitions/Workflow" - } - }, - "400": { - "description": "If request is invalid", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while querying a non-existent workflow": { - "errors": [ - { - "code": "wfx.workflowNotFound", - "logref": "c452719774086b6e803bb8f6ecea9899", - "message": "Workflow not found for given name" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "delete": { - "description": "Delete an existing workflow\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "workflows", - "northbound" - ], - "summary": "Delete an existing workflow", - "parameters": [ - { - "type": "string", - "description": "Workflow name", - "name": "name", - "in": "path", - "required": true - } - ], - "responses": { - "204": { - "description": "The workflow has been deleted." - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while querying a non-existent workflow": { - "errors": [ - { - "code": "wfx.workflowNotFound", - "logref": "c452719774086b6e803bb8f6ecea9899", - "message": "Workflow not found for given name" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - } - }, - "definitions": { - "ActionEnum": { - "type": "string", - "enum": [ - "IMMEDIATE", - "WAIT" - ] - }, - "EligibleEnum": { - "type": "string", - "enum": [ - "CLIENT", - "WFX" - ], - "x-nullable": false - }, - "Error": { - "type": "object", - "properties": { - "code": { - "description": "Identifier code for the reason of the error", - "type": "string" - }, - "logref": { - "description": "Log correlation ID", - "type": "string" - }, - "message": { - "description": "Error message", - "type": "string" - } - } - }, - "ErrorResponse": { - "type": "object", - "properties": { - "errors": { - "type": "array", - "maxItems": 128, - "items": { - "$ref": "#/definitions/Error" - } - } - } - }, - "Group": { - "type": "object", - "required": [ - "name", - "states" - ], - "properties": { - "description": { - "type": "string", - "example": "Description of the group" - }, - "name": { - "type": "string", - "x-nullable": false, - "example": "OPEN" - }, - "states": { - "description": "A list of states belonging to this group", - "type": "array", - "maxItems": 4096, - "minItems": 1, - "items": { - "type": "string" - } - } - } - }, - "History": { - "type": "object", - "properties": { - "definition": { - "type": "object", - "additionalProperties": { - "type": "object" - }, - "example": "{ \"userDefined\": {} }\n" - }, - "mtime": { - "description": "Date and time (ISO8601) when the job was modified (set by wfx)", - "type": "string", - "format": "date-time", - "readOnly": true - }, - "status": { - "description": "A previous job status", - "$ref": "#/definitions/JobStatus" - } - } - }, - "Job": { - "type": "object", - "properties": { - "clientId": { - "type": "string", - "x-nullable": false, - "example": "client42" - }, - "definition": { - "type": "object", - "additionalProperties": { - "type": "object" - }, - "example": "{ \"userDefined\": {} }\n" - }, - "history": { - "description": "The job's history. Last in, first out (LIFO). Array is truncated if its length exceeds the maximum allowed length.\nBy default, the job history is omitted from responses unless explicitly requested by the client (see the ` + "`" + `history` + "`" + ` URL parameter).\n", - "type": "array", - "maxItems": 8192, - "items": { - "$ref": "#/definitions/History" - }, - "x-omitempty": true - }, - "id": { - "description": "Unique job ID (wfx-generated)", - "type": "string", - "maxLength": 36, - "x-nullable": false, - "readOnly": true, - "example": "3307e5cb-074c-49b7-99d4-5e61839a4c2d" - }, - "mtime": { - "description": "Date and time (ISO8601) when the job was last modified (set by wfx)", - "type": "string", - "format": "date-time", - "x-nullable": true, - "readOnly": true - }, - "status": { - "$ref": "#/definitions/JobStatus" - }, - "stime": { - "description": "Date and time (ISO8601) when the job was created (set by wfx). Although stime conceptually always exists, it's nullable because we don't want to serialize stime in some cases (e.g. for job events).", - "type": "string", - "format": "date-time", - "x-nullable": true, - "readOnly": true - }, - "tags": { - "type": "array", - "items": { - "type": "string", - "maxItems": 16 - }, - "x-omitempty": true - }, - "workflow": { - "$ref": "#/definitions/Workflow" - } - } - }, - "JobRequest": { - "type": "object", - "required": [ - "clientId", - "workflow" - ], - "properties": { - "clientId": { - "description": "Create job for the given client ID", - "type": "string", - "x-nullable": false, - "example": "client42" - }, - "definition": { - "description": "The existing job definition will be replaced with this if this property is not empty.", - "type": "object", - "additionalProperties": { - "type": "object" - }, - "example": "{ \"userDefined\": {} }\n" - }, - "tags": { - "type": "array", - "maxItems": 16, - "items": { - "type": "string", - "example": "EUROPE_WEST" - } - }, - "workflow": { - "description": "Workflow name", - "type": "string", - "x-nullable": false, - "example": "wfx.workflow.dau.direct" - } - } - }, - "JobStatus": { - "description": "Job status information", - "type": "object", - "required": [ - "state" - ], - "properties": { - "clientId": { - "description": "Client which sent the status update", - "type": "string", - "x-nullable": false, - "example": "client42" - }, - "context": { - "description": "Client-specific JSON object to report additional context information such as error details, stack traces, etc", - "type": "object", - "maxLength": 20000, - "additionalProperties": { - "type": "object" - }, - "example": "{\n \"lines\": [ \"line1\", \"line2\" ]\n}\n" - }, - "definitionHash": { - "description": "Job definition hash", - "type": "string", - "maxLength": 64, - "readOnly": true - }, - "message": { - "description": "Reason message/info, free text from client", - "type": "string", - "maxLength": 1024 - }, - "progress": { - "description": "Current job progress percentage", - "type": "number", - "format": "int32", - "maximum": 100 - }, - "state": { - "description": "Name of the new workflow state", - "type": "string", - "x-nullable": false, - "example": "END" - } - } - }, - "PaginatedJobList": { - "description": "Paginated list of jobs", - "type": "object", - "properties": { - "content": { - "type": "array", - "items": { - "$ref": "#/definitions/Job" - } - }, - "pagination": { - "type": "object", - "properties": { - "limit": { - "description": "the maximum number of items to return", - "type": "integer", - "format": "int32", - "example": 20 - }, - "offset": { - "description": "the number of items to skip before starting to return results", - "type": "integer", - "format": "int64", - "example": 0 - }, - "total": { - "description": "the total number of items", - "type": "integer", - "format": "int64", - "example": 1000 - } - } - } - } - }, - "PaginatedWorkflowList": { - "description": "Paginated list of workflows", - "type": "object", - "properties": { - "content": { - "type": "array", - "items": { - "$ref": "#/definitions/Workflow" - } - }, - "pagination": { - "type": "object", - "properties": { - "limit": { - "description": "the maximum number of items to return", - "type": "integer", - "format": "int32", - "example": 20 - }, - "offset": { - "description": "the number of items to skip before starting to return results", - "type": "integer", - "format": "int64", - "example": 0 - }, - "total": { - "description": "the total number of items", - "type": "integer", - "format": "int64", - "example": 1000 - } - } - } - } - }, - "State": { - "type": "object", - "required": [ - "name" - ], - "properties": { - "description": { - "type": "string", - "example": "Description of the state" - }, - "name": { - "type": "string", - "x-nullable": false, - "example": "START" - } - } - }, - "Transition": { - "type": "object", - "required": [ - "from", - "to", - "eligible" - ], - "properties": { - "action": { - "description": "The transition execution action (default: WAIT)", - "$ref": "#/definitions/ActionEnum", - "example": "WAIT" - }, - "description": { - "type": "string", - "example": "Description of the transition" - }, - "eligible": { - "description": "The entity that may execute the transition", - "$ref": "#/definitions/EligibleEnum", - "example": "CLIENT" - }, - "from": { - "type": "string", - "x-nullable": false, - "example": "START" - }, - "to": { - "type": "string", - "x-nullable": false, - "example": "END" - } - } - }, - "Workflow": { - "type": "object", - "required": [ - "name" - ], - "properties": { - "description": { - "description": "Description of the workflow", - "type": "string", - "maxLength": 1024, - "example": "This is a workflow" - }, - "groups": { - "type": "array", - "maxItems": 1024, - "items": { - "$ref": "#/definitions/Group" - }, - "x-omitempty": true - }, - "name": { - "description": "User provided unique workflow name", - "type": "string", - "maxLength": 64, - "minLength": 1, - "pattern": "^[a-zA-Z0-9\\-\\.]+$", - "x-nullable": false, - "example": "wfx.workflow.dau.direct" - }, - "states": { - "type": "array", - "maxItems": 4096, - "items": { - "$ref": "#/definitions/State" - }, - "x-omitempty": true - }, - "transitions": { - "type": "array", - "maxItems": 16384, - "items": { - "$ref": "#/definitions/Transition" - }, - "x-omitempty": true - } - } - } - }, - "parameters": { - "clientId": { - "type": "string", - "description": "Filter jobs belonging to a specific client with clientId", - "name": "clientId", - "in": "query" - }, - "group": { - "type": "array", - "items": { - "type": "string" - }, - "description": "Filter jobs based on the group they are in", - "name": "group", - "in": "query" - }, - "history": { - "type": "boolean", - "description": "Boolean flag to include the transition history of the job", - "name": "history", - "in": "query" - }, - "jobId": { - "type": "string", - "description": "Job ID", - "name": "id", - "in": "path", - "required": true - }, - "limit": { - "maxItems": 1024, - "type": "integer", - "format": "int32", - "default": 10, - "description": "the maximum number of items to return", - "name": "limit", - "in": "query" - }, - "offset": { - "type": "integer", - "format": "int64", - "default": 0, - "description": "the number of items to skip before starting to return results", - "name": "offset", - "in": "query" - }, - "sort": { - "enum": [ - "asc", - "desc" - ], - "type": "string", - "default": "asc", - "description": "the order of returned elements", - "name": "sort", - "in": "query" - }, - "state": { - "type": "string", - "description": "Filter jobs based on the current state value", - "name": "state", - "in": "query" - }, - "tag": { - "type": "array", - "items": { - "type": "string" - }, - "description": "Filter jobs by tags", - "name": "tag", - "in": "query" - }, - "workflow": { - "type": "string", - "description": "Filter jobs matching by workflow", - "name": "workflow", - "in": "query" - } - }, - "tags": [ - { - "description": "Workflows used to instantiate jobs", - "name": "workflows" - }, - { - "description": "Jobs derived from workflows and executed by a client", - "name": "jobs" - }, - { - "description": "All southbound API endpoints", - "name": "southbound" - }, - { - "description": "All northbound API endpoints", - "name": "northbound" - } - ], - "x-definitions-templates": { - "Limits": { - "maxErrorCount": { - "maxItems": 128 - }, - "maxGroupCount": { - "maxItems": 1024 - }, - "maxHistoryCount": { - "maxItems": 8192 - }, - "maxItemsCount": { - "maxItems": 1024 - }, - "maxStateCount": { - "maxItems": 4096 - }, - "maxTagsCount": { - "maxItems": 16 - }, - "maxTransitionCount": { - "maxItems": 16384 - } - }, - "Pagination": { - "pagination": { - "properties": { - "limit": { - "description": "the maximum number of items to return", - "example": 20, - "format": "int32", - "type": "integer" - }, - "offset": { - "description": "the number of items to skip before starting to return results", - "example": 0, - "format": "int64", - "type": "integer" - }, - "total": { - "description": "the total number of items", - "example": 1000, - "format": "int64", - "type": "integer" - } - }, - "type": "object" - } - } - }, - "x-paths-templates": { - "Errors": { - "invalidRequestError": { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - }, - "jobNotFoundError": { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - }, - "jobTerminalStateError": { - "code": "wfx.jobTerminalState", - "logref": "916f0a913a3e4a52a96bd271e029c201", - "message": "The request was invalid because the job is in a terminal state" - }, - "workflowInvalidError": { - "code": "wfx.workflowInvalid", - "logref": "18f57adc70dd79c7fb4f1246be8a6e04", - "message": "Workflow validation failed" - }, - "workflowNotFoundError": { - "code": "wfx.workflowNotFound", - "logref": "c452719774086b6e803bb8f6ecea9899", - "message": "Workflow not found for given name" - }, - "workflowNotUniqueError": { - "code": "wfx.workflowNotUnique", - "logref": "e1ee1f2aea859b9dd34579610e386da6", - "message": "Workflow with name already exists" - } - } - } -}`)) - FlatSwaggerJSON = json.RawMessage([]byte(`{ - "schemes": [ - "http" - ], - "swagger": "2.0", - "info": { - "title": "Workflow Executor", - "license": { - "name": "Apache 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0.html" - }, - "version": "1.0.0", - "x-visibility": "external" - }, - "basePath": "/api/wfx/v1", - "paths": { - "/jobs": { - "get": { - "description": "List of job descriptions\nBy default, this endpoint returns the list of jobs in a specific order and predetermined paging properties.\nThese defaults are:\n - Ascending sort on stime\n - 10 entries per page\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "southbound", - "northbound" - ], - "summary": "List of job descriptions", - "parameters": [ - { - "type": "integer", - "format": "int64", - "default": 0, - "description": "the number of items to skip before starting to return results", - "name": "offset", - "in": "query" - }, - { - "maxItems": 1024, - "type": "integer", - "format": "int32", - "default": 10, - "description": "the maximum number of items to return", - "name": "limit", - "in": "query" - }, - { - "enum": [ - "asc", - "desc" - ], - "type": "string", - "default": "asc", - "description": "the order of returned elements", - "name": "sort", - "in": "query" - }, - { - "type": "string", - "description": "Filter jobs based on the current state value", - "name": "state", - "in": "query" - }, - { - "type": "array", - "items": { - "type": "string" - }, - "description": "Filter jobs based on the group they are in", - "name": "group", - "in": "query" - }, - { - "type": "string", - "description": "Filter jobs belonging to a specific client with clientId", - "name": "clientId", - "in": "query" - }, - { - "type": "string", - "description": "Filter jobs matching by workflow", - "name": "workflow", - "in": "query" - }, - { - "type": "array", - "items": { - "type": "string" - }, - "description": "Filter jobs by tags", - "name": "tag", - "in": "query" - } - ], - "responses": { - "200": { - "description": "A paginated job list.", - "schema": { - "$ref": "#/definitions/PaginatedJobList" - } - }, - "400": { - "description": "If request is invalid", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "post": { - "description": "Add a new job\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound" - ], - "summary": "Add a new job", - "parameters": [ - { - "description": "Job which shall be created", - "name": "Job", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/JobRequest" - } - } - ], - "responses": { - "201": { - "description": "Job was created", - "schema": { - "$ref": "#/definitions/Job" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - }, - "/jobs/events": { - "get": { - "description": "Obtain instant notifications when there are job changes matching the criteria. This endpoint utilizes server-sent events (SSE), where responses are \"chunked\" with double newline breaks. For example, a single event might look like this:\n data: {\"clientId\":\"example_client\",\"state\":\"INSTALLING\"}\\n\\n\n", - "produces": [ - "application/json", - "text/event-stream" - ], - "tags": [ - "jobs", - "northbound", - "southbound" - ], - "summary": "Subscribe to job-related events such as status updates", - "parameters": [ - { - "type": "string", - "description": "The job's clientId must be one of these clientIds (comma-separated).", - "name": "clientIds", - "in": "query" - }, - { - "type": "string", - "description": "The job's id must be one of these ids (comma-separated).", - "name": "jobIds", - "in": "query" - }, - { - "type": "string", - "description": "The job's workflow must be equal to one of the provided workflow names (comma-separated).", - "name": "workflows", - "in": "query" - }, - { - "type": "string", - "description": "A (comma-separated) list of tags to include into each job event. This can be used to aggregrate events from multiple wfx instances.\n", - "name": "tags", - "in": "query" - } - ], - "responses": { - "200": { - "description": "A stream of server-sent events" - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.jobTerminalState", - "logref": "916f0a913a3e4a52a96bd271e029c201", - "message": "The request was invalid because the job is in a terminal state" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format" - } - } - } - }, - "/jobs/{id}": { - "get": { - "description": "Job description for a given ID\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "southbound", - "northbound" - ], - "summary": "Job description for a given ID", - "parameters": [ - { - "type": "string", - "description": "Job ID", - "name": "id", - "in": "path", - "required": true - }, - { - "type": "boolean", - "description": "Boolean flag to include the transition history of the job", - "name": "history", - "in": "query" - } - ], - "responses": { - "200": { - "description": "Job description for for a given ID", - "schema": { - "$ref": "#/definitions/Job" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while querying a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "delete": { - "description": "Delete an existing job\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound" - ], - "summary": "Delete an existing job", - "parameters": [ - { - "type": "string", - "description": "Job ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "204": { - "description": "The job has been deleted." - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while querying a non-existent workflow": { - "errors": [ - { - "code": "wfx.workflowNotFound", - "logref": "c452719774086b6e803bb8f6ecea9899", - "message": "Workflow not found for given name" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - }, - "/jobs/{id}/definition": { - "get": { - "description": "Retrieve the job definition", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound", - "southbound" - ], - "summary": "Get job definition", - "parameters": [ - { - "type": "string", - "description": "Job ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Job definition", - "schema": { - "type": "object", - "additionalProperties": { - "type": "object" - }, - "example": "{ \"userDefined\": {} }\n" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "put": { - "description": "Modify the job definition of an existing job\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "southbound", - "northbound" - ], - "summary": "Modify job definition", - "parameters": [ - { - "type": "string", - "description": "Job ID", - "name": "id", - "in": "path", - "required": true - }, - { - "description": "How to modify the job", - "name": "JobDefinition", - "in": "body", - "required": true, - "schema": { - "type": "object", - "additionalProperties": { - "type": "object" - }, - "example": "{ \"userDefined\": {} }\n" - } - } - ], - "responses": { - "200": { - "description": "Job modified successfully", - "schema": { - "type": "object", - "additionalProperties": { - "type": "object" - }, - "example": "{ \"userDefined\": {} }\n" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - }, - "/jobs/{id}/status": { - "get": { - "description": "Retrieve the job status", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound", - "southbound" - ], - "summary": "Get job status", - "parameters": [ - { - "type": "string", - "description": "Job ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Job status", - "schema": { - "$ref": "#/definitions/JobStatus" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "put": { - "description": "Modify status of an existing job\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "southbound", - "northbound" - ], - "summary": "Modify status of an existing job", - "parameters": [ - { - "type": "string", - "description": "Job ID", - "name": "id", - "in": "path", - "required": true - }, - { - "description": "This contains the new job status", - "name": "New job status", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/JobStatus" - } - } - ], - "responses": { - "200": { - "description": "Job modified successfully", - "schema": { - "$ref": "#/definitions/JobStatus" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - }, - "/jobs/{id}/tags": { - "get": { - "description": "Get the tags of a job", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound", - "southbound" - ], - "summary": "Get tags", - "parameters": [ - { - "type": "string", - "description": "Job ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Job tags", - "schema": { - "type": "array", - "items": { - "type": "string", - "example": "EUROPE_WEST" - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "post": { - "description": "Add a tag to an existing job\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound" - ], - "summary": "Add a tag", - "parameters": [ - { - "type": "string", - "description": "Job ID", - "name": "id", - "in": "path", - "required": true - }, - { - "description": "Tags to add", - "name": "Tags", - "in": "body", - "required": true, - "schema": { - "type": "array", - "maxItems": 16, - "minItems": 1, - "items": { - "type": "string" - } - } - } - ], - "responses": { - "200": { - "description": "Successfully added tag to job", - "schema": { - "type": "array", - "items": { - "type": "string", - "example": "EUROPE_WEST" - } - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "delete": { - "description": "Delete a tag from an existing job\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound" - ], - "summary": "Delete a tag", - "parameters": [ - { - "type": "string", - "description": "Job ID", - "name": "id", - "in": "path", - "required": true - }, - { - "description": "Tags to add", - "name": "Tags", - "in": "body", - "required": true, - "schema": { - "type": "array", - "maxItems": 16, - "minItems": 1, - "items": { - "type": "string" - } - } - } - ], - "responses": { - "200": { - "description": "Successfully deleted tag", - "schema": { - "type": "array", - "items": { - "type": "string", - "example": "EUROPE_WEST" - } - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - }, - "/workflows": { - "get": { - "description": "List of available workflows", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "workflows", - "northbound", - "southbound" - ], - "summary": "List of available workflows", - "parameters": [ - { - "maxItems": 1024, - "type": "integer", - "format": "int32", - "default": 10, - "description": "the maximum number of items to return", - "name": "limit", - "in": "query" - }, - { - "type": "integer", - "format": "int64", - "default": 0, - "description": "the number of items to skip before starting to return results", - "name": "offset", - "in": "query" - }, - { - "enum": [ - "asc", - "desc" - ], - "type": "string", - "default": "asc", - "description": "the order of returned elements", - "name": "sort", - "in": "query" - } - ], - "responses": { - "200": { - "description": "A list of workflows", - "schema": { - "$ref": "#/definitions/PaginatedWorkflowList" - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "post": { - "description": "Add a new workflow", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "workflows", - "northbound" - ], - "summary": "Add a new workflow", - "parameters": [ - { - "description": "Workflow object to be added", - "name": "Workflow", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/Workflow" - } - } - ], - "responses": { - "201": { - "description": "Workflow was created", - "schema": { - "$ref": "#/definitions/Workflow" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.workflowNotUnique", - "logref": "e1ee1f2aea859b9dd34579610e386da6", - "message": "Workflow with name already exists" - }, - { - "code": "wfx.workflowInvalid", - "logref": "18f57adc70dd79c7fb4f1246be8a6e04", - "message": "Workflow validation failed" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - }, - "/workflows/{name}": { - "get": { - "description": "Workflow description for a given name", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "workflows", - "northbound", - "southbound" - ], - "summary": "Workflow description for a given name", - "parameters": [ - { - "type": "string", - "description": "Unique name for the workflow", - "name": "name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Workflow description with the provided key", - "schema": { - "$ref": "#/definitions/Workflow" - } - }, - "400": { - "description": "If request is invalid", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while querying a non-existent workflow": { - "errors": [ - { - "code": "wfx.workflowNotFound", - "logref": "c452719774086b6e803bb8f6ecea9899", - "message": "Workflow not found for given name" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "delete": { - "description": "Delete an existing workflow\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "workflows", - "northbound" - ], - "summary": "Delete an existing workflow", - "parameters": [ - { - "type": "string", - "description": "Workflow name", - "name": "name", - "in": "path", - "required": true - } - ], - "responses": { - "204": { - "description": "The workflow has been deleted." - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while querying a non-existent workflow": { - "errors": [ - { - "code": "wfx.workflowNotFound", - "logref": "c452719774086b6e803bb8f6ecea9899", - "message": "Workflow not found for given name" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - } - }, - "definitions": { - "ActionEnum": { - "type": "string", - "enum": [ - "IMMEDIATE", - "WAIT" - ] - }, - "EligibleEnum": { - "type": "string", - "enum": [ - "CLIENT", - "WFX" - ], - "x-nullable": false - }, - "Error": { - "type": "object", - "properties": { - "code": { - "description": "Identifier code for the reason of the error", - "type": "string" - }, - "logref": { - "description": "Log correlation ID", - "type": "string" - }, - "message": { - "description": "Error message", - "type": "string" - } - } - }, - "ErrorResponse": { - "type": "object", - "properties": { - "errors": { - "type": "array", - "maxItems": 128, - "items": { - "$ref": "#/definitions/Error" - } - } - } - }, - "Group": { - "type": "object", - "required": [ - "name", - "states" - ], - "properties": { - "description": { - "type": "string", - "example": "Description of the group" - }, - "name": { - "type": "string", - "x-nullable": false, - "example": "OPEN" - }, - "states": { - "description": "A list of states belonging to this group", - "type": "array", - "maxItems": 4096, - "minItems": 1, - "items": { - "type": "string" - } - } - } - }, - "History": { - "type": "object", - "properties": { - "definition": { - "type": "object", - "additionalProperties": { - "type": "object" - }, - "example": "{ \"userDefined\": {} }\n" - }, - "mtime": { - "description": "Date and time (ISO8601) when the job was modified (set by wfx)", - "type": "string", - "format": "date-time", - "readOnly": true - }, - "status": { - "description": "A previous job status", - "$ref": "#/definitions/JobStatus" - } - } - }, - "Job": { - "type": "object", - "properties": { - "clientId": { - "type": "string", - "x-nullable": false, - "example": "client42" - }, - "definition": { - "type": "object", - "additionalProperties": { - "type": "object" - }, - "example": "{ \"userDefined\": {} }\n" - }, - "history": { - "description": "The job's history. Last in, first out (LIFO). Array is truncated if its length exceeds the maximum allowed length.\nBy default, the job history is omitted from responses unless explicitly requested by the client (see the ` + "`" + `history` + "`" + ` URL parameter).\n", - "type": "array", - "maxItems": 8192, - "items": { - "$ref": "#/definitions/History" - }, - "x-omitempty": true - }, - "id": { - "description": "Unique job ID (wfx-generated)", - "type": "string", - "maxLength": 36, - "x-nullable": false, - "readOnly": true, - "example": "3307e5cb-074c-49b7-99d4-5e61839a4c2d" - }, - "mtime": { - "description": "Date and time (ISO8601) when the job was last modified (set by wfx)", - "type": "string", - "format": "date-time", - "x-nullable": true, - "readOnly": true - }, - "status": { - "$ref": "#/definitions/JobStatus" - }, - "stime": { - "description": "Date and time (ISO8601) when the job was created (set by wfx). Although stime conceptually always exists, it's nullable because we don't want to serialize stime in some cases (e.g. for job events).", - "type": "string", - "format": "date-time", - "x-nullable": true, - "readOnly": true - }, - "tags": { - "type": "array", - "items": { - "type": "string" - }, - "x-omitempty": true - }, - "workflow": { - "$ref": "#/definitions/Workflow" - } - } - }, - "JobRequest": { - "type": "object", - "required": [ - "clientId", - "workflow" - ], - "properties": { - "clientId": { - "description": "Create job for the given client ID", - "type": "string", - "x-nullable": false, - "example": "client42" - }, - "definition": { - "description": "The existing job definition will be replaced with this if this property is not empty.", - "type": "object", - "additionalProperties": { - "type": "object" - }, - "example": "{ \"userDefined\": {} }\n" - }, - "tags": { - "type": "array", - "maxItems": 16, - "items": { - "type": "string", - "example": "EUROPE_WEST" - } - }, - "workflow": { - "description": "Workflow name", - "type": "string", - "x-nullable": false, - "example": "wfx.workflow.dau.direct" - } - } - }, - "JobStatus": { - "description": "Job status information", - "type": "object", - "required": [ - "state" - ], - "properties": { - "clientId": { - "description": "Client which sent the status update", - "type": "string", - "x-nullable": false, - "example": "client42" - }, - "context": { - "description": "Client-specific JSON object to report additional context information such as error details, stack traces, etc", - "type": "object", - "maxLength": 20000, - "minLength": 0, - "additionalProperties": { - "type": "object" - }, - "example": "{\n \"lines\": [ \"line1\", \"line2\" ]\n}\n" - }, - "definitionHash": { - "description": "Job definition hash", - "type": "string", - "maxLength": 64, - "readOnly": true - }, - "message": { - "description": "Reason message/info, free text from client", - "type": "string", - "maxLength": 1024 - }, - "progress": { - "description": "Current job progress percentage", - "type": "number", - "format": "int32", - "maximum": 100 - }, - "state": { - "description": "Name of the new workflow state", - "type": "string", - "x-nullable": false, - "example": "END" - } - } - }, - "PaginatedJobList": { - "description": "Paginated list of jobs", - "type": "object", - "properties": { - "content": { - "type": "array", - "items": { - "$ref": "#/definitions/Job" - } - }, - "pagination": { - "type": "object", - "properties": { - "limit": { - "description": "the maximum number of items to return", - "type": "integer", - "format": "int32", - "example": 20 - }, - "offset": { - "description": "the number of items to skip before starting to return results", - "type": "integer", - "format": "int64", - "example": 0 - }, - "total": { - "description": "the total number of items", - "type": "integer", - "format": "int64", - "example": 1000 - } - } - } - } - }, - "PaginatedJobListPagination": { - "type": "object", - "properties": { - "limit": { - "description": "the maximum number of items to return", - "type": "integer", - "format": "int32", - "example": 20 - }, - "offset": { - "description": "the number of items to skip before starting to return results", - "type": "integer", - "format": "int64", - "example": 0 - }, - "total": { - "description": "the total number of items", - "type": "integer", - "format": "int64", - "example": 1000 - } - } - }, - "PaginatedWorkflowList": { - "description": "Paginated list of workflows", - "type": "object", - "properties": { - "content": { - "type": "array", - "items": { - "$ref": "#/definitions/Workflow" - } - }, - "pagination": { - "type": "object", - "properties": { - "limit": { - "description": "the maximum number of items to return", - "type": "integer", - "format": "int32", - "example": 20 - }, - "offset": { - "description": "the number of items to skip before starting to return results", - "type": "integer", - "format": "int64", - "example": 0 - }, - "total": { - "description": "the total number of items", - "type": "integer", - "format": "int64", - "example": 1000 - } - } - } - } - }, - "PaginatedWorkflowListPagination": { - "type": "object", - "properties": { - "limit": { - "description": "the maximum number of items to return", - "type": "integer", - "format": "int32", - "example": 20 - }, - "offset": { - "description": "the number of items to skip before starting to return results", - "type": "integer", - "format": "int64", - "example": 0 - }, - "total": { - "description": "the total number of items", - "type": "integer", - "format": "int64", - "example": 1000 - } - } - }, - "State": { - "type": "object", - "required": [ - "name" - ], - "properties": { - "description": { - "type": "string", - "example": "Description of the state" - }, - "name": { - "type": "string", - "x-nullable": false, - "example": "START" - } - } - }, - "Transition": { - "type": "object", - "required": [ - "from", - "to", - "eligible" - ], - "properties": { - "action": { - "description": "The transition execution action (default: WAIT)", - "$ref": "#/definitions/ActionEnum", - "example": "WAIT" - }, - "description": { - "type": "string", - "example": "Description of the transition" - }, - "eligible": { - "description": "The entity that may execute the transition", - "$ref": "#/definitions/EligibleEnum", - "example": "CLIENT" - }, - "from": { - "type": "string", - "x-nullable": false, - "example": "START" - }, - "to": { - "type": "string", - "x-nullable": false, - "example": "END" - } - } - }, - "Workflow": { - "type": "object", - "required": [ - "name" - ], - "properties": { - "description": { - "description": "Description of the workflow", - "type": "string", - "maxLength": 1024, - "example": "This is a workflow" - }, - "groups": { - "type": "array", - "maxItems": 1024, - "items": { - "$ref": "#/definitions/Group" - }, - "x-omitempty": true - }, - "name": { - "description": "User provided unique workflow name", - "type": "string", - "maxLength": 64, - "minLength": 1, - "pattern": "^[a-zA-Z0-9\\-\\.]+$", - "x-nullable": false, - "example": "wfx.workflow.dau.direct" - }, - "states": { - "type": "array", - "maxItems": 4096, - "items": { - "$ref": "#/definitions/State" - }, - "x-omitempty": true - }, - "transitions": { - "type": "array", - "maxItems": 16384, - "items": { - "$ref": "#/definitions/Transition" - }, - "x-omitempty": true - } - } - } - }, - "parameters": { - "clientId": { - "type": "string", - "description": "Filter jobs belonging to a specific client with clientId", - "name": "clientId", - "in": "query" - }, - "group": { - "type": "array", - "items": { - "type": "string" - }, - "description": "Filter jobs based on the group they are in", - "name": "group", - "in": "query" - }, - "history": { - "type": "boolean", - "description": "Boolean flag to include the transition history of the job", - "name": "history", - "in": "query" - }, - "jobId": { - "type": "string", - "description": "Job ID", - "name": "id", - "in": "path", - "required": true - }, - "limit": { - "maxItems": 1024, - "type": "integer", - "format": "int32", - "default": 10, - "description": "the maximum number of items to return", - "name": "limit", - "in": "query" - }, - "offset": { - "type": "integer", - "format": "int64", - "default": 0, - "description": "the number of items to skip before starting to return results", - "name": "offset", - "in": "query" - }, - "sort": { - "enum": [ - "asc", - "desc" - ], - "type": "string", - "default": "asc", - "description": "the order of returned elements", - "name": "sort", - "in": "query" - }, - "state": { - "type": "string", - "description": "Filter jobs based on the current state value", - "name": "state", - "in": "query" - }, - "tag": { - "type": "array", - "items": { - "type": "string" - }, - "description": "Filter jobs by tags", - "name": "tag", - "in": "query" - }, - "workflow": { - "type": "string", - "description": "Filter jobs matching by workflow", - "name": "workflow", - "in": "query" - } - }, - "tags": [ - { - "description": "Workflows used to instantiate jobs", - "name": "workflows" - }, - { - "description": "Jobs derived from workflows and executed by a client", - "name": "jobs" - }, - { - "description": "All southbound API endpoints", - "name": "southbound" - }, - { - "description": "All northbound API endpoints", - "name": "northbound" - } - ], - "x-definitions-templates": { - "Limits": { - "maxErrorCount": { - "maxItems": 128 - }, - "maxGroupCount": { - "maxItems": 1024 - }, - "maxHistoryCount": { - "maxItems": 8192 - }, - "maxItemsCount": { - "maxItems": 1024 - }, - "maxStateCount": { - "maxItems": 4096 - }, - "maxTagsCount": { - "maxItems": 16 - }, - "maxTransitionCount": { - "maxItems": 16384 - } - }, - "Pagination": { - "pagination": { - "properties": { - "limit": { - "description": "the maximum number of items to return", - "example": 20, - "format": "int32", - "type": "integer" - }, - "offset": { - "description": "the number of items to skip before starting to return results", - "example": 0, - "format": "int64", - "type": "integer" - }, - "total": { - "description": "the total number of items", - "example": 1000, - "format": "int64", - "type": "integer" - } - }, - "type": "object" - } - } - }, - "x-paths-templates": { - "Errors": { - "invalidRequestError": { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - }, - "jobNotFoundError": { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - }, - "jobTerminalStateError": { - "code": "wfx.jobTerminalState", - "logref": "916f0a913a3e4a52a96bd271e029c201", - "message": "The request was invalid because the job is in a terminal state" - }, - "workflowInvalidError": { - "code": "wfx.workflowInvalid", - "logref": "18f57adc70dd79c7fb4f1246be8a6e04", - "message": "Workflow validation failed" - }, - "workflowNotFoundError": { - "code": "wfx.workflowNotFound", - "logref": "c452719774086b6e803bb8f6ecea9899", - "message": "Workflow not found for given name" - }, - "workflowNotUniqueError": { - "code": "wfx.workflowNotUnique", - "logref": "e1ee1f2aea859b9dd34579610e386da6", - "message": "Workflow with name already exists" - } - } - } -}`)) -} diff --git a/generated/northbound/restapi/operations/northbound/delete_jobs_id.go b/generated/northbound/restapi/operations/northbound/delete_jobs_id.go deleted file mode 100644 index ebd255ab..00000000 --- a/generated/northbound/restapi/operations/northbound/delete_jobs_id.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// DeleteJobsIDHandlerFunc turns a function with the right signature into a delete jobs ID handler -type DeleteJobsIDHandlerFunc func(DeleteJobsIDParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn DeleteJobsIDHandlerFunc) Handle(params DeleteJobsIDParams) middleware.Responder { - return fn(params) -} - -// DeleteJobsIDHandler interface for that can handle valid delete jobs ID params -type DeleteJobsIDHandler interface { - Handle(DeleteJobsIDParams) middleware.Responder -} - -// NewDeleteJobsID creates a new http.Handler for the delete jobs ID operation -func NewDeleteJobsID(ctx *middleware.Context, handler DeleteJobsIDHandler) *DeleteJobsID { - return &DeleteJobsID{Context: ctx, Handler: handler} -} - -/* - DeleteJobsID swagger:route DELETE /jobs/{id} northbound deleteJobsId - -# Delete an existing job - -Delete an existing job -*/ -type DeleteJobsID struct { - Context *middleware.Context - Handler DeleteJobsIDHandler -} - -func (o *DeleteJobsID) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewDeleteJobsIDParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/northbound/restapi/operations/northbound/delete_jobs_id_parameters.go b/generated/northbound/restapi/operations/northbound/delete_jobs_id_parameters.go deleted file mode 100644 index 0a74fdea..00000000 --- a/generated/northbound/restapi/operations/northbound/delete_jobs_id_parameters.go +++ /dev/null @@ -1,76 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" -) - -// NewDeleteJobsIDParams creates a new DeleteJobsIDParams object -// -// There are no default values defined in the spec. -func NewDeleteJobsIDParams() DeleteJobsIDParams { - - return DeleteJobsIDParams{} -} - -// DeleteJobsIDParams contains all the bound params for the delete jobs ID operation -// typically these are obtained from a http.Request -// -// swagger:parameters DeleteJobsID -type DeleteJobsIDParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*Job ID - Required: true - In: path - */ - ID string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewDeleteJobsIDParams() beforehand. -func (o *DeleteJobsIDParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - rID, rhkID, _ := route.Params.GetOK("id") - if err := o.bindID(rID, rhkID, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindID binds and validates parameter ID from path. -func (o *DeleteJobsIDParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: true - // Parameter is provided by construction from the route - o.ID = raw - - return nil -} diff --git a/generated/northbound/restapi/operations/northbound/delete_jobs_id_responses.go b/generated/northbound/restapi/operations/northbound/delete_jobs_id_responses.go deleted file mode 100644 index df9fb50f..00000000 --- a/generated/northbound/restapi/operations/northbound/delete_jobs_id_responses.go +++ /dev/null @@ -1,127 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// DeleteJobsIDNoContentCode is the HTTP code returned for type DeleteJobsIDNoContent -const DeleteJobsIDNoContentCode int = 204 - -/* -DeleteJobsIDNoContent The job has been deleted. - -swagger:response deleteJobsIdNoContent -*/ -type DeleteJobsIDNoContent struct { -} - -// NewDeleteJobsIDNoContent creates DeleteJobsIDNoContent with default headers values -func NewDeleteJobsIDNoContent() *DeleteJobsIDNoContent { - - return &DeleteJobsIDNoContent{} -} - -// WriteResponse to the client -func (o *DeleteJobsIDNoContent) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(204) -} - -// DeleteJobsIDNotFoundCode is the HTTP code returned for type DeleteJobsIDNotFound -const DeleteJobsIDNotFoundCode int = 404 - -/* -DeleteJobsIDNotFound Not Found - -swagger:response deleteJobsIdNotFound -*/ -type DeleteJobsIDNotFound struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewDeleteJobsIDNotFound creates DeleteJobsIDNotFound with default headers values -func NewDeleteJobsIDNotFound() *DeleteJobsIDNotFound { - - return &DeleteJobsIDNotFound{} -} - -// WithPayload adds the payload to the delete jobs Id not found response -func (o *DeleteJobsIDNotFound) WithPayload(payload *model.ErrorResponse) *DeleteJobsIDNotFound { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the delete jobs Id not found response -func (o *DeleteJobsIDNotFound) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *DeleteJobsIDNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(404) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -DeleteJobsIDDefault Other error with any status code and response body format. - -swagger:response deleteJobsIdDefault -*/ -type DeleteJobsIDDefault struct { - _statusCode int -} - -// NewDeleteJobsIDDefault creates DeleteJobsIDDefault with default headers values -func NewDeleteJobsIDDefault(code int) *DeleteJobsIDDefault { - if code <= 0 { - code = 500 - } - - return &DeleteJobsIDDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the delete jobs ID default response -func (o *DeleteJobsIDDefault) WithStatusCode(code int) *DeleteJobsIDDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the delete jobs ID default response -func (o *DeleteJobsIDDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *DeleteJobsIDDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/northbound/restapi/operations/northbound/delete_jobs_id_tags.go b/generated/northbound/restapi/operations/northbound/delete_jobs_id_tags.go deleted file mode 100644 index 6663b1af..00000000 --- a/generated/northbound/restapi/operations/northbound/delete_jobs_id_tags.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// DeleteJobsIDTagsHandlerFunc turns a function with the right signature into a delete jobs ID tags handler -type DeleteJobsIDTagsHandlerFunc func(DeleteJobsIDTagsParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn DeleteJobsIDTagsHandlerFunc) Handle(params DeleteJobsIDTagsParams) middleware.Responder { - return fn(params) -} - -// DeleteJobsIDTagsHandler interface for that can handle valid delete jobs ID tags params -type DeleteJobsIDTagsHandler interface { - Handle(DeleteJobsIDTagsParams) middleware.Responder -} - -// NewDeleteJobsIDTags creates a new http.Handler for the delete jobs ID tags operation -func NewDeleteJobsIDTags(ctx *middleware.Context, handler DeleteJobsIDTagsHandler) *DeleteJobsIDTags { - return &DeleteJobsIDTags{Context: ctx, Handler: handler} -} - -/* - DeleteJobsIDTags swagger:route DELETE /jobs/{id}/tags northbound deleteJobsIdTags - -# Delete a tag - -Delete a tag from an existing job -*/ -type DeleteJobsIDTags struct { - Context *middleware.Context - Handler DeleteJobsIDTagsHandler -} - -func (o *DeleteJobsIDTags) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewDeleteJobsIDTagsParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/northbound/restapi/operations/northbound/delete_jobs_id_tags_parameters.go b/generated/northbound/restapi/operations/northbound/delete_jobs_id_tags_parameters.go deleted file mode 100644 index 37443bb6..00000000 --- a/generated/northbound/restapi/operations/northbound/delete_jobs_id_tags_parameters.go +++ /dev/null @@ -1,123 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "io" - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/validate" -) - -// NewDeleteJobsIDTagsParams creates a new DeleteJobsIDTagsParams object -// -// There are no default values defined in the spec. -func NewDeleteJobsIDTagsParams() DeleteJobsIDTagsParams { - - return DeleteJobsIDTagsParams{} -} - -// DeleteJobsIDTagsParams contains all the bound params for the delete jobs ID tags operation -// typically these are obtained from a http.Request -// -// swagger:parameters DeleteJobsIDTags -type DeleteJobsIDTagsParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*Tags to add - Required: true - Max Items: 16 - Min Items: 1 - In: body - */ - Tags []string - /*Job ID - Required: true - In: path - */ - ID string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewDeleteJobsIDTagsParams() beforehand. -func (o *DeleteJobsIDTagsParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - if runtime.HasBody(r) { - defer r.Body.Close() - var body []string - if err := route.Consumer.Consume(r.Body, &body); err != nil { - if err == io.EOF { - res = append(res, errors.Required("tags", "body", "")) - } else { - res = append(res, errors.NewParseError("tags", "body", "", err)) - } - } else { - // validate inline body array - o.Tags = body - if err := o.validateTagsBody(route.Formats); err != nil { - res = append(res, err) - } - } - } else { - res = append(res, errors.Required("tags", "body", "")) - } - - rID, rhkID, _ := route.Params.GetOK("id") - if err := o.bindID(rID, rhkID, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// validateTagsBody validates an inline body parameter -func (o *DeleteJobsIDTagsParams) validateTagsBody(formats strfmt.Registry) error { - - tagsSize := int64(len(o.Tags)) - - // minItems: 1 - if err := validate.MinItems("Tags", "body", tagsSize, 1); err != nil { - return err - } - - // maxItems: 16 - if err := validate.MaxItems("Tags", "body", tagsSize, 16); err != nil { - return err - } - return nil -} - -// bindID binds and validates parameter ID from path. -func (o *DeleteJobsIDTagsParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: true - // Parameter is provided by construction from the route - o.ID = raw - - return nil -} diff --git a/generated/northbound/restapi/operations/northbound/delete_jobs_id_tags_responses.go b/generated/northbound/restapi/operations/northbound/delete_jobs_id_tags_responses.go deleted file mode 100644 index 0575b71c..00000000 --- a/generated/northbound/restapi/operations/northbound/delete_jobs_id_tags_responses.go +++ /dev/null @@ -1,195 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// DeleteJobsIDTagsOKCode is the HTTP code returned for type DeleteJobsIDTagsOK -const DeleteJobsIDTagsOKCode int = 200 - -/* -DeleteJobsIDTagsOK Successfully deleted tag - -swagger:response deleteJobsIdTagsOK -*/ -type DeleteJobsIDTagsOK struct { - - /* - In: Body - */ - Payload []string `json:"body,omitempty"` -} - -// NewDeleteJobsIDTagsOK creates DeleteJobsIDTagsOK with default headers values -func NewDeleteJobsIDTagsOK() *DeleteJobsIDTagsOK { - - return &DeleteJobsIDTagsOK{} -} - -// WithPayload adds the payload to the delete jobs Id tags o k response -func (o *DeleteJobsIDTagsOK) WithPayload(payload []string) *DeleteJobsIDTagsOK { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the delete jobs Id tags o k response -func (o *DeleteJobsIDTagsOK) SetPayload(payload []string) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *DeleteJobsIDTagsOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(200) - payload := o.Payload - if payload == nil { - // return empty array - payload = make([]string, 0, 50) - } - - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } -} - -// DeleteJobsIDTagsBadRequestCode is the HTTP code returned for type DeleteJobsIDTagsBadRequest -const DeleteJobsIDTagsBadRequestCode int = 400 - -/* -DeleteJobsIDTagsBadRequest Bad Request - -swagger:response deleteJobsIdTagsBadRequest -*/ -type DeleteJobsIDTagsBadRequest struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewDeleteJobsIDTagsBadRequest creates DeleteJobsIDTagsBadRequest with default headers values -func NewDeleteJobsIDTagsBadRequest() *DeleteJobsIDTagsBadRequest { - - return &DeleteJobsIDTagsBadRequest{} -} - -// WithPayload adds the payload to the delete jobs Id tags bad request response -func (o *DeleteJobsIDTagsBadRequest) WithPayload(payload *model.ErrorResponse) *DeleteJobsIDTagsBadRequest { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the delete jobs Id tags bad request response -func (o *DeleteJobsIDTagsBadRequest) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *DeleteJobsIDTagsBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(400) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// DeleteJobsIDTagsNotFoundCode is the HTTP code returned for type DeleteJobsIDTagsNotFound -const DeleteJobsIDTagsNotFoundCode int = 404 - -/* -DeleteJobsIDTagsNotFound Not Found - -swagger:response deleteJobsIdTagsNotFound -*/ -type DeleteJobsIDTagsNotFound struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewDeleteJobsIDTagsNotFound creates DeleteJobsIDTagsNotFound with default headers values -func NewDeleteJobsIDTagsNotFound() *DeleteJobsIDTagsNotFound { - - return &DeleteJobsIDTagsNotFound{} -} - -// WithPayload adds the payload to the delete jobs Id tags not found response -func (o *DeleteJobsIDTagsNotFound) WithPayload(payload *model.ErrorResponse) *DeleteJobsIDTagsNotFound { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the delete jobs Id tags not found response -func (o *DeleteJobsIDTagsNotFound) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *DeleteJobsIDTagsNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(404) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -DeleteJobsIDTagsDefault Other error with any status code and response body format. - -swagger:response deleteJobsIdTagsDefault -*/ -type DeleteJobsIDTagsDefault struct { - _statusCode int -} - -// NewDeleteJobsIDTagsDefault creates DeleteJobsIDTagsDefault with default headers values -func NewDeleteJobsIDTagsDefault(code int) *DeleteJobsIDTagsDefault { - if code <= 0 { - code = 500 - } - - return &DeleteJobsIDTagsDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the delete jobs ID tags default response -func (o *DeleteJobsIDTagsDefault) WithStatusCode(code int) *DeleteJobsIDTagsDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the delete jobs ID tags default response -func (o *DeleteJobsIDTagsDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *DeleteJobsIDTagsDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/northbound/restapi/operations/northbound/delete_jobs_id_tags_urlbuilder.go b/generated/northbound/restapi/operations/northbound/delete_jobs_id_tags_urlbuilder.go deleted file mode 100644 index 6b2a7a4e..00000000 --- a/generated/northbound/restapi/operations/northbound/delete_jobs_id_tags_urlbuilder.go +++ /dev/null @@ -1,104 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" - "strings" -) - -// DeleteJobsIDTagsURL generates an URL for the delete jobs ID tags operation -type DeleteJobsIDTagsURL struct { - ID string - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *DeleteJobsIDTagsURL) WithBasePath(bp string) *DeleteJobsIDTagsURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *DeleteJobsIDTagsURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *DeleteJobsIDTagsURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/jobs/{id}/tags" - - id := o.ID - if id != "" { - _path = strings.Replace(_path, "{id}", id, -1) - } else { - return nil, errors.New("id is required on DeleteJobsIDTagsURL") - } - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *DeleteJobsIDTagsURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *DeleteJobsIDTagsURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *DeleteJobsIDTagsURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on DeleteJobsIDTagsURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on DeleteJobsIDTagsURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *DeleteJobsIDTagsURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/northbound/restapi/operations/northbound/delete_jobs_id_urlbuilder.go b/generated/northbound/restapi/operations/northbound/delete_jobs_id_urlbuilder.go deleted file mode 100644 index 7ea3d3a9..00000000 --- a/generated/northbound/restapi/operations/northbound/delete_jobs_id_urlbuilder.go +++ /dev/null @@ -1,104 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" - "strings" -) - -// DeleteJobsIDURL generates an URL for the delete jobs ID operation -type DeleteJobsIDURL struct { - ID string - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *DeleteJobsIDURL) WithBasePath(bp string) *DeleteJobsIDURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *DeleteJobsIDURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *DeleteJobsIDURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/jobs/{id}" - - id := o.ID - if id != "" { - _path = strings.Replace(_path, "{id}", id, -1) - } else { - return nil, errors.New("id is required on DeleteJobsIDURL") - } - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *DeleteJobsIDURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *DeleteJobsIDURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *DeleteJobsIDURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on DeleteJobsIDURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on DeleteJobsIDURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *DeleteJobsIDURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/northbound/restapi/operations/northbound/delete_workflows_name.go b/generated/northbound/restapi/operations/northbound/delete_workflows_name.go deleted file mode 100644 index 6183f274..00000000 --- a/generated/northbound/restapi/operations/northbound/delete_workflows_name.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// DeleteWorkflowsNameHandlerFunc turns a function with the right signature into a delete workflows name handler -type DeleteWorkflowsNameHandlerFunc func(DeleteWorkflowsNameParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn DeleteWorkflowsNameHandlerFunc) Handle(params DeleteWorkflowsNameParams) middleware.Responder { - return fn(params) -} - -// DeleteWorkflowsNameHandler interface for that can handle valid delete workflows name params -type DeleteWorkflowsNameHandler interface { - Handle(DeleteWorkflowsNameParams) middleware.Responder -} - -// NewDeleteWorkflowsName creates a new http.Handler for the delete workflows name operation -func NewDeleteWorkflowsName(ctx *middleware.Context, handler DeleteWorkflowsNameHandler) *DeleteWorkflowsName { - return &DeleteWorkflowsName{Context: ctx, Handler: handler} -} - -/* - DeleteWorkflowsName swagger:route DELETE /workflows/{name} northbound deleteWorkflowsName - -# Delete an existing workflow - -Delete an existing workflow -*/ -type DeleteWorkflowsName struct { - Context *middleware.Context - Handler DeleteWorkflowsNameHandler -} - -func (o *DeleteWorkflowsName) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewDeleteWorkflowsNameParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/northbound/restapi/operations/northbound/delete_workflows_name_parameters.go b/generated/northbound/restapi/operations/northbound/delete_workflows_name_parameters.go deleted file mode 100644 index 1e137fbe..00000000 --- a/generated/northbound/restapi/operations/northbound/delete_workflows_name_parameters.go +++ /dev/null @@ -1,76 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" -) - -// NewDeleteWorkflowsNameParams creates a new DeleteWorkflowsNameParams object -// -// There are no default values defined in the spec. -func NewDeleteWorkflowsNameParams() DeleteWorkflowsNameParams { - - return DeleteWorkflowsNameParams{} -} - -// DeleteWorkflowsNameParams contains all the bound params for the delete workflows name operation -// typically these are obtained from a http.Request -// -// swagger:parameters DeleteWorkflowsName -type DeleteWorkflowsNameParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*Workflow name - Required: true - In: path - */ - Name string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewDeleteWorkflowsNameParams() beforehand. -func (o *DeleteWorkflowsNameParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - rName, rhkName, _ := route.Params.GetOK("name") - if err := o.bindName(rName, rhkName, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindName binds and validates parameter Name from path. -func (o *DeleteWorkflowsNameParams) bindName(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: true - // Parameter is provided by construction from the route - o.Name = raw - - return nil -} diff --git a/generated/northbound/restapi/operations/northbound/delete_workflows_name_responses.go b/generated/northbound/restapi/operations/northbound/delete_workflows_name_responses.go deleted file mode 100644 index 5f8c0c1e..00000000 --- a/generated/northbound/restapi/operations/northbound/delete_workflows_name_responses.go +++ /dev/null @@ -1,127 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// DeleteWorkflowsNameNoContentCode is the HTTP code returned for type DeleteWorkflowsNameNoContent -const DeleteWorkflowsNameNoContentCode int = 204 - -/* -DeleteWorkflowsNameNoContent The workflow has been deleted. - -swagger:response deleteWorkflowsNameNoContent -*/ -type DeleteWorkflowsNameNoContent struct { -} - -// NewDeleteWorkflowsNameNoContent creates DeleteWorkflowsNameNoContent with default headers values -func NewDeleteWorkflowsNameNoContent() *DeleteWorkflowsNameNoContent { - - return &DeleteWorkflowsNameNoContent{} -} - -// WriteResponse to the client -func (o *DeleteWorkflowsNameNoContent) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(204) -} - -// DeleteWorkflowsNameNotFoundCode is the HTTP code returned for type DeleteWorkflowsNameNotFound -const DeleteWorkflowsNameNotFoundCode int = 404 - -/* -DeleteWorkflowsNameNotFound Not Found - -swagger:response deleteWorkflowsNameNotFound -*/ -type DeleteWorkflowsNameNotFound struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewDeleteWorkflowsNameNotFound creates DeleteWorkflowsNameNotFound with default headers values -func NewDeleteWorkflowsNameNotFound() *DeleteWorkflowsNameNotFound { - - return &DeleteWorkflowsNameNotFound{} -} - -// WithPayload adds the payload to the delete workflows name not found response -func (o *DeleteWorkflowsNameNotFound) WithPayload(payload *model.ErrorResponse) *DeleteWorkflowsNameNotFound { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the delete workflows name not found response -func (o *DeleteWorkflowsNameNotFound) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *DeleteWorkflowsNameNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(404) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -DeleteWorkflowsNameDefault Other error with any status code and response body format. - -swagger:response deleteWorkflowsNameDefault -*/ -type DeleteWorkflowsNameDefault struct { - _statusCode int -} - -// NewDeleteWorkflowsNameDefault creates DeleteWorkflowsNameDefault with default headers values -func NewDeleteWorkflowsNameDefault(code int) *DeleteWorkflowsNameDefault { - if code <= 0 { - code = 500 - } - - return &DeleteWorkflowsNameDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the delete workflows name default response -func (o *DeleteWorkflowsNameDefault) WithStatusCode(code int) *DeleteWorkflowsNameDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the delete workflows name default response -func (o *DeleteWorkflowsNameDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *DeleteWorkflowsNameDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/northbound/restapi/operations/northbound/delete_workflows_name_urlbuilder.go b/generated/northbound/restapi/operations/northbound/delete_workflows_name_urlbuilder.go deleted file mode 100644 index e35d81a7..00000000 --- a/generated/northbound/restapi/operations/northbound/delete_workflows_name_urlbuilder.go +++ /dev/null @@ -1,104 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" - "strings" -) - -// DeleteWorkflowsNameURL generates an URL for the delete workflows name operation -type DeleteWorkflowsNameURL struct { - Name string - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *DeleteWorkflowsNameURL) WithBasePath(bp string) *DeleteWorkflowsNameURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *DeleteWorkflowsNameURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *DeleteWorkflowsNameURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/workflows/{name}" - - name := o.Name - if name != "" { - _path = strings.Replace(_path, "{name}", name, -1) - } else { - return nil, errors.New("name is required on DeleteWorkflowsNameURL") - } - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *DeleteWorkflowsNameURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *DeleteWorkflowsNameURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *DeleteWorkflowsNameURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on DeleteWorkflowsNameURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on DeleteWorkflowsNameURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *DeleteWorkflowsNameURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/northbound/restapi/operations/northbound/get_jobs.go b/generated/northbound/restapi/operations/northbound/get_jobs.go deleted file mode 100644 index 50a7acd1..00000000 --- a/generated/northbound/restapi/operations/northbound/get_jobs.go +++ /dev/null @@ -1,67 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// GetJobsHandlerFunc turns a function with the right signature into a get jobs handler -type GetJobsHandlerFunc func(GetJobsParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn GetJobsHandlerFunc) Handle(params GetJobsParams) middleware.Responder { - return fn(params) -} - -// GetJobsHandler interface for that can handle valid get jobs params -type GetJobsHandler interface { - Handle(GetJobsParams) middleware.Responder -} - -// NewGetJobs creates a new http.Handler for the get jobs operation -func NewGetJobs(ctx *middleware.Context, handler GetJobsHandler) *GetJobs { - return &GetJobs{Context: ctx, Handler: handler} -} - -/* - GetJobs swagger:route GET /jobs northbound getJobs - -# List of job descriptions - -List of job descriptions -By default, this endpoint returns the list of jobs in a specific order and predetermined paging properties. -These defaults are: - - Ascending sort on stime - - 10 entries per page -*/ -type GetJobs struct { - Context *middleware.Context - Handler GetJobsHandler -} - -func (o *GetJobs) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewGetJobsParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/northbound/restapi/operations/northbound/get_jobs_events.go b/generated/northbound/restapi/operations/northbound/get_jobs_events.go deleted file mode 100644 index 98855ad5..00000000 --- a/generated/northbound/restapi/operations/northbound/get_jobs_events.go +++ /dev/null @@ -1,65 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// GetJobsEventsHandlerFunc turns a function with the right signature into a get jobs events handler -type GetJobsEventsHandlerFunc func(GetJobsEventsParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn GetJobsEventsHandlerFunc) Handle(params GetJobsEventsParams) middleware.Responder { - return fn(params) -} - -// GetJobsEventsHandler interface for that can handle valid get jobs events params -type GetJobsEventsHandler interface { - Handle(GetJobsEventsParams) middleware.Responder -} - -// NewGetJobsEvents creates a new http.Handler for the get jobs events operation -func NewGetJobsEvents(ctx *middleware.Context, handler GetJobsEventsHandler) *GetJobsEvents { - return &GetJobsEvents{Context: ctx, Handler: handler} -} - -/* - GetJobsEvents swagger:route GET /jobs/events northbound getJobsEvents - -# Subscribe to job-related events such as status updates - -Obtain instant notifications when there are job changes matching the criteria. This endpoint utilizes server-sent events (SSE), where responses are "chunked" with double newline breaks. For example, a single event might look like this: - - data: {"clientId":"example_client","state":"INSTALLING"}\n\n -*/ -type GetJobsEvents struct { - Context *middleware.Context - Handler GetJobsEventsHandler -} - -func (o *GetJobsEvents) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewGetJobsEventsParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/northbound/restapi/operations/northbound/get_jobs_events_parameters.go b/generated/northbound/restapi/operations/northbound/get_jobs_events_parameters.go deleted file mode 100644 index 9d8d8f5d..00000000 --- a/generated/northbound/restapi/operations/northbound/get_jobs_events_parameters.go +++ /dev/null @@ -1,164 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" -) - -// NewGetJobsEventsParams creates a new GetJobsEventsParams object -// -// There are no default values defined in the spec. -func NewGetJobsEventsParams() GetJobsEventsParams { - - return GetJobsEventsParams{} -} - -// GetJobsEventsParams contains all the bound params for the get jobs events operation -// typically these are obtained from a http.Request -// -// swagger:parameters GetJobsEvents -type GetJobsEventsParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*The job's clientId must be one of these clientIds (comma-separated). - In: query - */ - ClientIds *string - /*The job's id must be one of these ids (comma-separated). - In: query - */ - JobIds *string - /*A (comma-separated) list of tags to include into each job event. This can be used to aggregrate events from multiple wfx instances. - - In: query - */ - Tags *string - /*The job's workflow must be equal to one of the provided workflow names (comma-separated). - In: query - */ - Workflows *string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewGetJobsEventsParams() beforehand. -func (o *GetJobsEventsParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - qs := runtime.Values(r.URL.Query()) - - qClientIds, qhkClientIds, _ := qs.GetOK("clientIds") - if err := o.bindClientIds(qClientIds, qhkClientIds, route.Formats); err != nil { - res = append(res, err) - } - - qJobIds, qhkJobIds, _ := qs.GetOK("jobIds") - if err := o.bindJobIds(qJobIds, qhkJobIds, route.Formats); err != nil { - res = append(res, err) - } - - qTags, qhkTags, _ := qs.GetOK("tags") - if err := o.bindTags(qTags, qhkTags, route.Formats); err != nil { - res = append(res, err) - } - - qWorkflows, qhkWorkflows, _ := qs.GetOK("workflows") - if err := o.bindWorkflows(qWorkflows, qhkWorkflows, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindClientIds binds and validates parameter ClientIds from query. -func (o *GetJobsEventsParams) bindClientIds(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - return nil - } - o.ClientIds = &raw - - return nil -} - -// bindJobIds binds and validates parameter JobIds from query. -func (o *GetJobsEventsParams) bindJobIds(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - return nil - } - o.JobIds = &raw - - return nil -} - -// bindTags binds and validates parameter Tags from query. -func (o *GetJobsEventsParams) bindTags(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - return nil - } - o.Tags = &raw - - return nil -} - -// bindWorkflows binds and validates parameter Workflows from query. -func (o *GetJobsEventsParams) bindWorkflows(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - return nil - } - o.Workflows = &raw - - return nil -} diff --git a/generated/northbound/restapi/operations/northbound/get_jobs_events_responses.go b/generated/northbound/restapi/operations/northbound/get_jobs_events_responses.go deleted file mode 100644 index 3c1da9e3..00000000 --- a/generated/northbound/restapi/operations/northbound/get_jobs_events_responses.go +++ /dev/null @@ -1,172 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// GetJobsEventsOKCode is the HTTP code returned for type GetJobsEventsOK -const GetJobsEventsOKCode int = 200 - -/* -GetJobsEventsOK A stream of server-sent events - -swagger:response getJobsEventsOK -*/ -type GetJobsEventsOK struct { -} - -// NewGetJobsEventsOK creates GetJobsEventsOK with default headers values -func NewGetJobsEventsOK() *GetJobsEventsOK { - - return &GetJobsEventsOK{} -} - -// WriteResponse to the client -func (o *GetJobsEventsOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(200) -} - -// GetJobsEventsBadRequestCode is the HTTP code returned for type GetJobsEventsBadRequest -const GetJobsEventsBadRequestCode int = 400 - -/* -GetJobsEventsBadRequest Bad Request - -swagger:response getJobsEventsBadRequest -*/ -type GetJobsEventsBadRequest struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewGetJobsEventsBadRequest creates GetJobsEventsBadRequest with default headers values -func NewGetJobsEventsBadRequest() *GetJobsEventsBadRequest { - - return &GetJobsEventsBadRequest{} -} - -// WithPayload adds the payload to the get jobs events bad request response -func (o *GetJobsEventsBadRequest) WithPayload(payload *model.ErrorResponse) *GetJobsEventsBadRequest { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs events bad request response -func (o *GetJobsEventsBadRequest) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsEventsBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(400) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// GetJobsEventsNotFoundCode is the HTTP code returned for type GetJobsEventsNotFound -const GetJobsEventsNotFoundCode int = 404 - -/* -GetJobsEventsNotFound Not Found - -swagger:response getJobsEventsNotFound -*/ -type GetJobsEventsNotFound struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewGetJobsEventsNotFound creates GetJobsEventsNotFound with default headers values -func NewGetJobsEventsNotFound() *GetJobsEventsNotFound { - - return &GetJobsEventsNotFound{} -} - -// WithPayload adds the payload to the get jobs events not found response -func (o *GetJobsEventsNotFound) WithPayload(payload *model.ErrorResponse) *GetJobsEventsNotFound { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs events not found response -func (o *GetJobsEventsNotFound) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsEventsNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(404) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -GetJobsEventsDefault Other error with any status code and response body format - -swagger:response getJobsEventsDefault -*/ -type GetJobsEventsDefault struct { - _statusCode int -} - -// NewGetJobsEventsDefault creates GetJobsEventsDefault with default headers values -func NewGetJobsEventsDefault(code int) *GetJobsEventsDefault { - if code <= 0 { - code = 500 - } - - return &GetJobsEventsDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the get jobs events default response -func (o *GetJobsEventsDefault) WithStatusCode(code int) *GetJobsEventsDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the get jobs events default response -func (o *GetJobsEventsDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *GetJobsEventsDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/northbound/restapi/operations/northbound/get_jobs_events_urlbuilder.go b/generated/northbound/restapi/operations/northbound/get_jobs_events_urlbuilder.go deleted file mode 100644 index 11810c10..00000000 --- a/generated/northbound/restapi/operations/northbound/get_jobs_events_urlbuilder.go +++ /dev/null @@ -1,135 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" -) - -// GetJobsEventsURL generates an URL for the get jobs events operation -type GetJobsEventsURL struct { - ClientIds *string - JobIds *string - Tags *string - Workflows *string - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetJobsEventsURL) WithBasePath(bp string) *GetJobsEventsURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetJobsEventsURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *GetJobsEventsURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/jobs/events" - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - qs := make(url.Values) - - var clientIdsQ string - if o.ClientIds != nil { - clientIdsQ = *o.ClientIds - } - if clientIdsQ != "" { - qs.Set("clientIds", clientIdsQ) - } - - var jobIdsQ string - if o.JobIds != nil { - jobIdsQ = *o.JobIds - } - if jobIdsQ != "" { - qs.Set("jobIds", jobIdsQ) - } - - var tagsQ string - if o.Tags != nil { - tagsQ = *o.Tags - } - if tagsQ != "" { - qs.Set("tags", tagsQ) - } - - var workflowsQ string - if o.Workflows != nil { - workflowsQ = *o.Workflows - } - if workflowsQ != "" { - qs.Set("workflows", workflowsQ) - } - - _result.RawQuery = qs.Encode() - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *GetJobsEventsURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *GetJobsEventsURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *GetJobsEventsURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on GetJobsEventsURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on GetJobsEventsURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *GetJobsEventsURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/northbound/restapi/operations/northbound/get_jobs_id.go b/generated/northbound/restapi/operations/northbound/get_jobs_id.go deleted file mode 100644 index aa8e5493..00000000 --- a/generated/northbound/restapi/operations/northbound/get_jobs_id.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// GetJobsIDHandlerFunc turns a function with the right signature into a get jobs ID handler -type GetJobsIDHandlerFunc func(GetJobsIDParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn GetJobsIDHandlerFunc) Handle(params GetJobsIDParams) middleware.Responder { - return fn(params) -} - -// GetJobsIDHandler interface for that can handle valid get jobs ID params -type GetJobsIDHandler interface { - Handle(GetJobsIDParams) middleware.Responder -} - -// NewGetJobsID creates a new http.Handler for the get jobs ID operation -func NewGetJobsID(ctx *middleware.Context, handler GetJobsIDHandler) *GetJobsID { - return &GetJobsID{Context: ctx, Handler: handler} -} - -/* - GetJobsID swagger:route GET /jobs/{id} northbound getJobsId - -# Job description for a given ID - -Job description for a given ID -*/ -type GetJobsID struct { - Context *middleware.Context - Handler GetJobsIDHandler -} - -func (o *GetJobsID) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewGetJobsIDParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/northbound/restapi/operations/northbound/get_jobs_id_definition.go b/generated/northbound/restapi/operations/northbound/get_jobs_id_definition.go deleted file mode 100644 index b5e24f82..00000000 --- a/generated/northbound/restapi/operations/northbound/get_jobs_id_definition.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// GetJobsIDDefinitionHandlerFunc turns a function with the right signature into a get jobs ID definition handler -type GetJobsIDDefinitionHandlerFunc func(GetJobsIDDefinitionParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn GetJobsIDDefinitionHandlerFunc) Handle(params GetJobsIDDefinitionParams) middleware.Responder { - return fn(params) -} - -// GetJobsIDDefinitionHandler interface for that can handle valid get jobs ID definition params -type GetJobsIDDefinitionHandler interface { - Handle(GetJobsIDDefinitionParams) middleware.Responder -} - -// NewGetJobsIDDefinition creates a new http.Handler for the get jobs ID definition operation -func NewGetJobsIDDefinition(ctx *middleware.Context, handler GetJobsIDDefinitionHandler) *GetJobsIDDefinition { - return &GetJobsIDDefinition{Context: ctx, Handler: handler} -} - -/* - GetJobsIDDefinition swagger:route GET /jobs/{id}/definition northbound getJobsIdDefinition - -# Get job definition - -Retrieve the job definition -*/ -type GetJobsIDDefinition struct { - Context *middleware.Context - Handler GetJobsIDDefinitionHandler -} - -func (o *GetJobsIDDefinition) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewGetJobsIDDefinitionParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/northbound/restapi/operations/northbound/get_jobs_id_definition_parameters.go b/generated/northbound/restapi/operations/northbound/get_jobs_id_definition_parameters.go deleted file mode 100644 index d7926253..00000000 --- a/generated/northbound/restapi/operations/northbound/get_jobs_id_definition_parameters.go +++ /dev/null @@ -1,76 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" -) - -// NewGetJobsIDDefinitionParams creates a new GetJobsIDDefinitionParams object -// -// There are no default values defined in the spec. -func NewGetJobsIDDefinitionParams() GetJobsIDDefinitionParams { - - return GetJobsIDDefinitionParams{} -} - -// GetJobsIDDefinitionParams contains all the bound params for the get jobs ID definition operation -// typically these are obtained from a http.Request -// -// swagger:parameters GetJobsIDDefinition -type GetJobsIDDefinitionParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*Job ID - Required: true - In: path - */ - ID string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewGetJobsIDDefinitionParams() beforehand. -func (o *GetJobsIDDefinitionParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - rID, rhkID, _ := route.Params.GetOK("id") - if err := o.bindID(rID, rhkID, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindID binds and validates parameter ID from path. -func (o *GetJobsIDDefinitionParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: true - // Parameter is provided by construction from the route - o.ID = raw - - return nil -} diff --git a/generated/northbound/restapi/operations/northbound/get_jobs_id_definition_responses.go b/generated/northbound/restapi/operations/northbound/get_jobs_id_definition_responses.go deleted file mode 100644 index 87a57bbf..00000000 --- a/generated/northbound/restapi/operations/northbound/get_jobs_id_definition_responses.go +++ /dev/null @@ -1,150 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// GetJobsIDDefinitionOKCode is the HTTP code returned for type GetJobsIDDefinitionOK -const GetJobsIDDefinitionOKCode int = 200 - -/* -GetJobsIDDefinitionOK Job definition - -swagger:response getJobsIdDefinitionOK -*/ -type GetJobsIDDefinitionOK struct { - - /* - In: Body - */ - Payload map[string]interface{} `json:"body,omitempty"` -} - -// NewGetJobsIDDefinitionOK creates GetJobsIDDefinitionOK with default headers values -func NewGetJobsIDDefinitionOK() *GetJobsIDDefinitionOK { - - return &GetJobsIDDefinitionOK{} -} - -// WithPayload adds the payload to the get jobs Id definition o k response -func (o *GetJobsIDDefinitionOK) WithPayload(payload map[string]interface{}) *GetJobsIDDefinitionOK { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs Id definition o k response -func (o *GetJobsIDDefinitionOK) SetPayload(payload map[string]interface{}) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsIDDefinitionOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(200) - payload := o.Payload - if payload == nil { - // return empty map - payload = make(map[string]interface{}, 50) - } - - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } -} - -// GetJobsIDDefinitionNotFoundCode is the HTTP code returned for type GetJobsIDDefinitionNotFound -const GetJobsIDDefinitionNotFoundCode int = 404 - -/* -GetJobsIDDefinitionNotFound Not Found - -swagger:response getJobsIdDefinitionNotFound -*/ -type GetJobsIDDefinitionNotFound struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewGetJobsIDDefinitionNotFound creates GetJobsIDDefinitionNotFound with default headers values -func NewGetJobsIDDefinitionNotFound() *GetJobsIDDefinitionNotFound { - - return &GetJobsIDDefinitionNotFound{} -} - -// WithPayload adds the payload to the get jobs Id definition not found response -func (o *GetJobsIDDefinitionNotFound) WithPayload(payload *model.ErrorResponse) *GetJobsIDDefinitionNotFound { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs Id definition not found response -func (o *GetJobsIDDefinitionNotFound) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsIDDefinitionNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(404) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -GetJobsIDDefinitionDefault Other error with any status code and response body format. - -swagger:response getJobsIdDefinitionDefault -*/ -type GetJobsIDDefinitionDefault struct { - _statusCode int -} - -// NewGetJobsIDDefinitionDefault creates GetJobsIDDefinitionDefault with default headers values -func NewGetJobsIDDefinitionDefault(code int) *GetJobsIDDefinitionDefault { - if code <= 0 { - code = 500 - } - - return &GetJobsIDDefinitionDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the get jobs ID definition default response -func (o *GetJobsIDDefinitionDefault) WithStatusCode(code int) *GetJobsIDDefinitionDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the get jobs ID definition default response -func (o *GetJobsIDDefinitionDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *GetJobsIDDefinitionDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/northbound/restapi/operations/northbound/get_jobs_id_definition_urlbuilder.go b/generated/northbound/restapi/operations/northbound/get_jobs_id_definition_urlbuilder.go deleted file mode 100644 index 3e51ced2..00000000 --- a/generated/northbound/restapi/operations/northbound/get_jobs_id_definition_urlbuilder.go +++ /dev/null @@ -1,104 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" - "strings" -) - -// GetJobsIDDefinitionURL generates an URL for the get jobs ID definition operation -type GetJobsIDDefinitionURL struct { - ID string - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetJobsIDDefinitionURL) WithBasePath(bp string) *GetJobsIDDefinitionURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetJobsIDDefinitionURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *GetJobsIDDefinitionURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/jobs/{id}/definition" - - id := o.ID - if id != "" { - _path = strings.Replace(_path, "{id}", id, -1) - } else { - return nil, errors.New("id is required on GetJobsIDDefinitionURL") - } - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *GetJobsIDDefinitionURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *GetJobsIDDefinitionURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *GetJobsIDDefinitionURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on GetJobsIDDefinitionURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on GetJobsIDDefinitionURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *GetJobsIDDefinitionURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/northbound/restapi/operations/northbound/get_jobs_id_parameters.go b/generated/northbound/restapi/operations/northbound/get_jobs_id_parameters.go deleted file mode 100644 index 90572ec2..00000000 --- a/generated/northbound/restapi/operations/northbound/get_jobs_id_parameters.go +++ /dev/null @@ -1,112 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// NewGetJobsIDParams creates a new GetJobsIDParams object -// -// There are no default values defined in the spec. -func NewGetJobsIDParams() GetJobsIDParams { - - return GetJobsIDParams{} -} - -// GetJobsIDParams contains all the bound params for the get jobs ID operation -// typically these are obtained from a http.Request -// -// swagger:parameters GetJobsID -type GetJobsIDParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*Boolean flag to include the transition history of the job - In: query - */ - History *bool - /*Job ID - Required: true - In: path - */ - ID string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewGetJobsIDParams() beforehand. -func (o *GetJobsIDParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - qs := runtime.Values(r.URL.Query()) - - qHistory, qhkHistory, _ := qs.GetOK("history") - if err := o.bindHistory(qHistory, qhkHistory, route.Formats); err != nil { - res = append(res, err) - } - - rID, rhkID, _ := route.Params.GetOK("id") - if err := o.bindID(rID, rhkID, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindHistory binds and validates parameter History from query. -func (o *GetJobsIDParams) bindHistory(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - return nil - } - - value, err := swag.ConvertBool(raw) - if err != nil { - return errors.InvalidType("history", "query", "bool", raw) - } - o.History = &value - - return nil -} - -// bindID binds and validates parameter ID from path. -func (o *GetJobsIDParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: true - // Parameter is provided by construction from the route - o.ID = raw - - return nil -} diff --git a/generated/northbound/restapi/operations/northbound/get_jobs_id_responses.go b/generated/northbound/restapi/operations/northbound/get_jobs_id_responses.go deleted file mode 100644 index 14ad48ef..00000000 --- a/generated/northbound/restapi/operations/northbound/get_jobs_id_responses.go +++ /dev/null @@ -1,192 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// GetJobsIDOKCode is the HTTP code returned for type GetJobsIDOK -const GetJobsIDOKCode int = 200 - -/* -GetJobsIDOK Job description for for a given ID - -swagger:response getJobsIdOK -*/ -type GetJobsIDOK struct { - - /* - In: Body - */ - Payload *model.Job `json:"body,omitempty"` -} - -// NewGetJobsIDOK creates GetJobsIDOK with default headers values -func NewGetJobsIDOK() *GetJobsIDOK { - - return &GetJobsIDOK{} -} - -// WithPayload adds the payload to the get jobs Id o k response -func (o *GetJobsIDOK) WithPayload(payload *model.Job) *GetJobsIDOK { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs Id o k response -func (o *GetJobsIDOK) SetPayload(payload *model.Job) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsIDOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(200) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// GetJobsIDBadRequestCode is the HTTP code returned for type GetJobsIDBadRequest -const GetJobsIDBadRequestCode int = 400 - -/* -GetJobsIDBadRequest Bad Request - -swagger:response getJobsIdBadRequest -*/ -type GetJobsIDBadRequest struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewGetJobsIDBadRequest creates GetJobsIDBadRequest with default headers values -func NewGetJobsIDBadRequest() *GetJobsIDBadRequest { - - return &GetJobsIDBadRequest{} -} - -// WithPayload adds the payload to the get jobs Id bad request response -func (o *GetJobsIDBadRequest) WithPayload(payload *model.ErrorResponse) *GetJobsIDBadRequest { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs Id bad request response -func (o *GetJobsIDBadRequest) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsIDBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(400) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// GetJobsIDNotFoundCode is the HTTP code returned for type GetJobsIDNotFound -const GetJobsIDNotFoundCode int = 404 - -/* -GetJobsIDNotFound Not Found - -swagger:response getJobsIdNotFound -*/ -type GetJobsIDNotFound struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewGetJobsIDNotFound creates GetJobsIDNotFound with default headers values -func NewGetJobsIDNotFound() *GetJobsIDNotFound { - - return &GetJobsIDNotFound{} -} - -// WithPayload adds the payload to the get jobs Id not found response -func (o *GetJobsIDNotFound) WithPayload(payload *model.ErrorResponse) *GetJobsIDNotFound { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs Id not found response -func (o *GetJobsIDNotFound) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsIDNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(404) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -GetJobsIDDefault Other error with any status code and response body format. - -swagger:response getJobsIdDefault -*/ -type GetJobsIDDefault struct { - _statusCode int -} - -// NewGetJobsIDDefault creates GetJobsIDDefault with default headers values -func NewGetJobsIDDefault(code int) *GetJobsIDDefault { - if code <= 0 { - code = 500 - } - - return &GetJobsIDDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the get jobs ID default response -func (o *GetJobsIDDefault) WithStatusCode(code int) *GetJobsIDDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the get jobs ID default response -func (o *GetJobsIDDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *GetJobsIDDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/northbound/restapi/operations/northbound/get_jobs_id_status.go b/generated/northbound/restapi/operations/northbound/get_jobs_id_status.go deleted file mode 100644 index 2ab98889..00000000 --- a/generated/northbound/restapi/operations/northbound/get_jobs_id_status.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// GetJobsIDStatusHandlerFunc turns a function with the right signature into a get jobs ID status handler -type GetJobsIDStatusHandlerFunc func(GetJobsIDStatusParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn GetJobsIDStatusHandlerFunc) Handle(params GetJobsIDStatusParams) middleware.Responder { - return fn(params) -} - -// GetJobsIDStatusHandler interface for that can handle valid get jobs ID status params -type GetJobsIDStatusHandler interface { - Handle(GetJobsIDStatusParams) middleware.Responder -} - -// NewGetJobsIDStatus creates a new http.Handler for the get jobs ID status operation -func NewGetJobsIDStatus(ctx *middleware.Context, handler GetJobsIDStatusHandler) *GetJobsIDStatus { - return &GetJobsIDStatus{Context: ctx, Handler: handler} -} - -/* - GetJobsIDStatus swagger:route GET /jobs/{id}/status northbound getJobsIdStatus - -# Get job status - -Retrieve the job status -*/ -type GetJobsIDStatus struct { - Context *middleware.Context - Handler GetJobsIDStatusHandler -} - -func (o *GetJobsIDStatus) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewGetJobsIDStatusParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/northbound/restapi/operations/northbound/get_jobs_id_status_parameters.go b/generated/northbound/restapi/operations/northbound/get_jobs_id_status_parameters.go deleted file mode 100644 index eb804e27..00000000 --- a/generated/northbound/restapi/operations/northbound/get_jobs_id_status_parameters.go +++ /dev/null @@ -1,76 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" -) - -// NewGetJobsIDStatusParams creates a new GetJobsIDStatusParams object -// -// There are no default values defined in the spec. -func NewGetJobsIDStatusParams() GetJobsIDStatusParams { - - return GetJobsIDStatusParams{} -} - -// GetJobsIDStatusParams contains all the bound params for the get jobs ID status operation -// typically these are obtained from a http.Request -// -// swagger:parameters GetJobsIDStatus -type GetJobsIDStatusParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*Job ID - Required: true - In: path - */ - ID string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewGetJobsIDStatusParams() beforehand. -func (o *GetJobsIDStatusParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - rID, rhkID, _ := route.Params.GetOK("id") - if err := o.bindID(rID, rhkID, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindID binds and validates parameter ID from path. -func (o *GetJobsIDStatusParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: true - // Parameter is provided by construction from the route - o.ID = raw - - return nil -} diff --git a/generated/northbound/restapi/operations/northbound/get_jobs_id_status_responses.go b/generated/northbound/restapi/operations/northbound/get_jobs_id_status_responses.go deleted file mode 100644 index 40d83838..00000000 --- a/generated/northbound/restapi/operations/northbound/get_jobs_id_status_responses.go +++ /dev/null @@ -1,147 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// GetJobsIDStatusOKCode is the HTTP code returned for type GetJobsIDStatusOK -const GetJobsIDStatusOKCode int = 200 - -/* -GetJobsIDStatusOK Job status - -swagger:response getJobsIdStatusOK -*/ -type GetJobsIDStatusOK struct { - - /* - In: Body - */ - Payload *model.JobStatus `json:"body,omitempty"` -} - -// NewGetJobsIDStatusOK creates GetJobsIDStatusOK with default headers values -func NewGetJobsIDStatusOK() *GetJobsIDStatusOK { - - return &GetJobsIDStatusOK{} -} - -// WithPayload adds the payload to the get jobs Id status o k response -func (o *GetJobsIDStatusOK) WithPayload(payload *model.JobStatus) *GetJobsIDStatusOK { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs Id status o k response -func (o *GetJobsIDStatusOK) SetPayload(payload *model.JobStatus) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsIDStatusOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(200) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// GetJobsIDStatusNotFoundCode is the HTTP code returned for type GetJobsIDStatusNotFound -const GetJobsIDStatusNotFoundCode int = 404 - -/* -GetJobsIDStatusNotFound Not Found - -swagger:response getJobsIdStatusNotFound -*/ -type GetJobsIDStatusNotFound struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewGetJobsIDStatusNotFound creates GetJobsIDStatusNotFound with default headers values -func NewGetJobsIDStatusNotFound() *GetJobsIDStatusNotFound { - - return &GetJobsIDStatusNotFound{} -} - -// WithPayload adds the payload to the get jobs Id status not found response -func (o *GetJobsIDStatusNotFound) WithPayload(payload *model.ErrorResponse) *GetJobsIDStatusNotFound { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs Id status not found response -func (o *GetJobsIDStatusNotFound) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsIDStatusNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(404) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -GetJobsIDStatusDefault Other error with any status code and response body format. - -swagger:response getJobsIdStatusDefault -*/ -type GetJobsIDStatusDefault struct { - _statusCode int -} - -// NewGetJobsIDStatusDefault creates GetJobsIDStatusDefault with default headers values -func NewGetJobsIDStatusDefault(code int) *GetJobsIDStatusDefault { - if code <= 0 { - code = 500 - } - - return &GetJobsIDStatusDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the get jobs ID status default response -func (o *GetJobsIDStatusDefault) WithStatusCode(code int) *GetJobsIDStatusDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the get jobs ID status default response -func (o *GetJobsIDStatusDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *GetJobsIDStatusDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/northbound/restapi/operations/northbound/get_jobs_id_status_urlbuilder.go b/generated/northbound/restapi/operations/northbound/get_jobs_id_status_urlbuilder.go deleted file mode 100644 index 7480b95b..00000000 --- a/generated/northbound/restapi/operations/northbound/get_jobs_id_status_urlbuilder.go +++ /dev/null @@ -1,104 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" - "strings" -) - -// GetJobsIDStatusURL generates an URL for the get jobs ID status operation -type GetJobsIDStatusURL struct { - ID string - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetJobsIDStatusURL) WithBasePath(bp string) *GetJobsIDStatusURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetJobsIDStatusURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *GetJobsIDStatusURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/jobs/{id}/status" - - id := o.ID - if id != "" { - _path = strings.Replace(_path, "{id}", id, -1) - } else { - return nil, errors.New("id is required on GetJobsIDStatusURL") - } - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *GetJobsIDStatusURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *GetJobsIDStatusURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *GetJobsIDStatusURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on GetJobsIDStatusURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on GetJobsIDStatusURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *GetJobsIDStatusURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/northbound/restapi/operations/northbound/get_jobs_id_tags.go b/generated/northbound/restapi/operations/northbound/get_jobs_id_tags.go deleted file mode 100644 index 997b8d5d..00000000 --- a/generated/northbound/restapi/operations/northbound/get_jobs_id_tags.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// GetJobsIDTagsHandlerFunc turns a function with the right signature into a get jobs ID tags handler -type GetJobsIDTagsHandlerFunc func(GetJobsIDTagsParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn GetJobsIDTagsHandlerFunc) Handle(params GetJobsIDTagsParams) middleware.Responder { - return fn(params) -} - -// GetJobsIDTagsHandler interface for that can handle valid get jobs ID tags params -type GetJobsIDTagsHandler interface { - Handle(GetJobsIDTagsParams) middleware.Responder -} - -// NewGetJobsIDTags creates a new http.Handler for the get jobs ID tags operation -func NewGetJobsIDTags(ctx *middleware.Context, handler GetJobsIDTagsHandler) *GetJobsIDTags { - return &GetJobsIDTags{Context: ctx, Handler: handler} -} - -/* - GetJobsIDTags swagger:route GET /jobs/{id}/tags northbound getJobsIdTags - -# Get tags - -Get the tags of a job -*/ -type GetJobsIDTags struct { - Context *middleware.Context - Handler GetJobsIDTagsHandler -} - -func (o *GetJobsIDTags) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewGetJobsIDTagsParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/northbound/restapi/operations/northbound/get_jobs_id_tags_parameters.go b/generated/northbound/restapi/operations/northbound/get_jobs_id_tags_parameters.go deleted file mode 100644 index 8d4e57af..00000000 --- a/generated/northbound/restapi/operations/northbound/get_jobs_id_tags_parameters.go +++ /dev/null @@ -1,76 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" -) - -// NewGetJobsIDTagsParams creates a new GetJobsIDTagsParams object -// -// There are no default values defined in the spec. -func NewGetJobsIDTagsParams() GetJobsIDTagsParams { - - return GetJobsIDTagsParams{} -} - -// GetJobsIDTagsParams contains all the bound params for the get jobs ID tags operation -// typically these are obtained from a http.Request -// -// swagger:parameters GetJobsIDTags -type GetJobsIDTagsParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*Job ID - Required: true - In: path - */ - ID string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewGetJobsIDTagsParams() beforehand. -func (o *GetJobsIDTagsParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - rID, rhkID, _ := route.Params.GetOK("id") - if err := o.bindID(rID, rhkID, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindID binds and validates parameter ID from path. -func (o *GetJobsIDTagsParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: true - // Parameter is provided by construction from the route - o.ID = raw - - return nil -} diff --git a/generated/northbound/restapi/operations/northbound/get_jobs_id_tags_responses.go b/generated/northbound/restapi/operations/northbound/get_jobs_id_tags_responses.go deleted file mode 100644 index 6f10b125..00000000 --- a/generated/northbound/restapi/operations/northbound/get_jobs_id_tags_responses.go +++ /dev/null @@ -1,150 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// GetJobsIDTagsOKCode is the HTTP code returned for type GetJobsIDTagsOK -const GetJobsIDTagsOKCode int = 200 - -/* -GetJobsIDTagsOK Job tags - -swagger:response getJobsIdTagsOK -*/ -type GetJobsIDTagsOK struct { - - /* - In: Body - */ - Payload []string `json:"body,omitempty"` -} - -// NewGetJobsIDTagsOK creates GetJobsIDTagsOK with default headers values -func NewGetJobsIDTagsOK() *GetJobsIDTagsOK { - - return &GetJobsIDTagsOK{} -} - -// WithPayload adds the payload to the get jobs Id tags o k response -func (o *GetJobsIDTagsOK) WithPayload(payload []string) *GetJobsIDTagsOK { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs Id tags o k response -func (o *GetJobsIDTagsOK) SetPayload(payload []string) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsIDTagsOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(200) - payload := o.Payload - if payload == nil { - // return empty array - payload = make([]string, 0, 50) - } - - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } -} - -// GetJobsIDTagsNotFoundCode is the HTTP code returned for type GetJobsIDTagsNotFound -const GetJobsIDTagsNotFoundCode int = 404 - -/* -GetJobsIDTagsNotFound Not Found - -swagger:response getJobsIdTagsNotFound -*/ -type GetJobsIDTagsNotFound struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewGetJobsIDTagsNotFound creates GetJobsIDTagsNotFound with default headers values -func NewGetJobsIDTagsNotFound() *GetJobsIDTagsNotFound { - - return &GetJobsIDTagsNotFound{} -} - -// WithPayload adds the payload to the get jobs Id tags not found response -func (o *GetJobsIDTagsNotFound) WithPayload(payload *model.ErrorResponse) *GetJobsIDTagsNotFound { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs Id tags not found response -func (o *GetJobsIDTagsNotFound) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsIDTagsNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(404) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -GetJobsIDTagsDefault Other error with any status code and response body format. - -swagger:response getJobsIdTagsDefault -*/ -type GetJobsIDTagsDefault struct { - _statusCode int -} - -// NewGetJobsIDTagsDefault creates GetJobsIDTagsDefault with default headers values -func NewGetJobsIDTagsDefault(code int) *GetJobsIDTagsDefault { - if code <= 0 { - code = 500 - } - - return &GetJobsIDTagsDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the get jobs ID tags default response -func (o *GetJobsIDTagsDefault) WithStatusCode(code int) *GetJobsIDTagsDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the get jobs ID tags default response -func (o *GetJobsIDTagsDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *GetJobsIDTagsDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/northbound/restapi/operations/northbound/get_jobs_id_tags_urlbuilder.go b/generated/northbound/restapi/operations/northbound/get_jobs_id_tags_urlbuilder.go deleted file mode 100644 index 95c5440c..00000000 --- a/generated/northbound/restapi/operations/northbound/get_jobs_id_tags_urlbuilder.go +++ /dev/null @@ -1,104 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" - "strings" -) - -// GetJobsIDTagsURL generates an URL for the get jobs ID tags operation -type GetJobsIDTagsURL struct { - ID string - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetJobsIDTagsURL) WithBasePath(bp string) *GetJobsIDTagsURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetJobsIDTagsURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *GetJobsIDTagsURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/jobs/{id}/tags" - - id := o.ID - if id != "" { - _path = strings.Replace(_path, "{id}", id, -1) - } else { - return nil, errors.New("id is required on GetJobsIDTagsURL") - } - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *GetJobsIDTagsURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *GetJobsIDTagsURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *GetJobsIDTagsURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on GetJobsIDTagsURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on GetJobsIDTagsURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *GetJobsIDTagsURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/northbound/restapi/operations/northbound/get_jobs_id_urlbuilder.go b/generated/northbound/restapi/operations/northbound/get_jobs_id_urlbuilder.go deleted file mode 100644 index 6c7c0525..00000000 --- a/generated/northbound/restapi/operations/northbound/get_jobs_id_urlbuilder.go +++ /dev/null @@ -1,120 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" - "strings" - - "github.com/go-openapi/swag" -) - -// GetJobsIDURL generates an URL for the get jobs ID operation -type GetJobsIDURL struct { - ID string - - History *bool - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetJobsIDURL) WithBasePath(bp string) *GetJobsIDURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetJobsIDURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *GetJobsIDURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/jobs/{id}" - - id := o.ID - if id != "" { - _path = strings.Replace(_path, "{id}", id, -1) - } else { - return nil, errors.New("id is required on GetJobsIDURL") - } - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - qs := make(url.Values) - - var historyQ string - if o.History != nil { - historyQ = swag.FormatBool(*o.History) - } - if historyQ != "" { - qs.Set("history", historyQ) - } - - _result.RawQuery = qs.Encode() - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *GetJobsIDURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *GetJobsIDURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *GetJobsIDURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on GetJobsIDURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on GetJobsIDURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *GetJobsIDURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/northbound/restapi/operations/northbound/get_jobs_parameters.go b/generated/northbound/restapi/operations/northbound/get_jobs_parameters.go deleted file mode 100644 index 374d9633..00000000 --- a/generated/northbound/restapi/operations/northbound/get_jobs_parameters.go +++ /dev/null @@ -1,334 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewGetJobsParams creates a new GetJobsParams object -// with the default values initialized. -func NewGetJobsParams() GetJobsParams { - - var ( - // initialize parameters with default values - - limitDefault = int32(10) - offsetDefault = int64(0) - sortDefault = string("asc") - ) - - return GetJobsParams{ - Limit: &limitDefault, - - Offset: &offsetDefault, - - Sort: &sortDefault, - } -} - -// GetJobsParams contains all the bound params for the get jobs operation -// typically these are obtained from a http.Request -// -// swagger:parameters GetJobs -type GetJobsParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*Filter jobs belonging to a specific client with clientId - In: query - */ - ClientID *string - /*Filter jobs based on the group they are in - In: query - */ - Group []string - /*the maximum number of items to return - In: query - Default: 10 - */ - Limit *int32 - /*the number of items to skip before starting to return results - In: query - Default: 0 - */ - Offset *int64 - /*the order of returned elements - In: query - Default: "asc" - */ - Sort *string - /*Filter jobs based on the current state value - In: query - */ - State *string - /*Filter jobs by tags - In: query - */ - Tag []string - /*Filter jobs matching by workflow - In: query - */ - Workflow *string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewGetJobsParams() beforehand. -func (o *GetJobsParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - qs := runtime.Values(r.URL.Query()) - - qClientID, qhkClientID, _ := qs.GetOK("clientId") - if err := o.bindClientID(qClientID, qhkClientID, route.Formats); err != nil { - res = append(res, err) - } - - qGroup, qhkGroup, _ := qs.GetOK("group") - if err := o.bindGroup(qGroup, qhkGroup, route.Formats); err != nil { - res = append(res, err) - } - - qLimit, qhkLimit, _ := qs.GetOK("limit") - if err := o.bindLimit(qLimit, qhkLimit, route.Formats); err != nil { - res = append(res, err) - } - - qOffset, qhkOffset, _ := qs.GetOK("offset") - if err := o.bindOffset(qOffset, qhkOffset, route.Formats); err != nil { - res = append(res, err) - } - - qSort, qhkSort, _ := qs.GetOK("sort") - if err := o.bindSort(qSort, qhkSort, route.Formats); err != nil { - res = append(res, err) - } - - qState, qhkState, _ := qs.GetOK("state") - if err := o.bindState(qState, qhkState, route.Formats); err != nil { - res = append(res, err) - } - - qTag, qhkTag, _ := qs.GetOK("tag") - if err := o.bindTag(qTag, qhkTag, route.Formats); err != nil { - res = append(res, err) - } - - qWorkflow, qhkWorkflow, _ := qs.GetOK("workflow") - if err := o.bindWorkflow(qWorkflow, qhkWorkflow, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindClientID binds and validates parameter ClientID from query. -func (o *GetJobsParams) bindClientID(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - return nil - } - o.ClientID = &raw - - return nil -} - -// bindGroup binds and validates array parameter Group from query. -// -// Arrays are parsed according to CollectionFormat: "" (defaults to "csv" when empty). -func (o *GetJobsParams) bindGroup(rawData []string, hasKey bool, formats strfmt.Registry) error { - var qvGroup string - if len(rawData) > 0 { - qvGroup = rawData[len(rawData)-1] - } - - // CollectionFormat: - groupIC := swag.SplitByFormat(qvGroup, "") - if len(groupIC) == 0 { - return nil - } - - var groupIR []string - for _, groupIV := range groupIC { - groupI := groupIV - - groupIR = append(groupIR, groupI) - } - - o.Group = groupIR - - return nil -} - -// bindLimit binds and validates parameter Limit from query. -func (o *GetJobsParams) bindLimit(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - // Default values have been previously initialized by NewGetJobsParams() - return nil - } - - value, err := swag.ConvertInt32(raw) - if err != nil { - return errors.InvalidType("limit", "query", "int32", raw) - } - o.Limit = &value - - return nil -} - -// bindOffset binds and validates parameter Offset from query. -func (o *GetJobsParams) bindOffset(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - // Default values have been previously initialized by NewGetJobsParams() - return nil - } - - value, err := swag.ConvertInt64(raw) - if err != nil { - return errors.InvalidType("offset", "query", "int64", raw) - } - o.Offset = &value - - return nil -} - -// bindSort binds and validates parameter Sort from query. -func (o *GetJobsParams) bindSort(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - // Default values have been previously initialized by NewGetJobsParams() - return nil - } - o.Sort = &raw - - if err := o.validateSort(formats); err != nil { - return err - } - - return nil -} - -// validateSort carries on validations for parameter Sort -func (o *GetJobsParams) validateSort(formats strfmt.Registry) error { - - if err := validate.EnumCase("sort", "query", *o.Sort, []interface{}{"asc", "desc"}, true); err != nil { - return err - } - - return nil -} - -// bindState binds and validates parameter State from query. -func (o *GetJobsParams) bindState(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - return nil - } - o.State = &raw - - return nil -} - -// bindTag binds and validates array parameter Tag from query. -// -// Arrays are parsed according to CollectionFormat: "" (defaults to "csv" when empty). -func (o *GetJobsParams) bindTag(rawData []string, hasKey bool, formats strfmt.Registry) error { - var qvTag string - if len(rawData) > 0 { - qvTag = rawData[len(rawData)-1] - } - - // CollectionFormat: - tagIC := swag.SplitByFormat(qvTag, "") - if len(tagIC) == 0 { - return nil - } - - var tagIR []string - for _, tagIV := range tagIC { - tagI := tagIV - - tagIR = append(tagIR, tagI) - } - - o.Tag = tagIR - - return nil -} - -// bindWorkflow binds and validates parameter Workflow from query. -func (o *GetJobsParams) bindWorkflow(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - return nil - } - o.Workflow = &raw - - return nil -} diff --git a/generated/northbound/restapi/operations/northbound/get_jobs_responses.go b/generated/northbound/restapi/operations/northbound/get_jobs_responses.go deleted file mode 100644 index 87d4e2f9..00000000 --- a/generated/northbound/restapi/operations/northbound/get_jobs_responses.go +++ /dev/null @@ -1,147 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// GetJobsOKCode is the HTTP code returned for type GetJobsOK -const GetJobsOKCode int = 200 - -/* -GetJobsOK A paginated job list. - -swagger:response getJobsOK -*/ -type GetJobsOK struct { - - /* - In: Body - */ - Payload *model.PaginatedJobList `json:"body,omitempty"` -} - -// NewGetJobsOK creates GetJobsOK with default headers values -func NewGetJobsOK() *GetJobsOK { - - return &GetJobsOK{} -} - -// WithPayload adds the payload to the get jobs o k response -func (o *GetJobsOK) WithPayload(payload *model.PaginatedJobList) *GetJobsOK { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs o k response -func (o *GetJobsOK) SetPayload(payload *model.PaginatedJobList) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(200) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// GetJobsBadRequestCode is the HTTP code returned for type GetJobsBadRequest -const GetJobsBadRequestCode int = 400 - -/* -GetJobsBadRequest If request is invalid - -swagger:response getJobsBadRequest -*/ -type GetJobsBadRequest struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewGetJobsBadRequest creates GetJobsBadRequest with default headers values -func NewGetJobsBadRequest() *GetJobsBadRequest { - - return &GetJobsBadRequest{} -} - -// WithPayload adds the payload to the get jobs bad request response -func (o *GetJobsBadRequest) WithPayload(payload *model.ErrorResponse) *GetJobsBadRequest { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs bad request response -func (o *GetJobsBadRequest) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(400) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -GetJobsDefault Other error with any status code and response body format. - -swagger:response getJobsDefault -*/ -type GetJobsDefault struct { - _statusCode int -} - -// NewGetJobsDefault creates GetJobsDefault with default headers values -func NewGetJobsDefault(code int) *GetJobsDefault { - if code <= 0 { - code = 500 - } - - return &GetJobsDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the get jobs default response -func (o *GetJobsDefault) WithStatusCode(code int) *GetJobsDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the get jobs default response -func (o *GetJobsDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *GetJobsDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/northbound/restapi/operations/northbound/get_jobs_urlbuilder.go b/generated/northbound/restapi/operations/northbound/get_jobs_urlbuilder.go deleted file mode 100644 index b86bde80..00000000 --- a/generated/northbound/restapi/operations/northbound/get_jobs_urlbuilder.go +++ /dev/null @@ -1,191 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" - - "github.com/go-openapi/swag" -) - -// GetJobsURL generates an URL for the get jobs operation -type GetJobsURL struct { - ClientID *string - Group []string - Limit *int32 - Offset *int64 - Sort *string - State *string - Tag []string - Workflow *string - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetJobsURL) WithBasePath(bp string) *GetJobsURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetJobsURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *GetJobsURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/jobs" - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - qs := make(url.Values) - - var clientIDQ string - if o.ClientID != nil { - clientIDQ = *o.ClientID - } - if clientIDQ != "" { - qs.Set("clientId", clientIDQ) - } - - var groupIR []string - for _, groupI := range o.Group { - groupIS := groupI - if groupIS != "" { - groupIR = append(groupIR, groupIS) - } - } - - group := swag.JoinByFormat(groupIR, "") - - if len(group) > 0 { - qsv := group[0] - if qsv != "" { - qs.Set("group", qsv) - } - } - - var limitQ string - if o.Limit != nil { - limitQ = swag.FormatInt32(*o.Limit) - } - if limitQ != "" { - qs.Set("limit", limitQ) - } - - var offsetQ string - if o.Offset != nil { - offsetQ = swag.FormatInt64(*o.Offset) - } - if offsetQ != "" { - qs.Set("offset", offsetQ) - } - - var sortQ string - if o.Sort != nil { - sortQ = *o.Sort - } - if sortQ != "" { - qs.Set("sort", sortQ) - } - - var stateQ string - if o.State != nil { - stateQ = *o.State - } - if stateQ != "" { - qs.Set("state", stateQ) - } - - var tagIR []string - for _, tagI := range o.Tag { - tagIS := tagI - if tagIS != "" { - tagIR = append(tagIR, tagIS) - } - } - - tag := swag.JoinByFormat(tagIR, "") - - if len(tag) > 0 { - qsv := tag[0] - if qsv != "" { - qs.Set("tag", qsv) - } - } - - var workflowQ string - if o.Workflow != nil { - workflowQ = *o.Workflow - } - if workflowQ != "" { - qs.Set("workflow", workflowQ) - } - - _result.RawQuery = qs.Encode() - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *GetJobsURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *GetJobsURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *GetJobsURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on GetJobsURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on GetJobsURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *GetJobsURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/northbound/restapi/operations/northbound/get_workflows.go b/generated/northbound/restapi/operations/northbound/get_workflows.go deleted file mode 100644 index 1f4cac0f..00000000 --- a/generated/northbound/restapi/operations/northbound/get_workflows.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// GetWorkflowsHandlerFunc turns a function with the right signature into a get workflows handler -type GetWorkflowsHandlerFunc func(GetWorkflowsParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn GetWorkflowsHandlerFunc) Handle(params GetWorkflowsParams) middleware.Responder { - return fn(params) -} - -// GetWorkflowsHandler interface for that can handle valid get workflows params -type GetWorkflowsHandler interface { - Handle(GetWorkflowsParams) middleware.Responder -} - -// NewGetWorkflows creates a new http.Handler for the get workflows operation -func NewGetWorkflows(ctx *middleware.Context, handler GetWorkflowsHandler) *GetWorkflows { - return &GetWorkflows{Context: ctx, Handler: handler} -} - -/* - GetWorkflows swagger:route GET /workflows northbound getWorkflows - -# List of available workflows - -List of available workflows -*/ -type GetWorkflows struct { - Context *middleware.Context - Handler GetWorkflowsHandler -} - -func (o *GetWorkflows) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewGetWorkflowsParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/northbound/restapi/operations/northbound/get_workflows_name.go b/generated/northbound/restapi/operations/northbound/get_workflows_name.go deleted file mode 100644 index e1def33c..00000000 --- a/generated/northbound/restapi/operations/northbound/get_workflows_name.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// GetWorkflowsNameHandlerFunc turns a function with the right signature into a get workflows name handler -type GetWorkflowsNameHandlerFunc func(GetWorkflowsNameParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn GetWorkflowsNameHandlerFunc) Handle(params GetWorkflowsNameParams) middleware.Responder { - return fn(params) -} - -// GetWorkflowsNameHandler interface for that can handle valid get workflows name params -type GetWorkflowsNameHandler interface { - Handle(GetWorkflowsNameParams) middleware.Responder -} - -// NewGetWorkflowsName creates a new http.Handler for the get workflows name operation -func NewGetWorkflowsName(ctx *middleware.Context, handler GetWorkflowsNameHandler) *GetWorkflowsName { - return &GetWorkflowsName{Context: ctx, Handler: handler} -} - -/* - GetWorkflowsName swagger:route GET /workflows/{name} northbound getWorkflowsName - -# Workflow description for a given name - -Workflow description for a given name -*/ -type GetWorkflowsName struct { - Context *middleware.Context - Handler GetWorkflowsNameHandler -} - -func (o *GetWorkflowsName) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewGetWorkflowsNameParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/northbound/restapi/operations/northbound/get_workflows_name_parameters.go b/generated/northbound/restapi/operations/northbound/get_workflows_name_parameters.go deleted file mode 100644 index 6dd73ef2..00000000 --- a/generated/northbound/restapi/operations/northbound/get_workflows_name_parameters.go +++ /dev/null @@ -1,76 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" -) - -// NewGetWorkflowsNameParams creates a new GetWorkflowsNameParams object -// -// There are no default values defined in the spec. -func NewGetWorkflowsNameParams() GetWorkflowsNameParams { - - return GetWorkflowsNameParams{} -} - -// GetWorkflowsNameParams contains all the bound params for the get workflows name operation -// typically these are obtained from a http.Request -// -// swagger:parameters GetWorkflowsName -type GetWorkflowsNameParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*Unique name for the workflow - Required: true - In: path - */ - Name string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewGetWorkflowsNameParams() beforehand. -func (o *GetWorkflowsNameParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - rName, rhkName, _ := route.Params.GetOK("name") - if err := o.bindName(rName, rhkName, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindName binds and validates parameter Name from path. -func (o *GetWorkflowsNameParams) bindName(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: true - // Parameter is provided by construction from the route - o.Name = raw - - return nil -} diff --git a/generated/northbound/restapi/operations/northbound/get_workflows_name_responses.go b/generated/northbound/restapi/operations/northbound/get_workflows_name_responses.go deleted file mode 100644 index 5f02956d..00000000 --- a/generated/northbound/restapi/operations/northbound/get_workflows_name_responses.go +++ /dev/null @@ -1,192 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// GetWorkflowsNameOKCode is the HTTP code returned for type GetWorkflowsNameOK -const GetWorkflowsNameOKCode int = 200 - -/* -GetWorkflowsNameOK Workflow description with the provided key - -swagger:response getWorkflowsNameOK -*/ -type GetWorkflowsNameOK struct { - - /* - In: Body - */ - Payload *model.Workflow `json:"body,omitempty"` -} - -// NewGetWorkflowsNameOK creates GetWorkflowsNameOK with default headers values -func NewGetWorkflowsNameOK() *GetWorkflowsNameOK { - - return &GetWorkflowsNameOK{} -} - -// WithPayload adds the payload to the get workflows name o k response -func (o *GetWorkflowsNameOK) WithPayload(payload *model.Workflow) *GetWorkflowsNameOK { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get workflows name o k response -func (o *GetWorkflowsNameOK) SetPayload(payload *model.Workflow) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetWorkflowsNameOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(200) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// GetWorkflowsNameBadRequestCode is the HTTP code returned for type GetWorkflowsNameBadRequest -const GetWorkflowsNameBadRequestCode int = 400 - -/* -GetWorkflowsNameBadRequest If request is invalid - -swagger:response getWorkflowsNameBadRequest -*/ -type GetWorkflowsNameBadRequest struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewGetWorkflowsNameBadRequest creates GetWorkflowsNameBadRequest with default headers values -func NewGetWorkflowsNameBadRequest() *GetWorkflowsNameBadRequest { - - return &GetWorkflowsNameBadRequest{} -} - -// WithPayload adds the payload to the get workflows name bad request response -func (o *GetWorkflowsNameBadRequest) WithPayload(payload *model.ErrorResponse) *GetWorkflowsNameBadRequest { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get workflows name bad request response -func (o *GetWorkflowsNameBadRequest) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetWorkflowsNameBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(400) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// GetWorkflowsNameNotFoundCode is the HTTP code returned for type GetWorkflowsNameNotFound -const GetWorkflowsNameNotFoundCode int = 404 - -/* -GetWorkflowsNameNotFound Not Found - -swagger:response getWorkflowsNameNotFound -*/ -type GetWorkflowsNameNotFound struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewGetWorkflowsNameNotFound creates GetWorkflowsNameNotFound with default headers values -func NewGetWorkflowsNameNotFound() *GetWorkflowsNameNotFound { - - return &GetWorkflowsNameNotFound{} -} - -// WithPayload adds the payload to the get workflows name not found response -func (o *GetWorkflowsNameNotFound) WithPayload(payload *model.ErrorResponse) *GetWorkflowsNameNotFound { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get workflows name not found response -func (o *GetWorkflowsNameNotFound) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetWorkflowsNameNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(404) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -GetWorkflowsNameDefault Other error with any status code and response body format. - -swagger:response getWorkflowsNameDefault -*/ -type GetWorkflowsNameDefault struct { - _statusCode int -} - -// NewGetWorkflowsNameDefault creates GetWorkflowsNameDefault with default headers values -func NewGetWorkflowsNameDefault(code int) *GetWorkflowsNameDefault { - if code <= 0 { - code = 500 - } - - return &GetWorkflowsNameDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the get workflows name default response -func (o *GetWorkflowsNameDefault) WithStatusCode(code int) *GetWorkflowsNameDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the get workflows name default response -func (o *GetWorkflowsNameDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *GetWorkflowsNameDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/northbound/restapi/operations/northbound/get_workflows_name_urlbuilder.go b/generated/northbound/restapi/operations/northbound/get_workflows_name_urlbuilder.go deleted file mode 100644 index 1e8127f0..00000000 --- a/generated/northbound/restapi/operations/northbound/get_workflows_name_urlbuilder.go +++ /dev/null @@ -1,104 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" - "strings" -) - -// GetWorkflowsNameURL generates an URL for the get workflows name operation -type GetWorkflowsNameURL struct { - Name string - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetWorkflowsNameURL) WithBasePath(bp string) *GetWorkflowsNameURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetWorkflowsNameURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *GetWorkflowsNameURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/workflows/{name}" - - name := o.Name - if name != "" { - _path = strings.Replace(_path, "{name}", name, -1) - } else { - return nil, errors.New("name is required on GetWorkflowsNameURL") - } - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *GetWorkflowsNameURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *GetWorkflowsNameURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *GetWorkflowsNameURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on GetWorkflowsNameURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on GetWorkflowsNameURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *GetWorkflowsNameURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/northbound/restapi/operations/northbound/get_workflows_parameters.go b/generated/northbound/restapi/operations/northbound/get_workflows_parameters.go deleted file mode 100644 index c85ab1a7..00000000 --- a/generated/northbound/restapi/operations/northbound/get_workflows_parameters.go +++ /dev/null @@ -1,181 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewGetWorkflowsParams creates a new GetWorkflowsParams object -// with the default values initialized. -func NewGetWorkflowsParams() GetWorkflowsParams { - - var ( - // initialize parameters with default values - - limitDefault = int32(10) - offsetDefault = int64(0) - sortDefault = string("asc") - ) - - return GetWorkflowsParams{ - Limit: &limitDefault, - - Offset: &offsetDefault, - - Sort: &sortDefault, - } -} - -// GetWorkflowsParams contains all the bound params for the get workflows operation -// typically these are obtained from a http.Request -// -// swagger:parameters GetWorkflows -type GetWorkflowsParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*the maximum number of items to return - In: query - Default: 10 - */ - Limit *int32 - /*the number of items to skip before starting to return results - In: query - Default: 0 - */ - Offset *int64 - /*the order of returned elements - In: query - Default: "asc" - */ - Sort *string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewGetWorkflowsParams() beforehand. -func (o *GetWorkflowsParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - qs := runtime.Values(r.URL.Query()) - - qLimit, qhkLimit, _ := qs.GetOK("limit") - if err := o.bindLimit(qLimit, qhkLimit, route.Formats); err != nil { - res = append(res, err) - } - - qOffset, qhkOffset, _ := qs.GetOK("offset") - if err := o.bindOffset(qOffset, qhkOffset, route.Formats); err != nil { - res = append(res, err) - } - - qSort, qhkSort, _ := qs.GetOK("sort") - if err := o.bindSort(qSort, qhkSort, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindLimit binds and validates parameter Limit from query. -func (o *GetWorkflowsParams) bindLimit(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - // Default values have been previously initialized by NewGetWorkflowsParams() - return nil - } - - value, err := swag.ConvertInt32(raw) - if err != nil { - return errors.InvalidType("limit", "query", "int32", raw) - } - o.Limit = &value - - return nil -} - -// bindOffset binds and validates parameter Offset from query. -func (o *GetWorkflowsParams) bindOffset(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - // Default values have been previously initialized by NewGetWorkflowsParams() - return nil - } - - value, err := swag.ConvertInt64(raw) - if err != nil { - return errors.InvalidType("offset", "query", "int64", raw) - } - o.Offset = &value - - return nil -} - -// bindSort binds and validates parameter Sort from query. -func (o *GetWorkflowsParams) bindSort(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - // Default values have been previously initialized by NewGetWorkflowsParams() - return nil - } - o.Sort = &raw - - if err := o.validateSort(formats); err != nil { - return err - } - - return nil -} - -// validateSort carries on validations for parameter Sort -func (o *GetWorkflowsParams) validateSort(formats strfmt.Registry) error { - - if err := validate.EnumCase("sort", "query", *o.Sort, []interface{}{"asc", "desc"}, true); err != nil { - return err - } - - return nil -} diff --git a/generated/northbound/restapi/operations/northbound/get_workflows_responses.go b/generated/northbound/restapi/operations/northbound/get_workflows_responses.go deleted file mode 100644 index 4fb03d80..00000000 --- a/generated/northbound/restapi/operations/northbound/get_workflows_responses.go +++ /dev/null @@ -1,102 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// GetWorkflowsOKCode is the HTTP code returned for type GetWorkflowsOK -const GetWorkflowsOKCode int = 200 - -/* -GetWorkflowsOK A list of workflows - -swagger:response getWorkflowsOK -*/ -type GetWorkflowsOK struct { - - /* - In: Body - */ - Payload *model.PaginatedWorkflowList `json:"body,omitempty"` -} - -// NewGetWorkflowsOK creates GetWorkflowsOK with default headers values -func NewGetWorkflowsOK() *GetWorkflowsOK { - - return &GetWorkflowsOK{} -} - -// WithPayload adds the payload to the get workflows o k response -func (o *GetWorkflowsOK) WithPayload(payload *model.PaginatedWorkflowList) *GetWorkflowsOK { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get workflows o k response -func (o *GetWorkflowsOK) SetPayload(payload *model.PaginatedWorkflowList) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetWorkflowsOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(200) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -GetWorkflowsDefault Other error with any status code and response body format. - -swagger:response getWorkflowsDefault -*/ -type GetWorkflowsDefault struct { - _statusCode int -} - -// NewGetWorkflowsDefault creates GetWorkflowsDefault with default headers values -func NewGetWorkflowsDefault(code int) *GetWorkflowsDefault { - if code <= 0 { - code = 500 - } - - return &GetWorkflowsDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the get workflows default response -func (o *GetWorkflowsDefault) WithStatusCode(code int) *GetWorkflowsDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the get workflows default response -func (o *GetWorkflowsDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *GetWorkflowsDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/northbound/restapi/operations/northbound/get_workflows_urlbuilder.go b/generated/northbound/restapi/operations/northbound/get_workflows_urlbuilder.go deleted file mode 100644 index 3184eb61..00000000 --- a/generated/northbound/restapi/operations/northbound/get_workflows_urlbuilder.go +++ /dev/null @@ -1,128 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" - - "github.com/go-openapi/swag" -) - -// GetWorkflowsURL generates an URL for the get workflows operation -type GetWorkflowsURL struct { - Limit *int32 - Offset *int64 - Sort *string - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetWorkflowsURL) WithBasePath(bp string) *GetWorkflowsURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetWorkflowsURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *GetWorkflowsURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/workflows" - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - qs := make(url.Values) - - var limitQ string - if o.Limit != nil { - limitQ = swag.FormatInt32(*o.Limit) - } - if limitQ != "" { - qs.Set("limit", limitQ) - } - - var offsetQ string - if o.Offset != nil { - offsetQ = swag.FormatInt64(*o.Offset) - } - if offsetQ != "" { - qs.Set("offset", offsetQ) - } - - var sortQ string - if o.Sort != nil { - sortQ = *o.Sort - } - if sortQ != "" { - qs.Set("sort", sortQ) - } - - _result.RawQuery = qs.Encode() - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *GetWorkflowsURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *GetWorkflowsURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *GetWorkflowsURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on GetWorkflowsURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on GetWorkflowsURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *GetWorkflowsURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/northbound/restapi/operations/northbound/post_jobs.go b/generated/northbound/restapi/operations/northbound/post_jobs.go deleted file mode 100644 index a7263c22..00000000 --- a/generated/northbound/restapi/operations/northbound/post_jobs.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// PostJobsHandlerFunc turns a function with the right signature into a post jobs handler -type PostJobsHandlerFunc func(PostJobsParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn PostJobsHandlerFunc) Handle(params PostJobsParams) middleware.Responder { - return fn(params) -} - -// PostJobsHandler interface for that can handle valid post jobs params -type PostJobsHandler interface { - Handle(PostJobsParams) middleware.Responder -} - -// NewPostJobs creates a new http.Handler for the post jobs operation -func NewPostJobs(ctx *middleware.Context, handler PostJobsHandler) *PostJobs { - return &PostJobs{Context: ctx, Handler: handler} -} - -/* - PostJobs swagger:route POST /jobs northbound postJobs - -# Add a new job - -Add a new job -*/ -type PostJobs struct { - Context *middleware.Context - Handler PostJobsHandler -} - -func (o *PostJobs) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewPostJobsParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/northbound/restapi/operations/northbound/post_jobs_id_tags.go b/generated/northbound/restapi/operations/northbound/post_jobs_id_tags.go deleted file mode 100644 index b8824f00..00000000 --- a/generated/northbound/restapi/operations/northbound/post_jobs_id_tags.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// PostJobsIDTagsHandlerFunc turns a function with the right signature into a post jobs ID tags handler -type PostJobsIDTagsHandlerFunc func(PostJobsIDTagsParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn PostJobsIDTagsHandlerFunc) Handle(params PostJobsIDTagsParams) middleware.Responder { - return fn(params) -} - -// PostJobsIDTagsHandler interface for that can handle valid post jobs ID tags params -type PostJobsIDTagsHandler interface { - Handle(PostJobsIDTagsParams) middleware.Responder -} - -// NewPostJobsIDTags creates a new http.Handler for the post jobs ID tags operation -func NewPostJobsIDTags(ctx *middleware.Context, handler PostJobsIDTagsHandler) *PostJobsIDTags { - return &PostJobsIDTags{Context: ctx, Handler: handler} -} - -/* - PostJobsIDTags swagger:route POST /jobs/{id}/tags northbound postJobsIdTags - -# Add a tag - -Add a tag to an existing job -*/ -type PostJobsIDTags struct { - Context *middleware.Context - Handler PostJobsIDTagsHandler -} - -func (o *PostJobsIDTags) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewPostJobsIDTagsParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/northbound/restapi/operations/northbound/post_jobs_id_tags_parameters.go b/generated/northbound/restapi/operations/northbound/post_jobs_id_tags_parameters.go deleted file mode 100644 index f2de3af5..00000000 --- a/generated/northbound/restapi/operations/northbound/post_jobs_id_tags_parameters.go +++ /dev/null @@ -1,123 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "io" - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/validate" -) - -// NewPostJobsIDTagsParams creates a new PostJobsIDTagsParams object -// -// There are no default values defined in the spec. -func NewPostJobsIDTagsParams() PostJobsIDTagsParams { - - return PostJobsIDTagsParams{} -} - -// PostJobsIDTagsParams contains all the bound params for the post jobs ID tags operation -// typically these are obtained from a http.Request -// -// swagger:parameters PostJobsIDTags -type PostJobsIDTagsParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*Tags to add - Required: true - Max Items: 16 - Min Items: 1 - In: body - */ - Tags []string - /*Job ID - Required: true - In: path - */ - ID string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewPostJobsIDTagsParams() beforehand. -func (o *PostJobsIDTagsParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - if runtime.HasBody(r) { - defer r.Body.Close() - var body []string - if err := route.Consumer.Consume(r.Body, &body); err != nil { - if err == io.EOF { - res = append(res, errors.Required("tags", "body", "")) - } else { - res = append(res, errors.NewParseError("tags", "body", "", err)) - } - } else { - // validate inline body array - o.Tags = body - if err := o.validateTagsBody(route.Formats); err != nil { - res = append(res, err) - } - } - } else { - res = append(res, errors.Required("tags", "body", "")) - } - - rID, rhkID, _ := route.Params.GetOK("id") - if err := o.bindID(rID, rhkID, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// validateTagsBody validates an inline body parameter -func (o *PostJobsIDTagsParams) validateTagsBody(formats strfmt.Registry) error { - - tagsSize := int64(len(o.Tags)) - - // minItems: 1 - if err := validate.MinItems("Tags", "body", tagsSize, 1); err != nil { - return err - } - - // maxItems: 16 - if err := validate.MaxItems("Tags", "body", tagsSize, 16); err != nil { - return err - } - return nil -} - -// bindID binds and validates parameter ID from path. -func (o *PostJobsIDTagsParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: true - // Parameter is provided by construction from the route - o.ID = raw - - return nil -} diff --git a/generated/northbound/restapi/operations/northbound/post_jobs_id_tags_responses.go b/generated/northbound/restapi/operations/northbound/post_jobs_id_tags_responses.go deleted file mode 100644 index 5e66dd3d..00000000 --- a/generated/northbound/restapi/operations/northbound/post_jobs_id_tags_responses.go +++ /dev/null @@ -1,195 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// PostJobsIDTagsOKCode is the HTTP code returned for type PostJobsIDTagsOK -const PostJobsIDTagsOKCode int = 200 - -/* -PostJobsIDTagsOK Successfully added tag to job - -swagger:response postJobsIdTagsOK -*/ -type PostJobsIDTagsOK struct { - - /* - In: Body - */ - Payload []string `json:"body,omitempty"` -} - -// NewPostJobsIDTagsOK creates PostJobsIDTagsOK with default headers values -func NewPostJobsIDTagsOK() *PostJobsIDTagsOK { - - return &PostJobsIDTagsOK{} -} - -// WithPayload adds the payload to the post jobs Id tags o k response -func (o *PostJobsIDTagsOK) WithPayload(payload []string) *PostJobsIDTagsOK { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the post jobs Id tags o k response -func (o *PostJobsIDTagsOK) SetPayload(payload []string) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *PostJobsIDTagsOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(200) - payload := o.Payload - if payload == nil { - // return empty array - payload = make([]string, 0, 50) - } - - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } -} - -// PostJobsIDTagsBadRequestCode is the HTTP code returned for type PostJobsIDTagsBadRequest -const PostJobsIDTagsBadRequestCode int = 400 - -/* -PostJobsIDTagsBadRequest Bad Request - -swagger:response postJobsIdTagsBadRequest -*/ -type PostJobsIDTagsBadRequest struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewPostJobsIDTagsBadRequest creates PostJobsIDTagsBadRequest with default headers values -func NewPostJobsIDTagsBadRequest() *PostJobsIDTagsBadRequest { - - return &PostJobsIDTagsBadRequest{} -} - -// WithPayload adds the payload to the post jobs Id tags bad request response -func (o *PostJobsIDTagsBadRequest) WithPayload(payload *model.ErrorResponse) *PostJobsIDTagsBadRequest { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the post jobs Id tags bad request response -func (o *PostJobsIDTagsBadRequest) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *PostJobsIDTagsBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(400) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// PostJobsIDTagsNotFoundCode is the HTTP code returned for type PostJobsIDTagsNotFound -const PostJobsIDTagsNotFoundCode int = 404 - -/* -PostJobsIDTagsNotFound Not Found - -swagger:response postJobsIdTagsNotFound -*/ -type PostJobsIDTagsNotFound struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewPostJobsIDTagsNotFound creates PostJobsIDTagsNotFound with default headers values -func NewPostJobsIDTagsNotFound() *PostJobsIDTagsNotFound { - - return &PostJobsIDTagsNotFound{} -} - -// WithPayload adds the payload to the post jobs Id tags not found response -func (o *PostJobsIDTagsNotFound) WithPayload(payload *model.ErrorResponse) *PostJobsIDTagsNotFound { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the post jobs Id tags not found response -func (o *PostJobsIDTagsNotFound) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *PostJobsIDTagsNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(404) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -PostJobsIDTagsDefault Other error with any status code and response body format. - -swagger:response postJobsIdTagsDefault -*/ -type PostJobsIDTagsDefault struct { - _statusCode int -} - -// NewPostJobsIDTagsDefault creates PostJobsIDTagsDefault with default headers values -func NewPostJobsIDTagsDefault(code int) *PostJobsIDTagsDefault { - if code <= 0 { - code = 500 - } - - return &PostJobsIDTagsDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the post jobs ID tags default response -func (o *PostJobsIDTagsDefault) WithStatusCode(code int) *PostJobsIDTagsDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the post jobs ID tags default response -func (o *PostJobsIDTagsDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *PostJobsIDTagsDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/northbound/restapi/operations/northbound/post_jobs_id_tags_urlbuilder.go b/generated/northbound/restapi/operations/northbound/post_jobs_id_tags_urlbuilder.go deleted file mode 100644 index 1a7c6d88..00000000 --- a/generated/northbound/restapi/operations/northbound/post_jobs_id_tags_urlbuilder.go +++ /dev/null @@ -1,104 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" - "strings" -) - -// PostJobsIDTagsURL generates an URL for the post jobs ID tags operation -type PostJobsIDTagsURL struct { - ID string - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *PostJobsIDTagsURL) WithBasePath(bp string) *PostJobsIDTagsURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *PostJobsIDTagsURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *PostJobsIDTagsURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/jobs/{id}/tags" - - id := o.ID - if id != "" { - _path = strings.Replace(_path, "{id}", id, -1) - } else { - return nil, errors.New("id is required on PostJobsIDTagsURL") - } - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *PostJobsIDTagsURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *PostJobsIDTagsURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *PostJobsIDTagsURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on PostJobsIDTagsURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on PostJobsIDTagsURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *PostJobsIDTagsURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/northbound/restapi/operations/northbound/post_jobs_parameters.go b/generated/northbound/restapi/operations/northbound/post_jobs_parameters.go deleted file mode 100644 index 92153a49..00000000 --- a/generated/northbound/restapi/operations/northbound/post_jobs_parameters.go +++ /dev/null @@ -1,88 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "io" - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/validate" - "github.com/siemens/wfx/generated/model" -) - -// NewPostJobsParams creates a new PostJobsParams object -// -// There are no default values defined in the spec. -func NewPostJobsParams() PostJobsParams { - - return PostJobsParams{} -} - -// PostJobsParams contains all the bound params for the post jobs operation -// typically these are obtained from a http.Request -// -// swagger:parameters PostJobs -type PostJobsParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*Job which shall be created - Required: true - In: body - */ - Job *model.JobRequest -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewPostJobsParams() beforehand. -func (o *PostJobsParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - if runtime.HasBody(r) { - defer r.Body.Close() - var body model.JobRequest - if err := route.Consumer.Consume(r.Body, &body); err != nil { - if err == io.EOF { - res = append(res, errors.Required("job", "body", "")) - } else { - res = append(res, errors.NewParseError("job", "body", "", err)) - } - } else { - // validate body object - if err := body.Validate(route.Formats); err != nil { - res = append(res, err) - } - - ctx := validate.WithOperationRequest(r.Context()) - if err := body.ContextValidate(ctx, route.Formats); err != nil { - res = append(res, err) - } - - if len(res) == 0 { - o.Job = &body - } - } - } else { - res = append(res, errors.Required("job", "body", "")) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/generated/northbound/restapi/operations/northbound/post_jobs_responses.go b/generated/northbound/restapi/operations/northbound/post_jobs_responses.go deleted file mode 100644 index 39403446..00000000 --- a/generated/northbound/restapi/operations/northbound/post_jobs_responses.go +++ /dev/null @@ -1,147 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// PostJobsCreatedCode is the HTTP code returned for type PostJobsCreated -const PostJobsCreatedCode int = 201 - -/* -PostJobsCreated Job was created - -swagger:response postJobsCreated -*/ -type PostJobsCreated struct { - - /* - In: Body - */ - Payload *model.Job `json:"body,omitempty"` -} - -// NewPostJobsCreated creates PostJobsCreated with default headers values -func NewPostJobsCreated() *PostJobsCreated { - - return &PostJobsCreated{} -} - -// WithPayload adds the payload to the post jobs created response -func (o *PostJobsCreated) WithPayload(payload *model.Job) *PostJobsCreated { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the post jobs created response -func (o *PostJobsCreated) SetPayload(payload *model.Job) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *PostJobsCreated) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(201) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// PostJobsBadRequestCode is the HTTP code returned for type PostJobsBadRequest -const PostJobsBadRequestCode int = 400 - -/* -PostJobsBadRequest Bad Request - -swagger:response postJobsBadRequest -*/ -type PostJobsBadRequest struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewPostJobsBadRequest creates PostJobsBadRequest with default headers values -func NewPostJobsBadRequest() *PostJobsBadRequest { - - return &PostJobsBadRequest{} -} - -// WithPayload adds the payload to the post jobs bad request response -func (o *PostJobsBadRequest) WithPayload(payload *model.ErrorResponse) *PostJobsBadRequest { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the post jobs bad request response -func (o *PostJobsBadRequest) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *PostJobsBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(400) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -PostJobsDefault Other error with any status code and response body format. - -swagger:response postJobsDefault -*/ -type PostJobsDefault struct { - _statusCode int -} - -// NewPostJobsDefault creates PostJobsDefault with default headers values -func NewPostJobsDefault(code int) *PostJobsDefault { - if code <= 0 { - code = 500 - } - - return &PostJobsDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the post jobs default response -func (o *PostJobsDefault) WithStatusCode(code int) *PostJobsDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the post jobs default response -func (o *PostJobsDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *PostJobsDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/northbound/restapi/operations/northbound/post_jobs_urlbuilder.go b/generated/northbound/restapi/operations/northbound/post_jobs_urlbuilder.go deleted file mode 100644 index 16cc8905..00000000 --- a/generated/northbound/restapi/operations/northbound/post_jobs_urlbuilder.go +++ /dev/null @@ -1,92 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" -) - -// PostJobsURL generates an URL for the post jobs operation -type PostJobsURL struct { - _basePath string -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *PostJobsURL) WithBasePath(bp string) *PostJobsURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *PostJobsURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *PostJobsURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/jobs" - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *PostJobsURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *PostJobsURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *PostJobsURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on PostJobsURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on PostJobsURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *PostJobsURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/northbound/restapi/operations/northbound/post_workflows.go b/generated/northbound/restapi/operations/northbound/post_workflows.go deleted file mode 100644 index 1b0b733a..00000000 --- a/generated/northbound/restapi/operations/northbound/post_workflows.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// PostWorkflowsHandlerFunc turns a function with the right signature into a post workflows handler -type PostWorkflowsHandlerFunc func(PostWorkflowsParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn PostWorkflowsHandlerFunc) Handle(params PostWorkflowsParams) middleware.Responder { - return fn(params) -} - -// PostWorkflowsHandler interface for that can handle valid post workflows params -type PostWorkflowsHandler interface { - Handle(PostWorkflowsParams) middleware.Responder -} - -// NewPostWorkflows creates a new http.Handler for the post workflows operation -func NewPostWorkflows(ctx *middleware.Context, handler PostWorkflowsHandler) *PostWorkflows { - return &PostWorkflows{Context: ctx, Handler: handler} -} - -/* - PostWorkflows swagger:route POST /workflows northbound postWorkflows - -# Add a new workflow - -Add a new workflow -*/ -type PostWorkflows struct { - Context *middleware.Context - Handler PostWorkflowsHandler -} - -func (o *PostWorkflows) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewPostWorkflowsParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/northbound/restapi/operations/northbound/post_workflows_parameters.go b/generated/northbound/restapi/operations/northbound/post_workflows_parameters.go deleted file mode 100644 index 4dc8706b..00000000 --- a/generated/northbound/restapi/operations/northbound/post_workflows_parameters.go +++ /dev/null @@ -1,88 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "io" - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/validate" - "github.com/siemens/wfx/generated/model" -) - -// NewPostWorkflowsParams creates a new PostWorkflowsParams object -// -// There are no default values defined in the spec. -func NewPostWorkflowsParams() PostWorkflowsParams { - - return PostWorkflowsParams{} -} - -// PostWorkflowsParams contains all the bound params for the post workflows operation -// typically these are obtained from a http.Request -// -// swagger:parameters PostWorkflows -type PostWorkflowsParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*Workflow object to be added - Required: true - In: body - */ - Workflow *model.Workflow -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewPostWorkflowsParams() beforehand. -func (o *PostWorkflowsParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - if runtime.HasBody(r) { - defer r.Body.Close() - var body model.Workflow - if err := route.Consumer.Consume(r.Body, &body); err != nil { - if err == io.EOF { - res = append(res, errors.Required("workflow", "body", "")) - } else { - res = append(res, errors.NewParseError("workflow", "body", "", err)) - } - } else { - // validate body object - if err := body.Validate(route.Formats); err != nil { - res = append(res, err) - } - - ctx := validate.WithOperationRequest(r.Context()) - if err := body.ContextValidate(ctx, route.Formats); err != nil { - res = append(res, err) - } - - if len(res) == 0 { - o.Workflow = &body - } - } - } else { - res = append(res, errors.Required("workflow", "body", "")) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/generated/northbound/restapi/operations/northbound/post_workflows_responses.go b/generated/northbound/restapi/operations/northbound/post_workflows_responses.go deleted file mode 100644 index 0d6f8446..00000000 --- a/generated/northbound/restapi/operations/northbound/post_workflows_responses.go +++ /dev/null @@ -1,147 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// PostWorkflowsCreatedCode is the HTTP code returned for type PostWorkflowsCreated -const PostWorkflowsCreatedCode int = 201 - -/* -PostWorkflowsCreated Workflow was created - -swagger:response postWorkflowsCreated -*/ -type PostWorkflowsCreated struct { - - /* - In: Body - */ - Payload *model.Workflow `json:"body,omitempty"` -} - -// NewPostWorkflowsCreated creates PostWorkflowsCreated with default headers values -func NewPostWorkflowsCreated() *PostWorkflowsCreated { - - return &PostWorkflowsCreated{} -} - -// WithPayload adds the payload to the post workflows created response -func (o *PostWorkflowsCreated) WithPayload(payload *model.Workflow) *PostWorkflowsCreated { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the post workflows created response -func (o *PostWorkflowsCreated) SetPayload(payload *model.Workflow) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *PostWorkflowsCreated) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(201) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// PostWorkflowsBadRequestCode is the HTTP code returned for type PostWorkflowsBadRequest -const PostWorkflowsBadRequestCode int = 400 - -/* -PostWorkflowsBadRequest Bad Request - -swagger:response postWorkflowsBadRequest -*/ -type PostWorkflowsBadRequest struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewPostWorkflowsBadRequest creates PostWorkflowsBadRequest with default headers values -func NewPostWorkflowsBadRequest() *PostWorkflowsBadRequest { - - return &PostWorkflowsBadRequest{} -} - -// WithPayload adds the payload to the post workflows bad request response -func (o *PostWorkflowsBadRequest) WithPayload(payload *model.ErrorResponse) *PostWorkflowsBadRequest { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the post workflows bad request response -func (o *PostWorkflowsBadRequest) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *PostWorkflowsBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(400) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -PostWorkflowsDefault Other error with any status code and response body format. - -swagger:response postWorkflowsDefault -*/ -type PostWorkflowsDefault struct { - _statusCode int -} - -// NewPostWorkflowsDefault creates PostWorkflowsDefault with default headers values -func NewPostWorkflowsDefault(code int) *PostWorkflowsDefault { - if code <= 0 { - code = 500 - } - - return &PostWorkflowsDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the post workflows default response -func (o *PostWorkflowsDefault) WithStatusCode(code int) *PostWorkflowsDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the post workflows default response -func (o *PostWorkflowsDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *PostWorkflowsDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/northbound/restapi/operations/northbound/post_workflows_urlbuilder.go b/generated/northbound/restapi/operations/northbound/post_workflows_urlbuilder.go deleted file mode 100644 index a4a7b7ec..00000000 --- a/generated/northbound/restapi/operations/northbound/post_workflows_urlbuilder.go +++ /dev/null @@ -1,92 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" -) - -// PostWorkflowsURL generates an URL for the post workflows operation -type PostWorkflowsURL struct { - _basePath string -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *PostWorkflowsURL) WithBasePath(bp string) *PostWorkflowsURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *PostWorkflowsURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *PostWorkflowsURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/workflows" - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *PostWorkflowsURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *PostWorkflowsURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *PostWorkflowsURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on PostWorkflowsURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on PostWorkflowsURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *PostWorkflowsURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/northbound/restapi/operations/northbound/put_jobs_id_definition.go b/generated/northbound/restapi/operations/northbound/put_jobs_id_definition.go deleted file mode 100644 index b36c66a1..00000000 --- a/generated/northbound/restapi/operations/northbound/put_jobs_id_definition.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// PutJobsIDDefinitionHandlerFunc turns a function with the right signature into a put jobs ID definition handler -type PutJobsIDDefinitionHandlerFunc func(PutJobsIDDefinitionParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn PutJobsIDDefinitionHandlerFunc) Handle(params PutJobsIDDefinitionParams) middleware.Responder { - return fn(params) -} - -// PutJobsIDDefinitionHandler interface for that can handle valid put jobs ID definition params -type PutJobsIDDefinitionHandler interface { - Handle(PutJobsIDDefinitionParams) middleware.Responder -} - -// NewPutJobsIDDefinition creates a new http.Handler for the put jobs ID definition operation -func NewPutJobsIDDefinition(ctx *middleware.Context, handler PutJobsIDDefinitionHandler) *PutJobsIDDefinition { - return &PutJobsIDDefinition{Context: ctx, Handler: handler} -} - -/* - PutJobsIDDefinition swagger:route PUT /jobs/{id}/definition northbound putJobsIdDefinition - -# Modify job definition - -Modify the job definition of an existing job -*/ -type PutJobsIDDefinition struct { - Context *middleware.Context - Handler PutJobsIDDefinitionHandler -} - -func (o *PutJobsIDDefinition) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewPutJobsIDDefinitionParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/northbound/restapi/operations/northbound/put_jobs_id_definition_parameters.go b/generated/northbound/restapi/operations/northbound/put_jobs_id_definition_parameters.go deleted file mode 100644 index c91480d7..00000000 --- a/generated/northbound/restapi/operations/northbound/put_jobs_id_definition_parameters.go +++ /dev/null @@ -1,100 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "io" - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" -) - -// NewPutJobsIDDefinitionParams creates a new PutJobsIDDefinitionParams object -// -// There are no default values defined in the spec. -func NewPutJobsIDDefinitionParams() PutJobsIDDefinitionParams { - - return PutJobsIDDefinitionParams{} -} - -// PutJobsIDDefinitionParams contains all the bound params for the put jobs ID definition operation -// typically these are obtained from a http.Request -// -// swagger:parameters PutJobsIDDefinition -type PutJobsIDDefinitionParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*How to modify the job - Required: true - In: body - */ - JobDefinition map[string]interface{} - /*Job ID - Required: true - In: path - */ - ID string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewPutJobsIDDefinitionParams() beforehand. -func (o *PutJobsIDDefinitionParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - if runtime.HasBody(r) { - defer r.Body.Close() - var body map[string]interface{} - if err := route.Consumer.Consume(r.Body, &body); err != nil { - if err == io.EOF { - res = append(res, errors.Required("jobDefinition", "body", "")) - } else { - res = append(res, errors.NewParseError("jobDefinition", "body", "", err)) - } - } else { - // no validation for this map - o.JobDefinition = body - } - } else { - res = append(res, errors.Required("jobDefinition", "body", "")) - } - - rID, rhkID, _ := route.Params.GetOK("id") - if err := o.bindID(rID, rhkID, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindID binds and validates parameter ID from path. -func (o *PutJobsIDDefinitionParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: true - // Parameter is provided by construction from the route - o.ID = raw - - return nil -} diff --git a/generated/northbound/restapi/operations/northbound/put_jobs_id_definition_responses.go b/generated/northbound/restapi/operations/northbound/put_jobs_id_definition_responses.go deleted file mode 100644 index cf58e77c..00000000 --- a/generated/northbound/restapi/operations/northbound/put_jobs_id_definition_responses.go +++ /dev/null @@ -1,195 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// PutJobsIDDefinitionOKCode is the HTTP code returned for type PutJobsIDDefinitionOK -const PutJobsIDDefinitionOKCode int = 200 - -/* -PutJobsIDDefinitionOK Job modified successfully - -swagger:response putJobsIdDefinitionOK -*/ -type PutJobsIDDefinitionOK struct { - - /* - In: Body - */ - Payload map[string]interface{} `json:"body,omitempty"` -} - -// NewPutJobsIDDefinitionOK creates PutJobsIDDefinitionOK with default headers values -func NewPutJobsIDDefinitionOK() *PutJobsIDDefinitionOK { - - return &PutJobsIDDefinitionOK{} -} - -// WithPayload adds the payload to the put jobs Id definition o k response -func (o *PutJobsIDDefinitionOK) WithPayload(payload map[string]interface{}) *PutJobsIDDefinitionOK { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the put jobs Id definition o k response -func (o *PutJobsIDDefinitionOK) SetPayload(payload map[string]interface{}) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *PutJobsIDDefinitionOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(200) - payload := o.Payload - if payload == nil { - // return empty map - payload = make(map[string]interface{}, 50) - } - - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } -} - -// PutJobsIDDefinitionBadRequestCode is the HTTP code returned for type PutJobsIDDefinitionBadRequest -const PutJobsIDDefinitionBadRequestCode int = 400 - -/* -PutJobsIDDefinitionBadRequest Bad Request - -swagger:response putJobsIdDefinitionBadRequest -*/ -type PutJobsIDDefinitionBadRequest struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewPutJobsIDDefinitionBadRequest creates PutJobsIDDefinitionBadRequest with default headers values -func NewPutJobsIDDefinitionBadRequest() *PutJobsIDDefinitionBadRequest { - - return &PutJobsIDDefinitionBadRequest{} -} - -// WithPayload adds the payload to the put jobs Id definition bad request response -func (o *PutJobsIDDefinitionBadRequest) WithPayload(payload *model.ErrorResponse) *PutJobsIDDefinitionBadRequest { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the put jobs Id definition bad request response -func (o *PutJobsIDDefinitionBadRequest) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *PutJobsIDDefinitionBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(400) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// PutJobsIDDefinitionNotFoundCode is the HTTP code returned for type PutJobsIDDefinitionNotFound -const PutJobsIDDefinitionNotFoundCode int = 404 - -/* -PutJobsIDDefinitionNotFound Not Found - -swagger:response putJobsIdDefinitionNotFound -*/ -type PutJobsIDDefinitionNotFound struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewPutJobsIDDefinitionNotFound creates PutJobsIDDefinitionNotFound with default headers values -func NewPutJobsIDDefinitionNotFound() *PutJobsIDDefinitionNotFound { - - return &PutJobsIDDefinitionNotFound{} -} - -// WithPayload adds the payload to the put jobs Id definition not found response -func (o *PutJobsIDDefinitionNotFound) WithPayload(payload *model.ErrorResponse) *PutJobsIDDefinitionNotFound { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the put jobs Id definition not found response -func (o *PutJobsIDDefinitionNotFound) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *PutJobsIDDefinitionNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(404) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -PutJobsIDDefinitionDefault Other error with any status code and response body format. - -swagger:response putJobsIdDefinitionDefault -*/ -type PutJobsIDDefinitionDefault struct { - _statusCode int -} - -// NewPutJobsIDDefinitionDefault creates PutJobsIDDefinitionDefault with default headers values -func NewPutJobsIDDefinitionDefault(code int) *PutJobsIDDefinitionDefault { - if code <= 0 { - code = 500 - } - - return &PutJobsIDDefinitionDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the put jobs ID definition default response -func (o *PutJobsIDDefinitionDefault) WithStatusCode(code int) *PutJobsIDDefinitionDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the put jobs ID definition default response -func (o *PutJobsIDDefinitionDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *PutJobsIDDefinitionDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/northbound/restapi/operations/northbound/put_jobs_id_definition_urlbuilder.go b/generated/northbound/restapi/operations/northbound/put_jobs_id_definition_urlbuilder.go deleted file mode 100644 index 48874f78..00000000 --- a/generated/northbound/restapi/operations/northbound/put_jobs_id_definition_urlbuilder.go +++ /dev/null @@ -1,104 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" - "strings" -) - -// PutJobsIDDefinitionURL generates an URL for the put jobs ID definition operation -type PutJobsIDDefinitionURL struct { - ID string - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *PutJobsIDDefinitionURL) WithBasePath(bp string) *PutJobsIDDefinitionURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *PutJobsIDDefinitionURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *PutJobsIDDefinitionURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/jobs/{id}/definition" - - id := o.ID - if id != "" { - _path = strings.Replace(_path, "{id}", id, -1) - } else { - return nil, errors.New("id is required on PutJobsIDDefinitionURL") - } - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *PutJobsIDDefinitionURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *PutJobsIDDefinitionURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *PutJobsIDDefinitionURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on PutJobsIDDefinitionURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on PutJobsIDDefinitionURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *PutJobsIDDefinitionURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/northbound/restapi/operations/northbound/put_jobs_id_status.go b/generated/northbound/restapi/operations/northbound/put_jobs_id_status.go deleted file mode 100644 index 7383e5fe..00000000 --- a/generated/northbound/restapi/operations/northbound/put_jobs_id_status.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// PutJobsIDStatusHandlerFunc turns a function with the right signature into a put jobs ID status handler -type PutJobsIDStatusHandlerFunc func(PutJobsIDStatusParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn PutJobsIDStatusHandlerFunc) Handle(params PutJobsIDStatusParams) middleware.Responder { - return fn(params) -} - -// PutJobsIDStatusHandler interface for that can handle valid put jobs ID status params -type PutJobsIDStatusHandler interface { - Handle(PutJobsIDStatusParams) middleware.Responder -} - -// NewPutJobsIDStatus creates a new http.Handler for the put jobs ID status operation -func NewPutJobsIDStatus(ctx *middleware.Context, handler PutJobsIDStatusHandler) *PutJobsIDStatus { - return &PutJobsIDStatus{Context: ctx, Handler: handler} -} - -/* - PutJobsIDStatus swagger:route PUT /jobs/{id}/status northbound putJobsIdStatus - -# Modify status of an existing job - -Modify status of an existing job -*/ -type PutJobsIDStatus struct { - Context *middleware.Context - Handler PutJobsIDStatusHandler -} - -func (o *PutJobsIDStatus) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewPutJobsIDStatusParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/northbound/restapi/operations/northbound/put_jobs_id_status_parameters.go b/generated/northbound/restapi/operations/northbound/put_jobs_id_status_parameters.go deleted file mode 100644 index c96697fb..00000000 --- a/generated/northbound/restapi/operations/northbound/put_jobs_id_status_parameters.go +++ /dev/null @@ -1,113 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "io" - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/validate" - "github.com/siemens/wfx/generated/model" -) - -// NewPutJobsIDStatusParams creates a new PutJobsIDStatusParams object -// -// There are no default values defined in the spec. -func NewPutJobsIDStatusParams() PutJobsIDStatusParams { - - return PutJobsIDStatusParams{} -} - -// PutJobsIDStatusParams contains all the bound params for the put jobs ID status operation -// typically these are obtained from a http.Request -// -// swagger:parameters PutJobsIDStatus -type PutJobsIDStatusParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*This contains the new job status - Required: true - In: body - */ - NewJobStatus *model.JobStatus - /*Job ID - Required: true - In: path - */ - ID string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewPutJobsIDStatusParams() beforehand. -func (o *PutJobsIDStatusParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - if runtime.HasBody(r) { - defer r.Body.Close() - var body model.JobStatus - if err := route.Consumer.Consume(r.Body, &body); err != nil { - if err == io.EOF { - res = append(res, errors.Required("newJobStatus", "body", "")) - } else { - res = append(res, errors.NewParseError("newJobStatus", "body", "", err)) - } - } else { - // validate body object - if err := body.Validate(route.Formats); err != nil { - res = append(res, err) - } - - ctx := validate.WithOperationRequest(r.Context()) - if err := body.ContextValidate(ctx, route.Formats); err != nil { - res = append(res, err) - } - - if len(res) == 0 { - o.NewJobStatus = &body - } - } - } else { - res = append(res, errors.Required("newJobStatus", "body", "")) - } - - rID, rhkID, _ := route.Params.GetOK("id") - if err := o.bindID(rID, rhkID, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindID binds and validates parameter ID from path. -func (o *PutJobsIDStatusParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: true - // Parameter is provided by construction from the route - o.ID = raw - - return nil -} diff --git a/generated/northbound/restapi/operations/northbound/put_jobs_id_status_responses.go b/generated/northbound/restapi/operations/northbound/put_jobs_id_status_responses.go deleted file mode 100644 index f2911f78..00000000 --- a/generated/northbound/restapi/operations/northbound/put_jobs_id_status_responses.go +++ /dev/null @@ -1,192 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// PutJobsIDStatusOKCode is the HTTP code returned for type PutJobsIDStatusOK -const PutJobsIDStatusOKCode int = 200 - -/* -PutJobsIDStatusOK Job modified successfully - -swagger:response putJobsIdStatusOK -*/ -type PutJobsIDStatusOK struct { - - /* - In: Body - */ - Payload *model.JobStatus `json:"body,omitempty"` -} - -// NewPutJobsIDStatusOK creates PutJobsIDStatusOK with default headers values -func NewPutJobsIDStatusOK() *PutJobsIDStatusOK { - - return &PutJobsIDStatusOK{} -} - -// WithPayload adds the payload to the put jobs Id status o k response -func (o *PutJobsIDStatusOK) WithPayload(payload *model.JobStatus) *PutJobsIDStatusOK { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the put jobs Id status o k response -func (o *PutJobsIDStatusOK) SetPayload(payload *model.JobStatus) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *PutJobsIDStatusOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(200) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// PutJobsIDStatusBadRequestCode is the HTTP code returned for type PutJobsIDStatusBadRequest -const PutJobsIDStatusBadRequestCode int = 400 - -/* -PutJobsIDStatusBadRequest Bad Request - -swagger:response putJobsIdStatusBadRequest -*/ -type PutJobsIDStatusBadRequest struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewPutJobsIDStatusBadRequest creates PutJobsIDStatusBadRequest with default headers values -func NewPutJobsIDStatusBadRequest() *PutJobsIDStatusBadRequest { - - return &PutJobsIDStatusBadRequest{} -} - -// WithPayload adds the payload to the put jobs Id status bad request response -func (o *PutJobsIDStatusBadRequest) WithPayload(payload *model.ErrorResponse) *PutJobsIDStatusBadRequest { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the put jobs Id status bad request response -func (o *PutJobsIDStatusBadRequest) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *PutJobsIDStatusBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(400) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// PutJobsIDStatusNotFoundCode is the HTTP code returned for type PutJobsIDStatusNotFound -const PutJobsIDStatusNotFoundCode int = 404 - -/* -PutJobsIDStatusNotFound Not Found - -swagger:response putJobsIdStatusNotFound -*/ -type PutJobsIDStatusNotFound struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewPutJobsIDStatusNotFound creates PutJobsIDStatusNotFound with default headers values -func NewPutJobsIDStatusNotFound() *PutJobsIDStatusNotFound { - - return &PutJobsIDStatusNotFound{} -} - -// WithPayload adds the payload to the put jobs Id status not found response -func (o *PutJobsIDStatusNotFound) WithPayload(payload *model.ErrorResponse) *PutJobsIDStatusNotFound { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the put jobs Id status not found response -func (o *PutJobsIDStatusNotFound) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *PutJobsIDStatusNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(404) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -PutJobsIDStatusDefault Other error with any status code and response body format. - -swagger:response putJobsIdStatusDefault -*/ -type PutJobsIDStatusDefault struct { - _statusCode int -} - -// NewPutJobsIDStatusDefault creates PutJobsIDStatusDefault with default headers values -func NewPutJobsIDStatusDefault(code int) *PutJobsIDStatusDefault { - if code <= 0 { - code = 500 - } - - return &PutJobsIDStatusDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the put jobs ID status default response -func (o *PutJobsIDStatusDefault) WithStatusCode(code int) *PutJobsIDStatusDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the put jobs ID status default response -func (o *PutJobsIDStatusDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *PutJobsIDStatusDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/northbound/restapi/operations/northbound/put_jobs_id_status_urlbuilder.go b/generated/northbound/restapi/operations/northbound/put_jobs_id_status_urlbuilder.go deleted file mode 100644 index f68c6a7e..00000000 --- a/generated/northbound/restapi/operations/northbound/put_jobs_id_status_urlbuilder.go +++ /dev/null @@ -1,104 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package northbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" - "strings" -) - -// PutJobsIDStatusURL generates an URL for the put jobs ID status operation -type PutJobsIDStatusURL struct { - ID string - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *PutJobsIDStatusURL) WithBasePath(bp string) *PutJobsIDStatusURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *PutJobsIDStatusURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *PutJobsIDStatusURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/jobs/{id}/status" - - id := o.ID - if id != "" { - _path = strings.Replace(_path, "{id}", id, -1) - } else { - return nil, errors.New("id is required on PutJobsIDStatusURL") - } - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *PutJobsIDStatusURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *PutJobsIDStatusURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *PutJobsIDStatusURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on PutJobsIDStatusURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on PutJobsIDStatusURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *PutJobsIDStatusURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/northbound/restapi/operations/workflow_executor_api.go b/generated/northbound/restapi/operations/workflow_executor_api.go deleted file mode 100644 index 3e655556..00000000 --- a/generated/northbound/restapi/operations/workflow_executor_api.go +++ /dev/null @@ -1,500 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package operations - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "fmt" - "io" - "net/http" - "strings" - - "github.com/go-openapi/errors" - "github.com/go-openapi/loads" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/runtime/security" - "github.com/go-openapi/spec" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - - "github.com/siemens/wfx/generated/northbound/restapi/operations/northbound" -) - -// NewWorkflowExecutorAPI creates a new WorkflowExecutor instance -func NewWorkflowExecutorAPI(spec *loads.Document) *WorkflowExecutorAPI { - return &WorkflowExecutorAPI{ - handlers: make(map[string]map[string]http.Handler), - formats: strfmt.Default, - defaultConsumes: "application/json", - defaultProduces: "application/json", - customConsumers: make(map[string]runtime.Consumer), - customProducers: make(map[string]runtime.Producer), - PreServerShutdown: func() {}, - ServerShutdown: func() {}, - spec: spec, - useSwaggerUI: false, - ServeError: errors.ServeError, - BasicAuthenticator: security.BasicAuth, - APIKeyAuthenticator: security.APIKeyAuth, - BearerAuthenticator: security.BearerAuth, - - JSONConsumer: runtime.JSONConsumer(), - - JSONProducer: runtime.JSONProducer(), - TextEventStreamProducer: runtime.ProducerFunc(func(w io.Writer, data interface{}) error { - return errors.NotImplemented("textEventStream producer has not yet been implemented") - }), - - NorthboundDeleteJobsIDHandler: northbound.DeleteJobsIDHandlerFunc(func(params northbound.DeleteJobsIDParams) middleware.Responder { - return middleware.NotImplemented("operation northbound.DeleteJobsID has not yet been implemented") - }), - NorthboundDeleteJobsIDTagsHandler: northbound.DeleteJobsIDTagsHandlerFunc(func(params northbound.DeleteJobsIDTagsParams) middleware.Responder { - return middleware.NotImplemented("operation northbound.DeleteJobsIDTags has not yet been implemented") - }), - NorthboundDeleteWorkflowsNameHandler: northbound.DeleteWorkflowsNameHandlerFunc(func(params northbound.DeleteWorkflowsNameParams) middleware.Responder { - return middleware.NotImplemented("operation northbound.DeleteWorkflowsName has not yet been implemented") - }), - NorthboundGetJobsHandler: northbound.GetJobsHandlerFunc(func(params northbound.GetJobsParams) middleware.Responder { - return middleware.NotImplemented("operation northbound.GetJobs has not yet been implemented") - }), - NorthboundGetJobsEventsHandler: northbound.GetJobsEventsHandlerFunc(func(params northbound.GetJobsEventsParams) middleware.Responder { - return middleware.NotImplemented("operation northbound.GetJobsEvents has not yet been implemented") - }), - NorthboundGetJobsIDHandler: northbound.GetJobsIDHandlerFunc(func(params northbound.GetJobsIDParams) middleware.Responder { - return middleware.NotImplemented("operation northbound.GetJobsID has not yet been implemented") - }), - NorthboundGetJobsIDDefinitionHandler: northbound.GetJobsIDDefinitionHandlerFunc(func(params northbound.GetJobsIDDefinitionParams) middleware.Responder { - return middleware.NotImplemented("operation northbound.GetJobsIDDefinition has not yet been implemented") - }), - NorthboundGetJobsIDStatusHandler: northbound.GetJobsIDStatusHandlerFunc(func(params northbound.GetJobsIDStatusParams) middleware.Responder { - return middleware.NotImplemented("operation northbound.GetJobsIDStatus has not yet been implemented") - }), - NorthboundGetJobsIDTagsHandler: northbound.GetJobsIDTagsHandlerFunc(func(params northbound.GetJobsIDTagsParams) middleware.Responder { - return middleware.NotImplemented("operation northbound.GetJobsIDTags has not yet been implemented") - }), - NorthboundGetWorkflowsHandler: northbound.GetWorkflowsHandlerFunc(func(params northbound.GetWorkflowsParams) middleware.Responder { - return middleware.NotImplemented("operation northbound.GetWorkflows has not yet been implemented") - }), - NorthboundGetWorkflowsNameHandler: northbound.GetWorkflowsNameHandlerFunc(func(params northbound.GetWorkflowsNameParams) middleware.Responder { - return middleware.NotImplemented("operation northbound.GetWorkflowsName has not yet been implemented") - }), - NorthboundPostJobsHandler: northbound.PostJobsHandlerFunc(func(params northbound.PostJobsParams) middleware.Responder { - return middleware.NotImplemented("operation northbound.PostJobs has not yet been implemented") - }), - NorthboundPostJobsIDTagsHandler: northbound.PostJobsIDTagsHandlerFunc(func(params northbound.PostJobsIDTagsParams) middleware.Responder { - return middleware.NotImplemented("operation northbound.PostJobsIDTags has not yet been implemented") - }), - NorthboundPostWorkflowsHandler: northbound.PostWorkflowsHandlerFunc(func(params northbound.PostWorkflowsParams) middleware.Responder { - return middleware.NotImplemented("operation northbound.PostWorkflows has not yet been implemented") - }), - NorthboundPutJobsIDDefinitionHandler: northbound.PutJobsIDDefinitionHandlerFunc(func(params northbound.PutJobsIDDefinitionParams) middleware.Responder { - return middleware.NotImplemented("operation northbound.PutJobsIDDefinition has not yet been implemented") - }), - NorthboundPutJobsIDStatusHandler: northbound.PutJobsIDStatusHandlerFunc(func(params northbound.PutJobsIDStatusParams) middleware.Responder { - return middleware.NotImplemented("operation northbound.PutJobsIDStatus has not yet been implemented") - }), - } -} - -/*WorkflowExecutorAPI the workflow executor API */ -type WorkflowExecutorAPI struct { - spec *loads.Document - context *middleware.Context - handlers map[string]map[string]http.Handler - formats strfmt.Registry - customConsumers map[string]runtime.Consumer - customProducers map[string]runtime.Producer - defaultConsumes string - defaultProduces string - Middleware func(middleware.Builder) http.Handler - useSwaggerUI bool - - // BasicAuthenticator generates a runtime.Authenticator from the supplied basic auth function. - // It has a default implementation in the security package, however you can replace it for your particular usage. - BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator - - // APIKeyAuthenticator generates a runtime.Authenticator from the supplied token auth function. - // It has a default implementation in the security package, however you can replace it for your particular usage. - APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator - - // BearerAuthenticator generates a runtime.Authenticator from the supplied bearer token auth function. - // It has a default implementation in the security package, however you can replace it for your particular usage. - BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator - - // JSONConsumer registers a consumer for the following mime types: - // - application/json - JSONConsumer runtime.Consumer - - // JSONProducer registers a producer for the following mime types: - // - application/json - JSONProducer runtime.Producer - // TextEventStreamProducer registers a producer for the following mime types: - // - text/event-stream - TextEventStreamProducer runtime.Producer - - // NorthboundDeleteJobsIDHandler sets the operation handler for the delete jobs ID operation - NorthboundDeleteJobsIDHandler northbound.DeleteJobsIDHandler - // NorthboundDeleteJobsIDTagsHandler sets the operation handler for the delete jobs ID tags operation - NorthboundDeleteJobsIDTagsHandler northbound.DeleteJobsIDTagsHandler - // NorthboundDeleteWorkflowsNameHandler sets the operation handler for the delete workflows name operation - NorthboundDeleteWorkflowsNameHandler northbound.DeleteWorkflowsNameHandler - // NorthboundGetJobsHandler sets the operation handler for the get jobs operation - NorthboundGetJobsHandler northbound.GetJobsHandler - // NorthboundGetJobsEventsHandler sets the operation handler for the get jobs events operation - NorthboundGetJobsEventsHandler northbound.GetJobsEventsHandler - // NorthboundGetJobsIDHandler sets the operation handler for the get jobs ID operation - NorthboundGetJobsIDHandler northbound.GetJobsIDHandler - // NorthboundGetJobsIDDefinitionHandler sets the operation handler for the get jobs ID definition operation - NorthboundGetJobsIDDefinitionHandler northbound.GetJobsIDDefinitionHandler - // NorthboundGetJobsIDStatusHandler sets the operation handler for the get jobs ID status operation - NorthboundGetJobsIDStatusHandler northbound.GetJobsIDStatusHandler - // NorthboundGetJobsIDTagsHandler sets the operation handler for the get jobs ID tags operation - NorthboundGetJobsIDTagsHandler northbound.GetJobsIDTagsHandler - // NorthboundGetWorkflowsHandler sets the operation handler for the get workflows operation - NorthboundGetWorkflowsHandler northbound.GetWorkflowsHandler - // NorthboundGetWorkflowsNameHandler sets the operation handler for the get workflows name operation - NorthboundGetWorkflowsNameHandler northbound.GetWorkflowsNameHandler - // NorthboundPostJobsHandler sets the operation handler for the post jobs operation - NorthboundPostJobsHandler northbound.PostJobsHandler - // NorthboundPostJobsIDTagsHandler sets the operation handler for the post jobs ID tags operation - NorthboundPostJobsIDTagsHandler northbound.PostJobsIDTagsHandler - // NorthboundPostWorkflowsHandler sets the operation handler for the post workflows operation - NorthboundPostWorkflowsHandler northbound.PostWorkflowsHandler - // NorthboundPutJobsIDDefinitionHandler sets the operation handler for the put jobs ID definition operation - NorthboundPutJobsIDDefinitionHandler northbound.PutJobsIDDefinitionHandler - // NorthboundPutJobsIDStatusHandler sets the operation handler for the put jobs ID status operation - NorthboundPutJobsIDStatusHandler northbound.PutJobsIDStatusHandler - - // ServeError is called when an error is received, there is a default handler - // but you can set your own with this - ServeError func(http.ResponseWriter, *http.Request, error) - - // PreServerShutdown is called before the HTTP(S) server is shutdown - // This allows for custom functions to get executed before the HTTP(S) server stops accepting traffic - PreServerShutdown func() - - // ServerShutdown is called when the HTTP(S) server is shut down and done - // handling all active connections and does not accept connections any more - ServerShutdown func() - - // Custom command line argument groups with their descriptions - CommandLineOptionsGroups []swag.CommandLineOptionsGroup - - // User defined logger function. - Logger func(string, ...interface{}) -} - -// UseRedoc for documentation at /docs -func (o *WorkflowExecutorAPI) UseRedoc() { - o.useSwaggerUI = false -} - -// UseSwaggerUI for documentation at /docs -func (o *WorkflowExecutorAPI) UseSwaggerUI() { - o.useSwaggerUI = true -} - -// SetDefaultProduces sets the default produces media type -func (o *WorkflowExecutorAPI) SetDefaultProduces(mediaType string) { - o.defaultProduces = mediaType -} - -// SetDefaultConsumes returns the default consumes media type -func (o *WorkflowExecutorAPI) SetDefaultConsumes(mediaType string) { - o.defaultConsumes = mediaType -} - -// SetSpec sets a spec that will be served for the clients. -func (o *WorkflowExecutorAPI) SetSpec(spec *loads.Document) { - o.spec = spec -} - -// DefaultProduces returns the default produces media type -func (o *WorkflowExecutorAPI) DefaultProduces() string { - return o.defaultProduces -} - -// DefaultConsumes returns the default consumes media type -func (o *WorkflowExecutorAPI) DefaultConsumes() string { - return o.defaultConsumes -} - -// Formats returns the registered string formats -func (o *WorkflowExecutorAPI) Formats() strfmt.Registry { - return o.formats -} - -// RegisterFormat registers a custom format validator -func (o *WorkflowExecutorAPI) RegisterFormat(name string, format strfmt.Format, validator strfmt.Validator) { - o.formats.Add(name, format, validator) -} - -// Validate validates the registrations in the WorkflowExecutorAPI -func (o *WorkflowExecutorAPI) Validate() error { - var unregistered []string - - if o.JSONConsumer == nil { - unregistered = append(unregistered, "JSONConsumer") - } - - if o.JSONProducer == nil { - unregistered = append(unregistered, "JSONProducer") - } - if o.TextEventStreamProducer == nil { - unregistered = append(unregistered, "TextEventStreamProducer") - } - - if o.NorthboundDeleteJobsIDHandler == nil { - unregistered = append(unregistered, "northbound.DeleteJobsIDHandler") - } - if o.NorthboundDeleteJobsIDTagsHandler == nil { - unregistered = append(unregistered, "northbound.DeleteJobsIDTagsHandler") - } - if o.NorthboundDeleteWorkflowsNameHandler == nil { - unregistered = append(unregistered, "northbound.DeleteWorkflowsNameHandler") - } - if o.NorthboundGetJobsHandler == nil { - unregistered = append(unregistered, "northbound.GetJobsHandler") - } - if o.NorthboundGetJobsEventsHandler == nil { - unregistered = append(unregistered, "northbound.GetJobsEventsHandler") - } - if o.NorthboundGetJobsIDHandler == nil { - unregistered = append(unregistered, "northbound.GetJobsIDHandler") - } - if o.NorthboundGetJobsIDDefinitionHandler == nil { - unregistered = append(unregistered, "northbound.GetJobsIDDefinitionHandler") - } - if o.NorthboundGetJobsIDStatusHandler == nil { - unregistered = append(unregistered, "northbound.GetJobsIDStatusHandler") - } - if o.NorthboundGetJobsIDTagsHandler == nil { - unregistered = append(unregistered, "northbound.GetJobsIDTagsHandler") - } - if o.NorthboundGetWorkflowsHandler == nil { - unregistered = append(unregistered, "northbound.GetWorkflowsHandler") - } - if o.NorthboundGetWorkflowsNameHandler == nil { - unregistered = append(unregistered, "northbound.GetWorkflowsNameHandler") - } - if o.NorthboundPostJobsHandler == nil { - unregistered = append(unregistered, "northbound.PostJobsHandler") - } - if o.NorthboundPostJobsIDTagsHandler == nil { - unregistered = append(unregistered, "northbound.PostJobsIDTagsHandler") - } - if o.NorthboundPostWorkflowsHandler == nil { - unregistered = append(unregistered, "northbound.PostWorkflowsHandler") - } - if o.NorthboundPutJobsIDDefinitionHandler == nil { - unregistered = append(unregistered, "northbound.PutJobsIDDefinitionHandler") - } - if o.NorthboundPutJobsIDStatusHandler == nil { - unregistered = append(unregistered, "northbound.PutJobsIDStatusHandler") - } - - if len(unregistered) > 0 { - return fmt.Errorf("missing registration: %s", strings.Join(unregistered, ", ")) - } - - return nil -} - -// ServeErrorFor gets a error handler for a given operation id -func (o *WorkflowExecutorAPI) ServeErrorFor(operationID string) func(http.ResponseWriter, *http.Request, error) { - return o.ServeError -} - -// AuthenticatorsFor gets the authenticators for the specified security schemes -func (o *WorkflowExecutorAPI) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[string]runtime.Authenticator { - return nil -} - -// Authorizer returns the registered authorizer -func (o *WorkflowExecutorAPI) Authorizer() runtime.Authorizer { - return nil -} - -// ConsumersFor gets the consumers for the specified media types. -// MIME type parameters are ignored here. -func (o *WorkflowExecutorAPI) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer { - result := make(map[string]runtime.Consumer, len(mediaTypes)) - for _, mt := range mediaTypes { - switch mt { - case "application/json": - result["application/json"] = o.JSONConsumer - } - - if c, ok := o.customConsumers[mt]; ok { - result[mt] = c - } - } - return result -} - -// ProducersFor gets the producers for the specified media types. -// MIME type parameters are ignored here. -func (o *WorkflowExecutorAPI) ProducersFor(mediaTypes []string) map[string]runtime.Producer { - result := make(map[string]runtime.Producer, len(mediaTypes)) - for _, mt := range mediaTypes { - switch mt { - case "application/json": - result["application/json"] = o.JSONProducer - case "text/event-stream": - result["text/event-stream"] = o.TextEventStreamProducer - } - - if p, ok := o.customProducers[mt]; ok { - result[mt] = p - } - } - return result -} - -// HandlerFor gets a http.Handler for the provided operation method and path -func (o *WorkflowExecutorAPI) HandlerFor(method, path string) (http.Handler, bool) { - if o.handlers == nil { - return nil, false - } - um := strings.ToUpper(method) - if _, ok := o.handlers[um]; !ok { - return nil, false - } - if path == "/" { - path = "" - } - h, ok := o.handlers[um][path] - return h, ok -} - -// Context returns the middleware context for the workflow executor API -func (o *WorkflowExecutorAPI) Context() *middleware.Context { - if o.context == nil { - o.context = middleware.NewRoutableContext(o.spec, o, nil) - } - - return o.context -} - -func (o *WorkflowExecutorAPI) initHandlerCache() { - o.Context() // don't care about the result, just that the initialization happened - if o.handlers == nil { - o.handlers = make(map[string]map[string]http.Handler) - } - - if o.handlers["DELETE"] == nil { - o.handlers["DELETE"] = make(map[string]http.Handler) - } - o.handlers["DELETE"]["/jobs/{id}"] = northbound.NewDeleteJobsID(o.context, o.NorthboundDeleteJobsIDHandler) - if o.handlers["DELETE"] == nil { - o.handlers["DELETE"] = make(map[string]http.Handler) - } - o.handlers["DELETE"]["/jobs/{id}/tags"] = northbound.NewDeleteJobsIDTags(o.context, o.NorthboundDeleteJobsIDTagsHandler) - if o.handlers["DELETE"] == nil { - o.handlers["DELETE"] = make(map[string]http.Handler) - } - o.handlers["DELETE"]["/workflows/{name}"] = northbound.NewDeleteWorkflowsName(o.context, o.NorthboundDeleteWorkflowsNameHandler) - if o.handlers["GET"] == nil { - o.handlers["GET"] = make(map[string]http.Handler) - } - o.handlers["GET"]["/jobs"] = northbound.NewGetJobs(o.context, o.NorthboundGetJobsHandler) - if o.handlers["GET"] == nil { - o.handlers["GET"] = make(map[string]http.Handler) - } - o.handlers["GET"]["/jobs/events"] = northbound.NewGetJobsEvents(o.context, o.NorthboundGetJobsEventsHandler) - if o.handlers["GET"] == nil { - o.handlers["GET"] = make(map[string]http.Handler) - } - o.handlers["GET"]["/jobs/{id}"] = northbound.NewGetJobsID(o.context, o.NorthboundGetJobsIDHandler) - if o.handlers["GET"] == nil { - o.handlers["GET"] = make(map[string]http.Handler) - } - o.handlers["GET"]["/jobs/{id}/definition"] = northbound.NewGetJobsIDDefinition(o.context, o.NorthboundGetJobsIDDefinitionHandler) - if o.handlers["GET"] == nil { - o.handlers["GET"] = make(map[string]http.Handler) - } - o.handlers["GET"]["/jobs/{id}/status"] = northbound.NewGetJobsIDStatus(o.context, o.NorthboundGetJobsIDStatusHandler) - if o.handlers["GET"] == nil { - o.handlers["GET"] = make(map[string]http.Handler) - } - o.handlers["GET"]["/jobs/{id}/tags"] = northbound.NewGetJobsIDTags(o.context, o.NorthboundGetJobsIDTagsHandler) - if o.handlers["GET"] == nil { - o.handlers["GET"] = make(map[string]http.Handler) - } - o.handlers["GET"]["/workflows"] = northbound.NewGetWorkflows(o.context, o.NorthboundGetWorkflowsHandler) - if o.handlers["GET"] == nil { - o.handlers["GET"] = make(map[string]http.Handler) - } - o.handlers["GET"]["/workflows/{name}"] = northbound.NewGetWorkflowsName(o.context, o.NorthboundGetWorkflowsNameHandler) - if o.handlers["POST"] == nil { - o.handlers["POST"] = make(map[string]http.Handler) - } - o.handlers["POST"]["/jobs"] = northbound.NewPostJobs(o.context, o.NorthboundPostJobsHandler) - if o.handlers["POST"] == nil { - o.handlers["POST"] = make(map[string]http.Handler) - } - o.handlers["POST"]["/jobs/{id}/tags"] = northbound.NewPostJobsIDTags(o.context, o.NorthboundPostJobsIDTagsHandler) - if o.handlers["POST"] == nil { - o.handlers["POST"] = make(map[string]http.Handler) - } - o.handlers["POST"]["/workflows"] = northbound.NewPostWorkflows(o.context, o.NorthboundPostWorkflowsHandler) - if o.handlers["PUT"] == nil { - o.handlers["PUT"] = make(map[string]http.Handler) - } - o.handlers["PUT"]["/jobs/{id}/definition"] = northbound.NewPutJobsIDDefinition(o.context, o.NorthboundPutJobsIDDefinitionHandler) - if o.handlers["PUT"] == nil { - o.handlers["PUT"] = make(map[string]http.Handler) - } - o.handlers["PUT"]["/jobs/{id}/status"] = northbound.NewPutJobsIDStatus(o.context, o.NorthboundPutJobsIDStatusHandler) -} - -// Serve creates a http handler to serve the API over HTTP -// can be used directly in http.ListenAndServe(":8000", api.Serve(nil)) -func (o *WorkflowExecutorAPI) Serve(builder middleware.Builder) http.Handler { - o.Init() - - if o.Middleware != nil { - return o.Middleware(builder) - } - if o.useSwaggerUI { - return o.context.APIHandlerSwaggerUI(builder) - } - return o.context.APIHandler(builder) -} - -// Init allows you to just initialize the handler cache, you can then recompose the middleware as you see fit -func (o *WorkflowExecutorAPI) Init() { - if len(o.handlers) == 0 { - o.initHandlerCache() - } -} - -// RegisterConsumer allows you to add (or override) a consumer for a media type. -func (o *WorkflowExecutorAPI) RegisterConsumer(mediaType string, consumer runtime.Consumer) { - o.customConsumers[mediaType] = consumer -} - -// RegisterProducer allows you to add (or override) a producer for a media type. -func (o *WorkflowExecutorAPI) RegisterProducer(mediaType string, producer runtime.Producer) { - o.customProducers[mediaType] = producer -} - -// AddMiddlewareFor adds a http middleware to existing handler -func (o *WorkflowExecutorAPI) AddMiddlewareFor(method, path string, builder middleware.Builder) { - um := strings.ToUpper(method) - if path == "/" { - path = "" - } - o.Init() - if h, ok := o.handlers[um][path]; ok { - o.handlers[um][path] = builder(h) - } -} diff --git a/generated/southbound/restapi/configure_workflow_executor.go b/generated/southbound/restapi/configure_workflow_executor.go deleted file mode 100644 index 13570198..00000000 --- a/generated/southbound/restapi/configure_workflow_executor.go +++ /dev/null @@ -1,50 +0,0 @@ -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 - -package restapi - -import ( - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/rs/zerolog/log" - - "github.com/siemens/wfx/generated/southbound/restapi/operations" - "github.com/siemens/wfx/internal/producer" -) - -func ConfigureAPI(api *operations.WorkflowExecutorAPI) http.Handler { - // configure the api here - api.ServeError = func(rw http.ResponseWriter, r *http.Request, err error) { - log.Error().Msg(err.Error()) - errors.ServeError(rw, r, err) - } - - api.Logger = log.Printf - - api.UseSwaggerUI() - - api.JSONConsumer = runtime.JSONConsumer() - - api.JSONProducer = producer.JSONProducer() - - api.TextEventStreamProducer = producer.TextEventStreamProducer() - - api.PreServerShutdown = func() {} - - return setupGlobalMiddleware(api.Serve(setupMiddlewares)) -} - -// The middleware configuration is for the handler executors. These do not apply to the swagger.json document. -// The middleware executes after routing but before authentication, binding and validation. -func setupMiddlewares(handler http.Handler) http.Handler { - return handler -} - -// The middleware configuration happens before anything, this middleware also applies to serving the swagger.json document. -// So this is a good place to plug in a panic handling middleware, logging and metrics -func setupGlobalMiddleware(handler http.Handler) http.Handler { - return handler -} diff --git a/generated/southbound/restapi/doc.go b/generated/southbound/restapi/doc.go deleted file mode 100644 index 5876cb2b..00000000 --- a/generated/southbound/restapi/doc.go +++ /dev/null @@ -1,24 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -// Package restapi Workflow Executor -// -// Schemes: -// http -// Host: localhost -// BasePath: /api/wfx/v1 -// Version: 1.0.0 -// License: Apache 2.0 http://www.apache.org/licenses/LICENSE-2.0.html -// -// Consumes: -// - application/json -// -// Produces: -// - application/json -// - text/event-stream -// -// swagger:meta -package restapi diff --git a/generated/southbound/restapi/embedded_spec.go b/generated/southbound/restapi/embedded_spec.go deleted file mode 100644 index edc8f3af..00000000 --- a/generated/southbound/restapi/embedded_spec.go +++ /dev/null @@ -1,3415 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package restapi - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "encoding/json" -) - -var ( - // SwaggerJSON embedded version of the swagger document used at generation time - SwaggerJSON json.RawMessage - // FlatSwaggerJSON embedded flattened version of the swagger document used at generation time - FlatSwaggerJSON json.RawMessage -) - -func init() { - SwaggerJSON = json.RawMessage([]byte(`{ - "schemes": [ - "http" - ], - "swagger": "2.0", - "info": { - "title": "Workflow Executor", - "license": { - "name": "Apache 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0.html" - }, - "version": "1.0.0", - "x-visibility": "external" - }, - "basePath": "/api/wfx/v1", - "paths": { - "/jobs": { - "get": { - "description": "List of job descriptions\nBy default, this endpoint returns the list of jobs in a specific order and predetermined paging properties.\nThese defaults are:\n - Ascending sort on stime\n - 10 entries per page\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "southbound", - "northbound" - ], - "summary": "List of job descriptions", - "parameters": [ - { - "$ref": "#/parameters/offset" - }, - { - "$ref": "#/parameters/limit" - }, - { - "$ref": "#/parameters/sort" - }, - { - "$ref": "#/parameters/state" - }, - { - "$ref": "#/parameters/group" - }, - { - "$ref": "#/parameters/clientId" - }, - { - "$ref": "#/parameters/workflow" - }, - { - "$ref": "#/parameters/tag" - } - ], - "responses": { - "200": { - "description": "A paginated job list.", - "schema": { - "$ref": "#/definitions/PaginatedJobList" - } - }, - "400": { - "description": "If request is invalid", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "post": { - "description": "Add a new job\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound" - ], - "summary": "Add a new job", - "parameters": [ - { - "description": "Job which shall be created", - "name": "Job", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/JobRequest" - } - } - ], - "responses": { - "201": { - "description": "Job was created", - "schema": { - "$ref": "#/definitions/Job" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - }, - "/jobs/events": { - "get": { - "description": "Obtain instant notifications when there are job changes matching the criteria. This endpoint utilizes server-sent events (SSE), where responses are \"chunked\" with double newline breaks. For example, a single event might look like this:\n data: {\"clientId\":\"example_client\",\"state\":\"INSTALLING\"}\\n\\n\n", - "produces": [ - "application/json", - "text/event-stream" - ], - "tags": [ - "jobs", - "northbound", - "southbound" - ], - "summary": "Subscribe to job-related events such as status updates", - "parameters": [ - { - "type": "string", - "description": "The job's clientId must be one of these clientIds (comma-separated).", - "name": "clientIds", - "in": "query" - }, - { - "type": "string", - "description": "The job's id must be one of these ids (comma-separated).", - "name": "jobIds", - "in": "query" - }, - { - "type": "string", - "description": "The job's workflow must be equal to one of the provided workflow names (comma-separated).", - "name": "workflows", - "in": "query" - }, - { - "type": "string", - "description": "A (comma-separated) list of tags to include into each job event. This can be used to aggregrate events from multiple wfx instances.\n", - "name": "tags", - "in": "query" - } - ], - "responses": { - "200": { - "description": "A stream of server-sent events" - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.jobTerminalState", - "logref": "916f0a913a3e4a52a96bd271e029c201", - "message": "The request was invalid because the job is in a terminal state" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format" - } - } - } - }, - "/jobs/{id}": { - "get": { - "description": "Job description for a given ID\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "southbound", - "northbound" - ], - "summary": "Job description for a given ID", - "parameters": [ - { - "$ref": "#/parameters/jobId" - }, - { - "$ref": "#/parameters/history" - } - ], - "responses": { - "200": { - "description": "Job description for for a given ID", - "schema": { - "$ref": "#/definitions/Job" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while querying a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "delete": { - "description": "Delete an existing job\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound" - ], - "summary": "Delete an existing job", - "parameters": [ - { - "$ref": "#/parameters/jobId" - } - ], - "responses": { - "204": { - "description": "The job has been deleted." - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while querying a non-existent workflow": { - "errors": [ - { - "code": "wfx.workflowNotFound", - "logref": "c452719774086b6e803bb8f6ecea9899", - "message": "Workflow not found for given name" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - }, - "/jobs/{id}/definition": { - "get": { - "description": "Retrieve the job definition", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound", - "southbound" - ], - "summary": "Get job definition", - "parameters": [ - { - "$ref": "#/parameters/jobId" - } - ], - "responses": { - "200": { - "description": "Job definition", - "schema": { - "type": "object", - "additionalProperties": { - "type": "object" - }, - "example": "{ \"userDefined\": {} }\n" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "put": { - "description": "Modify the job definition of an existing job\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "southbound", - "northbound" - ], - "summary": "Modify job definition", - "parameters": [ - { - "$ref": "#/parameters/jobId" - }, - { - "description": "How to modify the job", - "name": "JobDefinition", - "in": "body", - "required": true, - "schema": { - "type": "object", - "additionalProperties": { - "type": "object" - }, - "example": "{ \"userDefined\": {} }\n" - } - } - ], - "responses": { - "200": { - "description": "Job modified successfully", - "schema": { - "type": "object", - "additionalProperties": { - "type": "object" - }, - "example": "{ \"userDefined\": {} }\n" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - }, - "/jobs/{id}/status": { - "get": { - "description": "Retrieve the job status", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound", - "southbound" - ], - "summary": "Get job status", - "parameters": [ - { - "$ref": "#/parameters/jobId" - } - ], - "responses": { - "200": { - "description": "Job status", - "schema": { - "$ref": "#/definitions/JobStatus" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "put": { - "description": "Modify status of an existing job\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "southbound", - "northbound" - ], - "summary": "Modify status of an existing job", - "parameters": [ - { - "$ref": "#/parameters/jobId" - }, - { - "description": "This contains the new job status", - "name": "New job status", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/JobStatus" - } - } - ], - "responses": { - "200": { - "description": "Job modified successfully", - "schema": { - "$ref": "#/definitions/JobStatus" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - }, - "/jobs/{id}/tags": { - "get": { - "description": "Get the tags of a job", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound", - "southbound" - ], - "summary": "Get tags", - "parameters": [ - { - "$ref": "#/parameters/jobId" - } - ], - "responses": { - "200": { - "description": "Job tags", - "schema": { - "type": "array", - "items": { - "type": "string", - "example": "EUROPE_WEST" - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "post": { - "description": "Add a tag to an existing job\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound" - ], - "summary": "Add a tag", - "parameters": [ - { - "$ref": "#/parameters/jobId" - }, - { - "description": "Tags to add", - "name": "Tags", - "in": "body", - "required": true, - "schema": { - "type": "array", - "maxItems": 16, - "minItems": 1, - "items": { - "type": "string" - } - } - } - ], - "responses": { - "200": { - "description": "Successfully added tag to job", - "schema": { - "type": "array", - "items": { - "type": "string", - "example": "EUROPE_WEST" - } - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "delete": { - "description": "Delete a tag from an existing job\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound" - ], - "summary": "Delete a tag", - "parameters": [ - { - "$ref": "#/parameters/jobId" - }, - { - "description": "Tags to add", - "name": "Tags", - "in": "body", - "required": true, - "schema": { - "type": "array", - "maxItems": 16, - "minItems": 1, - "items": { - "type": "string" - } - } - } - ], - "responses": { - "200": { - "description": "Successfully deleted tag", - "schema": { - "type": "array", - "items": { - "type": "string", - "example": "EUROPE_WEST" - } - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - }, - "/workflows": { - "get": { - "description": "List of available workflows", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "workflows", - "northbound", - "southbound" - ], - "summary": "List of available workflows", - "parameters": [ - { - "$ref": "#/parameters/limit" - }, - { - "$ref": "#/parameters/offset" - }, - { - "$ref": "#/parameters/sort" - } - ], - "responses": { - "200": { - "description": "A list of workflows", - "schema": { - "$ref": "#/definitions/PaginatedWorkflowList" - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "post": { - "description": "Add a new workflow", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "workflows", - "northbound" - ], - "summary": "Add a new workflow", - "parameters": [ - { - "description": "Workflow object to be added", - "name": "Workflow", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/Workflow" - } - } - ], - "responses": { - "201": { - "description": "Workflow was created", - "schema": { - "$ref": "#/definitions/Workflow" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.workflowNotUnique", - "logref": "e1ee1f2aea859b9dd34579610e386da6", - "message": "Workflow with name already exists" - }, - { - "code": "wfx.workflowInvalid", - "logref": "18f57adc70dd79c7fb4f1246be8a6e04", - "message": "Workflow validation failed" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - }, - "/workflows/{name}": { - "get": { - "description": "Workflow description for a given name", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "workflows", - "northbound", - "southbound" - ], - "summary": "Workflow description for a given name", - "parameters": [ - { - "type": "string", - "description": "Unique name for the workflow", - "name": "name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Workflow description with the provided key", - "schema": { - "$ref": "#/definitions/Workflow" - } - }, - "400": { - "description": "If request is invalid", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while querying a non-existent workflow": { - "errors": [ - { - "code": "wfx.workflowNotFound", - "logref": "c452719774086b6e803bb8f6ecea9899", - "message": "Workflow not found for given name" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "delete": { - "description": "Delete an existing workflow\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "workflows", - "northbound" - ], - "summary": "Delete an existing workflow", - "parameters": [ - { - "type": "string", - "description": "Workflow name", - "name": "name", - "in": "path", - "required": true - } - ], - "responses": { - "204": { - "description": "The workflow has been deleted." - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while querying a non-existent workflow": { - "errors": [ - { - "code": "wfx.workflowNotFound", - "logref": "c452719774086b6e803bb8f6ecea9899", - "message": "Workflow not found for given name" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - } - }, - "definitions": { - "ActionEnum": { - "type": "string", - "enum": [ - "IMMEDIATE", - "WAIT" - ] - }, - "EligibleEnum": { - "type": "string", - "enum": [ - "CLIENT", - "WFX" - ], - "x-nullable": false - }, - "Error": { - "type": "object", - "properties": { - "code": { - "description": "Identifier code for the reason of the error", - "type": "string" - }, - "logref": { - "description": "Log correlation ID", - "type": "string" - }, - "message": { - "description": "Error message", - "type": "string" - } - } - }, - "ErrorResponse": { - "type": "object", - "properties": { - "errors": { - "type": "array", - "maxItems": 128, - "items": { - "$ref": "#/definitions/Error" - } - } - } - }, - "Group": { - "type": "object", - "required": [ - "name", - "states" - ], - "properties": { - "description": { - "type": "string", - "example": "Description of the group" - }, - "name": { - "type": "string", - "x-nullable": false, - "example": "OPEN" - }, - "states": { - "description": "A list of states belonging to this group", - "type": "array", - "maxItems": 4096, - "minItems": 1, - "items": { - "type": "string" - } - } - } - }, - "History": { - "type": "object", - "properties": { - "definition": { - "type": "object", - "additionalProperties": { - "type": "object" - }, - "example": "{ \"userDefined\": {} }\n" - }, - "mtime": { - "description": "Date and time (ISO8601) when the job was modified (set by wfx)", - "type": "string", - "format": "date-time", - "readOnly": true - }, - "status": { - "description": "A previous job status", - "$ref": "#/definitions/JobStatus" - } - } - }, - "Job": { - "type": "object", - "properties": { - "clientId": { - "type": "string", - "x-nullable": false, - "example": "client42" - }, - "definition": { - "type": "object", - "additionalProperties": { - "type": "object" - }, - "example": "{ \"userDefined\": {} }\n" - }, - "history": { - "description": "The job's history. Last in, first out (LIFO). Array is truncated if its length exceeds the maximum allowed length.\nBy default, the job history is omitted from responses unless explicitly requested by the client (see the ` + "`" + `history` + "`" + ` URL parameter).\n", - "type": "array", - "maxItems": 8192, - "items": { - "$ref": "#/definitions/History" - }, - "x-omitempty": true - }, - "id": { - "description": "Unique job ID (wfx-generated)", - "type": "string", - "maxLength": 36, - "x-nullable": false, - "readOnly": true, - "example": "3307e5cb-074c-49b7-99d4-5e61839a4c2d" - }, - "mtime": { - "description": "Date and time (ISO8601) when the job was last modified (set by wfx)", - "type": "string", - "format": "date-time", - "x-nullable": true, - "readOnly": true - }, - "status": { - "$ref": "#/definitions/JobStatus" - }, - "stime": { - "description": "Date and time (ISO8601) when the job was created (set by wfx). Although stime conceptually always exists, it's nullable because we don't want to serialize stime in some cases (e.g. for job events).", - "type": "string", - "format": "date-time", - "x-nullable": true, - "readOnly": true - }, - "tags": { - "type": "array", - "items": { - "type": "string", - "maxItems": 16 - }, - "x-omitempty": true - }, - "workflow": { - "$ref": "#/definitions/Workflow" - } - } - }, - "JobRequest": { - "type": "object", - "required": [ - "clientId", - "workflow" - ], - "properties": { - "clientId": { - "description": "Create job for the given client ID", - "type": "string", - "x-nullable": false, - "example": "client42" - }, - "definition": { - "description": "The existing job definition will be replaced with this if this property is not empty.", - "type": "object", - "additionalProperties": { - "type": "object" - }, - "example": "{ \"userDefined\": {} }\n" - }, - "tags": { - "type": "array", - "maxItems": 16, - "items": { - "type": "string", - "example": "EUROPE_WEST" - } - }, - "workflow": { - "description": "Workflow name", - "type": "string", - "x-nullable": false, - "example": "wfx.workflow.dau.direct" - } - } - }, - "JobStatus": { - "description": "Job status information", - "type": "object", - "required": [ - "state" - ], - "properties": { - "clientId": { - "description": "Client which sent the status update", - "type": "string", - "x-nullable": false, - "example": "client42" - }, - "context": { - "description": "Client-specific JSON object to report additional context information such as error details, stack traces, etc", - "type": "object", - "maxLength": 20000, - "additionalProperties": { - "type": "object" - }, - "example": "{\n \"lines\": [ \"line1\", \"line2\" ]\n}\n" - }, - "definitionHash": { - "description": "Job definition hash", - "type": "string", - "maxLength": 64, - "readOnly": true - }, - "message": { - "description": "Reason message/info, free text from client", - "type": "string", - "maxLength": 1024 - }, - "progress": { - "description": "Current job progress percentage", - "type": "number", - "format": "int32", - "maximum": 100 - }, - "state": { - "description": "Name of the new workflow state", - "type": "string", - "x-nullable": false, - "example": "END" - } - } - }, - "PaginatedJobList": { - "description": "Paginated list of jobs", - "type": "object", - "properties": { - "content": { - "type": "array", - "items": { - "$ref": "#/definitions/Job" - } - }, - "pagination": { - "type": "object", - "properties": { - "limit": { - "description": "the maximum number of items to return", - "type": "integer", - "format": "int32", - "example": 20 - }, - "offset": { - "description": "the number of items to skip before starting to return results", - "type": "integer", - "format": "int64", - "example": 0 - }, - "total": { - "description": "the total number of items", - "type": "integer", - "format": "int64", - "example": 1000 - } - } - } - } - }, - "PaginatedWorkflowList": { - "description": "Paginated list of workflows", - "type": "object", - "properties": { - "content": { - "type": "array", - "items": { - "$ref": "#/definitions/Workflow" - } - }, - "pagination": { - "type": "object", - "properties": { - "limit": { - "description": "the maximum number of items to return", - "type": "integer", - "format": "int32", - "example": 20 - }, - "offset": { - "description": "the number of items to skip before starting to return results", - "type": "integer", - "format": "int64", - "example": 0 - }, - "total": { - "description": "the total number of items", - "type": "integer", - "format": "int64", - "example": 1000 - } - } - } - } - }, - "State": { - "type": "object", - "required": [ - "name" - ], - "properties": { - "description": { - "type": "string", - "example": "Description of the state" - }, - "name": { - "type": "string", - "x-nullable": false, - "example": "START" - } - } - }, - "Transition": { - "type": "object", - "required": [ - "from", - "to", - "eligible" - ], - "properties": { - "action": { - "description": "The transition execution action (default: WAIT)", - "$ref": "#/definitions/ActionEnum", - "example": "WAIT" - }, - "description": { - "type": "string", - "example": "Description of the transition" - }, - "eligible": { - "description": "The entity that may execute the transition", - "$ref": "#/definitions/EligibleEnum", - "example": "CLIENT" - }, - "from": { - "type": "string", - "x-nullable": false, - "example": "START" - }, - "to": { - "type": "string", - "x-nullable": false, - "example": "END" - } - } - }, - "Workflow": { - "type": "object", - "required": [ - "name" - ], - "properties": { - "description": { - "description": "Description of the workflow", - "type": "string", - "maxLength": 1024, - "example": "This is a workflow" - }, - "groups": { - "type": "array", - "maxItems": 1024, - "items": { - "$ref": "#/definitions/Group" - }, - "x-omitempty": true - }, - "name": { - "description": "User provided unique workflow name", - "type": "string", - "maxLength": 64, - "minLength": 1, - "pattern": "^[a-zA-Z0-9\\-\\.]+$", - "x-nullable": false, - "example": "wfx.workflow.dau.direct" - }, - "states": { - "type": "array", - "maxItems": 4096, - "items": { - "$ref": "#/definitions/State" - }, - "x-omitempty": true - }, - "transitions": { - "type": "array", - "maxItems": 16384, - "items": { - "$ref": "#/definitions/Transition" - }, - "x-omitempty": true - } - } - } - }, - "parameters": { - "clientId": { - "type": "string", - "description": "Filter jobs belonging to a specific client with clientId", - "name": "clientId", - "in": "query" - }, - "group": { - "type": "array", - "items": { - "type": "string" - }, - "description": "Filter jobs based on the group they are in", - "name": "group", - "in": "query" - }, - "history": { - "type": "boolean", - "description": "Boolean flag to include the transition history of the job", - "name": "history", - "in": "query" - }, - "jobId": { - "type": "string", - "description": "Job ID", - "name": "id", - "in": "path", - "required": true - }, - "limit": { - "maxItems": 1024, - "type": "integer", - "format": "int32", - "default": 10, - "description": "the maximum number of items to return", - "name": "limit", - "in": "query" - }, - "offset": { - "type": "integer", - "format": "int64", - "default": 0, - "description": "the number of items to skip before starting to return results", - "name": "offset", - "in": "query" - }, - "sort": { - "enum": [ - "asc", - "desc" - ], - "type": "string", - "default": "asc", - "description": "the order of returned elements", - "name": "sort", - "in": "query" - }, - "state": { - "type": "string", - "description": "Filter jobs based on the current state value", - "name": "state", - "in": "query" - }, - "tag": { - "type": "array", - "items": { - "type": "string" - }, - "description": "Filter jobs by tags", - "name": "tag", - "in": "query" - }, - "workflow": { - "type": "string", - "description": "Filter jobs matching by workflow", - "name": "workflow", - "in": "query" - } - }, - "tags": [ - { - "description": "Workflows used to instantiate jobs", - "name": "workflows" - }, - { - "description": "Jobs derived from workflows and executed by a client", - "name": "jobs" - }, - { - "description": "All southbound API endpoints", - "name": "southbound" - }, - { - "description": "All northbound API endpoints", - "name": "northbound" - } - ], - "x-definitions-templates": { - "Limits": { - "maxErrorCount": { - "maxItems": 128 - }, - "maxGroupCount": { - "maxItems": 1024 - }, - "maxHistoryCount": { - "maxItems": 8192 - }, - "maxItemsCount": { - "maxItems": 1024 - }, - "maxStateCount": { - "maxItems": 4096 - }, - "maxTagsCount": { - "maxItems": 16 - }, - "maxTransitionCount": { - "maxItems": 16384 - } - }, - "Pagination": { - "pagination": { - "properties": { - "limit": { - "description": "the maximum number of items to return", - "example": 20, - "format": "int32", - "type": "integer" - }, - "offset": { - "description": "the number of items to skip before starting to return results", - "example": 0, - "format": "int64", - "type": "integer" - }, - "total": { - "description": "the total number of items", - "example": 1000, - "format": "int64", - "type": "integer" - } - }, - "type": "object" - } - } - }, - "x-paths-templates": { - "Errors": { - "invalidRequestError": { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - }, - "jobNotFoundError": { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - }, - "jobTerminalStateError": { - "code": "wfx.jobTerminalState", - "logref": "916f0a913a3e4a52a96bd271e029c201", - "message": "The request was invalid because the job is in a terminal state" - }, - "workflowInvalidError": { - "code": "wfx.workflowInvalid", - "logref": "18f57adc70dd79c7fb4f1246be8a6e04", - "message": "Workflow validation failed" - }, - "workflowNotFoundError": { - "code": "wfx.workflowNotFound", - "logref": "c452719774086b6e803bb8f6ecea9899", - "message": "Workflow not found for given name" - }, - "workflowNotUniqueError": { - "code": "wfx.workflowNotUnique", - "logref": "e1ee1f2aea859b9dd34579610e386da6", - "message": "Workflow with name already exists" - } - } - } -}`)) - FlatSwaggerJSON = json.RawMessage([]byte(`{ - "schemes": [ - "http" - ], - "swagger": "2.0", - "info": { - "title": "Workflow Executor", - "license": { - "name": "Apache 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0.html" - }, - "version": "1.0.0", - "x-visibility": "external" - }, - "basePath": "/api/wfx/v1", - "paths": { - "/jobs": { - "get": { - "description": "List of job descriptions\nBy default, this endpoint returns the list of jobs in a specific order and predetermined paging properties.\nThese defaults are:\n - Ascending sort on stime\n - 10 entries per page\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "southbound", - "northbound" - ], - "summary": "List of job descriptions", - "parameters": [ - { - "type": "integer", - "format": "int64", - "default": 0, - "description": "the number of items to skip before starting to return results", - "name": "offset", - "in": "query" - }, - { - "maxItems": 1024, - "type": "integer", - "format": "int32", - "default": 10, - "description": "the maximum number of items to return", - "name": "limit", - "in": "query" - }, - { - "enum": [ - "asc", - "desc" - ], - "type": "string", - "default": "asc", - "description": "the order of returned elements", - "name": "sort", - "in": "query" - }, - { - "type": "string", - "description": "Filter jobs based on the current state value", - "name": "state", - "in": "query" - }, - { - "type": "array", - "items": { - "type": "string" - }, - "description": "Filter jobs based on the group they are in", - "name": "group", - "in": "query" - }, - { - "type": "string", - "description": "Filter jobs belonging to a specific client with clientId", - "name": "clientId", - "in": "query" - }, - { - "type": "string", - "description": "Filter jobs matching by workflow", - "name": "workflow", - "in": "query" - }, - { - "type": "array", - "items": { - "type": "string" - }, - "description": "Filter jobs by tags", - "name": "tag", - "in": "query" - } - ], - "responses": { - "200": { - "description": "A paginated job list.", - "schema": { - "$ref": "#/definitions/PaginatedJobList" - } - }, - "400": { - "description": "If request is invalid", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "post": { - "description": "Add a new job\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound" - ], - "summary": "Add a new job", - "parameters": [ - { - "description": "Job which shall be created", - "name": "Job", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/JobRequest" - } - } - ], - "responses": { - "201": { - "description": "Job was created", - "schema": { - "$ref": "#/definitions/Job" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - }, - "/jobs/events": { - "get": { - "description": "Obtain instant notifications when there are job changes matching the criteria. This endpoint utilizes server-sent events (SSE), where responses are \"chunked\" with double newline breaks. For example, a single event might look like this:\n data: {\"clientId\":\"example_client\",\"state\":\"INSTALLING\"}\\n\\n\n", - "produces": [ - "application/json", - "text/event-stream" - ], - "tags": [ - "jobs", - "northbound", - "southbound" - ], - "summary": "Subscribe to job-related events such as status updates", - "parameters": [ - { - "type": "string", - "description": "The job's clientId must be one of these clientIds (comma-separated).", - "name": "clientIds", - "in": "query" - }, - { - "type": "string", - "description": "The job's id must be one of these ids (comma-separated).", - "name": "jobIds", - "in": "query" - }, - { - "type": "string", - "description": "The job's workflow must be equal to one of the provided workflow names (comma-separated).", - "name": "workflows", - "in": "query" - }, - { - "type": "string", - "description": "A (comma-separated) list of tags to include into each job event. This can be used to aggregrate events from multiple wfx instances.\n", - "name": "tags", - "in": "query" - } - ], - "responses": { - "200": { - "description": "A stream of server-sent events" - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.jobTerminalState", - "logref": "916f0a913a3e4a52a96bd271e029c201", - "message": "The request was invalid because the job is in a terminal state" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format" - } - } - } - }, - "/jobs/{id}": { - "get": { - "description": "Job description for a given ID\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "southbound", - "northbound" - ], - "summary": "Job description for a given ID", - "parameters": [ - { - "type": "string", - "description": "Job ID", - "name": "id", - "in": "path", - "required": true - }, - { - "type": "boolean", - "description": "Boolean flag to include the transition history of the job", - "name": "history", - "in": "query" - } - ], - "responses": { - "200": { - "description": "Job description for for a given ID", - "schema": { - "$ref": "#/definitions/Job" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while querying a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "delete": { - "description": "Delete an existing job\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound" - ], - "summary": "Delete an existing job", - "parameters": [ - { - "type": "string", - "description": "Job ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "204": { - "description": "The job has been deleted." - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while querying a non-existent workflow": { - "errors": [ - { - "code": "wfx.workflowNotFound", - "logref": "c452719774086b6e803bb8f6ecea9899", - "message": "Workflow not found for given name" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - }, - "/jobs/{id}/definition": { - "get": { - "description": "Retrieve the job definition", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound", - "southbound" - ], - "summary": "Get job definition", - "parameters": [ - { - "type": "string", - "description": "Job ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Job definition", - "schema": { - "type": "object", - "additionalProperties": { - "type": "object" - }, - "example": "{ \"userDefined\": {} }\n" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "put": { - "description": "Modify the job definition of an existing job\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "southbound", - "northbound" - ], - "summary": "Modify job definition", - "parameters": [ - { - "type": "string", - "description": "Job ID", - "name": "id", - "in": "path", - "required": true - }, - { - "description": "How to modify the job", - "name": "JobDefinition", - "in": "body", - "required": true, - "schema": { - "type": "object", - "additionalProperties": { - "type": "object" - }, - "example": "{ \"userDefined\": {} }\n" - } - } - ], - "responses": { - "200": { - "description": "Job modified successfully", - "schema": { - "type": "object", - "additionalProperties": { - "type": "object" - }, - "example": "{ \"userDefined\": {} }\n" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - }, - "/jobs/{id}/status": { - "get": { - "description": "Retrieve the job status", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound", - "southbound" - ], - "summary": "Get job status", - "parameters": [ - { - "type": "string", - "description": "Job ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Job status", - "schema": { - "$ref": "#/definitions/JobStatus" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "put": { - "description": "Modify status of an existing job\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "southbound", - "northbound" - ], - "summary": "Modify status of an existing job", - "parameters": [ - { - "type": "string", - "description": "Job ID", - "name": "id", - "in": "path", - "required": true - }, - { - "description": "This contains the new job status", - "name": "New job status", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/JobStatus" - } - } - ], - "responses": { - "200": { - "description": "Job modified successfully", - "schema": { - "$ref": "#/definitions/JobStatus" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - }, - "/jobs/{id}/tags": { - "get": { - "description": "Get the tags of a job", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound", - "southbound" - ], - "summary": "Get tags", - "parameters": [ - { - "type": "string", - "description": "Job ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Job tags", - "schema": { - "type": "array", - "items": { - "type": "string", - "example": "EUROPE_WEST" - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "post": { - "description": "Add a tag to an existing job\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound" - ], - "summary": "Add a tag", - "parameters": [ - { - "type": "string", - "description": "Job ID", - "name": "id", - "in": "path", - "required": true - }, - { - "description": "Tags to add", - "name": "Tags", - "in": "body", - "required": true, - "schema": { - "type": "array", - "maxItems": 16, - "minItems": 1, - "items": { - "type": "string" - } - } - } - ], - "responses": { - "200": { - "description": "Successfully added tag to job", - "schema": { - "type": "array", - "items": { - "type": "string", - "example": "EUROPE_WEST" - } - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "delete": { - "description": "Delete a tag from an existing job\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "jobs", - "northbound" - ], - "summary": "Delete a tag", - "parameters": [ - { - "type": "string", - "description": "Job ID", - "name": "id", - "in": "path", - "required": true - }, - { - "description": "Tags to add", - "name": "Tags", - "in": "body", - "required": true, - "schema": { - "type": "array", - "maxItems": 16, - "minItems": 1, - "items": { - "type": "string" - } - } - } - ], - "responses": { - "200": { - "description": "Successfully deleted tag", - "schema": { - "type": "array", - "items": { - "type": "string", - "example": "EUROPE_WEST" - } - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while updating a non-existent job": { - "errors": [ - { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - }, - "/workflows": { - "get": { - "description": "List of available workflows", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "workflows", - "northbound", - "southbound" - ], - "summary": "List of available workflows", - "parameters": [ - { - "maxItems": 1024, - "type": "integer", - "format": "int32", - "default": 10, - "description": "the maximum number of items to return", - "name": "limit", - "in": "query" - }, - { - "type": "integer", - "format": "int64", - "default": 0, - "description": "the number of items to skip before starting to return results", - "name": "offset", - "in": "query" - }, - { - "enum": [ - "asc", - "desc" - ], - "type": "string", - "default": "asc", - "description": "the order of returned elements", - "name": "sort", - "in": "query" - } - ], - "responses": { - "200": { - "description": "A list of workflows", - "schema": { - "$ref": "#/definitions/PaginatedWorkflowList" - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "post": { - "description": "Add a new workflow", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "workflows", - "northbound" - ], - "summary": "Add a new workflow", - "parameters": [ - { - "description": "Workflow object to be added", - "name": "Workflow", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/Workflow" - } - } - ], - "responses": { - "201": { - "description": "Workflow was created", - "schema": { - "$ref": "#/definitions/Workflow" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.workflowNotUnique", - "logref": "e1ee1f2aea859b9dd34579610e386da6", - "message": "Workflow with name already exists" - }, - { - "code": "wfx.workflowInvalid", - "logref": "18f57adc70dd79c7fb4f1246be8a6e04", - "message": "Workflow validation failed" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - }, - "/workflows/{name}": { - "get": { - "description": "Workflow description for a given name", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "workflows", - "northbound", - "southbound" - ], - "summary": "Workflow description for a given name", - "parameters": [ - { - "type": "string", - "description": "Unique name for the workflow", - "name": "name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Workflow description with the provided key", - "schema": { - "$ref": "#/definitions/Workflow" - } - }, - "400": { - "description": "If request is invalid", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation for invalid requests": { - "errors": [ - { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - } - ] - } - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while querying a non-existent workflow": { - "errors": [ - { - "code": "wfx.workflowNotFound", - "logref": "c452719774086b6e803bb8f6ecea9899", - "message": "Workflow not found for given name" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - }, - "delete": { - "description": "Delete an existing workflow\n", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "workflows", - "northbound" - ], - "summary": "Delete an existing workflow", - "parameters": [ - { - "type": "string", - "description": "Workflow name", - "name": "name", - "in": "path", - "required": true - } - ], - "responses": { - "204": { - "description": "The workflow has been deleted." - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/ErrorResponse" - }, - "examples": { - "Error responses occurring at this operation while querying a non-existent workflow": { - "errors": [ - { - "code": "wfx.workflowNotFound", - "logref": "c452719774086b6e803bb8f6ecea9899", - "message": "Workflow not found for given name" - } - ] - } - } - }, - "default": { - "description": "Other error with any status code and response body format." - } - } - } - } - }, - "definitions": { - "ActionEnum": { - "type": "string", - "enum": [ - "IMMEDIATE", - "WAIT" - ] - }, - "EligibleEnum": { - "type": "string", - "enum": [ - "CLIENT", - "WFX" - ], - "x-nullable": false - }, - "Error": { - "type": "object", - "properties": { - "code": { - "description": "Identifier code for the reason of the error", - "type": "string" - }, - "logref": { - "description": "Log correlation ID", - "type": "string" - }, - "message": { - "description": "Error message", - "type": "string" - } - } - }, - "ErrorResponse": { - "type": "object", - "properties": { - "errors": { - "type": "array", - "maxItems": 128, - "items": { - "$ref": "#/definitions/Error" - } - } - } - }, - "Group": { - "type": "object", - "required": [ - "name", - "states" - ], - "properties": { - "description": { - "type": "string", - "example": "Description of the group" - }, - "name": { - "type": "string", - "x-nullable": false, - "example": "OPEN" - }, - "states": { - "description": "A list of states belonging to this group", - "type": "array", - "maxItems": 4096, - "minItems": 1, - "items": { - "type": "string" - } - } - } - }, - "History": { - "type": "object", - "properties": { - "definition": { - "type": "object", - "additionalProperties": { - "type": "object" - }, - "example": "{ \"userDefined\": {} }\n" - }, - "mtime": { - "description": "Date and time (ISO8601) when the job was modified (set by wfx)", - "type": "string", - "format": "date-time", - "readOnly": true - }, - "status": { - "description": "A previous job status", - "$ref": "#/definitions/JobStatus" - } - } - }, - "Job": { - "type": "object", - "properties": { - "clientId": { - "type": "string", - "x-nullable": false, - "example": "client42" - }, - "definition": { - "type": "object", - "additionalProperties": { - "type": "object" - }, - "example": "{ \"userDefined\": {} }\n" - }, - "history": { - "description": "The job's history. Last in, first out (LIFO). Array is truncated if its length exceeds the maximum allowed length.\nBy default, the job history is omitted from responses unless explicitly requested by the client (see the ` + "`" + `history` + "`" + ` URL parameter).\n", - "type": "array", - "maxItems": 8192, - "items": { - "$ref": "#/definitions/History" - }, - "x-omitempty": true - }, - "id": { - "description": "Unique job ID (wfx-generated)", - "type": "string", - "maxLength": 36, - "x-nullable": false, - "readOnly": true, - "example": "3307e5cb-074c-49b7-99d4-5e61839a4c2d" - }, - "mtime": { - "description": "Date and time (ISO8601) when the job was last modified (set by wfx)", - "type": "string", - "format": "date-time", - "x-nullable": true, - "readOnly": true - }, - "status": { - "$ref": "#/definitions/JobStatus" - }, - "stime": { - "description": "Date and time (ISO8601) when the job was created (set by wfx). Although stime conceptually always exists, it's nullable because we don't want to serialize stime in some cases (e.g. for job events).", - "type": "string", - "format": "date-time", - "x-nullable": true, - "readOnly": true - }, - "tags": { - "type": "array", - "items": { - "type": "string" - }, - "x-omitempty": true - }, - "workflow": { - "$ref": "#/definitions/Workflow" - } - } - }, - "JobRequest": { - "type": "object", - "required": [ - "clientId", - "workflow" - ], - "properties": { - "clientId": { - "description": "Create job for the given client ID", - "type": "string", - "x-nullable": false, - "example": "client42" - }, - "definition": { - "description": "The existing job definition will be replaced with this if this property is not empty.", - "type": "object", - "additionalProperties": { - "type": "object" - }, - "example": "{ \"userDefined\": {} }\n" - }, - "tags": { - "type": "array", - "maxItems": 16, - "items": { - "type": "string", - "example": "EUROPE_WEST" - } - }, - "workflow": { - "description": "Workflow name", - "type": "string", - "x-nullable": false, - "example": "wfx.workflow.dau.direct" - } - } - }, - "JobStatus": { - "description": "Job status information", - "type": "object", - "required": [ - "state" - ], - "properties": { - "clientId": { - "description": "Client which sent the status update", - "type": "string", - "x-nullable": false, - "example": "client42" - }, - "context": { - "description": "Client-specific JSON object to report additional context information such as error details, stack traces, etc", - "type": "object", - "maxLength": 20000, - "minLength": 0, - "additionalProperties": { - "type": "object" - }, - "example": "{\n \"lines\": [ \"line1\", \"line2\" ]\n}\n" - }, - "definitionHash": { - "description": "Job definition hash", - "type": "string", - "maxLength": 64, - "readOnly": true - }, - "message": { - "description": "Reason message/info, free text from client", - "type": "string", - "maxLength": 1024 - }, - "progress": { - "description": "Current job progress percentage", - "type": "number", - "format": "int32", - "maximum": 100 - }, - "state": { - "description": "Name of the new workflow state", - "type": "string", - "x-nullable": false, - "example": "END" - } - } - }, - "PaginatedJobList": { - "description": "Paginated list of jobs", - "type": "object", - "properties": { - "content": { - "type": "array", - "items": { - "$ref": "#/definitions/Job" - } - }, - "pagination": { - "type": "object", - "properties": { - "limit": { - "description": "the maximum number of items to return", - "type": "integer", - "format": "int32", - "example": 20 - }, - "offset": { - "description": "the number of items to skip before starting to return results", - "type": "integer", - "format": "int64", - "example": 0 - }, - "total": { - "description": "the total number of items", - "type": "integer", - "format": "int64", - "example": 1000 - } - } - } - } - }, - "PaginatedJobListPagination": { - "type": "object", - "properties": { - "limit": { - "description": "the maximum number of items to return", - "type": "integer", - "format": "int32", - "example": 20 - }, - "offset": { - "description": "the number of items to skip before starting to return results", - "type": "integer", - "format": "int64", - "example": 0 - }, - "total": { - "description": "the total number of items", - "type": "integer", - "format": "int64", - "example": 1000 - } - } - }, - "PaginatedWorkflowList": { - "description": "Paginated list of workflows", - "type": "object", - "properties": { - "content": { - "type": "array", - "items": { - "$ref": "#/definitions/Workflow" - } - }, - "pagination": { - "type": "object", - "properties": { - "limit": { - "description": "the maximum number of items to return", - "type": "integer", - "format": "int32", - "example": 20 - }, - "offset": { - "description": "the number of items to skip before starting to return results", - "type": "integer", - "format": "int64", - "example": 0 - }, - "total": { - "description": "the total number of items", - "type": "integer", - "format": "int64", - "example": 1000 - } - } - } - } - }, - "PaginatedWorkflowListPagination": { - "type": "object", - "properties": { - "limit": { - "description": "the maximum number of items to return", - "type": "integer", - "format": "int32", - "example": 20 - }, - "offset": { - "description": "the number of items to skip before starting to return results", - "type": "integer", - "format": "int64", - "example": 0 - }, - "total": { - "description": "the total number of items", - "type": "integer", - "format": "int64", - "example": 1000 - } - } - }, - "State": { - "type": "object", - "required": [ - "name" - ], - "properties": { - "description": { - "type": "string", - "example": "Description of the state" - }, - "name": { - "type": "string", - "x-nullable": false, - "example": "START" - } - } - }, - "Transition": { - "type": "object", - "required": [ - "from", - "to", - "eligible" - ], - "properties": { - "action": { - "description": "The transition execution action (default: WAIT)", - "$ref": "#/definitions/ActionEnum", - "example": "WAIT" - }, - "description": { - "type": "string", - "example": "Description of the transition" - }, - "eligible": { - "description": "The entity that may execute the transition", - "$ref": "#/definitions/EligibleEnum", - "example": "CLIENT" - }, - "from": { - "type": "string", - "x-nullable": false, - "example": "START" - }, - "to": { - "type": "string", - "x-nullable": false, - "example": "END" - } - } - }, - "Workflow": { - "type": "object", - "required": [ - "name" - ], - "properties": { - "description": { - "description": "Description of the workflow", - "type": "string", - "maxLength": 1024, - "example": "This is a workflow" - }, - "groups": { - "type": "array", - "maxItems": 1024, - "items": { - "$ref": "#/definitions/Group" - }, - "x-omitempty": true - }, - "name": { - "description": "User provided unique workflow name", - "type": "string", - "maxLength": 64, - "minLength": 1, - "pattern": "^[a-zA-Z0-9\\-\\.]+$", - "x-nullable": false, - "example": "wfx.workflow.dau.direct" - }, - "states": { - "type": "array", - "maxItems": 4096, - "items": { - "$ref": "#/definitions/State" - }, - "x-omitempty": true - }, - "transitions": { - "type": "array", - "maxItems": 16384, - "items": { - "$ref": "#/definitions/Transition" - }, - "x-omitempty": true - } - } - } - }, - "parameters": { - "clientId": { - "type": "string", - "description": "Filter jobs belonging to a specific client with clientId", - "name": "clientId", - "in": "query" - }, - "group": { - "type": "array", - "items": { - "type": "string" - }, - "description": "Filter jobs based on the group they are in", - "name": "group", - "in": "query" - }, - "history": { - "type": "boolean", - "description": "Boolean flag to include the transition history of the job", - "name": "history", - "in": "query" - }, - "jobId": { - "type": "string", - "description": "Job ID", - "name": "id", - "in": "path", - "required": true - }, - "limit": { - "maxItems": 1024, - "type": "integer", - "format": "int32", - "default": 10, - "description": "the maximum number of items to return", - "name": "limit", - "in": "query" - }, - "offset": { - "type": "integer", - "format": "int64", - "default": 0, - "description": "the number of items to skip before starting to return results", - "name": "offset", - "in": "query" - }, - "sort": { - "enum": [ - "asc", - "desc" - ], - "type": "string", - "default": "asc", - "description": "the order of returned elements", - "name": "sort", - "in": "query" - }, - "state": { - "type": "string", - "description": "Filter jobs based on the current state value", - "name": "state", - "in": "query" - }, - "tag": { - "type": "array", - "items": { - "type": "string" - }, - "description": "Filter jobs by tags", - "name": "tag", - "in": "query" - }, - "workflow": { - "type": "string", - "description": "Filter jobs matching by workflow", - "name": "workflow", - "in": "query" - } - }, - "tags": [ - { - "description": "Workflows used to instantiate jobs", - "name": "workflows" - }, - { - "description": "Jobs derived from workflows and executed by a client", - "name": "jobs" - }, - { - "description": "All southbound API endpoints", - "name": "southbound" - }, - { - "description": "All northbound API endpoints", - "name": "northbound" - } - ], - "x-definitions-templates": { - "Limits": { - "maxErrorCount": { - "maxItems": 128 - }, - "maxGroupCount": { - "maxItems": 1024 - }, - "maxHistoryCount": { - "maxItems": 8192 - }, - "maxItemsCount": { - "maxItems": 1024 - }, - "maxStateCount": { - "maxItems": 4096 - }, - "maxTagsCount": { - "maxItems": 16 - }, - "maxTransitionCount": { - "maxItems": 16384 - } - }, - "Pagination": { - "pagination": { - "properties": { - "limit": { - "description": "the maximum number of items to return", - "example": 20, - "format": "int32", - "type": "integer" - }, - "offset": { - "description": "the number of items to skip before starting to return results", - "example": 0, - "format": "int64", - "type": "integer" - }, - "total": { - "description": "the total number of items", - "example": 1000, - "format": "int64", - "type": "integer" - } - }, - "type": "object" - } - } - }, - "x-paths-templates": { - "Errors": { - "invalidRequestError": { - "code": "wfx.invalidRequest", - "logref": "96a37ea1f7d205ffbfa12334c6812727", - "message": "The request was invalid and could not be completed by the storage" - }, - "jobNotFoundError": { - "code": "wfx.jobNotFound", - "logref": "11cc67762090e15b79a1387eca65ba65", - "message": "Job ID was not found" - }, - "jobTerminalStateError": { - "code": "wfx.jobTerminalState", - "logref": "916f0a913a3e4a52a96bd271e029c201", - "message": "The request was invalid because the job is in a terminal state" - }, - "workflowInvalidError": { - "code": "wfx.workflowInvalid", - "logref": "18f57adc70dd79c7fb4f1246be8a6e04", - "message": "Workflow validation failed" - }, - "workflowNotFoundError": { - "code": "wfx.workflowNotFound", - "logref": "c452719774086b6e803bb8f6ecea9899", - "message": "Workflow not found for given name" - }, - "workflowNotUniqueError": { - "code": "wfx.workflowNotUnique", - "logref": "e1ee1f2aea859b9dd34579610e386da6", - "message": "Workflow with name already exists" - } - } - } -}`)) -} diff --git a/generated/southbound/restapi/operations/southbound/get_jobs.go b/generated/southbound/restapi/operations/southbound/get_jobs.go deleted file mode 100644 index b10b790f..00000000 --- a/generated/southbound/restapi/operations/southbound/get_jobs.go +++ /dev/null @@ -1,67 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// GetJobsHandlerFunc turns a function with the right signature into a get jobs handler -type GetJobsHandlerFunc func(GetJobsParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn GetJobsHandlerFunc) Handle(params GetJobsParams) middleware.Responder { - return fn(params) -} - -// GetJobsHandler interface for that can handle valid get jobs params -type GetJobsHandler interface { - Handle(GetJobsParams) middleware.Responder -} - -// NewGetJobs creates a new http.Handler for the get jobs operation -func NewGetJobs(ctx *middleware.Context, handler GetJobsHandler) *GetJobs { - return &GetJobs{Context: ctx, Handler: handler} -} - -/* - GetJobs swagger:route GET /jobs southbound getJobs - -# List of job descriptions - -List of job descriptions -By default, this endpoint returns the list of jobs in a specific order and predetermined paging properties. -These defaults are: - - Ascending sort on stime - - 10 entries per page -*/ -type GetJobs struct { - Context *middleware.Context - Handler GetJobsHandler -} - -func (o *GetJobs) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewGetJobsParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/southbound/restapi/operations/southbound/get_jobs_events.go b/generated/southbound/restapi/operations/southbound/get_jobs_events.go deleted file mode 100644 index 4fc069e3..00000000 --- a/generated/southbound/restapi/operations/southbound/get_jobs_events.go +++ /dev/null @@ -1,65 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// GetJobsEventsHandlerFunc turns a function with the right signature into a get jobs events handler -type GetJobsEventsHandlerFunc func(GetJobsEventsParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn GetJobsEventsHandlerFunc) Handle(params GetJobsEventsParams) middleware.Responder { - return fn(params) -} - -// GetJobsEventsHandler interface for that can handle valid get jobs events params -type GetJobsEventsHandler interface { - Handle(GetJobsEventsParams) middleware.Responder -} - -// NewGetJobsEvents creates a new http.Handler for the get jobs events operation -func NewGetJobsEvents(ctx *middleware.Context, handler GetJobsEventsHandler) *GetJobsEvents { - return &GetJobsEvents{Context: ctx, Handler: handler} -} - -/* - GetJobsEvents swagger:route GET /jobs/events southbound getJobsEvents - -# Subscribe to job-related events such as status updates - -Obtain instant notifications when there are job changes matching the criteria. This endpoint utilizes server-sent events (SSE), where responses are "chunked" with double newline breaks. For example, a single event might look like this: - - data: {"clientId":"example_client","state":"INSTALLING"}\n\n -*/ -type GetJobsEvents struct { - Context *middleware.Context - Handler GetJobsEventsHandler -} - -func (o *GetJobsEvents) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewGetJobsEventsParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/southbound/restapi/operations/southbound/get_jobs_events_parameters.go b/generated/southbound/restapi/operations/southbound/get_jobs_events_parameters.go deleted file mode 100644 index dbefd672..00000000 --- a/generated/southbound/restapi/operations/southbound/get_jobs_events_parameters.go +++ /dev/null @@ -1,164 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" -) - -// NewGetJobsEventsParams creates a new GetJobsEventsParams object -// -// There are no default values defined in the spec. -func NewGetJobsEventsParams() GetJobsEventsParams { - - return GetJobsEventsParams{} -} - -// GetJobsEventsParams contains all the bound params for the get jobs events operation -// typically these are obtained from a http.Request -// -// swagger:parameters GetJobsEvents -type GetJobsEventsParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*The job's clientId must be one of these clientIds (comma-separated). - In: query - */ - ClientIds *string - /*The job's id must be one of these ids (comma-separated). - In: query - */ - JobIds *string - /*A (comma-separated) list of tags to include into each job event. This can be used to aggregrate events from multiple wfx instances. - - In: query - */ - Tags *string - /*The job's workflow must be equal to one of the provided workflow names (comma-separated). - In: query - */ - Workflows *string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewGetJobsEventsParams() beforehand. -func (o *GetJobsEventsParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - qs := runtime.Values(r.URL.Query()) - - qClientIds, qhkClientIds, _ := qs.GetOK("clientIds") - if err := o.bindClientIds(qClientIds, qhkClientIds, route.Formats); err != nil { - res = append(res, err) - } - - qJobIds, qhkJobIds, _ := qs.GetOK("jobIds") - if err := o.bindJobIds(qJobIds, qhkJobIds, route.Formats); err != nil { - res = append(res, err) - } - - qTags, qhkTags, _ := qs.GetOK("tags") - if err := o.bindTags(qTags, qhkTags, route.Formats); err != nil { - res = append(res, err) - } - - qWorkflows, qhkWorkflows, _ := qs.GetOK("workflows") - if err := o.bindWorkflows(qWorkflows, qhkWorkflows, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindClientIds binds and validates parameter ClientIds from query. -func (o *GetJobsEventsParams) bindClientIds(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - return nil - } - o.ClientIds = &raw - - return nil -} - -// bindJobIds binds and validates parameter JobIds from query. -func (o *GetJobsEventsParams) bindJobIds(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - return nil - } - o.JobIds = &raw - - return nil -} - -// bindTags binds and validates parameter Tags from query. -func (o *GetJobsEventsParams) bindTags(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - return nil - } - o.Tags = &raw - - return nil -} - -// bindWorkflows binds and validates parameter Workflows from query. -func (o *GetJobsEventsParams) bindWorkflows(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - return nil - } - o.Workflows = &raw - - return nil -} diff --git a/generated/southbound/restapi/operations/southbound/get_jobs_events_responses.go b/generated/southbound/restapi/operations/southbound/get_jobs_events_responses.go deleted file mode 100644 index e2916bd0..00000000 --- a/generated/southbound/restapi/operations/southbound/get_jobs_events_responses.go +++ /dev/null @@ -1,172 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// GetJobsEventsOKCode is the HTTP code returned for type GetJobsEventsOK -const GetJobsEventsOKCode int = 200 - -/* -GetJobsEventsOK A stream of server-sent events - -swagger:response getJobsEventsOK -*/ -type GetJobsEventsOK struct { -} - -// NewGetJobsEventsOK creates GetJobsEventsOK with default headers values -func NewGetJobsEventsOK() *GetJobsEventsOK { - - return &GetJobsEventsOK{} -} - -// WriteResponse to the client -func (o *GetJobsEventsOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(200) -} - -// GetJobsEventsBadRequestCode is the HTTP code returned for type GetJobsEventsBadRequest -const GetJobsEventsBadRequestCode int = 400 - -/* -GetJobsEventsBadRequest Bad Request - -swagger:response getJobsEventsBadRequest -*/ -type GetJobsEventsBadRequest struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewGetJobsEventsBadRequest creates GetJobsEventsBadRequest with default headers values -func NewGetJobsEventsBadRequest() *GetJobsEventsBadRequest { - - return &GetJobsEventsBadRequest{} -} - -// WithPayload adds the payload to the get jobs events bad request response -func (o *GetJobsEventsBadRequest) WithPayload(payload *model.ErrorResponse) *GetJobsEventsBadRequest { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs events bad request response -func (o *GetJobsEventsBadRequest) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsEventsBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(400) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// GetJobsEventsNotFoundCode is the HTTP code returned for type GetJobsEventsNotFound -const GetJobsEventsNotFoundCode int = 404 - -/* -GetJobsEventsNotFound Not Found - -swagger:response getJobsEventsNotFound -*/ -type GetJobsEventsNotFound struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewGetJobsEventsNotFound creates GetJobsEventsNotFound with default headers values -func NewGetJobsEventsNotFound() *GetJobsEventsNotFound { - - return &GetJobsEventsNotFound{} -} - -// WithPayload adds the payload to the get jobs events not found response -func (o *GetJobsEventsNotFound) WithPayload(payload *model.ErrorResponse) *GetJobsEventsNotFound { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs events not found response -func (o *GetJobsEventsNotFound) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsEventsNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(404) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -GetJobsEventsDefault Other error with any status code and response body format - -swagger:response getJobsEventsDefault -*/ -type GetJobsEventsDefault struct { - _statusCode int -} - -// NewGetJobsEventsDefault creates GetJobsEventsDefault with default headers values -func NewGetJobsEventsDefault(code int) *GetJobsEventsDefault { - if code <= 0 { - code = 500 - } - - return &GetJobsEventsDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the get jobs events default response -func (o *GetJobsEventsDefault) WithStatusCode(code int) *GetJobsEventsDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the get jobs events default response -func (o *GetJobsEventsDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *GetJobsEventsDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/southbound/restapi/operations/southbound/get_jobs_events_urlbuilder.go b/generated/southbound/restapi/operations/southbound/get_jobs_events_urlbuilder.go deleted file mode 100644 index 902f0d96..00000000 --- a/generated/southbound/restapi/operations/southbound/get_jobs_events_urlbuilder.go +++ /dev/null @@ -1,135 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" -) - -// GetJobsEventsURL generates an URL for the get jobs events operation -type GetJobsEventsURL struct { - ClientIds *string - JobIds *string - Tags *string - Workflows *string - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetJobsEventsURL) WithBasePath(bp string) *GetJobsEventsURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetJobsEventsURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *GetJobsEventsURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/jobs/events" - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - qs := make(url.Values) - - var clientIdsQ string - if o.ClientIds != nil { - clientIdsQ = *o.ClientIds - } - if clientIdsQ != "" { - qs.Set("clientIds", clientIdsQ) - } - - var jobIdsQ string - if o.JobIds != nil { - jobIdsQ = *o.JobIds - } - if jobIdsQ != "" { - qs.Set("jobIds", jobIdsQ) - } - - var tagsQ string - if o.Tags != nil { - tagsQ = *o.Tags - } - if tagsQ != "" { - qs.Set("tags", tagsQ) - } - - var workflowsQ string - if o.Workflows != nil { - workflowsQ = *o.Workflows - } - if workflowsQ != "" { - qs.Set("workflows", workflowsQ) - } - - _result.RawQuery = qs.Encode() - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *GetJobsEventsURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *GetJobsEventsURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *GetJobsEventsURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on GetJobsEventsURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on GetJobsEventsURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *GetJobsEventsURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/southbound/restapi/operations/southbound/get_jobs_id.go b/generated/southbound/restapi/operations/southbound/get_jobs_id.go deleted file mode 100644 index eab25424..00000000 --- a/generated/southbound/restapi/operations/southbound/get_jobs_id.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// GetJobsIDHandlerFunc turns a function with the right signature into a get jobs ID handler -type GetJobsIDHandlerFunc func(GetJobsIDParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn GetJobsIDHandlerFunc) Handle(params GetJobsIDParams) middleware.Responder { - return fn(params) -} - -// GetJobsIDHandler interface for that can handle valid get jobs ID params -type GetJobsIDHandler interface { - Handle(GetJobsIDParams) middleware.Responder -} - -// NewGetJobsID creates a new http.Handler for the get jobs ID operation -func NewGetJobsID(ctx *middleware.Context, handler GetJobsIDHandler) *GetJobsID { - return &GetJobsID{Context: ctx, Handler: handler} -} - -/* - GetJobsID swagger:route GET /jobs/{id} southbound getJobsId - -# Job description for a given ID - -Job description for a given ID -*/ -type GetJobsID struct { - Context *middleware.Context - Handler GetJobsIDHandler -} - -func (o *GetJobsID) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewGetJobsIDParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/southbound/restapi/operations/southbound/get_jobs_id_definition.go b/generated/southbound/restapi/operations/southbound/get_jobs_id_definition.go deleted file mode 100644 index ab3b7bf4..00000000 --- a/generated/southbound/restapi/operations/southbound/get_jobs_id_definition.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// GetJobsIDDefinitionHandlerFunc turns a function with the right signature into a get jobs ID definition handler -type GetJobsIDDefinitionHandlerFunc func(GetJobsIDDefinitionParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn GetJobsIDDefinitionHandlerFunc) Handle(params GetJobsIDDefinitionParams) middleware.Responder { - return fn(params) -} - -// GetJobsIDDefinitionHandler interface for that can handle valid get jobs ID definition params -type GetJobsIDDefinitionHandler interface { - Handle(GetJobsIDDefinitionParams) middleware.Responder -} - -// NewGetJobsIDDefinition creates a new http.Handler for the get jobs ID definition operation -func NewGetJobsIDDefinition(ctx *middleware.Context, handler GetJobsIDDefinitionHandler) *GetJobsIDDefinition { - return &GetJobsIDDefinition{Context: ctx, Handler: handler} -} - -/* - GetJobsIDDefinition swagger:route GET /jobs/{id}/definition southbound getJobsIdDefinition - -# Get job definition - -Retrieve the job definition -*/ -type GetJobsIDDefinition struct { - Context *middleware.Context - Handler GetJobsIDDefinitionHandler -} - -func (o *GetJobsIDDefinition) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewGetJobsIDDefinitionParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/southbound/restapi/operations/southbound/get_jobs_id_definition_parameters.go b/generated/southbound/restapi/operations/southbound/get_jobs_id_definition_parameters.go deleted file mode 100644 index 08650974..00000000 --- a/generated/southbound/restapi/operations/southbound/get_jobs_id_definition_parameters.go +++ /dev/null @@ -1,76 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" -) - -// NewGetJobsIDDefinitionParams creates a new GetJobsIDDefinitionParams object -// -// There are no default values defined in the spec. -func NewGetJobsIDDefinitionParams() GetJobsIDDefinitionParams { - - return GetJobsIDDefinitionParams{} -} - -// GetJobsIDDefinitionParams contains all the bound params for the get jobs ID definition operation -// typically these are obtained from a http.Request -// -// swagger:parameters GetJobsIDDefinition -type GetJobsIDDefinitionParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*Job ID - Required: true - In: path - */ - ID string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewGetJobsIDDefinitionParams() beforehand. -func (o *GetJobsIDDefinitionParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - rID, rhkID, _ := route.Params.GetOK("id") - if err := o.bindID(rID, rhkID, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindID binds and validates parameter ID from path. -func (o *GetJobsIDDefinitionParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: true - // Parameter is provided by construction from the route - o.ID = raw - - return nil -} diff --git a/generated/southbound/restapi/operations/southbound/get_jobs_id_definition_responses.go b/generated/southbound/restapi/operations/southbound/get_jobs_id_definition_responses.go deleted file mode 100644 index 43f04651..00000000 --- a/generated/southbound/restapi/operations/southbound/get_jobs_id_definition_responses.go +++ /dev/null @@ -1,150 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// GetJobsIDDefinitionOKCode is the HTTP code returned for type GetJobsIDDefinitionOK -const GetJobsIDDefinitionOKCode int = 200 - -/* -GetJobsIDDefinitionOK Job definition - -swagger:response getJobsIdDefinitionOK -*/ -type GetJobsIDDefinitionOK struct { - - /* - In: Body - */ - Payload map[string]interface{} `json:"body,omitempty"` -} - -// NewGetJobsIDDefinitionOK creates GetJobsIDDefinitionOK with default headers values -func NewGetJobsIDDefinitionOK() *GetJobsIDDefinitionOK { - - return &GetJobsIDDefinitionOK{} -} - -// WithPayload adds the payload to the get jobs Id definition o k response -func (o *GetJobsIDDefinitionOK) WithPayload(payload map[string]interface{}) *GetJobsIDDefinitionOK { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs Id definition o k response -func (o *GetJobsIDDefinitionOK) SetPayload(payload map[string]interface{}) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsIDDefinitionOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(200) - payload := o.Payload - if payload == nil { - // return empty map - payload = make(map[string]interface{}, 50) - } - - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } -} - -// GetJobsIDDefinitionNotFoundCode is the HTTP code returned for type GetJobsIDDefinitionNotFound -const GetJobsIDDefinitionNotFoundCode int = 404 - -/* -GetJobsIDDefinitionNotFound Not Found - -swagger:response getJobsIdDefinitionNotFound -*/ -type GetJobsIDDefinitionNotFound struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewGetJobsIDDefinitionNotFound creates GetJobsIDDefinitionNotFound with default headers values -func NewGetJobsIDDefinitionNotFound() *GetJobsIDDefinitionNotFound { - - return &GetJobsIDDefinitionNotFound{} -} - -// WithPayload adds the payload to the get jobs Id definition not found response -func (o *GetJobsIDDefinitionNotFound) WithPayload(payload *model.ErrorResponse) *GetJobsIDDefinitionNotFound { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs Id definition not found response -func (o *GetJobsIDDefinitionNotFound) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsIDDefinitionNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(404) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -GetJobsIDDefinitionDefault Other error with any status code and response body format. - -swagger:response getJobsIdDefinitionDefault -*/ -type GetJobsIDDefinitionDefault struct { - _statusCode int -} - -// NewGetJobsIDDefinitionDefault creates GetJobsIDDefinitionDefault with default headers values -func NewGetJobsIDDefinitionDefault(code int) *GetJobsIDDefinitionDefault { - if code <= 0 { - code = 500 - } - - return &GetJobsIDDefinitionDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the get jobs ID definition default response -func (o *GetJobsIDDefinitionDefault) WithStatusCode(code int) *GetJobsIDDefinitionDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the get jobs ID definition default response -func (o *GetJobsIDDefinitionDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *GetJobsIDDefinitionDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/southbound/restapi/operations/southbound/get_jobs_id_definition_urlbuilder.go b/generated/southbound/restapi/operations/southbound/get_jobs_id_definition_urlbuilder.go deleted file mode 100644 index 6f379834..00000000 --- a/generated/southbound/restapi/operations/southbound/get_jobs_id_definition_urlbuilder.go +++ /dev/null @@ -1,104 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" - "strings" -) - -// GetJobsIDDefinitionURL generates an URL for the get jobs ID definition operation -type GetJobsIDDefinitionURL struct { - ID string - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetJobsIDDefinitionURL) WithBasePath(bp string) *GetJobsIDDefinitionURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetJobsIDDefinitionURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *GetJobsIDDefinitionURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/jobs/{id}/definition" - - id := o.ID - if id != "" { - _path = strings.Replace(_path, "{id}", id, -1) - } else { - return nil, errors.New("id is required on GetJobsIDDefinitionURL") - } - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *GetJobsIDDefinitionURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *GetJobsIDDefinitionURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *GetJobsIDDefinitionURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on GetJobsIDDefinitionURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on GetJobsIDDefinitionURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *GetJobsIDDefinitionURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/southbound/restapi/operations/southbound/get_jobs_id_parameters.go b/generated/southbound/restapi/operations/southbound/get_jobs_id_parameters.go deleted file mode 100644 index c321fdce..00000000 --- a/generated/southbound/restapi/operations/southbound/get_jobs_id_parameters.go +++ /dev/null @@ -1,112 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// NewGetJobsIDParams creates a new GetJobsIDParams object -// -// There are no default values defined in the spec. -func NewGetJobsIDParams() GetJobsIDParams { - - return GetJobsIDParams{} -} - -// GetJobsIDParams contains all the bound params for the get jobs ID operation -// typically these are obtained from a http.Request -// -// swagger:parameters GetJobsID -type GetJobsIDParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*Boolean flag to include the transition history of the job - In: query - */ - History *bool - /*Job ID - Required: true - In: path - */ - ID string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewGetJobsIDParams() beforehand. -func (o *GetJobsIDParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - qs := runtime.Values(r.URL.Query()) - - qHistory, qhkHistory, _ := qs.GetOK("history") - if err := o.bindHistory(qHistory, qhkHistory, route.Formats); err != nil { - res = append(res, err) - } - - rID, rhkID, _ := route.Params.GetOK("id") - if err := o.bindID(rID, rhkID, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindHistory binds and validates parameter History from query. -func (o *GetJobsIDParams) bindHistory(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - return nil - } - - value, err := swag.ConvertBool(raw) - if err != nil { - return errors.InvalidType("history", "query", "bool", raw) - } - o.History = &value - - return nil -} - -// bindID binds and validates parameter ID from path. -func (o *GetJobsIDParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: true - // Parameter is provided by construction from the route - o.ID = raw - - return nil -} diff --git a/generated/southbound/restapi/operations/southbound/get_jobs_id_responses.go b/generated/southbound/restapi/operations/southbound/get_jobs_id_responses.go deleted file mode 100644 index a13609cd..00000000 --- a/generated/southbound/restapi/operations/southbound/get_jobs_id_responses.go +++ /dev/null @@ -1,192 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// GetJobsIDOKCode is the HTTP code returned for type GetJobsIDOK -const GetJobsIDOKCode int = 200 - -/* -GetJobsIDOK Job description for for a given ID - -swagger:response getJobsIdOK -*/ -type GetJobsIDOK struct { - - /* - In: Body - */ - Payload *model.Job `json:"body,omitempty"` -} - -// NewGetJobsIDOK creates GetJobsIDOK with default headers values -func NewGetJobsIDOK() *GetJobsIDOK { - - return &GetJobsIDOK{} -} - -// WithPayload adds the payload to the get jobs Id o k response -func (o *GetJobsIDOK) WithPayload(payload *model.Job) *GetJobsIDOK { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs Id o k response -func (o *GetJobsIDOK) SetPayload(payload *model.Job) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsIDOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(200) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// GetJobsIDBadRequestCode is the HTTP code returned for type GetJobsIDBadRequest -const GetJobsIDBadRequestCode int = 400 - -/* -GetJobsIDBadRequest Bad Request - -swagger:response getJobsIdBadRequest -*/ -type GetJobsIDBadRequest struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewGetJobsIDBadRequest creates GetJobsIDBadRequest with default headers values -func NewGetJobsIDBadRequest() *GetJobsIDBadRequest { - - return &GetJobsIDBadRequest{} -} - -// WithPayload adds the payload to the get jobs Id bad request response -func (o *GetJobsIDBadRequest) WithPayload(payload *model.ErrorResponse) *GetJobsIDBadRequest { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs Id bad request response -func (o *GetJobsIDBadRequest) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsIDBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(400) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// GetJobsIDNotFoundCode is the HTTP code returned for type GetJobsIDNotFound -const GetJobsIDNotFoundCode int = 404 - -/* -GetJobsIDNotFound Not Found - -swagger:response getJobsIdNotFound -*/ -type GetJobsIDNotFound struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewGetJobsIDNotFound creates GetJobsIDNotFound with default headers values -func NewGetJobsIDNotFound() *GetJobsIDNotFound { - - return &GetJobsIDNotFound{} -} - -// WithPayload adds the payload to the get jobs Id not found response -func (o *GetJobsIDNotFound) WithPayload(payload *model.ErrorResponse) *GetJobsIDNotFound { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs Id not found response -func (o *GetJobsIDNotFound) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsIDNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(404) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -GetJobsIDDefault Other error with any status code and response body format. - -swagger:response getJobsIdDefault -*/ -type GetJobsIDDefault struct { - _statusCode int -} - -// NewGetJobsIDDefault creates GetJobsIDDefault with default headers values -func NewGetJobsIDDefault(code int) *GetJobsIDDefault { - if code <= 0 { - code = 500 - } - - return &GetJobsIDDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the get jobs ID default response -func (o *GetJobsIDDefault) WithStatusCode(code int) *GetJobsIDDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the get jobs ID default response -func (o *GetJobsIDDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *GetJobsIDDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/southbound/restapi/operations/southbound/get_jobs_id_status.go b/generated/southbound/restapi/operations/southbound/get_jobs_id_status.go deleted file mode 100644 index 71fef553..00000000 --- a/generated/southbound/restapi/operations/southbound/get_jobs_id_status.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// GetJobsIDStatusHandlerFunc turns a function with the right signature into a get jobs ID status handler -type GetJobsIDStatusHandlerFunc func(GetJobsIDStatusParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn GetJobsIDStatusHandlerFunc) Handle(params GetJobsIDStatusParams) middleware.Responder { - return fn(params) -} - -// GetJobsIDStatusHandler interface for that can handle valid get jobs ID status params -type GetJobsIDStatusHandler interface { - Handle(GetJobsIDStatusParams) middleware.Responder -} - -// NewGetJobsIDStatus creates a new http.Handler for the get jobs ID status operation -func NewGetJobsIDStatus(ctx *middleware.Context, handler GetJobsIDStatusHandler) *GetJobsIDStatus { - return &GetJobsIDStatus{Context: ctx, Handler: handler} -} - -/* - GetJobsIDStatus swagger:route GET /jobs/{id}/status southbound getJobsIdStatus - -# Get job status - -Retrieve the job status -*/ -type GetJobsIDStatus struct { - Context *middleware.Context - Handler GetJobsIDStatusHandler -} - -func (o *GetJobsIDStatus) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewGetJobsIDStatusParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/southbound/restapi/operations/southbound/get_jobs_id_status_parameters.go b/generated/southbound/restapi/operations/southbound/get_jobs_id_status_parameters.go deleted file mode 100644 index 2345b8c3..00000000 --- a/generated/southbound/restapi/operations/southbound/get_jobs_id_status_parameters.go +++ /dev/null @@ -1,76 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" -) - -// NewGetJobsIDStatusParams creates a new GetJobsIDStatusParams object -// -// There are no default values defined in the spec. -func NewGetJobsIDStatusParams() GetJobsIDStatusParams { - - return GetJobsIDStatusParams{} -} - -// GetJobsIDStatusParams contains all the bound params for the get jobs ID status operation -// typically these are obtained from a http.Request -// -// swagger:parameters GetJobsIDStatus -type GetJobsIDStatusParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*Job ID - Required: true - In: path - */ - ID string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewGetJobsIDStatusParams() beforehand. -func (o *GetJobsIDStatusParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - rID, rhkID, _ := route.Params.GetOK("id") - if err := o.bindID(rID, rhkID, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindID binds and validates parameter ID from path. -func (o *GetJobsIDStatusParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: true - // Parameter is provided by construction from the route - o.ID = raw - - return nil -} diff --git a/generated/southbound/restapi/operations/southbound/get_jobs_id_status_responses.go b/generated/southbound/restapi/operations/southbound/get_jobs_id_status_responses.go deleted file mode 100644 index f07dbb5c..00000000 --- a/generated/southbound/restapi/operations/southbound/get_jobs_id_status_responses.go +++ /dev/null @@ -1,147 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// GetJobsIDStatusOKCode is the HTTP code returned for type GetJobsIDStatusOK -const GetJobsIDStatusOKCode int = 200 - -/* -GetJobsIDStatusOK Job status - -swagger:response getJobsIdStatusOK -*/ -type GetJobsIDStatusOK struct { - - /* - In: Body - */ - Payload *model.JobStatus `json:"body,omitempty"` -} - -// NewGetJobsIDStatusOK creates GetJobsIDStatusOK with default headers values -func NewGetJobsIDStatusOK() *GetJobsIDStatusOK { - - return &GetJobsIDStatusOK{} -} - -// WithPayload adds the payload to the get jobs Id status o k response -func (o *GetJobsIDStatusOK) WithPayload(payload *model.JobStatus) *GetJobsIDStatusOK { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs Id status o k response -func (o *GetJobsIDStatusOK) SetPayload(payload *model.JobStatus) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsIDStatusOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(200) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// GetJobsIDStatusNotFoundCode is the HTTP code returned for type GetJobsIDStatusNotFound -const GetJobsIDStatusNotFoundCode int = 404 - -/* -GetJobsIDStatusNotFound Not Found - -swagger:response getJobsIdStatusNotFound -*/ -type GetJobsIDStatusNotFound struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewGetJobsIDStatusNotFound creates GetJobsIDStatusNotFound with default headers values -func NewGetJobsIDStatusNotFound() *GetJobsIDStatusNotFound { - - return &GetJobsIDStatusNotFound{} -} - -// WithPayload adds the payload to the get jobs Id status not found response -func (o *GetJobsIDStatusNotFound) WithPayload(payload *model.ErrorResponse) *GetJobsIDStatusNotFound { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs Id status not found response -func (o *GetJobsIDStatusNotFound) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsIDStatusNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(404) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -GetJobsIDStatusDefault Other error with any status code and response body format. - -swagger:response getJobsIdStatusDefault -*/ -type GetJobsIDStatusDefault struct { - _statusCode int -} - -// NewGetJobsIDStatusDefault creates GetJobsIDStatusDefault with default headers values -func NewGetJobsIDStatusDefault(code int) *GetJobsIDStatusDefault { - if code <= 0 { - code = 500 - } - - return &GetJobsIDStatusDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the get jobs ID status default response -func (o *GetJobsIDStatusDefault) WithStatusCode(code int) *GetJobsIDStatusDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the get jobs ID status default response -func (o *GetJobsIDStatusDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *GetJobsIDStatusDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/southbound/restapi/operations/southbound/get_jobs_id_status_urlbuilder.go b/generated/southbound/restapi/operations/southbound/get_jobs_id_status_urlbuilder.go deleted file mode 100644 index 7d2ac48d..00000000 --- a/generated/southbound/restapi/operations/southbound/get_jobs_id_status_urlbuilder.go +++ /dev/null @@ -1,104 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" - "strings" -) - -// GetJobsIDStatusURL generates an URL for the get jobs ID status operation -type GetJobsIDStatusURL struct { - ID string - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetJobsIDStatusURL) WithBasePath(bp string) *GetJobsIDStatusURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetJobsIDStatusURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *GetJobsIDStatusURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/jobs/{id}/status" - - id := o.ID - if id != "" { - _path = strings.Replace(_path, "{id}", id, -1) - } else { - return nil, errors.New("id is required on GetJobsIDStatusURL") - } - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *GetJobsIDStatusURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *GetJobsIDStatusURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *GetJobsIDStatusURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on GetJobsIDStatusURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on GetJobsIDStatusURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *GetJobsIDStatusURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/southbound/restapi/operations/southbound/get_jobs_id_tags.go b/generated/southbound/restapi/operations/southbound/get_jobs_id_tags.go deleted file mode 100644 index b49881bd..00000000 --- a/generated/southbound/restapi/operations/southbound/get_jobs_id_tags.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// GetJobsIDTagsHandlerFunc turns a function with the right signature into a get jobs ID tags handler -type GetJobsIDTagsHandlerFunc func(GetJobsIDTagsParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn GetJobsIDTagsHandlerFunc) Handle(params GetJobsIDTagsParams) middleware.Responder { - return fn(params) -} - -// GetJobsIDTagsHandler interface for that can handle valid get jobs ID tags params -type GetJobsIDTagsHandler interface { - Handle(GetJobsIDTagsParams) middleware.Responder -} - -// NewGetJobsIDTags creates a new http.Handler for the get jobs ID tags operation -func NewGetJobsIDTags(ctx *middleware.Context, handler GetJobsIDTagsHandler) *GetJobsIDTags { - return &GetJobsIDTags{Context: ctx, Handler: handler} -} - -/* - GetJobsIDTags swagger:route GET /jobs/{id}/tags southbound getJobsIdTags - -# Get tags - -Get the tags of a job -*/ -type GetJobsIDTags struct { - Context *middleware.Context - Handler GetJobsIDTagsHandler -} - -func (o *GetJobsIDTags) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewGetJobsIDTagsParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/southbound/restapi/operations/southbound/get_jobs_id_tags_parameters.go b/generated/southbound/restapi/operations/southbound/get_jobs_id_tags_parameters.go deleted file mode 100644 index 571ca388..00000000 --- a/generated/southbound/restapi/operations/southbound/get_jobs_id_tags_parameters.go +++ /dev/null @@ -1,76 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" -) - -// NewGetJobsIDTagsParams creates a new GetJobsIDTagsParams object -// -// There are no default values defined in the spec. -func NewGetJobsIDTagsParams() GetJobsIDTagsParams { - - return GetJobsIDTagsParams{} -} - -// GetJobsIDTagsParams contains all the bound params for the get jobs ID tags operation -// typically these are obtained from a http.Request -// -// swagger:parameters GetJobsIDTags -type GetJobsIDTagsParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*Job ID - Required: true - In: path - */ - ID string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewGetJobsIDTagsParams() beforehand. -func (o *GetJobsIDTagsParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - rID, rhkID, _ := route.Params.GetOK("id") - if err := o.bindID(rID, rhkID, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindID binds and validates parameter ID from path. -func (o *GetJobsIDTagsParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: true - // Parameter is provided by construction from the route - o.ID = raw - - return nil -} diff --git a/generated/southbound/restapi/operations/southbound/get_jobs_id_tags_responses.go b/generated/southbound/restapi/operations/southbound/get_jobs_id_tags_responses.go deleted file mode 100644 index e80f7573..00000000 --- a/generated/southbound/restapi/operations/southbound/get_jobs_id_tags_responses.go +++ /dev/null @@ -1,150 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// GetJobsIDTagsOKCode is the HTTP code returned for type GetJobsIDTagsOK -const GetJobsIDTagsOKCode int = 200 - -/* -GetJobsIDTagsOK Job tags - -swagger:response getJobsIdTagsOK -*/ -type GetJobsIDTagsOK struct { - - /* - In: Body - */ - Payload []string `json:"body,omitempty"` -} - -// NewGetJobsIDTagsOK creates GetJobsIDTagsOK with default headers values -func NewGetJobsIDTagsOK() *GetJobsIDTagsOK { - - return &GetJobsIDTagsOK{} -} - -// WithPayload adds the payload to the get jobs Id tags o k response -func (o *GetJobsIDTagsOK) WithPayload(payload []string) *GetJobsIDTagsOK { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs Id tags o k response -func (o *GetJobsIDTagsOK) SetPayload(payload []string) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsIDTagsOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(200) - payload := o.Payload - if payload == nil { - // return empty array - payload = make([]string, 0, 50) - } - - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } -} - -// GetJobsIDTagsNotFoundCode is the HTTP code returned for type GetJobsIDTagsNotFound -const GetJobsIDTagsNotFoundCode int = 404 - -/* -GetJobsIDTagsNotFound Not Found - -swagger:response getJobsIdTagsNotFound -*/ -type GetJobsIDTagsNotFound struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewGetJobsIDTagsNotFound creates GetJobsIDTagsNotFound with default headers values -func NewGetJobsIDTagsNotFound() *GetJobsIDTagsNotFound { - - return &GetJobsIDTagsNotFound{} -} - -// WithPayload adds the payload to the get jobs Id tags not found response -func (o *GetJobsIDTagsNotFound) WithPayload(payload *model.ErrorResponse) *GetJobsIDTagsNotFound { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs Id tags not found response -func (o *GetJobsIDTagsNotFound) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsIDTagsNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(404) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -GetJobsIDTagsDefault Other error with any status code and response body format. - -swagger:response getJobsIdTagsDefault -*/ -type GetJobsIDTagsDefault struct { - _statusCode int -} - -// NewGetJobsIDTagsDefault creates GetJobsIDTagsDefault with default headers values -func NewGetJobsIDTagsDefault(code int) *GetJobsIDTagsDefault { - if code <= 0 { - code = 500 - } - - return &GetJobsIDTagsDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the get jobs ID tags default response -func (o *GetJobsIDTagsDefault) WithStatusCode(code int) *GetJobsIDTagsDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the get jobs ID tags default response -func (o *GetJobsIDTagsDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *GetJobsIDTagsDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/southbound/restapi/operations/southbound/get_jobs_id_tags_urlbuilder.go b/generated/southbound/restapi/operations/southbound/get_jobs_id_tags_urlbuilder.go deleted file mode 100644 index 65bfced1..00000000 --- a/generated/southbound/restapi/operations/southbound/get_jobs_id_tags_urlbuilder.go +++ /dev/null @@ -1,104 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" - "strings" -) - -// GetJobsIDTagsURL generates an URL for the get jobs ID tags operation -type GetJobsIDTagsURL struct { - ID string - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetJobsIDTagsURL) WithBasePath(bp string) *GetJobsIDTagsURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetJobsIDTagsURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *GetJobsIDTagsURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/jobs/{id}/tags" - - id := o.ID - if id != "" { - _path = strings.Replace(_path, "{id}", id, -1) - } else { - return nil, errors.New("id is required on GetJobsIDTagsURL") - } - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *GetJobsIDTagsURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *GetJobsIDTagsURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *GetJobsIDTagsURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on GetJobsIDTagsURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on GetJobsIDTagsURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *GetJobsIDTagsURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/southbound/restapi/operations/southbound/get_jobs_id_urlbuilder.go b/generated/southbound/restapi/operations/southbound/get_jobs_id_urlbuilder.go deleted file mode 100644 index 8dd96369..00000000 --- a/generated/southbound/restapi/operations/southbound/get_jobs_id_urlbuilder.go +++ /dev/null @@ -1,120 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" - "strings" - - "github.com/go-openapi/swag" -) - -// GetJobsIDURL generates an URL for the get jobs ID operation -type GetJobsIDURL struct { - ID string - - History *bool - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetJobsIDURL) WithBasePath(bp string) *GetJobsIDURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetJobsIDURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *GetJobsIDURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/jobs/{id}" - - id := o.ID - if id != "" { - _path = strings.Replace(_path, "{id}", id, -1) - } else { - return nil, errors.New("id is required on GetJobsIDURL") - } - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - qs := make(url.Values) - - var historyQ string - if o.History != nil { - historyQ = swag.FormatBool(*o.History) - } - if historyQ != "" { - qs.Set("history", historyQ) - } - - _result.RawQuery = qs.Encode() - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *GetJobsIDURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *GetJobsIDURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *GetJobsIDURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on GetJobsIDURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on GetJobsIDURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *GetJobsIDURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/southbound/restapi/operations/southbound/get_jobs_parameters.go b/generated/southbound/restapi/operations/southbound/get_jobs_parameters.go deleted file mode 100644 index 31fff695..00000000 --- a/generated/southbound/restapi/operations/southbound/get_jobs_parameters.go +++ /dev/null @@ -1,334 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewGetJobsParams creates a new GetJobsParams object -// with the default values initialized. -func NewGetJobsParams() GetJobsParams { - - var ( - // initialize parameters with default values - - limitDefault = int32(10) - offsetDefault = int64(0) - sortDefault = string("asc") - ) - - return GetJobsParams{ - Limit: &limitDefault, - - Offset: &offsetDefault, - - Sort: &sortDefault, - } -} - -// GetJobsParams contains all the bound params for the get jobs operation -// typically these are obtained from a http.Request -// -// swagger:parameters GetJobs -type GetJobsParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*Filter jobs belonging to a specific client with clientId - In: query - */ - ClientID *string - /*Filter jobs based on the group they are in - In: query - */ - Group []string - /*the maximum number of items to return - In: query - Default: 10 - */ - Limit *int32 - /*the number of items to skip before starting to return results - In: query - Default: 0 - */ - Offset *int64 - /*the order of returned elements - In: query - Default: "asc" - */ - Sort *string - /*Filter jobs based on the current state value - In: query - */ - State *string - /*Filter jobs by tags - In: query - */ - Tag []string - /*Filter jobs matching by workflow - In: query - */ - Workflow *string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewGetJobsParams() beforehand. -func (o *GetJobsParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - qs := runtime.Values(r.URL.Query()) - - qClientID, qhkClientID, _ := qs.GetOK("clientId") - if err := o.bindClientID(qClientID, qhkClientID, route.Formats); err != nil { - res = append(res, err) - } - - qGroup, qhkGroup, _ := qs.GetOK("group") - if err := o.bindGroup(qGroup, qhkGroup, route.Formats); err != nil { - res = append(res, err) - } - - qLimit, qhkLimit, _ := qs.GetOK("limit") - if err := o.bindLimit(qLimit, qhkLimit, route.Formats); err != nil { - res = append(res, err) - } - - qOffset, qhkOffset, _ := qs.GetOK("offset") - if err := o.bindOffset(qOffset, qhkOffset, route.Formats); err != nil { - res = append(res, err) - } - - qSort, qhkSort, _ := qs.GetOK("sort") - if err := o.bindSort(qSort, qhkSort, route.Formats); err != nil { - res = append(res, err) - } - - qState, qhkState, _ := qs.GetOK("state") - if err := o.bindState(qState, qhkState, route.Formats); err != nil { - res = append(res, err) - } - - qTag, qhkTag, _ := qs.GetOK("tag") - if err := o.bindTag(qTag, qhkTag, route.Formats); err != nil { - res = append(res, err) - } - - qWorkflow, qhkWorkflow, _ := qs.GetOK("workflow") - if err := o.bindWorkflow(qWorkflow, qhkWorkflow, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindClientID binds and validates parameter ClientID from query. -func (o *GetJobsParams) bindClientID(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - return nil - } - o.ClientID = &raw - - return nil -} - -// bindGroup binds and validates array parameter Group from query. -// -// Arrays are parsed according to CollectionFormat: "" (defaults to "csv" when empty). -func (o *GetJobsParams) bindGroup(rawData []string, hasKey bool, formats strfmt.Registry) error { - var qvGroup string - if len(rawData) > 0 { - qvGroup = rawData[len(rawData)-1] - } - - // CollectionFormat: - groupIC := swag.SplitByFormat(qvGroup, "") - if len(groupIC) == 0 { - return nil - } - - var groupIR []string - for _, groupIV := range groupIC { - groupI := groupIV - - groupIR = append(groupIR, groupI) - } - - o.Group = groupIR - - return nil -} - -// bindLimit binds and validates parameter Limit from query. -func (o *GetJobsParams) bindLimit(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - // Default values have been previously initialized by NewGetJobsParams() - return nil - } - - value, err := swag.ConvertInt32(raw) - if err != nil { - return errors.InvalidType("limit", "query", "int32", raw) - } - o.Limit = &value - - return nil -} - -// bindOffset binds and validates parameter Offset from query. -func (o *GetJobsParams) bindOffset(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - // Default values have been previously initialized by NewGetJobsParams() - return nil - } - - value, err := swag.ConvertInt64(raw) - if err != nil { - return errors.InvalidType("offset", "query", "int64", raw) - } - o.Offset = &value - - return nil -} - -// bindSort binds and validates parameter Sort from query. -func (o *GetJobsParams) bindSort(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - // Default values have been previously initialized by NewGetJobsParams() - return nil - } - o.Sort = &raw - - if err := o.validateSort(formats); err != nil { - return err - } - - return nil -} - -// validateSort carries on validations for parameter Sort -func (o *GetJobsParams) validateSort(formats strfmt.Registry) error { - - if err := validate.EnumCase("sort", "query", *o.Sort, []interface{}{"asc", "desc"}, true); err != nil { - return err - } - - return nil -} - -// bindState binds and validates parameter State from query. -func (o *GetJobsParams) bindState(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - return nil - } - o.State = &raw - - return nil -} - -// bindTag binds and validates array parameter Tag from query. -// -// Arrays are parsed according to CollectionFormat: "" (defaults to "csv" when empty). -func (o *GetJobsParams) bindTag(rawData []string, hasKey bool, formats strfmt.Registry) error { - var qvTag string - if len(rawData) > 0 { - qvTag = rawData[len(rawData)-1] - } - - // CollectionFormat: - tagIC := swag.SplitByFormat(qvTag, "") - if len(tagIC) == 0 { - return nil - } - - var tagIR []string - for _, tagIV := range tagIC { - tagI := tagIV - - tagIR = append(tagIR, tagI) - } - - o.Tag = tagIR - - return nil -} - -// bindWorkflow binds and validates parameter Workflow from query. -func (o *GetJobsParams) bindWorkflow(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - return nil - } - o.Workflow = &raw - - return nil -} diff --git a/generated/southbound/restapi/operations/southbound/get_jobs_responses.go b/generated/southbound/restapi/operations/southbound/get_jobs_responses.go deleted file mode 100644 index c52a144d..00000000 --- a/generated/southbound/restapi/operations/southbound/get_jobs_responses.go +++ /dev/null @@ -1,147 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// GetJobsOKCode is the HTTP code returned for type GetJobsOK -const GetJobsOKCode int = 200 - -/* -GetJobsOK A paginated job list. - -swagger:response getJobsOK -*/ -type GetJobsOK struct { - - /* - In: Body - */ - Payload *model.PaginatedJobList `json:"body,omitempty"` -} - -// NewGetJobsOK creates GetJobsOK with default headers values -func NewGetJobsOK() *GetJobsOK { - - return &GetJobsOK{} -} - -// WithPayload adds the payload to the get jobs o k response -func (o *GetJobsOK) WithPayload(payload *model.PaginatedJobList) *GetJobsOK { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs o k response -func (o *GetJobsOK) SetPayload(payload *model.PaginatedJobList) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(200) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// GetJobsBadRequestCode is the HTTP code returned for type GetJobsBadRequest -const GetJobsBadRequestCode int = 400 - -/* -GetJobsBadRequest If request is invalid - -swagger:response getJobsBadRequest -*/ -type GetJobsBadRequest struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewGetJobsBadRequest creates GetJobsBadRequest with default headers values -func NewGetJobsBadRequest() *GetJobsBadRequest { - - return &GetJobsBadRequest{} -} - -// WithPayload adds the payload to the get jobs bad request response -func (o *GetJobsBadRequest) WithPayload(payload *model.ErrorResponse) *GetJobsBadRequest { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get jobs bad request response -func (o *GetJobsBadRequest) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetJobsBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(400) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -GetJobsDefault Other error with any status code and response body format. - -swagger:response getJobsDefault -*/ -type GetJobsDefault struct { - _statusCode int -} - -// NewGetJobsDefault creates GetJobsDefault with default headers values -func NewGetJobsDefault(code int) *GetJobsDefault { - if code <= 0 { - code = 500 - } - - return &GetJobsDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the get jobs default response -func (o *GetJobsDefault) WithStatusCode(code int) *GetJobsDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the get jobs default response -func (o *GetJobsDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *GetJobsDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/southbound/restapi/operations/southbound/get_jobs_urlbuilder.go b/generated/southbound/restapi/operations/southbound/get_jobs_urlbuilder.go deleted file mode 100644 index e5487edb..00000000 --- a/generated/southbound/restapi/operations/southbound/get_jobs_urlbuilder.go +++ /dev/null @@ -1,191 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" - - "github.com/go-openapi/swag" -) - -// GetJobsURL generates an URL for the get jobs operation -type GetJobsURL struct { - ClientID *string - Group []string - Limit *int32 - Offset *int64 - Sort *string - State *string - Tag []string - Workflow *string - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetJobsURL) WithBasePath(bp string) *GetJobsURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetJobsURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *GetJobsURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/jobs" - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - qs := make(url.Values) - - var clientIDQ string - if o.ClientID != nil { - clientIDQ = *o.ClientID - } - if clientIDQ != "" { - qs.Set("clientId", clientIDQ) - } - - var groupIR []string - for _, groupI := range o.Group { - groupIS := groupI - if groupIS != "" { - groupIR = append(groupIR, groupIS) - } - } - - group := swag.JoinByFormat(groupIR, "") - - if len(group) > 0 { - qsv := group[0] - if qsv != "" { - qs.Set("group", qsv) - } - } - - var limitQ string - if o.Limit != nil { - limitQ = swag.FormatInt32(*o.Limit) - } - if limitQ != "" { - qs.Set("limit", limitQ) - } - - var offsetQ string - if o.Offset != nil { - offsetQ = swag.FormatInt64(*o.Offset) - } - if offsetQ != "" { - qs.Set("offset", offsetQ) - } - - var sortQ string - if o.Sort != nil { - sortQ = *o.Sort - } - if sortQ != "" { - qs.Set("sort", sortQ) - } - - var stateQ string - if o.State != nil { - stateQ = *o.State - } - if stateQ != "" { - qs.Set("state", stateQ) - } - - var tagIR []string - for _, tagI := range o.Tag { - tagIS := tagI - if tagIS != "" { - tagIR = append(tagIR, tagIS) - } - } - - tag := swag.JoinByFormat(tagIR, "") - - if len(tag) > 0 { - qsv := tag[0] - if qsv != "" { - qs.Set("tag", qsv) - } - } - - var workflowQ string - if o.Workflow != nil { - workflowQ = *o.Workflow - } - if workflowQ != "" { - qs.Set("workflow", workflowQ) - } - - _result.RawQuery = qs.Encode() - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *GetJobsURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *GetJobsURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *GetJobsURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on GetJobsURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on GetJobsURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *GetJobsURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/southbound/restapi/operations/southbound/get_workflows.go b/generated/southbound/restapi/operations/southbound/get_workflows.go deleted file mode 100644 index 96215bb8..00000000 --- a/generated/southbound/restapi/operations/southbound/get_workflows.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// GetWorkflowsHandlerFunc turns a function with the right signature into a get workflows handler -type GetWorkflowsHandlerFunc func(GetWorkflowsParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn GetWorkflowsHandlerFunc) Handle(params GetWorkflowsParams) middleware.Responder { - return fn(params) -} - -// GetWorkflowsHandler interface for that can handle valid get workflows params -type GetWorkflowsHandler interface { - Handle(GetWorkflowsParams) middleware.Responder -} - -// NewGetWorkflows creates a new http.Handler for the get workflows operation -func NewGetWorkflows(ctx *middleware.Context, handler GetWorkflowsHandler) *GetWorkflows { - return &GetWorkflows{Context: ctx, Handler: handler} -} - -/* - GetWorkflows swagger:route GET /workflows southbound getWorkflows - -# List of available workflows - -List of available workflows -*/ -type GetWorkflows struct { - Context *middleware.Context - Handler GetWorkflowsHandler -} - -func (o *GetWorkflows) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewGetWorkflowsParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/southbound/restapi/operations/southbound/get_workflows_name.go b/generated/southbound/restapi/operations/southbound/get_workflows_name.go deleted file mode 100644 index 97c655c6..00000000 --- a/generated/southbound/restapi/operations/southbound/get_workflows_name.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// GetWorkflowsNameHandlerFunc turns a function with the right signature into a get workflows name handler -type GetWorkflowsNameHandlerFunc func(GetWorkflowsNameParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn GetWorkflowsNameHandlerFunc) Handle(params GetWorkflowsNameParams) middleware.Responder { - return fn(params) -} - -// GetWorkflowsNameHandler interface for that can handle valid get workflows name params -type GetWorkflowsNameHandler interface { - Handle(GetWorkflowsNameParams) middleware.Responder -} - -// NewGetWorkflowsName creates a new http.Handler for the get workflows name operation -func NewGetWorkflowsName(ctx *middleware.Context, handler GetWorkflowsNameHandler) *GetWorkflowsName { - return &GetWorkflowsName{Context: ctx, Handler: handler} -} - -/* - GetWorkflowsName swagger:route GET /workflows/{name} southbound getWorkflowsName - -# Workflow description for a given name - -Workflow description for a given name -*/ -type GetWorkflowsName struct { - Context *middleware.Context - Handler GetWorkflowsNameHandler -} - -func (o *GetWorkflowsName) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewGetWorkflowsNameParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/southbound/restapi/operations/southbound/get_workflows_name_parameters.go b/generated/southbound/restapi/operations/southbound/get_workflows_name_parameters.go deleted file mode 100644 index 0d5f3743..00000000 --- a/generated/southbound/restapi/operations/southbound/get_workflows_name_parameters.go +++ /dev/null @@ -1,76 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" -) - -// NewGetWorkflowsNameParams creates a new GetWorkflowsNameParams object -// -// There are no default values defined in the spec. -func NewGetWorkflowsNameParams() GetWorkflowsNameParams { - - return GetWorkflowsNameParams{} -} - -// GetWorkflowsNameParams contains all the bound params for the get workflows name operation -// typically these are obtained from a http.Request -// -// swagger:parameters GetWorkflowsName -type GetWorkflowsNameParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*Unique name for the workflow - Required: true - In: path - */ - Name string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewGetWorkflowsNameParams() beforehand. -func (o *GetWorkflowsNameParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - rName, rhkName, _ := route.Params.GetOK("name") - if err := o.bindName(rName, rhkName, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindName binds and validates parameter Name from path. -func (o *GetWorkflowsNameParams) bindName(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: true - // Parameter is provided by construction from the route - o.Name = raw - - return nil -} diff --git a/generated/southbound/restapi/operations/southbound/get_workflows_name_responses.go b/generated/southbound/restapi/operations/southbound/get_workflows_name_responses.go deleted file mode 100644 index 9daff7ce..00000000 --- a/generated/southbound/restapi/operations/southbound/get_workflows_name_responses.go +++ /dev/null @@ -1,192 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// GetWorkflowsNameOKCode is the HTTP code returned for type GetWorkflowsNameOK -const GetWorkflowsNameOKCode int = 200 - -/* -GetWorkflowsNameOK Workflow description with the provided key - -swagger:response getWorkflowsNameOK -*/ -type GetWorkflowsNameOK struct { - - /* - In: Body - */ - Payload *model.Workflow `json:"body,omitempty"` -} - -// NewGetWorkflowsNameOK creates GetWorkflowsNameOK with default headers values -func NewGetWorkflowsNameOK() *GetWorkflowsNameOK { - - return &GetWorkflowsNameOK{} -} - -// WithPayload adds the payload to the get workflows name o k response -func (o *GetWorkflowsNameOK) WithPayload(payload *model.Workflow) *GetWorkflowsNameOK { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get workflows name o k response -func (o *GetWorkflowsNameOK) SetPayload(payload *model.Workflow) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetWorkflowsNameOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(200) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// GetWorkflowsNameBadRequestCode is the HTTP code returned for type GetWorkflowsNameBadRequest -const GetWorkflowsNameBadRequestCode int = 400 - -/* -GetWorkflowsNameBadRequest If request is invalid - -swagger:response getWorkflowsNameBadRequest -*/ -type GetWorkflowsNameBadRequest struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewGetWorkflowsNameBadRequest creates GetWorkflowsNameBadRequest with default headers values -func NewGetWorkflowsNameBadRequest() *GetWorkflowsNameBadRequest { - - return &GetWorkflowsNameBadRequest{} -} - -// WithPayload adds the payload to the get workflows name bad request response -func (o *GetWorkflowsNameBadRequest) WithPayload(payload *model.ErrorResponse) *GetWorkflowsNameBadRequest { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get workflows name bad request response -func (o *GetWorkflowsNameBadRequest) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetWorkflowsNameBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(400) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// GetWorkflowsNameNotFoundCode is the HTTP code returned for type GetWorkflowsNameNotFound -const GetWorkflowsNameNotFoundCode int = 404 - -/* -GetWorkflowsNameNotFound Not Found - -swagger:response getWorkflowsNameNotFound -*/ -type GetWorkflowsNameNotFound struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewGetWorkflowsNameNotFound creates GetWorkflowsNameNotFound with default headers values -func NewGetWorkflowsNameNotFound() *GetWorkflowsNameNotFound { - - return &GetWorkflowsNameNotFound{} -} - -// WithPayload adds the payload to the get workflows name not found response -func (o *GetWorkflowsNameNotFound) WithPayload(payload *model.ErrorResponse) *GetWorkflowsNameNotFound { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get workflows name not found response -func (o *GetWorkflowsNameNotFound) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetWorkflowsNameNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(404) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -GetWorkflowsNameDefault Other error with any status code and response body format. - -swagger:response getWorkflowsNameDefault -*/ -type GetWorkflowsNameDefault struct { - _statusCode int -} - -// NewGetWorkflowsNameDefault creates GetWorkflowsNameDefault with default headers values -func NewGetWorkflowsNameDefault(code int) *GetWorkflowsNameDefault { - if code <= 0 { - code = 500 - } - - return &GetWorkflowsNameDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the get workflows name default response -func (o *GetWorkflowsNameDefault) WithStatusCode(code int) *GetWorkflowsNameDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the get workflows name default response -func (o *GetWorkflowsNameDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *GetWorkflowsNameDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/southbound/restapi/operations/southbound/get_workflows_name_urlbuilder.go b/generated/southbound/restapi/operations/southbound/get_workflows_name_urlbuilder.go deleted file mode 100644 index 2a55c8c2..00000000 --- a/generated/southbound/restapi/operations/southbound/get_workflows_name_urlbuilder.go +++ /dev/null @@ -1,104 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" - "strings" -) - -// GetWorkflowsNameURL generates an URL for the get workflows name operation -type GetWorkflowsNameURL struct { - Name string - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetWorkflowsNameURL) WithBasePath(bp string) *GetWorkflowsNameURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetWorkflowsNameURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *GetWorkflowsNameURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/workflows/{name}" - - name := o.Name - if name != "" { - _path = strings.Replace(_path, "{name}", name, -1) - } else { - return nil, errors.New("name is required on GetWorkflowsNameURL") - } - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *GetWorkflowsNameURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *GetWorkflowsNameURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *GetWorkflowsNameURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on GetWorkflowsNameURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on GetWorkflowsNameURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *GetWorkflowsNameURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/southbound/restapi/operations/southbound/get_workflows_parameters.go b/generated/southbound/restapi/operations/southbound/get_workflows_parameters.go deleted file mode 100644 index aed2b984..00000000 --- a/generated/southbound/restapi/operations/southbound/get_workflows_parameters.go +++ /dev/null @@ -1,181 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewGetWorkflowsParams creates a new GetWorkflowsParams object -// with the default values initialized. -func NewGetWorkflowsParams() GetWorkflowsParams { - - var ( - // initialize parameters with default values - - limitDefault = int32(10) - offsetDefault = int64(0) - sortDefault = string("asc") - ) - - return GetWorkflowsParams{ - Limit: &limitDefault, - - Offset: &offsetDefault, - - Sort: &sortDefault, - } -} - -// GetWorkflowsParams contains all the bound params for the get workflows operation -// typically these are obtained from a http.Request -// -// swagger:parameters GetWorkflows -type GetWorkflowsParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*the maximum number of items to return - In: query - Default: 10 - */ - Limit *int32 - /*the number of items to skip before starting to return results - In: query - Default: 0 - */ - Offset *int64 - /*the order of returned elements - In: query - Default: "asc" - */ - Sort *string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewGetWorkflowsParams() beforehand. -func (o *GetWorkflowsParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - qs := runtime.Values(r.URL.Query()) - - qLimit, qhkLimit, _ := qs.GetOK("limit") - if err := o.bindLimit(qLimit, qhkLimit, route.Formats); err != nil { - res = append(res, err) - } - - qOffset, qhkOffset, _ := qs.GetOK("offset") - if err := o.bindOffset(qOffset, qhkOffset, route.Formats); err != nil { - res = append(res, err) - } - - qSort, qhkSort, _ := qs.GetOK("sort") - if err := o.bindSort(qSort, qhkSort, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindLimit binds and validates parameter Limit from query. -func (o *GetWorkflowsParams) bindLimit(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - // Default values have been previously initialized by NewGetWorkflowsParams() - return nil - } - - value, err := swag.ConvertInt32(raw) - if err != nil { - return errors.InvalidType("limit", "query", "int32", raw) - } - o.Limit = &value - - return nil -} - -// bindOffset binds and validates parameter Offset from query. -func (o *GetWorkflowsParams) bindOffset(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - // Default values have been previously initialized by NewGetWorkflowsParams() - return nil - } - - value, err := swag.ConvertInt64(raw) - if err != nil { - return errors.InvalidType("offset", "query", "int64", raw) - } - o.Offset = &value - - return nil -} - -// bindSort binds and validates parameter Sort from query. -func (o *GetWorkflowsParams) bindSort(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: false - // AllowEmptyValue: false - - if raw == "" { // empty values pass all other validations - // Default values have been previously initialized by NewGetWorkflowsParams() - return nil - } - o.Sort = &raw - - if err := o.validateSort(formats); err != nil { - return err - } - - return nil -} - -// validateSort carries on validations for parameter Sort -func (o *GetWorkflowsParams) validateSort(formats strfmt.Registry) error { - - if err := validate.EnumCase("sort", "query", *o.Sort, []interface{}{"asc", "desc"}, true); err != nil { - return err - } - - return nil -} diff --git a/generated/southbound/restapi/operations/southbound/get_workflows_responses.go b/generated/southbound/restapi/operations/southbound/get_workflows_responses.go deleted file mode 100644 index 347d3a8c..00000000 --- a/generated/southbound/restapi/operations/southbound/get_workflows_responses.go +++ /dev/null @@ -1,102 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// GetWorkflowsOKCode is the HTTP code returned for type GetWorkflowsOK -const GetWorkflowsOKCode int = 200 - -/* -GetWorkflowsOK A list of workflows - -swagger:response getWorkflowsOK -*/ -type GetWorkflowsOK struct { - - /* - In: Body - */ - Payload *model.PaginatedWorkflowList `json:"body,omitempty"` -} - -// NewGetWorkflowsOK creates GetWorkflowsOK with default headers values -func NewGetWorkflowsOK() *GetWorkflowsOK { - - return &GetWorkflowsOK{} -} - -// WithPayload adds the payload to the get workflows o k response -func (o *GetWorkflowsOK) WithPayload(payload *model.PaginatedWorkflowList) *GetWorkflowsOK { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get workflows o k response -func (o *GetWorkflowsOK) SetPayload(payload *model.PaginatedWorkflowList) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetWorkflowsOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(200) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -GetWorkflowsDefault Other error with any status code and response body format. - -swagger:response getWorkflowsDefault -*/ -type GetWorkflowsDefault struct { - _statusCode int -} - -// NewGetWorkflowsDefault creates GetWorkflowsDefault with default headers values -func NewGetWorkflowsDefault(code int) *GetWorkflowsDefault { - if code <= 0 { - code = 500 - } - - return &GetWorkflowsDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the get workflows default response -func (o *GetWorkflowsDefault) WithStatusCode(code int) *GetWorkflowsDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the get workflows default response -func (o *GetWorkflowsDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *GetWorkflowsDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/southbound/restapi/operations/southbound/get_workflows_urlbuilder.go b/generated/southbound/restapi/operations/southbound/get_workflows_urlbuilder.go deleted file mode 100644 index a45164b9..00000000 --- a/generated/southbound/restapi/operations/southbound/get_workflows_urlbuilder.go +++ /dev/null @@ -1,128 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" - - "github.com/go-openapi/swag" -) - -// GetWorkflowsURL generates an URL for the get workflows operation -type GetWorkflowsURL struct { - Limit *int32 - Offset *int64 - Sort *string - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetWorkflowsURL) WithBasePath(bp string) *GetWorkflowsURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetWorkflowsURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *GetWorkflowsURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/workflows" - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - qs := make(url.Values) - - var limitQ string - if o.Limit != nil { - limitQ = swag.FormatInt32(*o.Limit) - } - if limitQ != "" { - qs.Set("limit", limitQ) - } - - var offsetQ string - if o.Offset != nil { - offsetQ = swag.FormatInt64(*o.Offset) - } - if offsetQ != "" { - qs.Set("offset", offsetQ) - } - - var sortQ string - if o.Sort != nil { - sortQ = *o.Sort - } - if sortQ != "" { - qs.Set("sort", sortQ) - } - - _result.RawQuery = qs.Encode() - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *GetWorkflowsURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *GetWorkflowsURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *GetWorkflowsURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on GetWorkflowsURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on GetWorkflowsURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *GetWorkflowsURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/southbound/restapi/operations/southbound/put_jobs_id_definition.go b/generated/southbound/restapi/operations/southbound/put_jobs_id_definition.go deleted file mode 100644 index 1b2a36f4..00000000 --- a/generated/southbound/restapi/operations/southbound/put_jobs_id_definition.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// PutJobsIDDefinitionHandlerFunc turns a function with the right signature into a put jobs ID definition handler -type PutJobsIDDefinitionHandlerFunc func(PutJobsIDDefinitionParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn PutJobsIDDefinitionHandlerFunc) Handle(params PutJobsIDDefinitionParams) middleware.Responder { - return fn(params) -} - -// PutJobsIDDefinitionHandler interface for that can handle valid put jobs ID definition params -type PutJobsIDDefinitionHandler interface { - Handle(PutJobsIDDefinitionParams) middleware.Responder -} - -// NewPutJobsIDDefinition creates a new http.Handler for the put jobs ID definition operation -func NewPutJobsIDDefinition(ctx *middleware.Context, handler PutJobsIDDefinitionHandler) *PutJobsIDDefinition { - return &PutJobsIDDefinition{Context: ctx, Handler: handler} -} - -/* - PutJobsIDDefinition swagger:route PUT /jobs/{id}/definition southbound putJobsIdDefinition - -# Modify job definition - -Modify the job definition of an existing job -*/ -type PutJobsIDDefinition struct { - Context *middleware.Context - Handler PutJobsIDDefinitionHandler -} - -func (o *PutJobsIDDefinition) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewPutJobsIDDefinitionParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/southbound/restapi/operations/southbound/put_jobs_id_definition_parameters.go b/generated/southbound/restapi/operations/southbound/put_jobs_id_definition_parameters.go deleted file mode 100644 index b556eb92..00000000 --- a/generated/southbound/restapi/operations/southbound/put_jobs_id_definition_parameters.go +++ /dev/null @@ -1,100 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "io" - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" -) - -// NewPutJobsIDDefinitionParams creates a new PutJobsIDDefinitionParams object -// -// There are no default values defined in the spec. -func NewPutJobsIDDefinitionParams() PutJobsIDDefinitionParams { - - return PutJobsIDDefinitionParams{} -} - -// PutJobsIDDefinitionParams contains all the bound params for the put jobs ID definition operation -// typically these are obtained from a http.Request -// -// swagger:parameters PutJobsIDDefinition -type PutJobsIDDefinitionParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*How to modify the job - Required: true - In: body - */ - JobDefinition map[string]interface{} - /*Job ID - Required: true - In: path - */ - ID string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewPutJobsIDDefinitionParams() beforehand. -func (o *PutJobsIDDefinitionParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - if runtime.HasBody(r) { - defer r.Body.Close() - var body map[string]interface{} - if err := route.Consumer.Consume(r.Body, &body); err != nil { - if err == io.EOF { - res = append(res, errors.Required("jobDefinition", "body", "")) - } else { - res = append(res, errors.NewParseError("jobDefinition", "body", "", err)) - } - } else { - // no validation for this map - o.JobDefinition = body - } - } else { - res = append(res, errors.Required("jobDefinition", "body", "")) - } - - rID, rhkID, _ := route.Params.GetOK("id") - if err := o.bindID(rID, rhkID, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindID binds and validates parameter ID from path. -func (o *PutJobsIDDefinitionParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: true - // Parameter is provided by construction from the route - o.ID = raw - - return nil -} diff --git a/generated/southbound/restapi/operations/southbound/put_jobs_id_definition_responses.go b/generated/southbound/restapi/operations/southbound/put_jobs_id_definition_responses.go deleted file mode 100644 index 674f6318..00000000 --- a/generated/southbound/restapi/operations/southbound/put_jobs_id_definition_responses.go +++ /dev/null @@ -1,195 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// PutJobsIDDefinitionOKCode is the HTTP code returned for type PutJobsIDDefinitionOK -const PutJobsIDDefinitionOKCode int = 200 - -/* -PutJobsIDDefinitionOK Job modified successfully - -swagger:response putJobsIdDefinitionOK -*/ -type PutJobsIDDefinitionOK struct { - - /* - In: Body - */ - Payload map[string]interface{} `json:"body,omitempty"` -} - -// NewPutJobsIDDefinitionOK creates PutJobsIDDefinitionOK with default headers values -func NewPutJobsIDDefinitionOK() *PutJobsIDDefinitionOK { - - return &PutJobsIDDefinitionOK{} -} - -// WithPayload adds the payload to the put jobs Id definition o k response -func (o *PutJobsIDDefinitionOK) WithPayload(payload map[string]interface{}) *PutJobsIDDefinitionOK { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the put jobs Id definition o k response -func (o *PutJobsIDDefinitionOK) SetPayload(payload map[string]interface{}) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *PutJobsIDDefinitionOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(200) - payload := o.Payload - if payload == nil { - // return empty map - payload = make(map[string]interface{}, 50) - } - - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } -} - -// PutJobsIDDefinitionBadRequestCode is the HTTP code returned for type PutJobsIDDefinitionBadRequest -const PutJobsIDDefinitionBadRequestCode int = 400 - -/* -PutJobsIDDefinitionBadRequest Bad Request - -swagger:response putJobsIdDefinitionBadRequest -*/ -type PutJobsIDDefinitionBadRequest struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewPutJobsIDDefinitionBadRequest creates PutJobsIDDefinitionBadRequest with default headers values -func NewPutJobsIDDefinitionBadRequest() *PutJobsIDDefinitionBadRequest { - - return &PutJobsIDDefinitionBadRequest{} -} - -// WithPayload adds the payload to the put jobs Id definition bad request response -func (o *PutJobsIDDefinitionBadRequest) WithPayload(payload *model.ErrorResponse) *PutJobsIDDefinitionBadRequest { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the put jobs Id definition bad request response -func (o *PutJobsIDDefinitionBadRequest) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *PutJobsIDDefinitionBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(400) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// PutJobsIDDefinitionNotFoundCode is the HTTP code returned for type PutJobsIDDefinitionNotFound -const PutJobsIDDefinitionNotFoundCode int = 404 - -/* -PutJobsIDDefinitionNotFound Not Found - -swagger:response putJobsIdDefinitionNotFound -*/ -type PutJobsIDDefinitionNotFound struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewPutJobsIDDefinitionNotFound creates PutJobsIDDefinitionNotFound with default headers values -func NewPutJobsIDDefinitionNotFound() *PutJobsIDDefinitionNotFound { - - return &PutJobsIDDefinitionNotFound{} -} - -// WithPayload adds the payload to the put jobs Id definition not found response -func (o *PutJobsIDDefinitionNotFound) WithPayload(payload *model.ErrorResponse) *PutJobsIDDefinitionNotFound { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the put jobs Id definition not found response -func (o *PutJobsIDDefinitionNotFound) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *PutJobsIDDefinitionNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(404) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -PutJobsIDDefinitionDefault Other error with any status code and response body format. - -swagger:response putJobsIdDefinitionDefault -*/ -type PutJobsIDDefinitionDefault struct { - _statusCode int -} - -// NewPutJobsIDDefinitionDefault creates PutJobsIDDefinitionDefault with default headers values -func NewPutJobsIDDefinitionDefault(code int) *PutJobsIDDefinitionDefault { - if code <= 0 { - code = 500 - } - - return &PutJobsIDDefinitionDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the put jobs ID definition default response -func (o *PutJobsIDDefinitionDefault) WithStatusCode(code int) *PutJobsIDDefinitionDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the put jobs ID definition default response -func (o *PutJobsIDDefinitionDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *PutJobsIDDefinitionDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/southbound/restapi/operations/southbound/put_jobs_id_definition_urlbuilder.go b/generated/southbound/restapi/operations/southbound/put_jobs_id_definition_urlbuilder.go deleted file mode 100644 index 60e3625c..00000000 --- a/generated/southbound/restapi/operations/southbound/put_jobs_id_definition_urlbuilder.go +++ /dev/null @@ -1,104 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" - "strings" -) - -// PutJobsIDDefinitionURL generates an URL for the put jobs ID definition operation -type PutJobsIDDefinitionURL struct { - ID string - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *PutJobsIDDefinitionURL) WithBasePath(bp string) *PutJobsIDDefinitionURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *PutJobsIDDefinitionURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *PutJobsIDDefinitionURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/jobs/{id}/definition" - - id := o.ID - if id != "" { - _path = strings.Replace(_path, "{id}", id, -1) - } else { - return nil, errors.New("id is required on PutJobsIDDefinitionURL") - } - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *PutJobsIDDefinitionURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *PutJobsIDDefinitionURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *PutJobsIDDefinitionURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on PutJobsIDDefinitionURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on PutJobsIDDefinitionURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *PutJobsIDDefinitionURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/southbound/restapi/operations/southbound/put_jobs_id_status.go b/generated/southbound/restapi/operations/southbound/put_jobs_id_status.go deleted file mode 100644 index e2a51c22..00000000 --- a/generated/southbound/restapi/operations/southbound/put_jobs_id_status.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// PutJobsIDStatusHandlerFunc turns a function with the right signature into a put jobs ID status handler -type PutJobsIDStatusHandlerFunc func(PutJobsIDStatusParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn PutJobsIDStatusHandlerFunc) Handle(params PutJobsIDStatusParams) middleware.Responder { - return fn(params) -} - -// PutJobsIDStatusHandler interface for that can handle valid put jobs ID status params -type PutJobsIDStatusHandler interface { - Handle(PutJobsIDStatusParams) middleware.Responder -} - -// NewPutJobsIDStatus creates a new http.Handler for the put jobs ID status operation -func NewPutJobsIDStatus(ctx *middleware.Context, handler PutJobsIDStatusHandler) *PutJobsIDStatus { - return &PutJobsIDStatus{Context: ctx, Handler: handler} -} - -/* - PutJobsIDStatus swagger:route PUT /jobs/{id}/status southbound putJobsIdStatus - -# Modify status of an existing job - -Modify status of an existing job -*/ -type PutJobsIDStatus struct { - Context *middleware.Context - Handler PutJobsIDStatusHandler -} - -func (o *PutJobsIDStatus) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewPutJobsIDStatusParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/generated/southbound/restapi/operations/southbound/put_jobs_id_status_parameters.go b/generated/southbound/restapi/operations/southbound/put_jobs_id_status_parameters.go deleted file mode 100644 index f4b62217..00000000 --- a/generated/southbound/restapi/operations/southbound/put_jobs_id_status_parameters.go +++ /dev/null @@ -1,113 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "io" - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/validate" - "github.com/siemens/wfx/generated/model" -) - -// NewPutJobsIDStatusParams creates a new PutJobsIDStatusParams object -// -// There are no default values defined in the spec. -func NewPutJobsIDStatusParams() PutJobsIDStatusParams { - - return PutJobsIDStatusParams{} -} - -// PutJobsIDStatusParams contains all the bound params for the put jobs ID status operation -// typically these are obtained from a http.Request -// -// swagger:parameters PutJobsIDStatus -type PutJobsIDStatusParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /*This contains the new job status - Required: true - In: body - */ - NewJobStatus *model.JobStatus - /*Job ID - Required: true - In: path - */ - ID string -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewPutJobsIDStatusParams() beforehand. -func (o *PutJobsIDStatusParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - if runtime.HasBody(r) { - defer r.Body.Close() - var body model.JobStatus - if err := route.Consumer.Consume(r.Body, &body); err != nil { - if err == io.EOF { - res = append(res, errors.Required("newJobStatus", "body", "")) - } else { - res = append(res, errors.NewParseError("newJobStatus", "body", "", err)) - } - } else { - // validate body object - if err := body.Validate(route.Formats); err != nil { - res = append(res, err) - } - - ctx := validate.WithOperationRequest(r.Context()) - if err := body.ContextValidate(ctx, route.Formats); err != nil { - res = append(res, err) - } - - if len(res) == 0 { - o.NewJobStatus = &body - } - } - } else { - res = append(res, errors.Required("newJobStatus", "body", "")) - } - - rID, rhkID, _ := route.Params.GetOK("id") - if err := o.bindID(rID, rhkID, route.Formats); err != nil { - res = append(res, err) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// bindID binds and validates parameter ID from path. -func (o *PutJobsIDStatusParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { - var raw string - if len(rawData) > 0 { - raw = rawData[len(rawData)-1] - } - - // Required: true - // Parameter is provided by construction from the route - o.ID = raw - - return nil -} diff --git a/generated/southbound/restapi/operations/southbound/put_jobs_id_status_responses.go b/generated/southbound/restapi/operations/southbound/put_jobs_id_status_responses.go deleted file mode 100644 index 3a25dd16..00000000 --- a/generated/southbound/restapi/operations/southbound/put_jobs_id_status_responses.go +++ /dev/null @@ -1,192 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/siemens/wfx/generated/model" -) - -// PutJobsIDStatusOKCode is the HTTP code returned for type PutJobsIDStatusOK -const PutJobsIDStatusOKCode int = 200 - -/* -PutJobsIDStatusOK Job modified successfully - -swagger:response putJobsIdStatusOK -*/ -type PutJobsIDStatusOK struct { - - /* - In: Body - */ - Payload *model.JobStatus `json:"body,omitempty"` -} - -// NewPutJobsIDStatusOK creates PutJobsIDStatusOK with default headers values -func NewPutJobsIDStatusOK() *PutJobsIDStatusOK { - - return &PutJobsIDStatusOK{} -} - -// WithPayload adds the payload to the put jobs Id status o k response -func (o *PutJobsIDStatusOK) WithPayload(payload *model.JobStatus) *PutJobsIDStatusOK { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the put jobs Id status o k response -func (o *PutJobsIDStatusOK) SetPayload(payload *model.JobStatus) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *PutJobsIDStatusOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(200) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// PutJobsIDStatusBadRequestCode is the HTTP code returned for type PutJobsIDStatusBadRequest -const PutJobsIDStatusBadRequestCode int = 400 - -/* -PutJobsIDStatusBadRequest Bad Request - -swagger:response putJobsIdStatusBadRequest -*/ -type PutJobsIDStatusBadRequest struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewPutJobsIDStatusBadRequest creates PutJobsIDStatusBadRequest with default headers values -func NewPutJobsIDStatusBadRequest() *PutJobsIDStatusBadRequest { - - return &PutJobsIDStatusBadRequest{} -} - -// WithPayload adds the payload to the put jobs Id status bad request response -func (o *PutJobsIDStatusBadRequest) WithPayload(payload *model.ErrorResponse) *PutJobsIDStatusBadRequest { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the put jobs Id status bad request response -func (o *PutJobsIDStatusBadRequest) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *PutJobsIDStatusBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(400) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// PutJobsIDStatusNotFoundCode is the HTTP code returned for type PutJobsIDStatusNotFound -const PutJobsIDStatusNotFoundCode int = 404 - -/* -PutJobsIDStatusNotFound Not Found - -swagger:response putJobsIdStatusNotFound -*/ -type PutJobsIDStatusNotFound struct { - - /* - In: Body - */ - Payload *model.ErrorResponse `json:"body,omitempty"` -} - -// NewPutJobsIDStatusNotFound creates PutJobsIDStatusNotFound with default headers values -func NewPutJobsIDStatusNotFound() *PutJobsIDStatusNotFound { - - return &PutJobsIDStatusNotFound{} -} - -// WithPayload adds the payload to the put jobs Id status not found response -func (o *PutJobsIDStatusNotFound) WithPayload(payload *model.ErrorResponse) *PutJobsIDStatusNotFound { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the put jobs Id status not found response -func (o *PutJobsIDStatusNotFound) SetPayload(payload *model.ErrorResponse) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *PutJobsIDStatusNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(404) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -/* -PutJobsIDStatusDefault Other error with any status code and response body format. - -swagger:response putJobsIdStatusDefault -*/ -type PutJobsIDStatusDefault struct { - _statusCode int -} - -// NewPutJobsIDStatusDefault creates PutJobsIDStatusDefault with default headers values -func NewPutJobsIDStatusDefault(code int) *PutJobsIDStatusDefault { - if code <= 0 { - code = 500 - } - - return &PutJobsIDStatusDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the put jobs ID status default response -func (o *PutJobsIDStatusDefault) WithStatusCode(code int) *PutJobsIDStatusDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the put jobs ID status default response -func (o *PutJobsIDStatusDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WriteResponse to the client -func (o *PutJobsIDStatusDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(o._statusCode) -} diff --git a/generated/southbound/restapi/operations/southbound/put_jobs_id_status_urlbuilder.go b/generated/southbound/restapi/operations/southbound/put_jobs_id_status_urlbuilder.go deleted file mode 100644 index 0adc34b8..00000000 --- a/generated/southbound/restapi/operations/southbound/put_jobs_id_status_urlbuilder.go +++ /dev/null @@ -1,104 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package southbound - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" - "strings" -) - -// PutJobsIDStatusURL generates an URL for the put jobs ID status operation -type PutJobsIDStatusURL struct { - ID string - - _basePath string - // avoid unkeyed usage - _ struct{} -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *PutJobsIDStatusURL) WithBasePath(bp string) *PutJobsIDStatusURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *PutJobsIDStatusURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *PutJobsIDStatusURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/jobs/{id}/status" - - id := o.ID - if id != "" { - _path = strings.Replace(_path, "{id}", id, -1) - } else { - return nil, errors.New("id is required on PutJobsIDStatusURL") - } - - _basePath := o._basePath - if _basePath == "" { - _basePath = "/api/wfx/v1" - } - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *PutJobsIDStatusURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *PutJobsIDStatusURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *PutJobsIDStatusURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on PutJobsIDStatusURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on PutJobsIDStatusURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *PutJobsIDStatusURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/generated/southbound/restapi/operations/workflow_executor_api.go b/generated/southbound/restapi/operations/workflow_executor_api.go deleted file mode 100644 index 66692151..00000000 --- a/generated/southbound/restapi/operations/workflow_executor_api.go +++ /dev/null @@ -1,428 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// SPDX-FileCopyrightText: 2023 Siemens AG -// -// SPDX-License-Identifier: Apache-2.0 -// - -package operations - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "fmt" - "io" - "net/http" - "strings" - - "github.com/go-openapi/errors" - "github.com/go-openapi/loads" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/runtime/security" - "github.com/go-openapi/spec" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - - "github.com/siemens/wfx/generated/southbound/restapi/operations/southbound" -) - -// NewWorkflowExecutorAPI creates a new WorkflowExecutor instance -func NewWorkflowExecutorAPI(spec *loads.Document) *WorkflowExecutorAPI { - return &WorkflowExecutorAPI{ - handlers: make(map[string]map[string]http.Handler), - formats: strfmt.Default, - defaultConsumes: "application/json", - defaultProduces: "application/json", - customConsumers: make(map[string]runtime.Consumer), - customProducers: make(map[string]runtime.Producer), - PreServerShutdown: func() {}, - ServerShutdown: func() {}, - spec: spec, - useSwaggerUI: false, - ServeError: errors.ServeError, - BasicAuthenticator: security.BasicAuth, - APIKeyAuthenticator: security.APIKeyAuth, - BearerAuthenticator: security.BearerAuth, - - JSONConsumer: runtime.JSONConsumer(), - - JSONProducer: runtime.JSONProducer(), - TextEventStreamProducer: runtime.ProducerFunc(func(w io.Writer, data interface{}) error { - return errors.NotImplemented("textEventStream producer has not yet been implemented") - }), - - SouthboundGetJobsHandler: southbound.GetJobsHandlerFunc(func(params southbound.GetJobsParams) middleware.Responder { - return middleware.NotImplemented("operation southbound.GetJobs has not yet been implemented") - }), - SouthboundGetJobsEventsHandler: southbound.GetJobsEventsHandlerFunc(func(params southbound.GetJobsEventsParams) middleware.Responder { - return middleware.NotImplemented("operation southbound.GetJobsEvents has not yet been implemented") - }), - SouthboundGetJobsIDHandler: southbound.GetJobsIDHandlerFunc(func(params southbound.GetJobsIDParams) middleware.Responder { - return middleware.NotImplemented("operation southbound.GetJobsID has not yet been implemented") - }), - SouthboundGetJobsIDDefinitionHandler: southbound.GetJobsIDDefinitionHandlerFunc(func(params southbound.GetJobsIDDefinitionParams) middleware.Responder { - return middleware.NotImplemented("operation southbound.GetJobsIDDefinition has not yet been implemented") - }), - SouthboundGetJobsIDStatusHandler: southbound.GetJobsIDStatusHandlerFunc(func(params southbound.GetJobsIDStatusParams) middleware.Responder { - return middleware.NotImplemented("operation southbound.GetJobsIDStatus has not yet been implemented") - }), - SouthboundGetJobsIDTagsHandler: southbound.GetJobsIDTagsHandlerFunc(func(params southbound.GetJobsIDTagsParams) middleware.Responder { - return middleware.NotImplemented("operation southbound.GetJobsIDTags has not yet been implemented") - }), - SouthboundGetWorkflowsHandler: southbound.GetWorkflowsHandlerFunc(func(params southbound.GetWorkflowsParams) middleware.Responder { - return middleware.NotImplemented("operation southbound.GetWorkflows has not yet been implemented") - }), - SouthboundGetWorkflowsNameHandler: southbound.GetWorkflowsNameHandlerFunc(func(params southbound.GetWorkflowsNameParams) middleware.Responder { - return middleware.NotImplemented("operation southbound.GetWorkflowsName has not yet been implemented") - }), - SouthboundPutJobsIDDefinitionHandler: southbound.PutJobsIDDefinitionHandlerFunc(func(params southbound.PutJobsIDDefinitionParams) middleware.Responder { - return middleware.NotImplemented("operation southbound.PutJobsIDDefinition has not yet been implemented") - }), - SouthboundPutJobsIDStatusHandler: southbound.PutJobsIDStatusHandlerFunc(func(params southbound.PutJobsIDStatusParams) middleware.Responder { - return middleware.NotImplemented("operation southbound.PutJobsIDStatus has not yet been implemented") - }), - } -} - -/*WorkflowExecutorAPI the workflow executor API */ -type WorkflowExecutorAPI struct { - spec *loads.Document - context *middleware.Context - handlers map[string]map[string]http.Handler - formats strfmt.Registry - customConsumers map[string]runtime.Consumer - customProducers map[string]runtime.Producer - defaultConsumes string - defaultProduces string - Middleware func(middleware.Builder) http.Handler - useSwaggerUI bool - - // BasicAuthenticator generates a runtime.Authenticator from the supplied basic auth function. - // It has a default implementation in the security package, however you can replace it for your particular usage. - BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator - - // APIKeyAuthenticator generates a runtime.Authenticator from the supplied token auth function. - // It has a default implementation in the security package, however you can replace it for your particular usage. - APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator - - // BearerAuthenticator generates a runtime.Authenticator from the supplied bearer token auth function. - // It has a default implementation in the security package, however you can replace it for your particular usage. - BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator - - // JSONConsumer registers a consumer for the following mime types: - // - application/json - JSONConsumer runtime.Consumer - - // JSONProducer registers a producer for the following mime types: - // - application/json - JSONProducer runtime.Producer - // TextEventStreamProducer registers a producer for the following mime types: - // - text/event-stream - TextEventStreamProducer runtime.Producer - - // SouthboundGetJobsHandler sets the operation handler for the get jobs operation - SouthboundGetJobsHandler southbound.GetJobsHandler - // SouthboundGetJobsEventsHandler sets the operation handler for the get jobs events operation - SouthboundGetJobsEventsHandler southbound.GetJobsEventsHandler - // SouthboundGetJobsIDHandler sets the operation handler for the get jobs ID operation - SouthboundGetJobsIDHandler southbound.GetJobsIDHandler - // SouthboundGetJobsIDDefinitionHandler sets the operation handler for the get jobs ID definition operation - SouthboundGetJobsIDDefinitionHandler southbound.GetJobsIDDefinitionHandler - // SouthboundGetJobsIDStatusHandler sets the operation handler for the get jobs ID status operation - SouthboundGetJobsIDStatusHandler southbound.GetJobsIDStatusHandler - // SouthboundGetJobsIDTagsHandler sets the operation handler for the get jobs ID tags operation - SouthboundGetJobsIDTagsHandler southbound.GetJobsIDTagsHandler - // SouthboundGetWorkflowsHandler sets the operation handler for the get workflows operation - SouthboundGetWorkflowsHandler southbound.GetWorkflowsHandler - // SouthboundGetWorkflowsNameHandler sets the operation handler for the get workflows name operation - SouthboundGetWorkflowsNameHandler southbound.GetWorkflowsNameHandler - // SouthboundPutJobsIDDefinitionHandler sets the operation handler for the put jobs ID definition operation - SouthboundPutJobsIDDefinitionHandler southbound.PutJobsIDDefinitionHandler - // SouthboundPutJobsIDStatusHandler sets the operation handler for the put jobs ID status operation - SouthboundPutJobsIDStatusHandler southbound.PutJobsIDStatusHandler - - // ServeError is called when an error is received, there is a default handler - // but you can set your own with this - ServeError func(http.ResponseWriter, *http.Request, error) - - // PreServerShutdown is called before the HTTP(S) server is shutdown - // This allows for custom functions to get executed before the HTTP(S) server stops accepting traffic - PreServerShutdown func() - - // ServerShutdown is called when the HTTP(S) server is shut down and done - // handling all active connections and does not accept connections any more - ServerShutdown func() - - // Custom command line argument groups with their descriptions - CommandLineOptionsGroups []swag.CommandLineOptionsGroup - - // User defined logger function. - Logger func(string, ...interface{}) -} - -// UseRedoc for documentation at /docs -func (o *WorkflowExecutorAPI) UseRedoc() { - o.useSwaggerUI = false -} - -// UseSwaggerUI for documentation at /docs -func (o *WorkflowExecutorAPI) UseSwaggerUI() { - o.useSwaggerUI = true -} - -// SetDefaultProduces sets the default produces media type -func (o *WorkflowExecutorAPI) SetDefaultProduces(mediaType string) { - o.defaultProduces = mediaType -} - -// SetDefaultConsumes returns the default consumes media type -func (o *WorkflowExecutorAPI) SetDefaultConsumes(mediaType string) { - o.defaultConsumes = mediaType -} - -// SetSpec sets a spec that will be served for the clients. -func (o *WorkflowExecutorAPI) SetSpec(spec *loads.Document) { - o.spec = spec -} - -// DefaultProduces returns the default produces media type -func (o *WorkflowExecutorAPI) DefaultProduces() string { - return o.defaultProduces -} - -// DefaultConsumes returns the default consumes media type -func (o *WorkflowExecutorAPI) DefaultConsumes() string { - return o.defaultConsumes -} - -// Formats returns the registered string formats -func (o *WorkflowExecutorAPI) Formats() strfmt.Registry { - return o.formats -} - -// RegisterFormat registers a custom format validator -func (o *WorkflowExecutorAPI) RegisterFormat(name string, format strfmt.Format, validator strfmt.Validator) { - o.formats.Add(name, format, validator) -} - -// Validate validates the registrations in the WorkflowExecutorAPI -func (o *WorkflowExecutorAPI) Validate() error { - var unregistered []string - - if o.JSONConsumer == nil { - unregistered = append(unregistered, "JSONConsumer") - } - - if o.JSONProducer == nil { - unregistered = append(unregistered, "JSONProducer") - } - if o.TextEventStreamProducer == nil { - unregistered = append(unregistered, "TextEventStreamProducer") - } - - if o.SouthboundGetJobsHandler == nil { - unregistered = append(unregistered, "southbound.GetJobsHandler") - } - if o.SouthboundGetJobsEventsHandler == nil { - unregistered = append(unregistered, "southbound.GetJobsEventsHandler") - } - if o.SouthboundGetJobsIDHandler == nil { - unregistered = append(unregistered, "southbound.GetJobsIDHandler") - } - if o.SouthboundGetJobsIDDefinitionHandler == nil { - unregistered = append(unregistered, "southbound.GetJobsIDDefinitionHandler") - } - if o.SouthboundGetJobsIDStatusHandler == nil { - unregistered = append(unregistered, "southbound.GetJobsIDStatusHandler") - } - if o.SouthboundGetJobsIDTagsHandler == nil { - unregistered = append(unregistered, "southbound.GetJobsIDTagsHandler") - } - if o.SouthboundGetWorkflowsHandler == nil { - unregistered = append(unregistered, "southbound.GetWorkflowsHandler") - } - if o.SouthboundGetWorkflowsNameHandler == nil { - unregistered = append(unregistered, "southbound.GetWorkflowsNameHandler") - } - if o.SouthboundPutJobsIDDefinitionHandler == nil { - unregistered = append(unregistered, "southbound.PutJobsIDDefinitionHandler") - } - if o.SouthboundPutJobsIDStatusHandler == nil { - unregistered = append(unregistered, "southbound.PutJobsIDStatusHandler") - } - - if len(unregistered) > 0 { - return fmt.Errorf("missing registration: %s", strings.Join(unregistered, ", ")) - } - - return nil -} - -// ServeErrorFor gets a error handler for a given operation id -func (o *WorkflowExecutorAPI) ServeErrorFor(operationID string) func(http.ResponseWriter, *http.Request, error) { - return o.ServeError -} - -// AuthenticatorsFor gets the authenticators for the specified security schemes -func (o *WorkflowExecutorAPI) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[string]runtime.Authenticator { - return nil -} - -// Authorizer returns the registered authorizer -func (o *WorkflowExecutorAPI) Authorizer() runtime.Authorizer { - return nil -} - -// ConsumersFor gets the consumers for the specified media types. -// MIME type parameters are ignored here. -func (o *WorkflowExecutorAPI) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer { - result := make(map[string]runtime.Consumer, len(mediaTypes)) - for _, mt := range mediaTypes { - switch mt { - case "application/json": - result["application/json"] = o.JSONConsumer - } - - if c, ok := o.customConsumers[mt]; ok { - result[mt] = c - } - } - return result -} - -// ProducersFor gets the producers for the specified media types. -// MIME type parameters are ignored here. -func (o *WorkflowExecutorAPI) ProducersFor(mediaTypes []string) map[string]runtime.Producer { - result := make(map[string]runtime.Producer, len(mediaTypes)) - for _, mt := range mediaTypes { - switch mt { - case "application/json": - result["application/json"] = o.JSONProducer - case "text/event-stream": - result["text/event-stream"] = o.TextEventStreamProducer - } - - if p, ok := o.customProducers[mt]; ok { - result[mt] = p - } - } - return result -} - -// HandlerFor gets a http.Handler for the provided operation method and path -func (o *WorkflowExecutorAPI) HandlerFor(method, path string) (http.Handler, bool) { - if o.handlers == nil { - return nil, false - } - um := strings.ToUpper(method) - if _, ok := o.handlers[um]; !ok { - return nil, false - } - if path == "/" { - path = "" - } - h, ok := o.handlers[um][path] - return h, ok -} - -// Context returns the middleware context for the workflow executor API -func (o *WorkflowExecutorAPI) Context() *middleware.Context { - if o.context == nil { - o.context = middleware.NewRoutableContext(o.spec, o, nil) - } - - return o.context -} - -func (o *WorkflowExecutorAPI) initHandlerCache() { - o.Context() // don't care about the result, just that the initialization happened - if o.handlers == nil { - o.handlers = make(map[string]map[string]http.Handler) - } - - if o.handlers["GET"] == nil { - o.handlers["GET"] = make(map[string]http.Handler) - } - o.handlers["GET"]["/jobs"] = southbound.NewGetJobs(o.context, o.SouthboundGetJobsHandler) - if o.handlers["GET"] == nil { - o.handlers["GET"] = make(map[string]http.Handler) - } - o.handlers["GET"]["/jobs/events"] = southbound.NewGetJobsEvents(o.context, o.SouthboundGetJobsEventsHandler) - if o.handlers["GET"] == nil { - o.handlers["GET"] = make(map[string]http.Handler) - } - o.handlers["GET"]["/jobs/{id}"] = southbound.NewGetJobsID(o.context, o.SouthboundGetJobsIDHandler) - if o.handlers["GET"] == nil { - o.handlers["GET"] = make(map[string]http.Handler) - } - o.handlers["GET"]["/jobs/{id}/definition"] = southbound.NewGetJobsIDDefinition(o.context, o.SouthboundGetJobsIDDefinitionHandler) - if o.handlers["GET"] == nil { - o.handlers["GET"] = make(map[string]http.Handler) - } - o.handlers["GET"]["/jobs/{id}/status"] = southbound.NewGetJobsIDStatus(o.context, o.SouthboundGetJobsIDStatusHandler) - if o.handlers["GET"] == nil { - o.handlers["GET"] = make(map[string]http.Handler) - } - o.handlers["GET"]["/jobs/{id}/tags"] = southbound.NewGetJobsIDTags(o.context, o.SouthboundGetJobsIDTagsHandler) - if o.handlers["GET"] == nil { - o.handlers["GET"] = make(map[string]http.Handler) - } - o.handlers["GET"]["/workflows"] = southbound.NewGetWorkflows(o.context, o.SouthboundGetWorkflowsHandler) - if o.handlers["GET"] == nil { - o.handlers["GET"] = make(map[string]http.Handler) - } - o.handlers["GET"]["/workflows/{name}"] = southbound.NewGetWorkflowsName(o.context, o.SouthboundGetWorkflowsNameHandler) - if o.handlers["PUT"] == nil { - o.handlers["PUT"] = make(map[string]http.Handler) - } - o.handlers["PUT"]["/jobs/{id}/definition"] = southbound.NewPutJobsIDDefinition(o.context, o.SouthboundPutJobsIDDefinitionHandler) - if o.handlers["PUT"] == nil { - o.handlers["PUT"] = make(map[string]http.Handler) - } - o.handlers["PUT"]["/jobs/{id}/status"] = southbound.NewPutJobsIDStatus(o.context, o.SouthboundPutJobsIDStatusHandler) -} - -// Serve creates a http handler to serve the API over HTTP -// can be used directly in http.ListenAndServe(":8000", api.Serve(nil)) -func (o *WorkflowExecutorAPI) Serve(builder middleware.Builder) http.Handler { - o.Init() - - if o.Middleware != nil { - return o.Middleware(builder) - } - if o.useSwaggerUI { - return o.context.APIHandlerSwaggerUI(builder) - } - return o.context.APIHandler(builder) -} - -// Init allows you to just initialize the handler cache, you can then recompose the middleware as you see fit -func (o *WorkflowExecutorAPI) Init() { - if len(o.handlers) == 0 { - o.initHandlerCache() - } -} - -// RegisterConsumer allows you to add (or override) a consumer for a media type. -func (o *WorkflowExecutorAPI) RegisterConsumer(mediaType string, consumer runtime.Consumer) { - o.customConsumers[mediaType] = consumer -} - -// RegisterProducer allows you to add (or override) a producer for a media type. -func (o *WorkflowExecutorAPI) RegisterProducer(mediaType string, producer runtime.Producer) { - o.customProducers[mediaType] = producer -} - -// AddMiddlewareFor adds a http middleware to existing handler -func (o *WorkflowExecutorAPI) AddMiddlewareFor(method, path string, builder middleware.Builder) { - um := strings.ToUpper(method) - if path == "/" { - path = "" - } - o.Init() - if h, ok := o.handlers[um][path]; ok { - o.handlers[um][path] = builder(h) - } -} diff --git a/go.mod b/go.mod index e42c6e96..3832834b 100644 --- a/go.mod +++ b/go.mod @@ -10,13 +10,8 @@ require ( github.com/approvals/go-approval-tests v0.0.0-20241211183344-15d1ffb738a9 github.com/cnf/structhash v0.0.0-20201127153200-e1b16c1ebc08 github.com/coreos/go-systemd/v22 v22.5.0 - github.com/go-openapi/errors v0.22.0 - github.com/go-openapi/loads v0.22.0 - github.com/go-openapi/runtime v0.28.0 - github.com/go-openapi/spec v0.21.0 + github.com/getkin/kin-openapi v0.128.0 github.com/go-openapi/strfmt v0.23.0 - github.com/go-openapi/swag v0.23.0 - github.com/go-openapi/validate v0.24.0 github.com/go-sql-driver/mysql v1.8.1 github.com/golang-migrate/migrate/v4 v4.18.1 github.com/google/flatbuffers v24.3.25+incompatible @@ -30,7 +25,10 @@ require ( github.com/knadh/koanf/v2 v2.1.2 github.com/mattn/go-isatty v0.0.20 github.com/mattn/go-sqlite3 v1.14.24 + github.com/oapi-codegen/nethttp-middleware v1.0.2 + github.com/oapi-codegen/runtime v1.1.1 github.com/olebedev/emitter v0.0.0-20230411050614-349169dec2ba + github.com/pkg/errors v0.9.1 github.com/rs/cors v1.11.1 github.com/rs/zerolog v1.33.0 github.com/spf13/cobra v1.8.1 @@ -43,6 +41,7 @@ require ( github.com/yourbasic/graph v0.0.0-20210606180040-8ecfec1c2869 go.uber.org/automaxprocs v1.6.0 go.uber.org/goleak v1.3.0 + golang.org/x/sync v0.10.0 golang.org/x/term v0.27.0 gopkg.in/go-playground/colors.v1 v1.2.0 gopkg.in/yaml.v3 v3.0.1 @@ -55,12 +54,8 @@ require ( github.com/agext/levenshtein v1.2.3 // indirect github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/docker/go-units v0.5.0 // indirect - github.com/go-logr/logr v1.4.2 // indirect - github.com/go-logr/stdr v1.2.2 // indirect github.com/go-openapi/inflect v0.21.0 // indirect github.com/go-openapi/jsonpointer v0.21.0 // indirect - github.com/go-openapi/jsonreference v0.21.0 // indirect github.com/google/go-cmp v0.6.0 // indirect github.com/google/uuid v1.6.0 github.com/hashicorp/errwrap v1.1.0 // indirect @@ -75,11 +70,9 @@ require ( github.com/mattn/go-colorable v0.1.13 // indirect github.com/mitchellh/go-wordwrap v1.0.1 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect - github.com/opentracing/opentracing-go v1.2.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/shopspring/decimal v1.4.0 // indirect github.com/zclconf/go-cty v1.15.1 // indirect - go.opentelemetry.io/otel v1.32.0 // indirect go.opentelemetry.io/otel/trace v1.32.0 // indirect go.uber.org/atomic v1.11.0 // indirect golang.org/x/crypto v0.31.0 // indirect @@ -89,19 +82,25 @@ require ( require ( filippo.io/edwards25519 v1.1.0 // indirect + github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect github.com/bmatcuk/doublestar v1.3.4 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.4 // indirect github.com/fsnotify/fsnotify v1.8.0 // indirect - github.com/go-openapi/analysis v0.23.0 // indirect + github.com/go-openapi/errors v0.22.0 // indirect + github.com/go-openapi/swag v0.23.0 // indirect github.com/go-viper/mapstructure/v2 v2.2.1 // indirect + github.com/gorilla/mux v1.8.1 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/influxdata/tdigest v0.0.1 // indirect + github.com/invopop/yaml v0.3.1 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect github.com/knadh/koanf/maps v0.1.1 // indirect github.com/mitchellh/copystructure v1.2.0 // indirect github.com/mitchellh/reflectwalk v1.0.2 // indirect + github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect github.com/oklog/ulid v1.3.1 // indirect + github.com/perimeterx/marshmallow v1.1.5 // indirect github.com/rs/dnscache v0.0.0-20230804202142-fc85eb664529 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/stretchr/objx v0.5.2 // indirect @@ -111,7 +110,6 @@ require ( go.opentelemetry.io/otel/metric v1.32.0 // indirect golang.org/x/exp v0.0.0-20241210194714-1829a127f884 // indirect golang.org/x/net v0.32.0 // indirect - golang.org/x/sync v0.10.0 // indirect golang.org/x/sys v0.28.0 // indirect golang.org/x/tools v0.28.0 // indirect ) diff --git a/go.sum b/go.sum index e2826e84..50f71676 100644 --- a/go.sum +++ b/go.sum @@ -18,18 +18,22 @@ github.com/PaesslerAG/gval v1.2.4/go.mod h1:XRFLwvmkTEdYziLdaCeCa5ImcGVrfQbeNUbV github.com/PaesslerAG/jsonpath v0.1.0/go.mod h1:4BzmtoM/PI8fPO4aQGIusjGxGir2BzcV0grWtFzq1Y8= github.com/PaesslerAG/jsonpath v0.1.1 h1:c1/AToHQMVsduPAa4Vh6xp2U0evy4t8SWp8imEsylIk= github.com/PaesslerAG/jsonpath v0.1.1/go.mod h1:lVboNxFGal/VwW6d9JzIy56bUsYAP6tH/x80vjnCseY= +github.com/RaveNoX/go-jsoncommentstrip v1.0.0/go.mod h1:78ihd09MekBnJnxpICcwzCMzGrKSKYe4AqU6PDYYpjk= github.com/Southclaws/fault v0.8.1 h1:mgqqdC6kUBQ6ExMALZ0nNaDfNJD5h2+wq3se5mAyX+8= github.com/Southclaws/fault v0.8.1/go.mod h1:VUVkAWutC59SL16s6FTqf3I6I2z77RmnaW5XRz4bLOE= github.com/agext/levenshtein v1.2.3 h1:YB2fHEn0UJagG8T1rrWknE3ZQzWM06O8AMAatNn7lmo= github.com/agext/levenshtein v1.2.3/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= github.com/alexliesenfeld/health v0.8.0 h1:lCV0i+ZJPTbqP7LfKG7p3qZBl5VhelwUFCIVWl77fgk= github.com/alexliesenfeld/health v0.8.0/go.mod h1:TfNP0f+9WQVWMQRzvMUjlws4ceXKEL3WR+6Hp95HUFc= +github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7Dml6nw9rQ= +github.com/apapsch/go-jsonmerge/v2 v2.0.0/go.mod h1:lvDnEdqiQrp0O42VQGgmlKpxL1AP2+08jFMw88y4klk= github.com/apparentlymart/go-textseg/v15 v15.0.0 h1:uYvfpb3DyLSCGWnctWKGj857c6ew1u1fNQOlOtuGxQY= github.com/apparentlymart/go-textseg/v15 v15.0.0/go.mod h1:K8XmNZdhEBkdlyDdvbmmsvpAG721bKi0joRfFdHIWJ4= github.com/approvals/go-approval-tests v0.0.0-20241211183344-15d1ffb738a9 h1:zfQwAI2fXGieaEZTtHdxha2Uq2MywDSUe8AXzdOKBtQ= github.com/approvals/go-approval-tests v0.0.0-20241211183344-15d1ffb738a9/go.mod h1:PJOqSY8IofNv3heAD6k8E7EfFS6okiSS9bSAasaAUME= github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= +github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvFv1sNto9p6w= github.com/bmatcuk/doublestar v1.3.4 h1:gPypJ5xD31uhX6Tf54sDPUOBXTqKH4c9aPY66CyQrS0= github.com/bmatcuk/doublestar v1.3.4/go.mod h1:wiQtGV+rzVYxB7WIlirSN++5HPtPlXEo9MEoZQC/PmE= github.com/bmizerany/perks v0.0.0-20230307044200-03f9df79da1e h1:mWOqoK5jV13ChKf/aF3plwQ96laasTJgZi4f1aSOu+M= @@ -61,37 +65,26 @@ github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2 github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M= github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= -github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/getkin/kin-openapi v0.128.0 h1:jqq3D9vC9pPq1dGcOCv7yOp1DaEe7c/T1vzcLbITSp4= +github.com/getkin/kin-openapi v0.128.0/go.mod h1:OZrfXzUfGrNbsKj+xmFBx6E5c6yH3At/tAKSc2UszXM= github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= -github.com/go-openapi/analysis v0.23.0 h1:aGday7OWupfMs+LbmLZG4k0MYXIANxcuBTYUC03zFCU= -github.com/go-openapi/analysis v0.23.0/go.mod h1:9mz9ZWaSlV8TvjQHLl2mUW2PbZtemkE8yA5v22ohupo= github.com/go-openapi/errors v0.22.0 h1:c4xY/OLxUBSTiepAg3j/MHuAv5mJhnf53LLMWFB+u/w= github.com/go-openapi/errors v0.22.0/go.mod h1:J3DmZScxCDufmIMsdOuDHxJbdOGC0xtUynjIx092vXE= github.com/go-openapi/inflect v0.21.0 h1:FoBjBTQEcbg2cJUWX6uwL9OyIW8eqc9k4KhN4lfbeYk= github.com/go-openapi/inflect v0.21.0/go.mod h1:INezMuUu7SJQc2AyR3WO0DqqYUJSj8Kb4hBd7WtjlAw= github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ= github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY= -github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ= -github.com/go-openapi/jsonreference v0.21.0/go.mod h1:LmZmgsrTkVg9LG4EaHeY8cBDslNPMo06cago5JNLkm4= -github.com/go-openapi/loads v0.22.0 h1:ECPGd4jX1U6NApCGG1We+uEozOAvXvJSF4nnwHZ8Aco= -github.com/go-openapi/loads v0.22.0/go.mod h1:yLsaTCS92mnSAZX5WWoxszLj0u+Ojl+Zs5Stn1oF+rs= -github.com/go-openapi/runtime v0.28.0 h1:gpPPmWSNGo214l6n8hzdXYhPuJcGtziTOgUpvsFWGIQ= -github.com/go-openapi/runtime v0.28.0/go.mod h1:QN7OzcS+XuYmkQLw05akXk0jRH/eZ3kb18+1KwW9gyc= -github.com/go-openapi/spec v0.21.0 h1:LTVzPc3p/RzRnkQqLRndbAzjY0d0BCL72A6j3CdL9ZY= -github.com/go-openapi/spec v0.21.0/go.mod h1:78u6VdPw81XU44qEWGhtr982gJ5BWg2c0I5XwVMotYk= github.com/go-openapi/strfmt v0.23.0 h1:nlUS6BCqcnAk0pyhi9Y+kdDVZdZMHfEKQiS4HaMgO/c= github.com/go-openapi/strfmt v0.23.0/go.mod h1:NrtIpfKtWIygRkKVsxh7XQMDQW5HKQl6S5ik2elW+K4= github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE= github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ= -github.com/go-openapi/validate v0.24.0 h1:LdfDKwNbpB6Vn40xhTdNZAnfLECL81w+VX3BumrGD58= -github.com/go-openapi/validate v0.24.0/go.mod h1:iyeX1sEufmv3nPbBdX3ieNviWnOZaJ1+zquzJEf2BAQ= github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= -github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68= -github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA= +github.com/go-test/deep v1.0.8 h1:TDsG77qcSprGbC6vTN8OuXp5g+J+b5Pcguhf7Zt61VM= +github.com/go-test/deep v1.0.8/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE= github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss= github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= @@ -108,6 +101,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0= github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w= +github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= +github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= @@ -119,6 +114,8 @@ github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2 github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/influxdata/tdigest v0.0.1 h1:XpFptwYmnEKUqmkcDjrzffswZ3nvNeevbUSLPP/ZzIY= github.com/influxdata/tdigest v0.0.1/go.mod h1:Z0kXnxzbTC2qrx4NaIzYkE1k66+6oEDQTvL95hQFh5Y= +github.com/invopop/yaml v0.3.1 h1:f0+ZpmhfBSS4MhG+4HYseMdJhoeeopbSKbq5Rpeelso= +github.com/invopop/yaml v0.3.1/go.mod h1:PMOp3nn4/12yEZUFfmOuNHJsZToEEOwoWsT+D81KkeA= github.com/itchyny/gojq v0.12.17 h1:8av8eGduDb5+rvEdaOO+zQUjA04MS0m3Ps8HiD+fceg= github.com/itchyny/gojq v0.12.17/go.mod h1:WBrEMkgAfAGO1LUcGOckBl5O726KPp+OlkKug0I/FEY= github.com/itchyny/timefmt-go v0.1.6 h1:ia3s54iciXDdzWzwaVKXZPbiXzxxnv1SPGFfM/myJ5Q= @@ -135,6 +132,7 @@ github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/juju/gnuflag v0.0.0-20171113085948-2ce1bb71843d/go.mod h1:2PavIy+JPciBPrBUjwbNvtwB6RQlve+hkpll6QSNmOE= github.com/knadh/koanf/maps v0.1.1 h1:G5TjmUh2D7G2YWf5SQQqSiHRJEjaicvU0KpypqB3NIs= github.com/knadh/koanf/maps v0.1.1/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI= github.com/knadh/koanf/parsers/yaml v0.1.0 h1:ZZ8/iGfRLvKSaMEECEBPM1HQslrZADk8fP1XFUxVI5w= @@ -175,8 +173,14 @@ github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3N github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0= github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y= +github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw= +github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8= github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A= github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= +github.com/oapi-codegen/nethttp-middleware v1.0.2 h1:A5tfAcKJhWIbIPnlQH+l/DtfVE1i5TFgPlQAiW+l1vQ= +github.com/oapi-codegen/nethttp-middleware v1.0.2/go.mod h1:DfDalonSO+eRQ3RTb8kYoWZByCCPFRxm9WKq1UbY0E4= +github.com/oapi-codegen/runtime v1.1.1 h1:EXLHh0DXIJnWhdRPN2w4MXAzFyE4CskzhNLUmtpMYro= +github.com/oapi-codegen/runtime v1.1.1/go.mod h1:SK9X900oXmPWilYR5/WKPzt3Kqxn/uS/+lbpREv+eCg= github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/olebedev/emitter v0.0.0-20230411050614-349169dec2ba h1:/Q5vvLs180BFH7u+Nakdrr1B9O9RAxVaIurFQy0c8QQ= @@ -185,8 +189,8 @@ github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8 github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug= github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM= -github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs= -github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= +github.com/perimeterx/marshmallow v1.1.5 h1:a2LALqQ1BlHM8PZblsDdidgv1mWi1DgC2UmX50IvK2s= +github.com/perimeterx/marshmallow v1.1.5/go.mod h1:dsXbUu8CRzfYP5a87xpp0xq9S3u0Vchtcl8we9tYaXw= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= @@ -211,6 +215,7 @@ github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM= github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spkg/bom v0.0.0-20160624110644-59b7046e48ad/go.mod h1:qLr4V1qq6nMqFKkMo8ZTx3f+BZEkzsRUY10Xsm2mwU0= github.com/steinfletcher/apitest v1.5.10/go.mod h1:cf7Bneo52IIAgpqhP8xaLlzWgAiQ9fHtsDMjeDnZ3so= github.com/steinfletcher/apitest v1.5.17 h1:nlrfVNLN/g6T2GxDnjfK+QTeQ2be1SNAt8VkAy5twLQ= github.com/steinfletcher/apitest v1.5.17/go.mod h1:mF+KnYaIkuHM0C4JgGzkIIOJAEjo+EA5tTjJ+bHXnQc= @@ -233,6 +238,8 @@ github.com/tsenart/go-tsz v0.0.0-20180814235614-0bd30b3df1c3 h1:pcQGQzTwCg//7FgV github.com/tsenart/go-tsz v0.0.0-20180814235614-0bd30b3df1c3/go.mod h1:SWZznP1z5Ki7hDT2ioqiFKEse8K9tU2OUvaRI0NeGQo= github.com/tsenart/vegeta/v12 v12.12.0 h1:FKMMNomd3auAElO/TtbXzRFXAKGee6N/GKCGweFVm2U= github.com/tsenart/vegeta/v12 v12.12.0/go.mod h1:gpdfR++WHV9/RZh4oux0f6lNPhsOH8pCjIGUlcPQe1M= +github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU= +github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= github.com/yourbasic/graph v0.0.0-20210606180040-8ecfec1c2869 h1:7v7L5lsfw4w8iqBBXETukHo4IPltmD+mWoLRYUmeGN8= @@ -249,8 +256,6 @@ go.opentelemetry.io/otel v1.32.0 h1:WnBN+Xjcteh0zdk01SVqV55d/m62NJLJdIyb4y/WO5U= go.opentelemetry.io/otel v1.32.0/go.mod h1:00DCVSB0RQcnzlwyTfqtxSm+DRr9hpYrHjNGiBHVQIg= go.opentelemetry.io/otel/metric v1.32.0 h1:xV2umtmNcThh2/a/aCP+h64Xx5wsj8qqnkYZktzNa0M= go.opentelemetry.io/otel/metric v1.32.0/go.mod h1:jH7CIbbK6SH2V2wE16W05BHCtIDzauciCRLoc/SyMv8= -go.opentelemetry.io/otel/sdk v1.29.0 h1:vkqKjk7gwhS8VaWb0POZKmIEDimRCMsopNYnriHyryo= -go.opentelemetry.io/otel/sdk v1.29.0/go.mod h1:pM8Dx5WKnvxLCb+8lG1PRNIDxu9g9b9g59Qr7hfAAok= go.opentelemetry.io/otel/trace v1.32.0 h1:WIC9mYrXf8TmY/EXuULKc8hR17vE+Hjv2cssQDe03fM= go.opentelemetry.io/otel/trace v1.32.0/go.mod h1:+i4rkvCraA+tG6AzwloGaCtkx53Fa+L+V8e9a7YvhT8= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= diff --git a/hugo/.gitignore b/hugo/.gitignore index f02d79b9..685087fe 100644 --- a/hugo/.gitignore +++ b/hugo/.gitignore @@ -20,7 +20,7 @@ content/docs/use-cases.md static/benchmark.png static/favicons/ -static/wfx.swagger.yml +static/wfx.openapi.yml static/wfx.workflow.dau.direct.yml static/wfx.workflow.dau.phased.yml static/wfx.workflow.config.deployment.yml diff --git a/hugo/content/docs/api.md b/hugo/content/docs/api.md index ecbfe2fa..ced2f785 100644 --- a/hugo/content/docs/api.md +++ b/hugo/content/docs/api.md @@ -3,4 +3,4 @@ title = "REST API" type = "swagger" +++ -{{< swaggerui src="/wfx/wfx.swagger.yml" >}} +{{< swaggerui src="/wfx/wfx.openapiv3.yml" >}} diff --git a/internal/cmd/man/cmd.go b/internal/cmd/man/cmd.go index cc21dfd1..3870e932 100644 --- a/internal/cmd/man/cmd.go +++ b/internal/cmd/man/cmd.go @@ -16,9 +16,10 @@ import ( "github.com/spf13/cobra/doc" ) -var ( - manDir string - Command = &cobra.Command{ +var manDir string + +func NewCommand() *cobra.Command { + cmd := &cobra.Command{ Use: "man", Short: "Generate man pages and exit", RunE: func(cmd *cobra.Command, _ []string) error { @@ -33,10 +34,8 @@ var ( return nil }, } -) - -func init() { - Command.Flags().StringVar(&manDir, "dir", "man", "directory to store the man page files") + cmd.Flags().StringVar(&manDir, "dir", "man", "directory to store the man page files") + return cmd } func disableAutoGenTag(cmd *cobra.Command) { diff --git a/internal/cmd/man/cmd_test.go b/internal/cmd/man/cmd_test.go index f9eb37bf..2d1f3837 100644 --- a/internal/cmd/man/cmd_test.go +++ b/internal/cmd/man/cmd_test.go @@ -24,7 +24,7 @@ func TestExecuteCommand(t *testing.T) { Short: "a command for testing purposes", TraverseChildren: true, } - dummy.AddCommand(Command) + dummy.AddCommand(NewCommand()) flags := dummy.PersistentFlags() flags.String("foo", "bar", "example argument") diff --git a/internal/config/koanf.go b/internal/config/koanf.go deleted file mode 100644 index 0b2d11da..00000000 --- a/internal/config/koanf.go +++ /dev/null @@ -1,41 +0,0 @@ -package config - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "sync" - - "github.com/knadh/koanf/v2" -) - -// ThreadSafeKoanf is a thread-safe wrapper around Koanf. -type ThreadSafeKoanf struct { - instance *koanf.Koanf - sync.RWMutex -} - -func New() *ThreadSafeKoanf { - result := new(ThreadSafeKoanf) - result.instance = koanf.New(".") - return result -} - -// Read provides thread-safe read access to the Koanf instance. -func (t *ThreadSafeKoanf) Read(cb func(k *koanf.Koanf)) { - t.RLock() - defer t.RUnlock() - cb(t.instance) -} - -// Write provides thread-safe write access to the Koanf instance. -func (t *ThreadSafeKoanf) Write(cb func(k *koanf.Koanf)) { - t.Lock() - defer t.Unlock() - cb(t.instance) -} diff --git a/internal/config/koanf_test.go b/internal/config/koanf_test.go deleted file mode 100644 index 3b1580ca..00000000 --- a/internal/config/koanf_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package config - -import ( - "testing" - - "github.com/knadh/koanf/v2" - "github.com/stretchr/testify/assert" -) - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -func TestReadAndWrite(t *testing.T) { - cfg := New() - cfg.Write(func(k *koanf.Koanf) { - _ = k.Set("hello", "world") - }) - var actual string - cfg.Read(func(k *koanf.Koanf) { - actual = k.String("hello") - }) - assert.Equal(t, "world", actual) -} diff --git a/internal/errutil/main_test.go b/internal/errutil/main_test.go deleted file mode 100644 index 368b8c47..00000000 --- a/internal/errutil/main_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package errutil - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "testing" - - "go.uber.org/goleak" -) - -func TestMain(m *testing.M) { - goleak.VerifyTestMain(m) -} diff --git a/internal/errutil/wrap.go b/internal/errutil/wrap.go deleted file mode 100644 index 2d64e975..00000000 --- a/internal/errutil/wrap.go +++ /dev/null @@ -1,17 +0,0 @@ -package errutil - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import "github.com/Southclaws/fault" - -// Wrap2 wraps the provided error using fault.Wrap and returns -// the original value along with the wrapped error. -func Wrap2[T any](value T, err error) (T, error) { - return value, fault.Wrap(err) -} diff --git a/internal/errutil/wrap_test.go b/internal/errutil/wrap_test.go deleted file mode 100644 index 40f018f2..00000000 --- a/internal/errutil/wrap_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package errutil - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "errors" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestWrap2(t *testing.T) { - t.Parallel() - - t.Run("no error", func(t *testing.T) { - t.Parallel() - - val, err := Wrap2("foo", nil) - assert.Equal(t, "foo", val) - assert.Nil(t, err) - }) - - t.Run("error", func(t *testing.T) { - t.Parallel() - - val, err := Wrap2[any](nil, errors.New("test")) - assert.Nil(t, val) - assert.NotNil(t, err) - }) - - t.Run("both", func(t *testing.T) { - t.Parallel() - - val, err := Wrap2("foo", errors.New("test")) - assert.Equal(t, "foo", val) - assert.NotNil(t, err) - }) -} diff --git a/internal/handler/job/create.go b/internal/handler/job/create.go index 9e3b7f51..1a50320c 100644 --- a/internal/handler/job/create.go +++ b/internal/handler/job/create.go @@ -16,7 +16,7 @@ import ( "github.com/Southclaws/fault" "github.com/Southclaws/fault/ftag" "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/internal/handler/job/definition" "github.com/siemens/wfx/internal/handler/job/events" "github.com/siemens/wfx/internal/workflow" @@ -24,7 +24,7 @@ import ( "github.com/siemens/wfx/persistence" ) -func CreateJob(ctx context.Context, storage persistence.Storage, request *model.JobRequest) (*model.Job, error) { +func CreateJob(ctx context.Context, storage persistence.Storage, request *api.JobRequest) (*api.Job, error) { log := logging.LoggerFromCtx(ctx) contextLogger := log.With().Str("clientId", request.ClientID).Str("name", request.Workflow).Logger() @@ -41,27 +41,22 @@ func CreateJob(ctx context.Context, storage persistence.Storage, request *model. } initialState := workflow.FollowImmediateTransitions(wf, *initial) - now := strfmt.DateTime(time.Now()) - job := model.Job{ + now := time.Now() + job := api.Job{ ClientID: request.ClientID, Workflow: wf, Mtime: &now, Stime: &now, - Status: &model.JobStatus{ + Status: &api.JobStatus{ ClientID: request.ClientID, State: initialState, }, Definition: request.Definition, Tags: request.Tags, - History: []*model.History{}, + History: &[]api.History{}, } job.Status.DefinitionHash = definition.Hash(&job) - if err := job.Validate(strfmt.Default); err != nil { - log.Error().Err(err).Msg("Job validation failed") - return nil, fault.Wrap(err) - } - createdJob, err := storage.CreateJob(ctx, &job) if err != nil { contextLogger.Error().Err(err).Msg("Failed to persist job") @@ -74,6 +69,6 @@ func CreateJob(ctx context.Context, storage persistence.Storage, request *model. Job: createdJob, }) - contextLogger.Info().Str("id", job.ID).Msg("Created new job") + contextLogger.Info().Str("id", createdJob.ID).Msg("Created new job") return createdJob, nil } diff --git a/internal/handler/job/create_test.go b/internal/handler/job/create_test.go index 00cf6c57..4b4773b7 100644 --- a/internal/handler/job/create_test.go +++ b/internal/handler/job/create_test.go @@ -12,7 +12,7 @@ import ( "context" "testing" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/internal/handler/job/events" "github.com/siemens/wfx/internal/persistence/entgo" "github.com/siemens/wfx/persistence" @@ -25,7 +25,7 @@ func TestCreateJob(t *testing.T) { db := newInMemoryDB(t) wf := createDirectWorkflow(t, db) - job, err := CreateJob(context.Background(), db, &model.JobRequest{ + job, err := CreateJob(context.Background(), db, &api.JobRequest{ ClientID: "foo", Workflow: wf.Name, }) @@ -42,7 +42,7 @@ func TestCreateJob_Notification(t *testing.T) { ch, err := events.AddSubscriber(context.Background(), events.FilterParams{}, nil) require.NoError(t, err) - job, err := CreateJob(context.Background(), db, &model.JobRequest{ + job, err := CreateJob(context.Background(), db, &api.JobRequest{ ClientID: "foo", Workflow: wf.Name, }) @@ -56,7 +56,7 @@ func TestCreateJob_Notification(t *testing.T) { func newInMemoryDB(t *testing.T) persistence.Storage { db := &entgo.SQLite{} - err := db.Initialize(context.Background(), "file:wfx?mode=memory&cache=shared&_fk=1") + err := db.Initialize("file:wfx?mode=memory&cache=shared&_fk=1") require.NoError(t, err) t.Cleanup(db.Shutdown) @@ -70,7 +70,7 @@ func newInMemoryDB(t *testing.T) persistence.Storage { } } { - list, _ := db.QueryWorkflows(context.Background(), persistence.PaginationParams{Limit: 100}) + list, _ := db.QueryWorkflows(context.Background(), persistence.SortParams{}, persistence.PaginationParams{Limit: 100}) for _, wf := range list.Content { _ = db.DeleteWorkflow(context.Background(), wf.Name) } @@ -79,7 +79,7 @@ func newInMemoryDB(t *testing.T) persistence.Storage { return db } -func createDirectWorkflow(t *testing.T, db persistence.Storage) *model.Workflow { +func createDirectWorkflow(t *testing.T, db persistence.Storage) *api.Workflow { wf, err := db.CreateWorkflow(context.Background(), dau.DirectWorkflow()) require.NoError(t, err) return wf diff --git a/internal/handler/job/definition/get_test.go b/internal/handler/job/definition/get_test.go index fd9c54db..c73240c6 100644 --- a/internal/handler/job/definition/get_test.go +++ b/internal/handler/job/definition/get_test.go @@ -13,7 +13,7 @@ import ( "testing" "github.com/Southclaws/fault/ftag" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/internal/persistence/entgo" "github.com/siemens/wfx/persistence" "github.com/siemens/wfx/workflow/dau" @@ -26,10 +26,10 @@ func TestGetJobDefinition(t *testing.T) { wf, err := db.CreateWorkflow(context.Background(), dau.PhasedWorkflow()) require.NoError(t, err) - job, err := db.CreateJob(context.Background(), &model.Job{ + job, err := db.CreateJob(context.Background(), &api.Job{ ClientID: "abc", Workflow: wf, - Status: &model.JobStatus{State: "CREATED"}, + Status: &api.JobStatus{State: "CREATED"}, Definition: map[string]any{ "foo": "bar", }, @@ -50,7 +50,7 @@ func TestGetJobDefinition_NotFound(t *testing.T) { func newInMemoryDB(t *testing.T) persistence.Storage { db := &entgo.SQLite{} - err := db.Initialize(context.Background(), "file:wfx?mode=memory&cache=shared&_fk=1") + err := db.Initialize("file:wfx?mode=memory&cache=shared&_fk=1") require.NoError(t, err) t.Cleanup(db.Shutdown) t.Cleanup(func() { @@ -62,7 +62,7 @@ func newInMemoryDB(t *testing.T) persistence.Storage { } } { - list, _ := db.QueryWorkflows(context.Background(), persistence.PaginationParams{Limit: 100}) + list, _ := db.QueryWorkflows(context.Background(), persistence.SortParams{}, persistence.PaginationParams{Limit: 100}) for _, wf := range list.Content { _ = db.DeleteWorkflow(context.Background(), wf.Name) } diff --git a/internal/handler/job/definition/update.go b/internal/handler/job/definition/update.go index 34c502b0..50c5a124 100644 --- a/internal/handler/job/definition/update.go +++ b/internal/handler/job/definition/update.go @@ -17,7 +17,7 @@ import ( "github.com/Southclaws/fault" "github.com/cnf/structhash" "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/internal/handler/job/events" "github.com/siemens/wfx/middleware/logging" "github.com/siemens/wfx/persistence" @@ -45,12 +45,12 @@ func Update(ctx context.Context, storage persistence.Storage, jobID string, defi _ = events.PublishEvent(ctx, &events.JobEvent{ Ctime: strfmt.DateTime(time.Now()), Action: events.ActionUpdateDefinition, - Job: &model.Job{ + Job: &api.Job{ ID: result.ID, ClientID: result.ClientID, - Workflow: &model.Workflow{Name: job.Workflow.Name}, + Workflow: &api.Workflow{Name: job.Workflow.Name}, Definition: result.Definition, - Status: &model.JobStatus{ + Status: &api.JobStatus{ DefinitionHash: result.Status.DefinitionHash, }, }, @@ -60,7 +60,7 @@ func Update(ctx context.Context, storage persistence.Storage, jobID string, defi return result.Definition, nil } -func Hash(job *model.Job) string { +func Hash(job *api.Job) string { hasher := sha256.New() hasher.Write(structhash.Dump(job.Definition, 1)) return fmt.Sprintf("%x", hasher.Sum(nil)) diff --git a/internal/handler/job/definition/update_test.go b/internal/handler/job/definition/update_test.go index d0f4b70c..be6a2a05 100644 --- a/internal/handler/job/definition/update_test.go +++ b/internal/handler/job/definition/update_test.go @@ -13,7 +13,7 @@ import ( "testing" "github.com/Southclaws/fault/ftag" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/internal/handler/job/events" "github.com/siemens/wfx/persistence" "github.com/siemens/wfx/workflow/dau" @@ -27,10 +27,10 @@ func TestUpdateJobDefinition(t *testing.T) { wf, err := db.CreateWorkflow(context.Background(), dau.PhasedWorkflow()) require.NoError(t, err) - tmpJob := model.Job{ + tmpJob := api.Job{ ClientID: "abc", Workflow: wf, - Status: &model.JobStatus{ClientID: "abc", State: "CREATED"}, + Status: &api.JobStatus{ClientID: "abc", State: "CREATED"}, Definition: map[string]any{ "foo": "bar", }, diff --git a/internal/handler/job/delete.go b/internal/handler/job/delete.go index 7baf34be..ccb6c734 100644 --- a/internal/handler/job/delete.go +++ b/internal/handler/job/delete.go @@ -14,7 +14,7 @@ import ( "github.com/Southclaws/fault" "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/internal/handler/job/events" "github.com/siemens/wfx/middleware/logging" "github.com/siemens/wfx/persistence" @@ -37,10 +37,10 @@ func DeleteJob(ctx context.Context, storage persistence.Storage, jobID string) e _ = events.PublishEvent(ctx, &events.JobEvent{ Ctime: strfmt.DateTime(time.Now()), Action: events.ActionDelete, - Job: &model.Job{ + Job: &api.Job{ ID: jobID, ClientID: job.ClientID, - Workflow: &model.Workflow{Name: job.Workflow.Name}, + Workflow: &api.Workflow{Name: job.Workflow.Name}, }, }) diff --git a/internal/handler/job/delete_test.go b/internal/handler/job/delete_test.go index 99212cf1..6a515c17 100644 --- a/internal/handler/job/delete_test.go +++ b/internal/handler/job/delete_test.go @@ -14,7 +14,7 @@ import ( "testing" "github.com/Southclaws/fault/ftag" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/internal/handler/job/events" "github.com/siemens/wfx/persistence" "github.com/stretchr/testify/assert" @@ -48,10 +48,10 @@ func TestDeleteJob_NotFound(t *testing.T) { } func TestDeleteJob_Error(t *testing.T) { - dbMock := persistence.NewMockStorage(t) + dbMock := persistence.NewHealthyMockStorage(t) ctx := context.Background() jobID := "42" - dbMock.EXPECT().GetJob(ctx, jobID, persistence.FetchParams{History: false}).Return(&model.Job{ID: jobID}, nil) + dbMock.EXPECT().GetJob(ctx, jobID, persistence.FetchParams{History: false}).Return(&api.Job{ID: jobID}, nil) dbMock.EXPECT().DeleteJob(ctx, jobID).Return(errors.New("something went wrong")) err := DeleteJob(ctx, dbMock, jobID) assert.Equal(t, ftag.Internal, ftag.Get(err)) diff --git a/internal/handler/job/events/events.go b/internal/handler/job/events/events.go index 1d5e2117..2329b606 100644 --- a/internal/handler/job/events/events.go +++ b/internal/handler/job/events/events.go @@ -16,7 +16,7 @@ import ( "github.com/olebedev/emitter" "github.com/rs/zerolog" "github.com/rs/zerolog/log" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/middleware/logging" ) @@ -24,7 +24,7 @@ type JobEvent struct { // Ctime is the time when the event was created Ctime strfmt.DateTime `json:"ctime"` Action Action `json:"action"` - Job *model.Job `json:"job"` + Job *api.Job `json:"job"` Tags []string `json:"tags"` } @@ -72,11 +72,12 @@ func AddSubscriber(ctx context.Context, filter FilterParams, tags []string) (<-c // ShutdownSubscribers disconnects all subscribers. func ShutdownSubscribers() { + count := len(e.Topics()) for _, topic := range e.Topics() { log.Debug().Str("topic", topic).Msg("Closing subscribers") e.Off(topic) } - log.Info().Msg("Unsubscribed all subscribers") + log.Info().Int("count", count).Msg("Subscriber shutdown complete") } // SubscriberCount counts the total number of subscribers across all topics. diff --git a/internal/handler/job/events/events_test.go b/internal/handler/job/events/events_test.go index a9b1e799..745b7206 100644 --- a/internal/handler/job/events/events_test.go +++ b/internal/handler/job/events/events_test.go @@ -13,7 +13,7 @@ import ( "testing" "github.com/olebedev/emitter" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -29,8 +29,8 @@ func TestAddSubscriberAndShutdown(t *testing.T) { } func TestFiltering(t *testing.T) { - job1 := model.Job{ID: "1", Workflow: &model.Workflow{Name: "workflow"}, Status: &model.JobStatus{State: "INITIAL"}} - job2 := model.Job{ID: "2", Workflow: &model.Workflow{Name: "workflow"}, Status: &model.JobStatus{State: "INITIAL"}} + job1 := api.Job{ID: "1", Workflow: &api.Workflow{Name: "workflow"}, Status: &api.JobStatus{State: "INITIAL"}} + job2 := api.Job{ID: "2", Workflow: &api.Workflow{Name: "workflow"}, Status: &api.JobStatus{State: "INITIAL"}} ctx := context.Background() ch1, _ := AddSubscriber(ctx, FilterParams{JobIDs: []string{job1.ID}}, nil) diff --git a/internal/handler/job/get.go b/internal/handler/job/get.go index c382df1c..cea36b40 100644 --- a/internal/handler/job/get.go +++ b/internal/handler/job/get.go @@ -12,12 +12,12 @@ import ( "context" "github.com/Southclaws/fault" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/middleware/logging" "github.com/siemens/wfx/persistence" ) -func GetJob(ctx context.Context, storage persistence.Storage, id string, history bool) (*model.Job, error) { +func GetJob(ctx context.Context, storage persistence.Storage, id string, history bool) (*api.Job, error) { fetchParams := persistence.FetchParams{History: history} job, err := storage.GetJob(ctx, id, fetchParams) if err != nil { diff --git a/internal/handler/job/get_test.go b/internal/handler/job/get_test.go index 8ba8a3f1..a7d058af 100644 --- a/internal/handler/job/get_test.go +++ b/internal/handler/job/get_test.go @@ -14,7 +14,7 @@ import ( "time" "github.com/Southclaws/fault/ftag" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/stretchr/testify/assert" ) @@ -26,7 +26,7 @@ func TestGetJob(t *testing.T) { var jobID string { - job, err := CreateJob(context.Background(), db, &model.JobRequest{ + job, err := CreateJob(context.Background(), db, &api.JobRequest{ ClientID: "foo", Workflow: wf.Name, Definition: map[string]interface{}{"foo": "bar"}, diff --git a/internal/handler/job/query.go b/internal/handler/job/query.go index 820099b4..06ab8a6a 100644 --- a/internal/handler/job/query.go +++ b/internal/handler/job/query.go @@ -13,12 +13,12 @@ import ( "strings" "github.com/Southclaws/fault" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/middleware/logging" "github.com/siemens/wfx/persistence" ) -func QueryJobs(ctx context.Context, storage persistence.Storage, filterParams persistence.FilterParams, paginationParams persistence.PaginationParams, sort *string) (*model.PaginatedJobList, error) { +func QueryJobs(ctx context.Context, storage persistence.Storage, filterParams persistence.FilterParams, paginationParams persistence.PaginationParams, sort *string) (*api.PaginatedJobList, error) { log := logging.LoggerFromCtx(ctx) var sortParams persistence.SortParams diff --git a/internal/handler/job/query_test.go b/internal/handler/job/query_test.go index ac88dc79..b902bdd1 100644 --- a/internal/handler/job/query_test.go +++ b/internal/handler/job/query_test.go @@ -12,7 +12,7 @@ import ( "context" "testing" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/persistence" "github.com/siemens/wfx/workflow/dau" "github.com/stretchr/testify/assert" @@ -49,16 +49,13 @@ func TestParseSortParamDesc(t *testing.T) { assert.Equal(t, true, sp.Desc) } -func newValidJob(clientID, state string) model.Job { +func newValidJob(clientID, state string) api.Job { wf := dau.DirectWorkflow() - return model.Job{ + return api.Job{ ClientID: clientID, - Status: &model.JobStatus{ - State: state, - Progress: 0, - Message: "", + Status: &api.JobStatus{ + State: state, }, Workflow: wf, - History: []*model.History{}, } } diff --git a/internal/handler/job/status/get.go b/internal/handler/job/status/get.go index ac084873..43448c75 100644 --- a/internal/handler/job/status/get.go +++ b/internal/handler/job/status/get.go @@ -12,12 +12,12 @@ import ( "context" "github.com/Southclaws/fault" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/middleware/logging" "github.com/siemens/wfx/persistence" ) -func Get(ctx context.Context, storage persistence.Storage, jobID string) (*model.JobStatus, error) { +func Get(ctx context.Context, storage persistence.Storage, jobID string) (*api.JobStatus, error) { log := logging.LoggerFromCtx(ctx) contextLogger := log.With().Str("id", jobID).Logger() contextLogger.Debug().Msg("Fetching status") diff --git a/internal/handler/job/status/get_test.go b/internal/handler/job/status/get_test.go index 3daff170..ed3fd5f0 100644 --- a/internal/handler/job/status/get_test.go +++ b/internal/handler/job/status/get_test.go @@ -13,7 +13,7 @@ import ( "testing" "github.com/Southclaws/fault/ftag" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/internal/persistence/entgo" "github.com/siemens/wfx/persistence" "github.com/siemens/wfx/workflow/dau" @@ -27,10 +27,10 @@ func TestGetJobStatus(t *testing.T) { wf, err := db.CreateWorkflow(context.Background(), dau.PhasedWorkflow()) require.NoError(t, err) - tmpJob := model.Job{ + tmpJob := api.Job{ ClientID: "foo", Workflow: wf, - Status: &model.JobStatus{State: "CREATED"}, + Status: &api.JobStatus{State: "CREATED"}, } job, err := db.CreateJob(context.Background(), &tmpJob) @@ -51,7 +51,7 @@ func TestGetJobStatus_NotFound(t *testing.T) { func newInMemoryDB(t *testing.T) persistence.Storage { db := &entgo.SQLite{} - err := db.Initialize(context.Background(), "file:wfx?mode=memory&cache=shared&_fk=1") + err := db.Initialize("file:wfx?mode=memory&cache=shared&_fk=1") require.NoError(t, err) t.Cleanup(db.Shutdown) @@ -65,7 +65,7 @@ func newInMemoryDB(t *testing.T) persistence.Storage { } } { - list, _ := db.QueryWorkflows(context.Background(), persistence.PaginationParams{Limit: 100}) + list, _ := db.QueryWorkflows(context.Background(), persistence.SortParams{Desc: false}, persistence.PaginationParams{Limit: 100}) for _, wf := range list.Content { _ = db.DeleteWorkflow(context.Background(), wf.Name) } diff --git a/internal/handler/job/status/update.go b/internal/handler/job/status/update.go index c82e6cf4..542af67d 100644 --- a/internal/handler/job/status/update.go +++ b/internal/handler/job/status/update.go @@ -16,14 +16,14 @@ import ( "github.com/Southclaws/fault" "github.com/Southclaws/fault/ftag" "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/internal/handler/job/events" "github.com/siemens/wfx/internal/workflow" "github.com/siemens/wfx/middleware/logging" "github.com/siemens/wfx/persistence" ) -func Update(ctx context.Context, storage persistence.Storage, jobID string, newStatus *model.JobStatus, actor model.EligibleEnum) (*model.JobStatus, error) { +func Update(ctx context.Context, storage persistence.Storage, jobID string, newStatus *api.JobStatus, actor api.EligibleEnum) (*api.JobStatus, error) { contextLogger := logging.LoggerFromCtx(ctx).With().Str("id", jobID).Str("actor", string(actor)).Logger() job, err := storage.GetJob(ctx, jobID, persistence.FetchParams{History: false}) @@ -66,7 +66,7 @@ func Update(ctx context.Context, storage persistence.Storage, jobID string, newS newTo := workflow.FollowImmediateTransitions(job.Workflow, to) if newTo != to { contextLogger.Debug().Str("to", to).Str("newTo", newTo).Msg("Resetting state since we moved the transition forward") - newStatus = &model.JobStatus{} + newStatus = &api.JobStatus{} } newStatus.State = newTo // override any definitionHash provided by client @@ -81,10 +81,10 @@ func Update(ctx context.Context, storage persistence.Storage, jobID string, newS _ = events.PublishEvent(ctx, &events.JobEvent{ Ctime: strfmt.DateTime(time.Now()), Action: events.ActionUpdateStatus, - Job: &model.Job{ + Job: &api.Job{ ID: result.ID, ClientID: result.ClientID, - Workflow: &model.Workflow{Name: job.Workflow.Name}, + Workflow: &api.Workflow{Name: job.Workflow.Name}, Status: result.Status, }, }) diff --git a/internal/handler/job/status/update_test.go b/internal/handler/job/status/update_test.go index 9059dff0..8144be33 100644 --- a/internal/handler/job/status/update_test.go +++ b/internal/handler/job/status/update_test.go @@ -16,7 +16,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/internal/handler/job/events" "github.com/siemens/wfx/persistence" "github.com/siemens/wfx/workflow/dau" @@ -25,14 +25,14 @@ import ( type testCase struct { from string to string - eligible model.EligibleEnum + eligible api.EligibleEnum expected string } func TestUpdateJob_Ok(t *testing.T) { tcs := []testCase{ - {from: "INSTALLING", to: "TERMINATED", eligible: model.EligibleEnumCLIENT, expected: "TERMINATED"}, - {from: "ACTIVATING", to: "ACTIVATED", eligible: model.EligibleEnumCLIENT, expected: "ACTIVATED"}, + {from: "INSTALLING", to: "TERMINATED", eligible: api.CLIENT, expected: "TERMINATED"}, + {from: "ACTIVATING", to: "ACTIVATED", eligible: api.CLIENT, expected: "ACTIVATED"}, } for _, tc := range tcs { t.Run(fmt.Sprintf("%v", tc), func(t *testing.T) { @@ -41,25 +41,26 @@ func TestUpdateJob_Ok(t *testing.T) { var jobID string { - job, err := db.CreateJob(context.Background(), &model.Job{ + job, err := db.CreateJob(context.Background(), &api.Job{ ClientID: "abc", Workflow: wf, - Status: &model.JobStatus{ClientID: "abc", State: tc.from}, + Status: &api.JobStatus{ClientID: "abc", State: tc.from}, }) jobID = job.ID assert.NoError(t, err) assert.Equal(t, tc.from, job.Status.State) } - status, err := Update(context.Background(), db, jobID, &model.JobStatus{ + progress := int32(100) + status, err := Update(context.Background(), db, jobID, &api.JobStatus{ ClientID: "foo", State: tc.to, - Progress: 100, + Progress: &progress, }, tc.eligible) assert.NoError(t, err) assert.Equal(t, "foo", status.ClientID) assert.Equal(t, tc.expected, status.State) - assert.Equal(t, int32(100), status.Progress) + assert.Equal(t, int32(100), *status.Progress) }) } } @@ -68,39 +69,39 @@ func TestUpdateJobStatus_Message(t *testing.T) { db := newInMemoryDB(t) wf := createDirectWorkflow(t, db) - job, err := db.CreateJob(context.Background(), &model.Job{ + progress := int32(42) + job, err := db.CreateJob(context.Background(), &api.Job{ ClientID: "abc", Workflow: wf, - Status: &model.JobStatus{ClientID: "abc", State: "INSTALLING", Progress: 42}, + Status: &api.JobStatus{ClientID: "abc", State: "INSTALLING", Progress: &progress}, }) require.NoError(t, err) message := "Updating message!" - status, err := Update(context.Background(), db, job.ID, &model.JobStatus{ClientID: "foo", Message: message, State: job.Status.State}, model.EligibleEnumCLIENT) + status, err := Update(context.Background(), db, job.ID, &api.JobStatus{ClientID: "foo", Message: message, State: job.Status.State}, api.CLIENT) assert.NoError(t, err) assert.Equal(t, "INSTALLING", status.State) - assert.Equal(t, int32(0), status.Progress) + assert.Nil(t, status.Progress) assert.Equal(t, message, status.Message) } func TestUpdateJobStatus_StateWarp(t *testing.T) { from := "INSTALLING" to := "INSTALLED" - source := model.EligibleEnumCLIENT - expected := "ACTIVATE" + source := api.CLIENT db := newInMemoryDB(t) wf := createDirectWorkflow(t, db) - job, err := db.CreateJob(context.Background(), &model.Job{ + job, err := db.CreateJob(context.Background(), &api.Job{ ClientID: "foo", Workflow: wf, - Status: &model.JobStatus{ClientID: "foo", State: from, DefinitionHash: "abc"}, + Status: &api.JobStatus{ClientID: "foo", State: from, DefinitionHash: "abc"}, }) require.NoError(t, err) - updatedJob, err := db.UpdateJob(context.Background(), job, persistence.JobUpdate{Status: &model.JobStatus{ + updatedJob, err := db.UpdateJob(context.Background(), job, persistence.JobUpdate{Status: &api.JobStatus{ ClientID: "foo", State: "INSTALLING", DefinitionHash: job.Status.DefinitionHash, @@ -108,15 +109,16 @@ func TestUpdateJobStatus_StateWarp(t *testing.T) { assert.NoError(t, err) assert.NotEmpty(t, updatedJob.Status.DefinitionHash) - status, err := Update(context.Background(), db, job.ID, &model.JobStatus{ + progress := int32(100) + status, err := Update(context.Background(), db, job.ID, &api.JobStatus{ State: to, Message: "update installed", - Progress: 100, + Progress: &progress, }, source) - assert.NoError(t, err) + require.NoError(t, err) - assert.Equal(t, expected, status.State) - assert.Equal(t, int32(0), status.Progress) + assert.Equal(t, "ACTIVATE", status.State) + assert.Nil(t, status.Progress) // status was reset due to state warp assert.Equal(t, "", status.Message) assert.Empty(t, status.Context) assert.Equal(t, job.Status.DefinitionHash, status.DefinitionHash) @@ -129,17 +131,17 @@ func TestUpdateJobStatusNotAllowed(t *testing.T) { wf := createDirectWorkflow(t, db) var jobID string { - job, err := db.CreateJob(context.Background(), &model.Job{ + job, err := db.CreateJob(context.Background(), &api.Job{ ClientID: "abc", Workflow: wf, - Status: &model.JobStatus{State: from}, + Status: &api.JobStatus{State: from}, }) jobID = job.ID require.NoError(t, err) require.Equal(t, from, job.Status.State) } - status, err := Update(context.Background(), db, jobID, &model.JobStatus{State: to}, model.EligibleEnumWFX) + status, err := Update(context.Background(), db, jobID, &api.JobStatus{State: to}, api.WFX) assert.Error(t, err) assert.Nil(t, status) } @@ -147,25 +149,23 @@ func TestUpdateJobStatusNotAllowed(t *testing.T) { func TestUpdateJob_NotifySubscribers(t *testing.T) { db := newInMemoryDB(t) wf := createDirectWorkflow(t, db) - job, err := db.CreateJob(context.Background(), &model.Job{ + job, err := db.CreateJob(context.Background(), &api.Job{ ClientID: "abc", Workflow: wf, - Status: &model.JobStatus{ClientID: "abc", State: "ACTIVATING"}, + Status: &api.JobStatus{ClientID: "abc", State: "ACTIVATING"}, }) require.NoError(t, err) assert.Equal(t, "ACTIVATING", job.Status.State) - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - ch, err := events.AddSubscriber(ctx, events.FilterParams{JobIDs: []string{job.ID}}, nil) + ch, err := events.AddSubscriber(context.Background(), events.FilterParams{JobIDs: []string{job.ID}}, nil) require.NoError(t, err) - _, err = Update(context.Background(), db, job.ID, &model.JobStatus{ + progress := int32(100) + _, err = Update(context.Background(), db, job.ID, &api.JobStatus{ ClientID: "foo", State: "ACTIVATED", - Progress: 100, - }, model.EligibleEnumCLIENT) + Progress: &progress, + }, api.CLIENT) require.NoError(t, err) event := <-ch @@ -175,7 +175,7 @@ func TestUpdateJob_NotifySubscribers(t *testing.T) { assert.Equal(t, wf.Name, receivedEvent.Job.Workflow.Name) } -func createDirectWorkflow(t *testing.T, db persistence.Storage) *model.Workflow { +func createDirectWorkflow(t *testing.T, db persistence.Storage) *api.Workflow { wf, err := db.CreateWorkflow(context.Background(), dau.DirectWorkflow()) require.NoError(t, err) return wf diff --git a/internal/handler/job/tags/add.go b/internal/handler/job/tags/add.go index 8b5178ad..fac806e7 100644 --- a/internal/handler/job/tags/add.go +++ b/internal/handler/job/tags/add.go @@ -14,7 +14,7 @@ import ( "github.com/Southclaws/fault" "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/internal/handler/job/events" "github.com/siemens/wfx/middleware/logging" "github.com/siemens/wfx/persistence" @@ -39,7 +39,7 @@ func Add(ctx context.Context, storage persistence.Storage, jobID string, tags [] _ = events.PublishEvent(ctx, &events.JobEvent{ Ctime: strfmt.DateTime(time.Now()), Action: events.ActionAddTags, - Job: &model.Job{ + Job: &api.Job{ ID: updatedJob.ID, ClientID: updatedJob.ClientID, Workflow: updatedJob.Workflow, diff --git a/internal/handler/job/tags/add_test.go b/internal/handler/job/tags/add_test.go index 89dffa7b..2bf792bd 100644 --- a/internal/handler/job/tags/add_test.go +++ b/internal/handler/job/tags/add_test.go @@ -14,7 +14,7 @@ import ( "sort" "testing" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/internal/handler/job/events" "github.com/siemens/wfx/internal/persistence/entgo" "github.com/siemens/wfx/persistence" @@ -28,10 +28,10 @@ func TestAdd(t *testing.T) { wf, err := db.CreateWorkflow(context.Background(), dau.PhasedWorkflow()) require.NoError(t, err) - job, err := db.CreateJob(context.Background(), &model.Job{ + job, err := db.CreateJob(context.Background(), &api.Job{ ClientID: "foo", Workflow: wf, - Status: &model.JobStatus{State: "CREATED"}, + Status: &api.JobStatus{State: "CREATED"}, }) require.NoError(t, err) @@ -53,35 +53,35 @@ func TestAdd(t *testing.T) { } func TestAdd_FaultyStorageGet(t *testing.T) { - db := persistence.NewMockStorage(t) + dbMock := persistence.NewHealthyMockStorage(t) ctx := context.Background() expectedErr := errors.New("mock error") - db.On("GetJob", ctx, "1", persistence.FetchParams{History: false}).Return(nil, expectedErr) + dbMock.On("GetJob", ctx, "1", persistence.FetchParams{History: false}).Return(nil, expectedErr) - tags, err := Add(ctx, db, "1", []string{"foo", "bar"}) + tags, err := Add(ctx, dbMock, "1", []string{"foo", "bar"}) assert.Nil(t, tags) assert.NotNil(t, err) } func TestAdd_FaultyStorageUpdate(t *testing.T) { - db := persistence.NewMockStorage(t) + dbMock := persistence.NewHealthyMockStorage(t) ctx := context.Background() expectedErr := errors.New("mock error") - dummyJob := model.Job{ID: "1"} + dummyJob := api.Job{ID: "1"} tags := []string{"foo", "bar"} - db.On("GetJob", ctx, "1", persistence.FetchParams{History: false}).Return(&dummyJob, nil) - db.On("UpdateJob", ctx, &dummyJob, persistence.JobUpdate{AddTags: &tags}).Return(nil, expectedErr) + dbMock.On("GetJob", ctx, "1", persistence.FetchParams{History: false}).Return(&dummyJob, nil) + dbMock.On("UpdateJob", ctx, &dummyJob, persistence.JobUpdate{AddTags: &tags}).Return(nil, expectedErr) - tags, err := Add(ctx, db, "1", tags) + tags, err := Add(ctx, dbMock, "1", tags) assert.Nil(t, tags) assert.NotNil(t, err) } func newInMemoryDB(t *testing.T) persistence.Storage { db := &entgo.SQLite{} - err := db.Initialize(context.Background(), "file:wfx?mode=memory&cache=shared&_fk=1") + err := db.Initialize("file:wfx?mode=memory&cache=shared&_fk=1") require.NoError(t, err) t.Cleanup(db.Shutdown) @@ -94,7 +94,7 @@ func newInMemoryDB(t *testing.T) persistence.Storage { } } { - list, _ := db.QueryWorkflows(context.Background(), persistence.PaginationParams{Limit: 100}) + list, _ := db.QueryWorkflows(context.Background(), persistence.SortParams{Desc: false}, persistence.PaginationParams{Limit: 100}) for _, wf := range list.Content { _ = db.DeleteWorkflow(context.Background(), wf.Name) } diff --git a/internal/handler/job/tags/delete.go b/internal/handler/job/tags/delete.go index 95e8453d..3e365ae3 100644 --- a/internal/handler/job/tags/delete.go +++ b/internal/handler/job/tags/delete.go @@ -14,7 +14,7 @@ import ( "github.com/Southclaws/fault" "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/internal/handler/job/events" "github.com/siemens/wfx/middleware/logging" "github.com/siemens/wfx/persistence" @@ -39,7 +39,7 @@ func Delete(ctx context.Context, storage persistence.Storage, jobID string, tags _ = events.PublishEvent(ctx, &events.JobEvent{ Ctime: strfmt.DateTime(time.Now()), Action: events.ActionDeleteTags, - Job: &model.Job{ + Job: &api.Job{ ID: updatedJob.ID, ClientID: updatedJob.ClientID, Workflow: updatedJob.Workflow, diff --git a/internal/handler/job/tags/delete_test.go b/internal/handler/job/tags/delete_test.go index 1be760a5..0ead7c2a 100644 --- a/internal/handler/job/tags/delete_test.go +++ b/internal/handler/job/tags/delete_test.go @@ -13,7 +13,7 @@ import ( "errors" "testing" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/internal/handler/job/events" "github.com/siemens/wfx/persistence" "github.com/siemens/wfx/workflow/dau" @@ -26,10 +26,10 @@ func TestDelete(t *testing.T) { wf, err := db.CreateWorkflow(context.Background(), dau.DirectWorkflow()) require.NoError(t, err) - job, err := db.CreateJob(context.Background(), &model.Job{ + job, err := db.CreateJob(context.Background(), &api.Job{ ClientID: "foo", Workflow: wf, - Status: &model.JobStatus{State: "INSTALL"}, + Status: &api.JobStatus{State: "INSTALL"}, Tags: []string{"foo", "bar"}, }) require.NoError(t, err) @@ -50,7 +50,7 @@ func TestDelete(t *testing.T) { } func TestDelete_FaultyStorageGet(t *testing.T) { - db := persistence.NewMockStorage(t) + db := persistence.NewHealthyMockStorage(t) ctx := context.Background() expectedErr := errors.New("mock error") db.On("GetJob", ctx, "1", persistence.FetchParams{History: false}).Return(nil, expectedErr) @@ -61,11 +61,11 @@ func TestDelete_FaultyStorageGet(t *testing.T) { } func TestDelete_FaultyStorageUpdate(t *testing.T) { - db := persistence.NewMockStorage(t) + db := persistence.NewHealthyMockStorage(t) ctx := context.Background() expectedErr := errors.New("mock error") - dummyJob := model.Job{ID: "1"} + dummyJob := api.Job{ID: "1"} tags := []string{"foo", "bar"} db.On("GetJob", ctx, "1", persistence.FetchParams{History: false}).Return(&dummyJob, nil) diff --git a/internal/handler/job/tags/get_test.go b/internal/handler/job/tags/get_test.go index 3f18f230..bbf35d60 100644 --- a/internal/handler/job/tags/get_test.go +++ b/internal/handler/job/tags/get_test.go @@ -12,7 +12,7 @@ import ( "context" "testing" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/workflow/dau" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -23,10 +23,10 @@ func TestGet(t *testing.T) { wf, err := db.CreateWorkflow(context.Background(), dau.DirectWorkflow()) require.NoError(t, err) - job, err := db.CreateJob(context.Background(), &model.Job{ + job, err := db.CreateJob(context.Background(), &api.Job{ ClientID: "foo", Workflow: wf, - Status: &model.JobStatus{State: "CREATED"}, + Status: &api.JobStatus{State: "CREATED"}, Tags: []string{"foo", "bar"}, }) require.NoError(t, err) @@ -41,10 +41,10 @@ func TestGetEmpty(t *testing.T) { wf, err := db.CreateWorkflow(context.Background(), dau.DirectWorkflow()) require.NoError(t, err) - job, err := db.CreateJob(context.Background(), &model.Job{ + job, err := db.CreateJob(context.Background(), &api.Job{ ClientID: "foo", Workflow: wf, - Status: &model.JobStatus{State: "CREATED"}, + Status: &api.JobStatus{State: "CREATED"}, }) require.NoError(t, err) diff --git a/internal/handler/workflow/create.go b/internal/handler/workflow/create.go index 791d1bdf..d3fd5c3e 100644 --- a/internal/handler/workflow/create.go +++ b/internal/handler/workflow/create.go @@ -14,12 +14,12 @@ import ( "github.com/Southclaws/fault" "github.com/Southclaws/fault/ftag" "github.com/rs/zerolog/log" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/persistence" "github.com/siemens/wfx/workflow" ) -func CreateWorkflow(ctx context.Context, storage persistence.Storage, wf *model.Workflow) (*model.Workflow, error) { +func CreateWorkflow(ctx context.Context, storage persistence.Storage, wf *api.Workflow) (*api.Workflow, error) { if err := workflow.ValidateWorkflow(wf); err != nil { return nil, fault.Wrap(err, ftag.With(ftag.InvalidArgument)) } diff --git a/internal/handler/workflow/create_test.go b/internal/handler/workflow/create_test.go index b1f7b73f..3450b57a 100644 --- a/internal/handler/workflow/create_test.go +++ b/internal/handler/workflow/create_test.go @@ -28,7 +28,7 @@ func TestCreateWorkflow(t *testing.T) { func newInMemoryDB(t *testing.T) persistence.Storage { var db entgo.SQLite - err := db.Initialize(context.Background(), "file:wfx?mode=memory&cache=shared&_fk=1") + err := db.Initialize("file:wfx?mode=memory&cache=shared&_fk=1") require.NoError(t, err) t.Cleanup(db.Shutdown) t.Cleanup(func() { diff --git a/internal/handler/workflow/get.go b/internal/handler/workflow/get.go index 8f1d4ea4..527512bb 100644 --- a/internal/handler/workflow/get.go +++ b/internal/handler/workflow/get.go @@ -13,12 +13,12 @@ import ( "github.com/Southclaws/fault" "github.com/Southclaws/fault/ftag" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/middleware/logging" "github.com/siemens/wfx/persistence" ) -func GetWorkflow(ctx context.Context, storage persistence.Storage, name string) (*model.Workflow, error) { +func GetWorkflow(ctx context.Context, storage persistence.Storage, name string) (*api.Workflow, error) { log := logging.LoggerFromCtx(ctx).With().Str("name", name).Logger() log.Debug().Str("name", name).Msg("Fetching workflow") workflow, err := storage.GetWorkflow(ctx, name) diff --git a/internal/handler/workflow/get_test.go b/internal/handler/workflow/get_test.go index 5479363c..304d35c4 100644 --- a/internal/handler/workflow/get_test.go +++ b/internal/handler/workflow/get_test.go @@ -34,10 +34,10 @@ func TestGetWorkflow(t *testing.T) { func TestGetWorkflow_NotFound(t *testing.T) { ctx := context.Background() - db := persistence.NewMockStorage(t) - db.EXPECT().GetWorkflow(ctx, "foo").Return(nil, fault.Wrap(errors.New("Not found"), ftag.With(ftag.NotFound))) + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().GetWorkflow(ctx, "foo").Return(nil, fault.Wrap(errors.New("Not found"), ftag.With(ftag.NotFound))) - wf, err := GetWorkflow(ctx, db, "foo") + wf, err := GetWorkflow(ctx, dbMock, "foo") assert.Nil(t, wf) assert.NotNil(t, err) } @@ -45,10 +45,10 @@ func TestGetWorkflow_NotFound(t *testing.T) { func TestGetWorkflow_Internal(t *testing.T) { ctx := context.Background() - db := persistence.NewMockStorage(t) - db.EXPECT().GetWorkflow(ctx, "foo").Return(nil, fault.Wrap(errors.New("Not found"), ftag.With(ftag.Internal))) + dbMock := persistence.NewHealthyMockStorage(t) + dbMock.EXPECT().GetWorkflow(ctx, "foo").Return(nil, fault.Wrap(errors.New("Not found"), ftag.With(ftag.Internal))) - wf, err := GetWorkflow(ctx, db, "foo") + wf, err := GetWorkflow(ctx, dbMock, "foo") assert.Nil(t, wf) assert.NotNil(t, err) } diff --git a/internal/handler/workflow/query.go b/internal/handler/workflow/query.go index 2ea8f998..86353efd 100644 --- a/internal/handler/workflow/query.go +++ b/internal/handler/workflow/query.go @@ -10,16 +10,21 @@ package workflow import ( "context" + "strings" "github.com/Southclaws/fault" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/middleware/logging" "github.com/siemens/wfx/persistence" ) -func QueryWorkflows(ctx context.Context, storage persistence.Storage, paginationParams persistence.PaginationParams) (*model.PaginatedWorkflowList, error) { +func QueryWorkflows(ctx context.Context, storage persistence.Storage, paginationParams persistence.PaginationParams, sort *string) (*api.PaginatedWorkflowList, error) { log := logging.LoggerFromCtx(ctx) - log.Debug().Msg("Querying workflows") - list, err := storage.QueryWorkflows(ctx, paginationParams) + var sortParams persistence.SortParams + if sort != nil { + sortParams.Desc = strings.ToLower(*sort) == "desc" + } + log.Debug().Bool("desc", sortParams.Desc).Msg("Querying workflows") + list, err := storage.QueryWorkflows(ctx, sortParams, paginationParams) return list, fault.Wrap(err) } diff --git a/internal/handler/workflow/query_test.go b/internal/handler/workflow/query_test.go index e0e0d75f..1f0f783e 100644 --- a/internal/handler/workflow/query_test.go +++ b/internal/handler/workflow/query_test.go @@ -23,7 +23,7 @@ func TestQueryWorkflow(t *testing.T) { wf, err := CreateWorkflow(context.Background(), db, dau.DirectWorkflow()) require.NoError(t, err) - list, err := QueryWorkflows(context.Background(), db, persistence.PaginationParams{Limit: 10}) + list, err := QueryWorkflows(context.Background(), db, persistence.PaginationParams{Limit: 10}, nil) assert.NoError(t, err) assert.Len(t, list.Content, 1) assert.Equal(t, wf.Name, list.Content[0].Name) diff --git a/internal/persistence/entgo/health.go b/internal/persistence/entgo/health.go index c34a3cd1..d8ed0d89 100644 --- a/internal/persistence/entgo/health.go +++ b/internal/persistence/entgo/health.go @@ -14,7 +14,7 @@ import ( "github.com/Southclaws/fault" ) -func (db Database) CheckHealth(_ context.Context) error { - _, err := db.client.ExecContext(context.Background(), "SELECT 1") +func (db Database) CheckHealth(ctx context.Context) error { + _, err := db.client.ExecContext(ctx, "SELECT 1") return fault.Wrap(err) } diff --git a/internal/persistence/entgo/job_create.go b/internal/persistence/entgo/job_create.go index 1108274e..be2c81dd 100644 --- a/internal/persistence/entgo/job_create.go +++ b/internal/persistence/entgo/job_create.go @@ -15,17 +15,17 @@ import ( "github.com/Southclaws/fault" "github.com/rs/zerolog/log" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/generated/ent" "github.com/siemens/wfx/generated/ent/predicate" "github.com/siemens/wfx/generated/ent/tag" "github.com/siemens/wfx/generated/ent/workflow" - "github.com/siemens/wfx/generated/model" wfutil "github.com/siemens/wfx/internal/workflow" "github.com/siemens/wfx/middleware/logging" ) // CreateJob persists a new job and sets the job ID field. -func (db Database) CreateJob(ctx context.Context, job *model.Job) (*model.Job, error) { +func (db Database) CreateJob(ctx context.Context, job *api.Job) (*api.Job, error) { log := logging.LoggerFromCtx(ctx) tx, err := db.client.Tx(ctx) @@ -50,11 +50,15 @@ func (db Database) CreateJob(ctx context.Context, job *model.Job) (*model.Job, e return createdJob, nil } -func createJobHelper(ctx context.Context, tx *ent.Tx, job *model.Job) (*model.Job, error) { +func createJobHelper(ctx context.Context, tx *ent.Tx, job *api.Job) (*api.Job, error) { + tags := make([]string, 0) + if job.Tags != nil { + tags = job.Tags + } log.Debug(). Str("workflow", job.Workflow.Name). Str("state", job.Status.State). - Strs("tags", job.Tags). + Strs("tags", tags). Msg("Creating new job") wfEntity, err := tx.Workflow. @@ -66,14 +70,14 @@ func createJobHelper(ctx context.Context, tx *ent.Tx, job *model.Job) (*model.Jo return nil, fault.Wrap(err) } wf := convertWorkflow(wfEntity) - group := wfutil.FindStateGroup(wf, job.Status.State) + group := wfutil.FindStateGroup(&wf, job.Status.State) // start tags - n := len(job.Tags) + n := len(tags) allTagIDs := make([]int, 0, n) if n > 0 { tagPreds := make([]predicate.Tag, n) - for i, name := range job.Tags { + for i, name := range tags { tagPreds[i] = tag.Name(name) } @@ -90,10 +94,10 @@ func createJobHelper(ctx context.Context, tx *ent.Tx, job *model.Job) (*model.Jo } { // create missing tags - delta := len(job.Tags) - len(existingTags) + delta := len(tags) - len(existingTags) if delta > 0 { missingTags := make([]*ent.TagCreate, 0, delta) - for _, name := range job.Tags { + for _, name := range tags { if _, found := existingTags[name]; !found { missingTags = append(missingTags, tx.Tag.Create().SetName(name)) } @@ -118,9 +122,9 @@ func createJobHelper(ctx context.Context, tx *ent.Tx, job *model.Job) (*model.Jo SetClientID(job.ClientID). SetStatus(*job.Status). SetWorkflowID(wfEntity.ID). - SetDefinition(job.Definition). AddTagIDs(allTagIDs...). - SetGroup(group) + SetGroup(group). + SetDefinition(job.Definition) if job.Stime != nil { builder.SetStime(time.Time(*job.Stime)) @@ -138,6 +142,6 @@ func createJobHelper(ctx context.Context, tx *ent.Tx, job *model.Job) (*model.Jo result := convertJob(entity) // tags and workflow are not fetched by entgo, so we have to add them manually result.Tags = job.Tags - result.Workflow = wf - return result, nil + result.Workflow = &wf + return &result, nil } diff --git a/internal/persistence/entgo/job_get.go b/internal/persistence/entgo/job_get.go index 30253e4d..e69cc9e3 100644 --- a/internal/persistence/entgo/job_get.go +++ b/internal/persistence/entgo/job_get.go @@ -14,17 +14,16 @@ import ( "github.com/Southclaws/fault" "github.com/Southclaws/fault/ftag" - "github.com/go-openapi/strfmt" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/generated/ent" "github.com/siemens/wfx/generated/ent/history" "github.com/siemens/wfx/generated/ent/job" "github.com/siemens/wfx/generated/ent/tag" - "github.com/siemens/wfx/generated/model" "github.com/siemens/wfx/middleware/logging" "github.com/siemens/wfx/persistence" ) -func (db Database) GetJob(ctx context.Context, jobID string, fetchParams persistence.FetchParams) (*model.Job, error) { +func (db Database) GetJob(ctx context.Context, jobID string, fetchParams persistence.FetchParams) (*api.Job, error) { log := logging.LoggerFromCtx(ctx) contextLogger := log.With().Str("id", jobID).Logger() contextLogger.Debug().Msg("Fetching job") @@ -45,7 +44,7 @@ func (db Database) GetJob(ctx context.Context, jobID string, fetchParams persist }) } - job, err := builder.Only(ctx) + entity, err := builder.Only(ctx) if err != nil { if ent.IsNotFound(err) { contextLogger.Debug().Msg("Job not found") @@ -55,42 +54,44 @@ func (db Database) GetJob(ctx context.Context, jobID string, fetchParams persist return nil, fault.Wrap(err) } contextLogger.Debug().Msg("Fetched job") - return convertJob(job), nil + job := convertJob(entity) + return &job, nil } -func convertJob(entity *ent.Job) *model.Job { - var wf *model.Workflow +func convertJob(entity *ent.Job) api.Job { + var wf api.Workflow if entity.Edges.Workflow != nil { wf = convertWorkflow(entity.Edges.Workflow) } - stime := strfmt.DateTime(entity.Stime) - mtime := strfmt.DateTime(entity.Mtime) - job := model.Job{ + stime := entity.Stime + mtime := entity.Mtime + tags := convertTags(entity.Edges.Tags) + job := api.Job{ ID: entity.ID, ClientID: entity.ClientID, Definition: entity.Definition, Stime: &stime, Mtime: &mtime, Status: &entity.Status, - Tags: convertTags(entity.Edges.Tags), - Workflow: wf, + Tags: tags, + Workflow: &wf, } n := len(entity.Edges.History) if n > 0 { - job.History = make([]*model.History, n) + history := make([]api.History, n) for i, entity := range entity.Edges.History { - hist := convertHistory(entity) - job.History[i] = &hist + history[i] = convertHistory(entity) } + job.History = &history } - return &job + return job } -func convertHistory(entity *ent.History) model.History { - return model.History{ - Mtime: strfmt.DateTime(entity.Mtime), +func convertHistory(entity *ent.History) api.History { + return api.History{ + Mtime: &entity.Mtime, Status: &entity.Status, } } diff --git a/internal/persistence/entgo/job_query.go b/internal/persistence/entgo/job_query.go index bbb853c2..8d165406 100644 --- a/internal/persistence/entgo/job_query.go +++ b/internal/persistence/entgo/job_query.go @@ -15,11 +15,11 @@ import ( "entgo.io/ent/dialect/sql/sqljson" "github.com/Southclaws/fault" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/generated/ent" "github.com/siemens/wfx/generated/ent/job" "github.com/siemens/wfx/generated/ent/tag" "github.com/siemens/wfx/generated/ent/workflow" - "github.com/siemens/wfx/generated/model" "github.com/siemens/wfx/middleware/logging" "github.com/siemens/wfx/persistence" ) @@ -29,7 +29,7 @@ func (db Database) QueryJobs(ctx context.Context, filterParams persistence.FilterParams, sortParams persistence.SortParams, paginationParams persistence.PaginationParams, -) (*model.PaginatedJobList, error) { +) (*api.PaginatedJobList, error) { log := logging.LoggerFromCtx(ctx) builder := db.client.Job.Query().WithWorkflow().WithTags(func(q *ent.TagQuery) { q.Order(ent.Asc(tag.FieldName)) @@ -83,16 +83,17 @@ func (db Database) QueryJobs(ctx context.Context, return nil, fault.Wrap(err) } - result := model.PaginatedJobList{ - Pagination: &model.PaginatedJobListPagination{ + content := make([]api.Job, 0, len(jobs)) + for _, entity := range jobs { + content = append(content, convertJob(entity)) + } + result := api.PaginatedJobList{ + Pagination: api.Pagination{ Total: int64(total), Limit: paginationParams.Limit, Offset: paginationParams.Offset, }, - Content: make([]*model.Job, 0, len(jobs)), - } - for _, entity := range jobs { - result.Content = append(result.Content, convertJob(entity)) + Content: content, } log.Debug(). diff --git a/internal/persistence/entgo/job_update.go b/internal/persistence/entgo/job_update.go index 117d0348..c89a499c 100644 --- a/internal/persistence/entgo/job_update.go +++ b/internal/persistence/entgo/job_update.go @@ -14,16 +14,16 @@ import ( "time" "github.com/Southclaws/fault" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/generated/ent" "github.com/siemens/wfx/generated/ent/tag" - "github.com/siemens/wfx/generated/model" "github.com/siemens/wfx/internal/workflow" "github.com/siemens/wfx/middleware/logging" "github.com/siemens/wfx/persistence" ) // UpdateJob updates an existing job and its history. -func (db Database) UpdateJob(ctx context.Context, job *model.Job, request persistence.JobUpdate) (*model.Job, error) { +func (db Database) UpdateJob(ctx context.Context, job *api.Job, request persistence.JobUpdate) (*api.Job, error) { log := logging.LoggerFromCtx(ctx).With().Str("id", job.ID).Logger() tx, err := db.client.Tx(ctx) @@ -48,14 +48,13 @@ func (db Database) UpdateJob(ctx context.Context, job *model.Job, request persis } log.Debug(). - Str("message", updatedJob.Status.Message). Str("state", updatedJob.Status.State). Msg("Updated job") return updatedJob, nil } -func doUpdateJob(ctx context.Context, tx *ent.Tx, job *model.Job, request persistence.JobUpdate) (*model.Job, error) { +func doUpdateJob(ctx context.Context, tx *ent.Tx, job *api.Job, request persistence.JobUpdate) (*api.Job, error) { log := logging.LoggerFromCtx(ctx).With().Str("id", job.ID).Logger() updater := tx.Job.UpdateOneID(job.ID) @@ -154,7 +153,7 @@ func doUpdateJob(ctx context.Context, tx *ent.Tx, job *model.Job, request persis if request.Status != nil { history.SetStatus(*job.Status) } - if request.Definition != nil { + if request.Definition != nil && job.Definition != nil { history.SetDefinition(job.Definition) } if _, err = history.Save(ctx); err != nil { @@ -165,11 +164,13 @@ func doUpdateJob(ctx context.Context, tx *ent.Tx, job *model.Job, request persis updatedJob := convertJob(entity) // XXX: this feels like a bug in entgo, shouldn't be necessary to set Tags - updatedJob.Tags = make([]string, 0, len(allTags)) + tags := make([]string, 0, len(allTags)) for t := range allTags { - updatedJob.Tags = append(updatedJob.Tags, t) + tags = append(tags, t) } - sort.Strings(updatedJob.Tags) + sort.Strings(tags) - return updatedJob, nil + updatedJob.Tags = tags + + return &updatedJob, nil } diff --git a/internal/persistence/entgo/mysql.go b/internal/persistence/entgo/mysql.go index e1a9ed13..c4a1dfd6 100644 --- a/internal/persistence/entgo/mysql.go +++ b/internal/persistence/entgo/mysql.go @@ -37,7 +37,7 @@ func init() { persistence.RegisterStorage("mysql", &MySQL{}) } -func (wrapper *MySQL) Initialize(ctx context.Context, options string) error { +func (wrapper *MySQL) Initialize(options string) error { // parse user-supplied dsn and enrich it cfg, err := driver.ParseDSN(options) if err != nil { @@ -57,7 +57,7 @@ func (wrapper *MySQL) Initialize(ctx context.Context, options string) error { } db := sql.OpenDB(connector) - if err := db.PingContext(ctx); err != nil { + if err := db.Ping(); err != nil { log.Error().Err(err).Msg("Failed to ping MySQL database") _ = db.Close() return fault.Wrap(err) @@ -70,6 +70,7 @@ func (wrapper *MySQL) Initialize(ctx context.Context, options string) error { return fault.Wrap(err) } + ctx := context.Background() conn, err := db.Conn(ctx) if err != nil { return fault.Wrap(err) diff --git a/internal/persistence/entgo/mysql_test.go b/internal/persistence/entgo/mysql_test.go index 00b58885..d295be0e 100644 --- a/internal/persistence/entgo/mysql_test.go +++ b/internal/persistence/entgo/mysql_test.go @@ -11,7 +11,6 @@ package entgo */ import ( - "context" "fmt" "os" "path/filepath" @@ -23,11 +22,9 @@ import ( "github.com/siemens/wfx/internal/persistence/tests" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "go.uber.org/goleak" ) func TestMySQL_Initialize(t *testing.T) { - defer goleak.VerifyNone(t) db := setupMySQL(t) db.Shutdown() } @@ -35,7 +32,7 @@ func TestMySQL_Initialize(t *testing.T) { func TestMain_InitializeFail(t *testing.T) { dsn := "foo:bar@tcp(localhost)/wfx" var mysql MySQL - err := mysql.Initialize(context.Background(), dsn) + err := mysql.Initialize(dsn) assert.NotNil(t, err) } @@ -59,7 +56,7 @@ func setupMySQL(t *testing.T) MySQL { db := os.Getenv("MYSQL_DATABASE") dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s", user, pass, host, db) var mysql MySQL - err := mysql.Initialize(context.Background(), dsn) + err := mysql.Initialize(dsn) require.NoError(t, err) return mysql } diff --git a/internal/persistence/entgo/postgres.go b/internal/persistence/entgo/postgres.go index ed23c6ac..a63b5439 100644 --- a/internal/persistence/entgo/postgres.go +++ b/internal/persistence/entgo/postgres.go @@ -11,7 +11,6 @@ package entgo */ import ( - "context" "database/sql" "embed" "time" @@ -45,7 +44,7 @@ func init() { // example dsn: "user= password= host=localhost port=5432 database=wfx sslmode=disable" // see https://github.com/jackc/pgx/blob/master/stdlib/sql.go -func (wrapper *PostgreSQL) Initialize(ctx context.Context, options string) error { +func (wrapper *PostgreSQL) Initialize(options string) error { connConfig, err := pgx.ParseConfig(options) if err != nil { return fault.Wrap(err) @@ -59,7 +58,7 @@ func (wrapper *PostgreSQL) Initialize(ctx context.Context, options string) error if err != nil { return fault.Wrap(err) } - if err := db.PingContext(ctx); err != nil { + if err := db.Ping(); err != nil { log.Error().Err(err).Msg("Failed to ping PostgreSQL database") return fault.Wrap(err) } diff --git a/internal/persistence/entgo/postgres_test.go b/internal/persistence/entgo/postgres_test.go index 9314496f..43d0fdad 100644 --- a/internal/persistence/entgo/postgres_test.go +++ b/internal/persistence/entgo/postgres_test.go @@ -11,7 +11,6 @@ package entgo */ import ( - "context" "path/filepath" "reflect" "runtime" @@ -20,11 +19,9 @@ import ( "github.com/siemens/wfx/internal/persistence/tests" "github.com/stretchr/testify/require" - "go.uber.org/goleak" ) func TestPostgreSQL_Initialize(t *testing.T) { - defer goleak.VerifyNone(t) db := setupPostgreSQL(t) db.Shutdown() } @@ -44,7 +41,7 @@ func TestPostgreSQL(t *testing.T) { func setupPostgreSQL(t *testing.T) PostgreSQL { var postgres PostgreSQL - err := postgres.Initialize(context.Background(), "sslmode=disable") + err := postgres.Initialize("sslmode=disable") require.NoError(t, err) return postgres } diff --git a/internal/persistence/entgo/sqlite.go b/internal/persistence/entgo/sqlite.go index 3da055df..1ff07bd8 100644 --- a/internal/persistence/entgo/sqlite.go +++ b/internal/persistence/entgo/sqlite.go @@ -11,7 +11,6 @@ package entgo */ import ( - "context" "embed" "net/url" @@ -39,7 +38,7 @@ func init() { persistence.RegisterStorage("sqlite", &SQLite{}) } -func (instance *SQLite) Initialize(_ context.Context, dsn string) error { +func (instance *SQLite) Initialize(dsn string) error { log.Debug().Str("dsn", dsn).Msg("Connecting to SQLite") drv, err := sql.Open(dialect.SQLite, dsn) if err != nil { diff --git a/internal/persistence/entgo/sqlite_test.go b/internal/persistence/entgo/sqlite_test.go index f17c32c5..e8576c21 100644 --- a/internal/persistence/entgo/sqlite_test.go +++ b/internal/persistence/entgo/sqlite_test.go @@ -11,7 +11,6 @@ package entgo */ import ( - "context" "fmt" "os" "path" @@ -21,21 +20,11 @@ import ( "strings" "testing" - "github.com/google/uuid" - "github.com/rs/zerolog/log" "github.com/siemens/wfx/internal/persistence/tests" - "github.com/siemens/wfx/middleware/logging" "github.com/siemens/wfx/persistence" "github.com/stretchr/testify/require" - "go.uber.org/goleak" ) -func TestSQLite_Initialize(t *testing.T) { - defer goleak.VerifyNone(t) - db := setupSQLite(t) - db.Shutdown() -} - func TestSQLite(t *testing.T) { db := setupSQLite(t) t.Cleanup(db.Shutdown) @@ -53,10 +42,6 @@ func TestSQLite(t *testing.T) { func setupSQLite(t *testing.T) SQLite { var sqlite SQLite - reqID := uuid.New().String() - l := log.With().Str("reqID", reqID).Logger() - ctx := context.WithValue(context.Background(), logging.KeyRequestLogger, l) - dir, err := os.MkdirTemp("", "wfx.db.*") require.NoError(t, err) f, err := os.Create(path.Join(dir, "wfx.db")) @@ -67,7 +52,7 @@ func setupSQLite(t *testing.T) SQLite { }) opts := fmt.Sprintf("file:%s?_fk=1&_journal=WAL", f.Name()) - err = sqlite.Initialize(ctx, opts) + err = sqlite.Initialize(opts) require.NoError(t, err) require.NotNil(t, sqlite.Database) return sqlite diff --git a/internal/persistence/entgo/workflow_create.go b/internal/persistence/entgo/workflow_create.go index 1f260005..ca867a20 100644 --- a/internal/persistence/entgo/workflow_create.go +++ b/internal/persistence/entgo/workflow_create.go @@ -13,23 +13,23 @@ import ( "github.com/Southclaws/fault" "github.com/Southclaws/fault/ftag" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/generated/ent" - "github.com/siemens/wfx/generated/model" "github.com/siemens/wfx/middleware/logging" ) // CreateWorkflow creates a new workflow. -func (db Database) CreateWorkflow(ctx context.Context, workflow *model.Workflow) (*model.Workflow, error) { +func (db Database) CreateWorkflow(ctx context.Context, workflow *api.Workflow) (*api.Workflow, error) { log := logging.LoggerFromCtx(ctx) - entity, err := db.client.Workflow. + builder := db.client.Workflow. Create(). SetName(workflow.Name). - SetDescription(workflow.Description). SetStates(workflow.States). SetTransitions(workflow.Transitions). SetGroups(workflow.Groups). - Save(ctx) + SetDescription(workflow.Description) + entity, err := builder.Save(ctx) if err != nil { if ent.IsConstraintError(err) { log.Error().Err(err).Msg("Failed to persist workflow due to constraints") @@ -38,5 +38,6 @@ func (db Database) CreateWorkflow(ctx context.Context, workflow *model.Workflow) log.Error().Err(err).Msg("Failed to persist workflow due to internal problem") return nil, fault.Wrap(err, ftag.With(ftag.Internal)) } - return convertWorkflow(entity), nil + wf := convertWorkflow(entity) + return &wf, nil } diff --git a/internal/persistence/entgo/workflow_get.go b/internal/persistence/entgo/workflow_get.go index 3465806a..a1784d24 100644 --- a/internal/persistence/entgo/workflow_get.go +++ b/internal/persistence/entgo/workflow_get.go @@ -14,12 +14,12 @@ import ( "github.com/Southclaws/fault" "github.com/Southclaws/fault/ftag" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/generated/ent" "github.com/siemens/wfx/generated/ent/workflow" - "github.com/siemens/wfx/generated/model" ) -func (db Database) GetWorkflow(ctx context.Context, name string) (*model.Workflow, error) { +func (db Database) GetWorkflow(ctx context.Context, name string) (*api.Workflow, error) { wf, err := db.client.Workflow. Query(). Where(workflow.Name(name)). @@ -30,11 +30,12 @@ func (db Database) GetWorkflow(ctx context.Context, name string) (*model.Workflo } return nil, fault.Wrap(err) } - return convertWorkflow(wf), nil + result := convertWorkflow(wf) + return &result, nil } -func convertWorkflow(wf *ent.Workflow) *model.Workflow { - return &model.Workflow{ +func convertWorkflow(wf *ent.Workflow) api.Workflow { + return api.Workflow{ Name: wf.Name, Description: wf.Description, States: wf.States, diff --git a/internal/persistence/entgo/workflow_query.go b/internal/persistence/entgo/workflow_query.go index d4166693..983616be 100644 --- a/internal/persistence/entgo/workflow_query.go +++ b/internal/persistence/entgo/workflow_query.go @@ -12,15 +12,15 @@ import ( "context" "github.com/Southclaws/fault" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/generated/ent" "github.com/siemens/wfx/generated/ent/workflow" - "github.com/siemens/wfx/generated/model" "github.com/siemens/wfx/middleware/logging" "github.com/siemens/wfx/persistence" ) // QueryWorkflows returns multiple workflows (paginated). -func (db Database) QueryWorkflows(ctx context.Context, paginationParams persistence.PaginationParams) (*model.PaginatedWorkflowList, error) { +func (db Database) QueryWorkflows(ctx context.Context, sortParams persistence.SortParams, paginationParams persistence.PaginationParams) (*api.PaginatedWorkflowList, error) { log := logging.LoggerFromCtx(ctx) builder := db.client.Workflow. Query() @@ -28,11 +28,20 @@ func (db Database) QueryWorkflows(ctx context.Context, paginationParams persiste // need to clone builder because it is unusable after we call `All` counter := builder.Clone() - workflows, err := builder. + builder. Limit(int(paginationParams.Limit)). - Offset(int(paginationParams.Offset)). - Order(ent.Asc(workflow.FieldName)). - All(ctx) + Offset(int(paginationParams.Offset)) + + // deterministic ordering + if sortParams.Desc { + log.Debug().Msg("Sorting workflows in descending order") + builder.Order(ent.Desc(workflow.FieldName)) + } else { + log.Debug().Msg("Sorting workflows in ascending order") + builder.Order(ent.Asc(workflow.FieldName)) + } + + workflows, err := builder.All(ctx) if err != nil { return nil, fault.Wrap(err) } @@ -43,16 +52,17 @@ func (db Database) QueryWorkflows(ctx context.Context, paginationParams persiste return nil, fault.Wrap(err) } - result := model.PaginatedWorkflowList{ - Pagination: &model.PaginatedWorkflowListPagination{ + content := make([]api.Workflow, 0, len(workflows)) + for _, wf := range workflows { + content = append(content, convertWorkflow(wf)) + } + result := api.PaginatedWorkflowList{ + Pagination: api.Pagination{ Total: int64(total), Offset: paginationParams.Offset, Limit: paginationParams.Limit, }, - Content: make([]*model.Workflow, 0, len(workflows)), - } - for _, wf := range workflows { - result.Content = append(result.Content, convertWorkflow(wf)) + Content: content, } log.Debug(). diff --git a/internal/persistence/tests/all.go b/internal/persistence/tests/all.go index fbab07f9..1db3568a 100644 --- a/internal/persistence/tests/all.go +++ b/internal/persistence/tests/all.go @@ -29,4 +29,5 @@ var AllTests = []PersistenceTest{ TestUpdateJobStatus, TestUpdateJobStatusNonExisting, TestWorkflowsPagination, + TestQueryWorkflowsSort, } diff --git a/internal/persistence/tests/job_get.go b/internal/persistence/tests/job_get.go index 881727b3..710eeaed 100644 --- a/internal/persistence/tests/job_get.go +++ b/internal/persistence/tests/job_get.go @@ -15,8 +15,7 @@ import ( "testing" "time" - "github.com/go-openapi/strfmt" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/persistence" "github.com/siemens/wfx/workflow/dau" "github.com/stretchr/testify/assert" @@ -53,18 +52,20 @@ func TestGetJobWithHistory(t *testing.T, db persistence.Storage) { job, err := db.CreateJob(context.Background(), tmpJob) require.NoError(t, err) + var progress int32 = 42 + message := "First Update" _, err = db.UpdateJob(context.Background(), job, - persistence.JobUpdate{Status: &model.JobStatus{Progress: 42, Message: "First Update", State: "DOWNLOADING"}}) + persistence.JobUpdate{Status: &api.JobStatus{Progress: &progress, Message: message, State: "DOWNLOADING"}}) require.NoError(t, err) { job, err := db.GetJob(context.Background(), job.ID, persistence.FetchParams{History: true}) require.NoError(t, err) - assert.Len(t, job.History, 1) + assert.Len(t, *job.History, 1) job, err = db.GetJob(context.Background(), job.ID, persistence.FetchParams{History: false}) require.NoError(t, err) - assert.Len(t, job.History, 0) + assert.Nil(t, job.History) } result, err := db.QueryJobs(context.Background(), persistence.FilterParams{ClientID: &clientID}, sortAsc, defaultPaginationParams) @@ -73,18 +74,18 @@ func TestGetJobWithHistory(t *testing.T, db persistence.Storage) { assert.Len(t, actualJobs, 1) assert.Equal(t, job.ID, actualJobs[0].ID) // query jobs does not fetch history - assert.Len(t, actualJobs[0].History, 0) + assert.Nil(t, actualJobs[0].History) } // Create a new, *unpersisted* job entity. -func newValidJob(clientID string) *model.Job { - now := strfmt.DateTime(time.Now()) - return &model.Job{ +func newValidJob(clientID string) *api.Job { + now := time.Now() + return &api.Job{ Mtime: &now, Stime: &now, ClientID: clientID, - Status: &model.JobStatus{ - ClientID: "foo", + Status: &api.JobStatus{ + ClientID: clientID, State: "CREATED", }, Tags: []string{ @@ -92,6 +93,6 @@ func newValidJob(clientID string) *model.Job { "tag2", }, Workflow: dau.DirectWorkflow(), - History: []*model.History{}, + History: &[]api.History{}, } } diff --git a/internal/persistence/tests/job_query.go b/internal/persistence/tests/job_query.go index c455a930..3143a4e9 100644 --- a/internal/persistence/tests/job_query.go +++ b/internal/persistence/tests/job_query.go @@ -12,17 +12,13 @@ package tests import ( "context" - "encoding/json" "fmt" "strconv" "testing" "time" - "github.com/go-openapi/strfmt" - "github.com/itchyny/gojq" "github.com/rs/zerolog" - "github.com/siemens/wfx/generated/model" - "github.com/siemens/wfx/generated/southbound/restapi" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/persistence" "github.com/siemens/wfx/workflow/dau" "github.com/stretchr/testify/assert" @@ -46,13 +42,14 @@ func TestQueryJobsFilter(t *testing.T, db persistence.Storage) { now := time.Now() - firstJob, err := db.CreateJob(context.Background(), &model.Job{ + tags := []string{"bar", "foo"} + firstJob, err := db.CreateJob(context.Background(), &api.Job{ ClientID: clientID, Workflow: wf, - Status: &model.JobStatus{ + Status: &api.JobStatus{ State: installedState, }, - Tags: []string{"bar", "foo"}, + Tags: tags, }) require.NoError(t, err) assert.NotNil(t, firstJob.Stime) @@ -60,22 +57,22 @@ func TestQueryJobsFilter(t *testing.T, db persistence.Storage) { assert.True(t, time.Time(*firstJob.Stime).After(now) || time.Time(*firstJob.Stime).Equal(now)) assert.True(t, time.Time(*firstJob.Mtime).After(now) || time.Time(*firstJob.Mtime).Equal(now)) - secondStime := strfmt.DateTime(now.Add(time.Second)) - secondJob, err := db.CreateJob(context.Background(), &model.Job{ + secondStime := now.Add(time.Second) + secondJob, err := db.CreateJob(context.Background(), &api.Job{ ClientID: clientID, Workflow: wf, - Status: &model.JobStatus{ + Status: &api.JobStatus{ State: installState, }, Stime: &secondStime, }) require.NoError(t, err) - thirdStime := strfmt.DateTime(now.Add(2 * time.Second)) - thirdJob, err := db.CreateJob(context.Background(), &model.Job{ + thirdStime := now.Add(2 * time.Second) + thirdJob, err := db.CreateJob(context.Background(), &api.Job{ ClientID: clientID, Workflow: wf, - Status: &model.JobStatus{ + Status: &api.JobStatus{ State: activatedState, }, Tags: []string{"meh"}, @@ -170,7 +167,7 @@ func TestQueryJobsFilter(t *testing.T, db persistence.Storage) { func TestGetJobsSorted(t *testing.T, db persistence.Storage) { clientID := "my_client" - var first, second, third *model.Job + var first, second, third *api.Job var err error { @@ -178,7 +175,7 @@ func TestGetJobsSorted(t *testing.T, db persistence.Storage) { _, err := db.CreateWorkflow(context.Background(), tmp.Workflow) require.NoError(t, err) - stime := strfmt.DateTime(time.Now().Add(-2 * time.Minute)) + stime := time.Now().Add(-2 * time.Minute) tmp.Stime = &stime first, err = db.CreateJob(context.Background(), tmp) require.NoError(t, err) @@ -186,7 +183,7 @@ func TestGetJobsSorted(t *testing.T, db persistence.Storage) { { tmp := newValidJob(clientID) - mtime := strfmt.DateTime(time.Now().Add(-time.Minute)) + mtime := time.Now().Add(-time.Minute) tmp.Mtime = &mtime second, err = db.CreateJob(context.Background(), tmp) require.NoError(t, err) @@ -233,25 +230,15 @@ func TestGetJobMaxHistorySize(t *testing.T, db persistence.Storage) { zerolog.SetGlobalLevel(zerolog.InfoLevel) defer zerolog.SetGlobalLevel(oldLevel) - var n int - { - // introspect SwaggerJSON and extract history maxItems - b, _ := restapi.SwaggerJSON.MarshalJSON() - var spec any - _ = json.Unmarshal(b, &spec) - query, _ := gojq.Parse(".definitions.Job.properties.history.maxItems") - iter := query.Run(spec) - v, ok := iter.Next() - assert.True(t, ok) - n = int(v.(float64)) - } + maxEntries := 8192 var jobID string { // job which we are going to update often tmp := newValidJob("foo") - tmp.Status.Message = "0" + message := "0" + tmp.Status.Message = message _, err := db.CreateWorkflow(context.Background(), tmp.Workflow) require.NoError(t, err) job, err := db.CreateJob(context.Background(), tmp) @@ -266,10 +253,10 @@ func TestGetJobMaxHistorySize(t *testing.T, db persistence.Storage) { require.Equal(t, job.Status.Message, "0") // update the job n+1 times - for i := 1; i <= n+1; i++ { + for i := 1; i <= maxEntries+1; i++ { msg := fmt.Sprintf("%d", i) job, err = db.UpdateJob(context.Background(), job, persistence.JobUpdate{ - Status: &model.JobStatus{ + Status: &api.JobStatus{ State: job.Status.State, Message: msg, }, @@ -282,18 +269,19 @@ func TestGetJobMaxHistorySize(t *testing.T, db persistence.Storage) { job, err := db.GetJob(context.Background(), jobID, persistence.FetchParams{History: true}) require.NoError(t, err) require.NotNil(t, job.History) - require.Len(t, job.History, n) + require.Len(t, *job.History, maxEntries) - ids := make([]int, len(job.History)) - for i, hist := range job.History { + history := *job.History + ids := make([]int, 0, len(history)) + for _, hist := range history { id, _ := strconv.Atoi(hist.Status.Message) - ids[i] = id + ids = append(ids, id) } t.Log(ids) assert.IsDecreasing(t, ids) - assert.Equal(t, fmt.Sprintf("%d", n), job.History[0].Status.Message) - assert.Equal(t, "1", job.History[len(job.History)-1].Status.Message) + assert.Equal(t, fmt.Sprintf("%d", maxEntries), history[0].Status.Message) + assert.Equal(t, "1", history[len(history)-1].Status.Message) } func TestJobsPagination(t *testing.T, db persistence.Storage) { diff --git a/internal/persistence/tests/job_update_status.go b/internal/persistence/tests/job_update_status.go index d84e23e1..1268d79a 100644 --- a/internal/persistence/tests/job_update_status.go +++ b/internal/persistence/tests/job_update_status.go @@ -14,7 +14,7 @@ import ( "context" "testing" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/persistence" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -33,26 +33,28 @@ func TestUpdateJobStatus(t *testing.T, db persistence.Storage) { mtime := job.Mtime message := "Some arbitrary message" - update := model.JobStatus{Message: message, State: "ACTIVATING"} + update := api.JobStatus{Message: message, State: "ACTIVATING"} updatedJob, err := db.UpdateJob(context.Background(), job, persistence.JobUpdate{Status: &update}) assert.NoError(t, err) assert.Greater(t, *updatedJob.Mtime, *mtime) assert.Equal(t, "ACTIVATING", updatedJob.Status.State) assert.Equal(t, message, updatedJob.Status.Message) - assert.Len(t, updatedJob.History, 0) + assert.Nil(t, updatedJob.History) { // now fetch history and check our old state is there job, err := db.GetJob(context.Background(), job.ID, persistence.FetchParams{History: true}) + history := *job.History require.NoError(t, err) - assert.Len(t, job.History, 1) - assert.Equal(t, *job.Stime, job.History[0].Mtime) + assert.Len(t, history, 1) + assert.Equal(t, *job.Stime, *history[0].Mtime) } } func TestUpdateJobStatusNonExisting(t *testing.T, db persistence.Storage) { job := newValidJob(defaultClientID) + message := "message" updatedJob, err := db.UpdateJob(context.Background(), job, - persistence.JobUpdate{Status: &model.JobStatus{Message: "message", State: "ACTIVATING"}}, + persistence.JobUpdate{Status: &api.JobStatus{Message: message, State: "ACTIVATING"}}, ) assert.Error(t, err) assert.Nil(t, updatedJob) diff --git a/internal/persistence/tests/workflow.go b/internal/persistence/tests/workflow.go index 333e342e..4ca49860 100644 --- a/internal/persistence/tests/workflow.go +++ b/internal/persistence/tests/workflow.go @@ -70,15 +70,9 @@ func TestQueryWorkflows(t *testing.T, db persistence.Storage) { require.NoError(t, err) allCount := 1 - result, err := db.QueryWorkflows(context.Background(), persistence.PaginationParams{Offset: 0, Limit: int32(allCount)}) + result, err := db.QueryWorkflows(context.Background(), persistence.SortParams{}, persistence.PaginationParams{Offset: 0, Limit: int32(allCount)}) require.NoError(t, err) assert.Len(t, result.Content, allCount) - - keys := make([]string, 0, len(result.Content)) - for _, workflow := range result.Content { - keys = append(keys, workflow.Name) - } - assert.IsIncreasing(t, keys) } func TestWorkflowsPagination(t *testing.T, db persistence.Storage) { @@ -87,16 +81,46 @@ func TestWorkflowsPagination(t *testing.T, db persistence.Storage) { _, err = db.CreateWorkflow(context.Background(), dau.PhasedWorkflow()) require.NoError(t, err) - result, err := db.QueryWorkflows(context.Background(), persistence.PaginationParams{Offset: 0, Limit: 1}) + result, err := db.QueryWorkflows(context.Background(), persistence.SortParams{}, persistence.PaginationParams{Offset: 0, Limit: 1}) assert.NoError(t, err) assert.Len(t, result.Content, 1) - result2, err := db.QueryWorkflows(context.Background(), persistence.PaginationParams{Offset: 1, Limit: 1}) + result2, err := db.QueryWorkflows(context.Background(), persistence.SortParams{}, persistence.PaginationParams{Offset: 1, Limit: 1}) assert.NoError(t, err) assert.Len(t, result2.Content, 1) assert.NotEqual(t, result.Content[0].Name, result2.Content[0].Name) - result3, err := db.QueryWorkflows(context.Background(), persistence.PaginationParams{Offset: 2, Limit: 1}) + result3, err := db.QueryWorkflows(context.Background(), persistence.SortParams{}, persistence.PaginationParams{Offset: 2, Limit: 1}) assert.NoError(t, err) assert.Len(t, result3.Content, 0) } + +func TestQueryWorkflowsSort(t *testing.T, db persistence.Storage) { + _, _ = db.CreateWorkflow(context.Background(), dau.DirectWorkflow()) + _, _ = db.CreateWorkflow(context.Background(), dau.PhasedWorkflow()) + + allCount := 2 + t.Run("asc", func(t *testing.T) { + result, err := db.QueryWorkflows(context.Background(), persistence.SortParams{Desc: false}, persistence.PaginationParams{Offset: 0, Limit: int32(allCount)}) + require.NoError(t, err) + assert.Len(t, result.Content, allCount) + + keys := make([]string, 0, len(result.Content)) + for _, workflow := range result.Content { + keys = append(keys, workflow.Name) + } + assert.IsIncreasing(t, keys) + }) + + t.Run("desc", func(t *testing.T) { + result, err := db.QueryWorkflows(context.Background(), persistence.SortParams{Desc: true}, persistence.PaginationParams{Offset: 0, Limit: int32(allCount)}) + require.NoError(t, err) + assert.Len(t, result.Content, allCount) + + keys := make([]string, 0, len(result.Content)) + for _, workflow := range result.Content { + keys = append(keys, workflow.Name) + } + assert.IsDecreasing(t, keys) + }) +} diff --git a/internal/producer/json.go b/internal/producer/json.go deleted file mode 100644 index a6068385..00000000 --- a/internal/producer/json.go +++ /dev/null @@ -1,67 +0,0 @@ -package producer - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "encoding/json" - "io" - "net/http" - - "github.com/Southclaws/fault" - "github.com/go-openapi/runtime" - "github.com/itchyny/gojq" - "github.com/rs/zerolog/log" -) - -// JSONProducer creates a new JSON producer. Nil slices are mapped to an empty array instead of "null". -// This is a workaround for https://github.com/golang/go/issues/27589 -func JSONProducer() runtime.Producer { - return runtime.ProducerFunc(func(writer io.Writer, data any) error { - jsonData, err := json.Marshal(data) - if err != nil { - return fault.Wrap(err) - } - - if rw, ok := writer.(http.ResponseWriter); ok { - filter := rw.Header().Get("X-Response-Filter") - if filter != "" { - contextLogger := log.With().Str("filter", filter).Logger() - query, err := gojq.Parse(filter) - if err != nil { - contextLogger.Err(err).Msg("Failed to parse response filter") - return fault.Wrap(err) - } - - var input any - // need to unmarshal again, but to type 'any'; this cannot fail - // because we own the local variable jsonData and know it's - // valid JSON - _ = json.Unmarshal(jsonData, &input) - - contextLogger.Debug().Msg("Applying response filter") - iter := query.Run(input) - ok := true - for ok { - var v any - v, ok = iter.Next() - if ok { - // this cannot fail because we own `input` - jsonData, _ = json.Marshal(v) - if _, err := writer.Write(jsonData); err != nil { - return fault.Wrap(err) - } - } - } - return nil - } - } - _, err = writer.Write(jsonData) - return fault.Wrap(err) - }) -} diff --git a/internal/producer/json_test.go b/internal/producer/json_test.go deleted file mode 100644 index fe77e4ab..00000000 --- a/internal/producer/json_test.go +++ /dev/null @@ -1,121 +0,0 @@ -package producer - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "bytes" - "errors" - "net/http" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestJSONProducer_NilSliceEmpty(t *testing.T) { - var nilSlice []string - buf := new(bytes.Buffer) - err := JSONProducer().Produce(buf, nilSlice) - require.NoError(t, err) - assert.JSONEq(t, "null", buf.String()) -} - -func TestJSONProducer_NilMapEmpty(t *testing.T) { - var nilMap map[string]string - buf := new(bytes.Buffer) - err := JSONProducer().Produce(buf, nilMap) - require.NoError(t, err) - assert.JSONEq(t, "null", buf.String()) -} - -type TestResponseWriter struct { - Headers map[string][]string - Output []byte -} - -func (w *TestResponseWriter) Header() http.Header { - return w.Headers -} - -func (w *TestResponseWriter) Write(buf []byte) (int, error) { - w.Output = buf - return len(buf), nil -} - -func (w *TestResponseWriter) WriteHeader(int) {} - -func TestJSONProducer_ResponseFilter(t *testing.T) { - headers := make(map[string][]string) - headers["X-Response-Filter"] = []string{".name"} - - writer := TestResponseWriter{ - Headers: headers, - Output: make([]byte, 2048), - } - - data := make(map[string]string) - data["name"] = "foo" - data["id"] = "42" - - prod := JSONProducer() - err := prod.Produce(&writer, data) - require.NoError(t, err) - assert.Equal(t, `"foo"`, string(writer.Output)) -} - -type BadMarshal struct{} - -func (bm *BadMarshal) MarshalJSON() ([]byte, error) { - return nil, errors.New("Marshaling this struct always fails") -} - -func TestJSONProducer_BadMarshal(t *testing.T) { - badMarshal := BadMarshal{} - buf := new(bytes.Buffer) - err := JSONProducer().Produce(buf, &badMarshal) - assert.NotNil(t, err) -} - -func TestJSONProducer_BadFilter(t *testing.T) { - headers := make(map[string][]string) - headers["X-Response-Filter"] = []string{"!!!"} - writer := TestResponseWriter{ - Headers: headers, - Output: make([]byte, 2048), - } - - s := "hello world" - err := JSONProducer().Produce(&writer, &s) - assert.NotNil(t, err) -} - -type BadWriter struct { - Headers map[string][]string -} - -func (w *BadWriter) Header() http.Header { - return w.Headers -} - -func (w *BadWriter) Write([]byte) (int, error) { - return 0, errors.New("This writer always fails") -} - -func (w *BadWriter) WriteHeader(int) {} - -func TestJSONProducer_BadWriter(t *testing.T) { - headers := make(map[string][]string) - headers["X-Response-Filter"] = []string{".hello"} - writer := BadWriter{Headers: headers} - - data := make(map[string]string) - data["hello"] = "world" - err := JSONProducer().Produce(&writer, &data) - assert.NotNil(t, err) -} diff --git a/internal/producer/main_test.go b/internal/producer/main_test.go deleted file mode 100644 index 55a26083..00000000 --- a/internal/producer/main_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package producer - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "testing" - - "go.uber.org/goleak" -) - -func TestMain(m *testing.M) { - goleak.VerifyTestMain(m) -} diff --git a/internal/producer/text_event_stream.go b/internal/producer/text_event_stream.go deleted file mode 100644 index 6323fac7..00000000 --- a/internal/producer/text_event_stream.go +++ /dev/null @@ -1,37 +0,0 @@ -package producer - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "encoding/json" - "io" - - "github.com/Southclaws/fault" - "github.com/go-openapi/runtime" -) - -func TextEventStreamProducer() runtime.Producer { - return runtime.ProducerFunc(func(rw io.Writer, data any) error { - if _, err := rw.Write([]byte("data: ")); err != nil { - return fault.Wrap(err) - } - b, err := json.Marshal(data) - if err != nil { - return fault.Wrap(err) - } - if _, err := rw.Write(b); err != nil { - return fault.Wrap(err) - } - // text/event-stream responses are "chunked" with double newline breaks - if _, err := rw.Write([]byte("\n\n")); err != nil { - return fault.Wrap(err) - } - return nil - }) -} diff --git a/internal/producer/text_event_stream_test.go b/internal/producer/text_event_stream_test.go deleted file mode 100644 index 3e356bcd..00000000 --- a/internal/producer/text_event_stream_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package producer - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "bytes" - "testing" - - "github.com/siemens/wfx/generated/model" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestTextEventStreamProducer(t *testing.T) { - prod := TextEventStreamProducer() - event := model.JobStatus{ - ClientID: "foo", - Message: "hello world", - State: "INSTALLING", - } - - buf := new(bytes.Buffer) - err := prod.Produce(buf, event) - require.NoError(t, err) - assert.Equal(t, `data: {"clientId":"foo","message":"hello world","state":"INSTALLING"} - -`, buf.String()) -} diff --git a/internal/server/http.go b/internal/server/http.go index 4262051d..46976238 100644 --- a/internal/server/http.go +++ b/internal/server/http.go @@ -9,40 +9,79 @@ package server */ import ( + "crypto/tls" + "crypto/x509" + "fmt" "net/http" - "time" + "os" - "github.com/go-openapi/runtime/flagext" + "github.com/Southclaws/fault" + "github.com/rs/zerolog/log" + "github.com/siemens/wfx/cmd/wfx/cmd/config" ) -type HTTPSettings struct { - Host string - Port int - TLSHost string - TLSPort int - UDSPath string - MaxHeaderSize flagext.ByteSize - KeepAlive time.Duration - ReadTimeout time.Duration - WriteTimeout time.Duration - CleanupTimeout time.Duration -} - -func NewHTTPServer(settings *HTTPSettings, handler http.Handler) *http.Server { +func NewHTTPServer(cfg *config.AppConfig, handler http.Handler) (*http.Server, error) { server := new(http.Server) - server.MaxHeaderBytes = int(settings.MaxHeaderSize) - server.ReadTimeout = settings.ReadTimeout - server.WriteTimeout = settings.WriteTimeout - server.SetKeepAlivesEnabled(int64(settings.KeepAlive) > 0) + server.MaxHeaderBytes = int(cfg.MaxHeaderSize()) + server.ReadTimeout = cfg.ReadTimeout() + server.WriteTimeout = cfg.WriteTimeout() + server.SetKeepAlivesEnabled(cfg.KeepAlive()) - if int64(settings.CleanupTimeout) > 0 { - server.IdleTimeout = settings.CleanupTimeout + if cfg.CleanupTimeout() > 0 { + server.IdleTimeout = cfg.CleanupTimeout() } + if err := configureTLS(server, cfg.TLSCACertificate()); err != nil { + return nil, fault.Wrap(err) + } + server.Handler = handler + return server, nil +} - if int64(settings.CleanupTimeout) > 0 { - server.IdleTimeout = settings.CleanupTimeout +func configureTLS(server *http.Server, caCert string) error { + // Inspired by https://blog.bracebin.com/achieving-perfect-ssl-labs-score-with-go + server.TLSConfig = &tls.Config{ + // Causes servers to use Go's default ciphersuite preferences, + // which are tuned to avoid attacks. Does nothing on clients. + PreferServerCipherSuites: true, + // Only use curves which have assembly implementations + // https://github.com/golang/go/tree/master/src/crypto/elliptic + CurvePreferences: []tls.CurveID{tls.CurveP256}, + // Use modern tls mode https://wiki.mozilla.org/Security/Server_Side_TLS#Modern_compatibility + NextProtos: []string{"h2", "http/1.1"}, + // https://www.owasp.org/index.php/Transport_Layer_Protection_Cheat_Sheet#Rule_-_Only_Support_Strong_Protocols + MinVersion: tls.VersionTLS12, + // These ciphersuites support Forward Secrecy: https://en.wikipedia.org/wiki/Forward_secrecy + CipherSuites: []uint16{ + tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, + tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, + tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, + tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, + tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, + tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, + }, } - server.Handler = handler - return server + if caCert != "" { + log.Debug(). + Str("caCertificates", caCert). + Msg("Loading CA certs") + // include specified CA certificate + caCert, caCertErr := os.ReadFile(caCert) + if caCertErr != nil { + return fault.Wrap(caCertErr) + } + caCertPool, err := x509.SystemCertPool() + if err != nil { + log.Warn().Err(err).Msg("Failed to load system cert pool, using empty pool") + caCertPool = x509.NewCertPool() + } + caCertPool.AppendCertsFromPEM(caCert) + ok := caCertPool.AppendCertsFromPEM(caCert) + if !ok { + return fmt.Errorf("cannot parse CA certificate") + } + server.TLSConfig.ClientCAs = caCertPool + server.TLSConfig.ClientAuth = tls.RequireAndVerifyClientCert + } + return nil } diff --git a/internal/server/http_test.go b/internal/server/http_test.go index 54fde585..134e0d39 100644 --- a/internal/server/http_test.go +++ b/internal/server/http_test.go @@ -9,27 +9,99 @@ package server */ import ( + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "math/big" "net/http" + "os" + "path" "testing" "time" + "github.com/siemens/wfx/cmd/wfx/cmd/config" + "github.com/spf13/pflag" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) -func TestNewHTTPServer(t *testing.T) { - settings := &HTTPSettings{ - MaxHeaderSize: 1024, - ReadTimeout: 10 * time.Second, - WriteTimeout: 5 * time.Second, - KeepAlive: time.Minute, - CleanupTimeout: 5 * time.Minute, - } +func TestNewHTTPServer_CustomSettings(t *testing.T) { + f := pflag.NewFlagSet("", pflag.ContinueOnError) + f.Int(config.MaxHeaderSizeFlag, 1000000, "controls the maximum number of bytes the server will read parsing the request header's keys and values, including the request line. It does not limit the size of the request body") + f.Duration(config.ReadTimeoutFlag, 30*time.Second, "maximum duration before timing out read of the request") + f.Duration(config.WriteTimoutFlag, 10*time.Minute, "maximum duration before timing out write of the response") + f.Bool(config.KeepAliveFlag, true, "sets the TCP keep-alive timeouts on accepted connections. It prunes dead TCP connections ( e.g. closing laptop mid-download)") + f.Duration(config.CleanupTimeoutFlag, 10*time.Second, "grace period for which to wait before killing idle connections") + _ = f.Parse([]string{"--max-header-size=1024", "--read-timeout=10s", "--write-timeout=5s", "--keep-alive", "--cleanup-timeout=5m"}) + + cfg, err := config.NewAppConfig(f) + require.NoError(t, err) + defer cfg.Stop() handler := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}) - server := NewHTTPServer(settings, handler) + server, err := NewHTTPServer(cfg, handler) + require.NoError(t, err) assert.Equal(t, 1024, server.MaxHeaderBytes) assert.Equal(t, 10*time.Second, server.ReadTimeout) assert.Equal(t, 5*time.Second, server.WriteTimeout) assert.Equal(t, 5*time.Minute, server.IdleTimeout) } + +func TestNewHTTPServer_DefaultSettings(t *testing.T) { + _, err := NewHTTPServer(new(config.AppConfig), nil) + require.NoError(t, err) +} + +func TestConfigureTLS(t *testing.T) { + privateKey, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + + template := x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: pkix.Name{CommonName: "My CA"}, + NotBefore: time.Now(), + NotAfter: time.Now().AddDate(0, 0, 1), // Valid for 1 day + KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, + BasicConstraintsValid: true, + IsCA: true, + } + + derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey) + require.NoError(t, err) + + dir, err := os.MkdirTemp(os.TempDir(), "wfx-tlsca") + require.NoError(t, err) + defer os.RemoveAll(dir) + + caCrtFile := path.Join(dir, "ca.crt") + caKeyFile := path.Join(dir, "ca.key") + { + certOut, err := os.Create(caCrtFile) + require.NoError(t, err) + defer certOut.Close() + + err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) + require.NoError(t, err) + + keyOut, err := os.OpenFile(caKeyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) + require.NoError(t, err) + defer keyOut.Close() + + err = pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}) + require.NoError(t, err) + } + + f := pflag.NewFlagSet("", pflag.ContinueOnError) + f.String(config.TLSCaFlag, "", "the certificate authority certificate file to be used with mutual TLS auth") + _ = f.Parse([]string{"--tls-ca", caCrtFile}) + cfg, err := config.NewAppConfig(f) + require.NoError(t, err) + defer cfg.Stop() + + srv, err := NewHTTPServer(cfg, nil) + require.NoError(t, err) + assert.NotNil(t, srv.TLSConfig.ClientCAs) +} diff --git a/internal/server/tls.go b/internal/server/tls.go deleted file mode 100644 index 58e2fa7d..00000000 --- a/internal/server/tls.go +++ /dev/null @@ -1,82 +0,0 @@ -package server - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "crypto/tls" - "crypto/x509" - "fmt" - "net/http" - "os" - - "github.com/Southclaws/fault" - "github.com/rs/zerolog/log" -) - -type TLSSettings struct { - TLSCertificate string - TLSCertificateKey string - TLSCACertificate string -} - -func ConfigureTLS(server *http.Server, settings *TLSSettings) error { - var err error - - // Inspired by https://blog.bracebin.com/achieving-perfect-ssl-labs-score-with-go - server.TLSConfig = &tls.Config{ - // Causes servers to use Go's default ciphersuite preferences, - // which are tuned to avoid attacks. Does nothing on clients. - PreferServerCipherSuites: true, - // Only use curves which have assembly implementations - // https://github.com/golang/go/tree/master/src/crypto/elliptic - CurvePreferences: []tls.CurveID{tls.CurveP256}, - // Use modern tls mode https://wiki.mozilla.org/Security/Server_Side_TLS#Modern_compatibility - NextProtos: []string{"h2", "http/1.1"}, - // https://www.owasp.org/index.php/Transport_Layer_Protection_Cheat_Sheet#Rule_-_Only_Support_Strong_Protocols - MinVersion: tls.VersionTLS12, - // These ciphersuites support Forward Secrecy: https://en.wikipedia.org/wiki/Forward_secrecy - CipherSuites: []uint16{ - tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, - tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, - tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, - tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, - tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, - tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, - }, - } - - server.TLSConfig.Certificates = make([]tls.Certificate, 1) - log.Debug(). - Str("certificate", settings.TLSCertificate). - Str("certificateKey", settings.TLSCertificateKey). - Msg("Loading X509 keypairs") - server.TLSConfig.Certificates[0], err = tls.LoadX509KeyPair(settings.TLSCertificate, settings.TLSCertificateKey) - if err != nil { - return fault.Wrap(err) - } - - if settings.TLSCACertificate != "" { - log.Debug(). - Str("caCertificates", settings.TLSCACertificate). - Msg("Loading CA certs") - // include specified CA certificate - caCert, caCertErr := os.ReadFile(settings.TLSCACertificate) - if caCertErr != nil { - return fault.Wrap(caCertErr) - } - caCertPool := x509.NewCertPool() - ok := caCertPool.AppendCertsFromPEM(caCert) - if !ok { - return fmt.Errorf("cannot parse CA certificate") - } - server.TLSConfig.ClientCAs = caCertPool - server.TLSConfig.ClientAuth = tls.RequireAndVerifyClientCert - } - return nil -} diff --git a/internal/server/tls_test.go b/internal/server/tls_test.go deleted file mode 100644 index 468e8cbd..00000000 --- a/internal/server/tls_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package server - -import ( - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "crypto/x509/pkix" - "encoding/pem" - "math/big" - "os" - "path" - "testing" - "time" - - "github.com/stretchr/testify/require" -) - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -func TestConfigureTLS_DefaultSettings(t *testing.T) { - srv := NewHTTPServer(&HTTPSettings{}, nil) - err := ConfigureTLS(srv, &TLSSettings{}) - require.Error(t, err) -} - -func TestConfigureTLS(t *testing.T) { - privateKey, err := rsa.GenerateKey(rand.Reader, 2048) - require.NoError(t, err) - - template := x509.Certificate{ - SerialNumber: big.NewInt(1), - Subject: pkix.Name{CommonName: "My CA"}, - NotBefore: time.Now(), - NotAfter: time.Now().AddDate(0, 0, 1), // Valid for 1 day - KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, - BasicConstraintsValid: true, - IsCA: true, - } - - derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey) - require.NoError(t, err) - - dir, err := os.MkdirTemp(os.TempDir(), "wfx-tlsca") - require.NoError(t, err) - defer os.RemoveAll(dir) - - caCrtFile := path.Join(dir, "ca.crt") - caKeyFile := path.Join(dir, "ca.key") - { - certOut, err := os.Create(caCrtFile) - require.NoError(t, err) - defer certOut.Close() - - err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) - require.NoError(t, err) - - keyOut, err := os.OpenFile(caKeyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) - require.NoError(t, err) - defer keyOut.Close() - - err = pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}) - require.NoError(t, err) - } - - srv := NewHTTPServer(&HTTPSettings{}, nil) - err = ConfigureTLS(srv, &TLSSettings{ - TLSCACertificate: caCrtFile, - TLSCertificate: caCrtFile, - TLSCertificateKey: caKeyFile, - }) - require.NoError(t, err) -} diff --git a/internal/workflow/workflow.go b/internal/workflow/workflow.go index 502a2d1c..0e33375c 100644 --- a/internal/workflow/workflow.go +++ b/internal/workflow/workflow.go @@ -11,11 +11,11 @@ package workflow import ( "sort" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" ) // FindStateGroup tries to find the group of a state. If not found, it returns the empty string. -func FindStateGroup(workflow *model.Workflow, state string) string { +func FindStateGroup(workflow *api.Workflow, state string) string { for _, group := range workflow.Groups { for _, s := range group.States { if s == state { @@ -27,11 +27,11 @@ func FindStateGroup(workflow *model.Workflow, state string) string { } // FollowImmediateTransitions follows the edges of type `actor` starting at the `from` state. -func FollowImmediateTransitions(workflow *model.Workflow, from string) string { +func FollowImmediateTransitions(workflow *api.Workflow, from string) string { // map of transitions which we handle jump := make(map[string]string, len(workflow.Transitions)) for _, t := range workflow.Transitions { - if t.Eligible == model.EligibleEnumWFX && t.Action == model.ActionEnumIMMEDIATE { + if t.Eligible == api.WFX && t.Action != nil && *t.Action == api.IMMEDIATE { jump[t.From] = t.To } } @@ -48,7 +48,7 @@ func FollowImmediateTransitions(workflow *model.Workflow, from string) string { } } -func FindInitialState(workflow *model.Workflow) *string { +func FindInitialState(workflow *api.Workflow) *string { parent := make(map[string]string, len(workflow.States)) for _, state := range workflow.States { parent[state.Name] = "" @@ -67,14 +67,16 @@ func FindInitialState(workflow *model.Workflow) *string { return nil } -func FindFinalStates(workflow *model.Workflow) []string { +func FindFinalStates(workflow *api.Workflow) []string { finalStateMap := make(map[string]bool, len(workflow.States)) // add all states and then remove the ones that are not final for _, state := range workflow.States { finalStateMap[state.Name] = true } - for _, transition := range workflow.Transitions { - delete(finalStateMap, transition.From) + if workflow.Transitions != nil { + for _, transition := range workflow.Transitions { + delete(finalStateMap, transition.From) + } } finalStates := make([]string, 0, len(finalStateMap)) for name := range finalStateMap { diff --git a/internal/workflow/workflow_test.go b/internal/workflow/workflow_test.go index 2cd64552..4e4659dd 100644 --- a/internal/workflow/workflow_test.go +++ b/internal/workflow/workflow_test.go @@ -11,7 +11,7 @@ package workflow import ( "testing" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/workflow/dau" "github.com/stretchr/testify/assert" ) @@ -34,15 +34,15 @@ func TestFollowTransitions(t *testing.T) { c := "c" d := "d" - eligibleWfx := model.EligibleEnumWFX - - transitions := []*model.Transition{ - {From: a, To: b, Eligible: eligibleWfx, Action: model.ActionEnumIMMEDIATE}, - {From: b, To: c, Eligible: eligibleWfx, Action: model.ActionEnumIMMEDIATE}, - {From: c, To: d, Eligible: eligibleWfx, Action: model.ActionEnumIMMEDIATE}, + eligibleWfx := api.WFX + immediate := api.IMMEDIATE + transitions := []api.Transition{ + {From: a, To: b, Eligible: eligibleWfx, Action: &immediate}, + {From: b, To: c, Eligible: eligibleWfx, Action: &immediate}, + {From: c, To: d, Eligible: eligibleWfx, Action: &immediate}, } - actual := FollowImmediateTransitions(&model.Workflow{Transitions: transitions}, "a") + actual := FollowImmediateTransitions(&api.Workflow{Transitions: transitions}, "a") assert.Equal(t, d, actual, "should warp from a to d") } diff --git a/justfile b/justfile index 95692424..6bdf5932 100644 --- a/justfile +++ b/justfile @@ -88,25 +88,13 @@ format: prettier -l -w . just --fmt --unstable -_generate-swagger: +_generate-openapi: #!/usr/bin/env bash - set -euxo pipefail - cd "{{ THISDIR }}/generated" - - # remove existing code - for dir in client model northbound southbound; do - find $dir -not -name configure_workflow_executor.go -type f -delete - done - - # generate spec (inline anchors) - just -d . --justfile ../spec/justfile generate wfx.swagger.yml - swagger generate model --copyright-file=../spec/spdx.txt --target=. --model-package=model --spec=wfx.swagger.yml - - for target in northbound southbound; do - swagger generate server --copyright-file=../spec/spdx.txt --target=$target --spec=wfx.swagger.yml --exclude-main --skip-models --model-package=model --existing-models=github.com/siemens/wfx/generated/model --flag-strategy=pflag --tags=$target - rm -f $target/restapi/server.go - done - swagger generate client --copyright-file=../spec/spdx.txt --target=. --model-package=model --spec=wfx.swagger.yml --skip-models --existing-models=github.com/siemens/wfx/generated/model + set -euo pipefail + source "{{ THISDIR }}/.ci/packages/versions.env" + cd "{{ THISDIR }}/spec" + set -x + go run "github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen@v${OAPI_CODEGEN_VERSION}" -config cfg.yaml wfx.openapiv3.yml _generate-ent: #!/usr/bin/env bash @@ -131,14 +119,15 @@ _generate-flatbuffers: gofumpt -l -w generated/plugin # Generate code -generate: _generate-swagger _generate-ent _generate-mockery _generate-flatbuffers +generate: _generate-openapi _generate-ent _generate-mockery _generate-flatbuffers # Start PostgreSQL container -postgres-start VERSION="15": +postgres-start: #!/usr/bin/env bash count=`{{ DOCKER }} container ls --quiet --noheading --filter name=wfx-postgres --filter "health=healthy" | wc -l` + image=`grep -m1 -o "image: postgres:.*" .github/workflows/ci.yml | sed -e 's/image:\s*//'` if [[ $count -eq 0 ]]; then - echo "Starting PostgreSQL {{ VERSION }}" + echo "Starting $image" {{ DOCKER }} run -d --rm \ --name wfx-postgres \ -e "POSTGRES_USER=$PGUSER" \ @@ -149,7 +138,7 @@ postgres-start VERSION="15": --health-interval 3s \ --health-timeout 5s \ --health-retries 20 \ - docker.io/library/postgres:{{ VERSION }}-alpine + "docker.io/library/$image" else echo "PostgreSQL is already running" fi @@ -203,8 +192,9 @@ _container-stop name: mysql-start: #!/usr/bin/env bash count=`{{ DOCKER }} container ls --quiet --noheading --filter name=wfx-mysql --filter "health=healthy" | wc -l` + image=`grep -m1 -o "image: mysql:.*" .github/workflows/ci.yml | sed -e 's/image:\s*//'` if [[ $count -eq 0 ]]; then - echo "Starting MySQL" + echo "Starting $image" {{ DOCKER }} run -d --rm \ --name wfx-mysql \ -e MYSQL_DATABASE \ @@ -214,7 +204,7 @@ mysql-start: --health-interval 3s \ --health-timeout 5s \ --health-retries 20 \ - docker.io/library/mysql:8-debian + "docker.io/library/$image" else echo "MySQL is already running" fi diff --git a/middleware/fileserver/fileserver.go b/middleware/fileserver/fileserver.go deleted file mode 100644 index 644b3c62..00000000 --- a/middleware/fileserver/fileserver.go +++ /dev/null @@ -1,65 +0,0 @@ -package fileserver - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "fmt" - "net/http" - "os" - "strings" - - "github.com/Southclaws/fault" - "github.com/knadh/koanf/v2" - "github.com/rs/zerolog/log" - "github.com/siemens/wfx/internal/config" -) - -const ( - SimpleFileServerFlag = "simple-fileserver" -) - -type MW struct { - k *config.ThreadSafeKoanf -} - -func NewFileServerMiddleware(k *config.ThreadSafeKoanf) (*MW, error) { - var rootDir string - k.Read(func(k *koanf.Koanf) { - rootDir = k.String(SimpleFileServerFlag) - }) - if rootDir != "" { - info, err := os.Stat(rootDir) - if err != nil { - return nil, fault.Wrap(err) - } - if !info.IsDir() { - return nil, fmt.Errorf("%s is not a directory", rootDir) - } - log.Info().Str("dir", rootDir).Msg("Fileserver is enabled") - } - return &MW{k: k}, nil -} - -func (mw MW) Wrap(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if strings.HasPrefix(r.URL.Path, "/download") { - var rootDir string - mw.k.Read(func(k *koanf.Koanf) { - rootDir = k.String(SimpleFileServerFlag) - }) - if rootDir != "" { - http.StripPrefix("/download", http.FileServer(http.Dir(rootDir))).ServeHTTP(w, r) - return - } - } - next.ServeHTTP(w, r) - }) -} - -func (mw MW) Shutdown() {} diff --git a/middleware/fileserver/fileserver_test.go b/middleware/fileserver/fileserver_test.go deleted file mode 100644 index ee72dcdf..00000000 --- a/middleware/fileserver/fileserver_test.go +++ /dev/null @@ -1,120 +0,0 @@ -package fileserver - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "fmt" - "io" - "net/http" - "net/http/httptest" - "os" - "path" - "testing" - - "github.com/knadh/koanf/v2" - "github.com/siemens/wfx/internal/config" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestFileServerMiddleware_Fallback(t *testing.T) { - dir, err := os.MkdirTemp(os.TempDir(), "wfx-fileservertest") - require.NoError(t, err) - defer os.RemoveAll(dir) - - k := config.New() - k.Write(func(k *koanf.Koanf) { - _ = k.Set(SimpleFileServerFlag, dir) - }) - - fsMW, err := NewFileServerMiddleware(k) - require.Nil(t, err) - handler := fsMW.Wrap(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - fmt.Fprintln(w, "Hello, client") - })) - - req := httptest.NewRequest(http.MethodGet, "/foo", nil) - w := httptest.NewRecorder() - handler.ServeHTTP(w, req) - - res := w.Result() - defer res.Body.Close() - b, _ := io.ReadAll(res.Body) - assert.Equal(t, "Hello, client\n", string(b)) -} - -func TestFileServerMiddleware_Download(t *testing.T) { - dir, err := os.MkdirTemp(os.TempDir(), "wfx-fileservertest") - require.NoError(t, err) - defer os.RemoveAll(dir) - err = os.WriteFile(path.Join(dir, "hello"), []byte("world"), 0o644) - require.NoError(t, err) - - k := config.New() - k.Write(func(k *koanf.Koanf) { - _ = k.Set(SimpleFileServerFlag, dir) - }) - - fsMW, err := NewFileServerMiddleware(k) - require.Nil(t, err) - handler := fsMW.Wrap(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - fmt.Fprintln(w, "Hello, client") - })) - - req := httptest.NewRequest(http.MethodGet, "/download/hello", nil) - w := httptest.NewRecorder() - handler.ServeHTTP(w, req) - - res := w.Result() - defer res.Body.Close() - b, _ := io.ReadAll(res.Body) - assert.Equal(t, "world", string(b)) -} - -func TestFileServerMiddleware_DirNotExist(t *testing.T) { - k := config.New() - k.Write(func(k *koanf.Koanf) { - _ = k.Set(SimpleFileServerFlag, "/this/dir/does/not/exist") - }) - fsMW, err := NewFileServerMiddleware(k) - assert.Nil(t, fsMW) - assert.NotNil(t, err) - assert.ErrorContains(t, err, "no such file or directory") -} - -func TestFileServerMiddleware_DirIsFile(t *testing.T) { - tmpFile, _ := os.CreateTemp(os.TempDir(), "wfx-cert-") - _, _ = tmpFile.Write([]byte("hello world")) - defer os.Remove(tmpFile.Name()) - - k := config.New() - k.Write(func(k *koanf.Koanf) { - _ = k.Set(SimpleFileServerFlag, tmpFile.Name()) - }) - fsMW, err := NewFileServerMiddleware(k) - assert.Nil(t, fsMW) - assert.NotNil(t, err) - assert.ErrorContains(t, err, "not a directory") -} - -func TestFileServerMiddleware_404(t *testing.T) { - k := config.New() - fsMW, err := NewFileServerMiddleware(k) - require.Nil(t, err) - handler := fsMW.Wrap(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusNotFound) - })) - - req := httptest.NewRequest(http.MethodGet, "/download", nil) - w := httptest.NewRecorder() - handler.ServeHTTP(w, req) - - res := w.Result() - assert.Equal(t, http.StatusNotFound, res.StatusCode) -} diff --git a/middleware/fileserver/main_test.go b/middleware/fileserver/main_test.go deleted file mode 100644 index d5c0f093..00000000 --- a/middleware/fileserver/main_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package fileserver - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "testing" - - "go.uber.org/goleak" -) - -func TestMain(m *testing.M) { - goleak.VerifyTestMain(m) -} diff --git a/middleware/health/health.go b/middleware/health/health.go deleted file mode 100644 index c7f26206..00000000 --- a/middleware/health/health.go +++ /dev/null @@ -1,82 +0,0 @@ -package health - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "context" - "net/http" - "strings" - "time" - - "github.com/Southclaws/fault" - "github.com/alexliesenfeld/health" - "github.com/rs/zerolog/log" - - "github.com/siemens/wfx/persistence" -) - -type MW struct { - checker health.Checker - health http.Handler -} - -func NewHealthMiddleware(storage persistence.Storage) MW { - log.Debug().Msg("Adding health middleware") - - checker := health.NewChecker( - health.WithTimeout(10*time.Second), - health.WithPeriodicCheck(30*time.Second, 3*time.Second, health.Check{ - Name: "persistence", - Check: func(ctx context.Context) error { - if storage == nil { - return nil - } - return fault.Wrap(storage.CheckHealth(ctx)) - }, - }), - health.WithStatusListener(statusListener)) - - return MW{ - checker: checker, - health: health.NewHandler(checker), - } -} - -func (mw MW) Wrap(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if strings.HasPrefix(r.URL.Path, "/health") { - mw.health.ServeHTTP(w, r) - return - } - next.ServeHTTP(w, r) - }) -} - -func (mw MW) Shutdown() { - mw.checker.Stop() -} - -func statusListener(_ context.Context, state health.CheckerState) { - logFn := log.Warn - switch state.Status { - case health.StatusDown: - logFn = log.Error - case health.StatusUp: - logFn = log.Info - case health.StatusUnknown: - logFn = log.Warn - } - - childLog := logFn() - for k, v := range state.CheckState { - childLog.Str(k, string(v.Status)) - } - - childLog.Str("overall", string(state.Status)).Msg("Health status changed") -} diff --git a/middleware/health/health_test.go b/middleware/health/health_test.go deleted file mode 100644 index 8f796f68..00000000 --- a/middleware/health/health_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package health - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "context" - "encoding/json" - "io" - "testing" - - "github.com/alexliesenfeld/health" - "github.com/steinfletcher/apitest" - "github.com/stretchr/testify/require" -) - -func TestNewHealthMiddleware(t *testing.T) { - mw := NewHealthMiddleware(nil) - defer mw.Shutdown() - - result := apitest.New(). - Handler(mw.Wrap(nil)). - Get("/health"). - Expect(t). - End() - - raw, err := io.ReadAll(result.Response.Body) - require.NoError(t, err) - var checkResult health.CheckerResult - err = json.Unmarshal(raw, &checkResult) - require.NoError(t, err) -} - -func TestStatusListener(*testing.T) { - statusListener(context.Background(), health.CheckerState{Status: health.StatusUp}) - statusListener(context.Background(), health.CheckerState{Status: health.StatusDown}) - statusListener(context.Background(), health.CheckerState{Status: health.StatusUnknown}) - statusListener(context.Background(), health.CheckerState{ - Status: health.StatusUp, - CheckState: map[string]health.CheckState{ - "db": {Status: health.StatusUp}, - }, - }) -} diff --git a/middleware/jq/gojq.go b/middleware/jq/gojq.go deleted file mode 100644 index 239b8354..00000000 --- a/middleware/jq/gojq.go +++ /dev/null @@ -1,27 +0,0 @@ -package jq - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "net/http" -) - -type MW struct{} - -func (mw MW) Wrap(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - filter := r.Header.Get("X-Response-Filter") - if filter != "" { - w.Header().Set("X-Response-Filter", filter) - } - next.ServeHTTP(w, r) - }) -} - -func (mw MW) Shutdown() {} diff --git a/middleware/jq/gojq_test.go b/middleware/jq/gojq_test.go deleted file mode 100644 index a94cd9f2..00000000 --- a/middleware/jq/gojq_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package jq - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "fmt" - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestNewJqMiddleware(t *testing.T) { - mw := MW{} - handler := mw.Wrap(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - fmt.Fprintln(w, "Hello, client") - })) - - w := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/foo", nil) - req.Header["X-Response-Filter"] = []string{".name"} - handler.ServeHTTP(w, req) - - resp := w.Result() - assert.Equal(t, []string{".name"}, resp.Header["X-Response-Filter"]) -} diff --git a/middleware/jq/main_test.go b/middleware/jq/main_test.go deleted file mode 100644 index be54c8c4..00000000 --- a/middleware/jq/main_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package jq - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "testing" - - "go.uber.org/goleak" -) - -func TestMain(m *testing.M) { - goleak.VerifyTestMain(m) -} diff --git a/middleware/logging/log.go b/middleware/logging/log.go index fc1fb05b..c0a04f10 100644 --- a/middleware/logging/log.go +++ b/middleware/logging/log.go @@ -28,61 +28,59 @@ const ( KeyRequestLogger key = iota ) -type MW struct{} - -func (mw MW) Wrap(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - start := time.Now() - reqID := uuid.New().String() - var path string - if r.URL != nil { - path = r.URL.Path - } - contextLogger := log.With(). - Str("reqID", reqID). - Str("remoteAddr", r.RemoteAddr). - Str("method", r.Method). - Str("path", path). - Str("host", r.Host). - Bool("tls", r.TLS != nil). - Logger() - contextLogger.Debug().Msg("Processing incoming request") +func NewLoggingMiddleware() func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + reqID := uuid.New().String() + var path string + if r.URL != nil { + path = r.URL.Path + } + contextLogger := log.With(). + Str("reqID", reqID). + Str("remoteAddr", r.RemoteAddr). + Str("method", r.Method). + Str("path", path). + Str("host", r.Host). + Bool("tls", r.TLS != nil). + Logger() + contextLogger.Debug().Msg("Processing incoming request") - l := log.With().Str("reqID", reqID).Logger() - ctx := context.WithValue(r.Context(), KeyRequestLogger, l) - r = r.WithContext(ctx) + l := log.With().Str("reqID", reqID).Logger() + ctx := context.WithValue(r.Context(), KeyRequestLogger, l) + r = r.WithContext(ctx) - tracing := contextLogger.GetLevel() <= zerolog.TraceLevel - writer := newMyResponseWriter(w, tracing) - if tracing { - request, err := PeekBody(r) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - return + tracing := contextLogger.GetLevel() <= zerolog.TraceLevel + writer := newMyResponseWriter(w, tracing) + if tracing { + request, err := PeekBody(r) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + return + } + contextLogger.Trace(). + Bytes("request", request). + Msg("Request") } - contextLogger.Trace(). - Bytes("request", request). - Msg("Request") - } - next.ServeHTTP(writer, r) - if response := writer.responseBody.Bytes(); len(response) > 0 { - if json.Valid(response) { - contextLogger.Trace().RawJSON("response", response).Msg("Response") - } else { // body is not in JSON format - contextLogger.Trace().Bytes("response", response).Msg("Response") + next.ServeHTTP(writer, r) + if response := writer.responseBody.Bytes(); len(response) > 0 { + if json.Valid(response) { + contextLogger.Trace().RawJSON("response", response).Msg("Response") + } else { // body is not in JSON format + contextLogger.Trace().Bytes("response", response).Msg("Response") + } } - } - contextLogger.Info(). - TimeDiff("duration", time.Now(), start). - Int("code", writer.statusCode). - Msg("Finished request") - }) + contextLogger.Info(). + TimeDiff("duration", time.Now(), start). + Int("code", writer.statusCode). + Msg("Finished request") + }) + } } -func (mw MW) Shutdown() {} - func LoggerFromCtx(ctx context.Context) zerolog.Logger { if log, ok := ctx.Value(KeyRequestLogger).(zerolog.Logger); ok { return log diff --git a/middleware/logging/log_test.go b/middleware/logging/log_test.go index 34d9c9a4..3ed94a88 100644 --- a/middleware/logging/log_test.go +++ b/middleware/logging/log_test.go @@ -23,8 +23,8 @@ import ( ) func TestLog(t *testing.T) { - mw := MW{} - handler := mw.Wrap(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + mw := NewLoggingMiddleware() + handler := mw(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { fmt.Fprintln(w, "Hello, client") })) @@ -39,11 +39,10 @@ func TestLog(t *testing.T) { assert.NoError(t, err) assert.Equal(t, "Hello, client\n", string(greeting)) - mw.Shutdown() } func TestLogDebug(t *testing.T) { - handler := MW{}.Wrap(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + handler := NewLoggingMiddleware()(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { fmt.Fprintln(w, "Hello, client") })) @@ -88,7 +87,7 @@ func TestPeekBody_ReadFailure(t *testing.T) { _, err := PeekBody(r) assert.NotNil(t, err) - handler := MW{}.Wrap(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + handler := NewLoggingMiddleware()(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { fmt.Fprintln(w, "Hello, client") })) rec := httptest.NewRecorder() diff --git a/middleware/plugin/fbplugin.go b/middleware/plugin/fbplugin.go index 23f4a8b1..7818b6c0 100644 --- a/middleware/plugin/fbplugin.go +++ b/middleware/plugin/fbplugin.go @@ -24,6 +24,9 @@ import ( "github.com/siemens/wfx/middleware/plugin/ioutil" ) +// compile-time check to ensure we fulfill the interface +var _ Plugin = (*FBPlugin)(nil) + // FBPlugin is a plugin which communicates using FlatBuffer messages. type FBPlugin struct { path string @@ -31,11 +34,10 @@ type FBPlugin struct { responses map[uint64]chan genPlugin.PluginResponseT responsesMutex sync.Mutex - cmd *exec.Cmd - waited atomic.Bool - stopped atomic.Bool - - chQuit chan error + cmd *exec.Cmd + waited atomic.Bool + stopCalled atomic.Bool + chErr chan error } // NewFBPlugin creates a new plugin instance. In order to start the plugin, call @@ -48,14 +50,13 @@ func (p *FBPlugin) Name() string { return p.path } -func (p *FBPlugin) Start(chQuit chan error) (chan Message, error) { +func (p *FBPlugin) Start(chErr chan error) (chan Message, error) { log.Info().Str("path", p.path).Msg("Starting plugin") cmd := createCmd(p.path) - p.chQuit = chQuit - // this ensures that a process group is created (needed to kill all child processes) p.responses = make(map[uint64]chan genPlugin.PluginResponseT) + p.chErr = chErr stdin, err := cmd.StdinPipe() if err != nil { @@ -78,10 +79,12 @@ func (p *FBPlugin) Start(chQuit chan error) (chan Message, error) { log.Debug().Str("path", cmd.Path).Msg("Plugin started") go func() { // our reaper + defer close(chErr) _ = cmd.Wait() + log.Debug().Msg("Plugin subprocess has exited") p.waited.Store(true) - if !p.stopped.Load() { - chQuit <- fmt.Errorf("plugin '%s' is down, shutdown necessary", p.Name()) + if !p.stopCalled.Load() { + chErr <- fmt.Errorf("plugin '%s' stopped unexpectedly", p.Name()) } }() @@ -96,14 +99,14 @@ func (p *FBPlugin) Start(chQuit chan error) (chan Message, error) { func (p *FBPlugin) Stop() error { log.Info().Str("path", p.path).Msg("Stopping plugin") - stopped := p.stopped.Swap(true) - if stopped || p.cmd == nil { + alreadyStopped := p.stopCalled.Swap(true) + alreadyWaited := p.waited.Load() + if alreadyStopped || alreadyWaited || p.cmd == nil { + log.Debug().Str("path", p.path).Msg("Plugin already stopped") return nil } - if !p.waited.Load() { - return fault.Wrap(p.terminateProcess()) - } - return nil + + return fault.Wrap(p.terminateProcess()) } func (p *FBPlugin) sender(w io.Writer, chMessage <-chan Message) { @@ -139,8 +142,8 @@ func (p *FBPlugin) receiver(r io.Reader) { delete(p.responses, cookie) p.responsesMutex.Unlock() if !ok { - log.Warn().Uint64("cookie", cookie).Msg("Received unexpected response from plugin") - p.chQuit <- errors.New("received unexpected response from plugin") + log.Error().Uint64("cookie", cookie).Msg("Received unexpected response from plugin") + _ = p.terminateProcess() // this results in wfx stopping gracefully because the plugin stops without Stop() being called break } chResp <- *resp diff --git a/middleware/plugin/fbplugin_test.go b/middleware/plugin/fbplugin_test.go index ee2c7f69..9d5a2174 100644 --- a/middleware/plugin/fbplugin_test.go +++ b/middleware/plugin/fbplugin_test.go @@ -42,9 +42,8 @@ func TestStopWithoutStart(t *testing.T) { func TestStop(t *testing.T) { p := NewFBPlugin("cat") - chQuit := make(chan error) - ch, err := p.Start(chQuit) - t.Cleanup(func() { close(ch) }) + chErr := make(chan error) + chMessages, err := p.Start(chErr) require.NoError(t, err) err = p.Stop() @@ -52,15 +51,22 @@ func TestStop(t *testing.T) { err = p.Stop() assert.NoError(t, err) + + select { + case err := <-chErr: + assert.NoError(t, err) + default: + // + } + + close(chMessages) } func TestSendAndReceive(t *testing.T) { p := NewFBPlugin("cat") - chQuit := make(chan error) - ch, err := p.Start(chQuit) - t.Cleanup(func() { close(ch) }) + chErr := make(chan error) + chMessages, err := p.Start(chErr) require.NoError(t, err) - t.Cleanup(func() { _ = p.Stop() }) headers := make(map[string][]string) headers["Content-Type"] = []string{"application/json"} @@ -79,26 +85,22 @@ func TestSendAndReceive(t *testing.T) { response: make(chan plugin.PluginResponseT, 1), } // send message to plugin - ch <- msg + chMessages <- msg // wait for response resp := <-msg.response assert.Equal(t, req.Cookie, resp.Cookie) + + close(chMessages) + _ = p.Stop() + + select { + case err := <-chErr: + assert.NoError(t, err) + default: + // + } } func TestName(t *testing.T) { assert.Equal(t, "true", NewFBPlugin("true").Name()) } - -func TestStart_Reaper(t *testing.T) { - p := NewFBPlugin("cat") - chQuit := make(chan error) - ch, err := p.Start(chQuit) - assert.NoError(t, err) - - _ = p.terminateProcess() - - err = <-chQuit - assert.NotNil(t, err) - - t.Cleanup(func() { close(ch) }) -} diff --git a/middleware/plugin/middleware.go b/middleware/plugin/middleware.go index c77975a8..e0b7d3d7 100644 --- a/middleware/plugin/middleware.go +++ b/middleware/plugin/middleware.go @@ -9,7 +9,6 @@ package plugin */ import ( - "errors" "net/http" "net/url" "sync/atomic" @@ -22,114 +21,126 @@ import ( "github.com/siemens/wfx/middleware/logging" ) -type MW struct { - plugin Plugin - chMessage chan Message - chQuit chan error +type Middleware struct { + plugin Plugin + cookieCounter atomic.Uint64 + chMessages chan Message + chStop chan struct{} + chErr chan error } -func NewMiddleware(plugin Plugin, chQuit chan error) (*MW, error) { - contextLogger := log.With().Str("plugin", plugin.Name()).Logger() - contextLogger.Debug().Msg("Creating new plugin middleware") - chMessage, err := plugin.Start(chQuit) +func NewMiddleware(plugin Plugin, chErr chan error) (*Middleware, error) { + log.Debug().Str("plugin", plugin.Name()).Msg("Creating plugin middleware") + chMessages, err := plugin.Start(chErr) if err != nil { - _ = plugin.Stop() return nil, fault.Wrap(err) } - return &MW{ - plugin: plugin, - chMessage: chMessage, - chQuit: chQuit, + return &Middleware{ + plugin: plugin, + chMessages: chMessages, + chStop: make(chan struct{}), + chErr: chErr, }, nil } -func (mw *MW) Wrap(next http.Handler) http.Handler { - var cookieCounter atomic.Uint64 - - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - log := logging.LoggerFromCtx(r.Context()).With().Str("plugin", mw.plugin.Name()).Logger() - - req := convertRequest(r, cookieCounter.Add(1)) - msg := Message{ - request: req, - response: make(chan genPlugin.PluginResponseT, 1), - } - - log.Debug().Msg("Sending request to plugin") - start := time.Now() - mw.chMessage <- msg - log.Debug().Msg("Waiting for plugin response") - resp := <-msg.response - duration := time.Since(start) - log.Debug().Dur("duration", duration).Msg("Received plugin response") - - if resp.Payload != nil { - switch resp.Payload.Type { - case genPlugin.Payloadgenerated_plugin_client_Response: - log.Debug().Msg("Sending response provided by plugin") - val := resp.Payload.Value.(*client.ResponseT) - for _, h := range val.Envelope { - for _, value := range h.Values { - w.Header().Add(h.Name, value) - } - } - switch val.Status { - case client.ResponseStatusAccept: - w.WriteHeader(http.StatusOK) - case client.ResponseStatusModified: - w.WriteHeader(http.StatusOK) - case client.ResponseStatusDeny: - w.WriteHeader(http.StatusForbidden) - case client.ResponseStatusUnavailable: - w.WriteHeader(http.StatusServiceUnavailable) - } - _, _ = w.Write(val.Content) - return - case genPlugin.Payloadgenerated_plugin_client_Request: - log.Info().Msg("Request was modified by plugin") - // override http.Request with the response - val := resp.Payload.Value.(*client.RequestT) - - if parsedURL, err := url.Parse(val.Destination); err != nil { - log.Err(err).Str("destination", val.Destination).Msg("Failed to parse destination") - } else { - r.URL = parsedURL - } +func (mw *Middleware) Stop() { + close(mw.chStop) + close(mw.chMessages) + if err := mw.plugin.Stop(); err != nil { + log.Err(err).Str("path", mw.plugin.Name()).Msg("There was an error while stopping the plugin") + } + log.Debug().Msg("Plugin stopped") +} - // delete existing headers - for k := range r.Header { - delete(r.Header, k) - } - if len(val.Envelope) > 0 { - if r.Header == nil { - r.Header = make(http.Header) - } +func (mw *Middleware) Middleware() func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + log := logging.LoggerFromCtx(r.Context()).With().Str("plugin", mw.plugin.Name()).Logger() + + req := convertRequest(r, mw.cookieCounter.Add(1)) + msg := Message{ + request: req, + response: make(chan genPlugin.PluginResponseT, 1), + } + + log.Debug().Msg("Sending request to plugin") + start := time.Now() + select { + case <-mw.chStop: + // avoid sending messages to a closed channel + case mw.chMessages <- msg: + // channel not closed, message was sent + } + + log.Debug().Msg("Waiting for plugin response") + resp := <-msg.response + duration := time.Since(start) + log.Debug().Dur("duration", duration).Msg("Received plugin response") + + if resp.Payload != nil { + switch resp.Payload.Type { + case genPlugin.Payloadgenerated_plugin_client_Response: + log.Debug().Msg("Sending response provided by plugin") + val := resp.Payload.Value.(*client.ResponseT) for _, h := range val.Envelope { for _, value := range h.Values { - r.Header.Add(h.Name, value) + w.Header().Add(h.Name, value) } } + switch val.Status { + case client.ResponseStatusAccept: + w.WriteHeader(http.StatusOK) + case client.ResponseStatusModified: + w.WriteHeader(http.StatusOK) + case client.ResponseStatusDeny: + w.WriteHeader(http.StatusForbidden) + case client.ResponseStatusUnavailable: + w.WriteHeader(http.StatusServiceUnavailable) + } + _, _ = w.Write(val.Content) + return + case genPlugin.Payloadgenerated_plugin_client_Request: + log.Info().Msg("Request was modified by plugin") + // override http.Request with the response + val := resp.Payload.Value.(*client.RequestT) + + if parsedURL, err := url.Parse(val.Destination); err != nil { + log.Err(err).Str("destination", val.Destination).Msg("Failed to parse destination") + } else { + r.URL = parsedURL + } + + // delete existing headers + for k := range r.Header { + delete(r.Header, k) + } + if len(val.Envelope) > 0 { + if r.Header == nil { + r.Header = make(http.Header) + } + for _, h := range val.Envelope { + for _, value := range h.Values { + r.Header.Add(h.Name, value) + } + } + } + default: + // shouldn't happen, but it's possible; maybe a plugin version + // mismatch or just a poorly written plugin, in any case we + // don't want to continue. + log.Error().Int("type", int(resp.Payload.Type)).Msg("Received unsupported payload type from plugin") + w.WriteHeader(http.StatusInternalServerError) + return } - default: - // shouldn't happen, but it's possible; maybe a plugin version - // mismatch or just a poorly written plugin, in any case we - // don't want to continue. - log.Error().Int("type", int(resp.Payload.Type)).Msg("Received unsupported payload type from plugin") - mw.chQuit <- errors.New("unsupported payload type") - w.WriteHeader(http.StatusInternalServerError) - return } - } - log.Debug().Msg("Request may continue") - next.ServeHTTP(w, r) - }) + log.Debug().Msg("Request may continue") + next.ServeHTTP(w, r) + }) + } } -func (mw *MW) Shutdown() { - close(mw.chMessage) - if err := mw.plugin.Stop(); err != nil { - log.Err(err).Str("path", mw.plugin.Name()).Msg("There was an error while stopping the plugin") - } +func (mw *Middleware) Errors() <-chan error { + return mw.chErr } func convertRequest(r *http.Request, cookie uint64) *genPlugin.PluginRequestT { diff --git a/middleware/plugin/middleware_test.go b/middleware/plugin/middleware_test.go index afc42dad..eacdf0bd 100644 --- a/middleware/plugin/middleware_test.go +++ b/middleware/plugin/middleware_test.go @@ -31,11 +31,9 @@ func (p StartFailPlugin) Stop() error { return nil } func TestNewMiddleware_StartFails(t *testing.T) { p := StartFailPlugin{} - chQuit := make(chan error) - mw, err := NewMiddleware(p, chQuit) + mw, err := NewMiddleware(p, make(chan error)) assert.Error(t, err) assert.Nil(t, mw) - _ = p.Stop() } type TestPlugin struct{ chMessage chan Message } @@ -69,12 +67,11 @@ func TestNewMiddleware_ModifyRequest(t *testing.T) { } }() - chQuit := make(chan error) - mw, err := NewMiddleware(p, chQuit) + mw, err := NewMiddleware(p, make(chan error)) require.Nil(t, err) - t.Cleanup(mw.Shutdown) + defer mw.Stop() - handler := mw.Wrap(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + handler := mw.Middleware()(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) recorder := httptest.NewRecorder() httpReq := &http.Request{ Method: http.MethodGet, @@ -108,12 +105,11 @@ func TestNewMiddleware_SendResponse(t *testing.T) { } }() - chQuit := make(chan error) - mw, err := NewMiddleware(p, chQuit) + mw, err := NewMiddleware(p, make(chan error)) require.Nil(t, err) - t.Cleanup(mw.Shutdown) + defer mw.Stop() - handler := mw.Wrap(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + handler := mw.Middleware()(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) recorder := httptest.NewRecorder() httpReq := &http.Request{ @@ -147,12 +143,11 @@ func TestNewMiddleware_Unavailable(t *testing.T) { } }() - chQuit := make(chan error) - mw, err := NewMiddleware(p, chQuit) + mw, err := NewMiddleware(p, make(chan error)) require.Nil(t, err) - t.Cleanup(mw.Shutdown) + defer mw.Stop() - handler := mw.Wrap(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + handler := mw.Middleware()(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) recorder := httptest.NewRecorder() httpReq := &http.Request{ @@ -196,12 +191,11 @@ func TestNewMiddleware_InvalidResponse(t *testing.T) { } }() - chQuit := make(chan error, 1) - mw, err := NewMiddleware(p, chQuit) + mw, err := NewMiddleware(p, make(chan error)) require.Nil(t, err) - t.Cleanup(mw.Shutdown) + defer mw.Stop() - handler := mw.Wrap(nil) + handler := mw.Middleware()(nil) recorder := httptest.NewRecorder() httpReq := &http.Request{ Method: http.MethodGet, @@ -212,7 +206,4 @@ func TestNewMiddleware_InvalidResponse(t *testing.T) { } handler.ServeHTTP(recorder, httpReq) assert.Equal(t, http.StatusInternalServerError, recorder.Code) - - err = <-chQuit - assert.ErrorContains(t, err, "unsupported payload type") } diff --git a/middleware/plugin/plugin.go b/middleware/plugin/plugin.go index a937427f..d553e123 100644 --- a/middleware/plugin/plugin.go +++ b/middleware/plugin/plugin.go @@ -23,7 +23,7 @@ type Plugin interface { // // After a successful call to Start the Stop method must be called in // order to release associated system resources. - Start(chQuit chan error) (chan Message, error) + Start(chan error) (chan Message, error) // Stop stops the plugin and release system resources. Stop() error diff --git a/middleware/responder/sse/responder.go b/middleware/responder/sse/responder.go deleted file mode 100644 index c0fe0fcf..00000000 --- a/middleware/responder/sse/responder.go +++ /dev/null @@ -1,76 +0,0 @@ -package sse - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" - "github.com/olebedev/emitter" - "github.com/siemens/wfx/middleware/logging" -) - -// Responder streams server-sent events (SSE) to a client. -// It listens for events from the provided channel and dispatches them -// to the client as soon as they arrive. -// -// Parameters: -// - ctx: The context for managing the lifecycle of the stream. If canceled, streaming stops. -// - source: A read-only channel of events to be transmitted. -func Responder(ctx context.Context, source <-chan emitter.Event) middleware.ResponderFunc { - return func(w http.ResponseWriter, _ runtime.Producer) { - log := logging.LoggerFromCtx(ctx) - - flusher, _ := w.(http.Flusher) - - w.Header().Set("Content-Type", "text/event-stream") - w.Header().Set("Cache-Control", "no-cache") - w.Header().Set("Connection", "keep-alive") - w.Header().Set("Access-Control-Allow-Origin", "*") - - flusher.Flush() - - var id uint64 = 1 - Loop: - for { - log.Debug().Msg("Waiting for next event") - select { - case ev, ok := <-source: - if !ok { - log.Debug().Msg("SSE channel is closed") - break Loop - } - b, err := json.Marshal(ev.Args[0]) - if err != nil { - log.Error().Err(err).Msg("Failed to marshal status event") - continue Loop - } - log.Debug().RawJSON("event", b).Msg("Sending event to client") - - _, _ = w.Write([]byte("data: ")) - _, _ = w.Write(b) - // must end with two newlines as required by the SSE spec: - _, _ = w.Write([]byte(fmt.Sprintf("\nid: %d\n\n", id))) - - flusher.Flush() - - id++ - case <-ctx.Done(): - // this typically happens when the client closes the connection - log.Debug().Msg("Context is done") - break Loop - } - } - log.Info().Msg("Event Subscriber finished") - } -} diff --git a/middleware/responder/util/content_type.go b/middleware/responder/util/content_type.go deleted file mode 100644 index c0d7743d..00000000 --- a/middleware/responder/util/content_type.go +++ /dev/null @@ -1,29 +0,0 @@ -package util - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "net/http" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" - "github.com/rs/zerolog/log" - "github.com/siemens/wfx/internal/producer" -) - -// ForceJSONResponse generates a JSON response using the provided payload. -func ForceJSONResponse(statusCode int, payload any) middleware.ResponderFunc { - return func(rw http.ResponseWriter, _ runtime.Producer) { - rw.Header().Add("Content-Type", "application/json") - rw.WriteHeader(statusCode) - if err := producer.JSONProducer().Produce(rw, payload); err != nil { - log.Error().Err(err).Msg("Failed to generate JSON response") - } - } -} diff --git a/middleware/responder/util/content_type_test.go b/middleware/responder/util/content_type_test.go deleted file mode 100644 index 948ec06d..00000000 --- a/middleware/responder/util/content_type_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package util - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "io" - "net/http" - "net/http/httptest" - "testing" - - "github.com/siemens/wfx/internal/producer" - "github.com/stretchr/testify/assert" -) - -func TestForceContentType(t *testing.T) { - resp := map[string]string{"hello": "world"} - f := ForceJSONResponse(http.StatusNotFound, resp) - rec := httptest.NewRecorder() - f.WriteResponse(rec, producer.JSONProducer()) - - result := rec.Result() - assert.Equal(t, "application/json", result.Header.Get("Content-Type")) - assert.Equal(t, http.StatusNotFound, result.StatusCode) - b, _ := io.ReadAll(result.Body) - body := string(b) - assert.JSONEq(t, `{"hello":"world"}`, body) -} diff --git a/middleware/responder/util/main_test.go b/middleware/responder/util/main_test.go deleted file mode 100644 index 92b2c098..00000000 --- a/middleware/responder/util/main_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package util - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "testing" - - "go.uber.org/goleak" -) - -func TestMain(m *testing.M) { - goleak.VerifyTestMain(m) -} diff --git a/middleware/setup.go b/middleware/setup.go deleted file mode 100644 index d38b3c3a..00000000 --- a/middleware/setup.go +++ /dev/null @@ -1,56 +0,0 @@ -package middleware - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "net/http" -) - -type GlobalMW struct { - handler http.Handler - intermediates []IntermediateMW -} - -type IntermediateMW interface { - Wrap(next http.Handler) http.Handler - Shutdown() -} - -// implements the http.Handler interface -func (global GlobalMW) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - global.handler.ServeHTTP(rw, r) -} - -func (global GlobalMW) Shutdown() { - for _, mw := range global.intermediates { - mw.Shutdown() - } -} - -func NewGlobalMiddleware(base http.Handler, intermediates []IntermediateMW) *GlobalMW { - handler := base - for _, mw := range intermediates { - handler = mw.Wrap(handler) - } - return &GlobalMW{handler: handler, intermediates: intermediates} -} - -type promotedMW struct { - wrap func(http.Handler) http.Handler -} - -func (promotedMW) Shutdown() {} - -func (mw promotedMW) Wrap(next http.Handler) http.Handler { - return mw.wrap(next) -} - -func PromoteWrapper(wrap func(http.Handler) http.Handler) IntermediateMW { - return promotedMW{wrap: wrap} -} diff --git a/middleware/responder/sse/main_test.go b/middleware/sse/main_test.go similarity index 100% rename from middleware/responder/sse/main_test.go rename to middleware/sse/main_test.go diff --git a/middleware/sse/responder.go b/middleware/sse/responder.go new file mode 100644 index 00000000..d44b9fa0 --- /dev/null +++ b/middleware/sse/responder.go @@ -0,0 +1,82 @@ +package sse + +/* + * SPDX-FileCopyrightText: 2024 Siemens AG + * + * SPDX-License-Identifier: Apache-2.0 + * + * Author: Michael Adler + */ + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + + "github.com/olebedev/emitter" + "github.com/siemens/wfx/middleware/logging" +) + +// Responder streams server-sent events (SSE) to a client. +// It listens for events from the provided channel and dispatches them +// to the client as soon as they arrive. +// +// Parameters: +// - ctx: The context for managing the lifecycle of the stream. If canceled, streaming stops. +// - source: A read-only channel of events to be transmitted. +type Responder struct { + ctx context.Context + eventChan <-chan emitter.Event +} + +func NewResponder(ctx context.Context, eventChan <-chan emitter.Event) Responder { + return Responder{ctx: ctx, eventChan: eventChan} +} + +func (responder Responder) VisitGetJobsEventsResponse(w http.ResponseWriter) error { + log := logging.LoggerFromCtx(responder.ctx) + + flusher, _ := w.(http.Flusher) + + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set("Cache-Control", "no-cache") + w.Header().Set("Connection", "keep-alive") + w.Header().Set("Access-Control-Allow-Origin", "*") + + flusher.Flush() + + var id uint64 = 1 +Loop: + for { + log.Debug().Msg("Waiting for next event") + select { + case ev, ok := <-responder.eventChan: + if !ok { + log.Debug().Msg("SSE channel is closed") + break Loop + } + b, err := json.Marshal(ev.Args[0]) + if err != nil { + log.Error().Err(err).Msg("Failed to marshal status event") + continue Loop + } + log.Debug().RawJSON("event", b).Msg("Sending event to client") + + _, _ = w.Write([]byte("data: ")) + _, _ = w.Write(b) + // must end with two newlines as required by the SSE spec: + _, _ = w.Write([]byte(fmt.Sprintf("\nid: %d\n\n", id))) + + flusher.Flush() + + id++ + case <-responder.ctx.Done(): + // this typically happens when the client closes the connection + log.Debug().Msg("Context is done") + break Loop + } + } + log.Info().Msg("Event Subscriber finished") + return nil +} diff --git a/middleware/responder/sse/responder_test.go b/middleware/sse/responder_test.go similarity index 73% rename from middleware/responder/sse/responder_test.go rename to middleware/sse/responder_test.go index 239f2562..519f7842 100644 --- a/middleware/responder/sse/responder_test.go +++ b/middleware/sse/responder_test.go @@ -15,8 +15,7 @@ import ( "testing" "github.com/olebedev/emitter" - "github.com/siemens/wfx/generated/model" - "github.com/siemens/wfx/internal/producer" + "github.com/siemens/wfx/generated/api" "github.com/stretchr/testify/assert" ) @@ -29,13 +28,15 @@ func TestSSEResponder(t *testing.T) { wg.Add(1) go func() { defer wg.Done() - responder := Responder(context.Background(), events) - responder.WriteResponse(rw, producer.JSONProducer()) + responder := NewResponder(context.Background(), events) + _ = responder.VisitGetJobsEventsResponse(rw) }() - jobStatus := model.JobStatus{ - ClientID: "foo", - Message: "hello world", + clientID := "foo" + message := "hello world" + jobStatus := api.JobStatus{ + ClientID: clientID, + Message: message, State: "INSTALLING", } events <- emitter.Event{ diff --git a/middleware/swagger/main_test.go b/middleware/swagger/main_test.go deleted file mode 100644 index c6782757..00000000 --- a/middleware/swagger/main_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package swagger - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "testing" - - "go.uber.org/goleak" -) - -func TestMain(m *testing.M) { - goleak.VerifyTestMain(m) -} diff --git a/middleware/swagger/middleware.go b/middleware/swagger/middleware.go deleted file mode 100644 index 8f230a71..00000000 --- a/middleware/swagger/middleware.go +++ /dev/null @@ -1,45 +0,0 @@ -package swagger - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "net/http" - "path" -) - -type MW struct { - swaggerJSON []byte - basePath string -} - -func (mw MW) Shutdown() {} - -func (mw MW) Wrap(next http.Handler) http.Handler { - swaggerPath := path.Join(mw.basePath, "swagger.json") - return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - if r.URL.Path == "/" { - rw.WriteHeader(http.StatusNotFound) - _, _ = rw.Write([]byte(`The requested resource could not be found. - -Hint: Check /swagger.json to see available endpoints. -`)) - return - } else if r.URL.Path == swaggerPath { - rw.Header().Set("Content-Type", "application/json") - rw.WriteHeader(http.StatusOK) - _, _ = rw.Write(mw.swaggerJSON) - return - } - next.ServeHTTP(rw, r) - }) -} - -func NewSpecMiddleware(basePath string, swaggerJSON []byte) MW { - return MW{basePath: basePath, swaggerJSON: swaggerJSON} -} diff --git a/middleware/swagger/middleware_test.go b/middleware/swagger/middleware_test.go deleted file mode 100644 index 5e07f762..00000000 --- a/middleware/swagger/middleware_test.go +++ /dev/null @@ -1,47 +0,0 @@ -package swagger - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "io" - "net/http" - "testing" - - "github.com/steinfletcher/apitest" - "github.com/stretchr/testify/assert" -) - -func TestHint(t *testing.T) { - mw := NewSpecMiddleware("/api", []byte(`{ "hello": "world" }`)) - result := apitest.New(). - Handler(mw.Wrap(nil)). - Get("/"). - Expect(t). - Status(http.StatusNotFound). - End() - actual, err := io.ReadAll(result.Response.Body) - assert.NoError(t, err) - assert.Equal(t, `The requested resource could not be found. - -Hint: Check /swagger.json to see available endpoints. -`, string(actual)) -} - -func TestSwaggerJSON(t *testing.T) { - mw := NewSpecMiddleware("/api", []byte(`{ "hello": "world" }`)) - result := apitest.New(). - Handler(mw.Wrap(nil)). - Get("/api/swagger.json"). - Expect(t). - Status(http.StatusOK). - End() - actual, err := io.ReadAll(result.Response.Body) - assert.NoError(t, err) - assert.JSONEq(t, `{ "hello": "world" }`, string(actual)) -} diff --git a/middleware/version/main_test.go b/middleware/version/main_test.go deleted file mode 100644 index 9e5a812f..00000000 --- a/middleware/version/main_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package version - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "testing" - - "go.uber.org/goleak" -) - -func TestMain(m *testing.M) { - goleak.VerifyTestMain(m) -} diff --git a/middleware/version/version.go b/middleware/version/version.go deleted file mode 100644 index 9e757eaf..00000000 --- a/middleware/version/version.go +++ /dev/null @@ -1,47 +0,0 @@ -package version - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "encoding/json" - "net/http" - "strings" - - "github.com/siemens/wfx/cmd/wfx/metadata" -) - -type Version struct { - Version string `json:"version"` - Commit string `json:"commit"` - BuildDate string `json:"buildDate"` - APIVersion string `json:"apiVersion"` -} - -type MW struct{} - -func (mw MW) Wrap(next http.Handler) http.Handler { - v := Version{ - Version: metadata.Version, - Commit: metadata.Commit, - BuildDate: metadata.Date, - APIVersion: metadata.APIVersion, - } - info, _ := json.MarshalIndent(v, "", " ") - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if strings.HasPrefix(r.URL.Path, "/version") { - w.Header().Set("Content-Type", "application/json; charset=utf-8") - w.WriteHeader(http.StatusOK) - _, _ = w.Write(info) - return - } - next.ServeHTTP(w, r) - }) -} - -func (mw MW) Shutdown() {} diff --git a/middleware/version/version_test.go b/middleware/version/version_test.go deleted file mode 100644 index ad13cf9e..00000000 --- a/middleware/version/version_test.go +++ /dev/null @@ -1,35 +0,0 @@ -package version - -/* - * SPDX-FileCopyrightText: 2023 Siemens AG - * - * SPDX-License-Identifier: Apache-2.0 - * - * Author: Michael Adler - */ - -import ( - "encoding/json" - "io" - "net/http" - "testing" - - "github.com/steinfletcher/apitest" - "github.com/stretchr/testify/assert" -) - -func TestGetVersion(t *testing.T) { - result := apitest.New(). - Handler(MW{}.Wrap(nil)). - Get("/version"). - Expect(t). - Status(http.StatusOK). - End() - - actual, err := io.ReadAll(result.Response.Body) - assert.NoError(t, err) - - var data map[string]string - err = json.Unmarshal(actual, &data) - assert.NoError(t, err) -} diff --git a/persistence/all_test.go b/persistence/all_test.go index fc017afd..3cef5c85 100644 --- a/persistence/all_test.go +++ b/persistence/all_test.go @@ -15,13 +15,13 @@ import ( ) func TestStorageAPI(t *testing.T) { - storage1 := NewMockStorage(t) + storage1 := NewHealthyMockStorage(t) RegisterStorage("storage1", storage1) actual := GetStorage("storage1") assert.Same(t, storage1, actual) - storage2 := NewMockStorage(t) + storage2 := NewHealthyMockStorage(t) RegisterStorage("storage2", storage2) all := Storages() assert.Len(t, all, 2) diff --git a/persistence/mock.go b/persistence/mock.go new file mode 100644 index 00000000..b555ba1f --- /dev/null +++ b/persistence/mock.go @@ -0,0 +1,22 @@ +package persistence + +/* + * SPDX-FileCopyrightText: 2024 Siemens AG + * + * SPDX-License-Identifier: Apache-2.0 + * + * Author: Michael Adler + */ + +import ( + "testing" + + mock "github.com/stretchr/testify/mock" +) + +func NewHealthyMockStorage(t *testing.T) *MockStorage { + m := new(MockStorage) + m.Mock.Test(t) + m.On("CheckHealth", mock.Anything).Return(nil) + return m +} diff --git a/persistence/mock_Storage.go b/persistence/mock_Storage.go index 54f43139..86bd3692 100644 --- a/persistence/mock_Storage.go +++ b/persistence/mock_Storage.go @@ -13,7 +13,8 @@ package persistence import ( context "context" - model "github.com/siemens/wfx/generated/model" + api "github.com/siemens/wfx/generated/api" + mock "github.com/stretchr/testify/mock" ) @@ -77,27 +78,27 @@ func (_c *MockStorage_CheckHealth_Call) RunAndReturn(run func(context.Context) e } // CreateJob provides a mock function with given fields: ctx, job -func (_m *MockStorage) CreateJob(ctx context.Context, job *model.Job) (*model.Job, error) { +func (_m *MockStorage) CreateJob(ctx context.Context, job *api.Job) (*api.Job, error) { ret := _m.Called(ctx, job) if len(ret) == 0 { panic("no return value specified for CreateJob") } - var r0 *model.Job + var r0 *api.Job var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *model.Job) (*model.Job, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, *api.Job) (*api.Job, error)); ok { return rf(ctx, job) } - if rf, ok := ret.Get(0).(func(context.Context, *model.Job) *model.Job); ok { + if rf, ok := ret.Get(0).(func(context.Context, *api.Job) *api.Job); ok { r0 = rf(ctx, job) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*model.Job) + r0 = ret.Get(0).(*api.Job) } } - if rf, ok := ret.Get(1).(func(context.Context, *model.Job) error); ok { + if rf, ok := ret.Get(1).(func(context.Context, *api.Job) error); ok { r1 = rf(ctx, job) } else { r1 = ret.Error(1) @@ -113,50 +114,50 @@ type MockStorage_CreateJob_Call struct { // CreateJob is a helper method to define mock.On call // - ctx context.Context -// - job *model.Job +// - job *api.Job func (_e *MockStorage_Expecter) CreateJob(ctx interface{}, job interface{}) *MockStorage_CreateJob_Call { return &MockStorage_CreateJob_Call{Call: _e.mock.On("CreateJob", ctx, job)} } -func (_c *MockStorage_CreateJob_Call) Run(run func(ctx context.Context, job *model.Job)) *MockStorage_CreateJob_Call { +func (_c *MockStorage_CreateJob_Call) Run(run func(ctx context.Context, job *api.Job)) *MockStorage_CreateJob_Call { _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(*model.Job)) + run(args[0].(context.Context), args[1].(*api.Job)) }) return _c } -func (_c *MockStorage_CreateJob_Call) Return(_a0 *model.Job, _a1 error) *MockStorage_CreateJob_Call { +func (_c *MockStorage_CreateJob_Call) Return(_a0 *api.Job, _a1 error) *MockStorage_CreateJob_Call { _c.Call.Return(_a0, _a1) return _c } -func (_c *MockStorage_CreateJob_Call) RunAndReturn(run func(context.Context, *model.Job) (*model.Job, error)) *MockStorage_CreateJob_Call { +func (_c *MockStorage_CreateJob_Call) RunAndReturn(run func(context.Context, *api.Job) (*api.Job, error)) *MockStorage_CreateJob_Call { _c.Call.Return(run) return _c } // CreateWorkflow provides a mock function with given fields: ctx, workflow -func (_m *MockStorage) CreateWorkflow(ctx context.Context, workflow *model.Workflow) (*model.Workflow, error) { +func (_m *MockStorage) CreateWorkflow(ctx context.Context, workflow *api.Workflow) (*api.Workflow, error) { ret := _m.Called(ctx, workflow) if len(ret) == 0 { panic("no return value specified for CreateWorkflow") } - var r0 *model.Workflow + var r0 *api.Workflow var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *model.Workflow) (*model.Workflow, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, *api.Workflow) (*api.Workflow, error)); ok { return rf(ctx, workflow) } - if rf, ok := ret.Get(0).(func(context.Context, *model.Workflow) *model.Workflow); ok { + if rf, ok := ret.Get(0).(func(context.Context, *api.Workflow) *api.Workflow); ok { r0 = rf(ctx, workflow) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*model.Workflow) + r0 = ret.Get(0).(*api.Workflow) } } - if rf, ok := ret.Get(1).(func(context.Context, *model.Workflow) error); ok { + if rf, ok := ret.Get(1).(func(context.Context, *api.Workflow) error); ok { r1 = rf(ctx, workflow) } else { r1 = ret.Error(1) @@ -172,24 +173,24 @@ type MockStorage_CreateWorkflow_Call struct { // CreateWorkflow is a helper method to define mock.On call // - ctx context.Context -// - workflow *model.Workflow +// - workflow *api.Workflow func (_e *MockStorage_Expecter) CreateWorkflow(ctx interface{}, workflow interface{}) *MockStorage_CreateWorkflow_Call { return &MockStorage_CreateWorkflow_Call{Call: _e.mock.On("CreateWorkflow", ctx, workflow)} } -func (_c *MockStorage_CreateWorkflow_Call) Run(run func(ctx context.Context, workflow *model.Workflow)) *MockStorage_CreateWorkflow_Call { +func (_c *MockStorage_CreateWorkflow_Call) Run(run func(ctx context.Context, workflow *api.Workflow)) *MockStorage_CreateWorkflow_Call { _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(*model.Workflow)) + run(args[0].(context.Context), args[1].(*api.Workflow)) }) return _c } -func (_c *MockStorage_CreateWorkflow_Call) Return(_a0 *model.Workflow, _a1 error) *MockStorage_CreateWorkflow_Call { +func (_c *MockStorage_CreateWorkflow_Call) Return(_a0 *api.Workflow, _a1 error) *MockStorage_CreateWorkflow_Call { _c.Call.Return(_a0, _a1) return _c } -func (_c *MockStorage_CreateWorkflow_Call) RunAndReturn(run func(context.Context, *model.Workflow) (*model.Workflow, error)) *MockStorage_CreateWorkflow_Call { +func (_c *MockStorage_CreateWorkflow_Call) RunAndReturn(run func(context.Context, *api.Workflow) (*api.Workflow, error)) *MockStorage_CreateWorkflow_Call { _c.Call.Return(run) return _c } @@ -289,23 +290,23 @@ func (_c *MockStorage_DeleteWorkflow_Call) RunAndReturn(run func(context.Context } // GetJob provides a mock function with given fields: ctx, jobID, fetchParams -func (_m *MockStorage) GetJob(ctx context.Context, jobID string, fetchParams FetchParams) (*model.Job, error) { +func (_m *MockStorage) GetJob(ctx context.Context, jobID string, fetchParams FetchParams) (*api.Job, error) { ret := _m.Called(ctx, jobID, fetchParams) if len(ret) == 0 { panic("no return value specified for GetJob") } - var r0 *model.Job + var r0 *api.Job var r1 error - if rf, ok := ret.Get(0).(func(context.Context, string, FetchParams) (*model.Job, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, string, FetchParams) (*api.Job, error)); ok { return rf(ctx, jobID, fetchParams) } - if rf, ok := ret.Get(0).(func(context.Context, string, FetchParams) *model.Job); ok { + if rf, ok := ret.Get(0).(func(context.Context, string, FetchParams) *api.Job); ok { r0 = rf(ctx, jobID, fetchParams) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*model.Job) + r0 = ret.Get(0).(*api.Job) } } @@ -338,34 +339,34 @@ func (_c *MockStorage_GetJob_Call) Run(run func(ctx context.Context, jobID strin return _c } -func (_c *MockStorage_GetJob_Call) Return(_a0 *model.Job, _a1 error) *MockStorage_GetJob_Call { +func (_c *MockStorage_GetJob_Call) Return(_a0 *api.Job, _a1 error) *MockStorage_GetJob_Call { _c.Call.Return(_a0, _a1) return _c } -func (_c *MockStorage_GetJob_Call) RunAndReturn(run func(context.Context, string, FetchParams) (*model.Job, error)) *MockStorage_GetJob_Call { +func (_c *MockStorage_GetJob_Call) RunAndReturn(run func(context.Context, string, FetchParams) (*api.Job, error)) *MockStorage_GetJob_Call { _c.Call.Return(run) return _c } // GetWorkflow provides a mock function with given fields: ctx, name -func (_m *MockStorage) GetWorkflow(ctx context.Context, name string) (*model.Workflow, error) { +func (_m *MockStorage) GetWorkflow(ctx context.Context, name string) (*api.Workflow, error) { ret := _m.Called(ctx, name) if len(ret) == 0 { panic("no return value specified for GetWorkflow") } - var r0 *model.Workflow + var r0 *api.Workflow var r1 error - if rf, ok := ret.Get(0).(func(context.Context, string) (*model.Workflow, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, string) (*api.Workflow, error)); ok { return rf(ctx, name) } - if rf, ok := ret.Get(0).(func(context.Context, string) *model.Workflow); ok { + if rf, ok := ret.Get(0).(func(context.Context, string) *api.Workflow); ok { r0 = rf(ctx, name) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*model.Workflow) + r0 = ret.Get(0).(*api.Workflow) } } @@ -397,27 +398,27 @@ func (_c *MockStorage_GetWorkflow_Call) Run(run func(ctx context.Context, name s return _c } -func (_c *MockStorage_GetWorkflow_Call) Return(_a0 *model.Workflow, _a1 error) *MockStorage_GetWorkflow_Call { +func (_c *MockStorage_GetWorkflow_Call) Return(_a0 *api.Workflow, _a1 error) *MockStorage_GetWorkflow_Call { _c.Call.Return(_a0, _a1) return _c } -func (_c *MockStorage_GetWorkflow_Call) RunAndReturn(run func(context.Context, string) (*model.Workflow, error)) *MockStorage_GetWorkflow_Call { +func (_c *MockStorage_GetWorkflow_Call) RunAndReturn(run func(context.Context, string) (*api.Workflow, error)) *MockStorage_GetWorkflow_Call { _c.Call.Return(run) return _c } -// Initialize provides a mock function with given fields: ctx, options -func (_m *MockStorage) Initialize(ctx context.Context, options string) error { - ret := _m.Called(ctx, options) +// Initialize provides a mock function with given fields: options +func (_m *MockStorage) Initialize(options string) error { + ret := _m.Called(options) if len(ret) == 0 { panic("no return value specified for Initialize") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, string) error); ok { - r0 = rf(ctx, options) + if rf, ok := ret.Get(0).(func(string) error); ok { + r0 = rf(options) } else { r0 = ret.Error(0) } @@ -431,15 +432,14 @@ type MockStorage_Initialize_Call struct { } // Initialize is a helper method to define mock.On call -// - ctx context.Context // - options string -func (_e *MockStorage_Expecter) Initialize(ctx interface{}, options interface{}) *MockStorage_Initialize_Call { - return &MockStorage_Initialize_Call{Call: _e.mock.On("Initialize", ctx, options)} +func (_e *MockStorage_Expecter) Initialize(options interface{}) *MockStorage_Initialize_Call { + return &MockStorage_Initialize_Call{Call: _e.mock.On("Initialize", options)} } -func (_c *MockStorage_Initialize_Call) Run(run func(ctx context.Context, options string)) *MockStorage_Initialize_Call { +func (_c *MockStorage_Initialize_Call) Run(run func(options string)) *MockStorage_Initialize_Call { _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(string)) + run(args[0].(string)) }) return _c } @@ -449,29 +449,29 @@ func (_c *MockStorage_Initialize_Call) Return(_a0 error) *MockStorage_Initialize return _c } -func (_c *MockStorage_Initialize_Call) RunAndReturn(run func(context.Context, string) error) *MockStorage_Initialize_Call { +func (_c *MockStorage_Initialize_Call) RunAndReturn(run func(string) error) *MockStorage_Initialize_Call { _c.Call.Return(run) return _c } // QueryJobs provides a mock function with given fields: ctx, filterParams, sortParams, paginationParams -func (_m *MockStorage) QueryJobs(ctx context.Context, filterParams FilterParams, sortParams SortParams, paginationParams PaginationParams) (*model.PaginatedJobList, error) { +func (_m *MockStorage) QueryJobs(ctx context.Context, filterParams FilterParams, sortParams SortParams, paginationParams PaginationParams) (*api.PaginatedJobList, error) { ret := _m.Called(ctx, filterParams, sortParams, paginationParams) if len(ret) == 0 { panic("no return value specified for QueryJobs") } - var r0 *model.PaginatedJobList + var r0 *api.PaginatedJobList var r1 error - if rf, ok := ret.Get(0).(func(context.Context, FilterParams, SortParams, PaginationParams) (*model.PaginatedJobList, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, FilterParams, SortParams, PaginationParams) (*api.PaginatedJobList, error)); ok { return rf(ctx, filterParams, sortParams, paginationParams) } - if rf, ok := ret.Get(0).(func(context.Context, FilterParams, SortParams, PaginationParams) *model.PaginatedJobList); ok { + if rf, ok := ret.Get(0).(func(context.Context, FilterParams, SortParams, PaginationParams) *api.PaginatedJobList); ok { r0 = rf(ctx, filterParams, sortParams, paginationParams) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*model.PaginatedJobList) + r0 = ret.Get(0).(*api.PaginatedJobList) } } @@ -505,39 +505,39 @@ func (_c *MockStorage_QueryJobs_Call) Run(run func(ctx context.Context, filterPa return _c } -func (_c *MockStorage_QueryJobs_Call) Return(_a0 *model.PaginatedJobList, _a1 error) *MockStorage_QueryJobs_Call { +func (_c *MockStorage_QueryJobs_Call) Return(_a0 *api.PaginatedJobList, _a1 error) *MockStorage_QueryJobs_Call { _c.Call.Return(_a0, _a1) return _c } -func (_c *MockStorage_QueryJobs_Call) RunAndReturn(run func(context.Context, FilterParams, SortParams, PaginationParams) (*model.PaginatedJobList, error)) *MockStorage_QueryJobs_Call { +func (_c *MockStorage_QueryJobs_Call) RunAndReturn(run func(context.Context, FilterParams, SortParams, PaginationParams) (*api.PaginatedJobList, error)) *MockStorage_QueryJobs_Call { _c.Call.Return(run) return _c } -// QueryWorkflows provides a mock function with given fields: ctx, paginationParams -func (_m *MockStorage) QueryWorkflows(ctx context.Context, paginationParams PaginationParams) (*model.PaginatedWorkflowList, error) { - ret := _m.Called(ctx, paginationParams) +// QueryWorkflows provides a mock function with given fields: ctx, sortParams, paginationParams +func (_m *MockStorage) QueryWorkflows(ctx context.Context, sortParams SortParams, paginationParams PaginationParams) (*api.PaginatedWorkflowList, error) { + ret := _m.Called(ctx, sortParams, paginationParams) if len(ret) == 0 { panic("no return value specified for QueryWorkflows") } - var r0 *model.PaginatedWorkflowList + var r0 *api.PaginatedWorkflowList var r1 error - if rf, ok := ret.Get(0).(func(context.Context, PaginationParams) (*model.PaginatedWorkflowList, error)); ok { - return rf(ctx, paginationParams) + if rf, ok := ret.Get(0).(func(context.Context, SortParams, PaginationParams) (*api.PaginatedWorkflowList, error)); ok { + return rf(ctx, sortParams, paginationParams) } - if rf, ok := ret.Get(0).(func(context.Context, PaginationParams) *model.PaginatedWorkflowList); ok { - r0 = rf(ctx, paginationParams) + if rf, ok := ret.Get(0).(func(context.Context, SortParams, PaginationParams) *api.PaginatedWorkflowList); ok { + r0 = rf(ctx, sortParams, paginationParams) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*model.PaginatedWorkflowList) + r0 = ret.Get(0).(*api.PaginatedWorkflowList) } } - if rf, ok := ret.Get(1).(func(context.Context, PaginationParams) error); ok { - r1 = rf(ctx, paginationParams) + if rf, ok := ret.Get(1).(func(context.Context, SortParams, PaginationParams) error); ok { + r1 = rf(ctx, sortParams, paginationParams) } else { r1 = ret.Error(1) } @@ -552,24 +552,25 @@ type MockStorage_QueryWorkflows_Call struct { // QueryWorkflows is a helper method to define mock.On call // - ctx context.Context +// - sortParams SortParams // - paginationParams PaginationParams -func (_e *MockStorage_Expecter) QueryWorkflows(ctx interface{}, paginationParams interface{}) *MockStorage_QueryWorkflows_Call { - return &MockStorage_QueryWorkflows_Call{Call: _e.mock.On("QueryWorkflows", ctx, paginationParams)} +func (_e *MockStorage_Expecter) QueryWorkflows(ctx interface{}, sortParams interface{}, paginationParams interface{}) *MockStorage_QueryWorkflows_Call { + return &MockStorage_QueryWorkflows_Call{Call: _e.mock.On("QueryWorkflows", ctx, sortParams, paginationParams)} } -func (_c *MockStorage_QueryWorkflows_Call) Run(run func(ctx context.Context, paginationParams PaginationParams)) *MockStorage_QueryWorkflows_Call { +func (_c *MockStorage_QueryWorkflows_Call) Run(run func(ctx context.Context, sortParams SortParams, paginationParams PaginationParams)) *MockStorage_QueryWorkflows_Call { _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(PaginationParams)) + run(args[0].(context.Context), args[1].(SortParams), args[2].(PaginationParams)) }) return _c } -func (_c *MockStorage_QueryWorkflows_Call) Return(_a0 *model.PaginatedWorkflowList, _a1 error) *MockStorage_QueryWorkflows_Call { +func (_c *MockStorage_QueryWorkflows_Call) Return(_a0 *api.PaginatedWorkflowList, _a1 error) *MockStorage_QueryWorkflows_Call { _c.Call.Return(_a0, _a1) return _c } -func (_c *MockStorage_QueryWorkflows_Call) RunAndReturn(run func(context.Context, PaginationParams) (*model.PaginatedWorkflowList, error)) *MockStorage_QueryWorkflows_Call { +func (_c *MockStorage_QueryWorkflows_Call) RunAndReturn(run func(context.Context, SortParams, PaginationParams) (*api.PaginatedWorkflowList, error)) *MockStorage_QueryWorkflows_Call { _c.Call.Return(run) return _c } @@ -607,27 +608,27 @@ func (_c *MockStorage_Shutdown_Call) RunAndReturn(run func()) *MockStorage_Shutd } // UpdateJob provides a mock function with given fields: ctx, job, request -func (_m *MockStorage) UpdateJob(ctx context.Context, job *model.Job, request JobUpdate) (*model.Job, error) { +func (_m *MockStorage) UpdateJob(ctx context.Context, job *api.Job, request JobUpdate) (*api.Job, error) { ret := _m.Called(ctx, job, request) if len(ret) == 0 { panic("no return value specified for UpdateJob") } - var r0 *model.Job + var r0 *api.Job var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *model.Job, JobUpdate) (*model.Job, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, *api.Job, JobUpdate) (*api.Job, error)); ok { return rf(ctx, job, request) } - if rf, ok := ret.Get(0).(func(context.Context, *model.Job, JobUpdate) *model.Job); ok { + if rf, ok := ret.Get(0).(func(context.Context, *api.Job, JobUpdate) *api.Job); ok { r0 = rf(ctx, job, request) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*model.Job) + r0 = ret.Get(0).(*api.Job) } } - if rf, ok := ret.Get(1).(func(context.Context, *model.Job, JobUpdate) error); ok { + if rf, ok := ret.Get(1).(func(context.Context, *api.Job, JobUpdate) error); ok { r1 = rf(ctx, job, request) } else { r1 = ret.Error(1) @@ -643,25 +644,25 @@ type MockStorage_UpdateJob_Call struct { // UpdateJob is a helper method to define mock.On call // - ctx context.Context -// - job *model.Job +// - job *api.Job // - request JobUpdate func (_e *MockStorage_Expecter) UpdateJob(ctx interface{}, job interface{}, request interface{}) *MockStorage_UpdateJob_Call { return &MockStorage_UpdateJob_Call{Call: _e.mock.On("UpdateJob", ctx, job, request)} } -func (_c *MockStorage_UpdateJob_Call) Run(run func(ctx context.Context, job *model.Job, request JobUpdate)) *MockStorage_UpdateJob_Call { +func (_c *MockStorage_UpdateJob_Call) Run(run func(ctx context.Context, job *api.Job, request JobUpdate)) *MockStorage_UpdateJob_Call { _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(*model.Job), args[2].(JobUpdate)) + run(args[0].(context.Context), args[1].(*api.Job), args[2].(JobUpdate)) }) return _c } -func (_c *MockStorage_UpdateJob_Call) Return(_a0 *model.Job, _a1 error) *MockStorage_UpdateJob_Call { +func (_c *MockStorage_UpdateJob_Call) Return(_a0 *api.Job, _a1 error) *MockStorage_UpdateJob_Call { _c.Call.Return(_a0, _a1) return _c } -func (_c *MockStorage_UpdateJob_Call) RunAndReturn(run func(context.Context, *model.Job, JobUpdate) (*model.Job, error)) *MockStorage_UpdateJob_Call { +func (_c *MockStorage_UpdateJob_Call) RunAndReturn(run func(context.Context, *api.Job, JobUpdate) (*api.Job, error)) *MockStorage_UpdateJob_Call { _c.Call.Return(run) return _c } diff --git a/persistence/storage.go b/persistence/storage.go index 9048cd69..1f5a62a3 100644 --- a/persistence/storage.go +++ b/persistence/storage.go @@ -11,14 +11,14 @@ package persistence import ( "context" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" ) // Storage represents an interface for a persistence layer (such as PostgreSQL, SQLite). // It provides methods for managing jobs and workflows in the storage. type Storage interface { // Initialize sets up the storage using the provided options string. - Initialize(ctx context.Context, options string) error + Initialize(options string) error // Shutdown gracefully closes the storage connection. Shutdown() @@ -27,40 +27,40 @@ type Storage interface { CheckHealth(ctx context.Context) error // CreateJob adds a new job to the storage. - CreateJob(ctx context.Context, job *model.Job) (*model.Job, error) + CreateJob(ctx context.Context, job *api.Job) (*api.Job, error) // GetJob retrieves an existing job identified by jobID from the storage. // If an issue occurs during the fetch operation, the method returns an error. - GetJob(ctx context.Context, jobID string, fetchParams FetchParams) (*model.Job, error) + GetJob(ctx context.Context, jobID string, fetchParams FetchParams) (*api.Job, error) // UpdateJob modifies an existing job in the storage based on the provided JobUpdate request. - UpdateJob(ctx context.Context, job *model.Job, request JobUpdate) (*model.Job, error) + UpdateJob(ctx context.Context, job *api.Job, request JobUpdate) (*api.Job, error) // DeleteJob removes an existing job identified by jobID from the storage. DeleteJob(ctx context.Context, jobID string) error // QueryJobs retrieves jobs that satisfy the filterParams, sortParams, and paginationParams. - QueryJobs(ctx context.Context, filterParams FilterParams, sortParams SortParams, paginationParams PaginationParams) (*model.PaginatedJobList, error) + QueryJobs(ctx context.Context, filterParams FilterParams, sortParams SortParams, paginationParams PaginationParams) (*api.PaginatedJobList, error) // CreateWorkflow adds a new workflow to the storage. - CreateWorkflow(ctx context.Context, workflow *model.Workflow) (*model.Workflow, error) + CreateWorkflow(ctx context.Context, workflow *api.Workflow) (*api.Workflow, error) // GetWorkflow retrieves an existing workflow identified by name from the storage. // If an issue occurs during the fetch operation, the method returns an error. - GetWorkflow(ctx context.Context, name string) (*model.Workflow, error) + GetWorkflow(ctx context.Context, name string) (*api.Workflow, error) // DeleteWorkflow removes an existing workflow identified by name from the storage. DeleteWorkflow(ctx context.Context, name string) error // QueryWorkflows retrieves all workflows from the storage respecting the paginationParams. - QueryWorkflows(ctx context.Context, paginationParams PaginationParams) (*model.PaginatedWorkflowList, error) + QueryWorkflows(ctx context.Context, sortParams SortParams, paginationParams PaginationParams) (*api.PaginatedWorkflowList, error) } // JobUpdate encapsulates the properties of a job that can be updated. // If a property is nil, its corresponding value in the job will not be changed. type JobUpdate struct { // Status is the new job status. If provided, it replaces the existing status of the job. - Status *model.JobStatus + Status *api.JobStatus // Definition is the new job definition. If provided, it replaces the existing job definition. Definition *map[string]any // AddTags is a list of tags to be added to the job. If provided, these tags will be added to the existing tags. diff --git a/spec/cfg.yaml b/spec/cfg.yaml new file mode 100644 index 00000000..207d31d1 --- /dev/null +++ b/spec/cfg.yaml @@ -0,0 +1,9 @@ +# yaml-language-server: $schema=https://raw.githubusercontent.com/deepmap/oapi-codegen/HEAD/configuration-schema.json +package: api +generate: + std-http-server: true + strict-server: true + embedded-spec: true + models: true + client: true +output: ../generated/api/wfx.openapi.gen.go diff --git a/spec/justfile b/spec/justfile deleted file mode 100644 index 065c7e04..00000000 --- a/spec/justfile +++ /dev/null @@ -1,19 +0,0 @@ -# SPDX-FileCopyrightText: 2023 Siemens AG -# -# SPDX-License-Identifier: Apache-2.0 -# - -# Author: Michael Adler -generate OUTFILE: - #!/usr/bin/env python3 - import sys - import yaml - - try: - from yaml import CLoader as Loader, CDumper as Dumper - except ImportError: - from yaml import Loader, Dumper - - with open('{{ justfile_directory() }}/wfx.swagger.yml', 'r') as f: - with open('{{ OUTFILE }}', 'w') as g: - yaml.dump(yaml.load(f, Loader=Loader), stream=g, Dumper=Dumper) diff --git a/spec/middleware.go b/spec/middleware.go new file mode 100644 index 00000000..ade70f68 --- /dev/null +++ b/spec/middleware.go @@ -0,0 +1,13 @@ +package spec + +/* + * SPDX-FileCopyrightText: 2024 Siemens AG + * + * SPDX-License-Identifier: Apache-2.0 + * + * Author: Michael Adler + */ + +import "net/http" + +var Handlers = make(map[string]http.Handler, 0) diff --git a/spec/openapiv3.go b/spec/openapiv3.go new file mode 100644 index 00000000..14bf6c5e --- /dev/null +++ b/spec/openapiv3.go @@ -0,0 +1,48 @@ +package spec + +/* + * SPDX-FileCopyrightText: 2024 Siemens AG + * + * SPDX-License-Identifier: Apache-2.0 + * + * Author: Michael Adler + */ + +import ( + _ "embed" + "encoding/json" + "fmt" + "net/http" + + "gopkg.in/yaml.v3" +) + +//go:embed wfx.openapiv3.yml +var openapiv3YAML string + +func init() { + var yamlObj map[string]any + if err := yaml.Unmarshal([]byte(openapiv3YAML), &yamlObj); err != nil { + panic(err) + } + servers := yamlObj["servers"].([]any) + servers2 := servers[0].(map[string]any) + basePath := servers2["url"] + specEndpoint := fmt.Sprintf("%s/openapiv3.json", basePath) + + jsonData, err := json.Marshal(yamlObj) + if err != nil { + panic(err) + } + + Handlers[fmt.Sprintf("GET %s", specEndpoint)] = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write(jsonData) + }) + + Handlers["GET /"] = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(fmt.Sprintf("The requested resource could not be found.\n\nHint: Check %s to see available endpoints.\n", specEndpoint))) + }) +} diff --git a/spec/spdx.txt b/spec/spdx.txt deleted file mode 100644 index 3b367fa1..00000000 --- a/spec/spdx.txt +++ /dev/null @@ -1,3 +0,0 @@ -SPDX-FileCopyrightText: 2023 Siemens AG - -SPDX-License-Identifier: Apache-2.0 diff --git a/spec/swagger.go b/spec/swagger.go new file mode 100644 index 00000000..60910598 --- /dev/null +++ b/spec/swagger.go @@ -0,0 +1,52 @@ +//go:build swagger + +package spec + +/* + * SPDX-FileCopyrightText: 2024 Siemens AG + * + * SPDX-License-Identifier: Apache-2.0 + * + * Author: Michael Adler + */ + +import ( + _ "embed" + "encoding/json" + "fmt" + "net/http" + + "gopkg.in/yaml.v3" +) + +//go:embed wfx.swagger.yml +var swaggerYAML string + +func init() { + var yamlObj map[string]any + if err := yaml.Unmarshal([]byte(swaggerYAML), &yamlObj); err != nil { + panic(err) + } + basePath := yamlObj["basePath"].(string) + + jsonData, err := json.Marshal(yamlObj) + if err != nil { + panic(err) + } + + Handlers[fmt.Sprintf("GET %s/swagger.json", basePath)] = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write(jsonData) + }) +} + +func yamlToJSON(yamlData []byte) ([]byte, error) { + var yamlObj any + if err := yaml.Unmarshal(yamlData, &yamlObj); err != nil { + return nil, err + } + jsonData, err := json.Marshal(yamlObj) + if err != nil { + return nil, err + } + return jsonData, nil +} diff --git a/spec/wfx.openapiv3.yml b/spec/wfx.openapiv3.yml new file mode 100644 index 00000000..8bca058f --- /dev/null +++ b/spec/wfx.openapiv3.yml @@ -0,0 +1,1330 @@ +# SPDX-FileCopyrightText: 2024 Siemens AG +# +# SPDX-License-Identifier: Apache-2.0 +--- +openapi: 3.0.0 +info: + title: Workflow Executor + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.1.0 + x-visibility: external +servers: + - url: /api/wfx/v1 +tags: + - name: workflows + description: Workflows used to instantiate jobs + - name: jobs + description: Jobs derived from workflows and executed by a client + - name: southbound + description: All southbound API endpoints + - name: northbound + description: All northbound API endpoints +paths: + /health: + get: + tags: + - southbound + - northbound + summary: Query health status + description: Query health status + responses: + default: + description: Other error with any status code and response body format. + content: {} + "200": + description: All systems up and running + headers: + Cache-Control: + schema: + type: string + Pragma: + schema: + type: string + Expires: + schema: + type: string + content: + application/json: + schema: + $ref: "#/components/schemas/CheckerResult" + "503": + description: Some (or all) systems are down + headers: + Cache-Control: + schema: + type: string + Pragma: + schema: + type: string + Expires: + schema: + type: string + content: + application/json: + schema: + $ref: "#/components/schemas/CheckerResult" + + /version: + get: + summary: Get version information + description: Returns the version information of the application + responses: + default: + description: Other error with any status code and response body format. + content: {} + "200": + description: Successful response with version information. + content: + application/json: + schema: + type: object + properties: + version: + type: string + example: 0.3.1 + x-go-type-skip-optional-pointer: true + commit: + type: string + example: 25f4dd3f9828553c9e437a24f7fa451ae60916f2 + x-go-type-skip-optional-pointer: true + buildDate: + type: string + format: date-time + example: "2024-07-23T15:28:54+02:00" + x-go-type-skip-optional-pointer: true + apiVersion: + type: string + example: "v1" + x-go-type-skip-optional-pointer: true + + /workflows: + get: + tags: + - southbound + - northbound + summary: List of available workflows + description: List of available workflows + parameters: + - $ref: "#/components/parameters/responseFilter" + - $ref: "#/components/parameters/limit" + - $ref: "#/components/parameters/offset" + - $ref: "#/components/parameters/sort" + responses: + default: + description: Other error with any status code and response body format. + content: {} + "200": + description: A list of workflows + content: + application/json: + schema: + $ref: "#/components/schemas/PaginatedWorkflowList" + post: + tags: + - northbound + summary: Add a new workflow + description: Add a new workflow + parameters: + - $ref: "#/components/parameters/responseFilter" + requestBody: + description: Workflow object to be added + content: + application/json: + schema: + $ref: "#/components/schemas/Workflow" + required: true + responses: + default: + description: Other error with any status code and response body format. + content: {} + "201": + description: Workflow was created + content: + application/json: + schema: + $ref: "#/components/schemas/Workflow" + "400": + description: Bad Request + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + example: + errors: + - "<<": workflowNotUniqueError + - "<<": workflowInvalidError + "403": + description: Forbidden + + /workflows/{name}: + get: + tags: + - southbound + - northbound + summary: Workflow description for a given name + description: Workflow description for a given name + parameters: + - $ref: "#/components/parameters/responseFilter" + - name: name + in: path + description: Unique name for the workflow + required: true + schema: + type: string + responses: + default: + description: Other error with any status code and response body format. + content: {} + "200": + description: Workflow description with the provided key + content: + application/json: + schema: + $ref: "#/components/schemas/Workflow" + "400": + description: If request is invalid + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + example: + errors: + - "<<": invalidRequestError + "404": + description: Not Found + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + example: + errors: + - "<<": workflowNotFoundError + delete: + tags: + - northbound + summary: Delete an existing workflow + description: | + Delete an existing workflow + parameters: + - name: name + in: path + description: Workflow name + required: true + schema: + type: string + responses: + default: + description: Other error with any status code and response body format. + content: {} + "204": + description: The workflow has been deleted. + content: {} + "403": + description: Forbidden + "404": + description: Not Found + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + example: + errors: + - "<<": workflowNotFoundError + + /jobs: + get: + tags: + - southbound + - northbound + summary: List of job descriptions + description: | + List of job descriptions + By default, this endpoint returns the list of jobs in a specific order and predetermined paging properties. + These defaults are: + - Ascending sort on stime + - 10 entries per page + parameters: + - $ref: "#/components/parameters/responseFilter" + - $ref: "#/components/parameters/limit" + - $ref: "#/components/parameters/offset" + - $ref: "#/components/parameters/sort" + - $ref: "#/components/parameters/state" + - $ref: "#/components/parameters/group" + - $ref: "#/components/parameters/clientId" + - $ref: "#/components/parameters/tag" + - name: workflow + x-go-name: paramWorkflow + in: query + description: Filter jobs matching by workflow + schema: + type: string + responses: + default: + description: Error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + "200": + description: A paginated job list. + content: + application/json: + schema: + $ref: "#/components/schemas/PaginatedJobList" + "400": + description: If request is invalid + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + example: + errors: + - "<<": invalidRequestError + post: + tags: + - northbound + summary: Add a new job + description: | + Add a new job + parameters: + - $ref: "#/components/parameters/responseFilter" + requestBody: + description: Job which shall be created + content: + application/json: + schema: + $ref: "#/components/schemas/JobRequest" + required: true + responses: + default: + description: Other error with any status code and response body format. + content: {} + "201": + description: Job was created + content: + application/json: + schema: + $ref: "#/components/schemas/Job" + "400": + description: Bad Request + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + example: + errors: + - "<<": invalidRequestError + "403": + description: Forbidden + + /jobs/events: + get: + tags: + - southbound + - northbound + summary: Subscribe to job-related events such as status updates + description: | + Obtain instant notifications when there are job changes matching the criteria. This endpoint utilizes server-sent events (SSE), where responses are "chunked" with double newline breaks. For example, a single event might look like this: + data: {"clientId":"example_client","state":"INSTALLING"}\n\n + parameters: + - name: clientIds + in: query + description: The job's clientId must be one of these clientIds (comma-separated). + schema: + type: string + x-go-name: ClientIDs + - name: jobIds + in: query + description: The job's id must be one of these ids (comma-separated). + schema: + type: string + - name: workflows + in: query + description: + The job's workflow must be equal to one of the provided workflow + names (comma-separated). + schema: + type: string + - name: tags + in: query + description: | + A (comma-separated) list of tags to include into each job event. This can be used to aggregrate events from multiple wfx instances. + schema: + type: string + responses: + default: + description: Other error with any status code and response body format + content: {} + "200": + description: A stream of server-sent events + content: + text/event-stream: + schema: + title: Server Sent Events + type: array + items: + title: Job Event + type: object + properties: + id: + description: The event ID. + type: integer + data: + $ref: "#/components/schemas/JobEvent" + "400": + description: Bad Request + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + example: + errors: + - "<<": jobTerminalStateError + "404": + description: Not Found + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + example: + errors: + - "<<": jobNotFoundError + /jobs/{id}: + get: + tags: + - southbound + - northbound + summary: Job description for a given ID + description: | + Job description for a given ID + parameters: + - $ref: "#/components/parameters/responseFilter" + - name: id + in: path + description: Job ID + required: true + schema: + type: string + - $ref: "#/components/parameters/history" + responses: + default: + description: Other error with any status code and response body format. + content: {} + "200": + description: Job description for for a given ID + content: + application/json: + schema: + $ref: "#/components/schemas/Job" + "400": + description: Bad Request + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + example: + errors: + - "<<": invalidRequestError + "404": + description: Not Found + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + example: + errors: + - "<<": jobNotFoundError + delete: + tags: + - northbound + summary: Delete an existing job + description: | + Delete an existing job + parameters: + - name: id + in: path + description: Job ID + required: true + schema: + type: string + responses: + default: + description: Other error with any status code and response body format. + content: {} + "204": + description: The job has been deleted. + content: {} + "403": + description: Forbidden + "404": + description: Not Found + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + example: + errors: + - "<<": workflowNotFoundError + + /jobs/{id}/status: + get: + tags: + - southbound + - northbound + summary: Get job status + description: Retrieve the job status + parameters: + - $ref: "#/components/parameters/responseFilter" + - name: id + in: path + description: Job ID + required: true + schema: + type: string + responses: + default: + description: Other error with any status code and response body format. + content: {} + "200": + description: Job status + content: + application/json: + schema: + $ref: "#/components/schemas/JobStatus" + "404": + description: Not Found + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + example: + errors: + - "<<": jobNotFoundError + put: + tags: + - southbound + - northbound + summary: Modify status of an existing job + description: | + Modify status of an existing job + parameters: + - $ref: "#/components/parameters/responseFilter" + - name: id + in: path + description: Job ID + required: true + schema: + type: string + requestBody: + description: This contains the new job status + content: + application/json: + schema: + $ref: "#/components/schemas/JobStatus" + required: true + responses: + default: + description: Other error with any status code and response body format. + content: {} + "200": + description: Job modified successfully + content: + application/json: + schema: + $ref: "#/components/schemas/JobStatus" + "400": + description: Bad Request + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + example: + errors: + - "<<": invalidRequestError + "404": + description: Not Found + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + example: + errors: + - "<<": jobNotFoundError + x-codegen-request-body-name: New job status + + /jobs/{id}/definition: + get: + tags: + - southbound + - northbound + summary: Get job definition + description: Retrieve the job definition + parameters: + - $ref: "#/components/parameters/responseFilter" + - name: id + in: path + description: Job ID + required: true + schema: + type: string + responses: + default: + description: Other error with any status code and response body format. + content: {} + "200": + description: Job definition + content: + application/json: + schema: + type: object + example: | + { "userDefined": {} } + "404": + description: Not Found + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + example: + errors: + - "<<": jobNotFoundError + put: + tags: + - southbound + - northbound + summary: Modify job definition + description: | + Modify the job definition of an existing job + parameters: + - $ref: "#/components/parameters/responseFilter" + - name: id + in: path + description: Job ID + required: true + schema: + type: string + requestBody: + description: The new job definition + content: + application/json: + schema: + type: object + example: | + { "userDefined": {} } + required: true + responses: + default: + description: Other error with any status code and response body format. + content: {} + "200": + description: Job modified successfully + content: + application/json: + schema: + type: object + example: | + { "userDefined": {} } + "400": + description: Bad Request + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + example: + errors: + - "<<": invalidRequestError + "404": + description: Not Found + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + example: + errors: + - "<<": jobNotFoundError + x-codegen-request-body-name: JobDefinition + + /jobs/{id}/tags: + get: + tags: + - southbound + - northbound + summary: Get tags + description: Get the tags of a job + parameters: + - $ref: "#/components/parameters/responseFilter" + - name: id + in: path + description: Job ID + required: true + schema: + type: string + responses: + default: + description: Other error with any status code and response body format. + content: {} + "200": + description: Job tags + content: + application/json: + schema: + $ref: "#/components/schemas/TagList" + "404": + description: Not Found + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + example: + errors: + - "<<": jobNotFoundError + post: + tags: + - northbound + summary: Add a tag + description: | + Add a tag to an existing job + parameters: + - $ref: "#/components/parameters/responseFilter" + - name: id + in: path + description: Job ID + required: true + schema: + type: string + requestBody: + description: Tags to add + content: + application/json: + schema: + minItems: 1 + type: array + items: + type: string + required: true + responses: + default: + description: Other error with any status code and response body format. + content: {} + "200": + description: Successfully added tag to job + content: + application/json: + schema: + $ref: "#/components/schemas/TagList" + "400": + description: Bad Request + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + example: + errors: + - "<<": invalidRequestError + "403": + description: Forbidden + "404": + description: Not Found + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + example: + errors: + - "<<": jobNotFoundError + x-codegen-request-body-name: Tags + + delete: + tags: + - northbound + summary: Delete a tag + description: | + Delete a tag from an existing job + parameters: + - $ref: "#/components/parameters/responseFilter" + - name: id + in: path + description: Job ID + required: true + schema: + type: string + requestBody: + description: Tags to delete + content: + application/json: + schema: + minItems: 1 + type: array + items: + type: string + required: true + responses: + default: + description: Other error with any status code and response body format. + content: {} + "200": + description: Successfully deleted tag + content: + application/json: + schema: + $ref: "#/components/schemas/TagList" + "400": + description: Bad Request + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + example: + errors: + - "<<": invalidRequestError + "403": + description: Forbidden + "404": + description: Not Found + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + example: + errors: + - "<<": jobNotFoundError + x-codegen-request-body-name: Tags + +components: + schemas: + PaginatedWorkflowList: + type: object + required: + - pagination + - content + properties: + pagination: + $ref: "#/components/schemas/Pagination" + content: + type: array + items: + $ref: "#/components/schemas/Workflow" + description: Paginated list of workflows + + Workflow: + required: + - name + - transitions + - states + type: object + properties: + name: + maxLength: 64 + minLength: 1 + pattern: "^[a-zA-Z0-9\\-\\.]+$" + type: string + description: User provided unique workflow name + nullable: false + example: wfx.workflow.dau.direct + description: + maxLength: 1024 + type: string + description: Description of the workflow + example: This is a workflow + x-go-type-skip-optional-pointer: true + states: + type: array + maxItems: 4096 + items: + $ref: "#/components/schemas/State" + x-omitempty: true + groups: + type: array + maxItems: 1024 + items: + $ref: "#/components/schemas/Group" + x-omitempty: true + x-go-type-skip-optional-pointer: true + transitions: + type: array + maxItems: 16384 + items: + $ref: "#/components/schemas/Transition" + x-omitempty: true + + State: + required: + - name + type: object + properties: + name: + type: string + nullable: false + example: START + description: + type: string + example: Description of the state + x-go-type-skip-optional-pointer: true + + Group: + required: + - name + - states + type: object + properties: + name: + type: string + nullable: false + example: OPEN + description: + type: string + example: Description of the group + x-go-type-skip-optional-pointer: true + states: + minItems: 1 + type: array + description: A list of states belonging to this group + items: + type: string + + Transition: + required: + - eligible + - from + - to + type: object + properties: + from: + type: string + nullable: false + example: START + to: + type: string + nullable: false + example: END + description: + type: string + example: Description of the transition + x-go-type-skip-optional-pointer: true + eligible: + $ref: "#/components/schemas/EligibleEnum" + action: + $ref: "#/components/schemas/ActionEnum" + + EligibleEnum: + type: string + nullable: false + enum: + - CLIENT + - WFX + x-nullable: false + + ActionEnum: + type: string + enum: + - IMMEDIATE + - WAIT + + SortEnum: + type: string + default: asc + enum: + - asc + - desc + + JobRequest: + required: + - clientId + - workflow + type: object + properties: + clientId: + type: string + description: Create job for the given client ID + nullable: false + example: client42 + x-go-name: ClientID + workflow: + type: string + description: Workflow name + nullable: false + example: wfx.workflow.dau.direct + tags: + $ref: "#/components/schemas/TagList" + definition: + type: object + description: + The existing job definition will be replaced with this if this + property is not empty. + example: | + { "userDefined": {} } + x-go-type-skip-optional-pointer: true + + JobStatus: + required: + - state + type: object + properties: + state: + type: string + description: Name of the new workflow state + nullable: false + example: END + clientId: + type: string + description: Client which sent the status update + nullable: false + example: client42 + x-go-name: ClientID + x-omitempty: true + x-go-type-skip-optional-pointer: true + progress: + maximum: 100 + type: integer + description: Current job progress percentage + format: int32 + message: + maxLength: 1024 + type: string + description: "Reason message/info, free text from client" + x-omitempty: true + x-go-type-skip-optional-pointer: true + definitionHash: + maxLength: 64 + type: string + description: Job definition hash + readOnly: true + x-omitempty: true + x-go-type-skip-optional-pointer: true + context: + type: object + description: + "Client-specific JSON object to report additional context information\ + \ such as error details, stack traces, etc" + example: | + { + "lines": [ "line1", "line2" ] + } + description: Job status information + + Job: + type: object + required: + - id + properties: + id: + maxLength: 36 + type: string + description: Unique job ID (wfx-generated) + nullable: false + readOnly: true + example: 3307e5cb-074c-49b7-99d4-5e61839a4c2d + x-go-name: ID + x-go-type-skip-optional-pointer: true + clientId: + type: string + nullable: false + example: client42 + x-go-name: ClientID + x-go-type-skip-optional-pointer: true + workflow: + $ref: "#/components/schemas/Workflow" + tags: + $ref: "#/components/schemas/TagList" + definition: + type: object + example: | + { "userDefined": {} } + x-go-type-skip-optional-pointer: true + status: + $ref: "#/components/schemas/JobStatus" + stime: + type: string + description: + "Date and time (ISO8601) when the job was created (set by wfx).\ + \ Although stime conceptually always exists, it's nullable because we\ + \ don't want to serialize stime in some cases (e.g. for job events)." + format: date-time + nullable: true + readOnly: true + mtime: + type: string + description: + Date and time (ISO8601) when the job was last modified (set + by wfx) + format: date-time + nullable: true + readOnly: true + history: + type: array + description: | + The job's history. Last in, first out (LIFO). Array is truncated if its length exceeds the maximum allowed length. + By default, the job history is omitted from responses unless explicitly requested by the client (see the `history` URL parameter). + items: + $ref: "#/components/schemas/History" + x-omitempty: true + maxItems: 8192 + + JobEvent: + type: object + properties: + ctime: + type: string + format: date-time + nullable: true + action: + type: string + job: + $ref: "#/components/schemas/Job" + tags: + type: array + items: + type: string + + History: + type: object + properties: + mtime: + type: string + description: Date and time (ISO8601) when the job was modified (set by wfx) + format: date-time + readOnly: true + status: + $ref: "#/components/schemas/JobStatus" + definition: + type: object + example: | + { "userDefined": {} } + + PaginatedJobList: + type: object + required: + - pagination + - content + properties: + pagination: + $ref: "#/components/schemas/Pagination" + content: + type: array + items: + $ref: "#/components/schemas/Job" + description: Paginated list of jobs + + ErrorResponse: + type: object + properties: + errors: + type: array + maxItems: 128 + items: + $ref: "#/components/schemas/Error" + Error: + type: object + required: + - code + - logref + - message + properties: + code: + type: string + description: Identifier code for the reason of the error + logref: + type: string + description: Log correlation ID + message: + type: string + description: Error message + + Pagination: + type: object + required: + - limit + - offset + - total + properties: + limit: + type: integer + format: int32 + description: the maximum number of items to return + example: 20 + maximum: 1024 + offset: + type: integer + format: int64 + description: the number of items to skip before starting to return results + example: 0 + total: + type: integer + format: int64 + description: the total number of items + example: 1000 + + TagList: + type: array + maxItems: 16 + items: + type: string + example: EUROPE_WEST + x-omitempty: true + x-go-type-skip-optional-pointer: true + + CheckerResult: + type: object + properties: + info: + type: object + description: Info contains additional information about this health result. + status: + $ref: "#/components/schemas/AvailabilityStatus" + description: Status is the aggregated system availability status. + details: + type: object + additionalProperties: + $ref: "#/components/schemas/CheckResult" + description: Details contains health information for all checked components. + required: + - status + + AvailabilityStatus: + type: string + description: Enumeration of possible availability statuses. + enum: + - up + - down + - unknown + x-go-type-skip-optional-pointer: true + x-omitempty: true + + CheckResult: + type: object + description: Health information for a checked component. + properties: + status: + $ref: "#/components/schemas/AvailabilityStatus" + timestamp: + type: string + format: date-time + description: The time when the check was executed. + example: "2023-10-03T10:15:30Z" + x-go-type-skip-optional-pointer: true + x-omitempty: true + error: + type: string + description: The check error message, if the check failed. + example: "Component not reachable" + x-go-type-skip-optional-pointer: true + x-omitempty: true + + parameters: + state: + name: state + x-go-name: paramState + in: query + description: Filter jobs based on the current state value + schema: + type: string + group: + name: group + x-go-name: paramGroup + in: query + description: Filter jobs based on the group they are in + style: form + explode: false + schema: + type: array + items: + type: string + clientId: + name: clientId + x-go-name: paramClientID + in: query + description: Filter jobs belonging to a specific client with clientId + schema: + type: string + workflow: + name: workflow + x-go-name: paramWorkflow + in: query + description: Filter jobs matching by workflow + schema: + type: string + history: + x-go-name: paramHistory + name: history + in: query + description: Boolean flag to include the transition history of the job + schema: + type: boolean + jobId: + name: id + x-go-name: paramJobID + in: path + description: Job ID + required: true + schema: + type: string + tag: + name: tag + x-go-name: paramTag + in: query + description: A list of tags + style: form + explode: false + schema: + $ref: "#/components/schemas/TagList" + sort: + name: sort + x-go-name: paramSort + in: query + description: the order of returned elements + schema: + $ref: "#/components/schemas/SortEnum" + limit: + name: limit + x-go-name: paramLimit + in: query + description: the maximum number of items to return + schema: + type: integer + format: int32 + default: 10 + offset: + name: offset + x-go-name: paramOffset + in: query + description: the number of items to skip before starting to return results + schema: + type: integer + format: int64 + default: 0 + responseFilter: + name: X-Response-Filter + in: header + description: Apply a jq-like filter to the response + required: false + schema: + type: string + +x-paths-templates: + Errors: + invalidRequestError: + code: wfx.invalidRequest + logref: 96a37ea1f7d205ffbfa12334c6812727 + message: The request was invalid and could not be completed by the storage + jobNotFoundError: + code: wfx.jobNotFound + logref: 11cc67762090e15b79a1387eca65ba65 + message: Job ID was not found + jobTerminalStateError: + code: wfx.jobTerminalState + logref: 916f0a913a3e4a52a96bd271e029c201 + message: The request was invalid because the job is in a terminal state + workflowNotFoundError: + code: wfx.workflowNotFound + logref: c452719774086b6e803bb8f6ecea9899 + message: Workflow not found for given name + workflowNotUniqueError: + code: wfx.workflowNotUnique + logref: e1ee1f2aea859b9dd34579610e386da6 + message: Workflow with name already exists + workflowInvalidError: + code: wfx.workflowInvalid + logref: 18f57adc70dd79c7fb4f1246be8a6e04 + message: Workflow validation failed diff --git a/test/01-api.bats b/test/01-api.bats deleted file mode 100755 index 0a5214ed..00000000 --- a/test/01-api.bats +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env bats -# -# SPDX-FileCopyrightText: 2023 Siemens AG -# -# SPDX-License-Identifier: Apache-2.0 -# -# Author: Michael Adler - -. lib.sh - -setup_file() { - launch_wfx - wait_wfx_running -} - -teardown_file() { - pkill wfx -} - -@test "check /swagger.json available" { - curl -s -f "$BASEURL/swagger.json" -} - -@test "response filters" { - create_kanban_workflow - local id - id=$(create_kanban_job) - run curl -s -f "$BASEURL/jobs/$id/status" -H "X-Response-Filter: .state" - assert_output '"NEW"' -} - -@test "check health" { - curl http://localhost:8080/health -} - -@test "check version" { - run sh -c "curl -s -f http://localhost:8080/version | jq -r .apiVersion" - assert_output 'v1' -} diff --git a/test/01-storage.bats b/test/01-storage.bats new file mode 100755 index 00000000..74afa989 --- /dev/null +++ b/test/01-storage.bats @@ -0,0 +1,52 @@ +#!/usr/bin/env bats +# +# SPDX-FileCopyrightText: 2024 Siemens AG +# +# SPDX-License-Identifier: Apache-2.0 +# +# Author: Michael Adler + +. lib.sh + +teardown() { + pkill wfx + rm -f wfx.db* +} + +@test "Default storage" { + cd "$BATS_TEST_TMPDIR" + wfx & + local count + wait_wfx_running 2 + assert_file_exists wfx.db +} + +@test "SQLite in-memory storage" { + cd "$BATS_TEST_TMPDIR" + wfx --storage sqlite --storage-opt "file:wfx?mode=memory&cache=shared&_fk=1" & + local count + wait_wfx_running 2 + assert_file_not_exists wfx.db +} + +@test "PostgreSQL storage using CLI args" { + wfx --storage postgres \ + --storage-opt "host=${PGHOST:-localhost} port=${PGPORT:-5432} user=${PGUSER:-wfx} password=${PGPASSWORD:-secret} database=${PGDATABASE:-wfx}" & + wait_wfx_running 2 +} + +@test "PostgreSQL storage using env variables" { + env PGHOST=${PGHOST:-localhost} \ + PGPORT=${PGPORT:-5432} \ + PGUSER=${PGUSER:-wfx} \ + PGPASSWORD=${PGPASSWORD:-secret} \ + PGDATABASE=${PGDATABASE:-wfx} \ + wfx --storage postgres & + wait_wfx_running 2 +} + +@test "MySQL storage using CLI args" { + wfx --storage mysql \ + --storage-opt "${MYSQL_USER:-root}:${MYSQL_PASSWORD:-root}@tcp(${MYSQL_HOST:-localhost}:${MYSQL_PORT:-3306})/${MYSQL_DATABASE:-wfx}" & + wait_wfx_running 2 +} diff --git a/test/02-configuration.bats b/test/02-configuration.bats index 793beda8..e422a2c8 100755 --- a/test/02-configuration.bats +++ b/test/02-configuration.bats @@ -13,89 +13,13 @@ teardown() { rm -f wfx.db* } -@test "default storage" { - cd "$BATS_TEST_TMPDIR" - wfx & - local count - count=$(wait_wfx_running) - assert_equal "$count" 2 - assert_file_exists wfx.db -} - -@test "SQLite storage" { - cd "$BATS_TEST_TMPDIR" - wfx --storage sqlite --storage-opt "file:wfx?mode=memory&cache=shared&_fk=1" & - local count - count=$(wait_wfx_running) - assert_equal "$count" 2 - assert_file_not_exists wfx.db -} - -@test "PostgreSQL storage using cli args" { - wfx --storage postgres \ - --storage-opt "host=${PGHOST:-localhost} port=${PGPORT:-5432} user=${PGUSER:-wfx} password=${PGPASSWORD:-secret} database=${PGDATABASE:-wfx}" & - local count - count=$(wait_wfx_running) - assert_equal "$count" 2 -} - -@test "PostgreSQL storage using env variables" { - env PGHOST=${PGHOST:-localhost} \ - PGPORT=${PGPORT:-5432} \ - PGUSER=${PGUSER:-wfx} \ - PGPASSWORD=${PGPASSWORD:-secret} \ - PGDATABASE=${PGDATABASE:-wfx} \ - wfx --storage postgres & - local count - count=$(wait_wfx_running) - assert_equal "$count" 2 -} - -@test "MySQL storage" { - wfx --storage mysql \ - --storage-opt "${MYSQL_USER:-root}:${MYSQL_PASSWORD:-root}@tcp(${MYSQL_HOST:-localhost}:${MYSQL_PORT:-3306})/${MYSQL_DATABASE:-wfx}" & - local count - count=$(wait_wfx_running) - assert_equal "$count" 2 -} - -@test "Fileserver is off by default" { - launch_wfx - wait_wfx_running - run curl -s http://localhost:8080/download - assert_output '{"code":404,"message":"path /download was not found"}' -} - -@test "Fileserver is on if --simple-fileserver is non-empty" { - mkdir -p "$BATS_TEST_TMPDIR/download" - echo "hello world" >"$BATS_TEST_TMPDIR"/download/hello - wfx --storage sqlite \ - --storage-opt "file:wfx?mode=memory&cache=shared&_fk=1" \ - --simple-fileserver "$BATS_TEST_TMPDIR/download" & - wait_wfx_running - run curl -s -f http://localhost:8080/download/hello - assert_output 'hello world' -} - -@test "Configuration via env variables" { - cd "$BATS_TEST_TMPDIR" - export WFX_LOG_LEVEL=debug - wfx 1>wfx.log 2>&1 & - sleep 0.5 - # this message has level debug - local msg="Setting up persistence storage" - local count - count=$(grep -c "$msg" wfx.log) - assert_equal "$count" 1 -} - @test "Configuration via yaml file" { cd "$BATS_TEST_TMPDIR" echo "log-level: debug" > wfx.yml wfx 1>wfx.log 2>&1 & sleep 0.5 # this message has level debug - local msg="Setting up persistence storage" + local msg="Setting up persistent storage" local count count=$(grep -c "$msg" wfx.log) assert_equal "$count" 1 diff --git a/test/04-operations.bats b/test/04-operations.bats index b14d0130..470ccbb5 100755 --- a/test/04-operations.bats +++ b/test/04-operations.bats @@ -8,76 +8,26 @@ . lib.sh -PRIVATE_KEY="$BATS_FILE_TMPDIR/private.pem" -PUBLIC_KEY="$BATS_FILE_TMPDIR/public.pem" - -setup_file() { - openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout "$PRIVATE_KEY" -out "$PUBLIC_KEY" -subj "/CN=example.com" -} - -teardown_file() { - rm -f "$PUBLIC_KEY" "$PRIVATE_KEY" -} - teardown() { pkill wfx } -@test "TLS only" { - cd "$BATS_TEST_TMPDIR" - wfx --scheme=https \ - --tls-certificate="$PUBLIC_KEY" \ - --tls-key="$PRIVATE_KEY" & - local count - count=$(wait_wfx_running) - assert_equal "$count" 2 -} - -@test "Unix-Domain Sockets" { - cd "$BATS_TEST_TMPDIR" - wfx --scheme unix \ - --client-unix-socket "$BATS_TEST_TMPDIR/wfx-client.sock" \ - --mgmt-unix-socket "$BATS_TEST_TMPDIR/wfx-mgmt.sock" & - local i=0 - while [[ $i -lt 30 ]]; do - RC=0 - wfxctl --client-unix-socket "$BATS_TEST_TMPDIR/wfx-client.sock" version || RC=$? - if [[ $RC -eq 0 ]]; then - return 0 - fi - sleep 1 - i=$((i+1)) - done - return 1 -} - -@test "TLS mixed-mode" { - cd "$BATS_TEST_TMPDIR" - wfx --scheme=http,https \ - --client-host=localhost \ - --client-tls-host=0.0.0.0 \ - --tls-certificate="$PUBLIC_KEY" \ - --tls-key="$PRIVATE_KEY" & - local count - count=$(wait_wfx_running 4) - assert_equal "$count" 4 -} - @test "Socket-based activation" { cd "$BATS_TEST_TMPDIR" systemd-socket-activate \ --listen "$BATS_TEST_TMPDIR/wfx-client.sock" \ --listen "$BATS_TEST_TMPDIR/wfx-mgmt.sock" \ wfx --scheme unix & + local RC local i=0 while [[ $i -lt 30 ]]; do RC=0 wfxctl --client-unix-socket "$BATS_TEST_TMPDIR/wfx-client.sock" version || RC=$? if [[ $RC -eq 0 ]]; then - return 0 + break fi sleep 1 i=$((i+1)) done - return 1 + assert_equal "$RC" 0 } diff --git a/test/05-workflows.bats b/test/05-workflows.bats index 553bb4dd..53eeaf8a 100755 --- a/test/05-workflows.bats +++ b/test/05-workflows.bats @@ -10,7 +10,7 @@ setup_file() { launch_wfx - wait_wfx_running + wait_wfx_running 2 } teardown_file() { diff --git a/test/06-plugins.bats b/test/06-plugins.bats new file mode 100755 index 00000000..8af00715 --- /dev/null +++ b/test/06-plugins.bats @@ -0,0 +1,53 @@ +#!/usr/bin/env bats +# +# SPDX-FileCopyrightText: 2024 Siemens AG +# +# SPDX-License-Identifier: Apache-2.0 +# +# Author: Michael Adler + +. lib.sh + +setup_file() { + make -s -C.. plugins +} + +teardown() { + if pgrep -x wfx > /dev/null; then + pkill -9 wfx + fi +} + +@test "plugins work and wfx shuts down cleanly" { + wfx --log-level=debug --log-format=pretty \ + --storage=sqlite --storage-opt="file:wfx?mode=memory&cache=shared&_fk=1" \ + --client-plugins-dir ../example/plugin & + wait_wfx_running 2 + run curl -s -o /dev/null -w "%{http_code}" "$BASEURL/workflows" + assert_output "403" + kill %1 # wfx, expect a clean shutdown + local job_count=1 + for _ in {1..10}; do + job_count=$(jobs -r | wc -l | tr -d " ") + if [ "$job_count" -eq 0 ]; then + break + fi + sleep 0.3 + done + assert_equal "$job_count" 0 +} + +@test "wfx exits if plugin crashes" { + wfx --log-level=debug --log-format=pretty \ + --storage=sqlite --storage-opt="file:wfx?mode=memory&cache=shared&_fk=1" \ + --client-plugins-dir ../example/plugin & + WFX_PID=$! + wait_wfx_running 2 + pkill -9 plugin + + for _ in {1..10}; do + if [[ ! -d "/proc/$WFX_PID" ]]; then break; fi + sleep 0.1 + done + assert [ ! -e "/proc/$WFX_PID" ] +} diff --git a/test/lib.sh b/test/lib.sh index dca0bf64..40925944 100644 --- a/test/lib.sh +++ b/test/lib.sh @@ -12,130 +12,21 @@ load 'test_helper/bats-file/load' BASEURL="http://localhost:8080/api/wfx/v1" wait_wfx_running() { - local expected=${1:-2} - local count=0 + local expected=$1 + local count for _i in {1..20}; do - count=$(wfxctl health | grep -c up || echo 0) - if [[ "$count" -ge "$expected" ]]; then - break - fi - sleep 0.1 + count=$(wfxctl health 2>/dev/null || echo "") + count=$(echo "$count" | grep -c up || true) + if [[ "${count:-0}" -eq "$expected" ]]; then + break + fi + sleep 0.5 done - echo "$count" + assert_equal "$count" "$expected" } launch_wfx() { - wfx --storage sqlite --storage-opt "file:wfx?mode=memory&cache=shared&_fk=1" & -} - -create_kanban_workflow() { - local fname="$BATS_FILE_TMPDIR/kanban.yml" - cat <>"$fname" -name: wfx.workflow.kanban - -groups: - - name: OPEN - description: The task is ready for the client(s). - states: - - NEW - - PROGRESS - - VALIDATE - - - name: CLOSED - description: The task is in a final state, i.e. it cannot progress any further. - states: - - DONE - - DISCARDED - -states: - - name: BACKLOG - description: Task is created - - - name: NEW - description: task is ready to be pulled - - - name: PROGRESS - description: task is being worked on - - - name: VALIDATE - description: task is validated - - - name: DONE - description: task is done according to the definition of done - - - name: DISCARDED - description: task is discarded - -transitions: - - from: BACKLOG - to: NEW - eligible: WFX - action: IMMEDIATE - description: | - Immediately transition to "NEW" upon a task hitting the backlog, - conveniently done by wfx "on behalf of" the Product Owner. - - - from: NEW - to: PROGRESS - eligible: CLIENT - description: | - A Developer pulls the task or - the Product Owner discards it (see below transition), - whoever comes first. - - - from: NEW - to: DISCARDED - eligible: WFX - description: | - The Product Owner discards the task or - a Developer pulls it (see preceding transition), - whoever comes first. - - - from: PROGRESS - to: VALIDATE - eligible: CLIENT - description: | - The Developer has completed the task, it's ready for validation. - - - from: PROGRESS - to: PROGRESS - eligible: CLIENT - description: | - The Developer reports task completion progress percentage. - - - from: VALIDATE - to: DISCARDED - eligible: WFX - description: | - The task result has no customer value. - - - from: VALIDATE - to: DISCARDED - eligible: CLIENT - description: | - The task result cannot be integrated into Production software. - - - from: VALIDATE - to: DONE - eligible: CLIENT - description: | - A Developer has validated the task result as useful. - - - from: VALIDATE - to: DONE - eligible: WFX - action: WAIT - description: | - The Product Owner has validated the task result as useful -EOF - wfxctl workflow create "$fname" >/dev/null -} - -create_kanban_job() { - local id - id=$(wfxctl job create --workflow wfx.workflow.kanban \ - --client-id Dana --filter '.id' --raw) - echo "$id" + wfx --log-level=debug --log-format=pretty --storage=sqlite --storage-opt="file:wfx?mode=memory&cache=shared&_fk=1" & } # vim: ft=bash diff --git a/workflow/dau/dau.go b/workflow/dau/dau.go index ef0fc742..84f11280 100644 --- a/workflow/dau/dau.go +++ b/workflow/dau/dau.go @@ -11,7 +11,7 @@ package dau import ( _ "embed" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "gopkg.in/yaml.v3" ) @@ -21,14 +21,14 @@ var DirectYAML string //go:embed wfx.workflow.dau.phased.yml var PhasedYAML string -func DirectWorkflow() *model.Workflow { - var result model.Workflow +func DirectWorkflow() *api.Workflow { + var result api.Workflow _ = yaml.Unmarshal([]byte(DirectYAML), &result) return &result } -func PhasedWorkflow() *model.Workflow { - var result model.Workflow +func PhasedWorkflow() *api.Workflow { + var result api.Workflow _ = yaml.Unmarshal([]byte(PhasedYAML), &result) return &result } diff --git a/workflow/validate.go b/workflow/validate.go index 4b0853f9..55db6535 100644 --- a/workflow/validate.go +++ b/workflow/validate.go @@ -12,11 +12,9 @@ import ( "errors" "fmt" - "github.com/Southclaws/fault" - "github.com/go-openapi/strfmt" "github.com/yourbasic/graph" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" ) type edge struct { @@ -24,13 +22,9 @@ type edge struct { To string } -func ValidateWorkflow(workflow *model.Workflow) error { - if err := workflow.Validate(strfmt.Default); err != nil { - return fault.Wrap(err) - } - - stateCount := len(workflow.States) - stateToNode := make(map[string]int, stateCount) +func ValidateWorkflow(workflow *api.Workflow) error { + numStates := len(workflow.States) + stateToNode := make(map[string]int, numStates) for i, s := range workflow.States { if _, found := stateToNode[s.Name]; found { @@ -40,39 +34,37 @@ func ValidateWorkflow(workflow *model.Workflow) error { stateToNode[s.Name] = i } - { - // for each state, count in how many groups we can find it - stateCount := make(map[string]int) - groupNameCount := make(map[string]int) - for _, group := range workflow.Groups { - for _, s := range group.States { - stateCount[s]++ - } - groupNameCount[group.Name]++ + // for each state, count in how many groups we can find it + stateCount := make(map[string]int) + groupNameCount := make(map[string]int) + for _, group := range workflow.Groups { + for _, s := range group.States { + stateCount[s]++ } + groupNameCount[group.Name]++ + } - // check groups do not overlap - for state, count := range stateCount { - if count > 1 { - return fmt.Errorf("state %s belongs to more than one group", state) - } + // check groups do not overlap + for state, count := range stateCount { + if count > 1 { + return fmt.Errorf("state %s belongs to more than one group", state) } + } - // ensure that no two groups have the same name - for name, count := range groupNameCount { - if count > 1 { - return fmt.Errorf("group name %s used multiple times", name) - } + // ensure that no two groups have the same name + for name, count := range groupNameCount { + if count > 1 { + return fmt.Errorf("group name %s used multiple times", name) } } // build a graph from the transitions - g := graph.New(stateCount) + g := graph.New(numStates) // (from, to) -> [client, wfx] - transitions := make(map[edge]([]model.EligibleEnum)) + transitions := make(map[edge]([]api.EligibleEnum)) // for each edge (from, _), count the ones containing actor WFX - outgoingActions := make(map[string]([]model.ActionEnum)) + outgoingActions := make(map[string]([]api.ActionEnum)) for _, t := range workflow.Transitions { from, foundFrom := stateToNode[t.From] @@ -84,11 +76,12 @@ func ValidateWorkflow(workflow *model.Workflow) error { transitions[e] = append(transitions[e], t.Eligible) action := t.Action - if action == "" { + if action == nil { // default action - action = model.ActionEnumWAIT + wait := api.WAIT + action = &wait } - outgoingActions[t.From] = append(outgoingActions[t.From], action) + outgoingActions[t.From] = append(outgoingActions[t.From], *action) if from != to { // we allow trivial loops @@ -108,7 +101,7 @@ func ValidateWorkflow(workflow *model.Workflow) error { // count immediate actions count := 0 for _, act := range actions { - if act == model.ActionEnumIMMEDIATE { + if act == api.IMMEDIATE { count++ } } diff --git a/workflow/validate_test.go b/workflow/validate_test.go index f296b3ba..7a0bede2 100644 --- a/workflow/validate_test.go +++ b/workflow/validate_test.go @@ -13,7 +13,7 @@ import ( "github.com/stretchr/testify/assert" - "github.com/siemens/wfx/generated/model" + "github.com/siemens/wfx/generated/api" "github.com/siemens/wfx/workflow/dau" ) @@ -23,8 +23,8 @@ var ( state3 = "state3" state4 = "state4" - eligibleClient = model.EligibleEnumCLIENT - eligibleWfx = model.EligibleEnumWFX + eligibleClient = api.CLIENT + eligibleWfx = api.WFX groupOpen = "OPEN" @@ -32,7 +32,7 @@ var ( ) func TestValidateWorkflow_NoStates(t *testing.T) { - err := ValidateWorkflow(&model.Workflow{}) + err := ValidateWorkflow(&api.Workflow{}) assert.Error(t, err) } @@ -45,10 +45,10 @@ func TestValidateWorkflow_Dau(t *testing.T) { } func TestValidateWorkflow_StateNamesMustBeUnique(t *testing.T) { - eligible := model.EligibleEnumWFX - m := model.Workflow{ + eligible := api.WFX + m := api.Workflow{ Name: name, - States: []*model.State{ + States: []api.State{ { Name: state1, }, @@ -56,7 +56,7 @@ func TestValidateWorkflow_StateNamesMustBeUnique(t *testing.T) { Name: state1, }, }, - Transitions: []*model.Transition{ + Transitions: []api.Transition{ {From: state1, To: state1, Eligible: eligible}, }, } @@ -65,9 +65,9 @@ func TestValidateWorkflow_StateNamesMustBeUnique(t *testing.T) { } func TestValidateWorkflow_TransitionsMustExist(t *testing.T) { - m := model.Workflow{ + m := api.Workflow{ Name: name, - States: []*model.State{ + States: []api.State{ { Name: state1, }, @@ -75,7 +75,7 @@ func TestValidateWorkflow_TransitionsMustExist(t *testing.T) { Name: state2, }, }, - Transitions: []*model.Transition{ + Transitions: []api.Transition{ { From: state1, To: state4, @@ -88,9 +88,9 @@ func TestValidateWorkflow_TransitionsMustExist(t *testing.T) { } func TestValidateWorkflow_DuplicateTransition(t *testing.T) { - m := model.Workflow{ + m := api.Workflow{ Name: name, - States: []*model.State{ + States: []api.State{ { Name: state1, }, @@ -98,7 +98,7 @@ func TestValidateWorkflow_DuplicateTransition(t *testing.T) { Name: state2, }, }, - Transitions: []*model.Transition{ + Transitions: []api.Transition{ { From: state1, To: state2, @@ -116,9 +116,9 @@ func TestValidateWorkflow_DuplicateTransition(t *testing.T) { } func TestValidateWorkflow_ReachableFromInitial(t *testing.T) { - m := model.Workflow{ + m := api.Workflow{ Name: name, - States: []*model.State{ + States: []api.State{ { Name: state1, }, @@ -129,7 +129,7 @@ func TestValidateWorkflow_ReachableFromInitial(t *testing.T) { Name: state3, }, }, - Transitions: []*model.Transition{ + Transitions: []api.Transition{ { From: state1, To: state2, @@ -142,9 +142,9 @@ func TestValidateWorkflow_ReachableFromInitial(t *testing.T) { } func TestValidateWorkflow_NoCycles(t *testing.T) { - m := model.Workflow{ + m := api.Workflow{ Name: name, - States: []*model.State{ + States: []api.State{ { Name: state1, }, @@ -155,7 +155,7 @@ func TestValidateWorkflow_NoCycles(t *testing.T) { Name: state3, }, }, - Transitions: []*model.Transition{ + Transitions: []api.Transition{ { From: state1, To: state2, @@ -178,9 +178,10 @@ func TestValidateWorkflow_NoCycles(t *testing.T) { } func TestValidateWorkflow_UnambiguousWfxTransition(t *testing.T) { - m := model.Workflow{ + immediate := api.IMMEDIATE + m := api.Workflow{ Name: name, - States: []*model.State{ + States: []api.State{ { Name: state1, }, @@ -191,18 +192,18 @@ func TestValidateWorkflow_UnambiguousWfxTransition(t *testing.T) { Name: state3, }, }, - Transitions: []*model.Transition{ + Transitions: []api.Transition{ { From: state1, To: state2, Eligible: eligibleWfx, - Action: model.ActionEnumIMMEDIATE, + Action: &immediate, }, { From: state1, To: state3, Eligible: eligibleWfx, - Action: model.ActionEnumIMMEDIATE, + Action: &immediate, }, }, } @@ -211,10 +212,12 @@ func TestValidateWorkflow_UnambiguousWfxTransition(t *testing.T) { } func TestValidateWorkflow_ImmediateActionUnique(t *testing.T) { + immediate := api.IMMEDIATE + wait := api.WAIT state3 := "state3" - m := model.Workflow{ + m := api.Workflow{ Name: name, - States: []*model.State{ + States: []api.State{ { Name: state1, }, @@ -225,18 +228,18 @@ func TestValidateWorkflow_ImmediateActionUnique(t *testing.T) { Name: state3, }, }, - Transitions: []*model.Transition{ + Transitions: []api.Transition{ { From: state1, To: state2, Eligible: eligibleWfx, - Action: model.ActionEnumIMMEDIATE, + Action: &immediate, }, { From: state1, To: state3, Eligible: eligibleWfx, - Action: model.ActionEnumWAIT, + Action: &wait, }, }, } @@ -245,9 +248,11 @@ func TestValidateWorkflow_ImmediateActionUnique(t *testing.T) { } func TestValidateWorkflow_ImmediateActionUnique2(t *testing.T) { - m := model.Workflow{ + immediate := api.IMMEDIATE + wait := api.WAIT + m := api.Workflow{ Name: name, - States: []*model.State{ + States: []api.State{ { Name: state1, }, @@ -258,18 +263,18 @@ func TestValidateWorkflow_ImmediateActionUnique2(t *testing.T) { Name: state3, }, }, - Transitions: []*model.Transition{ + Transitions: []api.Transition{ { From: state1, To: state1, Eligible: eligibleWfx, - Action: model.ActionEnumWAIT, + Action: &wait, }, { From: state1, To: state2, Eligible: eligibleWfx, - Action: model.ActionEnumIMMEDIATE, + Action: &immediate, }, { From: state2, @@ -284,9 +289,9 @@ func TestValidateWorkflow_ImmediateActionUnique2(t *testing.T) { func TestValidateWorkflow_AllowMultipleTransitions(t *testing.T) { state3 := "state3" - m := model.Workflow{ + m := api.Workflow{ Name: name, - States: []*model.State{ + States: []api.State{ { Name: state1, }, @@ -297,7 +302,7 @@ func TestValidateWorkflow_AllowMultipleTransitions(t *testing.T) { Name: state3, }, }, - Transitions: []*model.Transition{ + Transitions: []api.Transition{ { From: state1, To: state2, @@ -321,9 +326,9 @@ func TestValidateWorkflow_AllowMultipleTransitions(t *testing.T) { func TestValidateWorkflow_GroupsNoOverlap(t *testing.T) { groupName2 := "CLOSED" - m := model.Workflow{ + m := api.Workflow{ Name: name, - States: []*model.State{ + States: []api.State{ { Name: state1, }, @@ -331,14 +336,14 @@ func TestValidateWorkflow_GroupsNoOverlap(t *testing.T) { Name: state2, }, }, - Transitions: []*model.Transition{ + Transitions: []api.Transition{ { From: state1, To: state2, Eligible: eligibleClient, }, }, - Groups: []*model.Group{ + Groups: []api.Group{ { Name: groupOpen, States: []string{ @@ -359,9 +364,9 @@ func TestValidateWorkflow_GroupsNoOverlap(t *testing.T) { func TestValidateWorkflow_GroupNamesUnique(t *testing.T) { groupName2 := "OPEN" - m := model.Workflow{ + m := api.Workflow{ Name: name, - States: []*model.State{ + States: []api.State{ { Name: state1, }, @@ -369,14 +374,14 @@ func TestValidateWorkflow_GroupNamesUnique(t *testing.T) { Name: state2, }, }, - Transitions: []*model.Transition{ + Transitions: []api.Transition{ { From: state1, To: state2, Eligible: eligibleClient, }, }, - Groups: []*model.Group{ + Groups: []api.Group{ { Name: groupOpen, States: []string{