view pkg/octree/cache.go @ 1234:1a5564655f2a

refac: Sidebar reorganized In order to make context switches between administrative tasks which are map related and those which are system related, we now have a category "administration" and "systemadministration". The Riverbedmorphology does nothing than display the map, so it is renamed to that (map). In case the context of "systemadministration" is chosen, the "map" brings you just back to the map.
author Thomas Junk <thomas.junk@intevation.de>
date Tue, 20 Nov 2018 09:54:53 +0100
parents 19a04b150b6c
children d753ce6cf588
line wrap: on
line source

// This is Free Software under GNU Affero General Public License v >= 3.0
// without warranty, see README.md and license for details.
//
// SPDX-License-Identifier: AGPL-3.0-or-later
// License-Filename: LICENSES/AGPL-3.0.txt
//
// Copyright (C) 2018 by via donau
//   – Österreichische Wasserstraßen-Gesellschaft mbH
// Software engineering by Intevation GmbH
//
// Author(s):
//  * Sascha L. Teichmann <sascha.teichmann@intevation.de>

package octree

import (
	"context"
	"database/sql"
	"sync"
	"time"
)

type (
	cacheKey struct {
		date       time.Time
		bottleneck string
	}

	cacheEntry struct {
		checksum string
		tree     *Tree
		access   time.Time
	}
	OctreeCache struct {
		sync.Mutex
		entries map[cacheKey]*cacheEntry
	}
)

const (
	cleanupCacheSleep = 6 * time.Minute
	maxCacheAge       = 5 * time.Minute
	maxCacheEntries   = 4
)

const (
	fetchOctreeSQL = `
SELECT octree_checksum, octree_index
FROM waterway.sounding_results
WHERE bottleneck_id = $1 AND date_info = $2::date
  AND octree_checksum IS NOT NULL AND octree_index IS NOT NULL
`
	checkOctreeSQL = `
SELECT CASE
  WHEN octree_checksum = $3 THEN NULL
  ELSE octree_index
  END
FROM waterway.sounding_results
WHERE bottleneck_id = $1 AND date_info = $2::date
  AND octree_checksum IS NOT NULL AND octree_index IS NOT NULL
`
)

var Cache = OctreeCache{
	entries: map[cacheKey]*cacheEntry{},
}

func init() {
	go Cache.background()
}

func (oc *OctreeCache) background() {
	for {
		time.Sleep(cleanupCacheSleep)
		oc.cleanup()
	}
}

func (oc *OctreeCache) cleanup() {
	oc.Lock()
	defer oc.Unlock()
	good := time.Now().Add(-maxCacheAge)
	for k, v := range oc.entries {
		if v.access.Before(good) {
			delete(oc.entries, k)
		}
	}
}

func (oc *OctreeCache) Get(
	bottleneck string, date time.Time,
	conn *sql.Conn, ctx context.Context,
) (*Tree, error) {
	oc.Lock()
	defer oc.Unlock()

	key := cacheKey{date, bottleneck}
	entry := oc.entries[key]

	var data []byte
	var checksum string

	if entry == nil {
		// fetch from database
		err := conn.QueryRowContext(
			ctx, fetchOctreeSQL, bottleneck, date).Scan(&checksum, &data)
		switch {
		case err == sql.ErrNoRows:
			return nil, nil
		case err != nil:
			return nil, err
		}
	} else {
		// check if we are not outdated.
		err := conn.QueryRowContext(
			ctx, checkOctreeSQL, bottleneck, date, entry.checksum).Scan(&data)
		switch {
		case err == sql.ErrNoRows:
			return nil, nil
		case err != nil:
			return nil, err
		}
		if data == nil { // we are still current
			entry.access = time.Now()
			return entry.tree, nil
		}
	}

	tree, err := Deserialize(data)
	if err != nil {
		return nil, err
	}

	now := time.Now()

	if entry != nil {
		entry.tree = tree
		entry.access = now
		return tree, nil
	}

	for len(oc.entries) >= maxCacheEntries {
		// Evict the entry that is accessed the longest time ago.
		var oldestKey cacheKey
		oldest := now

		for k, v := range oc.entries {
			if v.access.Before(oldest) {
				oldest = v.access
				oldestKey = k
			}
		}
		delete(oc.entries, oldestKey)
	}

	oc.entries[key] = &cacheEntry{
		checksum: checksum,
		tree:     tree,
		access:   now,
	}

	return tree, nil
}