1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
16 "git.curoverse.com/arvados.git/sdk/go/arvados"
17 "github.com/Sirupsen/logrus"
21 errQueueFull = errors.New("client queue full")
22 errFrameTooBig = errors.New("frame too big")
24 // Send clients only these keys from the
25 // log.properties.old_attributes and
26 // log.properties.new_attributes hashes.
27 sendObjectAttributes = []string{
35 v0subscribeOK = []byte(`{"status":200}`)
36 v0subscribeFail = []byte(`{"status":400}`)
39 type v0session struct {
42 sendq chan<- interface{}
44 permChecker permChecker
45 subscriptions []v0subscribe
52 // newSessionV0 returns a v0 session: a partial port of the Rails/puma
53 // implementation, with just enough functionality to support Workbench
55 func newSessionV0(ws wsConn, sendq chan<- interface{}, db *sql.DB, pc permChecker, ac *arvados.Client) (session, error) {
62 log: logger(ws.Request().Context()),
65 err := ws.Request().ParseForm()
67 sess.log.WithError(err).Error("ParseForm failed")
70 token := ws.Request().Form.Get("api_token")
71 sess.permChecker.SetToken(token)
72 sess.log.WithField("token", token).Debug("set token")
77 func (sess *v0session) Receive(buf []byte) error {
79 if err := json.Unmarshal(buf, &sub); err != nil {
80 sess.log.WithError(err).Info("invalid message from client")
81 } else if sub.Method == "subscribe" {
83 sess.log.WithField("sub", sub).Debug("sub prepared")
84 sess.sendq <- v0subscribeOK
86 sess.subscriptions = append(sess.subscriptions, sub)
88 sub.sendOldEvents(sess)
90 } else if sub.Method == "unsubscribe" {
93 for i, s := range sess.subscriptions {
94 if !reflect.DeepEqual(s.Filters, sub.Filters) {
97 copy(sess.subscriptions[i:], sess.subscriptions[i+1:])
98 sess.subscriptions = sess.subscriptions[:len(sess.subscriptions)-1]
103 sess.log.WithField("sub", sub).WithField("found", found).Debug("unsubscribe")
105 sess.sendq <- v0subscribeOK
109 sess.log.WithField("Method", sub.Method).Info("unknown method")
111 sess.sendq <- v0subscribeFail
115 func (sess *v0session) EventMessage(e *event) ([]byte, error) {
121 var permTarget string
122 if detail.EventType == "delete" {
123 // It's pointless to check permission by reading
124 // ObjectUUID if it has just been deleted, but if the
125 // client has permission on the parent project then
126 // it's OK to send the event.
127 permTarget = detail.ObjectOwnerUUID
129 permTarget = detail.ObjectUUID
131 ok, err := sess.permChecker.Check(permTarget)
132 if err != nil || !ok {
136 kind, _ := sess.ac.KindForUUID(detail.ObjectUUID)
137 msg := map[string]interface{}{
138 "msgID": atomic.AddUint64(&sess.lastMsgID, 1),
141 "object_uuid": detail.ObjectUUID,
142 "object_owner_uuid": detail.ObjectOwnerUUID,
144 "event_type": detail.EventType,
145 "event_at": detail.EventAt,
147 if detail.Properties != nil && detail.Properties["text"] != nil {
148 msg["properties"] = detail.Properties
150 msgProps := map[string]map[string]interface{}{}
151 for _, ak := range []string{"old_attributes", "new_attributes"} {
152 eventAttrs, ok := detail.Properties[ak].(map[string]interface{})
156 msgAttrs := map[string]interface{}{}
157 for _, k := range sendObjectAttributes {
158 if v, ok := eventAttrs[k]; ok {
162 msgProps[ak] = msgAttrs
164 msg["properties"] = msgProps
166 return json.Marshal(msg)
169 func (sess *v0session) Filter(e *event) bool {
171 defer sess.mtx.Unlock()
172 for _, sub := range sess.subscriptions {
173 if sub.match(sess, e) {
180 func (sub *v0subscribe) sendOldEvents(sess *v0session) {
181 if sub.LastLogID == 0 {
184 sess.log.WithField("LastLogID", sub.LastLogID).Debug("sendOldEvents")
185 // Here we do a "select id" query and queue an event for every
186 // log since the given ID, then use (*event)Detail() to
187 // retrieve the whole row and decide whether to send it. This
188 // approach is very inefficient if the subscriber asks for
189 // last_log_id==1, even if the filters end up matching very
192 // To mitigate this, filter on "created > 10 minutes ago" when
193 // retrieving the list of old event IDs to consider.
194 rows, err := sess.db.Query(
195 `SELECT id FROM logs WHERE id > $1 AND created_at > $2 ORDER BY id`,
197 time.Now().UTC().Add(-10*time.Minute).Format(time.RFC3339Nano))
199 sess.log.WithError(err).Error("sendOldEvents db.Query failed")
206 err := rows.Scan(&id)
208 sess.log.WithError(err).Error("sendOldEvents row Scan failed")
211 ids = append(ids, id)
213 if err := rows.Err(); err != nil {
214 sess.log.WithError(err).Error("sendOldEvents db.Query failed")
218 for _, id := range ids {
219 for len(sess.sendq)*2 > cap(sess.sendq) {
220 // Ugly... but if we fill up the whole client
221 // queue with a backlog of old events, a
222 // single new event will overflow it and
223 // terminate the connection, and then the
224 // client will probably reconnect and do the
225 // same thing all over again.
226 time.Sleep(100 * time.Millisecond)
227 if sess.ws.Request().Context().Err() != nil {
228 // Session terminated while we were sleeping
239 if sub.match(sess, e) {
241 case sess.sendq <- e:
242 case <-sess.ws.Request().Context().Done():
249 type v0subscribe struct {
252 LastLogID int64 `json:"last_log_id"`
254 funcs []func(*event) bool
257 type v0filter [3]interface{}
259 func (sub *v0subscribe) match(sess *v0session, e *event) bool {
260 log := sess.log.WithField("LogID", e.LogID)
263 log.Error("match failed, no detail")
266 log = log.WithField("funcs", len(sub.funcs))
267 for i, f := range sub.funcs {
269 log.WithField("func", i).Debug("match failed")
273 log.Debug("match passed")
277 func (sub *v0subscribe) prepare(sess *v0session) {
278 for _, f := range sub.Filters {
282 if col, ok := f[0].(string); ok && col == "event_type" {
283 op, ok := f[1].(string)
284 if !ok || op != "in" {
287 arr, ok := f[2].([]interface{})
292 for _, s := range arr {
293 if s, ok := s.(string); ok {
294 strs = append(strs, s)
297 sub.funcs = append(sub.funcs, func(e *event) bool {
298 for _, s := range strs {
299 if s == e.Detail().EventType {
305 } else if ok && col == "created_at" {
306 op, ok := f[1].(string)
310 tstr, ok := f[2].(string)
314 t, err := time.Parse(time.RFC3339Nano, tstr)
316 sess.log.WithField("data", tstr).WithError(err).Info("time.Parse failed")
319 var fn func(*event) bool
322 fn = func(e *event) bool {
323 return !e.Detail().CreatedAt.Before(t)
326 fn = func(e *event) bool {
327 return !e.Detail().CreatedAt.After(t)
330 fn = func(e *event) bool {
331 return e.Detail().CreatedAt.After(t)
334 fn = func(e *event) bool {
335 return e.Detail().CreatedAt.Before(t)
338 fn = func(e *event) bool {
339 return e.Detail().CreatedAt.Equal(t)
342 sess.log.WithField("operator", op).Info("bogus operator")
345 sub.funcs = append(sub.funcs, fn)