cPickleCache.c 25.3 KB
Newer Older
1
/*****************************************************************************
matt@zope.com's avatar
matt@zope.com committed
2

Guido van Rossum's avatar
Guido van Rossum committed
3 4
  Copyright (c) 2001, 2002 Zope Corporation and Contributors.
  All Rights Reserved.
5

matt@zope.com's avatar
matt@zope.com committed
6 7 8 9 10 11
  This software is subject to the provisions of the Zope Public License,
  Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
  THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
  WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
  FOR A PARTICULAR PURPOSE
12

13
 ****************************************************************************/
14 15

static char cPickleCache_doc_string[] =
Jeremy Hylton's avatar
Jeremy Hylton committed
16 17
"Defines the PickleCache used by ZODB Connection objects.\n"
"\n"
18
"$Id: cPickleCache.c,v 1.45 2002/04/02 06:03:39 jeremy Exp $\n";
Jim Fulton's avatar
Jim Fulton committed
19

20 21 22 23
#define ASSIGN(V,E) {PyObject *__e; __e=(E); Py_XDECREF(V); (V)=__e;}
#define UNLESS(E) if(!(E))
#define UNLESS_ASSIGN(V,E) ASSIGN(V,E) UNLESS(V)
#define OBJECT(O) ((PyObject*)O)
24

25
#define DONT_USE_CPERSISTENCECAPI
26
#include "cPersistence.h"
Jim Fulton's avatar
Jim Fulton committed
27
#include <time.h>
28
#include <stddef.h>
29 30
#undef Py_FindMethod

31
static PyObject *py__p_oid, *py_reload, *py__p_jar, *py__p_changed;
Jim Fulton's avatar
Jim Fulton committed
32

33
/* define this for extra debugging checks, and lousy performance */
34 35 36
/* Are any of these checks necessary in production code?  How do we
   decide when to disable it?
*/
37
#define MUCH_RING_CHECKING 1
38

39 40 41 42 43 44 45
/* Do we want 'engine noise'.... abstract debugging output useful for
   visualizing cache behavior */
#if 0
#define ENGINE_NOISE(A) printf(A)
#else
#define ENGINE_NOISE(A) ((void)A)
#endif
46

47 48
/* the layout of this struct is the same as the start of ccobject_head in cPersistence.c */
typedef struct {
49 50 51 52 53 54 55 56
    CACHE_HEAD
    int klass_count;
    PyObject *data;
    PyObject *jar;
    PyObject *setklassstate;
    int cache_size;
    int ring_lock;
    int cache_drain_resistance;
57
} ccobject;
58

Jeremy Hylton's avatar
Jeremy Hylton committed
59 60 61
static int present_in_ring(ccobject *self, CPersistentRing *target);
static int check_ring(ccobject *self, const char *context);
static int cc_ass_sub(ccobject *self, PyObject *key, PyObject *v);
62

Jim Fulton's avatar
Jim Fulton committed
63 64
/* ---------------------------------------------------------------- */

Jeremy Hylton's avatar
Jeremy Hylton committed
65
static PyObject *object_from_oid(ccobject *self, PyObject *key)
66 67
/* somewhat of a replacement for PyDict_GetItem(self->data....
   however this returns a *new* reference */
68
{
69 70
    PyObject *v = PyDict_GetItem(self->data, key);
    if(!v) return NULL;
Jim Fulton's avatar
alpha1  
Jim Fulton committed
71

72 73 74
    Py_INCREF(v);

    return v;
75
}
Jim Fulton's avatar
Jim Fulton committed
76

77 78
static cPersistentObject *
object_from_ring(ccobject *self, CPersistentRing *here, const char *context)
79
{
80 81 82 83 84 85
    /* Given a position in the LRU ring, return a borrowed
    reference to the object at that point in the ring. The caller is
    responsible for ensuring that this ring position really does
    correspond to a persistent object, although the debugging
    version will double-check this. */

86 87 88
    PyObject *object;

    object = (PyObject *)(((char *)here) - offsetof(cPersistentObject, ring));
89 90

#ifdef MUCH_RING_CHECKING
91 92 93 94
    if (!PyExtensionInstance_Check(object)) {
        PyErr_Format(PyExc_RuntimeError,
	     "Unexpectedly encountered non-ExtensionClass object in %s",
		     context);
95 96
        return NULL;
    }
97 98 99
    if (!(((PyExtensionClass*)(object->ob_type))->class_flags & PERSISTENT_TYPE_FLAG)) {
        PyErr_Format(PyExc_RuntimeError,
	     "Unexpectedly encountered non-persistent object in %s", context);
100 101
        return NULL;
    }
102 103 104 105
    if (((cPersistentObject*)object)->jar != self->jar) {
        PyErr_Format(PyExc_RuntimeError,
	     "Unexpectedly encountered object from a different jar in %s",
		     context);
106 107
        return NULL;
    }
108 109 110
    if (((cPersistentObject *)object)->cache != (PerCache *)self) {
        PyErr_Format(PyExc_RuntimeError,
		     "Unexpectedly encountered broken ring in %s", context);
111 112 113 114
        return NULL;
    }
#endif
    return (cPersistentObject *)object;
115
}
116

117
static int
118
scan_gc_items(ccobject *self,int target)
119
{
120 121 122 123 124 125 126
    cPersistentObject *object;
    int error;
    CPersistentRing placeholder;
    CPersistentRing *here = self->ring_home.next;

#ifdef MUCH_RING_CHECKING
    int safety_counter = self->cache_size*10;
127 128
    if (safety_counter<10000) 
	safety_counter = 10000;
129 130
#endif

131 132 133
    while (1) {
        if (check_ring(self, "mid-gc")) 
	    return -1;
134 135

#ifdef MUCH_RING_CHECKING
136
        if (!safety_counter--) {
137 138 139 140 141 142 143
            /* This loop has been running for a very long time.
               It is possible that someone loaded a very large number of objects,
               and now wants us to blow them all away. However it may
               also indicate a logic error. If the loop has been running this
               long then you really have to doubt it will ever terminate.
               In the MUCH_RING_CHECKING build we prefer to raise an exception
               here */
144 145
            PyErr_SetString(PyExc_RuntimeError,
			    "scan_gc_items safety counter exceeded");
146 147 148
            return -1;
        }

149 150 151 152 153
        if (!present_in_ring(self, here)) {
            /* Our current working position is no longer in the ring. 
	       That's bad. */ 
            PyErr_SetString(PyExc_RuntimeError,
		    "working position fell out the ring, in scan_gc_items");
154 155 156 157
            return -1;
        }
#endif

158 159
	/* back to the home position. stop looking */
        if (here == &self->ring_home)
160 161 162 163 164
            return 0;

        /* At this point we know that the ring only contains nodes from
        persistent objects, plus our own home node. We can safely
        assume this is a persistent object now we know it is not the home */
165 166 167
        object = object_from_ring(self, here, "scan_gc_items");
        if (!object) 
	    return -1;
168

169 170
	/* we are small enough */
        if (self->non_ghost_count <= target)
171
            return 0;
172
        else if (object->state == cPersistent_UPTODATE_STATE) {
173 174 175 176 177 178 179 180
            /* deactivate it. This is the main memory saver. */

            ENGINE_NOISE("G");

            /* add a placeholder */
            placeholder.next = here->next;
            placeholder.prev = here;
            here->next->prev = &placeholder;
181
            here->next = &placeholder;
182

183 184
            error = PyObject_SetAttr((PyObject *)object, py__p_changed, 
				     Py_None);
185 186

            /* unlink the placeholder */
187 188
            placeholder.next->prev = placeholder.prev;
            placeholder.prev->next = placeholder.next;
189 190 191 192 193

            here = placeholder.next;

            if(error)
                return -1; /* problem */
194
        } else {
195 196 197 198
            ENGINE_NOISE(".");
            here = here->next;
        }
    }
199
}
200

201
static PyObject *
202
lockgc(ccobject *self, int target_size)
203
{
204
    if (self->ring_lock) {
205 206 207
        Py_INCREF(Py_None);
        return Py_None;
    }
208

209 210
    if (check_ring(self, "pre-gc")) 
	return NULL;
211 212
    ENGINE_NOISE("<");
    self->ring_lock = 1;
213
    if (scan_gc_items(self, target_size)) {
214 215 216 217 218
        self->ring_lock = 0;
        return NULL;
    }
    self->ring_lock = 0;
    ENGINE_NOISE(">\n");
219 220
    if (check_ring(self, "post-gc")) 
	return NULL;
221 222 223

    Py_INCREF(Py_None);
    return Py_None;
224 225
}

226 227
static PyObject *
cc_incrgc(ccobject *self, PyObject *args)
Jim Fulton's avatar
Jim Fulton committed
228
{
229
    int n = 1;
230 231
    int starting_size = self->non_ghost_count;
    int target_size = self->cache_size;
Jim Fulton's avatar
Jim Fulton committed
232

233
    if (self->cache_drain_resistance >= 1) {
234 235
        /* This cache will gradually drain down to a small size. Check
           a (small) number of objects proportional to the current size */
236

237 238 239
        int target_size_2 = (starting_size - 1 
			     - starting_size / self->cache_drain_resistance);
        if (target_size_2 < target_size)
240
            target_size = target_size_2;
241
    }
Jim Fulton's avatar
Jim Fulton committed
242

243 244
    if (!PyArg_ParseTuple(args, "|i:incrgc", &n)) 
	return NULL;
245

246
    return lockgc(self,target_size);
Jim Fulton's avatar
Jim Fulton committed
247 248 249
}

static PyObject *
250
cc_full_sweep(ccobject *self, PyObject *args)
Jim Fulton's avatar
Jim Fulton committed
251
{
252 253 254 255
    int dt = 0;
    if (!PyArg_ParseTuple(args, "|i:full_sweep", &dt)) 
	return NULL;
    return lockgc(self,0);
Jim Fulton's avatar
Jim Fulton committed
256 257
}

Jim Fulton's avatar
Jim Fulton committed
258 259 260
static PyObject *
cc_reallyfull_sweep(ccobject *self, PyObject *args)
{
261 262 263
  int dt = 0;
  if (!PyArg_ParseTuple(args, "|i:reallyfull_sweep", &dt)) 
      return NULL;
264
  return lockgc(self,0);
Jim Fulton's avatar
Jim Fulton committed
265 266
}

267 268
static void
_invalidate(ccobject *self, PyObject *key)
269
{
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    PyObject *v = object_from_oid(self, key);

    if (!v)
	return;
    if (PyExtensionClass_Check(v)) {
	if (v->ob_refcnt <= 1) {
	    self->klass_count--;
	    if (PyDict_DelItem(self->data, key) < 0)
		PyErr_Clear();
	}
	else {
	    v = PyObject_CallFunction(self->setklassstate, "O", v);
	    if (v) 
		Py_DECREF(v);
	    else 
		PyErr_Clear();
	}
    } else {
	if (PyObject_DelAttr(v, py__p_changed) < 0)
	    PyErr_Clear();
290
    }
291
    Py_DECREF(v);
292
}
293

294 295 296 297 298
static PyObject *
cc_invalidate(ccobject *self, PyObject *args)
{
  PyObject *inv, *key, *v;
  int i;
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
  if (PyArg_ParseTuple(args, "O!", &PyDict_Type, &inv)) {
    for (i=0; PyDict_Next(inv, &i, &key, &v); ) 
      if (key==Py_None)
	{ /* Eek some nitwit invalidated everything! */
	  for (i=0; PyDict_Next(self->data, &i, &key, &v); )
	    _invalidate(self, key);
	  break;
	}
      else
	_invalidate(self, key);
    PyDict_Clear(inv);
  }
  else {
    PyErr_Clear();
    UNLESS (PyArg_ParseTuple(args, "O", &inv)) return NULL;
    if (PyString_Check(inv))
      _invalidate(self, inv);
    else if (inv==Py_None)	/* All */
      for (i=0; PyDict_Next(self->data, &i, &key, &v); )
	_invalidate(self, key);
    else {
      int l;

      PyErr_Clear();
      if ((l=PyObject_Length(inv)) < 0) return NULL;
      for(i=l; --i >= 0; )
	{
	  UNLESS (key=PySequence_GetItem(inv, i)) return NULL;
	  _invalidate(self, key);
	  Py_DECREF(key);
	}
      PySequence_DelSlice(inv, 0, l);
    }
  }

335 336 337
  Py_INCREF(Py_None);
  return Py_None;
}
338 339 340 341
  
  
static PyObject *
cc_get(ccobject *self, PyObject *args)
342
{
343
  PyObject *r, *key, *d=0;
344

345 346 347 348 349 350 351 352 353 354 355 356 357 358
  UNLESS (PyArg_ParseTuple(args,"O|O", &key, &d)) return NULL;

  UNLESS (r=(PyObject *)object_from_oid(self, key))
    {
      if (d) 
	{
	  PyErr_Clear();
	  r=d;
          Py_INCREF(r);
	}
      else
	{
	  PyErr_SetObject(PyExc_KeyError, key);
	  return NULL;
359
	}
360 361 362
    }

  return r;
363 364
}

365 366
static PyObject *
cc_klass_items(ccobject *self, PyObject *args)
367
{
368 369 370
    PyObject *l,*k,*v;
    int p = 0;

371 372
    if (!PyArg_ParseTuple(args, ":klass_items")) 
	return NULL;
373

374 375 376
    l = PyList_New(PyDict_Size(self->data));
    if (l == NULL) 
	return NULL;
377

378 379 380 381 382 383 384 385 386 387 388 389 390
    while (PyDict_Next(self->data, &p, &k, &v)) {
        if(PyExtensionClass_Check(v)) {
	    v = Py_BuildValue("OO", k, v);
	    if (v == NULL) {
		Py_DECREF(l);
		return NULL;
	    }
	    if (PyList_Append(l, v) < 0) {
		Py_DECREF(v);
		Py_DECREF(l);
		return NULL;
	    }
	    Py_DECREF(v);
391 392
        }
    }
393

394
    return l;
395 396 397
}

static PyObject *
398
cc_lru_items(ccobject *self, PyObject *args)
399
{
400 401
    PyObject *l;
    CPersistentRing *here;
402

403 404
    if (!PyArg_ParseTuple(args, ":lru_items")) 
	return NULL;
405

406 407 408
    if (self->ring_lock) {
        PyErr_SetString(PyExc_ValueError,
		".lru_items() is unavailable during garbage collection");
409
        return NULL;
410
    }
411

412 413
    if (check_ring(self, "pre-cc_items")) 
	return NULL;
414 415

    l = PyList_New(0);
416 417
    if (l == NULL) 
	return NULL;
418 419

    here = self->ring_home.next;
420
    while (here != &self->ring_home) {
421
        PyObject *v;
422 423 424
        cPersistentObject *object = object_from_ring(self, here, "cc_items");

        if (object == NULL) {
425 426 427
            Py_DECREF(l);
            return NULL;
        }
428 429
	v = Py_BuildValue("OO", object->oid, object);
	if (v == NULL) {
430 431
            Py_DECREF(l);
            return NULL;
432 433 434 435 436 437
	}
	if (PyList_Append(l, v) < 0) {
	    Py_DECREF(v);
            Py_DECREF(l);
            return NULL;
	}
438 439 440 441 442
        Py_DECREF(v);
        here = here->next;
    }

    return l;
443
}
444

445 446
/* XXX What does this function do? */

Jim Fulton's avatar
Jim Fulton committed
447
static PyObject *
448
cc_oid_unreferenced(ccobject *self, PyObject *args)
Jim Fulton's avatar
Jim Fulton committed
449
{
450 451 452
    PyObject *oid, *v;
    if (!PyArg_ParseTuple(args, "O:_oid_unreferenced", &oid)) 
	return NULL;
Jim Fulton's avatar
Jim Fulton committed
453

454
    v = PyDict_GetItem(self->data, oid);
455 456 457 458 459 460 461
    if (v == NULL) {
	PyErr_SetObject(PyExc_KeyError, oid);
	/* jeremy debug
	   fprintf(stderr, "oid_unreferenced: key error\n");
	*/
	return NULL;
    }
462

463 464 465 466 467 468 469 470
    /* jeremy debug
    fprintf(stderr, "oid_unreferenced: %X %d %s\n", v,
	    v->ob_refcnt, v->ob_type->tp_name);
    */

    if (v->ob_refcnt) {
        PyErr_Format(PyExc_ValueError,
	     "object has reference count of %d, should be zero", v->ob_refcnt);
471
        return NULL;
Jim Fulton's avatar
Jim Fulton committed
472 473
    }

474
    /* Need to be very hairy here because a dictionary is about
475 476
       to decref an already deleted object. 
    */
477 478 479 480 481 482 483 484 485

#ifdef Py_TRACE_REFS
#error "this code path has not been tested - Toby Dickenson"
    _Py_NewReference(v);
    /* it may be a problem that v->ob_type is still NULL? */
#else
    Py_INCREF(v);
#endif

486 487 488
    if (v->ob_refcnt != 1) {
        PyErr_SetString(PyExc_ValueError,
			"refcount is not 1 after resurrection");
489 490 491 492 493 494 495 496
        return NULL;
    }

    /* return the stolen reference */
    Py_INCREF(v);

    PyDict_DelItem(self->data, oid);

497 498 499
    if (v->ob_refcnt != 1) {
        PyErr_SetString(PyExc_ValueError,
			"refcount is not 1 after removal from dict");
500 501 502 503 504 505 506 507 508 509 510 511
        return NULL;
    }

    /* undo the temporary resurrection */
#ifdef Py_TRACE_REFS
    _Py_ForgetReference(v);
#else
    v->ob_refcnt=0;
#endif

    Py_INCREF(Py_None);
    return Py_None;
Jim Fulton's avatar
Jim Fulton committed
512 513
}

514

Jim Fulton's avatar
Jim Fulton committed
515
static struct PyMethodDef cc_methods[] = {
516 517 518 519 520 521 522 523 524
  {"_oid_unreferenced", (PyCFunction)cc_oid_unreferenced, METH_VARARGS,
   NULL
   },
  {"lru_items", (PyCFunction)cc_lru_items, METH_VARARGS,
   "List (oid, object) pairs from the lru list, as 2-tuples.\n"
   },
  {"klass_items", (PyCFunction)cc_klass_items, METH_VARARGS,
   "List (oid, object) pairs of cached persistent classes.\n"
   },
Jim Fulton's avatar
alpha1  
Jim Fulton committed
525
  {"full_sweep", (PyCFunction)cc_full_sweep, METH_VARARGS,
526 527
   "full_sweep([age]) -- Perform a full sweep of the cache\n\n"
   "Make a single pass through the cache, removing any objects that are no\n"
528 529 530
   "longer referenced, and deactivating enough objects to bring\n"
   "the cache under its size limit\n"
   "The optional 'age' parameter is ignored.\n"
531
   },
Jim Fulton's avatar
alpha1  
Jim Fulton committed
532
  {"minimize",	(PyCFunction)cc_reallyfull_sweep, METH_VARARGS,
533 534
   "minimize([age]) -- Remove as many objects as possible\n\n"
   "Make multiple passes through the cache, removing any objects that are no\n"
535 536 537
   "longer referenced, and deactivating enough objects to bring the"
   " cache under its size limit\n"
   "The option 'age' parameter is ignored.\n"
538
   },
Jim Fulton's avatar
alpha1  
Jim Fulton committed
539
  {"incrgc", (PyCFunction)cc_incrgc, METH_VARARGS,
540 541 542
   "incrgc([n]) -- Perform incremental garbage collection\n\n"
   "Some other implementations support an optional parameter 'n' which\n"
   "indicates a repetition count; this value is ignored.\n"},
543 544
  {"invalidate", (PyCFunction)cc_invalidate, METH_VARARGS,
   "invalidate(oids) -- invalidate one, many, or all ids"},
Jim Fulton's avatar
Jim Fulton committed
545 546
  {"get", (PyCFunction)cc_get, METH_VARARGS,
   "get(key [, default]) -- get an item, or a default"},
Jim Fulton's avatar
Jim Fulton committed
547 548 549 550
  {NULL,		NULL}		/* sentinel */
};

static void
551
cc_dealloc(ccobject *self)
Jim Fulton's avatar
Jim Fulton committed
552
{
553 554 555 556
  Py_XDECREF(self->data);
  Py_XDECREF(self->jar);
  Py_XDECREF(self->setklassstate);
  PyMem_DEL(self);
Jim Fulton's avatar
Jim Fulton committed
557 558 559
}

static PyObject *
560
cc_getattr(ccobject *self, char *name)
Jim Fulton's avatar
Jim Fulton committed
561
{
562 563
  PyObject *r;

564 565
  if (check_ring(self, "getattr")) 
      return NULL;
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582

  if(*name=='c')
    {
      if(strcmp(name,"cache_age")==0)
	return PyInt_FromLong(0);   /* this cache does not use this value */
      if(strcmp(name,"cache_size")==0)
	return PyInt_FromLong(self->cache_size);
      if(strcmp(name,"cache_drain_resistance")==0)
	return PyInt_FromLong(self->cache_drain_resistance);
      if(strcmp(name,"cache_non_ghost_count")==0)
	return PyInt_FromLong(self->non_ghost_count);
      if(strcmp(name,"cache_klass_count")==0)
	return PyInt_FromLong(self->klass_count);
      if(strcmp(name,"cache_data")==0)
	{
	  /* now a copy of our data; the ring is too fragile */
	  return PyDict_Copy(self->data);
583
	}
584
    }
585 586 587 588 589 590 591
  if((*name=='h' && strcmp(name, "has_key")==0) ||
     (*name=='i' && strcmp(name, "items")==0) ||
     (*name=='k' && strcmp(name, "keys")==0)
     )
    return PyObject_GetAttrString(self->data, name);

  if((r=Py_FindMethod(cc_methods, (PyObject *)self, name)))
Jim Fulton's avatar
Jim Fulton committed
592
    return r;
593 594
  PyErr_Clear();
  return PyObject_GetAttrString(self->data, name);
Jim Fulton's avatar
Jim Fulton committed
595 596
}

Jim Fulton's avatar
Jim Fulton committed
597 598 599
static int
cc_setattr(ccobject *self, char *name, PyObject *value)
{
600 601
  if(value)
    {
Jim Fulton's avatar
Jim Fulton committed
602 603
      int v;

604 605 606
      if(strcmp(name,"cache_age")==0)
	{
	  /* this cache doesnt use the age */
607
	  return 0;
608
	}
Jim Fulton's avatar
Jim Fulton committed
609

610 611 612 613
      if(strcmp(name,"cache_size")==0)
	{
	  UNLESS(PyArg_Parse(value,"i",&v)) return -1;
	  self->cache_size=v;
614
	  return 0;
615 616 617 618 619 620 621 622 623
	}

      if(strcmp(name,"cache_drain_resistance")==0)
	{
	  UNLESS(PyArg_Parse(value,"i",&v)) return -1;
	  self->cache_drain_resistance=v;
	  return 0;
	}
    }
Jim Fulton's avatar
Jim Fulton committed
624 625 626 627
  PyErr_SetString(PyExc_AttributeError, name);
  return -1;
}

Jim Fulton's avatar
Jim Fulton committed
628
static int
629
cc_length(ccobject *self)
Jim Fulton's avatar
Jim Fulton committed
630
{
631
  return PyObject_Length(self->data);
Jim Fulton's avatar
Jim Fulton committed
632 633 634
}
  
static PyObject *
635
cc_subscript(ccobject *self, PyObject *key)
Jim Fulton's avatar
Jim Fulton committed
636 637 638
{
  PyObject *r;

639 640 641 642 643 644
  if(check_ring(self,"__getitem__")) return NULL;

  UNLESS (r=(PyObject *)object_from_oid(self, key))
  {
    PyErr_SetObject(PyExc_KeyError, key);
    return NULL;
Jim Fulton's avatar
Jim Fulton committed
645
  }
Jim Fulton's avatar
alpha1  
Jim Fulton committed
646

Jim Fulton's avatar
Jim Fulton committed
647 648 649 650
  return r;
}

static int
651
cc_add_item(ccobject *self, PyObject *key, PyObject *v)
Jim Fulton's avatar
Jim Fulton committed
652
{
653
    int result;
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
    PyExtensionClass *class;

    if (!PyExtensionInstance_Check(v)) {
	PyErr_SetString(PyExc_ValueError, 
			"Cache values must be persistent objects.");
	return -1;
    }
    /* Is this set of tests necessary? */
    class = (PyExtensionClass *)(v->ob_type);
    if (!((class->class_flags & PERSISTENT_TYPE_FLAG)
	  && v->ob_type->tp_basicsize >= sizeof(cPersistentObject))) {
	PyErr_SetString(PyExc_ValueError, 
			"Cache values must be persistent objects.");
	return -1;
    }

    /* XXX Why not self->oid? */
    PyObject *oid = PyObject_GetAttr(v, py__p_oid);
    PyObject *object_again;
    cPersistentObject *p;

    if (oid == NULL)
	return -1;
    /* XXX key and oid should both be PyString objects */
    if (PyObject_Cmp(key, oid, &result)) {
	Py_DECREF(oid);
	return -1;
    }
    Py_DECREF(oid);
    if (result) {
	PyErr_SetString(PyExc_ValueError,
			"key must be the same as the object's oid attribute");
	return -1;
    }
    object_again = object_from_oid(self, key);
    if (object_again) {
	/* XXX Do we need to check for this? */
	if (object_again != v) {
	    Py_DECREF(object_again);
	    PyErr_SetString(PyExc_ValueError,
			    "Can not re-register object under a different oid");
	    return -1;
	} else {
	    /* re-register under the same oid - no work needed */
	    Py_DECREF(object_again);
	    return 0;
	}
    }
    if (PyExtensionClass_Check(v)) {
	if (PyDict_SetItem(self->data, key, v)) 
	    return -1;
	self->klass_count++;
	return 0;
    } else {
	PerCache *cache = ((cPersistentObject *)v)->cache;
	if (cache) {
	    if (cache != (PerCache *)self)
		/* This object is already in a different cache. */
		PyErr_SetString(PyExc_ValueError, 
713
				"Cache values may only be in one cache.");
714 715 716 717 718 719 720 721
	    return -1;
	} 
	/* else:
	   
	   This object is already one of ours, which is ok.  It
	   would be very strange if someone was trying to register
	   the same object under a different key. 
	*/
722
    }
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
    
    if (check_ring(self, "pre-setitem")) 
	return -1;
    if (PyDict_SetItem(self->data, key, v)) 
	return -1;
    
    Py_INCREF(self);
    p = (cPersistentObject *)v;
    p->cache = (PerCache *)self;
    if (p->state >= 0) {
	/* insert this non-ghost object into the ring just 
	   behind the home position */
	self->non_ghost_count++;
	p->ring.next = &self->ring_home;
	p->ring.prev =  self->ring_home.prev;
	self->ring_home.prev->next = &p->ring;
	self->ring_home.prev = &p->ring;
    } else {
	/* steal a reference from the dictionary; 
	   ghosts have a weak reference */
	Py_DECREF(v);
    }
    
    if (check_ring(self, "post-setitem")) 
	return -1;
748
    else
749 750
	return 0;
}
751

752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
static int
cc_del_item(ccobject *self, PyObject *key)
{
    PyObject *v;
    cPersistentObject *p;

    /* unlink this item from the ring */
    if (check_ring(self, "pre-delitem")) 
	return -1;

    v = (PyObject *)object_from_oid(self, key);
    if (v == NULL)
	return -1;

    if (PyExtensionClass_Check(v)) {
	self->klass_count--;
    } else {
	p = (cPersistentObject *)v;
	if (p->state >= 0) {
	    self->non_ghost_count--;
	    p->ring.next->prev = p->ring.prev;
	    p->ring.prev->next = p->ring.next;
	    p->ring.prev = NULL;
	    p->ring.next = NULL;
	} else {
	    /* This is a ghost object, so we havent kept a reference
	       count on it.  For it have stayed alive this long
	       someone else must be keeping a reference to
	       it. Therefore we need to temporarily give it back a
	       reference count before calling DelItem below */
	    Py_INCREF(v);
	}
784

785 786 787
	Py_DECREF((PyObject *)p->cache);
	p->cache = NULL;
    }
788

789
    Py_DECREF(v);
790

791 792 793 794 795
    if (PyDict_DelItem(self->data, key) < 0) {
	PyErr_SetString(PyExc_RuntimeError,
			"unexpectedly couldnt remove key in cc_ass_sub");
	return -1;
    }
796

797 798
    if (check_ring(self, "post-delitem")) 
	return -1;
799

800
    return 0;
Jim Fulton's avatar
Jim Fulton committed
801 802
}

803 804
static int
cc_ass_sub(ccobject *self, PyObject *key, PyObject *v)
805
{
806 807 808 809 810
    if (v)
	return cc_add_item(self, key, v);
    else
	return cc_del_item(self, key);
}
811

812 813 814
static int 
_check_ring(ccobject *self,const char *context)
{
815 816 817
    CPersistentRing *here = &(self->ring_home);
    int expected = 1+self->non_ghost_count;
    int total = 0;
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
    do {
        if (++total > (expected + 10)) 
	    return 3;            /* ring too big, by a large margin */
        if (!here->next)
	    return 4;                      /* various linking problems */
        if (!here->prev) 
	    return 5;
        if (!here->next->prev) 
	    return 7;
        if (!here->prev->next) 
	    return 8;
        if (here->prev->next != here) 
	    return 9;
        if (here->next->prev != here) 
	    return 10;
        if (!self->ring_lock)
834 835
        {
            /* if the ring must be locked then it only contains object other than persistent instances */
836
            if (here!=&self->ring_home)
837 838
            {
                cPersistentObject *object = object_from_ring(self,here,context);
839 840
                if (!object) return 12;
                if (object->state==cPersistent_GHOST_STATE)
841 842 843 844 845 846 847
                    return 13;
            }
        }
        here = here->next;
    }
    while(here!=&self->ring_home);

848
    if (self->ring_lock)
849
    {
850
        if (total<expected) return 6;       /* ring too small; too big is ok when locked */
851 852 853
    }
    else
    {
854
        if (total!=expected) return 14;     /* ring size wrong, or bad ghost accounting */
855 856 857 858 859 860
    }


    return 0;
}

861 862 863 864 865 866 867 868 869
/* XXX This function returns false if everything is okay, which is
   backwards given its name.  All the tests say:

   if (check_ring(...))
       return error
*/

static int 
check_ring(ccobject *self, const char *context)
870 871
{
#ifdef MUCH_RING_CHECKING
872 873 874 875 876
    int code = _check_ring(self,context);
    if (code) {
        PyErr_Format(PyExc_RuntimeError,
		     "broken ring (code %d) in %s, size %d",
		     code, context, PyDict_Size(self->data));
877 878 879 880 881 882 883 884 885 886 887 888
        return code;
    }
#endif
    return 0;
}

static int
present_in_ring(ccobject *self,CPersistentRing *target)
{
    CPersistentRing *here = self->ring_home.next;
    while(1)
    {
889
        if (here==target)
890 891 892
        {
            return 1;
        }
893
        if (here==&self->ring_home)
894 895 896 897 898 899 900 901 902
        {
            /* back to the home position, and we didnt find it */
            return 0;
        }
        here = here->next;
    }
}


Jim Fulton's avatar
Jim Fulton committed
903 904 905 906 907 908 909
static PyMappingMethods cc_as_mapping = {
  (inquiry)cc_length,		/*mp_length*/
  (binaryfunc)cc_subscript,	/*mp_subscript*/
  (objobjargproc)cc_ass_sub,	/*mp_ass_subscript*/
};

static PyTypeObject Cctype = {
910
  PyObject_HEAD_INIT(NULL)
Jim Fulton's avatar
Jim Fulton committed
911 912 913 914 915 916 917 918
  0,				/*ob_size*/
  "cPickleCache",		/*tp_name*/
  sizeof(ccobject),		/*tp_basicsize*/
  0,				/*tp_itemsize*/
  /* methods */
  (destructor)cc_dealloc,	/*tp_dealloc*/
  (printfunc)0,			/*tp_print*/
  (getattrfunc)cc_getattr,	/*tp_getattr*/
Jim Fulton's avatar
Jim Fulton committed
919
  (setattrfunc)cc_setattr,	/*tp_setattr*/
Jim Fulton's avatar
Jim Fulton committed
920
  (cmpfunc)0,			/*tp_compare*/
Jim Fulton's avatar
alpha1  
Jim Fulton committed
921
  (reprfunc)0,   		/*tp_repr*/
Jim Fulton's avatar
Jim Fulton committed
922 923 924 925 926
  0,				/*tp_as_number*/
  0,				/*tp_as_sequence*/
  &cc_as_mapping,		/*tp_as_mapping*/
  (hashfunc)0,			/*tp_hash*/
  (ternaryfunc)0,		/*tp_call*/
Jim Fulton's avatar
alpha1  
Jim Fulton committed
927
  (reprfunc)0,  		/*tp_str*/
928 929 930 931

  /* Space for future expansion */
  0L,0L,0L,0L,
  ""
Jim Fulton's avatar
Jim Fulton committed
932 933
};

Jeremy Hylton's avatar
Jeremy Hylton committed
934 935 936 937 938 939 940
static ccobject *
newccobject(PyObject *jar, int cache_size, int cache_age)
{
  ccobject *self;
  
  UNLESS(self = PyObject_NEW(ccobject, &Cctype)) return NULL;
  self->setklassstate=self->jar=NULL;
941
  if ((self->data=PyDict_New()))
Jeremy Hylton's avatar
Jeremy Hylton committed
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
    {
      self->jar=jar; 
      Py_INCREF(jar);
      UNLESS (self->setklassstate=PyObject_GetAttrString(jar, "setklassstate"))
	return NULL;
      self->cache_size=cache_size;
      self->non_ghost_count=0;
      self->klass_count=0;
      self->cache_drain_resistance=0;
      self->ring_lock=0;
      self->ring_home.next = &self->ring_home;
      self->ring_home.prev = &self->ring_home;
      return self;
    }
  Py_DECREF(self);
  return NULL;
}

Jim Fulton's avatar
Jim Fulton committed
960
static PyObject *
961
cCM_new(PyObject *self, PyObject *args)
Jim Fulton's avatar
Jim Fulton committed
962
{
963
  int cache_size=100, cache_age=1000;
Jim Fulton's avatar
Jim Fulton committed
964 965
  PyObject *jar;

966
  UNLESS(PyArg_ParseTuple(args, "O|ii", &jar, &cache_size, &cache_age))
Jeremy Hylton's avatar
Jeremy Hylton committed
967
      return NULL;
968
  return (PyObject*)newccobject(jar, cache_size,cache_age);
Jim Fulton's avatar
Jim Fulton committed
969 970 971
}

static struct PyMethodDef cCM_methods[] = {
Jim Fulton's avatar
alpha1  
Jim Fulton committed
972
  {"PickleCache",(PyCFunction)cCM_new,	METH_VARARGS, ""},
Jim Fulton's avatar
Jim Fulton committed
973 974 975 976
  {NULL,		NULL}		/* sentinel */
};

void
Jeremy Hylton's avatar
Jeremy Hylton committed
977
initcPickleCache(void)
Jim Fulton's avatar
Jim Fulton committed
978
{
979
  PyObject *m, *d;
980

981
  Cctype.ob_type=&PyType_Type;
982

983
  UNLESS(ExtensionClassImported) return;
Jim Fulton's avatar
Jim Fulton committed
984

Jeremy Hylton's avatar
Jeremy Hylton committed
985 986
  m = Py_InitModule4("cPickleCache", cCM_methods, cPickleCache_doc_string,
		     (PyObject*)NULL, PYTHON_API_VERSION);
Jim Fulton's avatar
Jim Fulton committed
987

988 989 990
  py_reload = PyString_InternFromString("reload");
  py__p_jar = PyString_InternFromString("_p_jar");
  py__p_changed = PyString_InternFromString("_p_changed");
991 992 993 994 995 996 997 998 999 1000 1001
  py__p_oid = PyString_InternFromString("_p_oid");

  d = PyModule_GetDict(m);

  PyDict_SetItemString(d,"cache_variant",PyString_FromString("stiff/c"));

#ifdef MUCH_RING_CHECKING
  PyDict_SetItemString(d,"MUCH_RING_CHECKING",PyInt_FromLong(1));
#else
  PyDict_SetItemString(d,"MUCH_RING_CHECKING",PyInt_FromLong(0));
#endif
Jim Fulton's avatar
Jim Fulton committed
1002
}