github.com/kyma-project/kyma/components/asset-store-controller-manager@v0.0.0-20191203152857-3792b5df17c5/internal/assethook/mutation_engine.go (about)

     1  package assethook
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"github.com/pkg/errors"
     7  	"io"
     8  	"io/ioutil"
     9  	"os"
    10  	"path/filepath"
    11  	"time"
    12  
    13  	"github.com/kyma-project/kyma/components/asset-store-controller-manager/pkg/apis/assetstore/v1alpha2"
    14  )
    15  
    16  type mutationEngine struct {
    17  	processor httpProcessor
    18  }
    19  
    20  //go:generate mockery -name=Mutator -output=automock -outpkg=automock -case=underscore
    21  type Mutator interface {
    22  	Mutate(ctx context.Context, basePath string, files []string, services []v1alpha2.AssetWebhookService) (Result, error)
    23  }
    24  
    25  func NewMutator(httpClient HttpClient, timeout time.Duration, workers int) Mutator {
    26  	return &mutationEngine{
    27  		processor: &processor{
    28  			timeout:        timeout,
    29  			workers:        workers,
    30  			onFail:         mutationFailureHandler,
    31  			onSuccess:      mutationSuccessHandler,
    32  			continueOnFail: false,
    33  			httpClient:     httpClient,
    34  		},
    35  	}
    36  }
    37  
    38  func mutationSuccessHandler(_ context.Context, basePath, filePath string, responseBody io.Reader, _ chan Message, errChan chan error) {
    39  	path := filepath.Join(basePath, filePath)
    40  	body, err := ioutil.ReadAll(responseBody)
    41  	if err != nil {
    42  		errChan <- errors.Wrap(err, "while reading response body")
    43  		return
    44  	}
    45  
    46  	err = ioutil.WriteFile(path, body, os.ModePerm)
    47  	if err != nil {
    48  		errChan <- errors.Wrapf(err, "while writing file %s", path)
    49  	}
    50  }
    51  
    52  func mutationFailureHandler(_ context.Context, _, filePath string, responseBody io.Reader, messagesChan chan Message, _ chan error) {
    53  	buffer := new(bytes.Buffer)
    54  	buffer.ReadFrom(responseBody)
    55  
    56  	message := Message{Filename: filePath, Message: buffer.String()}
    57  	messagesChan <- message
    58  }
    59  
    60  func (e *mutationEngine) Mutate(ctx context.Context, basePath string, files []string, services []v1alpha2.AssetWebhookService) (Result, error) {
    61  	results, err := e.processor.Do(ctx, basePath, files, services)
    62  	if err != nil {
    63  		return Result{}, errors.Wrap(err, "while mutating")
    64  	}
    65  
    66  	return Result{
    67  		Success:  len(results) == 0,
    68  		Messages: results,
    69  	}, nil
    70  }