Pairec Go Framework
repository·master·Indexed 40 days ago
https://github.com/alibaba/pairecA Go web framework optimized for building online recommendation services. It utilizes JSON configurations and built-in model functionalities to accelerate development. The framework includes tools like pairecmd for project initialization and supports remote model requests via EAS, Seldon, and TensorFlow Serving (TFservingRequest). It also features integrated Prometheus monitoring and a flexible callback hook system for post-recommendation processing.
What's inside Pairec
- pairec is a Go-based web framework designed for the rapid development of online recommendation services. It leverages JSON-based configurations to define service behavior and comes with a variety of built-in model functionalities to simplify the building process.
Install the pairec Go framework
masterTo use the
pairecframework in your Go projects, install the v2 module usinggo get.go get github.com/alibaba/pairec/v2Quick Start with pairecmd
masterFor a fast way to initialize a project and start a recommendation service, use thepairecmdtool. This tool automates the creation of project structures and service startup.How ConfigLoader manages dynamic configuration updates
masterThe
ConfigLoaderimplements a polling pattern to ensure the service stays synchronized with the remote configuration server without requiring a restart.Lifecycle:
- Initialization:
NewConfigLoader(configName)sets up the loader with the target config name and a version key (configName + "_version"). - Initial Fetch:
loadConfigFromConfigServer()retrieves raw data, performs string substitution for environment variables and A/B test parameters, and unmarshals the JSON into arecconf.RecommendConfigobject. - Polling Loop:
loopLoadConfig()runs in a background goroutine. Every 10 seconds, it callsloadConfigVersion()to check the current version via the A/B test parameter system. - Reload Trigger: If the version retrieved from the server differs from the locally cached
configVersionValue, the loader triggersreloadConfig(config). - Component Reloading:
reloadConfigiterates through all registered subsystems (e.g.,mysqldb,redisdb,algorithm,filter,service) and calls their respective.Load(config)methods to apply the new settings in-memory. - Global Update: Finally,
recconf.UpdateConf(config)is called to update the global configuration state used by the rest of the application.
- Initialization:
Configure HA3 Query parameters
masterThe
HaQuerystruct allows for complex search configurations. Key components include:Query: The main search string (required).Cluster: Specifies the cluster or partition.Config: AnHaQueryconfigClausedefiningStart(offset),Hit(count), andFormat(e.g.,jsonorxml).Filter: A string used to filter results after the initial query.Sort: A slice ofHaQuerySortClausespecifyingSortKeyandSortOrder(+for ascending,-for descending).Aggregate: A slice ofHaQueryAggregateClausefor statistical functions likecount(),sum(id),max(id), ormin(id)on aGroupKey.Distinct: A slice ofHaQueryDistinctClauseto ensure result diversity (e.g., usingDistKey).Kvpairs: A map of key-value pairs passed to feature functions.
Use Alibaba Cloud credentials for Prometheus Pushgateway
masterIf
PushGatewayUseAliyunCredentialis enabled in the Prometheus configuration, Pairec uses an internalaliyunPushGatewayCredentialprovider. This provider utilizes the Alibaba Cloud default credential chain (supporting environment variables, ECS RAM roles, OIDC, etc.).It automatically handles STS temporary credentials by formatting the password as
{AccessKeySecret}${SecurityToken}to comply with the Alibaba Cloud Prometheus format.Implement a recommendation API endpoint
masterTo create a recommendation service, use
pairec.Routeto map a URL path to a controller that implements theweb.Controllerinterface.In your
mainfunction:- Use
pairec.AddStartHookto register initialization logic. - Use
pairec.Route(path, controller)to register your endpoint. - Call
pairec.Run()to start the server.
Example implementation of a
FeedController:func main() { pairec.AddStartHook(func() error { return nil }) pairec.Route("/api/rec/feed", &controller.FeedController{}) pairec.Run() }package main import ( "${BINNAME}/src/controller" "github.com/alibaba/pairec/v2" ) func main() { pairec.AddStartHook(func() error { return nil }) pairec.Route("/api/rec/feed", &controller.FeedController{}) pairec.Run() }- Use
Initialize the HA3Engine Client
masterTo use the HA3Engine client, create a
Configobject with your connection details and pass it toNewClient. TheConfigrequires anEndpointand authentication credentials (AccessUserNameandAccessPassWord).Available configuration fields:
Endpoint: The service endpoint.InstanceId: The specific instance ID.Protocol: The communication protocol (e.g.,HTTP).AccessUserName: Username for authentication.AccessPassWord: Password for authentication.UserAgent: Custom user agent string.
import "github.com/alibaba/pairec/datasource/ha3engine/ha3client" config := &ha3client.Config{} config.SetEndpoint("your-endpoint.com") config.SetInstanceId("your-instance-id") config.SetAccessUserName("your-username") config.SetAccessPassWord("your-password") client, err := ha3client.NewClient(config) if err != nil { // handle error }Configure the Pairec service via JSON
masterThe Pairec service is configured using a JSON file (typically
config.json). Key configuration sections include:RunMode: Execution mode (e.g.,product).ListenConf: Network settings includingHttpAddrandHttpPort(default8000).ABTestConf: Configuration for A/B testing withHostandToken.RecallConfs: List of recall configurations. Each entry requires aName,RecallType, andRecallCount.SortNamesandFilterNames: Mapping of default sorting and filtering strategies.SceneConfs: Scene-specific configurations. For example, ahome_feedscene can define specificRecallNamesfor itsdefaultconfiguration.LogConf: Logging settings includingRetensionDays,DiskSize, andLogLevel(e.g.,INFO).HologresConfs,KafkaConfs,RedisConfs: Connection settings for external data stores.
{ "RunMode": "product", "ListenConf": { "HttpAddr": "", "HttpPort": 8000 }, "ABTestConf": { "Host": "", "Token": "" }, "RecallConfs": [ { "Name":"mock_recall", "RecallType":"MockRecall", "RecallCount":200 } ], "SceneConfs": { "home_feed":{ "default":{ "RecallNames":["mock_recall"] } } }, "LogConf": { "RetensionDays": 3, "DiskSize": 20, "LogLevel": "INFO" } }Configure Prometheus monitoring in Pairec
masterPairec integrates with Prometheus via the
github.com/alibaba/pairec/v2/middleware/prometheuspackage. Monitoring is enabled by settingrecconf.Config.PrometheusConfig.Enabletotrue.Key configuration options available in
recconf.Config.PrometheusConfig:Subsystem: A string to define the Prometheus subsystem.ReqDurBuckets: Buckets for request duration histograms.ReqSizeBuckets: Buckets for request size histograms.RespSizeBuckets: Buckets for response size histograms.PushGatewayURL: The URL for the Prometheus Pushgateway.PushGatewayToken: The token used for Pushgateway authentication.PushIntervalSecs: The interval at which metrics are pushed.Job: The job name for the push (defaults torecconf.Config.RunModeor thePAIREC_ENVIRONMENTenv var if not specified).PushGatewayUseAliyunCredential: If true, uses Alibaba Cloud credentials for the Pushgateway.PushGatewayUsername/PushGatewayPassword: Used for Basic Auth if not using Aliyun credentials.
Configure Callback Hook behavior via Scene and Callback configurations
masterThe behavior of the
CallBackHookFuncis controlled by two main configuration areas within theRecommendContext.Config:1. Scene Configuration (
SceneConfs)Used to determine if the callback should be triggered at all for a specific scene.
AutoInvokeCallBack: A boolean flag in thedefaultcategory of a scene's configuration that enables/disables the hook.AutoInvokeCallBackRate: An integer (0-100) representing the percentage of requests that should trigger the callback.
2. Callback Configuration (
CallBackConfs)Used to shape the data sent to the callback service for a specific scene.
ItemSize: Limits the number of items sent in theItemList.ItemSizeRate: A percentage (0-100) used to downsample the item list. If set, the system selects a subset of items using a randomized step-based approach.UseUserFeatures: A boolean determining whether to useuser.MakeUserFeatures2()or to extract features from thefeaturesparameter in the context.
Data Format Sent to Callback
The resulting
web.CallBackParamcontains:SceneId: The current scene string.RequestId: TheRecommendIdfrom the context.Uid: The string representation of the user ID.Features: A map of user features.ItemList: A slice of maps, where each map contains:item_id: The item ID.score: The item score.algo_scores: A clone of the item's algorithmic scores.- All other item features retrieved via
item.GetCloneFeatures().
Use logging utilities for CLI feedback
masterThe
logpackage provides simple utilities for printing formatted status messages to the console during CLI execution. It uses color coding to distinguish between success and failure states.Info(message string): Prints a message prefixed with a green[SUCCESS]tag. This is used for non-terminal informational messages.Error(message string): Prints a message prefixed with a red[FAILED]tag and immediately terminates the process with exit code-1. This should be used for unrecoverable errors.
package main import "github.com/alibaba/pairec/commands/log" func main() { // Prints [SUCCESS] message in green log.Info("Operation completed successfully") // Prints [FAILED] message in red and exits with -1 log.Error("An unexpected error occurred") }