-
Notifications
You must be signed in to change notification settings - Fork 0
feat: add proxy job #15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
f6d7ecd
feat: add proxy job
davideimola c6288c9
feat: improvements
davideimola 7588a29
feat: improvements of error communication with server
davideimola 4270a1a
refactor: streamline context handling and improve proxy routine concu…
ludusrusso 8189a7a
feat: does not verify ssl
davideimola a0c7036
feat: change
davideimola 9c0e062
feat: test
davideimola 7c6591a
feat: test
davideimola 3c2cbff
feat: test
davideimola 5a66d01
feat: test
davideimola 2bcac9f
feat: new version of headers
davideimola ac28c25
feat: skip encoding
davideimola d8145fa
feat: add timeout
davideimola File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,184 @@ | ||
| package routines | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "crypto/tls" | ||
| "encoding/json" | ||
| "fmt" | ||
| "io" | ||
| "net/http" | ||
| "strings" | ||
| "sync" | ||
| "time" | ||
|
|
||
| "connectrpc.com/connect" | ||
| "github.com/sirupsen/logrus" | ||
| "google.golang.org/protobuf/types/known/durationpb" | ||
| agents_publicv1 "pkg.redcarbon.ai/proto/redcarbon/agents_public/v1" | ||
| ) | ||
|
|
||
| var defaultTimeout = 1 * time.Minute | ||
|
|
||
| var httpCli = &http.Client{ | ||
| Timeout: defaultTimeout, | ||
| Transport: &http.Transport{ | ||
| TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, | ||
| }, | ||
| } | ||
|
|
||
| func (r RoutineConfig) ProxyRoutine(ctx context.Context) { | ||
| logrus.Debug("Starting the proxy routine...") | ||
|
|
||
| // Prepare the request to fetch agent requests | ||
| req := connect.NewRequest(&agents_publicv1.FetchAgentRequestsRequest{}) | ||
| req.Header().Set("authorization", fmt.Sprintf("ApiToken %s", r.profile.Profile.Token)) | ||
|
|
||
| ctx, cancel := context.WithTimeout(ctx, defaultTimeout) | ||
| defer cancel() | ||
|
|
||
| logrus.Debug("Fetching the agent requests...") | ||
| res, err := r.agentsCli.FetchAgentRequests(ctx, req) | ||
| if err != nil { | ||
| logrus.WithError(err).Error("Error while fetching the agent requests") | ||
| return | ||
| } | ||
|
|
||
| logrus.Debugf("Running %d agent requests...", len(res.Msg.Requests)) | ||
|
|
||
| var wg sync.WaitGroup | ||
|
|
||
| for _, agentReq := range res.Msg.Requests { | ||
| wg.Add(1) | ||
| go func() { | ||
| defer wg.Done() | ||
| r.processRequest(ctx, agentReq) | ||
| }() | ||
| } | ||
|
|
||
| wg.Wait() | ||
|
|
||
| logrus.Debug("Proxy routine completed") | ||
| } | ||
|
|
||
| func (r RoutineConfig) processRequest(ctx context.Context, req *agents_publicv1.AgentRequest) { | ||
| l := logrus.WithFields(logrus.Fields{ | ||
| "id": req.RequestId, | ||
| }) | ||
|
|
||
| l.Debug("Handling request...") | ||
|
|
||
| ctx, cancel := extractTimeout(ctx, req.Timeout) | ||
| defer cancel() | ||
|
|
||
| httpReq, err := r.createHTTPProxyRequest(ctx, req) | ||
| if err != nil { | ||
| l.WithError(err).Error("Error while creating the HTTP request") | ||
| r.sendErrorToServer(ctx, req, "error while creating the HTTP request") | ||
| return | ||
| } | ||
|
|
||
| logrus.WithField("headers", httpReq.Header).Infof("Executing HTTP request: %s %s", req.Method, req.Url) | ||
|
|
||
| httpRes, err := httpCli.Do(httpReq) | ||
| if err != nil { | ||
| l.WithError(err).Error("Error while executing the HTTP request") | ||
| r.sendErrorToServer(ctx, req, "error while executing the HTTP request") | ||
| return | ||
| } | ||
| defer httpRes.Body.Close() | ||
|
|
||
| l.Infof("Request completed with status code %d, sending the response to the server", httpRes.StatusCode) | ||
|
|
||
| err = r.sendResponseToServer(ctx, req, httpRes) | ||
| if err != nil { | ||
| l.WithError(err).Error("Error while sending the response to the server") | ||
| r.sendErrorToServer(ctx, req, "error while sending the response to the server") | ||
| return | ||
| } | ||
| } | ||
|
|
||
| func extractTimeout(ctx context.Context, requestTimeout *durationpb.Duration) (context.Context, context.CancelFunc) { | ||
| timeout := 10 * time.Second | ||
| if requestTimeout != nil && requestTimeout.AsDuration() > 0 { | ||
| timeout = requestTimeout.AsDuration() | ||
| } | ||
|
|
||
| return context.WithTimeout(ctx, timeout) | ||
| } | ||
|
|
||
| func (r RoutineConfig) createHTTPProxyRequest(ctx context.Context, req *agents_publicv1.AgentRequest) (*http.Request, error) { | ||
| // Url is already validated by the server | ||
| httpReq, err := http.NewRequestWithContext(ctx, req.Method, req.Url, bytes.NewBuffer(req.Body)) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| for key, value := range req.Headers { | ||
| if strings.ToLower(key) == "accept-encoding" { | ||
| continue | ||
| } | ||
|
|
||
| for _, v := range value.Values { | ||
| httpReq.Header.Add(key, v) | ||
| } | ||
| } | ||
|
|
||
| return httpReq, nil | ||
| } | ||
|
|
||
| func (r RoutineConfig) sendErrorToServer(ctx context.Context, req *agents_publicv1.AgentRequest, reason string) { | ||
| body, err := json.Marshal(map[string]string{ | ||
| "error": reason, | ||
| }) | ||
| if err != nil { | ||
| logrus.WithError(err).Error("Error while marshalling the error to the server") | ||
| return | ||
| } | ||
|
|
||
| response := connect.NewRequest(&agents_publicv1.SubmitAgentResponseRequest{ | ||
| RequestId: req.RequestId, | ||
| Response: &agents_publicv1.AgentResponse{ | ||
| Status: int32(http.StatusInternalServerError), | ||
| Body: body, | ||
| Headers: map[string]*agents_publicv1.ValueHeader{}, | ||
| }, | ||
| }) | ||
| response.Header().Set("authorization", fmt.Sprintf("ApiToken %s", r.profile.Profile.Token)) | ||
|
|
||
| _, err = r.agentsCli.SubmitAgentResponse(ctx, response) | ||
| if err != nil { | ||
| logrus.WithError(err).Error("Error while sending the error to the server") | ||
| } | ||
| } | ||
|
|
||
| func (r RoutineConfig) sendResponseToServer(ctx context.Context, req *agents_publicv1.AgentRequest, httpRes *http.Response) error { | ||
| body, err := io.ReadAll(httpRes.Body) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| headers := make(map[string]*agents_publicv1.ValueHeader) | ||
| for key, values := range httpRes.Header { | ||
| headers[key] = &agents_publicv1.ValueHeader{ | ||
| Values: values, | ||
| } | ||
| } | ||
|
|
||
| response := connect.NewRequest(&agents_publicv1.SubmitAgentResponseRequest{ | ||
| RequestId: req.RequestId, | ||
| Response: &agents_publicv1.AgentResponse{ | ||
| Status: int32(httpRes.StatusCode), | ||
| Body: body, | ||
| Headers: headers, | ||
| }, | ||
| }) | ||
| response.Header().Set("authorization", fmt.Sprintf("ApiToken %s", r.profile.Profile.Token)) | ||
|
|
||
| _, err = r.agentsCli.SubmitAgentResponse(ctx, response) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| [tools] | ||
| buf = "1.45.0" | ||
| go = "1.24" |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.