xt/service.go

373 lines
6.4 KiB
Go
Raw Permalink Normal View History

2024-11-10 13:23:00 -07:00
package main
import (
2024-11-20 09:05:05 -07:00
"cmp"
2024-11-10 13:23:00 -07:00
"database/sql"
2024-11-11 19:13:34 -07:00
"errors"
2024-11-10 13:23:00 -07:00
"fmt"
"io"
2024-11-11 19:13:34 -07:00
"iter"
2024-11-10 14:25:43 -07:00
"net/url"
2024-11-10 13:23:00 -07:00
"os"
2024-11-11 19:13:34 -07:00
"path/filepath"
"slices"
2024-11-10 13:23:00 -07:00
"strings"
"time"
_ "embed"
_ "github.com/mattn/go-sqlite3"
"go.yarn.social/lextwt"
2024-11-11 19:13:34 -07:00
"go.yarn.social/types"
2024-11-10 13:23:00 -07:00
)
func run(c console) error {
a := c.Args()
2024-11-20 09:05:05 -07:00
db, err := setupDB(c)
2024-11-10 13:23:00 -07:00
if err != nil {
return err
}
defer db.Close()
c.Set("db", db)
f, err := os.Open(a.baseFeed)
if err != nil {
return err
}
2024-11-20 09:05:05 -07:00
twtfile, err := lextwt.ParseFile(f, &types.Twter{
Nick: a.Nick,
URI: a.URI,
})
if err != nil {
return fmt.Errorf("%w: %w", ErrParseFailed, err)
}
f.Close()
err = storeFeed(db, twtfile)
2024-11-10 13:23:00 -07:00
if err != nil {
return err
}
c.Log("ready")
go refreshLoop(c)
<-c.Done()
return nil
}
var (
//go:embed init.sql
initSQL string
insertFeed = `
insert into feeds
(feed_id, uri, nick, last_scan_on, refresh_rate)
values (?, ?, ?, ?, ?)
ON CONFLICT (feed_id) DO NOTHING
`
2024-11-20 09:05:05 -07:00
2024-11-10 13:23:00 -07:00
insertTwt = `
insert into twts
(feed_id, hash, conv, dt, text, mentions, tags)
values (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (feed_id, hash) DO NOTHING
`
fetchFeeds = `
2024-11-11 19:13:34 -07:00
select
feed_id,
uri,
nick,
last_scan_on,
refresh_rate,
last_modified_on,
last_etag
from feeds
2024-11-10 13:23:00 -07:00
`
updateFeed = `
update feeds set
last_scan_on = ?,
2024-11-11 19:13:34 -07:00
refresh_rate = ?,
last_modified_on = ?,
last_etag = ?,
last_error = ?
2024-11-10 13:23:00 -07:00
where feed_id = ?
`
)
2024-11-20 09:05:05 -07:00
func setupDB(c console) (*sql.DB, error) {
a := c.Args()
db, err := sql.Open(a.dbtype, a.dbfile)
2024-11-10 13:23:00 -07:00
if err != nil {
2024-11-20 09:05:05 -07:00
return nil, err
2024-11-10 13:23:00 -07:00
}
2024-11-20 09:05:05 -07:00
for _, stmt := range strings.Split(initSQL, ";") {
_, err = db.ExecContext(c, stmt)
2024-11-10 13:23:00 -07:00
if err != nil {
2024-11-20 09:05:05 -07:00
return nil, err
2024-11-10 13:23:00 -07:00
}
}
2024-11-20 09:05:05 -07:00
return db, nil
2024-11-10 13:23:00 -07:00
}
func refreshLoop(c console) {
2024-11-11 19:13:34 -07:00
defer c.abort()
TenYear := 3153600000 // 10 year
OneDay := 86400 // 1 day
2024-11-20 09:05:05 -07:00
TenMinutes := 600 // 10 mins
2024-11-11 19:13:34 -07:00
fetch := NewHTTPFetcher()
2024-11-10 13:23:00 -07:00
2024-11-20 09:05:05 -07:00
queue := FibHeap(func(a, b *Feed) bool {
2024-11-10 13:23:00 -07:00
return a.LastScanOn.Time.Before(b.LastScanOn.Time)
2024-11-20 09:05:05 -07:00
})
2024-11-10 13:23:00 -07:00
db := c.Get("db").(*sql.DB)
2024-11-11 19:13:34 -07:00
c.Log("start refresh loop")
for c.Err() == nil {
if queue.IsEmpty() {
it, err := LoadFeeds(c)
for f := range it {
queue.Insert(&f)
}
if err != nil {
c.Log(err)
return
}
2024-11-10 13:23:00 -07:00
}
f := queue.ExtractMin()
2024-11-11 19:13:34 -07:00
c.Log("queue size", queue.count, "next", f.URI, "last scan on", f.LastScanOn.Time.Format(time.RFC3339))
if time.Until(f.LastScanOn.Time) > 2*time.Hour {
c.Log("too soon", f.URI)
continue
}
2024-11-10 14:25:43 -07:00
2024-11-10 13:23:00 -07:00
select {
case <-c.Done():
return
2024-11-10 14:25:43 -07:00
case <-time.After(time.Until(f.LastScanOn.Time)):
2024-11-10 13:23:00 -07:00
}
2024-11-11 19:13:34 -07:00
res, err := fetch.Fetch(c.Context, f)
2024-11-10 13:23:00 -07:00
if err != nil {
2024-11-11 19:13:34 -07:00
f.LastError.String, f.LastError.Valid = err.Error(), true
if errors.Is(err, ErrPermanentlyDead) {
f.RefreshRate = TenYear
}
if errors.Is(err, ErrTemporarilyDead) {
f.RefreshRate = OneDay
}
if errors.Is(err, ErrUnmodified) {
f.RefreshRate = OneDay
}
2024-11-10 13:23:00 -07:00
c.Log(err)
2024-11-11 19:13:34 -07:00
err = f.Save(c.Context, db)
2024-11-10 13:23:00 -07:00
if err != nil {
c.Log(err)
return
}
continue
}
2024-11-11 19:13:34 -07:00
f.ETag.String, f.ETag.Valid = res.ETag(), true
f.LastModified.Time, f.LastModified.Valid = res.LastModified(), true
cpy, err := os.OpenFile(filepath.Join("feeds", urlNS.UUID5(f.URI).MarshalText()), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
rdr := io.TeeReader(res.Body, cpy)
2024-11-20 09:05:05 -07:00
twtfile, err := lextwt.ParseFile(rdr, &types.Twter{Nick: f.Nick, URI: f.URI})
if err != nil {
c.Log(fmt.Errorf("%w: %w", ErrParseFailed, err))
return
}
if prev, ok :=twtfile.Info().GetN("prev", 0); ok {
_, part, ok := strings.Cut(prev.Value(), " ")
if ok {
part = f.URI[:strings.LastIndex(f.URI, "/")+1] + part
queue.Insert(&Feed{
FetchURI: part,
URI: f.URI,
Nick: f.Nick,
LastScanOn: f.LastScanOn,
RefreshRate: f.RefreshRate,
})
}
}
err = storeFeed(db, twtfile)
2024-11-10 13:23:00 -07:00
if err != nil {
2024-11-11 19:13:34 -07:00
c.Log(err)
return
}
cpy.Close()
f.LastScanOn.Time = time.Now()
f.RefreshRate = TenMinutes
f.LastError.String = ""
err = f.Save(c.Context, db)
if err != nil {
c.Log(err)
return
}
}
}
2024-11-20 09:05:05 -07:00
func storeFeed(db *sql.DB, f types.TwtFile) error {
loadTS := time.Now()
refreshRate := 600
feedID := urlNS.UUID5(cmp.Or(f.Twter().HashingURI, f.Twter().URI))
tx, err := db.Begin()
if err != nil {
return err
}
followers := f.Info().GetAll("follow")
followMap := make(map[string]string, len(followers))
for _, f := range f.Info().GetAll("follow") {
nick, uri, ok := strings.Cut(f.Value(), "http")
if !ok {
continue
}
nick = strings.TrimSpace(nick)
uri = "http" + strings.TrimSpace(uri)
if _, err := url.Parse(uri); err != nil {
continue
}
followMap[nick] = uri
}
defer tx.Rollback()
_, err = tx.Exec(
insertFeed,
feedID,
f.Twter().HashingURI,
f.Twter().DomainNick(),
loadTS,
refreshRate,
)
if err != nil {
return err
}
for _, twt := range f.Twts() {
mentions := make(uuids, 0, len(twt.Mentions()))
for _, mention := range twt.Mentions() {
followMap[mention.Twter().Nick] = mention.Twter().URI
mentions = append(mentions, urlNS.UUID5(mention.Twter().URI))
}
tags := make(strList, 0, len(twt.Tags()))
for _, tag := range twt.Tags() {
tags = append(tags, tag.Text())
}
subject := twt.Subject()
subjectTag := ""
if subject != nil {
if tag, ok := subject.Tag().(*lextwt.Tag); ok && tag != nil {
subjectTag = tag.Text()
}
}
_, err = tx.Exec(
insertTwt,
feedID,
twt.Hash(),
subjectTag,
twt.Created(),
fmt.Sprint(twt),
mentions.ToStrList(),
tags,
)
if err != nil {
return err
}
}
for nick, uri := range followMap {
_, err = tx.Exec(
insertFeed,
urlNS.UUID5(uri),
uri,
nick,
nil,
refreshRate,
)
if err != nil {
return err
}
}
return tx.Commit()
}
2024-11-11 19:13:34 -07:00
func LoadFeeds(c console) (iter.Seq[Feed], error) {
var err error
var res *sql.Rows
db := c.Get("db").(*sql.DB)
res, err = db.QueryContext(c.Context, fetchFeeds)
if err != nil {
return slices.Values([]Feed{}), err
}
c.Log("load feeds")
return func(yield func(Feed) bool) {
for res.Next() {
var f Feed
f.Version = "0.0.1"
err = res.Scan(
&f.FeedID,
&f.URI,
&f.Nick,
&f.LastScanOn,
&f.RefreshRate,
&f.LastModified,
&f.ETag,
)
2024-11-10 13:23:00 -07:00
if err != nil {
2024-11-11 19:13:34 -07:00
return
2024-11-10 13:23:00 -07:00
}
2024-11-11 19:13:34 -07:00
if !f.LastScanOn.Valid {
f.LastScanOn.Time = time.Now()
f.LastScanOn.Valid = true
} else {
f.LastScanOn.Time = f.LastScanOn.Time.Add(time.Duration(f.RefreshRate) * time.Second)
}
2024-11-10 13:23:00 -07:00
2024-11-20 09:05:05 -07:00
f.FetchURI = f.URI
2024-11-11 19:13:34 -07:00
if !yield(f) {
return
}
}
}, err
}