diff --git a/.speakeasy/gen.lock b/.speakeasy/gen.lock index 6ca39b4..76dc9f3 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: 8cca425d43827206f136d897f6b6d971 + docChecksum: 8a2ff4be25db818a35891d602baa4a25 docVersion: 1.0.0 - speakeasyVersion: 1.366.0 - generationVersion: 2.396.0 - releaseVersion: 0.16.0 - configChecksum: 074bf36ec11af180d6bf31a5857355fd + speakeasyVersion: 1.462.2 + generationVersion: 2.486.1 + releaseVersion: 0.17.0 + configChecksum: 1d514357e5b57e5c61c905d7e9caa121 repoURL: https://github.com/epilot-dev/terraform-provider-epilot-workflow.git repoSubDirectory: . published: true @@ -21,97 +21,18 @@ features: unions: 2.85.0 terraform: additionalDependencies: 0.1.0 - constsAndDefaults: 0.1.4 - core: 3.24.6 + core: 3.27.6 deprecations: 2.81.1 envVarSecurityUsage: 0.1.0 - globalSecurity: 2.81.8 + globalSecurity: 2.81.9 globalServerURLs: 2.82.1 - inputOutputModels: 2.83.0 - retries: 2.81.1 - typeOverrides: 2.81.1 - unions: 2.81.16 + unions: 2.81.17 generatedFiles: - - internal/sdk/closingreason.go - - internal/sdk/workflows.go - - internal/sdk/flowsv2.go - - internal/sdk/sdk.go - - internal/sdk/models/errors/sdkerror.go - - internal/sdk/retry/config.go - - internal/sdk/types/bigint.go - - internal/sdk/types/date.go - - internal/sdk/types/datetime.go - - internal/sdk/types/decimal.go - - internal/sdk/types/pointers.go - - internal/sdk/internal/utils/contenttype.go - - internal/sdk/internal/utils/form.go - - internal/sdk/internal/utils/headers.go - - internal/sdk/internal/utils/json.go - - internal/sdk/internal/utils/pathparams.go - - internal/sdk/internal/utils/queryparams.go - - internal/sdk/internal/utils/requestbody.go - - internal/sdk/internal/utils/retries.go - - internal/sdk/internal/utils/security.go - - internal/sdk/internal/utils/utils.go - - internal/sdk/models/operations/changereasonstatus.go - - internal/sdk/models/operations/createclosingreason.go - - internal/sdk/models/operations/deleteclosingreason.go - - internal/sdk/models/operations/getallclosingreasons.go - - internal/sdk/models/operations/getclosingreason.go - - internal/sdk/models/operations/getclosingreasonv1.go - - internal/sdk/models/operations/updateclosingreason.go - - internal/sdk/models/operations/createdefinition.go - - internal/sdk/models/operations/deletedefinition.go - - internal/sdk/models/operations/getdefinition.go - - internal/sdk/models/operations/getdefinitions.go - - internal/sdk/models/operations/getmaxallowedlimit.go - - internal/sdk/models/operations/getworkflowclosingreasons.go - - internal/sdk/models/operations/setworkflowclosingreasons.go - - internal/sdk/models/operations/updatedefinition.go - - internal/sdk/models/operations/createflowtemplate.go - - internal/sdk/models/operations/deleteflowtemplate.go - - internal/sdk/models/operations/getflowtemplate.go - - internal/sdk/models/operations/listflowtemplates.go - - internal/sdk/models/operations/updateflowtemplate.go - - internal/sdk/models/shared/errorresp.go - - internal/sdk/models/shared/changereasonstatusreq.go - - internal/sdk/models/shared/closingreasonsstatus.go - - internal/sdk/models/shared/closingreason.go - - internal/sdk/models/shared/closingreasoninput.go - - internal/sdk/models/shared/closingreasonnotfoundresp.go - - internal/sdk/models/shared/closingreasons.go - - internal/sdk/models/shared/workflowdefinition.go - - internal/sdk/models/shared/updateentityattributes.go - - internal/sdk/models/shared/dynamicduedate.go - - internal/sdk/models/shared/closingreasonid.go - - internal/sdk/models/shared/definitionnotfoundresp.go - - internal/sdk/models/shared/maxallowedlimit.go - - internal/sdk/models/shared/closingreasonsids.go - - internal/sdk/models/shared/flowtemplate.go - - internal/sdk/models/shared/task.go - - internal/sdk/models/shared/taskbase.go - - internal/sdk/models/shared/tasktype.go - - internal/sdk/models/shared/enablerequirement.go - - internal/sdk/models/shared/stepjourney.go - - internal/sdk/models/shared/ecpdetails.go - - internal/sdk/models/shared/duedateconfig.go - - internal/sdk/models/shared/stepdescription.go - - internal/sdk/models/shared/automationtask.go - - internal/sdk/models/shared/decisiontask.go - - internal/sdk/models/shared/condition.go - - internal/sdk/models/shared/statement.go - - internal/sdk/models/shared/evaluationsource.go - - internal/sdk/models/shared/operator.go - - internal/sdk/models/shared/phase.go - - internal/sdk/models/shared/edge.go - - internal/sdk/models/shared/flowtemplateslist.go - - internal/sdk/models/shared/security.go - - internal/sdk/.gitignore - - internal/sdk/models/operations/options.go - - internal/sdk/.gitattributes - - internal/sdk/internal/hooks/hooks.go - - internal/sdk/CONTRIBUTING.md + - .gitattributes + - CONTRIBUTING.md + - USAGE.md - examples/README.md + - examples/provider/provider.tf - go.mod - go.sum - internal/planmodifiers/boolplanmodifier/suppress_diff.go @@ -124,6 +45,7 @@ generatedFiles: - internal/planmodifiers/setplanmodifier/suppress_diff.go - internal/planmodifiers/stringplanmodifier/suppress_diff.go - internal/planmodifiers/utils/state_check.go + - internal/provider/provider.go - internal/provider/reflect/diags.go - internal/provider/reflect/doc.go - internal/provider/reflect/generic_attr_value.go @@ -139,6 +61,64 @@ generatedFiles: - internal/provider/reflect/slice.go - internal/provider/reflect/struct.go - internal/provider/utils.go + - internal/sdk/.gitattributes + - internal/sdk/.gitignore + - internal/sdk/CONTRIBUTING.md + - internal/sdk/closingreason.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 + - internal/sdk/internal/utils/pathparams.go + - internal/sdk/internal/utils/queryparams.go + - internal/sdk/internal/utils/requestbody.go + - internal/sdk/internal/utils/retries.go + - internal/sdk/internal/utils/security.go + - internal/sdk/internal/utils/utils.go + - internal/sdk/models/errors/sdkerror.go + - internal/sdk/models/operations/changereasonstatus.go + - internal/sdk/models/operations/createclosingreason.go + - internal/sdk/models/operations/createdefinition.go + - internal/sdk/models/operations/deletedefinition.go + - internal/sdk/models/operations/getallclosingreasons.go + - internal/sdk/models/operations/getdefinition.go + - internal/sdk/models/operations/getdefinitions.go + - internal/sdk/models/operations/getmaxallowedlimit.go + - internal/sdk/models/operations/getworkflowclosingreasons.go + - internal/sdk/models/operations/options.go + - internal/sdk/models/operations/setworkflowclosingreasons.go + - internal/sdk/models/operations/updatedefinition.go + - internal/sdk/models/shared/changereasonstatusreq.go + - internal/sdk/models/shared/closingreason.go + - internal/sdk/models/shared/closingreasonid.go + - internal/sdk/models/shared/closingreasons.go + - internal/sdk/models/shared/closingreasonsids.go + - internal/sdk/models/shared/closingreasonsstatus.go + - internal/sdk/models/shared/definitionnotfoundresp.go + - internal/sdk/models/shared/dynamicduedate.go + - internal/sdk/models/shared/ecpdetails.go + - internal/sdk/models/shared/errorresp.go + - internal/sdk/models/shared/itemtype.go + - internal/sdk/models/shared/maxallowedlimit.go + - internal/sdk/models/shared/section.go + - internal/sdk/models/shared/security.go + - internal/sdk/models/shared/step.go + - internal/sdk/models/shared/stepdescription.go + - internal/sdk/models/shared/stepjourney.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 + - internal/sdk/sdk.go + - internal/sdk/types/bigint.go + - internal/sdk/types/date.go + - internal/sdk/types/datetime.go + - internal/sdk/types/decimal.go + - internal/sdk/types/pointers.go + - internal/sdk/workflows.go - internal/validators/DateValidator.go - internal/validators/ExactlyOneChild.go - internal/validators/JSONParseValidator.go @@ -155,141 +135,29 @@ generatedFiles: - main.go - terraform-registry-manifest.json - tools/tools.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 - - USAGE.md - - internal/provider/provider.go - - examples/provider/provider.tf - - examples/resources/epilot-workflow_closing_reason/import.sh - - internal/provider/closingreason_resource.go - - internal/provider/closingreason_resource_sdk.go - - examples/resources/epilot-workflow_closing_reason/resource.tf - - examples/resources/epilot-workflow_workflow_definition/import.sh - - internal/provider/workflowdefinition_resource.go - - internal/provider/workflowdefinition_resource_sdk.go - - examples/resources/epilot-workflow_workflow_definition/resource.tf - - internal/provider/closingreason_data_source.go - - internal/provider/closingreason_data_source_sdk.go - - examples/data-sources/epilot-workflow_closing_reason/data-source.tf - - internal/provider/workflowdefinition_data_source.go - - internal/provider/workflowdefinition_data_source_sdk.go - - examples/data-sources/epilot-workflow_workflow_definition/data-source.tf - - .gitattributes - - CONTRIBUTING.md examples: changeReasonStatus: speakeasy-default-change-reason-status: parameters: path: - reasonId: + reasonId: "" + responses: + "400": + application/json: {} createClosingReason: "": requestBody: - application/json: - status: ACTIVE - title: better offer + application/json: {"status": "ACTIVE", "title": "better offer"} responses: "201": - application/json: - status: INACTIVE - title: + application/json: {"status": "INACTIVE", "title": ""} 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 - 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 + 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 - 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: [] + 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: @@ -432,7 +300,7 @@ examples: "": parameters: path: - definitionId: CustomerRequest + definitionId: "CustomerRequest" deleteFlowTemplate: speakeasy-default-delete-flow-template: parameters: @@ -445,10 +313,7 @@ examples: includeInactive: true responses: "200": - application/json: - reasons: - - status: ACTIVE - title: + application/json: {"reasons": [{"status": "ACTIVE", "title": ""}]} getClosingReason: "": parameters: @@ -466,114 +331,15 @@ examples: "": parameters: path: - definitionId: 7hj28a + 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 - 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 + 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 - 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 - 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"}] getFlowTemplate: speakeasy-default-get-flow-template: parameters: @@ -600,21 +366,15 @@ examples: "": responses: "200": - application/json: - currentNoOfWorkflows: 5 - maxAllowed: 7 + application/json: {"currentNoOfWorkflows": 5, "maxAllowed": 7} getWorkflowClosingReasons: "": parameters: path: - definitionId: fxcwfw + definitionId: "fxcwfw" responses: "200": - application/json: - reasons: - - id: x739cew - - id: x739cew - - id: x739cew + application/json: {"reasons": [{"id": "x739cew"}, {"id": "x739cew"}, {"id": "x739cew"}]} listFlowTemplates: speakeasy-default-list-flow-templates: responses: @@ -681,115 +441,17 @@ examples: path: definitionId: "7889" requestBody: - application/json: - reasons: - - id: x739cew + application/json: {"reasons": [{"id": "x739cew"}]} updateDefinition: "": parameters: path: - definitionId: 7hj28a + 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 - 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 + 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 - 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: [] + 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": []} updateFlowTemplate: speakeasy-default-update-flow-template: parameters: @@ -875,3 +537,4 @@ examples: 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..f9b7ffe --- /dev/null +++ b/.speakeasy/workflow.lock @@ -0,0 +1,29 @@ +speakeasyVersion: 1.462.2 +sources: + my-source: + sourceNamespace: my-source + sourceRevisionDigest: sha256:d91142963100f48742d5a80919603677fc05b83319830dfc8956fcad01824f57 + sourceBlobDigest: sha256:70f7887ca53e442fe927d5026a8b13d36761c95fa4b07bec97e18591a95d52a5 + tags: + - latest + - speakeasy-sdk-regen-1730852930 + - 1.0.0 +targets: + terraform: + source: my-source + sourceNamespace: my-source + sourceRevisionDigest: sha256:d91142963100f48742d5a80919603677fc05b83319830dfc8956fcad01824f57 + 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 690288c..a30188c 100644 --- a/README.md +++ b/README.md @@ -51,8 +51,8 @@ TF_REATTACH_PROVIDERS=... terraform apply - -## SDK Installation + +## Installation To install this provider, copy and paste this code into your Terraform configuration. Then, run `terraform init`. @@ -61,7 +61,7 @@ terraform { required_providers { epilot-workflow = { source = "epilot-dev/epilot-workflow" - version = "0.16.0" + version = "0.17.0" } } } @@ -70,19 +70,17 @@ provider "epilot-workflow" { # Configuration options } ``` - + - -## SDK Example Usage + +## Testing the provider locally -### Testing the provider locally +#### Local Provider Should you want to validate a change locally, the `--debug` flag allows you to execute the provider against a terraform instance locally. This also allows for debuggers (e.g. delve) to be attached to the provider. -### Example - ```sh go run main.go --debug # Copy the TF_REATTACH_PROVIDERS env var @@ -91,13 +89,38 @@ cd examples/your-example TF_REATTACH_PROVIDERS=... terraform init TF_REATTACH_PROVIDERS=... terraform apply ``` - - -## Available Resources and Operations +#### Compiled Provider + +Terraform allows you to use local provider builds by setting a `dev_overrides` block in a configuration file called `.terraformrc`. This block overrides all other configured installation methods. + +1. Execute `go build` to construct a binary called `terraform-provider-epilot-workflow` +2. Ensure that the `.terraformrc` file is configured with a `dev_overrides` section such that your local copy of terraform can see the provider binary + +Terraform searches for the `.terraformrc` file in your home directory and applies any configuration settings you set. + +``` +provider_installation { + + dev_overrides { + "registry.terraform.io/epilot-dev/epilot-workflow" = "" + } + + # For all other providers, install them directly from their origin provider + # registries as normal. If you omit this, Terraform will _only_ use + # the dev_overrides block, and so no other providers will be available. + direct {} +} +``` + + + +## Available Resources and Data Sources +### Resources - +### Data Sources + ## Summary @@ -107,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..9c5b72f 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] . + +## 2025-01-05 00:32:32 +### Changes +Based on: +- OpenAPI Doc +- Speakeasy CLI 1.462.2 (2.486.1) https://github.com/speakeasy-api/speakeasy +### Generated +- [terraform v0.17.0] . +### Releases +- [Terraform v0.17.0] https://registry.terraform.io/providers/epilot-dev/epilot-workflow/0.17.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 c87510a..0000000 --- a/docs/data-sources/closing_reason.md +++ /dev/null @@ -1,30 +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" { - reason_id = "x739cew" -} -``` - - -## Schema - -### Read-Only - -- `creation_time` (String) -- `id` (String) The ID of this resource. -- `last_update_time` (String) -- `status` (String) must be one of ["ACTIVE", "INACTIVE"] -- `title` (String) diff --git a/docs/data-sources/workflow_definition.md b/docs/data-sources/workflow_definition.md deleted file mode 100644 index 6e50617..0000000 --- a/docs/data-sources/workflow_definition.md +++ /dev/null @@ -1,75 +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" { - definition_id = "7hj28a" -} -``` - - -## 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) must be one of ["WORKFLOW_STARTED", "STEP_CLOSED"] -- `number_of_units` (Number) -- `step_id` (String) -- `time_period` (String) must be one of ["minutes", "hours", "days", "weeks", "months"] - - - -### Nested Schema for `update_entity_attributes` - -Read-Only: - -- `source` (String) must be one of ["workflow_status", "current_section", "current_step"] -- `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 025bdcc..e499d17 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.16.0" + version = "0.17.0" } } } diff --git a/docs/resources/closing_reason.md b/docs/resources/closing_reason.md deleted file mode 100644 index 7b812f1..0000000 --- a/docs/resources/closing_reason.md +++ /dev/null @@ -1,43 +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" { - reason_id = "x739cew" - status = "ACTIVE" - title = "Miss" -} -``` - - -## Schema - -### Required - -- `status` (String) must be one of ["ACTIVE", "INACTIVE"] -- `title` (String) - -### Read-Only - -- `creation_time` (String) -- `id` (String) The ID of this resource. -- `last_update_time` (String) - -## 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 8e47448..0000000 --- a/docs/resources/workflow_definition.md +++ /dev/null @@ -1,98 +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" { - creation_time = "2021-04-27T12:01:13.000Z" - definition_id = "7hj28a" - description = "...my_description..." - due_date = "2021-04-27T12:00:00.000Z" - enabled = true - enable_ecp_workflow = true - flow = "{ \"see\": \"documentation\" }" - id = "1a10cbc6-dd84-4604-abba-b3cfdce452e3" - last_update_time = "2021-04-27T12:01:13.000Z" - name = "Tammy Moore PhD" -} -``` - - -## 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 a97897a..0000000 --- a/examples/data-sources/epilot-workflow_closing_reason/data-source.tf +++ /dev/null @@ -1,3 +0,0 @@ -data "epilot-workflow_closing_reason" "my_closingreason" { - reason_id = "x739cew" -} \ 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 e0b2b3d..0000000 --- a/examples/data-sources/epilot-workflow_workflow_definition/data-source.tf +++ /dev/null @@ -1,3 +0,0 @@ -data "epilot-workflow_workflow_definition" "my_workflowdefinition" { - definition_id = "7hj28a" -} \ No newline at end of file diff --git a/examples/provider/provider.tf b/examples/provider/provider.tf index e48bf9c..1bb376d 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.16.0" + version = "0.17.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 f1bc9cb..0000000 --- a/examples/resources/epilot-workflow_closing_reason/resource.tf +++ /dev/null @@ -1,5 +0,0 @@ -resource "epilot-workflow_closing_reason" "my_closingreason" { - reason_id = "x739cew" - status = "ACTIVE" - title = "Miss" -} \ 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 99e4a5e..0000000 --- a/examples/resources/epilot-workflow_workflow_definition/resource.tf +++ /dev/null @@ -1,12 +0,0 @@ -resource "epilot-workflow_workflow_definition" "my_workflowdefinition" { - creation_time = "2021-04-27T12:01:13.000Z" - definition_id = "7hj28a" - description = "...my_description..." - due_date = "2021-04-27T12:00:00.000Z" - enabled = true - enable_ecp_workflow = true - flow = "{ \"see\": \"documentation\" }" - id = "1a10cbc6-dd84-4604-abba-b3cfdce452e3" - last_update_time = "2021-04-27T12:01:13.000Z" - name = "Tammy Moore PhD" -} \ No newline at end of file diff --git a/gen.yaml b/gen.yaml index 487c587..1530e04 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.16.0 + version: 0.17.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 6e8af53..9f02fa5 100644 --- a/go.mod +++ b/go.mod @@ -1,14 +1,15 @@ module github.com/epilot-dev/terraform-provider-epilot-workflow -go 1.21 +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.10.0 + 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.23.0 + github.com/hashicorp/terraform-plugin-go v0.24.0 + github.com/hashicorp/terraform-plugin-log v0.9.0 ) require ( @@ -32,13 +33,11 @@ require ( github.com/hashicorp/go-cleanhttp v0.5.2 // indirect 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.0 // indirect - github.com/hashicorp/go-uuid v1.0.3 // indirect + github.com/hashicorp/go-plugin v1.6.1 // 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 @@ -60,15 +59,15 @@ require ( github.com/yuin/goldmark-meta v1.1.0 // indirect github.com/zclconf/go-cty v1.14.4 // indirect go.abhg.dev/goldmark/frontmatter v0.2.0 // indirect - golang.org/x/crypto v0.21.0 // indirect + golang.org/x/crypto v0.24.0 // indirect golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df // indirect golang.org/x/mod v0.17.0 // indirect - golang.org/x/net v0.23.0 // indirect - golang.org/x/sys v0.18.0 // indirect - golang.org/x/text v0.15.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de // indirect - google.golang.org/grpc v1.63.2 // indirect - google.golang.org/protobuf v1.34.0 // indirect + golang.org/x/net v0.26.0 // indirect + golang.org/x/sys v0.21.0 // indirect + golang.org/x/text v0.16.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20240604185151-ef581f913117 // indirect + google.golang.org/grpc v1.66.2 // indirect + google.golang.org/protobuf v1.34.2 // indirect gopkg.in/yaml.v2 v2.3.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 2d68f29..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= @@ -72,8 +70,8 @@ github.com/hashicorp/go-hclog v1.5.0/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVH github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= -github.com/hashicorp/go-plugin v1.6.0 h1:wgd4KxHJTVGGqWBq4QPB1i5BZNEx9BR8+OFmHDmTk8A= -github.com/hashicorp/go-plugin v1.6.0/go.mod h1:lBS5MtSSBZk0SHc66KACcjjlU6WzEVP/8pwz68aMkCI= +github.com/hashicorp/go-plugin v1.6.1 h1:P7MR2UP6gNKGPp+y7EZw2kOiq4IR9WiqLvp0XOsVdwI= +github.com/hashicorp/go-plugin v1.6.1/go.mod h1:XPHFku2tFo3o3QKFgSYo+cghcUhw1NA1hZyMK0PWAw0= github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= @@ -87,12 +85,12 @@ github.com/hashicorp/terraform-json v0.22.1 h1:xft84GZR0QzjPVWs4lRUwvTcPnegqlyS7 github.com/hashicorp/terraform-json v0.22.1/go.mod h1:JbWSQCLFSXFFhg42T7l9iJwdGXBYV8fmmD6o/ML4p3A= github.com/hashicorp/terraform-plugin-docs v0.19.4 h1:G3Bgo7J22OMtegIgn8Cd/CaSeyEljqjH3G39w28JK4c= github.com/hashicorp/terraform-plugin-docs v0.19.4/go.mod h1:4pLASsatTmRynVzsjEhbXZ6s7xBlUw/2Kt0zfrq8HxA= -github.com/hashicorp/terraform-plugin-framework v1.10.0 h1:xXhICE2Fns1RYZxEQebwkB2+kXouLC932Li9qelozrc= -github.com/hashicorp/terraform-plugin-framework v1.10.0/go.mod h1:qBXLDn69kM97NNVi/MQ9qgd1uWWsVftGSnygYG1tImM= +github.com/hashicorp/terraform-plugin-framework v1.12.0 h1:7HKaueHPaikX5/7cbC1r9d1m12iYHY+FlNZEGxQ42CQ= +github.com/hashicorp/terraform-plugin-framework v1.12.0/go.mod h1:N/IOQ2uYjW60Jp39Cp3mw7I/OpC/GfZ0385R0YibmkE= github.com/hashicorp/terraform-plugin-framework-validators v0.13.0 h1:bxZfGo9DIUoLLtHMElsu+zwqI4IsMZQBRRy4iLzZJ8E= github.com/hashicorp/terraform-plugin-framework-validators v0.13.0/go.mod h1:wGeI02gEhj9nPANU62F2jCaHjXulejm/X+af4PdZaNo= -github.com/hashicorp/terraform-plugin-go v0.23.0 h1:AALVuU1gD1kPb48aPQUjug9Ir/125t+AAurhqphJ2Co= -github.com/hashicorp/terraform-plugin-go v0.23.0/go.mod h1:1E3Cr9h2vMlahWMbsSEcNrOCxovCZhOOIXjFHbjc/lQ= +github.com/hashicorp/terraform-plugin-go v0.24.0 h1:2WpHhginCdVhFIrWHxDEg6RBn3YaWzR2o6qUeIEat2U= +github.com/hashicorp/terraform-plugin-go v0.24.0/go.mod h1:tUQ53lAsOyYSckFGEefGC5C8BAaO0ENqzFd3bQeuYQg= github.com/hashicorp/terraform-plugin-log v0.9.0 h1:i7hOA+vdAItN1/7UrfBqBwvYPQ9TFvymaRGZED3FCV0= github.com/hashicorp/terraform-plugin-log v0.9.0/go.mod h1:rKL8egZQ/eXSyDqzLUuwUYLVdlYeamldAHSxjUFADow= github.com/hashicorp/terraform-registry-address v0.2.3 h1:2TAiKJ1A3MAkZlH1YI/aTVcLZRu7JseiXNRHbOAyoTI= @@ -180,8 +178,8 @@ go.abhg.dev/goldmark/frontmatter v0.2.0/go.mod h1:XqrEkZuM57djk7zrlRUB02x8I5J0px golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= -golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA= -golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs= +golang.org/x/crypto v0.24.0 h1:mnl8DM0o513X8fdIkmyFE/5hTYxbwYOjDS/+rK6qpRI= +golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM= golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df h1:UA2aFVmmsIlefxMk29Dp2juaUSth8Pyn3Tq5Y5mJGME= golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= @@ -191,10 +189,12 @@ golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY= -golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs= -golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= +golang.org/x/net v0.26.0 h1:soB7SVo0PWrY4vPW/+ay0jKDNScG2X9wFeYlXIvJsOQ= +golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= +golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -208,8 +208,8 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4= -golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws= +golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= @@ -217,20 +217,20 @@ golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= -golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4= +golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.13.0 h1:Iey4qkscZuv0VvIt8E0neZjtPVQFSc870HQ448QgEmQ= -golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= +golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg= +golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de h1:cZGRis4/ot9uVm639a+rHCUaG0JJHEsdyzSQTMX+suY= -google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de/go.mod h1:H4O17MA/PE9BsGx3w+a+W2VOLLD1Qf7oJneAoU6WktY= -google.golang.org/grpc v1.63.2 h1:MUeiw1B2maTVZthpU5xvASfTh3LDbxHd6IJ6QQVU+xM= -google.golang.org/grpc v1.63.2/go.mod h1:WAX/8DgncnokcFUldAxq7GeB5DXHDbMF+lLvDomNkRA= -google.golang.org/protobuf v1.34.0 h1:Qo/qEd2RZPCf2nKuorzksSknv0d3ERwp1vFG38gSmH4= -google.golang.org/protobuf v1.34.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240604185151-ef581f913117 h1:1GBuWVLM/KMVUv1t1En5Gs+gFZCNd360GGb4sSxtrhU= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240604185151-ef581f913117/go.mod h1:EfXuqaE1J41VCDicxHzUDm+8rk+7ZdXzHV0IhO/I6s0= +google.golang.org/grpc v1.66.2 h1:3QdXkuq3Bkh7w+ywLdLvM56cmGvQHUMZpiCzt6Rqaoo= +google.golang.org/grpc v1.66.2/go.mod h1:s3/l6xSSCURdVfAnL+TqCNMyTDAGN6+lZeVxnZR128Y= +google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= +google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/warnings.v0 v0.1.2 h1:wFXVbFY8DY5/xOe1ECiWdKCzZlxgshcYVNkBHstARME= diff --git a/internal/provider/closingreason_data_source.go b/internal/provider/closingreason_data_source.go deleted file mode 100644 index 76d699c..0000000 --- a/internal/provider/closingreason_data_source.go +++ /dev/null @@ -1,141 +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, - Description: `must be one of ["ACTIVE", "INACTIVE"]`, - }, - "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 482561a..0000000 --- a/internal/provider/closingreason_resource.go +++ /dev/null @@ -1,289 +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-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/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, - }, - "id": schema.StringAttribute{ - Computed: true, - }, - "last_update_time": schema.StringAttribute{ - Computed: true, - }, - "status": schema.StringAttribute{ - Required: true, - Description: `must be one of ["ACTIVE", "INACTIVE"]`, - Validators: []validator.String{ - stringvalidator.OneOf( - "ACTIVE", - "INACTIVE", - ), - }, - }, - "title": schema.StringAttribute{ - Required: true, - }, - }, - } -} - -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.ToSharedClosingReasonInput() - 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 - } - - closingReason := *data.ToSharedClosingReasonInput() - var reasonID string - reasonID = data.ID.ValueString() - - request := operations.UpdateClosingReasonRequest{ - ClosingReason: closingReason, - ReasonID: reasonID, - } - res, err := r.client.ClosingReason.UpdateClosingReason(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.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) 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 - } - - var reasonID string - reasonID = data.ID.ValueString() - - request := operations.DeleteClosingReasonRequest{ - ReasonID: reasonID, - } - res, err := r.client.ClosingReason.DeleteClosingReason(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 *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 b91515f..0000000 --- a/internal/provider/closingreason_resource_sdk.go +++ /dev/null @@ -1,30 +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) ToSharedClosingReasonInput() *shared.ClosingReasonInput { - status := shared.ClosingReasonsStatus(r.Status.ValueString()) - var title string - title = r.Title.ValueString() - - out := shared.ClosingReasonInput{ - 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 cb2cee2..87264ee 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -36,8 +36,7 @@ func (p *EpilotWorkflowProvider) Metadata(ctx context.Context, req provider.Meta func (p *EpilotWorkflowProvider) Schema(ctx context.Context, req provider.SchemaRequest, resp *provider.SchemaResponse) { resp.Schema = schema.Schema{ - MarkdownDescription: `Workflows Definitions: Service for Workflow Definitions for different processes inside of an Organization` + "\n" + - ``, + Description: `Workflows Definitions: Service for Workflow Definitions for different processes inside of an Organization`, Attributes: map[string]schema.Attribute{ "server_url": schema.StringAttribute{ MarkdownDescription: "Server URL (defaults to https://workflows-definition.sls.epilot.io)", @@ -77,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...) @@ -89,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 0757050..0000000 --- a/internal/provider/workflowdefinition_data_source.go +++ /dev/null @@ -1,234 +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, - Description: `must be one of ["WORKFLOW_STARTED", "STEP_CLOSED"]`, - }, - "number_of_units": schema.NumberAttribute{ - Computed: true, - }, - "step_id": schema.StringAttribute{ - Computed: true, - }, - "time_period": schema.StringAttribute{ - Computed: true, - Description: `must be one of ["minutes", "hours", "days", "weeks", "months"]`, - }, - }, - 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, - Description: `must be one of ["workflow_status", "current_section", "current_step"]`, - }, - "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 5199f58..0000000 --- a/internal/provider/workflowdefinition_resource.go +++ /dev/null @@ -1,452 +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{ - 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{ - 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/.gitignore b/internal/sdk/.gitignore index d3c2f59..f2c012b 100644 --- a/internal/sdk/.gitignore +++ b/internal/sdk/.gitignore @@ -1 +1,2 @@ # .gitignore +.speakeasy/reports diff --git a/internal/sdk/closingreason.go b/internal/sdk/closingreason.go index 0d589e4..0379389 100644 --- a/internal/sdk/closingreason.go +++ b/internal/sdk/closingreason.go @@ -6,14 +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" - "io" "net/http" "net/url" ) @@ -40,7 +37,6 @@ func (s *ClosingReason) ChangeReasonStatus(ctx context.Context, request operatio o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -50,7 +46,12 @@ func (s *ClosingReason) ChangeReasonStatus(ctx context.Context, request operatio } } - baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + var baseURL string + if o.ServerURL == nil { + baseURL = utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + } else { + baseURL = *o.ServerURL + } 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) @@ -84,94 +85,36 @@ 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, - } - } + for k, v := range o.SetHeaders { + req.Header.Set(k, v) } - 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 - }) + 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 { - 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,13 +124,6 @@ func (s *ClosingReason) ChangeReasonStatus(ctx context.Context, request operatio RawResponse: httpRes, } - rawBody, err := io.ReadAll(httpRes.Body) - if err != nil { - return nil, fmt.Errorf("error reading response body: %w", err) - } - httpRes.Body.Close() - httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) - switch { case httpRes.StatusCode == 202: case httpRes.StatusCode == 400: @@ -195,6 +131,11 @@ func (s *ClosingReason) ChangeReasonStatus(ctx context.Context, request operatio 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 @@ -202,9 +143,17 @@ func (s *ClosingReason) ChangeReasonStatus(ctx context.Context, request operatio 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) } @@ -214,7 +163,7 @@ func (s *ClosingReason) ChangeReasonStatus(ctx context.Context, request operatio // CreateClosingReason - createClosingReason // A created Closing Reason is stored for the organization and will be displayed in the library of reasons. -func (s *ClosingReason) CreateClosingReason(ctx context.Context, request shared.ClosingReasonInput, opts ...operations.Option) (*operations.CreateClosingReasonResponse, error) { +func (s *ClosingReason) CreateClosingReason(ctx context.Context, request shared.ClosingReason, opts ...operations.Option) (*operations.CreateClosingReasonResponse, error) { hookCtx := hooks.HookContext{ Context: ctx, OperationID: "createClosingReason", @@ -224,7 +173,6 @@ func (s *ClosingReason) CreateClosingReason(ctx context.Context, request shared. o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -234,7 +182,12 @@ func (s *ClosingReason) CreateClosingReason(ctx context.Context, request shared. } } - baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + var baseURL string + if o.ServerURL == nil { + baseURL = utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + } else { + baseURL = *o.ServerURL + } opURL, err := url.JoinPath(baseURL, "/v1/workflows/closing-reasons") if err != nil { return nil, fmt.Errorf("error generating URL: %w", err) @@ -268,312 +221,72 @@ 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, - } - } - } - - 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.CreateClosingReasonResponse{ - StatusCode: httpRes.StatusCode, - ContentType: httpRes.Header.Get("Content-Type"), - RawResponse: httpRes, - } - - rawBody, err := io.ReadAll(httpRes.Body) - if err != nil { - return nil, fmt.Errorf("error reading response body: %w", err) - } - httpRes.Body.Close() - httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) - - switch { - case httpRes.StatusCode == 201: - switch { - case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): - var out shared.ClosingReason - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.ClosingReason = &out - default: - return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) - } - default: - return nil, errors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) - } - - return res, nil - -} - -// DeleteClosingReason - deleteClosingReason -// Permanently delete a closing reason (Using INACTIVE status is recommended instead) -func (s *ClosingReason) DeleteClosingReason(ctx context.Context, request operations.DeleteClosingReasonRequest, opts ...operations.Option) (*operations.DeleteClosingReasonResponse, error) { - hookCtx := hooks.HookContext{ - Context: ctx, - OperationID: "deleteClosingReason", - 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/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() + for k, v := range o.SetHeaders { + req.Header.Set(k, v) } - req, err := http.NewRequestWithContext(ctx, "DELETE", 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.DeleteClosingReasonResponse{ + res := &operations.CreateClosingReasonResponse{ StatusCode: httpRes.StatusCode, ContentType: httpRes.Header.Get("Content-Type"), RawResponse: httpRes, } - rawBody, err := io.ReadAll(httpRes.Body) - if err != nil { - return nil, fmt.Errorf("error reading response body: %w", err) - } - httpRes.Body.Close() - httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) - switch { - case httpRes.StatusCode == 204: - case httpRes.StatusCode == 403: + case httpRes.StatusCode == 201: switch { case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): - var out shared.ErrorResp - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { return nil, err } - res.ErrorResp = &out - default: - 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`): - var out shared.ClosingReasonNotFoundResp + var out shared.ClosingReason if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { return nil, err } - res.ClosingReasonNotFoundResp = &out + 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) } 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) } @@ -593,7 +306,6 @@ func (s *ClosingReason) GetAllClosingReasons(ctx context.Context, request operat o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -603,7 +315,12 @@ func (s *ClosingReason) GetAllClosingReasons(ctx context.Context, request operat } } - baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + var baseURL string + if o.ServerURL == nil { + baseURL = utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + } else { + baseURL = *o.ServerURL + } opURL, err := url.JoinPath(baseURL, "/v1/workflows/closing-reasons") if err != nil { return nil, fmt.Errorf("error generating URL: %w", err) @@ -635,94 +352,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, - } - } + for k, v := range o.SetHeaders { + req.Header.Set(k, v) } - 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 - }) + 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 { - 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 - } } } @@ -732,17 +391,15 @@ func (s *ClosingReason) GetAllClosingReasons(ctx context.Context, request operat RawResponse: httpRes, } - rawBody, err := io.ReadAll(httpRes.Body) - if err != nil { - return nil, fmt.Errorf("error reading response body: %w", err) - } - httpRes.Body.Close() - httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) - 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 @@ -750,622 +407,17 @@ func (s *ClosingReason) GetAllClosingReasons(ctx context.Context, request operat 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: - 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, "/v2/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) - 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.GetClosingReasonResponse{ - StatusCode: httpRes.StatusCode, - ContentType: httpRes.Header.Get("Content-Type"), - RawResponse: httpRes, - } - - rawBody, err := io.ReadAll(httpRes.Body) - if err != nil { - return nil, fmt.Errorf("error reading response body: %w", err) - } - httpRes.Body.Close() - httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) - - switch { - case httpRes.StatusCode == 200: - switch { - case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): - var out shared.ClosingReason - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.ClosingReason = &out - default: - 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 == 403: - switch { - case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): - var out shared.ErrorResp - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.ErrorResp = &out - default: - 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`): - var out shared.ClosingReasonNotFoundResp - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.ClosingReasonNotFoundResp = &out - default: - return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) - } - default: - return nil, errors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) - } - - return res, nil - -} - -// GetClosingReasonV1 - getClosingReasonV1 -// Get specific closing reason by id from the organisation. -// -// Deprecated method: This will be removed in a future release, please migrate away from it as soon as possible. -func (s *ClosingReason) GetClosingReasonV1(ctx context.Context, request operations.GetClosingReasonV1Request, opts ...operations.Option) (*operations.GetClosingReasonV1Response, error) { - hookCtx := hooks.HookContext{ - Context: ctx, - OperationID: "getClosingReasonV1", - 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) - 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) + rawBody, err := utils.ConsumeRawBody(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.GetClosingReasonV1Response{ - StatusCode: httpRes.StatusCode, - ContentType: httpRes.Header.Get("Content-Type"), - RawResponse: httpRes, - } - - rawBody, err := io.ReadAll(httpRes.Body) - if err != nil { - return nil, fmt.Errorf("error reading response body: %w", err) - } - httpRes.Body.Close() - httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) - - switch { - case httpRes.StatusCode == 200: - switch { - case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): - var out shared.ClosingReason - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.ClosingReason = &out - default: - 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`): - var out shared.ErrorResp - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.ErrorResp = &out - default: - 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`): - var out shared.ClosingReasonNotFoundResp - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.ClosingReasonNotFoundResp = &out - default: - return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) - } - default: - return nil, errors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) - } - - return res, nil - -} - -// UpdateClosingReason - updateClosingReason -// Update an existing closing reason -func (s *ClosingReason) UpdateClosingReason(ctx context.Context, request operations.UpdateClosingReasonRequest, opts ...operations.Option) (*operations.UpdateClosingReasonResponse, error) { - hookCtx := hooks.HookContext{ - Context: ctx, - OperationID: "updateClosingReason", - 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/workflows/closing-reasons/{reasonId}", request, nil) - if err != nil { - return nil, fmt.Errorf("error generating URL: %w", err) - } - - bodyReader, reqContentType, err := utils.SerializeRequestBody(ctx, request, false, false, "ClosingReason", "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, "PATCH", 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.UpdateClosingReasonResponse{ - StatusCode: httpRes.StatusCode, - ContentType: httpRes.Header.Get("Content-Type"), - RawResponse: httpRes, - } - - rawBody, err := io.ReadAll(httpRes.Body) - if err != nil { - return nil, fmt.Errorf("error reading response body: %w", err) - } - httpRes.Body.Close() - httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) - - switch { - case httpRes.StatusCode == 200: - switch { - case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): - var out shared.ClosingReason - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.ClosingReason = &out - default: - 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 == 403: - switch { - case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): - var out shared.ErrorResp - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.ErrorResp = &out - default: - 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`): - var out shared.ClosingReasonNotFoundResp - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.ClosingReasonNotFoundResp = &out - default: - return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) - } - default: return nil, errors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) } diff --git a/internal/sdk/flowsv2.go b/internal/sdk/flowsv2.go deleted file mode 100644 index 33b0979..0000000 --- a/internal/sdk/flowsv2.go +++ /dev/null @@ -1,991 +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" - "io" - "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, - } - - rawBody, err := io.ReadAll(httpRes.Body) - if err != nil { - return nil, fmt.Errorf("error reading response body: %w", err) - } - httpRes.Body.Close() - httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) - - switch { - case httpRes.StatusCode == 201: - switch { - case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): - var out shared.FlowTemplate - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.FlowTemplate = &out - default: - 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`): - var out shared.ErrorResp - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.ErrorResp = &out - default: - return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) - } - default: - 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, - } - - rawBody, err := io.ReadAll(httpRes.Body) - if err != nil { - return nil, fmt.Errorf("error reading response body: %w", err) - } - httpRes.Body.Close() - httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) - - 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`): - var out shared.ErrorResp - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.ErrorResp = &out - default: - return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) - } - default: - 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, - } - - rawBody, err := io.ReadAll(httpRes.Body) - if err != nil { - return nil, fmt.Errorf("error reading response body: %w", err) - } - httpRes.Body.Close() - httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) - - switch { - case httpRes.StatusCode == 200: - switch { - case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): - var out shared.FlowTemplate - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.FlowTemplate = &out - default: - 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`): - var out shared.ErrorResp - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.ErrorResp = &out - default: - 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`): - var out shared.DefinitionNotFoundResp - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.DefinitionNotFoundResp = &out - default: - return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) - } - default: - 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, - } - - rawBody, err := io.ReadAll(httpRes.Body) - if err != nil { - return nil, fmt.Errorf("error reading response body: %w", err) - } - httpRes.Body.Close() - httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) - - switch { - case httpRes.StatusCode == 200: - switch { - case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): - var out shared.FlowTemplatesList - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.FlowTemplatesList = &out - default: - 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`): - var out shared.ErrorResp - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.ErrorResp = &out - default: - return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) - } - default: - 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, - } - - rawBody, err := io.ReadAll(httpRes.Body) - if err != nil { - return nil, fmt.Errorf("error reading response body: %w", err) - } - httpRes.Body.Close() - httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) - - switch { - case httpRes.StatusCode == 200: - switch { - case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): - var out shared.FlowTemplate - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.FlowTemplate = &out - default: - 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`): - var out shared.ErrorResp - if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { - return nil, err - } - - res.ErrorResp = &out - default: - return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) - } - default: - 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/json.go b/internal/sdk/internal/utils/json.go index 986393e..bd307e1 100644 --- a/internal/sdk/internal/utils/json.go +++ b/internal/sdk/internal/utils/json.go @@ -487,30 +487,29 @@ func unmarshalValue(value json.RawMessage, v reflect.Value, tag reflect.StructTa v.Set(m) return nil case reflect.Slice, reflect.Array: - if bytes.Equal(value, []byte("null")) || !isComplexValueType(dereferenceTypePointer(typ.Elem())) { - if v.CanAddr() { - return json.Unmarshal(value, v.Addr().Interface()) - } else { - return json.Unmarshal(value, v.Interface()) - } - } - - var unmarhsaled []json.RawMessage + var unmarshaled []json.RawMessage - if err := json.Unmarshal(value, &unmarhsaled); err != nil { + if err := json.Unmarshal(value, &unmarshaled); err != nil { return err } - arrVal := v + arrVal := reflect.MakeSlice(typ, len(unmarshaled), len(unmarshaled)) - for _, value := range unmarhsaled { + for index, value := range unmarshaled { itemVal := reflect.New(typ.Elem()) if err := unmarshalValue(value, itemVal, tag, disallowUnknownFields); err != nil { return err } - arrVal = reflect.Append(arrVal, itemVal.Elem()) + arrVal.Index(index).Set(itemVal.Elem()) + } + + if v.Kind() == reflect.Pointer { + if v.IsNil() { + v.Set(reflect.New(typ)) + } + v = v.Elem() } v.Set(arrVal) diff --git a/internal/sdk/internal/utils/queryparams.go b/internal/sdk/internal/utils/queryparams.go index ad359eb..85fbff6 100644 --- a/internal/sdk/internal/utils/queryparams.go +++ b/internal/sdk/internal/utils/queryparams.go @@ -214,7 +214,11 @@ func populateDeepObjectParamsStruct(qsValues url.Values, priorScope string, stru continue } - scope := priorScope + "[" + qpTag.ParamName + "]" + scope := priorScope + + if !qpTag.Inline { + scope = priorScope + "[" + qpTag.ParamName + "]" + } switch fieldValue.Kind() { case reflect.Array, reflect.Slice: @@ -252,6 +256,13 @@ type paramTag struct { Explode bool ParamName string Serialization string + + // Inline is a special case for union/oneOf. When a wrapper struct type is + // used, each union/oneOf value field should be inlined (e.g. not appended + // in deepObject style with the name) as if the value was directly on the + // parent struct field. Without this annotation, the value would not be + // encoded by downstream logic that requires the struct field tag. + Inline bool } func parseQueryParamTag(field reflect.StructField) *paramTag { diff --git a/internal/sdk/internal/utils/requestbody.go b/internal/sdk/internal/utils/requestbody.go index 0fd33cf..78479c6 100644 --- a/internal/sdk/internal/utils/requestbody.go +++ b/internal/sdk/internal/utils/requestbody.go @@ -66,15 +66,16 @@ func serializeRequestBody(request interface{}, nullable, optional bool, requestF if tag != nil { // request object (non-flattened) requestVal := requestValType.FieldByName(requestFieldName) + val := reflect.ValueOf(requestVal.Interface()) if isNil(requestField.Type, requestVal) { if !nullable && optional { return nil, "", nil } - return serializeContentType(requestFieldName, tag.MediaType, requestVal, string(requestField.Tag)) + return serializeContentType(requestFieldName, tag.MediaType, val, string(requestField.Tag)) } - return serializeContentType(requestFieldName, tag.MediaType, requestVal, string(requestField.Tag)) + return serializeContentType(requestFieldName, tag.MediaType, val, string(requestField.Tag)) } } @@ -82,7 +83,7 @@ func serializeRequestBody(request interface{}, nullable, optional bool, requestF return serializeContentType(requestFieldName, SerializationMethodToContentType[serializationMethod], reflect.ValueOf(request), tag) } -func serializeContentType(fieldName string, mediaType string, val reflect.Value, tag string) (*bytes.Buffer, string, error) { +func serializeContentType(fieldName string, mediaType string, val reflect.Value, tag string) (io.Reader, string, error) { buf := &bytes.Buffer{} if isNil(val.Type(), val) { @@ -116,6 +117,8 @@ func serializeContentType(fieldName string, mediaType string, val reflect.Value, if err := encodeFormData(fieldName, buf, val.Interface()); err != nil { return nil, "", err } + case val.Type().Implements(reflect.TypeOf((*io.Reader)(nil)).Elem()): + return val.Interface().(io.Reader), mediaType, nil default: val = reflect.Indirect(val) @@ -124,8 +127,8 @@ func serializeContentType(fieldName string, mediaType string, val reflect.Value, if _, err := buf.WriteString(valToString(val.Interface())); err != nil { return nil, "", err } - case val.Type() == reflect.TypeOf([]byte(nil)): - if _, err := buf.Write(val.Bytes()); err != nil { + case reflect.TypeOf(val.Interface()) == reflect.TypeOf([]byte(nil)): + if _, err := buf.Write(val.Interface().([]byte)); err != nil { return nil, "", err } default: @@ -163,7 +166,7 @@ func encodeMultipartFormData(w io.Writer, data interface{}) (string, error) { tag := parseMultipartFormTag(field) if tag.File { - if err := encodeMultipartFormDataFile(writer, fieldType, valType); err != nil { + if err := encodeMultipartFormDataFile(writer, tag.Name, fieldType, valType); err != nil { writer.Close() return "", err } @@ -208,14 +211,13 @@ func encodeMultipartFormData(w io.Writer, data interface{}) (string, error) { return writer.FormDataContentType(), nil } -func encodeMultipartFormDataFile(w *multipart.Writer, fieldType reflect.Type, valType reflect.Value) error { +func encodeMultipartFormDataFile(w *multipart.Writer, fieldName string, fieldType reflect.Type, valType reflect.Value) error { if fieldType.Kind() != reflect.Struct { return fmt.Errorf("invalid type %s for multipart/form-data file", valType.Type()) } - var fieldName string var fileName string - var content []byte + var reader io.Reader for i := 0; i < fieldType.NumField(); i++ { field := fieldType.Field(i) @@ -226,15 +228,18 @@ func encodeMultipartFormDataFile(w *multipart.Writer, fieldType reflect.Type, va continue } - if tag.Content { - content = val.Bytes() + if tag.Content && val.CanInterface() { + if reflect.TypeOf(val.Interface()) == reflect.TypeOf([]byte(nil)) { + reader = bytes.NewReader(val.Interface().([]byte)) + } else if reflect.TypeOf(val.Interface()).Implements(reflect.TypeOf((*io.Reader)(nil)).Elem()) { + reader = val.Interface().(io.Reader) + } } else { - fieldName = tag.Name fileName = val.String() } } - if fieldName == "" || fileName == "" || content == nil { + if fileName == "" || reader == nil { return fmt.Errorf("invalid multipart/form-data file") } @@ -242,7 +247,7 @@ func encodeMultipartFormDataFile(w *multipart.Writer, fieldType reflect.Type, va if err != nil { return err } - if _, err := fw.Write(content); err != nil { + if _, err := io.Copy(fw, reader); err != nil { return err } 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/internal/utils/security.go b/internal/sdk/internal/utils/security.go index c8503f9..19dfa6f 100644 --- a/internal/sdk/internal/utils/security.go +++ b/internal/sdk/internal/utils/security.go @@ -119,9 +119,14 @@ func parseSecurityScheme(headers, queryParams map[string]string, schemeTag *secu } if schemeType.Kind() == reflect.Struct { - if schemeTag.Type == "http" && schemeTag.SubType == "basic" { - handleBasicAuthScheme(headers, schemeVal.Interface()) - return + if schemeTag.Type == "http" { + switch schemeTag.SubType { + case "basic": + handleBasicAuthScheme(headers, schemeVal.Interface()) + return + case "custom": + return + } } for i := 0; i < schemeType.NumField(); i++ { @@ -171,6 +176,7 @@ func parseSecuritySchemeValue(headers, queryParams map[string]string, schemeTag switch schemeTag.SubType { case "bearer": headers[secTag.Name] = prefixBearer(valToString(val)) + case "custom": default: panic("not supported") } diff --git a/internal/sdk/internal/utils/utils.go b/internal/sdk/internal/utils/utils.go index adb2f70..031a71a 100644 --- a/internal/sdk/internal/utils/utils.go +++ b/internal/sdk/internal/utils/utils.go @@ -3,10 +3,12 @@ package utils import ( + "bytes" "context" "fmt" "io" "math/big" + "net/http" "reflect" "regexp" "strconv" @@ -125,6 +127,7 @@ func parseStructTag(tagKey string, field reflect.StructField) map[string]string func parseParamTag(tagKey string, field reflect.StructField, defaultStyle string, defaultExplode bool) *paramTag { // example `{tagKey}:"style=simple,explode=false,name=apiID"` + // example `{tagKey}:"inline"` values := parseStructTag(tagKey, field) if values == nil { return nil @@ -138,6 +141,8 @@ func parseParamTag(tagKey string, field reflect.StructField, defaultStyle string for k, v := range values { switch k { + case "inline": + tag.Inline = v == "true" case "style": tag.Style = v case "explode": @@ -228,3 +233,15 @@ func contains(arr []string, str string) bool { } return false } + +func ConsumeRawBody(res *http.Response) ([]byte, error) { + rawBody, err := io.ReadAll(res.Body) + if err != nil { + return nil, fmt.Errorf("error reading response body: %w", err) + } + + res.Body.Close() + res.Body = io.NopCloser(bytes.NewBuffer(rawBody)) + + return rawBody, nil +} 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/deleteclosingreason.go b/internal/sdk/models/operations/deleteclosingreason.go deleted file mode 100644 index 5fdfff7..0000000 --- a/internal/sdk/models/operations/deleteclosingreason.go +++ /dev/null @@ -1,68 +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 DeleteClosingReasonRequest struct { - // unique id to identify the closing reason. - ReasonID string `pathParam:"style=simple,explode=false,name=reasonId"` -} - -func (o *DeleteClosingReasonRequest) GetReasonID() string { - if o == nil { - return "" - } - return o.ReasonID -} - -type DeleteClosingReasonResponse struct { - // Closing reason not found - ClosingReasonNotFoundResp *shared.ClosingReasonNotFoundResp - // HTTP response content type for this operation - ContentType string - // Forbidden - 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 *DeleteClosingReasonResponse) GetClosingReasonNotFoundResp() *shared.ClosingReasonNotFoundResp { - if o == nil { - return nil - } - return o.ClosingReasonNotFoundResp -} - -func (o *DeleteClosingReasonResponse) GetContentType() string { - if o == nil { - return "" - } - return o.ContentType -} - -func (o *DeleteClosingReasonResponse) GetErrorResp() *shared.ErrorResp { - if o == nil { - return nil - } - return o.ErrorResp -} - -func (o *DeleteClosingReasonResponse) GetStatusCode() int { - if o == nil { - return 0 - } - return o.StatusCode -} - -func (o *DeleteClosingReasonResponse) 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 39ba554..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 { - // unique id 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/getclosingreasonv1.go b/internal/sdk/models/operations/getclosingreasonv1.go deleted file mode 100644 index 2ff49e1..0000000 --- a/internal/sdk/models/operations/getclosingreasonv1.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 GetClosingReasonV1Request struct { - // uuid to identify the closing reason. - ReasonID string `pathParam:"style=simple,explode=false,name=reasonId"` -} - -func (o *GetClosingReasonV1Request) GetReasonID() string { - if o == nil { - return "" - } - return o.ReasonID -} - -type GetClosingReasonV1Response 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 *GetClosingReasonV1Response) GetClosingReason() *shared.ClosingReason { - if o == nil { - return nil - } - return o.ClosingReason -} - -func (o *GetClosingReasonV1Response) GetClosingReasonNotFoundResp() *shared.ClosingReasonNotFoundResp { - if o == nil { - return nil - } - return o.ClosingReasonNotFoundResp -} - -func (o *GetClosingReasonV1Response) GetContentType() string { - if o == nil { - return "" - } - return o.ContentType -} - -func (o *GetClosingReasonV1Response) GetErrorResp() *shared.ErrorResp { - if o == nil { - return nil - } - return o.ErrorResp -} - -func (o *GetClosingReasonV1Response) GetStatusCode() int { - if o == nil { - return 0 - } - return o.StatusCode -} - -func (o *GetClosingReasonV1Response) 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/options.go b/internal/sdk/models/operations/options.go index 4d0008e..edf02ad 100644 --- a/internal/sdk/models/operations/options.go +++ b/internal/sdk/models/operations/options.go @@ -12,7 +12,6 @@ import ( var ErrUnsupportedOption = errors.New("unsupported option") const ( - SupportedOptionServerURL = "serverURL" SupportedOptionRetries = "retries" SupportedOptionTimeout = "timeout" SupportedOptionAcceptHeaderOverride = "acceptHeaderOverride" @@ -22,8 +21,8 @@ const ( type AcceptHeaderEnum string const ( - AcceptHeaderEnumApplicationJson AcceptHeaderEnum = "application/json" - AcceptHeaderEnumWildcardWildcard AcceptHeaderEnum = "*/*" + AcceptHeaderEnumApplicationJson AcceptHeaderEnum = "application/json" + AcceptHeaderEnumWildcardRootWildcard AcceptHeaderEnum = "*/*" ) func (e AcceptHeaderEnum) ToPointer() *AcceptHeaderEnum { @@ -36,6 +35,7 @@ type Options struct { Timeout *time.Duration AcceptHeaderOverride *AcceptHeaderEnum URLOverride *string + SetHeaders map[string]string } type Option func(*Options, ...string) error @@ -43,10 +43,6 @@ type Option func(*Options, ...string) error // WithServerURL allows providing an alternative server URL. func WithServerURL(serverURL string) Option { return func(opts *Options, supportedOptions ...string) error { - if !utils.Contains(supportedOptions, SupportedOptionServerURL) { - return ErrUnsupportedOption - } - opts.ServerURL = &serverURL return nil } @@ -55,10 +51,6 @@ func WithServerURL(serverURL string) Option { // WithTemplatedServerURL allows providing an alternative server URL with templated parameters. func WithTemplatedServerURL(serverURL string, params map[string]string) Option { return func(opts *Options, supportedOptions ...string) error { - if !utils.Contains(supportedOptions, SupportedOptionServerURL) { - return ErrUnsupportedOption - } - if params != nil { serverURL = utils.ReplaceParameters(serverURL, params) } @@ -114,3 +106,12 @@ func WithURLOverride(urlOverride string) Option { return nil } } + +// WithSetHeaders takes a map of headers that will applied to a request. If the +// request contains headers that are in the map then they will be overwritten. +func WithSetHeaders(hdrs map[string]string) Option { + return func(opts *Options, supportedOptions ...string) error { + opts.SetHeaders = hdrs + return nil + } +} diff --git a/internal/sdk/models/operations/updateclosingreason.go b/internal/sdk/models/operations/updateclosingreason.go deleted file mode 100644 index b5cfd90..0000000 --- a/internal/sdk/models/operations/updateclosingreason.go +++ /dev/null @@ -1,86 +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 UpdateClosingReasonRequest struct { - // Updated closing reason fields - ClosingReason shared.ClosingReasonInput `request:"mediaType=application/json"` - // unique id to identify the closing reason. - ReasonID string `pathParam:"style=simple,explode=false,name=reasonId"` -} - -func (o *UpdateClosingReasonRequest) GetClosingReason() shared.ClosingReasonInput { - if o == nil { - return shared.ClosingReasonInput{} - } - return o.ClosingReason -} - -func (o *UpdateClosingReasonRequest) GetReasonID() string { - if o == nil { - return "" - } - return o.ReasonID -} - -type UpdateClosingReasonResponse struct { - // Closing reason updated successfully - 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 *UpdateClosingReasonResponse) GetClosingReason() *shared.ClosingReason { - if o == nil { - return nil - } - return o.ClosingReason -} - -func (o *UpdateClosingReasonResponse) GetClosingReasonNotFoundResp() *shared.ClosingReasonNotFoundResp { - if o == nil { - return nil - } - return o.ClosingReasonNotFoundResp -} - -func (o *UpdateClosingReasonResponse) GetContentType() string { - if o == nil { - return "" - } - return o.ContentType -} - -func (o *UpdateClosingReasonResponse) GetErrorResp() *shared.ErrorResp { - if o == nil { - return nil - } - return o.ErrorResp -} - -func (o *UpdateClosingReasonResponse) GetStatusCode() int { - if o == nil { - return 0 - } - return o.StatusCode -} - -func (o *UpdateClosingReasonResponse) 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 9737948..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 - DueDateConfig *DueDateConfig `json:"due_date_config,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) GetDueDateConfig() *DueDateConfig { - if o == nil { - return nil - } - return o.DueDateConfig -} - -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/closingreasoninput.go b/internal/sdk/models/shared/closingreasoninput.go deleted file mode 100644 index 47eadf7..0000000 --- a/internal/sdk/models/shared/closingreasoninput.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package shared - -// ClosingReasonInput - One Closing reason for a workflow -type ClosingReasonInput struct { - Status ClosingReasonsStatus `json:"status"` - Title string `json:"title"` -} - -func (o *ClosingReasonInput) GetStatus() ClosingReasonsStatus { - if o == nil { - return ClosingReasonsStatus("") - } - return o.Status -} - -func (o *ClosingReasonInput) GetTitle() string { - if o == nil { - return "" - } - return o.Title -} 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 25ecc71..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 - DueDateConfig *DueDateConfig `json:"due_date_config,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) GetDueDateConfig() *DueDateConfig { - if o == nil { - return nil - } - return o.DueDateConfig -} - -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 1cb5a48..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 - DueDateConfig *DueDateConfig `json:"due_date_config,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) GetDueDateConfig() *DueDateConfig { - if o == nil { - return nil - } - return o.DueDateConfig -} - -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 7c954b5..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 - DueDateConfig *DueDateConfig `json:"due_date_config,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) GetDueDateConfig() *DueDateConfig { - if o == nil { - return nil - } - return o.DueDateConfig -} - -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 800728b..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 - DueDateConfig *DueDateConfig `json:"due_date_config,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) GetDueDateConfig() *DueDateConfig { - if o == nil { - return nil - } - return o.DueDateConfig -} - -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..8763f74 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 `queryParam:"inline"` + Step *Step `queryParam:"inline"` + + 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 3f7a605..27ac1bf 100644 --- a/internal/sdk/sdk.go +++ b/internal/sdk/sdk.go @@ -41,6 +41,9 @@ func Float32(f float32) *float32 { return &f } // Float64 provides a helper function to return a pointer to a float64 func Float64(f float64) *float64 { return &f } +// Pointer provides a helper function to return a pointer to a type +func Pointer[T any](v T) *T { return &v } + type sdkConfiguration struct { Client HTTPClient Security func(context.Context) (interface{}, error) @@ -68,7 +71,6 @@ func (c *sdkConfiguration) GetServerDetails() (string, map[string]string) { type SDK struct { ClosingReason *ClosingReason Workflows *Workflows - FlowsV2 *FlowsV2 sdkConfiguration sdkConfiguration } @@ -146,9 +148,9 @@ func New(opts ...SDKOption) *SDK { sdkConfiguration: sdkConfiguration{ Language: "go", OpenAPIDocVersion: "1.0.0", - SDKVersion: "0.0.1", - GenVersion: "2.396.0", - UserAgent: "speakeasy-sdk/go 0.0.1 2.396.0 1.0.0 github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk", + SDKVersion: "0.17.0", + GenVersion: "2.486.1", + UserAgent: "speakeasy-sdk/terraform 0.17.0 2.486.1 1.0.0 github.com/epilot-dev/terraform-provider-epilot-workflow/internal/sdk", Hooks: hooks.New(), }, } @@ -172,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/types/pointers.go b/internal/sdk/types/pointers.go index 950d6a3..35c439d 100644 --- a/internal/sdk/types/pointers.go +++ b/internal/sdk/types/pointers.go @@ -8,3 +8,4 @@ func Int(i int) *int { return &i } func Int64(i int64) *int64 { return &i } func Float32(f float32) *float32 { return &f } func Float64(f float64) *float64 { return &f } +func Pointer[T any](v T) *T { return &v } diff --git a/internal/sdk/workflows.go b/internal/sdk/workflows.go index 968b937..5d329ec 100644 --- a/internal/sdk/workflows.go +++ b/internal/sdk/workflows.go @@ -6,14 +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" - "io" "net/http" "net/url" ) @@ -40,7 +37,6 @@ func (s *Workflows) CreateDefinition(ctx context.Context, request shared.Workflo o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -50,7 +46,12 @@ func (s *Workflows) CreateDefinition(ctx context.Context, request shared.Workflo } } - baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + var baseURL string + if o.ServerURL == nil { + baseURL = utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + } else { + baseURL = *o.ServerURL + } opURL, err := url.JoinPath(baseURL, "/v1/workflows/definitions") if err != nil { return nil, fmt.Errorf("error generating URL: %w", err) @@ -84,94 +85,36 @@ 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, - } - } + for k, v := range o.SetHeaders { + req.Header.Set(k, v) } - 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 - }) + 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 { - 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,17 +124,15 @@ func (s *Workflows) CreateDefinition(ctx context.Context, request shared.Workflo RawResponse: httpRes, } - rawBody, err := io.ReadAll(httpRes.Body) - if err != nil { - return nil, fmt.Errorf("error reading response body: %w", err) - } - httpRes.Body.Close() - httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) - 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) + if err != nil { + return nil, err + } + var out shared.WorkflowDefinition if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { return nil, err @@ -199,6 +140,10 @@ func (s *Workflows) CreateDefinition(ctx context.Context, request shared.Workflo res.WorkflowDefinition = &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: @@ -208,6 +153,11 @@ func (s *Workflows) CreateDefinition(ctx context.Context, request shared.Workflo 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 @@ -215,9 +165,17 @@ func (s *Workflows) CreateDefinition(ctx context.Context, request shared.Workflo 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) } @@ -237,7 +195,6 @@ func (s *Workflows) DeleteDefinition(ctx context.Context, request operations.Del o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -247,7 +204,12 @@ func (s *Workflows) DeleteDefinition(ctx context.Context, request operations.Del } } - baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + var baseURL string + if o.ServerURL == nil { + baseURL = utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + } else { + baseURL = *o.ServerURL + } opURL, err := utils.GenerateURL(ctx, baseURL, "/v1/workflows/definitions/{definitionId}", request, nil) if err != nil { return nil, fmt.Errorf("error generating URL: %w", err) @@ -275,94 +237,36 @@ 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, - } - } + for k, v := range o.SetHeaders { + req.Header.Set(k, v) } - 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 - }) + 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 { - 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 - } } } @@ -372,13 +276,6 @@ func (s *Workflows) DeleteDefinition(ctx context.Context, request operations.Del RawResponse: httpRes, } - rawBody, err := io.ReadAll(httpRes.Body) - if err != nil { - return nil, fmt.Errorf("error reading response body: %w", err) - } - httpRes.Body.Close() - httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) - switch { case httpRes.StatusCode == 204: fallthrough @@ -386,6 +283,11 @@ func (s *Workflows) DeleteDefinition(ctx context.Context, request operations.Del 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 @@ -393,9 +295,17 @@ func (s *Workflows) DeleteDefinition(ctx context.Context, request operations.Del 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) } @@ -415,7 +325,6 @@ func (s *Workflows) GetDefinition(ctx context.Context, request operations.GetDef o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -425,7 +334,12 @@ func (s *Workflows) GetDefinition(ctx context.Context, request operations.GetDef } } - baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + var baseURL string + if o.ServerURL == nil { + baseURL = utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + } else { + baseURL = *o.ServerURL + } opURL, err := utils.GenerateURL(ctx, baseURL, "/v1/workflows/definitions/{definitionId}", request, nil) if err != nil { return nil, fmt.Errorf("error generating URL: %w", err) @@ -453,95 +367,37 @@ 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, - } - } + for k, v := range o.SetHeaders { + req.Header.Set(k, v) } - 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") - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err + } - _, 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.GetDefinitionResponse{ @@ -550,17 +406,15 @@ func (s *Workflows) GetDefinition(ctx context.Context, request operations.GetDef RawResponse: httpRes, } - rawBody, err := io.ReadAll(httpRes.Body) - if err != nil { - return nil, fmt.Errorf("error reading response body: %w", err) - } - httpRes.Body.Close() - httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) - 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.WorkflowDefinition if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { return nil, err @@ -568,6 +422,10 @@ func (s *Workflows) GetDefinition(ctx context.Context, request operations.GetDef res.WorkflowDefinition = &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: @@ -577,6 +435,11 @@ func (s *Workflows) GetDefinition(ctx context.Context, request operations.GetDef 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 @@ -584,11 +447,20 @@ func (s *Workflows) GetDefinition(ctx context.Context, request operations.GetDef 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 @@ -596,9 +468,17 @@ func (s *Workflows) GetDefinition(ctx context.Context, request operations.GetDef 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) } @@ -618,7 +498,6 @@ func (s *Workflows) GetDefinitions(ctx context.Context, opts ...operations.Optio o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -628,7 +507,12 @@ func (s *Workflows) GetDefinitions(ctx context.Context, opts ...operations.Optio } } - baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + var baseURL string + if o.ServerURL == nil { + baseURL = utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + } else { + baseURL = *o.ServerURL + } opURL, err := url.JoinPath(baseURL, "/v1/workflows/definitions") if err != nil { return nil, fmt.Errorf("error generating URL: %w", err) @@ -656,94 +540,36 @@ 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, - } - } + for k, v := range o.SetHeaders { + req.Header.Set(k, v) } - 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 - }) + 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 { - 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 - } } } @@ -753,17 +579,15 @@ func (s *Workflows) GetDefinitions(ctx context.Context, opts ...operations.Optio RawResponse: httpRes, } - rawBody, err := io.ReadAll(httpRes.Body) - if err != nil { - return nil, fmt.Errorf("error reading response body: %w", err) - } - httpRes.Body.Close() - httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) - 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.WorkflowDefinition if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { return nil, err @@ -771,11 +595,20 @@ func (s *Workflows) GetDefinitions(ctx context.Context, opts ...operations.Optio res.Classes = 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 @@ -783,9 +616,17 @@ func (s *Workflows) GetDefinitions(ctx context.Context, opts ...operations.Optio 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) } @@ -805,7 +646,6 @@ func (s *Workflows) GetMaxAllowedLimit(ctx context.Context, opts ...operations.O o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -815,7 +655,12 @@ func (s *Workflows) GetMaxAllowedLimit(ctx context.Context, opts ...operations.O } } - baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + var baseURL string + if o.ServerURL == nil { + baseURL = utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + } else { + baseURL = *o.ServerURL + } opURL, err := url.JoinPath(baseURL, "/v1/workflows/limits/max-allowed") if err != nil { return nil, fmt.Errorf("error generating URL: %w", err) @@ -843,94 +688,36 @@ 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, - } - } + for k, v := range o.SetHeaders { + req.Header.Set(k, v) } - 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 - }) + 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 { - 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 - } } } @@ -940,17 +727,15 @@ func (s *Workflows) GetMaxAllowedLimit(ctx context.Context, opts ...operations.O RawResponse: httpRes, } - rawBody, err := io.ReadAll(httpRes.Body) - if err != nil { - return nil, fmt.Errorf("error reading response body: %w", err) - } - httpRes.Body.Close() - httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) - 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.MaxAllowedLimit if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { return nil, err @@ -958,11 +743,20 @@ func (s *Workflows) GetMaxAllowedLimit(ctx context.Context, opts ...operations.O res.MaxAllowedLimit = &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 @@ -970,9 +764,17 @@ func (s *Workflows) GetMaxAllowedLimit(ctx context.Context, opts ...operations.O 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) } @@ -992,7 +794,6 @@ func (s *Workflows) GetWorkflowClosingReasons(ctx context.Context, request opera o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -1002,7 +803,12 @@ func (s *Workflows) GetWorkflowClosingReasons(ctx context.Context, request opera } } - baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + var baseURL string + if o.ServerURL == nil { + baseURL = utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + } else { + baseURL = *o.ServerURL + } opURL, err := utils.GenerateURL(ctx, baseURL, "/v1/workflows/definitions/{definitionId}/closing-reasons", request, nil) if err != nil { return nil, fmt.Errorf("error generating URL: %w", err) @@ -1030,94 +836,36 @@ 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, - } - } + for k, v := range o.SetHeaders { + req.Header.Set(k, v) } - 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 - }) + 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 { - 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 - } } } @@ -1127,17 +875,15 @@ func (s *Workflows) GetWorkflowClosingReasons(ctx context.Context, request opera RawResponse: httpRes, } - rawBody, err := io.ReadAll(httpRes.Body) - if err != nil { - return nil, fmt.Errorf("error reading response body: %w", err) - } - httpRes.Body.Close() - httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) - 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.ClosingReasonsIds if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { return nil, err @@ -1145,9 +891,17 @@ func (s *Workflows) GetWorkflowClosingReasons(ctx context.Context, request opera res.ClosingReasonsIds = &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) } @@ -1167,7 +921,6 @@ func (s *Workflows) SetWorkflowClosingReasons(ctx context.Context, request opera o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -1177,7 +930,12 @@ func (s *Workflows) SetWorkflowClosingReasons(ctx context.Context, request opera } } - baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + var baseURL string + if o.ServerURL == nil { + baseURL = utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + } else { + baseURL = *o.ServerURL + } opURL, err := utils.GenerateURL(ctx, baseURL, "/v1/workflows/definitions/{definitionId}/closing-reasons", request, nil) if err != nil { return nil, fmt.Errorf("error generating URL: %w", err) @@ -1211,94 +969,36 @@ 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, - } - } + for k, v := range o.SetHeaders { + req.Header.Set(k, v) } - 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 - }) + 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 { - 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 - } } } @@ -1308,16 +1008,13 @@ func (s *Workflows) SetWorkflowClosingReasons(ctx context.Context, request opera RawResponse: httpRes, } - rawBody, err := io.ReadAll(httpRes.Body) - if err != nil { - return nil, fmt.Errorf("error reading response body: %w", err) - } - httpRes.Body.Close() - httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) - switch { case httpRes.StatusCode == 201: 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) } @@ -1337,7 +1034,6 @@ func (s *Workflows) UpdateDefinition(ctx context.Context, request operations.Upd o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -1347,7 +1043,12 @@ func (s *Workflows) UpdateDefinition(ctx context.Context, request operations.Upd } } - baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + var baseURL string + if o.ServerURL == nil { + baseURL = utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + } else { + baseURL = *o.ServerURL + } opURL, err := utils.GenerateURL(ctx, baseURL, "/v1/workflows/definitions/{definitionId}", request, nil) if err != nil { return nil, fmt.Errorf("error generating URL: %w", err) @@ -1381,94 +1082,36 @@ 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, - } - } + for k, v := range o.SetHeaders { + req.Header.Set(k, v) } - 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 - }) + 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 { - 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 - } } } @@ -1478,17 +1121,15 @@ func (s *Workflows) UpdateDefinition(ctx context.Context, request operations.Upd RawResponse: httpRes, } - rawBody, err := io.ReadAll(httpRes.Body) - if err != nil { - return nil, fmt.Errorf("error reading response body: %w", err) - } - httpRes.Body.Close() - httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) - 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.WorkflowDefinition if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { return nil, err @@ -1496,6 +1137,10 @@ func (s *Workflows) UpdateDefinition(ctx context.Context, request operations.Upd res.WorkflowDefinition = &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: @@ -1505,6 +1150,11 @@ func (s *Workflows) UpdateDefinition(ctx context.Context, request operations.Upd 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 @@ -1512,9 +1162,17 @@ func (s *Workflows) UpdateDefinition(ctx context.Context, request operations.Upd 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) }