Make peek show next delayed job (#919).
[beanstalkd.git] / job.c
blob04d0df14a5869d9f4e6f1767366823e1bdd385d2
1 /* job.c - a job in the queue */
3 #include <stdlib.h>
4 #include <string.h>
6 #include "job.h"
7 #include "util.h"
9 static unsigned long long int next_id = 1;
11 job
12 allocate_job(int body_size)
14 job j;
16 j = malloc(sizeof(struct job) + body_size);
17 if (!j) return twarnx("OOM"), NULL;
19 j->state = JOB_STATE_INVALID;
20 j->creation = time(NULL);
21 j->timeout_ct = j->release_ct = j->bury_ct = j->kick_ct = 0;
22 j->body_size = body_size;
23 j->next = j->prev = j; /* not in a linked list */
25 return j;
28 job
29 make_job(unsigned int pri, unsigned int delay, int body_size)
31 job j;
33 j = allocate_job(body_size);
34 if (!j) return twarnx("OOM"), NULL;
36 j->id = next_id++;
37 j->pri = pri;
38 j->delay = delay;
40 return j;
43 int
44 job_pri_cmp(job a, job b)
46 if (a->pri == b->pri) {
47 /* we can't just subtract because id has too many bits */
48 if (a->id > b->id) return 1;
49 if (a->id < b->id) return -1;
50 return 0;
52 return a->pri - b->pri;
55 int
56 job_delay_cmp(job a, job b)
58 if (a->deadline == b->deadline) {
59 /* we can't just subtract because id has too many bits */
60 if (a->id > b->id) return 1;
61 if (a->id < b->id) return -1;
62 return 0;
64 return a->deadline - b->deadline;
67 job
68 job_copy(job j)
70 job n;
72 if (!j) return NULL;
74 n = malloc(sizeof(struct job) + j->body_size);
75 if (!n) return twarnx("OOM"), NULL;
77 n->id = j->id;
78 n->pri = j->pri;
79 n->body_size = j->body_size;
80 memcpy(n->body, j->body, j->body_size);
82 return n;
85 const char *
86 job_state(job j)
88 if (j->state == JOB_STATE_READY) return "ready";
89 if (j->state == JOB_STATE_RESERVED) return "reserved";
90 if (j->state == JOB_STATE_BURIED) return "buried";
91 if (j->state == JOB_STATE_DELAY) return "delay";
92 return "invalid";
95 int
96 job_list_any_p(job head)
98 return head->next != head || head->prev != head;
102 job_remove(job j)
104 if (!j) return NULL;
105 if (!job_list_any_p(j)) return NULL; /* not in a doubly-linked list */
107 j->next->prev = j->prev;
108 j->prev->next = j->next;
110 j->prev = j->next = j;
112 return j;
115 void
116 job_insert(job head, job j)
118 if (job_list_any_p(j)) return; /* already in a linked list */
120 j->prev = head->prev;
121 j->next = head;
122 head->prev->next = j;
123 head->prev = j;
126 unsigned long long int
127 total_jobs()
129 return next_id - 1;