239 lines
9.3 KiB
Go
239 lines
9.3 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
cityReadTimeout = 2 * time.Second
|
|
MaxCityMapNodes = 4096
|
|
MaxCityMapPagePlacements = 20000
|
|
MaxCityMapRelations = 8192
|
|
)
|
|
|
|
var ErrCityMapBudget = errors.New("City map exceeds the bounded projection budget")
|
|
|
|
// These helpers accept only SQL expressions owned by this package, never user
|
|
// input. Binary segment ranges preserve literal %, _, case and Unicode. The
|
|
// normalized root '/' covers all absolute Paths; an empty legacy boundary
|
|
// covers none. Paths and UUIDs are not rewritten to manufacture SQL patterns.
|
|
func cityPathScopeSQL(parent, child string) string {
|
|
return `(` + parent + `!='' AND (` + child + ` COLLATE BINARY = ` + parent + ` OR (` + child + ` COLLATE BINARY >= rtrim(` + parent + `,'/')||'/' AND ` + child + ` COLLATE BINARY < rtrim(` + parent + `,'/')||'0')))`
|
|
}
|
|
|
|
func cityPathOverlapSQL(left, right string) string {
|
|
return `(` + cityPathScopeSQL(left, right) + ` OR ` + cityPathScopeSQL(right, left) + `)`
|
|
}
|
|
|
|
type cityReadQuery struct {
|
|
ctx context.Context
|
|
tx *sql.Tx
|
|
}
|
|
|
|
func (q cityReadQuery) Query(query string, args ...any) (*sql.Rows, error) {
|
|
return q.tx.QueryContext(q.ctx, query, args...)
|
|
}
|
|
|
|
// visit always closes its cursor before its caller issues the next query.
|
|
// Visitors only scan/collect; they must not start another database operation.
|
|
func (q cityReadQuery) visit(query string, args []any, scan func(*sql.Rows) error) error {
|
|
rows, err := q.Query(query, args...)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer rows.Close()
|
|
for rows.Next() {
|
|
if err := scan(rows); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return err
|
|
}
|
|
return rows.Close()
|
|
}
|
|
|
|
func (s *Store) GetCityMap(domainUUID string) (CityMap, error) {
|
|
return s.GetCityMapContext(context.Background(), domainUUID)
|
|
}
|
|
|
|
// ListSpotPagesContext is the bounded HTTP/read projection. The existing
|
|
// ListSpotPages remains available to trusted callers that need a complete set.
|
|
func (s *Store) ListSpotPagesContext(parent context.Context, domainUUID, spotUUID string) (_ []CityPagePlacement, resultErr error) {
|
|
defer func() { resultErr = s.sqlError("spot pages", resultErr) }()
|
|
ctx, cancel := context.WithTimeout(parent, cityReadTimeout)
|
|
defer cancel()
|
|
tx, err := s.DB.BeginTx(ctx, s.policyReadOptions())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer tx.Rollback()
|
|
pages, err := s.listSpotPages(cityReadQuery{ctx: ctx, tx: tx}, domainUUID, spotUUID, MaxCityMapPagePlacements+1)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(pages) > MaxCityMapPagePlacements {
|
|
return nil, fmt.Errorf("%w: more than %d Page placements", ErrCityMapBudget, MaxCityMapPagePlacements)
|
|
}
|
|
return pages, nil
|
|
}
|
|
|
|
// GetCityMapContext reads one consistent topology/Page snapshot using exactly
|
|
// one connection. Bulk topology cursors are closed before Page queries. Limits
|
|
// reject a partial model instead of silently showing misleading counts/links.
|
|
func (s *Store) GetCityMapContext(parent context.Context, domainUUID string) (_ CityMap, resultErr error) {
|
|
defer func() { resultErr = s.sqlError("city map", resultErr) }()
|
|
empty := CityMap{DomainUUID: domainUUID, Version: 1, Quartiers: []CityQuartier{}, Relations: []CitySpotRelation{}}
|
|
ctx, cancel := context.WithTimeout(parent, cityReadTimeout)
|
|
defer cancel()
|
|
tx, err := s.DB.BeginTx(ctx, s.policyReadOptions())
|
|
if err != nil {
|
|
return empty, err
|
|
}
|
|
defer tx.Rollback()
|
|
result, err := s.readCityMapTx(cityReadQuery{ctx: ctx, tx: tx}, domainUUID)
|
|
if err != nil {
|
|
return empty, err
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func readCityMapTx(query cityReadQuery, domainUUID string) (CityMap, error) {
|
|
return (&Store{}).readCityMapTx(query, domainUUID)
|
|
}
|
|
|
|
func (s *Store) readCityMapTx(query cityReadQuery, domainUUID string) (CityMap, error) {
|
|
result := CityMap{DomainUUID: domainUUID, Version: 1, Quartiers: []CityQuartier{}, Relations: []CitySpotRelation{}}
|
|
err := query.tx.QueryRowContext(query.ctx, `SELECT version FROM domain_topology_versions WHERE domain_uuid=`+s.sqlParam(1), domainUUID).Scan(&result.Version)
|
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
|
return result, err
|
|
}
|
|
nodes := 0
|
|
checkNode := func() error {
|
|
nodes++
|
|
if nodes > MaxCityMapNodes {
|
|
return fmt.Errorf("%w: more than %d locality nodes", ErrCityMapBudget, MaxCityMapNodes)
|
|
}
|
|
return nil
|
|
}
|
|
quartiers := map[string]int{}
|
|
err = query.visit(`SELECT uuid,name,title,description,state,sort_key,path_prefix FROM zones WHERE domain_uuid=`+s.sqlParam(1)+` AND kind='quartier' AND state!='archived' ORDER BY sort_key,lower(title),name,uuid LIMIT `+s.sqlParam(2), []any{domainUUID, MaxCityMapNodes + 1}, func(rows *sql.Rows) error {
|
|
if err := checkNode(); err != nil {
|
|
return err
|
|
}
|
|
q := CityQuartier{Streets: []CityStreet{}}
|
|
if err := rows.Scan(&q.UUID, &q.Name, &q.Title, &q.Description, &q.State, &q.SortKey, &q.PathPrefix); err != nil {
|
|
return err
|
|
}
|
|
quartiers[q.UUID] = len(result.Quartiers)
|
|
result.Quartiers = append(result.Quartiers, q)
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return result, err
|
|
}
|
|
type streetIndex struct{ quartier, street int }
|
|
streets := map[string]streetIndex{}
|
|
err = query.visit(`SELECT st.parent_uuid,st.uuid,st.name,st.title,st.description,st.state,st.sort_key,st.path_prefix
|
|
FROM zones st JOIN zones q ON q.uuid=st.parent_uuid AND q.domain_uuid=st.domain_uuid AND q.kind='quartier' AND q.state!='archived'
|
|
WHERE st.domain_uuid=`+s.sqlParam(1)+` AND st.kind='street' AND st.state!='archived' ORDER BY st.sort_key,lower(st.title),st.name,st.uuid LIMIT `+s.sqlParam(2), []any{domainUUID, MaxCityMapNodes - nodes + 1}, func(rows *sql.Rows) error {
|
|
if err := checkNode(); err != nil {
|
|
return err
|
|
}
|
|
var parent string
|
|
st := CityStreet{Spots: []CitySpot{}}
|
|
if err := rows.Scan(&parent, &st.UUID, &st.Name, &st.Title, &st.Description, &st.State, &st.SortKey, &st.PathPrefix); err != nil {
|
|
return err
|
|
}
|
|
q, ok := quartiers[parent]
|
|
if !ok {
|
|
return errors.New("City snapshot has an inconsistent Street parent")
|
|
}
|
|
streets[st.UUID] = streetIndex{q, len(result.Quartiers[q].Streets)}
|
|
result.Quartiers[q].Streets = append(result.Quartiers[q].Streets, st)
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return result, err
|
|
}
|
|
spots := map[string]bool{}
|
|
err = query.visit(`SELECT ss.street_uuid,p.uuid,p.name,p.title,p.summary,p.state,ss.sort_key,p.path_prefix
|
|
FROM street_spots ss JOIN spots p ON p.uuid=ss.spot_uuid
|
|
JOIN zones st ON st.uuid=ss.street_uuid AND st.domain_uuid=p.domain_uuid AND st.kind='street' AND st.state!='archived'
|
|
JOIN zones q ON q.uuid=st.parent_uuid AND q.domain_uuid=st.domain_uuid AND q.kind='quartier' AND q.state!='archived'
|
|
WHERE p.domain_uuid=`+s.sqlParam(1)+` AND p.state!='archived' ORDER BY ss.sort_key,lower(p.title),p.name,p.uuid LIMIT `+s.sqlParam(2), []any{domainUUID, MaxCityMapNodes - nodes + 1}, func(rows *sql.Rows) error {
|
|
if err := checkNode(); err != nil {
|
|
return err
|
|
}
|
|
var parent string
|
|
spot := CitySpot{Pages: []CityPagePlacement{}}
|
|
if err := rows.Scan(&parent, &spot.UUID, &spot.Name, &spot.Title, &spot.Summary, &spot.State, &spot.SortKey, &spot.PathPrefix); err != nil {
|
|
return err
|
|
}
|
|
index, ok := streets[parent]
|
|
if !ok {
|
|
return errors.New("City snapshot has an inconsistent Spot parent")
|
|
}
|
|
street := &result.Quartiers[index.quartier].Streets[index.street]
|
|
street.Spots = append(street.Spots, spot)
|
|
spots[spot.UUID] = true
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return result, err
|
|
}
|
|
pageCount := 0
|
|
for qi := range result.Quartiers {
|
|
for si := range result.Quartiers[qi].Streets {
|
|
for pi := range result.Quartiers[qi].Streets[si].Spots {
|
|
spot := &result.Quartiers[qi].Streets[si].Spots[pi]
|
|
pages, err := s.listSpotPages(query, domainUUID, spot.UUID, MaxCityMapPagePlacements-pageCount+1)
|
|
if err != nil {
|
|
return result, err
|
|
}
|
|
pageCount += len(pages)
|
|
if pageCount > MaxCityMapPagePlacements {
|
|
return result, fmt.Errorf("%w: more than %d Page placements", ErrCityMapBudget, MaxCityMapPagePlacements)
|
|
}
|
|
if len(pages) == 0 {
|
|
continue
|
|
}
|
|
spot.Pages = pages
|
|
unique := map[string]bool{}
|
|
portal := pages[0]
|
|
for _, page := range pages {
|
|
unique[page.PageUUID] = true
|
|
if page.Path == spot.PathPrefix || (portal.Path != spot.PathPrefix && page.EdgeType == "primary" && portal.EdgeType != "primary") {
|
|
portal = page
|
|
}
|
|
}
|
|
spot.PageCount = len(unique)
|
|
spot.PortalPath, spot.PortalPageUUID = portal.Path, portal.PageUUID
|
|
}
|
|
}
|
|
}
|
|
relations := 0
|
|
err = query.visit(`SELECT r.source_spot_uuid,r.target_spot_uuid,r.relation_type,r.weight FROM spot_relations r
|
|
JOIN spots a ON a.uuid=r.source_spot_uuid AND a.domain_uuid=`+s.sqlParam(1)+` AND a.state!='archived'
|
|
JOIN spots b ON b.uuid=r.target_spot_uuid AND b.domain_uuid=`+s.sqlParam(2)+` AND b.state!='archived'
|
|
ORDER BY r.relation_type,r.source_spot_uuid,r.target_spot_uuid LIMIT `+s.sqlParam(3), []any{domainUUID, domainUUID, MaxCityMapRelations + 1}, func(rows *sql.Rows) error {
|
|
relations++
|
|
if relations > MaxCityMapRelations {
|
|
return fmt.Errorf("%w: more than %d relations", ErrCityMapBudget, MaxCityMapRelations)
|
|
}
|
|
var relation CitySpotRelation
|
|
if err := rows.Scan(&relation.SourceSpotUUID, &relation.TargetSpotUUID, &relation.RelationType, &relation.Weight); err != nil {
|
|
return err
|
|
}
|
|
if spots[relation.SourceSpotUUID] && spots[relation.TargetSpotUUID] {
|
|
result.Relations = append(result.Relations, relation)
|
|
}
|
|
return nil
|
|
})
|
|
return result, err
|
|
}
|