myxce/src/lib/idgen.c
2025-11-07 18:17:34 +08:00

70 lines
1.4 KiB
C

#include <stdint.h>
#include <time.h>
#include "idgen.h"
#include "mylock.h"
#include "utils.h"
#include "xce/errnox.h"
int idgen_ctx_init(idgen_ctx_t* ctx)
{
if (ctx == NULL) {
return -EINVAL;
}
mylock_init(&(ctx->lock));
ctx->timestamp = time(NULL);
ctx->sequence = 0;
return 0;
}
int idgen(idgen_ctx_t* ctx, size_t clusterId, size_t apiserverId,
size_t arraySize, uint64_t* pidx)
{
time_t now;
uint64_t idx;
uint64_t ts, tag, seq;
if ((ctx == NULL) || (clusterId > MAX_CLUSTER_ID)
|| (apiserverId > MAX_APISERVER_ID) || (arraySize < 1)
|| (arraySize > MAX_ARRAY_IDX + 1) || (pidx == NULL)) {
return -EINVAL;
}
mylock_lock(&(ctx->lock));
now = time(NULL);
if (now != ctx->timestamp) {
ctx->timestamp = now;
ctx->sequence = 0;
}
ts = ctx->timestamp;
if (arraySize == 1) {
/* non array job */
tag = 0x0;
seq = ctx->sequence;
ctx->sequence++;
} else {
tag = TAG_JOB_ARRAY;
seq = ROUNDUP(ctx->sequence, N_ARRAY_IDX_BITS);
ctx->sequence = ROUNDUP(seq + 1, N_ARRAY_IDX_BITS);
}
mylock_unlock(&(ctx->lock));
idx = MAKE_JOBID(clusterId, apiserverId, ts, tag, seq);
*pidx = idx;
return arraySize;
}
void idgen_ctx_fini(idgen_ctx_t* ctx)
{
if (ctx == NULL) {
return;
}
mylock_fini(&(ctx->lock));
}