Skip to content

improve the trigger.execute function #61

@RabbITCybErSeC

Description

@RabbITCybErSeC

reuse existing context, with timeout instead of current trigger.execute functionality"

func (trigger *triggerHandler) execute(playbook *cacao.Playbook, context *gin.Context) {
	decomposer := trigger.controller.NewDecomposer()
	go decomposer.ExecuteAsync(*playbook, trigger.ExecutionsChannel)
	timer := time.NewTimer(time.Duration(3) * time.Second)
	for {
		select {
		case <-timer.C:
			log.Error("async execution timed out for playbook ", playbook.ID)

			apiError.SendErrorResponse(context,
				http.StatusRequestTimeout,
				"async execution timed out for playbook "+playbook.ID,
				"POST "+context.Request.URL.Path, "")
			return

		case executionsDetail := <-trigger.ExecutionsChannel:
			playbookId := executionsDetail.PlaybookId
			executionId := executionsDetail.ExecutionId
			if playbookId == playbook.ID {
				context.JSON(http.StatusOK,
					api.Execution{ExecutionId: executionId,
						PlaybookId: playbookId})
				return
			}
		}
	}
}

to something like:

func (trigger *triggerHandler) execute(playbook *cacao.Playbook, context *gin.Context) {

    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()

    decomposer := trigger.controller.NewDecomposer()
    
    executionResultChan := make(chan ExecutionResult, 1)
    
    go func() {
        defer close(executionResultChan)
        executionDetails := decomposer.ExecuteAsync(ctx, *playbook)
        executionResultChan <- executionDetails
    }()

    select {
    case <-ctx.Done():

        log.Error("async execution timed out for playbook", playbook.ID)
        apiError.SendErrorResponse(context,
            http.StatusRequestTimeout,
            fmt.Sprintf("async execution timed out for playbook %s", playbook.ID),
            "POST "+context.Request.URL.Path, "")
        return

    case result, ok := <-executionResultChan:
        if !ok {
  
            log.Error("execution channel closed unexpectedly")
            apiError.SendErrorResponse(context,
                http.StatusInternalServerError,
                "execution failed", 
                "POST "+context.Request.URL.Path, "")
            return
        }

        if result.PlaybookId == playbook.ID {
            context.JSON(http.StatusOK, api.Execution{
                ExecutionId: result.ExecutionId,
                PlaybookId:  result.PlaybookId,
            })
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions