A pastebin for markdown pages.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1008 B

8 years ago
package main
import (
"database/sql"
"sync"
"time"
"github.com/labstack/echo"
)
const statsSavingInterval = 1 * time.Minute
var stats = &sync.Map{}
func flushStatsLoop(logger echo.Logger, db *sql.DB) {
8 years ago
for {
c, err := flush(db)
8 years ago
if err != nil {
logger.Errorf("couldn't flush stats: %v", err)
8 years ago
}
if c > 0 {
logger.Infof("successfully persisted %d values", c)
}
time.Sleep(statsSavingInterval)
}
}
func flush(db *sql.DB) (int, error) {
c := 0
tx, err := db.Begin()
if err != nil {
return c, err
8 years ago
}
stats.Range(func(id, views interface{}) bool {
stmt, _ := tx.Prepare("update notes set views = ? where id = ?")
_, err := stmt.Exec(views, id)
if err == nil {
c++
}
stmt.Close()
defer stats.Delete(id)
return true
})
return c, tx.Commit()
8 years ago
}
func incViews(n *Note, db *sql.DB) {
views := n.Views
if viewsCached, found := stats.Load(n.ID); found {
if val, ok := viewsCached.(int); ok {
views = val
}
}
stats.Store(n.ID, views+1)
_, _ = flush(db)
}