Skip to content
quarry Artifact [b73d554253]
Login

Artifact [b73d554253]

Artifact b73d5542539052b847b818fd2d57119cd34a16947d9a6b60d4e3148b18f3eca1:


// chatkey.go is the key of a repository's chat channel.
//
// A channel and the robot lines kept for it used to be keyed by the
// store's project code, which two repositories of one project share (two
// mirrors of one upstream, a mirror and a fork), so they shared a
// channel too, a private one's included. The key is now the
// repository's own, assigned once and kept in its row. The project code
// stays what it was: the project's.
package oltp

import (
	"database/sql"
	"errors"
	"strconv"
	"strings"
)

// ChatKeyRow is one repository as the chat key migration reads it.
type ChatKeyRow struct {
	Name       string
	Path       string
	State      string
	Visibility string
	// Code is the project code recorded for the store, "" when none.
	Code string
	// Key is the chat key, "" until one is assigned.
	Key string
}

// ChatKeyRows lists every repository with the code and chat key its row
// holds, name-ordered.
func (d *DB) ChatKeyRows() ([]ChatKeyRow, error) {
	rows, err := d.db.Query(`SELECT name, path, state, visibility, code, chat_key FROM repo ORDER BY name`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []ChatKeyRow
	for rows.Next() {
		var r ChatKeyRow
		if err := rows.Scan(&r.Name, &r.Path, &r.State, &r.Visibility, &r.Code, &r.Key); err != nil {
			return nil, err
		}
		out = append(out, r)
	}
	return out, rows.Err()
}

// ChatKey is the key of a repository's chat channel, "" when none is
// assigned or the repository is not registered.
func (d *DB) ChatKey(name string) (string, error) {
	var key string
	err := d.db.QueryRow(`SELECT chat_key FROM repo WHERE name = ?`, name).Scan(&key)
	if errors.Is(err, sql.ErrNoRows) {
		return "", nil
	}
	return key, err
}

const chatKeyCohortSchema = `
CREATE TABLE IF NOT EXISTS chat_key_cohort (
	name TEXT PRIMARY KEY
);
CREATE TABLE IF NOT EXISTS chat_key_meta (
	k TEXT PRIMARY KEY,
	v INTEGER NOT NULL
);`

// ChatKeyCohort answers the names of the repositories that existed
// without a chat key when keys were introduced, and so may have a
// history under their project code to be settled. It is captured once,
// by the first call, and only shrinks after: a repository that appears
// later has no such history, whatever code it holds, and is never
// given a copy of anyone's channel.
func (d *DB) ChatKeyCohort() (map[string]bool, error) {
	err := d.runOnce("chat-key-cohort", func() error {
		_, err := d.w.Exec(`INSERT OR IGNORE INTO chat_key_cohort (name)
			SELECT name FROM repo WHERE chat_key = ''`)
		return err
	})
	if err != nil {
		return nil, err
	}
	rows, err := d.db.Query(`SELECT name FROM chat_key_cohort`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	out := map[string]bool{}
	for rows.Next() {
		var n string
		if err := rows.Scan(&n); err != nil {
			return nil, err
		}
		out[n] = true
	}
	return out, rows.Err()
}

// ChatKeyCeiling is the stream sequence at which channels were split: a
// copy of a shared channel may carry only what was said at or below it.
// The first call records last, the stream's last sequence at that
// moment, and every later one answers that same number.
func (d *DB) ChatKeyCeiling(last uint64) (uint64, error) {
	if _, err := d.w.Exec(`INSERT OR IGNORE INTO chat_key_meta (k, v) VALUES ('ceiling', ?)`, last); err != nil {
		return 0, err
	}
	var v uint64
	err := d.db.QueryRow(`SELECT v FROM chat_key_meta WHERE k = 'ceiling'`).Scan(&v)
	return v, err
}

// AssignChatKey gives a repository the chat key key unless it has one,
// and answers the key it now holds. It never changes a key: the channel
// and the rows kept for it are under the first. It leaves a repository's
// cohort membership (ChatKeyCohort) alone only when it gives it no key.
func (d *DB) AssignChatKey(name, key string) (string, error) {
	if _, err := d.w.Exec(`UPDATE repo SET chat_key = ? WHERE name = ? AND chat_key = ''`, key, name); err != nil {
		return "", err
	}
	if _, err := d.w.Exec(`DELETE FROM chat_key_cohort WHERE name = ?`, name); err != nil {
		return "", err
	}
	return d.ChatKey(name)
}

// RekeyChatSeqs rewrites the rows a repository keeps about the messages
// of its chat channel after those messages were given new sequences:
// each old sequence in seqs becomes the sequence it maps to, and a row
// about a sequence that is not in it is dropped. An empty map is a
// channel that starts over, and clears them all.
//
// A read pointer is "seen up to N", so it moves to the new sequence of
// the last message at or below N and is dropped when there is none.
// Rows that say nothing about the channel (a bridge's own cursor on the
// upstream) are left alone.
//
// The rows and the key are one transaction: a repository that has a key
// has had its rows rewritten, and one that has none has not, so a run
// cut short is repeated from the start without rewriting twice. It does
// nothing for a repository that already has a key.
func (d *DB) RekeyChatSeqs(repo, key string, seqs map[uint64]uint64) error {
	tx, err := d.w.Begin()
	if err != nil {
		return err
	}
	defer tx.Rollback()
	var have string
	if err := tx.QueryRow(`SELECT chat_key FROM repo WHERE name = ?`, repo).Scan(&have); err != nil {
		return err
	}
	if have != "" {
		return nil
	}

	// chat_read: one row per account, floor-mapped.
	if err := rewrite(tx, repo,
		`SELECT account, seq, at FROM chat_read WHERE repo = ?`,
		`DELETE FROM chat_read WHERE repo = ?`,
		`INSERT INTO chat_read (repo, account, seq, at) VALUES (?, ?, ?, ?)`,
		func(v []any) ([]any, bool) {
			n, ok := floor(seqs, uint64(v[1].(int64)))
			if !ok {
				return nil, false
			}
			return []any{repo, v[0], n, v[2]}, true
		}, 3); err != nil {
		return err
	}
	exact := func(sel, del, ins string, cols, seqCol int, mk func(v []any, n uint64) []any) error {
		return rewrite(tx, repo, sel, del, ins, func(v []any) ([]any, bool) {
			n, ok := seqs[uint64(v[seqCol].(int64))]
			if !ok {
				return nil, false
			}
			return mk(v, n), true
		}, cols)
	}
	if err := exact(`SELECT name, size, type, sha256, who, created, seq FROM chat_file WHERE repo = ?`,
		`DELETE FROM chat_file WHERE repo = ?`,
		`INSERT INTO chat_file (repo, seq, name, size, type, sha256, who, created) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
		7, 6, func(v []any, n uint64) []any { return []any{repo, n, v[0], v[1], v[2], v[3], v[4], v[5]} }); err != nil {
		return err
	}
	if err := exact(`SELECT target, at, seq FROM chat_ref WHERE repo = ?`,
		`DELETE FROM chat_ref WHERE repo = ?`,
		`INSERT INTO chat_ref (repo, target, seq, at) VALUES (?, ?, ?, ?)`,
		3, 2, func(v []any, n uint64) []any { return []any{repo, v[0], n, v[1]} }); err != nil {
		return err
	}
	// chat_reply names two sequences; both must have been copied.
	if err := rewrite(tx, repo,
		`SELECT ref_seq, seq FROM chat_reply WHERE repo = ?`,
		`DELETE FROM chat_reply WHERE repo = ?`,
		`INSERT OR IGNORE INTO chat_reply (repo, ref_seq, seq) VALUES (?, ?, ?)`,
		func(v []any) ([]any, bool) {
			a, ok1 := seqs[uint64(v[0].(int64))]
			b, ok2 := seqs[uint64(v[1].(int64))]
			return []any{repo, a, b}, ok1 && ok2
		}, 2); err != nil {
		return err
	}
	if err := exact(`SELECT msgid, seq FROM mirror_chatbridge_msg WHERE repo = ?`,
		`DELETE FROM mirror_chatbridge_msg WHERE repo = ?`,
		`INSERT OR IGNORE INTO mirror_chatbridge_msg (repo, msgid, seq) VALUES (?, ?, ?)`,
		2, 1, func(v []any, n uint64) []any { return []any{repo, v[0], n} }); err != nil {
		return err
	}
	// mention names a chat line as "chat:<seq>"; a forum mention is not
	// about the channel and stays.
	if err := rewrite(tx, repo,
		`SELECT ref, who, by, at FROM mention WHERE repo = ? AND ref LIKE 'chat:%'`,
		`DELETE FROM mention WHERE repo = ? AND ref LIKE 'chat:%'`,
		`INSERT OR IGNORE INTO mention (repo, ref, who, by, at) VALUES (?, ?, ?, ?, ?)`,
		func(v []any) ([]any, bool) {
			old, err := strconv.ParseUint(strings.TrimPrefix(v[0].(string), "chat:"), 10, 64)
			if err != nil {
				return nil, false
			}
			n, ok := seqs[old]
			return []any{repo, "chat:" + strconv.FormatUint(n, 10), v[1], v[2], v[3]}, ok
		}, 4); err != nil {
		return err
	}
	if _, err := tx.Exec(`UPDATE repo SET chat_key = ? WHERE name = ?`, key, repo); err != nil {
		return err
	}
	if _, err := tx.Exec(`DELETE FROM chat_key_cohort WHERE name = ?`, repo); err != nil {
		return err
	}
	return tx.Commit()
}

// rewrite reads a repository's rows, deletes them and inserts what
// keep returns for each. cols is how many values sel returns; every
// value arrives as the driver gives it, integers as int64.
func rewrite(tx *sql.Tx, repo, sel, del, ins string, keep func([]any) ([]any, bool), cols int) error {
	rows, err := tx.Query(sel, repo)
	if err != nil {
		return err
	}
	var kept [][]any
	for rows.Next() {
		v := make([]any, cols)
		ptrs := make([]any, cols)
		for i := range v {
			ptrs[i] = &v[i]
		}
		if err := rows.Scan(ptrs...); err != nil {
			rows.Close()
			return err
		}
		for i, x := range v {
			if b, ok := x.([]byte); ok {
				v[i] = string(b)
			}
		}
		if out, ok := keep(v); ok {
			kept = append(kept, out)
		}
	}
	if err := rows.Err(); err != nil {
		rows.Close()
		return err
	}
	rows.Close()
	if _, err := tx.Exec(del, repo); err != nil {
		return err
	}
	for _, out := range kept {
		if _, err := tx.Exec(ins, out...); err != nil {
			return err
		}
	}
	return nil
}

// floor is the new sequence of the greatest old sequence <= at.
func floor(seqs map[uint64]uint64, at uint64) (uint64, bool) {
	var best, found uint64
	for old, n := range seqs {
		if old <= at && old >= best && n != 0 {
			best, found = old, n
		}
	}
	return found, found != 0
}