magnus

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2025 License: Apache-2.0 Imports: 8 Imported by: 0

README

magnus-sdk — Magnus Remote API client for Go

GoReportCard GoDoc

This library is compatible with Go 1.22+

Please refer to CHANGELOG.md if you encounter breaking changes.

Overview

magnus-sdk is a thin, type-safe HTTP client for the Magnus Remote API. It supports:

  • Running workflows (Remote Workflow Execution v2)
  • Retrieving workflow history and recent history
  • Searching workflows
  • Locking/unlocking workflows
  • Generating signed URLs

JWT is carried in the request body under the jwt field (not in headers). The SDK can mint and inject this token automatically when configured with a signer.

Installation

go get github.com/viant/magnus-sdk

Authentication

Magnus expects a signed JWT in the request body (jwt). This SDK integrates with github.com/viant/scy to sign tokens using RSA private keys (e.g., Google Service Account private_key PEM).

You can either:

  • Pass a token explicitly to calls that accept it; or
  • Configure a per-client signer and (optionally) default claims/TTL to auto-inject jwt into supported requests.

Quick Start

package main

import (
    "context"
    "time"

    "github.com/viant/magnus-sdk"
    "github.com/viant/scy"
)

func main() {
    ctx := context.Background()

    // Load RSA private key from a scy secret (PEM content)
    rsaRes := scy.NewResource(nil, "~/.secret/service_account.pem", "blowfish://default")

    client, err := magnus.New(
        ctx,
        magnus.WithEndpoint("https://magnus.viantinc.com/remote"),
        magnus.WithScyRSA(ctx, rsaRes),               // load signer once per client
        magnus.WithJWTDefaults(time.Hour, map[string]any{"email": "svc@company.com"}),
    )
    if err != nil { panic(err) }

    // Run a workflow (auto-signed: jwt injected into body)
    params := []magnus.Parameter{{Name: "var_env", Value: "dev"}}
    _, err = client.RunWorkflow(ctx, "", "<base64-workflow-id>", true, params, "", false)
    if err != nil { panic(err) }
}

API Examples

Run Workflow

// Auto-signed (empty jwt) when signer configured
resp, err := client.RunWorkflow(ctx, "", encodedWorkflowID, true, params, "", false)

// Or pass an explicit token
jwt, _ := client.CreateJWT(time.Minute*30, map[string]any{"email": "svc@company.com"})
resp, err = client.RunWorkflow(ctx, jwt, encodedWorkflowID, true, params, "", false)

Parameters are sent to Magnus as overrides in the configuration.runWorkflow.parameters array:

params := []magnus.Parameter{
  {Name: "var_env", Value: "prod"},
  {Name: "var_xxxxx", Value: 123},
  {Name: "var_username", Value: "john.doe"},
}

Get History

// Auto-signed (empty jwt)
hist, err := client.GetHistory(ctx, "", workflowID, historyID)

Recent History

recent, err := client.GetRecentHistory(ctx, workflowID, 7, 100, "")

Search Workflows

filters := &magnus.SearchFilters{UserID: "user@example.com", IsEnabled: ptr(true)}
found, err := client.SearchWorkflows(ctx, filters, "summary", 50, "")

Lock/Unlock Workflows

_, err := client.LockWorkflows(ctx, []string{"wf1", "wf2"}, "maintenance window")
_, err = client.UnlockWorkflows(ctx, []string{"wf1", "wf2"}, "done")

Sign URLs

signed, err := client.SignUrls(ctx, []string{"gs://bucket/object"}, 3600)

Client Options

  • WithEndpoint(string): Set Magnus Remote API endpoint (defaults to http://magnus.viantinc.com/remote).
  • WithHTTPClient(*http.Client): Provide a custom HTTP client.
  • WithSigner(*jwtSigner.Service): Use a pre-initialized scy JWT signer (enforced once per client).
  • WithScyRSA(ctx, *scy.Resource): Initialize an RSA signer from a scy resource (enforced once per client).
  • WithJWTDefaults(ttl time.Duration, claims any): Default TTL/claims for auto-signed requests when jwt is not provided.

License

The source code is made available under the terms of the Apache License, Version 2, as stated in the file LICENSE.


Note: Magnus expects JWT in the request body under the jwt field. The SDK handles this automatically when configured with a signer.

Documentation

Index

Constants

View Source
const (
	CommandRunWorkflowV2    = "713aa58d" // Remote Workflow Execution v2
	CommandGetHistory       = "a83270b7" // Get Workflow History
	CommandSignUrls         = "4ab037fb" // Generate Signed URLs
	CommandLockWorkflows    = "6f570e7l" // Lock workflows
	CommandUnlockWorkflows  = "6f570e7u" // Unlock workflows
	CommandSearchWorkflows  = "searchWorkflows"
	CommandGetRecentHistory = "getRecentHistory"
)

Command constants for Magnus Remote API.

View Source
const DefaultEndpoint = "http://magnus.viantinc.com/remote"

DefaultEndpoint is the default Magnus Remote API endpoint.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	// Endpoint is the Magnus remote URL, for example DefaultEndpoint.
	Endpoint string
	// HTTPClient is the underlying HTTP client. If nil, http.DefaultClient is used.
	HTTPClient *http.Client
	// contains filtered or unexported fields
}

Client is a thin HTTP client for the Magnus Remote API.

func New

func New(ctx context.Context, opts ...Option) (*Client, error)

New constructs a client via options.

func NewClient

func NewClient(endpoint string, httpClient *http.Client) *Client

NewClient (compat) creates a new Magnus client with explicit endpoint and http client. It delegates to New with appropriate options.

func (*Client) CreateJWT

func (c *Client) CreateJWT(ttl time.Duration, claims any) (string, error)

CreateJWT creates a JWT using the configured signer.

func (*Client) GetHistory

func (c *Client) GetHistory(ctx context.Context, jwt, workflowID, historyID string) (*GetHistoryResponse, error)

GetHistory retrieves a single workflow history record by workflowId and historyId.

func (*Client) GetRecentHistory

func (c *Client) GetRecentHistory(ctx context.Context, workflowID string, maxDays, maxResults int, pageToken string) (*GetRecentHistoryResponse, error)

GetRecentHistory returns recent execution history for a workflow.

func (*Client) LockWorkflows

func (c *Client) LockWorkflows(ctx context.Context, ids []string, comment string) (*LockWorkflowsResponse, error)

LockWorkflows locks the given workflows.

func (*Client) RunWorkflow

func (c *Client) RunWorkflow(ctx context.Context, jwt, encodedWorkflowID string, queue bool, params []Parameter, billingProject string, cascadeBilling bool) (*RunWorkflowResponse, error)

RunWorkflow executes a Magnus workflow asynchronously using Remote Workflow Execution v2.

func (*Client) RunWorkflowV2Signed

func (c *Client) RunWorkflowV2Signed(ctx context.Context, encodedWorkflowID string, queue bool, params []Parameter, billingProject string, cascadeBilling bool, ttl time.Duration, claims any) (*RunWorkflowResponse, error)

RunWorkflowV2Signed mints a JWT using the client's signer and runs the workflow.

func (*Client) SearchWorkflows

func (c *Client) SearchWorkflows(ctx context.Context, filters *SearchFilters, view string, maxResults int, pageToken string) (*SearchWorkflowsResponse, error)

SearchWorkflows searches for workflows matching provided filters.

func (*Client) SignUrls

func (c *Client) SignUrls(ctx context.Context, gcsURIs []string, expirationSec int64) (*SignUrlsResponse, error)

SignUrls generates signed URLs for the given GCS URIs.

func (*Client) UnlockWorkflows

func (c *Client) UnlockWorkflows(ctx context.Context, ids []string, comment string) (*LockWorkflowsResponse, error)

UnlockWorkflows unlocks the given workflows.

type Error

type Error struct {
	StatusCode int
	Reason     string
	Message    string
}

Error is a Go error wrapping a Magnus error response.

func (*Error) Error

func (e *Error) Error() string

type ErrorDetail

type ErrorDetail struct {
	Reason  string `json:"reason"`
	Message string `json:"message"`
}

ErrorDetail describes an error returned by Magnus in the response body.

type GetHistoryBody

type GetHistoryBody struct {
	WorkflowID string `json:"workflowId"`
	HistoryID  string `json:"historyId"`
}

GetHistoryBody is configuration.getHistory.

type GetHistoryRequest

type GetHistoryRequest struct {
	Jwt           string           `json:"jwt,omitempty"`
	C             string           `json:"c"`
	Configuration getHistoryConfig `json:"configuration"`
}

GetHistoryRequest is the request payload for the Get Workflow History API.

type GetHistoryResponse

type GetHistoryResponse struct {
	Result *struct {
		History History `json:"history"`
	} `json:"result,omitempty"`
	// contains filtered or unexported fields
}

GetHistoryResponse is the response for Get Workflow History.

type GetRecentHistoryRequest

type GetRecentHistoryRequest struct {
	Jwt           string              `json:"jwt,omitempty"`
	C             string              `json:"c"`
	Configuration recentHistoryConfig `json:"configuration"`
}

GetRecentHistoryRequest is the request payload for the Get Recent History API.

type GetRecentHistoryResponse

type GetRecentHistoryResponse struct {
	Result *struct {
		History       []RecentHistory `json:"history"`
		NextPageToken string          `json:"nextPageToken,omitempty"`
	} `json:"result,omitempty"`
	// contains filtered or unexported fields
}

GetRecentHistoryResponse is the response for Get Recent History.

type History

type History struct {
	HistoryID      string `json:"historyId"`
	WorkflowID     string `json:"workflowId"`
	RunReason      string `json:"runReason"`
	WorkflowOwners string `json:"workflowOwners"`
	StartTime      int64  `json:"startTime"`
	EndTime        int64  `json:"endTime"`
	Status         struct {
		State string       `json:"state"`
		Error *ErrorDetail `json:"error,omitempty"`
	} `json:"status"`
}

History represents a workflow history record.

type LockUnlockBody

type LockUnlockBody struct {
	WorkflowIDs []string `json:"workflowIds"`
	Comment     string   `json:"comment,omitempty"`
}

LockUnlockBody represents configuration.lockWorkflows or configuration.unlockWorkflows.

type LockWorkflowsRequest

type LockWorkflowsRequest struct {
	Jwt           string           `json:"jwt,omitempty"`
	C             string           `json:"c"`
	Configuration lockUnlockConfig `json:"configuration"`
}

LockWorkflowsRequest is the request for locking or unlocking workflows.

type LockWorkflowsResponse

type LockWorkflowsResponse struct {
	Result *struct {
		UpdatedWorkflows []string `json:"updatedWorkflows"`
		Errors           []string `json:"errors"`
	} `json:"result,omitempty"`
	// contains filtered or unexported fields
}

LockWorkflowsResponse is the response from lock/unlock workflows API.

type Option

type Option func(*Client) error

Option configures a Client.

func WithEndpoint

func WithEndpoint(endpoint string) Option

WithEndpoint sets the remote endpoint.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient sets a custom HTTP client.

func WithJWTDefaults

func WithJWTDefaults(ttl time.Duration, claims any) Option

WithJWTDefaults sets default TTL and claims used when a JWT is not explicitly provided.

func WithScyRSA

func WithScyRSA(ctx context.Context, r *scy.Resource) Option

WithScyRSA initializes an RSA signer from a scy resource; only once per client.

func WithSigner

func WithSigner(s *jwtSigner.Service) Option

WithSigner assigns a pre-initialized JWT signer; only once per client.

type Parameter

type Parameter struct {
	Name  string      `json:"name"`
	Value interface{} `json:"value"`
}

Parameter represents a single workflow parameter override.

type RecentHistory

type RecentHistory struct {
	HistoryID   string `json:"historyId"`
	WorkflowID  string `json:"workflowId"`
	Owner       string `json:"owner"`
	RunBy       string `json:"runBy"`
	RunReason   string `json:"runReason"`
	StartTime   int64  `json:"startTime"`
	EndTime     int64  `json:"endTime,omitempty"`
	StatusState string `json:"statusState"`
	StatusError string `json:"statusError,omitempty"`
}

RecentHistory is a single history entry from Get Recent History.

type RunWorkflow

type RunWorkflow struct {
	// L is the encoded workflow ID (required).
	L string `json:"l"`
	// Queue controls Fair Scheduler queuing. Default is false.
	Queue bool `json:"queue,omitempty"`
	// Parameters is the list of parameter overrides.
	Parameters []Parameter `json:"parameters,omitempty"`
	// BillingProject is the billing project for execution (optional).
	BillingProject string `json:"billingProject,omitempty"`
	// CascadeBillingProject cascades the billing project to child workflows.
	CascadeBillingProject bool `json:"cascadeBillingProject,omitempty"`
}

RunWorkflow describes configuration.runWorkflow for Remote Workflow Execution v2.

type RunWorkflowRequest

type RunWorkflowRequest struct {
	// Jwt is required for direct HTTP calls.
	Jwt string `json:"jwt,omitempty"`
	// C is the command code; should be CommandRunWorkflowV2.
	C string `json:"c"`
	// Configuration holds the run workflow configuration.
	Configuration runWorkflowConfig `json:"configuration"`
}

RunWorkflowRequest is the full Remote Workflow Execution v2 request.

type RunWorkflowResponse

type RunWorkflowResponse struct {
	Result *RunWorkflowResult `json:"result,omitempty"`
	// contains filtered or unexported fields
}

RunWorkflowResponse is the typed response for run workflow v2.

type RunWorkflowResult

type RunWorkflowResult struct {
	WorkflowID string `json:"workflowId"`
	HistoryID  string `json:"historyId"`
}

RunWorkflowResult holds workflowId and historyId on success.

type SearchFilters

type SearchFilters struct {
	UserID               string              `json:"userId,omitempty"`
	UserRoles            []string            `json:"userRoles,omitempty"`
	OrgID                string              `json:"orgId,omitempty"`
	IsModificationLocked *bool               `json:"isModificationLocked,omitempty"`
	IsEnabled            *bool               `json:"isEnabled,omitempty"`
	IsCritical           *bool               `json:"isCritical,omitempty"`
	IsPublic             *bool               `json:"isPublic,omitempty"`
	IsArchived           *bool               `json:"isArchived,omitempty"`
	IsDraft              *bool               `json:"isDraft,omitempty"`
	Labels               []map[string]string `json:"labels,omitempty"`
	Content              string              `json:"content,omitempty"`
}

SearchFilters represents configuration.filters.

type SearchWorkflowsRequest

type SearchWorkflowsRequest struct {
	Jwt           string       `json:"jwt,omitempty"`
	C             string       `json:"c"`
	Configuration searchConfig `json:"configuration"`
}

SearchWorkflowsRequest is the request payload for the Search Workflows API.

type SearchWorkflowsResponse

type SearchWorkflowsResponse struct {
	Result *struct {
		Workflows     []Workflow `json:"workflows"`
		NextPageToken string     `json:"nextPageToken,omitempty"`
	} `json:"result,omitempty"`
	// contains filtered or unexported fields
}

SearchWorkflowsResponse is the response for Search Workflows.

type SignUrlsBody

type SignUrlsBody struct {
	GcsURIs       []string `json:"gcsUris"`
	ExpirationSec int64    `json:"expirationSec"`
}

SignUrlsBody is configuration.signUrls.

type SignUrlsRequest

type SignUrlsRequest struct {
	Jwt           string         `json:"jwt,omitempty"`
	C             string         `json:"c"`
	Configuration signUrlsConfig `json:"configuration"`
}

SignUrlsRequest is the request for the Sign URLs API.

type SignUrlsResponse

type SignUrlsResponse struct {
	Result *struct {
		SignedUrls []string `json:"signedUrls"`
	} `json:"result,omitempty"`
	// contains filtered or unexported fields
}

SignUrlsResponse is the response for Sign URLs.

type Workflow

type Workflow struct {
	WorkflowID           string   `json:"workflowId"`
	Owner                string   `json:"owner"`
	Delegates            []string `json:"delegates,omitempty"`
	SharedWith           []string `json:"sharedWith,omitempty"`
	LifetimeStartDate    string   `json:"lifetimeStartDate,omitempty"`
	LifetimeEndDate      string   `json:"lifetimeEndDate,omitempty"`
	Schedule             string   `json:"schedule,omitempty"`
	TimeZone             string   `json:"timeZone,omitempty"`
	IsEnabled            bool     `json:"isEnabled"`
	IsPublic             bool     `json:"isPublic"`
	IsCritical           bool     `json:"isCritical"`
	IsRunByOwnerAlways   bool     `json:"isRunByOwnerAlways"`
	IsModificationLocked bool     `json:"isModificationLocked"`
	IsDraft              bool     `json:"isDraft"`
	IsArchived           bool     `json:"isArchived"`
	LastRunAt            int64    `json:"lastRunAt,omitempty"`
	NextRunAt            int64    `json:"nextRunAt,omitempty"`
	Labels               []struct {
		Key   string `json:"key"`
		Value string `json:"value"`
	} `json:"labels,omitempty"`
	CreatedBy    string `json:"createdBy"`
	CreatedTime  int64  `json:"createdTime"`
	ModifiedBy   string `json:"modifiedBy"`
	ModifiedTime int64  `json:"modifiedTime"`
	Comment      string `json:"comment,omitempty"`
}

Workflow is a single workflow entry returned by Search Workflows.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL