dacV3

package module
v0.1.14 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 31, 2026 License: MIT Imports: 21 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

/media/franky/tiuviweb/go/bin/go run main.go

/media/franky/tiuviweb/go/bin/go mod init dacv3 /media/franky/tiuviweb/go/bin/go get golang.org/x/sys/unix /media/franky/tiuviweb/go/bin/go run main.go

Inicio de doc V3 y mecanismos de recuperación

1° Lectura de WAL Si el tipo de índice es 0 se descarta.

Si el tipo de índice es directo se pide los datos en su offset original y se compara con el checksum; si no coincide se abortan los datos.

Si el tipo de índice es modify se pide los datos que hay en el WAL; si coincide con el checksum se escriben los datos en su origen.

La lectura del WAL sigue orden de secuencia.

2° Lectura e iniciación del almacenamiento global Primero se lee el mapa de almacenamiento global y se lee en las posiciones ocupadas; en caso de no estar ocupada una posición serían datos huérfanos.

3° Lectura e iniciación de índices

Verificar secuencia superior en el índice.

Verificar el checksum.

4º Lectura e iniciacion de pages

Comprobar lista de activados con todos los subindices de paginas, si en la lista se activo pero el subindice esta vacio borrarlo de la lista de activados. (Significa que se reservo un espacio en ese indice pero al final no se escribio)

verificar la version de los subindices de paginas el superior gana

Creacion de indexMaster y gestion del espacio

index master es un mapa de bits donde cada bit respresenta el bloque mas pequeño de la configuracion de bloques

Su unica funcion newIndexs crea indices y reserva el tamaño en el mapa de bits

En caso de falta de espacio tambien amplia el tamaño total del archivo.

Escritura en orden: -primero se guardan los indices directos en el disco -Despues se actualiza el mapa de bit y se guarda en el disco

recuperacion -Cada vez que se inicia hay que verificar el mapa de bits y leer en los bloques ocupados.

APERTURA DE ARCHIVOS Y GESTION DEL TAMAÑO DEL ARCHIVO

Apertura de archivo con cap 0

Abre una pagina minima por ejemplo de tamaño 4096, si el tamaño aumenta
entonces se mueve todo el contenido a un tamaño superior por ejemplo 16384

Esto ocurre hasta llegar al tamaño maximo de pagina de por ejemplo 65536

Cuando llega al tamaño maximo esa pagina hay que moverla a un indice indexado.
En la pagina vez de datos tiene hash que apuntan a indices indexados mas la posicion
exacta de la pagina (hash indice indexado + subindice)

En los indices indexados encontramos los datos

¿Que es es un indice indexado?
significa que en vez de indexar las paginas se indexa el indice y se accede mediante
un mapa indice -> id y despues sabiendo la posicion del id en ese indice

APERTURAS DE ARCHIVOS POR NOMBRE O POR HASH

Primer caso apertura de pagina La ruta se pasa por un hash si existe se abre la pagina si no existe se crea

func openRoute(route [128]byte)

Segundo caso apertura con hash, Se accede directamente a la pagina y si no existe se crea con el hash dado

func openWithHash(hash [32]byte)

Tercer caso las mismas funciones peri si no existe ya el hash devuelve error

func openRouteIfNotExist(route [128]byte)

func openWithHashIfNotExist(hash [32]byte)

ESCRITURAS INDICES

Los indices tienen el doble de su tamaño para hacer pingpong entre uno
Los indices siempre permanecen en memoria y su buffer se reutiliza nunca se elimina

funcionalidades
	Crear un archivo
		funcion -> WritePageDirect
	Eliminar un archivo, escribir datos vacios.
		funcion -> WritePageDirect

ESCRITURAS DATOS

Primer caso la escritura escritura en un offset superior al tamaño del archivo , necesitando una nueva pagina.

-Primero se escriben todos los datos en una pagina nueva
-se boquea solamente en memoria usando field_IndexKeptInit
	funcion -> WritePageDirect


2º Se actualizan los dos indices en disco a la vez usando el wall
	funcion -> WritePageWall

Recuperacion:
Si esta escrito en el wal, se vuelven a escribir los indices y se recupera el nuevo archivo,
si los indices no se han escrito la pagina se queda desbloqueada pero con datos antiguos que
abria que limpiar.

Segundo caso escritura en un offset superior al tamaño del archivo pero sin ser mas grande que el archivo total

-Primero se escribe en el wal , la escritura offset y un checksum con cr32
-Segundo se escriben los datos directos en el archivo
	funcion -> WritePageDirect

-tercero se actualiza el indice con el tamaño del subindice directamente subiendo la secuencia

Recuperacion:
	-Si existe el wall se compara los datos que se han editado con el checksum en caso de que no coincida
	los datos se borran.
	-Si el indice no se actualiza quedan datos huerfanos que al volver ser escritos se actualizarian
	-Si no existe el wall se busca los datos con el checksum y si no coincide se borran.

ADICIONAL:
	Esta escritura permite archivos de grandes puedan ser escritos directamente los datos sin ser reubicados

Tercer caso escritura en un offset inferior al tamaño

-primero se escribe en un wall los datos completos y donde van
-segundo se escribe en la pagina donde corresponda.
	funcion -> WritePageWall

Recuperacion:
	-Si existen los wall se encolan en orden

LECTURA DE DATOS

Primer caso si la pagina no ha sido abierta

	-Primero se busca el hash
	-Se pide un bufer
	-Se sincroniza los datos con el disco

Segundo caso si la pagina ya ha sido abierta

	-Se responde directamente desde el buffer

Tercer caso lecturas de archivos grandes

	- por defeninir

*/

/* https://go.dev/play/

Calculo de tamaño page 32 Calculo de tamaño index 32

package main

import ( "sync" "unsafe" )

type Index struct { mu sync.Mutex isBuffering bool idLocationBuffer uint32 idLocationIndex uint32 offset int64 }

type Page struct {

mu sync.Mutex

sizeFile uint64
isBuffering bool
idBuffer uint32
idIndex uint32
idSubIndex uint8

}

func main() {

p := Page{}

println("El struct ocupa:", unsafe.Sizeof(p), "bytes")

idx := Index{}

println("Tamaño de Index:", unsafe.Sizeof(idx), "bytes")

}

*/

/* Calculo del mapa 78 bytes package main

import ( "encoding/binary" "runtime" )

func main() { var m1, m2 runtime.MemStats

runtime.GC()
runtime.ReadMemStats(&m1)

const totalEntradas = 10000

// ¡AQUÍ ESTÁ LA MAGIA! Le decimos que reserve espacio para 10,000.
files := make(map[[32]byte]int, totalEntradas)

for i := 0; i < totalEntradas; i++ {
	var key [32]byte
	binary.LittleEndian.PutUint64(key[0:8], uint64(i))
	files[key] = i
}

runtime.ReadMemStats(&m2)

totalAlloc := m2.Alloc - m1.Alloc
println("Bytes totales asignados:", totalAlloc)
println("Promedio por entrada (Preasignado):", totalAlloc / totalEntradas, "bytes")

}

*/

/* 4096 * 51 208896

4096 16384 65536 262144 1048576 */

/* Optimizar a partir de datos de entrada como megabytes de escritura del ssd e iops, la operacion es una division 12 KB ≈ 65 000 IOPS 16 KB ≈ 51 200 IOPS 64 KB ≈ 12 800 IOPS

ESto se traduce en 65 operaciones de 12kb por milesima de segundo 12.8 operaciones de 64kb por milesima de segundo

Tamaño para los indices maximo seria 64*4092 = 261888 Tamaño para los datos maximo seria 64000 * 12.8 = 819200 tamaño total 1081088

Pruebas de rendimiento

Las siguientes pruebas comparan DacV3 con otros almacenes de clave-valor integrados en Go: Pebble (CockroachDB), BadgerDB (Dgraph) y bbolt (BoltDB).

Configuración de la prueba

  • Concurrencia: 256 trabajadores paralelos (goroutines)
  • Operaciones: 2000 escrituras concurrentes seguidas de 2000 lecturas concurrentes
  • Durabilidad: Escrituras síncronas (fsync habilitado por transacción/operación en todos los motores)
  • Carga útil: Claves y valores de cadena corta (~14 bytes por registro)

Resultados de rendimiento

Motor Tiempo Total Escritura Promedio Escritura/Op Tiempo Total Lectura Promedio Lectura/Op
DacV3 69,28 ms 34,64 µs 487,10 µs 243 ns
Pebble 19,21 ms 9,60 µs 538,23 µs 269 ns
BadgerDB 967,21 ms 483,60 µs 6,54 ms 3,27 µs
bbolt 2084,10 ms 1,04 ms 2,37 ms 1,18 µs

Metodología y paridad

Para mantener la paridad en todos los motores de almacenamiento probados:

  • Vacío síncrono: Todos los motores se configuraron para vaciar las escrituras directamente en el disco (SyncWrites = true en BadgerDB, pebble.Sync en Pebble y transacciones predeterminadas de un solo escritor en bbolt).

  • Aislamiento: Los temporizadores se iniciaron solo después de que se completara la generación de datos y la configuración del trabajador.

  • Memoria de búfer: Las operaciones de lectura copian los datos en búferes locales del trabajador preasignados para simular el uso en entornos reales y evitar sesgos en la asignación de memoria.

Documentation

Index

Constants

View Source
const (
	Kilobyte = 1024
	Megabyte = Kilobyte * 1024
	Gigabyte = Megabyte * 1024
	Terabyte = Gigabyte * 1024
)
View Source
const (

	//ESCRITURAS
	CrashNewPageBeforeWrite = iota + 1
	CrashNewPageAfterWrite

	//CORRUPCION ESCRITURAS
	CrashNewPageWhileWriteData
	CrashNewPageWhileWriteWalIndex
	CrashNewPageWhileWriteWalData

	//INDICES
	CrashNewPageWhileWriteNewIndex
	CrashNewPageAfterNewIndexWrite
	CrashNewPageWhileWriteOldIndex

	//ESCRITURAS
	CrashPageDirectAfterWrite

	//CORRUPCION ESCRITURAS
	CrashPageDirectWhileWriteData
	CrashPageDirectWhileWriteWalIndex
	CrashPageDirectWhileWriteWalData

	//INDICES
	CrashPageDirectWhileWriteIndex

	//ESCRITURAS
	CrashPageWalAfterWrite

	//CORRUPCION ESCRITURAS
	CrashPageWalWhileWriteData
	CrashPageWalWhileWriteWalData
	CrashPageWalWhileWriteWalIndex

	//INDICES
	CrashPageWalWhileWriteIndex

	//ESCRITURA DE DATOS OFFSET REAL
	CrashWriteUnsafeCorrupt

	//ESCRITURA INDICES EN EL WAL
	CrashWriteWallIndexCorrupt

	//ESCRITURA DATOS EN EL WAL
	CrashWriteWallCorrupt

	//ESCRITURA INDICES DE PAGINAS
	CrashWriteIndexCorrupt
)
View Source
const BufferAlignMask = BufferAlignSize - 1
View Source
const BufferAlignSize = 4096 // Tamaño de bloque típico en Linux (ext4/XFS)
View Source
const FieldSizeUUIDString = 64
View Source
const IndexOverheadBlocks int64 = 4

4 bloques fijos de 4096 perdidos para índices

View Source
const MaxSubIndexPerIndex = 82

maximo de subindices por indice 4096

View Source
const Test bool = false

Variables

View Source
var (
	ErrNegativeOffset = errors.New("offset cannot be negative")
	ErrBufferOverflow = errors.New("data exceeds buffer capacity")
)
View Source
var CrashNames = map[int]string{

	CrashNewPageBeforeWrite:        "CrashNewPageBeforeWrite",
	CrashNewPageAfterWrite:         "CrashNewPageAfterWrite",
	CrashNewPageWhileWriteData:     "CrashNewPageWhileWriteData",
	CrashNewPageWhileWriteWalIndex: "CrashNewPageWhileWriteWalIndex",
	CrashNewPageWhileWriteWalData:  "CrashNewPageWhileWriteWalData",
	CrashNewPageWhileWriteNewIndex: "CrashNewPageWhileWriteNewIndex",
	CrashNewPageAfterNewIndexWrite: "CrashNewPageAfterNewIndexWrite",
	CrashNewPageWhileWriteOldIndex: "CrashNewPageWhileWriteOldIndex",

	CrashPageDirectAfterWrite:         "CrashPageDirectAfterWrite",
	CrashPageDirectWhileWriteData:     "CrashPageDirectWhileWriteData",
	CrashPageDirectWhileWriteWalIndex: "CrashPageDirectWhileWriteWalIndex",
	CrashPageDirectWhileWriteWalData:  "CrashPageDirectWhileWriteWalData",
	CrashPageDirectWhileWriteIndex:    "CrashPageDirectWhileWriteIndex",

	CrashPageWalAfterWrite:         "CrashPageWalAfterWrite",
	CrashPageWalWhileWriteData:     "CrashPageWalWhileWriteData",
	CrashPageWalWhileWriteWalData:  "CrashPageWalWhileWriteWalData",
	CrashPageWalWhileWriteWalIndex: "CrashPageWalWhileWriteWalIndex",
	CrashPageWalWhileWriteIndex:    "CrashPageWalWhileWriteIndex",

	CrashWriteUnsafeCorrupt:    "CrashWriteUnsafeCorrupt",
	CrashWriteWallIndexCorrupt: "CrashWriteWallIndexCorrupt",
	CrashWriteWallCorrupt:      "CrashWriteWallCorrupt",
	CrashWriteIndexCorrupt:     "CrashWriteIndexCorrupt",
}

Mapa inverso: ID numérico -> Nombre legible del Crash

View Source
var ErrCorruptedData = errors.New("el checksum no coincide")
View Source
var ErrNoSpaceAllocated = errors.New("no se pudo asignar espacio tras agotar todos los intentos y tamaños")
View Source
var ErrServerBusy = errors.New("server busy")
View Source
var TestCrashEnergiChan = make(chan bool)
View Source
var TestCrashEnergy int64
View Source
var TestCrashTarget atomic.Int64

Functions

func BoolToBytes

func BoolToBytes(value bool) []byte

func BytesToBool

func BytesToBool(buffer []byte) bool

func BytesToComplex64

func BytesToComplex64(buffer []byte) complex64

func BytesToComplex128

func BytesToComplex128(buffer []byte) complex128

func BytesToFloat32

func BytesToFloat32(buffer []byte) float32

func BytesToFloat32Array

func BytesToFloat32Array(buffer []byte) []float32

func BytesToFloat64

func BytesToFloat64(buffer []byte) float64

func BytesToFloat64Slice

func BytesToFloat64Slice(buf []byte) []float64

func BytesToInt

func BytesToInt(buffer []byte) int

func BytesToInt8

func BytesToInt8(buffer []byte) int8

func BytesToInt16

func BytesToInt16(buffer []byte) int16

func BytesToInt32

func BytesToInt32(buffer []byte) int32

func BytesToInt64

func BytesToInt64(buffer []byte) int64

func BytesToRune

func BytesToRune(buffer []byte) []rune

func BytesToTypesGolang

func BytesToTypesGolang(buffer []byte, outRef interface{}) error

func BytesToUint8

func BytesToUint8(buffer []byte) uint8

func BytesToUint16

func BytesToUint16(buffer []byte) uint16

func BytesToUint32

func BytesToUint32(buffer []byte) uint32

func BytesToUint64

func BytesToUint64(buffer []byte) uint64

func Complex64ToBytes

func Complex64ToBytes(value complex64) []byte

func Complex128ToBytes

func Complex128ToBytes(value complex128) []byte

func CrashName added in v0.1.13

func CrashName(crashID int) string

CrashName devuelve el nombre del crash o un string genérico si no existe

func Float32ArrayToBytes

func Float32ArrayToBytes(values []float32) []byte

func Float32ToBytes

func Float32ToBytes(value float32) []byte

func Float64SliceToBytes

func Float64SliceToBytes(value []float64) []byte

func Float64ToBytes

func Float64ToBytes(value float64) []byte

func GetCheckSum

func GetCheckSum(index []byte, data []byte) error

GetCheckSum lee el checksum guardado en index y lo compara con el calculado a partir de data

func GetCheckSumIndex added in v0.1.13

func GetCheckSumIndex(index []byte) error

GetCheckSumIndex lee el checksum del índice y verifica su integridad

func GetDataLenWall added in v0.1.13

func GetDataLenWall(index []byte) int64

func GetHashWallData added in v0.1.13

func GetHashWallData(index []byte) [32]byte

func GetOffsetData

func GetOffsetData(index []byte) (int64, int64, error)

GetOffsetData recupera los valores de 'init' y 'end' desde el buffer index

func GetOffsetWalData

func GetOffsetWalData(index []byte) (int64, int64, error)

func GetRelativeOffsetWall added in v0.1.13

func GetRelativeOffsetWall(index []byte) int64

func GetSequence added in v0.1.14

func GetSequence(index []byte) uint64

GetSequence lee el número de secuencia almacenado en el índice WAL

func Int8ToBytes

func Int8ToBytes(value int8) []byte

func Int16ToBytes

func Int16ToBytes(value int16) []byte

func Int32ToBytes

func Int32ToBytes(value int32) []byte

func Int64ToBytes

func Int64ToBytes(value int64) []byte

func IntToBytes

func IntToBytes(value int) []byte

func JsonBytesToTypesGolang

func JsonBytesToTypesGolang(buffer []byte, outRef interface{}) error

func MakeAlignedBlock

func MakeAlignedBlock(size int) []byte

AlignedBlock crea un buffer de tamaño 'size' alineado a 4096 bytes.

func NewUUID

func NewUUID() string

1. Generador aleatorio de String (64 caracteres)

func NewUUIDBytes

func NewUUIDBytes() [32]byte

2. Generador aleatorio de Bytes (32 bytes puros)

func NewUUIDSheed

func NewUUIDSheed(key []byte) string

5. El corazón del sistema: BLAKE3 (Seguridad absoluta de 32 bytes)

func NewUUIDSheedBytes

func NewUUIDSheedBytes(key []byte) [32]byte

func ParseUUIDBytes

func ParseUUIDBytes(s string) ([32]byte, error)

3. Parsear String a Bytes (Solo acepta cadenas de 64 caracteres exactos)

func RunesToBytes

func RunesToBytes(runes []rune) []byte

func SetCheckSum

func SetCheckSum(index []byte, data []byte)

SetCheckSum calcula el checksum de data y lo escribe en la sección de checksum de index

func SetCheckSumIndex added in v0.1.13

func SetCheckSumIndex(index []byte)

SetCheckSumIndex calcula el checksum de los metadatos del índice y lo escribe

func SetDataLenWall added in v0.1.13

func SetDataLenWall(dataLen int64, index []byte)

func SetHashWallData added in v0.1.13

func SetHashWallData(hash [32]byte, index []byte)

func SetOffsetData

func SetOffsetData(init int64, end int64, index []byte) error

func SetOffsetWalData

func SetOffsetWalData(init int64, end int64, index []byte) error

func SetRelativeOffsetWall added in v0.1.13

func SetRelativeOffsetWall(offset int64, index []byte)

func SetSequence added in v0.1.14

func SetSequence(sequence uint64, index []byte)

SetSequence escribe el número de secuencia en el índice WAL

func SetTypeIndexWall

func SetTypeIndexWall(typeIndex IndexWallType, index []byte)

SetTypeIndexWall escribe el tipo de Wall en la posición correspondiente (offset 4)

func TypesGolangToBytes

func TypesGolangToBytes(valueIn interface{}) ([]byte, error)

func TypesGolangToJsonBytes

func TypesGolangToJsonBytes(valueIn interface{}) ([]byte, error)

func UUIDToString

func UUIDToString(id [32]byte) string

4. Formatear Bytes a String (Texto plano Hexadecimal, hiper rápido)

func UUIDToStringParts

func UUIDToStringParts(id [32]byte) (shard1, shard2, uuidStr string)

func Uint8ToBytes

func Uint8ToBytes(value uint8) []byte

func Uint16ToBytes

func Uint16ToBytes(value uint16) []byte

func Uint32ToBytes

func Uint32ToBytes(value uint32) []byte

func Uint64ToBytes

func Uint64ToBytes(value uint64) []byte

Types

type ConcurrentMap added in v0.1.9

type ConcurrentMap[V any] struct {
	ShardMask uint16
	// contains filtered or unexported fields
}

ConcurrentMap con valor genérico

func NewConcurrentMap added in v0.1.9

func NewConcurrentMap[V any](numShards int) *ConcurrentMap[V]

NewConcurrentMap recibe el número total de shards (potencia de 2)

func (*ConcurrentMap[V]) Clear added in v0.1.13

func (m *ConcurrentMap[V]) Clear()

func (*ConcurrentMap[V]) Get added in v0.1.9

func (m *ConcurrentMap[V]) Get(key [32]byte) (V, bool)

func (*ConcurrentMap[V]) StoreOrGet added in v0.1.9

func (m *ConcurrentMap[V]) StoreOrGet(key [32]byte, allocator func() V) V

type DacV3 added in v0.1.10

type DacV3 struct {
	PendingCorrupt []WalCorruptEntry
	// contains filtered or unexported fields
}

func InitDacV3 added in v0.1.8

func InitDacV3(opts DacV3Options) *DacV3

func (*DacV3) CheckIndexPage added in v0.1.12

func (sfDacV3 *DacV3) CheckIndexPage(sfIndexHandle *indexHandle, sfPageHandle *pageHandle)

func (*DacV3) CheckIndexPageFromHash added in v0.1.12

func (sfDacV3 *DacV3) CheckIndexPageFromHash(hash [32]byte) (err error)

func (*DacV3) Clear added in v0.1.13

func (sfDacV3 *DacV3) Clear()

func (*DacV3) CreatePageInIndex added in v0.1.10

func (sfDacV3 *DacV3) CreatePageInIndex(hash [32]byte, requiredSpace uint32) (sfIndexHandle *indexHandle, newIdIndex uint32, newIdSubIndex uint8, err error)

func (*DacV3) ExpandSize added in v0.1.10

func (sf *DacV3) ExpandSize(newSize int64)

func (*DacV3) GetSizeForIndex added in v0.1.11

func (sfDacV3 *DacV3) GetSizeForIndex(requiredSpace uint32) (size uint32)

func (*DacV3) InitAllPagesPerIndex added in v0.1.10

func (sfDacV3 *DacV3) InitAllPagesPerIndex(idIndex uint32, index *Index)

ESTA FUNCION ESTA MAL DEBUGEAR MIENTRAS DEBUGEO LOS WRITES Inicia todas las paginas de un indice, añadie su id y posicion al mapa de datos pero no el buffer Si el indice es indexSearch no se inicia

func (*DacV3) LoadIndex added in v0.1.10

func (sfDacV3 *DacV3) LoadIndex(index *Index) (*indexBuffer, error)

LoadIndex Refresca el buffer del índice Nota: Se ha añadido el retorno de 'error' para no fallar silenciosamente si hay corrupción.

func (*DacV3) NewWorkerPool added in v0.1.10

func (sfDacV3 *DacV3) NewWorkerPool(numWorkers int,
	queueSize int,
	walSequence uint64,
	walLenIndexBytes int64,
	numOfBuffersWal int,
	walLenTotalBytes int64,
	walBuffersTotal [][]byte)

func (*DacV3) ReadAt added in v0.1.10

func (sfDacV3 *DacV3) ReadAt(data []byte, offset int64)

func (*DacV3) ReadPage added in v0.1.10

func (sfDacV3 *DacV3) ReadPage(hash [32]byte, data []byte, offset int64) (n int, err error)

func (*DacV3) ReadPageIfExist added in v0.1.12

func (sfDacV3 *DacV3) ReadPageIfExist(hash [32]byte, data []byte, offset int64) (n int, err error)

func (*DacV3) Size added in v0.1.13

func (sfDacV3 *DacV3) Size(hash [32]byte) (size int64, err error)

func (*DacV3) Stop added in v0.1.10

func (sfDacV3 *DacV3) Stop()

func (*DacV3) SwapIndexDirection added in v0.1.12

func (sfDacV3 *DacV3) SwapIndexDirection(sfIndexOld *indexHandle, idSubIndexOld uint8, sfIndexNew *indexHandle, idSubIndexNew uint8, newSize int64)

func (*DacV3) UpdatePageInIndex added in v0.1.11

func (sfDacV3 *DacV3) UpdatePageInIndex(idSubIndexCurrent uint8, requiredSpace uint32) (sfIndexHandle *indexHandle, newIdIndex uint32, newIdSubIndex uint8, err error)

func (*DacV3) WriteAt added in v0.1.10

func (sfDacV3 *DacV3) WriteAt(data []byte, offset int64)

func (*DacV3) WriteAtSync added in v0.1.10

func (sfDacV3 *DacV3) WriteAtSync(data []byte, offset int64)

func (*DacV3) WriteDirect added in v0.1.10

func (sfDacV3 *DacV3) WriteDirect(hash [32]byte, relativeOffset int64, dataLen int64, idDataArena uint32, data []byte, offset int64) error

func (*DacV3) WriteDirectIo added in v0.1.14

func (sfDacV3 *DacV3) WriteDirectIo(hash [32]byte, relativeOffset int64, dataLen int64, idDataArena uint32, data []byte, offset int64) error

ESCRITURA: 1º - Escribe primero un checksum en el wal e envia la respuesta como completado 2º - De manera asincrona en el siguiente ciclo de wal escribe los datos en su pagina original

RECUPERACION

  • se lee el indice wal y se recupera el checksum y se compara con el bloque de datos en la pagina original -si es positivo no se hace nada -Si es negativo los datos se borran

direct no es compatible con Batching

func (*DacV3) WriteIfExistPage added in v0.1.10

func (sfDacV3 *DacV3) WriteIfExistPage(hash [32]byte, data []byte, offset int64) error

func (*DacV3) WriteIndex added in v0.1.10

func (sfDacV3 *DacV3) WriteIndex(data *indexBuffer, offset int64, onCopy func())

-Esta funcion escribe los datos directos en el origen sin validacion de ningun tipo. -

func (*DacV3) WriteIndexMaster added in v0.1.10

func (sfDacV3 *DacV3) WriteIndexMaster(data []byte, offset int64) error

func (*DacV3) WritePage added in v0.1.10

func (sfDacV3 *DacV3) WritePage(hash [32]byte, data []byte, offset int64) error

func (*DacV3) WritePageDirect added in v0.1.10

func (sfDacV3 *DacV3) WritePageDirect(hash [32]byte, relativeOffset int64, dataLen int64, data []byte, offset int64, onCopy func()) error

WritePageDirect escribe datos de forma directa utilizando los buffers de la arena. onCopy (opcional) se invoca tan pronto como la copia en memoria finaliza, permitiendo al invocador liberar mutexes u otros bloqueos antes del I/O.

func (*DacV3) WritePageWall added in v0.1.10

func (sfDacV3 *DacV3) WritePageWall(hash [32]byte, relativeOffset int64, dataLen int64, data []byte, offset int64, onCopy func()) error

func (*DacV3) WriteUnSafeAsync added in v0.1.10

func (sfDacV3 *DacV3) WriteUnSafeAsync(jTask *jobWriterTask)

ESCRITURA 1º - Se escribe directamente los datos en el orgigen, esta funcion es de uso exclusivo interno

func (*DacV3) WriteUnSafeAsyncPriority added in v0.1.14

func (sfDacV3 *DacV3) WriteUnSafeAsyncPriority(jobWriterItem *jobWriter)

func (*DacV3) WriteUnSafeSync added in v0.1.10

func (sfDacV3 *DacV3) WriteUnSafeSync(jTask *jobWriterTask) error

ESCRITURA 1º - Se escribe directamente los datos en el orgigen, esta funcion es de uso exclusivo interno con respuesta

func (*DacV3) WriteWall added in v0.1.10

func (sfDacV3 *DacV3) WriteWall(hash [32]byte, relativeOffset int64, dataLen int64, idDataArena uint32, data []byte, offset int64) error

func (*DacV3) WriteWallBath added in v0.1.10

func (sfDacV3 *DacV3) WriteWallBath(tasks []jobWriterTask) error

Escritura del wall por lotes

type DacV3Options

type DacV3Options struct {
	DacRoute               string
	Truncate               bool
	SizeIndexMaster        int
	MaxReserveSize         int64
	SsdNIopsMili           uint32
	NBuffersAvailableIndex uint32

	NChanAvaibleIndexSearch      uint32
	NBuffersAvailableIndexSearch uint32

	NBuffersAvailableIndexSearchData uint32
	SupportedSizes                   []SizeConfig
	NWorkers                         int
	QueueSize                        int
	// contains filtered or unexported fields
}

func NewDacV3Options added in v0.1.11

func NewDacV3Options(diskPath string, truncate bool, multiplierChan uint32) DacV3Options

DefaultDacV3Options devuelve la configuración por defecto para DacV3.

type GlobalBuffer added in v0.1.9

type GlobalBuffer struct {
	// contains filtered or unexported fields
}

GlobalBuffer representa la estructura de control que maneja el segmento de buffer, sus límites y su estado dentro del pool.

func (*GlobalBuffer) CopyAt added in v0.1.9

func (pb *GlobalBuffer) CopyAt(offset int64, data []byte) error

WriteAt escribe datos en un offset específico. Retorna un error si se intenta escribir fuera de los límites actuales del buffer.

type GlobalBufferPool added in v0.1.9

type GlobalBufferPool struct {
	// contains filtered or unexported fields
}

GlobalBufferPool unifica el pool indexado dinámicamente de estructuras de control junto con el gestor de asignación física de memoria (arena) para los buffers.

func NewGlobalBufferPool added in v0.1.9

func NewGlobalBufferPool(chunkSize uint32, blocksPerArena uint32, blockSize int64) *GlobalBufferPool

NewGlobalBufferPool inicializa el pool combinado con tamaños definidos en tiempo de ejecución.

blockSize: tamaño del buffer alineado que se va a recibir, por ejemplo 4096 blocksPerArena: Es el número de blockSize que caben en una sola ARENA de RAM chunkSize: Es simplemente la cantidad de estructuras de Go (GlobalBuffer) que se guarda en un arreglo de metadatos

func (*GlobalBufferPool) Free added in v0.1.9

func (p *GlobalBufferPool) Free(id uint32)

Free libera el buffer y la estructura del pool, dejándolos disponibles para reuso.

func (*GlobalBufferPool) Get added in v0.1.9

func (p *GlobalBufferPool) Get(id uint32) *GlobalBuffer

Get devuelve el puntero al GlobalBuffer según el ID de usuario provisto.

func (*GlobalBufferPool) New added in v0.1.9

func (p *GlobalBufferPool) New() (uint32, *GlobalBuffer)

New solicita una estructura GlobalBuffer y le asocia un bloque de memoria []byte de la arena.

type Index

type Index struct {
	// contains filtered or unexported fields
}

Indice en array necesita su offset para poder eliminar el buffer y volver abrir el buffer cuando se use

type IndexPoolItem added in v0.1.11

type IndexPoolItem struct {
	IDIndex        uint32
	AvailableSlots uint8 // Número de slots vacíos disponibles en este índice
}

type IndexSearch added in v0.1.6

type IndexSearch struct {
	// contains filtered or unexported fields
}

No necesita mutex ya que depende de otra pagina padre

type IndexWallType

type IndexWallType byte
const (
	// Puedes renombrar "TypeA", "TypeB", "TypeC" por nombres que describan su uso
	WallDirectType IndexWallType = 1
	WallModifyType IndexWallType = 2
)

2. Definimos las tres constantes para los tres tipos de Wall

func GetTypeIndexWall

func GetTypeIndexWall(index []byte) IndexWallType

GetTypeIndexWall lee la posición correspondiente (offset 4) y la retorna como IndexWallType

type MapShard added in v0.1.9

type MapShard[V any] struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

MapShard ahora tiene la clave fija a [32]byte, y el valor genérico V

type Page

type Page struct {
	// contains filtered or unexported fields
}

Datos

type PagedPool

type PagedPool[T any] struct {
	// contains filtered or unexported fields
}

PagedPool es el gestor principal genérico con tamaño dinámico y reuso de IDs

func NewPoolArray added in v0.1.7

func NewPoolArray[T any](chunkSize uint32) *PagedPool[T]

NewPoolArray Constructor genérico con tamaño de bloque dinámico

func (*PagedPool[T]) Clear added in v0.1.13

func (p *PagedPool[T]) Clear()

func (*PagedPool[T]) Delete added in v0.1.9

func (p *PagedPool[T]) Delete(id uint32)

Delete libera el elemento, limpia su memoria y permite su posterior reuso

func (*PagedPool[T]) Get

func (p *PagedPool[T]) Get(id uint32) *T

Get devuelve el puntero al elemento de forma concurrente y segura

func (*PagedPool[T]) New

func (p *PagedPool[T]) New() (position uint32, itemPoint *T)

New obtiene un espacio disponible en el pool (nuevo o reutilizado)

type SizeConfig

type SizeConfig struct {
	Size                uint32
	IndexSizeChan       uint32
	NBuffersAvaibleData uint32
}

type SubIndex

type SubIndex struct {
	// contains filtered or unexported fields
}

type WalAppend

type WalAppend struct {
	// contains filtered or unexported fields
}

type WalCorruptEntry added in v0.1.13

type WalCorruptEntry struct {
	Hash           [32]byte // O []byte si prefieres slices dinamicos
	OffsetRelative int64
	// contains filtered or unexported fields
}

type WalUpdateEntry added in v0.1.13

type WalUpdateEntry struct {
	Hash           [32]byte // O []byte si prefieres slices dinamicos
	OffsetRelative int64
	Offset         int64
	Data           []byte
}

type WalZeroCopy

type WalZeroCopy struct {
	// contains filtered or unexported fields
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址