File: buffer.c

package info (click to toggle)
py-postgresql 1.2.1%2Bgit20180803.ef7b9a9-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,620 kB
  • sloc: python: 18,317; ansic: 2,024; sql: 282; sh: 26; makefile: 22
file content (629 lines) | stat: -rw-r--r-- 12,100 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
/*
 * .port.optimized.pq_message_buffer - PQ message stream
 */
/*
 * PQ messages normally take the form {type, (size), data}
 */
#define include_buffer_types \
	mTYPE(pq_message_stream)

struct p_list
{
	PyObject *data; /* PyBytes pushed onto the buffer */
	struct p_list *next;
};

struct p_place
{
	struct p_list *list;
	uint32_t offset;
};

struct p_buffer
{
	PyObject_HEAD

	struct p_place position;
	struct p_list *last; /* for quick appends */
};

/*
 * Free the list until the given stop
 */
static void
pl_truncate(struct p_list *pl, struct p_list *stop)
{
	while (pl != stop)
	{
		struct p_list *next = pl->next;
		Py_DECREF(pl->data);
		free(pl);
		pl = next;
	}
}

/*
 * Reset the buffer
 */
static void
pb_truncate(struct p_buffer *pb)
{
	struct p_list *pl = pb->position.list;

	pb->position.offset = 0;
	pb->position.list = NULL;
	pb->last = NULL;

	pl_truncate(pl, NULL);
}

/*
 * p_truncate - truncate the buffer
 */
static PyObject *
p_truncate(PyObject *self)
{
	pb_truncate((struct p_buffer *) self);
	Py_INCREF(Py_None);
	return(Py_None);
}


static void
p_dealloc(PyObject *self)
{
	struct p_buffer *pb = ((struct p_buffer *) self);
	pb_truncate(pb);
	self->ob_type->tp_free(self);
}

static PyObject *
p_new(PyTypeObject *subtype, PyObject *args, PyObject *kw)
{
	static char *kwlist[] = {NULL};
	struct p_buffer *pb;
	PyObject *rob;

	if (!PyArg_ParseTupleAndKeywords(args, kw, "", kwlist))
		return(NULL);

	rob = subtype->tp_alloc(subtype, 0);
	pb = ((struct p_buffer *) rob);
	pb->last = pb->position.list = NULL;
	pb->position.offset = 0;
	return(rob);
}

/*
 * p_at_least - whether the position has at least given number of bytes.
 */
static char
p_at_least(struct p_place *p, uint32_t amount)
{
	uint32_t current = 0;
	struct p_list *pl;

	pl = p->list;
	if (pl)
		current += PyBytes_GET_SIZE(pl->data) - p->offset;

	if (current >= amount)
		return((char) 1);

	if (pl)
	{
		for (pl = pl->next; pl != NULL; pl = pl->next)
		{
			current += PyBytes_GET_SIZE(pl->data);
			if (current >= amount)
				return((char) 1);
		}
	}

	return((char) 0);
}

static uint32_t
p_seek(struct p_place *p, uint32_t amount)
{
	uint32_t amount_left = amount;
	Py_ssize_t chunk_size;

	/* Can't seek after the end. */
	if (!p->list || p->offset == PyBytes_GET_SIZE(p->list->data))
		return(0);

	chunk_size = PyBytes_GET_SIZE(p->list->data) - p->offset;

	while (amount_left > 0)
	{
		/*
		 * The current list item has the position.
		 * Set the offset and break out.
		 */
		if (amount_left < chunk_size)
		{
			p->offset += amount_left;
			amount_left = 0;
			break;
		}

		amount_left -= chunk_size;
		p->list = p->list->next;
		p->offset = 0;
		if (p->list == NULL)
			break;

		chunk_size = PyBytes_GET_SIZE(p->list->data);
	}

	return(amount - amount_left);
}

static uint32_t
p_memcpy(char *dst, struct p_place *p, uint32_t amount)
{
	struct p_list *pl = p->list;
	uint32_t offset = p->offset;
	uint32_t amount_left = amount;
	char *src;
	Py_ssize_t chunk_size;

	/* Nothing to read */
	if (pl == NULL)
		return(0);

	src = (PyBytes_AS_STRING(pl->data) + offset);
	chunk_size = PyBytes_GET_SIZE(pl->data) - offset;

	while (amount_left > 0)
	{
		uint32_t this_read =
			chunk_size < amount_left ? chunk_size : amount_left;

		memcpy(dst, src, this_read);
		dst = dst + this_read;
		amount_left = amount_left - this_read;

		pl = pl->next;
		if (pl == NULL)
			break;

		src = PyBytes_AS_STRING(pl->data);
		chunk_size = PyBytes_GET_SIZE(pl->data);
	}

	return(amount - amount_left);
}

static Py_ssize_t
p_length(PyObject *self)
{
	char header[5];
	long msg_count = 0;
	uint32_t msg_length;
	uint32_t copy_amount = 0;
	struct p_buffer *pb;
	struct p_place p;

	pb = ((struct p_buffer *) self);
	p.list = pb->position.list;
	p.offset = pb->position.offset;

	while (p.list != NULL)
	{
		copy_amount = p_memcpy(header, &p, 5);
		if (copy_amount < 5)
			break;
		p_seek(&p, copy_amount);

		memcpy(&msg_length, header + 1, 4);
		msg_length = local_ntohl(msg_length);
		if (msg_length < 4)
		{
			PyErr_Format(PyExc_ValueError,
				"invalid message size '%d'", msg_length);
			return(-1);
		}
		msg_length -= 4;

		if (p_seek(&p, msg_length) < msg_length)
			break;

		++msg_count;
	}

	return(msg_count);
}

static PySequenceMethods pq_ms_as_sequence = {
	(lenfunc) p_length, 0
};


/*
 * Build a tuple from the given place.
 */
static PyObject *
p_build_tuple(struct p_place *p)
{
	char header[5];
	uint32_t msg_length;
	PyObject *tuple;
	PyObject *mt, *md;

	char *body = NULL;
	uint32_t copy_amount = 0;

	copy_amount = p_memcpy(header, p, 5);
	if (copy_amount < 5)
		return(NULL);
	p_seek(p, copy_amount);

	memcpy(&msg_length, header + 1, 4);
	msg_length = local_ntohl(msg_length);
	if (msg_length < 4)
	{
		PyErr_Format(PyExc_ValueError,
			"invalid message size '%d'", msg_length);
		return(NULL);
	}
	msg_length -= 4;

	if (!p_at_least(p, msg_length))
		return(NULL);

	/*
	 * Copy out the message body if we need to.
	 */
	if (msg_length > 0)
	{
		body = malloc(msg_length);
		if (body == NULL)
		{
			PyErr_SetString(PyExc_MemoryError,
				"could not allocate memory for message data");
			return(NULL);
		}
		copy_amount = p_memcpy(body, p, msg_length);

		if (copy_amount != msg_length)
		{
			free(body);
			return(NULL);
		}

		p_seek(p, copy_amount);
	}

	mt = PyTuple_GET_ITEM(message_types, (int) header[0]);
	if (mt == NULL)
	{
		/*
		 * With message_types, this is nearly a can't happen.
		 */
		if (body != NULL) free(body);
		return(NULL);
	}
	Py_INCREF(mt);

	md = PyBytes_FromStringAndSize(body, (Py_ssize_t) msg_length);
	if (body != NULL)
		free(body);
	if (md == NULL)
	{
		Py_DECREF(mt);
		return(NULL);
	}


	tuple = PyTuple_New(2);
	if (tuple == NULL)
	{
		Py_DECREF(mt);
		Py_DECREF(md);
	}
	else
	{
		PyTuple_SET_ITEM(tuple, 0, mt);
		PyTuple_SET_ITEM(tuple, 1, md);
	}

	return(tuple);
}

static PyObject *
p_write(PyObject *self, PyObject *data)
{
	struct p_buffer *pb;

	if (!PyBytes_Check(data))
	{
		PyErr_SetString(PyExc_TypeError,
			"pq buffer.write() method requires a bytes object");
		return(NULL);
	}
	pb = ((struct p_buffer *) self);

	if (PyBytes_GET_SIZE(data) > 0)
	{
		struct p_list *pl;

		pl = malloc(sizeof(struct p_list));
		if (pl == NULL)
		{
			PyErr_SetString(PyExc_MemoryError,
				"could not allocate memory for pq message stream data");
			return(NULL);
		}

		pl->data = data;
		Py_INCREF(data);
		pl->next = NULL;

		if (pb->last == NULL)
		{
			/*
			 * First and last.
			 */
			pb->position.list = pb->last = pl;
		}
		else
		{
			pb->last->next = pl;
			pb->last = pl;
		}
	}

	Py_INCREF(Py_None);
	return(Py_None);
}

static PyObject *
p_next(PyObject *self)
{
	struct p_buffer *pb = ((struct p_buffer *) self);
	struct p_place p;
	PyObject *rob;

	p.offset = pb->position.offset;
	p.list = pb->position.list;

	rob = p_build_tuple(&p);
	if (rob != NULL)
	{
		pl_truncate(pb->position.list, p.list);
		pb->position.list = p.list;
		pb->position.offset = p.offset;
		if (p.list == NULL)
			pb->last = NULL;
	}
	return(rob);
}

static PyObject *
p_read(PyObject *self, PyObject *args)
{
	int cur_msg, msg_count = -1, msg_in = 0;
	struct p_place p;
	struct p_buffer *pb;
	PyObject *rob = NULL;

	if (!PyArg_ParseTuple(args, "|i", &msg_count))
		return(NULL);

	pb = (struct p_buffer *) self;
	p.list = pb->position.list;
	p.offset = pb->position.offset;

	msg_in = p_length(self);
	msg_count = msg_count < msg_in && msg_count != -1 ? msg_count : msg_in;

	rob = PyTuple_New(msg_count);
	for (cur_msg = 0; cur_msg < msg_count; ++cur_msg)
	{
		PyObject *msg_tup = NULL;
		msg_tup = p_build_tuple(&p);
		if (msg_tup == NULL)
		{
			if (PyErr_Occurred())
			{
				Py_DECREF(rob);
				return(NULL);
			}
			break;
		}

		PyTuple_SET_ITEM(rob, cur_msg, msg_tup);
	}

	pl_truncate(pb->position.list, p.list);
	pb->position.list = p.list;
	pb->position.offset = p.offset;
	if (p.list == NULL)
		pb->last = NULL;

	return(rob);
}

static PyObject *
p_has_message(PyObject *self)
{
	char header[5];
	uint32_t msg_length;
	uint32_t copy_amount = 0;
	struct p_buffer *pb;
	struct p_place p;
	PyObject *rob;

	pb = ((struct p_buffer *) self);
	p.list = pb->position.list;
	p.offset = pb->position.offset;

	copy_amount = p_memcpy(header, &p, 5);
	if (copy_amount < 5)
	{
		Py_INCREF(Py_False);
		return(Py_False);
	}
	p_seek(&p, copy_amount);
	memcpy(&msg_length, header + 1, 4);

	msg_length = local_ntohl(msg_length);
	if (msg_length < 4)
	{
		PyErr_Format(PyExc_ValueError,
			"invalid message size '%d'", msg_length);
		return(NULL);
	}
	msg_length -= 4;

	rob = p_at_least(&p, msg_length) ? Py_True : Py_False;
	Py_INCREF(rob);
	return(rob);
}

static PyObject *
p_next_message(PyObject *self)
{
	struct p_buffer *pb = ((struct p_buffer *) self);
	struct p_place p;
	PyObject *rob;

	p.offset = pb->position.offset;
	p.list = pb->position.list;

	rob = p_build_tuple(&p);
	if (rob == NULL)
	{
		if (!PyErr_Occurred())
		{
			rob = Py_None;
			Py_INCREF(rob);
		}
	}
	else
	{
		pl_truncate(pb->position.list, p.list);
		pb->position.list = p.list;
		pb->position.offset = p.offset;
		if (p.list == NULL)
			pb->last = NULL;
	}

	return(rob);
}

/*
 * p_getvalue - get the unconsumed data in the buffer
 *
 * Normally used in conjunction with truncate to transfer
 * control of the wire to another state machine.
 */
static PyObject *
p_getvalue(PyObject *self)
{
	struct p_buffer *pb = ((struct p_buffer *) self);
	struct p_list *l;
	uint32_t initial_offset;
	PyObject *rob;

	/*
	 * Don't include data from already read() messages.
	 */
	initial_offset = pb->position.offset;

	l = pb->position.list;
	if (l == NULL)
	{
		/*
		 * Empty list.
		 */
		return(PyBytes_FromString(""));
	}

	/*
	 * Get the first chunk.
	 */
	rob = PyBytes_FromStringAndSize(
		(PyBytes_AS_STRING(l->data) + initial_offset),
		PyBytes_GET_SIZE(l->data) - initial_offset
	);
	if (rob == NULL)
		return(NULL);

	l = l->next;
	while (l != NULL)
	{
		PyBytes_Concat(&rob, l->data);
		if (rob == NULL)
			break;

		l = l->next;
	}

	return(rob);
}

static PyMethodDef p_methods[] = {
	{"write", p_write, METH_O,
		PyDoc_STR("write the string to the buffer"),},
	{"read", p_read, METH_VARARGS,
		PyDoc_STR("read the number of messages from the buffer")},
	{"truncate", (PyCFunction) p_truncate, METH_NOARGS,
		PyDoc_STR("remove the contents of the buffer"),},
	{"has_message", (PyCFunction) p_has_message, METH_NOARGS,
		PyDoc_STR("whether the buffer has a message ready"),},
	{"next_message", (PyCFunction) p_next_message, METH_NOARGS,
		PyDoc_STR("get and remove the next message--None if none."),},
	{"getvalue", (PyCFunction) p_getvalue, METH_NOARGS,
		PyDoc_STR("get the unprocessed data in the buffer")},
	{NULL}
};

PyTypeObject pq_message_stream_Type = {
	PyVarObject_HEAD_INIT(NULL, 0)
	"postgresql.port.optimized.pq_message_stream",	/* tp_name */
	sizeof(struct p_buffer),		/* tp_basicsize */
	0,										/* tp_itemsize */
	p_dealloc,							/* tp_dealloc */
	NULL,									/* tp_print */
	NULL,									/* tp_getattr */
	NULL,									/* tp_setattr */
	NULL,									/* tp_compare */
	NULL,									/* tp_repr */
	NULL,									/* tp_as_number */
	&pq_ms_as_sequence,				/* tp_as_sequence */
	NULL,									/* tp_as_mapping */
	NULL,									/* tp_hash */
	NULL,									/* tp_call */
	NULL,									/* tp_str */
	NULL,									/* tp_getattro */
	NULL,									/* tp_setattro */
	NULL,									/* tp_as_buffer */
	Py_TPFLAGS_DEFAULT,			   /* tp_flags */
	PyDoc_STR(
		"Buffer data on write, return messages on read"
	),										/* tp_doc */
	NULL,									/* tp_traverse */
	NULL,									/* tp_clear */
	NULL,									/* tp_richcompare */
	0,										/* tp_weaklistoffset */
	NULL,									/* tp_iter */
	p_next,								/* tp_iternext */
	p_methods,							/* tp_methods */
	NULL,									/* tp_members */
	NULL,									/* tp_getset */
	NULL,									/* tp_base */
	NULL,									/* tp_dict */
	NULL,									/* tp_descr_get */
	NULL,									/* tp_descr_set */
	0,										/* tp_dictoffset */
	NULL,									/* tp_init */
	NULL,									/* tp_alloc */
	p_new,								/* tp_new */
	NULL,									/* tp_free */
};
/*
 * vim: ts=3:sw=3:noet:
 */