Skip to content

Commit

Permalink
improve variable naming
Browse files Browse the repository at this point in the history
  • Loading branch information
mpldr committed Feb 27, 2024
1 parent b1191c3 commit 4044eb6
Show file tree
Hide file tree
Showing 11 changed files with 84 additions and 86 deletions.
20 changes: 10 additions & 10 deletions api/_auth_cache/auth_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,25 +103,25 @@ func GetUserId(ctx rcontext.RequestContext, accessToken string, appserviceUserId
return checkTokenWithHomeserver(ctx, accessToken, appserviceUserId, true)
}

for _, r := range ctx.Config.AccessTokens.Appservices {
if r.AppserviceToken != accessToken {
for _, appSrv := range ctx.Config.AccessTokens.Appservices {
if appSrv.AppserviceToken != accessToken {
continue
}

if r.SenderUserId != "" && (r.SenderUserId == appserviceUserId || appserviceUserId == "") {
ctx.Log.Debugf("Access token belongs to appservice (sender user ID): %s", r.Id)
cacheToken(ctx, accessToken, appserviceUserId, r.SenderUserId, nil)
return r.SenderUserId, nil
if appSrv.SenderUserId != "" && (appSrv.SenderUserId == appserviceUserId || appserviceUserId == "") {
ctx.Log.Debugf("Access token belongs to appservice (sender user ID): %s", appSrv.Id)
cacheToken(ctx, accessToken, appserviceUserId, appSrv.SenderUserId, nil)
return appSrv.SenderUserId, nil
}

for _, n := range r.UserNamespaces {
for _, n := range appSrv.UserNamespaces {
regex, ok := regexCache[n.Regex]
if !ok {
regex = regexp.MustCompile(n.Regex)
regexCache[n.Regex] = regex
}
if regex.MatchString(appserviceUserId) {
ctx.Log.Debugf("Access token belongs to appservice: %s", r.Id)
ctx.Log.Debugf("Access token belongs to appservice: %s", appSrv.Id)
cacheToken(ctx, accessToken, appserviceUserId, appserviceUserId, nil)
return appserviceUserId, nil
}
Expand All @@ -133,13 +133,13 @@ func GetUserId(ctx rcontext.RequestContext, accessToken string, appserviceUserId
}

func cacheToken(ctx rcontext.RequestContext, accessToken string, appserviceUserId string, userId string, err error) {
v := cachedToken{
token := cachedToken{
userId: userId,
err: err,
}
t := time.Duration(ctx.Config.AccessTokens.MaxCacheTimeSeconds) * time.Second
rwLock.Lock()
tokenCache.Set(cacheKey(accessToken, appserviceUserId), v, t)
tokenCache.Set(cacheKey(accessToken, appserviceUserId), token, t)
rwLock.Unlock()
}

Expand Down
6 changes: 3 additions & 3 deletions api/_routers/00-install-params.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ var ServerNameRegex = regexp.MustCompile("[a-zA-Z0-9.:\\-_]+")

// var NumericIdRegex = regexp.MustCompile("[0-9]+")
func GetParam(name string, r *http.Request) string {
p := httprouter.ParamsFromContext(r.Context())
if p == nil {
parameter := httprouter.ParamsFromContext(r.Context())
if parameter == nil {
return ""
}
return p.ByName(name)
return parameter.ByName(name)
}

func ForceSetParam(name string, val string, r *http.Request) *http.Request {
Expand Down
28 changes: 14 additions & 14 deletions api/_routers/01-install_metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ func NewInstallMetadataRouter(ignoreHost bool, actionName string, counter *Reque
}
}

func (i *InstallMetadataRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
requestId := i.counter.NextId()
func (router *InstallMetadataRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
requestId := router.counter.NextId()
logger := logrus.WithFields(logrus.Fields{
"method": r.Method,
"host": r.Host,
Expand All @@ -54,44 +54,44 @@ func (i *InstallMetadataRouter) ServeHTTP(w http.ResponseWriter, r *http.Request
ctx := r.Context()
ctx = context.WithValue(ctx, common.ContextRequestStartTime, util.NowMillis())
ctx = context.WithValue(ctx, common.ContextRequestId, requestId)
ctx = context.WithValue(ctx, common.ContextAction, i.actionName)
ctx = context.WithValue(ctx, common.ContextIgnoreHost, i.ignoreHost)
ctx = context.WithValue(ctx, common.ContextAction, router.actionName)
ctx = context.WithValue(ctx, common.ContextIgnoreHost, router.ignoreHost)
ctx = context.WithValue(ctx, common.ContextLogger, logger)
r = r.WithContext(ctx)

if i.next != nil {
i.next.ServeHTTP(w, r)
if router.next != nil {
router.next.ServeHTTP(w, r)
}
}

func GetActionName(r *http.Request) string {
x, ok := r.Context().Value(common.ContextAction).(string)
action, ok := r.Context().Value(common.ContextAction).(string)
if !ok {
return "<UNKNOWN>"
}
return x
return action
}

func ShouldIgnoreHost(r *http.Request) bool {
x, ok := r.Context().Value(common.ContextIgnoreHost).(bool)
ignoreHost, ok := r.Context().Value(common.ContextIgnoreHost).(bool)
if !ok {
return false
}
return x
return ignoreHost
}

func GetLogger(r *http.Request) *logrus.Entry {
x, ok := r.Context().Value(common.ContextLogger).(*logrus.Entry)
log, ok := r.Context().Value(common.ContextLogger).(*logrus.Entry)
if !ok {
return nil
}
return x
return log
}

func GetRequestDuration(r *http.Request) float64 {
x, ok := r.Context().Value(common.ContextRequestStartTime).(int64)
duration, ok := r.Context().Value(common.ContextRequestStartTime).(int64)
if !ok {
return -1
}
return float64(util.NowMillis()-x) / 1000.0
return float64(util.NowMillis()-duration) / 1000.0
}
20 changes: 10 additions & 10 deletions api/branched_route.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ type splitBranch struct {

func branchedRoute(branches []branch) http.Handler {
sbranches := make([]splitBranch, len(branches))
for i, b := range branches {
for i, branch := range branches {
sbranches[i] = splitBranch{
segments: strings.Split(b.string, "/"),
handler: b.Handler,
segments: strings.Split(branch.string, "/"),
handler: branch.Handler,
}
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand All @@ -31,17 +31,17 @@ func branchedRoute(branches []branch) http.Handler {
catchAll = catchAll[1:]
}
params := strings.Split(catchAll, "/")
for _, b := range sbranches {
if b.segments[0][0] == ':' || b.segments[0] == params[0] {
if len(b.segments) != len(params) {
for _, branch := range sbranches {
if branch.segments[0][0] == ':' || branch.segments[0] == params[0] {
if len(branch.segments) != len(params) {
continue
}
for i, s := range b.segments {
if s[0] == ':' {
r = _routers.ForceSetParam(s[1:], params[i], r)
for i, segment := range branch.segments {
if segment[0] == ':' {
r = _routers.ForceSetParam(segment[1:], params[i], r)
}
}
b.handler.ServeHTTP(w, r)
branch.handler.ServeHTTP(w, r)
return
}
}
Expand Down
18 changes: 9 additions & 9 deletions api/custom/datastores.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"net/http"
"strconv"
"time"

"github.com/getsentry/sentry-go"
"github.com/t2bot/matrix-media-repo/api/_apimeta"
Expand All @@ -16,7 +17,6 @@ import (

"github.com/sirupsen/logrus"
"github.com/t2bot/matrix-media-repo/common/rcontext"
"github.com/t2bot/matrix-media-repo/util"
)

type DatastoreMigration struct {
Expand All @@ -26,25 +26,25 @@ type DatastoreMigration struct {

func GetDatastores(r *http.Request, rctx rcontext.RequestContext, user _apimeta.UserInfo) interface{} {
response := make(map[string]interface{})
for _, ds := range config.UniqueDatastores() {
uri, err := datastores.GetUri(ds)
for _, store := range config.UniqueDatastores() {
uri, err := datastores.GetUri(store)
if err != nil {
sentry.CaptureException(err)
rctx.Log.Error("Error getting datastore URI: ", err)
return _responses.InternalServerError(errors.New("unexpected error getting datastore information"))
}
dsMap := make(map[string]interface{})
dsMap["type"] = ds.Type
dsMap["uri"] = uri
response[ds.Id] = dsMap
dataStoreMap := make(map[string]interface{})
dataStoreMap["type"] = store.Type
dataStoreMap["uri"] = uri
response[store.Id] = dataStoreMap
}

return &_responses.DoNotCacheResponse{Payload: response}
}

func MigrateBetweenDatastores(r *http.Request, rctx rcontext.RequestContext, user _apimeta.UserInfo) interface{} {
beforeTsStr := r.URL.Query().Get("before_ts")
beforeTs := util.NowMillis()
beforeTs := time.Now().UnixNano() / int64(time.Millisecond)
var err error
if beforeTsStr != "" {
beforeTs, err = strconv.ParseInt(beforeTsStr, 10, 64)
Expand Down Expand Up @@ -97,7 +97,7 @@ func MigrateBetweenDatastores(r *http.Request, rctx rcontext.RequestContext, use

func GetDatastoreStorageEstimate(r *http.Request, rctx rcontext.RequestContext, user _apimeta.UserInfo) interface{} {
beforeTsStr := r.URL.Query().Get("before_ts")
beforeTs := util.NowMillis()
beforeTs := time.Now().UnixNano() / int64(time.Millisecond)
var err error
if beforeTsStr != "" {
beforeTs, err = strconv.ParseInt(beforeTsStr, 10, 64)
Expand Down
12 changes: 6 additions & 6 deletions api/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,23 +25,23 @@ func buildPrimaryRouter() *httprouter.Router {
func methodNotAllowedFn(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusMethodNotAllowed)
b, err := json.Marshal(_responses.MethodNotAllowed())
reponse, err := json.Marshal(_responses.MethodNotAllowed())
if err != nil {
sentry.CaptureException(fmt.Errorf("error preparing MethodNotAllowed: %v", err))
return
}
w.Write(b)
w.Write(reponse)
}

func notFoundFn(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound)
b, err := json.Marshal(_responses.NotFoundError())
reponse, err := json.Marshal(_responses.NotFoundError())
if err != nil {
sentry.CaptureException(fmt.Errorf("error preparing NotFound: %v", err))
return
}
w.Write(b)
w.Write(reponse)
}

func finishCorsFn(w http.ResponseWriter, r *http.Request) {
Expand All @@ -61,10 +61,10 @@ func panicFn(w http.ResponseWriter, r *http.Request, i interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)

b, err := json.Marshal(_responses.InternalServerError(errors.New("unexpected error")))
reponse, err := json.Marshal(_responses.InternalServerError(errors.New("unexpected error")))
if err != nil {
sentry.CaptureException(fmt.Errorf("error preparing InternalServerError: %v", err))
return
}
w.Write(b)
w.Write(reponse)
}
12 changes: 7 additions & 5 deletions api/webserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ import (
"github.com/t2bot/matrix-media-repo/common/config"
)

var srv *http.Server
var waitGroup = &sync.WaitGroup{}
var reload = false
var (
srv *http.Server
waitGroup = &sync.WaitGroup{}
reload = false
)

func Init() *sync.WaitGroup {
address := net.JoinHostPort(config.Get().General.BindAddress, strconv.Itoa(config.Get().General.Port))
Expand All @@ -35,8 +37,8 @@ func Init() *sync.WaitGroup {
limiter.SetBurst(config.Get().RateLimit.BurstCount)
limiter.SetMax(config.Get().RateLimit.RequestsPerSecond)

b, _ := json.Marshal(_responses.RateLimitReached())
limiter.SetMessage(string(b))
reponse, _ := json.Marshal(_responses.RateLimitReached())
limiter.SetMessage(string(reponse))
limiter.SetMessageContentType("application/json")

handler = tollbooth.LimitHandler(limiter, handler)
Expand Down
12 changes: 6 additions & 6 deletions database/table_url_previews.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ func (s *urlPreviewsTableStatements) Prepare(ctx rcontext.RequestContext) *urlPr
}
}

func (s *urlPreviewsTableWithContext) Get(url string, ts int64, languageHeader string) (*DbUrlPreview, error) {
row := s.statements.selectUrlPreview.QueryRowContext(s.ctx, url, ts, languageHeader)
func (s *urlPreviewsTableWithContext) Get(url string, timestamp int64, languageHeader string) (*DbUrlPreview, error) {
row := s.statements.selectUrlPreview.QueryRowContext(s.ctx, url, timestamp, languageHeader)
val := &DbUrlPreview{}
err := row.Scan(&val.Url, &val.ErrorCode, &val.BucketTs, &val.SiteUrl, &val.SiteName, &val.ResourceType, &val.Description, &val.Title, &val.ImageMxc, &val.ImageType, &val.ImageSize, &val.ImageWidth, &val.ImageHeight, &val.LanguageHeader)
if errors.Is(err, sql.ErrNoRows) {
Expand All @@ -75,8 +75,8 @@ func (s *urlPreviewsTableWithContext) Get(url string, ts int64, languageHeader s
return val, err
}

func (s *urlPreviewsTableWithContext) Insert(p *DbUrlPreview) error {
_, err := s.statements.insertUrlPreview.ExecContext(s.ctx, p.Url, p.ErrorCode, p.BucketTs, p.SiteUrl, p.SiteName, p.ResourceType, p.Description, p.Title, p.ImageMxc, p.ImageType, p.ImageSize, p.ImageWidth, p.ImageHeight, p.LanguageHeader)
func (s *urlPreviewsTableWithContext) Insert(preview *DbUrlPreview) error {
_, err := s.statements.insertUrlPreview.ExecContext(s.ctx, preview.Url, preview.ErrorCode, preview.BucketTs, preview.SiteUrl, preview.SiteName, preview.ResourceType, preview.Description, preview.Title, preview.ImageMxc, preview.ImageType, preview.ImageSize, preview.ImageWidth, preview.ImageHeight, preview.LanguageHeader)
return err
}

Expand All @@ -89,7 +89,7 @@ func (s *urlPreviewsTableWithContext) InsertError(url string, errorCode string)
})
}

func (s *urlPreviewsTableWithContext) DeleteOlderThan(ts int64) error {
_, err := s.statements.deleteOldUrlPreviews.ExecContext(s.ctx, ts)
func (s *urlPreviewsTableWithContext) DeleteOlderThan(timestamp int64) error {
_, err := s.statements.deleteOldUrlPreviews.ExecContext(s.ctx, timestamp)
return err
}
Loading

0 comments on commit 4044eb6

Please sign in to comment.