view auth/connection.go @ 339:33b59c848771

Factored out some miscellaneous code into own package.
author Sascha L. Teichmann <teichmann@intevation.de>
date Sun, 05 Aug 2018 15:35:29 +0200
parents 11d1a488b08f
children 4c211ad5349e
line wrap: on
line source

package auth

import (
	"database/sql"
	"errors"
	"io"
	"log"
	"sync"
	"time"

	"gemma.intevation.de/gemma/misc"
)

var ErrNoSuchToken = errors.New("No such token")

const (
	maxOpen   = 16
	maxDBIdle = time.Minute * 5
)

type Connection struct {
	session *Session

	access   time.Time
	db       *sql.DB
	refCount int

	mu sync.Mutex
}

func (c *Connection) serialize(w io.Writer) error {
	if err := c.session.serialize(w); err != nil {
		return err
	}
	access, err := c.last().MarshalText()
	if err != nil {
		return err
	}
	wr := misc.BinWriter{W: w}
	wr.Write(uint32(len(access)))
	wr.Write(access)
	return wr.Err
}

func (c *Connection) deserialize(r io.Reader) error {
	session := new(Session)
	if err := session.deserialize(r); err != nil {
		return err
	}

	rd := misc.BinReader{R: r}
	var l uint32
	rd.Read(&l)
	access := make([]byte, l)
	rd.Read(access)

	if rd.Err != nil {
		return rd.Err
	}

	var t time.Time
	if err := t.UnmarshalText(access); err != nil {
		return err
	}

	*c = Connection{
		session: session,
		access:  t,
	}

	return nil
}

func (c *Connection) set(session *Session) {
	c.session = session
	c.touch()
}

func (c *Connection) touch() {
	c.mu.Lock()
	c.access = time.Now()
	c.mu.Unlock()
}

func (c *Connection) last() time.Time {
	c.mu.Lock()
	access := c.access
	c.mu.Unlock()
	return access
}

func (c *Connection) close() {
	if c.db != nil {
		if err := c.db.Close(); err != nil {
			log.Printf("warn: %v\n", err)
		}
		c.db = nil
	}
}