From 0f370dfd5e395b99f06612581f9d43ed0828a5bc Mon Sep 17 00:00:00 2001 From: speakeasybot Date: Fri, 29 Nov 2024 00:32:39 +0000 Subject: [PATCH] ci: regenerated with OpenAPI Doc , Speakeasy CLI 1.448.2 --- .speakeasy/gen.lock | 77 +- .speakeasy/workflow.lock | 29 + .speakeasy/workflow.yaml | 3 + README.md | 15 +- RELEASES.md | 12 +- docs/data-sources/closing_reason.md | 29 - docs/data-sources/workflow_definition.md | 74 -- docs/index.md | 2 +- docs/resources/closing_reason.md | 45 - docs/resources/workflow_definition.md | 126 -- .../data-source.tf | 2 - .../data-source.tf | 2 - examples/provider/provider.tf | 2 +- .../epilot-workflow_closing_reason/import.sh | 1 - .../resource.tf | 7 - .../import.sh | 1 - .../resource.tf | 40 - gen.yaml | 5 +- go.mod | 5 +- go.sum | 2 - .../provider/closingreason_data_source.go | 140 --- .../provider/closingreason_data_source_sdk.go | 18 - internal/provider/closingreason_resource.go | 268 ----- .../provider/closingreason_resource_sdk.go | 51 - internal/provider/provider.go | 15 +- internal/provider/reflect/helpers.go | 2 +- internal/provider/types/closing_reason_id.go | 9 - internal/provider/types/dynamic_due_date.go | 12 - internal/provider/types/target.go | 10 - .../types/update_entity_attributes.go | 10 - internal/provider/utils.go | 182 +++ .../workflowdefinition_data_source.go | 231 ---- .../workflowdefinition_data_source_sdk.go | 76 -- .../provider/workflowdefinition_resource.go | 458 ------- .../workflowdefinition_resource_sdk.go | 204 ---- internal/sdk/closingreason.go | 518 +------- internal/sdk/flowsv2.go | 1065 ----------------- internal/sdk/internal/utils/env.go | 16 + internal/sdk/internal/utils/retries.go | 152 ++- .../models/operations/createflowtemplate.go | 56 - .../models/operations/deleteflowtemplate.go | 59 - .../sdk/models/operations/getclosingreason.go | 77 -- .../sdk/models/operations/getflowtemplate.go | 76 -- .../models/operations/listflowtemplates.go | 56 - .../models/operations/updateflowtemplate.go | 76 -- internal/sdk/models/shared/automationtask.go | 136 --- .../shared/closingreasonnotfoundresp.go | 15 - internal/sdk/models/shared/condition.go | 61 - internal/sdk/models/shared/decisiontask.go | 124 -- internal/sdk/models/shared/duedateconfig.go | 105 -- internal/sdk/models/shared/dynamicduedate.go | 12 +- internal/sdk/models/shared/edge.go | 38 - .../sdk/models/shared/enablerequirement.go | 62 - .../sdk/models/shared/evaluationsource.go | 243 ---- internal/sdk/models/shared/flowtemplate.go | 155 --- .../sdk/models/shared/flowtemplateslist.go | 14 - internal/sdk/models/shared/itemtype.go | 34 + internal/sdk/models/shared/operator.go | 70 -- internal/sdk/models/shared/phase.go | 56 - internal/sdk/models/shared/section.go | 47 + internal/sdk/models/shared/statement.go | 38 - internal/sdk/models/shared/step.go | 147 +++ internal/sdk/models/shared/steprequirement.go | 59 + internal/sdk/models/shared/steptype.go | 34 + internal/sdk/models/shared/task.go | 94 -- internal/sdk/models/shared/taskbase.go | 116 -- internal/sdk/models/shared/tasktype.go | 37 - .../sdk/models/shared/workflowdefinition.go | 108 +- internal/sdk/retry/config.go | 129 ++ internal/sdk/sdk.go | 7 +- internal/sdk/workflows.go | 780 +++--------- 71 files changed, 1127 insertions(+), 5910 deletions(-) create mode 100644 .speakeasy/workflow.lock delete mode 100644 docs/data-sources/closing_reason.md delete mode 100644 docs/data-sources/workflow_definition.md delete mode 100644 docs/resources/closing_reason.md delete mode 100644 docs/resources/workflow_definition.md delete mode 100644 examples/data-sources/epilot-workflow_closing_reason/data-source.tf delete mode 100644 examples/data-sources/epilot-workflow_workflow_definition/data-source.tf delete mode 100644 examples/resources/epilot-workflow_closing_reason/import.sh delete mode 100644 examples/resources/epilot-workflow_closing_reason/resource.tf delete mode 100644 examples/resources/epilot-workflow_workflow_definition/import.sh delete mode 100644 examples/resources/epilot-workflow_workflow_definition/resource.tf delete mode 100644 internal/provider/closingreason_data_source.go delete mode 100644 internal/provider/closingreason_data_source_sdk.go delete mode 100644 internal/provider/closingreason_resource.go delete mode 100644 internal/provider/closingreason_resource_sdk.go delete mode 100644 internal/provider/types/closing_reason_id.go delete mode 100644 internal/provider/types/dynamic_due_date.go delete mode 100644 internal/provider/types/target.go delete mode 100644 internal/provider/types/update_entity_attributes.go delete mode 100644 internal/provider/workflowdefinition_data_source.go delete mode 100644 internal/provider/workflowdefinition_data_source_sdk.go delete mode 100644 internal/provider/workflowdefinition_resource.go delete mode 100644 internal/provider/workflowdefinition_resource_sdk.go delete mode 100644 internal/sdk/flowsv2.go create mode 100644 internal/sdk/internal/utils/env.go delete mode 100644 internal/sdk/models/operations/createflowtemplate.go delete mode 100644 internal/sdk/models/operations/deleteflowtemplate.go delete mode 100644 internal/sdk/models/operations/getclosingreason.go delete mode 100644 internal/sdk/models/operations/getflowtemplate.go delete mode 100644 internal/sdk/models/operations/listflowtemplates.go delete mode 100644 internal/sdk/models/operations/updateflowtemplate.go delete mode 100644 internal/sdk/models/shared/automationtask.go delete mode 100644 internal/sdk/models/shared/closingreasonnotfoundresp.go delete mode 100644 internal/sdk/models/shared/condition.go delete mode 100644 internal/sdk/models/shared/decisiontask.go delete mode 100644 internal/sdk/models/shared/duedateconfig.go delete mode 100644 internal/sdk/models/shared/edge.go delete mode 100644 internal/sdk/models/shared/enablerequirement.go delete mode 100644 internal/sdk/models/shared/evaluationsource.go delete mode 100644 internal/sdk/models/shared/flowtemplate.go delete mode 100644 internal/sdk/models/shared/flowtemplateslist.go create mode 100644 internal/sdk/models/shared/itemtype.go delete mode 100644 internal/sdk/models/shared/operator.go delete mode 100644 internal/sdk/models/shared/phase.go create mode 100644 internal/sdk/models/shared/section.go delete mode 100644 internal/sdk/models/shared/statement.go create mode 100644 internal/sdk/models/shared/step.go create mode 100644 internal/sdk/models/shared/steprequirement.go create mode 100644 internal/sdk/models/shared/steptype.go delete mode 100644 internal/sdk/models/shared/task.go delete mode 100644 internal/sdk/models/shared/taskbase.go delete mode 100644 internal/sdk/models/shared/tasktype.go diff --git a/.speakeasy/gen.lock b/.speakeasy/gen.lock index c9aa25a..6b599e2 100755 --- a/.speakeasy/gen.lock +++ b/.speakeasy/gen.lock @@ -1,12 +1,12 @@ lockVersion: 2.0.0 id: 5a857039-7f4b-42d5-86fd-449767242ed2 management: - docChecksum: ae471e39d05055eb1d09ad61715bb339 + docChecksum: 8a2ff4be25db818a35891d602baa4a25 docVersion: 1.0.0 - speakeasyVersion: 1.422.1 - generationVersion: 2.438.15 - releaseVersion: 0.15.2 - configChecksum: 51df825a76e7f72ef6717314a9f0d4b4 + speakeasyVersion: 1.448.2 + generationVersion: 2.467.4 + releaseVersion: 0.16.0 + configChecksum: cd9fb60e7891a051771f5a4d382a5475 repoURL: https://github.com/epilot-dev/terraform-provider-epilot-workflow.git repoSubDirectory: . published: true @@ -21,27 +21,18 @@ features: unions: 2.85.0 terraform: additionalDependencies: 0.1.0 - constsAndDefaults: 0.1.4 - core: 3.25.0 + core: 3.27.0 deprecations: 2.81.1 envVarSecurityUsage: 0.1.0 globalSecurity: 2.81.9 globalServerURLs: 2.82.1 - retries: 2.81.1 - typeOverrides: 2.81.1 - unions: 2.81.16 + unions: 2.81.17 generatedFiles: - .gitattributes - CONTRIBUTING.md - USAGE.md - examples/README.md - - examples/data-sources/epilot-workflow_closing_reason/data-source.tf - - examples/data-sources/epilot-workflow_workflow_definition/data-source.tf - examples/provider/provider.tf - - examples/resources/epilot-workflow_closing_reason/import.sh - - examples/resources/epilot-workflow_closing_reason/resource.tf - - examples/resources/epilot-workflow_workflow_definition/import.sh - - examples/resources/epilot-workflow_workflow_definition/resource.tf - go.mod - go.sum - internal/planmodifiers/boolplanmodifier/suppress_diff.go @@ -54,10 +45,6 @@ generatedFiles: - internal/planmodifiers/setplanmodifier/suppress_diff.go - internal/planmodifiers/stringplanmodifier/suppress_diff.go - internal/planmodifiers/utils/state_check.go - - internal/provider/closingreason_data_source.go - - internal/provider/closingreason_data_source_sdk.go - - internal/provider/closingreason_resource.go - - internal/provider/closingreason_resource_sdk.go - internal/provider/provider.go - internal/provider/reflect/diags.go - internal/provider/reflect/doc.go @@ -73,22 +60,14 @@ generatedFiles: - internal/provider/reflect/primitive.go - internal/provider/reflect/slice.go - internal/provider/reflect/struct.go - - internal/provider/types/closing_reason_id.go - - internal/provider/types/dynamic_due_date.go - - internal/provider/types/target.go - - internal/provider/types/update_entity_attributes.go - internal/provider/utils.go - - internal/provider/workflowdefinition_data_source.go - - internal/provider/workflowdefinition_data_source_sdk.go - - internal/provider/workflowdefinition_resource.go - - internal/provider/workflowdefinition_resource_sdk.go - internal/sdk/.gitattributes - internal/sdk/.gitignore - internal/sdk/CONTRIBUTING.md - internal/sdk/closingreason.go - - internal/sdk/flowsv2.go - internal/sdk/internal/hooks/hooks.go - internal/sdk/internal/utils/contenttype.go + - internal/sdk/internal/utils/env.go - internal/sdk/internal/utils/form.go - internal/sdk/internal/utils/headers.go - internal/sdk/internal/utils/json.go @@ -102,51 +81,34 @@ generatedFiles: - internal/sdk/models/operations/changereasonstatus.go - internal/sdk/models/operations/createclosingreason.go - internal/sdk/models/operations/createdefinition.go - - internal/sdk/models/operations/createflowtemplate.go - internal/sdk/models/operations/deletedefinition.go - - internal/sdk/models/operations/deleteflowtemplate.go - internal/sdk/models/operations/getallclosingreasons.go - - internal/sdk/models/operations/getclosingreason.go - internal/sdk/models/operations/getdefinition.go - internal/sdk/models/operations/getdefinitions.go - - internal/sdk/models/operations/getflowtemplate.go - internal/sdk/models/operations/getmaxallowedlimit.go - internal/sdk/models/operations/getworkflowclosingreasons.go - - internal/sdk/models/operations/listflowtemplates.go - internal/sdk/models/operations/options.go - internal/sdk/models/operations/setworkflowclosingreasons.go - internal/sdk/models/operations/updatedefinition.go - - internal/sdk/models/operations/updateflowtemplate.go - - internal/sdk/models/shared/automationtask.go - internal/sdk/models/shared/changereasonstatusreq.go - internal/sdk/models/shared/closingreason.go - internal/sdk/models/shared/closingreasonid.go - - internal/sdk/models/shared/closingreasonnotfoundresp.go - internal/sdk/models/shared/closingreasons.go - internal/sdk/models/shared/closingreasonsids.go - internal/sdk/models/shared/closingreasonsstatus.go - - internal/sdk/models/shared/condition.go - - internal/sdk/models/shared/decisiontask.go - internal/sdk/models/shared/definitionnotfoundresp.go - - internal/sdk/models/shared/duedateconfig.go - internal/sdk/models/shared/dynamicduedate.go - internal/sdk/models/shared/ecpdetails.go - - internal/sdk/models/shared/edge.go - - internal/sdk/models/shared/enablerequirement.go - internal/sdk/models/shared/errorresp.go - - internal/sdk/models/shared/evaluationsource.go - - internal/sdk/models/shared/flowtemplate.go - - internal/sdk/models/shared/flowtemplateslist.go + - internal/sdk/models/shared/itemtype.go - internal/sdk/models/shared/maxallowedlimit.go - - internal/sdk/models/shared/operator.go - - internal/sdk/models/shared/phase.go + - internal/sdk/models/shared/section.go - internal/sdk/models/shared/security.go - - internal/sdk/models/shared/statement.go + - internal/sdk/models/shared/step.go - internal/sdk/models/shared/stepdescription.go - internal/sdk/models/shared/stepjourney.go - - internal/sdk/models/shared/task.go - - internal/sdk/models/shared/taskbase.go - - internal/sdk/models/shared/tasktype.go + - internal/sdk/models/shared/steprequirement.go + - internal/sdk/models/shared/steptype.go - internal/sdk/models/shared/updateentityattributes.go - internal/sdk/models/shared/workflowdefinition.go - internal/sdk/retry/config.go @@ -197,10 +159,10 @@ examples: createDefinition: "": requestBody: - application/json: {"assignedTo": ["952802", "80225"], "closingReasons": [{"id": "x739cew"}], "creationTime": "2021-04-27T12:01:13.000Z", "description": "Lead Qualification description", "dueDate": "2022-08-04T12:00:00.000Z", "flow": [{"name": "Initial Information Gathering", "order": 1, "type": "SECTION", "steps": [{"name": "Call client and confirm address and product", "type": "STEP", "order": 1, "assignedTo": ["123482"]}, {"name": "Check product availability", "type": "STEP", "order": 2, "assignedTo": ["123482"]}, {"name": "Send email confirming contact with the client", "type": "STEP", "order": 3, "assignedTo": ["123482"]}]}, {"name": "Print and send catalog", "type": "STEP", "order": 2, "assignedTo": ["123482"]}], "lastUpdateTime": "2021-04-27T12:01:13.000Z", "name": "Lead Qualification", "updateEntityAttributes": [{"source": "workflow_status", "target": {"entityAttribute": "my_status", "entitySchema": "opportunity"}}, {"source": "current_step", "target": {"entityAttribute": "my_status", "entitySchema": "opportunity"}}]} + application/json: {"assignedTo": ["952802", "80225"], "closingReasons": [{"id": "x739cew"}], "creationTime": "2021-04-27T12:01:13.000Z", "description": "Lead Qualification description", "dueDate": "2022-08-04T12:00:00.000Z", "flow": [{"name": "Initial Information Gathering", "order": 1, "steps": [{"assignedTo": ["123482"], "name": "Call client and confirm address and product", "order": 1, "type": "STEP"}, {"assignedTo": ["123482"], "name": "Check product availability", "order": 2, "type": "STEP"}, {"assignedTo": ["123482"], "name": "Send email confirming contact with the client", "order": 3, "type": "STEP"}], "type": "SECTION"}, {"assignedTo": ["123482"], "name": "Print and send catalog", "order": 2, "type": "STEP"}], "lastUpdateTime": "2021-04-27T12:01:13.000Z", "name": "Lead Qualification", "updateEntityAttributes": [{"source": "workflow_status", "target": {"entityAttribute": "my_status", "entitySchema": "opportunity"}}, {"source": "current_step", "target": {"entityAttribute": "my_status", "entitySchema": "opportunity"}}]} responses: "200": - application/json: {"assignedTo": ["952802", "80225"], "closingReasons": [{"id": "x739cew"}, {"id": "x739cew"}, {"id": "x739cew"}], "creationTime": "2021-08-04T21:13:50.373Z", "description": "Lead Qualification description", "dueDate": "2022-08-04T12:00:00.000Z", "flow": [{"id": "5892na2", "name": "Initial Information Gathering", "order": 1, "type": "SECTION", "steps": [{"id": "2hja82a", "name": "Call client and confirm address and product", "type": "STEP", "order": 1, "assignedTo": ["48829"]}, {"id": "ga92ha2", "name": "Check product availability", "type": "STEP", "order": 2, "assignedTo": ["45390"]}, {"id": "jga92ha", "name": "Send email confirming contact with the client", "type": "STEP", "order": 3, "assignedTo": ["8230"]}]}, {"id": "0a7g22a", "name": "Print and send catalog", "type": "STEP", "order": 2, "assignedTo": ["8239"]}], "id": "25n2k52ja", "lastUpdateTime": "2021-08-04T21:13:50.373Z", "name": "Lead Qualification", "updateEntityAttributes": []} + application/json: {"assignedTo": ["952802", "80225"], "closingReasons": [{"id": "x739cew"}, {"id": "x739cew"}, {"id": "x739cew"}], "creationTime": "2021-08-04T21:13:50.373Z", "description": "Lead Qualification description", "dueDate": "2022-08-04T12:00:00.000Z", "flow": [{"id": "5892na2", "name": "Initial Information Gathering", "order": 1, "steps": [{"assignedTo": ["48829"], "id": "2hja82a", "name": "Call client and confirm address and product", "order": 1, "type": "STEP"}, {"assignedTo": ["45390"], "id": "ga92ha2", "name": "Check product availability", "order": 2, "type": "STEP"}, {"assignedTo": ["8230"], "id": "jga92ha", "name": "Send email confirming contact with the client", "order": 3, "type": "STEP"}], "type": "SECTION"}, {"assignedTo": ["8239"], "id": "0a7g22a", "name": "Print and send catalog", "order": 2, "type": "STEP"}], "id": "25n2k52ja", "lastUpdateTime": "2021-08-04T21:13:50.373Z", "name": "Lead Qualification", "updateEntityAttributes": []} "201": application/json: {"assignedTo": ["952802", "80225"], "closingReasons": [{"id": "x739cew"}], "creationTime": "2021-08-04T21:13:50.373Z", "description": "Lead Qualification description", "dueDate": "2022-08-04T12:00:00.000Z", "flow": [{"id": "5892na2", "name": "Initial Information Gathering", "order": 1, "type": "SECTION", "steps": [{"id": "2hja82a", "name": "Call client and confirm address and product", "type": "STEP", "order": 1, "assignedTo": ["48829"]}, {"id": "ga92ha2", "name": "Check product availability", "type": "STEP", "order": 2, "assignedTo": ["45390"]}, {"id": "jga92ha", "name": "Send email confirming contact with the client", "type": "STEP", "order": 3, "assignedTo": ["8230"]}]}, {"id": "0a7g22a", "name": "Print and send catalog", "type": "STEP", "order": 2, "assignedTo": ["8239"]}], "id": "25n2k52ja", "lastUpdateTime": "2021-08-04T21:13:50.373Z", "name": "Lead Qualification", "updateEntityAttributes": [{"source": "workflow_status", "target": {"entityAttribute": "my_status", "entitySchema": "opportunity"}}, {"source": "current_step", "target": {"entityAttribute": "my_status", "entitySchema": "opportunity"}}]} deleteDefinition: @@ -215,12 +177,12 @@ examples: definitionId: "7hj28a" responses: "200": - application/json: {"assignedTo": ["952802", "80225"], "closingReasons": [{"id": "ffoowef"}, {"id": "hebwoeu"}, {"id": "mbnoenq"}], "creationTime": "2021-08-04T21:13:50.373Z", "dueDate": "2022-08-04T12:00:00.000Z", "flow": [{"id": "5892na2", "name": "Initial Information Gathering", "order": 1, "type": "SECTION", "steps": [{"id": "2hja82a", "name": "Call client and confirm address and product", "type": "STEP", "order": 1, "assignedTo": ["923432"]}, {"id": "ga92ha2", "name": "Check product availability", "type": "STEP", "order": 2, "assignedTo": ["45488"]}, {"id": "jga92ha", "name": "Send email confirming contact with the client", "type": "STEP", "order": 3, "assignedTo": ["45488"]}]}, {"id": "0a7g22a", "name": "Print and send catalog", "type": "STEP", "order": 2, "assignedTo": ["8988"]}], "id": "25n2k52ja", "lastUpdateTime": "2021-08-04T21:13:50.373Z", "name": "Lead Qualification", "updateEntityAttributes": [{"source": "current_step", "target": {"entityAttribute": "my_status", "entitySchema": "opportunity"}}, {"source": "current_section", "target": {"entityAttribute": "my_status", "entitySchema": "opportunity"}}, {"source": "current_section", "target": {"entityAttribute": "my_status", "entitySchema": "opportunity"}}]} + application/json: {"assignedTo": ["952802", "80225"], "closingReasons": [{"id": "ffoowef"}, {"id": "hebwoeu"}, {"id": "mbnoenq"}], "creationTime": "2021-08-04T21:13:50.373Z", "dueDate": "2022-08-04T12:00:00.000Z", "flow": [{"id": "5892na2", "name": "Initial Information Gathering", "order": 1, "steps": [{"assignedTo": ["923432"], "id": "2hja82a", "name": "Call client and confirm address and product", "order": 1, "type": "STEP"}, {"assignedTo": ["45488"], "id": "ga92ha2", "name": "Check product availability", "order": 2, "type": "STEP"}, {"assignedTo": ["45488"], "id": "jga92ha", "name": "Send email confirming contact with the client", "order": 3, "type": "STEP"}], "type": "SECTION"}, {"assignedTo": ["8988"], "id": "0a7g22a", "name": "Print and send catalog", "order": 2, "type": "STEP"}], "id": "25n2k52ja", "lastUpdateTime": "2021-08-04T21:13:50.373Z", "name": "Lead Qualification", "updateEntityAttributes": [{"source": "current_step", "target": {"entityAttribute": "my_status", "entitySchema": "opportunity"}}, {"source": "current_section", "target": {"entityAttribute": "my_status", "entitySchema": "opportunity"}}, {"source": "current_section", "target": {"entityAttribute": "my_status", "entitySchema": "opportunity"}}]} getDefinitions: "": responses: "200": - application/json: [{"assignedTo": ["18625", "90252"], "closingReasons": [{"id": "x739cew"}, {"id": "x739cew"}, {"id": "x739cew"}], "creationTime": "2021-08-04T21:13:50.373Z", "description": "Lead Qualification description", "dueDate": "2021-08-04T21:13:50.373Z", "flow": [{"id": "5892na2", "name": "Initial Information Gathering", "order": 1, "type": "SECTION", "steps": [{"id": "2hja82a", "name": "Call client and confirm address and product", "type": "STEP", "order": 1, "assignedTo": ["123482"]}, {"id": "ga92ha2", "name": "Check product availability", "type": "STEP", "order": 2, "assignedTo": ["123482"]}, {"id": "jga92ha", "name": "Send email confirming contact with the client", "type": "STEP", "order": 3, "assignedTo": ["123482"]}]}, {"id": "0a7g22a", "name": "Print and send catalog", "type": "STEP", "order": 2, "assignedTo": ["123482"]}], "id": "25n2k52ja", "lastUpdateTime": "2021-08-04T21:13:50.373Z", "name": "Lead Qualification", "updateEntityAttributes": []}] + application/json: [{"assignedTo": ["18625", "90252"], "creationTime": "2021-08-04T21:13:50.373Z", "description": "Lead Qualification description", "dueDate": "2021-08-04T21:13:50.373Z", "flow": [{"id": "5892na2", "name": "Initial Information Gathering", "order": 1, "steps": [{"assignedTo": ["123482"], "id": "2hja82a", "name": "Call client and confirm address and product", "order": 1, "type": "STEP"}, {"assignedTo": ["123482"], "id": "ga92ha2", "name": "Check product availability", "order": 2, "type": "STEP"}, {"assignedTo": ["123482"], "id": "jga92ha", "name": "Send email confirming contact with the client", "order": 3, "type": "STEP"}], "type": "SECTION"}, {"assignedTo": ["123482"], "id": "0a7g22a", "name": "Print and send catalog", "order": 2, "type": "STEP"}], "id": "25n2k52ja", "lastUpdateTime": "2021-08-04T21:13:50.373Z", "name": "Lead Qualification"}] getMaxAllowedLimit: "": responses: @@ -247,10 +209,10 @@ examples: path: definitionId: "7hj28a" requestBody: - application/json: {"assignedTo": ["952802", "80225"], "closingReasons": [{"id": "x739cew"}], "creationTime": "2021-08-04T21:13:50.373Z", "dueDate": "2022-08-04T12:00:00.000Z", "flow": [{"id": "5892na2", "name": "Initial Information Gathering", "order": 1, "type": "SECTION", "steps": [{"id": "2hja82a", "name": "Call client and confirm address and product", "type": "STEP", "order": 1, "assignedTo": ["8988"]}, {"id": "ga92ha2", "name": "Check product availability", "type": "STEP", "order": 2, "assignedTo": ["8988"]}, {"id": "jga92ha", "name": "Send email confirming contact with the client", "type": "STEP", "order": 3, "assignedTo": ["8988"]}]}, {"id": "0a7g22a", "name": "Print and send catalog", "type": "STEP", "order": 2, "assignedTo": ["8988"]}], "id": "25n2k52ja", "lastUpdateTime": "2021-08-04T21:13:50.373Z", "name": "Lead Qualification", "updateEntityAttributes": [{"source": "workflow_status", "target": {"entityAttribute": "my_status", "entitySchema": "opportunity"}}, {"source": "current_step", "target": {"entityAttribute": "my_status", "entitySchema": "opportunity"}}, {"source": "current_section", "target": {"entityAttribute": "my_status", "entitySchema": "opportunity"}}]} + application/json: {"assignedTo": ["952802", "80225"], "closingReasons": [{"id": "x739cew"}], "creationTime": "2021-08-04T21:13:50.373Z", "dueDate": "2022-08-04T12:00:00.000Z", "flow": [{"id": "5892na2", "name": "Initial Information Gathering", "order": 1, "steps": [{"assignedTo": ["8988"], "id": "2hja82a", "name": "Call client and confirm address and product", "order": 1, "type": "STEP"}, {"assignedTo": ["8988"], "id": "ga92ha2", "name": "Check product availability", "order": 2, "type": "STEP"}, {"assignedTo": ["8988"], "id": "jga92ha", "name": "Send email confirming contact with the client", "order": 3, "type": "STEP"}], "type": "SECTION"}, {"assignedTo": ["8988"], "id": "0a7g22a", "name": "Print and send catalog", "order": 2, "type": "STEP"}], "id": "25n2k52ja", "lastUpdateTime": "2021-08-04T21:13:50.373Z", "name": "Lead Qualification", "updateEntityAttributes": [{"source": "workflow_status", "target": {"entityAttribute": "my_status", "entitySchema": "opportunity"}}, {"source": "current_step", "target": {"entityAttribute": "my_status", "entitySchema": "opportunity"}}, {"source": "current_section", "target": {"entityAttribute": "my_status", "entitySchema": "opportunity"}}]} responses: "200": - application/json: {"assignedTo": ["952802", "80225"], "closingReasons": [{"id": "x739cew"}, {"id": "x739cew"}, {"id": "x739cew"}], "creationTime": "2021-08-04T21:13:50.373Z", "dueDate": "2022-08-04T12:00:00.000Z", "flow": [{"id": "5892na2", "name": "Initial Information Gathering", "order": 1, "type": "SECTION", "steps": [{"id": "2hja82a", "name": "Call client and confirm address and product", "type": "STEP", "order": 1, "assignedTo": ["1"]}, {"id": "ga92ha2", "name": "Check product availability", "type": "STEP", "order": 2, "assignedTo": ["56645"]}, {"id": "jga92ha", "name": "Send email confirming contact with the client", "type": "STEP", "order": 3, "assignedTo": ["949923"]}]}, {"id": "0a7g22a", "name": "Print and send catalog", "type": "STEP", "order": 2, "assignedTo": ["156645"]}], "id": "25n2k52ja", "lastUpdateTime": "2021-08-04T21:13:50.373Z", "name": "Lead Qualification", "updateEntityAttributes": []} + application/json: {"assignedTo": ["952802", "80225"], "closingReasons": [{"id": "x739cew"}, {"id": "x739cew"}, {"id": "x739cew"}], "creationTime": "2021-08-04T21:13:50.373Z", "dueDate": "2022-08-04T12:00:00.000Z", "flow": [{"id": "5892na2", "name": "Initial Information Gathering", "order": 1, "steps": [{"assignedTo": ["1"], "id": "2hja82a", "name": "Call client and confirm address and product", "order": 1, "type": "STEP"}, {"assignedTo": ["56645"], "id": "ga92ha2", "name": "Check product availability", "order": 2, "type": "STEP"}, {"assignedTo": ["949923"], "id": "jga92ha", "name": "Send email confirming contact with the client", "order": 3, "type": "STEP"}], "type": "SECTION"}, {"assignedTo": ["156645"], "id": "0a7g22a", "name": "Print and send catalog", "order": 2, "type": "STEP"}], "id": "25n2k52ja", "lastUpdateTime": "2021-08-04T21:13:50.373Z", "name": "Lead Qualification", "updateEntityAttributes": []} getClosingReason: "": parameters: @@ -299,3 +261,4 @@ examples: "200": application/json: {"closing_reasons": [{"id": "x739cew"}, {"id": "x739cew"}, {"id": "x739cew"}], "created_at": "2021-04-27T12:01:13.000Z", "due_date": "2021-04-27T12:00:00.000Z", "edges": [{"from_id": "", "id": "", "to_id": ""}], "name": "", "phases": [{"due_date": "2021-04-27T12:00:00.000Z", "id": "", "name": ""}, {"due_date": "2021-04-27T12:00:00.000Z", "id": "", "name": ""}, {"due_date": "2021-04-27T12:00:00.000Z", "id": "", "name": ""}], "tasks": [{"due_date": "2021-04-27T12:00:00.000Z", "id": "", "name": "", "task_type": "DECISION"}, {"automation_config": {"flow_id": ""}, "due_date": "2021-04-27T12:00:00.000Z", "id": "", "name": "", "task_type": "AUTOMATION"}, {"automation_config": {"flow_id": ""}, "due_date": "2021-04-27T12:00:00.000Z", "id": "", "name": "", "task_type": "AUTOMATION"}], "update_entity_attributes": [{"source": "workflow_status", "target": {"entityAttribute": "my_status", "entitySchema": "opportunity"}}, {"source": "current_step", "target": {"entityAttribute": "my_status", "entitySchema": "opportunity"}}], "updated_at": "2021-04-27T12:01:13.000Z"} "400": {} +generatedTests: {} diff --git a/.speakeasy/workflow.lock b/.speakeasy/workflow.lock new file mode 100644 index 0000000..219519b --- /dev/null +++ b/.speakeasy/workflow.lock @@ -0,0 +1,29 @@ +speakeasyVersion: 1.448.2 +sources: + my-source: + sourceNamespace: my-source + sourceRevisionDigest: sha256:e1f7c37b27d8914d33ca38746ba602451e31b936cfa25d16bb87db0f6ca7ff0c + sourceBlobDigest: sha256:70f7887ca53e442fe927d5026a8b13d36761c95fa4b07bec97e18591a95d52a5 + tags: + - latest + - speakeasy-sdk-regen-1730852930 + - 1.0.0 +targets: + terraform: + source: my-source + sourceNamespace: my-source + sourceRevisionDigest: sha256:e1f7c37b27d8914d33ca38746ba602451e31b936cfa25d16bb87db0f6ca7ff0c + sourceBlobDigest: sha256:70f7887ca53e442fe927d5026a8b13d36761c95fa4b07bec97e18591a95d52a5 +workflow: + workflowVersion: 1.0.0 + speakeasyVersion: latest + sources: + my-source: + inputs: + - location: https://docs.api.epilot.io/workflows-definition.yaml + registry: + location: registry.speakeasyapi.dev/epilot/epilot/my-source + targets: + terraform: + target: terraform + source: my-source diff --git a/.speakeasy/workflow.yaml b/.speakeasy/workflow.yaml index 320d33a..2144af3 100644 --- a/.speakeasy/workflow.yaml +++ b/.speakeasy/workflow.yaml @@ -1,8 +1,11 @@ workflowVersion: 1.0.0 +speakeasyVersion: latest sources: my-source: inputs: - location: https://docs.api.epilot.io/workflows-definition.yaml + registry: + location: registry.speakeasyapi.dev/epilot/epilot/my-source targets: terraform: target: terraform diff --git a/README.md b/README.md index f076bdd..6789e33 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ terraform { required_providers { epilot-workflow = { source = "epilot-dev/epilot-workflow" - version = "0.15.2" + version = "0.16.0" } } } @@ -119,12 +119,7 @@ provider_installation { ### Resources -* [epilot-workflow_closing_reason](docs/resources/closing_reason.md) -* [epilot-workflow_workflow_definition](docs/resources/workflow_definition.md) ### Data Sources - -* [epilot-workflow_closing_reason](docs/data-sources/closing_reason.md) -* [epilot-workflow_workflow_definition](docs/data-sources/workflow_definition.md) @@ -135,10 +130,12 @@ Workflows Definitions: Service for Workflow Definitions for different processes ## Table of Contents + +* [epilot-workflow](#epilot-workflow) + * [Installation](#installation) + * [Testing the provider locally](#testing-the-provider-locally) + * [Available Resources and Data Sources](#available-resources-and-data-sources) -* [Installation](#installation) -* [Available Resources and Data Sources](#available-resources-and-data-sources) -* [Testing the provider locally](#testing-the-provider-locally) diff --git a/RELEASES.md b/RELEASES.md index 3a0103b..0f9f618 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -22,4 +22,14 @@ Based on: - OpenAPI Doc 1.0.0 - Speakeasy CLI 1.303.0 (2.339.1) https://github.com/speakeasy-api/speakeasy ### Generated -- [terraform v0.8.2] . \ No newline at end of file +- [terraform v0.8.2] . + +## 2024-11-29 00:31:29 +### Changes +Based on: +- OpenAPI Doc +- Speakeasy CLI 1.448.2 (2.467.4) https://github.com/speakeasy-api/speakeasy +### Generated +- [terraform v0.16.0] . +### Releases +- [Terraform v0.16.0] https://registry.terraform.io/providers/epilot-dev/epilot-workflow/0.16.0 - . \ No newline at end of file diff --git a/docs/data-sources/closing_reason.md b/docs/data-sources/closing_reason.md deleted file mode 100644 index 40e29df..0000000 --- a/docs/data-sources/closing_reason.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -# generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "epilot-workflow_closing_reason Data Source - terraform-provider-epilot-workflow" -subcategory: "" -description: |- - ClosingReason DataSource ---- - -# epilot-workflow_closing_reason (Data Source) - -ClosingReason DataSource - -## Example Usage - -```terraform -data "epilot-workflow_closing_reason" "my_closingreason" { -} -``` - - -## Schema - -### Read-Only - -- `creation_time` (String) -- `id` (String) The ID of this resource. -- `last_update_time` (String) -- `status` (String) -- `title` (String) diff --git a/docs/data-sources/workflow_definition.md b/docs/data-sources/workflow_definition.md deleted file mode 100644 index f37c0bc..0000000 --- a/docs/data-sources/workflow_definition.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -# generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "epilot-workflow_workflow_definition Data Source - terraform-provider-epilot-workflow" -subcategory: "" -description: |- - WorkflowDefinition DataSource ---- - -# epilot-workflow_workflow_definition (Data Source) - -WorkflowDefinition DataSource - -## Example Usage - -```terraform -data "epilot-workflow_workflow_definition" "my_workflowdefinition" { -} -``` - - -## Schema - -### Read-Only - -- `assigned_to` (List of String) -- `closing_reasons` (Attributes List) (see [below for nested schema](#nestedatt--closing_reasons)) -- `creation_time` (String) ISO String Date & Time -- `description` (String) -- `due_date` (String) -- `dynamic_due_date` (Attributes) set a Duedate for a step then a specific (see [below for nested schema](#nestedatt--dynamic_due_date)) -- `enable_ecp_workflow` (Boolean) Indicates whether this workflow is available for End Customer Portal or not. By default it's not. -- `enabled` (Boolean) Whether the workflow is enabled or not -- `flow` (String) Parsed as JSON. -- `id` (String) The ID of this resource. -- `last_update_time` (String) ISO String Date & Time -- `name` (String) -- `taxonomies` (List of String) Taxonomy ids that are associated with this workflow and used for filtering -- `update_entity_attributes` (Attributes List) (see [below for nested schema](#nestedatt--update_entity_attributes)) -- `user_ids` (List of Number) This field is deprecated. Please use assignedTo - - -### Nested Schema for `closing_reasons` - -Read-Only: - -- `id` (String) - - - -### Nested Schema for `dynamic_due_date` - -Read-Only: - -- `action_type_condition` (String) -- `number_of_units` (Number) -- `step_id` (String) -- `time_period` (String) - - - -### Nested Schema for `update_entity_attributes` - -Read-Only: - -- `source` (String) -- `target` (Attributes) (see [below for nested schema](#nestedatt--update_entity_attributes--target)) - - -### Nested Schema for `update_entity_attributes.target` - -Read-Only: - -- `entity_attribute` (String) -- `entity_schema` (String) diff --git a/docs/index.md b/docs/index.md index 3e527c2..025bdcc 100644 --- a/docs/index.md +++ b/docs/index.md @@ -17,7 +17,7 @@ terraform { required_providers { epilot-workflow = { source = "epilot-dev/epilot-workflow" - version = "0.15.2" + version = "0.16.0" } } } diff --git a/docs/resources/closing_reason.md b/docs/resources/closing_reason.md deleted file mode 100644 index 55f90d2..0000000 --- a/docs/resources/closing_reason.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -# generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "epilot-workflow_closing_reason Resource - terraform-provider-epilot-workflow" -subcategory: "" -description: |- - ClosingReason Resource ---- - -# epilot-workflow_closing_reason (Resource) - -ClosingReason Resource - -## Example Usage - -```terraform -resource "epilot-workflow_closing_reason" "my_closingreason" { - creation_time = "...my_creation_time..." - id = "...my_id..." - last_update_time = "...my_last_update_time..." - status = "INACTIVE" - title = "...my_title..." -} -``` - - -## Schema - -### Required - -- `status` (String) must be one of ["ACTIVE", "INACTIVE"]; Requires replacement if changed. -- `title` (String) Requires replacement if changed. - -### Optional - -- `creation_time` (String) Requires replacement if changed. -- `id` (String) Requires replacement if changed. -- `last_update_time` (String) Requires replacement if changed. - -## Import - -Import is supported using the following syntax: - -```shell -terraform import epilot-workflow_closing_reason.my_epilot-workflow_closing_reason "" -``` diff --git a/docs/resources/workflow_definition.md b/docs/resources/workflow_definition.md deleted file mode 100644 index 36f10fc..0000000 --- a/docs/resources/workflow_definition.md +++ /dev/null @@ -1,126 +0,0 @@ ---- -# generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "epilot-workflow_workflow_definition Resource - terraform-provider-epilot-workflow" -subcategory: "" -description: |- - WorkflowDefinition Resource ---- - -# epilot-workflow_workflow_definition (Resource) - -WorkflowDefinition Resource - -## Example Usage - -```terraform -resource "epilot-workflow_workflow_definition" "my_workflowdefinition" { - assigned_to = [ - "..." - ] - closing_reasons = [ - { - id = "x739cew" - } - ] - creation_time = "2021-04-27T12:01:13.000Z" - description = "...my_description..." - due_date = "2021-04-27T12:00:00.000Z" - dynamic_due_date = { - action_type_condition = "STEP_CLOSED" - number_of_units = 0.36 - step_id = "...my_step_id..." - time_period = "days" - } - enable_ecp_workflow = false - enabled = false - flow = "{ \"see\": \"documentation\" }" - id = "...my_id..." - last_update_time = "2021-04-27T12:01:13.000Z" - name = "...my_name..." - taxonomies = [ - "..." - ] - update_entity_attributes = [ - { - source = "current_step" - target = { - entity_attribute = "my_status" - entity_schema = "opportunity" - } - } - ] - user_ids = [ - 5.93 - ] -} -``` - - -## Schema - -### Required - -- `flow` (String) Parsed as JSON. -- `name` (String) - -### Optional - -- `assigned_to` (List of String) -- `closing_reasons` (Attributes List) (see [below for nested schema](#nestedatt--closing_reasons)) -- `creation_time` (String) ISO String Date & Time -- `description` (String) -- `due_date` (String) -- `dynamic_due_date` (Attributes) set a Duedate for a step then a specific (see [below for nested schema](#nestedatt--dynamic_due_date)) -- `enable_ecp_workflow` (Boolean) Indicates whether this workflow is available for End Customer Portal or not. By default it's not. -- `enabled` (Boolean) Whether the workflow is enabled or not. Default: true -- `last_update_time` (String) ISO String Date & Time -- `taxonomies` (List of String) Taxonomy ids that are associated with this workflow and used for filtering -- `update_entity_attributes` (Attributes List) (see [below for nested schema](#nestedatt--update_entity_attributes)) -- `user_ids` (List of Number) This field is deprecated. Please use assignedTo - -### Read-Only - -- `id` (String) The ID of this resource. - - -### Nested Schema for `closing_reasons` - -Optional: - -- `id` (String) Not Null - - - -### Nested Schema for `dynamic_due_date` - -Optional: - -- `action_type_condition` (String) Not Null; must be one of ["WORKFLOW_STARTED", "STEP_CLOSED"] -- `number_of_units` (Number) Not Null -- `step_id` (String) -- `time_period` (String) Not Null; must be one of ["minutes", "hours", "days", "weeks", "months"] - - - -### Nested Schema for `update_entity_attributes` - -Optional: - -- `source` (String) Not Null; must be one of ["workflow_status", "current_section", "current_step"] -- `target` (Attributes) Not Null (see [below for nested schema](#nestedatt--update_entity_attributes--target)) - - -### Nested Schema for `update_entity_attributes.target` - -Optional: - -- `entity_attribute` (String) Not Null -- `entity_schema` (String) Not Null - -## Import - -Import is supported using the following syntax: - -```shell -terraform import epilot-workflow_workflow_definition.my_epilot-workflow_workflow_definition "" -``` diff --git a/examples/data-sources/epilot-workflow_closing_reason/data-source.tf b/examples/data-sources/epilot-workflow_closing_reason/data-source.tf deleted file mode 100644 index 2d40804..0000000 --- a/examples/data-sources/epilot-workflow_closing_reason/data-source.tf +++ /dev/null @@ -1,2 +0,0 @@ -data "epilot-workflow_closing_reason" "my_closingreason" { -} \ No newline at end of file diff --git a/examples/data-sources/epilot-workflow_workflow_definition/data-source.tf b/examples/data-sources/epilot-workflow_workflow_definition/data-source.tf deleted file mode 100644 index 3592e48..0000000 --- a/examples/data-sources/epilot-workflow_workflow_definition/data-source.tf +++ /dev/null @@ -1,2 +0,0 @@ -data "epilot-workflow_workflow_definition" "my_workflowdefinition" { -} \ No newline at end of file diff --git a/examples/provider/provider.tf b/examples/provider/provider.tf index 4407b05..e48bf9c 100644 --- a/examples/provider/provider.tf +++ b/examples/provider/provider.tf @@ -2,7 +2,7 @@ terraform { required_providers { epilot-workflow = { source = "epilot-dev/epilot-workflow" - version = "0.15.2" + version = "0.16.0" } } } diff --git a/examples/resources/epilot-workflow_closing_reason/import.sh b/examples/resources/epilot-workflow_closing_reason/import.sh deleted file mode 100644 index fb38494..0000000 --- a/examples/resources/epilot-workflow_closing_reason/import.sh +++ /dev/null @@ -1 +0,0 @@ -terraform import epilot-workflow_closing_reason.my_epilot-workflow_closing_reason "" diff --git a/examples/resources/epilot-workflow_closing_reason/resource.tf b/examples/resources/epilot-workflow_closing_reason/resource.tf deleted file mode 100644 index 3a46938..0000000 --- a/examples/resources/epilot-workflow_closing_reason/resource.tf +++ /dev/null @@ -1,7 +0,0 @@ -resource "epilot-workflow_closing_reason" "my_closingreason" { - creation_time = "...my_creation_time..." - id = "...my_id..." - last_update_time = "...my_last_update_time..." - status = "INACTIVE" - title = "...my_title..." -} \ No newline at end of file diff --git a/examples/resources/epilot-workflow_workflow_definition/import.sh b/examples/resources/epilot-workflow_workflow_definition/import.sh deleted file mode 100644 index e37820e..0000000 --- a/examples/resources/epilot-workflow_workflow_definition/import.sh +++ /dev/null @@ -1 +0,0 @@ -terraform import epilot-workflow_workflow_definition.my_epilot-workflow_workflow_definition "" diff --git a/examples/resources/epilot-workflow_workflow_definition/resource.tf b/examples/resources/epilot-workflow_workflow_definition/resource.tf deleted file mode 100644 index 09c31a6..0000000 --- a/examples/resources/epilot-workflow_workflow_definition/resource.tf +++ /dev/null @@ -1,40 +0,0 @@ -resource "epilot-workflow_workflow_definition" "my_workflowdefinition" { - assigned_to = [ - "..." - ] - closing_reasons = [ - { - id = "x739cew" - } - ] - creation_time = "2021-04-27T12:01:13.000Z" - description = "...my_description..." - due_date = "2021-04-27T12:00:00.000Z" - dynamic_due_date = { - action_type_condition = "STEP_CLOSED" - number_of_units = 0.36 - step_id = "...my_step_id..." - time_period = "days" - } - enable_ecp_workflow = false - enabled = false - flow = "{ \"see\": \"documentation\" }" - id = "...my_id..." - last_update_time = "2021-04-27T12:01:13.000Z" - name = "...my_name..." - taxonomies = [ - "..." - ] - update_entity_attributes = [ - { - source = "current_step" - target = { - entity_attribute = "my_status" - entity_schema = "opportunity" - } - } - ] - user_ids = [ - 5.93 - ] -} \ No newline at end of file diff --git a/gen.yaml b/gen.yaml index 3f3771f..e61cee4 100644 --- a/gen.yaml +++ b/gen.yaml @@ -9,6 +9,7 @@ generation: requestResponseComponentNamesFeb2024: false auth: oAuth2ClientCredentialsEnabled: false + oAuth2PasswordEnabled: false telemetryEnabled: false go: version: 0.0.1 @@ -27,12 +28,14 @@ go: outputModelSuffix: output packageName: openapi terraform: - version: 0.15.2 + version: 0.16.0 additionalDataSources: [] additionalDependencies: {} additionalResources: [] allowUnknownFieldsInWeakUnions: false author: epilot-dev + defaultErrorName: SDKError + enableTypeDeduplication: true environmentVariables: [] imports: option: openapi diff --git a/go.mod b/go.mod index 4c453d7..9f02fa5 100644 --- a/go.mod +++ b/go.mod @@ -3,12 +3,13 @@ module github.com/epilot-dev/terraform-provider-epilot-workflow go 1.22.0 require ( - github.com/cenkalti/backoff/v4 v4.2.0 github.com/ericlagergren/decimal v0.0.0-20221120152707-495c53812d05 + github.com/hashicorp/go-uuid v1.0.3 github.com/hashicorp/terraform-plugin-docs v0.19.4 github.com/hashicorp/terraform-plugin-framework v1.12.0 github.com/hashicorp/terraform-plugin-framework-validators v0.13.0 github.com/hashicorp/terraform-plugin-go v0.24.0 + github.com/hashicorp/terraform-plugin-log v0.9.0 ) require ( @@ -33,12 +34,10 @@ require ( github.com/hashicorp/go-hclog v1.5.0 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/hashicorp/go-plugin v1.6.1 // indirect - github.com/hashicorp/go-uuid v1.0.3 // indirect github.com/hashicorp/go-version v1.7.0 // indirect github.com/hashicorp/hc-install v0.7.0 // indirect github.com/hashicorp/terraform-exec v0.21.0 // indirect github.com/hashicorp/terraform-json v0.22.1 // indirect - github.com/hashicorp/terraform-plugin-log v0.9.0 // indirect github.com/hashicorp/terraform-registry-address v0.2.3 // indirect github.com/hashicorp/terraform-svchost v0.1.1 // indirect github.com/hashicorp/yamux v0.1.1 // indirect diff --git a/go.sum b/go.sum index f9e8505..762ad5a 100644 --- a/go.sum +++ b/go.sum @@ -24,8 +24,6 @@ github.com/bmatcuk/doublestar/v4 v4.6.1 h1:FH9SifrbvJhnlQpztAx++wlkk70QBf0iBWDwN github.com/bmatcuk/doublestar/v4 v4.6.1/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc= github.com/bufbuild/protocompile v0.4.0 h1:LbFKd2XowZvQ/kajzguUp2DC9UEIQhIq77fZZlaQsNA= github.com/bufbuild/protocompile v0.4.0/go.mod h1:3v93+mbWn/v3xzN+31nwkJfrEpAUwp+BagBSZWx+TP8= -github.com/cenkalti/backoff/v4 v4.2.0 h1:HN5dHm3WBOgndBH6E8V0q2jIYIR3s9yglV8k/+MN3u4= -github.com/cenkalti/backoff/v4 v4.2.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/cloudflare/circl v1.3.7 h1:qlCDlTPz2n9fu58M0Nh1J/JzcFpfgkFHHX3O35r5vcU= github.com/cloudflare/circl v1.3.7/go.mod h1:sRTcRWXGLrKw6yIGJ+l7amYJFfAXbZG0kBSc8r4zxgA= github.com/cyphar/filepath-securejoin v0.2.4 h1:Ugdm7cg7i6ZK6x3xDF1oEu1nfkyfH53EtKeQYTC3kyg= diff --git a/internal/provider/closingreason_data_source.go b/internal/provider/closingreason_data_source.go deleted file mode 100644 index 2848b52..0000000 --- a/internal/provider/closingreason_data_source.go +++ /dev/null @@ -1,140 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package provider - -import ( - "context" - "fmt" - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk" - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/models/operations" - "github.com/hashicorp/terraform-plugin-framework/datasource" - "github.com/hashicorp/terraform-plugin-framework/datasource/schema" - "github.com/hashicorp/terraform-plugin-framework/types" - "github.com/hashicorp/terraform-plugin-framework/types/basetypes" -) - -// Ensure provider defined types fully satisfy framework interfaces. -var _ datasource.DataSource = &ClosingReasonDataSource{} -var _ datasource.DataSourceWithConfigure = &ClosingReasonDataSource{} - -func NewClosingReasonDataSource() datasource.DataSource { - return &ClosingReasonDataSource{} -} - -// ClosingReasonDataSource is the data source implementation. -type ClosingReasonDataSource struct { - client *sdk.SDK -} - -// ClosingReasonDataSourceModel describes the data model. -type ClosingReasonDataSourceModel struct { - CreationTime types.String `tfsdk:"creation_time"` - ID types.String `tfsdk:"id"` - LastUpdateTime types.String `tfsdk:"last_update_time"` - Status types.String `tfsdk:"status"` - Title types.String `tfsdk:"title"` -} - -// Metadata returns the data source type name. -func (r *ClosingReasonDataSource) Metadata(ctx context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { - resp.TypeName = req.ProviderTypeName + "_closing_reason" -} - -// Schema defines the schema for the data source. -func (r *ClosingReasonDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) { - resp.Schema = schema.Schema{ - MarkdownDescription: "ClosingReason DataSource", - - Attributes: map[string]schema.Attribute{ - "creation_time": schema.StringAttribute{ - Computed: true, - }, - "id": schema.StringAttribute{ - Computed: true, - }, - "last_update_time": schema.StringAttribute{ - Computed: true, - }, - "status": schema.StringAttribute{ - Computed: true, - }, - "title": schema.StringAttribute{ - Computed: true, - }, - }, - } -} - -func (r *ClosingReasonDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) { - // Prevent panic if the provider has not been configured. - if req.ProviderData == nil { - return - } - - client, ok := req.ProviderData.(*sdk.SDK) - - if !ok { - resp.Diagnostics.AddError( - "Unexpected DataSource Configure Type", - fmt.Sprintf("Expected *sdk.SDK, got: %T. Please report this issue to the provider developers.", req.ProviderData), - ) - - return - } - - r.client = client -} - -func (r *ClosingReasonDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { - var data *ClosingReasonDataSourceModel - var item types.Object - - resp.Diagnostics.Append(req.Config.Get(ctx, &item)...) - if resp.Diagnostics.HasError() { - return - } - - resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{ - UnhandledNullAsEmpty: true, - UnhandledUnknownAsEmpty: true, - })...) - - if resp.Diagnostics.HasError() { - return - } - - var reasonID string - reasonID = data.ID.ValueString() - - request := operations.GetClosingReasonRequest{ - ReasonID: reasonID, - } - res, err := r.client.ClosingReason.GetClosingReason(ctx, request) - if err != nil { - resp.Diagnostics.AddError("failure to invoke API", err.Error()) - if res != nil && res.RawResponse != nil { - resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) - } - return - } - if res == nil { - resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) - return - } - if res.StatusCode == 404 { - resp.State.RemoveResource(ctx) - return - } - if res.StatusCode != 200 { - resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) - return - } - if !(res.ClosingReason != nil) { - resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) - return - } - data.RefreshFromSharedClosingReason(res.ClosingReason) - - // Save updated data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} diff --git a/internal/provider/closingreason_data_source_sdk.go b/internal/provider/closingreason_data_source_sdk.go deleted file mode 100644 index 500ba02..0000000 --- a/internal/provider/closingreason_data_source_sdk.go +++ /dev/null @@ -1,18 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package provider - -import ( - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/models/shared" - "github.com/hashicorp/terraform-plugin-framework/types" -) - -func (r *ClosingReasonDataSourceModel) RefreshFromSharedClosingReason(resp *shared.ClosingReason) { - if resp != nil { - r.CreationTime = types.StringPointerValue(resp.CreationTime) - r.ID = types.StringPointerValue(resp.ID) - r.LastUpdateTime = types.StringPointerValue(resp.LastUpdateTime) - r.Status = types.StringValue(string(resp.Status)) - r.Title = types.StringValue(resp.Title) - } -} diff --git a/internal/provider/closingreason_resource.go b/internal/provider/closingreason_resource.go deleted file mode 100644 index 5414771..0000000 --- a/internal/provider/closingreason_resource.go +++ /dev/null @@ -1,268 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package provider - -import ( - "context" - "fmt" - speakeasy_stringplanmodifier "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/planmodifiers/stringplanmodifier" - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk" - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/models/operations" - "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" - "github.com/hashicorp/terraform-plugin-framework/path" - "github.com/hashicorp/terraform-plugin-framework/resource" - "github.com/hashicorp/terraform-plugin-framework/resource/schema" - "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" - "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" - "github.com/hashicorp/terraform-plugin-framework/schema/validator" - "github.com/hashicorp/terraform-plugin-framework/types" - "github.com/hashicorp/terraform-plugin-framework/types/basetypes" -) - -// Ensure provider defined types fully satisfy framework interfaces. -var _ resource.Resource = &ClosingReasonResource{} -var _ resource.ResourceWithImportState = &ClosingReasonResource{} - -func NewClosingReasonResource() resource.Resource { - return &ClosingReasonResource{} -} - -// ClosingReasonResource defines the resource implementation. -type ClosingReasonResource struct { - client *sdk.SDK -} - -// ClosingReasonResourceModel describes the resource data model. -type ClosingReasonResourceModel struct { - CreationTime types.String `tfsdk:"creation_time"` - ID types.String `tfsdk:"id"` - LastUpdateTime types.String `tfsdk:"last_update_time"` - Status types.String `tfsdk:"status"` - Title types.String `tfsdk:"title"` -} - -func (r *ClosingReasonResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { - resp.TypeName = req.ProviderTypeName + "_closing_reason" -} - -func (r *ClosingReasonResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { - resp.Schema = schema.Schema{ - MarkdownDescription: "ClosingReason Resource", - Attributes: map[string]schema.Attribute{ - "creation_time": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - stringplanmodifier.RequiresReplaceIfConfigured(), - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `Requires replacement if changed.`, - }, - "id": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - stringplanmodifier.RequiresReplaceIfConfigured(), - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `Requires replacement if changed.`, - }, - "last_update_time": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - stringplanmodifier.RequiresReplaceIfConfigured(), - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `Requires replacement if changed.`, - }, - "status": schema.StringAttribute{ - Required: true, - PlanModifiers: []planmodifier.String{ - stringplanmodifier.RequiresReplaceIfConfigured(), - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `must be one of ["ACTIVE", "INACTIVE"]; Requires replacement if changed.`, - Validators: []validator.String{ - stringvalidator.OneOf( - "ACTIVE", - "INACTIVE", - ), - }, - }, - "title": schema.StringAttribute{ - Required: true, - PlanModifiers: []planmodifier.String{ - stringplanmodifier.RequiresReplaceIfConfigured(), - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `Requires replacement if changed.`, - }, - }, - } -} - -func (r *ClosingReasonResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { - // Prevent panic if the provider has not been configured. - if req.ProviderData == nil { - return - } - - client, ok := req.ProviderData.(*sdk.SDK) - - if !ok { - resp.Diagnostics.AddError( - "Unexpected Resource Configure Type", - fmt.Sprintf("Expected *sdk.SDK, got: %T. Please report this issue to the provider developers.", req.ProviderData), - ) - - return - } - - r.client = client -} - -func (r *ClosingReasonResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { - var data *ClosingReasonResourceModel - var plan types.Object - - resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) - if resp.Diagnostics.HasError() { - return - } - - resp.Diagnostics.Append(plan.As(ctx, &data, basetypes.ObjectAsOptions{ - UnhandledNullAsEmpty: true, - UnhandledUnknownAsEmpty: true, - })...) - - if resp.Diagnostics.HasError() { - return - } - - request := *data.ToSharedClosingReason() - res, err := r.client.ClosingReason.CreateClosingReason(ctx, request) - if err != nil { - resp.Diagnostics.AddError("failure to invoke API", err.Error()) - if res != nil && res.RawResponse != nil { - resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) - } - return - } - if res == nil { - resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) - return - } - if res.StatusCode != 201 { - resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) - return - } - if !(res.ClosingReason != nil) { - resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) - return - } - data.RefreshFromSharedClosingReason(res.ClosingReason) - refreshPlan(ctx, plan, &data, resp.Diagnostics) - - // Save updated data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} - -func (r *ClosingReasonResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { - var data *ClosingReasonResourceModel - var item types.Object - - resp.Diagnostics.Append(req.State.Get(ctx, &item)...) - if resp.Diagnostics.HasError() { - return - } - - resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{ - UnhandledNullAsEmpty: true, - UnhandledUnknownAsEmpty: true, - })...) - - if resp.Diagnostics.HasError() { - return - } - - var reasonID string - reasonID = data.ID.ValueString() - - request := operations.GetClosingReasonRequest{ - ReasonID: reasonID, - } - res, err := r.client.ClosingReason.GetClosingReason(ctx, request) - if err != nil { - resp.Diagnostics.AddError("failure to invoke API", err.Error()) - if res != nil && res.RawResponse != nil { - resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) - } - return - } - if res == nil { - resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) - return - } - if res.StatusCode == 404 { - resp.State.RemoveResource(ctx) - return - } - if res.StatusCode != 200 { - resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) - return - } - if !(res.ClosingReason != nil) { - resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) - return - } - data.RefreshFromSharedClosingReason(res.ClosingReason) - - // Save updated data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} - -func (r *ClosingReasonResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { - var data *ClosingReasonResourceModel - var plan types.Object - - resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) - if resp.Diagnostics.HasError() { - return - } - - merge(ctx, req, resp, &data) - if resp.Diagnostics.HasError() { - return - } - - // Not Implemented; all attributes marked as RequiresReplace - - // Save updated data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} - -func (r *ClosingReasonResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { - var data *ClosingReasonResourceModel - var item types.Object - - resp.Diagnostics.Append(req.State.Get(ctx, &item)...) - if resp.Diagnostics.HasError() { - return - } - - resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{ - UnhandledNullAsEmpty: true, - UnhandledUnknownAsEmpty: true, - })...) - - if resp.Diagnostics.HasError() { - return - } - - // Not Implemented; entity does not have a configured DELETE operation -} - -func (r *ClosingReasonResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { - resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), req.ID)...) -} diff --git a/internal/provider/closingreason_resource_sdk.go b/internal/provider/closingreason_resource_sdk.go deleted file mode 100644 index 7695555..0000000 --- a/internal/provider/closingreason_resource_sdk.go +++ /dev/null @@ -1,51 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package provider - -import ( - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/models/shared" - "github.com/hashicorp/terraform-plugin-framework/types" -) - -func (r *ClosingReasonResourceModel) ToSharedClosingReason() *shared.ClosingReason { - creationTime := new(string) - if !r.CreationTime.IsUnknown() && !r.CreationTime.IsNull() { - *creationTime = r.CreationTime.ValueString() - } else { - creationTime = nil - } - id := new(string) - if !r.ID.IsUnknown() && !r.ID.IsNull() { - *id = r.ID.ValueString() - } else { - id = nil - } - lastUpdateTime := new(string) - if !r.LastUpdateTime.IsUnknown() && !r.LastUpdateTime.IsNull() { - *lastUpdateTime = r.LastUpdateTime.ValueString() - } else { - lastUpdateTime = nil - } - status := shared.ClosingReasonsStatus(r.Status.ValueString()) - var title string - title = r.Title.ValueString() - - out := shared.ClosingReason{ - CreationTime: creationTime, - ID: id, - LastUpdateTime: lastUpdateTime, - Status: status, - Title: title, - } - return &out -} - -func (r *ClosingReasonResourceModel) RefreshFromSharedClosingReason(resp *shared.ClosingReason) { - if resp != nil { - r.CreationTime = types.StringPointerValue(resp.CreationTime) - r.ID = types.StringPointerValue(resp.ID) - r.LastUpdateTime = types.StringPointerValue(resp.LastUpdateTime) - r.Status = types.StringValue(string(resp.Status)) - r.Title = types.StringValue(resp.Title) - } -} diff --git a/internal/provider/provider.go b/internal/provider/provider.go index b968962..87264ee 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -76,10 +76,13 @@ func (p *EpilotWorkflowProvider) Configure(ctx context.Context, req provider.Con BearerAuth: bearerAuth, } + httpClient := http.DefaultClient + httpClient.Transport = NewLoggingHTTPTransport(http.DefaultTransport) + opts := []sdk.SDKOption{ sdk.WithServerURL(ServerURL), sdk.WithSecurity(security), - sdk.WithClient(http.DefaultClient), + sdk.WithClient(httpClient), } client := sdk.New(opts...) @@ -88,17 +91,11 @@ func (p *EpilotWorkflowProvider) Configure(ctx context.Context, req provider.Con } func (p *EpilotWorkflowProvider) Resources(ctx context.Context) []func() resource.Resource { - return []func() resource.Resource{ - NewClosingReasonResource, - NewWorkflowDefinitionResource, - } + return []func() resource.Resource{} } func (p *EpilotWorkflowProvider) DataSources(ctx context.Context) []func() datasource.DataSource { - return []func() datasource.DataSource{ - NewClosingReasonDataSource, - NewWorkflowDefinitionDataSource, - } + return []func() datasource.DataSource{} } func New(version string) func() provider.Provider { diff --git a/internal/provider/reflect/helpers.go b/internal/provider/reflect/helpers.go index b17719d..8085789 100644 --- a/internal/provider/reflect/helpers.go +++ b/internal/provider/reflect/helpers.go @@ -46,7 +46,7 @@ func commaSeparatedString(in []string) string { // getStructTags returns a map of Terraform field names to their position in // the tags of the struct `in`. `in` must be a struct. -func getStructTags(_ context.Context, in reflect.Value, path path.Path, opts Options) (map[string]int, error) { +func getStructTags(_ context.Context, in reflect.Value, path path.Path, _ Options) (map[string]int, error) { tags := map[string]int{} typ := trueReflectValue(in).Type() if typ.Kind() != reflect.Struct { diff --git a/internal/provider/types/closing_reason_id.go b/internal/provider/types/closing_reason_id.go deleted file mode 100644 index 7206d40..0000000 --- a/internal/provider/types/closing_reason_id.go +++ /dev/null @@ -1,9 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package types - -import "github.com/hashicorp/terraform-plugin-framework/types" - -type ClosingReasonID struct { - ID types.String `tfsdk:"id"` -} diff --git a/internal/provider/types/dynamic_due_date.go b/internal/provider/types/dynamic_due_date.go deleted file mode 100644 index 3527805..0000000 --- a/internal/provider/types/dynamic_due_date.go +++ /dev/null @@ -1,12 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package types - -import "github.com/hashicorp/terraform-plugin-framework/types" - -type DynamicDueDate struct { - ActionTypeCondition types.String `tfsdk:"action_type_condition"` - NumberOfUnits types.Number `tfsdk:"number_of_units"` - StepID types.String `tfsdk:"step_id"` - TimePeriod types.String `tfsdk:"time_period"` -} diff --git a/internal/provider/types/target.go b/internal/provider/types/target.go deleted file mode 100644 index 37b5b1d..0000000 --- a/internal/provider/types/target.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package types - -import "github.com/hashicorp/terraform-plugin-framework/types" - -type Target struct { - EntityAttribute types.String `tfsdk:"entity_attribute"` - EntitySchema types.String `tfsdk:"entity_schema"` -} diff --git a/internal/provider/types/update_entity_attributes.go b/internal/provider/types/update_entity_attributes.go deleted file mode 100644 index ce1cd99..0000000 --- a/internal/provider/types/update_entity_attributes.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package types - -import "github.com/hashicorp/terraform-plugin-framework/types" - -type UpdateEntityAttributes struct { - Source types.String `tfsdk:"source"` - Target Target `tfsdk:"target"` -} diff --git a/internal/provider/utils.go b/internal/provider/utils.go index e827fab..82cc449 100644 --- a/internal/provider/utils.go +++ b/internal/provider/utils.go @@ -3,17 +3,25 @@ package provider import ( + "bufio" + "bytes" "context" "encoding/json" + "errors" "fmt" tfReflect "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/provider/reflect" + "github.com/hashicorp/go-uuid" "github.com/hashicorp/terraform-plugin-framework/diag" "github.com/hashicorp/terraform-plugin-framework/path" "github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" + "io" "net/http" "net/http/httputil" + "net/textproto" "reflect" + "strings" ) func debugResponse(response *http.Response) string { @@ -91,3 +99,177 @@ func refreshPlan(ctx context.Context, plan types.Object, target interface{}, dia SourceType: tfReflect.SourceTypePlan, }, path.Empty())...) } + +// Note: this is taken as a more minimal/specific version of https://github.com/hashicorp/terraform-plugin-sdk/blob/main/helper/logging/logging_http_transport.go +func NewLoggingHTTPTransport(t http.RoundTripper) *loggingHttpTransport { + return &loggingHttpTransport{t} +} + +const ( + FieldHttpOperationType = "tf_http_op_type" + OperationHttpRequest = "request" + OperationHttpResponse = "response" + FieldHttpRequestMethod = "tf_http_req_method" + FieldHttpRequestUri = "tf_http_req_uri" + FieldHttpRequestProtoVersion = "tf_http_req_version" + FieldHttpRequestBody = "tf_http_req_body" + FieldHttpResponseProtoVersion = "tf_http_res_version" + FieldHttpResponseStatusCode = "tf_http_res_status_code" + FieldHttpResponseStatusReason = "tf_http_res_status_reason" + FieldHttpResponseBody = "tf_http_res_body" + FieldHttpTransactionId = "tf_http_trans_id" +) + +type loggingHttpTransport struct { + transport http.RoundTripper +} + +func (t *loggingHttpTransport) RoundTrip(req *http.Request) (*http.Response, error) { + ctx := req.Context() + ctx = t.addTransactionIdField(ctx) + + // Decompose the request bytes in a message (HTTP body) and fields (HTTP headers), then log it + fields, err := decomposeRequestForLogging(req) + if err != nil { + tflog.Error(ctx, "Failed to parse request bytes for logging", []map[string]interface{}{map[string]interface{}{ + "error": err, + }}...) + } else { + tflog.Debug(ctx, "Sending HTTP Request", []map[string]interface{}{fields}...) + } + + // Invoke the wrapped RoundTrip now + res, err := t.transport.RoundTrip(req) + if err != nil { + return res, err + } + + // Decompose the response bytes in a message (HTTP body) and fields (HTTP headers), then log it + fields, err = decomposeResponseForLogging(res) + if err != nil { + tflog.Error(ctx, "Failed to parse response bytes for logging", []map[string]interface{}{map[string]interface{}{ + "error": err, + }}...) + } else { + tflog.Debug(ctx, "Received HTTP Response", []map[string]interface{}{fields}...) + } + + return res, nil +} + +func (t *loggingHttpTransport) addTransactionIdField(ctx context.Context) context.Context { + tId, err := uuid.GenerateUUID() + + if err != nil { + tId = "Unable to assign Transaction ID: " + err.Error() + } + + return tflog.SetField(ctx, FieldHttpTransactionId, tId) +} + +func decomposeRequestForLogging(req *http.Request) (map[string]interface{}, error) { + fields := make(map[string]interface{}, len(req.Header)+4) + fields[FieldHttpOperationType] = OperationHttpRequest + + fields[FieldHttpRequestMethod] = req.Method + fields[FieldHttpRequestUri] = req.URL.RequestURI() + fields[FieldHttpRequestProtoVersion] = req.Proto + + // Get the full body of the request, including headers appended by http.Transport: + // this is necessary because the http.Request at this stage doesn't contain + // all the headers that will be eventually sent. + // We rely on `httputil.DumpRequestOut` to obtain the actual bytes that will be sent out. + reqBytes, err := httputil.DumpRequestOut(req, true) + if err != nil { + return nil, err + } + + // Create a reader around the request full body + reqReader := textproto.NewReader(bufio.NewReader(bytes.NewReader(reqBytes))) + + err = fieldHeadersFromRequestReader(reqReader, fields) + if err != nil { + return nil, err + } + + // Read the rest of the body content + fields[FieldHttpRequestBody] = bodyFromRestOfRequestReader(reqReader) + return fields, nil +} + +func fieldHeadersFromRequestReader(reader *textproto.Reader, fields map[string]interface{}) error { + // Ignore the first line: it contains non-header content + // that we have already captured. + // Skipping this step, would cause the following call to `ReadMIMEHeader()` + // to fail as it cannot parse the first line. + _, err := reader.ReadLine() + if err != nil { + return err + } + + // Read the MIME-style headers + mimeHeader, err := reader.ReadMIMEHeader() + if err != nil { + return err + } + + // Set the headers as fields to log + for k, v := range mimeHeader { + if len(v) == 1 { + fields[k] = v[0] + } else { + fields[k] = v + } + } + if _, ok := fields["Authorization"]; ok { + fields["Authorization"] = "(sensitive)" + } + + return nil +} + +func bodyFromRestOfRequestReader(reader *textproto.Reader) string { + var builder strings.Builder + for { + line, err := reader.ReadContinuedLine() + if errors.Is(err, io.EOF) { + break + } + builder.WriteString(line) + } + + return builder.String() +} + +func decomposeResponseForLogging(res *http.Response) (map[string]interface{}, error) { + fields := make(map[string]interface{}, len(res.Header)+4) + fields[FieldHttpOperationType] = OperationHttpResponse + + fields[FieldHttpResponseProtoVersion] = res.Proto + fields[FieldHttpResponseStatusCode] = res.StatusCode + fields[FieldHttpResponseStatusReason] = res.Status + + // Set the headers as fields to log + for k, v := range res.Header { + if len(v) == 1 { + fields[k] = v[0] + } else { + fields[k] = v + } + } + + // Read the whole response body + resBody, err := io.ReadAll(res.Body) + if err != nil { + return nil, err + } + + // Wrap the bytes from the response body, back into an io.ReadCloser, + // to respect the interface of http.Response, as expected by users of the + // http.Client + res.Body = io.NopCloser(bytes.NewBuffer(resBody)) + + fields[FieldHttpResponseBody] = string(resBody) + + return fields, nil +} diff --git a/internal/provider/workflowdefinition_data_source.go b/internal/provider/workflowdefinition_data_source.go deleted file mode 100644 index 6ac8b05..0000000 --- a/internal/provider/workflowdefinition_data_source.go +++ /dev/null @@ -1,231 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package provider - -import ( - "context" - "fmt" - tfTypes "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/provider/types" - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk" - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/models/operations" - "github.com/hashicorp/terraform-plugin-framework/datasource" - "github.com/hashicorp/terraform-plugin-framework/datasource/schema" - "github.com/hashicorp/terraform-plugin-framework/types" - "github.com/hashicorp/terraform-plugin-framework/types/basetypes" -) - -// Ensure provider defined types fully satisfy framework interfaces. -var _ datasource.DataSource = &WorkflowDefinitionDataSource{} -var _ datasource.DataSourceWithConfigure = &WorkflowDefinitionDataSource{} - -func NewWorkflowDefinitionDataSource() datasource.DataSource { - return &WorkflowDefinitionDataSource{} -} - -// WorkflowDefinitionDataSource is the data source implementation. -type WorkflowDefinitionDataSource struct { - client *sdk.SDK -} - -// WorkflowDefinitionDataSourceModel describes the data model. -type WorkflowDefinitionDataSourceModel struct { - AssignedTo []types.String `tfsdk:"assigned_to"` - ClosingReasons []tfTypes.ClosingReasonID `tfsdk:"closing_reasons"` - CreationTime types.String `tfsdk:"creation_time"` - Description types.String `tfsdk:"description"` - DueDate types.String `tfsdk:"due_date"` - DynamicDueDate *tfTypes.DynamicDueDate `tfsdk:"dynamic_due_date"` - EnableECPWorkflow types.Bool `tfsdk:"enable_ecp_workflow"` - Enabled types.Bool `tfsdk:"enabled"` - Flow types.String `tfsdk:"flow"` - ID types.String `tfsdk:"id"` - LastUpdateTime types.String `tfsdk:"last_update_time"` - Name types.String `tfsdk:"name"` - Taxonomies []types.String `tfsdk:"taxonomies"` - UpdateEntityAttributes []tfTypes.UpdateEntityAttributes `tfsdk:"update_entity_attributes"` - UserIds []types.Number `tfsdk:"user_ids"` -} - -// Metadata returns the data source type name. -func (r *WorkflowDefinitionDataSource) Metadata(ctx context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { - resp.TypeName = req.ProviderTypeName + "_workflow_definition" -} - -// Schema defines the schema for the data source. -func (r *WorkflowDefinitionDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) { - resp.Schema = schema.Schema{ - MarkdownDescription: "WorkflowDefinition DataSource", - - Attributes: map[string]schema.Attribute{ - "assigned_to": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - }, - "closing_reasons": schema.ListNestedAttribute{ - Computed: true, - NestedObject: schema.NestedAttributeObject{ - Attributes: map[string]schema.Attribute{ - "id": schema.StringAttribute{ - Computed: true, - }, - }, - }, - }, - "creation_time": schema.StringAttribute{ - Computed: true, - Description: `ISO String Date & Time`, - }, - "description": schema.StringAttribute{ - Computed: true, - }, - "due_date": schema.StringAttribute{ - Computed: true, - }, - "dynamic_due_date": schema.SingleNestedAttribute{ - Computed: true, - Attributes: map[string]schema.Attribute{ - "action_type_condition": schema.StringAttribute{ - Computed: true, - }, - "number_of_units": schema.NumberAttribute{ - Computed: true, - }, - "step_id": schema.StringAttribute{ - Computed: true, - }, - "time_period": schema.StringAttribute{ - Computed: true, - }, - }, - Description: `set a Duedate for a step then a specific`, - }, - "enable_ecp_workflow": schema.BoolAttribute{ - Computed: true, - Description: `Indicates whether this workflow is available for End Customer Portal or not. By default it's not.`, - }, - "enabled": schema.BoolAttribute{ - Computed: true, - Description: `Whether the workflow is enabled or not`, - }, - "flow": schema.StringAttribute{ - Computed: true, - Description: `Parsed as JSON.`, - }, - "id": schema.StringAttribute{ - Computed: true, - }, - "last_update_time": schema.StringAttribute{ - Computed: true, - Description: `ISO String Date & Time`, - }, - "name": schema.StringAttribute{ - Computed: true, - }, - "taxonomies": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - Description: `Taxonomy ids that are associated with this workflow and used for filtering`, - }, - "update_entity_attributes": schema.ListNestedAttribute{ - Computed: true, - NestedObject: schema.NestedAttributeObject{ - Attributes: map[string]schema.Attribute{ - "source": schema.StringAttribute{ - Computed: true, - }, - "target": schema.SingleNestedAttribute{ - Computed: true, - Attributes: map[string]schema.Attribute{ - "entity_attribute": schema.StringAttribute{ - Computed: true, - }, - "entity_schema": schema.StringAttribute{ - Computed: true, - }, - }, - }, - }, - }, - }, - "user_ids": schema.ListAttribute{ - Computed: true, - ElementType: types.NumberType, - Description: `This field is deprecated. Please use assignedTo`, - }, - }, - } -} - -func (r *WorkflowDefinitionDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) { - // Prevent panic if the provider has not been configured. - if req.ProviderData == nil { - return - } - - client, ok := req.ProviderData.(*sdk.SDK) - - if !ok { - resp.Diagnostics.AddError( - "Unexpected DataSource Configure Type", - fmt.Sprintf("Expected *sdk.SDK, got: %T. Please report this issue to the provider developers.", req.ProviderData), - ) - - return - } - - r.client = client -} - -func (r *WorkflowDefinitionDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { - var data *WorkflowDefinitionDataSourceModel - var item types.Object - - resp.Diagnostics.Append(req.Config.Get(ctx, &item)...) - if resp.Diagnostics.HasError() { - return - } - - resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{ - UnhandledNullAsEmpty: true, - UnhandledUnknownAsEmpty: true, - })...) - - if resp.Diagnostics.HasError() { - return - } - - var definitionID string - definitionID = data.ID.ValueString() - - request := operations.GetDefinitionRequest{ - DefinitionID: definitionID, - } - res, err := r.client.Workflows.GetDefinition(ctx, request) - if err != nil { - resp.Diagnostics.AddError("failure to invoke API", err.Error()) - if res != nil && res.RawResponse != nil { - resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) - } - return - } - if res == nil { - resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) - return - } - if res.StatusCode == 404 { - resp.State.RemoveResource(ctx) - return - } - if res.StatusCode != 200 { - resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) - return - } - if !(res.WorkflowDefinition != nil) { - resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) - return - } - data.RefreshFromSharedWorkflowDefinition(res.WorkflowDefinition) - - // Save updated data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} diff --git a/internal/provider/workflowdefinition_data_source_sdk.go b/internal/provider/workflowdefinition_data_source_sdk.go deleted file mode 100644 index f709c47..0000000 --- a/internal/provider/workflowdefinition_data_source_sdk.go +++ /dev/null @@ -1,76 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package provider - -import ( - "encoding/json" - tfTypes "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/provider/types" - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/models/shared" - "github.com/hashicorp/terraform-plugin-framework/types" - "math/big" -) - -func (r *WorkflowDefinitionDataSourceModel) RefreshFromSharedWorkflowDefinition(resp *shared.WorkflowDefinition) { - if resp != nil { - r.AssignedTo = []types.String{} - for _, v := range resp.AssignedTo { - r.AssignedTo = append(r.AssignedTo, types.StringValue(v)) - } - r.ClosingReasons = []tfTypes.ClosingReasonID{} - if len(r.ClosingReasons) > len(resp.ClosingReasons) { - r.ClosingReasons = r.ClosingReasons[:len(resp.ClosingReasons)] - } - for closingReasonsCount, closingReasonsItem := range resp.ClosingReasons { - var closingReasons1 tfTypes.ClosingReasonID - closingReasons1.ID = types.StringValue(closingReasonsItem.ID) - if closingReasonsCount+1 > len(r.ClosingReasons) { - r.ClosingReasons = append(r.ClosingReasons, closingReasons1) - } else { - r.ClosingReasons[closingReasonsCount].ID = closingReasons1.ID - } - } - r.CreationTime = types.StringPointerValue(resp.CreationTime) - r.Description = types.StringPointerValue(resp.Description) - r.DueDate = types.StringPointerValue(resp.DueDate) - if resp.DynamicDueDate == nil { - r.DynamicDueDate = nil - } else { - r.DynamicDueDate = &tfTypes.DynamicDueDate{} - r.DynamicDueDate.ActionTypeCondition = types.StringValue(string(resp.DynamicDueDate.ActionTypeCondition)) - r.DynamicDueDate.NumberOfUnits = types.NumberValue(big.NewFloat(float64(resp.DynamicDueDate.NumberOfUnits))) - r.DynamicDueDate.StepID = types.StringPointerValue(resp.DynamicDueDate.StepID) - r.DynamicDueDate.TimePeriod = types.StringValue(string(resp.DynamicDueDate.TimePeriod)) - } - r.Enabled = types.BoolPointerValue(resp.Enabled) - r.EnableECPWorkflow = types.BoolPointerValue(resp.EnableECPWorkflow) - flowResult, _ := json.Marshal(resp.Flow) - r.Flow = types.StringValue(string(flowResult)) - r.ID = types.StringPointerValue(resp.ID) - r.LastUpdateTime = types.StringPointerValue(resp.LastUpdateTime) - r.Name = types.StringValue(resp.Name) - r.Taxonomies = []types.String{} - for _, v := range resp.Taxonomies { - r.Taxonomies = append(r.Taxonomies, types.StringValue(v)) - } - r.UpdateEntityAttributes = []tfTypes.UpdateEntityAttributes{} - if len(r.UpdateEntityAttributes) > len(resp.UpdateEntityAttributes) { - r.UpdateEntityAttributes = r.UpdateEntityAttributes[:len(resp.UpdateEntityAttributes)] - } - for updateEntityAttributesCount, updateEntityAttributesItem := range resp.UpdateEntityAttributes { - var updateEntityAttributes1 tfTypes.UpdateEntityAttributes - updateEntityAttributes1.Source = types.StringValue(string(updateEntityAttributesItem.Source)) - updateEntityAttributes1.Target.EntityAttribute = types.StringValue(updateEntityAttributesItem.Target.EntityAttribute) - updateEntityAttributes1.Target.EntitySchema = types.StringValue(updateEntityAttributesItem.Target.EntitySchema) - if updateEntityAttributesCount+1 > len(r.UpdateEntityAttributes) { - r.UpdateEntityAttributes = append(r.UpdateEntityAttributes, updateEntityAttributes1) - } else { - r.UpdateEntityAttributes[updateEntityAttributesCount].Source = updateEntityAttributes1.Source - r.UpdateEntityAttributes[updateEntityAttributesCount].Target = updateEntityAttributes1.Target - } - } - r.UserIds = []types.Number{} - for _, v := range resp.UserIds { - r.UserIds = append(r.UserIds, types.NumberValue(big.NewFloat(float64(v)))) - } - } -} diff --git a/internal/provider/workflowdefinition_resource.go b/internal/provider/workflowdefinition_resource.go deleted file mode 100644 index c4748a9..0000000 --- a/internal/provider/workflowdefinition_resource.go +++ /dev/null @@ -1,458 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package provider - -import ( - "context" - "fmt" - tfTypes "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/provider/types" - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk" - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/models/operations" - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/validators" - speakeasy_numbervalidators "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/validators/numbervalidators" - speakeasy_objectvalidators "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/validators/objectvalidators" - speakeasy_stringvalidators "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/validators/stringvalidators" - "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" - "github.com/hashicorp/terraform-plugin-framework/path" - "github.com/hashicorp/terraform-plugin-framework/resource" - "github.com/hashicorp/terraform-plugin-framework/resource/schema" - "github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault" - "github.com/hashicorp/terraform-plugin-framework/schema/validator" - "github.com/hashicorp/terraform-plugin-framework/types" - "github.com/hashicorp/terraform-plugin-framework/types/basetypes" -) - -// Ensure provider defined types fully satisfy framework interfaces. -var _ resource.Resource = &WorkflowDefinitionResource{} -var _ resource.ResourceWithImportState = &WorkflowDefinitionResource{} - -func NewWorkflowDefinitionResource() resource.Resource { - return &WorkflowDefinitionResource{} -} - -// WorkflowDefinitionResource defines the resource implementation. -type WorkflowDefinitionResource struct { - client *sdk.SDK -} - -// WorkflowDefinitionResourceModel describes the resource data model. -type WorkflowDefinitionResourceModel struct { - AssignedTo []types.String `tfsdk:"assigned_to"` - ClosingReasons []tfTypes.ClosingReasonID `tfsdk:"closing_reasons"` - CreationTime types.String `tfsdk:"creation_time"` - Description types.String `tfsdk:"description"` - DueDate types.String `tfsdk:"due_date"` - DynamicDueDate *tfTypes.DynamicDueDate `tfsdk:"dynamic_due_date"` - EnableECPWorkflow types.Bool `tfsdk:"enable_ecp_workflow"` - Enabled types.Bool `tfsdk:"enabled"` - Flow types.String `tfsdk:"flow"` - ID types.String `tfsdk:"id"` - LastUpdateTime types.String `tfsdk:"last_update_time"` - Name types.String `tfsdk:"name"` - Taxonomies []types.String `tfsdk:"taxonomies"` - UpdateEntityAttributes []tfTypes.UpdateEntityAttributes `tfsdk:"update_entity_attributes"` - UserIds []types.Number `tfsdk:"user_ids"` -} - -func (r *WorkflowDefinitionResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { - resp.TypeName = req.ProviderTypeName + "_workflow_definition" -} - -func (r *WorkflowDefinitionResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { - resp.Schema = schema.Schema{ - MarkdownDescription: "WorkflowDefinition Resource", - Attributes: map[string]schema.Attribute{ - "assigned_to": schema.ListAttribute{ - Computed: true, - Optional: true, - ElementType: types.StringType, - }, - "closing_reasons": schema.ListNestedAttribute{ - Computed: true, - Optional: true, - NestedObject: schema.NestedAttributeObject{ - Validators: []validator.Object{ - speakeasy_objectvalidators.NotNull(), - }, - Attributes: map[string]schema.Attribute{ - "id": schema.StringAttribute{ - Computed: true, - Optional: true, - Description: `Not Null`, - Validators: []validator.String{ - speakeasy_stringvalidators.NotNull(), - }, - }, - }, - }, - }, - "creation_time": schema.StringAttribute{ - Computed: true, - Optional: true, - Description: `ISO String Date & Time`, - }, - "description": schema.StringAttribute{ - Computed: true, - Optional: true, - }, - "due_date": schema.StringAttribute{ - Computed: true, - Optional: true, - }, - "dynamic_due_date": schema.SingleNestedAttribute{ - Computed: true, - Optional: true, - Attributes: map[string]schema.Attribute{ - "action_type_condition": schema.StringAttribute{ - Computed: true, - Optional: true, - Description: `Not Null; must be one of ["WORKFLOW_STARTED", "STEP_CLOSED"]`, - Validators: []validator.String{ - speakeasy_stringvalidators.NotNull(), - stringvalidator.OneOf( - "WORKFLOW_STARTED", - "STEP_CLOSED", - ), - }, - }, - "number_of_units": schema.NumberAttribute{ - Computed: true, - Optional: true, - Description: `Not Null`, - Validators: []validator.Number{ - speakeasy_numbervalidators.NotNull(), - }, - }, - "step_id": schema.StringAttribute{ - Computed: true, - Optional: true, - }, - "time_period": schema.StringAttribute{ - Computed: true, - Optional: true, - Description: `Not Null; must be one of ["minutes", "hours", "days", "weeks", "months"]`, - Validators: []validator.String{ - speakeasy_stringvalidators.NotNull(), - stringvalidator.OneOf( - "minutes", - "hours", - "days", - "weeks", - "months", - ), - }, - }, - }, - Description: `set a Duedate for a step then a specific`, - }, - "enable_ecp_workflow": schema.BoolAttribute{ - Computed: true, - Optional: true, - Description: `Indicates whether this workflow is available for End Customer Portal or not. By default it's not.`, - }, - "enabled": schema.BoolAttribute{ - Computed: true, - Optional: true, - Default: booldefault.StaticBool(true), - Description: `Whether the workflow is enabled or not. Default: true`, - }, - "flow": schema.StringAttribute{ - Required: true, - Description: `Parsed as JSON.`, - Validators: []validator.String{ - validators.IsValidJSON(), - }, - }, - "id": schema.StringAttribute{ - Computed: true, - Optional: true, - }, - "last_update_time": schema.StringAttribute{ - Computed: true, - Optional: true, - Description: `ISO String Date & Time`, - }, - "name": schema.StringAttribute{ - Required: true, - }, - "taxonomies": schema.ListAttribute{ - Computed: true, - Optional: true, - ElementType: types.StringType, - Description: `Taxonomy ids that are associated with this workflow and used for filtering`, - }, - "update_entity_attributes": schema.ListNestedAttribute{ - Computed: true, - Optional: true, - NestedObject: schema.NestedAttributeObject{ - Validators: []validator.Object{ - speakeasy_objectvalidators.NotNull(), - }, - Attributes: map[string]schema.Attribute{ - "source": schema.StringAttribute{ - Computed: true, - Optional: true, - Description: `Not Null; must be one of ["workflow_status", "current_section", "current_step"]`, - Validators: []validator.String{ - speakeasy_stringvalidators.NotNull(), - stringvalidator.OneOf( - "workflow_status", - "current_section", - "current_step", - ), - }, - }, - "target": schema.SingleNestedAttribute{ - Computed: true, - Optional: true, - Attributes: map[string]schema.Attribute{ - "entity_attribute": schema.StringAttribute{ - Computed: true, - Optional: true, - Description: `Not Null`, - Validators: []validator.String{ - speakeasy_stringvalidators.NotNull(), - }, - }, - "entity_schema": schema.StringAttribute{ - Computed: true, - Optional: true, - Description: `Not Null`, - Validators: []validator.String{ - speakeasy_stringvalidators.NotNull(), - }, - }, - }, - Description: `Not Null`, - Validators: []validator.Object{ - speakeasy_objectvalidators.NotNull(), - }, - }, - }, - }, - }, - "user_ids": schema.ListAttribute{ - Computed: true, - Optional: true, - ElementType: types.NumberType, - Description: `This field is deprecated. Please use assignedTo`, - }, - }, - } -} - -func (r *WorkflowDefinitionResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { - // Prevent panic if the provider has not been configured. - if req.ProviderData == nil { - return - } - - client, ok := req.ProviderData.(*sdk.SDK) - - if !ok { - resp.Diagnostics.AddError( - "Unexpected Resource Configure Type", - fmt.Sprintf("Expected *sdk.SDK, got: %T. Please report this issue to the provider developers.", req.ProviderData), - ) - - return - } - - r.client = client -} - -func (r *WorkflowDefinitionResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { - var data *WorkflowDefinitionResourceModel - var plan types.Object - - resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) - if resp.Diagnostics.HasError() { - return - } - - resp.Diagnostics.Append(plan.As(ctx, &data, basetypes.ObjectAsOptions{ - UnhandledNullAsEmpty: true, - UnhandledUnknownAsEmpty: true, - })...) - - if resp.Diagnostics.HasError() { - return - } - - request := *data.ToSharedWorkflowDefinition() - res, err := r.client.Workflows.CreateDefinition(ctx, request) - if err != nil { - resp.Diagnostics.AddError("failure to invoke API", err.Error()) - if res != nil && res.RawResponse != nil { - resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) - } - return - } - if res == nil { - resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) - return - } - if res.StatusCode != 201 { - resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) - return - } - if !(res.WorkflowDefinition != nil) { - resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) - return - } - data.RefreshFromSharedWorkflowDefinition(res.WorkflowDefinition) - refreshPlan(ctx, plan, &data, resp.Diagnostics) - - // Save updated data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} - -func (r *WorkflowDefinitionResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { - var data *WorkflowDefinitionResourceModel - var item types.Object - - resp.Diagnostics.Append(req.State.Get(ctx, &item)...) - if resp.Diagnostics.HasError() { - return - } - - resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{ - UnhandledNullAsEmpty: true, - UnhandledUnknownAsEmpty: true, - })...) - - if resp.Diagnostics.HasError() { - return - } - - var definitionID string - definitionID = data.ID.ValueString() - - request := operations.GetDefinitionRequest{ - DefinitionID: definitionID, - } - res, err := r.client.Workflows.GetDefinition(ctx, request) - if err != nil { - resp.Diagnostics.AddError("failure to invoke API", err.Error()) - if res != nil && res.RawResponse != nil { - resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) - } - return - } - if res == nil { - resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) - return - } - if res.StatusCode == 404 { - resp.State.RemoveResource(ctx) - return - } - if res.StatusCode != 200 { - resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) - return - } - if !(res.WorkflowDefinition != nil) { - resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) - return - } - data.RefreshFromSharedWorkflowDefinition(res.WorkflowDefinition) - - // Save updated data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} - -func (r *WorkflowDefinitionResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { - var data *WorkflowDefinitionResourceModel - var plan types.Object - - resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) - if resp.Diagnostics.HasError() { - return - } - - merge(ctx, req, resp, &data) - if resp.Diagnostics.HasError() { - return - } - - workflowDefinition := *data.ToSharedWorkflowDefinition() - var definitionID string - definitionID = data.ID.ValueString() - - request := operations.UpdateDefinitionRequest{ - WorkflowDefinition: workflowDefinition, - DefinitionID: definitionID, - } - res, err := r.client.Workflows.UpdateDefinition(ctx, request) - if err != nil { - resp.Diagnostics.AddError("failure to invoke API", err.Error()) - if res != nil && res.RawResponse != nil { - resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) - } - return - } - if res == nil { - resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) - return - } - if res.StatusCode != 200 { - resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) - return - } - if !(res.WorkflowDefinition != nil) { - resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) - return - } - data.RefreshFromSharedWorkflowDefinition(res.WorkflowDefinition) - refreshPlan(ctx, plan, &data, resp.Diagnostics) - - // Save updated data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} - -func (r *WorkflowDefinitionResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { - var data *WorkflowDefinitionResourceModel - var item types.Object - - resp.Diagnostics.Append(req.State.Get(ctx, &item)...) - if resp.Diagnostics.HasError() { - return - } - - resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{ - UnhandledNullAsEmpty: true, - UnhandledUnknownAsEmpty: true, - })...) - - if resp.Diagnostics.HasError() { - return - } - - var definitionID string - definitionID = data.ID.ValueString() - - request := operations.DeleteDefinitionRequest{ - DefinitionID: definitionID, - } - res, err := r.client.Workflows.DeleteDefinition(ctx, request) - if err != nil { - resp.Diagnostics.AddError("failure to invoke API", err.Error()) - if res != nil && res.RawResponse != nil { - resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) - } - return - } - if res == nil { - resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) - return - } - if res.StatusCode != 204 { - resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) - return - } - -} - -func (r *WorkflowDefinitionResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { - resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), req.ID)...) -} diff --git a/internal/provider/workflowdefinition_resource_sdk.go b/internal/provider/workflowdefinition_resource_sdk.go deleted file mode 100644 index 319f632..0000000 --- a/internal/provider/workflowdefinition_resource_sdk.go +++ /dev/null @@ -1,204 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package provider - -import ( - "encoding/json" - tfTypes "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/provider/types" - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/models/shared" - "github.com/hashicorp/terraform-plugin-framework/types" - "math/big" -) - -func (r *WorkflowDefinitionResourceModel) ToSharedWorkflowDefinition() *shared.WorkflowDefinition { - var assignedTo []string = []string{} - for _, assignedToItem := range r.AssignedTo { - assignedTo = append(assignedTo, assignedToItem.ValueString()) - } - var closingReasons []shared.ClosingReasonID = []shared.ClosingReasonID{} - for _, closingReasonsItem := range r.ClosingReasons { - var id string - id = closingReasonsItem.ID.ValueString() - - closingReasons = append(closingReasons, shared.ClosingReasonID{ - ID: id, - }) - } - creationTime := new(string) - if !r.CreationTime.IsUnknown() && !r.CreationTime.IsNull() { - *creationTime = r.CreationTime.ValueString() - } else { - creationTime = nil - } - description := new(string) - if !r.Description.IsUnknown() && !r.Description.IsNull() { - *description = r.Description.ValueString() - } else { - description = nil - } - dueDate := new(string) - if !r.DueDate.IsUnknown() && !r.DueDate.IsNull() { - *dueDate = r.DueDate.ValueString() - } else { - dueDate = nil - } - var dynamicDueDate *shared.DynamicDueDate - if r.DynamicDueDate != nil { - actionTypeCondition := shared.ActionTypeCondition(r.DynamicDueDate.ActionTypeCondition.ValueString()) - var numberOfUnits float64 - numberOfUnits, _ = r.DynamicDueDate.NumberOfUnits.ValueBigFloat().Float64() - - stepID := new(string) - if !r.DynamicDueDate.StepID.IsUnknown() && !r.DynamicDueDate.StepID.IsNull() { - *stepID = r.DynamicDueDate.StepID.ValueString() - } else { - stepID = nil - } - timePeriod := shared.TimePeriod(r.DynamicDueDate.TimePeriod.ValueString()) - dynamicDueDate = &shared.DynamicDueDate{ - ActionTypeCondition: actionTypeCondition, - NumberOfUnits: numberOfUnits, - StepID: stepID, - TimePeriod: timePeriod, - } - } - enableECPWorkflow := new(bool) - if !r.EnableECPWorkflow.IsUnknown() && !r.EnableECPWorkflow.IsNull() { - *enableECPWorkflow = r.EnableECPWorkflow.ValueBool() - } else { - enableECPWorkflow = nil - } - enabled := new(bool) - if !r.Enabled.IsUnknown() && !r.Enabled.IsNull() { - *enabled = r.Enabled.ValueBool() - } else { - enabled = nil - } - var flow interface{} - _ = json.Unmarshal([]byte(r.Flow.ValueString()), &flow) - id1 := new(string) - if !r.ID.IsUnknown() && !r.ID.IsNull() { - *id1 = r.ID.ValueString() - } else { - id1 = nil - } - lastUpdateTime := new(string) - if !r.LastUpdateTime.IsUnknown() && !r.LastUpdateTime.IsNull() { - *lastUpdateTime = r.LastUpdateTime.ValueString() - } else { - lastUpdateTime = nil - } - var name string - name = r.Name.ValueString() - - var taxonomies []string = []string{} - for _, taxonomiesItem := range r.Taxonomies { - taxonomies = append(taxonomies, taxonomiesItem.ValueString()) - } - var updateEntityAttributes []shared.UpdateEntityAttributes = []shared.UpdateEntityAttributes{} - for _, updateEntityAttributesItem := range r.UpdateEntityAttributes { - source := shared.Source(updateEntityAttributesItem.Source.ValueString()) - var entityAttribute string - entityAttribute = updateEntityAttributesItem.Target.EntityAttribute.ValueString() - - var entitySchema string - entitySchema = updateEntityAttributesItem.Target.EntitySchema.ValueString() - - target := shared.Target{ - EntityAttribute: entityAttribute, - EntitySchema: entitySchema, - } - updateEntityAttributes = append(updateEntityAttributes, shared.UpdateEntityAttributes{ - Source: source, - Target: target, - }) - } - var userIds []float64 = []float64{} - for _, userIdsItem := range r.UserIds { - userIdsTmp, _ := userIdsItem.ValueBigFloat().Float64() - userIds = append(userIds, userIdsTmp) - } - out := shared.WorkflowDefinition{ - AssignedTo: assignedTo, - ClosingReasons: closingReasons, - CreationTime: creationTime, - Description: description, - DueDate: dueDate, - DynamicDueDate: dynamicDueDate, - EnableECPWorkflow: enableECPWorkflow, - Enabled: enabled, - Flow: flow, - ID: id1, - LastUpdateTime: lastUpdateTime, - Name: name, - Taxonomies: taxonomies, - UpdateEntityAttributes: updateEntityAttributes, - UserIds: userIds, - } - return &out -} - -func (r *WorkflowDefinitionResourceModel) RefreshFromSharedWorkflowDefinition(resp *shared.WorkflowDefinition) { - if resp != nil { - r.AssignedTo = []types.String{} - for _, v := range resp.AssignedTo { - r.AssignedTo = append(r.AssignedTo, types.StringValue(v)) - } - r.ClosingReasons = []tfTypes.ClosingReasonID{} - if len(r.ClosingReasons) > len(resp.ClosingReasons) { - r.ClosingReasons = r.ClosingReasons[:len(resp.ClosingReasons)] - } - for closingReasonsCount, closingReasonsItem := range resp.ClosingReasons { - var closingReasons1 tfTypes.ClosingReasonID - closingReasons1.ID = types.StringValue(closingReasonsItem.ID) - if closingReasonsCount+1 > len(r.ClosingReasons) { - r.ClosingReasons = append(r.ClosingReasons, closingReasons1) - } else { - r.ClosingReasons[closingReasonsCount].ID = closingReasons1.ID - } - } - r.CreationTime = types.StringPointerValue(resp.CreationTime) - r.Description = types.StringPointerValue(resp.Description) - r.DueDate = types.StringPointerValue(resp.DueDate) - if resp.DynamicDueDate == nil { - r.DynamicDueDate = nil - } else { - r.DynamicDueDate = &tfTypes.DynamicDueDate{} - r.DynamicDueDate.ActionTypeCondition = types.StringValue(string(resp.DynamicDueDate.ActionTypeCondition)) - r.DynamicDueDate.NumberOfUnits = types.NumberValue(big.NewFloat(float64(resp.DynamicDueDate.NumberOfUnits))) - r.DynamicDueDate.StepID = types.StringPointerValue(resp.DynamicDueDate.StepID) - r.DynamicDueDate.TimePeriod = types.StringValue(string(resp.DynamicDueDate.TimePeriod)) - } - r.Enabled = types.BoolPointerValue(resp.Enabled) - r.EnableECPWorkflow = types.BoolPointerValue(resp.EnableECPWorkflow) - flowResult, _ := json.Marshal(resp.Flow) - r.Flow = types.StringValue(string(flowResult)) - r.ID = types.StringPointerValue(resp.ID) - r.LastUpdateTime = types.StringPointerValue(resp.LastUpdateTime) - r.Name = types.StringValue(resp.Name) - r.Taxonomies = []types.String{} - for _, v := range resp.Taxonomies { - r.Taxonomies = append(r.Taxonomies, types.StringValue(v)) - } - r.UpdateEntityAttributes = []tfTypes.UpdateEntityAttributes{} - if len(r.UpdateEntityAttributes) > len(resp.UpdateEntityAttributes) { - r.UpdateEntityAttributes = r.UpdateEntityAttributes[:len(resp.UpdateEntityAttributes)] - } - for updateEntityAttributesCount, updateEntityAttributesItem := range resp.UpdateEntityAttributes { - var updateEntityAttributes1 tfTypes.UpdateEntityAttributes - updateEntityAttributes1.Source = types.StringValue(string(updateEntityAttributesItem.Source)) - updateEntityAttributes1.Target.EntityAttribute = types.StringValue(updateEntityAttributesItem.Target.EntityAttribute) - updateEntityAttributes1.Target.EntitySchema = types.StringValue(updateEntityAttributesItem.Target.EntitySchema) - if updateEntityAttributesCount+1 > len(r.UpdateEntityAttributes) { - r.UpdateEntityAttributes = append(r.UpdateEntityAttributes, updateEntityAttributes1) - } else { - r.UpdateEntityAttributes[updateEntityAttributesCount].Source = updateEntityAttributes1.Source - r.UpdateEntityAttributes[updateEntityAttributesCount].Target = updateEntityAttributes1.Target - } - } - r.UserIds = []types.Number{} - for _, v := range resp.UserIds { - r.UserIds = append(r.UserIds, types.NumberValue(big.NewFloat(float64(v)))) - } - } -} diff --git a/internal/sdk/closingreason.go b/internal/sdk/closingreason.go index dbcb656..b55f350 100644 --- a/internal/sdk/closingreason.go +++ b/internal/sdk/closingreason.go @@ -6,13 +6,11 @@ import ( "bytes" "context" "fmt" - "github.com/cenkalti/backoff/v4" "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/internal/hooks" "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/internal/utils" "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/models/errors" "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/models/operations" "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/models/shared" - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/retry" "net/http" "net/url" ) @@ -39,7 +37,6 @@ func (s *ClosingReason) ChangeReasonStatus(ctx context.Context, request operatio o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -83,94 +80,32 @@ func (s *ClosingReason) ChangeReasonStatus(ctx context.Context, request operatio return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { if err != nil { - return nil, err + err = fmt.Errorf("error sending request: %w", err) } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + err = fmt.Errorf("error sending request: no response") } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err + } else if _httpRes != nil { + httpRes = _httpRes } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } } } @@ -229,7 +164,6 @@ func (s *ClosingReason) CreateClosingReason(ctx context.Context, request shared. o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -273,94 +207,32 @@ func (s *ClosingReason) CreateClosingReason(ctx context.Context, request shared. return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { if err != nil { - return nil, err + err = fmt.Errorf("error sending request: %w", err) } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + err = fmt.Errorf("error sending request: no response") } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err + } else if _httpRes != nil { + httpRes = _httpRes } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } } } @@ -416,7 +288,6 @@ func (s *ClosingReason) GetAllClosingReasons(ctx context.Context, request operat o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -458,279 +329,36 @@ func (s *ClosingReason) GetAllClosingReasons(ctx context.Context, request operat return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } - } - - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - - if err != nil { - return nil, err - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } - } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, err - } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } - } - } - - res := &operations.GetAllClosingReasonsResponse{ - StatusCode: httpRes.StatusCode, - ContentType: httpRes.Header.Get("Content-Type"), - RawResponse: httpRes, - } - - switch { - case httpRes.StatusCode == 200: - switch { - case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - - var out shared.ClosingReasons - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.ClosingReasons = &out - default: - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) - } - default: - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - return nil, errors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) - } - - return res, nil - -} - -// GetClosingReason - getClosingReason -// Get specific closing reason by id from the organisation. -func (s *ClosingReason) GetClosingReason(ctx context.Context, request operations.GetClosingReasonRequest, opts ...operations.Option) (*operations.GetClosingReasonResponse, error) { - hookCtx := hooks.HookContext{ - Context: ctx, - OperationID: "getClosingReason", - OAuth2Scopes: []string{}, - SecuritySource: s.sdkConfiguration.Security, - } - - o := operations.Options{} - supportedOptions := []string{ - operations.SupportedOptionRetries, - operations.SupportedOptionTimeout, - } - - for _, opt := range opts { - if err := opt(&o, supportedOptions...); err != nil { - return nil, fmt.Errorf("error applying option: %w", err) - } - } - - baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) - opURL, err := utils.GenerateURL(ctx, baseURL, "/v1/workflows/closing-reasons/{reasonId}", request, nil) - if err != nil { - return nil, fmt.Errorf("error generating URL: %w", err) - } - - timeout := o.Timeout - if timeout == nil { - timeout = s.sdkConfiguration.Timeout - } - - if timeout != nil { - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(ctx, *timeout) - defer cancel() - } - - req, err := http.NewRequestWithContext(ctx, "GET", opURL, nil) + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) if err != nil { - return nil, fmt.Errorf("error creating request: %w", err) - } - req.Header.Set("Accept", "application/json") - req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) - - if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } + err = fmt.Errorf("error sending request: no response") } - } - - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + } else if _httpRes != nil { + httpRes = _httpRes } } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) if err != nil { return nil, err } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } - } } - res := &operations.GetClosingReasonResponse{ + res := &operations.GetAllClosingReasonsResponse{ StatusCode: httpRes.StatusCode, ContentType: httpRes.Header.Get("Content-Type"), RawResponse: httpRes, @@ -745,58 +373,12 @@ func (s *ClosingReason) GetClosingReason(ctx context.Context, request operations return nil, err } - var out shared.ClosingReason - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.ClosingReason = &out - default: - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) - } - case httpRes.StatusCode == 400: - fallthrough - case httpRes.StatusCode == 401: - fallthrough - case httpRes.StatusCode == 500: - switch { - case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - - var out shared.ErrorResp - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.ErrorResp = &out - default: - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) - } - case httpRes.StatusCode == 404: - switch { - case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - - var out shared.ClosingReasonNotFoundResp + var out shared.ClosingReasons if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { return nil, err } - res.ClosingReasonNotFoundResp = &out + res.ClosingReasons = &out default: rawBody, err := utils.ConsumeRawBody(httpRes) if err != nil { diff --git a/internal/sdk/flowsv2.go b/internal/sdk/flowsv2.go deleted file mode 100644 index 4233b59..0000000 --- a/internal/sdk/flowsv2.go +++ /dev/null @@ -1,1065 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package sdk - -import ( - "bytes" - "context" - "fmt" - "github.com/cenkalti/backoff/v4" - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/internal/hooks" - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/internal/utils" - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/models/errors" - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/models/operations" - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/models/shared" - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/retry" - "net/http" - "net/url" -) - -type FlowsV2 struct { - sdkConfiguration sdkConfiguration -} - -func newFlowsV2(sdkConfig sdkConfiguration) *FlowsV2 { - return &FlowsV2{ - sdkConfiguration: sdkConfig, - } -} - -// CreateFlowTemplate - createFlowTemplate -// Create a new Flow Template. -func (s *FlowsV2) CreateFlowTemplate(ctx context.Context, request shared.FlowTemplate, opts ...operations.Option) (*operations.CreateFlowTemplateResponse, error) { - hookCtx := hooks.HookContext{ - Context: ctx, - OperationID: "createFlowTemplate", - OAuth2Scopes: []string{}, - SecuritySource: s.sdkConfiguration.Security, - } - - o := operations.Options{} - supportedOptions := []string{ - operations.SupportedOptionRetries, - operations.SupportedOptionTimeout, - } - - for _, opt := range opts { - if err := opt(&o, supportedOptions...); err != nil { - return nil, fmt.Errorf("error applying option: %w", err) - } - } - - baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) - opURL, err := url.JoinPath(baseURL, "/v2/flows/templates") - if err != nil { - return nil, fmt.Errorf("error generating URL: %w", err) - } - - bodyReader, reqContentType, err := utils.SerializeRequestBody(ctx, request, false, false, "Request", "json", `request:"mediaType=application/json"`) - if err != nil { - return nil, err - } - - timeout := o.Timeout - if timeout == nil { - timeout = s.sdkConfiguration.Timeout - } - - if timeout != nil { - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(ctx, *timeout) - defer cancel() - } - - req, err := http.NewRequestWithContext(ctx, "POST", opURL, bodyReader) - if err != nil { - return nil, fmt.Errorf("error creating request: %w", err) - } - req.Header.Set("Accept", "application/json") - req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) - req.Header.Set("Content-Type", reqContentType) - - if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { - return nil, err - } - - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } - } - - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - - if err != nil { - return nil, err - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } - } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, err - } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } - } - } - - res := &operations.CreateFlowTemplateResponse{ - StatusCode: httpRes.StatusCode, - ContentType: httpRes.Header.Get("Content-Type"), - RawResponse: httpRes, - } - - switch { - case httpRes.StatusCode == 201: - switch { - case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - - var out shared.FlowTemplate - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.FlowTemplate = &out - default: - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) - } - case httpRes.StatusCode == 400: - fallthrough - case httpRes.StatusCode == 401: - fallthrough - case httpRes.StatusCode == 500: - switch { - case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - - var out shared.ErrorResp - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.ErrorResp = &out - default: - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) - } - default: - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - return nil, errors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) - } - - return res, nil - -} - -// DeleteFlowTemplate - deleteFlowTemplate -// Delete Flow Template. -func (s *FlowsV2) DeleteFlowTemplate(ctx context.Context, request operations.DeleteFlowTemplateRequest, opts ...operations.Option) (*operations.DeleteFlowTemplateResponse, error) { - hookCtx := hooks.HookContext{ - Context: ctx, - OperationID: "deleteFlowTemplate", - OAuth2Scopes: []string{}, - SecuritySource: s.sdkConfiguration.Security, - } - - o := operations.Options{} - supportedOptions := []string{ - operations.SupportedOptionRetries, - operations.SupportedOptionTimeout, - } - - for _, opt := range opts { - if err := opt(&o, supportedOptions...); err != nil { - return nil, fmt.Errorf("error applying option: %w", err) - } - } - - baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) - opURL, err := utils.GenerateURL(ctx, baseURL, "/v2/flows/templates/{flowId}", request, nil) - if err != nil { - return nil, fmt.Errorf("error generating URL: %w", err) - } - - timeout := o.Timeout - if timeout == nil { - timeout = s.sdkConfiguration.Timeout - } - - if timeout != nil { - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(ctx, *timeout) - defer cancel() - } - - req, err := http.NewRequestWithContext(ctx, "DELETE", opURL, nil) - if err != nil { - return nil, fmt.Errorf("error creating request: %w", err) - } - req.Header.Set("Accept", "application/json") - req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) - - if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { - return nil, err - } - - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } - } - - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - - if err != nil { - return nil, err - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } - } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, err - } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } - } - } - - res := &operations.DeleteFlowTemplateResponse{ - StatusCode: httpRes.StatusCode, - ContentType: httpRes.Header.Get("Content-Type"), - RawResponse: httpRes, - } - - switch { - case httpRes.StatusCode == 204: - fallthrough - case httpRes.StatusCode == 404: - case httpRes.StatusCode == 401: - switch { - case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - - var out shared.ErrorResp - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.ErrorResp = &out - default: - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) - } - default: - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - return nil, errors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) - } - - return res, nil - -} - -// GetFlowTemplate - getFlowTemplate -// Get specific FLow template for a customer -func (s *FlowsV2) GetFlowTemplate(ctx context.Context, request operations.GetFlowTemplateRequest, opts ...operations.Option) (*operations.GetFlowTemplateResponse, error) { - hookCtx := hooks.HookContext{ - Context: ctx, - OperationID: "getFlowTemplate", - OAuth2Scopes: []string{}, - SecuritySource: s.sdkConfiguration.Security, - } - - o := operations.Options{} - supportedOptions := []string{ - operations.SupportedOptionRetries, - operations.SupportedOptionTimeout, - } - - for _, opt := range opts { - if err := opt(&o, supportedOptions...); err != nil { - return nil, fmt.Errorf("error applying option: %w", err) - } - } - - baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) - opURL, err := utils.GenerateURL(ctx, baseURL, "/v2/flows/templates/{flowId}", request, nil) - if err != nil { - return nil, fmt.Errorf("error generating URL: %w", err) - } - - timeout := o.Timeout - if timeout == nil { - timeout = s.sdkConfiguration.Timeout - } - - if timeout != nil { - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(ctx, *timeout) - defer cancel() - } - - req, err := http.NewRequestWithContext(ctx, "GET", opURL, nil) - if err != nil { - return nil, fmt.Errorf("error creating request: %w", err) - } - req.Header.Set("Accept", "application/json") - req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) - - if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { - return nil, err - } - - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } - } - - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - - if err != nil { - return nil, err - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } - } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, err - } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } - } - } - - res := &operations.GetFlowTemplateResponse{ - StatusCode: httpRes.StatusCode, - ContentType: httpRes.Header.Get("Content-Type"), - RawResponse: httpRes, - } - - switch { - case httpRes.StatusCode == 200: - switch { - case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - - var out shared.FlowTemplate - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.FlowTemplate = &out - default: - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) - } - case httpRes.StatusCode == 400: - fallthrough - case httpRes.StatusCode == 401: - fallthrough - case httpRes.StatusCode == 500: - switch { - case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - - var out shared.ErrorResp - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.ErrorResp = &out - default: - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) - } - case httpRes.StatusCode == 404: - switch { - case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - - var out shared.DefinitionNotFoundResp - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.DefinitionNotFoundResp = &out - default: - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) - } - default: - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - return nil, errors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) - } - - return res, nil - -} - -// ListFlowTemplates - listFlowTemplates -// List all Flow Templates for a customer -func (s *FlowsV2) ListFlowTemplates(ctx context.Context, opts ...operations.Option) (*operations.ListFlowTemplatesResponse, error) { - hookCtx := hooks.HookContext{ - Context: ctx, - OperationID: "listFlowTemplates", - OAuth2Scopes: []string{}, - SecuritySource: s.sdkConfiguration.Security, - } - - o := operations.Options{} - supportedOptions := []string{ - operations.SupportedOptionRetries, - operations.SupportedOptionTimeout, - } - - for _, opt := range opts { - if err := opt(&o, supportedOptions...); err != nil { - return nil, fmt.Errorf("error applying option: %w", err) - } - } - - baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) - opURL, err := url.JoinPath(baseURL, "/v2/flows/templates") - if err != nil { - return nil, fmt.Errorf("error generating URL: %w", err) - } - - timeout := o.Timeout - if timeout == nil { - timeout = s.sdkConfiguration.Timeout - } - - if timeout != nil { - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(ctx, *timeout) - defer cancel() - } - - req, err := http.NewRequestWithContext(ctx, "GET", opURL, nil) - if err != nil { - return nil, fmt.Errorf("error creating request: %w", err) - } - req.Header.Set("Accept", "application/json") - req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) - - if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { - return nil, err - } - - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } - } - - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - - if err != nil { - return nil, err - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } - } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, err - } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } - } - } - - res := &operations.ListFlowTemplatesResponse{ - StatusCode: httpRes.StatusCode, - ContentType: httpRes.Header.Get("Content-Type"), - RawResponse: httpRes, - } - - switch { - case httpRes.StatusCode == 200: - switch { - case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - - var out shared.FlowTemplatesList - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.FlowTemplatesList = &out - default: - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) - } - case httpRes.StatusCode == 500: - switch { - case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - - var out shared.ErrorResp - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.ErrorResp = &out - default: - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) - } - default: - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - return nil, errors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) - } - - return res, nil - -} - -// UpdateFlowTemplate - updateFlowTemplate -// Update Flow Template. -func (s *FlowsV2) UpdateFlowTemplate(ctx context.Context, request operations.UpdateFlowTemplateRequest, opts ...operations.Option) (*operations.UpdateFlowTemplateResponse, error) { - hookCtx := hooks.HookContext{ - Context: ctx, - OperationID: "updateFlowTemplate", - OAuth2Scopes: []string{}, - SecuritySource: s.sdkConfiguration.Security, - } - - o := operations.Options{} - supportedOptions := []string{ - operations.SupportedOptionRetries, - operations.SupportedOptionTimeout, - } - - for _, opt := range opts { - if err := opt(&o, supportedOptions...); err != nil { - return nil, fmt.Errorf("error applying option: %w", err) - } - } - - baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) - opURL, err := utils.GenerateURL(ctx, baseURL, "/v2/flows/templates/{flowId}", request, nil) - if err != nil { - return nil, fmt.Errorf("error generating URL: %w", err) - } - - bodyReader, reqContentType, err := utils.SerializeRequestBody(ctx, request, false, false, "FlowTemplate", "json", `request:"mediaType=application/json"`) - if err != nil { - return nil, err - } - - timeout := o.Timeout - if timeout == nil { - timeout = s.sdkConfiguration.Timeout - } - - if timeout != nil { - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(ctx, *timeout) - defer cancel() - } - - req, err := http.NewRequestWithContext(ctx, "PUT", opURL, bodyReader) - if err != nil { - return nil, fmt.Errorf("error creating request: %w", err) - } - req.Header.Set("Accept", "application/json") - req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) - req.Header.Set("Content-Type", reqContentType) - - if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { - return nil, err - } - - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } - } - - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - - if err != nil { - return nil, err - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } - } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, err - } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } - } - } - - res := &operations.UpdateFlowTemplateResponse{ - StatusCode: httpRes.StatusCode, - ContentType: httpRes.Header.Get("Content-Type"), - RawResponse: httpRes, - } - - switch { - case httpRes.StatusCode == 200: - switch { - case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - - var out shared.FlowTemplate - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.FlowTemplate = &out - default: - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) - } - case httpRes.StatusCode == 400: - fallthrough - case httpRes.StatusCode == 401: - fallthrough - case httpRes.StatusCode == 500: - switch { - case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - - var out shared.ErrorResp - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.ErrorResp = &out - default: - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) - } - default: - rawBody, err := utils.ConsumeRawBody(httpRes) - if err != nil { - return nil, err - } - return nil, errors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) - } - - return res, nil - -} diff --git a/internal/sdk/internal/utils/env.go b/internal/sdk/internal/utils/env.go new file mode 100644 index 0000000..110d464 --- /dev/null +++ b/internal/sdk/internal/utils/env.go @@ -0,0 +1,16 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package utils + +import ( + "os" +) + +// GetEnv returns the value of the environment variable named by the key or the defaultValue if the environment variable is not set. +func GetEnv(name, defaultValue string) string { + value := os.Getenv(name) + if value == "" { + return defaultValue + } + return value +} diff --git a/internal/sdk/internal/utils/retries.go b/internal/sdk/internal/utils/retries.go index 182ec60..6f768be 100644 --- a/internal/sdk/internal/utils/retries.go +++ b/internal/sdk/internal/utils/retries.go @@ -6,8 +6,9 @@ import ( "context" "errors" "fmt" - "github.com/cenkalti/backoff/v4" "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/retry" + "math" + "math/rand" "net/http" "net/url" "strconv" @@ -15,8 +16,6 @@ import ( "time" ) -var errRequestFailed = errors.New("request failed") - // Deprecated: Use retry.BackoffStrategy instead. type BackoffStrategy = retry.BackoffStrategy @@ -28,34 +27,27 @@ type Retries struct { StatusCodes []string } -func Retry(ctx context.Context, r Retries, action func() (*http.Response, error)) (*http.Response, error) { +func Retry(ctx context.Context, r Retries, operation func() (*http.Response, error)) (*http.Response, error) { switch r.Config.Strategy { case "backoff": if r.Config.Backoff == nil { - return action() + return operation() } - config := backoff.NewExponentialBackOff() - config.InitialInterval = time.Duration(r.Config.Backoff.InitialInterval) * time.Millisecond - config.MaxInterval = time.Duration(r.Config.Backoff.MaxInterval) * time.Millisecond - config.Multiplier = r.Config.Backoff.Exponent - config.MaxElapsedTime = time.Duration(r.Config.Backoff.MaxElapsedTime) * time.Millisecond - config.Reset() - var resp *http.Response - err := backoff.Retry(func() error { + err := retryWithBackoff(ctx, r.Config.Backoff, func() error { if resp != nil { resp.Body.Close() } select { case <-ctx.Done(): - return backoff.Permanent(ctx.Err()) + return retry.Permanent(ctx.Err()) default: } - res, err := action() + res, err := operation() if err != nil { urlError := new(url.Error) if errors.As(err, &urlError) { @@ -64,7 +56,7 @@ func Retry(ctx context.Context, r Retries, action func() (*http.Response, error) } } - return backoff.Permanent(err) + return retry.Permanent(err) } resp = res if res == nil { @@ -81,7 +73,7 @@ func Retry(ctx context.Context, r Retries, action func() (*http.Response, error) s := res.StatusCode / 100 if s >= codeRange && s < codeRange+1 { - return errRequestFailed + return retry.TemporaryFromResponse("request failed", res) } } else { parsedCode, err := strconv.Atoi(code) @@ -90,7 +82,7 @@ func Retry(ctx context.Context, r Retries, action func() (*http.Response, error) } if res.StatusCode == parsedCode { - return errRequestFailed + return retry.TemporaryFromResponse("request failed", res) } } } @@ -98,13 +90,131 @@ func Retry(ctx context.Context, r Retries, action func() (*http.Response, error) resp = res return nil - }, config) - if err != nil && !errors.Is(err, errRequestFailed) { + }) + + var tempErr *retry.TemporaryError + if err != nil && !errors.As(err, &tempErr) { return nil, err } return resp, nil default: - return action() + return operation() + } +} + +func retryWithBackoff(ctx context.Context, s *retry.BackoffStrategy, operation func() error) error { + var ( + err error + next time.Duration + attempt int + start = time.Now() + maxElapsedTime = time.Duration(s.MaxElapsedTime) * time.Millisecond + ) + + timer := &defaultTimer{} + defer func() { + timer.Stop() + }() + + for { + err = operation() + if err == nil { + return nil + } + + var permanent *retry.PermanentError + if errors.As(err, &permanent) { + return permanent.Unwrap() + } + + if time.Since(start) >= maxElapsedTime { + return err + } + + var temporary *retry.TemporaryError + if errors.As(err, &temporary) { + next = temporary.RetryAfter() + } + + if next <= 0 { + next = nextInterval(s, attempt) + } + + timer.Start(next) + + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C(): + } + + attempt += 1 } } + +type Timer interface { + Start(duration time.Duration) + Stop() + C() <-chan time.Time +} + +// defaultTimer implements Timer interface using time.Timer +type defaultTimer struct { + timer *time.Timer +} + +// C returns the timers channel which receives the current time when the timer fires. +func (t *defaultTimer) C() <-chan time.Time { + return t.timer.C +} + +// Start starts the timer to fire after the given duration +func (t *defaultTimer) Start(duration time.Duration) { + if t.timer == nil { + t.timer = time.NewTimer(duration) + return + } + + if !t.timer.Stop() { + select { + case <-t.timer.C: + default: + } + } + + t.timer.Reset(duration) +} + +// Stop is called when the timer is not used anymore and resources may be freed. +func (t *defaultTimer) Stop() { + if t.timer != nil { + t.timer.Stop() + } +} + +func nextInterval(s *retry.BackoffStrategy, attempt int) time.Duration { + initialInterval := float64(time.Duration(s.InitialInterval) * time.Millisecond) + maxInterval := float64(time.Duration(s.MaxInterval) * time.Millisecond) + exponent := s.Exponent + jitterFactor := float64(0.25) + + interval := initialInterval * math.Pow(float64(attempt+1), exponent) + + jitter := rand.Float64() * jitterFactor * interval + if rand.Float64() < 0.5 { + jitter = -1 * jitter + } + + interval = interval + jitter + + if interval <= 0 { + interval = initialInterval + } + + if interval > maxInterval { + interval = maxInterval + } + + return time.Duration(interval) +} diff --git a/internal/sdk/models/operations/createflowtemplate.go b/internal/sdk/models/operations/createflowtemplate.go deleted file mode 100644 index f88ddf5..0000000 --- a/internal/sdk/models/operations/createflowtemplate.go +++ /dev/null @@ -1,56 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package operations - -import ( - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/models/shared" - "net/http" -) - -type CreateFlowTemplateResponse struct { - // HTTP response content type for this operation - ContentType string - // Validation Errors - ErrorResp *shared.ErrorResp - // Success - if the flow template is created successfully - FlowTemplate *shared.FlowTemplate - // HTTP response status code for this operation - StatusCode int - // Raw HTTP response; suitable for custom response parsing - RawResponse *http.Response -} - -func (o *CreateFlowTemplateResponse) GetContentType() string { - if o == nil { - return "" - } - return o.ContentType -} - -func (o *CreateFlowTemplateResponse) GetErrorResp() *shared.ErrorResp { - if o == nil { - return nil - } - return o.ErrorResp -} - -func (o *CreateFlowTemplateResponse) GetFlowTemplate() *shared.FlowTemplate { - if o == nil { - return nil - } - return o.FlowTemplate -} - -func (o *CreateFlowTemplateResponse) GetStatusCode() int { - if o == nil { - return 0 - } - return o.StatusCode -} - -func (o *CreateFlowTemplateResponse) GetRawResponse() *http.Response { - if o == nil { - return nil - } - return o.RawResponse -} diff --git a/internal/sdk/models/operations/deleteflowtemplate.go b/internal/sdk/models/operations/deleteflowtemplate.go deleted file mode 100644 index e146494..0000000 --- a/internal/sdk/models/operations/deleteflowtemplate.go +++ /dev/null @@ -1,59 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package operations - -import ( - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/models/shared" - "net/http" -) - -type DeleteFlowTemplateRequest struct { - // Id of the flow template to de deleted. - FlowID string `pathParam:"style=simple,explode=false,name=flowId"` -} - -func (o *DeleteFlowTemplateRequest) GetFlowID() string { - if o == nil { - return "" - } - return o.FlowID -} - -type DeleteFlowTemplateResponse struct { - // HTTP response content type for this operation - ContentType string - // Failed to authenticate - ErrorResp *shared.ErrorResp - // HTTP response status code for this operation - StatusCode int - // Raw HTTP response; suitable for custom response parsing - RawResponse *http.Response -} - -func (o *DeleteFlowTemplateResponse) GetContentType() string { - if o == nil { - return "" - } - return o.ContentType -} - -func (o *DeleteFlowTemplateResponse) GetErrorResp() *shared.ErrorResp { - if o == nil { - return nil - } - return o.ErrorResp -} - -func (o *DeleteFlowTemplateResponse) GetStatusCode() int { - if o == nil { - return 0 - } - return o.StatusCode -} - -func (o *DeleteFlowTemplateResponse) GetRawResponse() *http.Response { - if o == nil { - return nil - } - return o.RawResponse -} diff --git a/internal/sdk/models/operations/getclosingreason.go b/internal/sdk/models/operations/getclosingreason.go deleted file mode 100644 index a1faf13..0000000 --- a/internal/sdk/models/operations/getclosingreason.go +++ /dev/null @@ -1,77 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package operations - -import ( - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/models/shared" - "net/http" -) - -type GetClosingReasonRequest struct { - // uuid to identify the closing reason. - ReasonID string `pathParam:"style=simple,explode=false,name=reasonId"` -} - -func (o *GetClosingReasonRequest) GetReasonID() string { - if o == nil { - return "" - } - return o.ReasonID -} - -type GetClosingReasonResponse struct { - // Returns the closing reason - ClosingReason *shared.ClosingReason - // Closing reason not found - ClosingReasonNotFoundResp *shared.ClosingReasonNotFoundResp - // HTTP response content type for this operation - ContentType string - // Validation Errors - ErrorResp *shared.ErrorResp - // HTTP response status code for this operation - StatusCode int - // Raw HTTP response; suitable for custom response parsing - RawResponse *http.Response -} - -func (o *GetClosingReasonResponse) GetClosingReason() *shared.ClosingReason { - if o == nil { - return nil - } - return o.ClosingReason -} - -func (o *GetClosingReasonResponse) GetClosingReasonNotFoundResp() *shared.ClosingReasonNotFoundResp { - if o == nil { - return nil - } - return o.ClosingReasonNotFoundResp -} - -func (o *GetClosingReasonResponse) GetContentType() string { - if o == nil { - return "" - } - return o.ContentType -} - -func (o *GetClosingReasonResponse) GetErrorResp() *shared.ErrorResp { - if o == nil { - return nil - } - return o.ErrorResp -} - -func (o *GetClosingReasonResponse) GetStatusCode() int { - if o == nil { - return 0 - } - return o.StatusCode -} - -func (o *GetClosingReasonResponse) GetRawResponse() *http.Response { - if o == nil { - return nil - } - return o.RawResponse -} diff --git a/internal/sdk/models/operations/getflowtemplate.go b/internal/sdk/models/operations/getflowtemplate.go deleted file mode 100644 index f956ebe..0000000 --- a/internal/sdk/models/operations/getflowtemplate.go +++ /dev/null @@ -1,76 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package operations - -import ( - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/models/shared" - "net/http" -) - -type GetFlowTemplateRequest struct { - FlowID string `pathParam:"style=simple,explode=false,name=flowId"` -} - -func (o *GetFlowTemplateRequest) GetFlowID() string { - if o == nil { - return "" - } - return o.FlowID -} - -type GetFlowTemplateResponse struct { - // HTTP response content type for this operation - ContentType string - // Definition Not found - DefinitionNotFoundResp *shared.DefinitionNotFoundResp - // Validation Errors - ErrorResp *shared.ErrorResp - // Returns the Flow Template - FlowTemplate *shared.FlowTemplate - // HTTP response status code for this operation - StatusCode int - // Raw HTTP response; suitable for custom response parsing - RawResponse *http.Response -} - -func (o *GetFlowTemplateResponse) GetContentType() string { - if o == nil { - return "" - } - return o.ContentType -} - -func (o *GetFlowTemplateResponse) GetDefinitionNotFoundResp() *shared.DefinitionNotFoundResp { - if o == nil { - return nil - } - return o.DefinitionNotFoundResp -} - -func (o *GetFlowTemplateResponse) GetErrorResp() *shared.ErrorResp { - if o == nil { - return nil - } - return o.ErrorResp -} - -func (o *GetFlowTemplateResponse) GetFlowTemplate() *shared.FlowTemplate { - if o == nil { - return nil - } - return o.FlowTemplate -} - -func (o *GetFlowTemplateResponse) GetStatusCode() int { - if o == nil { - return 0 - } - return o.StatusCode -} - -func (o *GetFlowTemplateResponse) GetRawResponse() *http.Response { - if o == nil { - return nil - } - return o.RawResponse -} diff --git a/internal/sdk/models/operations/listflowtemplates.go b/internal/sdk/models/operations/listflowtemplates.go deleted file mode 100644 index 4570a13..0000000 --- a/internal/sdk/models/operations/listflowtemplates.go +++ /dev/null @@ -1,56 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package operations - -import ( - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/models/shared" - "net/http" -) - -type ListFlowTemplatesResponse struct { - // HTTP response content type for this operation - ContentType string - // Other errors - ErrorResp *shared.ErrorResp - // Success - flow templates loaded with success. Empty array if customer has no flows defined. - FlowTemplatesList *shared.FlowTemplatesList - // HTTP response status code for this operation - StatusCode int - // Raw HTTP response; suitable for custom response parsing - RawResponse *http.Response -} - -func (o *ListFlowTemplatesResponse) GetContentType() string { - if o == nil { - return "" - } - return o.ContentType -} - -func (o *ListFlowTemplatesResponse) GetErrorResp() *shared.ErrorResp { - if o == nil { - return nil - } - return o.ErrorResp -} - -func (o *ListFlowTemplatesResponse) GetFlowTemplatesList() *shared.FlowTemplatesList { - if o == nil { - return nil - } - return o.FlowTemplatesList -} - -func (o *ListFlowTemplatesResponse) GetStatusCode() int { - if o == nil { - return 0 - } - return o.StatusCode -} - -func (o *ListFlowTemplatesResponse) GetRawResponse() *http.Response { - if o == nil { - return nil - } - return o.RawResponse -} diff --git a/internal/sdk/models/operations/updateflowtemplate.go b/internal/sdk/models/operations/updateflowtemplate.go deleted file mode 100644 index c2d23b5..0000000 --- a/internal/sdk/models/operations/updateflowtemplate.go +++ /dev/null @@ -1,76 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package operations - -import ( - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/models/shared" - "net/http" -) - -type UpdateFlowTemplateRequest struct { - // Flow Template payload - FlowTemplate shared.FlowTemplate `request:"mediaType=application/json"` - FlowID string `pathParam:"style=simple,explode=false,name=flowId"` -} - -func (o *UpdateFlowTemplateRequest) GetFlowTemplate() shared.FlowTemplate { - if o == nil { - return shared.FlowTemplate{} - } - return o.FlowTemplate -} - -func (o *UpdateFlowTemplateRequest) GetFlowID() string { - if o == nil { - return "" - } - return o.FlowID -} - -type UpdateFlowTemplateResponse struct { - // HTTP response content type for this operation - ContentType string - // Validation Errors - ErrorResp *shared.ErrorResp - // Flow template has been updated successfully - FlowTemplate *shared.FlowTemplate - // HTTP response status code for this operation - StatusCode int - // Raw HTTP response; suitable for custom response parsing - RawResponse *http.Response -} - -func (o *UpdateFlowTemplateResponse) GetContentType() string { - if o == nil { - return "" - } - return o.ContentType -} - -func (o *UpdateFlowTemplateResponse) GetErrorResp() *shared.ErrorResp { - if o == nil { - return nil - } - return o.ErrorResp -} - -func (o *UpdateFlowTemplateResponse) GetFlowTemplate() *shared.FlowTemplate { - if o == nil { - return nil - } - return o.FlowTemplate -} - -func (o *UpdateFlowTemplateResponse) GetStatusCode() int { - if o == nil { - return 0 - } - return o.StatusCode -} - -func (o *UpdateFlowTemplateResponse) GetRawResponse() *http.Response { - if o == nil { - return nil - } - return o.RawResponse -} diff --git a/internal/sdk/models/shared/automationtask.go b/internal/sdk/models/shared/automationtask.go deleted file mode 100644 index c44f2b3..0000000 --- a/internal/sdk/models/shared/automationtask.go +++ /dev/null @@ -1,136 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package shared - -type AutomationConfig struct { - // Id of the configured automation to run - FlowID string `json:"flow_id"` -} - -func (o *AutomationConfig) GetFlowID() string { - if o == nil { - return "" - } - return o.FlowID -} - -type AutomationTask struct { - AssignedTo []string `json:"assigned_to,omitempty"` - AutomationConfig AutomationConfig `json:"automation_config"` - // Longer information regarding Task - Description *StepDescription `json:"description,omitempty"` - DueDate *string `json:"due_date,omitempty"` - // Set due date for the task based on a dynamic condition - DynamicDueDate *DueDateConfig `json:"dynamic_due_date,omitempty"` - // Details regarding ECP for the workflow step - Ecp *ECPDetails `json:"ecp,omitempty"` - ID string `json:"id"` - // Details regarding ECP for the workflow step - Installer *ECPDetails `json:"installer,omitempty"` - Journey *StepJourney `json:"journey,omitempty"` - Name string `json:"name"` - PhaseID *string `json:"phase_id,omitempty"` - // requirements that need to be fulfilled in order to enable the task while flow instances are running - Requirements []EnableRequirement `json:"requirements,omitempty"` - TaskType TaskType `json:"task_type"` - // Taxonomy ids that are associated with this workflow and used for filtering - Taxonomies []string `json:"taxonomies,omitempty"` -} - -func (o *AutomationTask) GetAssignedTo() []string { - if o == nil { - return nil - } - return o.AssignedTo -} - -func (o *AutomationTask) GetAutomationConfig() AutomationConfig { - if o == nil { - return AutomationConfig{} - } - return o.AutomationConfig -} - -func (o *AutomationTask) GetDescription() *StepDescription { - if o == nil { - return nil - } - return o.Description -} - -func (o *AutomationTask) GetDueDate() *string { - if o == nil { - return nil - } - return o.DueDate -} - -func (o *AutomationTask) GetDynamicDueDate() *DueDateConfig { - if o == nil { - return nil - } - return o.DynamicDueDate -} - -func (o *AutomationTask) GetEcp() *ECPDetails { - if o == nil { - return nil - } - return o.Ecp -} - -func (o *AutomationTask) GetID() string { - if o == nil { - return "" - } - return o.ID -} - -func (o *AutomationTask) GetInstaller() *ECPDetails { - if o == nil { - return nil - } - return o.Installer -} - -func (o *AutomationTask) GetJourney() *StepJourney { - if o == nil { - return nil - } - return o.Journey -} - -func (o *AutomationTask) GetName() string { - if o == nil { - return "" - } - return o.Name -} - -func (o *AutomationTask) GetPhaseID() *string { - if o == nil { - return nil - } - return o.PhaseID -} - -func (o *AutomationTask) GetRequirements() []EnableRequirement { - if o == nil { - return nil - } - return o.Requirements -} - -func (o *AutomationTask) GetTaskType() TaskType { - if o == nil { - return TaskType("") - } - return o.TaskType -} - -func (o *AutomationTask) GetTaxonomies() []string { - if o == nil { - return nil - } - return o.Taxonomies -} diff --git a/internal/sdk/models/shared/closingreasonnotfoundresp.go b/internal/sdk/models/shared/closingreasonnotfoundresp.go deleted file mode 100644 index 2bbfab4..0000000 --- a/internal/sdk/models/shared/closingreasonnotfoundresp.go +++ /dev/null @@ -1,15 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package shared - -// ClosingReasonNotFoundResp - Closing reason could be not found -type ClosingReasonNotFoundResp struct { - Message *string `json:"message,omitempty"` -} - -func (o *ClosingReasonNotFoundResp) GetMessage() *string { - if o == nil { - return nil - } - return o.Message -} diff --git a/internal/sdk/models/shared/condition.go b/internal/sdk/models/shared/condition.go deleted file mode 100644 index 2b6c9b0..0000000 --- a/internal/sdk/models/shared/condition.go +++ /dev/null @@ -1,61 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package shared - -import ( - "encoding/json" - "fmt" -) - -type LogicalOperator string - -const ( - LogicalOperatorAnd LogicalOperator = "AND" - LogicalOperatorOr LogicalOperator = "OR" -) - -func (e LogicalOperator) ToPointer() *LogicalOperator { - return &e -} -func (e *LogicalOperator) UnmarshalJSON(data []byte) error { - var v string - if err := json.Unmarshal(data, &v); err != nil { - return err - } - switch v { - case "AND": - fallthrough - case "OR": - *e = LogicalOperator(v) - return nil - default: - return fmt.Errorf("invalid value for LogicalOperator: %v", v) - } -} - -type Condition struct { - ID string `json:"id"` - LogicalOperator LogicalOperator `json:"logical_operator"` - Statements []Statement `json:"statements"` -} - -func (o *Condition) GetID() string { - if o == nil { - return "" - } - return o.ID -} - -func (o *Condition) GetLogicalOperator() LogicalOperator { - if o == nil { - return LogicalOperator("") - } - return o.LogicalOperator -} - -func (o *Condition) GetStatements() []Statement { - if o == nil { - return []Statement{} - } - return o.Statements -} diff --git a/internal/sdk/models/shared/decisiontask.go b/internal/sdk/models/shared/decisiontask.go deleted file mode 100644 index 1300f97..0000000 --- a/internal/sdk/models/shared/decisiontask.go +++ /dev/null @@ -1,124 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package shared - -type DecisionTask struct { - AssignedTo []string `json:"assigned_to,omitempty"` - Conditions []Condition `json:"conditions"` - // Longer information regarding Task - Description *StepDescription `json:"description,omitempty"` - DueDate *string `json:"due_date,omitempty"` - // Set due date for the task based on a dynamic condition - DynamicDueDate *DueDateConfig `json:"dynamic_due_date,omitempty"` - // Details regarding ECP for the workflow step - Ecp *ECPDetails `json:"ecp,omitempty"` - ID string `json:"id"` - // Details regarding ECP for the workflow step - Installer *ECPDetails `json:"installer,omitempty"` - Journey *StepJourney `json:"journey,omitempty"` - Name string `json:"name"` - PhaseID *string `json:"phase_id,omitempty"` - // requirements that need to be fulfilled in order to enable the task while flow instances are running - Requirements []EnableRequirement `json:"requirements,omitempty"` - TaskType TaskType `json:"task_type"` - // Taxonomy ids that are associated with this workflow and used for filtering - Taxonomies []string `json:"taxonomies,omitempty"` -} - -func (o *DecisionTask) GetAssignedTo() []string { - if o == nil { - return nil - } - return o.AssignedTo -} - -func (o *DecisionTask) GetConditions() []Condition { - if o == nil { - return []Condition{} - } - return o.Conditions -} - -func (o *DecisionTask) GetDescription() *StepDescription { - if o == nil { - return nil - } - return o.Description -} - -func (o *DecisionTask) GetDueDate() *string { - if o == nil { - return nil - } - return o.DueDate -} - -func (o *DecisionTask) GetDynamicDueDate() *DueDateConfig { - if o == nil { - return nil - } - return o.DynamicDueDate -} - -func (o *DecisionTask) GetEcp() *ECPDetails { - if o == nil { - return nil - } - return o.Ecp -} - -func (o *DecisionTask) GetID() string { - if o == nil { - return "" - } - return o.ID -} - -func (o *DecisionTask) GetInstaller() *ECPDetails { - if o == nil { - return nil - } - return o.Installer -} - -func (o *DecisionTask) GetJourney() *StepJourney { - if o == nil { - return nil - } - return o.Journey -} - -func (o *DecisionTask) GetName() string { - if o == nil { - return "" - } - return o.Name -} - -func (o *DecisionTask) GetPhaseID() *string { - if o == nil { - return nil - } - return o.PhaseID -} - -func (o *DecisionTask) GetRequirements() []EnableRequirement { - if o == nil { - return nil - } - return o.Requirements -} - -func (o *DecisionTask) GetTaskType() TaskType { - if o == nil { - return TaskType("") - } - return o.TaskType -} - -func (o *DecisionTask) GetTaxonomies() []string { - if o == nil { - return nil - } - return o.Taxonomies -} diff --git a/internal/sdk/models/shared/duedateconfig.go b/internal/sdk/models/shared/duedateconfig.go deleted file mode 100644 index e01cfaf..0000000 --- a/internal/sdk/models/shared/duedateconfig.go +++ /dev/null @@ -1,105 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package shared - -import ( - "encoding/json" - "fmt" -) - -type Type string - -const ( - TypeWorkflowStarted Type = "WORKFLOW_STARTED" - TypeTaskFinished Type = "TASK_FINISHED" -) - -func (e Type) ToPointer() *Type { - return &e -} -func (e *Type) UnmarshalJSON(data []byte) error { - var v string - if err := json.Unmarshal(data, &v); err != nil { - return err - } - switch v { - case "WORKFLOW_STARTED": - fallthrough - case "TASK_FINISHED": - *e = Type(v) - return nil - default: - return fmt.Errorf("invalid value for Type: %v", v) - } -} - -type Unit string - -const ( - UnitMinutes Unit = "minutes" - UnitHours Unit = "hours" - UnitDays Unit = "days" - UnitWeeks Unit = "weeks" - UnitMonths Unit = "months" -) - -func (e Unit) ToPointer() *Unit { - return &e -} -func (e *Unit) UnmarshalJSON(data []byte) error { - var v string - if err := json.Unmarshal(data, &v); err != nil { - return err - } - switch v { - case "minutes": - fallthrough - case "hours": - fallthrough - case "days": - fallthrough - case "weeks": - fallthrough - case "months": - *e = Unit(v) - return nil - default: - return fmt.Errorf("invalid value for Unit: %v", v) - } -} - -// DueDateConfig - Set due date for the task based on a dynamic condition -type DueDateConfig struct { - Duration float64 `json:"duration"` - TaskID *string `json:"task_id,omitempty"` - Type Type `json:"type"` - Unit Unit `json:"unit"` -} - -func (o *DueDateConfig) GetDuration() float64 { - if o == nil { - return 0.0 - } - return o.Duration -} - -func (o *DueDateConfig) GetTaskID() *string { - if o == nil { - return nil - } - return o.TaskID -} - -func (o *DueDateConfig) GetType() Type { - if o == nil { - return Type("") - } - return o.Type -} - -func (o *DueDateConfig) GetUnit() Unit { - if o == nil { - return Unit("") - } - return o.Unit -} diff --git a/internal/sdk/models/shared/dynamicduedate.go b/internal/sdk/models/shared/dynamicduedate.go index 2bc585b..5c6a7e0 100644 --- a/internal/sdk/models/shared/dynamicduedate.go +++ b/internal/sdk/models/shared/dynamicduedate.go @@ -36,11 +36,9 @@ func (e *ActionTypeCondition) UnmarshalJSON(data []byte) error { type TimePeriod string const ( - TimePeriodMinutes TimePeriod = "minutes" - TimePeriodHours TimePeriod = "hours" - TimePeriodDays TimePeriod = "days" - TimePeriodWeeks TimePeriod = "weeks" - TimePeriodMonths TimePeriod = "months" + TimePeriodDays TimePeriod = "days" + TimePeriodWeeks TimePeriod = "weeks" + TimePeriodMonths TimePeriod = "months" ) func (e TimePeriod) ToPointer() *TimePeriod { @@ -52,10 +50,6 @@ func (e *TimePeriod) UnmarshalJSON(data []byte) error { return err } switch v { - case "minutes": - fallthrough - case "hours": - fallthrough case "days": fallthrough case "weeks": diff --git a/internal/sdk/models/shared/edge.go b/internal/sdk/models/shared/edge.go deleted file mode 100644 index 7766ee8..0000000 --- a/internal/sdk/models/shared/edge.go +++ /dev/null @@ -1,38 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package shared - -type Edge struct { - ConditionID *string `json:"condition_id,omitempty"` - FromID string `json:"from_id"` - ID string `json:"id"` - ToID string `json:"to_id"` -} - -func (o *Edge) GetConditionID() *string { - if o == nil { - return nil - } - return o.ConditionID -} - -func (o *Edge) GetFromID() string { - if o == nil { - return "" - } - return o.FromID -} - -func (o *Edge) GetID() string { - if o == nil { - return "" - } - return o.ID -} - -func (o *Edge) GetToID() string { - if o == nil { - return "" - } - return o.ToID -} diff --git a/internal/sdk/models/shared/enablerequirement.go b/internal/sdk/models/shared/enablerequirement.go deleted file mode 100644 index 5285e5a..0000000 --- a/internal/sdk/models/shared/enablerequirement.go +++ /dev/null @@ -1,62 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package shared - -import ( - "encoding/json" - "fmt" -) - -type When string - -const ( - WhenTaskFinished When = "TASK_FINISHED" - WhenPhaseFinished When = "PHASE_FINISHED" -) - -func (e When) ToPointer() *When { - return &e -} -func (e *When) UnmarshalJSON(data []byte) error { - var v string - if err := json.Unmarshal(data, &v); err != nil { - return err - } - switch v { - case "TASK_FINISHED": - fallthrough - case "PHASE_FINISHED": - *e = When(v) - return nil - default: - return fmt.Errorf("invalid value for When: %v", v) - } -} - -// EnableRequirement - describe the requirement for a task to be enabled -type EnableRequirement struct { - PhaseID *string `json:"phase_id,omitempty"` - TaskID *string `json:"task_id,omitempty"` - When When `json:"when"` -} - -func (o *EnableRequirement) GetPhaseID() *string { - if o == nil { - return nil - } - return o.PhaseID -} - -func (o *EnableRequirement) GetTaskID() *string { - if o == nil { - return nil - } - return o.TaskID -} - -func (o *EnableRequirement) GetWhen() When { - if o == nil { - return When("") - } - return o.When -} diff --git a/internal/sdk/models/shared/evaluationsource.go b/internal/sdk/models/shared/evaluationsource.go deleted file mode 100644 index bbdfa9a..0000000 --- a/internal/sdk/models/shared/evaluationsource.go +++ /dev/null @@ -1,243 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package shared - -import ( - "encoding/json" - "fmt" -) - -type AttributeOperation string - -const ( - AttributeOperationAll AttributeOperation = "all" - AttributeOperationUpdated AttributeOperation = "updated" - AttributeOperationAdded AttributeOperation = "added" - AttributeOperationDeleted AttributeOperation = "deleted" -) - -func (e AttributeOperation) ToPointer() *AttributeOperation { - return &e -} -func (e *AttributeOperation) UnmarshalJSON(data []byte) error { - var v string - if err := json.Unmarshal(data, &v); err != nil { - return err - } - switch v { - case "all": - fallthrough - case "updated": - fallthrough - case "added": - fallthrough - case "deleted": - *e = AttributeOperation(v) - return nil - default: - return fmt.Errorf("invalid value for AttributeOperation: %v", v) - } -} - -type AttributeType string - -const ( - AttributeTypeString AttributeType = "string" - AttributeTypeText AttributeType = "text" - AttributeTypeNumber AttributeType = "number" - AttributeTypeBoolean AttributeType = "boolean" - AttributeTypeDate AttributeType = "date" - AttributeTypeDatetime AttributeType = "datetime" - AttributeTypeTags AttributeType = "tags" - AttributeTypeCountry AttributeType = "country" - AttributeTypeEmail AttributeType = "email" - AttributeTypePhone AttributeType = "phone" - AttributeTypeProduct AttributeType = "product" - AttributeTypePrice AttributeType = "price" - AttributeTypeStatus AttributeType = "status" - AttributeTypeRelation AttributeType = "relation" - AttributeTypeMultiselect AttributeType = "multiselect" - AttributeTypeSelect AttributeType = "select" - AttributeTypeRadio AttributeType = "radio" - AttributeTypeRelationUser AttributeType = "relation_user" - AttributeTypePurpose AttributeType = "purpose" - AttributeTypeLabel AttributeType = "label" -) - -func (e AttributeType) ToPointer() *AttributeType { - return &e -} -func (e *AttributeType) UnmarshalJSON(data []byte) error { - var v string - if err := json.Unmarshal(data, &v); err != nil { - return err - } - switch v { - case "string": - fallthrough - case "text": - fallthrough - case "number": - fallthrough - case "boolean": - fallthrough - case "date": - fallthrough - case "datetime": - fallthrough - case "tags": - fallthrough - case "country": - fallthrough - case "email": - fallthrough - case "phone": - fallthrough - case "product": - fallthrough - case "price": - fallthrough - case "status": - fallthrough - case "relation": - fallthrough - case "multiselect": - fallthrough - case "select": - fallthrough - case "radio": - fallthrough - case "relation_user": - fallthrough - case "purpose": - fallthrough - case "label": - *e = AttributeType(v) - return nil - default: - return fmt.Errorf("invalid value for AttributeType: %v", v) - } -} - -type Origin string - -const ( - OriginTrigger Origin = "trigger" - OriginAction Origin = "action" -) - -func (e Origin) ToPointer() *Origin { - return &e -} -func (e *Origin) UnmarshalJSON(data []byte) error { - var v string - if err := json.Unmarshal(data, &v); err != nil { - return err - } - switch v { - case "trigger": - fallthrough - case "action": - *e = Origin(v) - return nil - default: - return fmt.Errorf("invalid value for Origin: %v", v) - } -} - -type OriginType string - -const ( - OriginTypeEntity OriginType = "entity" - OriginTypeWorkflow OriginType = "workflow" - OriginTypeJourneyBlock OriginType = "journey_block" -) - -func (e OriginType) ToPointer() *OriginType { - return &e -} -func (e *OriginType) UnmarshalJSON(data []byte) error { - var v string - if err := json.Unmarshal(data, &v); err != nil { - return err - } - switch v { - case "entity": - fallthrough - case "workflow": - fallthrough - case "journey_block": - *e = OriginType(v) - return nil - default: - return fmt.Errorf("invalid value for OriginType: %v", v) - } -} - -type EvaluationSource struct { - Attribute *string `json:"attribute,omitempty"` - AttributeOperation *AttributeOperation `json:"attribute_operation,omitempty"` - AttributeRepeatable *bool `json:"attribute_repeatable,omitempty"` - AttributeType *AttributeType `json:"attribute_type,omitempty"` - // The id of the action or trigger - ID *string `json:"id,omitempty"` - Origin *Origin `json:"origin,omitempty"` - OriginType *OriginType `json:"origin_type,omitempty"` - Schema *string `json:"schema,omitempty"` -} - -func (o *EvaluationSource) GetAttribute() *string { - if o == nil { - return nil - } - return o.Attribute -} - -func (o *EvaluationSource) GetAttributeOperation() *AttributeOperation { - if o == nil { - return nil - } - return o.AttributeOperation -} - -func (o *EvaluationSource) GetAttributeRepeatable() *bool { - if o == nil { - return nil - } - return o.AttributeRepeatable -} - -func (o *EvaluationSource) GetAttributeType() *AttributeType { - if o == nil { - return nil - } - return o.AttributeType -} - -func (o *EvaluationSource) GetID() *string { - if o == nil { - return nil - } - return o.ID -} - -func (o *EvaluationSource) GetOrigin() *Origin { - if o == nil { - return nil - } - return o.Origin -} - -func (o *EvaluationSource) GetOriginType() *OriginType { - if o == nil { - return nil - } - return o.OriginType -} - -func (o *EvaluationSource) GetSchema() *string { - if o == nil { - return nil - } - return o.Schema -} diff --git a/internal/sdk/models/shared/flowtemplate.go b/internal/sdk/models/shared/flowtemplate.go deleted file mode 100644 index 118ae1f..0000000 --- a/internal/sdk/models/shared/flowtemplate.go +++ /dev/null @@ -1,155 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package shared - -import ( - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/internal/utils" -) - -type FlowTemplate struct { - AssignedTo []string `json:"assigned_to,omitempty"` - // Indicates whether this workflow is available for End Customer Portal or not. By default it's not. - AvailableInEcp *bool `json:"available_in_ecp,omitempty"` - ClosingReasons []ClosingReasonID `json:"closing_reasons,omitempty"` - // ISO String Date & Time - CreatedAt *string `json:"created_at,omitempty"` - Description *string `json:"description,omitempty"` - DueDate *string `json:"due_date,omitempty"` - // Set due date for the task based on a dynamic condition - DynamicDueDate *DueDateConfig `json:"dynamic_due_date,omitempty"` - Edges []Edge `json:"edges"` - // Whether the workflow is enabled or not - Enabled *bool `default:"true" json:"enabled"` - ID *string `json:"id,omitempty"` - Name string `json:"name"` - Phases []Phase `json:"phases,omitempty"` - Tasks []Task `json:"tasks"` - // Taxonomy ids that are associated with this workflow and used for filtering - Taxonomies []string `json:"taxonomies,omitempty"` - UpdateEntityAttributes []UpdateEntityAttributes `json:"update_entity_attributes,omitempty"` - // ISO String Date & Time - UpdatedAt *string `json:"updated_at,omitempty"` -} - -func (f FlowTemplate) MarshalJSON() ([]byte, error) { - return utils.MarshalJSON(f, "", false) -} - -func (f *FlowTemplate) UnmarshalJSON(data []byte) error { - if err := utils.UnmarshalJSON(data, &f, "", false, false); err != nil { - return err - } - return nil -} - -func (o *FlowTemplate) GetAssignedTo() []string { - if o == nil { - return nil - } - return o.AssignedTo -} - -func (o *FlowTemplate) GetAvailableInEcp() *bool { - if o == nil { - return nil - } - return o.AvailableInEcp -} - -func (o *FlowTemplate) GetClosingReasons() []ClosingReasonID { - if o == nil { - return nil - } - return o.ClosingReasons -} - -func (o *FlowTemplate) GetCreatedAt() *string { - if o == nil { - return nil - } - return o.CreatedAt -} - -func (o *FlowTemplate) GetDescription() *string { - if o == nil { - return nil - } - return o.Description -} - -func (o *FlowTemplate) GetDueDate() *string { - if o == nil { - return nil - } - return o.DueDate -} - -func (o *FlowTemplate) GetDynamicDueDate() *DueDateConfig { - if o == nil { - return nil - } - return o.DynamicDueDate -} - -func (o *FlowTemplate) GetEdges() []Edge { - if o == nil { - return []Edge{} - } - return o.Edges -} - -func (o *FlowTemplate) GetEnabled() *bool { - if o == nil { - return nil - } - return o.Enabled -} - -func (o *FlowTemplate) GetID() *string { - if o == nil { - return nil - } - return o.ID -} - -func (o *FlowTemplate) GetName() string { - if o == nil { - return "" - } - return o.Name -} - -func (o *FlowTemplate) GetPhases() []Phase { - if o == nil { - return nil - } - return o.Phases -} - -func (o *FlowTemplate) GetTasks() []Task { - if o == nil { - return []Task{} - } - return o.Tasks -} - -func (o *FlowTemplate) GetTaxonomies() []string { - if o == nil { - return nil - } - return o.Taxonomies -} - -func (o *FlowTemplate) GetUpdateEntityAttributes() []UpdateEntityAttributes { - if o == nil { - return nil - } - return o.UpdateEntityAttributes -} - -func (o *FlowTemplate) GetUpdatedAt() *string { - if o == nil { - return nil - } - return o.UpdatedAt -} diff --git a/internal/sdk/models/shared/flowtemplateslist.go b/internal/sdk/models/shared/flowtemplateslist.go deleted file mode 100644 index bebfa65..0000000 --- a/internal/sdk/models/shared/flowtemplateslist.go +++ /dev/null @@ -1,14 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package shared - -type FlowTemplatesList struct { - Results []FlowTemplate `json:"results"` -} - -func (o *FlowTemplatesList) GetResults() []FlowTemplate { - if o == nil { - return []FlowTemplate{} - } - return o.Results -} diff --git a/internal/sdk/models/shared/itemtype.go b/internal/sdk/models/shared/itemtype.go new file mode 100644 index 0000000..a5c671f --- /dev/null +++ b/internal/sdk/models/shared/itemtype.go @@ -0,0 +1,34 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package shared + +import ( + "encoding/json" + "fmt" +) + +type ItemType string + +const ( + ItemTypeStep ItemType = "STEP" + ItemTypeSection ItemType = "SECTION" +) + +func (e ItemType) ToPointer() *ItemType { + return &e +} +func (e *ItemType) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "STEP": + fallthrough + case "SECTION": + *e = ItemType(v) + return nil + default: + return fmt.Errorf("invalid value for ItemType: %v", v) + } +} diff --git a/internal/sdk/models/shared/operator.go b/internal/sdk/models/shared/operator.go deleted file mode 100644 index bdbbab4..0000000 --- a/internal/sdk/models/shared/operator.go +++ /dev/null @@ -1,70 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package shared - -import ( - "encoding/json" - "fmt" -) - -type Operator string - -const ( - OperatorEquals Operator = "equals" - OperatorNotEquals Operator = "not_equals" - OperatorAnyOf Operator = "any_of" - OperatorNoneOf Operator = "none_of" - OperatorContains Operator = "contains" - OperatorNotContains Operator = "not_contains" - OperatorStartsWith Operator = "starts_with" - OperatorEndsWith Operator = "ends_with" - OperatorGreaterThan Operator = "greater_than" - OperatorLessThan Operator = "less_than" - OperatorGreaterThanOrEquals Operator = "greater_than_or_equals" - OperatorLessThanOrEquals Operator = "less_than_or_equals" - OperatorIsEmpty Operator = "is_empty" - OperatorIsNotEmpty Operator = "is_not_empty" -) - -func (e Operator) ToPointer() *Operator { - return &e -} -func (e *Operator) UnmarshalJSON(data []byte) error { - var v string - if err := json.Unmarshal(data, &v); err != nil { - return err - } - switch v { - case "equals": - fallthrough - case "not_equals": - fallthrough - case "any_of": - fallthrough - case "none_of": - fallthrough - case "contains": - fallthrough - case "not_contains": - fallthrough - case "starts_with": - fallthrough - case "ends_with": - fallthrough - case "greater_than": - fallthrough - case "less_than": - fallthrough - case "greater_than_or_equals": - fallthrough - case "less_than_or_equals": - fallthrough - case "is_empty": - fallthrough - case "is_not_empty": - *e = Operator(v) - return nil - default: - return fmt.Errorf("invalid value for Operator: %v", v) - } -} diff --git a/internal/sdk/models/shared/phase.go b/internal/sdk/models/shared/phase.go deleted file mode 100644 index fcd1c41..0000000 --- a/internal/sdk/models/shared/phase.go +++ /dev/null @@ -1,56 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package shared - -type Phase struct { - AssignedTo []string `json:"assigned_to,omitempty"` - DueDate *string `json:"due_date,omitempty"` - // Set due date for the task based on a dynamic condition - DynamicDueDate *DueDateConfig `json:"dynamic_due_date,omitempty"` - ID string `json:"id"` - Name string `json:"name"` - // Taxonomy ids that are associated with this workflow and used for filtering - Taxonomies []string `json:"taxonomies,omitempty"` -} - -func (o *Phase) GetAssignedTo() []string { - if o == nil { - return nil - } - return o.AssignedTo -} - -func (o *Phase) GetDueDate() *string { - if o == nil { - return nil - } - return o.DueDate -} - -func (o *Phase) GetDynamicDueDate() *DueDateConfig { - if o == nil { - return nil - } - return o.DynamicDueDate -} - -func (o *Phase) GetID() string { - if o == nil { - return "" - } - return o.ID -} - -func (o *Phase) GetName() string { - if o == nil { - return "" - } - return o.Name -} - -func (o *Phase) GetTaxonomies() []string { - if o == nil { - return nil - } - return o.Taxonomies -} diff --git a/internal/sdk/models/shared/section.go b/internal/sdk/models/shared/section.go new file mode 100644 index 0000000..2552ad2 --- /dev/null +++ b/internal/sdk/models/shared/section.go @@ -0,0 +1,47 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package shared + +// Section - A group of Steps that define the progress of the Workflow +type Section struct { + ID *string `json:"id,omitempty"` + Name string `json:"name"` + Order float64 `json:"order"` + Steps []Step `json:"steps"` + Type ItemType `json:"type"` +} + +func (o *Section) GetID() *string { + if o == nil { + return nil + } + return o.ID +} + +func (o *Section) GetName() string { + if o == nil { + return "" + } + return o.Name +} + +func (o *Section) GetOrder() float64 { + if o == nil { + return 0.0 + } + return o.Order +} + +func (o *Section) GetSteps() []Step { + if o == nil { + return []Step{} + } + return o.Steps +} + +func (o *Section) GetType() ItemType { + if o == nil { + return ItemType("") + } + return o.Type +} diff --git a/internal/sdk/models/shared/statement.go b/internal/sdk/models/shared/statement.go deleted file mode 100644 index 46e0b5b..0000000 --- a/internal/sdk/models/shared/statement.go +++ /dev/null @@ -1,38 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package shared - -type Statement struct { - ID string `json:"id"` - Operator Operator `json:"operator"` - Source EvaluationSource `json:"source"` - Values []string `json:"values"` -} - -func (o *Statement) GetID() string { - if o == nil { - return "" - } - return o.ID -} - -func (o *Statement) GetOperator() Operator { - if o == nil { - return Operator("") - } - return o.Operator -} - -func (o *Statement) GetSource() EvaluationSource { - if o == nil { - return EvaluationSource{} - } - return o.Source -} - -func (o *Statement) GetValues() []string { - if o == nil { - return []string{} - } - return o.Values -} diff --git a/internal/sdk/models/shared/step.go b/internal/sdk/models/shared/step.go new file mode 100644 index 0000000..f4ec993 --- /dev/null +++ b/internal/sdk/models/shared/step.go @@ -0,0 +1,147 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package shared + +type AutomationConfig struct { + // Id of the configured automation to run + FlowID string `json:"flowId"` +} + +func (o *AutomationConfig) GetFlowID() string { + if o == nil { + return "" + } + return o.FlowID +} + +// Step - Action that needs to be done in a Workflow +type Step struct { + AssignedTo []string `json:"assignedTo,omitempty"` + AutomationConfig *AutomationConfig `json:"automationConfig,omitempty"` + // Longer information regarding Task + Description *StepDescription `json:"description,omitempty"` + DueDate *string `json:"dueDate,omitempty"` + // set a Duedate for a step then a specific + DynamicDueDate *DynamicDueDate `json:"dynamicDueDate,omitempty"` + // Details regarding ECP for the workflow step + Ecp *ECPDetails `json:"ecp,omitempty"` + ExecutionType *StepType `json:"executionType,omitempty"` + ID *string `json:"id,omitempty"` + // Details regarding ECP for the workflow step + Installer *ECPDetails `json:"installer,omitempty"` + Journey *StepJourney `json:"journey,omitempty"` + Name string `json:"name"` + Order float64 `json:"order"` + // requirements that need to be fulfilled in order to enable the step execution + Requirements []StepRequirement `json:"requirements,omitempty"` + Type ItemType `json:"type"` + // This field is deprecated. Please use assignedTo + // + // Deprecated field: This will be removed in a future release, please migrate away from it as soon as possible. + UserIds []float64 `json:"userIds,omitempty"` +} + +func (o *Step) GetAssignedTo() []string { + if o == nil { + return nil + } + return o.AssignedTo +} + +func (o *Step) GetAutomationConfig() *AutomationConfig { + if o == nil { + return nil + } + return o.AutomationConfig +} + +func (o *Step) GetDescription() *StepDescription { + if o == nil { + return nil + } + return o.Description +} + +func (o *Step) GetDueDate() *string { + if o == nil { + return nil + } + return o.DueDate +} + +func (o *Step) GetDynamicDueDate() *DynamicDueDate { + if o == nil { + return nil + } + return o.DynamicDueDate +} + +func (o *Step) GetEcp() *ECPDetails { + if o == nil { + return nil + } + return o.Ecp +} + +func (o *Step) GetExecutionType() *StepType { + if o == nil { + return nil + } + return o.ExecutionType +} + +func (o *Step) GetID() *string { + if o == nil { + return nil + } + return o.ID +} + +func (o *Step) GetInstaller() *ECPDetails { + if o == nil { + return nil + } + return o.Installer +} + +func (o *Step) GetJourney() *StepJourney { + if o == nil { + return nil + } + return o.Journey +} + +func (o *Step) GetName() string { + if o == nil { + return "" + } + return o.Name +} + +func (o *Step) GetOrder() float64 { + if o == nil { + return 0.0 + } + return o.Order +} + +func (o *Step) GetRequirements() []StepRequirement { + if o == nil { + return nil + } + return o.Requirements +} + +func (o *Step) GetType() ItemType { + if o == nil { + return ItemType("") + } + return o.Type +} + +func (o *Step) GetUserIds() []float64 { + if o == nil { + return nil + } + return o.UserIds +} diff --git a/internal/sdk/models/shared/steprequirement.go b/internal/sdk/models/shared/steprequirement.go new file mode 100644 index 0000000..1d58fd4 --- /dev/null +++ b/internal/sdk/models/shared/steprequirement.go @@ -0,0 +1,59 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package shared + +import ( + "encoding/json" + "fmt" +) + +type Condition string + +const ( + ConditionClosed Condition = "CLOSED" +) + +func (e Condition) ToPointer() *Condition { + return &e +} +func (e *Condition) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "CLOSED": + *e = Condition(v) + return nil + default: + return fmt.Errorf("invalid value for Condition: %v", v) + } +} + +// StepRequirement - describe the requirement for step enablement +type StepRequirement struct { + Condition Condition `json:"condition"` + DefinitionID string `json:"definitionId"` + Type ItemType `json:"type"` +} + +func (o *StepRequirement) GetCondition() Condition { + if o == nil { + return Condition("") + } + return o.Condition +} + +func (o *StepRequirement) GetDefinitionID() string { + if o == nil { + return "" + } + return o.DefinitionID +} + +func (o *StepRequirement) GetType() ItemType { + if o == nil { + return ItemType("") + } + return o.Type +} diff --git a/internal/sdk/models/shared/steptype.go b/internal/sdk/models/shared/steptype.go new file mode 100644 index 0000000..e76cf9b --- /dev/null +++ b/internal/sdk/models/shared/steptype.go @@ -0,0 +1,34 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package shared + +import ( + "encoding/json" + "fmt" +) + +type StepType string + +const ( + StepTypeManual StepType = "MANUAL" + StepTypeAutomation StepType = "AUTOMATION" +) + +func (e StepType) ToPointer() *StepType { + return &e +} +func (e *StepType) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "MANUAL": + fallthrough + case "AUTOMATION": + *e = StepType(v) + return nil + default: + return fmt.Errorf("invalid value for StepType: %v", v) + } +} diff --git a/internal/sdk/models/shared/task.go b/internal/sdk/models/shared/task.go deleted file mode 100644 index 5516ce2..0000000 --- a/internal/sdk/models/shared/task.go +++ /dev/null @@ -1,94 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package shared - -import ( - "errors" - "fmt" - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/internal/utils" -) - -type TaskUnionType string - -const ( - TaskUnionTypeTaskBase TaskUnionType = "TaskBase" - TaskUnionTypeAutomationTask TaskUnionType = "AutomationTask" - TaskUnionTypeDecisionTask TaskUnionType = "DecisionTask" -) - -type Task struct { - TaskBase *TaskBase - AutomationTask *AutomationTask - DecisionTask *DecisionTask - - Type TaskUnionType -} - -func CreateTaskTaskBase(taskBase TaskBase) Task { - typ := TaskUnionTypeTaskBase - - return Task{ - TaskBase: &taskBase, - Type: typ, - } -} - -func CreateTaskAutomationTask(automationTask AutomationTask) Task { - typ := TaskUnionTypeAutomationTask - - return Task{ - AutomationTask: &automationTask, - Type: typ, - } -} - -func CreateTaskDecisionTask(decisionTask DecisionTask) Task { - typ := TaskUnionTypeDecisionTask - - return Task{ - DecisionTask: &decisionTask, - Type: typ, - } -} - -func (u *Task) UnmarshalJSON(data []byte) error { - - var taskBase TaskBase = TaskBase{} - if err := utils.UnmarshalJSON(data, &taskBase, "", true, true); err == nil { - u.TaskBase = &taskBase - u.Type = TaskUnionTypeTaskBase - return nil - } - - var automationTask AutomationTask = AutomationTask{} - if err := utils.UnmarshalJSON(data, &automationTask, "", true, true); err == nil { - u.AutomationTask = &automationTask - u.Type = TaskUnionTypeAutomationTask - return nil - } - - var decisionTask DecisionTask = DecisionTask{} - if err := utils.UnmarshalJSON(data, &decisionTask, "", true, true); err == nil { - u.DecisionTask = &decisionTask - u.Type = TaskUnionTypeDecisionTask - return nil - } - - return fmt.Errorf("could not unmarshal `%s` into any supported union types for Task", string(data)) -} - -func (u Task) MarshalJSON() ([]byte, error) { - if u.TaskBase != nil { - return utils.MarshalJSON(u.TaskBase, "", true) - } - - if u.AutomationTask != nil { - return utils.MarshalJSON(u.AutomationTask, "", true) - } - - if u.DecisionTask != nil { - return utils.MarshalJSON(u.DecisionTask, "", true) - } - - return nil, errors.New("could not marshal union type Task: all fields are null") -} diff --git a/internal/sdk/models/shared/taskbase.go b/internal/sdk/models/shared/taskbase.go deleted file mode 100644 index 68756e0..0000000 --- a/internal/sdk/models/shared/taskbase.go +++ /dev/null @@ -1,116 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package shared - -type TaskBase struct { - AssignedTo []string `json:"assigned_to,omitempty"` - // Longer information regarding Task - Description *StepDescription `json:"description,omitempty"` - DueDate *string `json:"due_date,omitempty"` - // Set due date for the task based on a dynamic condition - DynamicDueDate *DueDateConfig `json:"dynamic_due_date,omitempty"` - // Details regarding ECP for the workflow step - Ecp *ECPDetails `json:"ecp,omitempty"` - ID string `json:"id"` - // Details regarding ECP for the workflow step - Installer *ECPDetails `json:"installer,omitempty"` - Journey *StepJourney `json:"journey,omitempty"` - Name string `json:"name"` - PhaseID *string `json:"phase_id,omitempty"` - // requirements that need to be fulfilled in order to enable the task while flow instances are running - Requirements []EnableRequirement `json:"requirements,omitempty"` - TaskType TaskType `json:"task_type"` - // Taxonomy ids that are associated with this workflow and used for filtering - Taxonomies []string `json:"taxonomies,omitempty"` -} - -func (o *TaskBase) GetAssignedTo() []string { - if o == nil { - return nil - } - return o.AssignedTo -} - -func (o *TaskBase) GetDescription() *StepDescription { - if o == nil { - return nil - } - return o.Description -} - -func (o *TaskBase) GetDueDate() *string { - if o == nil { - return nil - } - return o.DueDate -} - -func (o *TaskBase) GetDynamicDueDate() *DueDateConfig { - if o == nil { - return nil - } - return o.DynamicDueDate -} - -func (o *TaskBase) GetEcp() *ECPDetails { - if o == nil { - return nil - } - return o.Ecp -} - -func (o *TaskBase) GetID() string { - if o == nil { - return "" - } - return o.ID -} - -func (o *TaskBase) GetInstaller() *ECPDetails { - if o == nil { - return nil - } - return o.Installer -} - -func (o *TaskBase) GetJourney() *StepJourney { - if o == nil { - return nil - } - return o.Journey -} - -func (o *TaskBase) GetName() string { - if o == nil { - return "" - } - return o.Name -} - -func (o *TaskBase) GetPhaseID() *string { - if o == nil { - return nil - } - return o.PhaseID -} - -func (o *TaskBase) GetRequirements() []EnableRequirement { - if o == nil { - return nil - } - return o.Requirements -} - -func (o *TaskBase) GetTaskType() TaskType { - if o == nil { - return TaskType("") - } - return o.TaskType -} - -func (o *TaskBase) GetTaxonomies() []string { - if o == nil { - return nil - } - return o.Taxonomies -} diff --git a/internal/sdk/models/shared/tasktype.go b/internal/sdk/models/shared/tasktype.go deleted file mode 100644 index e5d94ba..0000000 --- a/internal/sdk/models/shared/tasktype.go +++ /dev/null @@ -1,37 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package shared - -import ( - "encoding/json" - "fmt" -) - -type TaskType string - -const ( - TaskTypeManual TaskType = "MANUAL" - TaskTypeAutomation TaskType = "AUTOMATION" - TaskTypeDecision TaskType = "DECISION" -) - -func (e TaskType) ToPointer() *TaskType { - return &e -} -func (e *TaskType) UnmarshalJSON(data []byte) error { - var v string - if err := json.Unmarshal(data, &v); err != nil { - return err - } - switch v { - case "MANUAL": - fallthrough - case "AUTOMATION": - fallthrough - case "DECISION": - *e = TaskType(v) - return nil - default: - return fmt.Errorf("invalid value for TaskType: %v", v) - } -} diff --git a/internal/sdk/models/shared/workflowdefinition.go b/internal/sdk/models/shared/workflowdefinition.go index fe1090f..1207c29 100644 --- a/internal/sdk/models/shared/workflowdefinition.go +++ b/internal/sdk/models/shared/workflowdefinition.go @@ -3,9 +3,74 @@ package shared import ( + "errors" + "fmt" "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/internal/utils" ) +type FlowType string + +const ( + FlowTypeSection FlowType = "Section" + FlowTypeStep FlowType = "Step" +) + +type Flow struct { + Section *Section + Step *Step + + Type FlowType +} + +func CreateFlowSection(section Section) Flow { + typ := FlowTypeSection + + return Flow{ + Section: §ion, + Type: typ, + } +} + +func CreateFlowStep(step Step) Flow { + typ := FlowTypeStep + + return Flow{ + Step: &step, + Type: typ, + } +} + +func (u *Flow) UnmarshalJSON(data []byte) error { + + var section Section = Section{} + if err := utils.UnmarshalJSON(data, §ion, "", true, true); err == nil { + u.Section = §ion + u.Type = FlowTypeSection + return nil + } + + var step Step = Step{} + if err := utils.UnmarshalJSON(data, &step, "", true, true); err == nil { + u.Step = &step + u.Type = FlowTypeStep + return nil + } + + return fmt.Errorf("could not unmarshal `%s` into any supported union types for Flow", string(data)) +} + +func (u Flow) MarshalJSON() ([]byte, error) { + if u.Section != nil { + return utils.MarshalJSON(u.Section, "", true) + } + + if u.Step != nil { + return utils.MarshalJSON(u.Step, "", true) + } + + return nil, errors.New("could not marshal union type Flow: all fields are null") +} + type WorkflowDefinition struct { AssignedTo []string `json:"assignedTo,omitempty"` ClosingReasons []ClosingReasonID `json:"closingReasons,omitempty"` @@ -16,16 +81,12 @@ type WorkflowDefinition struct { // set a Duedate for a step then a specific DynamicDueDate *DynamicDueDate `json:"dynamicDueDate,omitempty"` // Indicates whether this workflow is available for End Customer Portal or not. By default it's not. - EnableECPWorkflow *bool `json:"enableECPWorkflow,omitempty"` - // Whether the workflow is enabled or not - Enabled *bool `default:"true" json:"enabled"` - Flow any `json:"flow"` - ID *string `json:"id,omitempty"` + EnableECPWorkflow *bool `json:"enableECPWorkflow,omitempty"` + Flow []Flow `json:"flow"` + ID *string `json:"id,omitempty"` // ISO String Date & Time - LastUpdateTime *string `json:"lastUpdateTime,omitempty"` - Name string `json:"name"` - // Taxonomy ids that are associated with this workflow and used for filtering - Taxonomies []string `json:"taxonomies,omitempty"` + LastUpdateTime *string `json:"lastUpdateTime,omitempty"` + Name string `json:"name"` UpdateEntityAttributes []UpdateEntityAttributes `json:"updateEntityAttributes,omitempty"` // This field is deprecated. Please use assignedTo // @@ -33,17 +94,6 @@ type WorkflowDefinition struct { UserIds []float64 `json:"userIds,omitempty"` } -func (w WorkflowDefinition) MarshalJSON() ([]byte, error) { - return utils.MarshalJSON(w, "", false) -} - -func (w *WorkflowDefinition) UnmarshalJSON(data []byte) error { - if err := utils.UnmarshalJSON(data, &w, "", false, false); err != nil { - return err - } - return nil -} - func (o *WorkflowDefinition) GetAssignedTo() []string { if o == nil { return nil @@ -93,16 +143,9 @@ func (o *WorkflowDefinition) GetEnableECPWorkflow() *bool { return o.EnableECPWorkflow } -func (o *WorkflowDefinition) GetEnabled() *bool { +func (o *WorkflowDefinition) GetFlow() []Flow { if o == nil { - return nil - } - return o.Enabled -} - -func (o *WorkflowDefinition) GetFlow() any { - if o == nil { - return nil + return []Flow{} } return o.Flow } @@ -128,13 +171,6 @@ func (o *WorkflowDefinition) GetName() string { return o.Name } -func (o *WorkflowDefinition) GetTaxonomies() []string { - if o == nil { - return nil - } - return o.Taxonomies -} - func (o *WorkflowDefinition) GetUpdateEntityAttributes() []UpdateEntityAttributes { if o == nil { return nil diff --git a/internal/sdk/retry/config.go b/internal/sdk/retry/config.go index c051b0a..aa4b334 100644 --- a/internal/sdk/retry/config.go +++ b/internal/sdk/retry/config.go @@ -2,6 +2,15 @@ package retry +import ( + "errors" + "net/http" + "strconv" + "time" +) + +// BackoffStrategy defines the parameters for exponential backoff. This can be +// used to drive a retry loop for example. type BackoffStrategy struct { InitialInterval int MaxInterval int @@ -9,8 +18,128 @@ type BackoffStrategy struct { MaxElapsedTime int } +// Config configures a retry policy. type Config struct { Strategy string Backoff *BackoffStrategy RetryConnectionErrors bool } + +// PermanentError is an error that signals that some operation has terminally +// failed and should not be retried. +type PermanentError struct { + cause error +} + +// Permanent creates a PermanentError that signals to a retry loop that it +// should stop retrying an operation and return the underlying error. +func Permanent(cause error) error { + if IsPermanentError(cause) { + return cause + } + + return &PermanentError{ + cause: cause, + } +} + +func (e *PermanentError) Error() string { + return e.cause.Error() +} + +func (e *PermanentError) Unwrap() error { + return e.cause +} + +// TemporaryError represents a retryable error and signals to a retry loop that +// an operation may be retried with an optional wait interval. +type TemporaryError struct { + wait time.Duration + message string +} + +// Temporary creates a TemporaryError that signals to a retry loop that an +// operation can be retried. The error may also carry details about how long to +// wait before retrying. This wait interval may be used to override the retry +// policy in use. +func Temporary(message string) error { + return &TemporaryError{ + message: message, + } +} + +// TemporaryFromResponse creates a TemporaryError similar to Temporary but +// additionally parses the Retry-After header from a response to determine the +// wait interval before the next retry attempt. +func TemporaryFromResponse(message string, res *http.Response) error { + return &TemporaryError{ + wait: retryIntervalFromResponse(res), + message: message, + } +} + +func (e *TemporaryError) Error() string { + return e.message +} + +// RetryAfter returns the time to wait before retrying the request. The zero +// value should be interpreted by retry loops to mean they should fallback on +// their default policy whether expenonential, constant backoff or something +// else. It does not mean that an operation should be retried immediately. +func (e *TemporaryError) RetryAfter() time.Duration { + return e.wait +} + +func retryIntervalFromResponse(res *http.Response) time.Duration { + if res == nil { + return 0 + } + + retryVal := res.Header.Get("retry-after") + if retryVal == "" { + return 0 + } + + parsedNumber, err := strconv.ParseInt(retryVal, 10, 64) + if err == nil { + if parsedNumber < 0 { + return 0 + } else { + return time.Duration(parsedNumber) * time.Second + } + } + + parsedDate, err := time.Parse(time.RFC1123, retryVal) + if err == nil { + delta := parsedDate.Sub(time.Now()) + if delta < 0 { + return 0 + } else { + return delta + } + } + + return 0 +} + +// IsPermanentError returns true if an error value is or contains a +// PermanentError in its chain of errors. +func IsPermanentError(err error) bool { + if err == nil { + return false + } + + var pe *PermanentError + return errors.As(err, &pe) +} + +// IsTemporaryError returns true if an error value is or contains a +// TemporaryError in its chain of errors. +func IsTemporaryError(err error) bool { + if err == nil { + return false + } + + var pe *TemporaryError + return errors.As(err, &pe) +} diff --git a/internal/sdk/sdk.go b/internal/sdk/sdk.go index e4e4c9b..3c35f6d 100644 --- a/internal/sdk/sdk.go +++ b/internal/sdk/sdk.go @@ -71,7 +71,6 @@ func (c *sdkConfiguration) GetServerDetails() (string, map[string]string) { type SDK struct { ClosingReason *ClosingReason Workflows *Workflows - FlowsV2 *FlowsV2 sdkConfiguration sdkConfiguration } @@ -150,8 +149,8 @@ func New(opts ...SDKOption) *SDK { Language: "go", OpenAPIDocVersion: "1.0.0", SDKVersion: "0.0.1", - GenVersion: "2.438.15", - UserAgent: "speakeasy-sdk/go 0.0.1 2.438.15 1.0.0 github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk", + GenVersion: "2.467.4", + UserAgent: "speakeasy-sdk/go 0.0.1 2.467.4 1.0.0 github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk", Hooks: hooks.New(), }, } @@ -175,7 +174,5 @@ func New(opts ...SDKOption) *SDK { sdk.Workflows = newWorkflows(sdk.sdkConfiguration) - sdk.FlowsV2 = newFlowsV2(sdk.sdkConfiguration) - return sdk } diff --git a/internal/sdk/workflows.go b/internal/sdk/workflows.go index 58aab7a..913ccab 100644 --- a/internal/sdk/workflows.go +++ b/internal/sdk/workflows.go @@ -6,13 +6,11 @@ import ( "bytes" "context" "fmt" - "github.com/cenkalti/backoff/v4" "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/internal/hooks" "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/internal/utils" "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/models/errors" "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/models/operations" "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/models/shared" - "github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk/retry" "net/http" "net/url" ) @@ -39,7 +37,6 @@ func (s *Workflows) CreateDefinition(ctx context.Context, request shared.Workflo o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -83,94 +80,32 @@ func (s *Workflows) CreateDefinition(ctx context.Context, request shared.Workflo return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { if err != nil { - return nil, err + err = fmt.Errorf("error sending request: %w", err) } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + err = fmt.Errorf("error sending request: no response") } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err + } else if _httpRes != nil { + httpRes = _httpRes } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } } } @@ -181,7 +116,7 @@ func (s *Workflows) CreateDefinition(ctx context.Context, request shared.Workflo } switch { - case httpRes.StatusCode == 201: + case httpRes.StatusCode == 200: switch { case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): rawBody, err := utils.ConsumeRawBody(httpRes) @@ -251,7 +186,6 @@ func (s *Workflows) DeleteDefinition(ctx context.Context, request operations.Del o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -289,95 +223,33 @@ func (s *Workflows) DeleteDefinition(ctx context.Context, request operations.Del return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) + } else { + err = fmt.Errorf("error sending request: no response") + } + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + } else if _httpRes != nil { + httpRes = _httpRes } } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) if err != nil { return nil, err } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } - } } res := &operations.DeleteDefinitionResponse{ @@ -435,7 +307,6 @@ func (s *Workflows) GetDefinition(ctx context.Context, request operations.GetDef o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -473,94 +344,32 @@ func (s *Workflows) GetDefinition(ctx context.Context, request operations.GetDef return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { if err != nil { - return nil, err + err = fmt.Errorf("error sending request: %w", err) } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + err = fmt.Errorf("error sending request: no response") } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err + } else if _httpRes != nil { + httpRes = _httpRes } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } } } @@ -662,7 +471,6 @@ func (s *Workflows) GetDefinitions(ctx context.Context, opts ...operations.Optio o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -700,94 +508,32 @@ func (s *Workflows) GetDefinitions(ctx context.Context, opts ...operations.Optio return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { if err != nil { - return nil, err + err = fmt.Errorf("error sending request: %w", err) } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + err = fmt.Errorf("error sending request: no response") } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err + } else if _httpRes != nil { + httpRes = _httpRes } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } } } @@ -864,7 +610,6 @@ func (s *Workflows) GetMaxAllowedLimit(ctx context.Context, opts ...operations.O o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -902,94 +647,32 @@ func (s *Workflows) GetMaxAllowedLimit(ctx context.Context, opts ...operations.O return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { if err != nil { - return nil, err + err = fmt.Errorf("error sending request: %w", err) } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + err = fmt.Errorf("error sending request: no response") } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err + } else if _httpRes != nil { + httpRes = _httpRes } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } } } @@ -1066,7 +749,6 @@ func (s *Workflows) GetWorkflowClosingReasons(ctx context.Context, request opera o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -1104,94 +786,32 @@ func (s *Workflows) GetWorkflowClosingReasons(ctx context.Context, request opera return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { if err != nil { - return nil, err + err = fmt.Errorf("error sending request: %w", err) } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + err = fmt.Errorf("error sending request: no response") } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err + } else if _httpRes != nil { + httpRes = _httpRes } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } } } @@ -1247,7 +867,6 @@ func (s *Workflows) SetWorkflowClosingReasons(ctx context.Context, request opera o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -1291,94 +910,32 @@ func (s *Workflows) SetWorkflowClosingReasons(ctx context.Context, request opera return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { if err != nil { - return nil, err + err = fmt.Errorf("error sending request: %w", err) } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + err = fmt.Errorf("error sending request: no response") } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err + } else if _httpRes != nil { + httpRes = _httpRes } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } } } @@ -1414,7 +971,6 @@ func (s *Workflows) UpdateDefinition(ctx context.Context, request operations.Upd o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -1458,94 +1014,32 @@ func (s *Workflows) UpdateDefinition(ctx context.Context, request operations.Upd return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { if err != nil { - return nil, err + err = fmt.Errorf("error sending request: %w", err) } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + err = fmt.Errorf("error sending request: no response") } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err + } else if _httpRes != nil { + httpRes = _httpRes } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } } }