]> git.saurik.com Git - redis.git/blame - src/t_list.c
top level Makefile added, so you do not need to cd src
[redis.git] / src / t_list.c
CommitLineData
e2641e09 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. */
10void 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
17void 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
41robj *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
78unsigned 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. */
89listTypeIterator *listTypeInitIterator(robj *subject, int 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. */
105void 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. */
112int 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. */
142robj *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
167void 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. */
198int listTypeEqual(listTypeEntry *entry, robj *o) {
199 listTypeIterator *li = entry->li;
200 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
201 redisAssert(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. */
211void 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
235void listTypeConvert(robj *subject, int enc) {
236 listTypeIterator *li;
237 listTypeEntry entry;
238 redisAssert(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
261void pushGenericCommand(redisClient *c, int where) {
262 robj *lobj = lookupKeyWrite(c->db,c->argv[1]);
263 if (lobj == NULL) {
264 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
265 addReply(c,shared.cone);
266 return;
267 }
268 lobj = createZiplistObject();
269 dbAdd(c->db,c->argv[1],lobj);
270 } else {
271 if (lobj->type != REDIS_LIST) {
272 addReply(c,shared.wrongtypeerr);
273 return;
274 }
275 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
276 addReply(c,shared.cone);
277 return;
278 }
279 }
280 listTypePush(lobj,c->argv[2],where);
281 addReplyLongLong(c,listTypeLength(lobj));
282 server.dirty++;
283}
284
285void lpushCommand(redisClient *c) {
286 pushGenericCommand(c,REDIS_HEAD);
287}
288
289void rpushCommand(redisClient *c) {
290 pushGenericCommand(c,REDIS_TAIL);
291}
292
293void pushxGenericCommand(redisClient *c, robj *refval, robj *val, int where) {
294 robj *subject;
295 listTypeIterator *iter;
296 listTypeEntry entry;
297 int inserted = 0;
298
299 if ((subject = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
300 checkType(c,subject,REDIS_LIST)) return;
301
302 if (refval != NULL) {
303 /* Note: we expect refval to be string-encoded because it is *not* the
304 * last argument of the multi-bulk LINSERT. */
305 redisAssert(refval->encoding == REDIS_ENCODING_RAW);
306
307 /* We're not sure if this value can be inserted yet, but we cannot
308 * convert the list inside the iterator. We don't want to loop over
309 * the list twice (once to see if the value can be inserted and once
310 * to do the actual insert), so we assume this value can be inserted
311 * and convert the ziplist to a regular list if necessary. */
312 listTypeTryConversion(subject,val);
313
314 /* Seek refval from head to tail */
315 iter = listTypeInitIterator(subject,0,REDIS_TAIL);
316 while (listTypeNext(iter,&entry)) {
317 if (listTypeEqual(&entry,refval)) {
318 listTypeInsert(&entry,val,where);
319 inserted = 1;
320 break;
321 }
322 }
323 listTypeReleaseIterator(iter);
324
325 if (inserted) {
326 /* Check if the length exceeds the ziplist length threshold. */
327 if (subject->encoding == REDIS_ENCODING_ZIPLIST &&
328 ziplistLen(subject->ptr) > server.list_max_ziplist_entries)
329 listTypeConvert(subject,REDIS_ENCODING_LINKEDLIST);
330 server.dirty++;
331 } else {
332 /* Notify client of a failed insert */
333 addReply(c,shared.cnegone);
334 return;
335 }
336 } else {
337 listTypePush(subject,val,where);
338 server.dirty++;
339 }
340
341 addReplyUlong(c,listTypeLength(subject));
342}
343
344void lpushxCommand(redisClient *c) {
345 pushxGenericCommand(c,NULL,c->argv[2],REDIS_HEAD);
346}
347
348void rpushxCommand(redisClient *c) {
349 pushxGenericCommand(c,NULL,c->argv[2],REDIS_TAIL);
350}
351
352void linsertCommand(redisClient *c) {
353 if (strcasecmp(c->argv[2]->ptr,"after") == 0) {
354 pushxGenericCommand(c,c->argv[3],c->argv[4],REDIS_TAIL);
355 } else if (strcasecmp(c->argv[2]->ptr,"before") == 0) {
356 pushxGenericCommand(c,c->argv[3],c->argv[4],REDIS_HEAD);
357 } else {
358 addReply(c,shared.syntaxerr);
359 }
360}
361
362void llenCommand(redisClient *c) {
363 robj *o = lookupKeyReadOrReply(c,c->argv[1],shared.czero);
364 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
365 addReplyUlong(c,listTypeLength(o));
366}
367
368void lindexCommand(redisClient *c) {
369 robj *o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk);
370 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
371 int index = atoi(c->argv[2]->ptr);
372 robj *value = NULL;
373
374 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
375 unsigned char *p;
376 unsigned char *vstr;
377 unsigned int vlen;
378 long long vlong;
379 p = ziplistIndex(o->ptr,index);
380 if (ziplistGet(p,&vstr,&vlen,&vlong)) {
381 if (vstr) {
382 value = createStringObject((char*)vstr,vlen);
383 } else {
384 value = createStringObjectFromLongLong(vlong);
385 }
386 addReplyBulk(c,value);
387 decrRefCount(value);
388 } else {
389 addReply(c,shared.nullbulk);
390 }
391 } else if (o->encoding == REDIS_ENCODING_LINKEDLIST) {
392 listNode *ln = listIndex(o->ptr,index);
393 if (ln != NULL) {
394 value = listNodeValue(ln);
395 addReplyBulk(c,value);
396 } else {
397 addReply(c,shared.nullbulk);
398 }
399 } else {
400 redisPanic("Unknown list encoding");
401 }
402}
403
404void lsetCommand(redisClient *c) {
405 robj *o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr);
406 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
407 int index = atoi(c->argv[2]->ptr);
408 robj *value = c->argv[3];
409
410 listTypeTryConversion(o,value);
411 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
412 unsigned char *p, *zl = o->ptr;
413 p = ziplistIndex(zl,index);
414 if (p == NULL) {
415 addReply(c,shared.outofrangeerr);
416 } else {
417 o->ptr = ziplistDelete(o->ptr,&p);
418 value = getDecodedObject(value);
419 o->ptr = ziplistInsert(o->ptr,p,value->ptr,sdslen(value->ptr));
420 decrRefCount(value);
421 addReply(c,shared.ok);
422 server.dirty++;
423 }
424 } else if (o->encoding == REDIS_ENCODING_LINKEDLIST) {
425 listNode *ln = listIndex(o->ptr,index);
426 if (ln == NULL) {
427 addReply(c,shared.outofrangeerr);
428 } else {
429 decrRefCount((robj*)listNodeValue(ln));
430 listNodeValue(ln) = value;
431 incrRefCount(value);
432 addReply(c,shared.ok);
433 server.dirty++;
434 }
435 } else {
436 redisPanic("Unknown list encoding");
437 }
438}
439
440void popGenericCommand(redisClient *c, int where) {
441 robj *o = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk);
442 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
443
444 robj *value = listTypePop(o,where);
445 if (value == NULL) {
446 addReply(c,shared.nullbulk);
447 } else {
448 addReplyBulk(c,value);
449 decrRefCount(value);
450 if (listTypeLength(o) == 0) dbDelete(c->db,c->argv[1]);
451 server.dirty++;
452 }
453}
454
455void lpopCommand(redisClient *c) {
456 popGenericCommand(c,REDIS_HEAD);
457}
458
459void rpopCommand(redisClient *c) {
460 popGenericCommand(c,REDIS_TAIL);
461}
462
463void lrangeCommand(redisClient *c) {
464 robj *o, *value;
465 int start = atoi(c->argv[2]->ptr);
466 int end = atoi(c->argv[3]->ptr);
467 int llen;
468 int rangelen, j;
469 listTypeEntry entry;
470
471 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
472 || checkType(c,o,REDIS_LIST)) return;
473 llen = listTypeLength(o);
474
475 /* convert negative indexes */
476 if (start < 0) start = llen+start;
477 if (end < 0) end = llen+end;
478 if (start < 0) start = 0;
e2641e09 479
d0a4e24e
PN
480 /* Invariant: start >= 0, so this test will be true when end < 0.
481 * The range is empty when start > end or start >= length. */
e2641e09 482 if (start > end || start >= llen) {
e2641e09 483 addReply(c,shared.emptymultibulk);
484 return;
485 }
486 if (end >= llen) end = llen-1;
487 rangelen = (end-start)+1;
488
489 /* Return the result in form of a multi-bulk reply */
490 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",rangelen));
491 listTypeIterator *li = listTypeInitIterator(o,start,REDIS_TAIL);
492 for (j = 0; j < rangelen; j++) {
493 redisAssert(listTypeNext(li,&entry));
494 value = listTypeGet(&entry);
495 addReplyBulk(c,value);
496 decrRefCount(value);
497 }
498 listTypeReleaseIterator(li);
499}
500
501void ltrimCommand(redisClient *c) {
502 robj *o;
503 int start = atoi(c->argv[2]->ptr);
504 int end = atoi(c->argv[3]->ptr);
505 int llen;
506 int j, ltrim, rtrim;
507 list *list;
508 listNode *ln;
509
510 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.ok)) == NULL ||
511 checkType(c,o,REDIS_LIST)) return;
512 llen = listTypeLength(o);
513
514 /* convert negative indexes */
515 if (start < 0) start = llen+start;
516 if (end < 0) end = llen+end;
517 if (start < 0) start = 0;
e2641e09 518
d0a4e24e
PN
519 /* Invariant: start >= 0, so this test will be true when end < 0.
520 * The range is empty when start > end or start >= length. */
e2641e09 521 if (start > end || start >= llen) {
522 /* Out of range start or start > end result in empty list */
523 ltrim = llen;
524 rtrim = 0;
525 } else {
526 if (end >= llen) end = llen-1;
527 ltrim = start;
528 rtrim = llen-end-1;
529 }
530
531 /* Remove list elements to perform the trim */
532 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
533 o->ptr = ziplistDeleteRange(o->ptr,0,ltrim);
534 o->ptr = ziplistDeleteRange(o->ptr,-rtrim,rtrim);
535 } else if (o->encoding == REDIS_ENCODING_LINKEDLIST) {
536 list = o->ptr;
537 for (j = 0; j < ltrim; j++) {
538 ln = listFirst(list);
539 listDelNode(list,ln);
540 }
541 for (j = 0; j < rtrim; j++) {
542 ln = listLast(list);
543 listDelNode(list,ln);
544 }
545 } else {
546 redisPanic("Unknown list encoding");
547 }
548 if (listTypeLength(o) == 0) dbDelete(c->db,c->argv[1]);
549 server.dirty++;
550 addReply(c,shared.ok);
551}
552
553void lremCommand(redisClient *c) {
554 robj *subject, *obj = c->argv[3];
555 int toremove = atoi(c->argv[2]->ptr);
556 int removed = 0;
557 listTypeEntry entry;
558
559 subject = lookupKeyWriteOrReply(c,c->argv[1],shared.czero);
560 if (subject == NULL || checkType(c,subject,REDIS_LIST)) return;
561
562 /* Make sure obj is raw when we're dealing with a ziplist */
563 if (subject->encoding == REDIS_ENCODING_ZIPLIST)
564 obj = getDecodedObject(obj);
565
566 listTypeIterator *li;
567 if (toremove < 0) {
568 toremove = -toremove;
569 li = listTypeInitIterator(subject,-1,REDIS_HEAD);
570 } else {
571 li = listTypeInitIterator(subject,0,REDIS_TAIL);
572 }
573
574 while (listTypeNext(li,&entry)) {
575 if (listTypeEqual(&entry,obj)) {
576 listTypeDelete(&entry);
577 server.dirty++;
578 removed++;
579 if (toremove && removed == toremove) break;
580 }
581 }
582 listTypeReleaseIterator(li);
583
584 /* Clean up raw encoded object */
585 if (subject->encoding == REDIS_ENCODING_ZIPLIST)
586 decrRefCount(obj);
587
588 if (listTypeLength(subject) == 0) dbDelete(c->db,c->argv[1]);
589 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",removed));
590}
591
592/* This is the semantic of this command:
593 * RPOPLPUSH srclist dstlist:
594 * IF LLEN(srclist) > 0
595 * element = RPOP srclist
596 * LPUSH dstlist element
597 * RETURN element
598 * ELSE
599 * RETURN nil
600 * END
601 * END
602 *
603 * The idea is to be able to get an element from a list in a reliable way
604 * since the element is not just returned but pushed against another list
605 * as well. This command was originally proposed by Ezra Zygmuntowicz.
606 */
607void rpoplpushcommand(redisClient *c) {
608 robj *sobj, *value;
609 if ((sobj = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
610 checkType(c,sobj,REDIS_LIST)) return;
611
612 if (listTypeLength(sobj) == 0) {
613 addReply(c,shared.nullbulk);
614 } else {
615 robj *dobj = lookupKeyWrite(c->db,c->argv[2]);
616 if (dobj && checkType(c,dobj,REDIS_LIST)) return;
617 value = listTypePop(sobj,REDIS_TAIL);
618
619 /* Add the element to the target list (unless it's directly
620 * passed to some BLPOP-ing client */
621 if (!handleClientsWaitingListPush(c,c->argv[2],value)) {
622 /* Create the list if the key does not exist */
623 if (!dobj) {
624 dobj = createZiplistObject();
625 dbAdd(c->db,c->argv[2],dobj);
626 }
627 listTypePush(dobj,value,REDIS_HEAD);
628 }
629
630 /* Send the element to the client as reply as well */
631 addReplyBulk(c,value);
632
633 /* listTypePop returns an object with its refcount incremented */
634 decrRefCount(value);
635
636 /* Delete the source list when it is empty */
637 if (listTypeLength(sobj) == 0) dbDelete(c->db,c->argv[1]);
638 server.dirty++;
639 }
640}
641
642/*-----------------------------------------------------------------------------
643 * Blocking POP operations
644 *----------------------------------------------------------------------------*/
645
646/* Currently Redis blocking operations support is limited to list POP ops,
647 * so the current implementation is not fully generic, but it is also not
648 * completely specific so it will not require a rewrite to support new
649 * kind of blocking operations in the future.
650 *
651 * Still it's important to note that list blocking operations can be already
652 * used as a notification mechanism in order to implement other blocking
653 * operations at application level, so there must be a very strong evidence
654 * of usefulness and generality before new blocking operations are implemented.
655 *
656 * This is how the current blocking POP works, we use BLPOP as example:
657 * - If the user calls BLPOP and the key exists and contains a non empty list
658 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
659 * if there is not to block.
660 * - If instead BLPOP is called and the key does not exists or the list is
661 * empty we need to block. In order to do so we remove the notification for
662 * new data to read in the client socket (so that we'll not serve new
663 * requests if the blocking request is not served). Also we put the client
664 * in a dictionary (db->blocking_keys) mapping keys to a list of clients
665 * blocking for this keys.
666 * - If a PUSH operation against a key with blocked clients waiting is
667 * performed, we serve the first in the list: basically instead to push
668 * the new element inside the list we return it to the (first / oldest)
669 * blocking client, unblock the client, and remove it form the list.
670 *
671 * The above comment and the source code should be enough in order to understand
672 * the implementation and modify / fix it later.
673 */
674
675/* Set a client in blocking mode for the specified key, with the specified
676 * timeout */
677void blockForKeys(redisClient *c, robj **keys, int numkeys, time_t timeout) {
678 dictEntry *de;
679 list *l;
680 int j;
681
682 c->blocking_keys = zmalloc(sizeof(robj*)*numkeys);
683 c->blocking_keys_num = numkeys;
684 c->blockingto = timeout;
685 for (j = 0; j < numkeys; j++) {
686 /* Add the key in the client structure, to map clients -> keys */
687 c->blocking_keys[j] = keys[j];
688 incrRefCount(keys[j]);
689
690 /* And in the other "side", to map keys -> clients */
691 de = dictFind(c->db->blocking_keys,keys[j]);
692 if (de == NULL) {
693 int retval;
694
695 /* For every key we take a list of clients blocked for it */
696 l = listCreate();
697 retval = dictAdd(c->db->blocking_keys,keys[j],l);
698 incrRefCount(keys[j]);
699 redisAssert(retval == DICT_OK);
700 } else {
701 l = dictGetEntryVal(de);
702 }
703 listAddNodeTail(l,c);
704 }
705 /* Mark the client as a blocked client */
706 c->flags |= REDIS_BLOCKED;
707 server.blpop_blocked_clients++;
708}
709
710/* Unblock a client that's waiting in a blocking operation such as BLPOP */
711void unblockClientWaitingData(redisClient *c) {
712 dictEntry *de;
713 list *l;
714 int j;
715
716 redisAssert(c->blocking_keys != NULL);
717 /* The client may wait for multiple keys, so unblock it for every key. */
718 for (j = 0; j < c->blocking_keys_num; j++) {
719 /* Remove this client from the list of clients waiting for this key. */
720 de = dictFind(c->db->blocking_keys,c->blocking_keys[j]);
721 redisAssert(de != NULL);
722 l = dictGetEntryVal(de);
723 listDelNode(l,listSearchKey(l,c));
724 /* If the list is empty we need to remove it to avoid wasting memory */
725 if (listLength(l) == 0)
726 dictDelete(c->db->blocking_keys,c->blocking_keys[j]);
727 decrRefCount(c->blocking_keys[j]);
728 }
729 /* Cleanup the client structure */
730 zfree(c->blocking_keys);
731 c->blocking_keys = NULL;
732 c->flags &= (~REDIS_BLOCKED);
733 server.blpop_blocked_clients--;
734 /* We want to process data if there is some command waiting
735 * in the input buffer. Note that this is safe even if
736 * unblockClientWaitingData() gets called from freeClient() because
737 * freeClient() will be smart enough to call this function
738 * *after* c->querybuf was set to NULL. */
739 if (c->querybuf && sdslen(c->querybuf) > 0) processInputBuffer(c);
740}
741
742/* This should be called from any function PUSHing into lists.
743 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
744 * 'ele' is the element pushed.
745 *
746 * If the function returns 0 there was no client waiting for a list push
747 * against this key.
748 *
749 * If the function returns 1 there was a client waiting for a list push
750 * against this key, the element was passed to this client thus it's not
751 * needed to actually add it to the list and the caller should return asap. */
752int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele) {
753 struct dictEntry *de;
754 redisClient *receiver;
755 list *l;
756 listNode *ln;
757
758 de = dictFind(c->db->blocking_keys,key);
759 if (de == NULL) return 0;
760 l = dictGetEntryVal(de);
761 ln = listFirst(l);
762 redisAssert(ln != NULL);
763 receiver = ln->value;
764
765 addReplySds(receiver,sdsnew("*2\r\n"));
766 addReplyBulk(receiver,key);
767 addReplyBulk(receiver,ele);
768 unblockClientWaitingData(receiver);
769 return 1;
770}
771
772/* Blocking RPOP/LPOP */
773void blockingPopGenericCommand(redisClient *c, int where) {
774 robj *o;
775 time_t timeout;
776 int j;
777
778 for (j = 1; j < c->argc-1; j++) {
779 o = lookupKeyWrite(c->db,c->argv[j]);
780 if (o != NULL) {
781 if (o->type != REDIS_LIST) {
782 addReply(c,shared.wrongtypeerr);
783 return;
784 } else {
785 if (listTypeLength(o) != 0) {
786 /* If the list contains elements fall back to the usual
787 * non-blocking POP operation */
788 robj *argv[2], **orig_argv;
789 int orig_argc;
790
791 /* We need to alter the command arguments before to call
792 * popGenericCommand() as the command takes a single key. */
793 orig_argv = c->argv;
794 orig_argc = c->argc;
795 argv[1] = c->argv[j];
796 c->argv = argv;
797 c->argc = 2;
798
799 /* Also the return value is different, we need to output
800 * the multi bulk reply header and the key name. The
801 * "real" command will add the last element (the value)
802 * for us. If this souds like an hack to you it's just
803 * because it is... */
804 addReplySds(c,sdsnew("*2\r\n"));
805 addReplyBulk(c,argv[1]);
806 popGenericCommand(c,where);
807
808 /* Fix the client structure with the original stuff */
809 c->argv = orig_argv;
810 c->argc = orig_argc;
811 return;
812 }
813 }
814 }
815 }
816 /* If the list is empty or the key does not exists we must block */
817 timeout = strtol(c->argv[c->argc-1]->ptr,NULL,10);
818 if (timeout > 0) timeout += time(NULL);
819 blockForKeys(c,c->argv+1,c->argc-2,timeout);
820}
821
822void blpopCommand(redisClient *c) {
823 blockingPopGenericCommand(c,REDIS_HEAD);
824}
825
826void brpopCommand(redisClient *c) {
827 blockingPopGenericCommand(c,REDIS_TAIL);
828}