sync.go 7.98 KB
Newer Older
ale's avatar
ale committed
1 2 3 4 5 6 7 8 9 10 11 12 13
package liber

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"
	"sync"
ale's avatar
ale committed
14
	"time"
ale's avatar
ale committed
15 16 17 18 19 20 21 22 23
)

const (
	diffChunkSize     = 1000
	uploadConcurrency = 3
)

type SyncClient interface {
	DiffRequest(*diffRequest) (*diffResponse, error)
ale's avatar
ale committed
24
	SendBook(*Book, []*File) error
ale's avatar
ale committed
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
}

type remoteServer struct {
	client    *http.Client
	remoteURL string
}

func NewRemoteServer(remoteURL string) *remoteServer {
	return &remoteServer{
		remoteURL: remoteURL,
		client:    &http.Client{},
	}
}

// DiffRequest sends a diffRequest to the remote server.
func (r *remoteServer) DiffRequest(diffreq *diffRequest) (*diffResponse, error) {
	var body bytes.Buffer
	if err := json.NewEncoder(&body).Encode(diffreq); err != nil {
		return nil, err
	}

	req, err := http.NewRequest("POST", r.remoteURL+"/api/sync/diff", &body)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")
	resp, err := r.client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		return nil, fmt.Errorf("HTTP error: %s", resp.Status)
	}

	var diffresp diffResponse
	if err := json.NewDecoder(resp.Body).Decode(&diffresp); err != nil {
		return nil, err
	}

	return &diffresp, nil
}

ale's avatar
ale committed
68
func addFilePart(w *multipart.Writer, varname, filename, mimeFilename string) error {
ale's avatar
ale committed
69 70 71 72 73 74
	file, err := os.Open(filename)
	if err != nil {
		return err
	}
	defer file.Close()

ale's avatar
ale committed
75
	part, err := w.CreateFormFile(varname, mimeFilename)
ale's avatar
ale committed
76 77 78 79 80 81 82 83 84 85 86
	if err != nil {
		return err
	}

	if _, err := io.Copy(part, file); err != nil {
		return err
	}
	return nil
}

// SendBook uploads a book to the remote server.
ale's avatar
ale committed
87
func (r *remoteServer) SendBook(book *Book, files []*File) error {
ale's avatar
ale committed
88 89 90 91 92
	// Create a multipart request with the JSON-encoded metadata
	// and the actual file contents as two separate mime/multipart
	// sections.
	var body bytes.Buffer
	w := multipart.NewWriter(&body)
ale's avatar
ale committed
93

ale's avatar
ale committed
94 95 96 97 98
	part, err := w.CreateFormFile("meta", "meta.json")
	if err := json.NewEncoder(part).Encode(book.Metadata); err != nil {
		return err
	}

ale's avatar
ale committed
99 100 101 102 103 104 105
	for i, f := range files {
		varname := fmt.Sprintf("book%d", i)
		filename := fmt.Sprintf("%d%s", book.Id, f.FileType)
		if err := addFilePart(w, varname, f.Path, filename); err != nil {
			w.Close()
			return err
		}
ale's avatar
ale committed
106 107 108
	}

	if book.CoverPath != "" {
ale's avatar
ale committed
109
		if err := addFilePart(w, "cover", book.CoverPath, "cover.jpg"); err != nil {
ale's avatar
ale committed
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
			w.Close()
			return err
		}
	}

	if err := w.Close(); err != nil {
		return err
	}

	req, err := http.NewRequest("POST", r.remoteURL+"/api/sync/upload", &body)
	if err != nil {
		return err
	}
	req.Header.Add("Content-Type", w.FormDataContentType())

	resp, err := r.client.Do(req)
	if err != nil {
		return err
	}
	resp.Body.Close()
	if resp.StatusCode != 200 {
		return fmt.Errorf("HTTP error: %s", resp.Status)
	}

	return nil
}

type uniqueIds struct {
	Id     string
	Unique []string
}

type diffRequest struct {
	Candidates []uniqueIds
}

type diffResponse struct {
	Missing []string
}

func (db *Database) findMissing(srv SyncClient) chan string {
	missing := make(chan string, diffChunkSize)

	doRequest := func(req *diffRequest) {
		resp, err := srv.DiffRequest(req)
		if err != nil {
			log.Printf("DiffRequest(): %v", err)
		} else {
			for _, id := range resp.Missing {
				missing <- id
			}
		}
	}

	go func() {
		n := 0
		var req diffRequest
		for iter := db.Scan(BookBucket); iter.Valid(); iter.Next() {
			var book Book
			if err := iter.Value(&book); err != nil {
				continue
			}
			req.Candidates = append(req.Candidates, uniqueIds{
				Id:     book.Id.String(),
				Unique: book.Metadata.Uniques(),
			})
			n++
			if n%diffChunkSize == 0 {
				doRequest(&req)
				req.Candidates = nil
			}
		}
		if req.Candidates != nil {
			doRequest(&req)
		}
		close(missing)
	}()

	return missing
}

// Sync the local database with a remote one. This is a one-way
// synchronization: files missing on the remote side will be uploaded
// to it.
func (db *Database) Sync(remote SyncClient) error {
	var wg sync.WaitGroup

	ch := db.findMissing(remote)

	for i := 0; i < uploadConcurrency; i++ {
		wg.Add(1)
		go func() {
			for id := range ch {
ale's avatar
ale committed
203 204 205 206 207 208
				bookid := ParseID(id)
				if book, err := db.GetBook(bookid); err == nil {
					if files, err := db.GetBookFiles(bookid); err == nil {
						if err := remote.SendBook(book, files); err != nil {
							log.Printf("SendBook(%d): %v", id, err)
						}
ale's avatar
ale committed
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
					}
				}
			}
			wg.Done()
		}()
	}
	wg.Wait()
	return nil
}

type syncServer struct {
	db      *Database
	storage *FileStorage
}

func (l *syncServer) handleDiffRequest(w http.ResponseWriter, req *http.Request) {
	if req.Header.Get("Content-Type") != "application/json" {
		http.Error(w, "Bad Request", http.StatusBadRequest)
		return
	}

	var diffreq diffRequest
	if err := json.NewDecoder(req.Body).Decode(&diffreq); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	var resp diffResponse
	for _, c := range diffreq.Candidates {
		// For every unique ID, decode it into a template
		// Metadata object and see if we can find a match in
		// the database.
		found := false
		for _, unique := range c.Unique {
			meta, err := parseUniqueId(unique)
			if err != nil {
				continue
			}
			if _, err := l.db.Find(meta); err == nil {
				found = true
				break
			}
		}
		if !found {
			resp.Missing = append(resp.Missing, c.Id)
		}
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(&resp)
}

func (l *syncServer) handleSyncUpload(w http.ResponseWriter, req *http.Request) {
	mf, _, err := req.FormFile("meta")
	if err != nil {
		log.Printf("request with no 'meta' field")
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	var md Metadata
	if err := json.NewDecoder(mf).Decode(&md); err != nil {
		log.Printf("error decoding metadata: %v", err)
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	// Check again that we don't have this book.
	if _, err := l.db.Find(&md); err == nil {
		log.Printf("attempt to upload duplicate: %#v", &md)
		http.Error(w, "Duplicate", http.StatusConflict)
		return
	}

	// Create a new Book with a local ID and path.
	bookid := NewID()
	book := &Book{
		Id:       bookid,
		Metadata: &md,
	}

ale's avatar
ale committed
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
	// Save the file data to our local storage.
	for i := 0; i < 10; i++ {
		// Use a temporary file, we'll know the right
		// extension to use only after having parsed the
		// file's MIME header.
		tmppath := l.storage.Path(fmt.Sprintf("%d.%d.tmp", bookid, i))
		varname := fmt.Sprintf("book%d", i)
		size, hdr, err := savePart(req, varname, l.storage, tmppath)
		if err == http.ErrMissingFile {
			break
		} else if err != nil {
			log.Printf("error saving local file: %v", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		filetype := filepath.Ext(hdr.Filename)
		path := l.storage.Path(fmt.Sprintf("%d.%d%s", bookid, i, filetype))
		if err := l.storage.Rename(tmppath, path); err != nil {
			log.Printf("error moving local file: %v", err)
		}

		file := &File{
			Path:     path,
			FileType: filetype,
			Mtime:    time.Now(),
			Size:     size,
			Id:       bookid,
		}
		if err := l.db.PutFile(file); err != nil {
			log.Printf("error saving file to the database: %v", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
ale's avatar
ale committed
323 324 325
	}

	// If the request contains a cover image, save that as well.
ale's avatar
ale committed
326 327
	coverPath := l.storage.Path(fmt.Sprintf("%s.cover.png", book.Id))
	if _, _, err := savePart(req, "cover", l.storage, coverPath); err == nil {
ale's avatar
ale committed
328 329 330 331 332 333 334 335 336 337 338 339 340
		book.CoverPath = coverPath
	}

	if err := l.db.PutBook(book); err != nil {
		log.Printf("error saving book to the database: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// Empty 200 OK response.
	w.WriteHeader(200)
}

ale's avatar
ale committed
341 342
func savePart(req *http.Request, fieldname string, storage *FileStorage, outname string) (int64, *multipart.FileHeader, error) {
	f, hdr, err := req.FormFile(fieldname)
ale's avatar
ale committed
343
	if err != nil {
ale's avatar
ale committed
344
		return 0, nil, err
ale's avatar
ale committed
345 346 347 348
	}

	outf, err := storage.Create(outname)
	if err != nil {
ale's avatar
ale committed
349
		return 0, nil, err
ale's avatar
ale committed
350 351 352
	}
	defer outf.Close()

ale's avatar
ale committed
353 354 355
	n, err := io.Copy(outf, f)
	if err != nil {
		return 0, nil, err
ale's avatar
ale committed
356 357
	}

ale's avatar
ale committed
358
	return n, hdr, nil
ale's avatar
ale committed
359
}