Overview Package Class Source Class tree Glossary
previous class      next class frames      no frames

LibHTTP4.HttpCache


00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042
00043
00044
00045
00046
00047
00048
00049
00050
00051
00052
00053
00054
00055
00056
00057
00058
00059
00060
00061
00062
00063
00064
00065
00066
00067
00068
00069
00070
00071
00072
00073
00074
00075
00076
00077
00078
00079
00080
00081
00082
00083
00084
00085
00086
00087
00088
00089
00090
00091
00092
00093
00094
00095
00096
00097
00098
00099
00100
00101
00102
00103
00104
00105
00106
00107
00108
00109
00110
00111
00112
00113
00114
00115
00116
00117
00118
00119
00120
00121
00122
00123
00124
00125
00126
00127
00128
00129
00130
00131
00132
00133
00134
00135
00136
00137
00138
00139
00140
00141
00142
00143
00144
00145
00146
00147
00148
00149
00150
00151
00152
00153
00154
00155
00156
00157
00158
00159
00160
00161
00162
00163
00164
00165
00166
00167
00168
00169
00170
00171
00172
00173
00174
00175
00176
00177
00178
00179
00180
00181
00182
00183
00184
00185
00186
00187
00188
00189
00190
00191
00192
00193
00194
00195
00196
00197
00198
00199
00200
00201
00202
00203
00204
00205
00206
00207
00208
00209
00210
00211
00212
00213
00214
00215
00216
00217
00218
00219
00220
00221
00222
00223
00224
00225
00226
00227
00228
00229
00230
00231
00232
00233
00234
00235
00236
00237
00238
00239
00240
00241
00242
00243
00244
00245
00246
00247
00248
00249
00250
00251
00252
00253
00254
00255
00256
00257
00258
00259
00260
00261
00262
00263
00264
00265
00266
00267
00268
00269
00270
00271
00272
00273
00274
00275
00276
00277
00278
00279
00280
00281
00282
00283
00284
00285
00286
00287
00288
00289
00290
00291
00292
00293
00294
00295
00296
00297
00298
00299
00300
00301
00302
00303
00304
00305
00306
00307
00308
00309
00310
00311
00312
00313
00314
00315
00316
00317
00318
00319
00320
00321
00322
00323
00324
00325
00326
00327
00328
00329
00330
00331
00332
00333
00334
00335
00336
00337
00338
00339
00340
00341
00342
00343
00344
00345
00346
00347
00348
00349
00350
00351
00352
00353
00354
00355
00356
00357
00358
00359
00360
00361
00362
00363
00364
00365
00366
00367
00368
00369
00370
00371
00372
00373
00374
00375
00376
00377
00378
00379
00380
00381
00382
00383
00384
00385
00386
00387
00388
00389
00390
00391
00392
00393
00394
00395
00396
00397
00398
00399
00400
00401
00402
00403
00404
00405
00406
00407
00408
00409
00410
00411
00412
00413
00414
00415
00416
00417
00418
00419
00420
00421
00422
00423
/*******************************************************************************
    HttpCache                                                                   <br />
    Disk\Memory cache for LibHTTP, it will handle caching of data. To use it
    simply create a HttpCache object and use it's get() request to get updated
    documents. Don't use a HttpSock instance for this.                          <br />
    When using this class it will perform a specially constructed get request
    when it's needed, it will try to satisfy the caching headers returned by the
    server. Ihis class is only usefull if you know the remote server returns
    correct cachable data. By default most dynamic pages (ASP, PHP, Perl, CGI)
    will return non-cachable pages.                                             <br />

                                                                                <br />
    Dcoumentation and Information:
        http://wiki.beyondunreal.com/wiki/LibHTTP                               <br />
                                                                                <br />
    Authors:    Michiel 'El Muerte' Hendriks <elmuerte@drunksnipers.com>  <br />
                                                                                <br />
    Copyright 2005 Michiel "El Muerte" Hendriks                                 <br />
    Released under the Lesser Open Unreal Mod License                           <br />
    http://wiki.beyondunreal.com/wiki/LesserOpenUnrealModLicense                <br />

    <!-- $Id: HttpCache.uc,v 1.9 2005/12/09 08:31:11 elmuerte Exp $ -->
*******************************************************************************/

class HttpCache extends Engine.Info
    config(HttpCache)
    ParseConfig
    dependsOn(HttpUtil);

/**  */
var class<HttpSock> HttpSockClass;
/**  */
var class<HttpCacheObject> HttpCacheObjectClass;

/** maximum cache size (entries?) */
var(Options) globalconfig int iCacheLimit;

/**
   Reasons for a failure
*/
enum ECacheFailError
{
    CF_None,        /* no error, won't be used anyway */
    CF_BadRequest,  /* the get request isn't valid */
    CF_AuthRequired,/* authentication required, you may not use that */
    CF_Timeout,     /* timeout connecting to the server to get initial data */
    CF_ResolveFailed,/* hostname couldn't be resolved */
    CF_Busy,        /* already busy performing a refresh of this request */

    CF_Unknown,     /* something serious happened */
};

/**
    Hints where the data came from
*/
enum EDataOrigin
{
    DO_Unknown,     /* yeah right */
    DO_Cache,       /* straight from the cache */
    DO_Initial,     /* initial retrieval of the data */
    DO_Refresh,     /* refreshed the data in the cache */
};

/** records of the cached entries */
struct CacheInfoRecord
{
    /** the request URL */
    var HttpUtil.xURL URL;
    /** hash used for record info */
    var int Hash;
    /** last datazie */
    var int DataSize;
    /** last update */
    var int LastUpdate;
    /** index in the CacheObjectList, volatile */
    var int colidx;
};

/** cache list, each entry is an URL */
var protected config array<CacheInfoRecord> CacheList;

/** the spawned cache objects */
var protected array<HttpCacheObject> CacheObjectList;

struct CacheRequest
{
    var HttpSock Socket;
    var int idx;
};
/** running requests */
var protected array<CacheRequest> Requests;

////////////////////////////////////////////////////////////////////////////////
//
//   Delegates
//
////////////////////////////////////////////////////////////////////////////////

/**
    Will be called in case of an internal error.
*/
delegate OnError(HttpCache Sender, string ErrorMessage, optional string Param1, optional string Param2);

/**
    Will be called when the operation was completed successfully.
*/
delegate OnComplete(HttpCache Sender, HttpCacheObject Data, EDataOrigin origin);

/**
    failed to complete the request, will be called when everything fails
*/
delegate OnFail(HttpCache Sender, int idx, ECacheFailError reason);

/**
    Will be called after the HttpSock instance has been created. Use it to set
    certain variables and delegates for the HttpSock. <br />
    Note: You shouldn't set any delegates in the sccket, most will be
    overwritten anyway.
*/
delegate OnCreateSock(HttpCache Sender, HttpSock Socket);

////////////////////////////////////////////////////////////////////////////////
//
//   Public functions
//
////////////////////////////////////////////////////////////////////////////////

/**
    Performs a get request. Returns the ID of the request. This Id can be used
    in to retrieve the URL in the future
*/
function int get(string location)
{
    local int hash;
    local int idx, i;
    local HttpUtil.xURL xloc;
    local HttpCacheObject co;

    if (!class'HttpUtil'.static.parseUrl(location, xloc))
    {
        OnFail(self, -1, CF_BadRequest);
        return -1;
    }
    //TODO: check http, etc.
    xloc.hostname = Locs(xloc.hostname);
    location = class'HttpUtil'.static.xUrlToString(xloc, true);
    hash = createHash(location);
    idx = findCacheRecord(hash);
    if (idx == -1)
    {
        idx = CacheList.length;
        CacheList.length = idx+1;
        CacheList[idx].URL = xloc;
        CacheList[idx].hash = hash;
        CacheList[idx].colidx = -1;
    }
    co = getCacheObject(idx);
    if (co.bBusy)
    {
        OnFail(self, -1, CF_Busy);
        return -1;
    }
    co.URL = location;
    co.bBusy = true;
    if (co.ExpiresOn > class'HttpUtil'.static.timestamp(Level.Year, Level.Month, Level.Day, Level.Hour, Level.Minute, Level.Second))
    {
        // content not yet expired
        OnComplete(self, co, DO_Cache);
        return idx; // no need to save anything
    }
    // find free sock
    for (i = 0; i < Requests.length; i++)
    {
        if (Requests[i].idx == -1) break;
    }
    if (i == Requests.length)
    {
        Requests.length = i+1;
        Requests[i].Socket = spawn(HttpSockClass);
        OnCreateSock(self, Requests[i].Socket);
        Requests[i].Socket.OnComplete = DownloadComplete;
        Requests[i].Socket.OnError = DownloadError;
        Requests[i].Socket.OnConnectionTimeout = DownloadTimeout;
        Requests[i].Socket.OnResolveFailed = ResolveFailed;
    }
    Requests[i].idx = idx;
    Requests[i].Socket.ClearRequestData();
    if (co.LastModification > 0)
        Requests[i].Socket.AddHeader("If-Modified-Since", class'HttpUtil'.static.timestampToString(co.LastModification));
    if (!Requests[i].Socket.get(location))
    {
        OnFail(self, -1, CF_BadRequest);
        return -1;
    }
    return idx;
}

/**
    Returns true when the location is cached
*/
function bool isCached(string location)
{
    local int i;
    local HttpUtil.xURL xloc;
    if (!class'HttpUtil'.static.parseUrl(location, xloc)) return false;
    xloc.hostname = Locs(xloc.hostname);
    for (i = 0; i < CacheList.length; i++)
    {
        if (CacheList[i].URL == xloc) return true;
    }
    return false;
}

/**
    Returns the URL for a certain ID. Result will be false when the ID is no
    longer valid.
*/
function bool getURLbyId(int id, out string URL)
{
    if ((id < 0) || (id > CacheList.length)) return false;
    URL = class'HttpUtil'.static.xUrlToString(CacheList[id].URL, true);
    return false;
}

////////////////////////////////////////////////////////////////////////////////
//
//   Private functions
//
////////////////////////////////////////////////////////////////////////////////

event PreBeginPlay()
{
    local int i;
    CacheCleanup();
    for (i = 0; i < CacheList.length; i++)
    {
        CacheList[i].colidx = -1;
    }
}

/**
    Clean up the cache
*/
protected function CacheCleanup()
{
    local int i, cursize, oldest;
    local HttpCacheObject co;

    if (CacheList.length == 0) return;
    if (iCacheLimit == 0) return;

    cursize = 0;
    for (i = 0; i < CacheList.length; i++)
    {
        cursize += CacheList[i].DataSize;
    }
    while (cursize > iCacheLimit)
    {
        oldest = 0;
        for (i = 1; i < CacheList.length; i++)
        {
            if (CacheList[i].LastUpdate == 0) continue;
            if (CacheList[i].LastUpdate < CacheList[oldest].LastUpdate)
                oldest = i;
        }
        cursize -= CacheList[oldest].DataSize;
        co = getCacheObject(oldest);
        co.ClearConfig();
        // co isn't destroyed because there's no object cleanup anyway,
        // also we can't reuse it because of the PerObjectConfig
        CacheObjectList[CacheList[oldest].colidx] = none;
        CacheList[oldest].DataSize = 0;
        CacheList[oldest].colidx = -1;
        CacheList[oldest].LastUpdate = 0;
    }
    SaveConfig();
}

/** return the hash of the URL */
static final function int createHash(string URL)
{
    local int result;
    local int i, g;
    result = 0x12345670;
    for (i = 0; i < len(url); ++i)
    {
        result = (result << 4) + asc(mid(url, i, 1));
        g = result & 0xf0000000;
        if (g > 0) result = result | (g >> 24) | g;
    }
    return result;
}

/** find an idx using a hash */
protected function int findCacheRecord(int hash)
{
    local int i;
    for (i = 0; i < CacheList.length; i++)
    {
        if (CacheList[i].Hash == hash) return i;
    }
    return -1;
}

/** get\create a CacheObject */
protected function HttpCacheObject getCacheObject(int idx)
{
    local int lidx;
    local HttpCacheObject co;

    if (idx < 0 || idx >= CacheList.length) return none;
    if ((CacheList[idx].colidx > -1) && (CacheList[idx].colidx < CacheObjectList.length))
    {
        return CacheObjectList[CacheList[idx].colidx];
    }
    lidx = CacheObjectList.length;
    CacheObjectList.length = lidx+1;
    CacheList[idx].colidx = lidx;
    co = new(None, "Cache_h"$string(CacheList[idx].Hash)) HttpCacheObjectClass;
    co.SaveConfig();
    CacheObjectList[lidx] = co;
    log("Created cache object "$co.name);
    return co;
}

protected function DownloadComplete(HttpSock Sender)
{
    local int idx, i;
    local HttpCacheObject co;
    local EDataOrigin origin;

    idx = -1;
    for (i = 0; i < Requests.Length; i++)
    {
        if (Requests[i].Socket == Sender)
        {
            idx = Requests[i].idx;
            Requests[i].idx = -1;
        }
    }
    if (idx == -1)
    {
        //error ?
        return;
    }
    co = getCacheObject(idx);
    co.bBusy = false;
    if (co.LastModification == -1) origin = DO_Initial;
    else if (Sender.LastStatus == 304) origin = DO_Cache;
    else origin = DO_Refresh;

    if (origin != DO_Cache)
    {
        co.Data = Sender.ReturnData;
        co.LastModification = class'HttpUtil'.static.stringToTimestamp(Sender.GetReturnHeader("Last-Modified", "0"), Sender.getTZoffset());
        co.ExpiresOn = class'HttpUtil'.static.stringToTimestamp(Sender.GetReturnHeader("Expires", "0"), Sender.getTZoffset());
        co.ContentType = class'HttpUtil'.static.trim(Sender.GetReturnHeader("Content-Type", ""));
        co.SaveConfig();
        CacheList[idx].DataSize = co.GetSize();
    }
    CacheList[idx].LastUpdate = class'HttpUtil'.static.timestamp(Level.Year, Level.Month, Level.Day, Level.Hour, Level.Minute, Level.Second);
    SaveConfig();
    OnComplete(self, co, origin);
}

protected function DownloadError(HttpSock Sender, string ErrorMessage, optional string Param1, optional string Param2)
{
    local int idx, i;
    local HttpCacheObject co;

    idx = -1;
    for (i = 0; i < Requests.Length; i++)
    {
        if (Requests[i].Socket == Sender)
        {
            idx = Requests[i].idx;
            Requests[i].idx = -1;
        }
    }
    if (idx == -1) return;
    co = getCacheObject(idx);
    co.bBusy = false;
    OnError(self, ErrorMessage, Param1, Param2);
}

protected function DownloadTimeout(HttpSock Sender)
{
    local int idx, i;
    idx = -1;
    for (i = 0; i < Requests.Length; i++)
    {
        if (Requests[i].Socket == Sender)
        {
            idx = Requests[i].idx;
        }
    }
    if (idx == -1) return;
    OnFail(self, idx, CF_Timeout);
}

protected function ResolveFailed(HttpSock Sender, string hostname)
{
    local int idx, i;
    idx = -1;
    for (i = 0; i < Requests.Length; i++)
    {
        if (Requests[i].Socket == Sender)
        {
            idx = Requests[i].idx;
        }
    }
    if (idx == -1) return;
    OnFail(self, idx, CF_ResolveFailed);
}

defaultproperties
{
    HttpSockClass=class'HttpSock'
    HttpCacheObjectClass=class'HttpCacheObject'
    // 512kb
    iCacheLimit=524288
}

Overview Package Class Source Class tree Glossary
previous class      next class frames      no frames
Class file time: Fr 9.12.2005 10:31:12.000 - Creation time: Do 14.8.2014 09:58:40.589 - Created with UnCodeX