Skip to content

Commit

Permalink
Add Fairness label key code examples (#3148)
Browse files Browse the repository at this point in the history
### Description of change

##### Checklist

- [ ] Tested in playground or other setup
- [ ] Screenshot (Grafana) from playground added to PR for 15+ minute
run
- [ ] Documentation is changed or added
- [ ] Tests and/or benchmarks are included
- [ ] Breaking changes


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **Refactor**
- Internal code improvements without any direct impact on end-user
features.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
  • Loading branch information
karansohi authored Jan 11, 2024
1 parent 78cd8e8 commit f4a1e8e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
6 changes: 4 additions & 2 deletions docs/content/code-snippets.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
"handleRequest": "// do some business logic to collect labels\n var labels = new Dictionary\u003cstring, string\u003e();\n labels.Add(\"userId\", \"some_user_id\");\n labels.Add(\"userTier\", \"gold\");\n labels.Add(\"priority\", \"100\");\n\n var rampMode = false;\n var flowTimeout = TimeSpan.FromSeconds(5);\n var pms = new FeatureFlowParams(\n \"featureName\",\n labels,\n rampMode,\n flowTimeout,\n new Grpc.Core.CallOptions(),\n \"test\",\n new RepeatedField\u003cstring\u003e { \"test\" });\n var flow = sdk.StartFlow(pms);\n if (flow.ShouldRun())\n {\n // do actual work\n Thread.Sleep(2000);\n SimpleHandlePath((int)HttpStatusCode.OK, \"Hello world!\", response);\n }\n else\n {\n // handle flow rejection by Aperture Agent\n flow.SetStatus(FlowStatus.Error);\n SimpleHandlePath(flow.GetRejectionHttpStatusCode(), \"REJECTED!\", response);\n }\n\n var endResponse = flow.End();\n if (endResponse.Error != null)\n {\n // handle end failure\n log.Error(\"Failed to end flow: {e}\", endResponse.Error);\n }\n else if (endResponse.FlowEndResponse != null)\n {\n // handle end success\n log.Info(\"Ended flow with response: \" + endResponse.FlowEndResponse.ToString());\n }"
},
"go": {
"clientConstructor": "opts := aperture.Options{\n\t\tAddress: \"ORGANIZATION.app.fluxninja.com:443\",\n\t\tDialOptions: grpcOptions(apertureAgentInsecureBool, apertureAgentSkipVerifyBool),\n\t\tAPIKey: getEnvOrDefault(\"APERTURE_API_KEY\", \"\"),\n\t}\n\n\t// initialize Aperture Client with the provided options.\n\tapertureClient, err := aperture.NewClient(ctx, opts)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}",
"clientConstructor": "opts := aperture.Options{\n\t\tAddress: apertureAgentAddress,\n\t\tDialOptions: grpcOptions(apertureAgentInsecureBool, apertureAgentSkipVerifyBool),\n\t}\n\n\t// initialize Aperture Client with the provided options.\n\tapertureClient, err := aperture.NewClient(ctx, opts)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}",
"defineFlowParams": "flowParams := aperture.FlowParams{\n\t\tLabels: labels,\n\t\tRampMode: false,\n\t}",
"defineLabels": "// business logic produces labels\n\tlabels := map[string]string{\n\t\t\"userId\": \"some_user_id\",\n\t\t\"userTier\": \"premium\",\n\t\t\"priority\": \"100\",\n\t}",
"grpcOptions": "// grpcOptions creates a new gRPC client that will be passed in order to initialize the Aperture client.\nfunc grpcOptions(insecureMode, skipVerify bool) []grpc.DialOption {\n\tvar grpcDialOptions []grpc.DialOption\n\tgrpcDialOptions = append(grpcDialOptions, grpc.WithConnectParams(grpc.ConnectParams{\n\t\tBackoff: backoff.DefaultConfig,\n\t\tMinConnectTimeout: time.Second * 10,\n\t}))\n\tgrpcDialOptions = append(grpcDialOptions, grpc.WithUserAgent(\"aperture-go\"))\n\tif insecureMode {\n\t\tgrpcDialOptions = append(grpcDialOptions, grpc.WithTransportCredentials(insecure.NewCredentials()))\n\t} else if skipVerify {\n\t\tgrpcDialOptions = append(grpcDialOptions, grpc.WithTransportCredentials(credentials.NewTLS(\u0026tls.Config{\n\t\t\tInsecureSkipVerify: true, //nolint:gosec // For testing purposes only\n\t\t})))\n\t} else {\n\t\tcertPool, err := x509.SystemCertPool()\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t\tgrpcDialOptions = append(grpcDialOptions, grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(certPool, \"\")))\n\t}\n\treturn grpcDialOptions\n}",
"manualFlowNoCaching": "// business logic produces labels\n\tlabels := map[string]string{\n\t\t\"userId\": \"some_user_id\",\n\t\t\"userTier\": \"premium\",\n\t\t\"priority\": \"100\",\n\t}\n\n\n\tflowParams := aperture.FlowParams{\n\t\tLabels: labels,\n\t\tRampMode: false,\n\t}\n\n\n\tflow := a.apertureClient.StartFlow(r.Context(), \"featureName\", flowParams)\n\t// StartFlow performs a flowcontrolv1.Check call to Aperture Agent. It returns a Flow object.\n\n\n\t// See whether flow was accepted by Aperture Agent.\n\tif flow.ShouldRun() {\n\n\t\t// do actual work\n\n\t\tlog.Println(\"Flow Accepted Processing work\")\n\t\tw.WriteHeader(http.StatusAccepted)\n\t\tw.Write([]byte(\"Super!\"))\n\n\t} else {\n\n\t\t// handle flow rejection by Aperture Agent\n\t\tlog.Println(\"Flow Rejected\")\n\t\tflow.SetStatus(aperture.Error)\n\t\tw.WriteHeader(http.StatusForbidden)\n\t}\n\n\tendResponse:= flow.End()\n\tif endResponse.Error != nil {\n\t\tlog.Printf(\"Failed to end flow: %+v\", endResponse.Error)\n\t}\n\n\tlog.Printf(\"Flow ended with response: %+v\", endResponse.FlowEndResponse)",
"manualFlowNoCaching": "// business logic produces labels\n\tlabels := map[string]string{\n\t\t\"userId\": \"some_user_id\",\n\t\t\"userTier\": \"premium\",\n\t\t\"priority\": \"100\",\n\t}\n\n\n\tflowParams := aperture.FlowParams{\n\t\tLabels: labels,\n\t\tRampMode: false,\n\t}\n\n\n\tflow := a.apertureClient.StartFlow(r.Context(), \"featureName\", flowParams)\n\t// StartFlow performs a flowcontrolv1.Check call to Aperture Agent. It returns a Flow object.\n\n\n\t// See whether flow was accepted by Aperture Agent.\n\tif flow.ShouldRun() {\n\n\t\t// do actual work\n\n\t\tlog.Println(\"Flow Accepted Processing work\")\n\t\tw.WriteHeader(http.StatusAccepted)\n\t} else {\n\t\t// handle flow rejection by Aperture Agent\n\t\tlog.Println(\"Flow Rejected\")\n\t\tflow.SetStatus(aperture.Error)\n\t\tw.WriteHeader(http.StatusForbidden)\n\t}\n\n\tendResponse := flow.End()\n\tif endResponse.Error != nil {\n\t\tlog.Printf(\"Failed to end flow: %+v\", endResponse.Error)\n\t}\n\n\tlog.Printf(\"Flow ended with response: %+v\", endResponse.FlowEndResponse)",
"middleware": "middlewareParams := aperture.MiddlewareParams{\n\t\tTimeout: 2000 * time.Millisecond,\n\t\tIgnoredPathsCompiled: []*regexp.Regexp{regexp.MustCompile(\"/health.*\")},\n\t\tIgnoredPaths: []string{\"/connected\"},\n\t}\n\n\tmiddleware, err := middleware.NewHTTPMiddleware(apertureClient, \"awesomeFeature\", middlewareParams)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create HTTP middleware: %v\", err)\n\t}\n\tsuperRouter.Use(middleware.Handle)",
"startFlow": "flow := a.apertureClient.StartFlow(r.Context(), \"featureName\", flowParams)\n\t// StartFlow performs a flowcontrolv1.Check call to Aperture Agent. It returns a Flow object."
},
Expand Down Expand Up @@ -42,10 +42,12 @@
"RLStartFlow": "const flow = await apertureClient.startFlow(\"rate-limiting-feature\", {\n labels: {\n user_id: \"some_user_id\",\n },\n grpcCallOptions: {\n deadline: Date.now() + 300, // ms\n },\n });",
"UICLLabelMatcher": "const flow = await apertureClient.startFlow(\"concurrency-limiting-feature\", {\n labels: {\n user_id: \"user1\",\n customer_tier: \"gold\",\n product_tier: \"trial\",\n },\n grpcCallOptions: {\n deadline: Date.now() + 300, // ms\n },\n });",
"UICS": "const flow = await apertureClient.startFlow(\n \"concurrency-scheduling-feature\",\n {\n labels: {\n user_id: \"some_user_id\",\n priority: priority.toString(),\n workload: tier,\n },\n grpcCallOptions: {\n deadline: Date.now() + 120000, // ms\n },\n },\n );",
"UICSFairness": "const flow = await apertureClient.startFlow(\"concurrency-scheduling-feature\", {\n labels: {\n user_id: \"some_user_id\",\n workload: \"gold user\",\n fairness: \"100\",\n },\n grpcCallOptions: {\n deadline: Date.now() + 300, // ms\n },\n });",
"UICSLabelMatcher": "const flow = await apertureClient.startFlow(\"concurrency-scheduling-feature\", {\n labels: {\n user_id: \"user1\",\n customer_tier: \"gold\",\n product_tier: \"trial\",\n },\n grpcCallOptions: {\n deadline: Date.now() + 300, // ms\n },\n });",
"UICSTokens": "const flow = await apertureClient.startFlow(\"concurrency-scheduling-feature\", {\n labels: {\n user_id: \"user1\",\n tier: \"premium\",\n tokens: \"50\",\n\n },\n grpcCallOptions: {\n deadline: Date.now() + 300, // 300ms deadline\n },\n });",
"UICSWorkload": "let userWorkload = \"subscriber\";\n const flow = await apertureClient.startFlow(\"concurrency-scheduling-feature\", {\n labels: {\n user_id: \"some_user_id\",\n product_tier: \"trial\",\n priority: priority.toString(),\n workload: userWorkload,\n },\n grpcCallOptions: {\n deadline: Date.now() + 2000, // ms\n },\n });",
"UIConcurrencyTokens": "const flow = await apertureClient.startFlow(\"concurrency-limiting-feature\", {\n labels: {\n user_id: \"user1\",\n tier: \"premium\",\n tokens: \"50\",\n\n },\n grpcCallOptions: {\n deadline: Date.now() + 300, // 300ms deadline\n },\n });",
"UIQSFairness": "const flow = await apertureClient.startFlow(\"quota-scheduling-feature\", {\n labels: {\n user_id: \"some_user_id\",\n workload: \"gold user\",\n fairness: \"100\",\n },\n grpcCallOptions: {\n deadline: Date.now() + 300, // ms\n },\n });",
"UIQSTokens": "let userTokens;\n switch (userType) {\n case \"premium\":\n userTokens = 100;\n break;\n case \"gold\":\n userTokens = 50;\n break;\n default:\n userTokens = 0;\n }\n const flow = await apertureClient.startFlow(\"quota-scheduling-feature\", {\n labels: {\n user_id: \"some_user_id\",\n product_tier: \"trial\",\n priority: \"100\",\n tokens: userTokens.toString(),\n },\n grpcCallOptions: {\n deadline: Date.now() + 120000, // ms\n },\n });",
"UIQSWorkload": "let userWorkload = \"subscriber\";\n const flow = await apertureClient.startFlow(\"quota-scheduling-feature\", {\n labels: {\n user_id: \"some_user_id\",\n product_tier: \"trial\",\n priority: priority.toString(),\n workload: userWorkload,\n },\n grpcCallOptions: {\n deadline: Date.now() + 120000, // ms\n },\n });",
"UIRLLabelMatcher": "const flow = await apertureClient.startFlow(\"rate-limiting-feature\", {\n labels: {\n user_id: \"user1\",\n customer_tier: \"gold\",\n product_tier: \"trial\",\n },\n grpcCallOptions: {\n deadline: Date.now() + 300, // ms\n },\n });",
Expand Down
32 changes: 32 additions & 0 deletions sdks/aperture-js/example/ui_snippets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,3 +227,35 @@ async function UICSLabelMatcher(apertureClient: ApertureClient){
// END: UICSLabelMatcher

}

async function UIQSFairness(apertureClient: ApertureClient){
// START: UIQSFairness
const flow = await apertureClient.startFlow("quota-scheduling-feature", {
labels: {
user_id: "some_user_id",
workload: "gold user",
fairness: "100",
},
grpcCallOptions: {
deadline: Date.now() + 300, // ms
},
});
// END: UIQSFairness

}

async function UICSFairness(apertureClient: ApertureClient){
// START: UICSFairness
const flow = await apertureClient.startFlow("concurrency-scheduling-feature", {
labels: {
user_id: "some_user_id",
workload: "gold user",
fairness: "100",
},
grpcCallOptions: {
deadline: Date.now() + 300, // ms
},
});
// END: UICSFairness

}

0 comments on commit f4a1e8e

Please sign in to comment.