Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c24a8ccc63 | ||
|
|
d066a6e11d |
No files matched your search
@@ -2,48 +2,106 @@ name: k6 Load Test
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, edited]
|
||||
schedule:
|
||||
- cron: '0 4 * * *'
|
||||
types: [opened, synchronize, reopened]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
ocis_ref:
|
||||
description: 'oCIS commit or branch to build on the target (must exist in owncloud/ocis)'
|
||||
default: master
|
||||
quick:
|
||||
description: 'Short smoke run instead of the full ramping suite'
|
||||
type: boolean
|
||||
default: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: k6-load-test-server
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
k6-load-test:
|
||||
name: k6-load-test
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: owncloudci/alpine:latest
|
||||
# The runner lives on the k6 driver itself, so there is no checkout, no
|
||||
# container and no ssh into the driver — only the target is remote.
|
||||
runs-on: [self-hosted, loadtest]
|
||||
timeout-minutes: 360
|
||||
if: >-
|
||||
github.event_name == 'schedule' ||
|
||||
github.event_name == 'workflow_dispatch' ||
|
||||
(github.event_name == 'pull_request' &&
|
||||
contains(github.event.pull_request.title || '', 'k6-test'))
|
||||
env:
|
||||
SSH_OCIS_REMOTE: ${{ secrets.SSH_OCIS_REMOTE }}
|
||||
SSH_OCIS_USERNAME: ${{ secrets.SSH_OCIS_USERNAME }}
|
||||
SSH_OCIS_PASSWORD: ${{ secrets.SSH_OCIS_PASSWORD }}
|
||||
TEST_SERVER_URL: ${{ secrets.TEST_SERVER_URL }}
|
||||
SSH_K6_REMOTE: ${{ secrets.SSH_K6_REMOTE }}
|
||||
SSH_K6_USERNAME: ${{ secrets.SSH_K6_USERNAME }}
|
||||
SSH_K6_PASSWORD: ${{ secrets.SSH_K6_PASSWORD }}
|
||||
OCIS_COMMIT_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
OCIS_HOST: ${{ vars.LOADTEST_OCIS_HOST || 'loadtest-ocis.svc.owncloud.host' }}
|
||||
OCIS_COMMIT_ID: ${{ inputs.ocis_ref || github.event.pull_request.head.sha || github.sha }}
|
||||
# inputs.* is empty on pull_request, so the workflow_dispatch default does
|
||||
# not apply here — the shell below falls back to a quick run.
|
||||
QUICK: ${{ inputs.quick }}
|
||||
SSH_OPTS: -o BatchMode=yes -o ServerAliveInterval=60 -o ServerAliveCountMax=10
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
- name: Show what will run
|
||||
run: |
|
||||
echo "driver : $(hostname -f)"
|
||||
echo "target : $OCIS_HOST"
|
||||
echo "oCIS : $OCIS_COMMIT_ID"
|
||||
/usr/local/bin/k6 version
|
||||
|
||||
- name: Install SSH dependencies
|
||||
run: apk add --no-cache openssh-client sshpass
|
||||
- name: Build and start oCIS on the target
|
||||
id: start
|
||||
run: |
|
||||
ssh $SSH_OPTS "loadtest@$OCIS_HOST" \
|
||||
"OCIS_COMMIT_ID='$OCIS_COMMIT_ID' /usr/local/bin/ocis.sh start"
|
||||
|
||||
- name: Run k6 load tests
|
||||
run: sh tests/config/drone/run_k6_tests.sh
|
||||
- name: Show the oCIS build log
|
||||
if: failure() && steps.start.outcome == 'failure'
|
||||
run: ssh $SSH_OPTS "loadtest@$OCIS_HOST" 'tail -n 200 /srv/loadtest/ocis-build.log' || true
|
||||
|
||||
- name: Retrieve OCIS logs
|
||||
# ocis.sh proves readiness from the target's own shell. This proves it from
|
||||
# the driver, which is a different question: firewalld, and whether the
|
||||
# server outlived the ssh session that started it.
|
||||
- name: Check that the target answers from the driver
|
||||
run: |
|
||||
if curl -sk -o /dev/null --max-time 10 \
|
||||
"https://$OCIS_HOST:9200/.well-known/openid-configuration"; then
|
||||
echo "oCIS answers at https://$OCIS_HOST:9200"
|
||||
exit 0
|
||||
fi
|
||||
echo "::error::oCIS is not answering on $OCIS_HOST:9200 from the driver"
|
||||
ssh $SSH_OPTS "loadtest@$OCIS_HOST" \
|
||||
'pgrep -af "bin/ocis server" || echo "no oCIS process on the target"'
|
||||
exit 1
|
||||
|
||||
# No !cancelled() here on purpose: k6 against a target that failed to start
|
||||
# just buries the real error under a TypeScript stack trace.
|
||||
- name: Run the k6 tests
|
||||
run: |
|
||||
if [ "${QUICK:-true}" = "true" ]; then
|
||||
# Seed at least one user per VU: each VU logs in as the pool user
|
||||
# matching its own VU number, so seeding fewer users than the 16 VUs
|
||||
# started below leaves those extra VUs with accounts that were never
|
||||
# created, and every request they make fails to authenticate.
|
||||
export SEED_USERS_TOTAL=20
|
||||
for id in 020 040 050 070 080 090 100 110; do
|
||||
export TEST_KOKO_PLATFORM_${id}_RAMPING_STAGES_VUS=2
|
||||
export TEST_KOKO_PLATFORM_${id}_RAMPING_STAGES_UP_DURATION=10s
|
||||
export TEST_KOKO_PLATFORM_${id}_RAMPING_STAGES_PEAK_DURATION=30s
|
||||
export TEST_KOKO_PLATFORM_${id}_RAMPING_STAGES_DOWN_DURATION=10s
|
||||
export TEST_KOKO_PLATFORM_${id}_RAMPING_SLEEP_AFTER_ITERATION=1s
|
||||
done
|
||||
fi
|
||||
/usr/local/bin/k6-tests.sh
|
||||
|
||||
- name: Retrieve the oCIS log
|
||||
if: ${{ !cancelled() }}
|
||||
run: ssh $SSH_OPTS "loadtest@$OCIS_HOST" '/usr/local/bin/ocis.sh log' || true
|
||||
|
||||
# always(), not the old fire-and-forget tail call: a failing k6 run used to
|
||||
# leave oCIS holding port 9200, and the next run then failed to start.
|
||||
- name: Stop oCIS on the target
|
||||
if: always()
|
||||
run: sh tests/config/drone/run_k6_tests.sh --ocis-log
|
||||
run: ssh $SSH_OPTS "loadtest@$OCIS_HOST" '/usr/local/bin/ocis.sh stop'
|
||||
|
||||
- name: Show Grafana dashboard link
|
||||
if: always()
|
||||
if: ${{ !cancelled() }}
|
||||
run: |
|
||||
echo "Grafana Dashboard: https://grafana.k6.infra.owncloud.works"
|
||||
echo "Grafana: http://$(hostname -f):3000 (office/VPN only)"
|
||||
@@ -0,0 +1,5 @@
|
||||
Enhancement: Bump Reva version
|
||||
|
||||
bumped reva version
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13108
|
||||
@@ -65,7 +65,7 @@ require (
|
||||
github.com/open-policy-agent/opa v1.19.0
|
||||
github.com/orcaman/concurrent-map v1.0.0
|
||||
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261001150122-9557cab91f00
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261009092845-29bcf6360c8b
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/pkg/xattr v0.4.12
|
||||
github.com/prometheus/client_golang v1.24.1
|
||||
@@ -98,7 +98,7 @@ require (
|
||||
golang.org/x/crypto v0.57.0
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f
|
||||
golang.org/x/image v0.45.0
|
||||
golang.org/x/net v0.59.0
|
||||
golang.org/x/net v0.60.0
|
||||
golang.org/x/oauth2 v0.36.0
|
||||
golang.org/x/sync v0.23.0
|
||||
golang.org/x/term v0.46.0
|
||||
|
||||
@@ -735,8 +735,8 @@ github.com/orcaman/concurrent-map v1.0.0 h1:I/2A2XPCb4IuQWcQhBhSwGfiuybl/J0ev9HD
|
||||
github.com/orcaman/concurrent-map v1.0.0/go.mod h1:Lu3tH6HLW3feq74c2GC+jIMS/K2CFcDWnWD9XkenwhI=
|
||||
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245 h1:JRidLTAKhnvyLMRtVtSF4lhBa0NSAOs6fof+d6JnKII=
|
||||
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245/go.mod h1:z61VMGAJRtR1nbgXWiNoCkxUXP1B3Je9rMuJbnGd+Og=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261001150122-9557cab91f00 h1:VbWKQwx5KV4Dls6FIfSzsdaWcXwTf6zr5l3Jy8ApQlw=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261001150122-9557cab91f00/go.mod h1:LSXqMWTC7Ya6uxmqp1ksrWYZXBuZ6PhcmVimxyG8U5o=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261009092845-29bcf6360c8b h1:n03A9f4FFTcQz+8yFuvup8zvC6Krzugmszzzj/qoCUQ=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261009092845-29bcf6360c8b/go.mod h1:HgmYZSSOMpf3qy4TOy8jfvWdvcJ3apAzPAKhk5ALlHk=
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw=
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
|
||||
github.com/pablodz/inotifywaitgo v0.0.12 h1:DVJJTFMDlSAdO46yisPF2vzozs/r+4k6ih8MVghq78M=
|
||||
@@ -1098,8 +1098,8 @@ golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
|
||||
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
|
||||
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU=
|
||||
golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
|
||||
Generated
Vendored
+6
@@ -440,6 +440,12 @@ func (s *Service) InitiateFileUpload(ctx context.Context, req *provider.Initiate
|
||||
st = status.NewFailedPrecondition(ctx, err, "failed precondition")
|
||||
case errtypes.Locked:
|
||||
st = status.NewLocked(ctx, "locked")
|
||||
case errtypes.TooEarly:
|
||||
st = status.NewTooEarly(ctx, "response from InitiateUpload: "+err.Error())
|
||||
case errtypes.Aborted:
|
||||
st = status.NewAborted(ctx, err, "response from InitiateUpload")
|
||||
case errtypes.AlreadyExists:
|
||||
st = status.NewAlreadyExists(ctx, err, "response from InitiateUpload")
|
||||
default:
|
||||
st = status.NewInternal(ctx, "error getting upload id: "+err.Error())
|
||||
}
|
||||
|
||||
+2
-1
@@ -24,6 +24,7 @@ package errtypes
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
|
||||
@@ -384,7 +385,7 @@ func NewErrtypeFromHTTPStatusCode(code int, message string) error {
|
||||
case StatusChecksumMismatch:
|
||||
return ChecksumMismatch(message)
|
||||
default:
|
||||
return InternalError(message)
|
||||
return InternalError("http " + strconv.Itoa(code) + ": " + message)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+11
@@ -170,6 +170,15 @@ func NewTooManyRequests(ctx context.Context, msg string) *rpc.Status {
|
||||
}
|
||||
}
|
||||
|
||||
// NewTooEarly returns a status Code_CODE_TOO_EARLY
|
||||
func NewTooEarly(ctx context.Context, msg string) *rpc.Status {
|
||||
return &rpc.Status{
|
||||
Code: rpc.Code_CODE_TOO_EARLY,
|
||||
Message: msg,
|
||||
Trace: getTrace(ctx),
|
||||
}
|
||||
}
|
||||
|
||||
// NewStatusFromErrType returns a status that corresponds to the given errtype
|
||||
func NewStatusFromErrType(ctx context.Context, msg string, err error) *rpc.Status {
|
||||
switch e := err.(type) {
|
||||
@@ -202,6 +211,8 @@ func NewStatusFromErrType(ctx context.Context, msg string, err error) *rpc.Statu
|
||||
return NewInvalid(ctx, msg+":"+err.Error())
|
||||
case errtypes.TooManyRequests:
|
||||
return NewTooManyRequests(ctx, msg+": "+err.Error())
|
||||
case errtypes.TooEarly:
|
||||
return NewTooEarly(ctx, msg+": "+err.Error())
|
||||
}
|
||||
|
||||
// map GRPC status codes coming from the auth middleware
|
||||
|
||||
+3
@@ -275,6 +275,9 @@ func handleError(w http.ResponseWriter, log *zerolog.Logger, err error, action s
|
||||
case errtypes.Aborted:
|
||||
log.Debug().Err(err).Str("action", action).Msg("etags do not match")
|
||||
w.WriteHeader(http.StatusPreconditionFailed)
|
||||
case errtypes.IsTooEarly:
|
||||
log.Debug().Err(err).Str("action", action).Msg("resource is processing")
|
||||
w.WriteHeader(http.StatusTooEarly)
|
||||
default:
|
||||
log.Error().Err(err).Str("action", action).Msg("unexpected error")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
// Package cas classifies CAS-conflict errors shared by providercache, sharecache, and receivedsharecache.
|
||||
package cas
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
backoff "github.com/cenkalti/backoff/v5"
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/metadata"
|
||||
"github.com/rs/zerolog"
|
||||
grpccodes "google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// NewBackoff returns the backoff policy shared by every CAS-retry loop.
|
||||
func NewBackoff() *backoff.ExponentialBackOff {
|
||||
bo := backoff.NewExponentialBackOff()
|
||||
bo.InitialInterval = 500 * time.Microsecond
|
||||
bo.Multiplier = 2.0
|
||||
bo.RandomizationFactor = 1.0
|
||||
bo.MaxInterval = 50 * time.Millisecond
|
||||
return bo
|
||||
}
|
||||
|
||||
// IsConflict reports whether err is a CAS conflict the caller should resync and retry on.
|
||||
func IsConflict(err error) bool {
|
||||
switch err.(type) {
|
||||
case errtypes.Aborted:
|
||||
// If-Match etag check failed
|
||||
return true
|
||||
case errtypes.PreconditionFailed:
|
||||
// same as Aborted; some server paths return this instead
|
||||
return true
|
||||
case errtypes.AlreadyExists:
|
||||
// If-None-Match=* conflict: cache thought there was no file yet
|
||||
return true
|
||||
case errtypes.TooEarly:
|
||||
// an upload is already in progress for this path
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// IsSyncTransient reports whether a sync's Download error is worth retrying.
|
||||
func IsSyncTransient(err error) bool {
|
||||
_, isTooEarly := err.(errtypes.IsTooEarly)
|
||||
return isTooEarly || IsTransientGRPCStatus(err)
|
||||
}
|
||||
|
||||
// IsTransientGRPCStatus catches raw gRPC transport errors that metadata.CS3 never wraps in errtypes.
|
||||
func IsTransientGRPCStatus(err error) bool {
|
||||
st, ok := status.FromError(err)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
switch st.Code() {
|
||||
case grpccodes.Unavailable, grpccodes.DeadlineExceeded, grpccodes.Canceled, grpccodes.ResourceExhausted:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// RetryPersist retries persistFunc on a CAS conflict, calling resyncFunc between attempts to
|
||||
// refresh in-memory state before the next persist, up to maxRetries times with this package's
|
||||
// shared backoff. onConflict/onPersistFailed/onResyncFailed let the caller record its own
|
||||
// span/log side effects for each outcome without this package depending on otel/zerolog.
|
||||
func RetryPersist(ctx context.Context, maxRetries int, persistFunc, resyncFunc func() error,
|
||||
onConflict, onPersistFailed, onResyncFailed func(err error)) error {
|
||||
bo := NewBackoff()
|
||||
var err error
|
||||
for retries := maxRetries; retries > 0; retries-- {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
err = persistFunc()
|
||||
switch {
|
||||
case err == nil:
|
||||
return nil
|
||||
case IsConflict(err):
|
||||
onConflict(err)
|
||||
default:
|
||||
onPersistFailed(err)
|
||||
return err
|
||||
}
|
||||
if rerr := resyncFunc(); rerr != nil {
|
||||
onResyncFailed(rerr)
|
||||
return rerr
|
||||
}
|
||||
timer := time.NewTimer(bo.NextBackOff())
|
||||
select {
|
||||
case <-timer.C:
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// DecideNotFoundReset reports whether a NotFound download result should be treated as a
|
||||
// legitimately empty resource (reset) rather than a lost update (error). A resync with a
|
||||
// prior etag never resets silently; otherwise the backend's trash state decides, failing
|
||||
// open (reset=true) when the backend can't tell (e.g. Disk). trashed is only meaningful
|
||||
// when reset is false, to pick the right log reason.
|
||||
func DecideNotFoundReset(ctx context.Context, storage metadata.Storage, path string, resetOnNotFound, hadPriorEtag bool, log zerolog.Logger) (reset, trashed bool) {
|
||||
if !resetOnNotFound && hadPriorEtag {
|
||||
return false, false
|
||||
}
|
||||
trashed, terr := storage.WasRecentlyDeleted(ctx, path)
|
||||
if terr != nil {
|
||||
log.Warn().Err(terr).Msg("could not check trash state, assuming not deleted")
|
||||
return true, false
|
||||
}
|
||||
return !trashed, trashed
|
||||
}
|
||||
Generated
Vendored
+68
-53
@@ -29,10 +29,12 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
backoff "github.com/cenkalti/backoff/v5"
|
||||
collaboration "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3/cas"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/mtimesyncedcache"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/metadata"
|
||||
"go.opentelemetry.io/otel"
|
||||
@@ -166,7 +168,7 @@ func (c *Cache) Add(ctx context.Context, storageID, spaceID, shareID string, sha
|
||||
|
||||
var err error
|
||||
if !c.isSpaceCached(storageID, spaceID) {
|
||||
err = c.syncWithLock(ctx, storageID, spaceID)
|
||||
err = c.syncWithRetry(ctx, storageID, spaceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -189,38 +191,22 @@ func (c *Cache) Add(ctx context.Context, storageID, spaceID, shareID string, sha
|
||||
return c.Persist(ctx, storageID, spaceID)
|
||||
}
|
||||
|
||||
for retries := 100; retries > 0; retries-- {
|
||||
err = persistFunc()
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
span.SetStatus(codes.Ok, "")
|
||||
return nil
|
||||
case errtypes.Aborted:
|
||||
log.Debug().Msg("aborted when persisting added provider share: etag changed. retrying...")
|
||||
// this is the expected status code from the server when the if-match etag check fails
|
||||
// continue with sync below
|
||||
case errtypes.PreconditionFailed:
|
||||
log.Debug().Msg("precondition failed when persisting added provider share: etag changed. retrying...")
|
||||
// actually, this is the wrong status code and we treat it like errtypes.Aborted because of inconsistencies on the server side
|
||||
// continue with sync below
|
||||
case errtypes.AlreadyExists:
|
||||
log.Debug().Msg("already exists when persisting added provider share. retrying...")
|
||||
// CS3 uses an already exists error instead of precondition failed when using an If-None-Match=* header / IfExists flag in the InitiateFileUpload call.
|
||||
// Thas happens when the cache thinks there is no file.
|
||||
// continue with sync below
|
||||
default:
|
||||
err = cas.RetryPersist(ctx, 100, persistFunc,
|
||||
func() error { return c.resyncAfterConflict(ctx, storageID, spaceID) },
|
||||
func(err error) { log.Debug().Err(err).Msg("CAS conflict persisting added provider share, retrying...") },
|
||||
func(err error) {
|
||||
span.SetStatus(codes.Error, fmt.Sprintf("persisting added provider share failed. giving up: %s", err.Error()))
|
||||
log.Error().Err(err).Msg("persisting added provider share failed")
|
||||
return err
|
||||
}
|
||||
if err := c.syncWithLock(ctx, storageID, spaceID); err != nil {
|
||||
},
|
||||
func(err error) {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
log.Error().Err(err).Msg("persisting added provider share failed. giving up.")
|
||||
return err
|
||||
}
|
||||
},
|
||||
)
|
||||
if err == nil {
|
||||
span.SetStatus(codes.Ok, "")
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -235,7 +221,7 @@ func (c *Cache) Remove(ctx context.Context, storageID, spaceID, shareID string)
|
||||
span.AddEvent("got lock")
|
||||
|
||||
if !c.isSpaceCached(storageID, spaceID) {
|
||||
err := c.syncWithLock(ctx, storageID, spaceID)
|
||||
err := c.syncWithRetry(ctx, storageID, spaceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -261,32 +247,21 @@ func (c *Cache) Remove(ctx context.Context, storageID, spaceID, shareID string)
|
||||
Str("spaceID", spaceID).
|
||||
Str("shareID", shareID).Logger()
|
||||
|
||||
var err error
|
||||
for retries := 100; retries > 0; retries-- {
|
||||
err = persistFunc()
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
span.SetStatus(codes.Ok, "")
|
||||
return nil
|
||||
case errtypes.Aborted:
|
||||
log.Debug().Msg("aborted when persisting removed provider share: etag changed. retrying...")
|
||||
// this is the expected status code from the server when the if-match etag check fails
|
||||
// continue with sync below
|
||||
case errtypes.PreconditionFailed:
|
||||
log.Debug().Msg("precondition failed when persisting removed provider share: etag changed. retrying...")
|
||||
// actually, this is the wrong status code and we treat it like errtypes.Aborted because of inconsistencies on the server side
|
||||
// continue with sync below
|
||||
default:
|
||||
err := cas.RetryPersist(ctx, 100, persistFunc,
|
||||
func() error { return c.resyncAfterConflict(ctx, storageID, spaceID) },
|
||||
func(err error) { log.Debug().Err(err).Msg("CAS conflict persisting removed provider share, retrying...") },
|
||||
func(err error) {
|
||||
span.SetStatus(codes.Error, fmt.Sprintf("persisting removed provider share failed. giving up: %s", err.Error()))
|
||||
log.Error().Err(err).Msg("persisting removed provider share failed")
|
||||
return err
|
||||
}
|
||||
if err := c.syncWithLock(ctx, storageID, spaceID); err != nil {
|
||||
},
|
||||
func(err error) {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
log.Error().Err(err).Msg("persisting removed provider share failed. giving up.")
|
||||
return err
|
||||
}
|
||||
},
|
||||
)
|
||||
if err == nil {
|
||||
span.SetStatus(codes.Ok, "")
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -303,7 +278,7 @@ func (c *Cache) Get(ctx context.Context, storageID, spaceID, shareID string, ski
|
||||
|
||||
if !skipSync {
|
||||
// sync cache, maybe our data is outdated
|
||||
err := c.syncWithLock(ctx, storageID, spaceID)
|
||||
err := c.syncWithRetry(ctx, storageID, spaceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -340,7 +315,8 @@ func (c *Cache) All(ctx context.Context) (*mtimesyncedcache.Map[string, *Spaces]
|
||||
|
||||
unlock := c.LockSpace(spaceID)
|
||||
span.AddEvent("got lock for space " + spaceID)
|
||||
if err := c.syncWithLock(ctx, storageID, spaceID); err != nil {
|
||||
if err := c.syncWithRetry(ctx, storageID, spaceID); err != nil {
|
||||
unlock()
|
||||
return nil, err
|
||||
}
|
||||
unlock()
|
||||
@@ -361,7 +337,7 @@ func (c *Cache) ListSpace(ctx context.Context, storageID, spaceID string) (*Shar
|
||||
span.AddEvent("got lock")
|
||||
|
||||
// sync cache, maybe our data is outdated
|
||||
err := c.syncWithLock(ctx, storageID, spaceID)
|
||||
err := c.syncWithRetry(ctx, storageID, spaceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -459,7 +435,7 @@ func (c *Cache) PurgeSpace(ctx context.Context, storageID, spaceID string) error
|
||||
span.AddEvent("got lock")
|
||||
|
||||
if !c.isSpaceCached(storageID, spaceID) {
|
||||
err := c.syncWithLock(ctx, storageID, spaceID)
|
||||
err := c.syncWithRetry(ctx, storageID, spaceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -478,7 +454,18 @@ func (c *Cache) PurgeSpace(ctx context.Context, storageID, spaceID string) error
|
||||
return c.Persist(ctx, storageID, spaceID)
|
||||
}
|
||||
|
||||
// syncWithLock treats NotFound as a legitimately empty space (cold-start only).
|
||||
func (c *Cache) syncWithLock(ctx context.Context, storageID, spaceID string) error {
|
||||
return c.doSync(ctx, storageID, spaceID, true)
|
||||
}
|
||||
|
||||
// Unlike syncWithLock, a NotFound here must not reset the cache -- a pending
|
||||
// mutation is about to overwrite it, dropping a sibling writer's data.
|
||||
func (c *Cache) resyncAfterConflict(ctx context.Context, storageID, spaceID string) error {
|
||||
return c.doSync(ctx, storageID, spaceID, false)
|
||||
}
|
||||
|
||||
func (c *Cache) doSync(ctx context.Context, storageID, spaceID string, resetOnNotFound bool) error {
|
||||
ctx, span := tracer.Start(ctx, "syncWithLock")
|
||||
defer span.End()
|
||||
|
||||
@@ -498,10 +485,22 @@ func (c *Cache) syncWithLock(ctx context.Context, storageID, spaceID string) err
|
||||
}
|
||||
|
||||
dlres, err := c.storage.Download(ctx, dlreq)
|
||||
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
span.AddEvent("updating local cache")
|
||||
case errtypes.NotFound:
|
||||
if reset, trashed := cas.DecideNotFoundReset(ctx, c.storage, dlreq.Path, resetOnNotFound, space.Etag != "", log); !reset {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
if trashed {
|
||||
log.Error().Err(err).Msg("lost update: backing file was recently trashed")
|
||||
} else {
|
||||
log.Error().Err(err).Msg("lost update: backing file disappeared mid-retry")
|
||||
}
|
||||
return err
|
||||
}
|
||||
spaces.Spaces.Store(spaceID, &Shares{Shares: map[string]*collaboration.Share{}})
|
||||
span.SetStatus(codes.Ok, "")
|
||||
return nil
|
||||
case errtypes.NotModified:
|
||||
@@ -529,6 +528,22 @@ func (c *Cache) syncWithLock(ctx context.Context, storageID, spaceID string) err
|
||||
return nil
|
||||
}
|
||||
|
||||
// syncWithRetry retries syncWithLock's cold-start read on transient errors, since callers have no other retry wrapper.
|
||||
func (c *Cache) syncWithRetry(ctx context.Context, storageID, spaceID string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err := backoff.Retry(ctx, func() (struct{}, error) {
|
||||
err := c.syncWithLock(ctx, storageID, spaceID)
|
||||
if err != nil && !cas.IsSyncTransient(err) {
|
||||
return struct{}{}, backoff.Permanent(err)
|
||||
}
|
||||
return struct{}{}, err
|
||||
}, backoff.WithBackOff(cas.NewBackoff()), backoff.WithMaxTries(20))
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Cache) initializeIfNeeded(storageID, spaceID string) {
|
||||
spaces, _ := c.Providers.LoadOrStore(storageID, &Spaces{
|
||||
Spaces: mtimesyncedcache.Map[string, *Shares]{},
|
||||
|
||||
Generated
Vendored
+151
-94
@@ -28,10 +28,12 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
backoff "github.com/cenkalti/backoff/v5"
|
||||
collaboration "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3/cas"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/mtimesyncedcache"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/metadata"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
@@ -94,12 +96,12 @@ func (c *Cache) lockUser(userID string) func() {
|
||||
func (c *Cache) Add(ctx context.Context, userID, spaceID string, rs *collaboration.ReceivedShare) error {
|
||||
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Grab lock")
|
||||
unlock := c.lockUser(userID)
|
||||
span.End()
|
||||
span.SetAttributes(attribute.String("cs3.userid", userID))
|
||||
span.End()
|
||||
defer unlock()
|
||||
|
||||
if _, ok := c.ReceivedSpaces.Load(userID); !ok {
|
||||
err := c.syncWithLock(ctx, userID)
|
||||
err := c.syncWithRetry(ctx, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -109,7 +111,7 @@ func (c *Cache) Add(ctx context.Context, userID, spaceID string, rs *collaborati
|
||||
defer span.End()
|
||||
span.SetAttributes(attribute.String("cs3.userid", userID), attribute.String("cs3.spaceid", spaceID))
|
||||
|
||||
persistFunc := func() error {
|
||||
err := c.retryPersist(ctx, userID, spaceID, func() error {
|
||||
c.initializeIfNeeded(userID, spaceID)
|
||||
|
||||
rss, _ := c.ReceivedSpaces.Load(userID)
|
||||
@@ -124,44 +126,12 @@ func (c *Cache) Add(ctx context.Context, userID, spaceID string, rs *collaborati
|
||||
}
|
||||
|
||||
return c.persist(ctx, userID)
|
||||
}
|
||||
|
||||
log := appctx.GetLogger(ctx).With().
|
||||
Str("hostname", os.Getenv("HOSTNAME")).
|
||||
Str("userID", userID).
|
||||
Str("spaceID", spaceID).Logger()
|
||||
|
||||
var err error
|
||||
for retries := 100; retries > 0; retries-- {
|
||||
err = persistFunc()
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
span.SetStatus(codes.Ok, "")
|
||||
return nil
|
||||
case errtypes.Aborted:
|
||||
log.Debug().Msg("aborted when persisting added received share: etag changed. retrying...")
|
||||
// this is the expected status code from the server when the if-match etag check fails
|
||||
// continue with sync below
|
||||
case errtypes.PreconditionFailed:
|
||||
log.Debug().Msg("precondition failed when persisting added received share: etag changed. retrying...")
|
||||
// actually, this is the wrong status code and we treat it like errtypes.Aborted because of inconsistencies on the server side
|
||||
// continue with sync below
|
||||
case errtypes.AlreadyExists:
|
||||
log.Debug().Msg("already exists when persisting added received share. retrying...")
|
||||
// CS3 uses an already exists error instead of precondition failed when using an If-None-Match=* header / IfExists flag in the InitiateFileUpload call.
|
||||
// Thas happens when the cache thinks there is no file.
|
||||
// continue with sync below
|
||||
default:
|
||||
span.SetStatus(codes.Error, fmt.Sprintf("persisting added received share failed. giving up: %s", err.Error()))
|
||||
log.Error().Err(err).Msg("persisting added received share failed")
|
||||
return err
|
||||
}
|
||||
if err := c.syncWithLock(ctx, userID); err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
log.Error().Err(err).Msg("persisting added received share failed. giving up.")
|
||||
return err
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
} else {
|
||||
span.SetStatus(codes.Ok, "")
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -170,11 +140,11 @@ func (c *Cache) Add(ctx context.Context, userID, spaceID string, rs *collaborati
|
||||
func (c *Cache) Get(ctx context.Context, userID, spaceID, shareID string) (*State, error) {
|
||||
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Grab lock")
|
||||
unlock := c.lockUser(userID)
|
||||
span.End()
|
||||
span.SetAttributes(attribute.String("cs3.userid", userID))
|
||||
span.End()
|
||||
defer unlock()
|
||||
|
||||
err := c.syncWithLock(ctx, userID)
|
||||
err := c.syncWithRetry(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -189,15 +159,15 @@ func (c *Cache) Get(ctx context.Context, userID, spaceID, shareID string) (*Stat
|
||||
func (c *Cache) Remove(ctx context.Context, userID, spaceID, shareID string) error {
|
||||
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Grab lock")
|
||||
unlock := c.lockUser(userID)
|
||||
span.End()
|
||||
span.SetAttributes(attribute.String("cs3.userid", userID))
|
||||
span.End()
|
||||
defer unlock()
|
||||
|
||||
ctx, span = appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Add")
|
||||
ctx, span = appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Remove")
|
||||
defer span.End()
|
||||
span.SetAttributes(attribute.String("cs3.userid", userID), attribute.String("cs3.spaceid", spaceID))
|
||||
|
||||
persistFunc := func() error {
|
||||
err := c.retryPersist(ctx, userID, spaceID, func() error {
|
||||
c.initializeIfNeeded(userID, spaceID)
|
||||
|
||||
rss, _ := c.ReceivedSpaces.Load(userID)
|
||||
@@ -211,44 +181,12 @@ func (c *Cache) Remove(ctx context.Context, userID, spaceID, shareID string) err
|
||||
}
|
||||
|
||||
return c.persist(ctx, userID)
|
||||
}
|
||||
|
||||
log := appctx.GetLogger(ctx).With().
|
||||
Str("hostname", os.Getenv("HOSTNAME")).
|
||||
Str("userID", userID).
|
||||
Str("spaceID", spaceID).Logger()
|
||||
|
||||
var err error
|
||||
for retries := 100; retries > 0; retries-- {
|
||||
err = persistFunc()
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
span.SetStatus(codes.Ok, "")
|
||||
return nil
|
||||
case errtypes.Aborted:
|
||||
log.Debug().Msg("aborted when persisting added received share: etag changed. retrying...")
|
||||
// this is the expected status code from the server when the if-match etag check fails
|
||||
// continue with sync below
|
||||
case errtypes.PreconditionFailed:
|
||||
log.Debug().Msg("precondition failed when persisting added received share: etag changed. retrying...")
|
||||
// actually, this is the wrong status code and we treat it like errtypes.Aborted because of inconsistencies on the server side
|
||||
// continue with sync below
|
||||
case errtypes.AlreadyExists:
|
||||
log.Debug().Msg("already exists when persisting added received share. retrying...")
|
||||
// CS3 uses an already exists error instead of precondition failed when using an If-None-Match=* header / IfExists flag in the InitiateFileUpload call.
|
||||
// Thas happens when the cache thinks there is no file.
|
||||
// continue with sync below
|
||||
default:
|
||||
span.SetStatus(codes.Error, fmt.Sprintf("persisting added received share failed. giving up: %s", err.Error()))
|
||||
log.Error().Err(err).Msg("persisting added received share failed")
|
||||
return err
|
||||
}
|
||||
if err := c.syncWithLock(ctx, userID); err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
log.Error().Err(err).Msg("persisting added received share failed. giving up.")
|
||||
return err
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
} else {
|
||||
span.SetStatus(codes.Ok, "")
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -256,13 +194,14 @@ func (c *Cache) Remove(ctx context.Context, userID, spaceID, shareID string) err
|
||||
// List returns a list of received shares for a given user
|
||||
// The return list is guaranteed to be thread-safe
|
||||
func (c *Cache) List(ctx context.Context, userID string) (map[string]*Space, error) {
|
||||
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Grab lock")
|
||||
unlock := c.lockUser(userID)
|
||||
span.End()
|
||||
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "List")
|
||||
defer span.End()
|
||||
span.SetAttributes(attribute.String("cs3.userid", userID))
|
||||
|
||||
unlock := c.lockUser(userID)
|
||||
defer unlock()
|
||||
|
||||
err := c.syncWithLock(ctx, userID)
|
||||
err := c.syncWithRetry(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -285,7 +224,110 @@ func (c *Cache) List(ctx context.Context, userID string) (map[string]*Space, err
|
||||
return spaces, nil
|
||||
}
|
||||
|
||||
func (c *Cache) syncWithLock(ctx context.Context, userID string) error {
|
||||
func (c *Cache) retryPersist(ctx context.Context, userID, spaceID string, persistFunc func() error) error {
|
||||
log := appctx.GetLogger(ctx).With().
|
||||
Str("hostname", os.Getenv("HOSTNAME")).
|
||||
Str("userID", userID).
|
||||
Str("spaceID", spaceID).Logger()
|
||||
|
||||
bo := cas.NewBackoff()
|
||||
|
||||
const maxPersistAttempts = 20
|
||||
// independent budget, not derived from maxPersistAttempts: a flaky resync must not starve the persist budget.
|
||||
const maxResyncAttemptsPerFailure = 20
|
||||
|
||||
var err error
|
||||
needsResync := false
|
||||
persistAttempts := 0
|
||||
resyncAttempts := 0
|
||||
for persistAttempts < maxPersistAttempts {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
|
||||
if needsResync {
|
||||
// a previous persist attempt failed and the re-read to pick up fresh state
|
||||
// was itself transient; keep retrying the re-read instead of hammering
|
||||
// persistFunc again with the same stale in-memory rss/etag
|
||||
serr := c.resyncAfterConflict(ctx, userID)
|
||||
if serr == nil {
|
||||
needsResync = false
|
||||
resyncAttempts = 0
|
||||
continue // fresh state is in memory; retry persistFunc next attempt, no need to wait
|
||||
}
|
||||
// keep err at its last real (persist or resync) failure; never let a
|
||||
// budget-exhausting resync success clobber it into a false nil return
|
||||
err = serr
|
||||
if !cas.IsSyncTransient(serr) {
|
||||
log.Error().Err(serr).Msg("lost update: re-read failed, aborting")
|
||||
return serr
|
||||
}
|
||||
resyncAttempts++
|
||||
if resyncAttempts >= maxResyncAttemptsPerFailure {
|
||||
log.Error().Err(serr).Msg("lost update: resync would not stabilize, giving up")
|
||||
return serr
|
||||
}
|
||||
log.Warn().Err(serr).Msg("lost update: re-read before retry")
|
||||
} else {
|
||||
persistAttempts++
|
||||
err = persistFunc()
|
||||
switch {
|
||||
case err == nil:
|
||||
return nil
|
||||
case cas.IsTransientGRPCStatus(err):
|
||||
log.Debug().Err(err).Msg("persist failed: transient gRPC error, retrying")
|
||||
case cas.IsConflict(err):
|
||||
log.Debug().Err(err).Msg("CAS conflict persisting received share, retrying")
|
||||
default:
|
||||
log.Error().Err(err).Msg("persisting received share failed, giving up")
|
||||
return err
|
||||
}
|
||||
needsResync = true
|
||||
}
|
||||
|
||||
timer := time.NewTimer(bo.NextBackOff())
|
||||
select {
|
||||
case <-timer.C:
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// syncWithRetry retries sync's cold-start read on transient errors, since
|
||||
// Add/Get/List call it directly with no other retry wrapper around it.
|
||||
func (c *Cache) syncWithRetry(ctx context.Context, userID string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err := backoff.Retry(ctx, func() (struct{}, error) {
|
||||
err := c.sync(ctx, userID)
|
||||
if err != nil && !cas.IsSyncTransient(err) {
|
||||
return struct{}{}, backoff.Permanent(err)
|
||||
}
|
||||
return struct{}{}, err
|
||||
}, backoff.WithBackOff(cas.NewBackoff()), backoff.WithMaxTries(20))
|
||||
return err
|
||||
}
|
||||
|
||||
// sync pulls the authoritative state from storage; caller must hold the user
|
||||
// lock. Treats NotFound as a legitimately empty user (cold-start only).
|
||||
func (c *Cache) sync(ctx context.Context, userID string) error {
|
||||
return c.doSync(ctx, userID, true)
|
||||
}
|
||||
|
||||
// Unlike sync, a NotFound here must not reset the cache -- a pending mutation
|
||||
// is about to overwrite it, dropping a sibling writer's data.
|
||||
func (c *Cache) resyncAfterConflict(ctx context.Context, userID string) error {
|
||||
return c.doSync(ctx, userID, false)
|
||||
}
|
||||
|
||||
func (c *Cache) doSync(ctx context.Context, userID string, resetOnNotFound bool) error {
|
||||
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Sync")
|
||||
defer span.End()
|
||||
span.SetAttributes(attribute.String("cs3.userid", userID))
|
||||
@@ -298,22 +340,38 @@ func (c *Cache) syncWithLock(ctx context.Context, userID string) error {
|
||||
span.AddEvent("updating cache")
|
||||
// - update cached list of created shares for the user in memory if changed
|
||||
rss, _ := c.ReceivedSpaces.Load(userID)
|
||||
dlres, err := c.storage.Download(ctx, metadata.DownloadRequest{
|
||||
dlreq := metadata.DownloadRequest{
|
||||
Path: jsonPath,
|
||||
IfNoneMatch: []string{rss.etag},
|
||||
})
|
||||
}
|
||||
dlres, err := c.storage.Download(ctx, dlreq)
|
||||
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
span.AddEvent("updating local cache")
|
||||
case errtypes.NotFound:
|
||||
if reset, trashed := cas.DecideNotFoundReset(ctx, c.storage, jsonPath, resetOnNotFound, rss.etag != "", log); !reset {
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
if trashed {
|
||||
log.Error().Err(err).Msg("lost update: backing file was recently trashed")
|
||||
} else {
|
||||
log.Error().Err(err).Msg("lost update: backing file disappeared mid-retry")
|
||||
}
|
||||
return err
|
||||
}
|
||||
c.ReceivedSpaces.Store(userID, &Spaces{Spaces: map[string]*Space{}})
|
||||
span.SetStatus(codes.Ok, "")
|
||||
return nil
|
||||
case errtypes.NotModified:
|
||||
span.SetStatus(codes.Ok, "")
|
||||
return nil
|
||||
default:
|
||||
span.SetStatus(codes.Error, fmt.Sprintf("Failed to download the received share: %s", err.Error()))
|
||||
log.Error().Err(err).Msg("Failed to download the received share")
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
if cas.IsSyncTransient(err) {
|
||||
log.Warn().Err(err).Msg("lost update: re-read transient error")
|
||||
} else {
|
||||
log.Error().Err(err).Msg("lost update: re-read failed")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -374,7 +432,6 @@ func (c *Cache) persist(ctx context.Context, userID string) error {
|
||||
return err
|
||||
}
|
||||
rss.etag = res.Etag
|
||||
|
||||
span.SetStatus(codes.Ok, "")
|
||||
return nil
|
||||
}
|
||||
|
||||
Generated
Vendored
+66
-57
@@ -28,12 +28,14 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
backoff "github.com/cenkalti/backoff/v5"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"golang.org/x/exp/maps"
|
||||
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3/cas"
|
||||
"github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3/shareid"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/mtimesyncedcache"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/metadata"
|
||||
@@ -97,7 +99,7 @@ func (c *Cache) Add(ctx context.Context, userid, shareID string) error {
|
||||
defer unlock()
|
||||
|
||||
if _, ok := c.UserShares.Load(userid); !ok {
|
||||
err := c.syncWithLock(ctx, userid)
|
||||
err := c.syncWithRetry(ctx, userid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -124,37 +126,21 @@ func (c *Cache) Add(ctx context.Context, userid, shareID string) error {
|
||||
Str("userID", userid).
|
||||
Str("shareID", shareID).Logger()
|
||||
|
||||
var err error
|
||||
for retries := 100; retries > 0; retries-- {
|
||||
err = persistFunc()
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
span.SetStatus(codes.Ok, "")
|
||||
return nil
|
||||
case errtypes.Aborted:
|
||||
log.Debug().Msg("aborted when persisting added share: etag changed. retrying...")
|
||||
// this is the expected status code from the server when the if-match etag check fails
|
||||
// continue with sync below
|
||||
case errtypes.PreconditionFailed:
|
||||
log.Debug().Msg("precondition failed when persisting added share: etag changed. retrying...")
|
||||
// actually, this is the wrong status code and we treat it like errtypes.Aborted because of inconsistencies on the server side
|
||||
// continue with sync below
|
||||
case errtypes.AlreadyExists:
|
||||
log.Debug().Msg("already exists when persisting added share. retrying...")
|
||||
// CS3 uses an already exists error instead of precondition failed when using an If-None-Match=* header / IfExists flag in the InitiateFileUpload call.
|
||||
// Thas happens when the cache thinks there is no file.
|
||||
// continue with sync below
|
||||
default:
|
||||
err := cas.RetryPersist(ctx, 100, persistFunc,
|
||||
func() error { return c.resyncAfterConflict(ctx, userid) },
|
||||
func(err error) { log.Debug().Err(err).Msg("CAS conflict persisting added share, retrying...") },
|
||||
func(err error) {
|
||||
span.SetStatus(codes.Error, fmt.Sprintf("persisting added share failed. giving up: %s", err.Error()))
|
||||
log.Error().Err(err).Msg("persisting added share failed")
|
||||
return err
|
||||
}
|
||||
if err := c.syncWithLock(ctx, userid); err != nil {
|
||||
},
|
||||
func(err error) {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
log.Error().Err(err).Msg("persisting added share failed. giving up.")
|
||||
return err
|
||||
}
|
||||
},
|
||||
)
|
||||
if err == nil {
|
||||
span.SetStatus(codes.Ok, "")
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -167,8 +153,8 @@ func (c *Cache) Remove(ctx context.Context, userid, shareID string) error {
|
||||
span.SetAttributes(attribute.String("cs3.userid", userid))
|
||||
defer unlock()
|
||||
|
||||
if _, ok := c.UserShares.Load(userid); ok {
|
||||
err := c.syncWithLock(ctx, userid)
|
||||
if _, ok := c.UserShares.Load(userid); !ok {
|
||||
err := c.syncWithRetry(ctx, userid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -199,38 +185,21 @@ func (c *Cache) Remove(ctx context.Context, userid, shareID string) error {
|
||||
Str("userID", userid).
|
||||
Str("shareID", shareID).Logger()
|
||||
|
||||
var err error
|
||||
for retries := 100; retries > 0; retries-- {
|
||||
err = persistFunc()
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
span.SetStatus(codes.Ok, "")
|
||||
return nil
|
||||
case errtypes.Aborted:
|
||||
log.Debug().Msg("aborted when persisting removed share: etag changed. retrying...")
|
||||
// this is the expected status code from the server when the if-match etag check fails
|
||||
// continue with sync below
|
||||
case errtypes.PreconditionFailed:
|
||||
log.Debug().Msg("precondition failed when persisting removed share: etag changed. retrying...")
|
||||
// actually, this is the wrong status code and we treat it like errtypes.Aborted because of inconsistencies on the server side
|
||||
// continue with sync below
|
||||
case errtypes.AlreadyExists:
|
||||
log.Debug().Msg("file already existed when persisting removed share. retrying...")
|
||||
// CS3 uses an already exists error instead of precondition failed when using an If-None-Match=* header / IfExists flag in the InitiateFileUpload call.
|
||||
// Thas happens when the cache thinks there is no file.
|
||||
// continue with sync below
|
||||
default:
|
||||
err := cas.RetryPersist(ctx, 100, persistFunc,
|
||||
func() error { return c.resyncAfterConflict(ctx, userid) },
|
||||
func(err error) { log.Debug().Err(err).Msg("CAS conflict persisting removed share, retrying...") },
|
||||
func(err error) {
|
||||
span.SetStatus(codes.Error, fmt.Sprintf("persisting removed share failed. giving up: %s", err.Error()))
|
||||
log.Error().Err(err).Msg("persisting removed share failed")
|
||||
return err
|
||||
}
|
||||
if err := c.syncWithLock(ctx, userid); err != nil {
|
||||
},
|
||||
func(err error) {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
return err
|
||||
}
|
||||
},
|
||||
)
|
||||
if err == nil {
|
||||
span.SetStatus(codes.Ok, "")
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -241,7 +210,7 @@ func (c *Cache) List(ctx context.Context, userid string) (map[string]SpaceShareI
|
||||
span.End()
|
||||
span.SetAttributes(attribute.String("cs3.userid", userid))
|
||||
defer unlock()
|
||||
if err := c.syncWithLock(ctx, userid); err != nil {
|
||||
if err := c.syncWithRetry(ctx, userid); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -259,7 +228,18 @@ func (c *Cache) List(ctx context.Context, userid string) (map[string]SpaceShareI
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// syncWithLock treats NotFound as a legitimately empty cache (cold-start only).
|
||||
func (c *Cache) syncWithLock(ctx context.Context, userID string) error {
|
||||
return c.doSync(ctx, userID, true)
|
||||
}
|
||||
|
||||
// Unlike syncWithLock, a NotFound here must not reset the cache -- a pending
|
||||
// mutation is about to overwrite it, dropping a sibling writer's data.
|
||||
func (c *Cache) resyncAfterConflict(ctx context.Context, userID string) error {
|
||||
return c.doSync(ctx, userID, false)
|
||||
}
|
||||
|
||||
func (c *Cache) doSync(ctx context.Context, userID string, resetOnNotFound bool) error {
|
||||
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Sync")
|
||||
defer span.End()
|
||||
span.SetAttributes(attribute.String("cs3.userid", userID))
|
||||
@@ -274,15 +254,28 @@ func (c *Cache) syncWithLock(ctx context.Context, userID string) error {
|
||||
dlreq := metadata.DownloadRequest{
|
||||
Path: userCreatedPath,
|
||||
}
|
||||
var hadEtag bool
|
||||
if us, ok := c.UserShares.Load(userID); ok && us.Etag != "" {
|
||||
hadEtag = true
|
||||
dlreq.IfNoneMatch = []string{us.Etag}
|
||||
}
|
||||
|
||||
dlres, err := c.storage.Download(ctx, dlreq)
|
||||
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
span.AddEvent("updating local cache")
|
||||
case errtypes.NotFound:
|
||||
if reset, trashed := cas.DecideNotFoundReset(ctx, c.storage, userCreatedPath, resetOnNotFound, hadEtag, log); !reset {
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
if trashed {
|
||||
log.Error().Err(err).Msg("lost update: backing file was recently trashed")
|
||||
} else {
|
||||
log.Error().Err(err).Msg("lost update: backing file disappeared mid-retry")
|
||||
}
|
||||
return err
|
||||
}
|
||||
c.UserShares.Store(userID, &UserShareCache{UserShares: map[string]*SpaceShareIDs{}})
|
||||
span.SetStatus(codes.Ok, "")
|
||||
return nil
|
||||
case errtypes.NotModified:
|
||||
@@ -355,6 +348,22 @@ func (c *Cache) Persist(ctx context.Context, userid string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// syncWithRetry retries syncWithLock's cold-start read on transient errors, since callers have no other retry wrapper.
|
||||
func (c *Cache) syncWithRetry(ctx context.Context, userID string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err := backoff.Retry(ctx, func() (struct{}, error) {
|
||||
err := c.syncWithLock(ctx, userID)
|
||||
if err != nil && !cas.IsSyncTransient(err) {
|
||||
return struct{}{}, backoff.Permanent(err)
|
||||
}
|
||||
return struct{}{}, err
|
||||
}, backoff.WithBackOff(cas.NewBackoff()), backoff.WithMaxTries(20))
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Cache) userCreatedPath(userid string) string {
|
||||
return filepath.Join("/", c.namespace, userid, c.filename)
|
||||
}
|
||||
|
||||
+4
@@ -26,6 +26,7 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/lookup"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/node"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
@@ -112,6 +113,9 @@ func (bs *Blobstore) Download(node *node.Node) (io.ReadCloser, error) {
|
||||
dest := bs.Path(node)
|
||||
file, err := os.Open(dest)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, errtypes.NotFound(dest)
|
||||
}
|
||||
return nil, errors.Wrapf(err, "could not read blob '%s'", dest)
|
||||
}
|
||||
return file, nil
|
||||
|
||||
Generated
Vendored
+6
@@ -1128,8 +1128,14 @@ func (fs *Decomposedfs) Download(ctx context.Context, ref *provider.Reference, o
|
||||
}
|
||||
var reader io.ReadCloser
|
||||
if openReaderFunc(ri) {
|
||||
if n.IsProcessing(ctx) {
|
||||
return nil, nil, errtypes.TooEarly(n.ID)
|
||||
}
|
||||
reader, err = fs.tp.ReadBlob(n)
|
||||
if err != nil {
|
||||
if _, ok := err.(errtypes.IsNotFound); ok {
|
||||
return nil, nil, err
|
||||
}
|
||||
return nil, nil, errors.Wrap(err, "Decomposedfs: error download blob '"+n.ID+"'")
|
||||
}
|
||||
}
|
||||
|
||||
+3
@@ -182,6 +182,9 @@ func (fs *Decomposedfs) DownloadRevision(ctx context.Context, ref *provider.Refe
|
||||
if openReaderFunc(ri) {
|
||||
reader, err = fs.tp.ReadBlob(&revisionNode)
|
||||
if err != nil {
|
||||
if _, ok := err.(errtypes.IsNotFound); ok {
|
||||
return nil, nil, err
|
||||
}
|
||||
return nil, nil, errors.Wrapf(err, "Decomposedfs: could not download blob of revision '%s' for node '%s'", n.ID, revisionKey)
|
||||
}
|
||||
}
|
||||
|
||||
+9
@@ -704,10 +704,19 @@ func (t *Tree) InitNewNode(ctx context.Context, n *node.Node, fsize uint64) (met
|
||||
h, err := os.OpenFile(n.InternalPath(), os.O_CREATE|os.O_EXCL, 0600)
|
||||
subspan.End()
|
||||
if err != nil {
|
||||
if errors.Is(err, fs.ErrExist) {
|
||||
return unlock, errtypes.AlreadyExists(n.Name)
|
||||
}
|
||||
return unlock, err
|
||||
}
|
||||
h.Close()
|
||||
|
||||
// Mark processing immediately so a reader never sees "not processing";
|
||||
// overwritten later with the full status. acquireLock=false: lock already held.
|
||||
if err := n.SetXattrsWithContext(ctx, map[string][]byte{prefixes.StatusPrefix: []byte(node.ProcessingStatus)}, false); err != nil {
|
||||
return unlock, err
|
||||
}
|
||||
|
||||
_, subspan = tracer.Start(ctx, "node.CheckQuota")
|
||||
_, err = node.CheckQuota(ctx, n.SpaceRoot, false, 0, fsize)
|
||||
subspan.End()
|
||||
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package metadata
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// barrierTimeout bounds how long an arrived Upload call waits for the
|
||||
// remaining callers before giving up, so a caller that never arrives (e.g.
|
||||
// because its own cold-start sync errored before reaching Upload) can't
|
||||
// hang the others for the full test-binary timeout.
|
||||
const barrierTimeout = 2 * time.Second
|
||||
|
||||
// BarrierStorage wraps a Storage and holds Upload calls until n goroutines have
|
||||
// arrived, then releases them all at once, to deterministically reproduce
|
||||
// concurrent-write races in tests.
|
||||
type BarrierStorage struct {
|
||||
Storage
|
||||
arrived int32
|
||||
n int32
|
||||
ready chan struct{}
|
||||
closeOnce sync.Once
|
||||
}
|
||||
|
||||
// NewBarrierStorage returns a BarrierStorage wrapping s that releases once n Upload calls have arrived.
|
||||
func NewBarrierStorage(s Storage, n int) *BarrierStorage {
|
||||
return &BarrierStorage{Storage: s, n: int32(n), ready: make(chan struct{})}
|
||||
}
|
||||
|
||||
// Upload blocks until n calls have arrived, then delegates to the wrapped Storage.
|
||||
func (b *BarrierStorage) Upload(ctx context.Context, req UploadRequest) (*UploadResponse, error) {
|
||||
if atomic.AddInt32(&b.arrived, 1) >= b.n {
|
||||
b.closeOnce.Do(func() { close(b.ready) })
|
||||
}
|
||||
select {
|
||||
case <-b.ready:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(barrierTimeout):
|
||||
return nil, fmt.Errorf("barrier: timed out after %s waiting for %d/%d callers to arrive", barrierTimeout, atomic.LoadInt32(&b.arrived), b.n)
|
||||
}
|
||||
return b.Storage.Upload(ctx, req)
|
||||
}
|
||||
|
||||
// SimpleUpload routes through Upload so it also counts toward and waits on
|
||||
// the barrier, instead of promoting straight to the embedded Storage.
|
||||
func (b *BarrierStorage) SimpleUpload(ctx context.Context, uploadpath string, content []byte) error {
|
||||
_, err := b.Upload(ctx, UploadRequest{
|
||||
Path: uploadpath,
|
||||
Content: content,
|
||||
})
|
||||
return err
|
||||
}
|
||||
+38
@@ -430,6 +430,44 @@ func (cs3 *CS3) Delete(ctx context.Context, path string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// WasRecentlyDeleted checks the recycle bin within a short window so a
|
||||
// long-settled deletion doesn't block a legitimate empty read.
|
||||
func (cs3 *CS3) WasRecentlyDeleted(ctx context.Context, path string) (bool, error) {
|
||||
ctx, span := tracer.Start(ctx, "WasRecentlyDeleted")
|
||||
defer span.End()
|
||||
|
||||
client, err := cs3.providerClient()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
ctx, err = cs3.getAuthContext(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
target := utils.MakeRelativePath(path)
|
||||
now := time.Now()
|
||||
res, err := client.ListRecycle(ctx, &provider.ListRecycleRequest{
|
||||
Ref: &provider.Reference{ResourceId: cs3.SpaceRoot},
|
||||
FromTs: utils.TimeToTS(now.Add(-5 * time.Minute)),
|
||||
ToTs: utils.TimeToTS(now),
|
||||
PageSize: 1000,
|
||||
})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if res.Status.Code != rpc.Code_CODE_OK {
|
||||
return false, errtypes.NewErrtypeFromStatus(res.Status)
|
||||
}
|
||||
|
||||
for _, item := range res.RecycleItems {
|
||||
if item.GetRef().GetPath() == target {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// ReadDir returns the entries in a given directory
|
||||
func (cs3 *CS3) ReadDir(ctx context.Context, path string) ([]string, error) {
|
||||
ctx, span := tracer.Start(ctx, "ReadDir")
|
||||
|
||||
+6
@@ -178,6 +178,12 @@ func (disk *Disk) Delete(_ context.Context, path string) error {
|
||||
return os.Remove(disk.targetPath(path))
|
||||
}
|
||||
|
||||
// WasRecentlyDeleted always reports false: Disk has no trash/recycle bin, so
|
||||
// a NotFound here stays ambiguous between "removed" and "never existed".
|
||||
func (disk *Disk) WasRecentlyDeleted(_ context.Context, _ string) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// ReadDir returns the resource infos in a given directory
|
||||
func (disk *Disk) ReadDir(_ context.Context, p string) ([]string, error) {
|
||||
infos, err := os.ReadDir(disk.targetPath(p))
|
||||
|
||||
+3
@@ -70,6 +70,9 @@ type Storage interface {
|
||||
SimpleDownload(ctx context.Context, path string) ([]byte, error)
|
||||
Delete(ctx context.Context, path string) error
|
||||
Stat(ctx context.Context, path string) (*provider.ResourceInfo, error)
|
||||
// WasRecentlyDeleted reports whether path was removed vs. never existed.
|
||||
// Backends without trash support always report false (see OCISDEV-855).
|
||||
WasRecentlyDeleted(ctx context.Context, path string) (bool, error)
|
||||
|
||||
ReadDir(ctx context.Context, path string) ([]string, error)
|
||||
ListDir(ctx context.Context, path string) ([]*provider.ResourceInfo, error)
|
||||
|
||||
+79
-24
@@ -10,6 +10,9 @@ package http2
|
||||
// flow control window update.
|
||||
const inflowMinRefresh = 4 << 10
|
||||
|
||||
// maxFlowWindow is the maximum size of a flow control window.
|
||||
const maxFlowWindow = (1 << 31) - 1
|
||||
|
||||
// inflow accounts for an inbound flow control window.
|
||||
// It tracks both the latest window sent to the peer (used for enforcement)
|
||||
// and the accumulated unsent window.
|
||||
@@ -74,47 +77,99 @@ func takeInflows(f1, f2 *inflow, n uint32) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// outflow is the outbound flow control window's size.
|
||||
// connOutflow is connection-level outbound flow control.
|
||||
type connOutflow struct {
|
||||
initial int32 // SETTINGS_INITIAL_WINDOW_SIZE, changes with settings updates
|
||||
n int32 // connection-level flow control window
|
||||
flowErr bool // set when a flow control error is encountered
|
||||
}
|
||||
|
||||
func (f *connOutflow) init() {
|
||||
f.initial = initialWindowSize // initial stream window size
|
||||
f.n = initialWindowSize // current connection window size
|
||||
}
|
||||
|
||||
func (f *connOutflow) changeInitialWindowSize(size int64) bool {
|
||||
if size > maxFlowWindow {
|
||||
f.flowErr = true
|
||||
return false
|
||||
}
|
||||
f.initial = int32(size)
|
||||
return true
|
||||
}
|
||||
|
||||
func (f *connOutflow) add(n int32) bool {
|
||||
sum := int64(f.n) + int64(n)
|
||||
if sum > maxFlowWindow {
|
||||
f.flowErr = true
|
||||
return false
|
||||
}
|
||||
f.n += n
|
||||
return true
|
||||
}
|
||||
|
||||
// outflow is the stream-level outbound flow control window's size.
|
||||
type outflow struct {
|
||||
_ incomparable
|
||||
|
||||
// n is the number of DATA bytes we're allowed to send.
|
||||
// An outflow is kept both on a conn and a per-stream.
|
||||
n int32
|
||||
// delta is the difference between the stream's flow control window and
|
||||
// the connection's initial window size (conn.initial).
|
||||
//
|
||||
// Another view is that delta is the number of flow control bytes provided to this
|
||||
// stream in WINDOW_UPDATE frames, less the number of bytes sent on the stream.
|
||||
delta int32
|
||||
|
||||
// conn points to the shared connection-level outflow that is
|
||||
// shared by all streams on that conn. It is nil for the outflow
|
||||
// that's on the conn directly.
|
||||
conn *outflow
|
||||
// shared by all streams on that conn.
|
||||
conn *connOutflow
|
||||
}
|
||||
|
||||
func (f *outflow) setConnFlow(cf *outflow) { f.conn = cf }
|
||||
|
||||
func (f *outflow) available() int32 {
|
||||
n := f.n
|
||||
if f.conn != nil && f.conn.n < n {
|
||||
n = f.conn.n
|
||||
func (f *outflow) available() (int32, bool) {
|
||||
if f.conn == nil {
|
||||
return maxFlowWindow, true // only happens in tests
|
||||
}
|
||||
return n
|
||||
if f.conn.flowErr {
|
||||
// Block all sending once any stream observes a flow control error.
|
||||
return 0, false
|
||||
}
|
||||
n := int64(f.conn.initial) + int64(f.delta)
|
||||
if n > maxFlowWindow {
|
||||
f.conn.flowErr = true
|
||||
return 0, false
|
||||
}
|
||||
return min(int32(n), f.conn.n), true
|
||||
}
|
||||
|
||||
func (f *outflow) take(n int32) {
|
||||
if n > f.available() {
|
||||
if f.conn == nil {
|
||||
return // only happens in tests
|
||||
}
|
||||
avail, _ := f.available()
|
||||
if n > avail {
|
||||
panic("internal error: took too much")
|
||||
}
|
||||
f.n -= n
|
||||
if f.conn != nil {
|
||||
f.conn.n -= n
|
||||
}
|
||||
f.delta -= n
|
||||
f.conn.n -= n
|
||||
}
|
||||
|
||||
// add adds n bytes (positive or negative) to the flow control window.
|
||||
// It returns false if the sum would exceed 2^31-1.
|
||||
func (f *outflow) add(n int32) bool {
|
||||
sum := f.n + n
|
||||
if (sum > n) == (f.n > 0) {
|
||||
f.n = sum
|
||||
return true
|
||||
if f.conn == nil {
|
||||
return true // only happens in tests
|
||||
}
|
||||
return false
|
||||
avail := int64(f.conn.initial) + int64(f.delta)
|
||||
if avail > maxFlowWindow {
|
||||
// An earlier change to the initial window pushed this stream over the limit.
|
||||
// This is a connection-level flow control error.
|
||||
f.conn.flowErr = true
|
||||
return false
|
||||
}
|
||||
if avail+int64(n) > maxFlowWindow {
|
||||
// This update would push the stream over the limit.
|
||||
// This is a stream-level flow control error.
|
||||
return false
|
||||
}
|
||||
f.delta += n
|
||||
return true
|
||||
}
|
||||
+25
-9
@@ -1711,7 +1711,8 @@ func (fr *Framer) readMetaFrame(hf *HeadersFrame) (Frame, error) {
|
||||
mh := &MetaHeadersFrame{
|
||||
HeadersFrame: hf,
|
||||
}
|
||||
var remainSize = fr.maxHeaderListSize()
|
||||
var headersRemainSize = fr.maxHeaderListSize()
|
||||
var trailersRemainSize = fr.maxHeaderListSize()
|
||||
var sawRegular bool
|
||||
|
||||
var invalid error // pseudo header field errors
|
||||
@@ -1743,14 +1744,29 @@ func (fr *Framer) readMetaFrame(hf *HeadersFrame) (Frame, error) {
|
||||
return
|
||||
}
|
||||
|
||||
size := hf.Size()
|
||||
if size > remainSize {
|
||||
var remainSize *uint32
|
||||
var size uint32
|
||||
if hf.Name == "trailer" {
|
||||
remainSize = &trailersRemainSize
|
||||
fieldCount := strings.Count(hf.Value, ",") + 1
|
||||
// Rather than actually constructing hpack.HeaderField for each
|
||||
// trailer field and cumulatively adding its Size, just do the math
|
||||
// manually to avoid unnecessary work. This does make it so
|
||||
// whitespaces after comma are counted against the budget, but that
|
||||
// should be innocuous.
|
||||
size = uint32(len(hf.Value)-fieldCount+1) + uint32(fieldCount)*hpack.HeaderField{}.Size()
|
||||
} else {
|
||||
remainSize = &headersRemainSize
|
||||
size = hf.Size()
|
||||
}
|
||||
if size > *remainSize {
|
||||
hdec.SetEmitEnabled(false)
|
||||
mh.Truncated = true
|
||||
remainSize = 0
|
||||
headersRemainSize = 0
|
||||
trailersRemainSize = 0
|
||||
return
|
||||
}
|
||||
remainSize -= size
|
||||
*remainSize -= size
|
||||
|
||||
mh.Fields = append(mh.Fields, hf)
|
||||
})
|
||||
@@ -1766,10 +1782,10 @@ func (fr *Framer) readMetaFrame(hf *HeadersFrame) (Frame, error) {
|
||||
// skip parsing the fragment and close the connection.
|
||||
//
|
||||
// "Too much" is either any CONTINUATION frame after we've already
|
||||
// exceeded the max header list size (in which case remainSize is 0),
|
||||
// or a frame whose encoded size is more than twice the remaining
|
||||
// header list bytes we're willing to accept.
|
||||
if int64(len(frag)) > int64(2*remainSize) {
|
||||
// exceeded the max header list size (if so, both budgets are 0), or a
|
||||
// frame whose encoded size is more than twice the remaining header
|
||||
// list bytes we're willing to accept.
|
||||
if int64(len(frag)) > 2*int64(headersRemainSize+trailersRemainSize) {
|
||||
if VerboseLogs {
|
||||
log.Printf("http2: header list too large")
|
||||
}
|
||||
|
||||
+66
-44
@@ -280,7 +280,6 @@ func (s *Server) serveConn(c net.Conn, opts *ServeConnOpts, newf func(*serverCon
|
||||
doneServing: make(chan struct{}),
|
||||
clientMaxStreams: math.MaxUint32, // Section 6.5.2: "Initially, there is no limit to this value"
|
||||
advMaxStreams: conf.MaxConcurrentStreams,
|
||||
initialStreamSendWindowSize: initialWindowSize,
|
||||
initialStreamRecvWindowSize: conf.MaxUploadBufferPerStream,
|
||||
maxFrameSize: initialMaxFrameSize,
|
||||
pingTimeout: conf.PingTimeout,
|
||||
@@ -320,7 +319,7 @@ func (s *Server) serveConn(c net.Conn, opts *ServeConnOpts, newf func(*serverCon
|
||||
// These start at the RFC-specified defaults. If there is a higher
|
||||
// configured value for inflow, that will be updated when we send a
|
||||
// WINDOW_UPDATE shortly after sending SETTINGS.
|
||||
sc.flow.add(initialWindowSize)
|
||||
sc.flow.init()
|
||||
sc.inflow.init(initialWindowSize)
|
||||
sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf)
|
||||
sc.hpackEncoder.SetMaxDynamicTableSizeLimit(conf.MaxEncoderHeaderTableSize)
|
||||
@@ -427,7 +426,7 @@ type serverConn struct {
|
||||
wroteFrameCh chan frameWriteResult // from writeFrameAsync -> serve, tickles more frame writes
|
||||
bodyReadCh chan bodyReadMsg // from handlers -> serve
|
||||
serveMsgCh chan interface{} // misc messages & code to send to / run on the serve loop
|
||||
flow outflow // conn-wide (not stream-specific) outbound flow control
|
||||
flow connOutflow // conn-wide (not stream-specific) outbound flow control
|
||||
inflow inflow // conn-wide inbound flow control
|
||||
tlsState *tls.ConnectionState // shared by all handlers, like net/http
|
||||
remoteAddrStr string
|
||||
@@ -441,6 +440,9 @@ type serverConn struct {
|
||||
sawFirstSettings bool // got the initial SETTINGS frame after the preface
|
||||
needToSendSettingsAck bool
|
||||
unackedSettings int // how many SETTINGS have we sent without ACKs?
|
||||
pendingEncoderTableSize bool // peer changed SETTINGS_HEADER_TABLE_SIZE; apply to hpackEncoder before the next frame write
|
||||
encoderTableSizeMin uint32 // smallest SETTINGS_HEADER_TABLE_SIZE since the last apply
|
||||
encoderTableSize uint32 // latest SETTINGS_HEADER_TABLE_SIZE
|
||||
queuedControlFrames int // control frames in the writeSched queue
|
||||
clientMaxStreams uint32 // SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit)
|
||||
advMaxStreams uint32 // our SETTINGS_MAX_CONCURRENT_STREAMS advertised the client
|
||||
@@ -451,7 +453,6 @@ type serverConn struct {
|
||||
maxPushPromiseID uint32 // ID of the last push promise (even), or 0 if there have been no pushes
|
||||
streams map[uint32]*stream
|
||||
unstartedHandlers []unstartedHandler
|
||||
initialStreamSendWindowSize int32
|
||||
initialStreamRecvWindowSize int32
|
||||
maxFrameSize int32
|
||||
peerMaxHeaderListSize uint32 // zero means unknown (default)
|
||||
@@ -521,7 +522,8 @@ type stream struct {
|
||||
// immutable:
|
||||
sc *serverConn
|
||||
id uint32
|
||||
body *pipe // non-nil if expecting DATA frames
|
||||
body *pipe // non-nil if expecting DATA frames
|
||||
reqBody *requestBody
|
||||
cw closeWaiter // closed wait stream transitions to closed state
|
||||
ctx context.Context
|
||||
cancelCtx func()
|
||||
@@ -1172,6 +1174,16 @@ func (sc *serverConn) startFrameWrite(wr FrameWriteRequest) {
|
||||
|
||||
sc.writingFrame = true
|
||||
sc.needsFrameFlush = true
|
||||
if sc.pendingEncoderTableSize {
|
||||
// hpackEncoder may be in use by writeFrameAsync, so SETTINGS
|
||||
// changes to it are deferred until no frame is being written.
|
||||
// Replaying the smallest size before the latest one keeps the
|
||||
// encoder's view identical to having applied every change
|
||||
// (RFC 7541, Section 4.2).
|
||||
sc.pendingEncoderTableSize = false
|
||||
sc.hpackEncoder.SetMaxDynamicTableSize(sc.encoderTableSizeMin)
|
||||
sc.hpackEncoder.SetMaxDynamicTableSize(sc.encoderTableSize)
|
||||
}
|
||||
if wr.write.staysWithinBuffer(sc.bw.Available()) {
|
||||
sc.writingFrameAsync = false
|
||||
err := wr.write.writeFrame(sc)
|
||||
@@ -1271,6 +1283,11 @@ func (sc *serverConn) scheduleFrameWrite() {
|
||||
}
|
||||
sc.inFrameScheduleLoop = true
|
||||
for !sc.writingFrameAsync {
|
||||
if sc.flow.flowErr && (!sc.inGoAway || sc.goAwayCode == ErrCodeNo) {
|
||||
sc.inGoAway = true
|
||||
sc.needToSendGoAway = true
|
||||
sc.goAwayCode = ErrCodeFlowControl
|
||||
}
|
||||
if sc.needToSendGoAway {
|
||||
sc.needToSendGoAway = false
|
||||
sc.startFrameWrite(FrameWriteRequest{
|
||||
@@ -1294,6 +1311,9 @@ func (sc *serverConn) scheduleFrameWrite() {
|
||||
sc.startFrameWrite(wr)
|
||||
continue
|
||||
}
|
||||
if sc.flow.flowErr {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if sc.needsFrameFlush {
|
||||
sc.startFrameWrite(FrameWriteRequest{write: flushFrameWriter{}})
|
||||
@@ -1526,6 +1546,10 @@ func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
|
||||
return nil
|
||||
}
|
||||
if !st.flow.add(int32(f.Increment)) {
|
||||
if st.flow.conn.flowErr {
|
||||
// This is a lazily-detected connection-level flow control error.
|
||||
return sc.countError("bad_flow", ConnectionError(ErrCodeFlowControl))
|
||||
}
|
||||
return sc.countError("bad_flow", streamError(f.StreamID, ErrCodeFlowControl))
|
||||
}
|
||||
default: // connection-level flow control
|
||||
@@ -1584,10 +1608,6 @@ func (sc *serverConn) closeStream(st *stream, err error) {
|
||||
}
|
||||
}
|
||||
if p := st.body; p != nil {
|
||||
// Return any buffered unread bytes worth of conn-level flow control.
|
||||
// See golang.org/issue/16481
|
||||
sc.sendWindowUpdate(nil, p.Len())
|
||||
|
||||
p.CloseWithError(err)
|
||||
}
|
||||
if e, ok := err.(StreamError); ok {
|
||||
@@ -1641,7 +1661,12 @@ func (sc *serverConn) processSetting(s Setting) error {
|
||||
}
|
||||
switch s.ID {
|
||||
case SettingHeaderTableSize:
|
||||
sc.hpackEncoder.SetMaxDynamicTableSize(s.Val)
|
||||
// Applied by startFrameWrite; see comment there.
|
||||
if !sc.pendingEncoderTableSize || s.Val < sc.encoderTableSizeMin {
|
||||
sc.encoderTableSizeMin = s.Val
|
||||
}
|
||||
sc.encoderTableSize = s.Val
|
||||
sc.pendingEncoderTableSize = true
|
||||
case SettingEnablePush:
|
||||
sc.pushEnabled = s.Val != 0
|
||||
case SettingMaxConcurrentStreams:
|
||||
@@ -1672,28 +1697,14 @@ func (sc *serverConn) processSetting(s Setting) error {
|
||||
|
||||
func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
|
||||
sc.serveG.check()
|
||||
// Note: val already validated to be within range by
|
||||
// processSetting's Valid call.
|
||||
|
||||
// "A SETTINGS frame can alter the initial flow control window
|
||||
// size for all current streams. When the value of
|
||||
// SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST
|
||||
// adjust the size of all stream flow control windows that it
|
||||
// maintains by the difference between the new value and the
|
||||
// old value."
|
||||
old := sc.initialStreamSendWindowSize
|
||||
sc.initialStreamSendWindowSize = int32(val)
|
||||
growth := int32(val) - old // may be negative
|
||||
for _, st := range sc.streams {
|
||||
if !st.flow.add(growth) {
|
||||
// 6.9.2 Initial Flow Control Window Size
|
||||
// "An endpoint MUST treat a change to
|
||||
// SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
|
||||
// control window to exceed the maximum size as a
|
||||
// connection error (Section 5.4.1) of type
|
||||
// FLOW_CONTROL_ERROR."
|
||||
return sc.countError("setting_win_size", ConnectionError(ErrCodeFlowControl))
|
||||
}
|
||||
if !sc.flow.changeInitialWindowSize(int64(val)) {
|
||||
// 6.9.2 Initial Flow Control Window Size
|
||||
// "An endpoint MUST treat a change to
|
||||
// SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
|
||||
// control window to exceed the maximum size as a
|
||||
// connection error (Section 5.4.1) of type
|
||||
// FLOW_CONTROL_ERROR."
|
||||
return sc.countError("setting_win_size", ConnectionError(ErrCodeFlowControl))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1966,7 +1977,7 @@ func (sc *serverConn) processHeaders(f *MetaHeadersFrame) error {
|
||||
if st.reqTrailer != nil {
|
||||
st.trailer = make(http.Header)
|
||||
}
|
||||
st.body = req.Body.(*requestBody).pipe // may be nil
|
||||
st.body = st.reqBody.pipe // may be nil
|
||||
st.declBodyBytes = req.ContentLength
|
||||
|
||||
handler := sc.handler.ServeHTTP
|
||||
@@ -1989,7 +2000,7 @@ func (sc *serverConn) processHeaders(f *MetaHeadersFrame) error {
|
||||
st.readDeadline = time.AfterFunc(sc.hs.ReadTimeout, st.onReadTimeout)
|
||||
}
|
||||
|
||||
return sc.scheduleHandler(id, rw, req, handler)
|
||||
return sc.scheduleHandler(st, rw, req, handler)
|
||||
}
|
||||
|
||||
func (sc *serverConn) upgradeRequest(req *http.Request) {
|
||||
@@ -2102,7 +2113,6 @@ func (sc *serverConn) newStream(id, pusherID uint32, state streamState, priority
|
||||
}
|
||||
st.cw.Init()
|
||||
st.flow.conn = &sc.flow // link to conn-level counter
|
||||
st.flow.add(sc.initialStreamSendWindowSize)
|
||||
st.inflow.init(sc.initialStreamRecvWindowSize)
|
||||
if sc.hs.WriteTimeout > 0 {
|
||||
st.writeDeadline = time.AfterFunc(sc.hs.WriteTimeout, st.onWriteTimeout)
|
||||
@@ -2184,7 +2194,7 @@ func (sc *serverConn) newWriterAndRequest(st *stream, f *MetaHeadersFrame) (*res
|
||||
} else {
|
||||
req.ContentLength = -1
|
||||
}
|
||||
req.Body.(*requestBody).pipe = &pipe{
|
||||
st.reqBody.pipe = &pipe{
|
||||
b: &dataBuffer{expected: req.ContentLength},
|
||||
}
|
||||
}
|
||||
@@ -2204,7 +2214,7 @@ func (sc *serverConn) newWriterAndRequestNoBody(st *stream, rp httpcommon.Server
|
||||
return nil, nil, sc.countError(res.InvalidReason, streamError(st.id, ErrCodeProtocol))
|
||||
}
|
||||
|
||||
body := &requestBody{
|
||||
st.reqBody = &requestBody{
|
||||
conn: sc,
|
||||
stream: st,
|
||||
needsContinue: res.NeedsContinue,
|
||||
@@ -2220,7 +2230,7 @@ func (sc *serverConn) newWriterAndRequestNoBody(st *stream, rp httpcommon.Server
|
||||
ProtoMinor: 0,
|
||||
TLS: tlsState,
|
||||
Host: rp.Authority,
|
||||
Body: body,
|
||||
Body: st.reqBody,
|
||||
Trailer: res.Trailer,
|
||||
}).WithContext(st.ctx)
|
||||
rw := sc.newResponseWriter(st, req)
|
||||
@@ -2244,11 +2254,12 @@ type unstartedHandler struct {
|
||||
rw *responseWriter
|
||||
req *http.Request
|
||||
handler func(http.ResponseWriter, *http.Request)
|
||||
body *pipe
|
||||
}
|
||||
|
||||
// scheduleHandler starts a handler goroutine,
|
||||
// or schedules one to start as soon as an existing handler finishes.
|
||||
func (sc *serverConn) scheduleHandler(streamID uint32, rw *responseWriter, req *http.Request, handler func(http.ResponseWriter, *http.Request)) error {
|
||||
func (sc *serverConn) scheduleHandler(st *stream, rw *responseWriter, req *http.Request, handler func(http.ResponseWriter, *http.Request)) error {
|
||||
sc.serveG.check()
|
||||
maxHandlers := sc.advMaxStreams
|
||||
if sc.curHandlers < maxHandlers {
|
||||
@@ -2260,10 +2271,11 @@ func (sc *serverConn) scheduleHandler(streamID uint32, rw *responseWriter, req *
|
||||
return sc.countError("too_many_early_resets", ConnectionError(ErrCodeEnhanceYourCalm))
|
||||
}
|
||||
sc.unstartedHandlers = append(sc.unstartedHandlers, unstartedHandler{
|
||||
streamID: streamID,
|
||||
streamID: st.id,
|
||||
rw: rw,
|
||||
req: req,
|
||||
handler: handler,
|
||||
body: st.body,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
@@ -2277,6 +2289,10 @@ func (sc *serverConn) handlerDone() {
|
||||
u := sc.unstartedHandlers[i]
|
||||
if sc.streams[u.streamID] == nil {
|
||||
// This stream was reset before its goroutine had a chance to start.
|
||||
if u.body != nil {
|
||||
u.body.BreakWithError(errClosedBody)
|
||||
sc.sendWindowUpdate(nil, u.body.Len())
|
||||
}
|
||||
continue
|
||||
}
|
||||
if sc.curHandlers >= maxHandlers {
|
||||
@@ -2298,6 +2314,12 @@ func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request, handler
|
||||
didPanic := true
|
||||
defer func() {
|
||||
rw.rws.stream.cancelCtx()
|
||||
if b := rw.rws.stream.reqBody; b != nil {
|
||||
// Closing the body refunds flow control credit for any unconsumed data.
|
||||
// (reqBody is nil for Upgrade: h2c requests, but those do not use flow
|
||||
// control for the request body.)
|
||||
b.Close()
|
||||
}
|
||||
if req.MultipartForm != nil {
|
||||
req.MultipartForm.RemoveAll()
|
||||
}
|
||||
@@ -2396,7 +2418,7 @@ func (sc *serverConn) noteBodyReadFromHandler(st *stream, n int, err error) {
|
||||
func (sc *serverConn) noteBodyRead(st *stream, n int) {
|
||||
sc.serveG.check()
|
||||
sc.sendWindowUpdate(nil, n) // conn-level
|
||||
if st.state != stateHalfClosedRemote && st.state != stateClosed {
|
||||
if st != nil && st.state != stateHalfClosedRemote && st.state != stateClosed {
|
||||
// Don't send this WINDOW_UPDATE if the stream is closed
|
||||
// remotely.
|
||||
sc.sendWindowUpdate(st, n)
|
||||
@@ -2444,6 +2466,9 @@ func (b *requestBody) Close() error {
|
||||
b.closeOnce.Do(func() {
|
||||
if b.pipe != nil {
|
||||
b.pipe.BreakWithError(errClosedBody)
|
||||
if unread := b.pipe.Len(); unread > 0 {
|
||||
b.conn.noteBodyReadFromHandler(nil, unread, errClosedBody)
|
||||
}
|
||||
}
|
||||
})
|
||||
return nil
|
||||
@@ -2461,9 +2486,6 @@ func (b *requestBody) Read(p []byte) (n int, err error) {
|
||||
if err == io.EOF {
|
||||
b.sawEOF = true
|
||||
}
|
||||
if b.conn == nil {
|
||||
return
|
||||
}
|
||||
b.conn.noteBodyReadFromHandler(b.stream, n, err)
|
||||
return
|
||||
}
|
||||
|
||||
+94
-48
@@ -27,6 +27,7 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptrace"
|
||||
"net/textproto"
|
||||
"slices"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
@@ -203,7 +204,7 @@ type ClientConn struct {
|
||||
|
||||
mu sync.Mutex // guards following
|
||||
cond *sync.Cond // hold mu; broadcast on flow/closed changes
|
||||
flow outflow // our conn-level flow control quota (cs.outflow is per stream)
|
||||
flow connOutflow // our conn-level flow control quota (cs.outflow is per stream)
|
||||
inflow inflow // peer's conn-level flow control
|
||||
doNotReuse bool // whether conn is marked to not be reused for any future requests
|
||||
closing bool
|
||||
@@ -227,7 +228,6 @@ type ClientConn struct {
|
||||
maxConcurrentStreams uint32
|
||||
peerMaxHeaderListSize uint64
|
||||
peerMaxHeaderTableSize uint32
|
||||
initialWindowSize uint32
|
||||
initialStreamRecvWindowSize int32
|
||||
readIdleTimeout time.Duration
|
||||
pingTimeout time.Duration
|
||||
@@ -472,7 +472,6 @@ func (t *Transport) newClientConn(c net.Conn, singleUse bool, internalStateHook
|
||||
readerDone: make(chan struct{}),
|
||||
nextStreamID: 1,
|
||||
maxFrameSize: 16 << 10, // spec default
|
||||
initialWindowSize: 65535, // spec default
|
||||
initialStreamRecvWindowSize: conf.MaxUploadBufferPerStream,
|
||||
maxConcurrentStreams: initialMaxConcurrentStreams, // "infinite", per spec. Use a smaller value until we have received server settings.
|
||||
strictMaxConcurrentStreams: conf.StrictMaxConcurrentRequests,
|
||||
@@ -497,7 +496,7 @@ func (t *Transport) newClientConn(c net.Conn, singleUse bool, internalStateHook
|
||||
}
|
||||
|
||||
cc.cond = sync.NewCond(&cc.mu)
|
||||
cc.flow.add(int32(initialWindowSize))
|
||||
cc.flow.init()
|
||||
|
||||
// TODO: adjust this writer size to account for frame size +
|
||||
// MTU + crypto/tls record padding.
|
||||
@@ -876,6 +875,33 @@ func (cc *ClientConn) sendGoAway() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cc *ClientConn) goAwayAndClose(code ErrCode) {
|
||||
cc.mu.Lock()
|
||||
closed := cc.closed
|
||||
cc.closing = true
|
||||
cc.closed = true
|
||||
cc.mu.Unlock()
|
||||
if closed {
|
||||
return
|
||||
}
|
||||
if f := cc.fr.countError; f != nil {
|
||||
f(fmt.Sprintf("conn_close_error_%s", code.stringToken()))
|
||||
}
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
cc.wmu.Lock()
|
||||
cc.fr.WriteGoAway(0, code, nil)
|
||||
cc.bw.Flush()
|
||||
cc.wmu.Unlock()
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(250 * time.Millisecond):
|
||||
}
|
||||
cc.closeForError(fmt.Errorf("http2: closing connection with %v", code))
|
||||
}
|
||||
|
||||
// closes the client connection immediately. In-flight requests are interrupted.
|
||||
// err is sent to streams.
|
||||
func (cc *ClientConn) closeForError(err error) {
|
||||
@@ -1319,7 +1345,9 @@ func (cs *clientStream) cleanupWriteRequest(err error) {
|
||||
}
|
||||
if err != nil {
|
||||
cs.abortStream(err) // possibly redundant, but harmless
|
||||
if cs.sentHeaders {
|
||||
if ce, ok := err.(ConnectionError); ok {
|
||||
cc.goAwayAndClose(ErrCode(ce))
|
||||
} else if cs.sentHeaders {
|
||||
if se, ok := err.(StreamError); ok {
|
||||
if se.Cause != errFromPeer {
|
||||
cc.writeStreamReset(cs.ID, se.Code, false, err)
|
||||
@@ -1648,8 +1676,12 @@ func (cs *clientStream) awaitFlowControl(maxBytes int) (taken int32, err error)
|
||||
return 0, errRequestCanceled
|
||||
default:
|
||||
}
|
||||
if a := cs.flow.available(); a > 0 {
|
||||
take := a
|
||||
avail, ok := cs.flow.available()
|
||||
if !ok {
|
||||
return 0, ConnectionError(ErrCodeFlowControl)
|
||||
}
|
||||
if avail > 0 {
|
||||
take := avail
|
||||
if int(take) > maxBytes {
|
||||
|
||||
take = int32(maxBytes) // can't truncate int; take is int32
|
||||
@@ -1710,8 +1742,7 @@ type resAndError struct {
|
||||
|
||||
// requires cc.mu be held.
|
||||
func (cc *ClientConn) addStreamLocked(cs *clientStream) {
|
||||
cs.flow.add(int32(cc.initialWindowSize))
|
||||
cs.flow.setConnFlow(&cc.flow)
|
||||
cs.flow.conn = &cc.flow
|
||||
cs.inflow.init(cc.initialStreamRecvWindowSize)
|
||||
cs.ID = cc.nextStreamID
|
||||
cc.nextStreamID += 2
|
||||
@@ -2095,18 +2126,42 @@ func (rl *clientConnReadLoop) handleResponse(cs *clientStream, f *MetaHeadersFra
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Delete various headers that might mess up framing for HTTP/1. This is
|
||||
// not a problem for HTTP/2, but someone might use HTTP/2 transport as a
|
||||
// reverse proxy which forwards the response to an HTTP/1 client. Our
|
||||
// HTTP/1 client transport will properly reject improper headers such as
|
||||
// multiple conflicting Content-Length headers, but other implementations
|
||||
// might not.
|
||||
// TODO: just reject such responses? We deleted them for compatibility
|
||||
// since this was done in a security fix (go.dev/issue/81115). However,
|
||||
// rejecting them seems entirely reasonable and relatively safe.
|
||||
|
||||
// Connection-specific header fields must not appear in an HTTP/2 message,
|
||||
// and any message containing them is malformed. RFC 9113, Section 8.2.2.
|
||||
for _, k := range connHeaders {
|
||||
delete(res.Header, k)
|
||||
}
|
||||
res.ContentLength = -1
|
||||
if clens := res.Header["Content-Length"]; len(clens) == 1 {
|
||||
if cl, err := strconv.ParseUint(clens[0], 10, 63); err == nil {
|
||||
res.ContentLength = int64(cl)
|
||||
if clens, ok := res.Header["Content-Length"]; ok {
|
||||
// Repeated Content-Length values may be collapsed into one only if
|
||||
// they are identical per RFC 9110 Section 8.6.
|
||||
// No need to trim whitespace, HTTP/2 header values must not have
|
||||
// extraneous whitespace per RFC 9113 Section 8.2.1.
|
||||
// Non-canonical headers are already rejected by our framer at this
|
||||
// point.
|
||||
conflicting := slices.ContainsFunc(clens[1:], func(clen string) bool {
|
||||
return clen != clens[0]
|
||||
})
|
||||
cl, err := strconv.ParseUint(clens[0], 10, 63)
|
||||
if conflicting || err != nil {
|
||||
delete(res.Header, "Content-Length")
|
||||
} else {
|
||||
// TODO: care? unlike http/1, it won't mess up our framing, so it's
|
||||
// more safe smuggling-wise to ignore.
|
||||
res.Header["Content-Length"] = clens[:1]
|
||||
res.ContentLength = int64(cl)
|
||||
}
|
||||
} else if len(clens) > 1 {
|
||||
// TODO: care? unlike http/1, it won't mess up our framing, so it's
|
||||
// more safe smuggling-wise to ignore.
|
||||
} else if f.StreamEnded() && !cs.isHead {
|
||||
}
|
||||
|
||||
if res.ContentLength < 0 && f.StreamEnded() && !cs.isHead {
|
||||
res.ContentLength = 0
|
||||
}
|
||||
|
||||
@@ -2417,6 +2472,10 @@ const (
|
||||
func (rl *clientConnReadLoop) streamByID(id uint32, headerOrData bool) *clientStream {
|
||||
rl.cc.mu.Lock()
|
||||
defer rl.cc.mu.Unlock()
|
||||
return rl.streamByIDLocked(id, headerOrData)
|
||||
}
|
||||
|
||||
func (rl *clientConnReadLoop) streamByIDLocked(id uint32, headerOrData bool) *clientStream {
|
||||
if headerOrData {
|
||||
// Work around an unfortunate gRPC behavior.
|
||||
// See comment on ClientConn.rstStreamPingsBlocked for details.
|
||||
@@ -2499,24 +2558,10 @@ func (rl *clientConnReadLoop) processSettingsNoWrite(f *SettingsFrame) error {
|
||||
case SettingMaxHeaderListSize:
|
||||
cc.peerMaxHeaderListSize = uint64(s.Val)
|
||||
case SettingInitialWindowSize:
|
||||
// Values above the maximum flow-control
|
||||
// window size of 2^31-1 MUST be treated as a
|
||||
// connection error (Section 5.4.1) of type
|
||||
// FLOW_CONTROL_ERROR.
|
||||
if s.Val > math.MaxInt32 {
|
||||
if !cc.flow.changeInitialWindowSize(int64(s.Val)) {
|
||||
return ConnectionError(ErrCodeFlowControl)
|
||||
}
|
||||
|
||||
// Adjust flow control of currently-open
|
||||
// frames by the difference of the old initial
|
||||
// window size and this one.
|
||||
delta := int32(s.Val) - int32(cc.initialWindowSize)
|
||||
for _, cs := range cc.streams {
|
||||
cs.flow.add(delta)
|
||||
}
|
||||
cc.cond.Broadcast()
|
||||
|
||||
cc.initialWindowSize = s.Val
|
||||
case SettingHeaderTableSize:
|
||||
cc.henc.SetMaxDynamicTableSize(s.Val)
|
||||
cc.peerMaxHeaderTableSize = s.Val
|
||||
@@ -2558,29 +2603,30 @@ func (rl *clientConnReadLoop) processSettingsNoWrite(f *SettingsFrame) error {
|
||||
|
||||
func (rl *clientConnReadLoop) processWindowUpdate(f *WindowUpdateFrame) error {
|
||||
cc := rl.cc
|
||||
cs := rl.streamByID(f.StreamID, notHeaderOrDataFrame)
|
||||
if f.StreamID != 0 && cs == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
cc.mu.Lock()
|
||||
defer cc.mu.Unlock()
|
||||
|
||||
fl := &cc.flow
|
||||
if cs != nil {
|
||||
fl = &cs.flow
|
||||
}
|
||||
if !fl.add(int32(f.Increment)) {
|
||||
// For stream, the sender sends RST_STREAM with an error code of FLOW_CONTROL_ERROR
|
||||
if cs != nil {
|
||||
if f.StreamID == 0 {
|
||||
if !cc.flow.add(int32(f.Increment)) {
|
||||
return ConnectionError(ErrCodeFlowControl)
|
||||
}
|
||||
} else {
|
||||
cs := rl.streamByIDLocked(f.StreamID, notHeaderOrDataFrame)
|
||||
if cs == nil {
|
||||
return nil
|
||||
}
|
||||
if !cs.flow.add(int32(f.Increment)) {
|
||||
if cs.flow.conn.flowErr {
|
||||
// This is a lazily-detected connection-level flow control error.
|
||||
return ConnectionError(ErrCodeFlowControl)
|
||||
}
|
||||
// For stream, the sender sends RST_STREAM with
|
||||
// an error code of FLOW_CONTROL_ERROR.
|
||||
rl.endStreamErrorLocked(cs, StreamError{
|
||||
StreamID: f.StreamID,
|
||||
Code: ErrCodeFlowControl,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
return ConnectionError(ErrCodeFlowControl)
|
||||
}
|
||||
cc.cond.Broadcast()
|
||||
return nil
|
||||
|
||||
+194
-20
@@ -119,33 +119,27 @@ type http2TransportContextKey struct{}
|
||||
|
||||
// DialFromContext dials a new connection using the http2.Transport's DialTLS/DialTLSContext.
|
||||
func (t transportConfig) DialFromContext(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
if ctx.Value(http2TransportContextKey{}) == nil {
|
||||
dial, _ := ctx.Value(http2TransportContextKey{}).(*transportRoundTripState)
|
||||
if dial == nil {
|
||||
// We're being called from a RoundTrip that did not start with an http2.Transport.
|
||||
// Use the http.Transport's dialer.
|
||||
return nil, errors.ErrUnsupported
|
||||
}
|
||||
|
||||
tlsConf := t.t.TLSClientConfig
|
||||
if tlsConf == nil {
|
||||
tlsConf = &tls.Config{}
|
||||
} else {
|
||||
tlsConf = tlsConf.Clone()
|
||||
}
|
||||
if !slices.Contains(tlsConf.NextProtos, "h2") {
|
||||
tlsConf.NextProtos = append([]string{"h2"}, tlsConf.NextProtos...)
|
||||
}
|
||||
if tlsConf.ServerName == "" {
|
||||
host, _, err := net.SplitHostPort(address)
|
||||
if err == nil {
|
||||
tlsConf.ServerName = host
|
||||
}
|
||||
}
|
||||
return t.t.dialTLS(ctx, network, address, tlsConf)
|
||||
return t.t.dialForRoundTrip(ctx, dial, network, address)
|
||||
}
|
||||
|
||||
type transportInternal struct {
|
||||
initOnce sync.Once
|
||||
lazyt1 *http.Transport
|
||||
|
||||
dialMu sync.Mutex
|
||||
dials map[string]*transportDialState
|
||||
}
|
||||
|
||||
type transportDialState struct {
|
||||
dialc chan struct{} // close when dial returns
|
||||
dialErr error // dial result, set before dialc is closed
|
||||
rtdonec chan struct{} // closed when RoundTrip initiating the dial returns
|
||||
}
|
||||
|
||||
func (t *Transport) init() *http.Transport {
|
||||
@@ -167,6 +161,52 @@ func (t *Transport) configure(t1 *http.Transport) {
|
||||
}
|
||||
}
|
||||
|
||||
// transportRoundTripState is the state of the dial for an http2.Transport.RoundTrip.
|
||||
type transportRoundTripState struct {
|
||||
mu sync.Mutex
|
||||
rtdone bool // set when RoundTrip returns
|
||||
rtdonec chan struct{} // closed when RoundTrip returns
|
||||
gotconnc chan struct{} // closed when GotConn hook is called
|
||||
}
|
||||
|
||||
// startDial is called when a dial starts.
|
||||
//
|
||||
// It returns done=true if the RoundTrip has already returned,
|
||||
// in which case we should skip dialing.
|
||||
func (dial *transportRoundTripState) startDial() (gotconnc chan struct{}, done bool) {
|
||||
dial.mu.Lock()
|
||||
defer dial.mu.Unlock()
|
||||
if dial.rtdone {
|
||||
return nil, true
|
||||
}
|
||||
if dial.rtdonec == nil {
|
||||
dial.rtdonec = make(chan struct{})
|
||||
}
|
||||
dial.gotconnc = make(chan struct{})
|
||||
return dial.gotconnc, false
|
||||
}
|
||||
|
||||
// gotConn is called when RoundTrip gets a connection.
|
||||
// This may happen multiple times per RoundTrip, if a request is retried.
|
||||
func (dial *transportRoundTripState) gotConn() {
|
||||
dial.mu.Lock()
|
||||
defer dial.mu.Unlock()
|
||||
if dial.gotconnc != nil {
|
||||
close(dial.gotconnc)
|
||||
dial.gotconnc = nil
|
||||
}
|
||||
}
|
||||
|
||||
// roundTripDone is called when RoundTrip returns.
|
||||
func (dial *transportRoundTripState) roundTripDone() {
|
||||
dial.mu.Lock()
|
||||
defer dial.mu.Unlock()
|
||||
dial.rtdone = true
|
||||
if dial.rtdonec != nil {
|
||||
close(dial.rtdonec)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *Transport) roundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) {
|
||||
t1 := t.init()
|
||||
|
||||
@@ -186,12 +226,146 @@ func (t *Transport) roundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Res
|
||||
// Both http.Transport and http2.Transport allow the user to provide a custom
|
||||
// dial function, and historically you only get the dial function from the
|
||||
// Transport you're calling RoundTrip on.
|
||||
ctx := context.WithValue(req.Context(), http2TransportContextKey{}, t)
|
||||
//
|
||||
// In addition, http2.Transport coalesces dials, which http.Transport historically
|
||||
// has not.
|
||||
dial := &transportRoundTripState{}
|
||||
defer dial.roundTripDone()
|
||||
ctx := context.WithValue(req.Context(), http2TransportContextKey{}, dial)
|
||||
ctx = httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{
|
||||
GotConn: func(httptrace.GotConnInfo) {
|
||||
// Tell dialForRoundTrip that we have received a connection.
|
||||
dial.gotConn()
|
||||
},
|
||||
})
|
||||
req = req.WithContext(ctx)
|
||||
|
||||
return t1.RoundTrip(req)
|
||||
}
|
||||
|
||||
var errCoalescedDialAbandoned = errors.New("http2: abandoned coalesced dial")
|
||||
|
||||
const coalescedDialRetryTimeout = 50 * time.Millisecond
|
||||
|
||||
// dialForRoundTrip is called (indirectly) by net/http when dialing a new connection
|
||||
// for a request call which originated as an http2.Transport.RoundTrip call.
|
||||
//
|
||||
// It uses the http2.Transport's Dial hooks and coalesces dials.
|
||||
func (t *Transport) dialForRoundTrip(ctx context.Context, dial *transportRoundTripState, network, address string) (net.Conn, error) {
|
||||
gotconnc, rtdone := dial.startDial()
|
||||
if rtdone {
|
||||
// RoundTrip returned, no need for this dial to proceed.
|
||||
return nil, errCoalescedDialAbandoned
|
||||
}
|
||||
|
||||
var state *transportDialState
|
||||
for {
|
||||
// The first dial to an address registers itself with t.dials.
|
||||
// When the dial finishes, it records the outcome and removes itself from t.dials
|
||||
// so future dials will start a new round of coalescing.
|
||||
//
|
||||
// Subsequent dials observe that a dial is in progress, and skip dialing.
|
||||
t.dialMu.Lock()
|
||||
if t.dials == nil {
|
||||
t.dials = make(map[string]*transportDialState)
|
||||
}
|
||||
leader := t.dials[address]
|
||||
if leader == nil {
|
||||
// No entry in t.dials to coalesce with. Add ourselves as leader.
|
||||
state = &transportDialState{
|
||||
dialc: make(chan struct{}),
|
||||
rtdonec: dial.rtdonec,
|
||||
}
|
||||
t.dials[address] = state
|
||||
}
|
||||
t.dialMu.Unlock()
|
||||
if leader == nil {
|
||||
// We are the leader, so we should dial for real.
|
||||
break
|
||||
}
|
||||
|
||||
// Coalesce with a previous dial.
|
||||
var (
|
||||
done = false
|
||||
leaderdialc = leader.dialc
|
||||
leaderrtdonec = leader.rtdonec
|
||||
timerc <-chan time.Time
|
||||
)
|
||||
for !done {
|
||||
if leaderdialc == nil && leaderrtdonec == nil && timerc == nil {
|
||||
// The leader finished dialing, and its RoundTrip finished.
|
||||
//
|
||||
// There are several possibilities, which reduce to:
|
||||
// - The RoundTrip we are dialing for is about to receive
|
||||
// a connection (possibly the one the leader just dialed),
|
||||
// but we haven't observed it yet.
|
||||
// - There's something wrong with the leader's connection,
|
||||
// such as a TLS handshake failure.
|
||||
//
|
||||
// We have no good way to distinguish between these cases.
|
||||
//
|
||||
// Wait a short time for the leader's connection (or some
|
||||
// other usable connection) to be delivered to our RoundTrip.
|
||||
// If it is not, start a dial of our own.
|
||||
timerc = time.After(coalescedDialRetryTimeout)
|
||||
}
|
||||
select {
|
||||
case <-leaderdialc:
|
||||
// The leader's dial completed.
|
||||
if leader.dialErr != nil {
|
||||
return nil, leader.dialErr
|
||||
}
|
||||
leaderdialc = nil
|
||||
case <-leaderrtdonec:
|
||||
// The leader's RoundTrip completed.
|
||||
leaderrtdonec = nil
|
||||
case <-timerc:
|
||||
// The leader's dial and RoundTrip completed, and some time
|
||||
// has passed. Assume we're not getting a connection and
|
||||
// restart the dial process.
|
||||
done = true
|
||||
case <-dial.rtdonec:
|
||||
// Our RoundTrip returned.
|
||||
return nil, errCoalescedDialAbandoned
|
||||
case <-gotconnc:
|
||||
// Our RoundTrip got a connection.
|
||||
return nil, errCoalescedDialAbandoned
|
||||
case <-ctx.Done():
|
||||
// net/http abandoned the dial.
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Dial for real.
|
||||
tlsConf := t.TLSClientConfig
|
||||
if tlsConf == nil {
|
||||
tlsConf = &tls.Config{}
|
||||
} else {
|
||||
tlsConf = tlsConf.Clone()
|
||||
}
|
||||
if !slices.Contains(tlsConf.NextProtos, "h2") {
|
||||
tlsConf.NextProtos = append([]string{"h2"}, tlsConf.NextProtos...)
|
||||
}
|
||||
if tlsConf.ServerName == "" {
|
||||
host, _, err := net.SplitHostPort(address)
|
||||
if err == nil {
|
||||
tlsConf.ServerName = host
|
||||
}
|
||||
}
|
||||
nc, err := t.dialTLS(ctx, network, address, tlsConf)
|
||||
|
||||
// Remove this dial from t.dials, so future dial attempts will not coalesce with it.
|
||||
t.dialMu.Lock()
|
||||
delete(t.dials, address)
|
||||
t.dialMu.Unlock()
|
||||
|
||||
// Notify any dial coalesced with this one that we are done.
|
||||
state.dialErr = err
|
||||
close(state.dialc)
|
||||
|
||||
return nc, err
|
||||
}
|
||||
|
||||
func (t *Transport) closeIdleConnections() {
|
||||
t1 := t.init()
|
||||
t1.CloseIdleConnections()
|
||||
|
||||
+4
-3
@@ -79,10 +79,11 @@ func (wr FrameWriteRequest) Consume(n int32) (FrameWriteRequest, FrameWriteReque
|
||||
}
|
||||
|
||||
// Might need to split after applying limits.
|
||||
allowed := wr.stream.flow.available()
|
||||
if n < allowed {
|
||||
allowed = n
|
||||
avail, ok := wr.stream.flow.available()
|
||||
if !ok {
|
||||
return empty, empty, 0
|
||||
}
|
||||
allowed := min(n, avail)
|
||||
if wr.stream.sc.maxFrameSize < allowed {
|
||||
allowed = wr.stream.sc.maxFrameSize
|
||||
}
|
||||
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
// Copyright 2026 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package httpcommon
|
||||
|
||||
import (
|
||||
"compress/flate"
|
||||
"compress/gzip"
|
||||
"errors"
|
||||
"io"
|
||||
"io/fs"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var errConcurrentRead = errors.New("http: concurrent read on response body")
|
||||
|
||||
// incomparable is a zero-width, non-comparable type. Adding it to a struct
|
||||
// makes that struct also non-comparable, and generally doesn't add
|
||||
// any size (as long as it's first).
|
||||
type incomparable [0]func()
|
||||
|
||||
// GzipReader wraps a response body so it can lazily
|
||||
// get gzip.Reader from the pool on the first call to Read.
|
||||
// After Close is called it puts gzip.Reader to the pool immediately
|
||||
// if there is no Read in progress or later when Read completes.
|
||||
type GzipReader struct {
|
||||
_ incomparable
|
||||
Body io.ReadCloser // underlying Response.Body
|
||||
mu sync.Mutex // guards zr and zerr
|
||||
zr *gzip.Reader // stores gzip reader from the pool between reads
|
||||
zerr error // sticky gzip reader init error or sentinel value to detect concurrent read and read after close
|
||||
}
|
||||
|
||||
type eofReader struct{}
|
||||
|
||||
func (eofReader) Read([]byte) (int, error) { return 0, io.EOF }
|
||||
func (eofReader) ReadByte() (byte, error) { return 0, io.EOF }
|
||||
|
||||
var gzipPool = sync.Pool{New: func() any { return new(gzip.Reader) }}
|
||||
|
||||
// gzipPoolGet gets a gzip.Reader from the pool and resets it to read from r.
|
||||
func gzipPoolGet(r io.Reader) (*gzip.Reader, error) {
|
||||
zr := gzipPool.Get().(*gzip.Reader)
|
||||
if err := zr.Reset(r); err != nil {
|
||||
gzipPoolPut(zr)
|
||||
return nil, err
|
||||
}
|
||||
return zr, nil
|
||||
}
|
||||
|
||||
// gzipPoolPut puts a gzip.Reader back into the pool.
|
||||
func gzipPoolPut(zr *gzip.Reader) {
|
||||
// Reset will allocate bufio.Reader if we pass it anything
|
||||
// other than a flate.Reader, so ensure that it's getting one.
|
||||
var r flate.Reader = eofReader{}
|
||||
zr.Reset(r)
|
||||
gzipPool.Put(zr)
|
||||
}
|
||||
|
||||
// acquire returns a gzip.Reader for reading response body.
|
||||
// The reader must be released after use.
|
||||
func (gz *GzipReader) acquire() (*gzip.Reader, error) {
|
||||
gz.mu.Lock()
|
||||
defer gz.mu.Unlock()
|
||||
if gz.zerr != nil {
|
||||
return nil, gz.zerr
|
||||
}
|
||||
if gz.zr == nil {
|
||||
// gzipPoolGet might block indefinitely since it reads the gzip header.
|
||||
// Therefore, drop mu temporarily when using gzipPoolGet.
|
||||
// We set zerr to errConcurrentRead to prevent concurrent read
|
||||
// even when mu is temporarily dropped.
|
||||
gz.zerr = errConcurrentRead
|
||||
gz.mu.Unlock()
|
||||
zr, err := gzipPoolGet(gz.Body)
|
||||
gz.mu.Lock()
|
||||
// Guard against Close being called while gzipPoolGet is running.
|
||||
if gz.zerr != errConcurrentRead {
|
||||
if zr != nil {
|
||||
gzipPoolPut(zr)
|
||||
}
|
||||
return nil, gz.zerr
|
||||
}
|
||||
gz.zr, gz.zerr = zr, err
|
||||
if gz.zerr != nil {
|
||||
return nil, gz.zerr
|
||||
}
|
||||
}
|
||||
ret := gz.zr
|
||||
gz.zr, gz.zerr = nil, errConcurrentRead
|
||||
return ret, nil
|
||||
}
|
||||
|
||||
// release returns the gzip.Reader to the pool if Close was called during Read.
|
||||
func (gz *GzipReader) release(zr *gzip.Reader) {
|
||||
gz.mu.Lock()
|
||||
defer gz.mu.Unlock()
|
||||
if gz.zerr == errConcurrentRead {
|
||||
gz.zr, gz.zerr = zr, nil
|
||||
} else { // fs.ErrClosed
|
||||
gzipPoolPut(zr)
|
||||
}
|
||||
}
|
||||
|
||||
// close returns the gzip.Reader to the pool immediately or
|
||||
// signals release to do so after Read completes.
|
||||
func (gz *GzipReader) close() {
|
||||
gz.mu.Lock()
|
||||
defer gz.mu.Unlock()
|
||||
if gz.zerr == nil && gz.zr != nil {
|
||||
gzipPoolPut(gz.zr)
|
||||
gz.zr = nil
|
||||
}
|
||||
gz.zerr = fs.ErrClosed
|
||||
}
|
||||
|
||||
func (gz *GzipReader) Read(p []byte) (n int, err error) {
|
||||
zr, err := gz.acquire()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer gz.release(zr)
|
||||
|
||||
return zr.Read(p)
|
||||
}
|
||||
|
||||
func (gz *GzipReader) Close() error {
|
||||
gz.close()
|
||||
|
||||
return gz.Body.Close()
|
||||
}
|
||||
Vendored
+4
-3
@@ -1325,8 +1325,8 @@ github.com/orcaman/concurrent-map
|
||||
# github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245
|
||||
## explicit; go 1.18
|
||||
github.com/owncloud/libre-graph-api-go
|
||||
# github.com/owncloud/reva/v2 v2.0.0-20261001150122-9557cab91f00
|
||||
## explicit; go 1.24.0
|
||||
# github.com/owncloud/reva/v2 v2.0.0-20261009092845-29bcf6360c8b
|
||||
## explicit; go 1.26.0
|
||||
github.com/owncloud/reva/v2/cmd/revad/internal/grace
|
||||
github.com/owncloud/reva/v2/cmd/revad/runtime
|
||||
github.com/owncloud/reva/v2/internal/grpc/interceptors/appctx
|
||||
@@ -1576,6 +1576,7 @@ github.com/owncloud/reva/v2/pkg/share/cache/warmup/registry
|
||||
github.com/owncloud/reva/v2/pkg/share/manager/cs3
|
||||
github.com/owncloud/reva/v2/pkg/share/manager/json
|
||||
github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3
|
||||
github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3/cas
|
||||
github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3/providercache
|
||||
github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3/receivedsharecache
|
||||
github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3/sharecache
|
||||
@@ -2305,7 +2306,7 @@ golang.org/x/image/webp
|
||||
golang.org/x/mod/internal/lazyregexp
|
||||
golang.org/x/mod/module
|
||||
golang.org/x/mod/semver
|
||||
# golang.org/x/net v0.59.0
|
||||
# golang.org/x/net v0.60.0
|
||||
## explicit; go 1.26.0
|
||||
golang.org/x/net/bpf
|
||||
golang.org/x/net/context
|
||||
|
||||
Reference in new issue
Block a user