Here's a well-organized C-based autosave system architecture designed for performance, robustness, and easy integration:
Core Architecture
Header File (autosave.h)
#ifndef AUTOSAVE_H
#define AUTOSAVE_H
#include <glib.h>
#include <stdint.h>
#include <stdbool.h>
/* Forward declarations */
typedef struct AutosaveContext AutosaveContext;
typedef struct AutosaveConfig AutosaveConfig;
/* Error codes */
typedef enum {
AUTOSAVE_SUCCESS = 0,
AUTOSAVE_ERROR_INIT,
AUTOSAVE_ERROR_IO,
AUTOSAVE_ERROR_CORRUPTION,
AUTOSAVE_ERROR_MEMORY,
AUTOSAVE_ERROR_INVALID_PARAM
} AutosaveResult;
/* Configuration structure */
struct AutosaveConfig {
const char *base_filename; /* Base model filename */
const char *autosave_dir; /* Directory for autosave files */
uint32_t client_id; /* Unique client identifier */
uint32_t save_interval_ms; /* Autosave interval in milliseconds */
size_t chunk_size; /* I/O chunk size for large files */
bool enable_compression; /* Enable data compression */
bool enable_checksums; /* Enable corruption detection */
};
/* Data provider callback - called when autosave needs current data */
typedef AutosaveResult (*AutosaveDataProvider)(
void *user_data,
uint8_t **data,
size_t *data_size,
uint64_t *data_version
);
/* Completion callback - called when autosave operation completes */
typedef void (*AutosaveCompletionCallback)(
AutosaveResult result,
const char *autosave_path,
void *user_data
);
/* Public API */
AutosaveResult autosave_init(
const AutosaveConfig *config,
AutosaveDataProvider data_provider,
AutosaveCompletionCallback completion_callback,
void *user_data,
AutosaveContext **context
);
AutosaveResult autosave_start(AutosaveContext *context);
AutosaveResult autosave_stop(AutosaveContext *context);
AutosaveResult autosave_trigger_immediate(AutosaveContext *context);
AutosaveResult autosave_list_available(
const char *base_filename,
const char *autosave_dir,
uint32_t client_id,
char ***autosave_files,
size_t *count
);
AutosaveResult autosave_restore(
const char *autosave_path,
uint8_t **data,
size_t *data_size,
uint64_t *data_version
);
AutosaveResult autosave_verify_integrity(const char *autosave_path);
AutosaveResult autosave_cleanup_old(
const char *autosave_dir,
uint32_t client_id,
uint32_t keep_count
);
void autosave_destroy(AutosaveContext *context);
const char *autosave_error_string(AutosaveResult result);
#endif /* AUTOSAVE_H */
Implementation Structure
Core Context Structure
/* Internal context structure */
struct AutosaveContext {
AutosaveConfig config;
AutosaveDataProvider data_provider;
AutosaveCompletionCallback completion_callback;
void *user_data;
GThread *worker_thread;
GAsyncQueue *work_queue;
GMutex state_mutex;
GCond state_cond;
volatile bool running;
volatile bool stop_requested;
char *autosave_path_template;
uint64_t last_saved_version;
GTimer *timer;
};
/* Work item for async operations */
typedef struct {
enum { WORK_AUTOSAVE, WORK_STOP } type;
bool immediate;
} WorkItem;
File Format Design
/* Autosave file header */
typedef struct {
uint32_t magic; /* 'ASAV' magic number */
uint32_t version; /* File format version */
uint32_t client_id; /* Client identifier */
uint64_t data_version; /* Data version number */
uint64_t timestamp; /* Creation timestamp */
uint64_t data_size; /* Original data size */
uint64_t compressed_size; /* Compressed size (if compression enabled) */
uint32_t header_checksum; /* Header integrity check */
uint32_t data_checksum; /* Data integrity check */
uint32_t flags; /* Compression, encryption flags */
uint8_t reserved[32]; /* Future expansion */
} AutosaveHeader;
#define AUTOSAVE_MAGIC 0x56415341 /* 'ASAV' */
#define AUTOSAVE_VERSION 1
Key Implementation Features
1. Filename Strategy
/* Generate unique autosave filename */
static char *generate_autosave_path(const AutosaveContext *ctx) {
GDateTime *now = g_date_time_new_now_local();
char *timestamp = g_date_time_format(now, "%Y%m%d_%H%M%S");
char *filename = g_strdup_printf("%s.client_%u.%s.asav",
ctx->config.base_filename,
ctx->config.client_id,
timestamp);
char *full_path = g_build_filename(ctx->config.autosave_dir, filename, NULL);
g_free(timestamp);
g_free(filename);
g_date_time_unref(now);
return full_path;
}
2. Async Worker Thread
static gpointer autosave_worker_thread(gpointer data) {
AutosaveContext *ctx = (AutosaveContext *)data;
while (ctx->running) {
WorkItem *item = g_async_queue_timeout_pop(ctx->work_queue,
ctx->config.save_interval_ms * 1000);
if (item) {
if (item->type == WORK_AUTOSAVE) {
perform_autosave(ctx);
} else if (item->type == WORK_STOP) {
break;
}
g_free(item);
} else {
/* Timeout - perform periodic autosave */
perform_autosave(ctx);
}
}
return NULL;
}
3. Corruption Detection
static uint32_t calculate_checksum(const uint8_t *data, size_t size) {
return g_checksum_get_digest(g_checksum_new(G_CHECKSUM_CRC32), data, size);
}
static AutosaveResult verify_file_integrity(const char *path) {
GError *error = NULL;
GMappedFile *mapped = g_mapped_file_new(path, FALSE, &error);
if (!mapped) {
return AUTOSAVE_ERROR_IO;
}
const AutosaveHeader *header = (const AutosaveHeader *)g_mapped_file_get_contents(mapped);
/* Verify header checksum */
AutosaveHeader temp_header = *header;
temp_header.header_checksum = 0;
uint32_t calculated_header_checksum = calculate_checksum((uint8_t *)&temp_header,
sizeof(AutosaveHeader));
if (calculated_header_checksum != header->header_checksum) {
g_mapped_file_unref(mapped);
return AUTOSAVE_ERROR_CORRUPTION;
}
/* Verify data checksum */
const uint8_t *data = (const uint8_t *)header + sizeof(AutosaveHeader);
uint32_t calculated_data_checksum = calculate_checksum(data, header->compressed_size);
if (calculated_data_checksum != header->data_checksum) {
g_mapped_file_unref(mapped);
return AUTOSAVE_ERROR_CORRUPTION;
}
g_mapped_file_unref(mapped);
return AUTOSAVE_SUCCESS;
}
4. High-Performance I/O
static AutosaveResult write_data_chunked(int fd, const uint8_t *data,
size_t size, size_t chunk_size) {
size_t written = 0;
while (written < size) {
size_t to_write = MIN(chunk_size, size - written);
ssize_t result = write(fd, data + written, to_write);
if (result < 0) {
return AUTOSAVE_ERROR_IO;
}
written += result;
}
return AUTOSAVE_SUCCESS;
}
Integration Example
/* Example integration */
typedef struct {
uint8_t *model_data;
size_t model_size;
uint64_t model_version;
} ApplicationData;
static AutosaveResult app_data_provider(void *user_data, uint8_t **data,
size_t *data_size, uint64_t *data_version) {
ApplicationData *app_data = (ApplicationData *)user_data;
/* Return copy of current data */
*data = g_memdup2(app_data->model_data, app_data->model_size);
*data_size = app_data->model_size;
*data_version = app_data->model_version;
return AUTOSAVE_SUCCESS;
}
static void app_autosave_complete(AutosaveResult result, const char *path, void *user_data) {
if (result == AUTOSAVE_SUCCESS) {
g_print("Autosave completed: %s\n", path);
} else {
g_warning("Autosave failed: %s\n", autosave_error_string(result));
}
}
/* Initialize autosave */
AutosaveConfig config = {
.base_filename = "model.dat",
.autosave_dir = "./autosave",
.client_id = getpid(), /* Use process ID as client ID */
.save_interval_ms = 30000, /* 30 seconds */
.chunk_size = 1024 * 1024, /* 1MB chunks */
.enable_compression = true,
.enable_checksums = true
};
AutosaveContext *autosave_ctx;
autosave_init(&config, app_data_provider, app_autosave_complete,
&app_data, &autosave_ctx);
autosave_start(autosave_ctx);
Key Design Benefits
Performance: Async worker thread, chunked I/O, optional compression, and memory-mapped file verification ensure efficient handling of multi-gigabyte files.
Robustness: Comprehensive checksums, atomic file operations, and structured error handling provide corruption resistance.
Multi-instance Support: Client ID-based filename generation allows multiple application instances to maintain separate autosave data.
Easy Integration: Simple callback-based interface requires minimal changes to existing applications.
Cross-platform: GLib provides consistent behavior across Windows and Linux while maintaining efficiency.
Server Coordination Ready: The client ID system and file naming convention support coordination through an external server application.
This architecture provides a solid foundation that can be extended with additional features like encryption, network synchronization, or more sophisticated compression algorithms as needed.