oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package conversation
2
3import (
4 "amadan.net/oficina/equipo/internal/equipo/kernel"
5 "context"
6 "crypto/sha256"
7 "database/sql"
8 "encoding/json"
9 "errors"
10 "fmt"
11 "net/http"
12 "strings"
13 "time"
14
15 "amadan.net/oficina/equipo/internal/equipo/identity"
16 "gorm.io/gorm"
17)
18
19func PersonalTopic(team, person string) string {
20 raw, _ := json.Marshal([]string{team, person})
21 return fmt.Sprintf("personal/%x", sha256.Sum256(raw))
22}
23func (h *PreferenceHandler) Allow(r *http.Request, key string) bool {
24 id, ok := identity.From(r)
25 if !ok {
26 return false
27 }
28 allowed := false
29 err := h.App.Write(r.Context(), func(tx *gorm.DB) error {
30 actor := Actor{Address: h.App.Normalize(id.Address)}
31 team, err := h.App.Conversation(tx).deps.Authorize(tx, actor)
32 if err != nil {
33 return err
34 }
35 allowed = PersonalTopic(team, actor.Address) == "personal/"+key
36 return nil
37 })
38 return err == nil && allowed
39}
40func InstallPersonalChanges(ctx context.Context, tx *sql.Tx) error {
41 for _, stmt := range []string{
42 `CREATE TEMP TABLE IF NOT EXISTS equipo_personal_changes(team TEXT,person TEXT,PRIMARY KEY(team,person))`,
43 `CREATE TEMP TRIGGER IF NOT EXISTS equipo_personal_update AFTER UPDATE ON main.conversations WHEN OLD.revision IS NOT NEW.revision BEGIN INSERT OR IGNORE INTO equipo_personal_changes VALUES(NEW.team_id,NEW.person); END`,
44 `DELETE FROM equipo_personal_changes`,
45 } {
46 if _, err := tx.ExecContext(ctx, stmt); err != nil {
47 return err
48 }
49 }
50 return nil
51}
52func PersonalChanges(ctx context.Context, tx *sql.Tx) ([]string, error) {
53 rows, err := tx.QueryContext(ctx, `SELECT team,person FROM equipo_personal_changes`)
54 if err != nil {
55 return nil, err
56 }
57 defer rows.Close()
58 var topics []string
59 for rows.Next() {
60 var team, person string
61 if err = rows.Scan(&team, &person); err != nil {
62 return nil, err
63 }
64 topics = append(topics, PersonalTopic(team, person))
65 }
66 return topics, rows.Err()
67}
68
69func ConversationTopic(team, person, resource string) string {
70 raw, _ := json.Marshal([]string{team, person, resource})
71 sum := sha256.Sum256(raw)
72 return fmt.Sprintf("conversation/%s_%x", resource, sum[:16])
73}
74func (s *Application) AllowConversation(r *http.Request, key string) bool {
75 id, ok := identity.From(r)
76 if !ok {
77 return false
78 }
79
80 resource, _, ok := strings.Cut(key, "_")
81 if !ok || resource == "" || s.Read == nil {
82 return false
83 }
84 allowed := false
85 err := s.Read(r.Context(), func(tx *gorm.DB) error {
86 a := Actor{Address: s.Normalize(id.Address)}
87 team, err := s.Conversation(tx).deps.Authorize(tx, a)
88 if err != nil {
89 return err
90 }
91 var main Main
92 err = tx.Where("id=? AND team_id=? AND person=?", resource, team, a.Address).Take(&main).Error
93 if err == nil {
94 allowed = ConversationTopic(team, a.Address, main.ID) == "conversation/"+key
95 return nil
96 }
97 if !errors.Is(err, gorm.ErrRecordNotFound) {
98 return err
99 }
100 var thread Thread
101 err = tx.Table("conversation_threads").Select("conversation_threads.*").Joins("JOIN tasks ON tasks.id=conversation_threads.task_id AND tasks.team_id=conversation_threads.team_id").Where("conversation_threads.id=? AND conversation_threads.team_id=?", resource, team).Take(&thread).Error
102 if err != nil {
103 return err
104 }
105 allowed = ConversationTopic(team, "", thread.ID) == "conversation/"+key
106 return nil
107 })
108 return err == nil && allowed
109}
110
111func InstallConversationChanges(ctx context.Context, tx *sql.Tx) error {
112 stmts := []string{
113 `CREATE TEMP TABLE IF NOT EXISTS equipo_conversation_changes(team TEXT,person TEXT,resource TEXT,PRIMARY KEY(team,person,resource))`,
114 `DELETE FROM equipo_conversation_changes`,
115 `CREATE TEMP TRIGGER IF NOT EXISTS equipo_conversation_main AFTER UPDATE ON main.conversations WHEN OLD.revision IS NOT NEW.revision BEGIN INSERT OR IGNORE INTO equipo_conversation_changes VALUES(NEW.team_id,NEW.person,NEW.id); END`,
116 `CREATE TEMP TRIGGER IF NOT EXISTS equipo_conversation_thread AFTER UPDATE ON main.conversation_threads WHEN OLD.revision IS NOT NEW.revision BEGIN INSERT OR IGNORE INTO equipo_conversation_changes VALUES(NEW.team_id,'',NEW.id); END`,
117 }
118 for _, table := range []string{"conversation_cards", "coordinator_bindings", "coordinator_turns", "coordinator_questions", "tasks", "jobs", "steps", "attempts", "questions", "plan_approval_settings", "coordinator_limits"} {
119 var match string
120 switch table {
121 case "conversation_cards":
122 match = "c.id=NEW.stream_id"
123 case "coordinator_bindings":
124 match = "c.team_id=NEW.team_id AND c.person=NEW.person_key"
125 case "coordinator_turns":
126 match = "c.id=NEW.conversation_id"
127 case "coordinator_questions":
128 match = "c.person=NEW.person AND EXISTS(SELECT 1 FROM coordinator_bindings b WHERE b.id=NEW.binding_id AND b.team_id=c.team_id)"
129 case "tasks":
130 match = "c.team_id=NEW.team_id AND c.person=NEW.requester"
131 case "jobs":
132 match = "EXISTS(SELECT 1 FROM tasks t WHERE t.job_id=NEW.id AND t.team_id=c.team_id AND t.requester=c.person)"
133 case "steps", "attempts":
134 match = "EXISTS(SELECT 1 FROM tasks t WHERE t.job_id=NEW.job_id AND t.team_id=c.team_id AND t.requester=c.person)"
135 case "questions":
136 match = "EXISTS(SELECT 1 FROM tasks t WHERE t.id=NEW.task_id AND t.team_id=c.team_id AND t.requester=c.person)"
137 case "plan_approval_settings":
138 match = "EXISTS(SELECT 1 FROM tasks t WHERE t.project_id=NEW.project_id AND t.team_id=c.team_id AND t.requester=c.person)"
139 case "coordinator_limits":
140 match = "c.team_id=NEW.account AND c.person=NEW.person"
141 }
142 for _, event := range []string{"INSERT", "UPDATE"} {
143 stmts = append(stmts, fmt.Sprintf(`CREATE TEMP TRIGGER IF NOT EXISTS equipo_conversation_%s_%s AFTER %s ON main.%s BEGIN INSERT OR IGNORE INTO equipo_conversation_changes SELECT c.team_id,c.person,c.id FROM conversations c WHERE %s; END`, table, event, event, table, match))
144 }
145 }
146 for _, stmt := range stmts {
147 if _, err := tx.ExecContext(ctx, stmt); err != nil {
148 return err
149 }
150 }
151 return nil
152}
153func ConversationChanges(ctx context.Context, tx *sql.Tx) ([]string, error) {
154 rows, err := tx.QueryContext(ctx, `SELECT team,person,resource FROM equipo_conversation_changes`)
155 if err != nil {
156 return nil, err
157 }
158 defer rows.Close()
159 var out []string
160 for rows.Next() {
161 var team, person, resource string
162 if err = rows.Scan(&team, &person, &resource); err != nil {
163 return nil, err
164 }
165 out = append(out, ConversationTopic(team, person, resource))
166 }
167 return out, rows.Err()
168}
169
170func ConversationDeadlines(ctx context.Context, tx *sql.Tx, deadlines map[string][]time.Time) error {
171 for _, query := range []struct {
172 sql string
173 clarification bool
174 }{
175 {`SELECT c.team_id,c.person,c.id,a.lease_deadline FROM coordinator_turns t JOIN attempts a ON a.id=t.attempt_id JOIN conversations c ON c.id=t.conversation_id WHERE t.state='running'`, false},
176 {`SELECT c.team_id,c.person,c.id,json_extract(t.claim,'$.AttemptDeadline') FROM coordinator_turns t JOIN conversations c ON c.id=t.conversation_id WHERE t.state='running' AND t.claim<>''`, false},
177 {`SELECT c.team_id,c.person,c.id,q.payload FROM coordinator_questions q JOIN coordinator_bindings b ON b.id=q.binding_id JOIN conversations c ON c.team_id=b.team_id AND c.person=q.person WHERE q.state='pending'`, true},
178 {`SELECT c.team_id,c.person,c.id,q.expires_at FROM questions q JOIN tasks t ON t.id=q.task_id JOIN conversations c ON c.team_id=t.team_id AND c.person=t.requester WHERE q.state='pending'`, false},
179 } {
180 rows, err := tx.QueryContext(ctx, query.sql)
181 if err != nil {
182 return err
183 }
184 for rows.Next() {
185 var team, person, id string
186 var raw any
187 if err = rows.Scan(&team, &person, &id, &raw); err != nil {
188 break
189 }
190 var at time.Time
191 if query.clarification {
192 var q struct{ ExpiresAt time.Time }
193 body := fmt.Sprint(raw)
194 if err = json.Unmarshal([]byte(body), &q); err != nil {
195 break
196 }
197 at = q.ExpiresAt
198 } else {
199 at = kernel.ReadTime(raw)
200 }
201 topic := ConversationTopic(team, person, id)
202 deadlines[topic] = append(deadlines[topic], at)
203 }
204 if err == nil {
205 err = rows.Err()
206 }
207 rows.Close()
208 if err != nil {
209 return err
210 }
211 }
212 return nil
213}
214