d3x0r/sack.vfs
حول
Node addon which adds a virtual file system interface; websockets; json(6) parsing; sql support(sqlite,odbc); javascript sched_yield; ssl certificate generation; more...
البيانات والتحليلاتالنمو المقاس للنجوم
- خلال 24 ساعة
- ٠
- خلال 7 أيام
- ٠
- خلال 15 يومًا
- ٠
- خلال شهر
- جارٍ جمع السجل
تغيّر صافي النجوم خلال فترات متداخلة، وليس مجموعًا يوميًا. تبقى القياسات المفقودة فارغة. النجوم تقيس الاهتمام لا جودة البرمجيات.
README.md
الأصلsack.vfs
Quick summary of features/subsystems.
- WebSocket/HTTP/HTTPS network library. UDP sockets (
http,UDPreplacment). - JSON/JSON6 (stream)parser,
- JSOX (streaming) parser,
- Node addon for a custom virtual and physical file system interface (fs replacement).
- USB keyboard raw input (windows)
- Graph Database and Object Storage.
- Primitive Natural Language tokenizer, and attributed text type.
- OpenSSL/LibreSSL Certificate Generation (https, wss).
- Salty Random Generator - procedural random content generator.
- Simple Play a Sound. (windows, but can port to openAl and cross platform)
- Process control; launch and control tasks launched.
- Sqlite/ODBC database driver; minimal SQL interface,
openanddo. - Option/Configuration Database support using sqlite/odbc interface; stores in a heirarchy of options per program and global.
- Monitor filesystem for changes to files (caching server update).
- Configuration file parser/log analyzer based on word token matches.
- opt-out per-worker access to tasks and filesystem access.
Requirements
All Systems
- Node.
npm install -g node-gyp- a working build environment
- (win32)
npm install -g windows-build-tools- if these are not initially installed, it will require a system restart, without any visible notice; but the install will not complete until restarted. - ninja, gcc
- (win32)
- (opt)
npm install -g cmake-jsandcmake.
ODBC and uuid support. (can be disabled)
ODBC connectivity is provided as an alternative to the sqlite interface, providing connectivity with all existing databases. It is not required; Sqlite itself is not 'required' but special steps have to be taken to disable it. When enabled, the SACK library uses it to configure some runtime options. Options may be controlled by an 'interface.conf' configuration file.
Various Linux
- yum install gcc-c++ libuuid-devel unixodbc-devel
- (uuid/uuid.h sql.h)
- apt-get install uuid-dev unixodbc-dev
- (uuid/uuid.h sql.h)
- pacman -S unixodbc util-linux
- (sql.h uuid/uuid.h(probably already available, fs2util) )
- (?)emerge unixodbc
Mac
- (ODBC might be optioned out; just uses sqlite typically)
- brew (brew install unixODBC)
Windows
- None additional
Usage
const sack = require( 'sack.vfs' );
import {SACK} from "sack.vfs";
Overview of SACK Namespace Object
{
ComPort(comport) - access to com ports.
JSOX - A jsox parser. (JSON5/6 input compatible)
parse(string) - result with a V8 object created from the json string.
stringify(obj [,stringifer [,formatter])
begin( cb ) - begin parsing JSOX stream; callback is called as each value is completed.
stringifier() - create a reusable stringifier which can be used for custom types
JSON6 - A json6 parser. (JSON5 input compatible)
parse(string [,reviver]) - result with a V8 object created from the json string.
begin( cb ) - begin parsing JSON6 stream; callback is called as each value is completed.
stringify(obj [,stringifer [,formatter])
JSON - A json parser.
parse(string) - result with a V8 object created from the json string.
begin( cb ) - begin parsing JSON stream; callback is called as each value is completed.
Sqlite(dbName) - an interface to sqlite which can open databases in the volume.
parameters - ( databaseName )
databaseName maybe a simple ODBC name; if the name ends with .db, it is assumed to be
a sqlite database. If ODBC is not available, it may be assumed that the name will
just be a sqlite database name. Extra syntax - if the name starts with a $, then the
next word after $ and before the next @ or $ is used to select a sqlite vfs name.
( https://sqlite.org/vfs.html )
if the name is 'sack' then after @ and before the next $ is specified a mounted filesystem name.
Sqlite has methods available on it to access native program options.
Sqlite.op( opName, defaultValue ) - read/write default option database option.
Sqlite.so( opName, newValue ) - write new value to default option database.
ObjectStorage( fileName [, version] ) - open a JS object storage database.
Volume([mountName,]fileName[,version]) - a virtual disk partition that holds files.
mountName - the mount name used to mount to volume as a filesystem; it may be referenced
later in the string passed to Sqlite. It may be `null` if it is anonymous mount.
if no parameters are passed, a Volume object representing the native filesystem is returned.
Volume.mkdir(pathname) - utility function to make directories which might not exist before volume does;
(Volume() auto creates directories now if specified path to filename does not exist)
parameters - (pathname)
path to create- will created missing parent path parts too.
Volume.readAsString( filename ) - memory map map a file from native filesystem as a utf8 string.
Volume.mapFile( filename, loaded_callback ) - memory map map a file from native filesystem as an arrayBuffer.
if loaded callback is specified, a thread is created that touches every page in the file, when it's done
the callback is called with no parameters.
File - some native filsystem utility methods(?)
FileMonitor - receive event notifications when files change
SaltyRNG(feed salt callback) - creates a random number generator
TLS - namespace for utilities to generate certificates/keys
genkey( length [,password]) - Generates a keypair
pubkey( {options} ) - gets public key of a keypair or certificate
gencert( { options } ) - Generates a self signed certificate.
genreq( {options} ) - Generates a certification request
signcert( {options} ) - uses a certificate to sign a certificate request
validate( {options} ) - validate a certificate against a certificate chain.
expiration( certificate ) - gets the expiration of a certificate as a Date().
WebSocket - Websocket interface
Client( ... ) - create a websocket client
Server( ... ) - create a websocket server
Thread - Helper functions to transport accepted clients to other threads.
post( accepted_socket, unique_destination_string ) - posts a socket to another thread
accept( unique_destination_string, ( newSocket )=>{} ) - receives posted accepted sockets
HTTP - HTTP Request Method
get( {options} ) - synchronous http request
HTTPS - HTTPS Request Method
get( {options} ) - synchronous https request
Network - Raw network utilities
Address( address [,port] ) - holder for network addresses.
UDP( ... ) - UDP Socket to send/received datagrams.
Config - Process configuration files; also streaming text parsing
(methods)[#Config_Methods]
ComPort - (see below)
System - Namespace for SACK system interface routines (The above methods should be moved into this namespace)
createMemory(name,byte size) - creates a named memory region; memory regions by name are shared on the system.
openMemory(name) - opens an existing names region; returns an ArrayBuffer which can be mapped to a typed array by application.
enableThreadFileSystem() - enables mounting file systems specifically for this thread
allowSpawn() - returns task allowed state
disallowSpawn() - disble task spawns for this thread
dumpRegisteredNames() - dumps internal procedure/interface registry
reboot() - on windows, trigger a reboot.
Task(options) - an interface for createing and monitoring tasks.
Task constructor takes an option object.
end() - cause a task to exit..
write() - send something to a task.
send() - send something to a task.
terminate() - terminate created task.
// windows only
registry - an interface to windows registry options
set( path, value ) - set a new value in the registry
get( path ) - get a value from the registry.
hid - raw keyboard interface, allows identification of different physical keyboard devices.
log(string) - log a string.
memDump() - log memory stats (track module memory leaks)
mkdir() - make a directory in the current path; handles recursive directory creation.
u8xor(s,k) - utility function to apply a string mask.
b64xor(s,k) - utility function to just xor a value into a base64 string without expanding the values.
id() - generate a unique ID (256 bits, 32 bytes, 44chars, trailing '=').
Id() - generate a short unique ID (12 bytes, 16chars).
loadComplete() - Indicate to SACK system that this is completed loading (task summoner support;linux;deprecated)
/* if( isolated )... */
setTimeout(fn,delay ) - same as JS function of same name (on sack object) (returns a number ID)
setInterval(fn,delay) - same as JS function of same name (returns a number ID)
clearTimeout( timeout_id )
clearInterval( timeout_id )
}
Interfaces
- Volume
- SQLite
- Object Storage
- JSON/JSON6/JSOX
- Websocket Server
- Websocket Client
- HTTP Requests
- UDP - Low level system UDP sockets.
- TCP - Low level system TCP sockets.
- ICMP - ICMP interface (name lookup and ping)
- TLS - certificate creation and validation
- Task - Process creation/control/information
- SSH - SSH connection interface
- ComPort - COM port IO
- File Changes - Monitors files for changes
- Sound - sound device and playback interface
- Misc... - Other
GUI Interfaces
These are available when building the GUI version.
- PSI; Image, Image.Color, Render, Intershell, Frame, Registration.
Quick App Helpers
Http/Websocket - simple script to handle basic resource requests, and provide a websocket endpoint interface. User supplies
accept()andconnect()callbacks. Also includes basic express-like interface addon.PRNG - Small seedable RNGs.
Events - Small event subscription/dispatch class
dbUtil - database utilities to read schema from database; builds JS objects representing table structures which can be queried for structure.
summoner - (experimental/example) this launches and tracks other tasks.
task-manager - Runs tasks, provides a simple UI which can get the tasks' logs and control run state of tasks.
Node JS Loader Support
Node loader hooks for .json6 and .jsox file types.
This loader does an import of sack.vfs and sets globalThis.SACK with the result; and then also assigns
globalThis.JSOX and globalThis.JSON6.
The loader hooks are loaded with the option
--experimental-loader=node_modules/sack.vfs/import.mjs
Previously support for .json6 and .jsox were only provided for require().
Loading either JS version of JSON6 or JSOX should be done after this, allowing them to replace the globalThis versions.
The sack.vfs version is still available via SACK.JSOX or SACK.JSON6.
Performance-wise the JS versions have advantages if the information to parse is sourced in JS, while the SACK versions can operate directly on the array buffers loaded from SACK databases, Volumes and files. Which limits the copy one side; otherwise there's a conversion to string from binary and a copy of that string from JS to C potentially.
Loader also supports fetching files over HTTP:// and HTTPS:// (or http:// and https://). This performs a request, and then sends the result as the loaded module.
As a further feature, since web files often just use .js as the extension for modules, and everything loaded from a type="module" script is loaded as a module,
the loader supports loading from module://./ (the '.' is important, since really the host is always this computer, and becomes part of the requests when a module loads another module).
The module://./ prefix is substituted, and uses environment variables RESOURCE_PATH for where to load default files, if the file path starts with /common then COMMON_PATH environment
variable is prepended to the file, and /node_modules file prefix uses NODE_MODULE_PATH environment variable to load modules; native modules will probably not load this way, but typical
javascript modules can be loaded this way.
There is a race condition, if http(s):// is used from the local server, then the loading might stall waiting for the server to become available; this is the reason
that module:// support was added. TODO: Fix stall, workaround, use module:// instead of http(s):// for local files loaded from a self contained server.
Changelog
- 1.3.135(in progress)
- JSOX: read an object or array used as an object key --
map{{id:1}:x},map{[1,2]:x}. The parser hands the key's text up with a newbNameIsComplexflag and the addon parses it as a document of its own; previouslymap{{id:1}:x}came back as a circularMap(0)andmap{[1,2]:x}was rejected, so a Map the JS library wrote could not be read back here. A type that accepts such a key is required -- a plain object would turn it into[object Object], which is what the syntax exists to replace. - JSOX: fixed an array as the value under a key in a
maparriving empty (map{x:[7,8]}gave'x' => []); the elements were filled in after the array had been read back out of the Map by property name, which a Map entry is not. - JSOX: fixed
Tag{}-- a tag with nothing between the brackets -- producing no value. An empty body cannot be a class definition, since a definition with no fields names nothing, so it is read as a tagged object with no fields:map{}(how an empty Map is written) came back as "Pending value could not complete", and in a streamfoo{a:1} foo{}quietly delivered only the first value. - JSOX:
stringifynow writes aMapkey that has no text form of its own -- an object, an array, a boolean, a BigInt -- instead of failing in the field-name code. - JSOX: a tag ahead of an object or array used as a key is part of that key:
map{tag{a:1}:x},map{ref[1]:x},map{ab[AAA]:x}. The key's text is collected from the bracket, and the bracket alone started it, so a tag defeated it and the bracket opened a value instead --map{tag{a:1}:5}failed as a duplicate colon, and the other two silently came back as empty Maps. A reference used as a key now says so: the text is parsed as a document of its own, and there is no outer document there for the path to point into. - Lists grow by doubling instead of by a fixed 8 slots, so a list that keeps growing is reallocated and copied O(log n) times rather than every 8 items. A list that never passes 8 items -- most of them -- is unchanged.
- JSON6: fixed a parse state leaked by every
JSON6.parse(). The parser is kept with the message it produced and released byjson6_dispose_message(), butjson_dispose_message()was called instead, which frees the message and leaves the parser pending -- so a loop of parses accumulated one parse state each, untilCreate view of file for memory access failed/Failed to expand space. The number benchmarks could not finish; they now run in full. Also disposes the message on theMultiple values would resultpath, which disposed nothing at all. - JSON, JSON6, JSOX and VESL: a parse state taken from the pool now clears the string gatherer's own state -- the escape, hex, unicode-wide and octal flags that have to live across a
write()that splits a string. A document that ended part-way through an escape poisoned the next parse to reuse that state, so a plain"\n\r"could come back as the faultparsing hex of \x. Nothing showed this while a finished state was never returned to the pool, since every parse then got untouched memory. json6_get_message_parser()returned the list node cast to a parse state, where the node's first member is the message rather than the state. It has never had a caller.- JSON, JSON6, JSOX and VESL: fixed a leak of one accumulator per unclosed container level in a document that fails to parse. A document that ends inside an object or array leaves the enclosing levels' accumulators parked on their parse contexts, since the close that would have restored them never came; the dispose popped those contexts without freeing them, so
{a:{a:{a:leaked three datalists every time it was parsed. 50,000 failed parses cost 62MB (JSON6), 51MB (JSON) and 42MB (JSOX) and climbed without limit; memory now plateaus. - New
system.memStats()returns the allocator's four aggregates --{ free, used, chunks, freeChunks, usedChunks }, bytes for the first two and chunk counts for the rest -- which is what to poll when the question is only whether something is growing.dumpMemory()logged the same numbers anddumpMemory( path )wrote a line per chunk (1.4MB of addresses for a 5500-chunk heap), and neither could be read back from JS.usedandfreedo not add up to the arena's size: each chunk also costs a header, whichchunks * CHUNK_SIZEaccounts for. Under a_DEBUGbuild the walk doubles as a consistency check, so it is not free there; outside one it is only run when asked. - Fixed an allocation just under the heap's unit size never completing. A fresh region spends part of itself on its own tracking, so it hands out less than it maps, but the allocator compared the request against the unit size itself: a request inside that overhead -- about 524080 to 524288 bytes with the default 512K unit -- asked for a region of exactly one unit, got one whose free chunk was smaller than the request, failed the search and came back to map another, until the system refused with
Failed to expand space by 524288. Parsing a JSOX document holding a 524080-byte string never returned.InitHeapalso refuses a region too small to track itself, where the unsigned size used to wrap and leave the root chunk claiming memory that was never mapped. - The memory stats are reported in
size_trather thanuint32_t.GetHeapMemStatsExcounted bytes in auintptr_tand cast both totals down on the way out, so a heap over 4GB reported a wrapped figure, and the chunk counters were plainint. system.dumpMemory( verbose, filename )reads the filename from the second argument. It read the first -- the verbose flag -- and stringified it, sodumpMemory( false, "heap.txt" )wrote the dump to a file namedfalsein the working directory and the name given was never used. TheUtf8Valueholding it was also never released.
- JSOX: read an object or array used as an object key --
- 1.3.134
- Took some time to stress test and debug corner cases in networking.
- Implemented HTTP 1.1 streaming request API.
- Improved performance; enabled TCP no delay on websocket connections; cache alignment and spin lock scheduling improvements on concurrent HTTP requests.
- Fixed task manager failure to kill a second time on windows.
- Fixed HTTP responses with no body (a bare
res.end(), including redirects) never completing on a keep-alive connection; they now sendContent-Length: 0. - Fixed
res.end( statusCode )throwing "Headers have already been set" on keep-alive connections; the implicit head is now written before any other header. - HTTP responses now carry the real reason phrase (
404 Not Found) instead ofOKfor every status. - Added
res.statusCode, settable; a response whose handler never calledwriteHead()now gets a status line from it instead of going out with none. - Report the size of library-owned ArrayBuffers to V8 (
AdjustAmountOfExternalAllocatedMemory), so file reads, mapped files, query blobs and socket messages create collection pressure instead of accumulating invisibly. NewmakeReleasableBackingStore()replaces everyNewBackingStore(...,releaseBufferBackingStore,NULL). - Update JSOX parsing to align more with the standard - NBSP is a non-breaking space, allowed in unquoted strings. Allow '/' in unquoted strings.
- SSH channels:
send()queues data the remote's window can't take instead of dropping it;eof()/close()wait for queued data. AddedbufferedAmount,drain(cb),pause()andresume()for flow control.reverse(addr, port, cb)delivers raw channels. Fixed a deadlock when calling SSH methods from JS while the session's network thread was delivering data. - Added
apps/ssh-relay, which joins a remote listener on one SSH server todirect-tcpipchannels through another. - Windows builds of libssh2 now use the bundled LibreSSL instead of WinCNG; WinCNG offered no key exchange current OpenSSH (10.x) accepts and could not load OpenSSH-format RSA keys.
- Fixed SSH receive-buffer rotation that duplicated a buffer and overwrote unread data once more than one read was queued (corrupted streams, then a 100% CPU spin); a session read error no longer spins.
- Fixed SSH sessions leaving received bytes unprocessed until more data arrived (libssh2 was fed one 4K read at a time, and stops after a short read); the end of a stream - last data, EOF, close - could stall indefinitely, especially with chacha20-poly1305.
- Fixed escaped carriage return as a escaped newline JSON6 and JSOX.
- 1.3.133
- Added
getRootexport utility that can find the root package.json. - Added program name to task information in task manager. Program name support is used for process exit signal generation.
- Added user database login support to default task manager app.
- Added environment configuration for task manager configuration files.
- Added reset ability to windows sound device support module.
- Added
rollback()function to SQL module; internally transaction sets up tracking states. - VFS initialization failed if same context and isolate was used but a new export object; fixed so it doesn't crash; not a completed solution. (check uv async event registrations)
- Added
bytesfield to content response for HTTP requests.
- Added
- 1.3.132
- Improve handling when there's no COM ports.
- Fix CMake build to support PSEUDOCON option on windows.
- Change build to build libressl and libssh as separate libraries.
- 1.3.131
- (WIN32) Added sound device support; get devices, set default, set/get volume
- Reoganized object storage facility; moved to extra module, does not auto load.
- make node/native client websocket protocol more similar to web client websocket module.
- enableExitSignal() deadlocks on linux; bypass feature. Process control signals are better handled in other ways on not-Windows.
- throw exception when socket open fails (instead of just logging state)
- improve JSOX error reporting.
- More in CHANGELOG.md
استكشف مشاريع مشابهة ومرتبطة
جارٍ التحميل…