Merge branch '20457-careful-near-quota'
[arvados.git] / sdk / go / arvados / container_gateway.go
index ce33fb3105a218a537fe8b0c28cf122041b962a5..897ae434e14bd0a0392d041a125a598b2c1d8b34 100644 (file)
@@ -15,6 +15,7 @@ import (
 )
 
 func (cresp ConnectionResponse) ServeHTTP(w http.ResponseWriter, req *http.Request) {
+       defer cresp.Conn.Close()
        hj, ok := w.(http.Hijacker)
        if !ok {
                http.Error(w, "ResponseWriter does not support connection upgrade", http.StatusInternalServerError)
@@ -33,8 +34,8 @@ func (cresp ConnectionResponse) ServeHTTP(w http.ResponseWriter, req *http.Reque
        defer conn.Close()
 
        var bytesIn, bytesOut int64
-       var wg sync.WaitGroup
        ctx, cancel := context.WithCancel(req.Context())
+       var wg sync.WaitGroup
        wg.Add(1)
        go func() {
                defer wg.Done()
@@ -63,11 +64,16 @@ func (cresp ConnectionResponse) ServeHTTP(w http.ResponseWriter, req *http.Reque
                        ctxlog.FromContext(ctx).WithError(err).Error("error copying upstream")
                }
        }()
-       wg.Wait()
-       if cresp.Logger != nil {
-               cresp.Logger.WithFields(logrus.Fields{
-                       "bytesIn":  bytesIn,
-                       "bytesOut": bytesOut,
-               }).Info("closed connection")
-       }
+       <-ctx.Done()
+       go func() {
+               // Wait for both io.Copy goroutines to finish and increment
+               // their byte counters.
+               wg.Wait()
+               if cresp.Logger != nil {
+                       cresp.Logger.WithFields(logrus.Fields{
+                               "bytesIn":  bytesIn,
+                               "bytesOut": bytesOut,
+                       }).Info("closed connection")
+               }
+       }()
 }