1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
16 "git.arvados.org/arvados.git/sdk/go/arvados"
17 "git.arvados.org/arvados.git/sdk/go/ctxlog"
18 "github.com/sirupsen/logrus"
22 errQueueFull = errors.New("client queue full")
23 errFrameTooBig = errors.New("frame too big")
25 // Send clients only these keys from the
26 // log.properties.old_attributes and
27 // log.properties.new_attributes hashes.
28 sendObjectAttributes = []string{
36 v0subscribeOK = []byte(`{"status":200}`)
37 v0subscribeFail = []byte(`{"status":400}`)
40 type v0session struct {
43 sendq chan<- interface{}
45 permChecker permChecker
46 subscriptions []v0subscribe
48 log logrus.FieldLogger
53 // newSessionV0 returns a v0 session: a partial port of the Rails/puma
54 // implementation, with just enough functionality to support Workbench
56 func newSessionV0(ws wsConn, sendq chan<- interface{}, db *sql.DB, pc permChecker, ac *arvados.Client) (session, error) {
63 log: ctxlog.FromContext(ws.Request().Context()),
66 err := ws.Request().ParseForm()
68 sess.log.WithError(err).Error("ParseForm failed")
71 token := ws.Request().Form.Get("api_token")
72 sess.permChecker.SetToken(token)
73 sess.log.WithField("token", token).Debug("set token")
78 func (sess *v0session) Receive(buf []byte) error {
80 if err := json.Unmarshal(buf, &sub); err != nil {
81 sess.log.WithError(err).Info("invalid message from client")
82 } else if sub.Method == "subscribe" {
84 sess.log.WithField("sub", sub).Debug("sub prepared")
85 sess.sendq <- v0subscribeOK
87 sess.subscriptions = append(sess.subscriptions, sub)
89 sub.sendOldEvents(sess)
91 } else if sub.Method == "unsubscribe" {
94 for i, s := range sess.subscriptions {
95 if !reflect.DeepEqual(s.Filters, sub.Filters) {
98 copy(sess.subscriptions[i:], sess.subscriptions[i+1:])
99 sess.subscriptions = sess.subscriptions[:len(sess.subscriptions)-1]
104 sess.log.WithField("sub", sub).WithField("found", found).Debug("unsubscribe")
106 sess.sendq <- v0subscribeOK
110 sess.log.WithField("Method", sub.Method).Info("unknown method")
112 sess.sendq <- v0subscribeFail
116 func (sess *v0session) EventMessage(e *event) ([]byte, error) {
122 var permTarget string
123 if detail.EventType == "delete" {
124 // It's pointless to check permission by reading
125 // ObjectUUID if it has just been deleted, but if the
126 // client has permission on the parent project then
127 // it's OK to send the event.
128 permTarget = detail.ObjectOwnerUUID
130 permTarget = detail.ObjectUUID
132 ok, err := sess.permChecker.Check(sess.ws.Request().Context(), permTarget)
133 if err != nil || !ok {
137 kind, _ := sess.ac.KindForUUID(detail.ObjectUUID)
138 msg := map[string]interface{}{
139 "msgID": atomic.AddUint64(&sess.lastMsgID, 1),
142 "object_uuid": detail.ObjectUUID,
143 "object_owner_uuid": detail.ObjectOwnerUUID,
145 "event_type": detail.EventType,
146 "event_at": detail.EventAt,
148 if detail.Properties != nil && detail.Properties["text"] != nil {
149 msg["properties"] = detail.Properties
151 msgProps := map[string]map[string]interface{}{}
152 for _, ak := range []string{"old_attributes", "new_attributes"} {
153 eventAttrs, ok := detail.Properties[ak].(map[string]interface{})
157 msgAttrs := map[string]interface{}{}
158 for _, k := range sendObjectAttributes {
159 if v, ok := eventAttrs[k]; ok {
163 msgProps[ak] = msgAttrs
165 msg["properties"] = msgProps
167 return json.Marshal(msg)
170 func (sess *v0session) Filter(e *event) bool {
172 defer sess.mtx.Unlock()
173 for _, sub := range sess.subscriptions {
174 if sub.match(sess, e) {
181 func (sub *v0subscribe) sendOldEvents(sess *v0session) {
182 if sub.LastLogID == 0 {
185 sess.log.WithField("LastLogID", sub.LastLogID).Debug("sendOldEvents")
186 // Here we do a "select id" query and queue an event for every
187 // log since the given ID, then use (*event)Detail() to
188 // retrieve the whole row and decide whether to send it. This
189 // approach is very inefficient if the subscriber asks for
190 // last_log_id==1, even if the filters end up matching very
193 // To mitigate this, filter on "created > 10 minutes ago" when
194 // retrieving the list of old event IDs to consider.
195 rows, err := sess.db.Query(
196 `SELECT id FROM logs WHERE id > $1 AND created_at > $2 ORDER BY id`,
198 time.Now().UTC().Add(-10*time.Minute).Format(time.RFC3339Nano))
200 sess.log.WithError(err).Error("sendOldEvents db.Query failed")
207 err := rows.Scan(&id)
209 sess.log.WithError(err).Error("sendOldEvents row Scan failed")
212 ids = append(ids, id)
214 if err := rows.Err(); err != nil {
215 sess.log.WithError(err).Error("sendOldEvents db.Query failed")
219 for _, id := range ids {
220 for len(sess.sendq)*2 > cap(sess.sendq) {
221 // Ugly... but if we fill up the whole client
222 // queue with a backlog of old events, a
223 // single new event will overflow it and
224 // terminate the connection, and then the
225 // client will probably reconnect and do the
226 // same thing all over again.
227 time.Sleep(100 * time.Millisecond)
228 if sess.ws.Request().Context().Err() != nil {
229 // Session terminated while we were sleeping
240 if sub.match(sess, e) {
242 case sess.sendq <- e:
243 case <-sess.ws.Request().Context().Done():
250 type v0subscribe struct {
253 LastLogID int64 `json:"last_log_id"`
255 funcs []func(*event) bool
258 type v0filter [3]interface{}
260 func (sub *v0subscribe) match(sess *v0session, e *event) bool {
261 log := sess.log.WithField("LogID", e.LogID)
264 log.Error("match failed, no detail")
267 log = log.WithField("funcs", len(sub.funcs))
268 for i, f := range sub.funcs {
270 log.WithField("func", i).Debug("match failed")
274 log.Debug("match passed")
278 func (sub *v0subscribe) prepare(sess *v0session) {
279 for _, f := range sub.Filters {
283 if col, ok := f[0].(string); ok && col == "event_type" {
284 op, ok := f[1].(string)
285 if !ok || op != "in" {
288 arr, ok := f[2].([]interface{})
293 for _, s := range arr {
294 if s, ok := s.(string); ok {
295 strs = append(strs, s)
298 sub.funcs = append(sub.funcs, func(e *event) bool {
299 for _, s := range strs {
300 if s == e.Detail().EventType {
306 } else if ok && col == "created_at" {
307 op, ok := f[1].(string)
311 tstr, ok := f[2].(string)
315 t, err := time.Parse(time.RFC3339Nano, tstr)
317 sess.log.WithField("data", tstr).WithError(err).Info("time.Parse failed")
320 var fn func(*event) bool
323 fn = func(e *event) bool {
324 return !e.Detail().CreatedAt.Before(t)
327 fn = func(e *event) bool {
328 return !e.Detail().CreatedAt.After(t)
331 fn = func(e *event) bool {
332 return e.Detail().CreatedAt.After(t)
335 fn = func(e *event) bool {
336 return e.Detail().CreatedAt.Before(t)
339 fn = func(e *event) bool {
340 return e.Detail().CreatedAt.Equal(t)
343 sess.log.WithField("operator", op).Info("bogus operator")
346 sub.funcs = append(sub.funcs, fn)