3 #include "mod_magnet_cache.h"
4 #include "stat_cache.h"
12 static script
*script_init() {
15 sc
= calloc(1, sizeof(*sc
));
16 sc
->name
= buffer_init();
17 sc
->etag
= buffer_init();
22 static void script_free(script
*sc
) {
25 lua_pop(sc
->L
, 1); /* the function copy */
27 buffer_free(sc
->name
);
28 buffer_free(sc
->etag
);
35 script_cache
*script_cache_init() {
38 p
= calloc(1, sizeof(*p
));
43 void script_cache_free(script_cache
*p
) {
48 for (i
= 0; i
< p
->used
; i
++) {
49 script_free(p
->ptr
[i
]);
57 lua_State
*script_cache_get_script(server
*srv
, connection
*con
, script_cache
*cache
, buffer
*name
) {
60 stat_cache_entry
*sce
;
62 for (i
= 0; i
< cache
->used
; i
++) {
65 if (buffer_is_equal(name
, sc
->name
)) {
66 sc
->last_used
= time(NULL
);
68 /* oops, the script failed last time */
70 if (lua_gettop(sc
->L
) == 0) break;
71 force_assert(lua_gettop(sc
->L
) == 1);
73 if (HANDLER_ERROR
== stat_cache_get_entry(srv
, con
, sc
->name
, &sce
)) {
74 lua_pop(sc
->L
, 1); /* pop the old function */
78 if (!buffer_is_equal(sce
->etag
, sc
->etag
)) {
79 /* the etag is outdated, reload the function */
84 force_assert(lua_isfunction(sc
->L
, -1));
92 /* if the script was script already loaded but either got changed or
93 * failed to load last time */
97 if (cache
->size
== 0) {
99 cache
->ptr
= malloc(cache
->size
* sizeof(*(cache
->ptr
)));
100 } else if (cache
->used
== cache
->size
) {
102 cache
->ptr
= realloc(cache
->ptr
, cache
->size
* sizeof(*(cache
->ptr
)));
105 cache
->ptr
[cache
->used
++] = sc
;
107 buffer_copy_buffer(sc
->name
, name
);
109 sc
->L
= luaL_newstate();
110 luaL_openlibs(sc
->L
);
113 sc
->last_used
= time(NULL
);
115 if (0 != luaL_loadfile(sc
->L
, name
->ptr
)) {
116 /* oops, an error, return it */
120 if (HANDLER_GO_ON
== stat_cache_get_entry(srv
, con
, sc
->name
, &sce
)) {
121 buffer_copy_buffer(sc
->etag
, sce
->etag
);
124 force_assert(lua_isfunction(sc
->L
, -1));