Interface modified mmap to fd

This commit is contained in:
Eli-Class
2026-01-29 09:24:48 +00:00
parent abc47d4909
commit c6e3eae22e
11 changed files with 727 additions and 1733 deletions

View File

@@ -1,3 +1,5 @@
가변 길이 배열이 포함된 데이터의 커스텀 바이너리 직렬화 방법을 보여드릴게요.
```typescript
// 가변 배열 직렬화 예시
import { createSerializer, DataWriter, DataReader } from './src/data-file/index.js';

View File

@@ -2,7 +2,7 @@
```typescript
// example.ts
import { DataWriter, DataReader, jsonSerializer, createSerializer } from '@elilee/index-file';
import { DataWriter, DataReader, jsonSerializer, createSerializer } from './index.js';
// ============================================
// 1. JSON 직렬화 (간단한 경우)

View File

@@ -1,6 +1,5 @@
// src/data-file/reader.ts
import * as fs from 'node:fs';
import mmap from '@elilee/mmap-native';
import { DATA_HEADER_SIZE } from './constants.js';
import { DataProtocol, DataHeader } from './protocol.js';
import { IndexReader } from '../idx/index.js';
@@ -8,7 +7,6 @@ import type { Serializer, DataEntry } from './types.js';
export class DataReader<T> {
private fd: number | null = null;
private buffer: Buffer | null = null;
private header: DataHeader | null = null;
private indexReader: IndexReader;
@@ -25,35 +23,39 @@ export class DataReader<T> {
}
open(): void {
const stats = fs.statSync(this.dataPath);
this.fd = fs.openSync(this.dataPath, 'r');
this.buffer = mmap.map(
stats.size,
mmap.PROT_READ,
mmap.MAP_SHARED,
this.fd,
0
);
// Read header only
const headerBuf = Buffer.alloc(DATA_HEADER_SIZE);
fs.readSync(this.fd, headerBuf, 0, DATA_HEADER_SIZE, 0);
this.header = DataProtocol.readHeader(headerBuf);
this.header = DataProtocol.readHeader(this.buffer);
this.indexReader.open();
}
private readRecord(offset: bigint, length: number): Buffer {
if (this.fd === null) throw new Error('Data file not opened');
const buf = Buffer.alloc(length);
fs.readSync(this.fd, buf, 0, length, Number(offset));
return buf;
}
getHeader(): DataHeader {
if (!this.header) throw new Error('Data file not opened');
return this.header;
}
getBySequence(sequence: number): DataEntry<T> | null {
if (!this.buffer) throw new Error('Data file not opened');
if (this.fd === null) throw new Error('Data file not opened');
const found = this.indexReader.binarySearchBySequence(sequence);
if (!found) return null;
const buf = this.readRecord(found.entry.offset, found.entry.length);
const result = DataProtocol.deserializeRecord(
this.buffer,
Number(found.entry.offset),
buf,
0,
this.serializer
);
if (!result) return null;
@@ -66,14 +68,15 @@ export class DataReader<T> {
}
getByIndex(index: number): DataEntry<T> | null {
if (!this.buffer) throw new Error('Data file not opened');
if (this.fd === null) throw new Error('Data file not opened');
const entry = this.indexReader.getEntry(index);
if (!entry) return null;
const buf = this.readRecord(entry.offset, entry.length);
const result = DataProtocol.deserializeRecord(
this.buffer,
Number(entry.offset),
buf,
0,
this.serializer
);
if (!result) return null;
@@ -86,22 +89,23 @@ export class DataReader<T> {
}
getBulkData(startSeq: number, endSeq: number): DataEntry<T>[] {
if (!this.buffer) throw new Error('Data file not opened');
if (this.fd === null) throw new Error('Data file not opened');
const results: DataEntry<T>[] = [];
const indexHeader = this.indexReader.getHeader();
let startIdx = this.findStartIndex(startSeq, indexHeader.validCount);
let startIdx = this.findStartIndex(startSeq, indexHeader.writtenCnt);
for (let i = startIdx; i < indexHeader.validCount; i++) {
for (let i = startIdx; i < indexHeader.writtenCnt; i++) {
const entry = this.indexReader.getEntry(i);
if (!entry) continue;
if (entry.sequence > endSeq) break;
if (entry.sequence >= startSeq) {
const buf = this.readRecord(entry.offset, entry.length);
const result = DataProtocol.deserializeRecord(
this.buffer,
Number(entry.offset),
buf,
0,
this.serializer
);
if (result) {
@@ -117,9 +121,9 @@ export class DataReader<T> {
return results;
}
private findStartIndex(targetSeq: number, validCount: number): number {
private findStartIndex(targetSeq: number, writtenCnt: number): number {
let left = 0;
let right = validCount - 1;
let right = writtenCnt - 1;
let result = 0;
while (left <= right) {
@@ -143,15 +147,16 @@ export class DataReader<T> {
}
getBulkDataByTime(startTs: bigint, endTs: bigint): DataEntry<T>[] {
if (!this.buffer) throw new Error('Data file not opened');
if (this.fd === null) throw new Error('Data file not opened');
const indexResults = this.indexReader.findByTimeRange(startTs, endTs);
const results: DataEntry<T>[] = [];
for (const { entry } of indexResults) {
const buf = this.readRecord(entry.offset, entry.length);
const result = DataProtocol.deserializeRecord(
this.buffer,
Number(entry.offset),
buf,
0,
this.serializer
);
if (result) {
@@ -167,15 +172,16 @@ export class DataReader<T> {
}
getAllData(): DataEntry<T>[] {
if (!this.buffer) throw new Error('Data file not opened');
if (this.fd === null) throw new Error('Data file not opened');
const entries = this.indexReader.getAllEntries();
const results: DataEntry<T>[] = [];
for (const entry of entries) {
const buf = this.readRecord(entry.offset, entry.length);
const result = DataProtocol.deserializeRecord(
this.buffer,
Number(entry.offset),
buf,
0,
this.serializer
);
if (result) {
@@ -191,18 +197,14 @@ export class DataReader<T> {
}
getRecordCount(): number {
return this.indexReader.getHeader().validCount;
return this.indexReader.getHeader().writtenCnt;
}
getLastSequence(): number {
return this.indexReader.getHeader().lastSequence;
return this.indexReader.getHeader().latestSequence;
}
close(): void {
if (this.buffer) {
mmap.unmap(this.buffer);
this.buffer = null;
}
if (this.fd !== null) {
fs.closeSync(this.fd);
this.fd = null;

View File

@@ -1,3 +1,5 @@
import { IndexFileOptions } from "../idx/types.js";
// src/data-file/types.ts
export interface Serializer<T> {
serialize(data: T): Buffer;
@@ -12,5 +14,6 @@ export interface DataEntry<T> {
export interface DataFileOptions<T> {
serializer: Serializer<T>;
maxEntries?: number;
forceTruncate?: boolean;
indexFileOpt: IndexFileOptions;
}

View File

@@ -2,7 +2,7 @@
import * as fs from 'node:fs';
import { DATA_HEADER_SIZE } from './constants.js';
import { DataProtocol } from './protocol.js';
import { IndexWriter } from '../idx/index.js';
import { IndexWriter, IndexFileOptionsRequired } from '../idx/index.js';
import type { Serializer, DataFileOptions } from './types.js';
export class DataWriter<T> {
@@ -12,42 +12,98 @@ export class DataWriter<T> {
private recordCount = 0;
private indexWriter: IndexWriter;
private serializer: Serializer<T>;
readonly dataPath: string;
readonly indexPath: string;
// See DataFileOptions
private readonly serializer: Serializer<T>;
private readonly forceTruncate: boolean;
constructor(basePath: string, options: DataFileOptions<T>) {
this.dataPath = `${basePath}.dat`;
this.indexPath = `${basePath}.idx`;
private latestSequence: number = 0;
private readonly indexFileOpt: IndexFileOptionsRequired;
private dataPath: string | null = null;
private indexPath: string | null = null;
constructor(options: DataFileOptions<T>) {
this.serializer = options.serializer;
this.forceTruncate = options.forceTruncate ?? false;
const maxEntries = options.maxEntries ?? 10_000_000;
this.indexWriter = new IndexWriter(this.indexPath, { maxEntries });
this.indexFileOpt = {
maxEntries: options.indexFileOpt.maxEntries ?? 10_000_000,
autoIncrementSequence: options.indexFileOpt.autoIncrementSequence ?? false
}
open(): void {
this.indexWriter = new IndexWriter(this.indexFileOpt);
}
open(basePath: string): void {
this.dataPath = `${basePath}.dat`;
this.indexPath = `${basePath}.idx`;
// Index file 을 Open 함으로써 파일을 시작 할 수 있는지 검증 (Throw 로써)
// Open index file with maxEntries and autoIncrementSequence
const writtenCount = this.indexWriter.open(this.indexPath, this.forceTruncate);
const isNew = !fs.existsSync(this.dataPath);
this.fd = fs.openSync(this.dataPath, isNew ? 'w+' : 'r+');
// Index file 은 초기화인데, 신규파일 혹은 강제 클리어가 아니라면
if (writtenCount === 0 && !(isNew || this.forceTruncate)) {
throw new Error(`Index file & Data File is invalid ${this.indexPath} is initial but ${this.dataPath} is exists`);
}
if (writtenCount > 0 && isNew) {
throw new Error(`Index file & Data File is invalid data of ${this.indexPath} | ${writtenCount} is exists but ${this.dataPath} is not exists`);
}
// Warn if forceTruncate will delete existing data
if (this.forceTruncate && !isNew) {
const stats = fs.statSync(this.dataPath);
const sizeMB = (stats.size / 1024 / 1024).toFixed(2);
console.warn(
`[DataWriter] forceTruncate enabled: Deleting ${sizeMB} MB of existing data\n` +
` Index: ${this.indexPath} (${writtenCount} records)\n` +
` Data: ${this.dataPath}`
);
}
this.fd = fs.openSync(this.dataPath,
isNew || this.forceTruncate ? 'w+' : 'r+');
try {
this.headerBuf = Buffer.alloc(DATA_HEADER_SIZE);
if (isNew) {
if (isNew || this.forceTruncate) {
const header = DataProtocol.createHeader();
fs.writeSync(this.fd, header, 0, DATA_HEADER_SIZE, 0);
this.currentOffset = BigInt(DATA_HEADER_SIZE);
this.recordCount = 0;
this.latestSequence = 0;
} else {
fs.readSync(this.fd, this.headerBuf, 0, DATA_HEADER_SIZE, 0);
const header = DataProtocol.readHeader(this.headerBuf);
// Validate: Data file recordCount must match Index file writtenCnt
if (header.recordCount !== writtenCount) {
throw new Error(
`Data file record count mismatch: Data has ${header.recordCount} but Index has ${writtenCount}`
);
}
this.currentOffset = header.fileSize;
this.recordCount = header.recordCount;
this.latestSequence = this.indexWriter.getLatestSequence();
}
} catch (error) {
// Clean up resources on error
if (this.fd !== null) {
fs.closeSync(this.fd);
this.fd = null;
}
this.headerBuf = null;
throw error;
}
}
this.indexWriter.open();
}
append(data: T, timestamp?: bigint): number {
append(data: T, sequence?: number, timestamp?: bigint): number {
if (this.fd === null) throw new Error('Data file not opened');
const buf = DataProtocol.serializeRecord(data, this.serializer);
@@ -55,35 +111,49 @@ export class DataWriter<T> {
fs.writeSync(this.fd, buf, 0, buf.length, Number(offset));
const sequence = this.indexWriter.getNextSequence();
const ts = timestamp ?? BigInt(Date.now()) * 1000000n;
// Write to index file
this.indexWriter.write(offset, buf.length, sequence, timestamp);
this.indexWriter.append(offset, buf.length, ts);
// Update latestSequence to the most recent sequence
this.latestSequence = this.indexWriter.getLatestSequence();
this.currentOffset += BigInt(buf.length);
this.recordCount++;
++this.recordCount;
return sequence;
return this.latestSequence;
}
appendBulk(records: T[], timestamp?: bigint): number[] {
const sequences: number[] = [];
/*
appendBulk(records: T[], sequences?: number[], timestamp?: bigint): number[] {
// Runtime check: sequences required when autoIncrementSequence is false
if (!this.autoIncrementSequence) {
if (!sequences) {
throw new Error('sequences is required when autoIncrementSequence is false');
}
if (sequences.length !== records.length) {
throw new Error(`sequences length (${sequences.length}) must match records length (${records.length})`);
}
}
const resultSequences: number[] = [];
const ts = timestamp ?? BigInt(Date.now()) * 1000000n;
for (const record of records) {
const seq = this.append(record, ts);
sequences.push(seq);
for (let i = 0; i < records.length; i++) {
const seq = sequences?.[i];
const resultSeq = this.append(records[i], seq, ts);
resultSequences.push(resultSeq);
}
return sequences;
return resultSequences;
}
*/
getLastSequence(): number {
return this.indexWriter.getLastSequence();
getLatestSequence(): number {
return this.latestSequence;
}
getNextSequence(): number {
return this.indexWriter.getNextSequence();
return this.latestSequence + 1;
}
sync(): void {
@@ -114,7 +184,7 @@ export class DataWriter<T> {
indexPath: this.indexPath,
currentOffset: this.currentOffset,
recordCount: this.recordCount,
lastSequence: this.indexWriter.getLastSequence(),
latestSequence: this.indexWriter.getLatestSequence(),
};
}
}

View File

@@ -27,16 +27,17 @@ export function crc32(buf: Buffer, start = 0, end?: number): number {
}
export class IndexProtocol {
static createHeader(entryCount: number, magic = INDEX_MAGIC): Buffer {
static createHeader(entryCount: number, autoIncrementSequence: boolean, magic = INDEX_MAGIC): Buffer {
const buf = Buffer.alloc(INDEX_HEADER_SIZE);
buf.write(magic, 0, 4, 'ascii');
buf.writeUInt32LE(INDEX_VERSION, 4);
buf.writeBigUInt64LE(BigInt(Date.now()) * 1000000n, 8);
buf.writeUInt32LE(INDEX_ENTRY_SIZE, 16);
buf.writeUInt32LE(entryCount, 20);
buf.writeUInt32LE(0, 24);
buf.writeBigUInt64LE(0n, 28);
buf.writeUInt32LE(0, 36);
buf.writeUInt32LE(0, 24); // writtenCnt
buf.writeBigUInt64LE(0n, 28); // dataFileSize
buf.writeUInt32LE(0, 36); // latestSequence
buf.writeUInt8(autoIncrementSequence ? 1 : 0, 40); // autoIncrementSequence
return buf;
}
@@ -47,22 +48,23 @@ export class IndexProtocol {
createdAt: buf.readBigUInt64LE(8),
entrySize: buf.readUInt32LE(16),
entryCount: buf.readUInt32LE(20),
validCount: buf.readUInt32LE(24),
writtenCnt: buf.readUInt32LE(24),
dataFileSize: buf.readBigUInt64LE(28),
lastSequence: buf.readUInt32LE(36),
reserved: buf.subarray(40, 64),
latestSequence: buf.readUInt32LE(36),
autoIncrementSequence: buf.readUInt8(40) === 1,
reserved: buf.subarray(41, 64),
};
}
static updateHeaderCounts(
buf: Buffer,
validCount: number,
writtenCnt: number,
dataFileSize: bigint,
lastSequence: number
latestSequence: number
): void {
buf.writeUInt32LE(validCount, 24);
buf.writeUInt32LE(writtenCnt, 24);
buf.writeBigUInt64LE(dataFileSize, 28);
buf.writeUInt32LE(lastSequence, 36);
buf.writeUInt32LE(latestSequence, 36);
}
static writeEntry(buf: Buffer, index: number, entry: Omit<IndexEntry, 'checksum'>): void {

View File

@@ -1,11 +1,9 @@
// src/index-file/reader.ts
import * as fs from 'node:fs';
import mmap from '@elilee/mmap-native';
import { IndexProtocol } from './protocol.js';
import type { IndexHeader, IndexEntry } from './types.js';
export class IndexReader {
private fd: number | null = null;
private buffer: Buffer | null = null;
private header: IndexHeader | null = null;
@@ -16,17 +14,8 @@ export class IndexReader {
}
open(): void {
const stats = fs.statSync(this.path);
this.fd = fs.openSync(this.path, 'r');
this.buffer = mmap.map(
stats.size,
mmap.PROT_READ,
mmap.MAP_SHARED,
this.fd,
0
);
// Read entire file into buffer (simpler than mmap for read-only access)
this.buffer = fs.readFileSync(this.path);
this.header = IndexProtocol.readHeader(this.buffer);
}
@@ -44,7 +33,7 @@ export class IndexReader {
findBySequence(sequence: number): { index: number; entry: IndexEntry } | null {
if (!this.buffer || !this.header) throw new Error('Index file not opened');
for (let i = 0; i < this.header.validCount; i++) {
for (let i = 0; i < this.header.writtenCnt; i++) {
const entry = IndexProtocol.readEntry(this.buffer, i);
if (entry && entry.sequence === sequence) {
return { index: i, entry };
@@ -57,7 +46,7 @@ export class IndexReader {
if (!this.buffer || !this.header) throw new Error('Index file not opened');
const results: { index: number; entry: IndexEntry }[] = [];
for (let i = 0; i < this.header.validCount; i++) {
for (let i = 0; i < this.header.writtenCnt; i++) {
const entry = IndexProtocol.readEntry(this.buffer, i);
if (entry && entry.sequence >= startSeq && entry.sequence <= endSeq) {
results.push({ index: i, entry });
@@ -70,7 +59,7 @@ export class IndexReader {
if (!this.buffer || !this.header) throw new Error('Index file not opened');
const entries: IndexEntry[] = [];
for (let i = 0; i < this.header.validCount; i++) {
for (let i = 0; i < this.header.writtenCnt; i++) {
const entry = IndexProtocol.readEntry(this.buffer, i);
if (entry) entries.push(entry);
}
@@ -81,7 +70,7 @@ export class IndexReader {
if (!this.buffer || !this.header) throw new Error('Index file not opened');
const results: { index: number; entry: IndexEntry }[] = [];
for (let i = 0; i < this.header.validCount; i++) {
for (let i = 0; i < this.header.writtenCnt; i++) {
const entry = IndexProtocol.readEntry(this.buffer, i);
if (entry && entry.timestamp >= startTs && entry.timestamp <= endTs) {
results.push({ index: i, entry });
@@ -94,7 +83,7 @@ export class IndexReader {
if (!this.buffer || !this.header) throw new Error('Index file not opened');
let left = 0;
let right = this.header.validCount - 1;
let right = this.header.writtenCnt - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
@@ -118,14 +107,8 @@ export class IndexReader {
}
close(): void {
if (this.buffer) {
mmap.unmap(this.buffer);
// Simply release buffer reference (GC will handle cleanup)
this.buffer = null;
}
if (this.fd !== null) {
fs.closeSync(this.fd);
this.fd = null;
}
this.header = null;
}
}

View File

@@ -5,9 +5,10 @@ export interface IndexHeader {
createdAt: bigint;
entrySize: number;
entryCount: number;
validCount: number;
writtenCnt: number;
dataFileSize: bigint;
lastSequence: number;
latestSequence: number;
autoIncrementSequence: boolean;
reserved: Buffer;
}
@@ -21,6 +22,8 @@ export interface IndexEntry {
}
export interface IndexFileOptions {
maxEntries: number;
magic?: string;
maxEntries?: number;
autoIncrementSequence?: boolean;
}
export type IndexFileOptionsRequired = Required<IndexFileOptions>;

View File

@@ -1,80 +1,150 @@
// src/index-file/writer.ts
import * as fs from 'node:fs';
import mmap from '@elilee/mmap-native';
import { INDEX_HEADER_SIZE, FLAG_VALID } from './constants.js';
import { INDEX_HEADER_SIZE, INDEX_ENTRY_SIZE, FLAG_VALID } from './constants.js';
import { IndexProtocol } from './protocol.js';
import type { IndexFileOptions } from './types.js';
import { IndexFileOptionsRequired } from './types.js';
export class IndexWriter {
private fd: number | null = null;
private buffer: Buffer | null = null;
private validCount = 0;
private headerBuf: Buffer | null = null;
private entryBuf: Buffer | null = null;
private writtenCnt = 0;
private dataFileSize = 0n;
private lastSequence = 0;
private latestSequence = 0;
readonly path: string;
readonly maxEntries: number;
readonly fileSize: number;
private path: string | null = null;
private fileSize: number = 0;
constructor(path: string, options: IndexFileOptions) {
this.path = path;
this.maxEntries = options.maxEntries;
this.fileSize = IndexProtocol.calcFileSize(options.maxEntries);
// see IndexFileOptions
private maxEntries: number = 0;
private autoIncrementSequence: boolean = false;
constructor(opt: IndexFileOptionsRequired) {
// Empty constructor - maxEntries provided in open()
this.maxEntries = opt.maxEntries;
this.autoIncrementSequence = opt.autoIncrementSequence;
}
open(): void {
open(path: string, forceTruncate: boolean = false): number {
this.path = path;
const isNew = !fs.existsSync(this.path);
this.fd = fs.openSync(this.path, isNew ? 'w+' : 'r+');
if (isNew || forceTruncate) {
// New file: use provided values
this.fileSize = IndexProtocol.calcFileSize(this.maxEntries);
this.writtenCnt = 0;
this.dataFileSize = 0n;
this.latestSequence = 0;
if (isNew) {
this.fd = fs.openSync(this.path, 'w+');
fs.ftruncateSync(this.fd, this.fileSize);
}
this.buffer = mmap.map(
this.fileSize,
mmap.PROT_READ | mmap.PROT_WRITE,
mmap.MAP_SHARED,
this.fd,
0
);
// Allocate buffers for header and entry
this.headerBuf = Buffer.alloc(INDEX_HEADER_SIZE);
this.entryBuf = Buffer.alloc(INDEX_ENTRY_SIZE);
if (isNew) {
const header = IndexProtocol.createHeader(this.maxEntries);
header.copy(this.buffer, 0);
this.syncHeader();
const header = IndexProtocol.createHeader(this.maxEntries, this.autoIncrementSequence);
header.copy(this.headerBuf, 0);
// Write header to file
fs.writeSync(this.fd, this.headerBuf, 0, INDEX_HEADER_SIZE, 0);
fs.fsyncSync(this.fd);
} else {
const header = IndexProtocol.readHeader(this.buffer);
this.validCount = header.validCount;
this.dataFileSize = header.dataFileSize;
this.lastSequence = header.lastSequence;
// Existing file: read header first
this.fd = fs.openSync(this.path, 'r+');
try {
this.headerBuf = Buffer.alloc(INDEX_HEADER_SIZE);
this.entryBuf = Buffer.alloc(INDEX_ENTRY_SIZE);
fs.readSync(this.fd, this.headerBuf, 0, INDEX_HEADER_SIZE, 0);
const header = IndexProtocol.readHeader(this.headerBuf);
if (this.maxEntries !== header.entryCount) {
throw new Error(
`maxEntries mismatch: provided ${this.maxEntries} but file has ${header.entryCount}`
);
}
if (this.autoIncrementSequence !== header.autoIncrementSequence) {
throw new Error(
`autoIncrementSequence mismatch: provided ${this.autoIncrementSequence} but file has ${header.autoIncrementSequence}`
);
}
const expectFileSize = IndexProtocol.calcFileSize(this.maxEntries);
const calcedFileSize = IndexProtocol.calcFileSize(header.entryCount);
if (expectFileSize !== calcedFileSize) {
// if (opt.version !== header.version) { 버전이 다른거니까 어떻게 처리 할지는 추후 고민 TODO }
throw new Error(
`Indexfile size calc is invalid : provided ${expectFileSize} but file has ${calcedFileSize}`
);
}
this.fileSize = calcedFileSize;
this.writtenCnt = header.writtenCnt;
this.dataFileSize = header.dataFileSize;
this.latestSequence = header.latestSequence;
} catch (error) {
// Clean up resources on error
if (this.fd !== null) {
fs.closeSync(this.fd);
this.fd = null;
}
this.headerBuf = null;
this.entryBuf = null;
throw error;
}
}
return this.writtenCnt;
}
write(
index: number,
sequence: number,
offset: bigint,
length: number,
sequence?: number,
timestamp?: bigint
): boolean {
if (!this.buffer) throw new Error('Index file not opened');
if (index < 0 || index >= this.maxEntries) return false;
if (!this.entryBuf || this.fd === null) throw new Error('Index file not opened');
if (this.writtenCnt >= this.maxEntries) {
throw new Error(`Data count exceed provide : ${this.writtenCnt + 1} - max : ${this.maxEntries}`);
}
// Calculate sequence
let seq: number;
if (!this.autoIncrementSequence) {
if (sequence === undefined) {
throw new Error('sequence is required when autoIncrementSequence is false');
}
seq = sequence;
} else {
seq = this.writtenCnt + 1;
}
const ts = timestamp ?? BigInt(Date.now()) * 1000000n;
IndexProtocol.writeEntry(this.buffer, index, {
sequence,
// Create a temporary buffer for this entry
const tempBuf = Buffer.alloc(INDEX_HEADER_SIZE + (this.writtenCnt + 1) * INDEX_ENTRY_SIZE);
// Write entry to temp buffer
IndexProtocol.writeEntry(tempBuf, this.writtenCnt, {
sequence: seq,
timestamp: ts,
offset,
length,
flags: FLAG_VALID,
});
this.validCount++;
if (sequence > this.lastSequence) {
this.lastSequence = sequence;
}
// Calculate file offset for this entry
const fileOffset = INDEX_HEADER_SIZE + this.writtenCnt * INDEX_ENTRY_SIZE;
// Write entry to file
fs.writeSync(this.fd, tempBuf, fileOffset, INDEX_ENTRY_SIZE, fileOffset);
this.writtenCnt++;
this.latestSequence = seq;
const newDataEnd = offset + BigInt(length);
if (newDataEnd > this.dataFileSize) {
@@ -84,58 +154,56 @@ export class IndexWriter {
return true;
}
append(offset: bigint, length: number, timestamp?: bigint): number {
const index = this.validCount;
if (index >= this.maxEntries) return -1;
const sequence = this.lastSequence + 1;
this.write(index, sequence, offset, length, timestamp);
return index;
}
getLastSequence(): number {
return this.lastSequence;
}
getNextSequence(): number {
return this.lastSequence + 1;
getLatestSequence(): number {
return this.latestSequence;
}
syncHeader(): void {
if (!this.buffer) return;
if (!this.headerBuf || this.fd === null) return;
// Update header counts
IndexProtocol.updateHeaderCounts(
this.buffer,
this.validCount,
this.headerBuf,
this.writtenCnt,
this.dataFileSize,
this.lastSequence
this.latestSequence
);
mmap.sync(this.buffer, 0, INDEX_HEADER_SIZE, mmap.MS_ASYNC);
// Write header to file
fs.writeSync(this.fd, this.headerBuf, 0, INDEX_HEADER_SIZE, 0);
}
syncAll(): void {
if (!this.buffer) return;
if (this.fd === null) return;
// Sync header first
this.syncHeader();
mmap.sync(this.buffer, 0, this.fileSize, mmap.MS_SYNC);
// Sync all file changes to disk
fs.fsyncSync(this.fd);
}
close(): void {
if (!this.buffer || this.fd === null) return;
if (this.fd === null) return;
// 1. Sync all changes
this.syncAll();
mmap.unmap(this.buffer);
fs.closeSync(this.fd);
this.buffer = null;
// 2. Close file descriptor
fs.closeSync(this.fd);
this.fd = null;
// 3. Clean up buffers
this.headerBuf = null;
this.entryBuf = null;
}
getStats() {
return {
path: this.path,
maxEntries: this.maxEntries,
validCount: this.validCount,
writtenCnt: this.writtenCnt,
dataFileSize: this.dataFileSize,
lastSequence: this.lastSequence,
latestSequence: this.latestSequence,
};
}
}

1138
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -14,8 +14,7 @@
],
"dependencies": {
"typescript": "^5.7.0",
"@types/node": "^22.0.0",
"@elilee/mmap-native": "git+https://git.satitech.co.kr/sati-open/sati.n-api.mmap.git"
"@types/node": "^22.0.0"
},
"scripts": {
"prepare": "tsc -p tsconfig.json",