]> git.saurik.com Git - redis.git/blob - src/t_list.c
Fix the build on Mac OS X, where features.h is non-existent
[redis.git] / src / t_list.c
1 #include "redis.h"
2
3 /*-----------------------------------------------------------------------------
4 * List API
5 *----------------------------------------------------------------------------*/
6
7 /* Check the argument length to see if it requires us to convert the ziplist
8 * to a real list. Only check raw-encoded objects because integer encoded
9 * objects are never too long. */
10 void listTypeTryConversion(robj *subject, robj *value) {
11 if (subject->encoding != REDIS_ENCODING_ZIPLIST) return;
12 if (value->encoding == REDIS_ENCODING_RAW &&
13 sdslen(value->ptr) > server.list_max_ziplist_value)
14 listTypeConvert(subject,REDIS_ENCODING_LINKEDLIST);
15 }
16
17 void listTypePush(robj *subject, robj *value, int where) {
18 /* Check if we need to convert the ziplist */
19 listTypeTryConversion(subject,value);
20 if (subject->encoding == REDIS_ENCODING_ZIPLIST &&
21 ziplistLen(subject->ptr) >= server.list_max_ziplist_entries)
22 listTypeConvert(subject,REDIS_ENCODING_LINKEDLIST);
23
24 if (subject->encoding == REDIS_ENCODING_ZIPLIST) {
25 int pos = (where == REDIS_HEAD) ? ZIPLIST_HEAD : ZIPLIST_TAIL;
26 value = getDecodedObject(value);
27 subject->ptr = ziplistPush(subject->ptr,value->ptr,sdslen(value->ptr),pos);
28 decrRefCount(value);
29 } else if (subject->encoding == REDIS_ENCODING_LINKEDLIST) {
30 if (where == REDIS_HEAD) {
31 listAddNodeHead(subject->ptr,value);
32 } else {
33 listAddNodeTail(subject->ptr,value);
34 }
35 incrRefCount(value);
36 } else {
37 redisPanic("Unknown list encoding");
38 }
39 }
40
41 robj *listTypePop(robj *subject, int where) {
42 robj *value = NULL;
43 if (subject->encoding == REDIS_ENCODING_ZIPLIST) {
44 unsigned char *p;
45 unsigned char *vstr;
46 unsigned int vlen;
47 long long vlong;
48 int pos = (where == REDIS_HEAD) ? 0 : -1;
49 p = ziplistIndex(subject->ptr,pos);
50 if (ziplistGet(p,&vstr,&vlen,&vlong)) {
51 if (vstr) {
52 value = createStringObject((char*)vstr,vlen);
53 } else {
54 value = createStringObjectFromLongLong(vlong);
55 }
56 /* We only need to delete an element when it exists */
57 subject->ptr = ziplistDelete(subject->ptr,&p);
58 }
59 } else if (subject->encoding == REDIS_ENCODING_LINKEDLIST) {
60 list *list = subject->ptr;
61 listNode *ln;
62 if (where == REDIS_HEAD) {
63 ln = listFirst(list);
64 } else {
65 ln = listLast(list);
66 }
67 if (ln != NULL) {
68 value = listNodeValue(ln);
69 incrRefCount(value);
70 listDelNode(list,ln);
71 }
72 } else {
73 redisPanic("Unknown list encoding");
74 }
75 return value;
76 }
77
78 unsigned long listTypeLength(robj *subject) {
79 if (subject->encoding == REDIS_ENCODING_ZIPLIST) {
80 return ziplistLen(subject->ptr);
81 } else if (subject->encoding == REDIS_ENCODING_LINKEDLIST) {
82 return listLength((list*)subject->ptr);
83 } else {
84 redisPanic("Unknown list encoding");
85 }
86 }
87
88 /* Initialize an iterator at the specified index. */
89 listTypeIterator *listTypeInitIterator(robj *subject, long index, unsigned char direction) {
90 listTypeIterator *li = zmalloc(sizeof(listTypeIterator));
91 li->subject = subject;
92 li->encoding = subject->encoding;
93 li->direction = direction;
94 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
95 li->zi = ziplistIndex(subject->ptr,index);
96 } else if (li->encoding == REDIS_ENCODING_LINKEDLIST) {
97 li->ln = listIndex(subject->ptr,index);
98 } else {
99 redisPanic("Unknown list encoding");
100 }
101 return li;
102 }
103
104 /* Clean up the iterator. */
105 void listTypeReleaseIterator(listTypeIterator *li) {
106 zfree(li);
107 }
108
109 /* Stores pointer to current the entry in the provided entry structure
110 * and advances the position of the iterator. Returns 1 when the current
111 * entry is in fact an entry, 0 otherwise. */
112 int listTypeNext(listTypeIterator *li, listTypeEntry *entry) {
113 /* Protect from converting when iterating */
114 redisAssert(li->subject->encoding == li->encoding);
115
116 entry->li = li;
117 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
118 entry->zi = li->zi;
119 if (entry->zi != NULL) {
120 if (li->direction == REDIS_TAIL)
121 li->zi = ziplistNext(li->subject->ptr,li->zi);
122 else
123 li->zi = ziplistPrev(li->subject->ptr,li->zi);
124 return 1;
125 }
126 } else if (li->encoding == REDIS_ENCODING_LINKEDLIST) {
127 entry->ln = li->ln;
128 if (entry->ln != NULL) {
129 if (li->direction == REDIS_TAIL)
130 li->ln = li->ln->next;
131 else
132 li->ln = li->ln->prev;
133 return 1;
134 }
135 } else {
136 redisPanic("Unknown list encoding");
137 }
138 return 0;
139 }
140
141 /* Return entry or NULL at the current position of the iterator. */
142 robj *listTypeGet(listTypeEntry *entry) {
143 listTypeIterator *li = entry->li;
144 robj *value = NULL;
145 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
146 unsigned char *vstr;
147 unsigned int vlen;
148 long long vlong;
149 redisAssert(entry->zi != NULL);
150 if (ziplistGet(entry->zi,&vstr,&vlen,&vlong)) {
151 if (vstr) {
152 value = createStringObject((char*)vstr,vlen);
153 } else {
154 value = createStringObjectFromLongLong(vlong);
155 }
156 }
157 } else if (li->encoding == REDIS_ENCODING_LINKEDLIST) {
158 redisAssert(entry->ln != NULL);
159 value = listNodeValue(entry->ln);
160 incrRefCount(value);
161 } else {
162 redisPanic("Unknown list encoding");
163 }
164 return value;
165 }
166
167 void listTypeInsert(listTypeEntry *entry, robj *value, int where) {
168 robj *subject = entry->li->subject;
169 if (entry->li->encoding == REDIS_ENCODING_ZIPLIST) {
170 value = getDecodedObject(value);
171 if (where == REDIS_TAIL) {
172 unsigned char *next = ziplistNext(subject->ptr,entry->zi);
173
174 /* When we insert after the current element, but the current element
175 * is the tail of the list, we need to do a push. */
176 if (next == NULL) {
177 subject->ptr = ziplistPush(subject->ptr,value->ptr,sdslen(value->ptr),REDIS_TAIL);
178 } else {
179 subject->ptr = ziplistInsert(subject->ptr,next,value->ptr,sdslen(value->ptr));
180 }
181 } else {
182 subject->ptr = ziplistInsert(subject->ptr,entry->zi,value->ptr,sdslen(value->ptr));
183 }
184 decrRefCount(value);
185 } else if (entry->li->encoding == REDIS_ENCODING_LINKEDLIST) {
186 if (where == REDIS_TAIL) {
187 listInsertNode(subject->ptr,entry->ln,value,AL_START_TAIL);
188 } else {
189 listInsertNode(subject->ptr,entry->ln,value,AL_START_HEAD);
190 }
191 incrRefCount(value);
192 } else {
193 redisPanic("Unknown list encoding");
194 }
195 }
196
197 /* Compare the given object with the entry at the current position. */
198 int listTypeEqual(listTypeEntry *entry, robj *o) {
199 listTypeIterator *li = entry->li;
200 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
201 redisAssertWithInfo(NULL,o,o->encoding == REDIS_ENCODING_RAW);
202 return ziplistCompare(entry->zi,o->ptr,sdslen(o->ptr));
203 } else if (li->encoding == REDIS_ENCODING_LINKEDLIST) {
204 return equalStringObjects(o,listNodeValue(entry->ln));
205 } else {
206 redisPanic("Unknown list encoding");
207 }
208 }
209
210 /* Delete the element pointed to. */
211 void listTypeDelete(listTypeEntry *entry) {
212 listTypeIterator *li = entry->li;
213 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
214 unsigned char *p = entry->zi;
215 li->subject->ptr = ziplistDelete(li->subject->ptr,&p);
216
217 /* Update position of the iterator depending on the direction */
218 if (li->direction == REDIS_TAIL)
219 li->zi = p;
220 else
221 li->zi = ziplistPrev(li->subject->ptr,p);
222 } else if (entry->li->encoding == REDIS_ENCODING_LINKEDLIST) {
223 listNode *next;
224 if (li->direction == REDIS_TAIL)
225 next = entry->ln->next;
226 else
227 next = entry->ln->prev;
228 listDelNode(li->subject->ptr,entry->ln);
229 li->ln = next;
230 } else {
231 redisPanic("Unknown list encoding");
232 }
233 }
234
235 void listTypeConvert(robj *subject, int enc) {
236 listTypeIterator *li;
237 listTypeEntry entry;
238 redisAssertWithInfo(NULL,subject,subject->type == REDIS_LIST);
239
240 if (enc == REDIS_ENCODING_LINKEDLIST) {
241 list *l = listCreate();
242 listSetFreeMethod(l,decrRefCount);
243
244 /* listTypeGet returns a robj with incremented refcount */
245 li = listTypeInitIterator(subject,0,REDIS_TAIL);
246 while (listTypeNext(li,&entry)) listAddNodeTail(l,listTypeGet(&entry));
247 listTypeReleaseIterator(li);
248
249 subject->encoding = REDIS_ENCODING_LINKEDLIST;
250 zfree(subject->ptr);
251 subject->ptr = l;
252 } else {
253 redisPanic("Unsupported list conversion");
254 }
255 }
256
257 /*-----------------------------------------------------------------------------
258 * List Commands
259 *----------------------------------------------------------------------------*/
260
261 void pushGenericCommand(redisClient *c, int where) {
262 int j, addlen = 0, pushed = 0;
263 robj *lobj = lookupKeyWrite(c->db,c->argv[1]);
264 int may_have_waiting_clients = (lobj == NULL);
265
266 if (lobj && lobj->type != REDIS_LIST) {
267 addReply(c,shared.wrongtypeerr);
268 return;
269 }
270
271 for (j = 2; j < c->argc; j++) {
272 c->argv[j] = tryObjectEncoding(c->argv[j]);
273 if (may_have_waiting_clients) {
274 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[j])) {
275 addlen++;
276 continue;
277 } else {
278 may_have_waiting_clients = 0;
279 }
280 }
281 if (!lobj) {
282 lobj = createZiplistObject();
283 dbAdd(c->db,c->argv[1],lobj);
284 }
285 listTypePush(lobj,c->argv[j],where);
286 pushed++;
287 }
288 addReplyLongLong(c,addlen + (lobj ? listTypeLength(lobj) : 0));
289 if (pushed) signalModifiedKey(c->db,c->argv[1]);
290 server.dirty += pushed;
291 }
292
293 void lpushCommand(redisClient *c) {
294 pushGenericCommand(c,REDIS_HEAD);
295 }
296
297 void rpushCommand(redisClient *c) {
298 pushGenericCommand(c,REDIS_TAIL);
299 }
300
301 void pushxGenericCommand(redisClient *c, robj *refval, robj *val, int where) {
302 robj *subject;
303 listTypeIterator *iter;
304 listTypeEntry entry;
305 int inserted = 0;
306
307 if ((subject = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
308 checkType(c,subject,REDIS_LIST)) return;
309
310 if (refval != NULL) {
311 /* Note: we expect refval to be string-encoded because it is *not* the
312 * last argument of the multi-bulk LINSERT. */
313 redisAssertWithInfo(c,refval,refval->encoding == REDIS_ENCODING_RAW);
314
315 /* We're not sure if this value can be inserted yet, but we cannot
316 * convert the list inside the iterator. We don't want to loop over
317 * the list twice (once to see if the value can be inserted and once
318 * to do the actual insert), so we assume this value can be inserted
319 * and convert the ziplist to a regular list if necessary. */
320 listTypeTryConversion(subject,val);
321
322 /* Seek refval from head to tail */
323 iter = listTypeInitIterator(subject,0,REDIS_TAIL);
324 while (listTypeNext(iter,&entry)) {
325 if (listTypeEqual(&entry,refval)) {
326 listTypeInsert(&entry,val,where);
327 inserted = 1;
328 break;
329 }
330 }
331 listTypeReleaseIterator(iter);
332
333 if (inserted) {
334 /* Check if the length exceeds the ziplist length threshold. */
335 if (subject->encoding == REDIS_ENCODING_ZIPLIST &&
336 ziplistLen(subject->ptr) > server.list_max_ziplist_entries)
337 listTypeConvert(subject,REDIS_ENCODING_LINKEDLIST);
338 signalModifiedKey(c->db,c->argv[1]);
339 server.dirty++;
340 } else {
341 /* Notify client of a failed insert */
342 addReply(c,shared.cnegone);
343 return;
344 }
345 } else {
346 listTypePush(subject,val,where);
347 signalModifiedKey(c->db,c->argv[1]);
348 server.dirty++;
349 }
350
351 addReplyLongLong(c,listTypeLength(subject));
352 }
353
354 void lpushxCommand(redisClient *c) {
355 c->argv[2] = tryObjectEncoding(c->argv[2]);
356 pushxGenericCommand(c,NULL,c->argv[2],REDIS_HEAD);
357 }
358
359 void rpushxCommand(redisClient *c) {
360 c->argv[2] = tryObjectEncoding(c->argv[2]);
361 pushxGenericCommand(c,NULL,c->argv[2],REDIS_TAIL);
362 }
363
364 void linsertCommand(redisClient *c) {
365 c->argv[4] = tryObjectEncoding(c->argv[4]);
366 if (strcasecmp(c->argv[2]->ptr,"after") == 0) {
367 pushxGenericCommand(c,c->argv[3],c->argv[4],REDIS_TAIL);
368 } else if (strcasecmp(c->argv[2]->ptr,"before") == 0) {
369 pushxGenericCommand(c,c->argv[3],c->argv[4],REDIS_HEAD);
370 } else {
371 addReply(c,shared.syntaxerr);
372 }
373 }
374
375 void llenCommand(redisClient *c) {
376 robj *o = lookupKeyReadOrReply(c,c->argv[1],shared.czero);
377 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
378 addReplyLongLong(c,listTypeLength(o));
379 }
380
381 void lindexCommand(redisClient *c) {
382 robj *o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk);
383 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
384 long index;
385 robj *value = NULL;
386
387 if ((getLongFromObjectOrReply(c, c->argv[2], &index, NULL) != REDIS_OK))
388 return;
389
390 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
391 unsigned char *p;
392 unsigned char *vstr;
393 unsigned int vlen;
394 long long vlong;
395 p = ziplistIndex(o->ptr,index);
396 if (ziplistGet(p,&vstr,&vlen,&vlong)) {
397 if (vstr) {
398 value = createStringObject((char*)vstr,vlen);
399 } else {
400 value = createStringObjectFromLongLong(vlong);
401 }
402 addReplyBulk(c,value);
403 decrRefCount(value);
404 } else {
405 addReply(c,shared.nullbulk);
406 }
407 } else if (o->encoding == REDIS_ENCODING_LINKEDLIST) {
408 listNode *ln = listIndex(o->ptr,index);
409 if (ln != NULL) {
410 value = listNodeValue(ln);
411 addReplyBulk(c,value);
412 } else {
413 addReply(c,shared.nullbulk);
414 }
415 } else {
416 redisPanic("Unknown list encoding");
417 }
418 }
419
420 void lsetCommand(redisClient *c) {
421 robj *o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr);
422 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
423 long index;
424 robj *value = (c->argv[3] = tryObjectEncoding(c->argv[3]));
425
426 if ((getLongFromObjectOrReply(c, c->argv[2], &index, NULL) != REDIS_OK))
427 return;
428
429 listTypeTryConversion(o,value);
430 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
431 unsigned char *p, *zl = o->ptr;
432 p = ziplistIndex(zl,index);
433 if (p == NULL) {
434 addReply(c,shared.outofrangeerr);
435 } else {
436 o->ptr = ziplistDelete(o->ptr,&p);
437 value = getDecodedObject(value);
438 o->ptr = ziplistInsert(o->ptr,p,value->ptr,sdslen(value->ptr));
439 decrRefCount(value);
440 addReply(c,shared.ok);
441 signalModifiedKey(c->db,c->argv[1]);
442 server.dirty++;
443 }
444 } else if (o->encoding == REDIS_ENCODING_LINKEDLIST) {
445 listNode *ln = listIndex(o->ptr,index);
446 if (ln == NULL) {
447 addReply(c,shared.outofrangeerr);
448 } else {
449 decrRefCount((robj*)listNodeValue(ln));
450 listNodeValue(ln) = value;
451 incrRefCount(value);
452 addReply(c,shared.ok);
453 signalModifiedKey(c->db,c->argv[1]);
454 server.dirty++;
455 }
456 } else {
457 redisPanic("Unknown list encoding");
458 }
459 }
460
461 void popGenericCommand(redisClient *c, int where) {
462 robj *o = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk);
463 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
464
465 robj *value = listTypePop(o,where);
466 if (value == NULL) {
467 addReply(c,shared.nullbulk);
468 } else {
469 addReplyBulk(c,value);
470 decrRefCount(value);
471 if (listTypeLength(o) == 0) dbDelete(c->db,c->argv[1]);
472 signalModifiedKey(c->db,c->argv[1]);
473 server.dirty++;
474 }
475 }
476
477 void lpopCommand(redisClient *c) {
478 popGenericCommand(c,REDIS_HEAD);
479 }
480
481 void rpopCommand(redisClient *c) {
482 popGenericCommand(c,REDIS_TAIL);
483 }
484
485 void lrangeCommand(redisClient *c) {
486 robj *o;
487 long start, end, llen, rangelen;
488
489 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
490 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
491
492 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
493 || checkType(c,o,REDIS_LIST)) return;
494 llen = listTypeLength(o);
495
496 /* convert negative indexes */
497 if (start < 0) start = llen+start;
498 if (end < 0) end = llen+end;
499 if (start < 0) start = 0;
500
501 /* Invariant: start >= 0, so this test will be true when end < 0.
502 * The range is empty when start > end or start >= length. */
503 if (start > end || start >= llen) {
504 addReply(c,shared.emptymultibulk);
505 return;
506 }
507 if (end >= llen) end = llen-1;
508 rangelen = (end-start)+1;
509
510 /* Return the result in form of a multi-bulk reply */
511 addReplyMultiBulkLen(c,rangelen);
512 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
513 unsigned char *p = ziplistIndex(o->ptr,start);
514 unsigned char *vstr;
515 unsigned int vlen;
516 long long vlong;
517
518 while(rangelen--) {
519 ziplistGet(p,&vstr,&vlen,&vlong);
520 if (vstr) {
521 addReplyBulkCBuffer(c,vstr,vlen);
522 } else {
523 addReplyBulkLongLong(c,vlong);
524 }
525 p = ziplistNext(o->ptr,p);
526 }
527 } else if (o->encoding == REDIS_ENCODING_LINKEDLIST) {
528 listNode *ln;
529
530 /* If we are nearest to the end of the list, reach the element
531 * starting from tail and going backward, as it is faster. */
532 if (start > llen/2) start -= llen;
533 ln = listIndex(o->ptr,start);
534
535 while(rangelen--) {
536 addReplyBulk(c,ln->value);
537 ln = ln->next;
538 }
539 } else {
540 redisPanic("List encoding is not LINKEDLIST nor ZIPLIST!");
541 }
542 }
543
544 void ltrimCommand(redisClient *c) {
545 robj *o;
546 long start, end, llen, j, ltrim, rtrim;
547 list *list;
548 listNode *ln;
549
550 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
551 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
552
553 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.ok)) == NULL ||
554 checkType(c,o,REDIS_LIST)) return;
555 llen = listTypeLength(o);
556
557 /* convert negative indexes */
558 if (start < 0) start = llen+start;
559 if (end < 0) end = llen+end;
560 if (start < 0) start = 0;
561
562 /* Invariant: start >= 0, so this test will be true when end < 0.
563 * The range is empty when start > end or start >= length. */
564 if (start > end || start >= llen) {
565 /* Out of range start or start > end result in empty list */
566 ltrim = llen;
567 rtrim = 0;
568 } else {
569 if (end >= llen) end = llen-1;
570 ltrim = start;
571 rtrim = llen-end-1;
572 }
573
574 /* Remove list elements to perform the trim */
575 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
576 o->ptr = ziplistDeleteRange(o->ptr,0,ltrim);
577 o->ptr = ziplistDeleteRange(o->ptr,-rtrim,rtrim);
578 } else if (o->encoding == REDIS_ENCODING_LINKEDLIST) {
579 list = o->ptr;
580 for (j = 0; j < ltrim; j++) {
581 ln = listFirst(list);
582 listDelNode(list,ln);
583 }
584 for (j = 0; j < rtrim; j++) {
585 ln = listLast(list);
586 listDelNode(list,ln);
587 }
588 } else {
589 redisPanic("Unknown list encoding");
590 }
591 if (listTypeLength(o) == 0) dbDelete(c->db,c->argv[1]);
592 signalModifiedKey(c->db,c->argv[1]);
593 server.dirty++;
594 addReply(c,shared.ok);
595 }
596
597 void lremCommand(redisClient *c) {
598 robj *subject, *obj;
599 obj = c->argv[3] = tryObjectEncoding(c->argv[3]);
600 long toremove;
601 long removed = 0;
602 listTypeEntry entry;
603
604 if ((getLongFromObjectOrReply(c, c->argv[2], &toremove, NULL) != REDIS_OK))
605 return;
606
607 subject = lookupKeyWriteOrReply(c,c->argv[1],shared.czero);
608 if (subject == NULL || checkType(c,subject,REDIS_LIST)) return;
609
610 /* Make sure obj is raw when we're dealing with a ziplist */
611 if (subject->encoding == REDIS_ENCODING_ZIPLIST)
612 obj = getDecodedObject(obj);
613
614 listTypeIterator *li;
615 if (toremove < 0) {
616 toremove = -toremove;
617 li = listTypeInitIterator(subject,-1,REDIS_HEAD);
618 } else {
619 li = listTypeInitIterator(subject,0,REDIS_TAIL);
620 }
621
622 while (listTypeNext(li,&entry)) {
623 if (listTypeEqual(&entry,obj)) {
624 listTypeDelete(&entry);
625 server.dirty++;
626 removed++;
627 if (toremove && removed == toremove) break;
628 }
629 }
630 listTypeReleaseIterator(li);
631
632 /* Clean up raw encoded object */
633 if (subject->encoding == REDIS_ENCODING_ZIPLIST)
634 decrRefCount(obj);
635
636 if (listTypeLength(subject) == 0) dbDelete(c->db,c->argv[1]);
637 addReplyLongLong(c,removed);
638 if (removed) signalModifiedKey(c->db,c->argv[1]);
639 }
640
641 /* This is the semantic of this command:
642 * RPOPLPUSH srclist dstlist:
643 * IF LLEN(srclist) > 0
644 * element = RPOP srclist
645 * LPUSH dstlist element
646 * RETURN element
647 * ELSE
648 * RETURN nil
649 * END
650 * END
651 *
652 * The idea is to be able to get an element from a list in a reliable way
653 * since the element is not just returned but pushed against another list
654 * as well. This command was originally proposed by Ezra Zygmuntowicz.
655 */
656
657 void rpoplpushHandlePush(redisClient *origclient, redisClient *c, robj *dstkey, robj *dstobj, robj *value) {
658 robj *aux;
659
660 if (!handleClientsWaitingListPush(origclient,dstkey,value)) {
661 /* Create the list if the key does not exist */
662 if (!dstobj) {
663 dstobj = createZiplistObject();
664 dbAdd(c->db,dstkey,dstobj);
665 } else {
666 signalModifiedKey(c->db,dstkey);
667 }
668 listTypePush(dstobj,value,REDIS_HEAD);
669 /* If we are pushing as a result of LPUSH against a key
670 * watched by BRPOPLPUSH, we need to rewrite the command vector
671 * as an LPUSH.
672 *
673 * If this is called directly by RPOPLPUSH (either directly
674 * or via a BRPOPLPUSH where the popped list exists)
675 * we should replicate the RPOPLPUSH command itself. */
676 if (c != origclient) {
677 aux = createStringObject("LPUSH",5);
678 rewriteClientCommandVector(origclient,3,aux,dstkey,value);
679 decrRefCount(aux);
680 } else {
681 /* Make sure to always use RPOPLPUSH in the replication / AOF,
682 * even if the original command was BRPOPLPUSH. */
683 aux = createStringObject("RPOPLPUSH",9);
684 rewriteClientCommandVector(origclient,3,aux,c->argv[1],c->argv[2]);
685 decrRefCount(aux);
686 }
687 server.dirty++;
688 }
689
690 /* Always send the pushed value to the client. */
691 addReplyBulk(c,value);
692 }
693
694 void rpoplpushCommand(redisClient *c) {
695 robj *sobj, *value;
696 if ((sobj = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
697 checkType(c,sobj,REDIS_LIST)) return;
698
699 if (listTypeLength(sobj) == 0) {
700 addReply(c,shared.nullbulk);
701 } else {
702 robj *dobj = lookupKeyWrite(c->db,c->argv[2]);
703 robj *touchedkey = c->argv[1];
704
705 if (dobj && checkType(c,dobj,REDIS_LIST)) return;
706 value = listTypePop(sobj,REDIS_TAIL);
707 /* We saved touched key, and protect it, since rpoplpushHandlePush
708 * may change the client command argument vector. */
709 incrRefCount(touchedkey);
710 rpoplpushHandlePush(c,c,c->argv[2],dobj,value);
711
712 /* listTypePop returns an object with its refcount incremented */
713 decrRefCount(value);
714
715 /* Delete the source list when it is empty */
716 if (listTypeLength(sobj) == 0) dbDelete(c->db,touchedkey);
717 signalModifiedKey(c->db,touchedkey);
718 decrRefCount(touchedkey);
719 server.dirty++;
720 }
721 }
722
723 /*-----------------------------------------------------------------------------
724 * Blocking POP operations
725 *----------------------------------------------------------------------------*/
726
727 /* Currently Redis blocking operations support is limited to list POP ops,
728 * so the current implementation is not fully generic, but it is also not
729 * completely specific so it will not require a rewrite to support new
730 * kind of blocking operations in the future.
731 *
732 * Still it's important to note that list blocking operations can be already
733 * used as a notification mechanism in order to implement other blocking
734 * operations at application level, so there must be a very strong evidence
735 * of usefulness and generality before new blocking operations are implemented.
736 *
737 * This is how the current blocking POP works, we use BLPOP as example:
738 * - If the user calls BLPOP and the key exists and contains a non empty list
739 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
740 * if there is not to block.
741 * - If instead BLPOP is called and the key does not exists or the list is
742 * empty we need to block. In order to do so we remove the notification for
743 * new data to read in the client socket (so that we'll not serve new
744 * requests if the blocking request is not served). Also we put the client
745 * in a dictionary (db->blocking_keys) mapping keys to a list of clients
746 * blocking for this keys.
747 * - If a PUSH operation against a key with blocked clients waiting is
748 * performed, we serve the first in the list: basically instead to push
749 * the new element inside the list we return it to the (first / oldest)
750 * blocking client, unblock the client, and remove it form the list.
751 *
752 * The above comment and the source code should be enough in order to understand
753 * the implementation and modify / fix it later.
754 */
755
756 /* Set a client in blocking mode for the specified key, with the specified
757 * timeout */
758 void blockForKeys(redisClient *c, robj **keys, int numkeys, time_t timeout, robj *target) {
759 dictEntry *de;
760 list *l;
761 int j;
762
763 c->bpop.keys = zmalloc(sizeof(robj*)*numkeys);
764 c->bpop.count = numkeys;
765 c->bpop.timeout = timeout;
766 c->bpop.target = target;
767
768 if (target != NULL) {
769 incrRefCount(target);
770 }
771
772 for (j = 0; j < numkeys; j++) {
773 /* Add the key in the client structure, to map clients -> keys */
774 c->bpop.keys[j] = keys[j];
775 incrRefCount(keys[j]);
776
777 /* And in the other "side", to map keys -> clients */
778 de = dictFind(c->db->blocking_keys,keys[j]);
779 if (de == NULL) {
780 int retval;
781
782 /* For every key we take a list of clients blocked for it */
783 l = listCreate();
784 retval = dictAdd(c->db->blocking_keys,keys[j],l);
785 incrRefCount(keys[j]);
786 redisAssertWithInfo(c,keys[j],retval == DICT_OK);
787 } else {
788 l = dictGetVal(de);
789 }
790 listAddNodeTail(l,c);
791 }
792 /* Mark the client as a blocked client */
793 c->flags |= REDIS_BLOCKED;
794 server.bpop_blocked_clients++;
795 }
796
797 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
798 void unblockClientWaitingData(redisClient *c) {
799 dictEntry *de;
800 list *l;
801 int j;
802
803 redisAssertWithInfo(c,NULL,c->bpop.keys != NULL);
804 /* The client may wait for multiple keys, so unblock it for every key. */
805 for (j = 0; j < c->bpop.count; j++) {
806 /* Remove this client from the list of clients waiting for this key. */
807 de = dictFind(c->db->blocking_keys,c->bpop.keys[j]);
808 redisAssertWithInfo(c,c->bpop.keys[j],de != NULL);
809 l = dictGetVal(de);
810 listDelNode(l,listSearchKey(l,c));
811 /* If the list is empty we need to remove it to avoid wasting memory */
812 if (listLength(l) == 0)
813 dictDelete(c->db->blocking_keys,c->bpop.keys[j]);
814 decrRefCount(c->bpop.keys[j]);
815 }
816
817 /* Cleanup the client structure */
818 zfree(c->bpop.keys);
819 c->bpop.keys = NULL;
820 if (c->bpop.target) decrRefCount(c->bpop.target);
821 c->bpop.target = NULL;
822 c->flags &= ~REDIS_BLOCKED;
823 c->flags |= REDIS_UNBLOCKED;
824 server.bpop_blocked_clients--;
825 listAddNodeTail(server.unblocked_clients,c);
826 }
827
828 /* This should be called from any function PUSHing into lists.
829 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
830 * 'ele' is the element pushed.
831 *
832 * If the function returns 0 there was no client waiting for a list push
833 * against this key.
834 *
835 * If the function returns 1 there was a client waiting for a list push
836 * against this key, the element was passed to this client thus it's not
837 * needed to actually add it to the list and the caller should return asap. */
838 int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele) {
839 struct dictEntry *de;
840 redisClient *receiver;
841 int numclients;
842 list *clients;
843 listNode *ln;
844 robj *dstkey, *dstobj;
845
846 de = dictFind(c->db->blocking_keys,key);
847 if (de == NULL) return 0;
848 clients = dictGetVal(de);
849 numclients = listLength(clients);
850
851 /* Try to handle the push as long as there are clients waiting for a push.
852 * Note that "numclients" is used because the list of clients waiting for a
853 * push on "key" is deleted by unblockClient() when empty.
854 *
855 * This loop will have more than 1 iteration when there is a BRPOPLPUSH
856 * that cannot push the target list because it does not contain a list. If
857 * this happens, it simply tries the next client waiting for a push. */
858 while (numclients--) {
859 ln = listFirst(clients);
860 redisAssertWithInfo(c,key,ln != NULL);
861 receiver = ln->value;
862 dstkey = receiver->bpop.target;
863
864 /* Protect receiver->bpop.target, that will be freed by
865 * the next unblockClientWaitingData() call. */
866 if (dstkey) incrRefCount(dstkey);
867
868 /* This should remove the first element of the "clients" list. */
869 unblockClientWaitingData(receiver);
870
871 if (dstkey == NULL) {
872 /* BRPOP/BLPOP */
873 addReplyMultiBulkLen(receiver,2);
874 addReplyBulk(receiver,key);
875 addReplyBulk(receiver,ele);
876 return 1; /* Serve just the first client as in B[RL]POP semantics */
877 } else {
878 /* BRPOPLPUSH, note that receiver->db is always equal to c->db. */
879 dstobj = lookupKeyWrite(receiver->db,dstkey);
880 if (!(dstobj && checkType(receiver,dstobj,REDIS_LIST))) {
881 rpoplpushHandlePush(c,receiver,dstkey,dstobj,ele);
882 decrRefCount(dstkey);
883 return 1;
884 }
885 decrRefCount(dstkey);
886 }
887 }
888
889 return 0;
890 }
891
892 int getTimeoutFromObjectOrReply(redisClient *c, robj *object, time_t *timeout) {
893 long tval;
894
895 if (getLongFromObjectOrReply(c,object,&tval,
896 "timeout is not an integer or out of range") != REDIS_OK)
897 return REDIS_ERR;
898
899 if (tval < 0) {
900 addReplyError(c,"timeout is negative");
901 return REDIS_ERR;
902 }
903
904 if (tval > 0) tval += time(NULL);
905 *timeout = tval;
906
907 return REDIS_OK;
908 }
909
910 /* Blocking RPOP/LPOP */
911 void blockingPopGenericCommand(redisClient *c, int where) {
912 robj *o;
913 time_t timeout;
914 int j;
915
916 if (getTimeoutFromObjectOrReply(c,c->argv[c->argc-1],&timeout) != REDIS_OK)
917 return;
918
919 for (j = 1; j < c->argc-1; j++) {
920 o = lookupKeyWrite(c->db,c->argv[j]);
921 if (o != NULL) {
922 if (o->type != REDIS_LIST) {
923 addReply(c,shared.wrongtypeerr);
924 return;
925 } else {
926 if (listTypeLength(o) != 0) {
927 /* If the list contains elements fall back to the usual
928 * non-blocking POP operation */
929 struct redisCommand *orig_cmd;
930 robj *argv[2], **orig_argv;
931 int orig_argc;
932
933 /* We need to alter the command arguments before to call
934 * popGenericCommand() as the command takes a single key. */
935 orig_argv = c->argv;
936 orig_argc = c->argc;
937 orig_cmd = c->cmd;
938 argv[1] = c->argv[j];
939 c->argv = argv;
940 c->argc = 2;
941
942 /* Also the return value is different, we need to output
943 * the multi bulk reply header and the key name. The
944 * "real" command will add the last element (the value)
945 * for us. If this souds like an hack to you it's just
946 * because it is... */
947 addReplyMultiBulkLen(c,2);
948 addReplyBulk(c,argv[1]);
949
950 popGenericCommand(c,where);
951
952 /* Fix the client structure with the original stuff */
953 c->argv = orig_argv;
954 c->argc = orig_argc;
955 c->cmd = orig_cmd;
956
957 return;
958 }
959 }
960 }
961 }
962
963 /* If we are inside a MULTI/EXEC and the list is empty the only thing
964 * we can do is treating it as a timeout (even with timeout 0). */
965 if (c->flags & REDIS_MULTI) {
966 addReply(c,shared.nullmultibulk);
967 return;
968 }
969
970 /* If the list is empty or the key does not exists we must block */
971 blockForKeys(c, c->argv + 1, c->argc - 2, timeout, NULL);
972 }
973
974 void blpopCommand(redisClient *c) {
975 blockingPopGenericCommand(c,REDIS_HEAD);
976 }
977
978 void brpopCommand(redisClient *c) {
979 blockingPopGenericCommand(c,REDIS_TAIL);
980 }
981
982 void brpoplpushCommand(redisClient *c) {
983 time_t timeout;
984
985 if (getTimeoutFromObjectOrReply(c,c->argv[3],&timeout) != REDIS_OK)
986 return;
987
988 robj *key = lookupKeyWrite(c->db, c->argv[1]);
989
990 if (key == NULL) {
991 if (c->flags & REDIS_MULTI) {
992
993 /* Blocking against an empty list in a multi state
994 * returns immediately. */
995 addReply(c, shared.nullbulk);
996 } else {
997 /* The list is empty and the client blocks. */
998 blockForKeys(c, c->argv + 1, 1, timeout, c->argv[2]);
999 }
1000 } else {
1001 if (key->type != REDIS_LIST) {
1002 addReply(c, shared.wrongtypeerr);
1003 } else {
1004
1005 /* The list exists and has elements, so
1006 * the regular rpoplpushCommand is executed. */
1007 redisAssertWithInfo(c,key,listTypeLength(key) > 0);
1008 rpoplpushCommand(c);
1009 }
1010 }
1011 }