@@ -0,0 +1,207 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"git.aiterp.net/rpdata/api/internal/auth"
|
||||
"git.aiterp.net/rpdata/api/models"
|
||||
"git.aiterp.net/rpdata/api/models/changekeys"
|
||||
"git.aiterp.net/rpdata/api/models/changes"
|
||||
"git.aiterp.net/rpdata/api/repositories"
|
||||
"git.aiterp.net/rpdata/api/services/loaders"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type CharacterService struct {
|
||||
characters repositories.CharacterRepository
|
||||
loader *loaders.CharacterLoader
|
||||
}
|
||||
|
||||
// Find uses the loader to find the character by the ID.
|
||||
func (s *CharacterService) Find(ctx context.Context, id string) (*models.Character, error) {
|
||||
return s.loader.Load(id)
|
||||
}
|
||||
|
||||
// Find uses the loader to find the character by the ID.
|
||||
func (s *CharacterService) FindNick(ctx context.Context, nick string) (*models.Character, error) {
|
||||
return s.characters.FindNick(ctx, nick)
|
||||
}
|
||||
|
||||
// List lists the characters. If the only filter active is `IDs`, the loader is used to batch together requests.
|
||||
func (s *CharacterService) List(ctx context.Context, filter models.CharacterFilter) ([]*models.Character, error) {
|
||||
if len(filter.IDs) > 0 && len(filter.Names) == 0 && len(filter.Nicks) == 0 && filter.Author == nil && filter.Search == nil {
|
||||
characters, errs := s.loader.LoadAll(filter.IDs)
|
||||
if len(characters) == 0 && len(errs) > 0 {
|
||||
if errs[0] == repositories.ErrNotFound {
|
||||
return []*models.Character{}, nil
|
||||
} else {
|
||||
return nil, errs[0]
|
||||
}
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var badIndices []int
|
||||
for i, character := range characters {
|
||||
if character == nil {
|
||||
badIndices = append(badIndices, i-len(badIndices))
|
||||
}
|
||||
}
|
||||
for _, index := range badIndices {
|
||||
characters = append(characters[:index], characters[index+1:]...)
|
||||
}
|
||||
|
||||
sort.Slice(characters, func(i, j int) bool {
|
||||
return strings.Compare(characters[i].ID, characters[j].ID) < 0
|
||||
})
|
||||
|
||||
return characters, nil
|
||||
}
|
||||
|
||||
return s.characters.List(ctx, filter)
|
||||
}
|
||||
|
||||
func (s *CharacterService) Create(ctx context.Context, nick, name, shortName, author, description string) (*models.Character, error) {
|
||||
token := auth.TokenFromContext(ctx)
|
||||
if token == nil {
|
||||
return nil, auth.ErrUnauthenticated
|
||||
}
|
||||
|
||||
if name == "" {
|
||||
return nil, errors.New("Name cannot be empty")
|
||||
}
|
||||
|
||||
if author == "" {
|
||||
author = token.UserID
|
||||
}
|
||||
|
||||
if shortName == "" {
|
||||
split := strings.SplitN(name, " ", 2)
|
||||
shortName = split[0]
|
||||
}
|
||||
|
||||
character := &models.Character{
|
||||
Name: name,
|
||||
ShortName: shortName,
|
||||
Author: author,
|
||||
Nicks: []string{nick},
|
||||
Description: description,
|
||||
}
|
||||
|
||||
err := auth.CheckPermission(ctx, "add", character)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
character, err = s.characters.Insert(ctx, *character)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
//TODO: New change submit system
|
||||
go changes.Submit("Character", "add", token.UserID, true, changekeys.Listed(character), character)
|
||||
|
||||
return character, nil
|
||||
}
|
||||
|
||||
func (s *CharacterService) Update(ctx context.Context, id string, name, shortName, description *string) (*models.Character, error) {
|
||||
character, err := s.characters.Find(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = auth.CheckPermission(ctx, "edit", character)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
character, err = s.characters.Update(ctx, *character, models.CharacterUpdate{
|
||||
Name: name,
|
||||
ShortName: shortName,
|
||||
Description: description,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
s.loader.Clear(character.ID)
|
||||
s.loader.Prime(character.ID, character)
|
||||
|
||||
//TODO: New change submit system
|
||||
token := auth.TokenFromContext(ctx)
|
||||
go changes.Submit("Character", "edit", token.UserID, true, changekeys.Listed(character), character)
|
||||
|
||||
return character, nil
|
||||
}
|
||||
|
||||
func (s *CharacterService) AddNick(ctx context.Context, id string, nick string) (*models.Character, error) {
|
||||
character, err := s.characters.Find(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = auth.CheckPermission(ctx, "edit", character)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
character, err = s.characters.AddNick(ctx, *character, nick)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
//TODO: New change submit system
|
||||
token := auth.TokenFromContext(ctx)
|
||||
go changes.Submit("Character", "edit", token.UserID, true, changekeys.Listed(character), character)
|
||||
|
||||
return character, nil
|
||||
}
|
||||
|
||||
func (s *CharacterService) RemoveNick(ctx context.Context, id string, nick string) (*models.Character, error) {
|
||||
character, err := s.characters.Find(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = auth.CheckPermission(ctx, "edit", character)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
character, err = s.characters.RemoveNick(ctx, *character, nick)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
//TODO: New change submit system
|
||||
token := auth.TokenFromContext(ctx)
|
||||
go changes.Submit("Character", "edit", token.UserID, true, changekeys.Listed(character), character)
|
||||
|
||||
return character, nil
|
||||
}
|
||||
|
||||
func (s *CharacterService) Delete(ctx context.Context, id string) (*models.Character, error) {
|
||||
character, err := s.characters.Find(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = auth.CheckPermission(ctx, "edit", character)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = s.characters.Delete(ctx, *character)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
//TODO: New change submit system
|
||||
token := auth.TokenFromContext(ctx)
|
||||
go changes.Submit("Character", "remove", token.UserID, true, changekeys.Listed(character), character)
|
||||
|
||||
return character, nil
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
// Code generated by github.com/vektah/dataloaden, DO NOT EDIT.
|
||||
|
||||
package loaders
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.aiterp.net/rpdata/api/models"
|
||||
)
|
||||
|
||||
// CharacterLoaderConfig captures the config to create a new CharacterLoader
|
||||
type CharacterLoaderConfig struct {
|
||||
// Fetch is a method that provides the data for the loader
|
||||
Fetch func(keys []string) ([]*models.Character, []error)
|
||||
|
||||
// Wait is how long wait before sending a batch
|
||||
Wait time.Duration
|
||||
|
||||
// MaxBatch will limit the maximum number of keys to send in one batch, 0 = not limit
|
||||
MaxBatch int
|
||||
}
|
||||
|
||||
// NewCharacterLoader creates a new CharacterLoader given a fetch, wait, and maxBatch
|
||||
func NewCharacterLoader(config CharacterLoaderConfig) *CharacterLoader {
|
||||
return &CharacterLoader{
|
||||
fetch: config.Fetch,
|
||||
wait: config.Wait,
|
||||
maxBatch: config.MaxBatch,
|
||||
}
|
||||
}
|
||||
|
||||
// CharacterLoader batches and caches requests
|
||||
type CharacterLoader struct {
|
||||
// this method provides the data for the loader
|
||||
fetch func(keys []string) ([]*models.Character, []error)
|
||||
|
||||
// how long to done before sending a batch
|
||||
wait time.Duration
|
||||
|
||||
// this will limit the maximum number of keys to send in one batch, 0 = no limit
|
||||
maxBatch int
|
||||
|
||||
// INTERNAL
|
||||
|
||||
// lazily created cache
|
||||
cache map[string]*models.Character
|
||||
|
||||
// the current batch. keys will continue to be collected until timeout is hit,
|
||||
// then everything will be sent to the fetch method and out to the listeners
|
||||
batch *characterLoaderBatch
|
||||
|
||||
// mutex to prevent races
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
type characterLoaderBatch struct {
|
||||
keys []string
|
||||
data []*models.Character
|
||||
error []error
|
||||
closing bool
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
// Load a Character by key, batching and caching will be applied automatically
|
||||
func (l *CharacterLoader) Load(key string) (*models.Character, error) {
|
||||
return l.LoadThunk(key)()
|
||||
}
|
||||
|
||||
// LoadThunk returns a function that when called will block waiting for a Character.
|
||||
// This method should be used if you want one goroutine to make requests to many
|
||||
// different data loaders without blocking until the thunk is called.
|
||||
func (l *CharacterLoader) LoadThunk(key string) func() (*models.Character, error) {
|
||||
l.mu.Lock()
|
||||
if it, ok := l.cache[key]; ok {
|
||||
l.mu.Unlock()
|
||||
return func() (*models.Character, error) {
|
||||
return it, nil
|
||||
}
|
||||
}
|
||||
if l.batch == nil {
|
||||
l.batch = &characterLoaderBatch{done: make(chan struct{})}
|
||||
}
|
||||
batch := l.batch
|
||||
pos := batch.keyIndex(l, key)
|
||||
l.mu.Unlock()
|
||||
|
||||
return func() (*models.Character, error) {
|
||||
<-batch.done
|
||||
|
||||
var data *models.Character
|
||||
if pos < len(batch.data) {
|
||||
data = batch.data[pos]
|
||||
}
|
||||
|
||||
var err error
|
||||
// its convenient to be able to return a single error for everything
|
||||
if len(batch.error) == 1 {
|
||||
err = batch.error[0]
|
||||
} else if batch.error != nil {
|
||||
err = batch.error[pos]
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
l.mu.Lock()
|
||||
l.unsafeSet(key, data)
|
||||
l.mu.Unlock()
|
||||
}
|
||||
|
||||
return data, err
|
||||
}
|
||||
}
|
||||
|
||||
// LoadAll fetches many keys at once. It will be broken into appropriate sized
|
||||
// sub batches depending on how the loader is configured
|
||||
func (l *CharacterLoader) LoadAll(keys []string) ([]*models.Character, []error) {
|
||||
results := make([]func() (*models.Character, error), len(keys))
|
||||
|
||||
for i, key := range keys {
|
||||
results[i] = l.LoadThunk(key)
|
||||
}
|
||||
|
||||
characters := make([]*models.Character, len(keys))
|
||||
errors := make([]error, len(keys))
|
||||
for i, thunk := range results {
|
||||
characters[i], errors[i] = thunk()
|
||||
}
|
||||
return characters, errors
|
||||
}
|
||||
|
||||
// LoadAllThunk returns a function that when called will block waiting for a Characters.
|
||||
// This method should be used if you want one goroutine to make requests to many
|
||||
// different data loaders without blocking until the thunk is called.
|
||||
func (l *CharacterLoader) LoadAllThunk(keys []string) func() ([]*models.Character, []error) {
|
||||
results := make([]func() (*models.Character, error), len(keys))
|
||||
for i, key := range keys {
|
||||
results[i] = l.LoadThunk(key)
|
||||
}
|
||||
return func() ([]*models.Character, []error) {
|
||||
characters := make([]*models.Character, len(keys))
|
||||
errors := make([]error, len(keys))
|
||||
for i, thunk := range results {
|
||||
characters[i], errors[i] = thunk()
|
||||
}
|
||||
return characters, errors
|
||||
}
|
||||
}
|
||||
|
||||
// Prime the cache with the provided key and value. If the key already exists, no change is made
|
||||
// and false is returned.
|
||||
// (To forcefully prime the cache, clear the key first with loader.clear(key).prime(key, value).)
|
||||
func (l *CharacterLoader) Prime(key string, value *models.Character) bool {
|
||||
l.mu.Lock()
|
||||
var found bool
|
||||
if _, found = l.cache[key]; !found {
|
||||
// make a copy when writing to the cache, its easy to pass a pointer in from a loop var
|
||||
// and end up with the whole cache pointing to the same value.
|
||||
cpy := *value
|
||||
l.unsafeSet(key, &cpy)
|
||||
}
|
||||
l.mu.Unlock()
|
||||
return !found
|
||||
}
|
||||
|
||||
// Clear the value at key from the cache, if it exists
|
||||
func (l *CharacterLoader) Clear(key string) {
|
||||
l.mu.Lock()
|
||||
delete(l.cache, key)
|
||||
l.mu.Unlock()
|
||||
}
|
||||
|
||||
func (l *CharacterLoader) unsafeSet(key string, value *models.Character) {
|
||||
if l.cache == nil {
|
||||
l.cache = map[string]*models.Character{}
|
||||
}
|
||||
l.cache[key] = value
|
||||
}
|
||||
|
||||
// keyIndex will return the location of the key in the batch, if its not found
|
||||
// it will add the key to the batch
|
||||
func (b *characterLoaderBatch) keyIndex(l *CharacterLoader, key string) int {
|
||||
for i, existingKey := range b.keys {
|
||||
if key == existingKey {
|
||||
return i
|
||||
}
|
||||
}
|
||||
|
||||
pos := len(b.keys)
|
||||
b.keys = append(b.keys, key)
|
||||
if pos == 0 {
|
||||
go b.startTimer(l)
|
||||
}
|
||||
|
||||
if l.maxBatch != 0 && pos >= l.maxBatch-1 {
|
||||
if !b.closing {
|
||||
b.closing = true
|
||||
l.batch = nil
|
||||
go b.end(l)
|
||||
}
|
||||
}
|
||||
|
||||
return pos
|
||||
}
|
||||
|
||||
func (b *characterLoaderBatch) startTimer(l *CharacterLoader) {
|
||||
time.Sleep(l.wait)
|
||||
l.mu.Lock()
|
||||
|
||||
// we must have hit a batch limit and are already finalizing this batch
|
||||
if b.closing {
|
||||
l.mu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
l.batch = nil
|
||||
l.mu.Unlock()
|
||||
|
||||
b.end(l)
|
||||
}
|
||||
|
||||
func (b *characterLoaderBatch) end(l *CharacterLoader) {
|
||||
b.data, b.error = l.fetch(b.keys)
|
||||
close(b.done)
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package loaders
|
||||
|
||||
import (
|
||||
"context"
|
||||
"git.aiterp.net/rpdata/api/models"
|
||||
"git.aiterp.net/rpdata/api/repositories"
|
||||
"time"
|
||||
)
|
||||
|
||||
//go:generate go run github.com/vektah/dataloaden CharacterLoader string *git.aiterp.net/rpdata/api/models.Character
|
||||
|
||||
// CharacterLoaderFromRepository creates a new CharacterLoader
|
||||
func CharacterLoaderFromRepository(repo repositories.CharacterRepository) *CharacterLoader {
|
||||
return &CharacterLoader{
|
||||
wait: time.Millisecond * 1,
|
||||
maxBatch: 100,
|
||||
fetch: func(keys []string) ([]*models.Character, []error) {
|
||||
timeout, cancel := context.WithTimeout(context.Background(), time.Second*15)
|
||||
defer cancel()
|
||||
|
||||
characters, err := repo.List(timeout, models.CharacterFilter{
|
||||
IDs: keys,
|
||||
})
|
||||
if err != nil {
|
||||
errs := make([]error, len(keys))
|
||||
for i := range errs {
|
||||
errs[i] = err
|
||||
}
|
||||
|
||||
return nil, errs
|
||||
}
|
||||
|
||||
charMap := make(map[string]*models.Character, len(keys))
|
||||
|
||||
for _, character := range characters {
|
||||
charMap[character.ID] = character
|
||||
}
|
||||
|
||||
results := make([]*models.Character, len(keys))
|
||||
errs := make([]error, len(keys))
|
||||
|
||||
for i, key := range keys {
|
||||
if character, ok := charMap[key]; ok {
|
||||
results[i] = character
|
||||
} else {
|
||||
errs[i] = repositories.ErrNotFound
|
||||
}
|
||||
}
|
||||
|
||||
return results, errs
|
||||
},
|
||||
}
|
||||
}
|
||||
+11
-3
@@ -1,10 +1,14 @@
|
||||
package services
|
||||
|
||||
import "git.aiterp.net/rpdata/api/repositories"
|
||||
import (
|
||||
"git.aiterp.net/rpdata/api/repositories"
|
||||
"git.aiterp.net/rpdata/api/services/loaders"
|
||||
)
|
||||
|
||||
// A Bundle contains all services, like a bean bag in the more caffeinated language family.
|
||||
// A Bundle contains all services.
|
||||
type Bundle struct {
|
||||
Tags *TagService
|
||||
Tags *TagService
|
||||
Characters *CharacterService
|
||||
}
|
||||
|
||||
// NewBundle creates a new bundle.
|
||||
@@ -12,6 +16,10 @@ func NewBundle(repos *repositories.Bundle) *Bundle {
|
||||
bundle := &Bundle{}
|
||||
|
||||
bundle.Tags = &TagService{tags: repos.Tags}
|
||||
bundle.Characters = &CharacterService{
|
||||
characters: repos.Characters,
|
||||
loader: loaders.CharacterLoaderFromRepository(repos.Characters),
|
||||
}
|
||||
|
||||
return bundle
|
||||
}
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ type TagService struct {
|
||||
}
|
||||
|
||||
// FindTag finds one tag.
|
||||
func (s *TagService) FindTag(ctx context.Context, source, id string) (*models.Tag, error) {
|
||||
func (s *TagService) FindTag(ctx context.Context, source models.TagKind, id string) (*models.Tag, error) {
|
||||
return s.tags.Find(ctx, source, id)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user