1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
15 "git.curoverse.com/arvados.git/sdk/go/arvados"
16 "github.com/Sirupsen/logrus"
20 errQueueFull = errors.New("client queue full")
21 errFrameTooBig = errors.New("frame too big")
23 // Send clients only these keys from the
24 // log.properties.old_attributes and
25 // log.properties.new_attributes hashes.
26 sendObjectAttributes = []string{
34 v0subscribeOK = []byte(`{"status":200}`)
35 v0subscribeFail = []byte(`{"status":400}`)
38 type v0session struct {
41 sendq chan<- interface{}
43 permChecker permChecker
44 subscriptions []v0subscribe
51 // newSessionV0 returns a v0 session: a partial port of the Rails/puma
52 // implementation, with just enough functionality to support Workbench
54 func newSessionV0(ws wsConn, sendq chan<- interface{}, db *sql.DB, pc permChecker, ac *arvados.Client) (session, error) {
61 log: logger(ws.Request().Context()),
64 err := ws.Request().ParseForm()
66 sess.log.WithError(err).Error("ParseForm failed")
69 token := ws.Request().Form.Get("api_token")
70 sess.permChecker.SetToken(token)
71 sess.log.WithField("token", token).Debug("set token")
76 func (sess *v0session) Receive(buf []byte) error {
78 if err := json.Unmarshal(buf, &sub); err != nil {
79 sess.log.WithError(err).Info("invalid message from client")
80 } else if sub.Method == "subscribe" {
82 sess.log.WithField("sub", sub).Debug("sub prepared")
83 sess.sendq <- v0subscribeOK
85 sess.subscriptions = append(sess.subscriptions, sub)
87 sub.sendOldEvents(sess)
90 sess.log.WithField("Method", sub.Method).Info("unknown method")
92 sess.sendq <- v0subscribeFail
96 func (sess *v0session) EventMessage(e *event) ([]byte, error) {
102 var permTarget string
103 if detail.EventType == "delete" {
104 // It's pointless to check permission by reading
105 // ObjectUUID if it has just been deleted, but if the
106 // client has permission on the parent project then
107 // it's OK to send the event.
108 permTarget = detail.ObjectOwnerUUID
110 permTarget = detail.ObjectUUID
112 ok, err := sess.permChecker.Check(permTarget)
113 if err != nil || !ok {
117 kind, _ := sess.ac.KindForUUID(detail.ObjectUUID)
118 msg := map[string]interface{}{
119 "msgID": atomic.AddUint64(&sess.lastMsgID, 1),
122 "object_uuid": detail.ObjectUUID,
123 "object_owner_uuid": detail.ObjectOwnerUUID,
125 "event_type": detail.EventType,
126 "event_at": detail.EventAt,
128 if detail.Properties != nil && detail.Properties["text"] != nil {
129 msg["properties"] = detail.Properties
131 msgProps := map[string]map[string]interface{}{}
132 for _, ak := range []string{"old_attributes", "new_attributes"} {
133 eventAttrs, ok := detail.Properties[ak].(map[string]interface{})
137 msgAttrs := map[string]interface{}{}
138 for _, k := range sendObjectAttributes {
139 if v, ok := eventAttrs[k]; ok {
143 msgProps[ak] = msgAttrs
145 msg["properties"] = msgProps
147 return json.Marshal(msg)
150 func (sess *v0session) Filter(e *event) bool {
152 defer sess.mtx.Unlock()
153 for _, sub := range sess.subscriptions {
154 if sub.match(sess, e) {
161 func (sub *v0subscribe) sendOldEvents(sess *v0session) {
162 if sub.LastLogID == 0 {
165 sess.log.WithField("LastLogID", sub.LastLogID).Debug("sendOldEvents")
166 // Here we do a "select id" query and queue an event for every
167 // log since the given ID, then use (*event)Detail() to
168 // retrieve the whole row and decide whether to send it. This
169 // approach is very inefficient if the subscriber asks for
170 // last_log_id==1, even if the filters end up matching very
173 // To mitigate this, filter on "created > 10 minutes ago" when
174 // retrieving the list of old event IDs to consider.
175 rows, err := sess.db.Query(
176 `SELECT id FROM logs WHERE id > $1 AND created_at > $2 ORDER BY id`,
178 time.Now().UTC().Add(-10*time.Minute).Format(time.RFC3339Nano))
180 sess.log.WithError(err).Error("sendOldEvents db.Query failed")
187 err := rows.Scan(&id)
189 sess.log.WithError(err).Error("sendOldEvents row Scan failed")
192 ids = append(ids, id)
194 if err := rows.Err(); err != nil {
195 sess.log.WithError(err).Error("sendOldEvents db.Query failed")
199 for _, id := range ids {
200 for len(sess.sendq)*2 > cap(sess.sendq) {
201 // Ugly... but if we fill up the whole client
202 // queue with a backlog of old events, a
203 // single new event will overflow it and
204 // terminate the connection, and then the
205 // client will probably reconnect and do the
206 // same thing all over again.
207 time.Sleep(100 * time.Millisecond)
216 if sub.match(sess, e) {
218 case sess.sendq <- e:
219 case <-sess.ws.Request().Context().Done():
226 type v0subscribe struct {
229 LastLogID int64 `json:"last_log_id"`
231 funcs []func(*event) bool
234 type v0filter [3]interface{}
236 func (sub *v0subscribe) match(sess *v0session, e *event) bool {
237 log := sess.log.WithField("LogID", e.LogID)
240 log.Error("match failed, no detail")
243 log = log.WithField("funcs", len(sub.funcs))
244 for i, f := range sub.funcs {
246 log.WithField("func", i).Debug("match failed")
250 log.Debug("match passed")
254 func (sub *v0subscribe) prepare(sess *v0session) {
255 for _, f := range sub.Filters {
259 if col, ok := f[0].(string); ok && col == "event_type" {
260 op, ok := f[1].(string)
261 if !ok || op != "in" {
264 arr, ok := f[2].([]interface{})
269 for _, s := range arr {
270 if s, ok := s.(string); ok {
271 strs = append(strs, s)
274 sub.funcs = append(sub.funcs, func(e *event) bool {
275 for _, s := range strs {
276 if s == e.Detail().EventType {
282 } else if ok && col == "created_at" {
283 op, ok := f[1].(string)
287 tstr, ok := f[2].(string)
291 t, err := time.Parse(time.RFC3339Nano, tstr)
293 sess.log.WithField("data", tstr).WithError(err).Info("time.Parse failed")
296 var fn func(*event) bool
299 fn = func(e *event) bool {
300 return !e.Detail().CreatedAt.Before(t)
303 fn = func(e *event) bool {
304 return !e.Detail().CreatedAt.After(t)
307 fn = func(e *event) bool {
308 return e.Detail().CreatedAt.After(t)
311 fn = func(e *event) bool {
312 return e.Detail().CreatedAt.Before(t)
315 fn = func(e *event) bool {
316 return e.Detail().CreatedAt.Equal(t)
319 sess.log.WithField("operator", op).Info("bogus operator")
322 sub.funcs = append(sub.funcs, fn)