view calsync/main.go @ 80:e8164bd2f9a1

hoist startupJitter to main
author drewp@bigasterisk.com
date Fri, 06 Sep 2024 18:25:32 -0700
parents 329144c7e711
children 0f0b15d8062c
line wrap: on
line source

package main

/*
go build && ./gcalendarwatch


let python continue to serve these:
		Route('/', getRoot),
		Route('/graph/calendar/upcoming', StaticGraph(agendaGraph)),
		use https://github.com/cayleygraph/quad
		Route('/graph/calendar/upcoming/events', GraphEvents(agendaGraph)),
		use https://github.com/tmaxmax/go-sse
		Route('/graph/calendar/countdown', StaticGraph(countdownGraph)),
		Route('/graph/calendar/countdown/events', GraphEvents(countdownGraph)),
		Route('/graph/currentEvents', StaticGraph(currentEventsGraph)),
		Route('/graph/currentEvents/events', GraphEvents(currentEventsGraph)),
*/

import (
	"context"
	"log"
	"net/http"
	"time"

	"bigasterisk.com/go/gcalendarwatch/gcalclient"
	"bigasterisk.com/go/gcalendarwatch/mongoclient"
	"bigasterisk.com/go/gcalendarwatch/notificationrouter"
	"github.com/gorilla/mux"
)

const startupJitter = 0 * time.Second

func main() {
	startLogging()
	ctx := context.Background()

	gc, err := gcalclient.New(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer gc.Close()

	mc, err := mongoclient.New(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer mc.Close()

	notifications := notificationrouter.New()

	// todo: if a cal is deleted, we don't clean up its events, even upon
	// restart.
	err = updateMongoCalsToMatchGoogleOnce(mc, gc)
	if err != nil {
		log.Fatal(err)
	}

	initialSyncBack := (7 * 24) * time.Hour
	initialSyncAhead := (14 * 24) * time.Hour
	err = updateMongoEventsToMatchGoogleForever(mc, gc, initialSyncBack, initialSyncAhead, notifications, startupJitter)
	if err != nil {
		log.Fatal(err)
	}

	r := mux.NewRouter()
	http.Handle("/", r)

	r.HandleFunc("/", homePage)
	r.HandleFunc("/gcalendarwatch", homePage)
	r.HandleFunc("/gcalendarwatch/notifications", notifications.NotificationHandler).Methods("POST")

	addr := ":8080"
	log.Println("serving /gcalendarwatch/notifications on", addr)
	log.Fatal(http.ListenAndServe(addr, nil))
}

func startLogging() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	log.Println(`
	==================================================
                    calsync
	  ----------------------------------------------`)
}

func homePage(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("calsync service for calendar updates. See https://console.cloud.google.com/apis/api/calendar-json.googleapis.com/metrics?project=bigasterisk-910"))
}