linktree Atrinik.org - Multiplayer Online Role Playing Game  >  Atrinik News  >  Developers' Corner
linktree Topic: Cache API
Pages: [1]   Go Down
  Print  
Author Topic: Cache API  (Read 2652 times)
0 Members and 1 Guest are viewing this topic. Bookmarked by 0 members.
Offline Cleo
Developer
Alex Tokar

Posts: 580
Gender: Male
« on: August 20, 2010, 03:13:00 pm »

Just a note to server devs/scripters:

r1673 implements a new generic cache API. This API can store an infinite number of pointers to memory locations, identified by unique key names (strings like 'test_cache', 'guild_db', etc). Such API is, naturally, not very useful for most server code (since it's trivial to create pointers to memory areas -- either static or global), but it's very useful for plugins, specifically the Python plugin.

This new revision includes Python wrappers to the API, so Python scripts can store any Python object in memory for later retrieval. There are very few cases where something like this is useful, but it can save a lot of CPU time. For example, r1675 optimizes the Guild class using this very functionality: instead of opening/closing the guild database file and the log file, it stores them in the memory using CacheAdd() function:

Code: [Select]
		# Try to get the db from the cache.
try:
self._db = CacheGet("guild_db")
# Not in cache.
except:
import shelve
## Initialize guild database from the database file.
self._db = shelve.open(_guilddb_file, writeback = True)
# Add it to the cache.
CacheAdd("guild_db", self._db)


and for the log:

Code: [Select]
	def log_add(self, s):
from datetime import datetime

# Try to get the file pointer from the cache.
try:
fp = CacheGet("guild_fp_append")
# Not in cache, make a new one.
except:
fp = open(_data_dir + "/" + self._guild + ".log", "a")
CacheAdd("guild_fp_append", fp)

fp.write("[" + datetime.now().strftime("%d-%m-%Y %H:%M:%S") + "] " + s + "\n")


Cached entries are only removed on server shutdown or when CacheRemove() is called.

Another functionality of the API is that when cached Python objects are removed (either by a shutdown or by CacheRemove()), if the removed object has a close() method, it will be called with no arguments. This means objects like opened files and shelve databases, among others. It is ensured that this is always done -- even if the server is terminating due to a SIGSEGV or SIGTERM (although it probably won't catch a SIGNUKE ;)).


The API uses a dynamically expanding (and shrinking, in case of removed entries) array, shared strings for the keys a binary search for finding the cached entries, so it's quite fast even with many entries.
 Logged
Pages: [1]   Go Up
  Print  
 
Jump to: