<commit_before>// Copyright 2016 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package web

import (
	"context"
	"encoding/json"
	"fmt"
	"html/template"
	"net/http"
	"sort"
	"sync"
	"time"

	"github.com/coreos/etcdlabs/cluster/clusterpb"

	"github.com/coreos/etcd/clientv3"
	humanize "github.com/dustin/go-humanize"
	"github.com/golang/glog"
)

type key int

const userKey key = 0

type userData struct {
	lastActive time.Time
}

var (
	globalUserCacheLock sync.RWMutex
	globalUserCache     = make(map[string]userData)
)

var globalStatusInterval = time.Second

func updateClusterStatus(stopc <-chan struct{}) {
	for {
		select {
		case <-stopc:
			return
		case <-time.After(globalStatusInterval):
		}

		if len(globalUserCache) == 0 {
			// glog.Info("no user online")
			continue
		}
		globalCluster.UpdateMemberStatus()
	}
}

func cleanCache(stopc <-chan struct{}) {
	for {
		select {
		case <-stopc:
			return
		case <-time.After(5 * time.Minute):
		}

		globalUserCacheLock.Lock()
		for k, v := range globalUserCache {
			since := time.Since(v.lastActive)
			if since > 15*time.Minute {
				glog.Infof("removing inactive user %q (last active %v)", k, since)
				delete(globalUserCache, k)
			}
		}
		globalUserCacheLock.Unlock()
	}
}

func withCache(h ContextHandler) ContextHandler {
	return ContextHandlerFunc(func(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
		userID := generateUserID(req)
		globalServerVisits.Insert([]byte(userID))
		ctx = context.WithValue(ctx, userKey, &userID)

		globalUserCacheLock.Lock()
		if _, ok := globalUserCache[userID]; !ok { // if user visits first time, create user cache
			glog.Infof("just created user %q", userID)
			globalUserCache[userID] = userData{lastActive: time.Now()}
		}
		globalUserCacheLock.Unlock()

		return h.ServeHTTPContext(ctx, w, req)
	})
}

// Connect contains initial server state.
type Connect struct {
	WebPort int
	User    string
	Deleted bool
}
<commit_msg>backend/web: count visits by date<commit_after>// Copyright 2016 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package web

import (
	"context"
	"encoding/json"
	"fmt"
	"html/template"
	"net/http"
	"sort"
	"sync"
	"time"

	"github.com/coreos/etcdlabs/cluster/clusterpb"

	"github.com/coreos/etcd/clientv3"
	humanize "github.com/dustin/go-humanize"
	"github.com/golang/glog"
)

type key int

const userKey key = 0

type userData struct {
	lastActive time.Time
}

var (
	globalUserCacheLock sync.RWMutex
	globalUserCache     = make(map[string]userData)
)

var globalStatusInterval = time.Second

func updateClusterStatus(stopc <-chan struct{}) {
	for {
		select {
		case <-stopc:
			return
		case <-time.After(globalStatusInterval):
		}

		if len(globalUserCache) == 0 {
			// glog.Info("no user online")
			continue
		}
		globalCluster.UpdateMemberStatus()
	}
}

func cleanCache(stopc <-chan struct{}) {
	for {
		select {
		case <-stopc:
			return
		case <-time.After(5 * time.Minute):
		}

		globalUserCacheLock.Lock()
		for k, v := range globalUserCache {
			since := time.Since(v.lastActive)
			if since > 15*time.Minute {
				glog.Infof("removing inactive user %q (last active %v)", k, since)
				delete(globalUserCache, k)
			}
		}
		globalUserCacheLock.Unlock()
	}
}

func withCache(h ContextHandler) ContextHandler {
	return ContextHandlerFunc(func(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
		userID := generateUserID(req)
		globalServerVisits.Insert([]byte(userID + time.Now().String()[:10]))
		ctx = context.WithValue(ctx, userKey, &userID)

		globalUserCacheLock.Lock()
		if _, ok := globalUserCache[userID]; !ok { // if user visits first time, create user cache
			glog.Infof("just created user %q", userID)
			globalUserCache[userID] = userData{lastActive: time.Now()}
		}
		globalUserCacheLock.Unlock()

		return h.ServeHTTPContext(ctx, w, req)
	})
}

// Connect contains initial server state.
type Connect struct {
	WebPort int
	User    string
	Deleted bool
}

{'fraction_non_alphanumeric': 0.1173887003393891, 'fraction_numerical': 0.005989219405070872, 'mean_word_length': 3.7714285714285714, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5682875', 'n_tokens_mistral': 1762, 'n_tokens_neox': 1624, 'n_words': 469}