-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlaunchdarkly-server-sdk.c
More file actions
2002 lines (1577 loc) · 63 KB
/
launchdarkly-server-sdk.c
File metadata and controls
2002 lines (1577 loc) · 63 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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***
Server-side SDK for LaunchDarkly.
@module launchdarkly-server-sdk
*/
#include <lua.h>
#include <lauxlib.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <launchdarkly/server_side/bindings/c/sdk.h>
#include <launchdarkly/server_side/bindings/c/config/builder.h>
#include <launchdarkly/bindings/c/logging/log_level.h>
#include <launchdarkly/bindings/c/context_builder.h>
#include <launchdarkly/bindings/c/array_builder.h>
#include <launchdarkly/bindings/c/object_builder.h>
#ifdef DEBUG
#define DEBUG_PRINT(fmt, ...) printf(fmt, __VA_ARGS__)
#else
#define DEBUG_PRINT(fmt, ...)
#endif
#define SDKVersion "2.1.3" /* {x-release-please-version} */
static LDValue
LuaValueToJSON(lua_State *const l, const int i);
static LDValue
LuaTableToJSON(lua_State *const l, const int i);
static LDValue
LuaArrayToJSON(lua_State *const l, const int i);
static void
LuaPushJSON(lua_State *const l, LDValue j);
static int lua_tablelen(lua_State *L, int index)
{
#if LUA_VERSION_NUM >= 502
return lua_rawlen(L, index);
#else
return lua_objlen(L, index);
#endif
}
/**
* The custom log backend struct (LDLogBackend) contains a void* userdata pointer, and two function pointers
* (enabled and write). This allows C users to avoid global logging functions.
* This doesn't quite match up with Lua's expectations, since:
* 1) The user-defined functions will be stored in the Lua registry
* 2) We need to keep around a lua_State pointer for accessing the registry when we need to invoke the callbacks
*
* This struct is therefore the equivalent of the C LDLogBackend struct, but with registry references and a lua_State pointer.
* We allocate a new Lua userdata and then wire up some global callbacks (lua_log_backend_enabled, lua_log_backend_write)
* to cast the void* to a lua_log_backend*, grab the function references, and forward the arguments.
*/
struct lua_log_backend {
lua_State *l;
int enabled_ref;
int write_ref;
};
/**
* Creates a new custom log backend. The functions provided must be thread safe as the SDK
* does not perform any locking.
* @function makeLogBackend
* @tparam function enabled A function that returns true if the specified log level is enabled. The signature
should be (level: string) -> boolean, where the known level strings are 'debug', 'info', 'warn', and 'error'.
* @tparam function write A function that writes a log message at a specified level. The signature should be
* (level: string, message: string) -> void.
* @treturn A new custom log backend, suitable for use in SDK `logging` configuration.
*/
static int LuaLDLogBackendNew(lua_State *l) {
if (lua_gettop(l) != 2) {
return luaL_error(l, "expecting exactly 2 arguments");
}
luaL_checktype(l, 1, LUA_TFUNCTION);
luaL_checktype(l, 2, LUA_TFUNCTION);
int write_ref = luaL_ref(l, LUA_REGISTRYINDEX);
int enabled_ref = luaL_ref(l, LUA_REGISTRYINDEX);
struct lua_log_backend* backend = lua_newuserdata(l, sizeof(struct lua_log_backend));
luaL_getmetatable(l, "LaunchDarklyLogBackend");
lua_setmetatable(l, -2);
backend->l = l;
backend->write_ref = write_ref;
backend->enabled_ref = enabled_ref;
return 1;
}
static struct lua_log_backend* check_log_backend(lua_State *l, int i) {
void *ud = luaL_checkudata(l, i, "LaunchDarklyLogBackend");
luaL_argcheck(l, ud != NULL, i, "`LaunchDarklyLogBackend' expected");
return ud;
}
bool lua_log_backend_enabled(enum LDLogLevel level, void *user_data) {
struct lua_log_backend* backend = user_data;
lua_State *l = backend->l;
lua_rawgeti(l, LUA_REGISTRYINDEX, backend->enabled_ref);
lua_pushstring(l, LDLogLevel_Name(level, "unknown"));
lua_call(l, 1, 1); // one argument (level - string), one result (enabled - boolean).
return lua_toboolean(l, -1);
}
void lua_log_backend_write(enum LDLogLevel level, const char* msg, void *user_data) {
struct lua_log_backend* backend = user_data;
lua_State *l = backend->l;
lua_rawgeti(l, LUA_REGISTRYINDEX, backend->write_ref);
lua_pushstring(l, LDLogLevel_Name(level, "unknown"));
lua_pushstring(l, msg);
lua_call(l, 2, 0); // two args (level - string, msg - string), no results.
}
static bool
isArray(lua_State *const l, const int i)
{
lua_pushvalue(l, i);
lua_pushnil(l);
bool array = true;
while (lua_next(l, -2) != 0) {
if (lua_type(l, -2) != LUA_TNUMBER) {
array = false;
}
lua_pop(l, 1);
}
lua_pop(l, 1);
return array;
}
static LDValue
LuaValueToJSON(lua_State *const l, const int i)
{
LDValue result = NULL;
switch (lua_type(l, i)) {
case LUA_TBOOLEAN:
result = LDValue_NewBool(lua_toboolean(l, i));
break;
case LUA_TNUMBER:
result = LDValue_NewNumber(lua_tonumber(l, i));
break;
case LUA_TSTRING:
result = LDValue_NewString(lua_tostring(l, i));
break;
case LUA_TTABLE:
if (isArray(l, i)) {
result = LuaArrayToJSON(l, i);
} else {
result = LuaTableToJSON(l, i);
}
break;
default:
result = LDValue_NewNull();
break;
}
return result;
}
static LDValue
LuaArrayToJSON(lua_State *const l, const int i)
{
LDArrayBuilder result = LDArrayBuilder_New();
lua_pushvalue(l, i);
lua_pushnil(l);
while (lua_next(l, -2) != 0) {
LDValue value = LuaValueToJSON(l, -1);
LDArrayBuilder_Add(result, value);
lua_pop(l, 1);
}
lua_pop(l, 1);
return LDArrayBuilder_Build(result);
}
static LDValue
LuaTableToJSON(lua_State *const l, const int i)
{
LDObjectBuilder result = LDObjectBuilder_New();
lua_pushvalue(l, i);
lua_pushnil(l);
while (lua_next(l, -2) != 0) {
const char *const key = lua_tostring(l, -2);
LDValue value = LuaValueToJSON(l, -1);
LDObjectBuilder_Add(result, key, value);
lua_pop(l, 1);
}
lua_pop(l, 1);
return LDObjectBuilder_Build(result);
}
static void
LuaPushJSONObject(lua_State *const l, LDValue j)
{
LDValue_ObjectIter iter;
lua_newtable(l);
for (iter = LDValue_ObjectIter_New(j); !LDValue_ObjectIter_End(iter); LDValue_ObjectIter_Next(iter)) {
LuaPushJSON(l, LDValue_ObjectIter_Value(iter));
lua_setfield(l, -2, LDValue_ObjectIter_Key(iter));
}
}
static void
LuaPushJSONArray(lua_State *const l, LDValue j)
{
LDValue_ArrayIter iter;
lua_newtable(l);
int index = 1;
for (iter = LDValue_ArrayIter_New(j); !LDValue_ArrayIter_End(iter); LDValue_ArrayIter_Next(iter)) {
LuaPushJSON(l, LDValue_ArrayIter_Value(iter));
lua_rawseti(l, -2, index);
index++;
}
}
static void
LuaPushJSON(lua_State *const l, LDValue j)
{
switch (LDValue_Type(j)) {
case LDValueType_String:
lua_pushstring(l, LDValue_GetString(j));
break;
case LDValueType_Bool:
lua_pushboolean(l, LDValue_GetBool(j));
break;
case LDValueType_Number:
lua_pushnumber(l, LDValue_GetNumber(j));
break;
case LDValueType_Object:
LuaPushJSONObject(l, j);
break;
case LDValueType_Array:
LuaPushJSONArray(l, j);
break;
default:
lua_pushnil(l);
break;
}
return;
}
/***
This function is deprecated and provided as a convenience. Please transition
to using @{makeContext} instead.
Create a new opaque context object of kind 'user'. This method
has changed from the previous Lua SDK v1.x `makeUser`, as users are no longer
supported.
Specifically:
1. 'secondary' attribute is no longer supported.
2. 'privateAttributeNames' is now called 'privateAttributes' and supports
attribute references (similar to JSON pointer syntax, e.g. `/foo/bar`).
3. all fields under 'custom' become top-level context attributes, rather than
being nested under an attribute named 'custom'.
For example, `{ custom = { foo = "bar" } }` would result in a context with attribute 'foo' equal to 'bar'.
@function makeUser
@tparam table fields list of user fields.
@tparam string fields.key The user's key
@tparam[opt] boolean fields.anonymous Mark the user as anonymous
@tparam[opt] string fields.ip Set the user's IP
@tparam[opt] string fields.firstName Set the user's first name
@tparam[opt] string fields.lastName Set the user's last name
@tparam[opt] string fields.email Set the user's email
@tparam[opt] string fields.name Set the user's name
@tparam[opt] string fields.avatar Set the user's avatar
@tparam[opt] string fields.country Set the user's country
@tparam[opt] table fields.privateAttributes A list of attributes to
redact
@tparam[opt] table fields.custom A table of additional context attributes.
@return an opaque context object
*/
static int
LuaLDUserNew(lua_State *const l)
{
if (lua_gettop(l) != 1) {
return luaL_error(l, "expecting exactly 1 argument");
}
luaL_checktype(l, 1, LUA_TTABLE);
lua_getfield(l, 1, "key");
const char *const key = luaL_checkstring(l, -1);
LDContextBuilder builder = LDContextBuilder_New();
LDContextBuilder_AddKind(builder, "user", key);
lua_getfield(l, 1, "anonymous");
if (lua_isboolean(l, -1)) {
LDContextBuilder_Attributes_SetAnonymous(builder, "user", true);
}
lua_getfield(l, 1, "ip");
if (lua_isstring(l, -1)) {
LDContextBuilder_Attributes_Set(builder, "user", "ip", LDValue_NewString(luaL_checkstring(l, -1)));
};
lua_getfield(l, 1, "firstName");
if (lua_isstring(l, -1)) {
LDContextBuilder_Attributes_Set(builder, "user", "firstName", LDValue_NewString(luaL_checkstring(l, -1)));
}
lua_getfield(l, 1, "lastName");
if (lua_isstring(l, -1)) {
LDContextBuilder_Attributes_Set(builder, "user", "lastName", LDValue_NewString(luaL_checkstring(l, -1)));
}
lua_getfield(l, 1, "email");
if (lua_isstring(l, -1)) {
LDContextBuilder_Attributes_Set(builder, "user", "email", LDValue_NewString(luaL_checkstring(l, -1)));
}
lua_getfield(l, 1, "name");
if (lua_isstring(l, -1)) {
LDContextBuilder_Attributes_SetName(builder, "user", luaL_checkstring(l, -1));
}
lua_getfield(l, 1, "avatar");
if (lua_isstring(l, -1)) {
LDContextBuilder_Attributes_Set(builder, "user", "avatar", LDValue_NewString(luaL_checkstring(l, -1)));
}
lua_getfield(l, 1, "country");
if (lua_isstring(l, -1)) {
LDContextBuilder_Attributes_Set(builder, "user", "country", LDValue_NewString(luaL_checkstring(l, -1)));
}
lua_getfield(l, 1, "custom");
// The individual fields of custom are added to the top-level of the context.
if (lua_istable(l, -1)) {
lua_pushnil(l);
while (lua_next(l, -2) != 0) {
const char *const key = luaL_checkstring(l, -2);
LDValue value = LuaValueToJSON(l, -1);
LDContextBuilder_Attributes_Set(builder, "user", key, value);
lua_pop(l, 1);
}
}
lua_getfield(l, 1, "privateAttributes");
if (lua_istable(l, -1)) {
int n = lua_tablelen(l, -1);
for (int i = 1; i <= n; i++) {
lua_rawgeti(l, -1, i);
if (lua_isstring(l, -1)) {
LDContextBuilder_Attributes_AddPrivateAttribute(builder, "user", luaL_checkstring(l, -1));
}
lua_pop(l, 1);
}
}
LDContext context = LDContextBuilder_Build(builder);
LDContext *u = (LDContext *)lua_newuserdata(l, sizeof(context));
*u = context;
luaL_getmetatable(l, "LaunchDarklyContext");
lua_setmetatable(l, -2);
return 1;
}
static void parse_private_attrs_or_cleanup(lua_State *const l, LDContextBuilder builder, const char* kind);
static void parse_attrs_or_cleanup(lua_State *const l, LDContextBuilder builder, const char* kind);
static bool field_is_type_or_cleanup(lua_State* const l, int actual_field_type, int expected_field_type, LDContextBuilder builder, const char* field_name, const char* kind);
/**
Create a new opaque context object. This method can be used to create single
or multi-kind contexts. The context's kind must always be specified, even if
it is a user.
For example, to create a context with a single user kind:
```
local context = ld.makeContext({
user = {
key = "alice-123",
name = "alice",
attributes = {
age = 52,
contact = {
email = "alice@mail.com",
phone = "555-555-5555"
}
},
privateAttributes = { "age", "/contact/phone" }
}
})
```
A multi-kind context can be useful when targeting based on multiple kinds of data.
For example, to associate a device context with a user:
```
local context = ld.makeContext({
user = {
key = "alice-123",
name = "alice",
anonymous = true
},
device {
key = "device-123",
attributes = {
manufacturer = "bigcorp"
}
}
})
```
SDK methods will automatically check for context validity. You may check manually
by calling @{valid} to detect errors earlier.
@function makeContext
@tparam table A table of context kinds, where the table keys are the kind names
and the values are tables containing context's information.
@tparam string [kind.key] The context's key, which is required.
@tparam[opt] [kind.name] A name for the context. This is useful for identifying the context
in the LaunchDarkly dashboard.
@tparam[opt] [kind.anonymous] A boolean indicating whether the context should be marked as anonymous.
@tparam[opt] [kind.attributes] A table of arbitrary attributes to associate with the context.
@tparam[opt] [kind.privateAttributes] An array of attribute references, indicating which
attributes should be marked private. Attribute references may be simple attribute names
(like 'age'), or may use a JSON-pointer-like syntax (like '/contact/phone').
@treturn A fresh context.
*/
static int
LuaLDContextNew(lua_State *const l) {
// The single argument is a table containing key/value pairs
// which represent kind/contexts. There is no implicit way of constructing
// a user context - you need to have a 'user = { .. }'.
if (lua_gettop(l) != 1) {
return luaL_error(l, "expecting exactly 1 argument");
}
luaL_checktype(l, 1, LUA_TTABLE);
LDContextBuilder builder = LDContextBuilder_New();
lua_pushnil(l);
while (lua_next(l, -2) != 0) {
lua_pushvalue(l, -2);
int kind_type = lua_type(l, -1);
int context_type = lua_type(l, -2);
if (kind_type != LUA_TSTRING) {
LDContextBuilder_Free(builder);
luaL_error(l, "top-level table keys must be context kinds; example: user = { ... }");
}
if (context_type != LUA_TTABLE) {
LDContextBuilder_Free(builder);
luaL_error(l, "top-level table values must be tables; example: user = { ... }");
}
const char* kind = lua_tostring(l, -1);
DEBUG_PRINT("inspecting %s context\n", kind);
// The context table is on the top of the stack. It must contain a key.
lua_getfield(l, -2, "key");
const char *const key = lua_tostring(l, -1);
lua_pop(l, 1);
if (key == NULL) {
LDContextBuilder_Free(builder);
luaL_error(l, "context kind %s: must contain key", kind);
}
LDContextBuilder_AddKind(builder, kind, key);
lua_getfield(l, -2, "attributes");
if (field_is_type_or_cleanup(l, lua_type(l, -1), LUA_TTABLE, builder, "attributes", kind)) {
parse_attrs_or_cleanup(l, builder, kind);
}
lua_pop(l, 1);
lua_getfield(l, -2, "privateAttributes");
if (field_is_type_or_cleanup(l, lua_type(l, -1), LUA_TTABLE, builder, "privateAttributes", kind)) {
parse_private_attrs_or_cleanup(l, builder, kind);
}
lua_pop(l, 1);
lua_getfield(l, -2, "name");
if (field_is_type_or_cleanup(l, lua_type(l, -1), LUA_TSTRING, builder, "name", kind)) {
LDContextBuilder_Attributes_SetName(builder, kind, lua_tostring(l, -1));
}
lua_pop(l, 1);
lua_getfield(l, -2, "anonymous");
if (field_is_type_or_cleanup(l, lua_type(l, -1), LUA_TBOOLEAN, builder, "anonymous", kind)) {
LDContextBuilder_Attributes_SetAnonymous(builder, kind, lua_toboolean(l, -1));
}
lua_pop(l, 1);
lua_pop(l, 2);
}
lua_pop(l, 1);
LDContext context = LDContextBuilder_Build(builder);
LDContext *u = (LDContext *)lua_newuserdata(l, sizeof(context));
*u = context;
luaL_getmetatable(l, "LaunchDarklyContext");
lua_setmetatable(l, -2);
return 1;
}
static bool field_is_type_or_cleanup(lua_State* const l, int actual_field_type, int expected_field_type, LDContextBuilder builder, const char* field_name, const char* kind) {
if (actual_field_type == expected_field_type) {
DEBUG_PRINT("field %s for %s context is a %s\n", field_name, kind, lua_typename(l, actual_field_type));
return true;
} else if (actual_field_type == LUA_TNIL) {
DEBUG_PRINT("no %s for %s context\n", field_name, kind);
} else {
LDContextBuilder_Free(builder);
luaL_error(l, "context kind %s: %s must be a %s", kind, field_name, lua_typename(l, expected_field_type));
}
return false;
}
static void parse_attrs_or_cleanup(lua_State *const l, LDContextBuilder builder, const char* kind) {
lua_pushnil(l);
while (lua_next(l, -2) != 0) {
lua_pushvalue(l, -2);
int key_type = lua_type(l, -1);
if (key_type != LUA_TSTRING) {
LDContextBuilder_Free(builder);
luaL_error(l, "context kind %s: top-level attribute keys must be strings", kind);
}
const char* key = lua_tostring(l, -1);
DEBUG_PRINT("context kind %s: parsing attribute %s\n", kind, key);
LDValue value = LuaValueToJSON(l, -2);
LDContextBuilder_Attributes_Set(builder, kind, key, value);
lua_pop(l, 2);
}
}
static void parse_private_attrs_or_cleanup(lua_State *const l, LDContextBuilder builder, const char* kind) {
int n = lua_tablelen(l, -1);
for (int i = 1; i <= n; i++) {
lua_rawgeti(l, -1, i);
if (lua_isstring(l, -1)) {
LDContextBuilder_Attributes_AddPrivateAttribute(builder, kind, luaL_checkstring(l, -1));
} else {
LDContextBuilder_Free(builder);
luaL_error(l, "context kind %s: privateAttributes must be a table of strings", kind);
}
lua_pop(l, 1);
}
}
/***
Return SDK version.
@function version
@return SDK version string.
*/
static int
LuaLDVersion(lua_State *const l)
{
lua_pushstring(l, SDKVersion);
return 1;
}
/**
Frees a context object.
*/
static int
LuaLDContextFree(lua_State *const l)
{
LDContext *context;
context = (LDContext *)luaL_checkudata(l, 1, "LaunchDarklyContext");
if (*context) {
LDContext_Free(*context);
*context = NULL;
}
return 0;
}
// field_validator is used to validate a single field in a config table.
// The field delegates to a parse function, which handles extracting the actual
// type.
struct field_validator {
// Name of the field used in Lua.
const char* key;
// Expected Lua type of the field.
int type;
// Function that parses the value at stack index i.
//
// The function must agree on the type of the argument 'setter', which is
// the value of this struct's 'setter' field.
//
// For example, parse might handle parsing bools. So the actual
// signature for 'setter' might be:
// void (*setter)(LDServerConfigBuilder, bool)
//
// Which would allow the implementation of parse to call setter(builder, value).
void (*parse) (lua_State *const l, int i, void* builder, void* setter);
// Stores a function that is capable of setting a value on an arbitrary builder.
// The type of the value being stored is erased here so that field_validator
// can handle all necessary types.
void *setter;
};
#define FIELD(key, type, parse, user_data) {key, type, parse, user_data}
// Parses a string.
// The setter must have the signature (void*, const char*).
static void parse_string(lua_State *const l, int i, void* builder, void* setter) {
const char *const value = lua_tostring(l, i);
DEBUG_PRINT("string = %s\n", value ? value : "NULL");
void (*string_setter)(void*, const char*) = setter;
string_setter(builder, value);
}
static void parse_log_level(lua_State *const l, int i, void* builder, void* setter) {
const char *const value = lua_tostring(l, i);
DEBUG_PRINT("log level = %s\n", value ? value : "NULL");
void (*log_level_setter)(void*, enum LDLogLevel) = setter;
// Issue an error if the log level isn't known. Another option would be
// to silently default to a known level, such as LD_LOG_INFO.
const int unknown_level_sentinel = 255;
enum LDLogLevel level = LDLogLevel_Enum(value, 255);
if (level == unknown_level_sentinel) {
luaL_error(l, "unknown log level: '%s' (known options include 'debug', 'info', 'warn', and 'error')", value);
}
log_level_setter(builder, level);
}
// Parses a bool.
// The setter must have the signature (void*, bool).
static void parse_bool(lua_State *const l, int i, void* builder, void* setter) {
const bool value = lua_toboolean(l, i);
DEBUG_PRINT("bool = %s\n", value ? "true" : "false");
void (*bool_setter)(void*, bool) = setter;
bool_setter(builder, value);
}
// Parses a number.
// The setter must have the signature (void*, unsigned int).
static void parse_unsigned(lua_State *const l, int i, void* builder, void* setter) {
const int value = lua_tointeger(l, i);
DEBUG_PRINT("number = %d\n", value);
if (value < 0) {
luaL_error(l, "got %d, expected positive int", value);
}
if (setter) {
void (*unsigned_int_setter)(void*, unsigned int) = setter;
unsigned_int_setter(builder, value);
}
}
// Forward declaration of the config used in traverse_config, to keep parse_table
// in the same place as the others.
struct config;
// Forward declaration for same reason as above. Traverses a config recursively,
// calling the appropriate parse function for each field. It expects a table to be
// on top of the stack.
void traverse_config(lua_State *const l, LDServerConfigBuilder builder, struct config *cfg);
// Parses a table using traverse_config. Can only be invoked on top level LDServerConfigBuilder
// configurations, not child builders.
static void parse_table(lua_State *const l, int i, void* builder, void* user_data) {
// since traverse_config expects the table to be on top of the stack,
// make it so.
lua_pushvalue(l, i);
traverse_config(l, (LDServerConfigBuilder) builder, user_data);
}
// Parses an array of strings. Items that aren't strings will trigger an error.
// The setter must have the signature (void*, const char*).
static void parse_string_array(lua_State *const l, int i, void* builder, void* setter) {
void (*string_setter)(void*, const char*) = setter;
int n = lua_tablelen(l, i);
DEBUG_PRINT("parsing string array of length %d\n", n);
for (int j = 1; j <= n; j++) {
lua_rawgeti(l, i, j);
if (lua_isstring(l, -1)) {
const char* elem = lua_tostring(l, -1);
DEBUG_PRINT("array[%d] = %s\n", j, elem);
string_setter(builder, elem);
} else {
luaL_error(l, "array[%d] is not a string", j);
}
lua_pop(l, 1);
}
}
// Special purpose parser for extracting a LaunchDarklySourceInterface from
// the stack. Setter must have the signature (void*, void*).
static void parse_lazyload_source(lua_State *const l, int i, void* builder, void* setter) {
LDServerLazyLoadSourcePtr *source = luaL_checkudata(l, i, "LaunchDarklySourceInterface");
DEBUG_PRINT("source = %p\n", *source);
void (*source_setter)(void*, void*) = setter;
// Dereferencing source because lua_touserdata returns a pointer (to our pointer).
source_setter(builder, *source);
}
static void parse_log_backend(lua_State *const l, int i, void* builder, void* setter) {
struct LDLogBackend backend;
LDLogBackend_Init(&backend);
struct lua_log_backend* lua_backend = check_log_backend(l, i);
backend.UserData = lua_backend;
backend.Enabled = lua_log_backend_enabled;
backend.Write = lua_log_backend_write;
LDLoggingCustomBuilder custom_logging = LDLoggingCustomBuilder_New();
LDLoggingCustomBuilder_Backend(custom_logging, backend);
void (*backend_setter)(void*, LDLoggingCustomBuilder) = setter;
backend_setter(builder, custom_logging);
}
// Function that returns a new child builder. This is used to allocate builders
// which are necessary for building a child config. This is needed when the C++ SDK's
// API requires a builder to be allocated and passed in to the top-level builder, e.g.
// the streaming or polling config builders.
typedef void* (*new_child_builder_fn)(void);
// Function that consumes the builder created by a new_child_builder_fn. This passes
// ownership of the builder back to the top-level configuration builder.
typedef void (*consume_child_builder_fn)(LDServerConfigBuilder, void*);
// Represents a logical chunk of config with a list of fields.
// Individual fields might themselves be configs.
//
// If a child config requires its own builder, then new_builder and consume_builder must be set.
// In this case, before any fields are parsed, new_builder will be invoked
// and stored in child_builder. After all fields are parsed, consume_builder will be invoked
// to transfer ownership of the child to the parent top-level config.
struct config {
// Name of the config, used for errors / logging.
const char *name;
// List of fields and length.
struct field_validator* fields;
int n;
// Null at compile-time; stores the result of new_builder at runtime (if set.)
void *child_builder;
// Assign both if this config needs a child builder.
new_child_builder_fn new_child_builder;
consume_child_builder_fn consume_child_builder;
};
#define ARR_SIZE(x) (sizeof(x) / sizeof(x[0]))
// Use this macro to define new config tables.
#define DEFINE_CONFIG(name, path, fields) \
struct config name = {path, fields, ARR_SIZE(fields), NULL, NULL, NULL}
// Use this macro to define a config table which requires a child builder.
#define DEFINE_CHILD_CONFIG(name, path, fields, new_builder, consume_builder) \
struct config name = {path, fields, ARR_SIZE(fields), NULL, (new_child_builder_fn) new_builder, (consume_child_builder_fn) consume_builder}
// Invokes a field's parse method, varying the builder argument depending on if this
// is a top-level or child config.
void config_invoke_parse(struct config *cfg, struct field_validator *field, LDServerConfigBuilder builder, lua_State *const l) {
if (cfg->child_builder) {
DEBUG_PRINT("invoking parser for %s with child builder (%p)\n", field->key, cfg->child_builder);
field->parse(l, -2, cfg->child_builder, field->setter);
} else {
DEBUG_PRINT("invoking parser for %s with top-level builder\n", field->key);
field->parse(l, -2, builder, field->setter);
}
}
struct field_validator lazyload_fields[] = {
FIELD("source", LUA_TUSERDATA, parse_lazyload_source, LDServerLazyLoadBuilder_SourcePtr),
FIELD("cacheRefreshMilliseconds", LUA_TNUMBER, parse_unsigned, LDServerLazyLoadBuilder_CacheRefreshMs),
FIELD("cacheEvictionPolicy", LUA_TNUMBER, parse_unsigned, LDServerLazyLoadBuilder_CachePolicy)
};
DEFINE_CHILD_CONFIG(lazyload_config,
"dataSystem.lazyLoad",
lazyload_fields,
LDServerLazyLoadBuilder_New,
LDServerConfigBuilder_DataSystem_LazyLoad
);
struct field_validator streaming_fields[] = {
FIELD("initialReconnectDelayMilliseconds", LUA_TNUMBER, parse_unsigned, LDServerDataSourceStreamBuilder_InitialReconnectDelayMs)
};
DEFINE_CHILD_CONFIG(streaming_config,
"dataSystem.backgroundSync.streaming",
streaming_fields,
LDServerDataSourceStreamBuilder_New,
LDServerConfigBuilder_DataSystem_BackgroundSync_Streaming
);
struct field_validator polling_fields[] = {
FIELD("intervalSeconds", LUA_TNUMBER, parse_unsigned, LDServerDataSourcePollBuilder_IntervalS)
};
DEFINE_CHILD_CONFIG(polling_config,
"dataSystem.backgroundSync.polling",
polling_fields,
LDServerDataSourcePollBuilder_New,
LDServerConfigBuilder_DataSystem_BackgroundSync_Polling
);
struct field_validator backgroundsync_fields[] = {
/* Mutually exclusive */
FIELD("streaming", LUA_TTABLE, parse_table, &streaming_config),
FIELD("polling", LUA_TTABLE, parse_table, &polling_config)
};
DEFINE_CONFIG(backgroundsync_config, "dataSystem.backgroundSync", backgroundsync_fields);
struct field_validator datasystem_fields[] = {
FIELD("enabled", LUA_TBOOLEAN, parse_bool, LDServerConfigBuilder_DataSystem_Enabled),
FIELD("backgroundSync", LUA_TTABLE, parse_table, &backgroundsync_config),
FIELD("lazyLoad", LUA_TTABLE, parse_table, &lazyload_config)
};
DEFINE_CONFIG(datasystem_config, "dataSystem", datasystem_fields);
struct field_validator event_fields[] = {
FIELD("enabled", LUA_TBOOLEAN, parse_bool, LDServerConfigBuilder_Events_Enabled),
FIELD("contextKeysCapacity", LUA_TNUMBER, parse_unsigned, LDServerConfigBuilder_Events_ContextKeysCapacity),
FIELD("capacity", LUA_TNUMBER, parse_unsigned, LDServerConfigBuilder_Events_Capacity),
FIELD("flushIntervalMilliseconds", LUA_TNUMBER, parse_unsigned, LDServerConfigBuilder_Events_FlushIntervalMs),
FIELD("allAttributesPrivate", LUA_TBOOLEAN, parse_bool, LDServerConfigBuilder_Events_AllAttributesPrivate),
FIELD("privateAttributes", LUA_TTABLE, parse_string_array, LDServerConfigBuilder_Events_PrivateAttribute)
};
DEFINE_CONFIG(event_config, "events", event_fields);
struct field_validator endpoint_fields[] = {
FIELD("pollingBaseURL", LUA_TSTRING, parse_string, LDServerConfigBuilder_ServiceEndpoints_PollingBaseURL),
FIELD("streamingBaseURL", LUA_TSTRING, parse_string, LDServerConfigBuilder_ServiceEndpoints_StreamingBaseURL),
FIELD("eventsBaseURL", LUA_TSTRING, parse_string, LDServerConfigBuilder_ServiceEndpoints_EventsBaseURL)
};
DEFINE_CONFIG(endpoint_config, "serviceEndpoints", endpoint_fields);
struct field_validator appinfo_fields[] = {
FIELD("identifier", LUA_TSTRING, parse_string, LDServerConfigBuilder_AppInfo_Identifier),
FIELD("version", LUA_TSTRING, parse_string, LDServerConfigBuilder_AppInfo_Version)
};
DEFINE_CONFIG(appinfo_config, "appInfo", appinfo_fields);
struct field_validator basic_logging_fields[] = {
FIELD("level", LUA_TSTRING, parse_log_level, LDLoggingBasicBuilder_Level),
FIELD("tag", LUA_TSTRING, parse_string, LDLoggingBasicBuilder_Tag)
};
DEFINE_CHILD_CONFIG(
basic_logging_config,
"logging.basic",
basic_logging_fields,
LDLoggingBasicBuilder_New,
LDServerConfigBuilder_Logging_Basic
);
struct field_validator logging_fields[] = {
/* These are mutually exclusive */
FIELD("basic", LUA_TTABLE, parse_table, &basic_logging_config),
FIELD("custom", LUA_TUSERDATA, parse_log_backend, LDServerConfigBuilder_Logging_Custom)
};
DEFINE_CONFIG(logging_config, "logging", logging_fields);
struct field_validator top_level_fields[] = {
FIELD("appInfo", LUA_TTABLE, parse_table, &appinfo_config),
FIELD("serviceEndpoints", LUA_TTABLE, parse_table, &endpoint_config),
FIELD("offline", LUA_TBOOLEAN, parse_bool, LDServerConfigBuilder_Offline),
FIELD("dataSystem", LUA_TTABLE, parse_table, &datasystem_config),
FIELD("events", LUA_TTABLE, parse_table, &event_config),
FIELD("logging", LUA_TTABLE, parse_table, &logging_config)
};
DEFINE_CONFIG(top_level_config, "config", top_level_fields);
// Finds a field by key in the given config, or returns NULL.
struct field_validator * find_field(const char *key, struct config* cfg);
void traverse_config(lua_State *const l, LDServerConfigBuilder builder, struct config *cfg) {
DEBUG_PRINT("traversing %s\n", cfg->name);
if (lua_type(l, -1) != LUA_TTABLE) {
luaL_error(l, "%s must be a table", cfg->name);
}
if (cfg->new_child_builder != NULL) {
cfg->child_builder = cfg->new_child_builder();
DEBUG_PRINT("created child builder (%p) for %s\n", cfg->child_builder, cfg->name);
}
lua_pushnil(l);
while (lua_next(l, -2) != 0) {
lua_pushvalue(l, -2);
const char* key = lua_tostring(l, -1);
int type = lua_type(l, -2);