Home Download Docs Code Community
     1	/*
     2	Copyright 2011 The Perkeep Authors
     3	
     4	Licensed under the Apache License, Version 2.0 (the "License");
     5	you may not use this file except in compliance with the License.
     6	You may obtain a copy of the License at
     7	
     8	     http://www.apache.org/licenses/LICENSE-2.0
     9	
    10	Unless required by applicable law or agreed to in writing, software
    11	distributed under the License is distributed on an "AS IS" BASIS,
    12	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13	See the License for the specific language governing permissions and
    14	limitations under the License.
    15	*/
    16	
    17	package server
    18	
    19	import (
    20		"errors"
    21		"fmt"
    22	
    23		"perkeep.org/internal/lru"
    24		"perkeep.org/pkg/blob"
    25		"perkeep.org/pkg/sorted"
    26	)
    27	
    28	const memLRUSize = 1024 // arbitrary
    29	
    30	var errCacheMiss = errors.New("not in cache")
    31	
    32	// ThumbMeta is a mapping from an image's scaling parameters (encoding
    33	// as an opaque "key" string) and the blobref of the thumbnail
    34	// (currently its file schema blob).
    35	// ThumbMeta is safe for concurrent use by multiple goroutines.
    36	//
    37	// The key will be some string containing the original full-sized image's
    38	// blobref, its target dimensions, and any possible transformations on
    39	// it (e.g. cropping it to square).
    40	type ThumbMeta struct {
    41		mem *lru.Cache      // key -> blob.Ref
    42		kv  sorted.KeyValue // optional
    43	}
    44	
    45	// NewThumbMeta returns a new in-memory ThumbMeta, backed with the
    46	// optional kv.
    47	// If kv is nil, key/value pairs are stored in memory only.
    48	func NewThumbMeta(kv sorted.KeyValue) *ThumbMeta {
    49		return &ThumbMeta{
    50			mem: lru.New(memLRUSize),
    51			kv:  kv,
    52		}
    53	}
    54	
    55	func (m *ThumbMeta) Get(key string) (blob.Ref, error) {
    56		var br blob.Ref
    57		if v, ok := m.mem.Get(key); ok {
    58			return v.(blob.Ref), nil
    59		}
    60		if m.kv != nil {
    61			v, err := m.kv.Get(key)
    62			if err == sorted.ErrNotFound {
    63				return br, errCacheMiss
    64			}
    65			if err != nil {
    66				return br, err
    67			}
    68			br, ok := blob.Parse(v)
    69			if !ok {
    70				return br, fmt.Errorf("Invalid blobref %q found for key %q in thumbnail mea", v, key)
    71			}
    72			m.mem.Add(key, br)
    73			return br, nil
    74		}
    75		return br, errCacheMiss
    76	}
    77	
    78	func (m *ThumbMeta) Put(key string, br blob.Ref) error {
    79		m.mem.Add(key, br)
    80		if m.kv != nil {
    81			return m.kv.Set(key, br.String())
    82		}
    83		return nil
    84	}
Website layout inspired by memcached.
Content by the authors.