oficina / mapa Public

Clone
git clone https://amadan.net/oficina/mapa

Plain git — no account needed to clone.

Download

Download this file

1package mapa
2
3import (
4 "context"
5 "sync"
6 "time"
7)
8
9// freshFor bounds how stale a cached read may be when no write in this
10// process has happened: Mapa is one process per instance, so its own
11// writes are seen at once through Store.Generation, and anything else
12// that writes the file is seen within this.
13const freshFor = time.Second
14
15// viewerCache keeps who a person is (member id, own time zone) between
16// requests, so a page view does not query and HMAC their address each
17// time. Cleared by any write.
18type viewerCache struct {
19 mutex sync.Mutex
20 generation int64
21 checked time.Time
22 byAddress map[string]Viewer
23}
24
25func (cache *viewerCache) get(generation int64, address string) (Viewer,
26 bool) {
27 cache.mutex.Lock()
28 defer cache.mutex.Unlock()
29 if cache.generation != generation ||
30 time.Since(cache.checked) > freshFor {
31 cache.generation, cache.checked = generation, time.Now()
32 cache.byAddress = map[string]Viewer{}
33 return Viewer{}, false
34 }
35 viewer, ok := cache.byAddress[address]
36 return viewer, ok
37}
38
39func (cache *viewerCache) put(generation int64, viewer Viewer) {
40 cache.mutex.Lock()
41 defer cache.mutex.Unlock()
42 if cache.generation == generation && cache.byAddress != nil {
43 cache.byAddress[viewer.Address] = viewer
44 }
45}
46
47// Viewer resolves address without writing anything. team is the zone
48// for a person who has not chosen their own.
49func (store *Store) Viewer(ctx context.Context, address string,
50 team *time.Location) (Viewer, error) {
51 address = normaliseAddress(address)
52 generation := store.Generation()
53 viewer, ok := store.viewers.get(generation, address)
54 if !ok {
55 var err error
56 if viewer, err = store.lookupViewer(ctx, address); err != nil {
57 return viewer, err
58 }
59 store.viewers.put(generation, viewer)
60 }
61 if !viewer.OwnTimeZone {
62 viewer.TimeZone = team
63 }
64 return viewer, nil
65}
66