Skip to content

Commit

Permalink
gateway: add WithContextHint to handler and implement it on `Bloc…
Browse files Browse the repository at this point in the history
…ksBackend`

This allows the `BlocksBackend` to inject a session in the context, it remove the problems where we keep reseting the bitswap session each time we call the `fetcher`.
  • Loading branch information
Jorropo committed Jan 12, 2024
1 parent 6c590b8 commit 20035c9
Showing 3 changed files with 19 additions and 0 deletions.
6 changes: 6 additions & 0 deletions gateway/blocks_backend.go
Original file line number Diff line number Diff line change
@@ -684,6 +684,12 @@ func (bb *BlocksBackend) IsCached(ctx context.Context, p path.Path) bool {
return has
}

var _ WithContextHint = (*BlocksBackend)(nil)

func (bb *BlocksBackend) WrapContextForRequest(ctx context.Context) context.Context {
return blockservice.ContextWithSession(ctx, bb.blockService)

Check warning on line 690 in gateway/blocks_backend.go

Codecov / codecov/patch

gateway/blocks_backend.go#L689-L690

Added lines #L689 - L690 were not covered by tests
}

func (bb *BlocksBackend) ResolvePath(ctx context.Context, path path.ImmutablePath) (ContentPathMetadata, error) {
roots, lastSeg, remainder, err := bb.getPathRoots(ctx, path)
if err != nil {
8 changes: 8 additions & 0 deletions gateway/gateway.go
Original file line number Diff line number Diff line change
@@ -386,6 +386,14 @@ type IPFSBackend interface {
GetDNSLinkRecord(context.Context, string) (path.Path, error)
}

// WithContextHint allows an [IPFSBackend] to inject custom [context.Context] configurations.
// This should be considered optional, consumers might only make a best effort attempt at calling WrapContextForRequest on requests.
type WithContextHint interface {
// WrapContextForRequest allows the backend to add request scopped modifications to the context, like debug values or value caches.
// There are no promises on actual usage in consumers.
WrapContextForRequest(context.Context) context.Context
}

// cleanHeaderSet is an helper function that cleans a set of headers by
// (1) canonicalizing, (2) de-duplicating and (3) sorting.
func cleanHeaderSet(headers []string) []string {
5 changes: 5 additions & 0 deletions gateway/handler.go
Original file line number Diff line number Diff line change
@@ -152,6 +152,11 @@ func (i *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// the hour is a hard fallback, we don't expect it to happen, but just in case
ctx, cancel := context.WithTimeout(r.Context(), time.Hour)
defer cancel()

if withCtxWrap, ok := i.backend.(WithContextHint); ok {
ctx = withCtxWrap.WrapContextForRequest(ctx)
}

Check warning on line 158 in gateway/handler.go

Codecov / codecov/patch

gateway/handler.go#L157-L158

Added lines #L157 - L158 were not covered by tests

r = r.WithContext(ctx)

switch r.Method {

0 comments on commit 20035c9

Please sign in to comment.