11 "git.curoverse.com/arvados.git/sdk/go/arvados"
12 "github.com/Sirupsen/logrus"
16 errQueueFull = errors.New("client queue full")
17 errFrameTooBig = errors.New("frame too big")
19 sendObjectAttributes = []string{"state", "name", "owner_uuid", "portable_data_hash"}
21 v0subscribeOK = []byte(`{"status":200}`)
22 v0subscribeFail = []byte(`{"status":400}`)
25 type v0session struct {
28 sendq chan<- interface{}
30 permChecker permChecker
31 subscriptions []v0subscribe
38 // newSessionV0 returns a v0 session: a partial port of the Rails/puma
39 // implementation, with just enough functionality to support Workbench
41 func newSessionV0(ws wsConn, sendq chan<- interface{}, db *sql.DB, pc permChecker, ac *arvados.Client) (session, error) {
48 log: logger(ws.Request().Context()),
51 err := ws.Request().ParseForm()
53 sess.log.WithError(err).Error("ParseForm failed")
56 token := ws.Request().Form.Get("api_token")
57 sess.permChecker.SetToken(token)
58 sess.log.WithField("token", token).Debug("set token")
63 func (sess *v0session) Receive(buf []byte) error {
65 if err := json.Unmarshal(buf, &sub); err != nil {
66 sess.log.WithError(err).Info("invalid message from client")
67 } else if sub.Method == "subscribe" {
69 sess.log.WithField("sub", sub).Debug("sub prepared")
70 sess.sendq <- v0subscribeOK
72 sess.subscriptions = append(sess.subscriptions, sub)
74 sub.sendOldEvents(sess)
77 sess.log.WithField("Method", sub.Method).Info("unknown method")
79 sess.sendq <- v0subscribeFail
83 func (sess *v0session) EventMessage(e *event) ([]byte, error) {
89 ok, err := sess.permChecker.Check(detail.ObjectUUID)
90 if err != nil || !ok {
94 kind, _ := sess.ac.KindForUUID(detail.ObjectUUID)
95 msg := map[string]interface{}{
96 "msgID": atomic.AddUint64(&sess.lastMsgID, 1),
99 "object_uuid": detail.ObjectUUID,
100 "object_owner_uuid": detail.ObjectOwnerUUID,
102 "event_type": detail.EventType,
103 "event_at": detail.EventAt,
105 if detail.Properties != nil && detail.Properties["text"] != nil {
106 msg["properties"] = detail.Properties
108 msgProps := map[string]map[string]interface{}{}
109 for _, ak := range []string{"old_attributes", "new_attributes"} {
110 eventAttrs, ok := detail.Properties[ak].(map[string]interface{})
114 msgAttrs := map[string]interface{}{}
115 for _, k := range sendObjectAttributes {
116 if v, ok := eventAttrs[k]; ok {
120 msgProps[ak] = msgAttrs
122 msg["properties"] = msgProps
124 return json.Marshal(msg)
127 func (sess *v0session) Filter(e *event) bool {
129 defer sess.mtx.Unlock()
130 for _, sub := range sess.subscriptions {
131 if sub.match(sess, e) {
138 func (sub *v0subscribe) sendOldEvents(sess *v0session) {
139 if sub.LastLogID == 0 {
142 sess.log.WithField("LastLogID", sub.LastLogID).Debug("getOldEvents")
143 // Here we do a "select id" query and queue an event for every
144 // log since the given ID, then use (*event)Detail() to
145 // retrieve the whole row and decide whether to send it. This
146 // approach is very inefficient if the subscriber asks for
147 // last_log_id==1, even if the filters end up matching very
150 // To mitigate this, filter on "created > 10 minutes ago" when
151 // retrieving the list of old event IDs to consider.
152 rows, err := sess.db.Query(
153 `SELECT id FROM logs WHERE id > $1 AND created_at > $2 ORDER BY id`,
155 time.Now().UTC().Add(-10*time.Minute).Format(time.RFC3339Nano))
157 sess.log.WithError(err).Error("db.Query failed")
162 err := rows.Scan(&id)
164 sess.log.WithError(err).Error("row Scan failed")
167 for len(sess.sendq)*2 > cap(sess.sendq) {
168 // Ugly... but if we fill up the whole client
169 // queue with a backlog of old events, a
170 // single new event will overflow it and
171 // terminate the connection, and then the
172 // client will probably reconnect and do the
173 // same thing all over again.
174 time.Sleep(100 * time.Millisecond)
183 if sub.match(sess, e) {
185 case sess.sendq <- e:
186 case <-sess.ws.Request().Context().Done():
191 if err := rows.Err(); err != nil {
192 sess.log.WithError(err).Error("db.Query failed")
196 type v0subscribe struct {
199 LastLogID int64 `json:"last_log_id"`
201 funcs []func(*event) bool
204 type v0filter [3]interface{}
206 func (sub *v0subscribe) match(sess *v0session, e *event) bool {
207 log := sess.log.WithField("LogID", e.LogID)
210 log.Error("match failed, no detail")
213 log = log.WithField("funcs", len(sub.funcs))
214 for i, f := range sub.funcs {
216 log.WithField("func", i).Debug("match failed")
220 log.Debug("match passed")
224 func (sub *v0subscribe) prepare(sess *v0session) {
225 for _, f := range sub.Filters {
229 if col, ok := f[0].(string); ok && col == "event_type" {
230 op, ok := f[1].(string)
231 if !ok || op != "in" {
234 arr, ok := f[2].([]interface{})
239 for _, s := range arr {
240 if s, ok := s.(string); ok {
241 strs = append(strs, s)
244 sub.funcs = append(sub.funcs, func(e *event) bool {
245 for _, s := range strs {
246 if s == e.Detail().EventType {
252 } else if ok && col == "created_at" {
253 op, ok := f[1].(string)
257 tstr, ok := f[2].(string)
261 t, err := time.Parse(time.RFC3339Nano, tstr)
263 sess.log.WithField("data", tstr).WithError(err).Info("time.Parse failed")
266 var fn func(*event) bool
269 fn = func(e *event) bool {
270 return !e.Detail().CreatedAt.Before(t)
273 fn = func(e *event) bool {
274 return !e.Detail().CreatedAt.After(t)
277 fn = func(e *event) bool {
278 return e.Detail().CreatedAt.After(t)
281 fn = func(e *event) bool {
282 return e.Detail().CreatedAt.Before(t)
285 fn = func(e *event) bool {
286 return e.Detail().CreatedAt.Equal(t)
289 sess.log.WithField("operator", op).Info("bogus operator")
292 sub.funcs = append(sub.funcs, fn)