Skip to content

Commit

Permalink
feat: cache file read by stat mod time
Browse files Browse the repository at this point in the history
  • Loading branch information
bcho committed Oct 1, 2023
1 parent 17f62a9 commit 41ba3a2
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 3 deletions.
73 changes: 73 additions & 0 deletions fs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package main

import (
"os"
"sync"
)

func readFileWithStatCache(file string) func() ([]byte, error) {
mu := new(sync.RWMutex)
var (
lastReadContent []byte
lastStat os.FileInfo
)

fast := func() (bool, []byte, error) {
stat, err := os.Stat(file)
if err != nil {
return false, nil, err
}

mu.RLock()
defer mu.RUnlock()

if lastStat == nil {
// no cache
return false, nil, nil
}

if lastStat.ModTime() == stat.ModTime() {
return true, lastReadContent, nil
}

// mod time changed
return false, nil, nil
}

slow := func() ([]byte, error) {
mu.Lock()
defer mu.Unlock()

stat, err := os.Stat(file)
if err != nil {
return nil, err
}

if lastStat != nil && lastStat.ModTime() == stat.ModTime() {
return lastReadContent, nil
}

lastStat = stat
lastReadContent = nil

content, err := os.ReadFile(file)
if err != nil {
return nil, err
}
lastReadContent = content

return content, nil
}

return func() ([]byte, error) {
readFromCache, content, err := fast()
if err != nil {
return nil, err
}
if readFromCache {
return content, nil
}

return slow()
}
}
9 changes: 6 additions & 3 deletions server_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package main
import (
"fmt"
"net/http"
"os"
"strings"

"github.com/golang-jwt/jwt"
Expand Down Expand Up @@ -66,14 +65,16 @@ func (opts *ServerAuthOptions) createAuthMiddleware(

switch {
case opts.RSAPublicKeyFilePath != "":
keyReader := readFileWithStatCache(opts.RSAPublicKeyFilePath)

jwtParser.ValidMethods = append(
jwtParser.ValidMethods,
jwt.SigningMethodRS256.Name,
jwt.SigningMethodRS384.Name,
jwt.SigningMethodRS512.Name,
)
jwtKeyFunc = func(t *jwt.Token) (interface{}, error) {
b, err := os.ReadFile(opts.RSAPublicKeyFilePath)
b, err := keyReader()
if err != nil {
return nil, err
}
Expand All @@ -85,14 +86,16 @@ func (opts *ServerAuthOptions) createAuthMiddleware(
return v, nil
}
case opts.TokenFilePath != "":
tokenReader := readFileWithStatCache(opts.TokenFilePath)

jwtParser.ValidMethods = append(
jwtParser.ValidMethods,
jwt.SigningMethodHS256.Name,
jwt.SigningMethodHS384.Name,
jwt.SigningMethodHS512.Name,
)
jwtKeyFunc = func(t *jwt.Token) (interface{}, error) {
b, err := os.ReadFile(opts.TokenFilePath)
b, err := tokenReader()
if err != nil {
return nil, err
}
Expand Down

0 comments on commit 41ba3a2

Please sign in to comment.