3 #include "mod_magnet_cache.h"
4 #include "stat_cache.h"
14 static script
*script_init() {
17 sc
= calloc(1, sizeof(*sc
));
18 sc
->name
= buffer_init();
19 sc
->etag
= buffer_init();
24 static void script_free(script
*sc
) {
27 lua_pop(sc
->L
, 1); /* the function copy */
29 buffer_free(sc
->name
);
30 buffer_free(sc
->etag
);
37 script_cache
*script_cache_init() {
40 p
= calloc(1, sizeof(*p
));
45 void script_cache_free(script_cache
*p
) {
50 for (i
= 0; i
< p
->used
; i
++) {
51 script_free(p
->ptr
[i
]);
59 lua_State
*script_cache_get_script(server
*srv
, connection
*con
, script_cache
*cache
, buffer
*name
) {
62 stat_cache_entry
*sce
;
64 for (i
= 0; i
< cache
->used
; i
++) {
67 if (buffer_is_equal(name
, sc
->name
)) {
68 sc
->last_used
= time(NULL
);
70 /* oops, the script failed last time */
72 if (lua_gettop(sc
->L
) == 0) break;
73 force_assert(lua_gettop(sc
->L
) == 1);
75 if (HANDLER_ERROR
== stat_cache_get_entry(srv
, con
, sc
->name
, &sce
)) {
76 lua_pop(sc
->L
, 1); /* pop the old function */
80 if (!buffer_is_equal(sce
->etag
, sc
->etag
)) {
81 /* the etag is outdated, reload the function */
86 force_assert(lua_isfunction(sc
->L
, -1));
94 /* if the script was script already loaded but either got changed or
95 * failed to load last time */
99 if (cache
->size
== 0) {
101 cache
->ptr
= malloc(cache
->size
* sizeof(*(cache
->ptr
)));
102 } else if (cache
->used
== cache
->size
) {
104 cache
->ptr
= realloc(cache
->ptr
, cache
->size
* sizeof(*(cache
->ptr
)));
107 cache
->ptr
[cache
->used
++] = sc
;
109 buffer_copy_buffer(sc
->name
, name
);
111 sc
->L
= luaL_newstate();
112 luaL_openlibs(sc
->L
);
115 sc
->last_used
= time(NULL
);
117 if (0 != luaL_loadfile(sc
->L
, name
->ptr
)) {
118 /* oops, an error, return it */
122 if (HANDLER_GO_ON
== stat_cache_get_entry(srv
, con
, sc
->name
, &sce
)) {
123 buffer_copy_buffer(sc
->etag
, sce
->etag
);
126 force_assert(lua_isfunction(sc
->L
, -1));