2020-05-15 03:32:40 -05:00
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
|
|
|
|
2020-05-21 08:40:13 -05:00
|
|
|
"github.com/matrix-org/dendrite/internal/caching"
|
2020-05-15 03:32:40 -05:00
|
|
|
"github.com/matrix-org/gomatrixserverlib"
|
2023-04-19 09:50:33 -05:00
|
|
|
"github.com/matrix-org/gomatrixserverlib/spec"
|
2020-05-15 03:32:40 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
// A Database implements gomatrixserverlib.KeyDatabase and is used to store
|
|
|
|
// the public keys for other matrix servers.
|
|
|
|
type KeyDatabase struct {
|
2020-05-27 04:19:24 -05:00
|
|
|
inner gomatrixserverlib.KeyDatabase
|
2020-06-05 10:42:01 -05:00
|
|
|
cache caching.ServerKeyCache
|
2020-05-15 03:32:40 -05:00
|
|
|
}
|
|
|
|
|
2020-06-05 10:42:01 -05:00
|
|
|
func NewKeyDatabase(inner gomatrixserverlib.KeyDatabase, cache caching.ServerKeyCache) (*KeyDatabase, error) {
|
2020-05-15 03:32:40 -05:00
|
|
|
if inner == nil {
|
|
|
|
return nil, errors.New("inner database can't be nil")
|
|
|
|
}
|
|
|
|
if cache == nil {
|
|
|
|
return nil, errors.New("cache can't be nil")
|
|
|
|
}
|
|
|
|
return &KeyDatabase{
|
|
|
|
inner: inner,
|
|
|
|
cache: cache,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// FetcherName implements KeyFetcher
|
|
|
|
func (d KeyDatabase) FetcherName() string {
|
|
|
|
return "InMemoryKeyCache"
|
|
|
|
}
|
|
|
|
|
|
|
|
// FetchKeys implements gomatrixserverlib.KeyDatabase
|
|
|
|
func (d *KeyDatabase) FetchKeys(
|
|
|
|
ctx context.Context,
|
2023-04-19 09:50:33 -05:00
|
|
|
requests map[gomatrixserverlib.PublicKeyLookupRequest]spec.Timestamp,
|
2020-05-15 03:32:40 -05:00
|
|
|
) (map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult, error) {
|
|
|
|
results := make(map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult)
|
2020-06-16 07:11:20 -05:00
|
|
|
for req, ts := range requests {
|
|
|
|
if res, cached := d.cache.GetServerKey(req, ts); cached {
|
2020-05-15 03:32:40 -05:00
|
|
|
results[req] = res
|
|
|
|
delete(requests, req)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
fromDB, err := d.inner.FetchKeys(ctx, requests)
|
|
|
|
if err != nil {
|
|
|
|
return results, err
|
|
|
|
}
|
|
|
|
for req, res := range fromDB {
|
|
|
|
results[req] = res
|
|
|
|
d.cache.StoreServerKey(req, res)
|
|
|
|
}
|
|
|
|
return results, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// StoreKeys implements gomatrixserverlib.KeyDatabase
|
|
|
|
func (d *KeyDatabase) StoreKeys(
|
|
|
|
ctx context.Context,
|
|
|
|
keyMap map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult,
|
|
|
|
) error {
|
|
|
|
for req, res := range keyMap {
|
|
|
|
d.cache.StoreServerKey(req, res)
|
|
|
|
}
|
|
|
|
return d.inner.StoreKeys(ctx, keyMap)
|
|
|
|
}
|