all repos — honk @ 3cd37d058cfd4b51c0d8fc470faabba9af050458

my fork of honk

backend.go (view raw)

  1//
  2// Copyright (c) 2019 Ted Unangst <tedu@tedunangst.com>
  3//
  4// Permission to use, copy, modify, and distribute this software for any
  5// purpose with or without fee is hereby granted, provided that the above
  6// copyright notice and this permission notice appear in all copies.
  7//
  8// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 10// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 11// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 12// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 13// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 14// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 15
 16package main
 17
 18import (
 19	"bytes"
 20	"log"
 21	"net"
 22	"net/rpc"
 23	"os"
 24	"os/exec"
 25
 26	"humungus.tedunangst.com/r/webs/image"
 27)
 28
 29type Shrinker struct {
 30}
 31
 32type ShrinkerArgs struct {
 33	Buf    []byte
 34	Params image.Params
 35}
 36
 37type ShrinkerResult struct {
 38	Image *image.Image
 39}
 40
 41func (s *Shrinker) Shrink(args *ShrinkerArgs, res *ShrinkerResult) error {
 42	img, err := image.Vacuum(bytes.NewReader(args.Buf), args.Params)
 43	if err != nil {
 44		return err
 45	}
 46	res.Image = img
 47	return nil
 48}
 49
 50func backendSockname() string {
 51	return dataDir + "/backend.sock"
 52}
 53
 54func shrinkit(data []byte) (*image.Image, error) {
 55	cl, err := rpc.Dial("unix", backendSockname())
 56	if err != nil {
 57		return nil, err
 58	}
 59	defer cl.Close()
 60	var res ShrinkerResult
 61	err = cl.Call("Shrinker.Shrink", &ShrinkerArgs{
 62		Buf:    data,
 63		Params: image.Params{LimitSize: 4200 * 4200, MaxWidth: 2048, MaxHeight: 2048},
 64	}, &res)
 65	if err != nil {
 66		return nil, err
 67	}
 68	return res.Image, nil
 69}
 70
 71func backendServer() {
 72	log.Printf("backend server running")
 73	shrinker := new(Shrinker)
 74	srv := rpc.NewServer()
 75	err := srv.Register(shrinker)
 76	if err != nil {
 77		log.Panicf("unable to register shrinker: %s", err)
 78	}
 79
 80	sockname := backendSockname()
 81	err = os.Remove(sockname)
 82	if err != nil && !os.IsNotExist(err) {
 83		log.Panicf("unable to unlink socket: %s", err)
 84	}
 85
 86	lis, err := net.Listen("unix", sockname)
 87	if err != nil {
 88		log.Panicf("unable to register shrinker: %s", err)
 89	}
 90	for _, h := range preservehooks {
 91		h()
 92	}
 93	srv.Accept(lis)
 94}
 95
 96func startBackendServer() {
 97	proc := exec.Command(os.Args[0], "-datadir", dataDir, "backend")
 98	proc.Stdout = os.Stdout
 99	proc.Stderr = os.Stderr
100	err := proc.Start()
101	if err != nil {
102		log.Panicf("can't exec backend: %s", err)
103	}
104}