mirror of
https://github.com/XTLS/Xray-core.git
synced 2026-11-25 19:11:45 +00:00
xdrive
This commit is contained in:
@@ -0,0 +1,266 @@
|
||||
# XDRIVE
|
||||
|
||||
xDrive carries an ordered byte stream in each direction. Use matching releases on
|
||||
both peers. Drive uses slots; local, URL-template and S3 stores keep their WAL.
|
||||
This repository is a review candidate based on the maintainer's fork, not a merge
|
||||
of the current upstream branch.
|
||||
|
||||
## Drive protocol
|
||||
|
||||
The announcement names a table of file IDs and one reader-owned watermark for
|
||||
**each direction**. IDs are allocated in batches. The first lap creates files
|
||||
on first publication. Established sessions do not list files to find data:
|
||||
sequence `n` maps directly to `slots[n % depth]`. If present, the announcement's
|
||||
first payload is sequence zero, not an additional record.
|
||||
|
||||
Mode 1 carries up to 14 KiB in metadata, mode 5 a media body, modes 3 and 4
|
||||
mean end and error. See "Transport model" below.
|
||||
|
||||
- **Write:** one goroutine batches caller input and assigns sequence numbers.
|
||||
Input is gathered for 25 ms; after idle, a small write has a 2 ms window.
|
||||
The planner uses up to 24 available inline positions; larger bursts can use
|
||||
media. There are at most 32 upload workers per direction and never more than
|
||||
the ring depth. For the eager window after a media upload starts (default 2 s),
|
||||
later bursts do not split into inline waves even if few uploads remain.
|
||||
Reuse requires previous local completion and cumulative remote credit.
|
||||
- **Read:** idle polling focuses on the head. After a minute without a head,
|
||||
one bounded background probe at a time rotates through other slot descriptions
|
||||
to distinguish a gap from a genuinely idle peer. During activity, up to
|
||||
24 known descriptions are prefetched, with one metadata GET per worker at a
|
||||
time. Empty-slot polling reaches only four positions beyond the observed
|
||||
frontier (or head); new observations advance that frontier immediately.
|
||||
All media sizes may be prefetched; byte admission follows sequence
|
||||
order, bounded to 4 MiB per media connection and held until head promotion.
|
||||
Ordinary media has four HTTP permits per connection (capped at 64); head
|
||||
media has separate permits (up to four), including queued requests promoted
|
||||
to head. Both use the same connections; the head has its own frame allowance.
|
||||
A prefetched frame returns its local byte reservation when promoted, even if
|
||||
its body is still downloading. Completed successors retain theirs until promoted.
|
||||
Workers can finish out of order; one coordinator alone delivers bytes.
|
||||
Ordered delivery refreshes the eager timer; speculative body downloads do not.
|
||||
- **Media:** frames through 1 MiB use one progressive GET; larger frames
|
||||
use up to four block ranges at once, capped by the media connection count
|
||||
and targeting at least 512 KiB of payload per range.
|
||||
If the first range returns a full HTTP 200 body, keep it and cancel the other
|
||||
ranges instead of downloading the full body four times. Validate every
|
||||
block's sequence tag, HTTP range/length and EOF. One retry can resume an
|
||||
incomplete span without delivering the same bytes twice. No media GET runs
|
||||
before discovering its frame description.
|
||||
- **Close:** Close discards unread input, drains its writer and publishes END.
|
||||
It keeps verifying input and returning credit until it reads the peer's END,
|
||||
then flushes any remaining verified watermark. The peer may still have a full
|
||||
ring to drain after our writer finishes. Interrupt cancels instead.
|
||||
|
||||
Unlike v6, a unilateral graceful Close can time out if the peer never publishes
|
||||
END. The one-minute watchdog tracks outbound progress until the local writer
|
||||
finishes, then also counts successful inbound watermark writes during Close.
|
||||
Receiving END alone does not close the outbound half.
|
||||
|
||||
## Transport model (Drive)
|
||||
|
||||
Each direction is a ring of `depth` Drive files plus one watermark file owned
|
||||
by the reader. Sequence `n` always lives in `slots[n % depth]`.
|
||||
|
||||
1. **Gather.** The writer collects caller input for up to 25 ms (2 ms after
|
||||
idle for a single small write) or until the current frame size is reached.
|
||||
With 4 or more uploads in flight the writer is streaming: it keeps
|
||||
gathering while input keeps arriving, up to 200 ms or a full frame, and
|
||||
sends once input pauses for 25 ms, so a reply burst goes out as one frame.
|
||||
2. **Frame size grows every round.** It starts at `segmentBytes` (512 KiB)
|
||||
and doubles after each round that filled a whole frame, up to 4 MiB (below
|
||||
Drive's 5 MB multipart limit). It halves (not below the start) when an
|
||||
upload waited more than 5 s for ring credit outside Drive cooldown.
|
||||
Cooldown freezes frame size instead of shrinking it: smaller frames spend
|
||||
more requests per byte. Routine credit takes 1-3 s; shorter waits only mean
|
||||
the writer is a ring ahead. Larger frames carry more bytes per position.
|
||||
3. **Publish.** Up to 14 KiB goes inline in the file description (one PATCH;
|
||||
an idle writer may split a burst into up to 24 inline frames, a streaming
|
||||
writer never does, because the reader finds only about 24 frames per round
|
||||
trip and 14 KiB frames would cap throughput near 1 MB/s). Larger frames
|
||||
are one multipart PATCH: the description holds `XDRVSL03`, sequence, mode
|
||||
and length; the body is blocks of an 8-byte sequence tag followed by up to
|
||||
256 KiB of data. At most 32 uploads and
|
||||
4 MiB of unfinished uploads per media connection run per direction (one
|
||||
frame may exceed it alone). Media requests rotate per request over
|
||||
the media connections (XMUX `maxConnections`, default 4): one Google
|
||||
connection carries only a fraction of a link (a measured single-connection
|
||||
client download averaged ~0.22 MB/s). The byte bound,
|
||||
about one 4 MiB frame per connection, bounds payload bytes, not request count
|
||||
or duplicated network traffic. Head reads have separate HTTP permits, not
|
||||
extra connections. Bounded look-ahead overlaps service latency between frames
|
||||
instead of forcing one large frame to finish before starting the next.
|
||||
4. **Discover.** The reader polls the head slot's description (25 ms while
|
||||
active; no duplicate hedged GET) and prefetches up to 24 descriptions. Slots
|
||||
beyond the observed frontier plus four wait without polling; the head always
|
||||
polls, and the existing gap probe still covers otherwise unobserved gaps.
|
||||
Bodies of all sizes download ahead within the byte budget, admitted in sequence
|
||||
order so distant successors cannot reserve it before nearer frames. The head
|
||||
bypasses that budget, and a queued media request switches to the reserved
|
||||
HTTP permits when promoted. Admission waits for the previous frame's ready
|
||||
signal, not its completed download.
|
||||
Promotion releases any existing look-ahead reservation, not remote ring credit.
|
||||
Thus a head discovered in advance no longer consumes both its own allowance
|
||||
and the successors' budget. Cancellation also releases each reservation once.
|
||||
5. **Fetch.** Media up to 1 MiB uses one streaming GET; larger frames use
|
||||
two to four block-aligned ranges with the default four connections,
|
||||
targeting at least 512 KiB per range and reaching four ranges at 2 MiB.
|
||||
They start together for each admitted frame: every block carries
|
||||
the sequence tag, so each range rejects an older lap by itself (before,
|
||||
later ranges waited for the first one, costing a second time-to-first-byte,
|
||||
~1 s, per large frame).
|
||||
A full HTTP 200 response to the first range replaces all ranges; the others
|
||||
are canceled before any of their bytes are delivered. Bytes are delivered
|
||||
in 32 KiB pieces as they arrive. One retry resumes
|
||||
after the delivered bytes; the declared length and exact EOF are checked.
|
||||
6. **Credit.** The reader writes its cumulative watermark every `depth/6`
|
||||
frames or 1.5 s. A slot is rewritten only after that credit. Frame size
|
||||
changes are logged at debug level (`xdrive frame size A -> B`), as is
|
||||
each media frame: `xdrive upload seq` (credit wait, PUT time) and
|
||||
`xdrive read seq` (time to find, admission/byte-budget wait, body time).
|
||||
`xdrive watermark seq N put P` records successful ACK publications, and
|
||||
`xdrive credit seq N ack A` records the writer observing newer credit.
|
||||
`xdrive span seq` records range status, wire bytes, time waiting for headers
|
||||
(including permit wait, retries and service latency), and time after headers.
|
||||
`xdrive span retry seq` records emitted payload bytes and the error that
|
||||
triggered the one stream resume; successful final reads can hide this error.
|
||||
`xdrive request retry seq` exposes retries before headers or buffered success.
|
||||
`xdrive cooldown D` records the shared delay after quota/service rejections.
|
||||
|
||||
There are no CRCs: integrity relies on TLS, the length checks and the
|
||||
per-block sequence tags, and VLESS encryption authenticates the payload. Both
|
||||
peers must run this release (`XDRVSL03` is not readable by older peers).
|
||||
|
||||
## Implementation and trade-offs
|
||||
|
||||
`slots.go` contains the frame codec, ring announcement and
|
||||
publication, outbound writer, and inbound reader, in that order. One reader
|
||||
ACK loop owns both periodic and final watermark writes. `drive.go` owns OAuth,
|
||||
Drive requests, quotas, object CRUD, ID allocation, and media verification.
|
||||
`client.go` is shared with the URL-template and S3 transports. It retains the
|
||||
configured TLS/QUIC dial path, socket and mask settings, stall timeout, HTTP/2
|
||||
keepalive and XMUX leases. Drive uses distinct metadata, priority and media
|
||||
pools. Metadata and priority select a lease once per session; media rotates
|
||||
per request across one-connection XMUX lanes instead of random selection
|
||||
(the upper `maxConnections` bound, default 4). Request/reuse/lifetime limits
|
||||
still apply within each lane; the media byte budget follows the same count.
|
||||
Peer-supplied IDs are checked for valid syntax and uniqueness. An existing
|
||||
object must match its announced session name and configured parent on first
|
||||
use. Keep the folder private to the two peers; these checks do not authenticate
|
||||
a writer who already has access to the session folder.
|
||||
|
||||
Removed from the larger implementation: custom spare-connection probes,
|
||||
background connection/token/ID keepers, eager spare rings, duplicated media
|
||||
rescue and latency controllers, and detailed per-burst telemetry. A Drive ID
|
||||
allocation failure now fails the dial explicitly instead of switching to WAL.
|
||||
Announcements are also created with reserved IDs. After a lost reply, read back
|
||||
the exact slot, watermark or inline announcement description; for a media
|
||||
announcement also compare the complete body. Never replay an ambiguous write.
|
||||
If an announcement was already deleted, a 404 is not proof of delivery. If confirmation fails,
|
||||
the original write error is preserved. Graceful close reports final ACK errors. These are
|
||||
behavior differences, not just source rearrangement. Historical throughput
|
||||
and tail-latency measurements from the larger version are **not** measurements
|
||||
of this one. Empty Drive announcements are rejected rather than opened as WAL
|
||||
sessions. Uploads and OAuth refresh requests do not follow redirects.
|
||||
|
||||
## Failure handling and verification
|
||||
|
||||
A fatal upload, media-read or watermark error cancels both halves of a Drive
|
||||
connection with the first error as the cause. A normal END only closes its
|
||||
own direction. Readers reject an overwritten sequence; a writer verifies that
|
||||
a cumulative ACK cannot cover its own unpublished sequence before reusing a slot.
|
||||
Buffered GETs can retry an interrupted response body. Streamed media resumes
|
||||
by delivered offset, and an ambiguous mutation is not replayed. Listing and ID allocation
|
||||
use the app-data space when `remoteFolder` is `appDataFolder`. Drive announcement
|
||||
age is seeded from `createdTime` and the listing response’s `Date`, so an expired
|
||||
announcement does not become fresh when a listener restarts. This is not a
|
||||
persistent exactly-once claim within the TTL. An unprovable gap (no subsequent
|
||||
frame) still looks like an idle connection; use a read deadline when one is required.
|
||||
|
||||
Transient OAuth transport and service failures can retry before any file operation
|
||||
is sent. All Drive file attempts, including retries, reserve spaced starts at
|
||||
80 requests/s per shared storage instance, across sessions and lanes. Two peers
|
||||
at this ceiling use about 9,600 attempts/minute against the observed 12,000
|
||||
quota, leaving headroom, not a guarantee for other processes or profiles sharing
|
||||
the project. Queued requests recheck cooldown before proceeding. Cancellation
|
||||
may leave unused pacing turns, but releases the request permit.
|
||||
Drive rate-limit responses and 503 responses with `Retry-After` apply a shared
|
||||
exponential cooldown (jittered 2–30 s base), reset after a minute without a new
|
||||
cooldown. Concurrent rejections in one cooldown do not escalate independently;
|
||||
a longer `Retry-After` still extends it. A 503 never permits mutation replay.
|
||||
Quota retry logs omit the repetitive JSON error body. Cleanup excludes
|
||||
folders and Google-native objects. Conflicting regular files with the exact same
|
||||
announcement name are not selected or deleted as a group; resolve them manually.
|
||||
The admission deadline also applies while loading or binding the announcement,
|
||||
not to the resulting connection. Use a dedicated folder for one listener and its clients.
|
||||
|
||||
### Verification of this candidate
|
||||
|
||||
This version descends from the v7 candidate, which began as a literal merge
|
||||
of v6's four slot files. The per-block CRCs, the checksum table and the
|
||||
checksummed media reader are gone here. Retry safety rules remain, but media
|
||||
reading, request pacing and shared cooldown now differ from v6.
|
||||
|
||||
The quota refinement passes `gofmt -l`, `go build ./...` and xdrive `go vet`.
|
||||
A Python virtual-clock model checks pacing, cancellation, cooldown extension,
|
||||
Retry-After, frontier progression and frame-size freezing; it is not a Go
|
||||
HTTP/race workload or a live-Drive throughput benchmark. No test files are added.
|
||||
|
||||
The receive-credit refinement releases local look-ahead bytes on head promotion;
|
||||
watermarks still advance only after verified ordered delivery and exact EOF.
|
||||
No budgets, request limits or wire-format fields changed. Validate with slow
|
||||
heads, completed successors, cancellation and unequal Close workloads under race
|
||||
detection before attributing a sustained-speed improvement to this change.
|
||||
|
||||
The following are **Python model checks against the v7 candidate, not runs of
|
||||
this Go package**:
|
||||
|
||||
- At ring depth two, the v6 and candidate models each delivered 1,096,163
|
||||
bytes in each direction, with separate deterministic payloads. All received
|
||||
bytes matched. The fixture crossed the inline, prefix and multi-range
|
||||
thresholds. It cut 16 model responses after a complete block plus 17 bytes;
|
||||
eight resumes simulated a server ignoring Range. No duplicated bytes.
|
||||
- Seven scripted quota/status cases per version checked the retry decision for
|
||||
429, rate-limited and ordinary 403, and 500/503, including a 503 with
|
||||
Retry-After on a mutation. Delays used a virtual clock, not HTTP or Drive.
|
||||
- A small exhaustive close model let the empty writer publish END before the
|
||||
opposite writer finished four data frames. Three v6 terminal states could
|
||||
not progress; none of the candidate's 45 reachable states was stuck. This
|
||||
is a bounded ordering check, not a goroutine race test.
|
||||
|
||||
**Release gates:** the candidate workspace had no Go 1.27 or `gofmt`, so the
|
||||
model checks above did not build it. This snapshot was formatted with `gofmt`
|
||||
(and the repository's `vformat`/`vprotogen` checks), vetted and built with the
|
||||
`go.mod` toolchain; it has not been run against an HTTP mock in Go, with a
|
||||
`-race` workload, or against live Drive. The inventory below is the physical
|
||||
post-`gofmt` count. No XDrive test file is shipped.
|
||||
|
||||
For deeper assurance, in a disposable checkout, run the same depth-two
|
||||
transfers against v6 and the candidate with a fault-injecting Drive HTTP mock
|
||||
under `go test -race`: compare both byte streams, truncate media responses,
|
||||
return 429/403/503, and close both peers with unequal outstanding writes.
|
||||
Also check one-sided Close, final ACK failure and Interrupt. A plain
|
||||
`go test -race` without a workload is not a concurrency test. Repeat the
|
||||
bidirectional transfer with a dedicated live Drive folder.
|
||||
|
||||
## Drive source budget (physical lines, including comments and blanks)
|
||||
|
||||
Count all three implementation files in full, including the shared HTTP client.
|
||||
For mixed files, the following inventory charges whole integration functions
|
||||
where practical, including generic code within them. The remaining WAL/backend,
|
||||
protocol-wide listener, configuration and generated protobuf code is shared or
|
||||
unrelated, not a hidden second Drive implementation. Ranges below are inclusive
|
||||
for this snapshot, relative to `transport/internet/xdrive` unless marked `infra/`.
|
||||
|
||||
| Source | Inclusive lines counted | Count |
|
||||
|---|---|---:|
|
||||
| `drive.go` | whole file | 1056 |
|
||||
| `slots.go` | whole file | 879 |
|
||||
| `client.go` | whole file | 537 |
|
||||
| `conn.go` | 65–79, 185–217, 219–244 | 74 |
|
||||
| `xdrive.go` | 9, 139–223, 276, 323–413, 479–490, 492–512, 538–572, 588–670 | 329 |
|
||||
| `params.go` | 75–91 | 17 |
|
||||
| `storage.go` | 9, 20–24, 36–63, 65–75 | 45 |
|
||||
| `storage_lease.go` | 26–32, 42–45, 47–63, 69–70, 89, 157–162 | 37 |
|
||||
| `infra/conf/transport_method.go` | 1020–1027, 1037, 1045–1050 | 15 |
|
||||
| `infra/conf/transport_internet.go` | 266–275 | 10 |
|
||||
| **Total** | | **2999** |
|
||||
+200
-182
@@ -32,10 +32,7 @@ type serviceTransport struct {
|
||||
stall time.Duration
|
||||
}
|
||||
|
||||
// RoundTrip ends a request that stands still for t.stall, with no answer that
|
||||
// long after its body went out or no byte of either body, but not one that just
|
||||
// runs long: a large object on a slow link takes minutes and is fine as long as
|
||||
// its bytes move
|
||||
// Cancel stalled requests, not long transfers that continue to make progress.
|
||||
func (t *serviceTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
next := t.plain
|
||||
if r.URL.Scheme == "https" {
|
||||
@@ -43,29 +40,46 @@ func (t *serviceTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancelCause(r.Context())
|
||||
timer := time.AfterFunc(t.stall, func() { cancel(errStalled) })
|
||||
alive := func() { timer.Reset(t.stall) }
|
||||
var timerMu sync.Mutex
|
||||
ended := false
|
||||
deadline := time.Now().Add(t.stall)
|
||||
timer := time.AfterFunc(t.stall, func() {
|
||||
timerMu.Lock()
|
||||
defer timerMu.Unlock()
|
||||
if !ended && !time.Now().Before(deadline) {
|
||||
cancel(errStalled)
|
||||
}
|
||||
})
|
||||
alive := func() {
|
||||
timerMu.Lock()
|
||||
defer timerMu.Unlock()
|
||||
if !ended {
|
||||
deadline = time.Now().Add(t.stall)
|
||||
timer.Reset(t.stall)
|
||||
}
|
||||
}
|
||||
end := func() {
|
||||
timerMu.Lock()
|
||||
ended = true
|
||||
timer.Stop()
|
||||
timerMu.Unlock()
|
||||
cancel(nil)
|
||||
}
|
||||
r = r.WithContext(ctx)
|
||||
// the headers of chrome as with XHTTP and DoH, net/http and http3 would send
|
||||
// their own user agent after a hello of chrome
|
||||
// Clone before setting defaults: the caller owns the original headers.
|
||||
r.Header = r.Header.Clone()
|
||||
utils.TryDefaultHeadersWith(r.Header, "fetch")
|
||||
if r.Body != nil && r.Body != http.NoBody {
|
||||
r.Body = &progressBody{ReadCloser: r.Body, alive: alive}
|
||||
r.Body = &progressBody{ReadCloser: r.Body, alive: alive, upload: true}
|
||||
}
|
||||
// a body sent again by the transport itself, after a GOAWAY or on a reused
|
||||
// connection that failed, moves just the same
|
||||
// Rewinds performed by the transport must also reset the stall timer.
|
||||
if getBody := r.GetBody; getBody != nil {
|
||||
r.GetBody = func() (io.ReadCloser, error) {
|
||||
body, err := getBody()
|
||||
if err != nil || body == http.NoBody {
|
||||
return body, err
|
||||
}
|
||||
return &progressBody{ReadCloser: body, alive: alive}, nil
|
||||
return &progressBody{ReadCloser: body, alive: alive, upload: true}, nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,8 +94,18 @@ func (t *serviceTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// stalled returns errStalled for an error that the stall gave, which http2 reports
|
||||
// as a plain cancel
|
||||
func (t *serviceTransport) CloseIdleConnections() {
|
||||
closeIdleTransport(t.plain)
|
||||
closeIdleTransport(t.secure)
|
||||
}
|
||||
|
||||
func closeIdleTransport(t http.RoundTripper) {
|
||||
if closer, ok := t.(interface{ CloseIdleConnections() }); ok {
|
||||
closer.CloseIdleConnections()
|
||||
}
|
||||
}
|
||||
|
||||
// HTTP/2 can report the stall timeout as an ordinary cancellation.
|
||||
func stalled(ctx context.Context, err error) error {
|
||||
if context.Cause(ctx) == errStalled {
|
||||
return errStalled
|
||||
@@ -91,16 +115,19 @@ func stalled(ctx context.Context, err error) error {
|
||||
|
||||
type progressBody struct {
|
||||
io.ReadCloser
|
||||
alive func()
|
||||
end func()
|
||||
alive func()
|
||||
end func()
|
||||
upload bool
|
||||
// ctx is that of the request, for the body of its response
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func (b *progressBody) Read(p []byte) (int, error) {
|
||||
// http2 reads a request body up to 512 KiB at a time and sends it all before
|
||||
// the next read, which on a slow link could look like no progress
|
||||
n, err := b.ReadCloser.Read(p[:min(len(p), 16<<10)])
|
||||
// Short upload reads keep the stall timer meaningful on slow connections.
|
||||
if b.upload {
|
||||
p = p[:min(len(p), 16<<10)]
|
||||
}
|
||||
n, err := b.ReadCloser.Read(p)
|
||||
if n > 0 {
|
||||
b.alive()
|
||||
}
|
||||
@@ -118,29 +145,27 @@ func (b *progressBody) Close() error {
|
||||
return err
|
||||
}
|
||||
|
||||
// newServiceClient returns a client whose requests end after stall without
|
||||
// progress, see serviceTransport.RoundTrip, and whose connections close when
|
||||
// connCtx is done. Clients that share h1Hosts share which hosts answer over h1
|
||||
// connCtx owns sockets; h1Hosts shares ALPN observations between clients.
|
||||
func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings *internet.MemoryStreamConfig, stall time.Duration, maxConns int) *http.Client {
|
||||
var (
|
||||
tlsConfig *tls.Config
|
||||
sockopt *internet.SocketConfig
|
||||
fronting *net.Destination
|
||||
keepAlive = net.ChromeH2KeepAlivePeriod
|
||||
// h3 keeps alive only when asked to, see below
|
||||
h3KeepAlive time.Duration
|
||||
// Detect silent h2 loss unless XMUX supplies an explicit keepalive.
|
||||
h2Idle, h2PingWait = 1500 * time.Millisecond, 2500 * time.Millisecond
|
||||
h3KeepAlive time.Duration
|
||||
)
|
||||
if streamSettings != nil {
|
||||
tlsConfig = tls.ConfigFromStreamSettings(streamSettings)
|
||||
sockopt = streamSettings.SocketSettings
|
||||
fronting = streamSettings.Destination
|
||||
if config, ok := streamSettings.ProtocolSettings.(*Config); ok && config.Xmux != nil {
|
||||
if config, ok := streamSettings.ProtocolSettings.(*Config); ok && config != nil && config.Xmux != nil {
|
||||
switch period := config.Xmux.HKeepAlivePeriod; {
|
||||
case period > 0:
|
||||
keepAlive = time.Duration(period) * time.Second
|
||||
h3KeepAlive = keepAlive
|
||||
h3KeepAlive = time.Duration(period) * time.Second
|
||||
h2Idle, h2PingWait = h3KeepAlive, 0
|
||||
case period < 0:
|
||||
keepAlive = 0
|
||||
h2Idle, h2PingWait = 0, 0
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -149,9 +174,15 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
}
|
||||
fingerprint := tls.GetFingerprint(tlsConfig.Fingerprint)
|
||||
|
||||
// fronting takes only the address and port, the network stays that of the
|
||||
// dial, which is UDP for h3 though the destination is built as TCP
|
||||
// A configured front replaces the address, not the transport network.
|
||||
dial := func(ctx context.Context, network, addr string) (net.Conn, net.Destination, error) {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
stop := context.AfterFunc(connCtx, cancel)
|
||||
defer stop()
|
||||
defer cancel()
|
||||
if err := connCtx.Err(); err != nil {
|
||||
return nil, net.Destination{}, err
|
||||
}
|
||||
host, err := net.ParseDestination(network + ":" + addr)
|
||||
if err != nil {
|
||||
return nil, host, errors.New("bad address: ", addr).Base(err)
|
||||
@@ -167,7 +198,7 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
|
||||
var conn net.Conn
|
||||
switch {
|
||||
case streamSettings.FinalMask == nil:
|
||||
case streamSettings == nil || streamSettings.FinalMask == nil:
|
||||
conn, err = internet.DialSystem(ctx, target, sockopt)
|
||||
case target.Network == net.Network_UDP:
|
||||
conn, err = streamSettings.FinalMask.DialUDP(ctx, target)
|
||||
@@ -177,15 +208,13 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
if err != nil {
|
||||
return nil, host, errors.New("failed to dial to dest").Base(err)
|
||||
}
|
||||
// h3 closes its QUIC connection instead, as the server never hears of a UDP
|
||||
// socket that closes
|
||||
// HTTP/3 must close QUIC itself as well as its UDP socket.
|
||||
if network == "udp" {
|
||||
return conn, host, nil
|
||||
}
|
||||
// CloseIdleConnections leaves an h2 connection open while a stream just
|
||||
// canceled has not left it yet
|
||||
stop := context.AfterFunc(connCtx, func() { conn.Close() })
|
||||
return &ctxConn{Conn: conn, stop: stop}, host, nil
|
||||
// A recently canceled h2 stream may still own the socket.
|
||||
stopConn := context.AfterFunc(connCtx, func() { conn.Close() })
|
||||
return &ctxConn{Conn: conn, stop: stopConn}, host, nil
|
||||
}
|
||||
|
||||
dialPlain := func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
@@ -207,8 +236,7 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
} else {
|
||||
tlsConn = tls.UClient(conn, gotlsConfig, fingerprint)
|
||||
}
|
||||
// the dial outlives the request that started it, and a handshake that hangs
|
||||
// would keep the one connection of the host to itself
|
||||
// Bound the handshake independently of connection reuse.
|
||||
ctx, cancel := context.WithTimeout(ctx, stall)
|
||||
defer cancel()
|
||||
if err := tlsConn.(tls.Interface).HandshakeContext(ctx); err != nil {
|
||||
@@ -226,7 +254,7 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
MaxIdleConns: maxConns,
|
||||
MaxIdleConnsPerHost: maxConns,
|
||||
MaxConnsPerHost: connsPerHost,
|
||||
HTTP2: &http.HTTP2Config{SendPingTimeout: keepAlive},
|
||||
HTTP2: &http.HTTP2Config{SendPingTimeout: h2Idle, PingTimeout: h2PingWait},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -237,9 +265,7 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
if quicParams == nil {
|
||||
quicParams = &internet.QuicParams{BbrProfile: string(bbr.ProfileStandard)}
|
||||
}
|
||||
// the defaults are those of quic-go, with no keepalive unless asked for, as
|
||||
// in DoH: http3 never closes a connection that is idle or that it dropped
|
||||
// after an error, so only the idle timeout or the end of connCtx ends it
|
||||
// QUIC idle timeout and connCtx bound unused connections.
|
||||
quicConfig := &quic.Config{
|
||||
InitialStreamReceiveWindow: quicParams.InitStreamReceiveWindow,
|
||||
MaxStreamReceiveWindow: quicParams.MaxStreamReceiveWindow,
|
||||
@@ -258,11 +284,16 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
https = &http3.Transport{
|
||||
QUICConfig: quicConfig,
|
||||
Dial: func(ctx context.Context, addr string, _ *gotls.Config, cfg *quic.Config) (*quic.Conn, error) {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
stop := context.AfterFunc(connCtx, cancel)
|
||||
defer stop()
|
||||
defer cancel()
|
||||
if connCtx.Err() != nil {
|
||||
cancel()
|
||||
}
|
||||
switch quicParams.Congestion {
|
||||
case "", "bbr", "reno":
|
||||
default:
|
||||
// brutal is for Hysteria servers, not services, and a panic here, in
|
||||
// a goroutine of http3, would end the process
|
||||
return nil, errors.New("unsupported congestion control over h3: ", quicParams.Congestion)
|
||||
}
|
||||
|
||||
@@ -284,8 +315,7 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
return nil, errors.New("failed to dial to dest: unexpected ", reflect.TypeOf(c))
|
||||
}
|
||||
|
||||
// built for each dial with the host as SNI, as for h2: http3 sets the
|
||||
// SNI on a copy, which a pinned CA and the ECH lookup do not see
|
||||
// Set SNI before certificate pinning and ECH lookup.
|
||||
gotlsConfig := tlsConfig.GetTLSConfig(tls.WithDestination(host))
|
||||
// it is for servers, and ChromeParrot refuses a config that has it
|
||||
gotlsConfig.GetCertificate = nil
|
||||
@@ -299,8 +329,8 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
pktConn.Close()
|
||||
return nil, err
|
||||
}
|
||||
stop := context.AfterFunc(connCtx, func() { qconn.CloseWithError(quic.ApplicationErrorCode(http3.ErrCodeNoError), "") })
|
||||
context.AfterFunc(qconn.Context(), func() { stop(); tr.Close(); pktConn.Close() })
|
||||
stopConn := context.AfterFunc(connCtx, func() { qconn.CloseWithError(quic.ApplicationErrorCode(http3.ErrCodeNoError), "") })
|
||||
context.AfterFunc(qconn.Context(), func() { stopConn(); tr.Close(); pktConn.Close() })
|
||||
if quicParams.Congestion != "reno" {
|
||||
congestion.UseBBR(qconn, bbr.Profile(quicParams.BbrProfile))
|
||||
}
|
||||
@@ -324,8 +354,7 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
}
|
||||
}
|
||||
|
||||
// ctxConn is a connection that connCtx no longer closes once it is closed,
|
||||
// so that one that ends on its own leaves nothing behind in connCtx
|
||||
// Closing the socket unregisters the owner-context callback.
|
||||
type ctxConn struct {
|
||||
net.Conn
|
||||
stop func() bool
|
||||
@@ -336,9 +365,7 @@ func (c *ctxConn) Close() error {
|
||||
return c.Conn.Close()
|
||||
}
|
||||
|
||||
// secureTransport keeps a host to one connection, all that h2 needs, as without
|
||||
// a limit parallel requests would each dial their own. A host that answers over
|
||||
// h1 moves to a transport with more, since h1 carries one request at a time
|
||||
// Use one h2 connection per host, but allow parallel h1 connections.
|
||||
type secureTransport struct {
|
||||
h2, h1 http.RoundTripper
|
||||
h1Hosts *sync.Map
|
||||
@@ -355,162 +382,153 @@ func (t *secureTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func (t *secureTransport) CloseIdleConnections() {
|
||||
closeIdleTransport(t.h2)
|
||||
closeIdleTransport(t.h1)
|
||||
}
|
||||
|
||||
var errSessionClosed = errors.New("the session is closed")
|
||||
|
||||
// connPool hands the sessions of a storage the connections of XMUX, each a
|
||||
// client of its own made by newClient
|
||||
// XMUX selects a lease once, not repeatedly while looking for a connection.
|
||||
// Running references cover both the session and any response bodies still open.
|
||||
type connPool struct {
|
||||
mu sync.Mutex
|
||||
xmux *splithttp.XmuxManager
|
||||
}
|
||||
|
||||
func newConnPool(config *splithttp.XmuxConfig, newClient func(connCtx context.Context) *http.Client) *connPool {
|
||||
var xmuxConfig splithttp.XmuxConfig
|
||||
if config != nil {
|
||||
xmuxConfig = *config
|
||||
}
|
||||
return &connPool{xmux: splithttp.NewXmuxManager(xmuxConfig, func() splithttp.XmuxConn {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
return &poolConn{next: newClient(ctx).Transport, cancel: cancel}
|
||||
})}
|
||||
}
|
||||
|
||||
// poolConn is a connection of XMUX, which closes once XMUX drops it and the
|
||||
// requests on it end
|
||||
type poolConn struct {
|
||||
next http.RoundTripper
|
||||
mu sync.Mutex
|
||||
mux *splithttp.XmuxManager
|
||||
media []*splithttp.XmuxManager // Drive-only, one connection per round-robin lane
|
||||
next int
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
|
||||
mu sync.Mutex
|
||||
inflight int
|
||||
closing bool
|
||||
}
|
||||
|
||||
func (c *poolConn) IsClosed() bool {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.closing
|
||||
type poolConn struct {
|
||||
transport http.RoundTripper
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
stop func() bool
|
||||
}
|
||||
|
||||
func (c *poolConn) IsClosed() bool { return c.ctx.Err() != nil }
|
||||
|
||||
func (c *poolConn) Close() error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.closing = true
|
||||
if c.inflight == 0 {
|
||||
c.cancel()
|
||||
}
|
||||
c.cancel()
|
||||
c.stop()
|
||||
closeIdleTransport(c.transport)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *poolConn) done() {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.inflight--
|
||||
if c.closing && c.inflight == 0 {
|
||||
c.cancel()
|
||||
// driveMediaConns is the number of Drive media connections: XMUX
|
||||
// maxConnections when set, else 4. One Google connection carries only a
|
||||
// fraction of a link, so media requests are spread over these.
|
||||
func driveMediaConns(x *splithttp.XmuxConfig) int32 {
|
||||
if x != nil && x.MaxConnections != nil && x.MaxConnections.To > 0 {
|
||||
return x.MaxConnections.To
|
||||
}
|
||||
return 4
|
||||
}
|
||||
|
||||
// Positive conns gives Drive round-robin lanes; other backends keep one manager.
|
||||
func newConnPool(config *splithttp.XmuxConfig, conns int32, newClient func(context.Context) *http.Client) *connPool {
|
||||
if config == nil {
|
||||
config = &splithttp.XmuxConfig{}
|
||||
}
|
||||
maxConns := config.MaxConnections
|
||||
if conns > 0 {
|
||||
maxConns = &splithttp.RangeConfig{From: 1, To: 1}
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
p := &connPool{ctx: ctx, cancel: cancel}
|
||||
newConn := func() splithttp.XmuxConn {
|
||||
ctx, cancel := context.WithCancel(p.ctx)
|
||||
c := &poolConn{ctx: ctx, cancel: cancel, transport: newClient(ctx).Transport}
|
||||
c.stop = context.AfterFunc(ctx, func() { closeIdleTransport(c.transport) })
|
||||
return c
|
||||
}
|
||||
newMux := func() *splithttp.XmuxManager {
|
||||
return splithttp.NewXmuxManager(splithttp.XmuxConfig{
|
||||
MaxConnections: maxConns, MaxConcurrency: config.MaxConcurrency,
|
||||
CMaxReuseTimes: config.CMaxReuseTimes, HMaxRequestTimes: config.HMaxRequestTimes,
|
||||
HMaxReusableSecs: config.HMaxReusableSecs, HKeepAlivePeriod: config.HKeepAlivePeriod,
|
||||
}, newConn)
|
||||
}
|
||||
p.mux = newMux()
|
||||
for i := int32(0); i < conns; i++ {
|
||||
mux := p.mux
|
||||
if i > 0 {
|
||||
mux = newMux()
|
||||
}
|
||||
p.media = append(p.media, mux)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *connPool) Close() {
|
||||
if p != nil {
|
||||
p.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
// roundTrip sends a request counted in inflight by the caller
|
||||
func (c *poolConn) roundTrip(r *http.Request) (*http.Response, error) {
|
||||
resp, err := c.next.RoundTrip(r)
|
||||
if err != nil {
|
||||
c.done()
|
||||
return nil, err
|
||||
}
|
||||
resp.Body = &doneBody{ReadCloser: resp.Body, done: sync.OnceFunc(c.done)}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
type doneBody struct {
|
||||
io.ReadCloser
|
||||
done func()
|
||||
}
|
||||
|
||||
func (b *doneBody) Close() error {
|
||||
err := b.ReadCloser.Close()
|
||||
b.done()
|
||||
return err
|
||||
}
|
||||
|
||||
// a connection that has not answered yet is given this long before its
|
||||
// timeouts retire it, so that a dial or handshake is not cut short again
|
||||
var stalledGrace = 12 * time.Second
|
||||
|
||||
// sessionTransport sends the requests of one session over a connection of
|
||||
// XMUX, and over another once that one has no requests or time left
|
||||
type sessionTransport struct {
|
||||
pool *connPool
|
||||
|
||||
mu sync.Mutex
|
||||
client *splithttp.XmuxClient
|
||||
closed bool
|
||||
slowAt, retiredAt time.Time
|
||||
movedAt time.Time
|
||||
takenAt time.Time
|
||||
served bool
|
||||
pool *connPool
|
||||
client *splithttp.XmuxClient // guarded by pool.mu
|
||||
closed bool
|
||||
// spread selects a pool connection per request instead of pinning one.
|
||||
spread bool
|
||||
}
|
||||
|
||||
func (t *sessionTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
t.mu.Lock()
|
||||
if t.closed {
|
||||
t.mu.Unlock()
|
||||
p := t.pool
|
||||
p.mu.Lock()
|
||||
if t.closed || p.ctx.Err() != nil || r.Context().Err() != nil {
|
||||
p.mu.Unlock()
|
||||
if r.Body != nil {
|
||||
r.Body.Close()
|
||||
}
|
||||
if err := r.Context().Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, errSessionClosed
|
||||
}
|
||||
client := t.client
|
||||
if client == nil || client.XmuxConn.IsClosed() || client.LeftRequests.Add(-1) < 0 || !client.UnreusableAt.IsZero() && time.Now().After(client.UnreusableAt) {
|
||||
t.pool.mu.Lock()
|
||||
t.client = t.pool.xmux.GetXmuxClient(r.Context())
|
||||
t.pool.mu.Unlock()
|
||||
t.client.AddRunning()
|
||||
t.client.LeftRequests.Add(-1)
|
||||
if client != nil {
|
||||
client.DoneRunning()
|
||||
t.movedAt = time.Now()
|
||||
c := t.client
|
||||
if t.spread {
|
||||
mux := p.mux
|
||||
if len(p.media) != 0 {
|
||||
mux = p.media[p.next]
|
||||
p.next = (p.next + 1) % len(p.media)
|
||||
}
|
||||
client = t.client
|
||||
t.takenAt, t.served = time.Now(), false
|
||||
}
|
||||
// counted under mu, or another request of the session that moves on could
|
||||
// close the connection before this one is sent
|
||||
conn := client.XmuxConn.(*poolConn)
|
||||
conn.mu.Lock()
|
||||
conn.inflight++
|
||||
conn.mu.Unlock()
|
||||
t.mu.Unlock()
|
||||
resp, err := conn.roundTrip(r)
|
||||
if err == nil {
|
||||
t.mu.Lock()
|
||||
if t.client == client {
|
||||
t.served = true
|
||||
c = mux.GetXmuxClient(r.Context())
|
||||
} else if c == nil || c.XmuxConn.IsClosed() || c.LeftRequests.Load() <= 0 || (!c.UnreusableAt.IsZero() && time.Now().After(c.UnreusableAt)) {
|
||||
if c != nil {
|
||||
c.DoneRunning()
|
||||
}
|
||||
t.mu.Unlock()
|
||||
c = p.mux.GetXmuxClient(r.Context())
|
||||
c.AddRunning()
|
||||
t.client = c
|
||||
}
|
||||
return resp, err
|
||||
c.LeftRequests.Add(-1)
|
||||
c.AddRunning()
|
||||
p.mu.Unlock()
|
||||
resp, err := c.XmuxConn.(*poolConn).transport.RoundTrip(r)
|
||||
if err != nil {
|
||||
c.DoneRunning()
|
||||
return nil, err
|
||||
}
|
||||
resp.Body = &leasedBody{ReadCloser: resp.Body, release: sync.OnceFunc(c.DoneRunning)}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (t *sessionTransport) stalled(began time.Time) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if began.Before(t.movedAt) {
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
if !t.served && now.Sub(t.takenAt) < stalledGrace {
|
||||
return
|
||||
}
|
||||
slow := now.Sub(t.slowAt) < 3*time.Second
|
||||
t.slowAt = now
|
||||
if !slow || t.client == nil || now.Sub(t.retiredAt) < 2*time.Second {
|
||||
return
|
||||
}
|
||||
t.retiredAt = now
|
||||
t.client.XmuxConn.(*poolConn).Close()
|
||||
type leasedBody struct {
|
||||
io.ReadCloser
|
||||
release func()
|
||||
}
|
||||
|
||||
func (b *leasedBody) Close() error {
|
||||
defer b.release()
|
||||
return b.ReadCloser.Close()
|
||||
}
|
||||
|
||||
func (t *sessionTransport) Close() {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.pool.mu.Lock()
|
||||
defer t.pool.mu.Unlock()
|
||||
t.closed = true
|
||||
if t.client != nil {
|
||||
t.client.DoneRunning()
|
||||
|
||||
@@ -15,21 +15,31 @@ var placeholderAddr = &net.TCPAddr{IP: net.IP{127, 0, 0, 1}, Port: 0}
|
||||
// Conn is a session in segments, walWriter and walReader, or in slots,
|
||||
// slotWriter and slotReader
|
||||
type Conn struct {
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
writer io.WriteCloser
|
||||
writer connWriter
|
||||
reader chunkReader
|
||||
onClose func()
|
||||
|
||||
readMu sync.Mutex
|
||||
readBuf []byte
|
||||
|
||||
deadlineMu sync.Mutex
|
||||
readDeadline time.Time
|
||||
writeDeadline time.Time
|
||||
readDeadline *pipeDeadline
|
||||
writeDeadline *pipeDeadline
|
||||
closing chan struct{}
|
||||
|
||||
publishWG sync.WaitGroup // registered before Dial exposes the connection
|
||||
closeOnce sync.Once
|
||||
closeErr error
|
||||
}
|
||||
|
||||
type connWriter interface {
|
||||
io.WriteCloser
|
||||
// writeUntil returns errWriteStopped, with the bytes it took, once either
|
||||
// channel is closed
|
||||
writeUntil(p []byte, deadline, closing <-chan struct{}) (int, error)
|
||||
}
|
||||
|
||||
type chunkReader interface {
|
||||
// chunks is closed when there are no more, then Err says why
|
||||
chunks() <-chan []byte
|
||||
@@ -37,54 +47,99 @@ type chunkReader interface {
|
||||
Wake()
|
||||
}
|
||||
|
||||
func newConn(ctx context.Context, storage Storage, writePrefix, readPrefix string, p params, onClose func()) *Conn {
|
||||
func newConn(ctx context.Context, storage Storage, writePrefix, readPrefix string, p params, discard bool, onClose func()) *Conn {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
return &Conn{
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
writer: newWALWriter(ctx, storage, writePrefix, p),
|
||||
reader: newWALReader(ctx, storage, readPrefix, p),
|
||||
reader: newWALReader(ctx, storage, readPrefix, p, discard),
|
||||
onClose: onClose,
|
||||
|
||||
readDeadline: newPipeDeadline(),
|
||||
writeDeadline: newPipeDeadline(),
|
||||
closing: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
func newSlotConn(ctx context.Context, store slotStore, write, read slotTable, p params, first []byte, onClose func()) *Conn {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
ctx, fail := context.WithCancelCause(ctx)
|
||||
closing := make(chan struct{})
|
||||
return &Conn{
|
||||
cancel: cancel,
|
||||
writer: newSlotWriter(ctx, store, write, p),
|
||||
reader: newSlotReader(ctx, store, read, p, first),
|
||||
ctx: ctx,
|
||||
cancel: func() { fail(context.Canceled) },
|
||||
writer: newSlotWriter(ctx, fail, store, write, p),
|
||||
reader: newSlotReader(ctx, fail, store, read, p, first, closing),
|
||||
onClose: onClose,
|
||||
|
||||
readDeadline: newPipeDeadline(),
|
||||
writeDeadline: newPipeDeadline(),
|
||||
closing: closing,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Conn) Read(b []byte) (int, error) {
|
||||
if len(c.readBuf) == 0 {
|
||||
data, err := c.receive()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
c.readBuf = data
|
||||
c.readMu.Lock()
|
||||
defer c.readMu.Unlock()
|
||||
|
||||
select {
|
||||
case <-c.closing:
|
||||
return 0, io.ErrClosedPipe
|
||||
default:
|
||||
}
|
||||
select {
|
||||
case <-c.readDeadline.wait():
|
||||
return 0, os.ErrDeadlineExceeded
|
||||
default:
|
||||
}
|
||||
if len(b) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
if len(c.readBuf) > 0 {
|
||||
// Check state again before consuming buffered bytes: deadline or Close
|
||||
// may have happened after we filled readBuf but before this Read call.
|
||||
select {
|
||||
case <-c.closing:
|
||||
return 0, io.ErrClosedPipe
|
||||
default:
|
||||
}
|
||||
select {
|
||||
case <-c.readDeadline.wait():
|
||||
return 0, os.ErrDeadlineExceeded
|
||||
default:
|
||||
}
|
||||
n := copy(b, c.readBuf)
|
||||
c.readBuf = c.readBuf[n:]
|
||||
if len(c.readBuf) == 0 {
|
||||
c.readBuf = nil
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
data, err := c.receive()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
c.readBuf = data
|
||||
n := copy(b, c.readBuf)
|
||||
c.readBuf = c.readBuf[n:]
|
||||
if len(c.readBuf) == 0 {
|
||||
c.readBuf = nil
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (c *Conn) receive() ([]byte, error) {
|
||||
deadline := c.getDeadline(true)
|
||||
if deadline.IsZero() {
|
||||
data, ok := <-c.reader.chunks()
|
||||
if !ok {
|
||||
return nil, c.reader.Err()
|
||||
}
|
||||
return data, nil
|
||||
select {
|
||||
case <-c.closing:
|
||||
return nil, io.ErrClosedPipe
|
||||
default:
|
||||
}
|
||||
|
||||
if !time.Now().Before(deadline) {
|
||||
deadline := c.readDeadline.wait()
|
||||
select {
|
||||
case <-deadline:
|
||||
return nil, os.ErrDeadlineExceeded
|
||||
default:
|
||||
}
|
||||
timer := time.NewTimer(time.Until(deadline))
|
||||
defer timer.Stop()
|
||||
|
||||
select {
|
||||
case data, ok := <-c.reader.chunks():
|
||||
@@ -92,17 +147,36 @@ func (c *Conn) receive() ([]byte, error) {
|
||||
return nil, c.reader.Err()
|
||||
}
|
||||
return data, nil
|
||||
case <-timer.C:
|
||||
case <-deadline:
|
||||
return nil, os.ErrDeadlineExceeded
|
||||
case <-c.closing:
|
||||
return nil, io.ErrClosedPipe
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Conn) Write(b []byte) (int, error) {
|
||||
if deadline := c.getDeadline(false); !deadline.IsZero() && !time.Now().Before(deadline) {
|
||||
return 0, os.ErrDeadlineExceeded
|
||||
select {
|
||||
case <-c.closing:
|
||||
return 0, io.ErrClosedPipe
|
||||
default:
|
||||
}
|
||||
n, err := c.writer.Write(b)
|
||||
if err == nil {
|
||||
deadline := c.writeDeadline.wait()
|
||||
select {
|
||||
case <-deadline:
|
||||
return 0, os.ErrDeadlineExceeded
|
||||
default:
|
||||
}
|
||||
|
||||
n, err := c.writer.writeUntil(b, deadline, c.closing)
|
||||
if err == errWriteStopped {
|
||||
select {
|
||||
case <-c.closing:
|
||||
err = io.ErrClosedPipe
|
||||
default:
|
||||
err = os.ErrDeadlineExceeded
|
||||
}
|
||||
}
|
||||
if n > 0 {
|
||||
c.reader.Wake()
|
||||
}
|
||||
return n, err
|
||||
@@ -110,15 +184,70 @@ func (c *Conn) Write(b []byte) (int, error) {
|
||||
|
||||
func (c *Conn) Close() error {
|
||||
c.closeOnce.Do(func() {
|
||||
c.closeErr = c.writer.Close()
|
||||
c.cancel()
|
||||
if c.onClose != nil {
|
||||
c.onClose()
|
||||
close(c.closing)
|
||||
c.readDeadline.stop()
|
||||
c.writeDeadline.stop()
|
||||
done := make(chan struct{})
|
||||
var result error
|
||||
started := time.Now()
|
||||
progress := func() time.Time { return started }
|
||||
if writer, ok := c.writer.(*slotWriter); ok {
|
||||
writer.markProgress()
|
||||
reader := c.reader.(*slotReader)
|
||||
progress = func() time.Time {
|
||||
last := writer.closeProgress()
|
||||
// Inbound activity must not hide a stalled outbound writer.
|
||||
if credit := reader.drainCredit.Load(); isClosedChan(writer.done) && credit != nil && credit.After(last) {
|
||||
return *credit
|
||||
}
|
||||
return last
|
||||
}
|
||||
}
|
||||
go func() {
|
||||
result = c.closeOrdered(c.writer.Close())
|
||||
close(done)
|
||||
}()
|
||||
c.closeErr = waitCloseProgress(done, progress)
|
||||
if c.closeErr == nil {
|
||||
c.closeErr = result
|
||||
}
|
||||
c.cancel()
|
||||
})
|
||||
return c.closeErr
|
||||
}
|
||||
|
||||
func (c *Conn) closeOrdered(err error) error {
|
||||
c.publishWG.Wait()
|
||||
if err == nil {
|
||||
if writer, ok := c.writer.(interface{ Err() error }); ok {
|
||||
err = writer.Err()
|
||||
}
|
||||
}
|
||||
if reader, ok := c.reader.(*slotReader); ok && err == nil {
|
||||
// Our END says nothing about the peer's outstanding writes. Keep the
|
||||
// discard reader and its ACK worker alive through the peer's END.
|
||||
// The outer watchdog bounds this wait even if the peer never closes.
|
||||
reader.wait()
|
||||
err = context.Cause(c.ctx)
|
||||
}
|
||||
c.cancel()
|
||||
if writer, ok := c.writer.(interface{ wait() }); ok {
|
||||
writer.wait()
|
||||
}
|
||||
if reader, ok := c.reader.(interface{ wait() }); ok {
|
||||
reader.wait()
|
||||
}
|
||||
if c.onClose != nil {
|
||||
c.onClose()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Conn) Interrupt() {
|
||||
c.cancel()
|
||||
c.Close()
|
||||
}
|
||||
|
||||
func (c *Conn) LocalAddr() net.Addr {
|
||||
return placeholderAddr
|
||||
}
|
||||
@@ -127,33 +256,101 @@ func (c *Conn) RemoteAddr() net.Addr {
|
||||
return placeholderAddr
|
||||
}
|
||||
|
||||
func (c *Conn) getDeadline(read bool) time.Time {
|
||||
c.deadlineMu.Lock()
|
||||
defer c.deadlineMu.Unlock()
|
||||
if read {
|
||||
return c.readDeadline
|
||||
}
|
||||
return c.writeDeadline
|
||||
}
|
||||
|
||||
func (c *Conn) SetDeadline(t time.Time) error {
|
||||
c.deadlineMu.Lock()
|
||||
defer c.deadlineMu.Unlock()
|
||||
c.readDeadline = t
|
||||
c.writeDeadline = t
|
||||
c.readDeadline.set(t)
|
||||
c.writeDeadline.set(t)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Conn) SetReadDeadline(t time.Time) error {
|
||||
c.deadlineMu.Lock()
|
||||
defer c.deadlineMu.Unlock()
|
||||
c.readDeadline = t
|
||||
c.readDeadline.set(t)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Conn) SetWriteDeadline(t time.Time) error {
|
||||
c.deadlineMu.Lock()
|
||||
defer c.deadlineMu.Unlock()
|
||||
c.writeDeadline = t
|
||||
c.writeDeadline.set(t)
|
||||
return nil
|
||||
}
|
||||
|
||||
// pipeDeadline is a deadline whose wait channel closes when it passes. Setting
|
||||
// a new time re-arms it, so a call already waiting on the channel sees the
|
||||
// change.
|
||||
type pipeDeadline struct {
|
||||
mu sync.Mutex
|
||||
timer *time.Timer
|
||||
cancel chan struct{}
|
||||
gen uint64
|
||||
stopped bool
|
||||
}
|
||||
|
||||
func newPipeDeadline() *pipeDeadline {
|
||||
return &pipeDeadline{cancel: make(chan struct{})}
|
||||
}
|
||||
|
||||
func (d *pipeDeadline) set(t time.Time) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if d.stopped {
|
||||
return
|
||||
}
|
||||
|
||||
if d.timer != nil {
|
||||
// Stop does not join a callback that has already started; gen makes
|
||||
// that callback skip its close, so a channel is closed at most once.
|
||||
d.timer.Stop()
|
||||
d.timer = nil
|
||||
d.gen++
|
||||
}
|
||||
|
||||
closed := isClosedChan(d.cancel)
|
||||
if t.IsZero() {
|
||||
if closed {
|
||||
d.cancel = make(chan struct{})
|
||||
}
|
||||
return
|
||||
}
|
||||
if dur := time.Until(t); dur > 0 {
|
||||
if closed {
|
||||
d.cancel = make(chan struct{})
|
||||
}
|
||||
cancel, gen := d.cancel, d.gen
|
||||
d.timer = time.AfterFunc(dur, func() {
|
||||
d.mu.Lock()
|
||||
if d.gen == gen {
|
||||
close(cancel)
|
||||
}
|
||||
d.mu.Unlock()
|
||||
})
|
||||
return
|
||||
}
|
||||
if !closed {
|
||||
close(d.cancel)
|
||||
d.gen++
|
||||
}
|
||||
}
|
||||
|
||||
func (d *pipeDeadline) stop() {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if d.timer != nil {
|
||||
d.timer.Stop()
|
||||
d.timer = nil
|
||||
}
|
||||
d.gen++ // an in-flight callback must not close a channel reused later
|
||||
d.stopped = true
|
||||
}
|
||||
|
||||
func (d *pipeDeadline) wait() chan struct{} {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
return d.cancel
|
||||
}
|
||||
|
||||
func isClosedChan(c <-chan struct{}) bool {
|
||||
select {
|
||||
case <-c:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
+865
-724
File diff suppressed because it is too large
Load Diff
@@ -31,10 +31,14 @@ func (s *localStorage) resolve(name string) (string, error) {
|
||||
if clean == "/" {
|
||||
return "", errors.New("invalid object name: ", name)
|
||||
}
|
||||
if strings.HasPrefix(path.Base(clean), tempPrefix) {
|
||||
local, err := filepath.Localize(clean[1:])
|
||||
if err != nil {
|
||||
return "", errors.New("invalid object name: ", name).Base(err)
|
||||
}
|
||||
if strings.HasPrefix(filepath.Base(local), tempPrefix) {
|
||||
return "", errors.New("reserved object name: ", name)
|
||||
}
|
||||
return filepath.Join(s.root, filepath.FromSlash(clean[1:])), nil
|
||||
return filepath.Join(s.root, local), nil
|
||||
}
|
||||
|
||||
func (s *localStorage) Put(ctx context.Context, name string, data []byte) error {
|
||||
|
||||
@@ -25,6 +25,7 @@ type params struct {
|
||||
holeTimeout time.Duration
|
||||
sessionTTL time.Duration
|
||||
concurrency int
|
||||
flightBytes int // Drive media bytes in flight per direction
|
||||
}
|
||||
|
||||
func millis(value uint32, fallback time.Duration) time.Duration {
|
||||
@@ -45,7 +46,7 @@ func capped(value uint32, fallback, limit int) int {
|
||||
if value == 0 {
|
||||
return fallback
|
||||
}
|
||||
if int(value) > limit {
|
||||
if uint64(value) > uint64(limit) {
|
||||
return limit
|
||||
}
|
||||
return int(value)
|
||||
@@ -72,18 +73,19 @@ func paramsFromConfig(c *Config) params {
|
||||
// is a slotStore and only to fields the config leaves at 0; wal-based backends
|
||||
// keep the defaults above because their concurrency and flush mean other things
|
||||
func paramsForStorage(c *Config, storage Storage) params {
|
||||
p := paramsFromConfig(c)
|
||||
if _, ok := storage.(slotStore); ok {
|
||||
cc := *c
|
||||
if cc.Concurrency == 0 {
|
||||
cc.Concurrency = 64
|
||||
if c.Concurrency == 0 {
|
||||
p.concurrency = 64
|
||||
}
|
||||
if cc.FlushIntervalMs == 0 {
|
||||
cc.FlushIntervalMs = 10
|
||||
// About one large frame per media connection keeps each one busy.
|
||||
p.flightBytes = int(driveMediaConns(c.Xmux)) * slotMaxFrame
|
||||
if c.FlushIntervalMs == 0 {
|
||||
p.flushInterval = 25 * time.Millisecond
|
||||
}
|
||||
if cc.MaxPollIntervalMs == 0 {
|
||||
cc.MaxPollIntervalMs = 200
|
||||
if c.MaxPollIntervalMs == 0 {
|
||||
p.maxPollInterval = max(200*time.Millisecond, p.minPollInterval)
|
||||
}
|
||||
c = &cc
|
||||
}
|
||||
return paramsFromConfig(c)
|
||||
return p
|
||||
}
|
||||
|
||||
@@ -55,6 +55,9 @@ func ValidateS3Config(c *Config) error {
|
||||
u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || u.Opaque != "" {
|
||||
return errors.New("S3 endpoint must be an http(s) URL without credentials, query or fragment")
|
||||
}
|
||||
if host, err := httpguts.PunycodeHostPort(u.Host); err != nil || !httpguts.ValidHostHeader(host) {
|
||||
return errors.New("invalid S3 endpoint authority")
|
||||
}
|
||||
if !httpguts.ValidHeaderFieldValue(c.S3.Region) || strings.ContainsAny(c.S3.Region, "/, \t") {
|
||||
return errors.New("invalid S3 signing region")
|
||||
}
|
||||
@@ -108,6 +111,8 @@ func newS3Storage(streamSettings *internet.MemoryStreamConfig, c *Config) (*s3St
|
||||
return nil, err
|
||||
}
|
||||
base, _ := url.Parse(c.S3.Endpoint)
|
||||
// Match the ASCII authority net/http transmits before using it in SigV4.
|
||||
base.Host, _ = httpguts.PunycodeHostPort(base.Host)
|
||||
// Encode the endpoint prefix for SigV4 without turning escaped slashes into separators.
|
||||
segments := strings.Split(base.EscapedPath(), "/")
|
||||
for i, segment := range segments {
|
||||
@@ -142,7 +147,7 @@ func newS3Storage(streamSettings *internet.MemoryStreamConfig, c *Config) (*s3St
|
||||
}
|
||||
s := &s3Storage{
|
||||
s3Shared: &s3Shared{
|
||||
conns: newConnPool(c.Xmux, newClient),
|
||||
conns: newConnPool(c.Xmux, 0, newClient),
|
||||
base: *base,
|
||||
prefix: strings.TrimSuffix(c.RemoteFolder, "/") + "/",
|
||||
region: s3Region(c.S3.Region),
|
||||
@@ -278,6 +283,10 @@ func (s *s3Storage) do(ctx context.Context, method, key string, query url.Values
|
||||
case <-ctx.Done():
|
||||
return 0, nil, ctx.Err()
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
<-s.inflight
|
||||
return 0, nil, err
|
||||
}
|
||||
status, payload, after, err := s.attempt(ctx, method, key, query, body, payloadHash)
|
||||
<-s.inflight
|
||||
if ctx.Err() != nil {
|
||||
@@ -319,23 +328,29 @@ func (s *s3Storage) attempt(ctx context.Context, method, key string, query url.V
|
||||
s.sign(req, hash, time.Now())
|
||||
resp, err := s.client.Do(req)
|
||||
if err != nil {
|
||||
if resp != nil && resp.Body != nil {
|
||||
resp.Body.Close()
|
||||
}
|
||||
if urlErr, ok := err.(*url.Error); ok {
|
||||
err = urlErr.Err
|
||||
}
|
||||
return 0, nil, 0, errors.New("S3 request failed").Base(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
limit := int64(maxSegmentBytes)
|
||||
limit := int64(adapterMaxMetadataBody)
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
limit = 64 << 10
|
||||
limit = adapterMaxErrorBody
|
||||
} else if method == http.MethodGet {
|
||||
if query.Get("list-type") != "" {
|
||||
limit = adapterMaxListResponse
|
||||
} else {
|
||||
limit = adapterObjectLimit(ctx)
|
||||
}
|
||||
}
|
||||
payload, err := io.ReadAll(io.LimitReader(resp.Body, limit+1))
|
||||
payload, err := readAdapterBody(resp.Body, limit)
|
||||
if err != nil {
|
||||
return resp.StatusCode, nil, 0, errors.New("failed to read S3 response (HTTP ", resp.StatusCode, ")").Base(err)
|
||||
}
|
||||
if int64(len(payload)) > limit {
|
||||
return 0, nil, 0, errors.New("S3 response exceeds size limit")
|
||||
}
|
||||
var after time.Duration
|
||||
if raw := resp.Header.Get("Retry-After"); raw != "" {
|
||||
if seconds, err := strconv.ParseInt(raw, 10, 32); err == nil && seconds > 0 {
|
||||
|
||||
+708
-900
File diff suppressed because it is too large
Load Diff
@@ -4,21 +4,27 @@ import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
"encoding/json"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
"github.com/xtls/xray-core/transport/internet/splithttp"
|
||||
"github.com/xtls/xray-core/transport/internet/tls"
|
||||
)
|
||||
|
||||
var errNotFound = errors.New("object not found")
|
||||
|
||||
type Entry struct {
|
||||
Name string
|
||||
Inline []byte
|
||||
Name string
|
||||
Inline []byte
|
||||
created time.Time // optional backend-supplied creation time on the local clock
|
||||
}
|
||||
|
||||
// Config.Secrets for clients need only create/update/read/list permissions;
|
||||
// only server credentials need delete permission.
|
||||
type Storage interface {
|
||||
Put(ctx context.Context, name string, data []byte) error
|
||||
Get(ctx context.Context, name string) ([]byte, error)
|
||||
@@ -27,22 +33,18 @@ type Storage interface {
|
||||
Close() error
|
||||
}
|
||||
|
||||
// testStorageFactory lets tests substitute a backend for newStorage; nil in
|
||||
// production so behaviour is unchanged.
|
||||
var testStorageFactory atomic.Pointer[func(config *Config) (Storage, error)]
|
||||
|
||||
func newStorage(streamSettings *internet.MemoryStreamConfig) (Storage, error) {
|
||||
config, err := streamConfig(streamSettings)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if f := testStorageFactory.Load(); f != nil {
|
||||
return (*f)(config)
|
||||
}
|
||||
|
||||
switch config.Service {
|
||||
case "local":
|
||||
return newLocalStorage(config.RemoteFolder)
|
||||
storage, err := newLocalStorage(config.RemoteFolder)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ownedStorage(storage), nil
|
||||
case "google-drive", "Google Drive":
|
||||
return sharedStorage(streamSettings, config, func() (Storage, error) {
|
||||
return newDriveStorage(streamSettings, config)
|
||||
@@ -60,10 +62,7 @@ func newStorage(streamSettings *internet.MemoryStreamConfig) (Storage, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// sessionStorage returns the storage of one session, which takes connections
|
||||
// of XMUX until Close, with the token and cache of storage. Local storage has
|
||||
// no connections
|
||||
func sessionStorage(storage Storage) Storage {
|
||||
func rawSessionStorage(storage Storage) Storage {
|
||||
switch s := storage.(type) {
|
||||
case *driveStorage:
|
||||
return s.session()
|
||||
@@ -77,49 +76,68 @@ func sessionStorage(storage Storage) Storage {
|
||||
|
||||
var (
|
||||
sharedMu sync.Mutex
|
||||
shared = make(map[string]Storage)
|
||||
shared = make(map[string]*storageOwner)
|
||||
)
|
||||
|
||||
func shareKey(streamSettings *internet.MemoryStreamConfig, config *Config) string {
|
||||
parts := []string{config.Service, config.RemoteFolder}
|
||||
// Encode only configuration, not protobuf runtime state or transport caches.
|
||||
// JSON provides field/element boundaries (unlike NUL-joined strings), with
|
||||
// deterministic map ordering. These concrete config types contain no funcs.
|
||||
profile := struct {
|
||||
Service, Folder, Template, SecurityType, Destination string
|
||||
Secrets []string
|
||||
S3 *S3Config
|
||||
TLS *tls.Config
|
||||
Socket *internet.SocketConfig
|
||||
QUIC *internet.QuicParams
|
||||
XMUX *splithttp.XmuxConfig
|
||||
}{
|
||||
Service: config.Service, Folder: config.RemoteFolder, Secrets: config.Secrets,
|
||||
Template: config.Template, XMUX: config.Xmux,
|
||||
}
|
||||
if config.S3 != nil {
|
||||
parts = append(parts, config.S3.Endpoint, s3Region(config.S3.Region), config.S3.Bucket)
|
||||
if config.S3.PathStyle {
|
||||
parts = append(parts, "path-style")
|
||||
} else {
|
||||
parts = append(parts, "virtual-hosted-style")
|
||||
profile.S3 = &S3Config{
|
||||
Endpoint: config.S3.Endpoint, Region: s3Region(config.S3.Region),
|
||||
Bucket: config.S3.Bucket, PathStyle: config.S3.PathStyle,
|
||||
}
|
||||
}
|
||||
parts = append(parts, config.Secrets...)
|
||||
if streamSettings != nil {
|
||||
parts = append(parts, streamSettings.SecurityType)
|
||||
profile.SecurityType = streamSettings.SecurityType
|
||||
profile.TLS = tls.ConfigFromStreamSettings(streamSettings)
|
||||
profile.Socket, profile.QUIC = streamSettings.SocketSettings, streamSettings.QuicParams
|
||||
if streamSettings.Destination != nil {
|
||||
parts = append(parts, streamSettings.Destination.NetAddr())
|
||||
profile.Destination = streamSettings.Destination.String()
|
||||
}
|
||||
}
|
||||
sum := sha256.Sum256([]byte(strings.Join(parts, "\x00")))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func resetSharedStorage() {
|
||||
sharedMu.Lock()
|
||||
shared = make(map[string]Storage)
|
||||
sharedMu.Unlock()
|
||||
h := sha256.New()
|
||||
common.Must(json.NewEncoder(h).Encode(profile))
|
||||
return hex.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
|
||||
func sharedStorage(streamSettings *internet.MemoryStreamConfig, config *Config, build func() (Storage, error)) (Storage, error) {
|
||||
// Opaque masks have no immutable configuration identity. Isolate their
|
||||
// owners rather than accidentally routing one profile through another.
|
||||
if streamSettings != nil && streamSettings.FinalMask != nil {
|
||||
storage, err := build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ownedStorage(storage), nil
|
||||
}
|
||||
key := shareKey(streamSettings, config)
|
||||
|
||||
sharedMu.Lock()
|
||||
defer sharedMu.Unlock()
|
||||
|
||||
if storage, ok := shared[key]; ok {
|
||||
return storage, nil
|
||||
if owner, ok := shared[key]; ok && !owner.closed {
|
||||
owner.refs++
|
||||
return wrapStorageLease(owner, owner.root, false), nil
|
||||
}
|
||||
storage, err := build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
shared[key] = storage
|
||||
return storage, nil
|
||||
owner := &storageOwner{root: storage, key: key, refs: 1}
|
||||
shared[key] = owner
|
||||
return wrapStorageLease(owner, storage, false), nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
package xdrive
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type storageOwner struct {
|
||||
root Storage
|
||||
key string
|
||||
refs int
|
||||
closed bool
|
||||
closeOnce sync.Once
|
||||
closeErr error
|
||||
}
|
||||
|
||||
type storageLease struct {
|
||||
owner *storageOwner
|
||||
backend Storage
|
||||
session bool
|
||||
mu sync.Mutex
|
||||
closed bool
|
||||
closeErr error
|
||||
}
|
||||
|
||||
type (
|
||||
leasedStorage struct{ *storageLease }
|
||||
leasedDriveStorage struct {
|
||||
*driveStorage
|
||||
lease *storageLease
|
||||
}
|
||||
)
|
||||
|
||||
type leasedTemplateStorage struct {
|
||||
*templateStorage
|
||||
lease *storageLease
|
||||
}
|
||||
type leasedS3Storage struct {
|
||||
*s3Storage
|
||||
lease *storageLease
|
||||
}
|
||||
type leasedSlotStorage struct {
|
||||
*leasedStorage
|
||||
slotStore
|
||||
}
|
||||
|
||||
func wrapStorageLease(owner *storageOwner, backend Storage, session bool) Storage {
|
||||
lease := &storageLease{owner: owner, backend: backend, session: session}
|
||||
switch s := backend.(type) {
|
||||
case *driveStorage:
|
||||
return &leasedDriveStorage{driveStorage: s, lease: lease}
|
||||
case *templateStorage:
|
||||
return &leasedTemplateStorage{templateStorage: s, lease: lease}
|
||||
case *s3Storage:
|
||||
return &leasedS3Storage{s3Storage: s, lease: lease}
|
||||
default:
|
||||
storage := &leasedStorage{storageLease: lease}
|
||||
if slots, ok := backend.(slotStore); ok {
|
||||
return &leasedSlotStorage{leasedStorage: storage, slotStore: slots}
|
||||
}
|
||||
return storage
|
||||
}
|
||||
}
|
||||
|
||||
func ownedStorage(storage Storage) Storage {
|
||||
return wrapStorageLease(&storageOwner{root: storage, refs: 1}, storage, false)
|
||||
}
|
||||
|
||||
func (s *storageLease) storageLeaseState() *storageLease { return s }
|
||||
func (s *leasedDriveStorage) storageLeaseState() *storageLease { return s.lease }
|
||||
func (s *leasedTemplateStorage) storageLeaseState() *storageLease { return s.lease }
|
||||
func (s *leasedS3Storage) storageLeaseState() *storageLease { return s.lease }
|
||||
|
||||
func (s *leasedStorage) Put(ctx context.Context, name string, data []byte) error {
|
||||
return s.backend.Put(ctx, name, data)
|
||||
}
|
||||
|
||||
func (s *leasedStorage) Get(ctx context.Context, name string) ([]byte, error) {
|
||||
return s.backend.Get(ctx, name)
|
||||
}
|
||||
|
||||
func (s *leasedStorage) Delete(ctx context.Context, name string) error {
|
||||
return s.backend.Delete(ctx, name)
|
||||
}
|
||||
|
||||
func (s *leasedStorage) List(ctx context.Context, prefix string) ([]Entry, error) {
|
||||
return s.backend.List(ctx, prefix)
|
||||
}
|
||||
func (s *leasedDriveStorage) Close() error { return s.lease.Close() }
|
||||
func (s *leasedTemplateStorage) Close() error { return s.lease.Close() }
|
||||
func (s *leasedS3Storage) Close() error { return s.lease.Close() }
|
||||
|
||||
func (s *storageLease) Close() error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.closed {
|
||||
return s.closeErr
|
||||
}
|
||||
s.closed = true
|
||||
if s.session && s.backend != s.owner.root {
|
||||
s.closeErr = s.backend.Close()
|
||||
}
|
||||
sharedMu.Lock()
|
||||
s.owner.refs--
|
||||
final := s.owner.refs == 0 && !s.owner.closed
|
||||
if final {
|
||||
s.owner.closed = true
|
||||
if s.owner.key != "" && shared[s.owner.key] == s.owner {
|
||||
delete(shared, s.owner.key)
|
||||
}
|
||||
}
|
||||
sharedMu.Unlock()
|
||||
if final {
|
||||
if err := s.owner.close(); s.closeErr == nil {
|
||||
s.closeErr = err
|
||||
}
|
||||
}
|
||||
return s.closeErr
|
||||
}
|
||||
|
||||
func (o *storageOwner) close() error {
|
||||
o.closeOnce.Do(func() { o.closeErr = closeStorageRoot(o.root) })
|
||||
return o.closeErr
|
||||
}
|
||||
|
||||
func acquireSessionStorage(storage Storage) (Storage, error) {
|
||||
if s, ok := storage.(interface{ storageLeaseState() *storageLease }); ok {
|
||||
lease := s.storageLeaseState()
|
||||
lease.mu.Lock()
|
||||
defer lease.mu.Unlock()
|
||||
sharedMu.Lock()
|
||||
if lease.closed || lease.owner.closed {
|
||||
sharedMu.Unlock()
|
||||
return nil, errSessionClosed
|
||||
}
|
||||
lease.owner.refs++
|
||||
sharedMu.Unlock()
|
||||
return wrapStorageLease(lease.owner, rawSessionStorage(lease.owner.root), true), nil
|
||||
}
|
||||
return rawSessionStorage(storage), nil
|
||||
}
|
||||
|
||||
// Dial and spare construction transfer their acquisition to a session. A
|
||||
// listener instead keeps its acquisition and clones one lease per child.
|
||||
func transferSessionStorage(storage Storage) (Storage, error) {
|
||||
session, err := acquireSessionStorage(storage)
|
||||
if err != nil {
|
||||
storage.Close()
|
||||
return nil, err
|
||||
}
|
||||
if _, ok := storage.(interface{ storageLeaseState() *storageLease }); ok {
|
||||
storage.Close()
|
||||
}
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func holdStorageSession(storage Storage, session string) (func(), error) {
|
||||
if s, ok := storage.(interface{ holdSession(string) (func(), error) }); ok {
|
||||
return s.holdSession(session)
|
||||
}
|
||||
return func() {}, nil
|
||||
}
|
||||
|
||||
func closeStorageRoot(storage Storage) error {
|
||||
switch s := storage.(type) {
|
||||
case *templateStorage:
|
||||
s.closeTokenWorkers()
|
||||
closeStoragePool(s.conns)
|
||||
if s.client != nil {
|
||||
s.client.CloseIdleConnections()
|
||||
}
|
||||
if s.tokenClient != nil {
|
||||
s.tokenClient.CloseIdleConnections()
|
||||
}
|
||||
case *s3Storage:
|
||||
closeStoragePool(s.conns)
|
||||
if s.client != nil {
|
||||
s.client.CloseIdleConnections()
|
||||
}
|
||||
}
|
||||
return storage.Close()
|
||||
}
|
||||
|
||||
func closeStoragePool(pool *connPool) {
|
||||
if pool != nil {
|
||||
pool.Close()
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,10 @@ import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
stderrors "errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -34,13 +36,17 @@ type opTemplate struct {
|
||||
Body string `json:"body"`
|
||||
NamesRegex string `json:"namesRegex"`
|
||||
|
||||
// NextPagePath extracts a JSON token for the next list URL's query-escaped {pageToken}.
|
||||
NextPagePath string `json:"nextPagePath"`
|
||||
|
||||
// HrefPath makes the operation two-step, as in the Yandex Disk REST API: the first request
|
||||
// answers with a JSON body, the URL found at HrefPath is then called with HrefMethod (GET by
|
||||
// default), carrying the payload. The URL is used as given, with neither auth nor headers.
|
||||
HrefPath string `json:"hrefPath"`
|
||||
HrefMethod string `json:"hrefMethod"`
|
||||
|
||||
presigned bool
|
||||
presigned bool
|
||||
responseLimit int64
|
||||
}
|
||||
|
||||
type retryTemplate struct {
|
||||
@@ -78,8 +84,30 @@ type templateShared struct {
|
||||
secrets []string
|
||||
|
||||
tokenMu sync.Mutex
|
||||
tokenWG sync.WaitGroup
|
||||
tokenClosed bool
|
||||
token string
|
||||
tokenExpiry time.Time
|
||||
tokenFlight *templateTokenFlight
|
||||
}
|
||||
|
||||
type templateTokenFlight struct {
|
||||
done chan struct{}
|
||||
cancel context.CancelFunc
|
||||
waiters int
|
||||
token string
|
||||
err error
|
||||
}
|
||||
|
||||
type adapterPermanentError struct{ error }
|
||||
|
||||
func (e *adapterPermanentError) Unwrap() error { return e.error }
|
||||
|
||||
func permanentAdapterError(err error) error { return &adapterPermanentError{err} }
|
||||
|
||||
func isPermanentAdapterError(err error) bool {
|
||||
var permanent *adapterPermanentError
|
||||
return stderrors.As(err, &permanent)
|
||||
}
|
||||
|
||||
func newTemplateStorage(streamSettings *internet.MemoryStreamConfig, config *Config) (*templateStorage, error) {
|
||||
@@ -93,6 +121,9 @@ func newTemplateStorage(streamSettings *internet.MemoryStreamConfig, config *Con
|
||||
if tmpl.List.NamesRegex == "" {
|
||||
return nil, errors.New("template list needs a namesRegex")
|
||||
}
|
||||
if tmpl.List.NextPagePath != "" && !strings.Contains(tmpl.List.URL, "{pageToken}") {
|
||||
return nil, errors.New("paginated template list URL needs {pageToken}")
|
||||
}
|
||||
re, err := regexp.Compile(tmpl.List.NamesRegex)
|
||||
if err != nil {
|
||||
return nil, errors.New("bad namesRegex").Base(err)
|
||||
@@ -114,7 +145,7 @@ func newTemplateStorage(streamSettings *internet.MemoryStreamConfig, config *Con
|
||||
client := newServiceClient(context.Background(), h1Hosts, streamSettings, driveTimeout, conc)
|
||||
return &templateStorage{
|
||||
templateShared: &templateShared{
|
||||
conns: newConnPool(config.Xmux, func(connCtx context.Context) *http.Client {
|
||||
conns: newConnPool(config.Xmux, 0, func(connCtx context.Context) *http.Client {
|
||||
return newServiceClient(connCtx, h1Hosts, streamSettings, driveTimeout, conc)
|
||||
}),
|
||||
tmpl: tmpl,
|
||||
@@ -139,7 +170,28 @@ func (s *templateStorage) session() Storage {
|
||||
}
|
||||
}
|
||||
|
||||
const maxTemplateConcurrency = 256
|
||||
const (
|
||||
maxTemplateConcurrency = 256
|
||||
adapterMaxListResponse = 32 << 20
|
||||
adapterMaxMetadataBody = 1 << 20
|
||||
adapterMaxErrorBody = 64 << 10
|
||||
)
|
||||
|
||||
func adapterObjectLimit(ctx context.Context) int64 {
|
||||
limit := int64(maxSegmentBytes)
|
||||
if v, ok := ctx.Value(maxBodyKey{}).(int64); ok && v > 0 {
|
||||
limit = min(limit, v)
|
||||
}
|
||||
return limit
|
||||
}
|
||||
|
||||
func readAdapterBody(body io.Reader, limit int64) ([]byte, error) {
|
||||
payload, err := io.ReadAll(io.LimitReader(body, limit+1))
|
||||
if int64(len(payload)) > limit {
|
||||
return nil, permanentAdapterError(errors.New("adapter response exceeds the ", limit, " byte cap"))
|
||||
}
|
||||
return payload, err
|
||||
}
|
||||
|
||||
func (s *templateStorage) baseVars() map[string]string {
|
||||
vars := map[string]string{"folder": s.folder}
|
||||
@@ -218,51 +270,123 @@ func (s *templateStorage) authHeaders(ctx context.Context, vars map[string]strin
|
||||
enc := base64.StdEncoding.EncodeToString([]byte(user + ":" + pass))
|
||||
return map[string]string{"Authorization": "Basic " + enc}, nil
|
||||
default:
|
||||
return nil, errors.New("unsupported auth type: ", s.tmpl.Auth.Type)
|
||||
return nil, permanentAdapterError(errors.New("unsupported auth type: ", s.tmpl.Auth.Type))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *templateStorage) accessToken(ctx context.Context) (string, error) {
|
||||
s.tokenMu.Lock()
|
||||
defer s.tokenMu.Unlock()
|
||||
|
||||
if s.token != "" && time.Now().Before(s.tokenExpiry) {
|
||||
return s.token, nil
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
form := make(map[string]string, len(s.tmpl.Auth.Form))
|
||||
vars := s.baseVars()
|
||||
values := strings.Builder{}
|
||||
first := true
|
||||
for k, v := range s.tmpl.Auth.Form {
|
||||
form[k] = subst(v, vars)
|
||||
if !first {
|
||||
values.WriteByte('&')
|
||||
s.tokenMu.Lock()
|
||||
if s.tokenClosed {
|
||||
s.tokenMu.Unlock()
|
||||
return "", context.Canceled
|
||||
}
|
||||
if s.token != "" && time.Now().Before(s.tokenExpiry) {
|
||||
token := s.token
|
||||
s.tokenMu.Unlock()
|
||||
return token, nil
|
||||
}
|
||||
f := s.tokenFlight
|
||||
if f == nil {
|
||||
fetchCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), driveTimeout)
|
||||
f = &templateTokenFlight{done: make(chan struct{}), cancel: cancel}
|
||||
s.tokenFlight = f
|
||||
s.tokenWG.Add(1)
|
||||
go func() {
|
||||
defer s.tokenWG.Done()
|
||||
token, lifetime, err := s.fetchTemplateToken(fetchCtx)
|
||||
cancel()
|
||||
s.tokenMu.Lock()
|
||||
f.token, f.err = token, err
|
||||
if s.tokenFlight == f {
|
||||
s.tokenFlight = nil
|
||||
if err == nil {
|
||||
s.token = token
|
||||
s.tokenExpiry = time.Now().Add(lifetime)
|
||||
}
|
||||
}
|
||||
close(f.done)
|
||||
s.tokenMu.Unlock()
|
||||
}()
|
||||
}
|
||||
f.waiters++
|
||||
s.tokenMu.Unlock()
|
||||
defer func() {
|
||||
s.tokenMu.Lock()
|
||||
f.waiters--
|
||||
if f.waiters == 0 && s.tokenFlight == f {
|
||||
s.tokenFlight = nil
|
||||
f.cancel()
|
||||
}
|
||||
first = false
|
||||
values.WriteString(k)
|
||||
values.WriteByte('=')
|
||||
values.WriteString(form[k])
|
||||
s.tokenMu.Unlock()
|
||||
}()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return "", ctx.Err()
|
||||
case <-f.done:
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return f.token, f.err
|
||||
}
|
||||
}
|
||||
|
||||
func (s *templateStorage) closeTokenWorkers() {
|
||||
s.tokenMu.Lock()
|
||||
s.tokenClosed = true
|
||||
if f := s.tokenFlight; f != nil {
|
||||
s.tokenFlight = nil
|
||||
f.cancel()
|
||||
}
|
||||
s.tokenMu.Unlock()
|
||||
s.tokenWG.Wait()
|
||||
}
|
||||
|
||||
func (s *templateStorage) fetchTemplateToken(ctx context.Context) (string, time.Duration, error) {
|
||||
form := make(url.Values, len(s.tmpl.Auth.Form))
|
||||
vars := s.baseVars()
|
||||
for k, v := range s.tmpl.Auth.Form {
|
||||
form.Add(k, subst(v, vars))
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.tmpl.Auth.TokenURL,
|
||||
strings.NewReader(values.String()))
|
||||
strings.NewReader(form.Encode()))
|
||||
if err != nil {
|
||||
return "", errors.New("failed to build the token request").Base(err)
|
||||
return "", 0, permanentAdapterError(errors.New("failed to build the token request").Base(err))
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
if req.URL.Scheme != "http" && req.URL.Scheme != "https" || req.URL.Host == "" {
|
||||
return "", 0, permanentAdapterError(errors.New("token URL must be an http(s) URL with an authority"))
|
||||
}
|
||||
resp, err := s.tokenClient.Do(req)
|
||||
if err != nil {
|
||||
return "", errors.New("failed to fetch the token").Base(err)
|
||||
if resp != nil && resp.Body != nil {
|
||||
resp.Body.Close()
|
||||
}
|
||||
return "", 0, errors.New("failed to fetch the token").Base(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
payload, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
limit := int64(adapterMaxMetadataBody)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
limit = adapterMaxErrorBody
|
||||
}
|
||||
payload, err := readAdapterBody(resp.Body, limit)
|
||||
if err != nil {
|
||||
return "", errors.New("failed to read the token response").Base(err)
|
||||
readErr := errors.New("failed to read the token response").Base(err)
|
||||
if resp.StatusCode >= 400 && resp.StatusCode < 500 && resp.StatusCode != http.StatusRequestTimeout && resp.StatusCode != http.StatusTooManyRequests {
|
||||
return "", 0, permanentAdapterError(readErr)
|
||||
}
|
||||
return "", 0, readErr
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", errors.New("the token endpoint answered ", resp.StatusCode, ": ", string(payload))
|
||||
err := errors.New("the token endpoint answered ", resp.StatusCode)
|
||||
if resp.StatusCode >= 400 && resp.StatusCode < 500 && resp.StatusCode != http.StatusRequestTimeout && resp.StatusCode != http.StatusTooManyRequests {
|
||||
return "", 0, permanentAdapterError(err)
|
||||
}
|
||||
return "", 0, err
|
||||
}
|
||||
|
||||
path := s.tmpl.Auth.TokenPath
|
||||
@@ -271,7 +395,7 @@ func (s *templateStorage) accessToken(ctx context.Context) (string, error) {
|
||||
}
|
||||
token := jsonString(payload, path)
|
||||
if token == "" {
|
||||
return "", errors.New("the token response has no token at ", path)
|
||||
return "", 0, permanentAdapterError(errors.New("the token response has no token at ", path))
|
||||
}
|
||||
|
||||
lifetime := int64(3600)
|
||||
@@ -280,12 +404,11 @@ func (s *templateStorage) accessToken(ctx context.Context) (string, error) {
|
||||
lifetime = n
|
||||
}
|
||||
}
|
||||
lifetime = min(lifetime, int64(365*24*60*60))
|
||||
if lifetime > 60 {
|
||||
lifetime -= 60
|
||||
}
|
||||
s.token = token
|
||||
s.tokenExpiry = time.Now().Add(time.Duration(lifetime) * time.Second)
|
||||
return s.token, nil
|
||||
return token, time.Duration(lifetime) * time.Second, nil
|
||||
}
|
||||
|
||||
func (s *templateStorage) invalidateToken() {
|
||||
@@ -304,6 +427,9 @@ func (s *templateStorage) do(ctx context.Context, op *opTemplate, vars map[strin
|
||||
}
|
||||
|
||||
for attempt := 0; attempt < driveMaxAttempts; attempt++ {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
if attempt > 0 {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
@@ -320,6 +446,12 @@ func (s *templateStorage) do(ctx context.Context, op *opTemplate, vars map[strin
|
||||
if !op.presigned {
|
||||
headers, err := s.authHeaders(ctx, vars)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return 0, nil, ctx.Err()
|
||||
}
|
||||
if isPermanentAdapterError(err) {
|
||||
return 0, nil, err
|
||||
}
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
@@ -351,20 +483,50 @@ func (s *templateStorage) do(ctx context.Context, op *opTemplate, vars map[strin
|
||||
case <-ctx.Done():
|
||||
return 0, nil, ctx.Err()
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
<-s.inflight
|
||||
return 0, nil, err
|
||||
}
|
||||
resp, err := s.client.Do(req)
|
||||
<-s.inflight
|
||||
if err != nil {
|
||||
if resp != nil && resp.Body != nil {
|
||||
resp.Body.Close()
|
||||
}
|
||||
<-s.inflight
|
||||
if ctx.Err() != nil {
|
||||
return 0, nil, ctx.Err()
|
||||
}
|
||||
lastErr = errors.New("request failed").Base(err)
|
||||
if errors.Cause(err) == errSessionClosed {
|
||||
return 0, nil, lastErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
payload, err := io.ReadAll(resp.Body)
|
||||
limit := op.responseLimit
|
||||
if limit <= 0 {
|
||||
switch op {
|
||||
case &s.tmpl.Get:
|
||||
limit = adapterObjectLimit(ctx)
|
||||
case &s.tmpl.List:
|
||||
limit = adapterMaxListResponse
|
||||
default:
|
||||
limit = adapterMaxMetadataBody
|
||||
}
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
limit = adapterMaxErrorBody
|
||||
} else if op.HrefPath != "" {
|
||||
limit = adapterMaxMetadataBody
|
||||
}
|
||||
payload, err := readAdapterBody(resp.Body, limit)
|
||||
resp.Body.Close()
|
||||
<-s.inflight
|
||||
if ctx.Err() != nil {
|
||||
return 0, nil, ctx.Err()
|
||||
}
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return 0, nil, ctx.Err()
|
||||
if isPermanentAdapterError(err) {
|
||||
return 0, nil, err
|
||||
}
|
||||
lastErr = errors.New("failed to read response").Base(err)
|
||||
continue
|
||||
@@ -397,7 +559,14 @@ func (s *templateStorage) run(ctx context.Context, op *opTemplate, vars map[stri
|
||||
if href == "" {
|
||||
return 0, nil, errors.New("the response has no href at ", op.HrefPath)
|
||||
}
|
||||
return s.do(ctx, &opTemplate{Method: op.HrefMethod, URL: href, presigned: true}, vars, body)
|
||||
limit := int64(adapterMaxMetadataBody)
|
||||
switch op {
|
||||
case &s.tmpl.Get:
|
||||
limit = adapterObjectLimit(ctx)
|
||||
case &s.tmpl.List:
|
||||
limit = adapterMaxListResponse
|
||||
}
|
||||
return s.do(ctx, &opTemplate{Method: op.HrefMethod, URL: href, presigned: true, responseLimit: limit}, vars, body)
|
||||
}
|
||||
|
||||
func (s *templateStorage) Put(ctx context.Context, name string, data []byte) error {
|
||||
@@ -438,10 +607,9 @@ func (s *templateStorage) Get(ctx context.Context, name string) ([]byte, error)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *templateStorage) Delete(ctx context.Context, name string) error {
|
||||
func (s *templateStorage) deleteStoredObject(ctx context.Context, name string) error {
|
||||
vars := s.baseVars()
|
||||
vars["name"] = s.storedName(name)
|
||||
|
||||
vars["name"] = name
|
||||
status, payload, err := s.run(ctx, &s.tmpl.Delete, vars, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -452,53 +620,100 @@ func (s *templateStorage) Delete(ctx context.Context, name string) error {
|
||||
return errors.New("delete of ", name, " answered ", status, ": ", string(payload))
|
||||
}
|
||||
|
||||
func (s *templateStorage) List(ctx context.Context, prefix string) ([]Entry, error) {
|
||||
vars := s.baseVars()
|
||||
flat := s.storedName(prefix)
|
||||
vars["prefix"] = flat
|
||||
|
||||
status, payload, err := s.run(ctx, &s.tmpl.List, vars, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if status == http.StatusNotFound {
|
||||
return nil, nil
|
||||
}
|
||||
if status < 200 || status >= 300 {
|
||||
return nil, errors.New("list of ", prefix, " answered ", status, ": ", string(payload))
|
||||
}
|
||||
|
||||
matches := s.tmpl.names.FindAllStringSubmatch(string(payload), -1)
|
||||
func (s *templateStorage) Delete(ctx context.Context, name string) error {
|
||||
flat := s.storedName(name)
|
||||
if !s.tmpl.Flatten {
|
||||
entries := make([]Entry, 0, len(matches))
|
||||
for _, m := range matches {
|
||||
entries = append(entries, Entry{Name: m[1]})
|
||||
}
|
||||
return entries, nil
|
||||
return s.deleteStoredObject(ctx, flat)
|
||||
}
|
||||
|
||||
want := flat + flatSeparator
|
||||
seen := make(map[string]bool, len(matches))
|
||||
entries := make([]Entry, 0, len(matches))
|
||||
for _, m := range matches {
|
||||
name := m[1]
|
||||
if !strings.HasPrefix(name, want) {
|
||||
continue
|
||||
seen := make(map[string]bool)
|
||||
var descendants []string
|
||||
// Finish pagination before deleting so offset-based listings cannot skip shifted entries.
|
||||
if err := s.listStoredNames(ctx, want, func(name string) {
|
||||
if strings.HasPrefix(name, want) && len(name) > len(want) && !seen[name] {
|
||||
seen[name] = true
|
||||
descendants = append(descendants, name)
|
||||
}
|
||||
rest := strings.TrimPrefix(name, want)
|
||||
if rest == "" {
|
||||
continue
|
||||
}
|
||||
if cut := strings.Index(rest, flatSeparator); cut >= 0 {
|
||||
rest = rest[:cut]
|
||||
}
|
||||
if seen[rest] {
|
||||
continue
|
||||
}
|
||||
seen[rest] = true
|
||||
entries = append(entries, Entry{Name: rest})
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return entries, nil
|
||||
for _, name := range descendants {
|
||||
if err := s.deleteStoredObject(ctx, name); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return s.deleteStoredObject(ctx, flat)
|
||||
}
|
||||
|
||||
func (s *templateStorage) listStoredNames(ctx context.Context, prefix string, visit func(string)) error {
|
||||
vars := s.baseVars()
|
||||
vars["prefix"] = prefix
|
||||
vars["pageToken"] = ""
|
||||
seen := make(map[string]bool)
|
||||
for {
|
||||
status, payload, err := s.run(ctx, &s.tmpl.List, vars, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if status == http.StatusNotFound && vars["pageToken"] == "" {
|
||||
return nil
|
||||
}
|
||||
if status < 200 || status >= 300 {
|
||||
return errors.New("list of ", prefix, " answered ", status, ": ", string(payload))
|
||||
}
|
||||
var token string
|
||||
if s.tmpl.List.NextPagePath != "" {
|
||||
if !json.Valid(payload) {
|
||||
return permanentAdapterError(errors.New("invalid JSON in paginated template list response"))
|
||||
}
|
||||
if node := jsonWalk(payload, s.tmpl.List.NextPagePath); node != nil {
|
||||
var ok bool
|
||||
token, ok = node.(string)
|
||||
if !ok {
|
||||
return permanentAdapterError(errors.New("template list continuation token must be a string"))
|
||||
}
|
||||
}
|
||||
if token != "" && seen[token] {
|
||||
return permanentAdapterError(errors.New("template list pagination did not advance"))
|
||||
}
|
||||
}
|
||||
for _, match := range s.tmpl.names.FindAllStringSubmatch(string(payload), -1) {
|
||||
visit(match[1])
|
||||
}
|
||||
if token == "" {
|
||||
return nil
|
||||
}
|
||||
seen[token] = true
|
||||
vars["pageToken"] = url.QueryEscape(token)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *templateStorage) List(ctx context.Context, prefix string) ([]Entry, error) {
|
||||
flat := s.storedName(prefix)
|
||||
want := flat + flatSeparator
|
||||
seen := make(map[string]bool)
|
||||
var entries []Entry
|
||||
err := s.listStoredNames(ctx, flat, func(name string) {
|
||||
if !s.tmpl.Flatten {
|
||||
entries = append(entries, Entry{Name: name})
|
||||
return
|
||||
}
|
||||
if !strings.HasPrefix(name, want) {
|
||||
return
|
||||
}
|
||||
name = strings.TrimPrefix(name, want)
|
||||
if name == "" {
|
||||
return
|
||||
}
|
||||
if cut := strings.Index(name, flatSeparator); cut >= 0 {
|
||||
name = name[:cut]
|
||||
}
|
||||
if !seen[name] {
|
||||
seen[name] = true
|
||||
entries = append(entries, Entry{Name: name})
|
||||
}
|
||||
})
|
||||
return entries, err
|
||||
}
|
||||
|
||||
func (s *templateStorage) Close() error {
|
||||
|
||||
@@ -46,8 +46,13 @@ type walWriter struct {
|
||||
storage Storage
|
||||
prefix string
|
||||
params
|
||||
sem chan struct{}
|
||||
wg sync.WaitGroup
|
||||
sem chan struct{}
|
||||
wg sync.WaitGroup
|
||||
flushDone chan struct{}
|
||||
stop chan struct{}
|
||||
failed chan struct{}
|
||||
closeOnce sync.Once
|
||||
closeErr error
|
||||
|
||||
mu sync.Mutex
|
||||
buf []byte
|
||||
@@ -60,37 +65,65 @@ type walWriter struct {
|
||||
|
||||
func newWALWriter(ctx context.Context, storage Storage, prefix string, p params) *walWriter {
|
||||
w := &walWriter{
|
||||
ctx: ctx,
|
||||
storage: storage,
|
||||
prefix: prefix,
|
||||
params: p,
|
||||
sem: make(chan struct{}, p.concurrency),
|
||||
ctx: ctx,
|
||||
storage: storage,
|
||||
prefix: prefix,
|
||||
params: p,
|
||||
sem: make(chan struct{}, p.concurrency),
|
||||
flushDone: make(chan struct{}),
|
||||
stop: make(chan struct{}),
|
||||
failed: make(chan struct{}),
|
||||
}
|
||||
go w.flushLoop()
|
||||
return w
|
||||
}
|
||||
|
||||
func (w *walWriter) Write(p []byte) (int, error) {
|
||||
return w.writeUntil(p, nil, nil)
|
||||
}
|
||||
|
||||
// writeUntil is Write that gives up with errWriteStopped, having returned the
|
||||
// bytes it took into buf, once either channel is closed
|
||||
func (w *walWriter) writeUntil(p []byte, deadline, closing <-chan struct{}) (int, error) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
|
||||
if w.err != nil {
|
||||
return 0, w.err
|
||||
}
|
||||
if w.closed {
|
||||
if w.closed || w.ctx.Err() != nil {
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
if isClosedChan(deadline) || isClosedChan(closing) {
|
||||
return 0, errWriteStopped
|
||||
}
|
||||
|
||||
w.buf = append(w.buf, p...)
|
||||
for len(w.buf) >= w.segmentBytes {
|
||||
if err := w.flushLocked(); err != nil {
|
||||
return 0, err
|
||||
accepted := 0
|
||||
for len(p) > 0 {
|
||||
if w.err != nil {
|
||||
return accepted, w.err
|
||||
}
|
||||
if w.closed || w.ctx.Err() != nil {
|
||||
return accepted, io.ErrClosedPipe
|
||||
}
|
||||
if isClosedChan(deadline) || isClosedChan(closing) {
|
||||
return accepted, errWriteStopped
|
||||
}
|
||||
n := min(len(p), w.segmentBytes-len(w.buf))
|
||||
w.buf = append(w.buf, p[:n]...)
|
||||
accepted += n
|
||||
p = p[n:]
|
||||
for len(w.buf) >= w.segmentBytes {
|
||||
if err := w.flushLocked(deadline, closing); err != nil {
|
||||
return accepted, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return len(p), nil
|
||||
return accepted, nil
|
||||
}
|
||||
|
||||
func (w *walWriter) flushLoop() {
|
||||
defer close(w.flushDone)
|
||||
ticker := time.NewTicker(w.flushInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
@@ -98,10 +131,12 @@ func (w *walWriter) flushLoop() {
|
||||
select {
|
||||
case <-w.ctx.Done():
|
||||
return
|
||||
case <-w.stop:
|
||||
return
|
||||
case <-ticker.C:
|
||||
w.mu.Lock()
|
||||
if !w.closed && w.err == nil && len(w.buf) > 0 && w.readyToFlush() {
|
||||
w.flushLocked()
|
||||
w.flushLocked(nil, w.stop)
|
||||
}
|
||||
done := w.closed || w.err != nil
|
||||
w.mu.Unlock()
|
||||
@@ -124,13 +159,67 @@ func (w *walWriter) readyToFlush() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (w *walWriter) flushLocked() error {
|
||||
// flushLocked takes an upload permit before it cuts a segment, waiting without
|
||||
// w.mu, so a store that falls behind holds Write back instead of piling up
|
||||
// goroutines and chunks. Either stop channel, when closed, ends the wait with
|
||||
// errWriteStopped
|
||||
func (w *walWriter) flushLocked(deadline, closing <-chan struct{}) error {
|
||||
return w.flushLockedMode(deadline, closing, false)
|
||||
}
|
||||
|
||||
func (w *walWriter) flushLockedMode(deadline, closing <-chan struct{}, draining bool) error {
|
||||
if err := w.ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if w.closed && !draining {
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
if len(w.buf) == 0 {
|
||||
return nil
|
||||
}
|
||||
if w.err != nil {
|
||||
return w.err
|
||||
}
|
||||
select {
|
||||
case <-deadline:
|
||||
return errWriteStopped
|
||||
case <-closing:
|
||||
return errWriteStopped
|
||||
default:
|
||||
}
|
||||
w.mu.Unlock()
|
||||
select {
|
||||
case w.sem <- struct{}{}:
|
||||
case <-w.failed:
|
||||
w.mu.Lock()
|
||||
return w.err
|
||||
case <-w.ctx.Done():
|
||||
w.mu.Lock()
|
||||
return w.ctx.Err()
|
||||
case <-deadline:
|
||||
w.mu.Lock()
|
||||
return errWriteStopped
|
||||
case <-closing:
|
||||
w.mu.Lock()
|
||||
return errWriteStopped
|
||||
}
|
||||
w.mu.Lock()
|
||||
if err := w.ctx.Err(); err != nil {
|
||||
<-w.sem
|
||||
return err
|
||||
}
|
||||
if w.closed && !draining {
|
||||
<-w.sem
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
if isClosedChan(deadline) || isClosedChan(closing) {
|
||||
<-w.sem
|
||||
return errWriteStopped
|
||||
}
|
||||
if w.err != nil || len(w.buf) == 0 {
|
||||
<-w.sem
|
||||
return w.err
|
||||
}
|
||||
|
||||
n := len(w.buf)
|
||||
if n > w.segmentBytes {
|
||||
@@ -157,18 +246,20 @@ func (w *walWriter) flushLocked() error {
|
||||
|
||||
func (w *walWriter) upload(seq int64, chunk []byte) {
|
||||
defer w.wg.Done()
|
||||
|
||||
select {
|
||||
case w.sem <- struct{}{}:
|
||||
case <-w.ctx.Done():
|
||||
defer func() { <-w.sem }()
|
||||
if w.ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
defer func() { <-w.sem }()
|
||||
|
||||
if err := w.storage.Put(w.ctx, objectName(w.prefix, seq, segSuffix), chunk); err != nil {
|
||||
err := w.storage.Put(w.ctx, objectName(w.prefix, seq, segSuffix), chunk)
|
||||
if err == nil && requiresWALCommit(w.storage) {
|
||||
err = w.storage.Put(w.ctx, objectName(w.prefix, seq, commitSuffix), encodeWALCommit(chunk))
|
||||
}
|
||||
if err != nil && w.ctx.Err() == nil {
|
||||
w.mu.Lock()
|
||||
if w.err == nil {
|
||||
w.err = errors.New("failed to store segment").Base(err)
|
||||
close(w.failed)
|
||||
}
|
||||
w.mu.Unlock()
|
||||
w.storage.Put(w.ctx, objectName(w.prefix, seq, errSuffix), nil)
|
||||
@@ -176,27 +267,39 @@ func (w *walWriter) upload(seq int64, chunk []byte) {
|
||||
}
|
||||
|
||||
func (w *walWriter) Close() error {
|
||||
w.mu.Lock()
|
||||
if w.closed {
|
||||
w.closeOnce.Do(func() {
|
||||
w.mu.Lock()
|
||||
w.closed = true
|
||||
close(w.stop)
|
||||
w.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
w.closed = true
|
||||
for len(w.buf) > 0 && w.err == nil {
|
||||
w.flushLocked()
|
||||
}
|
||||
w.mu.Unlock()
|
||||
<-w.flushDone
|
||||
|
||||
w.wg.Wait()
|
||||
w.mu.Lock()
|
||||
var flushErr error
|
||||
for len(w.buf) > 0 && w.err == nil {
|
||||
if err := w.flushLockedMode(nil, nil, true); err != nil {
|
||||
flushErr = err
|
||||
break
|
||||
}
|
||||
}
|
||||
w.mu.Unlock()
|
||||
w.wg.Wait()
|
||||
|
||||
w.mu.Lock()
|
||||
err, seq := w.err, w.seq
|
||||
w.mu.Unlock()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return w.storage.Put(w.ctx, objectName(w.prefix, seq, endSuffix), nil)
|
||||
w.mu.Lock()
|
||||
err, seq := w.err, w.seq
|
||||
w.mu.Unlock()
|
||||
switch {
|
||||
case err != nil:
|
||||
w.closeErr = err
|
||||
case w.ctx.Err() != nil:
|
||||
w.closeErr = w.ctx.Err()
|
||||
case flushErr != nil:
|
||||
w.closeErr = flushErr
|
||||
default:
|
||||
w.closeErr = w.storage.Put(w.ctx, objectName(w.prefix, seq, endSuffix), nil)
|
||||
}
|
||||
})
|
||||
return w.closeErr
|
||||
}
|
||||
|
||||
type walReader struct {
|
||||
@@ -207,26 +310,37 @@ type walReader struct {
|
||||
seq int64
|
||||
|
||||
ch chan []byte
|
||||
discard bool
|
||||
discards chan string
|
||||
wake chan struct{}
|
||||
holeSince time.Time
|
||||
|
||||
errMu sync.Mutex
|
||||
err error
|
||||
done chan struct{}
|
||||
work sync.WaitGroup
|
||||
}
|
||||
|
||||
func newWALReader(ctx context.Context, storage Storage, prefix string, p params) *walReader {
|
||||
func newWALReader(ctx context.Context, storage Storage, prefix string, p params, discard bool) *walReader {
|
||||
r := &walReader{
|
||||
ctx: ctx,
|
||||
storage: storage,
|
||||
prefix: prefix,
|
||||
params: p,
|
||||
ch: make(chan []byte, p.concurrency),
|
||||
discards: make(chan string, 4*p.concurrency),
|
||||
wake: make(chan struct{}, 1),
|
||||
ctx: ctx,
|
||||
storage: storage,
|
||||
prefix: prefix,
|
||||
params: p,
|
||||
ch: make(chan []byte, p.concurrency),
|
||||
discard: discard,
|
||||
wake: make(chan struct{}, 1),
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
if discard {
|
||||
r.discards = make(chan string, 4*p.concurrency)
|
||||
r.work.Add(1)
|
||||
go func() {
|
||||
defer r.work.Done()
|
||||
r.discardLoop()
|
||||
}()
|
||||
}
|
||||
go r.run()
|
||||
go r.discardLoop()
|
||||
return r
|
||||
}
|
||||
|
||||
@@ -241,7 +355,13 @@ func (r *walReader) Wake() {
|
||||
}
|
||||
}
|
||||
|
||||
func (r *walReader) wait() {
|
||||
<-r.done
|
||||
r.work.Wait()
|
||||
}
|
||||
|
||||
func (r *walReader) run() {
|
||||
defer close(r.done)
|
||||
defer close(r.ch)
|
||||
|
||||
delay := r.minPollInterval
|
||||
@@ -297,36 +417,37 @@ func (r *walReader) poll() (advanced, eof bool, err error) {
|
||||
return false, false, err
|
||||
}
|
||||
if len(listed) == 0 {
|
||||
return false, false, nil
|
||||
return false, false, r.pendingError(false)
|
||||
}
|
||||
|
||||
pending := make(map[int64]Entry, len(listed))
|
||||
ahead := false
|
||||
observedThrough := int64(-1)
|
||||
for _, entry := range listed {
|
||||
seq, ok := parseEntry(entry.Name)
|
||||
if !ok {
|
||||
if requiresWALCommit(r.storage) && strings.HasSuffix(entry.Name, commitSuffix) {
|
||||
seq, ok = parseEntry(strings.TrimSuffix(entry.Name, commitSuffix) + segSuffix)
|
||||
if ok {
|
||||
observedThrough = max(observedThrough, seq)
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
observedThrough = max(observedThrough, seq)
|
||||
if previous, exists := pending[seq]; exists && strings.HasSuffix(previous.Name, errSuffix) {
|
||||
continue
|
||||
}
|
||||
pending[seq] = entry
|
||||
if seq > r.seq {
|
||||
ahead = true
|
||||
}
|
||||
}
|
||||
|
||||
if _, ok := pending[r.seq]; !ok && ahead {
|
||||
if r.holeSince.IsZero() {
|
||||
r.holeSince = time.Now()
|
||||
} else if time.Since(r.holeSince) >= r.holeTimeout {
|
||||
return false, false, errors.New("segment ", r.seq,
|
||||
" never arrived while later ones did, the peer lost it")
|
||||
}
|
||||
} else {
|
||||
r.holeSince = time.Time{}
|
||||
}
|
||||
|
||||
for {
|
||||
if _, ok := pending[r.seq]; !ok {
|
||||
if err := r.pendingError(observedThrough >= r.seq); err != nil {
|
||||
return advanced, false, err
|
||||
}
|
||||
}
|
||||
if entry, ok := pending[r.seq]; ok && strings.HasSuffix(entry.Name, errSuffix) {
|
||||
r.discard(r.prefix + "/" + entry.Name)
|
||||
r.queueDiscard(r.prefix + "/" + entry.Name)
|
||||
return advanced, false, errors.New("the peer could not store segment ", r.seq)
|
||||
}
|
||||
|
||||
@@ -339,9 +460,9 @@ func (r *walReader) poll() (advanced, eof bool, err error) {
|
||||
}
|
||||
|
||||
chunks, err := r.fetch(batch)
|
||||
if err != nil {
|
||||
if err != nil && (err != errNotFound || len(chunks) == 0) {
|
||||
if err == errNotFound {
|
||||
return advanced, false, nil
|
||||
return advanced, false, r.pendingError(true)
|
||||
}
|
||||
return advanced, false, err
|
||||
}
|
||||
@@ -352,13 +473,34 @@ func (r *walReader) poll() (advanced, eof bool, err error) {
|
||||
case <-r.ctx.Done():
|
||||
return advanced, true, nil
|
||||
}
|
||||
seq := r.seq
|
||||
r.seq++
|
||||
r.holeSince = time.Time{}
|
||||
advanced = true
|
||||
r.discard(r.prefix + "/" + batch[i].Name)
|
||||
r.queueDiscard(r.prefix + "/" + batch[i].Name)
|
||||
if requiresWALCommit(r.storage) {
|
||||
r.queueDiscard(objectName(r.prefix, seq, commitSuffix))
|
||||
}
|
||||
}
|
||||
if err == errNotFound {
|
||||
return advanced, false, r.pendingError(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *walReader) pendingError(observed bool) error {
|
||||
if r.holeSince.IsZero() {
|
||||
if observed {
|
||||
r.holeSince = time.Now()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if time.Since(r.holeSince) >= r.holeTimeout {
|
||||
return errors.New("segment ", r.seq, " did not complete before the stream progress timeout")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *walReader) nextBatch(pending map[int64]Entry) (batch []Entry, done bool) {
|
||||
for i := 0; i < r.concurrency; i++ {
|
||||
entry, ok := pending[r.seq+int64(i)]
|
||||
@@ -367,7 +509,7 @@ func (r *walReader) nextBatch(pending map[int64]Entry) (batch []Entry, done bool
|
||||
}
|
||||
if !strings.HasSuffix(entry.Name, segSuffix) {
|
||||
if i == 0 && strings.HasSuffix(entry.Name, endSuffix) {
|
||||
r.discard(r.prefix + "/" + entry.Name)
|
||||
r.queueDiscard(r.prefix + "/" + entry.Name)
|
||||
return nil, true
|
||||
}
|
||||
break
|
||||
@@ -395,15 +537,51 @@ func (r *walReader) fetch(batch []Entry) ([][]byte, error) {
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
for i := range batch {
|
||||
if failures[i] != nil {
|
||||
return nil, failures[i]
|
||||
for _, err := range failures {
|
||||
if err != nil && err != errNotFound {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for _, chunk := range chunks {
|
||||
if len(chunk) > maxSegmentBytes {
|
||||
return nil, errors.New("segment exceeds the maximum size")
|
||||
}
|
||||
}
|
||||
commits := make([][]byte, len(batch))
|
||||
commitFailures := make([]error, len(batch))
|
||||
if requiresWALCommit(r.storage) {
|
||||
for i, entry := range batch {
|
||||
wg.Add(1)
|
||||
go func(i int, name string) {
|
||||
defer wg.Done()
|
||||
seq, _ := parseEntry(name)
|
||||
ctx := context.WithValue(r.ctx, maxBodyKey{}, int64(walCommitBytes))
|
||||
commits[i], commitFailures[i] = r.storage.Get(ctx, objectName(r.prefix, seq, commitSuffix))
|
||||
}(i, entry.Name)
|
||||
}
|
||||
wg.Wait()
|
||||
for _, err := range commitFailures {
|
||||
if err != nil && err != errNotFound {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
for i, err := range failures {
|
||||
if err != nil || len(chunks[i]) == 0 {
|
||||
return chunks[:i], errNotFound
|
||||
}
|
||||
if requiresWALCommit(r.storage) && (commitFailures[i] != nil || !validWALCommit(commits[i], chunks[i])) {
|
||||
return chunks[:i], errNotFound
|
||||
}
|
||||
}
|
||||
return chunks, nil
|
||||
}
|
||||
|
||||
func (r *walReader) discard(name string) {
|
||||
func (r *walReader) queueDiscard(name string) {
|
||||
if !r.discard {
|
||||
// Downlink segments stay until the server collects the idle session after sessionTTL.
|
||||
return
|
||||
}
|
||||
select {
|
||||
case r.discards <- name:
|
||||
default:
|
||||
@@ -411,6 +589,9 @@ func (r *walReader) discard(name string) {
|
||||
}
|
||||
|
||||
func (r *walReader) discardLoop() {
|
||||
if !r.discard {
|
||||
return
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
defer wg.Wait()
|
||||
|
||||
@@ -420,7 +601,11 @@ func (r *walReader) discardLoop() {
|
||||
case <-r.ctx.Done():
|
||||
return
|
||||
case name := <-r.discards:
|
||||
sem <- struct{}{}
|
||||
select {
|
||||
case sem <- struct{}{}:
|
||||
case <-r.ctx.Done():
|
||||
return
|
||||
}
|
||||
wg.Add(1)
|
||||
go func(name string) {
|
||||
defer wg.Done()
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package xdrive
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
)
|
||||
|
||||
const (
|
||||
commitSuffix = ".commit"
|
||||
walCommitMagic = "XDWALC01"
|
||||
walCommitBytes = 8 + 8 + sha256.Size
|
||||
)
|
||||
|
||||
func (*templateStorage) requiresWALCommit() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func requiresWALCommit(storage Storage) bool {
|
||||
s, ok := storage.(interface{ requiresWALCommit() bool })
|
||||
return ok && s.requiresWALCommit()
|
||||
}
|
||||
|
||||
func encodeWALCommit(data []byte) []byte {
|
||||
commit := make([]byte, walCommitBytes)
|
||||
copy(commit, walCommitMagic)
|
||||
binary.BigEndian.PutUint64(commit[8:16], uint64(len(data)))
|
||||
sum := sha256.Sum256(data)
|
||||
copy(commit[16:], sum[:])
|
||||
return commit
|
||||
}
|
||||
|
||||
func validWALCommit(commit, data []byte) bool {
|
||||
if len(commit) != walCommitBytes || string(commit[:8]) != walCommitMagic || len(data) == 0 || len(data) > maxSegmentBytes {
|
||||
return false
|
||||
}
|
||||
if binary.BigEndian.Uint64(commit[8:16]) != uint64(len(data)) {
|
||||
return false
|
||||
}
|
||||
sum := sha256.Sum256(data)
|
||||
return bytes.Equal(commit[16:], sum[:])
|
||||
}
|
||||
+377
-224
@@ -6,10 +6,10 @@ import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"maps"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
@@ -27,11 +27,6 @@ const (
|
||||
downlinkDir = "s2c"
|
||||
)
|
||||
|
||||
const (
|
||||
spareCount = 2
|
||||
spareIdleStop = 10 * time.Minute
|
||||
)
|
||||
|
||||
func init() {
|
||||
common.Must(internet.RegisterProtocolConfigCreator(protocolName, func() interface{} {
|
||||
return new(Config)
|
||||
@@ -53,6 +48,17 @@ func announceName(session string, at time.Time) string {
|
||||
}
|
||||
|
||||
func parseAnnounce(entry string) (string, time.Time, bool) {
|
||||
session, at, ok := announceParts(entry)
|
||||
if !ok || !safeSessionID(session) {
|
||||
return "", time.Time{}, false
|
||||
}
|
||||
return session, at, true
|
||||
}
|
||||
|
||||
// announceParts splits an announcement entry into its session and its time.
|
||||
// The session is not checked: a caller that turns it into an object name has
|
||||
// to ask safeSessionID first.
|
||||
func announceParts(entry string) (string, time.Time, bool) {
|
||||
dash := strings.IndexByte(entry, '-')
|
||||
if dash <= 0 || dash == len(entry)-1 {
|
||||
return "", time.Time{}, false
|
||||
@@ -64,6 +70,49 @@ func parseAnnounce(entry string) (string, time.Time, bool) {
|
||||
return entry[dash+1:], time.Unix(0, nanos), true
|
||||
}
|
||||
|
||||
// A session id reaches object names, so it must not traverse, must not
|
||||
// collide with another name once a separator is flattened, and must not name
|
||||
// a reserved file.
|
||||
func safeSessionID(session string) bool {
|
||||
return safeNameChars(session) && !reservedName(session)
|
||||
}
|
||||
|
||||
// A listed name becomes a delete target, so it must be safe to build one
|
||||
// from.
|
||||
func safeListedName(name string) bool {
|
||||
return safeNameChars(name) && !reservedName(name)
|
||||
}
|
||||
|
||||
func safeNameChars(name string) bool {
|
||||
if name == "" || len(name) > 255 {
|
||||
return false
|
||||
}
|
||||
for _, r := range name {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9':
|
||||
case r == '-' || r == '_' || r == '.':
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
return name[0] != '.' && name[len(name)-1] != '.'
|
||||
}
|
||||
|
||||
func reservedName(name string) bool {
|
||||
base := name
|
||||
if i := strings.IndexByte(base, '.'); i >= 0 {
|
||||
base = base[:i]
|
||||
}
|
||||
switch strings.ToUpper(base) {
|
||||
case "CON", "PRN", "AUX", "NUL":
|
||||
return true
|
||||
}
|
||||
if len(base) == 4 && base[3] >= '1' && base[3] <= '9' {
|
||||
return strings.EqualFold(base[:3], "COM") || strings.EqualFold(base[:3], "LPT")
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func sessionPrefix(session string) string {
|
||||
return streamsDir + "/" + session
|
||||
}
|
||||
@@ -77,6 +126,9 @@ func downlinkPrefix(session string) string {
|
||||
}
|
||||
|
||||
func streamConfig(streamSettings *internet.MemoryStreamConfig) (*Config, error) {
|
||||
if streamSettings == nil {
|
||||
return nil, errors.New("missing stream settings")
|
||||
}
|
||||
config, ok := streamSettings.ProtocolSettings.(*Config)
|
||||
if !ok || config == nil {
|
||||
return nil, errors.New("invalid protocol settings")
|
||||
@@ -84,185 +136,78 @@ func streamConfig(streamSettings *internet.MemoryStreamConfig) (*Config, error)
|
||||
return config, nil
|
||||
}
|
||||
|
||||
type spareRing struct {
|
||||
storage Storage
|
||||
session string
|
||||
ring ring
|
||||
at time.Time
|
||||
}
|
||||
|
||||
type spareBox struct {
|
||||
ch chan spareRing
|
||||
busy atomic.Bool
|
||||
last atomic.Int64
|
||||
stop atomic.Bool
|
||||
}
|
||||
|
||||
var spareBoxes sync.Map
|
||||
|
||||
func spareBoxFor(config *Config) *spareBox {
|
||||
if b, ok := spareBoxes.Load(config); ok {
|
||||
return b.(*spareBox)
|
||||
}
|
||||
b, _ := spareBoxes.LoadOrStore(config, &spareBox{ch: make(chan spareRing, spareCount)})
|
||||
return b.(*spareBox)
|
||||
}
|
||||
|
||||
func dropSpare(s spareRing) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
s.storage.Delete(ctx, sessionPrefix(s.session))
|
||||
s.storage.Close()
|
||||
}
|
||||
|
||||
func takeSpare(config *Config, p params) (spareRing, bool) {
|
||||
box := spareBoxFor(config)
|
||||
for {
|
||||
select {
|
||||
case s := <-box.ch:
|
||||
if time.Since(s.at) < p.sessionTTL*2/3 {
|
||||
return s, true
|
||||
}
|
||||
go dropSpare(s)
|
||||
default:
|
||||
return spareRing{}, false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func warmSpares(streamSettings *internet.MemoryStreamConfig, config *Config, p params) {
|
||||
spareBoxFor(config).last.Store(time.Now().UnixNano())
|
||||
fillSpares(streamSettings, config, p)
|
||||
}
|
||||
|
||||
func fillSpares(streamSettings *internet.MemoryStreamConfig, config *Config, p params) {
|
||||
box := spareBoxFor(config)
|
||||
if !box.busy.CompareAndSwap(false, true) {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
defer box.busy.Store(false)
|
||||
for n := len(box.ch); n > 0; n-- {
|
||||
select {
|
||||
case s := <-box.ch:
|
||||
if time.Since(s.at) < p.sessionTTL/3 {
|
||||
box.ch <- s
|
||||
} else {
|
||||
dropSpare(s)
|
||||
}
|
||||
default:
|
||||
}
|
||||
}
|
||||
for len(box.ch) < cap(box.ch) {
|
||||
for range 40 {
|
||||
if box.stop.Load() {
|
||||
return
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
if box.stop.Load() {
|
||||
return
|
||||
}
|
||||
storage, err := newStorage(streamSettings)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
storage = sessionStorage(storage)
|
||||
slots, ok := storage.(slotStore)
|
||||
if !ok {
|
||||
storage.Close()
|
||||
return
|
||||
}
|
||||
session, err := newSessionID()
|
||||
if err != nil {
|
||||
storage.Close()
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
r, err := makeRing(ctx, slots, session, p)
|
||||
cancel()
|
||||
if err != nil {
|
||||
dropSpare(spareRing{storage: storage, session: session})
|
||||
return
|
||||
}
|
||||
select {
|
||||
case box.ch <- spareRing{storage: storage, session: session, ring: r, at: time.Now()}:
|
||||
default:
|
||||
storage.Close()
|
||||
return
|
||||
}
|
||||
}
|
||||
time.AfterFunc(p.sessionTTL/4, func() {
|
||||
if !box.stop.Load() && time.Since(time.Unix(0, box.last.Load())) < spareIdleStop {
|
||||
fillSpares(streamSettings, config, p)
|
||||
}
|
||||
})
|
||||
}()
|
||||
}
|
||||
|
||||
func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (stat.Connection, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config, err := streamConfig(streamSettings)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
p := paramsFromConfig(config)
|
||||
if streamSettings.Destination == nil && dest.Address != nil {
|
||||
front := dest
|
||||
front.Network = net.Network_TCP
|
||||
patched := *streamSettings
|
||||
patched.Destination = &front
|
||||
streamSettings = &patched
|
||||
}
|
||||
|
||||
spare, warm := takeSpare(config, p)
|
||||
storage, session, r := spare.storage, spare.session, spare.ring
|
||||
if !warm {
|
||||
storage, err = newStorage(streamSettings)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
storage = sessionStorage(storage)
|
||||
|
||||
session, err = newSessionID()
|
||||
storage, err := newStorage(streamSettings)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
storage, err = transferSessionStorage(storage)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
session, err := newSessionID()
|
||||
if err != nil {
|
||||
storage.Close()
|
||||
return nil, err
|
||||
}
|
||||
p := paramsForStorage(config, storage)
|
||||
if slots, ok := storage.(slotStore); ok {
|
||||
depth := max(2, p.concurrency)
|
||||
ids, err := slots.takeIDs(ctx, 2*(depth+1)+1)
|
||||
if err != nil {
|
||||
storage.Close()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
p = paramsForStorage(config, storage)
|
||||
|
||||
slots, ok := storage.(slotStore)
|
||||
if ok && !warm {
|
||||
if r, err = makeRing(ctx, slots, session, p); err != nil {
|
||||
ok = false
|
||||
errors.LogWarningInner(ctx, err, "failed to make the slots of session ", session, ", it goes in segments")
|
||||
}
|
||||
}
|
||||
|
||||
if ok {
|
||||
warmSpares(streamSettings, config, p)
|
||||
r := lazyRing(session, depth, ids[:len(ids)-1])
|
||||
errors.LogInfo(ctx, "opened session ", session, " in ", len(r.Up.Slots), " slots")
|
||||
releaseSession, err := holdStorageSession(storage, session)
|
||||
if err != nil {
|
||||
storage.Close()
|
||||
return nil, err
|
||||
}
|
||||
conn := newSlotConn(context.Background(), slots, r.Up, r.Down, p, nil, func() {
|
||||
storage.Close()
|
||||
releaseSession()
|
||||
})
|
||||
writer := conn.writer.(*slotWriter)
|
||||
writer.first = make(chan []byte, 1)
|
||||
go func() {
|
||||
var first []byte
|
||||
|
||||
conn.publishWG.Go(func() {
|
||||
select {
|
||||
case first = <-writer.first:
|
||||
case <-conn.ctx.Done():
|
||||
return
|
||||
case r.First = <-writer.first:
|
||||
case <-time.After(25 * time.Millisecond):
|
||||
}
|
||||
if conn.ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
announce, _ := json.Marshal(r)
|
||||
if len(first) > 0 && len(first) <= slotInlineLimit {
|
||||
withFirst := r
|
||||
withFirst.First = first
|
||||
if encoded, err := json.Marshal(withFirst); err == nil && len(encoded) <= driveInlineLimit {
|
||||
announce = encoded
|
||||
}
|
||||
if len(r.First) != 0 && len(announce) > driveInlineLimit {
|
||||
r.First = nil
|
||||
announce, _ = json.Marshal(r)
|
||||
}
|
||||
// An announce failure surfaces as a connection error on the next Write/Read.
|
||||
if err := storage.Put(context.Background(), announceName(session, time.Now()), announce); err != nil {
|
||||
if err := putDriveObject(conn.ctx, slots, ids[len(ids)-1], announceName(session, time.Now()), announce); err != nil && conn.ctx.Err() == nil {
|
||||
err = errors.New("failed to announce session ", session).Base(err)
|
||||
writer.fail(err)
|
||||
conn.reader.(*slotReader).setErr(err)
|
||||
}
|
||||
}()
|
||||
})
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
@@ -272,7 +217,7 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.Me
|
||||
}
|
||||
errors.LogInfo(ctx, "opened session ", session)
|
||||
return newConn(context.Background(), storage,
|
||||
uplinkPrefix(session), downlinkPrefix(session), p, func() {
|
||||
uplinkPrefix(session), downlinkPrefix(session), p, false, func() {
|
||||
storage.Close()
|
||||
}), nil
|
||||
}
|
||||
@@ -288,8 +233,21 @@ type Listener struct {
|
||||
active map[string]bool
|
||||
handled map[string]time.Time
|
||||
idleSince map[string]time.Time
|
||||
collecting map[string]bool
|
||||
announceWarned map[string]bool
|
||||
firstSeen map[string]time.Time
|
||||
lastSeen map[string]time.Time
|
||||
stopping bool
|
||||
cleanupPending map[string]bool
|
||||
cleanupQueue []string
|
||||
cleanupRunning int
|
||||
loopWG sync.WaitGroup
|
||||
cleanupWG sync.WaitGroup
|
||||
closeOnce sync.Once
|
||||
closeErr error
|
||||
|
||||
// collectPause spaces the deletion of two collected sessions.
|
||||
collectPause time.Duration
|
||||
}
|
||||
|
||||
func Serve(ctx context.Context, address net.Address, port net.Port, streamSettings *internet.MemoryStreamConfig, addConn internet.ConnHandler) (internet.Listener, error) {
|
||||
@@ -315,10 +273,19 @@ func Serve(ctx context.Context, address net.Address, port net.Port, streamSettin
|
||||
idleSince: make(map[string]time.Time),
|
||||
announceWarned: make(map[string]bool),
|
||||
firstSeen: make(map[string]time.Time),
|
||||
lastSeen: make(map[string]time.Time),
|
||||
collectPause: cleanupSessionPause,
|
||||
}
|
||||
|
||||
go listener.acceptLoop(ctx)
|
||||
go listener.collectLoop(ctx)
|
||||
listener.loopWG.Add(2)
|
||||
go func() {
|
||||
defer listener.loopWG.Done()
|
||||
listener.acceptLoop(ctx)
|
||||
}()
|
||||
go func() {
|
||||
defer listener.loopWG.Done()
|
||||
listener.collectLoop(ctx)
|
||||
}()
|
||||
|
||||
return listener, nil
|
||||
}
|
||||
@@ -361,20 +328,22 @@ func (l *Listener) acceptPending(logCtx context.Context) (bool, error) {
|
||||
|
||||
accepted := false
|
||||
l.mu.Lock()
|
||||
if l.firstSeen == nil {
|
||||
l.firstSeen = make(map[string]time.Time)
|
||||
}
|
||||
now := time.Now()
|
||||
listedEntries := make(map[string]bool, len(sessions))
|
||||
for _, listed := range sessions {
|
||||
listedEntries[listed.Name] = true
|
||||
l.lastSeen[listed.Name] = now
|
||||
if _, seen := l.firstSeen[listed.Name]; !seen {
|
||||
l.firstSeen[listed.Name] = now
|
||||
first := listed.created
|
||||
if first.IsZero() || first.After(now) {
|
||||
first = now
|
||||
}
|
||||
l.firstSeen[listed.Name] = first
|
||||
}
|
||||
}
|
||||
// Keep first-seen times across brief listing omissions.
|
||||
for entry := range l.firstSeen {
|
||||
if !listedEntries[entry] {
|
||||
if now.Sub(l.lastSeen[entry]) >= 2*l.sessionTTL {
|
||||
delete(l.firstSeen, entry)
|
||||
delete(l.lastSeen, entry)
|
||||
}
|
||||
}
|
||||
l.mu.Unlock()
|
||||
@@ -383,86 +352,225 @@ func (l *Listener) acceptPending(logCtx context.Context) (bool, error) {
|
||||
entry := listed.Name
|
||||
full := sessionsDir + "/" + entry
|
||||
|
||||
session, _, ok := parseAnnounce(entry)
|
||||
session, _, ok := announceParts(entry)
|
||||
if !ok {
|
||||
go l.drop(full)
|
||||
// Never construct a deletion path from an unsafe name.
|
||||
if safeListedName(entry) {
|
||||
l.queueDrop(full)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !safeSessionID(session) {
|
||||
continue
|
||||
}
|
||||
l.mu.Lock()
|
||||
age := now.Sub(l.firstSeen[entry])
|
||||
expires := l.firstSeen[entry].Add(l.sessionTTL)
|
||||
l.mu.Unlock()
|
||||
if age > l.sessionTTL {
|
||||
if !time.Now().Before(expires) {
|
||||
errors.LogInfo(logCtx, "dropping the stale announcement of session ", session)
|
||||
go l.drop(full)
|
||||
l.mu.Lock()
|
||||
protected := l.active[session] || !l.handled[session].IsZero()
|
||||
l.mu.Unlock()
|
||||
if !protected {
|
||||
go l.drop(sessionPrefix(session))
|
||||
}
|
||||
l.queueDrop(full)
|
||||
l.queueSessionDrop(session)
|
||||
continue
|
||||
}
|
||||
if !l.claim(session) {
|
||||
l.mu.Lock()
|
||||
if !l.handled[session].IsZero() {
|
||||
l.queueDropLocked(full)
|
||||
}
|
||||
l.mu.Unlock()
|
||||
continue
|
||||
}
|
||||
admit, cancel := context.WithDeadline(l.ctx, expires)
|
||||
announce := listed.Inline
|
||||
if len(announce) == 0 {
|
||||
if _, ok := sessionStorage(l.storage).(slotStore); ok {
|
||||
announce, err = l.storage.Get(context.WithValue(l.ctx, maxBodyKey{}, int64(driveMaxAnnounce)), full)
|
||||
if err != nil {
|
||||
l.mu.Lock()
|
||||
delete(l.active, session)
|
||||
delete(l.handled, session)
|
||||
warn := !l.announceWarned[session]
|
||||
l.announceWarned[session] = true
|
||||
l.mu.Unlock()
|
||||
if warn {
|
||||
errors.LogWarningInner(logCtx, err, "failed to read the announcement of session ", session)
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
var conn *Conn
|
||||
var loadErr error
|
||||
if _, slots := l.storage.(slotStore); slots && len(announce) == 0 {
|
||||
announce, loadErr = l.storage.Get(context.WithValue(admit, maxBodyKey{}, int64(driveMaxAnnounce)), full)
|
||||
}
|
||||
go l.drop(full)
|
||||
if loadErr == nil && admit.Err() == nil {
|
||||
conn = l.newSessionConn(admit, session, announce)
|
||||
}
|
||||
cancel()
|
||||
if conn == nil {
|
||||
l.mu.Lock()
|
||||
delete(l.active, session)
|
||||
delete(l.handled, session)
|
||||
warn := loadErr != nil && !l.announceWarned[session]
|
||||
if warn {
|
||||
l.announceWarned[session] = true
|
||||
}
|
||||
l.mu.Unlock()
|
||||
if warn {
|
||||
errors.LogWarningInner(logCtx, loadErr, "failed to read the announcement of session ", session)
|
||||
}
|
||||
continue
|
||||
}
|
||||
l.queueDrop(full)
|
||||
accepted = true
|
||||
l.addConn(l.newSessionConn(logCtx, session, announce))
|
||||
l.addConn(conn)
|
||||
}
|
||||
return accepted, nil
|
||||
}
|
||||
|
||||
func (l *Listener) drop(name string) {
|
||||
l.storage.Delete(l.ctx, name)
|
||||
const (
|
||||
listenerCleanupWorkers = 2
|
||||
listenerCleanupQueue = 128
|
||||
)
|
||||
|
||||
func (l *Listener) queueDrop(name string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.queueDropLocked(name)
|
||||
}
|
||||
|
||||
func (l *Listener) queueSessionDrop(session string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if l.active[session] || !l.handled[session].IsZero() || l.collecting[session] {
|
||||
return
|
||||
}
|
||||
if since := l.idleSince[session]; !since.IsZero() && time.Since(since) < l.sessionTTL {
|
||||
return
|
||||
}
|
||||
if l.collecting == nil {
|
||||
l.collecting = make(map[string]bool)
|
||||
}
|
||||
l.collecting[session] = true
|
||||
if !l.queueDropLocked(sessionPrefix(session)) {
|
||||
delete(l.collecting, session)
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Listener) queueDropLocked(name string) bool {
|
||||
if l.stopping || l.ctx.Err() != nil || len(l.cleanupQueue) >= listenerCleanupQueue || l.cleanupPending[name] {
|
||||
return false
|
||||
}
|
||||
if l.cleanupPending == nil {
|
||||
l.cleanupPending = make(map[string]bool)
|
||||
}
|
||||
l.cleanupPending[name] = true
|
||||
l.cleanupQueue = append(l.cleanupQueue, name)
|
||||
if l.cleanupRunning < listenerCleanupWorkers {
|
||||
l.cleanupRunning++
|
||||
l.cleanupWG.Add(1)
|
||||
go l.cleanupWorker()
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (l *Listener) cleanupWorker() {
|
||||
defer l.cleanupWG.Done()
|
||||
for {
|
||||
l.mu.Lock()
|
||||
if len(l.cleanupQueue) == 0 {
|
||||
l.cleanupRunning--
|
||||
l.mu.Unlock()
|
||||
return
|
||||
}
|
||||
name := l.cleanupQueue[0]
|
||||
l.cleanupQueue[0] = ""
|
||||
l.cleanupQueue = l.cleanupQueue[1:]
|
||||
l.mu.Unlock()
|
||||
err := l.drop(name)
|
||||
l.finishDrop(name, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Listener) finishDrop(name string, err error) {
|
||||
l.mu.Lock()
|
||||
delete(l.cleanupPending, name)
|
||||
if strings.HasPrefix(name, streamsDir+"/") {
|
||||
session := strings.TrimPrefix(name, streamsDir+"/")
|
||||
delete(l.collecting, session)
|
||||
if err == nil || err == errSessionInUse || l.idleSince[session].IsZero() {
|
||||
l.idleSince[session] = time.Now()
|
||||
}
|
||||
}
|
||||
l.mu.Unlock()
|
||||
}
|
||||
|
||||
func (l *Listener) drop(name string) error {
|
||||
ctx := context.WithValue(l.ctx, cleanupKey{}, true)
|
||||
var last error
|
||||
for attempt := 0; attempt < cleanupMaxRetries && ctx.Err() == nil; attempt++ {
|
||||
if err := l.storage.Delete(ctx, name); err == nil {
|
||||
return nil
|
||||
} else if err == errSessionInUse {
|
||||
return err
|
||||
} else {
|
||||
last = err
|
||||
errors.LogDebug(ctx, "failed to drop ", name, ": ", err)
|
||||
}
|
||||
if attempt+1 < cleanupMaxRetries && sleepContext(ctx, cleanupRetryDelay+jitter(cleanupRetryDelay)) != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
return last
|
||||
}
|
||||
|
||||
func (l *Listener) claim(session string) bool {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if l.active[session] || !l.handled[session].IsZero() {
|
||||
if !safeSessionID(session) {
|
||||
return false
|
||||
}
|
||||
if l.stopping || l.ctx.Err() != nil || l.active[session] || !l.handled[session].IsZero() || l.collecting[session] {
|
||||
return false
|
||||
}
|
||||
if l.active == nil {
|
||||
l.active = make(map[string]bool)
|
||||
}
|
||||
if l.handled == nil {
|
||||
l.handled = make(map[string]time.Time)
|
||||
}
|
||||
l.active[session] = true
|
||||
l.handled[session] = time.Now()
|
||||
// The session was accepted, so the inactivity it was listed with is over:
|
||||
// a claim must not hand the session the age it had before it was taken.
|
||||
delete(l.idleSince, session)
|
||||
return true
|
||||
}
|
||||
|
||||
// newSessionConn takes a session in the slots that its announcement has, or
|
||||
// in segments if it has none
|
||||
func (l *Listener) newSessionConn(logCtx context.Context, session string, announce []byte) *Conn {
|
||||
storage := sessionStorage(l.storage)
|
||||
// Drive requires a ring announcement; other backends use the WAL.
|
||||
func (l *Listener) newSessionConn(admit context.Context, session string, announce []byte) *Conn {
|
||||
storage, err := acquireSessionStorage(l.storage)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
releaseSession, err := holdStorageSession(storage, session)
|
||||
if err != nil {
|
||||
storage.Close()
|
||||
return nil
|
||||
}
|
||||
onClose := func() {
|
||||
storage.Close()
|
||||
releaseSession()
|
||||
l.mu.Lock()
|
||||
delete(l.active, session)
|
||||
l.mu.Unlock()
|
||||
}
|
||||
if slots, ok := storage.(slotStore); ok {
|
||||
if r, ok := decodeRing(announce); ok {
|
||||
errors.LogInfo(logCtx, "accepted session ", session, " in ", len(r.Down.Slots), " slots")
|
||||
r.Up.lazy, r.Down.lazy = r.Lazy, r.Lazy
|
||||
r.Up.name, r.Down.name = uplinkPrefix(session), downlinkPrefix(session)
|
||||
deadline, _ := admit.Deadline() // acceptPending always supplies the announcement deadline
|
||||
if scoped, ok := slots.(interface {
|
||||
bindRing(context.Context, ring) error
|
||||
}); (ok && scoped.bindRing(admit, r) != nil) || admit.Err() != nil || !time.Now().Before(deadline) {
|
||||
onClose()
|
||||
return nil
|
||||
}
|
||||
errors.LogInfo(admit, "accepted session ", session, " in ", len(r.Down.Slots), " slots")
|
||||
return newSlotConn(l.ctx, slots, r.Down, r.Up, l.params, r.First, onClose)
|
||||
}
|
||||
onClose()
|
||||
return nil
|
||||
}
|
||||
errors.LogInfo(logCtx, "accepted session ", session)
|
||||
return newConn(l.ctx, storage, downlinkPrefix(session), uplinkPrefix(session), l.params, onClose)
|
||||
errors.LogInfo(admit, "accepted session ", session)
|
||||
return newConn(l.ctx, storage, downlinkPrefix(session), uplinkPrefix(session), l.params, true, onClose)
|
||||
}
|
||||
|
||||
func (l *Listener) collectLoop(logCtx context.Context) {
|
||||
@@ -480,7 +588,12 @@ func (l *Listener) collectLoop(logCtx context.Context) {
|
||||
}
|
||||
|
||||
func (l *Listener) collect() error {
|
||||
sessions, err := l.storage.List(l.ctx, streamsDir)
|
||||
if c, ok := l.storage.(interface{ cooling() bool }); ok && c.cooling() {
|
||||
return nil
|
||||
}
|
||||
ctx := context.WithValue(l.ctx, cleanupKey{}, true)
|
||||
ctx = context.WithValue(ctx, namesOnlyKey{}, true)
|
||||
sessions, err := l.storage.List(ctx, streamsDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -489,40 +602,70 @@ func (l *Listener) collect() error {
|
||||
var expired []string
|
||||
|
||||
l.mu.Lock()
|
||||
if l.collecting == nil {
|
||||
l.collecting = make(map[string]bool)
|
||||
}
|
||||
present := make(map[string]bool, len(sessions))
|
||||
for _, listed := range sessions {
|
||||
session := listed.Name
|
||||
if !safeSessionID(session) {
|
||||
// A listed stream name must never reach an object name.
|
||||
continue
|
||||
}
|
||||
present[session] = true
|
||||
if l.active[session] {
|
||||
delete(l.idleSince, session)
|
||||
continue
|
||||
}
|
||||
if l.collecting[session] || l.stopping {
|
||||
continue
|
||||
}
|
||||
since, seen := l.idleSince[session]
|
||||
if !seen {
|
||||
l.idleSince[session] = now
|
||||
continue
|
||||
}
|
||||
if now.Sub(since) >= l.sessionTTL {
|
||||
l.collecting[session] = true
|
||||
expired = append(expired, session)
|
||||
delete(l.idleSince, session)
|
||||
}
|
||||
}
|
||||
for session := range l.idleSince {
|
||||
if !present[session] {
|
||||
delete(l.idleSince, session)
|
||||
}
|
||||
}
|
||||
for session, at := range l.handled {
|
||||
if !l.active[session] && now.Sub(at) >= l.sessionTTL {
|
||||
delete(l.handled, session)
|
||||
maps.DeleteFunc(l.idleSince, func(id string, _ time.Time) bool { return !present[id] })
|
||||
announced := make(map[string]bool)
|
||||
for entry, seen := range l.lastSeen {
|
||||
if session, _, ok := parseAnnounce(entry); ok && now.Sub(seen) < 2*l.sessionTTL {
|
||||
announced[session] = true
|
||||
}
|
||||
}
|
||||
unused := func(id string) bool { return !l.active[id] && !l.collecting[id] && !announced[id] }
|
||||
maps.DeleteFunc(l.handled, func(id string, at time.Time) bool { return unused(id) && now.Sub(at) >= 2*l.sessionTTL })
|
||||
maps.DeleteFunc(l.announceWarned, func(id string, _ bool) bool { return unused(id) && l.handled[id].IsZero() })
|
||||
l.mu.Unlock()
|
||||
|
||||
defer func() {
|
||||
l.mu.Lock()
|
||||
for _, session := range expired {
|
||||
delete(l.collecting, session)
|
||||
}
|
||||
l.mu.Unlock()
|
||||
}()
|
||||
var first error
|
||||
for _, session := range expired {
|
||||
if err := l.storage.Delete(l.ctx, sessionPrefix(session)); err != nil && first == nil {
|
||||
first = err
|
||||
for i, session := range expired {
|
||||
if i > 0 && l.collectPause > 0 && sleepContext(l.ctx, l.collectPause) != nil {
|
||||
return l.ctx.Err()
|
||||
}
|
||||
if err := l.storage.Delete(ctx, sessionPrefix(session)); err != nil && err != errSessionInUse {
|
||||
if first == nil {
|
||||
first = err
|
||||
}
|
||||
} else if err == nil {
|
||||
l.mu.Lock()
|
||||
delete(l.idleSince, session)
|
||||
l.mu.Unlock()
|
||||
} else {
|
||||
l.mu.Lock()
|
||||
l.idleSince[session] = time.Now()
|
||||
l.mu.Unlock()
|
||||
}
|
||||
}
|
||||
return first
|
||||
@@ -533,6 +676,16 @@ func (l *Listener) Addr() net.Addr {
|
||||
}
|
||||
|
||||
func (l *Listener) Close() error {
|
||||
l.cancel()
|
||||
return l.storage.Close()
|
||||
l.closeOnce.Do(func() {
|
||||
l.mu.Lock()
|
||||
l.stopping = true
|
||||
l.mu.Unlock()
|
||||
if l.cancel != nil {
|
||||
l.cancel()
|
||||
}
|
||||
l.loopWG.Wait()
|
||||
l.cleanupWG.Wait()
|
||||
l.closeErr = l.storage.Close()
|
||||
})
|
||||
return l.closeErr
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user