github.com/akamai/AkamaiOPEN-edgegrid-golang/v8@v8.1.0/pkg/cloudlets/policy_version.go (about)

     1  package cloudlets
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"fmt"
     7  	"net/http"
     8  	"net/url"
     9  	"strconv"
    10  
    11  	"github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr"
    12  
    13  	validation "github.com/go-ozzo/ozzo-validation/v4"
    14  )
    15  
    16  type (
    17  	// PolicyVersions is a cloudlets policy versions API interface.
    18  	PolicyVersions interface {
    19  		// ListPolicyVersions lists policy versions by policyID.
    20  		//
    21  		// See: https://techdocs.akamai.com/cloudlets/v2/reference/get-policy-versions
    22  		ListPolicyVersions(context.Context, ListPolicyVersionsRequest) ([]PolicyVersion, error)
    23  
    24  		// GetPolicyVersion gets policy version by policyID and version.
    25  		//
    26  		// See: https://techdocs.akamai.com/cloudlets/v2/reference/get-policy-version
    27  		GetPolicyVersion(context.Context, GetPolicyVersionRequest) (*PolicyVersion, error)
    28  
    29  		// CreatePolicyVersion creates policy version.
    30  		//
    31  		// See: https://techdocs.akamai.com/cloudlets/v2/reference/post-policy-versions
    32  		CreatePolicyVersion(context.Context, CreatePolicyVersionRequest) (*PolicyVersion, error)
    33  
    34  		// DeletePolicyVersion deletes policy version.
    35  		//
    36  		// See: https://techdocs.akamai.com/cloudlets/v2/reference/delete-policy-version
    37  		DeletePolicyVersion(context.Context, DeletePolicyVersionRequest) error
    38  
    39  		// UpdatePolicyVersion updates policy version.
    40  		//
    41  		// See: https://techdocs.akamai.com/cloudlets/v2/reference/put-policy-version
    42  		UpdatePolicyVersion(context.Context, UpdatePolicyVersionRequest) (*PolicyVersion, error)
    43  	}
    44  
    45  	// PolicyVersion is response returned by GetPolicyVersion, CreatePolicyVersion or UpdatePolicyVersion
    46  	PolicyVersion struct {
    47  		Location         string             `json:"location"`
    48  		RevisionID       int64              `json:"revisionId"`
    49  		PolicyID         int64              `json:"policyId"`
    50  		Version          int64              `json:"version"`
    51  		Description      string             `json:"description"`
    52  		CreatedBy        string             `json:"createdBy"`
    53  		CreateDate       int64              `json:"createDate"`
    54  		LastModifiedBy   string             `json:"lastModifiedBy"`
    55  		LastModifiedDate int64              `json:"lastModifiedDate"`
    56  		RulesLocked      bool               `json:"rulesLocked"`
    57  		Activations      []PolicyActivation `json:"activations"`
    58  		MatchRules       MatchRules         `json:"matchRules"`
    59  		MatchRuleFormat  MatchRuleFormat    `json:"matchRuleFormat"`
    60  		Deleted          bool               `json:"deleted,omitempty"`
    61  		Warnings         []Warning          `json:"warnings,omitempty"`
    62  	}
    63  
    64  	// ListPolicyVersionsRequest describes the parameters needed to list policy versions
    65  	ListPolicyVersionsRequest struct {
    66  		PolicyID           int64
    67  		IncludeRules       bool
    68  		IncludeDeleted     bool
    69  		IncludeActivations bool
    70  		Offset             int
    71  		PageSize           *int
    72  	}
    73  
    74  	// GetPolicyVersionRequest describes the parameters needed to get policy version
    75  	GetPolicyVersionRequest struct {
    76  		PolicyID  int64
    77  		Version   int64
    78  		OmitRules bool
    79  	}
    80  
    81  	// CreatePolicyVersionRequest describes the body of the create policy request
    82  	CreatePolicyVersionRequest struct {
    83  		CreatePolicyVersion
    84  		PolicyID int64
    85  	}
    86  
    87  	// CreatePolicyVersion describes the body of the create policy request
    88  	CreatePolicyVersion struct {
    89  		Description     string          `json:"description,omitempty"`
    90  		MatchRuleFormat MatchRuleFormat `json:"matchRuleFormat,omitempty"`
    91  		MatchRules      MatchRules      `json:"matchRules"`
    92  	}
    93  
    94  	// UpdatePolicyVersion describes the body of the update policy version request
    95  	UpdatePolicyVersion struct {
    96  		Description     string          `json:"description,omitempty"`
    97  		MatchRuleFormat MatchRuleFormat `json:"matchRuleFormat,omitempty"`
    98  		MatchRules      MatchRules      `json:"matchRules"`
    99  		Deleted         bool            `json:"deleted"`
   100  	}
   101  
   102  	// DeletePolicyVersionRequest describes the parameters of the delete policy version request
   103  	DeletePolicyVersionRequest struct {
   104  		PolicyID int64
   105  		Version  int64
   106  	}
   107  
   108  	// UpdatePolicyVersionRequest describes the parameters of the update policy version request
   109  	UpdatePolicyVersionRequest struct {
   110  		UpdatePolicyVersion
   111  		PolicyID int64
   112  		Version  int64
   113  	}
   114  )
   115  
   116  // Validate validates ListPolicyVersionsRequest
   117  func (c ListPolicyVersionsRequest) Validate() error {
   118  	errs := validation.Errors{
   119  		"PolicyID": validation.Validate(c.PolicyID, validation.Required),
   120  		"Offset":   validation.Validate(c.Offset, validation.Min(0)),
   121  	}
   122  	return edgegriderr.ParseValidationErrors(errs)
   123  }
   124  
   125  // Validate validates CreatePolicyVersionRequest
   126  func (c CreatePolicyVersionRequest) Validate() error {
   127  	errs := validation.Errors{
   128  		"Description": validation.Validate(c.Description, validation.Length(0, 255)),
   129  		"MatchRuleFormat": validation.Validate(c.MatchRuleFormat, validation.In(MatchRuleFormat10).Error(
   130  			fmt.Sprintf("value '%s' is invalid. Must be one of: '1.0' or '' (empty)", (&c).MatchRuleFormat))),
   131  		"MatchRules": validation.Validate(c.MatchRules, validation.Length(0, 5000)),
   132  	}
   133  	return edgegriderr.ParseValidationErrors(errs)
   134  }
   135  
   136  // Validate validates UpdatePolicyVersionRequest
   137  func (o UpdatePolicyVersionRequest) Validate() error {
   138  	errs := validation.Errors{
   139  		"Description": validation.Validate(o.Description, validation.Length(0, 255)),
   140  		"MatchRuleFormat": validation.Validate(o.MatchRuleFormat, validation.In(MatchRuleFormat10).Error(
   141  			fmt.Sprintf("value '%s' is invalid. Must be one of: '1.0' or '' (empty)", (&o).MatchRuleFormat))),
   142  		"MatchRules": validation.Validate(o.MatchRules, validation.Length(0, 5000)),
   143  	}
   144  	return edgegriderr.ParseValidationErrors(errs)
   145  }
   146  
   147  var (
   148  	// ErrListPolicyVersions is returned when ListPolicyVersions fails
   149  	ErrListPolicyVersions = errors.New("list policy versions")
   150  	// ErrGetPolicyVersion is returned when GetPolicyVersion fails
   151  	ErrGetPolicyVersion = errors.New("get policy versions")
   152  	// ErrCreatePolicyVersion is returned when CreatePolicyVersion fails
   153  	ErrCreatePolicyVersion = errors.New("create policy versions")
   154  	// ErrDeletePolicyVersion is returned when DeletePolicyVersion fails
   155  	ErrDeletePolicyVersion = errors.New("delete policy versions")
   156  	// ErrUpdatePolicyVersion is returned when UpdatePolicyVersion fails
   157  	ErrUpdatePolicyVersion = errors.New("update policy versions")
   158  )
   159  
   160  func (c *cloudlets) ListPolicyVersions(ctx context.Context, params ListPolicyVersionsRequest) ([]PolicyVersion, error) {
   161  	logger := c.Log(ctx)
   162  	logger.Debug("ListPolicyVersions")
   163  
   164  	if err := params.Validate(); err != nil {
   165  		return nil, fmt.Errorf("%s: %w:\n%s", ErrListPolicyVersions, ErrStructValidation, err)
   166  	}
   167  
   168  	uri, err := url.Parse(fmt.Sprintf("/cloudlets/api/v2/policies/%d/versions", params.PolicyID))
   169  	if err != nil {
   170  		return nil, fmt.Errorf("%w: failed to parse url: %s", ErrListPolicyVersions, err)
   171  	}
   172  
   173  	q := uri.Query()
   174  	q.Add("offset", fmt.Sprintf("%d", params.Offset))
   175  	q.Add("includeRules", strconv.FormatBool(params.IncludeRules))
   176  	q.Add("includeDeleted", strconv.FormatBool(params.IncludeDeleted))
   177  	q.Add("includeActivations", strconv.FormatBool(params.IncludeActivations))
   178  	if params.PageSize != nil {
   179  		q.Add("pageSize", fmt.Sprintf("%d", *params.PageSize))
   180  	}
   181  	uri.RawQuery = q.Encode()
   182  
   183  	req, err := http.NewRequestWithContext(ctx, http.MethodGet, uri.String(), nil)
   184  	if err != nil {
   185  		return nil, fmt.Errorf("%w: failed to create request: %s", ErrListPolicyVersions, err)
   186  	}
   187  
   188  	var result []PolicyVersion
   189  	resp, err := c.Exec(req, &result)
   190  	if err != nil {
   191  		return nil, fmt.Errorf("%w: request failed: %s", ErrListPolicyVersions, err)
   192  	}
   193  
   194  	if resp.StatusCode != http.StatusOK {
   195  		return nil, fmt.Errorf("%s: %w", ErrListPolicyVersions, c.Error(resp))
   196  	}
   197  
   198  	return result, nil
   199  }
   200  
   201  func (c *cloudlets) GetPolicyVersion(ctx context.Context, params GetPolicyVersionRequest) (*PolicyVersion, error) {
   202  	logger := c.Log(ctx)
   203  	logger.Debug("GetPolicyVersion")
   204  
   205  	var result PolicyVersion
   206  
   207  	uri, err := url.Parse(fmt.Sprintf(
   208  		"/cloudlets/api/v2/policies/%d/versions/%d",
   209  		params.PolicyID, params.Version),
   210  	)
   211  	if err != nil {
   212  		return nil, fmt.Errorf("%w: failed to parse url: %s", ErrGetPolicyVersion, err)
   213  	}
   214  
   215  	q := uri.Query()
   216  	q.Add("omitRules", strconv.FormatBool(params.OmitRules))
   217  	uri.RawQuery = q.Encode()
   218  
   219  	req, err := http.NewRequestWithContext(ctx, http.MethodGet, uri.String(), nil)
   220  	if err != nil {
   221  		return nil, fmt.Errorf("%w: failed to create request: %s", ErrGetPolicyVersion, err)
   222  	}
   223  
   224  	resp, err := c.Exec(req, &result)
   225  	if err != nil {
   226  		return nil, fmt.Errorf("%w: request failed: %s", ErrGetPolicyVersion, err)
   227  	}
   228  
   229  	if resp.StatusCode != http.StatusOK {
   230  		return nil, fmt.Errorf("%s: %w", ErrGetPolicyVersion, c.Error(resp))
   231  	}
   232  
   233  	return &result, nil
   234  }
   235  
   236  func (c *cloudlets) CreatePolicyVersion(ctx context.Context, params CreatePolicyVersionRequest) (*PolicyVersion, error) {
   237  	logger := c.Log(ctx)
   238  	logger.Debug("CreatePolicyVersion")
   239  
   240  	if err := params.Validate(); err != nil {
   241  		return nil, fmt.Errorf("%s: %w:\n%s", ErrCreatePolicyVersion, ErrStructValidation, err)
   242  	}
   243  
   244  	uri, err := url.Parse(fmt.Sprintf("/cloudlets/api/v2/policies/%d/versions", params.PolicyID))
   245  	if err != nil {
   246  		return nil, fmt.Errorf("%w: failed to parse url: %s", ErrCreatePolicyVersion, err)
   247  	}
   248  
   249  	req, err := http.NewRequestWithContext(ctx, http.MethodPost, uri.String(), nil)
   250  	if err != nil {
   251  		return nil, fmt.Errorf("%w: failed to create request: %s", ErrCreatePolicyVersion, err)
   252  	}
   253  
   254  	var result PolicyVersion
   255  
   256  	resp, err := c.Exec(req, &result, params.CreatePolicyVersion)
   257  	if err != nil {
   258  		return nil, fmt.Errorf("%w: request failed: %s", ErrCreatePolicyVersion, err)
   259  	}
   260  
   261  	if resp.StatusCode != http.StatusCreated {
   262  		return nil, fmt.Errorf("%s: %w", ErrCreatePolicyVersion, c.Error(resp))
   263  	}
   264  
   265  	return &result, nil
   266  }
   267  
   268  func (c *cloudlets) DeletePolicyVersion(ctx context.Context, params DeletePolicyVersionRequest) error {
   269  	logger := c.Log(ctx)
   270  	logger.Debug("DeletePolicyVersion")
   271  
   272  	uri, err := url.Parse(fmt.Sprintf("/cloudlets/api/v2/policies/%d/versions/%d", params.PolicyID, params.Version))
   273  	if err != nil {
   274  		return fmt.Errorf("%w: failed to parse url: %s", ErrDeletePolicyVersion, err)
   275  	}
   276  
   277  	req, err := http.NewRequestWithContext(ctx, http.MethodDelete, uri.String(), nil)
   278  	if err != nil {
   279  		return fmt.Errorf("%w: failed to create request: %s", ErrDeletePolicyVersion, err)
   280  	}
   281  
   282  	resp, err := c.Exec(req, nil)
   283  	if err != nil {
   284  		return fmt.Errorf("%w: request failed: %s", ErrDeletePolicyVersion, err)
   285  	}
   286  
   287  	if resp.StatusCode != http.StatusNoContent {
   288  		return fmt.Errorf("%s: %w", ErrDeletePolicyVersion, c.Error(resp))
   289  	}
   290  
   291  	return nil
   292  }
   293  
   294  func (c *cloudlets) UpdatePolicyVersion(ctx context.Context, params UpdatePolicyVersionRequest) (*PolicyVersion, error) {
   295  	logger := c.Log(ctx)
   296  	logger.Debug("UpdatePolicyVersion")
   297  
   298  	if err := params.Validate(); err != nil {
   299  		return nil, fmt.Errorf("%s: %w:\n%s", ErrUpdatePolicyVersion, ErrStructValidation, err)
   300  	}
   301  
   302  	uri, err := url.Parse(fmt.Sprintf("/cloudlets/api/v2/policies/%d/versions/%d", params.PolicyID, params.Version))
   303  	if err != nil {
   304  		return nil, fmt.Errorf("%w: failed to parse url: %s", ErrUpdatePolicyVersion, err)
   305  	}
   306  
   307  	req, err := http.NewRequestWithContext(ctx, http.MethodPut, uri.String(), nil)
   308  	if err != nil {
   309  		return nil, fmt.Errorf("%w: failed to create request: %s", ErrUpdatePolicyVersion, err)
   310  	}
   311  
   312  	var result PolicyVersion
   313  
   314  	resp, err := c.Exec(req, &result, params.UpdatePolicyVersion)
   315  	if err != nil {
   316  		return nil, fmt.Errorf("%w: request failed: %s", ErrUpdatePolicyVersion, err)
   317  	}
   318  
   319  	if resp.StatusCode != http.StatusOK {
   320  		return nil, fmt.Errorf("%s: %w", ErrUpdatePolicyVersion, c.Error(resp))
   321  	}
   322  
   323  	return &result, nil
   324  }