std > io > Source
/// Base type for writing values to files. Use concrete implementations like GcbWriter, TextWriter, JsonWriter, or CsvWriter.
abstract type Writer<T> {
private path: String;
private append: bool?;
/// append the value v to the current writer.
abstract fn write(v: T);
/// flush buffer to disk, mandatory to open reader on same path
abstract fn flush();
}
/// Base type for reading values from files. Use concrete implementations like GcbReader, TextReader, JsonReader, or CsvReader.
abstract type Reader<T> {
private path: String;
pos: int?;
/// read a value from the reader.
abstract fn read(): T;
/// tells whether this reader has more to read
abstract fn can_read(): bool;
/// return the amount of available bytes in reader.
abstract fn available(): int;
}
type BinReader {
private path: String;
pos: int?;
/// read a 32-bit integer as int from the reader.
native fn read_i32(): int;
/// read a 64-bit integer as int from the reader.
native fn read_i64(): int;
/// read an IEEE 754 binary32 as float from the reader.
native fn read_f32(): float;
/// read an IEEE 754 binary64 as float from the reader.
native fn read_f64(): float;
/// read a tensor of value type and shape `shape` from the reader.
///
/// Every `read_*` above throws `end of file` when fewer bytes remain than the value
/// needs -- including on a file that was empty to begin with. Guard with `can_read()`.
native fn read_tensor(etype: TensorType, shape: Array<int>): Tensor;
/// tells whether this reader has more to read
///
/// False -- not an error -- for a file that is empty or already fully read, so
/// `while (reader.can_read())` terminates instead of throwing on the guard itself.
/// Still throws if the file does not exist or cannot be opened.
native fn can_read(): bool;
/// return the amount of available bytes in reader. Zero for an empty or fully-read file.
native fn available(): int;
}
/// GreyCat Binary (ABI encoded) writer utility can export a stream of serializable values to file.
type GcbWriter<T> extends Writer<T> {
native fn write(v: T);
native fn flush();
}
/// GreyCat Binary (ABI encoded) reader utility can read/import a stream of serializable values from file.
type GcbReader<T> extends Reader<T> {
native fn read(): T;
native fn can_read(): bool;
native fn available(): int;
}
/// GreyCat exchange writer: a stream of values in a self-describing binary file (`.gcx`) that does not depend on the
/// ABI, so a program whose types changed, or a tool outside GreyCat, can still read it.
/// Type, field and enum entry names are written once, in a dictionary at the end of the file, by `close()`:
/// the file is readable only once closed.
type GcxWriter<T> {
private path: String;
/// keep the values of an existing closed file and write after them
private append: bool?;
/// set when the file was opened: a writer whose native state was lost refuses to start the file over
private opened: bool?;
/// append the value v to the file.
native fn write(v: T);
/// write the dictionary and close the file. Further writes fail; a second close does nothing.
native fn close();
}
/// GreyCat exchange reader: reads the values a GcxWriter wrote, matching types, fields and enum entries by name to
/// the current program. A field the type no longer has is skipped; a field missing from the file reads as null.
/// Fails on a file that was not closed.
type GcxReader<T> extends Reader<T> {
native fn read(): T;
native fn can_read(): bool;
native fn available(): int;
}
/// Text writer utility can export values as text (utf-8), mostly used for line based format.
type TextWriter<T> extends Writer<T> {
native fn write(v: T);
native fn flush();
/// write the v param as text in writer and add a line separator.
native fn writeln(v: T);
}
/// Text reader utility for reading byte data line by line.
/// Note: Does not perform UTF-8 validation - returns raw byte sequences as strings.
type TextReader extends Reader<String> {
/// Reads the next line from the input, returning the content up to (but not including) the line terminator.
/// Skips leading null bytes, trims trailing null bytes and `'\r'` characters.
/// Line terminators: `'\n'` or `'\r\n'`
/// Throws an error when no more data is available to read.
native fn read(): String;
/// Returns true if there is data available to read, false otherwise.
native fn can_read(): bool;
/// Returns the number of bytes remaining in the input buffer.
native fn available(): int;
}
/// Json writer utility can export values as JSON (utf-8)
type JsonWriter<T> extends Writer<T> {
/// When true, every object is written with a `"_type":"<fqn>"` field, nested ones included,
/// so a `JsonReader` with `type_tag` set reads it back as that type even where `any` is expected.
/// By default only subtypes carry it.
type_tag: bool?;
native fn write(v: T);
native fn flush();
/// write the v param as json element in writer followed by a line separator.
native fn writeln(v: T);
}
/// How `JsonReader` and `Json` read an object carrying a `"_type":"<fqn>"` field, at any position,
/// where `any` is expected. Either way the object is read as that type when it parses as one, and
/// as a `Map` when the program defines no such type.
enum JsonTypeTag {
/// Never throws because of `_type`: any object that cannot be read as the named type is read as a
/// `Map`, `_type` included. For JSON written by other programs, such as log files.
lenient;
/// Throws when `_type` is not a string, names a native type or an enum, or the object does not
/// parse as the named type, with the error of that parse.
strict;
}
/// Json reader utility can read/import a stream of serializable values from file (ndjson or line separated json)
type JsonReader<T> extends Reader<T> {
/// Reads objects tagged with `"_type":"<fqn>"` as that type where `any` is expected, see
/// `JsonTypeTag`. When null, those objects are read as a `Map` like any other. Fields of the
/// JSON that the type does not declare are ignored, and where the reader expects a given type,
/// `_type` is ignored.
type_tag: JsonTypeTag?;
/// Reads the next JSON document from the input.
///
/// Throws when there is nothing left to read -- an exhausted stream, or a file that was
/// empty to begin with. Guard with `can_read()` rather than catching: the return type is
/// a non-null `T`, so there is no in-band value this can hand back to mean "nothing here".
native fn read(): T;
/// Returns true if there is data available to read, false otherwise.
///
/// False -- not an error -- for a file that is empty or already fully read, so
/// `while (reader.can_read())` terminates instead of throwing on the guard itself.
/// Still throws if the file does not exist or cannot be opened.
native fn can_read(): bool;
/// Returns the number of bytes remaining in the input. Zero for an empty or
/// fully-read file.
native fn available(): int;
}
type Json<T> {
/// Parses a JSON string into a GreyCat value, e.g. `Json<MyType>::parse(data)`.
///
/// If a generic type `T` is provided, the parser attempts to deserialize
/// the input into that type. An error is thrown if the JSON does not
/// match `T`.
static native fn parse(data: String): T;
/// Same as `parse`, reading objects tagged with `"_type":"<fqn>"` as that type where `any` is
/// expected, see `JsonReader::type_tag`.
static native fn parse_tagged(data: String, type_tag: JsonTypeTag): T;
/// Serializes a GreyCat value into its JSON string representation.
static native fn to_string(value: any?): String;
}
/// CSV writer utility can export a stream of GreyCat values as CSV lines (utf-8)
///
/// If the generic parameter is a non-primitive type, the field names of that type
/// will be used as headers if `format.header_lines > 0`. The automatic headers will
/// be lazily written. Which means the first call to `write()` will write the headers
/// if the underlying file/buf is empty.
type CsvWriter<T> extends Writer<T> {
private format: CsvFormat?;
native fn write(v: T);
/// Writes the given line as-is.
///
/// If this method is called before any `write()` and with `format.header_lines > 0`
/// no headers will be added automatically based on the generic parameter type.
///
/// No need to add a newline character (`'\n'`), it will be added automatically.
///
/// *Note: if the given `String` contains newline character (`'\n'`) they will not
/// be escaped by this method and will be directly written to the underlying file/buf.*
native fn write_line(line: String);
/// Writes out what is buffered, creating the file if no `write()` has reached it yet.
///
/// With `format.header_lines > 0` and no row written, this emits the headers on their own:
/// an export that matched nothing is a csv file with a header rather than no file at all.
/// An array field takes one bare column there, since its `name_0`, `name_1`, ... form is
/// sized from a row.
native fn flush();
}
type CsvSharding {
/// The id of this shard
id: int;
/// The column offset used for hashing
column: int;
/// The count of unique value for the column
modulo: int;
}
/// CSV reader utility can read/import a stream of serializable values from CSV lines (utf-8)
type CsvReader<T> extends Reader<T> {
private format: CsvFormat?;
private sharding: CsvSharding?;
/// Parses a line and returns a `T` only if valid
///
/// If the parsed line does not comply with the given `T` type, the line is skipped
/// and an error is thrown.
native fn read(): T;
/// Returns the row the last `read()` parsed as the file holds it, quotes included, without its line break, or
/// `null` if the end of file is reached
native fn last_line(): String?;
native fn can_read(): bool;
native fn available(): int;
/// Changes the path to the underlying file.
/// It will reset the reader state to start reading from the start of the new file.
///
/// *Re-using a reader might improve performance when dealing with many files as the buffers
/// and initialization of the format will be re-used instead of being re-created.*
native fn set_path(path: String);
}
/// How a value nested inside a csv row maps to columns.
///
/// This describes the *fields* of a row type. An element of an `Array` row carries no field
/// name for a column header to be built from, so it is one cell in either mode: write
/// `CsvWriter<MyType>` to spread `MyType` over columns, `CsvWriter<Array<MyType>>` to get one
/// `MyType` per cell.
enum CsvNested {
/// One column per leaf: an array field becomes `name_0`, `name_1`, ..., an object field
/// becomes `name_subfield`. A `Map` has no such expansion and cannot be written.
///
/// An array is as wide as its data, so nothing can follow it: it has to be the last
/// column of the row, and a format that puts a column after one is rejected.
flatten,
/// One column holding the JSON representation of the whole value.
json,
}
/// Configuration for CSV parsing and writing.
type CsvFormat {
/// Number of header lines. `null` or `0` means none and is the default.
header_lines: int?;
/// The column separator character (can only be one-byte wide)
separator: char?;
/// Can only be one-byte wide, eg. `'"'`
string_delimiter: char?;
/// Can only be one-byte wide, eg. `','`
decimal_separator: char?;
/// Can only be one-byte wide, eg. `'_'`
thousands_separator: char?;
/// Whether or not to trim spaces (.ie ` `, `\t`, `\r` and `\n`) from start and end, defaults to `false`.
///
/// Into a nullable column, an unquoted field that is empty, blank or `null` (in any case) reads as `null`
/// whatever `trim` says; quoted, it reads as the text it holds. `CsvWriter` quotes such a String for that reason.
trim: bool?;
/// The format to parse date in, defaults to ISO8601/epoch timestamp in milliseconds.
format: String?;
/// The timezone to interpret times in, defaults to the host global timezone.
tz: TimeZone?;
/// Whether or not to enable strict null checking. By default the parser will accept
/// any invalid value as a `null` as long as the target type for that column is nullable.
strict: bool?;
/// Whether or not a quoted field can still be read as a `null`, defaults to `false`.
///
/// By default quoting marks text: `""` reads as an empty `String`, `"null"` as the
/// four-character string, and `"42"` read into an `any` target as the two-character
/// string rather than the number. Set this to `true` for a producer that quotes every
/// field, where the quotes carry no information: the reader then infers through them and
/// an empty field reads as `null`.
///
/// A column with a declared type is unaffected either way, and so is `Csv::analyze`:
/// `"42"` read into an `int` field is `42`.
null_in_quotes: bool?;
/// How a nested value maps to columns, defaults to `CsvNested::flatten`.
///
/// Only applies below the top level: the row itself always spans the columns, so a
/// `CsvWriter<Array<T>>` still writes one column per element of the row.
nested: CsvNested?;
/// Whether or not to fallback to the nearest time when an invalid date is found, defaults to `false`
nearest_time: bool?;
}
type CsvColumnStatistics {
/// column name as in CSV header
name: String?;
/// one value
example: any?;
/// number of null values
null_count: int;
/// number of boolean values
bool_count: int;
/// number of integer values
int_count: int;
/// number of float values
float_count: int;
/// number of string values
string_count: int;
/// number of date values
date_count: int;
/// occurrence of each date format matched
date_format_count: Map<String, int>;
/// occurrences of the `enumerable_limit` values found
/// a value can be string, int or float
enumerable_count: Map<any, int>;
/// statistics on numeric values
profile: Gaussian;
}
type CsvStatistics {
header_lines: int?;
separator: char?;
string_delimiter: char?;
decimal_separator: char?;
thousands_separator: char?;
/// statistics per column
columns: Array<CsvColumnStatistics>;
/// accumulated analyzed (failed + parsed) rows for all accumulated CSV files
line_count: int;
/// accumulated number of failed lines for CSV files
fail_count: int;
/// number of CSV files explored
file_count: int;
}
type CsvAnalysisConfig {
static enumerable_limit_default: int = 100;
static date_check_limit_default: int = 100;
/// CsvAnalysis will try to detect header_lines if not set
header_lines: int?;
/// CsvAnalysis will try to detect separator if not set
separator: char?;
string_delimiter: char?;
decimal_separator: char?;
thousands_separator: char?;
/// `row_limit`:
/// maximum number of rows to parse for statistics collection
/// default value (when not set) means all rows are parsed
row_limit: int?;
/// `enumerable_limit`:
/// maximum number of enumerable elements to detect
/// default value (when not set) is 100 (enumerable_limit_default)
/// special values are 0: none, -1: all
enumerable_limit: int?;
/// `date_check_limit`:
/// check for dates for first 'date_check_limit' rows, but still keep statistics until 'row_limit'
/// default value (when not set) is 100 (date_check_limit_default)
/// special values are 0: none, -1: all
/// if a cell of a column matches, then continue until 'row_limit'
date_check_limit: int?;
/// date formats to look for, in addition to default formats
date_formats: Array<String>?;
}
type Csv {
/// Generates the necessary types and enums to read the records defined by this statistics
@expose
@permission("admin")
static native fn generate(stats: CsvStatistics): String;
/// Analyses a collection of csv files to infer statistics eventually to generate types
@expose
@permission("admin")
static native fn analyze(paths: Array<String>, config: CsvAnalysisConfig?): CsvStatistics;
/// Aggregates reads into a `Table`
///
/// By specifying `reader.pos` the reads will be made after the end of the line at that byte offset
@expose
@permission("admin")
static native fn sample(reader: CsvReader, max_lines: int?): Table;
}
/// Represents a file entry within operating system file system, can be plain file or directory.
type File {
/// path of the file entry
path: String;
/// size of the file, null if is directory
size: int?;
/// last modification of the file
last_modification: time?;
/// Returns the relative path to the directory for files
/// *Accessible remotely at `/files/`*
static native fn baseDir(): String;
/// Returns the relative path to the directory of the current user
/// *Accessible remotely at `/files/<user_name>/`*
static native fn userDir(): String;
/// Returns the relative path to the directory of the current task, RPC calls included
/// *Accessible remotely at `/files/<user_name>/tasks/<task_id>/`*
static native fn workingDir(): String;
/// Retrieve File from a path, return null if file not found
static native fn open(path: String): File?;
/// Deletes the file or directory from disk
static native fn delete(path: String): bool;
/// Rename the file or directory from disk
static native fn rename(old_path: String, new_path: String): bool;
/// Copy the file from disk
static native fn copy(src_path: String, target_path: String): bool;
/// Create directory and sub directory
static native fn mkdir(path: String): bool;
/// List all file, optionally filtered by ends_with suffix (e.g. select .csv extension), recursively or not
static native fn ls(path: String, ends_with: String?, recursive: bool): Array<File>;
/// Returns true in case the File describes a directory (therefore path ends with a '/'), false otherwise
native fn isDir(): bool;
/// Returns the name of the file
native fn name(): String;
/// Returns the name of the extension specific to the file
native fn extension(): String?;
/// Returns the hex sha256 of the file content, null in case of directory. Throws if the
/// path cannot be read, or if the file is modified while it is being hashed
native fn sha256(): String?;
}
/// Utility to iterate over files and directory of a file system
type FileWalker {
private path: String;
/// Return true if next() method will not return a file
native fn isEmpty(): bool;
/// Return the next file
native fn next(): File?;
}
/// Represents an URL string representation (e.g. `schema://host:port/path?param_key=paramValue#hash`)
type Url {
protocol: String?;
host: String?;
port: int?;
path: String?;
user: String?;
password: String?;
params: Map<String, String>?;
hash: String?;
/// create an URL from a string representation
static native fn parse(url: String): Url;
/// Encode any object as x-www-form-urlencoded content-type
/// String are url encoded, objects and map are flatten and values are url encodded
static native fn encode(value: any): String;
}
/// represent an email instance to be sent through SMTP utility
type Email {
from: String;
subject: String;
body: String;
body_is_html: bool;
to: Array<String>;
cc: Array<String>?;
bcc: Array<String>?;
}
/// Smtp Encryption Mode
enum SmtpMode {
/// plain exchange mode
plain(0);
/// ssl tls exchange mode
ssl_tls(1);
/// starttls exchange node
starttls(2);
}
/// Smtp authentication method
enum SmtpAuth {
/// no authentication
none(0);
/// basic authentication method
plain(1);
/// login:pass authentication method
login(2);
}
/// Utility to send mail through smtp protocol
type Smtp {
host: String;
port: int;
mode: SmtpMode?;
authenticate: SmtpAuth?;
user: String?;
pass: String?;
/// Send the parameter mail through smtp protocol
native fn send(email: Email);
}
/// The format of the records of a `Stream`, one per line: `ndjson` writes one JSON object per line, and
/// `csv` one CSV line with the default `CsvFormat` (no header, `,` separator).
enum StreamFormat {
ndjson,
csv,
}
/// The settings of a `Stream` that `Stream<T>::new` takes beyond its callback.
type StreamOptions {
/// The format of the records and the file extension, `StreamFormat::ndjson` when null.
format: StreamFormat?;
/// The number of buffered bytes that sends the buffer to the file, 64KB when null. `0` writes
/// each value to the file as it comes.
flush_size: int?;
/// The longest time a value stays buffered, 1s when null.
flush_step: duration?;
}
/// An append-only buffer that absorbs a high-rate, concurrent write stream of `T` values and
/// hands them to GreyCat in batches, at a bounded pace, instead of one graph transaction per write.
///
/// Producers call `write()` from any number of concurrent contexts. Each value is appended and
/// assigned an increasing byte offset. Values are buffered in memory and reach the file in batches:
/// once `flush_size` bytes are pending, at the latest `flush_step` after the first of them (both
/// set in `StreamOptions`), when a reader or `last_written_pos()` asks, on `flush()`, when the
/// file is read through the HTTP `/files` API, and at a clean shutdown. Consumption is
/// decoupled. The `callback` given to `new()` is triggered at most `max_dephasing` after values
/// reach the file, and it drains the stream with `reader()` starting from the offset it last
/// consumed. That offset is the consumer's own checkpoint (the stream does not track it), so
/// persist it in the graph next to the data it produced, and re-read from it after a restart. A
/// re-run of the callback may therefore see values it already processed, so keep the handling
/// idempotent.
///
/// Streams are registered once by name (`/` separates hierarchy levels, e.g. `"ingest/events"`)
/// and retrieved elsewhere with `get()`. Names are unique per user. The records live in
/// `files/<user>/streams/<name>.ndjson` (`.csv` for `StreamFormat::csv`), one JSON object or CSV
/// line each, and survive restarts. A `GET` or `HEAD` of that file through `/files` writes the
/// buffer first, so an HTTP client polling it with `Range: bytes=<offset>-` gets every value
/// written so far. The registry itself is in-memory, so register again at
/// startup. Registering a name whose file already holds records reattaches to it and fires the
/// callback once, so records written just before a shutdown are drained even though no new write
/// arrives.
///
/// Values still in the buffer are lost when the process is killed or crashes, and values in the
/// file but not yet synced to disk are lost when the machine does. `flush()` is the durability
/// point: once it returns, every value written before it is on disk. Call it before persisting a
/// drain offset when the stream must survive a machine crash, since a file cut back below a
/// persisted offset makes the next drain skip the values written after the restart.
///
/// Examples:
/// ```gcl
/// type Event { id: int; payload: String; }
/// type IngestState { pos: int; }
/// var ingest: node<IngestState?>;
///
/// fn on_events() {
/// var s = Stream<Event>::get("ingest/events");
/// var state = ingest.resolve();
/// if (state == null) {
/// state = IngestState { pos: 0 };
/// ingest.set(state);
/// }
/// var end = s.last_written_pos();
/// var r = s.reader(state.pos);
/// while (r.can_read()) {
/// handle(r.read());
/// }
/// state.pos = end;
/// }
///
/// fn start() {
/// var s = Stream<Event>::new("ingest/events", on_events, 500ms, null);
/// s.write(Event { id: 1, payload: "hello" });
/// }
/// ```
type Stream<T> {
/// Writes the buffered values to the file, then returns the offset just past the last of them.
///
/// Capture it before draining with `reader()` and persist it once the drain succeeds: it is
/// the `from` to resume from on the next callback or after a restart.
native fn last_written_pos(): int;
/// Returns the name this stream was registered under with `new()`.
native fn name(): String;
/// Registers a new stream and returns its handle.
///
/// `name` must be unique for the calling user; use `/` to group streams hierarchically. Empty,
/// `.` and `..` segments (so also a leading or trailing `/`) and `\` are rejected.
/// Called on the value type, as in `Stream<Event>::new(...)`: that `T` is the type of the values
/// written and the one `reader()` yields.
/// `callback` is invoked at most `max_dephasing` after values reach the file, so a burst of
/// writes costs one callback, not one per value. It must be a top-level function, as lambdas
/// do not capture their environment.
/// `options` holds the format and the buffering, see `StreamOptions`; null takes every default.
/// Throws when its `flush_size` or `flush_step` is negative.
native static fn new(name: String, callback: function, max_dephasing: duration, options: StreamOptions?): Stream<T>;
/// Returns the handle of a stream previously registered with `new()` under `name`.
///
/// Called on the value type, as in `Stream<Event>::get(...)`, which must match the one the stream
/// was registered with.
native static fn get(name: String): Stream<T>;
/// Returns the format this stream was registered with.
native fn format(): StreamFormat;
/// Points `reader` at this stream's file from offset `from`, bounded by `last_written_pos()`
/// as of this call, and returns it. `reader()` builds the reader and calls this: use it instead.
/// Throws when `reader` is not of the stream's format, a `JsonReader<T>` for ndjson or a
/// `CsvReader<T>` for csv.
native fn bind_reader(reader: Reader<T>, from: int): Reader<T>;
/// Opens a reader over the values appended from offset `from` onwards, up to
/// `last_written_pos()` as of this call.
///
/// Everything below that bound is a complete record, whatever the filesystem reports. The
/// buffered values are written to the file first, so every value written before this call is
/// visible, and values written after `reader()` returns are not. Pass the offset persisted
/// after the previous drain (`0` on first run). Values are handed back through the standard
/// `Reader` loop: guard with `can_read()`, then `read()`.
/// The reader is a `JsonReader<T>` on an ndjson stream and a `CsvReader<T>` on a csv one.
fn reader(from: int): Reader<T> {
// The literals give each Stream<X> its JsonReader<X> and CsvReader<X>: the compiler builds them as such in the
// Stream<X> copy of this method, where a reader created in C could only be the bare generic.
if (this.format() == StreamFormat::csv) {
return this.bind_reader(CsvReader<T> { path: "" }, from);
}
return this.bind_reader(JsonReader<T> { path: "" }, from);
}
/// Appends `value` to the stream's buffer.
///
/// Safe to call concurrently from any context. A failed write of the buffer to the file drops
/// the values it held. It is logged, not thrown, the next `flush()` throws it, and the file is
/// cut back to its last complete record. An object must be exactly a `T`: a subtype is
/// rejected, since `reader()` parses records back as `T`.
native fn write(value: T);
/// Writes the buffered values to the file and syncs it to disk. Returns once every value
/// written before this call is on disk. Throws when the write or the sync fails, or when an
/// earlier write to the file dropped values since the previous `flush()`.
native fn flush();
}