Refactor to WithoutCancel context.

With Go 1.21 the WithoutCancel context was introduced. This way we can keep the values passed in a new context without having the new context being canceled together with its parent. This behavior suits well for two occurrences where we explicitly had to copy one required value instead of implicitly keeping all values.
This commit is contained in:
Maximilian Paß
2023-08-16 12:18:02 +02:00
committed by Sebastian Serth
parent 2f43bced08
commit 89c18ad45c

View File

@ -4,7 +4,6 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"github.com/getsentry/sentry-go"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
"github.com/openHPI/poseidon/internal/api/ws" "github.com/openHPI/poseidon/internal/api/ws"
"github.com/openHPI/poseidon/internal/runner" "github.com/openHPI/poseidon/internal/runner"
@ -37,9 +36,9 @@ func upgradeConnection(writer http.ResponseWriter, request *http.Request) (ws.Co
// As this proxy is already started, a start message is send to the client. // As this proxy is already started, a start message is send to the client.
func newWebSocketProxy(connection ws.Connection, proxyCtx context.Context) *webSocketProxy { func newWebSocketProxy(connection ws.Connection, proxyCtx context.Context) *webSocketProxy {
// wsCtx is detached from the proxyCtx // wsCtx is detached from the proxyCtx
// as it should send all messages in the buffer even if the execution/proxy is done. // as it should send all messages in the buffer even shortly after the execution/proxy is done.
wsCtx, cancelWsCommunication := context.WithCancel(context.Background()) wsCtx := context.WithoutCancel(proxyCtx)
wsCtx = sentry.SetHubOnContext(wsCtx, sentry.GetHubFromContext(proxyCtx)) wsCtx, cancelWsCommunication := context.WithCancel(wsCtx)
proxy := &webSocketProxy{ proxy := &webSocketProxy{
ctx: wsCtx, ctx: wsCtx,
@ -92,9 +91,9 @@ func (r *RunnerController) connectToRunner(writer http.ResponseWriter, request *
return return
} }
// ToDo: Why can we not inherit from request.Context() here? // We do not inherit from the request.Context() here because we rely on the WebSocket Close Handler.
proxyCtx, cancelProxy := context.WithCancel(context.Background()) proxyCtx := context.WithoutCancel(request.Context())
proxyCtx = sentry.SetHubOnContext(proxyCtx, sentry.GetHubFromContext(request.Context())) proxyCtx, cancelProxy := context.WithCancel(proxyCtx)
defer cancelProxy() defer cancelProxy()
proxy := newWebSocketProxy(connection, proxyCtx) proxy := newWebSocketProxy(connection, proxyCtx)