Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
184 changes: 184 additions & 0 deletions template.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
package signalfx

import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"

"github.com/signalfx/signalfx-go/template"
)

// TemplateAPIURL is the base URL for interacting with Template API records.
const TemplateAPIURL = "/v2/template"

var (
errEmptyTemplateID = errors.New("template ID must not be empty")
errInvalidTemplateID = errors.New("template ID must be a single path segment")
errNilTemplateWrite = errors.New("template write must not be nil")
)

// CreateTemplate creates a Template record.
func (c *Client) CreateTemplate(ctx context.Context, write *template.CreateUpdateTemplateRequest) (*template.Result, error) {
if write == nil {
return nil, errNilTemplateWrite
}

result := &template.Result{}
if err := c.executeTemplateRequest(ctx, http.MethodPost, TemplateAPIURL, http.StatusCreated, write, nil, result); err != nil {
return nil, err
}

return result, nil
}

// GetTemplate gets a Template record by ID.
func (c *Client) GetTemplate(ctx context.Context, id string, options *template.GetOptions) (*template.Result, error) {
path, err := templateAPIPath(id)
if err != nil {
return nil, err
}

result := &template.Result{}
if err := c.executeTemplateRequest(ctx, http.MethodGet, path, http.StatusOK, nil, templateGetParams(options), result); err != nil {
return nil, err
}

return result, nil
}

// UpdateTemplate fully replaces a Template record.
func (c *Client) UpdateTemplate(ctx context.Context, id string, write *template.CreateUpdateTemplateRequest) (*template.Result, error) {
path, err := templateAPIPath(id)
if err != nil {
return nil, err
}
if write == nil {
return nil, errNilTemplateWrite
}

result := &template.Result{}
if err := c.executeTemplateRequest(ctx, http.MethodPut, path, http.StatusOK, write, nil, result); err != nil {
return nil, err
}

return result, nil
}

// DeleteTemplate deletes a Template record.
func (c *Client) DeleteTemplate(ctx context.Context, id string) error {
path, err := templateAPIPath(id)
if err != nil {
return err
}

return c.executeTemplateRequest(ctx, http.MethodDelete, path, http.StatusNoContent, nil, nil, nil)
}

// SearchTemplates searches Template records.
func (c *Client) SearchTemplates(ctx context.Context, options *template.SearchOptions) (*template.SearchResult, error) {
result := &template.SearchResult{}
if err := c.executeTemplateRequest(ctx, http.MethodGet, TemplateAPIURL, http.StatusOK, nil, templateSearchParams(options), result); err != nil {
return nil, err
}

return result, nil
}

func (c *Client) executeTemplateRequest(ctx context.Context, method string, path string, expectedStatus int, write *template.CreateUpdateTemplateRequest, params url.Values, result any) error {
var body io.Reader
if write != nil {
payload, err := json.Marshal(write)
if err != nil {
return fmt.Errorf("marshal template request: %w", err)
}
body = bytes.NewReader(payload)
}

resp, err := c.doRequest(ctx, method, path, params, body)
if err != nil {
return err
}
defer resp.Body.Close()

if err := newResponseError(resp, expectedStatus); err != nil {
return err
}

if result == nil {
_, _ = io.Copy(io.Discard, resp.Body)
return nil
}

if err := json.NewDecoder(resp.Body).Decode(result); err != nil {
_, _ = io.Copy(io.Discard, resp.Body)
return fmt.Errorf("decode template response: %w", err)
}
_, _ = io.Copy(io.Discard, resp.Body)

return nil
}

func templateAPIPath(id string) (string, error) {
if id == "" {
return "", errEmptyTemplateID
}
if id == "." || id == ".." || strings.Contains(id, "/") {
return "", errInvalidTemplateID
}
return TemplateAPIURL + "/" + id, nil
}

func templateGetParams(options *template.GetOptions) url.Values {
if options == nil {
return url.Values{}
}

params := url.Values{}
addTemplateImports(params, options.Imports)
return params
}

func templateSearchParams(options *template.SearchOptions) url.Values {
if options == nil {
return url.Values{}
}

params := url.Values{}
if options.Search != "" {
params.Set("search", options.Search)
}
for _, rootElement := range options.RootElements {
params.Add("rootElement", string(rootElement))
}
for _, id := range options.IDs {
params.Add("id", id)
}
for _, title := range options.Titles {
params.Add("title", title)
}
for _, orderBy := range options.OrderBy {
params.Add("orderBy", orderBy)
}
if options.Offset != 0 {
params.Set("offset", strconv.Itoa(options.Offset))
}
if options.Size != 0 {
params.Set("size", strconv.Itoa(options.Size))
}
addTemplateImports(params, options.Imports)

return params
}

func addTemplateImports(params url.Values, imports []template.Import) {
for _, include := range imports {
params.Add("import", string(include))
}
}
2 changes: 2 additions & 0 deletions template/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// Package template contains request and response models for the Template API.
package template
19 changes: 19 additions & 0 deletions template/model_options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package template

// GetOptions controls related records included with a Template read.
type GetOptions struct {
Imports []Import
}

// SearchOptions contains optional Template search filters and pagination.
// Slice fields are encoded as repeated query parameters in their given order.
type SearchOptions struct {
Search string
RootElements []RootElement
IDs []string
Titles []string
OrderBy []string
Offset int
Size int
Imports []Import
}
117 changes: 117 additions & 0 deletions template/model_template.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package template

import (
"encoding/json"

"github.com/signalfx/signalfx-go/util"
)

// RootElement identifies the kind of document stored in a Template record.
type RootElement string

const (
// RootElementDashboard identifies a Dashboard template document.
RootElementDashboard RootElement = "Dashboard"
// RootElementChart identifies a reusable Chart template document.
RootElementChart RootElement = "Chart"
)

// Import controls which related Template records the API includes in a
// response.
type Import string

const (
// ImportAllChildren requests all transitively imported Template records.
ImportAllChildren Import = "ALL_CHILDREN"
)

// DatasourceType identifies the kind of datasource associated with a Template
// write request.
type DatasourceType string

const (
// DatasourceTypeSplunkObservability identifies a SignalFlow datasource.
DatasourceTypeSplunkObservability DatasourceType = "SPLUNK_O11Y"
// DatasourceTypeSplunkObservabilitySLO identifies a Splunk Observability
// service-level objective datasource.
DatasourceTypeSplunkObservabilitySLO DatasourceType = "SPLUNK_O11Y_SLO"
)

// Datasource contains optional datasource metadata accepted when creating or
// replacing a Template. The API does not return this object in Template read
// metadata.
type Datasource struct {
Type DatasourceType `json:"type,omitempty"`
ProgramText string `json:"programText,omitempty"`
SLOID string `json:"sloId,omitempty"`
}

// WriteMetadata describes a Template document and the metadata extracted from
// it for a create or replace request.
type WriteMetadata struct {
RootElement *RootElement `json:"rootElement"`
Imports []string `json:"imports,omitempty"`
Datasource *Datasource `json:"datasource,omitempty"`
}

// Metadata describes the read-only metadata returned for a Template document.
type Metadata struct {
RootElement *RootElement `json:"rootElement"`
Imports []string `json:"imports"`
}

// CreateUpdateTemplateRequest is the body used to create or replace a Template record.
//
// Spec contains the polymorphic Dashify document. SignalView is omitted for a
// nil value and may contain the association update object accepted by the API.
type CreateUpdateTemplateRequest struct {
// Type is the record type identifier expected by the Template API.
Type string `json:"type"`
Spec json.RawMessage `json:"spec"`
Title string `json:"title"`
Metadata WriteMetadata `json:"metadata"`
SignalView json.RawMessage `json:"signalview,omitempty"`
Comment thread
MovieStoreGuy marked this conversation as resolved.
}

// Template is a Template record returned by the API.
type Template struct {
ID string `json:"id"`
Self string `json:"self"`
Type string `json:"type"`
Title string `json:"title"`
Spec json.RawMessage `json:"spec"`
Metadata *Metadata `json:"metadata"`
SignalView json.RawMessage `json:"signalview"`
DirectoryEntries []string `json:"directoryEntries"`
CreatedAt string `json:"createdAt"`
CreatedBy *string `json:"createdBy"`
UpdatedAt string `json:"updatedAt"`
UpdatedBy *string `json:"updatedBy"`
}

type APIError = util.APIError

// Result is the response envelope for a single Template operation.
type Result struct {
Data *Template `json:"data"`
Errors []APIError `json:"errors"`
Includes []Template `json:"includes"`
}

// SearchPage contains the pagination links, total count, and Template URI
// references returned by a Template search.
type SearchPage struct {
Type string `json:"type"`
Self string `json:"self"`
Next *string `json:"next"`
Prev *string `json:"prev"`
Count int64 `json:"count"`
Items []string `json:"items"`
}

// SearchResult is the response envelope for a Template search.
type SearchResult struct {
Data *SearchPage `json:"data"`
Errors []APIError `json:"errors"`
Includes []Template `json:"includes"`
}
Loading
Loading