This repository was archived by the owner on Mar 6, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathffi.go
More file actions
680 lines (573 loc) · 19.1 KB
/
ffi.go
File metadata and controls
680 lines (573 loc) · 19.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
package zerobus
/*
#cgo linux,amd64 LDFLAGS: ${SRCDIR}/lib/linux_amd64/libzerobus_ffi.a -ldl -lpthread -lm -lresolv -lgcc_s
#cgo linux,arm64 LDFLAGS: ${SRCDIR}/lib/linux_arm64/libzerobus_ffi.a -ldl -lpthread -lm -lresolv -lgcc_s
#cgo darwin,amd64 LDFLAGS: ${SRCDIR}/lib/darwin_amd64/libzerobus_ffi.a -framework CoreFoundation -framework Security -liconv
#cgo darwin,arm64 LDFLAGS: ${SRCDIR}/lib/darwin_arm64/libzerobus_ffi.a -framework CoreFoundation -framework Security -liconv
#cgo windows,amd64 LDFLAGS: ${SRCDIR}/lib/windows_amd64/libzerobus_ffi.a -lws2_32 -luserenv -lbcrypt -lntdll
#cgo CFLAGS: -I${SRCDIR}/zerobus-ffi -Wno-implicit-function-declaration
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
// Forward declare opaque types
typedef struct CZerobusSdk CZerobusSdk;
typedef struct CZerobusStream CZerobusStream;
// Define result type
typedef struct CResult {
bool success;
char *error_message;
bool is_retryable;
} CResult;
typedef struct CRecord {
bool is_json;
uint8_t *data;
uintptr_t data_len;
} CRecord;
typedef struct CRecordArray {
CRecord *records;
uintptr_t len;
} CRecordArray;
// Define headers types for callback
typedef struct CHeader {
char *key;
char *value;
} CHeader;
typedef struct CHeaders {
struct CHeader *headers;
uintptr_t count;
char *error_message;
} CHeaders;
typedef struct CHeaders (*HeadersProviderCallback)(void *user_data);
// Define stream configuration options
typedef struct CStreamConfigurationOptions {
uintptr_t max_inflight_requests;
bool recovery;
uint64_t recovery_timeout_ms;
uint64_t recovery_backoff_ms;
uint32_t recovery_retries;
uint64_t server_lack_of_ack_timeout_ms;
uint64_t flush_timeout_ms;
int32_t record_type;
uint64_t stream_paused_max_wait_time_ms;
bool has_stream_paused_max_wait_time_ms;
uint64_t callback_max_wait_time_ms;
bool has_callback_max_wait_time_ms;
} CStreamConfigurationOptions;
// Forward declare functions we need
extern CZerobusSdk* zerobus_sdk_new(const char* zerobus_endpoint,
const char* unity_catalog_url,
CResult* result);
extern void zerobus_sdk_free(CZerobusSdk* sdk);
extern void zerobus_sdk_set_use_tls(CZerobusSdk* sdk, bool use_tls);
extern CZerobusStream* zerobus_sdk_create_stream(CZerobusSdk* sdk,
const char* table_name,
const uint8_t* descriptor_proto_bytes,
uintptr_t descriptor_proto_len,
const char* client_id,
const char* client_secret,
const CStreamConfigurationOptions* options,
CResult* result);
extern CZerobusStream* zerobus_sdk_create_stream_with_headers_provider(
CZerobusSdk* sdk,
const char* table_name,
const uint8_t* descriptor_proto_bytes,
uintptr_t descriptor_proto_len,
HeadersProviderCallback headers_callback,
void* user_data,
const CStreamConfigurationOptions* options,
CResult* result);
extern void zerobus_stream_free(CZerobusStream* stream);
extern int64_t zerobus_stream_ingest_proto_record(CZerobusStream* stream,
const uint8_t* data,
uintptr_t data_len,
CResult* result);
extern int64_t zerobus_stream_ingest_json_record(CZerobusStream* stream,
const char* json_data,
CResult* result);
extern int64_t zerobus_stream_ingest_proto_records(CZerobusStream* stream,
const uint8_t** records,
const uintptr_t* record_lens,
uintptr_t num_records,
CResult* result);
extern int64_t zerobus_stream_ingest_json_records(CZerobusStream* stream,
const char** json_records,
uintptr_t num_records,
CResult* result);
extern bool zerobus_stream_wait_for_offset(CZerobusStream* stream,
int64_t offset,
CResult* result);
extern CRecordArray zerobus_stream_get_unacked_records(CZerobusStream* stream, CResult* result);
extern void zerobus_free_record_array(CRecordArray array);
extern bool zerobus_stream_flush(CZerobusStream* stream, CResult* result);
extern bool zerobus_stream_close(CZerobusStream* stream, CResult* result);
extern void zerobus_free_error_message(char* error_message);
extern CStreamConfigurationOptions zerobus_get_default_config();
// Forward declaration of Go function
extern void goGetHeaders(void* userData, CHeader** headers, uintptr_t* count, char** error);
// C callback that matches the HeadersProviderCallback signature
static CHeaders cHeadersCallback(void* userData) {
CHeader* headers = NULL;
uintptr_t count = 0;
char* error = NULL;
// Call Go function
goGetHeaders(userData, &headers, &count, &error);
CHeaders result;
result.headers = headers;
result.count = count;
result.error_message = error;
return result;
}
// Helper function to get the C callback function pointer
static HeadersProviderCallback getHeadersCallback() {
return (HeadersProviderCallback)cHeadersCallback;
}
*/
import "C"
import (
"runtime"
"runtime/cgo"
"sync"
"unsafe"
)
// Registry to map stream pointers to their handles for cleanup
// This allows us to properly release cgo.Handle when streams are freed
var (
streamHandleRegistry = make(map[unsafe.Pointer]cgo.Handle)
streamHandleRegistryMu sync.Mutex
)
// ffiResult converts a C.CResult to a Go error
func ffiResult(cres C.CResult) error {
if cres.success {
return nil
}
var message string
if cres.error_message != nil {
message = C.GoString(cres.error_message)
C.zerobus_free_error_message(cres.error_message)
} else {
message = "unknown error"
}
return &ZerobusError{
Message: message,
IsRetryable: bool(cres.is_retryable),
}
}
// convertConfigToC converts Go config to C config
// Applies defaults for any zero-valued fields
func convertConfigToC(opts *StreamConfigurationOptions) C.CStreamConfigurationOptions {
if opts == nil {
return C.zerobus_get_default_config()
}
// Start with defaults and override with provided values
defaults := DefaultStreamConfigurationOptions()
maxInflight := opts.MaxInflightRequests
if maxInflight == 0 {
maxInflight = defaults.MaxInflightRequests
}
recovery := opts.Recovery
// Note: Recovery is a bool, so we check if it was explicitly set to false
// by checking if ANY other field is non-zero (indicates intentional config)
// If all fields are default-like, we use the default Recovery value
if opts.RecoveryTimeoutMs == 0 && opts.RecoveryBackoffMs == 0 && opts.RecoveryRetries == 0 {
recovery = defaults.Recovery
}
recoveryTimeout := opts.RecoveryTimeoutMs
if recoveryTimeout == 0 {
recoveryTimeout = defaults.RecoveryTimeoutMs
}
recoveryBackoff := opts.RecoveryBackoffMs
if recoveryBackoff == 0 {
recoveryBackoff = defaults.RecoveryBackoffMs
}
recoveryRetries := opts.RecoveryRetries
if recoveryRetries == 0 {
recoveryRetries = defaults.RecoveryRetries
}
serverAckTimeout := opts.ServerLackOfAckTimeoutMs
if serverAckTimeout == 0 {
serverAckTimeout = defaults.ServerLackOfAckTimeoutMs
}
flushTimeout := opts.FlushTimeoutMs
if flushTimeout == 0 {
flushTimeout = defaults.FlushTimeoutMs
}
recordType := opts.RecordType
if recordType == RecordTypeUnspecified {
recordType = defaults.RecordType
}
// Handle optional StreamPausedMaxWaitTimeMs
var streamPausedMaxWaitMs C.uint64_t
hasStreamPausedMaxWait := C.bool(false)
if opts.StreamPausedMaxWaitTimeMs != nil {
streamPausedMaxWaitMs = C.uint64_t(*opts.StreamPausedMaxWaitTimeMs)
hasStreamPausedMaxWait = C.bool(true)
}
return C.CStreamConfigurationOptions{
max_inflight_requests: C.size_t(maxInflight),
recovery: C.bool(recovery),
recovery_timeout_ms: C.uint64_t(recoveryTimeout),
recovery_backoff_ms: C.uint64_t(recoveryBackoff),
recovery_retries: C.uint32_t(recoveryRetries),
server_lack_of_ack_timeout_ms: C.uint64_t(serverAckTimeout),
flush_timeout_ms: C.uint64_t(flushTimeout),
record_type: C.int(recordType),
stream_paused_max_wait_time_ms: streamPausedMaxWaitMs,
has_stream_paused_max_wait_time_ms: hasStreamPausedMaxWait,
callback_max_wait_time_ms: 0,
has_callback_max_wait_time_ms: C.bool(false),
}
}
// sdkNew creates a new SDK instance via FFI
func sdkNew(zerobusEndpoint, unityCatalogURL string) (unsafe.Pointer, error) {
cEndpoint := C.CString(zerobusEndpoint)
defer C.free(unsafe.Pointer(cEndpoint))
cCatalogURL := C.CString(unityCatalogURL)
defer C.free(unsafe.Pointer(cCatalogURL))
var cres C.CResult
ptr := C.zerobus_sdk_new(cEndpoint, cCatalogURL, &cres)
if ptr == nil {
return nil, ffiResult(cres)
}
// Disable TLS if using HTTP endpoint (for testing/mock servers)
if len(zerobusEndpoint) >= 7 && zerobusEndpoint[:7] == "http://" {
C.zerobus_sdk_set_use_tls(ptr, C.bool(false))
}
return unsafe.Pointer(ptr), nil
}
// sdkFree frees an SDK instance
func sdkFree(ptr unsafe.Pointer) {
if ptr != nil {
C.zerobus_sdk_free((*C.CZerobusSdk)(ptr))
}
}
// sdkCreateStream creates a stream via FFI
func sdkCreateStream(
sdkPtr unsafe.Pointer,
tableName string,
descriptorProto []byte,
clientID string,
clientSecret string,
options *StreamConfigurationOptions,
) (unsafe.Pointer, error) {
cTableName := C.CString(tableName)
defer C.free(unsafe.Pointer(cTableName))
cClientID := C.CString(clientID)
defer C.free(unsafe.Pointer(cClientID))
cClientSecret := C.CString(clientSecret)
defer C.free(unsafe.Pointer(cClientSecret))
var cDescriptor *C.uint8_t
var descriptorLen C.size_t
var pinner runtime.Pinner
if len(descriptorProto) > 0 {
defer pinner.Unpin()
cDescriptor = (*C.uint8_t)(unsafe.SliceData(descriptorProto))
pinner.Pin(cDescriptor)
descriptorLen = C.size_t(len(descriptorProto))
}
cOpts := convertConfigToC(options)
var cres C.CResult
ptr := C.zerobus_sdk_create_stream(
(*C.CZerobusSdk)(sdkPtr),
cTableName,
cDescriptor,
descriptorLen,
cClientID,
cClientSecret,
&cOpts,
&cres,
)
if ptr == nil {
return nil, ffiResult(cres)
}
return unsafe.Pointer(ptr), nil
}
//export goGetHeaders
func goGetHeaders(userData unsafe.Pointer, headers **C.CHeader, count *C.uintptr_t, errorMsg **C.char) {
// Convert userData back to cgo.Handle and retrieve the provider
handle := cgo.Handle(userData)
provider, ok := handle.Value().(HeadersProvider)
if !ok {
*errorMsg = C.CString("Invalid headers provider handle")
*headers = nil
*count = 0
return
}
// Call the Go interface method
headersMap, err := provider.GetHeaders()
if err != nil {
*errorMsg = C.CString(err.Error())
*headers = nil
*count = 0
return
}
// Convert Go map to C array
if len(headersMap) == 0 {
*headers = nil
*count = 0
*errorMsg = nil
return
}
// Allocate C array
cHeaders := C.malloc(C.size_t(len(headersMap)) * C.size_t(unsafe.Sizeof(C.CHeader{})))
if cHeaders == nil {
*errorMsg = C.CString("out of memory allocating headers")
*headers = nil
*count = 0
return
}
cHeadersSlice := (*[1 << 30]C.CHeader)(cHeaders)[:len(headersMap):len(headersMap)]
idx := 0
for key, value := range headersMap {
cHeadersSlice[idx].key = C.CString(key)
cHeadersSlice[idx].value = C.CString(value)
idx++
}
*headers = (*C.CHeader)(cHeaders)
*count = C.uintptr_t(len(headersMap))
*errorMsg = nil
}
// sdkCreateStreamWithHeadersProvider creates a stream with custom headers provider via FFI
func sdkCreateStreamWithHeadersProvider(
sdkPtr unsafe.Pointer,
tableName string,
descriptorProto []byte,
headersProvider HeadersProvider,
options *StreamConfigurationOptions,
) (unsafe.Pointer, error) {
cTableName := C.CString(tableName)
defer C.free(unsafe.Pointer(cTableName))
var cDescriptor *C.uint8_t
var descriptorLen C.size_t
var pinner runtime.Pinner
if len(descriptorProto) > 0 {
defer pinner.Unpin()
cDescriptor = (*C.uint8_t)(unsafe.SliceData(descriptorProto))
pinner.Pin(cDescriptor)
descriptorLen = C.size_t(len(descriptorProto))
}
// Create a cgo.Handle for the provider
// This keeps it alive and gives us a safe uintptr to pass to C
handle := cgo.NewHandle(headersProvider)
// Convert handle to unsafe.Pointer using a pattern the linter accepts
handlePtr := *(*unsafe.Pointer)(unsafe.Pointer(&handle))
cOpts := convertConfigToC(options)
var cres C.CResult
ptr := C.zerobus_sdk_create_stream_with_headers_provider(
(*C.CZerobusSdk)(sdkPtr),
cTableName,
cDescriptor,
descriptorLen,
C.getHeadersCallback(),
handlePtr,
&cOpts,
&cres,
)
if ptr == nil {
// Clean up handle on error
handle.Delete()
return nil, ffiResult(cres)
}
// Store the handle so we can clean it up when the stream is freed
streamHandleRegistryMu.Lock()
streamHandleRegistry[unsafe.Pointer(ptr)] = handle
streamHandleRegistryMu.Unlock()
return unsafe.Pointer(ptr), nil
}
// streamFree frees a stream instance
func streamFree(ptr unsafe.Pointer) {
if ptr != nil {
// Clean up the associated handle BEFORE freeing the stream
streamHandleRegistryMu.Lock()
if handle, exists := streamHandleRegistry[ptr]; exists {
handle.Delete() // This releases the Go object reference
delete(streamHandleRegistry, ptr)
}
streamHandleRegistryMu.Unlock()
C.zerobus_stream_free((*C.CZerobusStream)(ptr))
}
}
// streamIngestProtoRecord ingests a protobuf record
// Returns the offset directly
func streamIngestProtoRecord(streamPtr unsafe.Pointer, data []byte) (int64, error) {
if len(data) == 0 {
return -1, &ZerobusError{Message: "empty data", IsRetryable: false}
}
// Pin the data to prevent GC from moving it while Rust reads it
var pinner runtime.Pinner
defer pinner.Unpin()
cData := (*C.uint8_t)(unsafe.SliceData(data))
pinner.Pin(cData)
var cres C.CResult
offset := C.zerobus_stream_ingest_proto_record(
(*C.CZerobusStream)(streamPtr),
cData,
C.size_t(len(data)),
&cres,
)
if offset < 0 {
return -1, ffiResult(cres)
}
return int64(offset), nil
}
// streamIngestJSONRecord ingests a JSON record
// Returns the offset directly
func streamIngestJSONRecord(streamPtr unsafe.Pointer, jsonData string) (int64, error) {
cJSON := C.CString(jsonData)
defer C.free(unsafe.Pointer(cJSON))
var cres C.CResult
offset := C.zerobus_stream_ingest_json_record(
(*C.CZerobusStream)(streamPtr),
cJSON,
&cres,
)
if offset < 0 {
return -1, ffiResult(cres)
}
return int64(offset), nil
}
// streamIngestProtoRecords ingests a batch of protobuf records
func streamIngestProtoRecords(streamPtr unsafe.Pointer, records [][]byte) (int64, error) {
if len(records) == 0 {
return -1, nil // Return special value for empty batch
}
// Create arrays of pointers and lengths
recordPtrs := make([]*C.uint8_t, len(records))
recordLens := make([]C.size_t, len(records))
// Pin all record data to prevent GC from moving it while Rust reads
var pinner runtime.Pinner
defer pinner.Unpin()
for i, record := range records {
if len(record) > 0 {
unsafeRecord := (*C.uint8_t)(unsafe.SliceData(records[i]))
pinner.Pin(unsafeRecord)
recordPtrs[i] = unsafeRecord
recordLens[i] = C.size_t(len(record))
}
}
// Get pointers to the arrays for passing to C
inRecords := (**C.uint8_t)(unsafe.SliceData(recordPtrs))
inLengths := (*C.size_t)(unsafe.SliceData(recordLens))
pinner.Pin(inRecords)
pinner.Pin(inLengths)
var cres C.CResult
offset := C.zerobus_stream_ingest_proto_records(
(*C.CZerobusStream)(streamPtr),
inRecords,
inLengths,
C.size_t(len(records)),
&cres,
)
if offset == -2 {
return -1, nil // Empty batch
}
if offset < 0 {
return -1, ffiResult(cres)
}
return int64(offset), nil
}
// streamIngestJSONRecords ingests a batch of JSON records
func streamIngestJSONRecords(streamPtr unsafe.Pointer, records []string) (int64, error) {
if len(records) == 0 {
return -1, nil // Return special value for empty batch
}
// Create array of C string pointers
cStrings := make([]*C.char, len(records))
// Convert each Go string to C string
for i, record := range records {
cStr := C.CString(record)
cStrings[i] = cStr
defer C.free(unsafe.Pointer(cStr))
}
var pinner runtime.Pinner
defer pinner.Unpin()
// Get pointer to the array for passing to C
inStrings := (**C.char)(unsafe.SliceData(cStrings))
pinner.Pin(inStrings)
var cres C.CResult
offset := C.zerobus_stream_ingest_json_records(
(*C.CZerobusStream)(streamPtr),
inStrings,
C.size_t(len(records)),
&cres,
)
if offset == -2 {
return -1, nil // Empty batch
}
if offset < 0 {
return -1, ffiResult(cres)
}
return int64(offset), nil
}
// streamWaitForOffset waits for a specific offset to be acknowledged
func streamWaitForOffset(streamPtr unsafe.Pointer, offset int64) error {
var cres C.CResult
success := C.zerobus_stream_wait_for_offset(
(*C.CZerobusStream)(streamPtr),
C.int64_t(offset),
&cres,
)
if !success {
return ffiResult(cres)
}
return nil
}
// streamFlush flushes pending records
func streamFlush(streamPtr unsafe.Pointer) error {
var cres C.CResult
success := C.zerobus_stream_flush((*C.CZerobusStream)(streamPtr), &cres)
if !success {
return ffiResult(cres)
}
return nil
}
// streamGetUnackedRecords retrieves all unacknowledged records
func streamGetUnackedRecords(streamPtr unsafe.Pointer) ([]interface{}, error) {
var cres C.CResult
cArray := C.zerobus_stream_get_unacked_records(
(*C.CZerobusStream)(streamPtr),
&cres,
)
// Check if there was an error (null pointer indicates error)
if cArray.records == nil {
if cArray.len == 0 {
// Could be an error or empty - check result
err := ffiResult(cres)
if err != nil {
return nil, err
}
// Empty result, no error
return []interface{}{}, nil
}
return nil, ffiResult(cres)
}
// Convert C array to Go slice
if cArray.len == 0 {
return []interface{}{}, nil
}
records := make([]interface{}, cArray.len)
cRecords := unsafe.Slice(cArray.records, cArray.len)
for i, cRecord := range cRecords {
if cRecord.is_json {
// Convert C data to Go string for JSON
data := C.GoBytes(unsafe.Pointer(cRecord.data), C.int(cRecord.data_len))
records[i] = string(data)
} else {
// Convert C data to Go []byte for protobuf
data := C.GoBytes(unsafe.Pointer(cRecord.data), C.int(cRecord.data_len))
records[i] = data
}
}
// Free the C array memory
C.zerobus_free_record_array(cArray)
return records, nil
}
// streamClose closes the stream
func streamClose(streamPtr unsafe.Pointer) error {
var cres C.CResult
success := C.zerobus_stream_close((*C.CZerobusStream)(streamPtr), &cres)
if !success {
return ffiResult(cres)
}
return nil
}