rules

package
v0.0.0-...-0fffe9f Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2026 License: Apache-2.0 Imports: 53 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var MapToParseExpressionToStructKeys = map[string]string{
	"$index":        "Index",
	"$filter":       "Filter",
	"$query":        "Query",
	"$type":         "Type",
	"$origin":       "Origin",
	"$referer":      "Referer",
	"$path":         "Path",
	"$category":     "Category",
	"$acl":          "ACL",
	"$ipv4":         "IPv4",
	"$ipv6":         "IPv6",
	"$customEvents": "CustomEvents",
}
View Source
var MapToParseIndexExpressionToStructKeys = map[string]string{
	"$index":        "Index",
	"$type":         "Type",
	"$origin":       "Origin",
	"$referer":      "Referer",
	"$path":         "Path",
	"$category":     "Category",
	"$acl":          "ACL",
	"$ipv4":         "IPv4",
	"$ipv6":         "IPv6",
	"$customEvents": "CustomEvents",
}

Functions

func AddRuleToCache

func AddRuleToCache(rule ESRuleDoc)

AddRuleToCache adds a rule to cache

func Apply

func Apply() middleware.Middleware

Apply middleware intercepts the reactivesearch requests and applies query rules to the search results.

func ApplyCustomData

func ApplyCustomData(responseBody []byte, data *string) ([]byte, error)

Applies the custom data

func ApplyFilters

func ApplyFilters(req *querytranslate.RSQuery, data *string) error

Applies the filters

func ApplyHideResult

func ApplyHideResult(responseBody []byte, data *string) ([]byte, error)

Applies the hide results TODO: Not performance efficient when hits size is large

func ApplyPromotedResult

func ApplyPromotedResult(requestBody querytranslate.RSQuery, responseBody []byte, data *string) ([]byte, error)

func ApplyRemoveWords

func ApplyRemoveWords(req *querytranslate.RSQuery, data *string) error

func ApplyReplaceSearch

func ApplyReplaceSearch(req *querytranslate.RSQuery, data *string) error

Applies the replace search term

func ApplyReplaceWords

func ApplyReplaceWords(req *querytranslate.RSQuery, data *string) error

func ApplySearchSettings

func ApplySearchSettings(req *querytranslate.RSQuery, data *string) error

Applies the search settings

func DeleteRuleToCache

func DeleteRuleToCache(ruleID string) bool

DeleteRuleToCache deletes a rule from cache

func GetClientIP4

func GetClientIP4(ip string) string

Returns an ip address (1 byte)

func GetClientIP6

func GetClientIP6(ip string) string

Returns an ip address without last 8 bits (1 byte)

func InjectKV

func InjectKV(ctx *v8go.Context) error

InjectKV will inject the KV related functions into the passed context.

func IsIndexingRequest

func IsIndexingRequest(req *http.Request) bool

IsIndexingRequest checks if the request is an indexing one and accordingly returns it.

func NewContext

func NewContext(ctx context.Context, request ScriptRequest) context.Context

NewContext returns a new context with the given request body.

func ParseFilters

func ParseFilters(filters []querytranslate.TermFilter) map[string]string

Normalizes the filter keys i.e replaces the '.' with '__'

func ParseTriggerExprToLowerCase

func ParseTriggerExprToLowerCase(expression string) string

ParseTriggerExprToLowerCase finds all the single/double quoted strings having space as prefix (or suffix) and converts them to lower case Check the TestParseTriggerExprToLowerCase test cases for more info

func ParseTriggerExpression

func ParseTriggerExpression(expression string, triggerType TriggerType) string

ParseTriggerExpression parses the trigger expression and returns it as a string.

func RunCronRule

func RunCronRule(r *Rules, ruleDetails ESRuleDoc)

Run the cron rule based on the passed script details. Thie method is called either: - when cron rule is created/updated - when server restarts

func RunScript

func RunScript(scriptContext []byte, script string, timeout time.Duration) ([]byte, *[]string, error)

func SetRulesToCache

func SetRulesToCache(rules []ESRuleDoc)

SetRulesToCache sets the rules

func StoreValueInCacheWithObject

func StoreValueInCacheWithObject(key, value string, cacheObject *ristretto.Cache) error

func TriggerEnvsToMap

func TriggerEnvsToMap(envs TriggerEnvironmentsToEvaluate) map[string]interface{}

func UpdateRuleToCache

func UpdateRuleToCache(ruleID string, rule ESRuleDoc) bool

UpdateRuleToCache updates a rule without overriding the previous values

func ValidateIndexTriggerExpression

func ValidateIndexTriggerExpression(expression string) error

ValidateIndexTriggerExpression will validate the index trigger expression.

func ValidateTriggerExpression

func ValidateTriggerExpression(expression string) error

ValidateTriggerExpression will validate the expression for query type

Types

type Action

type Action struct {
	Type         *ActionType `json:"type,omitempty"`
	Data         *string     `json:"data,omitempty"`   // we store the stringified data in the ES
	Script       *string     `json:"script,omitempty"` // script has different data type (binary)
	DecodeScript *string
	Request      *ScriptRequest         `json:"request,omitempty"`
	Response     *ScriptResponse        `json:"response,omitempty"`
	Environments map[string]interface{} `json:"envs,omitempty"`
}

type ActionType

type ActionType int
const (
	PromoteResult      ActionType = iota // after
	HideResult                           // after
	CustomData                           // after
	ReplaceSearchTerm                    // before
	AddFilter                            // before
	SearchSettings                       // before
	RemoveWords                          // before
	ReplaceWords                         // before
	ReplaceSearchQuery                   // before
	Script
)

func (ActionType) MarshalJSON

func (o ActionType) MarshalJSON() ([]byte, error)

MarshalJSON is the implementation of the Marshaler interface for marshaling ActionType type.

func (ActionType) String

func (o ActionType) String() string

String is the implementation of Stringer interface that returns the string representation of ActionType type.

func (*ActionType) UnmarshalJSON

func (o *ActionType) UnmarshalJSON(bytes []byte) error

UnmarshalJSON is the implementation of the Unmarshaler interface for unmarshaling ActionType type.

type CacheSyncScript

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

func (CacheSyncScript) Index

func (s CacheSyncScript) Index() string

func (CacheSyncScript) PluginName

func (s CacheSyncScript) PluginName() string

func (CacheSyncScript) SetCache

func (s CacheSyncScript) SetCache(response *elastic.SearchResult) error

type CronScriptOutput

type CronScriptOutput struct {
	Category   string              `json:"category"`
	Request    *CronScriptRequest  `json:"request"`
	Response   *CronScriptResponse `json:"response"`
	ScriptTook *int                `json:"scriptTook,omitempty"`
	Console    []string            `json:"console_logs,omitempty"`
}

type CronScriptRequest

type CronScriptRequest struct {
	Context *RuleContext `json:"context"`
}

type CronScriptResponse

type CronScriptResponse struct {
	RuleId          *string   `json:"ruleId"`
	InvokeTimestamp time.Time `json:"invokeTimestamp"`
	Took            int       `json:"took"`
	Reason          *string   `json:"reason,omitempty"`
	Code            int       `json:"code"`
}

type ESRuleDoc

type ESRuleDoc struct {
	ID                *string   `json:"id,omitempty"`
	Name              *string   `json:"name,omitempty"`
	Description       *string   `json:"description,omitempty"`
	Enabled           *bool     `json:"enabled,omitempty"`
	Order             *int      `json:"order,omitempty"`
	UpdatedAt         *int64    `json:"updated_at,omitempty"`
	CreatedAt         *int64    `json:"created_at,omitempty"`
	Trigger           *Trigger  `json:"trigger,omitempty"`
	Actions           *[]Action `json:"actions,omitempty"`
	ShowAdvanceEditor *bool     `json:"show_advance_editor,omitempty"`
}

ESRuleDoc represents the shape of a rule doc stored in ES

func GetRuleFromCache

func GetRuleFromCache(ruleID string) *ESRuleDoc

GetRuleFromCache returns a rule by ID

func GetRulesFromCache

func GetRulesFromCache() []ESRuleDoc

GetRulesFromCache returns a list of cached rules

func IsRuleExistsInCache

func IsRuleExistsInCache(ruleID string) (*ESRuleDoc, *int)

IsRuleExistsInCache checks if a rule in present in cache

type ESRuleRequestBody

type ESRuleRequestBody struct {
	ID                *string          `json:"id,omitempty"`
	Name              *string          `json:"name,omitempty"`
	Description       *string          `json:"description,omitempty"`
	Enabled           *bool            `json:"enabled,omitempty"`
	Order             *int             `json:"order,omitempty"`
	UpdatedAt         *int64           `json:"updated_at,omitempty"`
	CreatedAt         *int64           `json:"created_at,omitempty"`
	Trigger           *Trigger         `json:"trigger,omitempty"`
	Actions           *[]RequestAction `json:"actions,omitempty"`
	ShowAdvanceEditor *bool            `json:"show_advance_editor,omitempty"`
}

type FetchRequest

type FetchRequest struct {
	Body     string            `json:"body"`
	Headers  map[string]string `json:"headers"`
	Method   string            `json:"method"`
	Redirect string            `json:"redirect"`
}

Request Body for fetch

type KV

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

func (*KV) GetKVReadFunctionCallback

func (kv *KV) GetKVReadFunctionCallback() v8go.FunctionCallback

GetKVReadFunctionCallback will return the callback function to be injected into v8go context.

This function will expose a way to fetch a value for a passed key.

func (*KV) GetKVWriteFunctionCallback

func (kv *KV) GetKVWriteFunctionCallback() v8go.FunctionCallback

GetKVWriteFunctionCallback will return the callback function to be injected into v8go context.

This function will expose a way to store the passed value against the passed key in badger.

func (*KV) GetValueFromCache

func (kv *KV) GetValueFromCache(key string) (interface{}, bool, error)

GetValueFromCache will read the value from the passed key

If the key is not found an empty string will be returned.

func (*KV) StoreValueInCache

func (kv *KV) StoreValueInCache(key, value string) error

StoreValueInCache will store the passed value against the passed key in ristretto.

The TTL of the key will be set according to the cache preferences of the cluster.

type MappingsMigration

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

func (MappingsMigration) ConditionCheck

func (m MappingsMigration) ConditionCheck() (bool, *util.Error)

func (MappingsMigration) IsAsync

func (m MappingsMigration) IsAsync() bool

func (MappingsMigration) Script

func (m MappingsMigration) Script() *util.Error

type PromotedResult

type PromotedResult struct {
	Doc      map[string]interface{} `json:"doc"`
	Position int                    `json:"position"`
}

type PromotedResultSuggestion

type PromotedResultSuggestion struct {
	Doc PromotedResultSuggestionDoc `json:"doc"`
}

type PromotedResultSuggestionDoc

type PromotedResultSuggestionDoc struct {
	Id     string                 `json:"_id"`
	Source map[string]interface{} `json:"_source"`
	Index  string                 `json:"_index"`
	Label  string                 `json:"_suggestion_display_value"`
	URL    string                 `json:"_suggestion_url"`
}

type RequestAction

type RequestAction struct {
	Type         *ActionType            `json:"type,omitempty"`
	Data         *interface{}           `json:"data,omitempty"` // we store the stringified data in the ES
	Script       *string                `json:"script,omitempty"`
	Request      *ScriptRequest         `json:"request,omitempty"`
	Response     *ScriptResponse        `json:"response,omitempty"`
	Environments map[string]interface{} `json:"envs,omitempty"`
}

type RuleContext

type RuleContext struct {
	Envs map[string]interface{} `json:"envs"`
}

type Rules

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

Rules plugin deals with managing query rules.

func Instance

func Instance() *Rules

Instance returns the singleton instance of the plugin. Instance should be the only way (both within or outside the package) to fetch the instance of the plugin, in order to avoid stateless duplicates.

func (*Rules) AlternateRoutes

func (r *Rules) AlternateRoutes() []plugins.Route

Expose plugin specific routes

func (*Rules) ESMiddleware

func (r *Rules) ESMiddleware() []middleware.Middleware

func (*Rules) InitFunc

func (r *Rules) InitFunc() error

InitFunc initializes the dao, i.e. elasticsearch client, and should be executed only once in the lifetime of the plugin.

func (*Rules) Name

func (r *Rules) Name() string

Name returns the name of the plugin: rules

func (*Rules) RSMiddleware

func (r *Rules) RSMiddleware() []middleware.Middleware

func (*Rules) ReInstantiateV8Context

func (r *Rules) ReInstantiateV8Context(global *v8go.ObjectTemplate)

ReInstantiateV8Context cleans up any heap associated with the existing context and reinstantiates it

func (*Rules) Routes

func (r *Rules) Routes() []plugins.Route

Routes returns an empty slices since the plugin solely acts as a middleware.

type RunningJob

type RunningJob struct {
	RuleId  *string
	CronJob *cron.Cron
}

Store details about all the running cron jobs

type ScriptContext

type ScriptContext struct {
	Request      ScriptRequest          `json:"request"`
	Response     ScriptResponse         `json:"response"`
	Environments map[string]interface{} `json:"envs"`
}

type ScriptData

type ScriptData struct {
	Script string `json:"script"`
}

type ScriptRequest

type ScriptRequest struct {
	Body    string            `json:"body"`
	Headers map[string]string `json:"headers"`
	URL     string            `json:"url"`
	Method  string            `json:"method"`
}

func FromContext

func FromContext(ctx context.Context) (*ScriptRequest, error)

FromContext retrieves the Script context request stored against the rules.ctxKey from the context.

type ScriptRequestIn

type ScriptRequestIn struct {
	Body    interface{}       `json:"body"`
	Headers map[string]string `json:"headers"`
}

type ScriptResponse

type ScriptResponse struct {
	Code    int               `json:"code"`
	Body    string            `json:"body"`
	Headers map[string]string `json:"headers"`
}

type ScriptResponseIn

type ScriptResponseIn struct {
	Code    int               `json:"code"`
	Body    interface{}       `json:"body"`
	Headers map[string]string `json:"headers"`
	Console []string          `json:"console"`
}

type SearchSettingsConfig

type SearchSettingsConfig struct {
	DataField    *[]string  `json:"dataField"`
	FieldWeights *[]float64 `json:"fieldWeights"`
}

type TimeFrame

type TimeFrame struct {
	StartTime *int64 `json:"start_time,omitempty"`
	EndTime   *int64 `json:"end_time,omitempty"` // EndTime could be optional when user wants to start this trigger after specific date forever
}

type Trigger

type Trigger struct {
	Type       *TriggerType `` /* 209-byte string literal not displayed */
	Expression string       `` /* 213-byte string literal not displayed */
	TimeFrame  *TimeFrame   `` /* 134-byte string literal not displayed */
}

type TriggerEnvironmentsToEvaluate

type TriggerEnvironmentsToEvaluate struct {
	Index        []string            `json:"index,omitempty"`
	Filter       map[string]string   `json:"filters,omitempty"`
	Query        string              `json:"query,omitempty"`
	Type         string              `json:"type,omitempty"`         // search|term|suggestion|geo|range
	Origin       string              `json:"origin,omitempty"`       // https://my-search.domain.com
	Referer      string              `json:"referer,omitempty"`      // https://my-search.domain.com/path?q=hello
	Path         string              `json:"path,omitempty"`         // /_doc/nested_something
	Method       []string            `json:"method,omitempty"`       // GET/POST
	URLValues    map[string]string   `json:"urlValues,omitempty"`    // {'q': 'hello'}
	Category     string              `json:"category,omitempty"`     // docs
	ACL          string              `json:"acl,omitempty"`          // bulk
	IPv4         string              `json:"ipv4,omitempty"`         // 29.120.12.12
	IPv6         string              `json:"ipv6,omitempty"`         // 2001:db8:3333:4444:5555:6666:7777:8888
	CustomEvents map[string]string   `json:"customEvents,omitempty"` // { 'platform': 'mac' }
	OpenAIConfig openai.OpenAIConfig `json:"openAIConfig,omitempty"`
}

TODO: Change the struct for filters to support multi value filters

func GetTriggerEnvs

func GetTriggerEnvs(ctx context.Context, r *http.Request, environments querytranslate.QueryEnvs, triggerType TriggerType) (*TriggerEnvironmentsToEvaluate, error)

GetTriggerEnvs extracts the trigger environments to run the trigger.

type TriggerType

type TriggerType int
const (
	Always TriggerType = iota
	Filter
	Index
	Query
	Cron
)

func (TriggerType) JSONSchema

func (o TriggerType) JSONSchema() *jsonschema.Schema

func (TriggerType) MarshalJSON

func (o TriggerType) MarshalJSON() ([]byte, error)

MarshalJSON is the implementation of the Marshaler interface for marshaling TiggerType type.

func (TriggerType) String

func (o TriggerType) String() string

String is the implementation of Stringer interface that returns the string representation of TriggerType type.

func (TriggerType) Timeout

func (o TriggerType) Timeout() time.Duration

Get the timeout in seconds for the passed trigger

func (*TriggerType) UnmarshalJSON

func (o *TriggerType) UnmarshalJSON(bytes []byte) error

UnmarshalJSON is the implementation of the Unmarshaler interface for unmarshaling TiggerType type.

type ValidateScriptError

type ValidateScriptError struct {
	Code    int    `json:"code"`
	Status  string `json:"status"`
	Message string `json:"message"`
}

ValidateScriptError is similar to what telemetry writes back when an error occurs but also contains a console field to indicate console logs

This struct should be used as value for the `error` field

type ValidateScriptRequest

type ValidateScriptRequest struct {
	Script   string                 `json:"script"` // required
	Envs     map[string]interface{} `json:"envs"`
	Request  *ScriptRequest         `json:"request"`
	Response *ScriptResponse        `json:"response"`
	IsCron   *bool                  `json:"isCron"`
}

type ValidateScriptRequestWrapper

type ValidateScriptRequestWrapper struct {
	Script   string                 `json:"script"` // required
	Envs     map[string]interface{} `json:"envs"`
	Request  *ScriptRequestIn       `json:"request"`
	Response *ScriptResponseIn      `json:"response"`
	IsCron   *bool                  `json:"isCron"`
}

type ValidateScriptResponse

type ValidateScriptResponse struct {
	Request    *ScriptRequest  `json:"request"`
	Response   *ScriptResponse `json:"response"`
	ScriptTook int             `json:"script_took"`
	Console    []string        `json:"console_logs"`
}

type ValidateScriptResponseWrapper

type ValidateScriptResponseWrapper struct {
	Request    *ScriptRequestIn  `json:"request"`
	Response   *ScriptResponseIn `json:"response"`
	ScriptTook int               `json:"script_took"`
	Console    []string          `json:"console_logs"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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