emissary/internal/client/query_agents.go

89 lines
2.0 KiB
Go

package client
import (
"context"
"fmt"
"net/url"
"forge.cadoles.com/Cadoles/emissary/internal/datastore"
"github.com/pkg/errors"
)
type QueryAgentsOptionFunc func(*QueryAgentsOptions)
type QueryAgentsOptions struct {
Limit *int
Offset *int
RemoteIDs []string
IDs []datastore.AgentID
Statuses []datastore.AgentStatus
}
func WithQueryAgentsLimit(limit int) QueryAgentsOptionFunc {
return func(opts *QueryAgentsOptions) {
opts.Limit = &limit
}
}
func WithQueryAgentsOffset(offset int) QueryAgentsOptionFunc {
return func(opts *QueryAgentsOptions) {
opts.Offset = &offset
}
}
func WithQueryAgentsRemoteID(remoteIDs ...string) QueryAgentsOptionFunc {
return func(opts *QueryAgentsOptions) {
opts.RemoteIDs = remoteIDs
}
}
func WithQueryAgentsID(ids ...datastore.AgentID) QueryAgentsOptionFunc {
return func(opts *QueryAgentsOptions) {
opts.IDs = ids
}
}
func WithQueryAgentsStatus(statuses ...datastore.AgentStatus) QueryAgentsOptionFunc {
return func(opts *QueryAgentsOptions) {
opts.Statuses = statuses
}
}
func (c *Client) QueryAgents(ctx context.Context, funcs ...QueryAgentsOptionFunc) ([]*datastore.Agent, int, error) {
options := &QueryAgentsOptions{}
for _, fn := range funcs {
fn(options)
}
query := url.Values{}
if options.IDs != nil && len(options.IDs) > 0 {
query.Set("ids", joinSlice(options.IDs))
}
if options.RemoteIDs != nil && len(options.RemoteIDs) > 0 {
query.Set("remoteIds", joinSlice(options.RemoteIDs))
}
if options.Statuses != nil && len(options.RemoteIDs) > 0 {
query.Set("statuses", joinSlice(options.Statuses))
}
path := fmt.Sprintf("/api/v1/agents?%s", query.Encode())
response := withResponse[struct {
Agents []*datastore.Agent `json:"agents"`
Total int `json:"total"`
}]()
if err := c.apiGet(ctx, path, &response); err != nil {
return nil, 0, errors.WithStack(err)
}
if response.Error != nil {
return nil, 0, errors.WithStack(response.Error)
}
return response.Data.Agents, response.Data.Total, nil
}