Skip to content
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion router-tests/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ require (
github.com/wundergraph/cosmo/router v0.0.0-20260710155145-803a4bc06d92
github.com/wundergraph/cosmo/router-plugin v0.0.0-20250808194725-de123ba1c65e
github.com/wundergraph/cosmo/speedtrap v0.0.0-00010101000000-000000000000
github.com/wundergraph/graphql-go-tools/v2 v2.14.2
github.com/wundergraph/graphql-go-tools/v2 v2.14.3-0.20260804183019-ff8f37c5cd22
go.opentelemetry.io/otel v1.44.0
go.opentelemetry.io/otel/sdk v1.44.0
go.opentelemetry.io/otel/sdk/metric v1.44.0
Expand Down
4 changes: 2 additions & 2 deletions router-tests/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -386,8 +386,8 @@ github.com/wundergraph/astjson v1.1.0 h1:xORDosrZ87zQFJwNGe/HIHXqzpdHOFmqWgykCLV
github.com/wundergraph/astjson v1.1.0/go.mod h1:h12D/dxxnedtLzsKyBLK7/Oe4TAoGpRVC9nDpDrZSWw=
github.com/wundergraph/go-arena v1.3.0 h1:n0ng5a1vbd8YGq1u3rMr0vPU5f6AZ1BXIiUhL1UIok8=
github.com/wundergraph/go-arena v1.3.0/go.mod h1:ROOysEHWJjLQ8FSfNxZCziagb7Qw2nXY3/vgKRh7eWw=
github.com/wundergraph/graphql-go-tools/v2 v2.14.2 h1:zPqpmGdVLtTR3nc/H7kPWgMN+a/DR5ccFLGyS1WtxeQ=
github.com/wundergraph/graphql-go-tools/v2 v2.14.2/go.mod h1:zREIKLmpjfNcGSubndaW/913r0Y8XbbYOXQeZFkwHdo=
github.com/wundergraph/graphql-go-tools/v2 v2.14.3-0.20260804183019-ff8f37c5cd22 h1:kU1zoy548x0x3I/LdyWEBJTDryguQjOv4R4fl4gqd30=
github.com/wundergraph/graphql-go-tools/v2 v2.14.3-0.20260804183019-ff8f37c5cd22/go.mod h1:zREIKLmpjfNcGSubndaW/913r0Y8XbbYOXQeZFkwHdo=
github.com/xrash/smetrics v0.0.0-20250705151800-55b8f293f342 h1:FnBeRrxr7OU4VvAzt5X7s6266i6cSVkkFPS0TuXWbIg=
github.com/xrash/smetrics v0.0.0-20250705151800-55b8f293f342/go.mod h1:Ohn+xnUBiLI6FVj/9LpzZWtj1/D6lUovWYBkxHVV3aM=
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
Expand Down
2 changes: 1 addition & 1 deletion router/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ require (
github.com/tidwall/gjson v1.18.0
github.com/tidwall/sjson v1.2.5
github.com/twmb/franz-go v1.16.1
github.com/wundergraph/graphql-go-tools/v2 v2.14.2
github.com/wundergraph/graphql-go-tools/v2 v2.14.3-0.20260804183019-ff8f37c5cd22
// Do not upgrade, it renames attributes we rely on
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0
go.opentelemetry.io/contrib/propagators/b3 v1.44.0
Expand Down
4 changes: 2 additions & 2 deletions router/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -334,8 +334,8 @@ github.com/wundergraph/astjson v1.1.0 h1:xORDosrZ87zQFJwNGe/HIHXqzpdHOFmqWgykCLV
github.com/wundergraph/astjson v1.1.0/go.mod h1:h12D/dxxnedtLzsKyBLK7/Oe4TAoGpRVC9nDpDrZSWw=
github.com/wundergraph/go-arena v1.3.0 h1:n0ng5a1vbd8YGq1u3rMr0vPU5f6AZ1BXIiUhL1UIok8=
github.com/wundergraph/go-arena v1.3.0/go.mod h1:ROOysEHWJjLQ8FSfNxZCziagb7Qw2nXY3/vgKRh7eWw=
github.com/wundergraph/graphql-go-tools/v2 v2.14.2 h1:zPqpmGdVLtTR3nc/H7kPWgMN+a/DR5ccFLGyS1WtxeQ=
github.com/wundergraph/graphql-go-tools/v2 v2.14.2/go.mod h1:zREIKLmpjfNcGSubndaW/913r0Y8XbbYOXQeZFkwHdo=
github.com/wundergraph/graphql-go-tools/v2 v2.14.3-0.20260804183019-ff8f37c5cd22 h1:kU1zoy548x0x3I/LdyWEBJTDryguQjOv4R4fl4gqd30=
github.com/wundergraph/graphql-go-tools/v2 v2.14.3-0.20260804183019-ff8f37c5cd22/go.mod h1:zREIKLmpjfNcGSubndaW/913r0Y8XbbYOXQeZFkwHdo=
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
Expand Down
119 changes: 119 additions & 0 deletions router/pkg/entitycaching/cache/in_memory.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
package cache

import (
"bytes"
"context"
"errors"
"fmt"
"sync"
"time"

enginecache "github.com/wundergraph/graphql-go-tools/v2/pkg/entitycaching"
)

// ErrMissingTTL reports items that were rejected because they carried no
// positive TTL. Every cached entry expires, so a TTL is mandatory.
var ErrMissingTTL = errors.New("cache item requires a positive TTL")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This error isn't specific to the in memory cache, right? I would define it in the corresponding graphql-go-tools package then and mention in the methods godoc when its returned

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

moved to graphqlgotools


type inMemoryEntry struct {
value []byte
// expiresAt is always set, an entry without an expiry is never stored.
expiresAt time.Time
}

// InMemoryCache sweeps every expired entry on each call, so both methods take
// the mutex exclusively, hence a plain Mutex rather than an RWMutex.
// This cache should only be used for tests OR development and never production

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This rather belongs to the mu field as a godoc instead of InMemoryCache.

Also this could become a major bottleneck. Using a normal mutex instead of an RWMutex forces syncronous reads to the cache for all concurrent requests on the router. You can't use an RWMutex because of sweepExipred on GetMany. Maybe worth checking if you can use Ristretto like mentioned above so you don't need to care about this kind of problem.

I mean yeah it's only meant to be used in tests but if Ristretto can solve it for free and have it production ready for when the situation calls for it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

switched to ristretto

type InMemoryCache struct {
mu sync.Mutex
entries map[string]inMemoryEntry

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not use map[string]enginecache.Item ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

switched to ristretto

now func() time.Time

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is only for test purposes right? Have you considered using testing/synctest? It lets you mock time inside the runtime, so you don't need to introduce code, which is only there for testing purposes.

https://go.dev/blog/testing-time

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cleaned up

}

// NewInMemoryCache returns an empty InMemoryCache ready for use.
func NewInMemoryCache() *InMemoryCache {
return &InMemoryCache{
entries: make(map[string]inMemoryEntry),
now: time.Now,
}
}

// GetMany returns one result per key, in the same order as keys. It also drops
// every expired entry, including those no key in this batch asked about.
func (c *InMemoryCache) GetMany(ctx context.Context, keys []string) ([]enginecache.Result, error) {
if len(keys) == 0 {
return nil, nil
}

if err := ctx.Err(); err != nil {
return nil, err
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd put this on the top like in SetMany

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done


c.mu.Lock()
defer c.mu.Unlock()

// Sweeping first means anything still present is live, so the lookup below
// needs no expiry check of its own.
c.sweepExpired(c.now())

results := make([]enginecache.Result, len(keys))
for i, key := range keys {
entry, ok := c.entries[key]
if !ok {
continue
}
results[i] = enginecache.Result{Value: bytes.Clone(entry.value), Found: true}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're not really making use of Result.Found because its always true for returned items. Do we really need the Found field?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cleaned up

}

return results, nil
}

// SetMany stores every item, all of which must carry a positive TTL. A single
// item without one fails the whole batch with an ErrMissingTTL and nothing is
// stored. It otherwise only fails on a cancelled context. It also drops every
// expired entry, including those no lookup has claimed.
func (c *InMemoryCache) SetMany(ctx context.Context, items []enginecache.Item) error {
if err := ctx.Err(); err != nil {
return err
}

if len(items) == 0 {
return nil
}

// Validated up front, before the lock is taken, so a batch carrying a bad
// item writes nothing at all rather than being applied in part.
for _, item := range items {
if item.TTL <= 0 {
return fmt.Errorf("%w: key %q", ErrMissingTTL, item.Key)
}
}

c.mu.Lock()
defer c.mu.Unlock()

now := c.now()
for _, item := range items {
c.entries[item.Key] = inMemoryEntry{
value: bytes.Clone(item.Value),
expiresAt: now.Add(item.TTL),
}
}

// Everything just stored has a deadline in the future, so a batch never
// sweeps away its own entries.
c.sweepExpired(now)

return nil
}

// sweepExpired drops every entry that has expired by now. The caller must hold
// the mutex. A TTL of d covers [set, set+d), so an entry reaching its deadline
// exactly is already expired.
func (c *InMemoryCache) sweepExpired(now time.Time) {
for key, entry := range c.entries {
if !now.Before(entry.expiresAt) {
delete(c.entries, key)
}
}
}
Loading
Loading