@bayoudhi/moose-lib-serverless 0.7.2 → 0.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2412 @@
1
+ import { IJsonSchemaCollection, tags } from 'typia';
2
+ import { Pattern, TagBase } from 'typia/lib/tags';
3
+ import { Readable } from 'node:stream';
4
+ import { ClickHouseClient, ResultSet, CommandResult } from '@clickhouse/client';
5
+ type Client = any;
6
+ import { JWTPayload } from 'jose';
7
+ import http from 'http';
8
+
9
+ /**
10
+ * Quote a ClickHouse identifier with backticks if not already quoted.
11
+ * Backticks allow special characters (e.g., hyphens) in identifiers.
12
+ */
13
+ declare const quoteIdentifier: (name: string) => string;
14
+ type IdentifierBrandedString = string & {
15
+ readonly __identifier_brand?: unique symbol;
16
+ };
17
+ type NonIdentifierBrandedString = string & {
18
+ readonly __identifier_brand?: unique symbol;
19
+ };
20
+ /**
21
+ * Values supported by SQL engine.
22
+ */
23
+ type Value = NonIdentifierBrandedString | number | boolean | Date | [string, string];
24
+ /**
25
+ * Supported value or SQL instance.
26
+ */
27
+ type RawValue = Value | Sql;
28
+ /**
29
+ * Sql template tag interface with attached helper methods.
30
+ */
31
+ interface SqlTemplateTag {
32
+ (strings: readonly string[], ...values: readonly (RawValue | Column | OlapTable<any> | View)[]): Sql;
33
+ /**
34
+ * Join an array of Sql fragments with a separator.
35
+ * @param fragments - Array of Sql fragments to join
36
+ * @param separator - Optional separator string (defaults to ", ")
37
+ */
38
+ join(fragments: Sql[], separator?: string): Sql;
39
+ /**
40
+ * Create raw SQL from a string without parameterization.
41
+ * WARNING: SQL injection risk if used with untrusted input.
42
+ */
43
+ raw(text: string): Sql;
44
+ }
45
+ declare const sql: SqlTemplateTag;
46
+ /**
47
+ * A SQL instance can be nested within each other to build SQL strings.
48
+ */
49
+ declare class Sql {
50
+ readonly values: Value[];
51
+ readonly strings: string[];
52
+ constructor(rawStrings: readonly string[], rawValues: readonly (RawValue | Column | OlapTable<any> | View | Sql)[]);
53
+ /**
54
+ * Append another Sql fragment, returning a new Sql instance.
55
+ */
56
+ append(other: Sql): Sql;
57
+ }
58
+ declare const toStaticQuery: (sql: Sql) => string;
59
+ declare const toQuery: (sql: Sql) => [string, {
60
+ [pN: string]: any;
61
+ }];
62
+ /**
63
+ * Build a display-only SQL string with values inlined for logging/debugging.
64
+ * Does not alter execution behavior; use toQuery for actual execution.
65
+ */
66
+ declare const toQueryPreview: (sql: Sql) => string;
67
+ declare const getValueFromParameter: (value: any) => any;
68
+ declare function createClickhouseParameter(parameterIndex: number, value: Value): string;
69
+ /**
70
+ * Convert the JS type (source is JSON format by API query parameter) to the corresponding ClickHouse type for generating named placeholder of parameterized query.
71
+ * Only support to convert number to Int or Float, boolean to Bool, string to String, other types will convert to String.
72
+ * If exist complex type e.g: object, Array, null, undefined, Date, Record.. etc, just convert to string type by ClickHouse function in SQL.
73
+ * ClickHouse support converting string to other types function.
74
+ * Please see Each section of the https://clickhouse.com/docs/en/sql-reference/functions and https://clickhouse.com/docs/en/sql-reference/functions/type-conversion-functions
75
+ * @param value
76
+ * @returns 'Float', 'Int', 'Bool', 'String'
77
+ */
78
+ declare const mapToClickHouseType: (value: Value) => string;
79
+
80
+ type EnumValues = {
81
+ name: string;
82
+ value: {
83
+ Int: number;
84
+ };
85
+ }[] | {
86
+ name: string;
87
+ value: {
88
+ String: string;
89
+ };
90
+ }[];
91
+ type DataEnum = {
92
+ name: string;
93
+ values: EnumValues;
94
+ };
95
+ type Nested = {
96
+ name: string;
97
+ columns: Column[];
98
+ jwt: boolean;
99
+ };
100
+ type ArrayType = {
101
+ elementType: DataType;
102
+ elementNullable: boolean;
103
+ };
104
+ type NamedTupleType = {
105
+ fields: Array<[string, DataType]>;
106
+ };
107
+ type MapType = {
108
+ keyType: DataType;
109
+ valueType: DataType;
110
+ };
111
+ type JsonOptions = {
112
+ max_dynamic_paths?: number;
113
+ max_dynamic_types?: number;
114
+ typed_paths?: Array<[string, DataType]>;
115
+ skip_paths?: string[];
116
+ skip_regexps?: string[];
117
+ };
118
+ type DataType = string | DataEnum | ArrayType | Nested | NamedTupleType | MapType | JsonOptions | {
119
+ nullable: DataType;
120
+ };
121
+ interface Column {
122
+ name: IdentifierBrandedString;
123
+ data_type: DataType;
124
+ required: boolean;
125
+ unique: false;
126
+ primary_key: boolean;
127
+ default: string | null;
128
+ materialized: string | null;
129
+ ttl: string | null;
130
+ codec: string | null;
131
+ annotations: [string, any][];
132
+ comment: string | null;
133
+ }
134
+
135
+ /**
136
+ * Type definition for typia validation functions
137
+ */
138
+ interface TypiaValidators<T> {
139
+ /** Typia validator function: returns { success: boolean, data?: T, errors?: any[] } */
140
+ validate?: (data: unknown) => {
141
+ success: boolean;
142
+ data?: T;
143
+ errors?: any[];
144
+ };
145
+ /** Typia assert function: throws on validation failure, returns T on success */
146
+ assert?: (data: unknown) => T;
147
+ /** Typia is function: returns boolean indicating if data matches type T */
148
+ is?: (data: unknown) => data is T;
149
+ }
150
+ /**
151
+ * Base class for all typed Moose dmv2 resources (OlapTable, Stream, etc.).
152
+ * Handles the storage and injection of schema information (JSON schema and Column array)
153
+ * provided by the Moose compiler plugin.
154
+ *
155
+ * @template T The data type (interface or type alias) defining the schema of the resource.
156
+ * @template C The specific configuration type for the resource (e.g., OlapConfig, StreamConfig).
157
+ */
158
+ declare class TypedBase<T, C> {
159
+ /** The JSON schema representation of type T. Injected by the compiler plugin. */
160
+ schema: IJsonSchemaCollection.IV3_1;
161
+ /** The name assigned to this resource instance. */
162
+ name: string;
163
+ /** A dictionary mapping column names (keys of T) to their Column definitions. */
164
+ columns: {
165
+ [columnName in keyof Required<T>]: Column;
166
+ };
167
+ /** An array containing the Column definitions for this resource. Injected by the compiler plugin. */
168
+ columnArray: Column[];
169
+ /** The configuration object specific to this resource type. */
170
+ config: C;
171
+ /** Typia validation functions for type T. Injected by the compiler plugin for OlapTable. */
172
+ validators?: TypiaValidators<T>;
173
+ /** Optional metadata for the resource, always present as an object. */
174
+ metadata: {
175
+ [key: string]: any;
176
+ };
177
+ /**
178
+ * Whether this resource allows extra fields beyond the defined columns.
179
+ * When true, extra fields in payloads are passed through to streaming functions.
180
+ * Injected by the compiler plugin when the type has an index signature.
181
+ */
182
+ allowExtraFields: boolean;
183
+ /**
184
+ * @internal Constructor intended for internal use by subclasses and the compiler plugin.
185
+ * It expects the schema and columns to be provided, typically injected by the compiler.
186
+ *
187
+ * @param name The name for the resource instance.
188
+ * @param config The configuration object for the resource.
189
+ * @param schema The JSON schema for the resource's data type T (injected).
190
+ * @param columns The array of Column definitions for T (injected).
191
+ * @param allowExtraFields Whether extra fields are allowed (injected when type has index signature).
192
+ */
193
+ constructor(name: string, config: C, schema?: IJsonSchemaCollection.IV3_1, columns?: Column[], validators?: TypiaValidators<T>, allowExtraFields?: boolean);
194
+ }
195
+
196
+ type ClickHousePrecision<P extends number> = {
197
+ _clickhouse_precision?: P;
198
+ };
199
+ declare const DecimalRegex: "^-?\\d+(\\.\\d+)?$";
200
+ type ClickHouseDecimal<P extends number, S extends number> = {
201
+ _clickhouse_precision?: P;
202
+ _clickhouse_scale?: S;
203
+ } & Pattern<typeof DecimalRegex>;
204
+ type ClickHouseFixedStringSize<N extends number> = {
205
+ _clickhouse_fixed_string_size?: N;
206
+ };
207
+ /**
208
+ * FixedString(N) - Fixed-length string of exactly N bytes.
209
+ *
210
+ * ClickHouse stores exactly N bytes, padding shorter values with null bytes.
211
+ * Values exceeding N bytes will throw an exception.
212
+ *
213
+ * Use for binary data: hashes, IP addresses, UUIDs, MAC addresses.
214
+ *
215
+ * @example
216
+ * interface BinaryData {
217
+ * md5_hash: string & FixedString<16>; // 16-byte MD5
218
+ * sha256_hash: string & FixedString<32>; // 32-byte SHA256
219
+ * }
220
+ */
221
+ type FixedString<N extends number> = string & ClickHouseFixedStringSize<N>;
222
+ type ClickHouseByteSize<N extends number> = {
223
+ _clickhouse_byte_size?: N;
224
+ };
225
+ type LowCardinality = {
226
+ _LowCardinality?: true;
227
+ };
228
+ type DateTime = Date;
229
+ type DateTime64<P extends number> = Date & ClickHousePrecision<P>;
230
+ type DateTimeString = string & tags.Format<"date-time">;
231
+ /**
232
+ * JS Date objects cannot hold microsecond precision.
233
+ * Use string as the runtime type to avoid losing information.
234
+ */
235
+ type DateTime64String<P extends number> = string & tags.Format<"date-time"> & ClickHousePrecision<P>;
236
+ type Float32 = number & ClickHouseFloat<"float32">;
237
+ type Float64 = number & ClickHouseFloat<"float64">;
238
+ type Int8 = number & ClickHouseInt<"int8">;
239
+ type Int16 = number & ClickHouseInt<"int16">;
240
+ type Int32 = number & ClickHouseInt<"int32">;
241
+ type Int64 = number & ClickHouseInt<"int64">;
242
+ type UInt8 = number & ClickHouseInt<"uint8">;
243
+ type UInt16 = number & ClickHouseInt<"uint16">;
244
+ type UInt32 = number & ClickHouseInt<"uint32">;
245
+ type UInt64 = number & ClickHouseInt<"uint64">;
246
+ type Decimal<P extends number, S extends number> = string & ClickHouseDecimal<P, S>;
247
+ /**
248
+ * Attach compression codec to a column type.
249
+ *
250
+ * Any valid ClickHouse codec expression is allowed. ClickHouse validates the codec at runtime.
251
+ *
252
+ * @template T The base data type
253
+ * @template CodecExpr The codec expression (single codec or chain)
254
+ *
255
+ * @example
256
+ * interface Metrics {
257
+ * // Single codec
258
+ * log_blob: string & ClickHouseCodec<"ZSTD(3)">;
259
+ *
260
+ * // Codec chain (processed left-to-right)
261
+ * timestamp: Date & ClickHouseCodec<"Delta, LZ4">;
262
+ * temperature: number & ClickHouseCodec<"Gorilla, ZSTD">;
263
+ *
264
+ * // Specialized codecs
265
+ * counter: number & ClickHouseCodec<"DoubleDelta">;
266
+ *
267
+ * // Can combine with other annotations
268
+ * count: UInt64 & ClickHouseCodec<"DoubleDelta, LZ4">;
269
+ * }
270
+ */
271
+ type ClickHouseCodec<CodecExpr extends string> = {
272
+ _clickhouse_codec?: CodecExpr;
273
+ };
274
+ type ClickHouseFloat<Value extends "float32" | "float64"> = tags.Type<Value extends "float32" ? "float" : "double">;
275
+ type ClickHouseInt<Value extends "int8" | "int16" | "int32" | "int64" | "uint8" | "uint16" | "uint32" | "uint64"> = Value extends "int32" | "int64" | "uint32" | "uint64" ? tags.Type<Value> : TagBase<{
276
+ target: "number";
277
+ kind: "type";
278
+ value: Value;
279
+ validate: Value extends "int8" ? "-128 <= $input && $input <= 127" : Value extends "int16" ? "-32768 <= $input && $input <= 32767" : Value extends "uint8" ? "0 <= $input && $input <= 255" : Value extends "uint16" ? "0 <= $input && $input <= 65535" : never;
280
+ exclusive: true;
281
+ schema: {
282
+ type: "integer";
283
+ };
284
+ }>;
285
+ /**
286
+ * By default, nested objects map to the `Nested` type in clickhouse.
287
+ * Write `nestedObject: AnotherInterfaceType & ClickHouseNamedTuple`
288
+ * to map AnotherInterfaceType to the named tuple type.
289
+ */
290
+ type ClickHouseNamedTuple = {
291
+ _clickhouse_mapped_type?: "namedTuple";
292
+ };
293
+ type ClickHouseJson<maxDynamicPaths extends number | undefined = undefined, maxDynamicTypes extends number | undefined = undefined, skipPaths extends string[] = [], skipRegexes extends string[] = []> = {
294
+ _clickhouse_mapped_type?: "JSON";
295
+ _clickhouse_json_settings?: {
296
+ maxDynamicPaths?: maxDynamicPaths;
297
+ maxDynamicTypes?: maxDynamicTypes;
298
+ skipPaths?: skipPaths;
299
+ skipRegexes?: skipRegexes;
300
+ };
301
+ };
302
+ type ClickHousePoint = [number, number] & {
303
+ _clickhouse_mapped_type?: "Point";
304
+ };
305
+ type ClickHouseRing = ClickHousePoint[] & {
306
+ _clickhouse_mapped_type?: "Ring";
307
+ };
308
+ type ClickHouseLineString = ClickHousePoint[] & {
309
+ _clickhouse_mapped_type?: "LineString";
310
+ };
311
+ type ClickHouseMultiLineString = ClickHouseLineString[] & {
312
+ _clickhouse_mapped_type?: "MultiLineString";
313
+ };
314
+ type ClickHousePolygon = ClickHouseRing[] & {
315
+ _clickhouse_mapped_type?: "Polygon";
316
+ };
317
+ type ClickHouseMultiPolygon = ClickHousePolygon[] & {
318
+ _clickhouse_mapped_type?: "MultiPolygon";
319
+ };
320
+ /**
321
+ * typia may have trouble handling this type.
322
+ * In which case, use {@link WithDefault} as a workaround
323
+ *
324
+ * @example
325
+ * { field: number & ClickHouseDefault<"0"> }
326
+ */
327
+ type ClickHouseDefault<SqlExpression extends string> = {
328
+ _clickhouse_default?: SqlExpression;
329
+ };
330
+ /**
331
+ * @example
332
+ * {
333
+ * ...
334
+ * timestamp: Date;
335
+ * debugMessage: string & ClickHouseTTL<"timestamp + INTERVAL 1 WEEK">;
336
+ * }
337
+ */
338
+ type ClickHouseTTL<SqlExpression extends string> = {
339
+ _clickhouse_ttl?: SqlExpression;
340
+ };
341
+ /**
342
+ * ClickHouse MATERIALIZED column annotation.
343
+ * The column value is computed at INSERT time and physically stored.
344
+ * Cannot be explicitly inserted by users.
345
+ *
346
+ * @example
347
+ * interface Events {
348
+ * eventTime: DateTime;
349
+ * // Extract date component - computed and stored at insert time
350
+ * eventDate: Date & ClickHouseMaterialized<"toDate(event_time)">;
351
+ *
352
+ * userId: string;
353
+ * // Precompute hash for fast lookups
354
+ * userHash: UInt64 & ClickHouseMaterialized<"cityHash64(userId)">;
355
+ * }
356
+ *
357
+ * @remarks
358
+ * - MATERIALIZED and DEFAULT are mutually exclusive
359
+ * - Can be combined with ClickHouseCodec for compression
360
+ * - Changing the expression modifies the column in-place (existing values preserved)
361
+ */
362
+ type ClickHouseMaterialized<SqlExpression extends string> = {
363
+ _clickhouse_materialized?: SqlExpression;
364
+ };
365
+ /**
366
+ * See also {@link ClickHouseDefault}
367
+ *
368
+ * @example{ updated_at: WithDefault<Date, "now()"> }
369
+ */
370
+ type WithDefault<T, _SqlExpression extends string> = T;
371
+ /**
372
+ * ClickHouse table engine types supported by Moose.
373
+ */
374
+ declare enum ClickHouseEngines {
375
+ MergeTree = "MergeTree",
376
+ ReplacingMergeTree = "ReplacingMergeTree",
377
+ SummingMergeTree = "SummingMergeTree",
378
+ AggregatingMergeTree = "AggregatingMergeTree",
379
+ CollapsingMergeTree = "CollapsingMergeTree",
380
+ VersionedCollapsingMergeTree = "VersionedCollapsingMergeTree",
381
+ GraphiteMergeTree = "GraphiteMergeTree",
382
+ S3Queue = "S3Queue",
383
+ S3 = "S3",
384
+ Buffer = "Buffer",
385
+ Distributed = "Distributed",
386
+ IcebergS3 = "IcebergS3",
387
+ Kafka = "Kafka",
388
+ Merge = "Merge",
389
+ ReplicatedMergeTree = "ReplicatedMergeTree",
390
+ ReplicatedReplacingMergeTree = "ReplicatedReplacingMergeTree",
391
+ ReplicatedAggregatingMergeTree = "ReplicatedAggregatingMergeTree",
392
+ ReplicatedSummingMergeTree = "ReplicatedSummingMergeTree",
393
+ ReplicatedCollapsingMergeTree = "ReplicatedCollapsingMergeTree",
394
+ ReplicatedVersionedCollapsingMergeTree = "ReplicatedVersionedCollapsingMergeTree"
395
+ }
396
+
397
+ /**
398
+ * Defines how Moose manages the lifecycle of database resources when your code changes.
399
+ *
400
+ * This enum controls the behavior when there are differences between your code definitions
401
+ * and the actual database schema or structure.
402
+ */
403
+ declare enum LifeCycle {
404
+ /**
405
+ * Full automatic management (default behavior).
406
+ * Moose will automatically modify database resources to match your code definitions,
407
+ * including potentially destructive operations like dropping columns or tables.
408
+ */
409
+ FULLY_MANAGED = "FULLY_MANAGED",
410
+ /**
411
+ * Deletion-protected automatic management.
412
+ * Moose will modify resources to match your code but will avoid destructive actions
413
+ * such as dropping columns, or tables. Only additive changes are applied.
414
+ */
415
+ DELETION_PROTECTED = "DELETION_PROTECTED",
416
+ /**
417
+ * External management - no automatic changes.
418
+ * Moose will not modify the database resources. You are responsible for managing
419
+ * the schema and ensuring it matches your code definitions manually.
420
+ */
421
+ EXTERNALLY_MANAGED = "EXTERNALLY_MANAGED"
422
+ }
423
+
424
+ interface TableIndex {
425
+ name: string;
426
+ expression: string;
427
+ type: string;
428
+ arguments?: string[];
429
+ granularity?: number;
430
+ }
431
+ /**
432
+ * Represents a failed record during insertion with error details
433
+ */
434
+ interface FailedRecord<T> {
435
+ /** The original record that failed to insert */
436
+ record: T;
437
+ /** The error message describing why the insertion failed */
438
+ error: string;
439
+ /** Optional: The index of this record in the original batch */
440
+ index?: number;
441
+ }
442
+ /**
443
+ * Result of an insert operation with detailed success/failure information
444
+ */
445
+ interface InsertResult<T> {
446
+ /** Number of records successfully inserted */
447
+ successful: number;
448
+ /** Number of records that failed to insert */
449
+ failed: number;
450
+ /** Total number of records processed */
451
+ total: number;
452
+ /** Detailed information about failed records (if record isolation was used) */
453
+ failedRecords?: FailedRecord<T>[];
454
+ }
455
+ /**
456
+ * Error handling strategy for insert operations
457
+ */
458
+ type ErrorStrategy = "fail-fast" | "discard" | "isolate";
459
+ /**
460
+ * Options for insert operations
461
+ */
462
+ interface InsertOptions {
463
+ /** Maximum number of bad records to tolerate before failing */
464
+ allowErrors?: number;
465
+ /** Maximum ratio of bad records to tolerate (0.0 to 1.0) before failing */
466
+ allowErrorsRatio?: number;
467
+ /** Error handling strategy */
468
+ strategy?: ErrorStrategy;
469
+ /** Whether to enable dead letter queue for failed records (future feature) */
470
+ deadLetterQueue?: boolean;
471
+ /** Whether to validate data against schema before insertion (default: true) */
472
+ validate?: boolean;
473
+ /** Whether to skip validation for individual records during 'isolate' strategy retries (default: false) */
474
+ skipValidationOnRetry?: boolean;
475
+ }
476
+ /**
477
+ * Validation result for a record with detailed error information
478
+ */
479
+ interface ValidationError {
480
+ /** The original record that failed validation */
481
+ record: any;
482
+ /** Detailed validation error message */
483
+ error: string;
484
+ /** Optional: The index of this record in the original batch */
485
+ index?: number;
486
+ /** The path to the field that failed validation */
487
+ path?: string;
488
+ }
489
+ /**
490
+ * Result of data validation with success/failure breakdown
491
+ */
492
+ interface ValidationResult<T> {
493
+ /** Records that passed validation */
494
+ valid: T[];
495
+ /** Records that failed validation with detailed error information */
496
+ invalid: ValidationError[];
497
+ /** Total number of records processed */
498
+ total: number;
499
+ }
500
+ /**
501
+ * S3Queue-specific table settings that can be modified with ALTER TABLE MODIFY SETTING
502
+ * Note: Since ClickHouse 24.7, settings no longer require the 's3queue_' prefix
503
+ */
504
+ interface S3QueueTableSettings {
505
+ /** Processing mode: "ordered" for sequential or "unordered" for parallel processing */
506
+ mode?: "ordered" | "unordered";
507
+ /** What to do with files after processing: 'keep' or 'delete' */
508
+ after_processing?: "keep" | "delete";
509
+ /** ZooKeeper/Keeper path for coordination between replicas */
510
+ keeper_path?: string;
511
+ /** Number of retry attempts for failed files */
512
+ loading_retries?: string;
513
+ /** Number of threads for parallel processing */
514
+ processing_threads_num?: string;
515
+ /** Enable parallel inserts */
516
+ parallel_inserts?: string;
517
+ /** Enable logging to system.s3queue_log table */
518
+ enable_logging_to_queue_log?: string;
519
+ /** Last processed file path (for ordered mode) */
520
+ last_processed_path?: string;
521
+ /** Maximum number of tracked files in ZooKeeper */
522
+ tracked_files_limit?: string;
523
+ /** TTL for tracked files in seconds */
524
+ tracked_file_ttl_sec?: string;
525
+ /** Minimum polling timeout in milliseconds */
526
+ polling_min_timeout_ms?: string;
527
+ /** Maximum polling timeout in milliseconds */
528
+ polling_max_timeout_ms?: string;
529
+ /** Polling backoff in milliseconds */
530
+ polling_backoff_ms?: string;
531
+ /** Minimum cleanup interval in milliseconds */
532
+ cleanup_interval_min_ms?: string;
533
+ /** Maximum cleanup interval in milliseconds */
534
+ cleanup_interval_max_ms?: string;
535
+ /** Number of buckets for sharding (0 = disabled) */
536
+ buckets?: string;
537
+ /** Batch size for listing objects */
538
+ list_objects_batch_size?: string;
539
+ /** Enable hash ring filtering for distributed processing */
540
+ enable_hash_ring_filtering?: string;
541
+ /** Maximum files to process before committing */
542
+ max_processed_files_before_commit?: string;
543
+ /** Maximum rows to process before committing */
544
+ max_processed_rows_before_commit?: string;
545
+ /** Maximum bytes to process before committing */
546
+ max_processed_bytes_before_commit?: string;
547
+ /** Maximum processing time in seconds before committing */
548
+ max_processing_time_sec_before_commit?: string;
549
+ /** Use persistent processing nodes (available from 25.8) */
550
+ use_persistent_processing_nodes?: string;
551
+ /** TTL for persistent processing nodes in seconds */
552
+ persistent_processing_nodes_ttl_seconds?: string;
553
+ /** Additional settings */
554
+ [key: string]: string | undefined;
555
+ }
556
+ /**
557
+ * Base configuration shared by all table engines
558
+ * @template T The data type of the records stored in the table.
559
+ */
560
+ type BaseOlapConfig<T> = ({
561
+ /**
562
+ * Specifies the fields to use for ordering data within the ClickHouse table.
563
+ * This is crucial for optimizing query performance.
564
+ */
565
+ orderByFields: (keyof T & string)[];
566
+ orderByExpression?: undefined;
567
+ } | {
568
+ orderByFields?: undefined;
569
+ /**
570
+ * An arbitrary ClickHouse SQL expression for the order by clause.
571
+ *
572
+ * `orderByExpression: "(id, name)"` is equivalent to `orderByFields: ["id", "name"]`
573
+ * `orderByExpression: "tuple()"` means no sorting
574
+ */
575
+ orderByExpression: string;
576
+ } | {
577
+ orderByFields?: undefined;
578
+ orderByExpression?: undefined;
579
+ }) & {
580
+ partitionBy?: string;
581
+ /**
582
+ * SAMPLE BY expression for approximate query processing.
583
+ *
584
+ * Examples:
585
+ * ```typescript
586
+ * // Single unsigned integer field
587
+ * sampleByExpression: "userId"
588
+ *
589
+ * // Hash function on any field type
590
+ * sampleByExpression: "cityHash64(id)"
591
+ *
592
+ * // Multiple fields with hash
593
+ * sampleByExpression: "cityHash64(userId, timestamp)"
594
+ * ```
595
+ *
596
+ * Requirements:
597
+ * - Expression must evaluate to an unsigned integer (UInt8/16/32/64)
598
+ * - Expression must be present in the ORDER BY clause
599
+ * - If using hash functions, the same expression must appear in orderByExpression
600
+ */
601
+ sampleByExpression?: string;
602
+ /**
603
+ * Optional PRIMARY KEY expression.
604
+ * When specified, this overrides the primary key inferred from Key<T> column annotations.
605
+ *
606
+ * This allows for:
607
+ * - Complex primary keys using functions (e.g., "cityHash64(id)")
608
+ * - Different column ordering in primary key vs schema definition
609
+ * - Primary keys that differ from ORDER BY
610
+ *
611
+ * Example: primaryKeyExpression: "(userId, cityHash64(eventId))"
612
+ *
613
+ * Note: When this is set, any Key<T> annotations on columns are ignored for PRIMARY KEY generation.
614
+ */
615
+ primaryKeyExpression?: string;
616
+ version?: string;
617
+ lifeCycle?: LifeCycle;
618
+ settings?: {
619
+ [key: string]: string;
620
+ };
621
+ /**
622
+ * Optional TTL configuration for the table.
623
+ * e.g., "TTL timestamp + INTERVAL 90 DAY DELETE"
624
+ *
625
+ * Use the {@link ClickHouseTTL} type to configure column level TTL
626
+ */
627
+ ttl?: string;
628
+ /** Optional secondary/data-skipping indexes */
629
+ indexes?: TableIndex[];
630
+ /**
631
+ * Optional database name for multi-database support.
632
+ * When not specified, uses the global ClickHouse config database.
633
+ */
634
+ database?: string;
635
+ /**
636
+ * Optional cluster name for ON CLUSTER support.
637
+ * Use this to enable replicated tables across ClickHouse clusters.
638
+ * The cluster must be defined in config.toml (dev environment only).
639
+ * Example: cluster: "prod_cluster"
640
+ */
641
+ cluster?: string;
642
+ };
643
+ /**
644
+ * Configuration for MergeTree engine
645
+ * @template T The data type of the records stored in the table.
646
+ */
647
+ type MergeTreeConfig<T> = BaseOlapConfig<T> & {
648
+ engine: ClickHouseEngines.MergeTree;
649
+ };
650
+ /**
651
+ * Configuration for ReplacingMergeTree engine (deduplication)
652
+ * @template T The data type of the records stored in the table.
653
+ */
654
+ type ReplacingMergeTreeConfig<T> = BaseOlapConfig<T> & {
655
+ engine: ClickHouseEngines.ReplacingMergeTree;
656
+ ver?: keyof T & string;
657
+ isDeleted?: keyof T & string;
658
+ };
659
+ /**
660
+ * Configuration for AggregatingMergeTree engine
661
+ * @template T The data type of the records stored in the table.
662
+ */
663
+ type AggregatingMergeTreeConfig<T> = BaseOlapConfig<T> & {
664
+ engine: ClickHouseEngines.AggregatingMergeTree;
665
+ };
666
+ /**
667
+ * Configuration for SummingMergeTree engine
668
+ * @template T The data type of the records stored in the table.
669
+ */
670
+ type SummingMergeTreeConfig<T> = BaseOlapConfig<T> & {
671
+ engine: ClickHouseEngines.SummingMergeTree;
672
+ columns?: string[];
673
+ };
674
+ /**
675
+ * Configuration for CollapsingMergeTree engine
676
+ * @template T The data type of the records stored in the table.
677
+ */
678
+ type CollapsingMergeTreeConfig<T> = BaseOlapConfig<T> & {
679
+ engine: ClickHouseEngines.CollapsingMergeTree;
680
+ sign: keyof T & string;
681
+ };
682
+ /**
683
+ * Configuration for VersionedCollapsingMergeTree engine
684
+ * @template T The data type of the records stored in the table.
685
+ */
686
+ type VersionedCollapsingMergeTreeConfig<T> = BaseOlapConfig<T> & {
687
+ engine: ClickHouseEngines.VersionedCollapsingMergeTree;
688
+ sign: keyof T & string;
689
+ ver: keyof T & string;
690
+ };
691
+ interface ReplicatedEngineProperties {
692
+ keeperPath?: string;
693
+ replicaName?: string;
694
+ }
695
+ /**
696
+ * Configuration for ReplicatedMergeTree engine
697
+ * @template T The data type of the records stored in the table.
698
+ *
699
+ * Note: keeperPath and replicaName are optional. Omit them for ClickHouse Cloud,
700
+ * which manages replication automatically. For self-hosted with ClickHouse Keeper,
701
+ * provide both parameters or neither (to use server defaults).
702
+ */
703
+ type ReplicatedMergeTreeConfig<T> = Omit<MergeTreeConfig<T>, "engine"> & ReplicatedEngineProperties & {
704
+ engine: ClickHouseEngines.ReplicatedMergeTree;
705
+ };
706
+ /**
707
+ * Configuration for ReplicatedReplacingMergeTree engine
708
+ * @template T The data type of the records stored in the table.
709
+ *
710
+ * Note: keeperPath and replicaName are optional. Omit them for ClickHouse Cloud,
711
+ * which manages replication automatically. For self-hosted with ClickHouse Keeper,
712
+ * provide both parameters or neither (to use server defaults).
713
+ */
714
+ type ReplicatedReplacingMergeTreeConfig<T> = Omit<ReplacingMergeTreeConfig<T>, "engine"> & ReplicatedEngineProperties & {
715
+ engine: ClickHouseEngines.ReplicatedReplacingMergeTree;
716
+ };
717
+ /**
718
+ * Configuration for ReplicatedAggregatingMergeTree engine
719
+ * @template T The data type of the records stored in the table.
720
+ *
721
+ * Note: keeperPath and replicaName are optional. Omit them for ClickHouse Cloud,
722
+ * which manages replication automatically. For self-hosted with ClickHouse Keeper,
723
+ * provide both parameters or neither (to use server defaults).
724
+ */
725
+ type ReplicatedAggregatingMergeTreeConfig<T> = Omit<AggregatingMergeTreeConfig<T>, "engine"> & ReplicatedEngineProperties & {
726
+ engine: ClickHouseEngines.ReplicatedAggregatingMergeTree;
727
+ };
728
+ /**
729
+ * Configuration for ReplicatedSummingMergeTree engine
730
+ * @template T The data type of the records stored in the table.
731
+ *
732
+ * Note: keeperPath and replicaName are optional. Omit them for ClickHouse Cloud,
733
+ * which manages replication automatically. For self-hosted with ClickHouse Keeper,
734
+ * provide both parameters or neither (to use server defaults).
735
+ */
736
+ type ReplicatedSummingMergeTreeConfig<T> = Omit<SummingMergeTreeConfig<T>, "engine"> & ReplicatedEngineProperties & {
737
+ engine: ClickHouseEngines.ReplicatedSummingMergeTree;
738
+ };
739
+ /**
740
+ * Configuration for ReplicatedCollapsingMergeTree engine
741
+ * @template T The data type of the records stored in the table.
742
+ *
743
+ * Note: keeperPath and replicaName are optional. Omit them for ClickHouse Cloud,
744
+ * which manages replication automatically. For self-hosted with ClickHouse Keeper,
745
+ * provide both parameters or neither (to use server defaults).
746
+ */
747
+ type ReplicatedCollapsingMergeTreeConfig<T> = Omit<CollapsingMergeTreeConfig<T>, "engine"> & ReplicatedEngineProperties & {
748
+ engine: ClickHouseEngines.ReplicatedCollapsingMergeTree;
749
+ };
750
+ /**
751
+ * Configuration for ReplicatedVersionedCollapsingMergeTree engine
752
+ * @template T The data type of the records stored in the table.
753
+ *
754
+ * Note: keeperPath and replicaName are optional. Omit them for ClickHouse Cloud,
755
+ * which manages replication automatically. For self-hosted with ClickHouse Keeper,
756
+ * provide both parameters or neither (to use server defaults).
757
+ */
758
+ type ReplicatedVersionedCollapsingMergeTreeConfig<T> = Omit<VersionedCollapsingMergeTreeConfig<T>, "engine"> & ReplicatedEngineProperties & {
759
+ engine: ClickHouseEngines.ReplicatedVersionedCollapsingMergeTree;
760
+ };
761
+ /**
762
+ * Configuration for S3Queue engine - only non-alterable constructor parameters.
763
+ * S3Queue-specific settings like 'mode', 'keeper_path', etc. should be specified
764
+ * in the settings field, not here.
765
+ * @template T The data type of the records stored in the table.
766
+ */
767
+ type S3QueueConfig<T> = Omit<BaseOlapConfig<T>, "settings" | "orderByFields" | "partitionBy" | "sampleByExpression"> & {
768
+ engine: ClickHouseEngines.S3Queue;
769
+ /** S3 bucket path with wildcards (e.g., 's3://bucket/data/*.json') */
770
+ s3Path: string;
771
+ /** Data format (e.g., 'JSONEachRow', 'CSV', 'Parquet') */
772
+ format: string;
773
+ /** AWS access key ID (optional, omit for NOSIGN/public buckets) */
774
+ awsAccessKeyId?: string;
775
+ /** AWS secret access key */
776
+ awsSecretAccessKey?: string;
777
+ /** Compression type (e.g., 'gzip', 'zstd') */
778
+ compression?: string;
779
+ /** Custom HTTP headers */
780
+ headers?: {
781
+ [key: string]: string;
782
+ };
783
+ /**
784
+ * S3Queue-specific table settings that can be modified with ALTER TABLE MODIFY SETTING.
785
+ * These settings control the behavior of the S3Queue engine.
786
+ */
787
+ settings?: S3QueueTableSettings;
788
+ };
789
+ /**
790
+ * Configuration for S3 engine
791
+ * Note: S3 engine supports ORDER BY clause, unlike S3Queue, Buffer, and Distributed engines
792
+ * @template T The data type of the records stored in the table.
793
+ */
794
+ type S3Config<T> = Omit<BaseOlapConfig<T>, "sampleByExpression"> & {
795
+ engine: ClickHouseEngines.S3;
796
+ /** S3 path (e.g., 's3://bucket/path/file.json') */
797
+ path: string;
798
+ /** Data format (e.g., 'JSONEachRow', 'CSV', 'Parquet') */
799
+ format: string;
800
+ /** AWS access key ID (optional, omit for NOSIGN/public buckets) */
801
+ awsAccessKeyId?: string;
802
+ /** AWS secret access key */
803
+ awsSecretAccessKey?: string;
804
+ /** Compression type (e.g., 'gzip', 'zstd', 'auto') */
805
+ compression?: string;
806
+ /** Partition strategy (optional) */
807
+ partitionStrategy?: string;
808
+ /** Partition columns in data file (optional) */
809
+ partitionColumnsInDataFile?: string;
810
+ };
811
+ /**
812
+ * Configuration for Buffer engine
813
+ * @template T The data type of the records stored in the table.
814
+ */
815
+ type BufferConfig<T> = Omit<BaseOlapConfig<T>, "orderByFields" | "orderByExpression" | "partitionBy" | "sampleByExpression"> & {
816
+ engine: ClickHouseEngines.Buffer;
817
+ /** Target database name for the destination table */
818
+ targetDatabase: string;
819
+ /** Target table name where data will be flushed */
820
+ targetTable: string;
821
+ /** Number of buffer layers (typically 16) */
822
+ numLayers: number;
823
+ /** Minimum time in seconds before flushing */
824
+ minTime: number;
825
+ /** Maximum time in seconds before flushing */
826
+ maxTime: number;
827
+ /** Minimum number of rows before flushing */
828
+ minRows: number;
829
+ /** Maximum number of rows before flushing */
830
+ maxRows: number;
831
+ /** Minimum bytes before flushing */
832
+ minBytes: number;
833
+ /** Maximum bytes before flushing */
834
+ maxBytes: number;
835
+ /** Optional: Flush time in seconds */
836
+ flushTime?: number;
837
+ /** Optional: Flush number of rows */
838
+ flushRows?: number;
839
+ /** Optional: Flush number of bytes */
840
+ flushBytes?: number;
841
+ };
842
+ /**
843
+ * Configuration for Distributed engine
844
+ * @template T The data type of the records stored in the table.
845
+ */
846
+ type DistributedConfig<T> = Omit<BaseOlapConfig<T>, "orderByFields" | "orderByExpression" | "partitionBy" | "sampleByExpression"> & {
847
+ engine: ClickHouseEngines.Distributed;
848
+ /** Cluster name from the ClickHouse configuration */
849
+ cluster: string;
850
+ /** Database name on the cluster */
851
+ targetDatabase: string;
852
+ /** Table name on the cluster */
853
+ targetTable: string;
854
+ /** Optional: Sharding key expression for data distribution */
855
+ shardingKey?: string;
856
+ /** Optional: Policy name for data distribution */
857
+ policyName?: string;
858
+ };
859
+ /** Kafka table settings. See: https://clickhouse.com/docs/engines/table-engines/integrations/kafka */
860
+ interface KafkaTableSettings {
861
+ kafka_security_protocol?: "PLAINTEXT" | "SSL" | "SASL_PLAINTEXT" | "SASL_SSL";
862
+ kafka_sasl_mechanism?: "GSSAPI" | "PLAIN" | "SCRAM-SHA-256" | "SCRAM-SHA-512" | "OAUTHBEARER";
863
+ kafka_sasl_username?: string;
864
+ kafka_sasl_password?: string;
865
+ kafka_schema?: string;
866
+ kafka_num_consumers?: string;
867
+ kafka_max_block_size?: string;
868
+ kafka_skip_broken_messages?: string;
869
+ kafka_commit_every_batch?: string;
870
+ kafka_client_id?: string;
871
+ kafka_poll_timeout_ms?: string;
872
+ kafka_poll_max_batch_size?: string;
873
+ kafka_flush_interval_ms?: string;
874
+ kafka_consumer_reschedule_ms?: string;
875
+ kafka_thread_per_consumer?: string;
876
+ kafka_handle_error_mode?: "default" | "stream";
877
+ kafka_commit_on_select?: string;
878
+ kafka_max_rows_per_message?: string;
879
+ kafka_compression_codec?: string;
880
+ kafka_compression_level?: string;
881
+ }
882
+ /** Kafka engine for streaming data from Kafka topics. Additional settings go in `settings`. */
883
+ type KafkaConfig<T> = Omit<BaseOlapConfig<T>, "orderByFields" | "orderByExpression" | "partitionBy" | "sampleByExpression"> & {
884
+ engine: ClickHouseEngines.Kafka;
885
+ brokerList: string;
886
+ topicList: string;
887
+ groupName: string;
888
+ format: string;
889
+ settings?: KafkaTableSettings;
890
+ };
891
+ /**
892
+ * Configuration for IcebergS3 engine - read-only Iceberg table access
893
+ *
894
+ * Provides direct querying of Apache Iceberg tables stored on S3.
895
+ * Data is not copied; queries stream directly from Parquet/ORC files.
896
+ *
897
+ * @template T The data type of the records stored in the table.
898
+ *
899
+ * @example
900
+ * ```typescript
901
+ * const lakeEvents = new OlapTable<Event>("lake_events", {
902
+ * engine: ClickHouseEngines.IcebergS3,
903
+ * path: "s3://datalake/events/",
904
+ * format: "Parquet",
905
+ * awsAccessKeyId: mooseRuntimeEnv.get("AWS_ACCESS_KEY_ID"),
906
+ * awsSecretAccessKey: mooseRuntimeEnv.get("AWS_SECRET_ACCESS_KEY")
907
+ * });
908
+ * ```
909
+ *
910
+ * @remarks
911
+ * - IcebergS3 engine is read-only
912
+ * - Does not support ORDER BY, PARTITION BY, or SAMPLE BY clauses
913
+ * - Queries always see the latest Iceberg snapshot (with metadata cache)
914
+ */
915
+ type IcebergS3Config<T> = Omit<BaseOlapConfig<T>, "orderByFields" | "orderByExpression" | "partitionBy" | "sampleByExpression"> & {
916
+ engine: ClickHouseEngines.IcebergS3;
917
+ /** S3 path to Iceberg table root (e.g., 's3://bucket/warehouse/events/') */
918
+ path: string;
919
+ /** Data format - 'Parquet' or 'ORC' */
920
+ format: "Parquet" | "ORC";
921
+ /** AWS access key ID (optional, omit for NOSIGN/public buckets) */
922
+ awsAccessKeyId?: string;
923
+ /** AWS secret access key (optional) */
924
+ awsSecretAccessKey?: string;
925
+ /** Compression type (optional: 'gzip', 'zstd', 'auto') */
926
+ compression?: string;
927
+ };
928
+ /**
929
+ * Configuration for Merge engine - read-only view over multiple tables matching a regex pattern.
930
+ *
931
+ * @template T The data type of the records in the source tables.
932
+ *
933
+ * @example
934
+ * ```typescript
935
+ * const allEvents = new OlapTable<Event>("all_events", {
936
+ * engine: ClickHouseEngines.Merge,
937
+ * sourceDatabase: "currentDatabase()",
938
+ * tablesRegexp: "^events_\\d+$",
939
+ * });
940
+ * ```
941
+ *
942
+ * @remarks
943
+ * - Merge engine is read-only; INSERT operations are not supported
944
+ * - Cannot be used as a destination in IngestPipeline
945
+ * - Does not support ORDER BY, PARTITION BY, or SAMPLE BY clauses
946
+ */
947
+ type MergeConfig<T> = Omit<BaseOlapConfig<T>, "orderByFields" | "orderByExpression" | "partitionBy" | "sampleByExpression"> & {
948
+ engine: ClickHouseEngines.Merge;
949
+ /** Database to scan for source tables (literal name, currentDatabase(), or REGEXP(...)) */
950
+ sourceDatabase: string;
951
+ /** Regex pattern to match table names in the source database */
952
+ tablesRegexp: string;
953
+ };
954
+ /**
955
+ * Legacy configuration (backward compatibility) - defaults to MergeTree engine
956
+ * @template T The data type of the records stored in the table.
957
+ */
958
+ type LegacyOlapConfig<T> = BaseOlapConfig<T>;
959
+ type EngineConfig<T> = MergeTreeConfig<T> | ReplacingMergeTreeConfig<T> | AggregatingMergeTreeConfig<T> | SummingMergeTreeConfig<T> | CollapsingMergeTreeConfig<T> | VersionedCollapsingMergeTreeConfig<T> | ReplicatedMergeTreeConfig<T> | ReplicatedReplacingMergeTreeConfig<T> | ReplicatedAggregatingMergeTreeConfig<T> | ReplicatedSummingMergeTreeConfig<T> | ReplicatedCollapsingMergeTreeConfig<T> | ReplicatedVersionedCollapsingMergeTreeConfig<T> | S3QueueConfig<T> | S3Config<T> | BufferConfig<T> | DistributedConfig<T> | IcebergS3Config<T> | KafkaConfig<T> | MergeConfig<T>;
960
+ /**
961
+ * Union of all engine-specific configurations (new API)
962
+ * @template T The data type of the records stored in the table.
963
+ */
964
+ type OlapConfig<T> = EngineConfig<T> | LegacyOlapConfig<T>;
965
+ /**
966
+ * Represents an OLAP (Online Analytical Processing) table, typically corresponding to a ClickHouse table.
967
+ * Provides a typed interface for interacting with the table.
968
+ *
969
+ * @template T The data type of the records stored in the table. The structure of T defines the table schema.
970
+ */
971
+ declare class OlapTable<T> extends TypedBase<T, OlapConfig<T>> {
972
+ name: IdentifierBrandedString;
973
+ /** @internal */
974
+ readonly kind = "OlapTable";
975
+ /** @internal Memoized ClickHouse client for reusing connections across insert calls */
976
+ private _memoizedClient?;
977
+ /** @internal Hash of the configuration used to create the memoized client */
978
+ private _configHash?;
979
+ /** @internal Cached table name to avoid repeated generation */
980
+ private _cachedTableName?;
981
+ /**
982
+ * Creates a new OlapTable instance.
983
+ * @param name The name of the table. This name is used for the underlying ClickHouse table.
984
+ * @param config Optional configuration for the OLAP table.
985
+ */
986
+ constructor(name: string, config?: OlapConfig<T>);
987
+ /** @internal **/
988
+ constructor(name: string, config: OlapConfig<T>, schema: IJsonSchemaCollection.IV3_1, columns: Column[], validators?: TypiaValidators<T>);
989
+ /**
990
+ * Generates the versioned table name following Moose's naming convention
991
+ * Format: {tableName}_{version_with_dots_replaced_by_underscores}
992
+ */
993
+ private generateTableName;
994
+ /**
995
+ * Creates a fast hash of the ClickHouse configuration.
996
+ * Uses crypto.createHash for better performance than JSON.stringify.
997
+ *
998
+ * @private
999
+ */
1000
+ private createConfigHash;
1001
+ /**
1002
+ * Gets or creates a memoized ClickHouse client.
1003
+ * The client is cached and reused across multiple insert calls for better performance.
1004
+ * If the configuration changes, a new client will be created.
1005
+ *
1006
+ * @private
1007
+ */
1008
+ private getMemoizedClient;
1009
+ /**
1010
+ * Closes the memoized ClickHouse client if it exists.
1011
+ * This is useful for cleaning up connections when the table instance is no longer needed.
1012
+ * The client will be automatically recreated on the next insert call if needed.
1013
+ */
1014
+ closeClient(): Promise<void>;
1015
+ /**
1016
+ * Validates a single record using typia's comprehensive type checking.
1017
+ * This provides the most accurate validation as it uses the exact TypeScript type information.
1018
+ *
1019
+ * @param record The record to validate
1020
+ * @returns Validation result with detailed error information
1021
+ */
1022
+ validateRecord(record: unknown): {
1023
+ success: boolean;
1024
+ data?: T;
1025
+ errors?: string[];
1026
+ };
1027
+ /**
1028
+ * Type guard function using typia's is() function.
1029
+ * Provides compile-time type narrowing for TypeScript.
1030
+ *
1031
+ * @param record The record to check
1032
+ * @returns True if record matches type T, with type narrowing
1033
+ */
1034
+ isValidRecord(record: unknown): record is T;
1035
+ /**
1036
+ * Assert that a record matches type T, throwing detailed errors if not.
1037
+ * Uses typia's assert() function for the most detailed error reporting.
1038
+ *
1039
+ * @param record The record to assert
1040
+ * @returns The validated and typed record
1041
+ * @throws Detailed validation error if record doesn't match type T
1042
+ */
1043
+ assertValidRecord(record: unknown): T;
1044
+ /**
1045
+ * Validates an array of records with comprehensive error reporting.
1046
+ * Uses the most appropriate validation method available (typia or basic).
1047
+ *
1048
+ * @param data Array of records to validate
1049
+ * @returns Detailed validation results
1050
+ */
1051
+ validateRecords(data: unknown[]): Promise<ValidationResult<T>>;
1052
+ /**
1053
+ * Optimized batch retry that minimizes individual insert operations.
1054
+ * Groups records into smaller batches to reduce round trips while still isolating failures.
1055
+ *
1056
+ * @private
1057
+ */
1058
+ private retryIndividualRecords;
1059
+ /**
1060
+ * Validates input parameters and strategy compatibility
1061
+ * @private
1062
+ */
1063
+ private validateInsertParameters;
1064
+ /**
1065
+ * Handles early return cases for empty data
1066
+ * @private
1067
+ */
1068
+ private handleEmptyData;
1069
+ /**
1070
+ * Performs pre-insertion validation for array data
1071
+ * @private
1072
+ */
1073
+ private performPreInsertionValidation;
1074
+ /**
1075
+ * Handles validation errors based on the specified strategy
1076
+ * @private
1077
+ */
1078
+ private handleValidationErrors;
1079
+ /**
1080
+ * Checks if validation errors exceed configured thresholds
1081
+ * @private
1082
+ */
1083
+ private checkValidationThresholds;
1084
+ /**
1085
+ * Optimized insert options preparation with better memory management
1086
+ * @private
1087
+ */
1088
+ private prepareInsertOptions;
1089
+ /**
1090
+ * Creates success result for completed insertions
1091
+ * @private
1092
+ */
1093
+ private createSuccessResult;
1094
+ /**
1095
+ * Handles insertion errors based on the specified strategy
1096
+ * @private
1097
+ */
1098
+ private handleInsertionError;
1099
+ /**
1100
+ * Handles the isolate strategy for insertion errors
1101
+ * @private
1102
+ */
1103
+ private handleIsolateStrategy;
1104
+ /**
1105
+ * Checks if insertion errors exceed configured thresholds
1106
+ * @private
1107
+ */
1108
+ private checkInsertionThresholds;
1109
+ /**
1110
+ * Recursively transforms a record to match ClickHouse's JSONEachRow requirements
1111
+ *
1112
+ * - For every Array(Nested(...)) field at any depth, each item is wrapped in its own array and recursively processed.
1113
+ * - For every Nested struct (not array), it recurses into the struct.
1114
+ * - This ensures compatibility with kafka_clickhouse_sync
1115
+ *
1116
+ * @param record The input record to transform (may be deeply nested)
1117
+ * @param columns The schema columns for this level (defaults to this.columnArray at the top level)
1118
+ * @returns The transformed record, ready for ClickHouse JSONEachRow insertion
1119
+ */
1120
+ private mapToClickhouseRecord;
1121
+ /**
1122
+ * Inserts data directly into the ClickHouse table with enhanced error handling and validation.
1123
+ * This method establishes a direct connection to ClickHouse using the project configuration
1124
+ * and inserts the provided data into the versioned table.
1125
+ *
1126
+ * PERFORMANCE OPTIMIZATIONS:
1127
+ * - Memoized client connections with fast config hashing
1128
+ * - Single-pass validation with pre-allocated arrays
1129
+ * - Batch-optimized retry strategy (batches of 10, then individual)
1130
+ * - Optimized ClickHouse settings for large datasets
1131
+ * - Reduced memory allocations and object creation
1132
+ *
1133
+ * Uses advanced typia validation when available for comprehensive type checking,
1134
+ * with fallback to basic validation for compatibility.
1135
+ *
1136
+ * The ClickHouse client is memoized and reused across multiple insert calls for better performance.
1137
+ * If the configuration changes, a new client will be automatically created.
1138
+ *
1139
+ * @param data Array of objects conforming to the table schema, or a Node.js Readable stream
1140
+ * @param options Optional configuration for error handling, validation, and insertion behavior
1141
+ * @returns Promise resolving to detailed insertion results
1142
+ * @throws {ConfigError} When configuration cannot be read or parsed
1143
+ * @throws {ClickHouseError} When insertion fails based on the error strategy
1144
+ * @throws {ValidationError} When validation fails and strategy is 'fail-fast'
1145
+ *
1146
+ * @example
1147
+ * ```typescript
1148
+ * // Create an OlapTable instance (typia validators auto-injected)
1149
+ * const userTable = new OlapTable<User>('users');
1150
+ *
1151
+ * // Insert with comprehensive typia validation
1152
+ * const result1 = await userTable.insert([
1153
+ * { id: 1, name: 'John', email: 'john@example.com' },
1154
+ * { id: 2, name: 'Jane', email: 'jane@example.com' }
1155
+ * ]);
1156
+ *
1157
+ * // Insert data with stream input (validation not available for streams)
1158
+ * const dataStream = new Readable({
1159
+ * objectMode: true,
1160
+ * read() { // Stream implementation }
1161
+ * });
1162
+ * const result2 = await userTable.insert(dataStream, { strategy: 'fail-fast' });
1163
+ *
1164
+ * // Insert with validation disabled for performance
1165
+ * const result3 = await userTable.insert(data, { validate: false });
1166
+ *
1167
+ * // Insert with error handling strategies
1168
+ * const result4 = await userTable.insert(mixedData, {
1169
+ * strategy: 'isolate',
1170
+ * allowErrorsRatio: 0.1,
1171
+ * validate: true // Use typia validation (default)
1172
+ * });
1173
+ *
1174
+ * // Optional: Clean up connection when completely done
1175
+ * await userTable.closeClient();
1176
+ * ```
1177
+ */
1178
+ insert(data: T[] | Readable, options?: InsertOptions): Promise<InsertResult<T>>;
1179
+ }
1180
+
1181
+ /**
1182
+ * @fileoverview Stream SDK for data streaming operations in Moose.
1183
+ *
1184
+ * This module provides the core streaming functionality including:
1185
+ * - Stream creation and configuration
1186
+ * - Message transformations between streams
1187
+ * - Consumer registration for message processing
1188
+ * - Dead letter queue handling for error recovery
1189
+ *
1190
+ * @module Stream
1191
+ */
1192
+
1193
+ /**
1194
+ * Represents zero, one, or many values of type T.
1195
+ * Used for flexible return types in transformations where a single input
1196
+ * can produce no output, one output, or multiple outputs.
1197
+ *
1198
+ * @template T The type of the value(s)
1199
+ * @example
1200
+ * ```typescript
1201
+ * // Can return a single value
1202
+ * const single: ZeroOrMany<string> = "hello";
1203
+ *
1204
+ * // Can return an array
1205
+ * const multiple: ZeroOrMany<string> = ["hello", "world"];
1206
+ *
1207
+ * // Can return null/undefined to filter out
1208
+ * const filtered: ZeroOrMany<string> = null;
1209
+ * ```
1210
+ */
1211
+ type ZeroOrMany<T> = T | T[] | undefined | null;
1212
+ /**
1213
+ * Function type for transforming records from one type to another.
1214
+ * Supports both synchronous and asynchronous transformations.
1215
+ *
1216
+ * @template T The input record type
1217
+ * @template U The output record type
1218
+ * @param record The input record to transform
1219
+ * @returns The transformed record(s), or null/undefined to filter out
1220
+ *
1221
+ * @example
1222
+ * ```typescript
1223
+ * const transform: SyncOrAsyncTransform<InputType, OutputType> = (record) => {
1224
+ * return { ...record, processed: true };
1225
+ * };
1226
+ * ```
1227
+ */
1228
+ type SyncOrAsyncTransform<T, U> = (record: T) => ZeroOrMany<U> | Promise<ZeroOrMany<U>>;
1229
+ /**
1230
+ * Function type for consuming records without producing output.
1231
+ * Used for side effects like logging, external API calls, or database writes.
1232
+ *
1233
+ * @template T The record type to consume
1234
+ * @param record The record to process
1235
+ * @returns Promise<void> or void
1236
+ *
1237
+ * @example
1238
+ * ```typescript
1239
+ * const consumer: Consumer<UserEvent> = async (event) => {
1240
+ * await sendToAnalytics(event);
1241
+ * };
1242
+ * ```
1243
+ */
1244
+ type Consumer<T> = (record: T) => Promise<void> | void;
1245
+ /**
1246
+ * Configuration options for stream transformations.
1247
+ *
1248
+ * @template T The type of records being transformed
1249
+ */
1250
+ interface TransformConfig<T> {
1251
+ /**
1252
+ * Optional version identifier for this transformation.
1253
+ * Multiple transformations to the same destination can coexist with different versions.
1254
+ */
1255
+ version?: string;
1256
+ /**
1257
+ * Optional metadata for documentation and tracking purposes.
1258
+ */
1259
+ metadata?: {
1260
+ description?: string;
1261
+ };
1262
+ /**
1263
+ * Optional dead letter queue for handling transformation failures.
1264
+ * Failed records will be sent to this queue for manual inspection or reprocessing.
1265
+ * Uses {@link Stream.defaultDeadLetterQueue} by default
1266
+ * unless a DeadLetterQueue is provided, or it is explicitly disabled with a null value
1267
+ */
1268
+ deadLetterQueue?: DeadLetterQueue<T> | null;
1269
+ /**
1270
+ * @internal Source file path where this transform was declared.
1271
+ * Automatically captured from stack trace.
1272
+ */
1273
+ sourceFile?: string;
1274
+ }
1275
+ /**
1276
+ * Configuration options for stream consumers.
1277
+ *
1278
+ * @template T The type of records being consumed
1279
+ */
1280
+ interface ConsumerConfig<T> {
1281
+ /**
1282
+ * Optional version identifier for this consumer.
1283
+ * Multiple consumers can coexist with different versions.
1284
+ */
1285
+ version?: string;
1286
+ /**
1287
+ * Optional dead letter queue for handling consumer failures.
1288
+ * Failed records will be sent to this queue for manual inspection or reprocessing.
1289
+ * Uses {@link Stream.defaultDeadLetterQueue} by default
1290
+ * unless a DeadLetterQueue is provided, or it is explicitly disabled with a null value
1291
+ */
1292
+ deadLetterQueue?: DeadLetterQueue<T> | null;
1293
+ /**
1294
+ * @internal Source file path where this consumer was declared.
1295
+ * Automatically captured from stack trace.
1296
+ */
1297
+ sourceFile?: string;
1298
+ }
1299
+ type SchemaRegistryEncoding = "JSON" | "AVRO" | "PROTOBUF";
1300
+ type SchemaRegistryReference = {
1301
+ id: number;
1302
+ } | {
1303
+ subjectLatest: string;
1304
+ } | {
1305
+ subject: string;
1306
+ version: number;
1307
+ };
1308
+ interface KafkaSchemaConfig {
1309
+ kind: SchemaRegistryEncoding;
1310
+ reference: SchemaRegistryReference;
1311
+ }
1312
+ /**
1313
+ * Represents a message routed to a specific destination stream.
1314
+ * Used internally by the multi-transform functionality to specify
1315
+ * where transformed messages should be sent.
1316
+ *
1317
+ * @internal
1318
+ */
1319
+ declare class RoutedMessage {
1320
+ /** The destination stream for the message */
1321
+ destination: Stream<any>;
1322
+ /** The message value(s) to send */
1323
+ values: ZeroOrMany<any>;
1324
+ /**
1325
+ * Creates a new routed message.
1326
+ *
1327
+ * @param destination The target stream
1328
+ * @param values The message(s) to route
1329
+ */
1330
+ constructor(destination: Stream<any>, values: ZeroOrMany<any>);
1331
+ }
1332
+ /**
1333
+ * Configuration options for a data stream (e.g., a Redpanda topic).
1334
+ * @template T The data type of the messages in the stream.
1335
+ */
1336
+ interface StreamConfig<T> {
1337
+ /**
1338
+ * Specifies the number of partitions for the stream. Affects parallelism and throughput.
1339
+ */
1340
+ parallelism?: number;
1341
+ /**
1342
+ * Specifies the data retention period for the stream in seconds. Messages older than this may be deleted.
1343
+ */
1344
+ retentionPeriod?: number;
1345
+ /**
1346
+ * An optional destination OLAP table where messages from this stream should be automatically ingested.
1347
+ */
1348
+ destination?: OlapTable<T>;
1349
+ /**
1350
+ * An optional version string for this configuration. Can be used for tracking changes or managing deployments.
1351
+ */
1352
+ version?: string;
1353
+ metadata?: {
1354
+ description?: string;
1355
+ };
1356
+ lifeCycle?: LifeCycle;
1357
+ defaultDeadLetterQueue?: DeadLetterQueue<T>;
1358
+ /** Optional Schema Registry configuration for this stream */
1359
+ schemaConfig?: KafkaSchemaConfig;
1360
+ }
1361
+ /**
1362
+ * Represents a data stream, typically corresponding to a Redpanda topic.
1363
+ * Provides a typed interface for producing to and consuming from the stream, and defining transformations.
1364
+ *
1365
+ * @template T The data type of the messages flowing through the stream. The structure of T defines the message schema.
1366
+ */
1367
+ declare class Stream<T> extends TypedBase<T, StreamConfig<T>> {
1368
+ defaultDeadLetterQueue?: DeadLetterQueue<T>;
1369
+ /** @internal Memoized KafkaJS producer for reusing connections across sends */
1370
+ private _memoizedProducer?;
1371
+ /** @internal Hash of the configuration used to create the memoized Kafka producer */
1372
+ private _kafkaConfigHash?;
1373
+ /**
1374
+ * Creates a new Stream instance.
1375
+ * @param name The name of the stream. This name is used for the underlying Redpanda topic.
1376
+ * @param config Optional configuration for the stream.
1377
+ */
1378
+ constructor(name: string, config?: StreamConfig<T>);
1379
+ /**
1380
+ * @internal
1381
+ * Note: `validators` parameter is a positional placeholder (always undefined for Stream).
1382
+ * It exists because TypedBase has validators as the 5th param, and we need to pass
1383
+ * allowExtraFields as the 6th param. Stream doesn't use validators.
1384
+ */
1385
+ constructor(name: string, config: StreamConfig<T>, schema: IJsonSchemaCollection.IV3_1, columns: Column[], validators: undefined, allowExtraFields: boolean);
1386
+ /**
1387
+ * Internal map storing transformation configurations.
1388
+ * Maps destination stream names to arrays of transformation functions and their configs.
1389
+ *
1390
+ * @internal
1391
+ */
1392
+ _transformations: Map<string, [Stream<any>, SyncOrAsyncTransform<T, any>, TransformConfig<T>][]>;
1393
+ /**
1394
+ * Internal function for multi-stream transformations.
1395
+ * Allows a single transformation to route messages to multiple destinations.
1396
+ *
1397
+ * @internal
1398
+ */
1399
+ _multipleTransformations?: (record: T) => [RoutedMessage];
1400
+ /**
1401
+ * Internal array storing consumer configurations.
1402
+ *
1403
+ * @internal
1404
+ */
1405
+ _consumers: {
1406
+ consumer: Consumer<T>;
1407
+ config: ConsumerConfig<T>;
1408
+ }[];
1409
+ /**
1410
+ * Builds the full Kafka topic name including optional namespace and version suffix.
1411
+ * Version suffix is appended as _x_y_z where dots in version are replaced with underscores.
1412
+ */
1413
+ private buildFullTopicName;
1414
+ /**
1415
+ * Creates a fast hash string from relevant Kafka configuration fields.
1416
+ */
1417
+ private createConfigHash;
1418
+ /**
1419
+ * Gets or creates a memoized KafkaJS producer using runtime configuration.
1420
+ */
1421
+ private getMemoizedProducer;
1422
+ /**
1423
+ * Closes the memoized Kafka producer if it exists.
1424
+ */
1425
+ closeProducer(): Promise<void>;
1426
+ /**
1427
+ * Sends one or more records to this stream's Kafka topic.
1428
+ * Values are JSON-serialized as message values.
1429
+ */
1430
+ send(values: ZeroOrMany<T>): Promise<void>;
1431
+ /**
1432
+ * Adds a transformation step that processes messages from this stream and sends the results to a destination stream.
1433
+ * Multiple transformations to the same destination stream can be added if they have distinct `version` identifiers in their config.
1434
+ *
1435
+ * @template U The data type of the messages in the destination stream.
1436
+ * @param destination The destination stream for the transformed messages.
1437
+ * @param transformation A function that takes a message of type T and returns zero or more messages of type U (or a Promise thereof).
1438
+ * Return `null` or `undefined` or an empty array `[]` to filter out a message. Return an array to emit multiple messages.
1439
+ * @param config Optional configuration for this specific transformation step, like a version.
1440
+ */
1441
+ addTransform<U>(destination: Stream<U>, transformation: SyncOrAsyncTransform<T, U>, config?: TransformConfig<T>): void;
1442
+ /**
1443
+ * Adds a consumer function that processes messages from this stream.
1444
+ * Multiple consumers can be added if they have distinct `version` identifiers in their config.
1445
+ *
1446
+ * @param consumer A function that takes a message of type T and performs an action (e.g., side effect, logging). Should return void or Promise<void>.
1447
+ * @param config Optional configuration for this specific consumer, like a version.
1448
+ */
1449
+ addConsumer(consumer: Consumer<T>, config?: ConsumerConfig<T>): void;
1450
+ /**
1451
+ * Helper method for `addMultiTransform` to specify the destination and values for a routed message.
1452
+ * @param values The value or values to send to this stream.
1453
+ * @returns A `RoutedMessage` object associating the values with this stream.
1454
+ *
1455
+ * @example
1456
+ * ```typescript
1457
+ * sourceStream.addMultiTransform((record) => [
1458
+ * destinationStream1.routed(transformedRecord1),
1459
+ * destinationStream2.routed([record2a, record2b])
1460
+ * ]);
1461
+ * ```
1462
+ */
1463
+ routed: (values: ZeroOrMany<T>) => RoutedMessage;
1464
+ /**
1465
+ * Adds a single transformation function that can route messages to multiple destination streams.
1466
+ * This is an alternative to adding multiple individual `addTransform` calls.
1467
+ * Only one multi-transform function can be added per stream.
1468
+ *
1469
+ * @param transformation A function that takes a message of type T and returns an array of `RoutedMessage` objects,
1470
+ * each specifying a destination stream and the message(s) to send to it.
1471
+ */
1472
+ addMultiTransform(transformation: (record: T) => [RoutedMessage]): void;
1473
+ }
1474
+ /**
1475
+ * Base model for dead letter queue entries.
1476
+ * Contains the original failed record along with error information.
1477
+ */
1478
+ interface DeadLetterModel {
1479
+ /** The original record that failed processing */
1480
+ originalRecord: Record<string, any>;
1481
+ /** Human-readable error message describing the failure */
1482
+ errorMessage: string;
1483
+ /** Classification of the error type (e.g., "ValidationError", "TransformError") */
1484
+ errorType: string;
1485
+ /** Timestamp when the failure occurred */
1486
+ failedAt: Date;
1487
+ /** The source component where the failure occurred */
1488
+ source: "api" | "transform" | "table";
1489
+ }
1490
+ /**
1491
+ * Enhanced dead letter model with type recovery functionality.
1492
+ * Extends the base model with the ability to recover the original typed record.
1493
+ *
1494
+ * @template T The original record type before failure
1495
+ */
1496
+ interface DeadLetter<T> extends DeadLetterModel {
1497
+ /**
1498
+ * Recovers the original record as its typed form.
1499
+ * Useful for reprocessing failed records with proper type safety.
1500
+ *
1501
+ * @returns The original record cast to type T
1502
+ */
1503
+ asTyped: () => T;
1504
+ }
1505
+ /**
1506
+ * Specialized stream for handling failed records (dead letters).
1507
+ * Provides type-safe access to failed records for reprocessing or analysis.
1508
+ *
1509
+ * @template T The original record type that failed processing
1510
+ *
1511
+ * @example
1512
+ * ```typescript
1513
+ * const dlq = new DeadLetterQueue<UserEvent>("user-events-dlq");
1514
+ *
1515
+ * dlq.addConsumer(async (deadLetter) => {
1516
+ * const originalEvent = deadLetter.asTyped();
1517
+ * console.log(`Failed event: ${deadLetter.errorMessage}`);
1518
+ * // Potentially reprocess or alert
1519
+ * });
1520
+ * ```
1521
+ */
1522
+ declare class DeadLetterQueue<T> extends Stream<DeadLetterModel> {
1523
+ /**
1524
+ * Creates a new DeadLetterQueue instance.
1525
+ * @param name The name of the dead letter queue stream
1526
+ * @param config Optional configuration for the stream. The metadata property is always present and includes stackTrace.
1527
+ */
1528
+ constructor(name: string, config?: StreamConfig<DeadLetterModel>);
1529
+ /** @internal **/
1530
+ constructor(name: string, config: StreamConfig<DeadLetterModel>, validate: (originalRecord: any) => T);
1531
+ /**
1532
+ * Internal type guard function for validating and casting original records.
1533
+ *
1534
+ * @internal
1535
+ */
1536
+ private typeGuard;
1537
+ /**
1538
+ * Adds a transformation step for dead letter records.
1539
+ * The transformation function receives a DeadLetter<T> with type recovery capabilities.
1540
+ *
1541
+ * @template U The output type for the transformation
1542
+ * @param destination The destination stream for transformed messages
1543
+ * @param transformation Function to transform dead letter records
1544
+ * @param config Optional transformation configuration
1545
+ */
1546
+ addTransform<U>(destination: Stream<U>, transformation: SyncOrAsyncTransform<DeadLetter<T>, U>, config?: TransformConfig<DeadLetterModel>): void;
1547
+ /**
1548
+ * Adds a consumer for dead letter records.
1549
+ * The consumer function receives a DeadLetter<T> with type recovery capabilities.
1550
+ *
1551
+ * @param consumer Function to process dead letter records
1552
+ * @param config Optional consumer configuration
1553
+ */
1554
+ addConsumer(consumer: Consumer<DeadLetter<T>>, config?: ConsumerConfig<DeadLetterModel>): void;
1555
+ /**
1556
+ * Adds a multi-stream transformation for dead letter records.
1557
+ * The transformation function receives a DeadLetter<T> with type recovery capabilities.
1558
+ *
1559
+ * @param transformation Function to route dead letter records to multiple destinations
1560
+ */
1561
+ addMultiTransform(transformation: (record: DeadLetter<T>) => [RoutedMessage]): void;
1562
+ }
1563
+
1564
+ /**
1565
+ * Context passed to task handlers. Single param to future-proof API changes.
1566
+ *
1567
+ * - state: shared mutable state for the task and its lifecycle hooks
1568
+ * - input: optional typed input for the task (undefined when task has no input)
1569
+ */
1570
+ /**
1571
+ * Task handler context. If the task declares an input type (T != null),
1572
+ * `input` is required and strongly typed. For no-input tasks (T = null),
1573
+ * `input` is omitted/optional.
1574
+ */
1575
+ type TaskContext<TInput> = TInput extends null ? {
1576
+ state: any;
1577
+ input?: null;
1578
+ } : {
1579
+ state: any;
1580
+ input: TInput;
1581
+ };
1582
+ /**
1583
+ * Configuration options for defining a task within a workflow.
1584
+ *
1585
+ * @template T - The input type for the task
1586
+ * @template R - The return type for the task
1587
+ */
1588
+ interface TaskConfig<T, R> {
1589
+ /** The main function that executes the task logic */
1590
+ run: (context: TaskContext<T>) => Promise<R>;
1591
+ /**
1592
+ * Optional array of tasks to execute after this task completes successfully.
1593
+ * Supports all combinations of input types (real type or null) and output types (real type or void).
1594
+ * When this task returns void, onComplete tasks expect null as input.
1595
+ * When this task returns a real type, onComplete tasks expect that type as input.
1596
+ */
1597
+ onComplete?: (Task<R extends void ? null : R, any> | Task<R extends void ? null : R, void>)[];
1598
+ /**
1599
+ * Optional function that is called when the task is cancelled.
1600
+ */
1601
+ /** Optional function that is called when the task is cancelled. */
1602
+ onCancel?: (context: TaskContext<T>) => Promise<void>;
1603
+ /** Optional timeout duration for the task execution (e.g., "30s", "5m") */
1604
+ timeout?: string;
1605
+ /** Optional number of retry attempts if the task fails */
1606
+ retries?: number;
1607
+ }
1608
+ /**
1609
+ * Represents a single task within a workflow system.
1610
+ *
1611
+ * A Task encapsulates the execution logic, completion handlers, and configuration
1612
+ * for a unit of work that can be chained with other tasks in a workflow.
1613
+ *
1614
+ * @template T - The input type that this task expects
1615
+ * @template R - The return type that this task produces
1616
+ */
1617
+ declare class Task<T, R> {
1618
+ readonly name: string;
1619
+ readonly config: TaskConfig<T, R>;
1620
+ /**
1621
+ * Creates a new Task instance.
1622
+ *
1623
+ * @param name - Unique identifier for the task
1624
+ * @param config - Configuration object defining the task behavior
1625
+ *
1626
+ * @example
1627
+ * ```typescript
1628
+ * // No input, no output
1629
+ * const task1 = new Task<null, void>("task1", {
1630
+ * run: async () => {
1631
+ * console.log("No input/output");
1632
+ * }
1633
+ * });
1634
+ *
1635
+ * // No input, but has output
1636
+ * const task2 = new Task<null, OutputType>("task2", {
1637
+ * run: async () => {
1638
+ * return someOutput;
1639
+ * }
1640
+ * });
1641
+ *
1642
+ * // Has input, no output
1643
+ * const task3 = new Task<InputType, void>("task3", {
1644
+ * run: async (input: InputType) => {
1645
+ * // process input but return nothing
1646
+ * }
1647
+ * });
1648
+ *
1649
+ * // Has both input and output
1650
+ * const task4 = new Task<InputType, OutputType>("task4", {
1651
+ * run: async (input: InputType) => {
1652
+ * return process(input);
1653
+ * }
1654
+ * });
1655
+ * ```
1656
+ */
1657
+ constructor(name: string, config: TaskConfig<T, R>);
1658
+ }
1659
+ /**
1660
+ * Configuration options for defining a workflow.
1661
+ *
1662
+ * A workflow orchestrates the execution of multiple tasks in a defined sequence
1663
+ * or pattern, with support for scheduling, retries, and timeouts.
1664
+ */
1665
+ interface WorkflowConfig {
1666
+ /**
1667
+ * The initial task that begins the workflow execution.
1668
+ * Supports all combinations of input types (real type or null) and output types (real type or void):
1669
+ * - Task<null, OutputType>: No input, returns a type
1670
+ * - Task<null, void>: No input, returns nothing
1671
+ * - Task<InputType, OutputType>: Has input, returns a type
1672
+ * - Task<InputType, void>: Has input, returns nothing
1673
+ */
1674
+ startingTask: Task<null, any> | Task<null, void> | Task<any, any> | Task<any, void>;
1675
+ /** Optional number of retry attempts if the entire workflow fails */
1676
+ retries?: number;
1677
+ /** Optional timeout duration for the entire workflow execution (e.g., "10m", "1h") */
1678
+ timeout?: string;
1679
+ /** Optional cron-style schedule string for automated workflow execution */
1680
+ schedule?: string;
1681
+ }
1682
+ /**
1683
+ * Represents a complete workflow composed of interconnected tasks.
1684
+ *
1685
+ * A Workflow manages the execution flow of multiple tasks, handling scheduling,
1686
+ * error recovery, and task orchestration. Once created, workflows are automatically
1687
+ * registered with the internal Moose system.
1688
+ *
1689
+ * @example
1690
+ * ```typescript
1691
+ * const dataProcessingWorkflow = new Workflow("dataProcessing", {
1692
+ * startingTask: extractDataTask,
1693
+ * schedule: "0 2 * * *", // Run daily at 2 AM
1694
+ * timeout: "1h",
1695
+ * retries: 2
1696
+ * });
1697
+ * ```
1698
+ */
1699
+ declare class Workflow {
1700
+ readonly name: string;
1701
+ readonly config: WorkflowConfig;
1702
+ /**
1703
+ * Creates a new Workflow instance and registers it with the Moose system.
1704
+ *
1705
+ * @param name - Unique identifier for the workflow
1706
+ * @param config - Configuration object defining the workflow behavior and task orchestration
1707
+ * @throws {Error} When the workflow contains null/undefined tasks or infinite loops
1708
+ */
1709
+ constructor(name: string, config: WorkflowConfig);
1710
+ /**
1711
+ * Validates the task graph to ensure there are no null tasks or infinite loops.
1712
+ *
1713
+ * @private
1714
+ * @param startingTask - The starting task to begin validation from
1715
+ * @param workflowName - The name of the workflow being validated (for error messages)
1716
+ * @throws {Error} When null/undefined tasks are found or infinite loops are detected
1717
+ */
1718
+ private validateTaskGraph;
1719
+ }
1720
+
1721
+ /**
1722
+ * @template T The data type of the messages expected by the destination stream.
1723
+ */
1724
+ interface IngestConfig<T> {
1725
+ /**
1726
+ * The destination stream where the ingested data should be sent.
1727
+ */
1728
+ destination: Stream<T>;
1729
+ deadLetterQueue?: DeadLetterQueue<T>;
1730
+ /**
1731
+ * An optional version string for this configuration.
1732
+ */
1733
+ version?: string;
1734
+ /**
1735
+ * An optional custom path for the ingestion endpoint.
1736
+ */
1737
+ path?: string;
1738
+ metadata?: {
1739
+ description?: string;
1740
+ };
1741
+ }
1742
+ /**
1743
+ * Represents an Ingest API endpoint, used for sending data into a Moose system, typically writing to a Stream.
1744
+ * Provides a typed interface for the expected data format.
1745
+ *
1746
+ * @template T The data type of the records that this API endpoint accepts. The structure of T defines the expected request body schema.
1747
+ */
1748
+ declare class IngestApi<T> extends TypedBase<T, IngestConfig<T>> {
1749
+ /**
1750
+ * Creates a new IngestApi instance.
1751
+ * @param name The name of the ingest API endpoint.
1752
+ * @param config Optional configuration for the ingest API.
1753
+ */
1754
+ constructor(name: string, config?: IngestConfig<T>);
1755
+ /**
1756
+ * @internal
1757
+ * Note: `validators` parameter is a positional placeholder (always undefined for IngestApi).
1758
+ * It exists because TypedBase has validators as the 5th param, and we need to pass
1759
+ * allowExtraFields as the 6th param. IngestApi doesn't use validators.
1760
+ */
1761
+ constructor(name: string, config: IngestConfig<T>, schema: IJsonSchemaCollection.IV3_1, columns: Column[], validators: undefined, allowExtraFields: boolean);
1762
+ }
1763
+
1764
+ /**
1765
+ * Utilities provided by getMooseUtils() for database access and SQL queries.
1766
+ * Works in both Moose runtime and standalone contexts.
1767
+ */
1768
+ interface MooseUtils {
1769
+ client: MooseClient;
1770
+ sql: typeof sql;
1771
+ jwt?: JWTPayload;
1772
+ }
1773
+ /**
1774
+ * @deprecated Use MooseUtils instead. ApiUtil is now a type alias to MooseUtils
1775
+ * and will be removed in a future version.
1776
+ *
1777
+ * Migration: Replace `ApiUtil` with `MooseUtils` in your type annotations.
1778
+ */
1779
+ type ApiUtil = MooseUtils;
1780
+ /** @deprecated Use MooseUtils instead. */
1781
+ type ConsumptionUtil = MooseUtils;
1782
+ declare class MooseClient {
1783
+ query: QueryClient;
1784
+ workflow: WorkflowClient;
1785
+ constructor(queryClient: QueryClient, temporalClient?: Client);
1786
+ }
1787
+ declare class QueryClient {
1788
+ client: ClickHouseClient;
1789
+ query_id_prefix: string;
1790
+ constructor(client: ClickHouseClient, query_id_prefix: string);
1791
+ execute<T = any>(sql: Sql): Promise<ResultSet<"JSONEachRow"> & {
1792
+ __query_result_t?: T[];
1793
+ }>;
1794
+ command(sql: Sql): Promise<CommandResult>;
1795
+ }
1796
+ declare class WorkflowClient {
1797
+ client: Client | undefined;
1798
+ constructor(temporalClient?: Client);
1799
+ execute(name: string, input_data: any): Promise<{
1800
+ status: number;
1801
+ body: string;
1802
+ }>;
1803
+ terminate(workflowId: string): Promise<{
1804
+ status: number;
1805
+ body: string;
1806
+ }>;
1807
+ private getWorkflowConfig;
1808
+ private processInputData;
1809
+ }
1810
+ /**
1811
+ * This looks similar to the client in runner.ts which is a worker.
1812
+ * Temporal SDK uses similar looking connection options & client,
1813
+ * but there are different libraries for a worker & client like this one
1814
+ * that triggers workflows.
1815
+ */
1816
+ declare function getTemporalClient(temporalUrl: string, namespace: string, clientCert: string, clientKey: string, apiKey: string): Promise<Client | undefined>;
1817
+ declare const ApiHelpers: {
1818
+ column: (value: string) => [string, string];
1819
+ table: (value: string) => [string, string];
1820
+ };
1821
+ /** @deprecated Use ApiHelpers instead. */
1822
+ declare const ConsumptionHelpers: {
1823
+ column: (value: string) => [string, string];
1824
+ table: (value: string) => [string, string];
1825
+ };
1826
+ declare function joinQueries({ values, separator, prefix, suffix, }: {
1827
+ values: readonly RawValue[];
1828
+ separator?: string;
1829
+ prefix?: string;
1830
+ suffix?: string;
1831
+ }): Sql;
1832
+
1833
+ /**
1834
+ * Defines the signature for a handler function used by a Consumption API.
1835
+ * @template T The expected type of the request parameters or query parameters.
1836
+ * @template R The expected type of the response data.
1837
+ * @param params An object containing the validated request parameters, matching the structure of T.
1838
+ * @param utils Utility functions provided to the handler, e.g., for database access (`runSql`).
1839
+ * @returns A Promise resolving to the response data of type R.
1840
+ */
1841
+ type ApiHandler<T, R> = (params: T, utils: ApiUtil) => Promise<R>;
1842
+ /**
1843
+ * @template T The data type of the request parameters.
1844
+ */
1845
+ interface ApiConfig<T> {
1846
+ /**
1847
+ * An optional version string for this configuration.
1848
+ */
1849
+ version?: string;
1850
+ /**
1851
+ * An optional custom path for the API endpoint.
1852
+ * If not specified, defaults to the API name.
1853
+ */
1854
+ path?: string;
1855
+ metadata?: {
1856
+ description?: string;
1857
+ };
1858
+ }
1859
+ /**
1860
+ * Represents a Consumption API endpoint (API), used for querying data from a Moose system.
1861
+ * Exposes data, often from an OlapTable or derived through a custom handler function.
1862
+ *
1863
+ * @template T The data type defining the expected structure of the API's query parameters.
1864
+ * @template R The data type defining the expected structure of the API's response body. Defaults to `any`.
1865
+ */
1866
+ declare class Api<T, R = any> extends TypedBase<T, ApiConfig<T>> {
1867
+ /** @internal The handler function that processes requests and generates responses. */
1868
+ _handler: ApiHandler<T, R>;
1869
+ /** @internal The JSON schema definition for the response type R. */
1870
+ responseSchema: IJsonSchemaCollection.IV3_1;
1871
+ /**
1872
+ * Creates a new Api instance.
1873
+ * @param name The name of the consumption API endpoint.
1874
+ * @param handler The function to execute when the endpoint is called. It receives validated query parameters and utility functions.
1875
+ * @param config Optional configuration for the consumption API.
1876
+ */
1877
+ constructor(name: string, handler: ApiHandler<T, R>, config?: {});
1878
+ /** @internal **/
1879
+ constructor(name: string, handler: ApiHandler<T, R>, config: ApiConfig<T>, schema: IJsonSchemaCollection.IV3_1, columns: Column[], responseSchema: IJsonSchemaCollection.IV3_1);
1880
+ /**
1881
+ * Retrieves the handler function associated with this Consumption API.
1882
+ * @returns The handler function.
1883
+ */
1884
+ getHandler: () => ApiHandler<T, R>;
1885
+ call(baseUrl: string, queryParams: T): Promise<R>;
1886
+ }
1887
+ /** @deprecated Use ApiConfig<T> directly instead. */
1888
+ type EgressConfig<T> = ApiConfig<T>;
1889
+ /** @deprecated Use Api directly instead. */
1890
+ declare const ConsumptionApi: typeof Api;
1891
+
1892
+ /**
1893
+ * Configuration options for a complete ingestion pipeline, potentially including an Ingest API, a Stream, and an OLAP Table.
1894
+ *
1895
+ * @template T The data type of the records being ingested.
1896
+ *
1897
+ * @example
1898
+ * ```typescript
1899
+ * // Simple pipeline with all components enabled
1900
+ * const pipelineConfig: IngestPipelineConfig<UserData> = {
1901
+ * table: true,
1902
+ * stream: true,
1903
+ * ingestApi: true
1904
+ * };
1905
+ *
1906
+ * // Advanced pipeline with custom configurations
1907
+ * const advancedConfig: IngestPipelineConfig<UserData> = {
1908
+ * table: { orderByFields: ['timestamp', 'userId'], engine: ClickHouseEngines.ReplacingMergeTree },
1909
+ * stream: { parallelism: 4, retentionPeriod: 86400 },
1910
+ * ingestApi: true,
1911
+ * version: '1.2.0',
1912
+ * metadata: { description: 'User data ingestion pipeline' }
1913
+ * };
1914
+ * ```
1915
+ */
1916
+ type IngestPipelineConfig<T> = {
1917
+ /**
1918
+ * Configuration for the OLAP table component of the pipeline.
1919
+ *
1920
+ * - If `true`, a table with default settings is created.
1921
+ * - If an `OlapConfig` object is provided, it specifies the table's configuration.
1922
+ * - If `false`, no OLAP table is created.
1923
+ *
1924
+ * @default false
1925
+ */
1926
+ table: boolean | OlapConfig<T>;
1927
+ /**
1928
+ * Configuration for the stream component of the pipeline.
1929
+ *
1930
+ * - If `true`, a stream with default settings is created.
1931
+ * - Pass a config object to specify the stream's configuration.
1932
+ * - The stream's destination will automatically be set to the pipeline's table if one exists.
1933
+ * - If `false`, no stream is created.
1934
+ *
1935
+ * @default false
1936
+ */
1937
+ stream: boolean | Omit<StreamConfig<T>, "destination">;
1938
+ /**
1939
+ * Configuration for the ingest API component of the pipeline.
1940
+ *
1941
+ * - If `true`, an ingest API with default settings is created.
1942
+ * - If a partial `IngestConfig` object (excluding `destination`) is provided, it specifies the API's configuration.
1943
+ * - The API's destination will automatically be set to the pipeline's stream if one exists.
1944
+ * - If `false`, no ingest API is created.
1945
+ *
1946
+ * **Note:** Requires a stream to be configured when enabled.
1947
+ *
1948
+ * @default false
1949
+ */
1950
+ ingestApi: boolean | Omit<IngestConfig<T>, "destination">;
1951
+ /**
1952
+ * @deprecated Use `ingestApi` instead. This parameter will be removed in a future version.
1953
+ */
1954
+ ingest?: boolean | Omit<IngestConfig<T>, "destination">;
1955
+ /**
1956
+ * Configuration for the dead letter queue of the pipeline.
1957
+ * If `true`, a dead letter queue with default settings is created.
1958
+ * If a partial `StreamConfig` object (excluding `destination`) is provided, it specifies the dead letter queue's configuration.
1959
+ * The API's destination will automatically be set to the pipeline's stream if one exists.
1960
+ * If `false` or `undefined`, no dead letter queue is created.
1961
+ */
1962
+ deadLetterQueue?: boolean | StreamConfig<DeadLetterModel>;
1963
+ /**
1964
+ * An optional version string applying to all components (table, stream, ingest) created by this pipeline configuration.
1965
+ * This version will be used for schema versioning and component identification.
1966
+ *
1967
+ * @example "v1.0.0", "2023-12", "prod"
1968
+ */
1969
+ version?: string;
1970
+ /**
1971
+ * An optional custom path for the ingestion API endpoint.
1972
+ * This will be used as the HTTP path for the ingest API if one is created.
1973
+ *
1974
+ * @example "pipelines/analytics", "data/events"
1975
+ */
1976
+ path?: string;
1977
+ /**
1978
+ * Optional metadata for the pipeline.
1979
+ */
1980
+ metadata?: {
1981
+ /** Human-readable description of the pipeline's purpose */
1982
+ description?: string;
1983
+ };
1984
+ /** Determines how changes in code will propagate to the resources. */
1985
+ lifeCycle?: LifeCycle;
1986
+ };
1987
+ /**
1988
+ * Represents a complete ingestion pipeline, potentially combining an Ingest API, a Stream, and an OLAP Table
1989
+ * under a single name and configuration. Simplifies the setup of common ingestion patterns.
1990
+ *
1991
+ * This class provides a high-level abstraction for creating data ingestion workflows that can include:
1992
+ * - An HTTP API endpoint for receiving data
1993
+ * - A streaming component for real-time data processing
1994
+ * - An OLAP table for analytical queries
1995
+ *
1996
+ * @template T The data type of the records flowing through the pipeline. This type defines the schema for the
1997
+ * Ingest API input, the Stream messages, and the OLAP Table rows.
1998
+ *
1999
+ * @example
2000
+ * ```typescript
2001
+ * // Create a complete pipeline with all components
2002
+ * const userDataPipeline = new IngestPipeline('userData', {
2003
+ * table: true,
2004
+ * stream: true,
2005
+ * ingestApi: true,
2006
+ * version: '1.0.0',
2007
+ * metadata: { description: 'Pipeline for user registration data' }
2008
+ * });
2009
+ *
2010
+ * // Create a pipeline with only table and stream
2011
+ * const analyticsStream = new IngestPipeline('analytics', {
2012
+ * table: { orderByFields: ['timestamp'], engine: ClickHouseEngines.ReplacingMergeTree },
2013
+ * stream: { parallelism: 8, retentionPeriod: 604800 },
2014
+ * ingestApi: false
2015
+ * });
2016
+ * ```
2017
+ */
2018
+ declare class IngestPipeline<T> extends TypedBase<T, IngestPipelineConfig<T>> {
2019
+ /**
2020
+ * The OLAP table component of the pipeline, if configured.
2021
+ * Provides analytical query capabilities for the ingested data.
2022
+ * Only present when `config.table` is not `false`.
2023
+ */
2024
+ table?: OlapTable<T>;
2025
+ /**
2026
+ * The stream component of the pipeline, if configured.
2027
+ * Handles real-time data flow and processing between components.
2028
+ * Only present when `config.stream` is not `false`.
2029
+ */
2030
+ stream?: Stream<T>;
2031
+ /**
2032
+ * The ingest API component of the pipeline, if configured.
2033
+ * Provides HTTP endpoints for data ingestion.
2034
+ * Only present when `config.ingestApi` is not `false`.
2035
+ */
2036
+ ingestApi?: IngestApi<T>;
2037
+ /** The dead letter queue of the pipeline, if configured. */
2038
+ deadLetterQueue?: DeadLetterQueue<T>;
2039
+ /**
2040
+ * Creates a new IngestPipeline instance.
2041
+ * Based on the configuration, it automatically creates and links the IngestApi, Stream, and OlapTable components.
2042
+ *
2043
+ * @param name The base name for the pipeline components (e.g., "userData" could create "userData" table, "userData" stream, "userData" ingest API).
2044
+ * @param config Optional configuration for the ingestion pipeline.
2045
+ *
2046
+ * @throws {Error} When ingest API is enabled but no stream is configured, since the API requires a stream destination.
2047
+ *
2048
+ * @example
2049
+ * ```typescript
2050
+ * const pipeline = new IngestPipeline('events', {
2051
+ * table: { orderByFields: ['timestamp'], engine: ClickHouseEngines.ReplacingMergeTree },
2052
+ * stream: { parallelism: 2 },
2053
+ * ingestApi: true
2054
+ * });
2055
+ * ```
2056
+ */
2057
+ constructor(name: string, config: IngestPipelineConfig<T>);
2058
+ /**
2059
+ * Internal constructor used by the framework for advanced initialization.
2060
+ *
2061
+ * @internal
2062
+ * @param name The base name for the pipeline components.
2063
+ * @param config Configuration specifying which components to create and their settings.
2064
+ * @param schema JSON schema collection for type validation.
2065
+ * @param columns Column definitions for the data model.
2066
+ * @param validators Typia validation functions.
2067
+ * @param allowExtraFields Whether extra fields are allowed (injected when type has index signature).
2068
+ */
2069
+ constructor(name: string, config: IngestPipelineConfig<T>, schema: IJsonSchemaCollection.IV3_1, columns: Column[], validators: TypiaValidators<T>, allowExtraFields: boolean);
2070
+ }
2071
+
2072
+ interface ETLPipelineConfig<T, U> {
2073
+ extract: AsyncIterable<T> | (() => AsyncIterable<T>);
2074
+ transform: (sourceData: T) => Promise<U>;
2075
+ load: ((data: U[]) => Promise<void>) | OlapTable<U>;
2076
+ }
2077
+ declare class ETLPipeline<T, U> {
2078
+ readonly name: string;
2079
+ readonly config: ETLPipelineConfig<T, U>;
2080
+ private batcher;
2081
+ constructor(name: string, config: ETLPipelineConfig<T, U>);
2082
+ private setupPipeline;
2083
+ private createBatcher;
2084
+ private getDefaultTaskConfig;
2085
+ private createAllTasks;
2086
+ private createExtractTask;
2087
+ private createTransformTask;
2088
+ private createLoadTask;
2089
+ run(): Promise<void>;
2090
+ }
2091
+
2092
+ /**
2093
+ * Represents a database View, defined by a SQL SELECT statement based on one or more base tables or other views.
2094
+ * Emits structured data for the Moose infrastructure system.
2095
+ */
2096
+ declare class View {
2097
+ /** @internal */
2098
+ readonly kind = "View";
2099
+ /** The name of the view */
2100
+ name: string;
2101
+ /** The SELECT SQL statement that defines the view */
2102
+ selectSql: string;
2103
+ /** Names of source tables/views that the SELECT reads from */
2104
+ sourceTables: string[];
2105
+ /** Optional metadata for the view */
2106
+ metadata: {
2107
+ [key: string]: any;
2108
+ };
2109
+ /**
2110
+ * Creates a new View instance.
2111
+ * @param name The name of the view to be created.
2112
+ * @param selectStatement The SQL SELECT statement that defines the view's logic.
2113
+ * @param baseTables An array of OlapTable or View objects that the `selectStatement` reads from. Used for dependency tracking.
2114
+ * @param metadata Optional metadata for the view (e.g., description, source file).
2115
+ */
2116
+ constructor(name: string, selectStatement: string | Sql, baseTables: (OlapTable<any> | View)[], metadata?: {
2117
+ [key: string]: any;
2118
+ });
2119
+ }
2120
+
2121
+ /**
2122
+ * Configuration options for creating a Materialized View.
2123
+ * @template T The data type of the records stored in the target table of the materialized view.
2124
+ */
2125
+ interface MaterializedViewConfig<T> {
2126
+ /** The SQL SELECT statement or `Sql` object defining the data to be materialized. Dynamic SQL (with parameters) is not allowed here. */
2127
+ selectStatement: string | Sql;
2128
+ /** An array of OlapTable or View objects that the `selectStatement` reads from. */
2129
+ selectTables: (OlapTable<any> | View)[];
2130
+ /** @deprecated See {@link targetTable}
2131
+ * The name for the underlying target OlapTable that stores the materialized data. */
2132
+ tableName?: string;
2133
+ /** The name for the ClickHouse MATERIALIZED VIEW object itself. */
2134
+ materializedViewName: string;
2135
+ /** @deprecated See {@link targetTable}
2136
+ * Optional ClickHouse engine for the target table (e.g., ReplacingMergeTree). Defaults to MergeTree. */
2137
+ engine?: ClickHouseEngines;
2138
+ targetTable?: OlapTable<T> /** Target table if the OlapTable object is already constructed. */ | {
2139
+ /** The name for the underlying target OlapTable that stores the materialized data. */
2140
+ name: string;
2141
+ /** Optional ClickHouse engine for the target table (e.g., ReplacingMergeTree). Defaults to MergeTree. */
2142
+ engine?: ClickHouseEngines;
2143
+ /** Optional ordering fields for the target table. Crucial if using ReplacingMergeTree. */
2144
+ orderByFields?: (keyof T & string)[];
2145
+ };
2146
+ /** @deprecated See {@link targetTable}
2147
+ * Optional ordering fields for the target table. Crucial if using ReplacingMergeTree. */
2148
+ orderByFields?: (keyof T & string)[];
2149
+ /** Optional metadata for the materialized view (e.g., description, source file). */
2150
+ metadata?: {
2151
+ [key: string]: any;
2152
+ };
2153
+ /** Optional lifecycle management policy for the materialized view.
2154
+ * Controls whether Moose can drop or modify the MV automatically.
2155
+ * Defaults to FULLY_MANAGED if not specified. */
2156
+ lifeCycle?: LifeCycle;
2157
+ }
2158
+ /**
2159
+ * Represents a Materialized View in ClickHouse.
2160
+ * This encapsulates both the target OlapTable that stores the data and the MATERIALIZED VIEW definition
2161
+ * that populates the table based on inserts into the source tables.
2162
+ *
2163
+ * @template TargetTable The data type of the records stored in the underlying target OlapTable. The structure of T defines the target table schema.
2164
+ */
2165
+ declare class MaterializedView<TargetTable> {
2166
+ /** @internal */
2167
+ readonly kind = "MaterializedView";
2168
+ /** The name of the materialized view */
2169
+ name: string;
2170
+ /** The target OlapTable instance where the materialized data is stored. */
2171
+ targetTable: OlapTable<TargetTable>;
2172
+ /** The SELECT SQL statement */
2173
+ selectSql: string;
2174
+ /** Names of source tables that the SELECT reads from */
2175
+ sourceTables: string[];
2176
+ /** Optional metadata for the materialized view */
2177
+ metadata: {
2178
+ [key: string]: any;
2179
+ };
2180
+ /** Optional lifecycle management policy for the materialized view */
2181
+ lifeCycle?: LifeCycle;
2182
+ /**
2183
+ * Creates a new MaterializedView instance.
2184
+ * Requires the `TargetTable` type parameter to be explicitly provided or inferred,
2185
+ * as it's needed to define the schema of the underlying target table.
2186
+ *
2187
+ * @param options Configuration options for the materialized view.
2188
+ */
2189
+ constructor(options: MaterializedViewConfig<TargetTable>);
2190
+ /** @internal **/
2191
+ constructor(options: MaterializedViewConfig<TargetTable>, targetSchema: IJsonSchemaCollection.IV3_1, targetColumns: Column[]);
2192
+ }
2193
+
2194
+ type SqlObject = OlapTable<any> | SqlResource | View | MaterializedView<any>;
2195
+ /**
2196
+ * Represents a generic SQL resource that requires setup and teardown commands.
2197
+ * Base class for constructs like Views and Materialized Views. Tracks dependencies.
2198
+ */
2199
+ declare class SqlResource {
2200
+ /** @internal */
2201
+ readonly kind = "SqlResource";
2202
+ /** Array of SQL statements to execute for setting up the resource. */
2203
+ setup: readonly string[];
2204
+ /** Array of SQL statements to execute for tearing down the resource. */
2205
+ teardown: readonly string[];
2206
+ /** The name of the SQL resource (e.g., view name, materialized view name). */
2207
+ name: string;
2208
+ /** List of OlapTables or Views that this resource reads data from. */
2209
+ pullsDataFrom: SqlObject[];
2210
+ /** List of OlapTables or Views that this resource writes data to. */
2211
+ pushesDataTo: SqlObject[];
2212
+ /** @internal Source file path where this resource was defined */
2213
+ sourceFile?: string;
2214
+ /** @internal Source line number where this resource was defined */
2215
+ sourceLine?: number;
2216
+ /** @internal Source column number where this resource was defined */
2217
+ sourceColumn?: number;
2218
+ /**
2219
+ * Creates a new SqlResource instance.
2220
+ * @param name The name of the resource.
2221
+ * @param setup An array of SQL DDL statements to create the resource.
2222
+ * @param teardown An array of SQL DDL statements to drop the resource.
2223
+ * @param options Optional configuration for specifying data dependencies.
2224
+ * @param options.pullsDataFrom Tables/Views this resource reads from.
2225
+ * @param options.pushesDataTo Tables/Views this resource writes to.
2226
+ */
2227
+ constructor(name: string, setup: readonly (string | Sql)[], teardown: readonly (string | Sql)[], options?: {
2228
+ pullsDataFrom?: SqlObject[];
2229
+ pushesDataTo?: SqlObject[];
2230
+ });
2231
+ }
2232
+
2233
+ type WebAppHandler = (req: http.IncomingMessage, res: http.ServerResponse) => void | Promise<void>;
2234
+ interface FrameworkApp {
2235
+ handle?: (req: http.IncomingMessage, res: http.ServerResponse, next?: (err?: any) => void) => void;
2236
+ callback?: () => WebAppHandler;
2237
+ routing?: (req: http.IncomingMessage, res: http.ServerResponse) => void;
2238
+ ready?: () => PromiseLike<unknown>;
2239
+ }
2240
+ interface WebAppConfig {
2241
+ mountPath: string;
2242
+ metadata?: {
2243
+ description?: string;
2244
+ };
2245
+ injectMooseUtils?: boolean;
2246
+ }
2247
+ declare class WebApp {
2248
+ name: string;
2249
+ handler: WebAppHandler;
2250
+ config: WebAppConfig;
2251
+ private _rawApp?;
2252
+ constructor(name: string, appOrHandler: FrameworkApp | WebAppHandler, config: WebAppConfig);
2253
+ private toHandler;
2254
+ getRawApp(): FrameworkApp | undefined;
2255
+ }
2256
+
2257
+ /**
2258
+ * @module registry
2259
+ * Public registry functions for accessing Moose Data Model v2 (dmv2) resources.
2260
+ *
2261
+ * This module provides functions to retrieve registered resources like tables, streams,
2262
+ * APIs, and more. These functions are part of the public API and can be used by
2263
+ * user applications to inspect and interact with registered Moose resources.
2264
+ */
2265
+
2266
+ /**
2267
+ * Get all registered OLAP tables.
2268
+ * @returns A Map of table name to OlapTable instance
2269
+ */
2270
+ declare function getTables(): Map<string, OlapTable<any>>;
2271
+ /**
2272
+ * Get a registered OLAP table by name.
2273
+ * @param name - The name of the table
2274
+ * @returns The OlapTable instance or undefined if not found
2275
+ */
2276
+ declare function getTable(name: string): OlapTable<any> | undefined;
2277
+ /**
2278
+ * Get all registered streams.
2279
+ * @returns A Map of stream name to Stream instance
2280
+ */
2281
+ declare function getStreams(): Map<string, Stream<any>>;
2282
+ /**
2283
+ * Get a registered stream by name.
2284
+ * @param name - The name of the stream
2285
+ * @returns The Stream instance or undefined if not found
2286
+ */
2287
+ declare function getStream(name: string): Stream<any> | undefined;
2288
+ /**
2289
+ * Get all registered ingestion APIs.
2290
+ * @returns A Map of API name to IngestApi instance
2291
+ */
2292
+ declare function getIngestApis(): Map<string, IngestApi<any>>;
2293
+ /**
2294
+ * Get a registered ingestion API by name.
2295
+ * @param name - The name of the ingestion API
2296
+ * @returns The IngestApi instance or undefined if not found
2297
+ */
2298
+ declare function getIngestApi(name: string): IngestApi<any> | undefined;
2299
+ /**
2300
+ * Get all registered APIs (consumption/egress APIs).
2301
+ * @returns A Map of API key to Api instance
2302
+ */
2303
+ declare function getApis(): Map<string, Api<any>>;
2304
+ /**
2305
+ * Get a registered API by name, version, or path.
2306
+ *
2307
+ * Supports multiple lookup strategies:
2308
+ * 1. Direct lookup by full key (name:version or name for unversioned)
2309
+ * 2. Lookup by name with automatic version aliasing when only one versioned API exists
2310
+ * 3. Lookup by custom path (if configured)
2311
+ *
2312
+ * @param nameOrPath - The name, name:version, or custom path of the API
2313
+ * @returns The Api instance or undefined if not found
2314
+ */
2315
+ declare function getApi(nameOrPath: string): Api<any> | undefined;
2316
+ /**
2317
+ * Get all registered SQL resources.
2318
+ * @returns A Map of resource name to SqlResource instance
2319
+ */
2320
+ declare function getSqlResources(): Map<string, SqlResource>;
2321
+ /**
2322
+ * Get a registered SQL resource by name.
2323
+ * @param name - The name of the SQL resource
2324
+ * @returns The SqlResource instance or undefined if not found
2325
+ */
2326
+ declare function getSqlResource(name: string): SqlResource | undefined;
2327
+ /**
2328
+ * Get all registered workflows.
2329
+ * @returns A Map of workflow name to Workflow instance
2330
+ */
2331
+ declare function getWorkflows(): Map<string, Workflow>;
2332
+ /**
2333
+ * Get a registered workflow by name.
2334
+ * @param name - The name of the workflow
2335
+ * @returns The Workflow instance or undefined if not found
2336
+ */
2337
+ declare function getWorkflow(name: string): Workflow | undefined;
2338
+ /**
2339
+ * Get all registered web apps.
2340
+ * @returns A Map of web app name to WebApp instance
2341
+ */
2342
+ declare function getWebApps(): Map<string, WebApp>;
2343
+ /**
2344
+ * Get a registered web app by name.
2345
+ * @param name - The name of the web app
2346
+ * @returns The WebApp instance or undefined if not found
2347
+ */
2348
+ declare function getWebApp(name: string): WebApp | undefined;
2349
+ /**
2350
+ * Get all registered materialized views.
2351
+ * @returns A Map of MV name to MaterializedView instance
2352
+ */
2353
+ declare function getMaterializedViews(): Map<string, MaterializedView<any>>;
2354
+ /**
2355
+ * Get a registered materialized view by name.
2356
+ * @param name - The name of the materialized view
2357
+ * @returns The MaterializedView instance or undefined if not found
2358
+ */
2359
+ declare function getMaterializedView(name: string): MaterializedView<any> | undefined;
2360
+ /**
2361
+ * Get all registered views.
2362
+ * @returns A Map of view name to View instance
2363
+ */
2364
+ declare function getViews(): Map<string, View>;
2365
+ /**
2366
+ * Get a registered view by name.
2367
+ * @param name - The name of the view
2368
+ * @returns The View instance or undefined if not found
2369
+ */
2370
+ declare function getView(name: string): View | undefined;
2371
+
2372
+ /**
2373
+ * @module dmv2
2374
+ * This module defines the core Moose v2 data model constructs, including OlapTable, Stream, IngestApi, Api,
2375
+ * IngestPipeline, View, and MaterializedView. These classes provide a typed interface for defining and managing
2376
+ * data infrastructure components like ClickHouse tables, Redpanda streams, and data processing pipelines.
2377
+ */
2378
+ /**
2379
+ * A helper type used potentially for indicating aggregated fields in query results or schemas.
2380
+ * Captures the aggregation function name and argument types.
2381
+ * (Usage context might be specific to query builders or ORM features).
2382
+ *
2383
+ * @template AggregationFunction The name of the aggregation function (e.g., 'sum', 'avg', 'count').
2384
+ * @template ArgTypes An array type representing the types of the arguments passed to the aggregation function.
2385
+ */
2386
+ type Aggregated<AggregationFunction extends string, ArgTypes extends any[] = []> = {
2387
+ _aggregationFunction?: AggregationFunction;
2388
+ _argTypes?: ArgTypes;
2389
+ };
2390
+ /**
2391
+ * A helper type for SimpleAggregateFunction in ClickHouse.
2392
+ * SimpleAggregateFunction stores the aggregated value directly instead of intermediate states,
2393
+ * offering better performance for functions like sum, max, min, any, anyLast, etc.
2394
+ *
2395
+ * @template AggregationFunction The name of the simple aggregation function (e.g., 'sum', 'max', 'anyLast').
2396
+ * @template ArgType The type of the argument (and result) of the aggregation function.
2397
+ *
2398
+ * @example
2399
+ * ```typescript
2400
+ * interface Stats {
2401
+ * rowCount: number & SimpleAggregated<'sum', number>;
2402
+ * maxValue: number & SimpleAggregated<'max', number>;
2403
+ * lastStatus: string & SimpleAggregated<'anyLast', string>;
2404
+ * }
2405
+ * ```
2406
+ */
2407
+ type SimpleAggregated<AggregationFunction extends string, ArgType = any> = {
2408
+ _simpleAggregationFunction?: AggregationFunction;
2409
+ _argType?: ArgType;
2410
+ };
2411
+
2412
+ export { type ClickHouseInt as $, type Aggregated as A, getSqlResource as B, ClickHouseEngines as C, type DeadLetterModel as D, type EgressConfig as E, type FrameworkApp as F, getWorkflows as G, getWorkflow as H, IngestApi as I, getWebApps as J, getWebApp as K, LifeCycle as L, MaterializedView as M, getView as N, OlapTable as O, getViews as P, getMaterializedView as Q, getMaterializedViews as R, type SimpleAggregated as S, Task as T, type ClickHousePrecision as U, View as V, Workflow as W, type ClickHouseDecimal as X, type ClickHouseByteSize as Y, type ClickHouseFixedStringSize as Z, type ClickHouseFloat as _, type OlapConfig as a, type ClickHouseJson as a0, type LowCardinality as a1, type ClickHouseNamedTuple as a2, type ClickHouseDefault as a3, type ClickHouseTTL as a4, type ClickHouseMaterialized as a5, type WithDefault as a6, type ClickHouseCodec as a7, type DateTime as a8, type DateTime64 as a9, toQueryPreview as aA, getValueFromParameter as aB, createClickhouseParameter as aC, mapToClickHouseType as aD, type MooseUtils as aE, MooseClient as aF, type ClickHousePoint as aG, type ClickHouseRing as aH, type ClickHouseLineString as aI, type ClickHouseMultiLineString as aJ, type ClickHousePolygon as aK, type ClickHouseMultiPolygon as aL, QueryClient as aM, WorkflowClient as aN, getTemporalClient as aO, ApiHelpers as aP, ConsumptionHelpers as aQ, joinQueries as aR, type ConsumerConfig as aS, type TransformConfig as aT, type TaskContext as aU, type TaskConfig as aV, type IngestPipelineConfig as aW, type MaterializedViewConfig as aX, type DateTimeString as aa, type DateTime64String as ab, type FixedString as ac, type Float32 as ad, type Float64 as ae, type Int8 as af, type Int16 as ag, type Int32 as ah, type Int64 as ai, type UInt8 as aj, type UInt16 as ak, type UInt32 as al, type UInt64 as am, type Decimal as an, type ApiUtil as ao, type ConsumptionUtil as ap, quoteIdentifier as aq, type IdentifierBrandedString as ar, type NonIdentifierBrandedString as as, type Value as at, type RawValue as au, type SqlTemplateTag as av, sql as aw, Sql as ax, toStaticQuery as ay, toQuery as az, type S3QueueTableSettings as b, Stream as c, type StreamConfig as d, type DeadLetter as e, DeadLetterQueue as f, type IngestConfig as g, Api as h, type ApiConfig as i, ConsumptionApi as j, IngestPipeline as k, SqlResource as l, ETLPipeline as m, type ETLPipelineConfig as n, WebApp as o, type WebAppConfig as p, type WebAppHandler as q, getTables as r, getTable as s, getStreams as t, getStream as u, getIngestApis as v, getIngestApi as w, getApis as x, getApi as y, getSqlResources as z };