utils

package
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2024 License: Apache-2.0 Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ApplicationJson      = "application/json"
	ClaceServiceLocation = "clace"
)
View Source
const (
	PASSWORD_CHARS  = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@#%^&*()_-+=<>?/|"
	PASSWORD_LENGTH = 16
	BCRYPT_COST     = 10
)
View Source
const (
	ID_PREFIX_APP_PROD      = "app_prd_"
	ID_PREFIX_APP_DEV       = "app_dev_"
	ID_PREFIX_APP_STAGE     = "app_stg_"
	ID_PREFIX_APP_PREVIEW   = "app_pre_"
	INTERNAL_URL_PREFIX     = "/_clace"
	APP_INTERNAL_URL_PREFIX = "/_clace_app"
	INTERNAL_APP_DELIM      = "_cl_"
	STAGE_SUFFIX            = INTERNAL_APP_DELIM + "stage"
	PREVIEW_SUFFIX          = INTERNAL_APP_DELIM + "preview"
)
View Source
const (
	TL_CONTEXT                  = "TL_context"
	TL_DEFER_MAP                = "TL_defer_map"
	TL_CURRENT_MODULE_FULL_PATH = "TL_current_module_full_path"
	TL_PLUGIN_API_FAILED_ERROR  = "TL_plugin_api_failed_error"
)
View Source
const DEFAULT_CONFIG = "clace.default.toml"
View Source
const Scheme = "http+unix"

Scheme is the URL scheme used for HTTP over UNIX domain sockets.

Variables

This section is empty.

Functions

func GenerateRandomPassword

func GenerateRandomPassword() (string, error)

GenerateRandomPassword generates a random password

func GetDefaultConfigs

func GetDefaultConfigs() (*GlobalConfig, *ClientConfig, *ServerConfig, error)

func IsEmptyStarlarkString

func IsEmptyStarlarkString(s starlark.String) bool

IsEmptyStarlarkString checks is a starlark string is empty ("" for a go string) starlark.String.String performs repr-style quotation, which is necessary for the starlark.Value contract but a frequent source of errors in API clients. This helper method makes sure it'll work properly

func KillGroup

func KillGroup(process *os.Process) error

KillGroup kills the process group

func LoadClientConfig

func LoadClientConfig(contents string, config *ClientConfig) error

LoadClientConfig load a ClientConfig from the given contents

func LoadGlobalConfig

func LoadGlobalConfig(contents string, config *GlobalConfig) error

LoadGlobalConfig load a GlobalConfig from the given contents

func LoadServerConfig

func LoadServerConfig(contents string, config *ServerConfig) error

LoadServerConfig loads a ServerConfig from the given contents

func MarshalStarlark

func MarshalStarlark(data interface{}) (v starlark.Value, err error)

MarshalStarlark turns go values into starlark types

func RollingFileLogger added in v0.1.8

func RollingFileLogger(config *LogConfig, logType string) io.Writer

func SetProcessGroup

func SetProcessGroup(cmd *exec.Cmd)

SetProcessGroup sets the process group flag for the command

func UnmarshalStarlark

func UnmarshalStarlark(x starlark.Value) (val interface{}, err error)

UnmarshalStarlark decodes a starlark.Value into it's golang counterpart

func UnquoteStarlark

func UnquoteStarlark(x starlark.Value) (string, error)

UnquoteStarlark unquotes a starlark string value

Types

type AccountLink struct {
	Plugin      string `json:"plugin"`
	AccountName string `json:"account_name"`
}

AccountLink links the account to use for each plugin

type AppApproveResponse added in v0.3.0

type AppApproveResponse struct {
	DryRun              bool            `json:"dry_run"`
	StagedUpdateResults []ApproveResult `json:"staged_update_results"`
	PromoteResults      []AppPathDomain `json:"promote_results"`
}

type AppAuthnType

type AppAuthnType string

AppAuthnType is the app level authentication type

const (
	AppAuthnNone    AppAuthnType = "none"    // No auth
	AppAuthnDefault AppAuthnType = "default" // Use whatever auth is the default for the system
	AppAuthnSystem  AppAuthnType = "system"  // Use the system admin user
)

type AppCreateResponse added in v0.3.0

type AppCreateResponse struct {
	DryRun         bool            `json:"dry_run"`
	ApproveResults []ApproveResult `json:"approve_results"`
}

type AppDeleteResponse added in v0.3.0

type AppDeleteResponse struct {
	DryRun  bool      `json:"dry_run"`
	AppInfo []AppInfo `json:"app_info"`
}

type AppEntry

type AppEntry struct {
	Id         AppId       `json:"id"`
	Path       string      `json:"path"`
	MainApp    AppId       `json:"main_app"` // the id of the app that this app is linked to
	Domain     string      `json:"domain"`
	SourceUrl  string      `json:"source_url"`
	IsDev      bool        `json:"is_dev"`
	UserID     string      `json:"user_id"`
	CreateTime *time.Time  `json:"create_time"`
	UpdateTime *time.Time  `json:"update_time"`
	Settings   AppSettings `json:"settings"` // settings are not version controlled
	Metadata   AppMetadata `json:"metadata"` // metadata is version controlled
}

AppEntry is the application configuration in the DB

func (*AppEntry) AppPathDomain added in v0.3.0

func (ae *AppEntry) AppPathDomain() AppPathDomain

func (*AppEntry) String added in v0.3.0

func (ae *AppEntry) String() string

type AppFile added in v0.4.1

type AppFile struct {
	Name string
	Etag string
	Size int64
}

type AppGetResponse added in v0.4.0

type AppGetResponse struct {
	AppEntry AppEntry `json:"app_entry"`
}

type AppId

type AppId string

AppId is the identifier for an App

type AppInfo added in v0.3.0

type AppInfo struct {
	AppPathDomain
	Id      AppId
	IsDev   bool
	MainApp AppId
}

AppInfo is the basic info for an app

func CreateAppInfo added in v0.3.0

func CreateAppInfo(id AppId, path, domain string, isDev bool, mainApp AppId) AppInfo

type AppLinkAccountResponse added in v0.4.0

type AppLinkAccountResponse struct {
	DryRun              bool            `json:"dry_run"`
	StagedUpdateResults []AppPathDomain `json:"staged_update_results"`
	PromoteResults      []AppPathDomain `json:"promote_results"`
}

type AppListResponse added in v0.3.0

type AppListResponse struct {
	Apps []AppResponse `json:"apps"`
}

type AppMetadata added in v0.3.0

type AppMetadata struct {
	VersionMetadata VersionMetadata `json:"version_metadata"`
	Loads           []string        `json:"loads"`
	Permissions     []Permission    `json:"permissions"`
	Accounts        []AccountLink   `json:"accounts"`
}

AppMetadata contains the configuration for an app. App configurations are version controlled.

type AppPathDomain

type AppPathDomain struct {
	Path   string
	Domain string
}

AppPathDomain is a unique identifier for an app, consisting of the path and domain

func CreateAppPathDomain

func CreateAppPathDomain(path, domain string) AppPathDomain

func (AppPathDomain) String added in v0.3.0

func (a AppPathDomain) String() string

type AppPreviewResponse added in v0.3.0

type AppPreviewResponse struct {
	DryRun        bool          `json:"dry_run"`
	Success       bool          `json:"success"`
	ApproveResult ApproveResult `json:"approve_result"`
}

type AppPromoteResponse added in v0.3.0

type AppPromoteResponse struct {
	DryRun         bool            `json:"dry_run"`
	PromoteResults []AppPathDomain `json:"promote_results"`
}

type AppReloadResponse added in v0.3.0

type AppReloadResponse struct {
	DryRun         bool            `json:"dry_run"`
	ReloadResults  []AppPathDomain `json:"reload_results"`
	ApproveResults []ApproveResult `json:"approve_results"`
	PromoteResults []AppPathDomain `json:"promote_results"`
}

type AppResponse added in v0.3.0

type AppResponse struct {
	AppEntry
	StagedChanges bool `json:"staged_changes"`
}

type AppSettings added in v0.3.0

type AppSettings struct {
	AuthnType          AppAuthnType `json:"authn_type"`
	GitAuthName        string       `json:"git_auth_name"`
	StageWriteAccess   bool         `json:"stage_write_access"`
	PreviewWriteAccess bool         `json:"preview_write_access"`
}

AppSettings contains the settings for an app. Settings are not version controlled.

type AppStagedUpdateResponse added in v0.4.1

type AppStagedUpdateResponse struct {
	DryRun              bool            `json:"dry_run"`
	StagedUpdateResults any             `json:"staged_update_results"`
	PromoteResults      []AppPathDomain `json:"promote_results"`
}

type AppUpdateSettingsResponse added in v0.3.0

type AppUpdateSettingsResponse struct {
	DryRun        bool            `json:"dry_run"`
	UpdateResults []AppPathDomain `json:"update_results"`
}

type AppVersion added in v0.4.1

type AppVersion struct {
	Active          bool
	AppId           AppId
	Version         int
	PreviousVersion int
	UserId          string
	Metadata        *AppMetadata
	CreateTime      time.Time
}

type AppVersionFilesResponse added in v0.4.1

type AppVersionFilesResponse struct {
	Files []AppFile `json:"files"`
}

type AppVersionListResponse added in v0.4.1

type AppVersionListResponse struct {
	Versions []AppVersion `json:"versions"`
}

type AppVersionSwitchResponse added in v0.4.1

type AppVersionSwitchResponse struct {
	DryRun      bool `json:"dry_run"`
	FromVersion int  `json:"from_version"`
	ToVersion   int  `json:"to_version"`
}

type ApproveResult added in v0.3.0

type ApproveResult struct {
	Id                  AppId         `json:"id"`
	AppPathDomain       AppPathDomain `json:"app_path_domain"`
	NewLoads            []string      `json:"new_loads"`
	NewPermissions      []Permission  `json:"new_permissions"`
	ApprovedLoads       []string      `json:"approved_loads"`
	ApprovedPermissions []Permission  `json:"approved_permissions"`
	NeedsApproval       bool          `json:"needs_approval"`
}

ApproveResult represents the result of an app approval audit

type AuthConfig added in v0.5.0

type AuthConfig struct {
	Key          string   `toml:"key"`           // the client id
	Secret       string   `toml:"secret"`        // the client secret
	OrgUrl       string   `toml:"org_url"`       // the org url, used for Okta
	Domain       string   `toml:"domain"`        // the domain, used for Auth0
	DiscoveryUrl string   `toml:"discovery_url"` // the discovery url, used for OIDC
	HostedDomain string   `toml:"hosted_domain"` // the hosted domain, used for Google
	Scopes       []string `toml:"scopes"`        // oauth scopes
}

AuthConfig is the configuration for the Authentication provider

type BoolValue added in v0.3.0

type BoolValue int
const (
	BoolValueUndefined BoolValue = iota
	BoolValueTrue
	BoolValueFalse
)

type ClientConfig

type ClientConfig struct {
	GlobalConfig
	SkipCertCheck bool   `toml:"skip_cert_check"`
	AdminPassword string `toml:"admin_password"`
}

ClientConfig is the configuration for the Clace Client

func NewClientConfigEmbedded

func NewClientConfigEmbedded() (*ClientConfig, error)

NewClientConfigEmbedded reads the embedded toml file and creates a ClientConfig

type CompressedReader added in v0.3.0

type CompressedReader interface {
	ReadCompressed() (data []byte, compressionType string, err error)
}

type CreateAppRequest

type CreateAppRequest struct {
	SourceUrl   string       `json:"source_url"`
	IsDev       bool         `json:"is_dev"`
	AppAuthn    AppAuthnType `json:"app_authn"`
	GitBranch   string       `json:"git_branch"`
	GitCommit   string       `json:"git_commit"`
	GitAuthName string       `json:"git_auth_name"`
}

CreateAppRequest is the request body for creating an app

type GitAuthEntry added in v0.3.0

type GitAuthEntry struct {
	UserID      string `toml:"user_id"`       // the user id of the user, defaults to "git" https://github.com/src-d/go-git/issues/637
	KeyFilePath string `toml:"key_file_path"` // the path to the private key file
	Password    string `toml:"password"`      // the password for the private key file
}

GitAuth is a github auth config entry

type GlobalConfig

type GlobalConfig struct {
	ConfigFile string `toml:"config_file"`
	AdminUser  string `toml:"admin_user"`
	ServerUri  string `toml:"server_uri"`
}

Config entries shared between client and server

type HttpClient

type HttpClient struct {
	// contains filtered or unexported fields
}

func NewHttpClient

func NewHttpClient(serverUri, user, password string, skipCertCheck bool) *HttpClient

NewHttpClient creates a new HttpClient instance

func (*HttpClient) Delete

func (h *HttpClient) Delete(url string, params url.Values, output any) error

func (*HttpClient) Get

func (h *HttpClient) Get(url string, params url.Values, output any) error

func (*HttpClient) Post

func (h *HttpClient) Post(url string, params url.Values, input any, output any) error

type HttpConfig

type HttpConfig struct {
	Host string `toml:"host"`
	Port int    `toml:"port"`
}

HttpConfig is the configuration for the HTTP server

type HttpsConfig

type HttpsConfig struct {
	Host             string `toml:"host"`
	Port             int    `toml:"port"`
	EnableCertLookup bool   `toml:"enable_cert_lookup"`
	ServiceEmail     string `toml:"service_email"`
	UseStaging       bool   `toml:"use_staging"`
	StorageLocation  string `toml:"storage_location"`
	CertLocation     string `toml:"cert_location"`
}

HttpsConfig is the configuration for the HTTPs server

type Index added in v0.4.0

type Index struct {
	Fields []string
	Unique bool
}

type LogConfig

type LogConfig struct {
	Level         string `toml:"level"`
	MaxBackups    int    `toml:"max_backups"`
	MaxSizeMB     int    `toml:"max_size_mb"`
	Console       bool   `toml:"console"`
	File          bool   `toml:"file"`
	AccessLogging bool   `toml:"access_logging"`
}

LogConfig is the configuration for the Logger

type Logger

type Logger struct {
	*zerolog.Logger
}

func NewLogger

func NewLogger(config *LogConfig) *Logger

type Marshaler

type Marshaler interface {
	// MarshalStarlark marshal a custom type to starlark object.
	MarshalStarlark() (starlark.Value, error)
}

Marshaler is the interface use to marshal starlark custom types.

type MetadataConfig

type MetadataConfig struct {
	DBConnection string `toml:"db_connection"`
	AutoUpgrade  bool   `toml:"auto_upgrade"`
}

MetadataConfig is the configuration for the Metadata persistence layer

type NewPluginFunc added in v0.4.0

type NewPluginFunc func(pluginContext *PluginContext) (any, error)

type Permission

type Permission struct {
	Plugin    string   `json:"plugin"`
	Method    string   `json:"method"`
	Arguments []string `json:"arguments"`
	IsRead    *bool    `json:"is_read,omitempty"` // Whether the call is a Read operation or Write operation.

}

Permission represents a permission granted to an app to run a plugin method with the given arguments

type PluginContext added in v0.4.0

type PluginContext struct {
	Logger    *Logger
	AppId     AppId
	StoreInfo *StoreInfo
	Config    PluginSettings
}

type PluginFunc added in v0.4.0

type PluginFunc struct {
	Name         string
	IsRead       bool
	FunctionName string
}

PluginFunc is the Clace plugin function mapping to starlark function

type PluginInfo added in v0.4.0

type PluginInfo struct {
	ModuleName  string // exec
	PluginPath  string // exec.in
	FuncName    string // run
	IsRead      bool
	HandlerName string
	Builder     NewPluginFunc
}

PluginFuncInfo is the Clace plugin function info for the starlark function

type PluginMap added in v0.4.0

type PluginMap map[string]*PluginInfo

PluginMap is the plugin function mapping to PluginFuncs

type PluginSettings added in v0.4.0

type PluginSettings map[string]any

type ReadableFS added in v0.2.0

type ReadableFS interface {
	fs.FS
	fs.ReadFileFS
	fs.GlobFS
	// Stat returns the stats for the named file.
	Stat(name string) (fs.FileInfo, error)
	Reset()                // Used to reset the file system transaction for the DbFs, no-op for others
	StaticFiles() []string // Return list of static files
}

WritableFS is the interface for the writable underlying file system used by AppFS

type Request added in v0.4.4

type Request struct {
	AppName     string
	AppPath     string
	AppUrl      string
	PagePath    string
	PageUrl     string
	Method      string
	IsDev       bool
	IsPartial   bool
	PushEvents  bool
	HtmxVersion string
	Headers     http.Header
	RemoteIP    string
	UrlParams   map[string]string
	Form        url.Values
	Query       url.Values
	PostForm    url.Values
	Data        any
}

Request is a starlark.Value that represents an HTTP request. A Request is created from the Go http.Request and passed to the starlark handler function as it only argument. The Data field is updated with the handler's response and then the template evaluation is done with the same Request

func (Request) Attr added in v0.4.4

func (r Request) Attr(name string) (starlark.Value, error)

func (Request) AttrNames added in v0.4.4

func (r Request) AttrNames() []string

func (Request) Freeze added in v0.4.4

func (r Request) Freeze()

func (Request) Hash added in v0.4.4

func (r Request) Hash() (uint32, error)

func (Request) String added in v0.4.4

func (r Request) String() string

func (Request) Truth added in v0.4.4

func (r Request) Truth() starlark.Bool

func (Request) Type added in v0.4.4

func (r Request) Type() string

type RequestError

type RequestError struct {
	Message string `json:"message"`
	Code    int    `json:"code"`
}

RequestError is the error returned by the API

func CreateRequestError

func CreateRequestError(message string, code int) RequestError

func (RequestError) Error

func (r RequestError) Error() string

type SecurityConfig

type SecurityConfig struct {
	AdminOverTCP        bool   `toml:"admin_over_tcp"`
	AdminPasswordBcrypt string `toml:"admin_password_bcrypt"`
	AppDefaultAuthType  string `toml:"app_default_auth_type"`
	SessionSecret       string `toml:"session_secret"`
	SessionMaxAge       int    `toml:"session_max_age"`
	SessionHttpsOnly    bool   `toml:"session_https_only"`
	CallbackUrl         string `toml:"callback_url"`
}

SecurityConfig is the configuration for Inter process communication

type ServerConfig

type ServerConfig struct {
	GlobalConfig
	Http        HttpConfig                `toml:"http"`
	Https       HttpsConfig               `toml:"https"`
	Security    SecurityConfig            `toml:"security"`
	Metadata    MetadataConfig            `toml:"metadata"`
	Log         LogConfig                 `toml:"logging"`
	System      SystemConfig              `toml:"system"`
	GitAuth     map[string]GitAuthEntry   `toml:"git_auth"`
	Plugins     map[string]PluginSettings `toml:"plugin"`
	Auth        map[string]AuthConfig     `toml:"auth"`
	ProfileMode string                    `toml:"profile_mode"`
}

ServerConfig is the configuration for the Clace Server

func NewServerConfigEmbedded

func NewServerConfigEmbedded() (*ServerConfig, error)

NewServerConfigEmbedded reads the embedded toml file and creates a ServerConfig

type StarlarkType added in v0.4.0

type StarlarkType struct {
	// contains filtered or unexported fields
}

StarlarkType represents a Starlark type created from the schema type definition.

func NewStarlarkType added in v0.4.0

func NewStarlarkType(name string, data map[string]starlark.Value) *StarlarkType

func (*StarlarkType) Attr added in v0.4.0

func (s *StarlarkType) Attr(attr string) (starlark.Value, error)

func (*StarlarkType) AttrNames added in v0.4.0

func (s *StarlarkType) AttrNames() []string

func (*StarlarkType) Freeze added in v0.4.0

func (s *StarlarkType) Freeze()

func (*StarlarkType) Hash added in v0.4.0

func (s *StarlarkType) Hash() (uint32, error)

func (*StarlarkType) SetField added in v0.4.0

func (s *StarlarkType) SetField(name string, val starlark.Value) error

func (*StarlarkType) String added in v0.4.0

func (s *StarlarkType) String() string

func (*StarlarkType) Truth added in v0.4.0

func (s *StarlarkType) Truth() starlark.Bool

func (*StarlarkType) Type added in v0.4.0

func (s *StarlarkType) Type() string

func (*StarlarkType) UnmarshalStarlarkType added in v0.4.0

func (s *StarlarkType) UnmarshalStarlarkType() (any, error)

type StoreField added in v0.4.0

type StoreField struct {
	Name    string
	Type    TypeName
	Default any
}

type StoreInfo added in v0.4.0

type StoreInfo struct {
	Bytes []byte // The raw bytes for the schema.star file
	Types []StoreType
}

type StoreType added in v0.4.0

type StoreType struct {
	Name    string
	Fields  []StoreField
	Indexes []Index
}

type StringValue added in v0.3.0

type StringValue string
const (
	StringValueUndefined StringValue = "<CL_UNDEFINED>"
)

type SystemConfig

type SystemConfig struct {
	TailwindCSSCommand        string `toml:"tailwindcss_command"`
	FileWatcherDebounceMillis int    `toml:"file_watcher_debounce_millis"`
	NodePath                  string `toml:"node_path"`
}

SystemConfig is the system level configuration

type Transport

type Transport struct {
	// DialTimeout is deprecated. Use context instead.
	DialTimeout time.Duration
	// RequestTimeout is deprecated and has no effect.
	RequestTimeout time.Duration
	// ResponseHeaderTimeout is deprecated. Use context instead.
	ResponseHeaderTimeout time.Duration
	// contains filtered or unexported fields
}

Transport is a http.RoundTripper that connects to Unix domain sockets.

func (*Transport) RegisterLocation

func (t *Transport) RegisterLocation(loc string, path string)

RegisterLocation registers an URL location and maps it to the given file system path.

Calling RegisterLocation twice for the same location is a programmer error, and causes a panic.

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip executes a single HTTP transaction. See net/http.RoundTripper.

type TypeBuilder added in v0.4.0

type TypeBuilder struct {
	Name   string
	Fields []StoreField
}

func (*TypeBuilder) CreateType added in v0.4.0

func (s *TypeBuilder) CreateType(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error)

type TypeName added in v0.4.0

type TypeName string
const (
	INT      TypeName = "INT"
	FLOAT    TypeName = "FLOAT"
	DATETIME TypeName = "DATETIME"
	STRING   TypeName = "STRING"
	BOOLEAN  TypeName = "BOOLEAN"
	LIST     TypeName = "LIST"
	DICT     TypeName = "DICT"
)

type TypeUnmarshaler added in v0.4.0

type TypeUnmarshaler interface {
	// UnmarshalStarlark unmarshals a starlark object to go object
	UnmarshalStarlarkType() (any, error)
}

Unmarshaler is the interface use to unmarshal starlark custom types.

type Unmarshaler

type Unmarshaler interface {
	// UnmarshalStarlark unmarshal a starlark object to custom type.
	UnmarshalStarlark(starlark.Value) error
}

Unmarshaler is the interface use to unmarshal starlark custom types.

type UpdateAppRequest added in v0.3.0

type UpdateAppRequest struct {
	AuthnType          StringValue `json:"authn_type"`
	GitAuthName        StringValue `json:"git_auth_name"`
	StageWriteAccess   BoolValue   `json:"stage_write_access"`
	PreviewWriteAccess BoolValue   `json:"preview_write_access"`
}

UpdateAppRequest is the request body for updating an app settings

func CreateUpdateAppRequest added in v0.3.0

func CreateUpdateAppRequest() UpdateAppRequest

type VersionMetadata added in v0.3.0

type VersionMetadata struct {
	Version         int    `json:"version"`
	PreviousVersion int    `json:"previous_version"`
	GitBranch       string `json:"git_branch"`
	GitCommit       string `json:"git_commit"`
	GitMessage      string `json:"git_message"`
}

VersionMetadata contains the metadata for an app

type WritableFS added in v0.2.0

type WritableFS interface {
	ReadableFS
	Write(name string, bytes []byte) error
	Remove(name string) error
}

WritableFS is the interface for the writable underlying file system used by AppFS

Jump to

Keyboard shortcuts

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