From 2cdc7fde42c1720feef09831eae5b50afd58463c Mon Sep 17 00:00:00 2001 From: ZackarySantana <64446617+ZackarySantana@users.noreply.github.com> Date: Wed, 20 Aug 2025 00:28:18 -0400 Subject: [PATCH 1/2] feat (ofrep handler): Initial implementation --- tools/ofrep-http-handler/CHANGELOG.md | 8 + tools/ofrep-http-handler/LICENSE | 201 ++++++++++++++++++ tools/ofrep-http-handler/README.md | 129 +++++++++++ tools/ofrep-http-handler/go.mod | 10 + tools/ofrep-http-handler/go.sum | 8 + tools/ofrep-http-handler/handler.go | 118 ++++++++++ tools/ofrep-http-handler/handler_test.go | 145 +++++++++++++ tools/ofrep-http-handler/mockprovider_test.go | 85 ++++++++ tools/ofrep-http-handler/options.go | 33 +++ 9 files changed, 737 insertions(+) create mode 100644 tools/ofrep-http-handler/CHANGELOG.md create mode 100644 tools/ofrep-http-handler/LICENSE create mode 100644 tools/ofrep-http-handler/README.md create mode 100644 tools/ofrep-http-handler/go.mod create mode 100644 tools/ofrep-http-handler/go.sum create mode 100644 tools/ofrep-http-handler/handler.go create mode 100644 tools/ofrep-http-handler/handler_test.go create mode 100644 tools/ofrep-http-handler/mockprovider_test.go create mode 100644 tools/ofrep-http-handler/options.go diff --git a/tools/ofrep-http-handler/CHANGELOG.md b/tools/ofrep-http-handler/CHANGELOG.md new file mode 100644 index 000000000..bf812b73c --- /dev/null +++ b/tools/ofrep-http-handler/CHANGELOG.md @@ -0,0 +1,8 @@ +# Changelog + +## [Unreleased] + +### Added + +- Initial release of OFREP HTTP Handler +- Example usage with documentation diff --git a/tools/ofrep-http-handler/LICENSE b/tools/ofrep-http-handler/LICENSE new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/tools/ofrep-http-handler/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tools/ofrep-http-handler/README.md b/tools/ofrep-http-handler/README.md new file mode 100644 index 000000000..a253a5f73 --- /dev/null +++ b/tools/ofrep-http-handler/README.md @@ -0,0 +1,129 @@ +# OFREP HTTP Handler + +This module provides an HTTP handler that wraps any OpenFeature provider and exposes it as an OFREP (OpenFeature Remote Evaluation Protocol) compliant HTTP handler. + +## Overview + +The OFREP HTTP Handler takes any OpenFeature provider. This allows you to: + +- Expose any OpenFeature provider as a remote service +- Use existing providers over HTTP without modification +- Create OFREP-compliant services for client-side SDKs +- Build distributed feature flag architectures + +## Installation + +```bash +go get github.com/open-feature/go-sdk-contrib/tools/ofrep-http-handler +``` + +## Usage + +### Basic Usage + +```go +package main + +import ( + "net/http" + "log" + + ofrephandler "github.com/open-feature/go-sdk-contrib/tools/ofrep-http-handler" + // Import any OpenFeature provider + "your-provider-package" +) + +func main() { + // Create any OpenFeature provider + provider := yourprovider.NewProvider("your-config") + + // Create the OFREP HTTP handler + handler := ofrephandler.NewHandler(provider) + + // Set up HTTP server + mux := http.NewServeMux() + mux.Handle("POST /ofrep/v1/evaluate/flags/{key}", handler) + + // Start server + log.Fatal(http.ListenAndServe(":8080", mux)) +} +``` + +There are some options to configure the handler to suit your needs: + +```go +handler := ofrephandler.NewHandler(provider, + // The handler will not require the "/ofrep/v1/evaluate/flags/" prefix. + ofrephandler.WithoutPathPrefix(), + // The handler will not require the "POST" method. + ofrephandler.WithoutOnlyPOST(), + // The handler will use a different path value name instead of "key". + ofrephandler.WithPathValueName("flag-key"), +) +``` + +### Client Usage + +There are some OFREP providers available listed [here](https://github.com/open-feature/protocol/tree/main?tab=readme-ov-file#providers). The one for golang is [github.com/open-feature/go-sdk-contrib/providers/ofrep](../../providers/ofrep/README.md). + +## OFREP Endpoint + +The handler exposes the standard OFREP endpoint: + +``` + +POST /ofrep/v1/evaluate/flags/{flag-key} + +``` + +### Request Format + +```json +{ + "context": { + "userId": "user123", + "email": "user@example.com", + "customAttribute": "value" + } +} +``` + +The `context` field is optional and contains evaluation context data. + +### Response Format + +#### Success Response (HTTP 200) + +```json +{ + "key": "feature-flag-key", + "value": true, + "reason": "STATIC", + "variant": "enabled", + "metadata": { + "customField": "value" + } +} +``` + +#### Error Response (HTTP 4xx/5xx) + +```json +{ + "errorCode": "ERROR_REASON", + "errorDetails": "This errored because..." +} +``` + +#### Flag Not Found Response + +```json +{ + "errorCode": "FLAG_NOT_FOUND", + "errorDetails": "Flag 'unknown-flag' not found" +} +``` + +## License + +This project follows the same license as the OpenFeature Go SDK Contrib repository. diff --git a/tools/ofrep-http-handler/go.mod b/tools/ofrep-http-handler/go.mod new file mode 100644 index 000000000..7c42812b1 --- /dev/null +++ b/tools/ofrep-http-handler/go.mod @@ -0,0 +1,10 @@ +module github.com/open-feature/go-sdk-contrib/tools/ofrep-http-handler + +go 1.23.0 + +require github.com/open-feature/go-sdk v1.15.1 + +require ( + github.com/go-logr/logr v1.4.3 // indirect + go.uber.org/mock v0.5.2 // indirect +) diff --git a/tools/ofrep-http-handler/go.sum b/tools/ofrep-http-handler/go.sum new file mode 100644 index 000000000..bf3f8e7c0 --- /dev/null +++ b/tools/ofrep-http-handler/go.sum @@ -0,0 +1,8 @@ +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/open-feature/go-sdk v1.15.1 h1:TC3FtHtOKlGlIbSf3SEpxXVhgTd/bCbuc39XHIyltkw= +github.com/open-feature/go-sdk v1.15.1/go.mod h1:2WAFYzt8rLYavcubpCoiym3iSCXiHdPB6DxtMkv2wyo= +go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko= +go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o= +golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M= +golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA= diff --git a/tools/ofrep-http-handler/handler.go b/tools/ofrep-http-handler/handler.go new file mode 100644 index 000000000..03df608fb --- /dev/null +++ b/tools/ofrep-http-handler/handler.go @@ -0,0 +1,118 @@ +package ofrephandler + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + + "github.com/open-feature/go-sdk/openfeature" +) + +const prefix = "/ofrep/v1/evaluate/flags/" + +// Handler implements an HTTP handler that wraps an OpenFeature provider +// and exposes it as an OFREP-compliant HTTP service. +type Handler struct { + provider openfeature.FeatureProvider + config *Configuration +} + +// New creates a new OFREP HTTP handler that wraps the given provider. +func New(provider openfeature.FeatureProvider, opts ...Option) *Handler { + config := &Configuration{ + requirePathPrefix: true, + requirePOST: true, + pathValueName: "key", + } + + for _, opt := range opts { + opt(config) + } + + return &Handler{ + provider: provider, + config: config, + } +} + +// EvaluationRequest represents the OFREP evaluation request +type EvaluationRequest struct { + Context any `json:"context,omitempty"` +} + +func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + + if h.config.requirePathPrefix && !strings.HasPrefix(r.URL.Path, prefix) { + h.writeError(w, http.StatusNotFound, "NOT_FOUND", "Endpoint not found") + return + } + + if h.config.requirePOST && r.Method != http.MethodPost { + h.writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Method not allowed") + return + } + + var request EvaluationRequest + if err := json.NewDecoder(r.Body).Decode(&request); err != nil && !errors.Is(err, io.EOF) { + h.writeError(w, http.StatusBadRequest, "PARSE_ERROR", fmt.Sprintf("Invalid request body: %v", err)) + return + } + + evalCtx := openfeature.FlattenedContext{} + if ctx, ok := request.Context.(map[string]any); ok { + evalCtx = openfeature.FlattenedContext(ctx) + } + + flagKey := r.PathValue(h.config.pathValueName) + if objectResult := h.provider.ObjectEvaluation(r.Context(), flagKey, nil, evalCtx); objectResult.Reason != openfeature.ErrorReason { + if objectResult.Reason == openfeature.DefaultReason { + h.writeFlagNotFoundError(w, flagKey) + return + } + h.writeSuccess(w, flagKey, objectResult) + return + } + h.writeFlagNotFoundError(w, flagKey) +} + +type EvaluationResponse struct { + Key string `json:"key"` + Value any `json:"value"` + Reason string `json:"reason"` + Variant string `json:"variant,omitempty"` + Metadata map[string]any `json:"metadata,omitempty"` +} + +func (h *Handler) writeSuccess(w http.ResponseWriter, flagKey string, objectResult openfeature.InterfaceResolutionDetail) { + w.WriteHeader(http.StatusOK) + response := EvaluationResponse{ + Key: flagKey, + Value: objectResult.Value, + Reason: string(objectResult.Reason), + Variant: objectResult.Variant, + Metadata: objectResult.FlagMetadata, + } + json.NewEncoder(w).Encode(response) +} + +type ErrorResponse struct { + ErrorCode string `json:"errorCode"` + ErrorDetails string `json:"errorDetails"` +} + +func (h *Handler) writeError(w http.ResponseWriter, statusCode int, errorCode, errorDetails string) { + w.WriteHeader(statusCode) + errorResponse := ErrorResponse{ + ErrorCode: errorCode, + ErrorDetails: errorDetails, + } + json.NewEncoder(w).Encode(errorResponse) +} + +func (h *Handler) writeFlagNotFoundError(w http.ResponseWriter, flagKey string) { + h.writeError(w, http.StatusNotFound, string(openfeature.FlagNotFoundCode), fmt.Sprintf("Flag '%s' not found", flagKey)) +} diff --git a/tools/ofrep-http-handler/handler_test.go b/tools/ofrep-http-handler/handler_test.go new file mode 100644 index 000000000..e51510c7d --- /dev/null +++ b/tools/ofrep-http-handler/handler_test.go @@ -0,0 +1,145 @@ +package ofrephandler_test + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + ofrephandler "github.com/open-feature/go-sdk-contrib/tools/ofrep-http-handler" +) + +func TestHandler_ServeHTTP(t *testing.T) { + flags := map[string]mockValue{ + "test-bool-flag": {value: true}, + "test-string-flag": {value: "hello"}, + "test-ctx-flag": { + value: "context-value", + requireCtx: map[string]any{"userId": "456"}, + }, + } + + tests := []struct { + name string + method string + path string + body any + expectedCode int + expectedType string + options []ofrephandler.Option + }{ + { + name: "successful boolean flag evaluation", + method: "POST", + path: "/ofrep/v1/evaluate/flags/test-bool-flag", + expectedCode: http.StatusOK, + expectedType: "bool", + }, + { + name: "successful string flag evaluation", + method: "POST", + path: "/ofrep/v1/evaluate/flags/test-string-flag", + expectedCode: http.StatusOK, + expectedType: "string", + }, + { + name: "successful matching context for flag", + method: "POST", + path: "/ofrep/v1/evaluate/flags/test-ctx-flag", + body: ofrephandler.EvaluationRequest{Context: map[string]any{"userId": "456"}}, + expectedCode: http.StatusOK, + }, + { + name: "fails non-matching context for flag", + method: "POST", + path: "/ofrep/v1/evaluate/flags/test-ctx-flag", + body: ofrephandler.EvaluationRequest{Context: map[string]any{"userId": "123"}}, + expectedCode: http.StatusNotFound, + }, + { + name: "successful flag evaluation on non-post with option", + method: "GET", + path: "/ofrep/v1/evaluate/flags/test-bool-flag", + expectedCode: http.StatusOK, + expectedType: "bool", + options: []ofrephandler.Option{ofrephandler.WithoutOnlyPOST()}, + }, + { + name: "successful flag evaluation on non-prefix path with option", + method: "POST", + path: "/test-bool-flag", + expectedCode: http.StatusOK, + expectedType: "bool", + options: []ofrephandler.Option{ofrephandler.WithoutPathPrefix()}, + }, + { + name: "flag not found", + method: "POST", + path: "/ofrep/v1/evaluate/flags/nonexistent-flag", + expectedCode: http.StatusNotFound, + }, + { + name: "method not allowed", + method: "GET", + path: "/ofrep/v1/evaluate/flags/test-bool-flag", + expectedCode: http.StatusMethodNotAllowed, + }, + { + name: "invalid path", + method: "POST", + path: "/invalid/path", + expectedCode: http.StatusNotFound, + }, + { + name: "empty flag key", + method: "POST", + path: "/ofrep/v1/evaluate/flags/", + expectedCode: http.StatusNotFound, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var body bytes.Buffer + if tt.body != nil { + json.NewEncoder(&body).Encode(tt.body) + } + + req := httptest.NewRequest(tt.method, tt.path, &body) + req.SetPathValue("key", strings.TrimPrefix(strings.TrimPrefix(tt.path, "/ofrep/v1/evaluate/flags/"), "/")) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + + ofrephandler.New(newMockProvider(flags), tt.options...).ServeHTTP(w, req) + + if w.Code != tt.expectedCode { + t.Errorf("expected status code %d, got %d", tt.expectedCode, w.Code) + } + + if tt.expectedCode == http.StatusOK { + var response ofrephandler.EvaluationResponse + err := json.NewDecoder(w.Body).Decode(&response) + if err != nil { + t.Fatalf("failed to decode response: %v", err) + } + + switch tt.expectedType { + case "bool": + if _, ok := response.Value.(bool); !ok { + t.Errorf("expected boolean value, got %T", response.Value) + } + case "string": + if _, ok := response.Value.(string); !ok { + t.Errorf("expected string value, got %T", response.Value) + } + } + + if response.Key == "" { + t.Error("expected key in response") + } + } + }) + } +} diff --git a/tools/ofrep-http-handler/mockprovider_test.go b/tools/ofrep-http-handler/mockprovider_test.go new file mode 100644 index 000000000..3c04cfcc0 --- /dev/null +++ b/tools/ofrep-http-handler/mockprovider_test.go @@ -0,0 +1,85 @@ +package ofrephandler_test + +import ( + "context" + "fmt" + + "github.com/open-feature/go-sdk/openfeature" +) + +func newMockProvider(flags map[string]mockValue) *mockProvider { + return &mockProvider{flags} +} + +type mockValue struct { + value any + requireCtx map[string]any +} + +type mockProvider struct { + flags map[string]mockValue +} + +func (c *mockProvider) BooleanEvaluation(ctx context.Context, flag string, defaultValue bool, flatCtx openfeature.FlattenedContext) openfeature.BoolResolutionDetail { + val, detail := evaluate(c.flags, flatCtx, flag, defaultValue) + return openfeature.BoolResolutionDetail{Value: val, ProviderResolutionDetail: detail} +} + +func (c *mockProvider) FloatEvaluation(ctx context.Context, flag string, defaultValue float64, flatCtx openfeature.FlattenedContext) openfeature.FloatResolutionDetail { + val, detail := evaluate(c.flags, flatCtx, flag, defaultValue) + return openfeature.FloatResolutionDetail{Value: val, ProviderResolutionDetail: detail} +} + +func (c *mockProvider) IntEvaluation(ctx context.Context, flag string, defaultValue int64, flatCtx openfeature.FlattenedContext) openfeature.IntResolutionDetail { + val, detail := evaluate(c.flags, flatCtx, flag, defaultValue) + return openfeature.IntResolutionDetail{Value: val, ProviderResolutionDetail: detail} +} + +func (c *mockProvider) ObjectEvaluation(ctx context.Context, flag string, defaultValue any, flatCtx openfeature.FlattenedContext) openfeature.InterfaceResolutionDetail { + val, detail := evaluate(c.flags, flatCtx, flag, defaultValue) + return openfeature.InterfaceResolutionDetail{Value: val, ProviderResolutionDetail: detail} +} + +func (c *mockProvider) StringEvaluation(ctx context.Context, flag string, defaultValue string, flatCtx openfeature.FlattenedContext) openfeature.StringResolutionDetail { + val, detail := evaluate(c.flags, flatCtx, flag, defaultValue) + return openfeature.StringResolutionDetail{Value: val, ProviderResolutionDetail: detail} +} + +func (c *mockProvider) Hooks() []openfeature.Hook { + return nil +} + +func (c *mockProvider) Metadata() openfeature.Metadata { + return openfeature.NamedProviderMetadata("mock-provider") +} + +func evaluate[T any](flags map[string]mockValue, flatCtx openfeature.FlattenedContext, flag string, defaultValue T) (T, openfeature.ProviderResolutionDetail) { + mockVal, ok := flags[flag] + if !ok { + return defaultValue, openfeature.ProviderResolutionDetail{ + Reason: openfeature.DefaultReason, + } + } + + if mockVal.requireCtx != nil { + for k, v := range mockVal.requireCtx { + if ctxVal, exists := flatCtx[k]; !exists || ctxVal != v { + return defaultValue, openfeature.ProviderResolutionDetail{ + Reason: openfeature.DefaultReason, + } + } + } + } + + parsedVal, ok := mockVal.value.(T) + if !ok { + return defaultValue, openfeature.ProviderResolutionDetail{ + Reason: openfeature.ErrorReason, + ResolutionError: openfeature.NewTypeMismatchResolutionError(fmt.Sprintf("expected type %T, got %T", defaultValue, mockVal)), + } + } + + return parsedVal, openfeature.ProviderResolutionDetail{ + Reason: openfeature.CachedReason, + } +} diff --git a/tools/ofrep-http-handler/options.go b/tools/ofrep-http-handler/options.go new file mode 100644 index 000000000..04388f84a --- /dev/null +++ b/tools/ofrep-http-handler/options.go @@ -0,0 +1,33 @@ +package ofrephandler + +type Configuration struct { + requirePathPrefix bool + requirePOST bool + pathValueName string +} + +type Option func(*Configuration) + +// WithoutPathPrefix makes the handler only accept requests from any path prefix. +// By default, it requires the path to start with "/ofrep/v1/evaluate/flags/". +func WithoutPathPrefix() Option { + return func(conf *Configuration) { + conf.requirePathPrefix = false + } +} + +// WithoutOnlyPOST makes the handler accept requests with any HTTP method. +// By default, it requires POST requests. +func WithoutOnlyPOST() Option { + return func(conf *Configuration) { + conf.requirePOST = false + } +} + +// WithKeyPathValueName sets the name of the path value to extract the flag key from. +// The default is "key". +func WithKeyPathValueName(pathValue string) Option { + return func(conf *Configuration) { + conf.pathValueName = pathValue + } +} From 7e4d1230081d85d9d24b2d7d18e8fa60b573428c Mon Sep 17 00:00:00 2001 From: ZackarySantana <64446617+ZackarySantana@users.noreply.github.com> Date: Wed, 20 Aug 2025 00:34:08 -0400 Subject: [PATCH 2/2] feat: add release info --- .github/component_owners.yml | 2 ++ .release-please-manifest.json | 3 ++- release-please-config.json | 8 ++++++++ tools/ofrep-http-handler/CHANGELOG.md | 2 +- 4 files changed, 13 insertions(+), 2 deletions(-) diff --git a/.github/component_owners.yml b/.github/component_owners.yml index 3fcf1d841..1d79f9a92 100644 --- a/.github/component_owners.yml +++ b/.github/component_owners.yml @@ -43,6 +43,8 @@ components: - semanticart tools/flagd-http-connector: - liran2000 + tools/ofrep: + - zackarysantana ignored-authors: - renovate-bot diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 909389e49..7e2946495 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -17,5 +17,6 @@ "tests/flagd": "1.4.1", "providers/go-feature-flag-in-process": "0.1.1", "providers/multi-provider": "0.0.4", - "tools/flagd-http-connector": "0.0.2" + "tools/flagd-http-connector": "0.0.2", + "tools/ofrep": "0.0.1" } diff --git a/release-please-config.json b/release-please-config.json index 960d31e31..07cdcabf4 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -156,6 +156,14 @@ "versioning": "default", "extra-files": [] }, + "tools/ofrep": { + "release-type": "go", + "package-name": "tools/ofrep", + "bump-minor-pre-major": true, + "bump-patch-for-minor-pre-major": true, + "versioning": "default", + "extra-files": [] + }, "providers/aws-ssm": { "release-type": "go", "package-name": "providers/aws-ssm", diff --git a/tools/ofrep-http-handler/CHANGELOG.md b/tools/ofrep-http-handler/CHANGELOG.md index bf812b73c..cb6bbd394 100644 --- a/tools/ofrep-http-handler/CHANGELOG.md +++ b/tools/ofrep-http-handler/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## [Unreleased] +## [0.0.1] ### Added