-
Notifications
You must be signed in to change notification settings - Fork 140
/
Copy pathjs.c
3577 lines (3070 loc) · 108 KB
/
js.c
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
// Copyright 2021-2024 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <ctype.h>
#include <limits.h>
#include "js.h"
#include "mem.h"
#include "conn.h"
#include "util.h"
#include "opts.h"
#include "sub.h"
#include "dispatch.h"
#include "glib/glib.h"
#ifdef DEV_MODE
// For type safety
void js_lock(jsCtx *js) { natsMutex_Lock(js->mu); }
void js_unlock(jsCtx *js) { natsMutex_Unlock(js->mu); }
static void _retain(jsCtx *js) { js->refs++; }
static void _release(jsCtx *js) { js->refs--; }
#else
#define _retain(js) ((js)->refs++)
#define _release(js) ((js)->refs--)
#endif // DEV_MODE
const char* jsDefaultAPIPrefix = "$JS.API";
const int64_t jsDefaultRequestWait = 5000;
const int64_t jsDefaultStallWait = 200;
const char *jsDigits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const int jsBase = 62;
const int64_t jsOrderedHBInterval = NATS_SECONDS_TO_NANOS(5);
#define jsReplyTokenSize (8)
#define jsDefaultMaxMsgs (512 * 1024)
#define jsLastConsumerSeqHdr "Nats-Last-Consumer"
// Forward declarations
static void _hbTimerFired(natsTimer *timer, void* closure);
static void _releaseSubWhenStopped(natsTimer *timer, void* closure);
typedef struct __jsOrderedConsInfo
{
int64_t osid;
int64_t nsid;
uint64_t sseq;
natsConnection *nc;
natsSubscription *sub;
char *ndlv;
natsThread *thread;
int max;
bool done;
} jsOrderedConsInfo;
static void
_destroyOptions(jsOptions *o)
{
NATS_FREE((char*) o->Prefix);
NATS_FREE((char*) o->Stream.Purge.Subject);
}
static void
_freeContext(jsCtx *js)
{
natsConnection *nc = NULL;
natsStrHash_Destroy(js->pm);
natsSubscription_Destroy(js->rsub);
_destroyOptions(&(js->opts));
NATS_FREE(js->rpre);
natsCondition_Destroy(js->cond);
natsMutex_Destroy(js->mu);
natsTimer_Destroy(js->pmtmr);
nc = js->nc;
NATS_FREE(js);
natsConn_release(nc);
}
void
js_retain(jsCtx *js)
{
js_lock(js);
js->refs++;
js_unlock(js);
}
void
js_release(jsCtx *js)
{
bool doFree;
if (js == NULL)
return;
js_lock(js);
doFree = (--(js->refs) == 0);
js_unlock(js);
if (doFree)
_freeContext(js);
}
static void
js_unlockAndRelease(jsCtx *js)
{
bool doFree;
doFree = (--(js->refs) == 0);
js_unlock(js);
if (doFree)
_freeContext(js);
}
static void
_destroyPMInfo(pmInfo *pmi)
{
if (pmi == NULL)
return;
NATS_FREE(pmi->subject);
NATS_FREE(pmi);
}
void
jsCtx_Destroy(jsCtx *js)
{
pmInfo *pm;
if (js == NULL)
return;
js_lock(js);
if (js->closed)
{
js_unlock(js);
return;
}
js->closed = true;
if (js->rsub != NULL)
{
natsSubscription_Destroy(js->rsub);
js->rsub = NULL;
}
if ((js->pm != NULL) && natsStrHash_Count(js->pm) > 0)
{
natsStrHashIter iter;
void *v = NULL;
natsStrHashIter_Init(&iter, js->pm);
while (natsStrHashIter_Next(&iter, NULL, &v))
{
natsMsg *msg = (natsMsg*) v;
natsStrHashIter_RemoveCurrent(&iter);
natsMsg_Destroy(msg);
}
}
while ((pm = js->pmHead) != NULL)
{
js->pmHead = pm->next;
_destroyPMInfo(pm);
}
if (js->pmtmr != NULL)
natsTimer_Stop(js->pmtmr);
js_unlockAndRelease(js);
}
natsStatus
jsOptions_Init(jsOptions *opts)
{
if (opts == NULL)
return nats_setDefaultError(NATS_INVALID_ARG);
memset(opts, 0, sizeof(jsOptions));
return NATS_OK;
}
// Parse the JSON represented by the NATS message's payload and returns the JSON object.
// Unmarshal the API response.
natsStatus
js_unmarshalResponse(jsApiResponse *ar, nats_JSON **new_json, natsMsg *resp)
{
nats_JSON *json = NULL;
nats_JSON *err = NULL;
natsStatus s;
memset(ar, 0, sizeof(jsApiResponse));
s = nats_JSONParse(&json, natsMsg_GetData(resp), natsMsg_GetDataLength(resp));
if (s != NATS_OK)
return NATS_UPDATE_ERR_STACK(s);
// Check if there is an "error" field.
s = nats_JSONGetObject(json, "error", &err);
if ((s == NATS_OK) && (err != NULL))
{
s = nats_JSONGetInt(err, "code", &(ar->Error.Code));
IFOK(s, nats_JSONGetUInt16(err, "err_code", &(ar->Error.ErrCode)));
IFOK(s, nats_JSONGetStr(err, "description", &(ar->Error.Description)));
}
if (s == NATS_OK)
*new_json = json;
else
nats_JSONDestroy(json);
return NATS_UPDATE_ERR_STACK(s);
}
void
js_freeApiRespContent(jsApiResponse *ar)
{
if (ar == NULL)
return;
NATS_FREE(ar->Type);
NATS_FREE(ar->Error.Description);
}
static natsStatus
_copyPurgeOptions(jsCtx *js, struct jsOptionsStreamPurge *o)
{
natsStatus s = NATS_OK;
struct jsOptionsStreamPurge *po = &(js->opts.Stream.Purge);
po->Sequence = o->Sequence;
po->Keep = o->Keep;
if (!nats_IsStringEmpty(o->Subject))
{
po->Subject = NATS_STRDUP(o->Subject);
if (po->Subject == NULL)
s = nats_setDefaultError(NATS_NO_MEMORY);
}
return NATS_UPDATE_ERR_STACK(s);
}
static natsStatus
_copyStreamInfoOptions(jsCtx *js, struct jsOptionsStreamInfo *o)
{
js->opts.Stream.Info.DeletedDetails = o->DeletedDetails;
return NATS_OK;
}
natsStatus
natsConnection_JetStream(jsCtx **new_js, natsConnection *nc, jsOptions *opts)
{
jsCtx *js = NULL;
natsStatus s;
if ((new_js == NULL) || (nc == NULL))
return nats_setDefaultError(NATS_INVALID_ARG);
if (opts != NULL)
{
if (opts->Wait < 0)
return nats_setError(NATS_INVALID_ARG, "option 'Wait' (%" PRId64 ") cannot be negative", opts->Wait);
if (opts->PublishAsync.StallWait < 0)
return nats_setError(NATS_INVALID_ARG, "option 'PublishAsyncStallWait' (%" PRId64 ") cannot be negative", opts->PublishAsync.StallWait);
}
js = (jsCtx*) NATS_CALLOC(1, sizeof(jsCtx));
if (js == NULL)
return nats_setDefaultError(NATS_NO_MEMORY);
js->refs = 1;
// Retain the NATS connection and keep track of it so that if we
// detroy the context, in case of failure to fully initialize,
// we properly release the NATS connection.
natsConn_retain(nc);
js->nc = nc;
// This will be immutable and is computed based on the possible custom
// inbox prefix length (or the default "_INBOX.")
js->rpreLen = nc->inboxPfxLen+jsReplyTokenSize+1;
s = natsMutex_Create(&(js->mu));
if (s == NATS_OK)
{
// If Domain is set, use domain to create prefix.
if ((opts != NULL) && !nats_IsStringEmpty(opts->Domain))
{
if (nats_asprintf((char**) &(js->opts.Prefix), "$JS.%.*s.API",
js_lenWithoutTrailingDot(opts->Domain), opts->Domain) < 0)
{
s = nats_setDefaultError(NATS_NO_MEMORY);
}
}
else if ((opts == NULL) || nats_IsStringEmpty(opts->Prefix))
{
js->opts.Prefix = NATS_STRDUP(jsDefaultAPIPrefix);
if (js->opts.Prefix == NULL)
s = nats_setDefaultError(NATS_NO_MEMORY);
}
else if (nats_asprintf((char**) &(js->opts.Prefix), "%.*s",
js_lenWithoutTrailingDot(opts->Prefix), opts->Prefix) < 0)
{
s = nats_setDefaultError(NATS_NO_MEMORY);
}
}
if ((s == NATS_OK) && (opts != NULL))
{
struct jsOptionsPublishAsync *pa = &(js->opts.PublishAsync);
pa->MaxPending = opts->PublishAsync.MaxPending;
// This takes precedence to error handler
if (opts->PublishAsync.AckHandler != NULL)
{
pa->AckHandler = opts->PublishAsync.AckHandler;
pa->AckHandlerClosure = opts->PublishAsync.AckHandlerClosure;
}
else
{
pa->ErrHandler = opts->PublishAsync.ErrHandler;
pa->ErrHandlerClosure = opts->PublishAsync.ErrHandlerClosure;
}
pa->StallWait = opts->PublishAsync.StallWait;
js->opts.Wait = opts->Wait;
}
if (js->opts.Wait == 0)
js->opts.Wait = jsDefaultRequestWait;
if (js->opts.PublishAsync.StallWait == 0)
js->opts.PublishAsync.StallWait = jsDefaultStallWait;
if ((s == NATS_OK) && (opts != NULL))
{
s = _copyPurgeOptions(js, &(opts->Stream.Purge));
IFOK(s, _copyStreamInfoOptions(js, &(opts->Stream.Info)));
}
if (s == NATS_OK)
*new_js = js;
else
jsCtx_Destroy(js);
return NATS_UPDATE_ERR_STACK(s);
}
int
js_lenWithoutTrailingDot(const char *str)
{
int l = (int) strlen(str);
if (str[l-1] == '.')
l--;
return l;
}
natsStatus
js_setOpts(natsConnection **nc, bool *freePfx, jsCtx *js, jsOptions *opts, jsOptions *resOpts)
{
natsStatus s = NATS_OK;
*freePfx = false;
jsOptions_Init(resOpts);
if ((opts != NULL) && !nats_IsStringEmpty(opts->Domain))
{
char *pfx = NULL;
if (nats_asprintf(&pfx, "$JS.%.*s.API",
js_lenWithoutTrailingDot(opts->Domain), opts->Domain) < 0)
{
s = nats_setDefaultError(NATS_NO_MEMORY);
}
else
{
resOpts->Prefix = pfx;
*freePfx = true;
}
}
if (s == NATS_OK)
{
struct jsOptionsStreamPurge *po = &(js->opts.Stream.Purge);
js_lock(js);
// If not set above...
if (resOpts->Prefix == NULL)
resOpts->Prefix = (opts == NULL || nats_IsStringEmpty(opts->Prefix)) ? js->opts.Prefix : opts->Prefix;
// Take provided one or default to context's.
resOpts->Wait = (opts == NULL || opts->Wait <= 0) ? js->opts.Wait : opts->Wait;
// Purge options
if (opts != NULL)
{
struct jsOptionsStreamPurge *opo = &(opts->Stream.Purge);
// If any field is set, use `opts`, otherwise, we will use the
// context's purge options.
if ((opo->Subject != NULL) || (opo->Sequence > 0) || (opo->Keep > 0))
po = opo;
}
memcpy(&(resOpts->Stream.Purge), po, sizeof(*po));
// Stream info options
resOpts->Stream.Info.DeletedDetails = (opts == NULL ? js->opts.Stream.Info.DeletedDetails : opts->Stream.Info.DeletedDetails);
resOpts->Stream.Info.SubjectsFilter = (opts == NULL ? js->opts.Stream.Info.SubjectsFilter : opts->Stream.Info.SubjectsFilter);
*nc = js->nc;
js_unlock(js);
}
return NATS_UPDATE_ERR_STACK(s);
}
natsStatus
jsPubOptions_Init(jsPubOptions *opts)
{
if (opts == NULL)
return nats_setDefaultError(NATS_INVALID_ARG);
memset(opts, 0, sizeof(jsPubOptions));
return NATS_OK;
}
natsStatus
js_Publish(jsPubAck **new_puback, jsCtx *js, const char *subj, const void *data, int dataLen,
jsPubOptions *opts, jsErrCode *errCode)
{
natsStatus s;
natsMsg msg;
natsMsg_init(&msg, subj, (const char*) data, dataLen);
s = js_PublishMsg(new_puback, js, &msg, opts, errCode);
natsMsg_freeHeaders(&msg);
return NATS_UPDATE_ERR_STACK(s);
}
static natsStatus
_setHeadersFromOptions(natsMsg *msg, jsPubOptions *opts)
{
natsStatus s = NATS_OK;
char temp[64] = {'\0'};
if (!nats_IsStringEmpty(opts->MsgId))
s = natsMsgHeader_Set(msg, jsMsgIdHdr, opts->MsgId);
if ((s == NATS_OK) && !nats_IsStringEmpty(opts->ExpectLastMsgId))
s = natsMsgHeader_Set(msg, jsExpectedLastMsgIdHdr, opts->ExpectLastMsgId);
if ((s == NATS_OK) && !nats_IsStringEmpty(opts->ExpectStream))
s = natsMsgHeader_Set(msg, jsExpectedStreamHdr, opts->ExpectStream);
if ((s == NATS_OK) && (opts->ExpectLastSeq > 0))
{
snprintf(temp, sizeof(temp), "%" PRIu64, opts->ExpectLastSeq);
s = natsMsgHeader_Set(msg, jsExpectedLastSeqHdr, temp);
}
if (s == NATS_OK)
{
if (opts->ExpectNoMessage)
{
s = natsMsgHeader_Set(msg, jsExpectedLastSubjSeqHdr, "0");
}
else if (opts->ExpectLastSubjectSeq > 0)
{
snprintf(temp, sizeof(temp), "%" PRIu64, opts->ExpectLastSubjectSeq);
s = natsMsgHeader_Set(msg, jsExpectedLastSubjSeqHdr, temp);
}
}
return NATS_UPDATE_ERR_STACK(s);
}
static natsStatus
_checkMaxWaitOpt(int64_t *new_ttl, jsPubOptions *opts)
{
int64_t ttl;
if ((ttl = opts->MaxWait) < 0)
return nats_setError(NATS_INVALID_ARG, "option 'MaxWait' (%" PRId64 ") cannot be negative", ttl);
*new_ttl = ttl;
return NATS_OK;
}
natsStatus
js_PublishMsg(jsPubAck **new_puback,jsCtx *js, natsMsg *msg,
jsPubOptions *opts, jsErrCode *errCode)
{
natsStatus s = NATS_OK;
int64_t ttl = 0;
nats_JSON *json = NULL;
natsMsg *resp = NULL;
jsApiResponse ar = JS_EMPTY_API_RESPONSE;
if (errCode != NULL)
*errCode = 0;
if ((js == NULL) || (msg == NULL) || nats_IsStringEmpty(msg->subject))
return nats_setDefaultError(NATS_INVALID_ARG);
if (opts != NULL)
{
s = _checkMaxWaitOpt(&ttl, opts);
IFOK(s, _setHeadersFromOptions(msg, opts));
if (s != NATS_OK)
return NATS_UPDATE_ERR_STACK(s);
}
// As it would be for a NATS connection, if the context has been destroyed,
// the memory is invalid and accessing any field of the context could cause
// a SEGFAULT. But assuming the context is still valid, we can access its
// options and the NATS connection without locking since they are immutable
// and the NATS connection has been retained when getting the JS context.
// If not set through options, default to the context's Wait value.
if (ttl == 0)
ttl = js->opts.Wait;
IFOK_JSR(s, natsConnection_RequestMsg(&resp, js->nc, msg, ttl));
if (s == NATS_OK)
s = js_unmarshalResponse(&ar, &json, resp);
if (s == NATS_OK)
{
if (js_apiResponseIsErr(&ar))
{
if (errCode != NULL)
*errCode = (int) ar.Error.ErrCode;
s = nats_setError(NATS_ERR, "%s", ar.Error.Description);
}
else if (new_puback != NULL)
{
// The user wants the jsPubAck object back, so we need to unmarshal it.
jsPubAck *pa = NULL;
pa = (jsPubAck*) NATS_CALLOC(1, sizeof(jsPubAck));
if (pa == NULL)
s = nats_setDefaultError(NATS_NO_MEMORY);
else
{
s = nats_JSONGetStr(json, "stream", &(pa->Stream));
IFOK(s, nats_JSONGetULong(json, "seq", &(pa->Sequence)));
IFOK(s, nats_JSONGetBool(json, "duplicate", &(pa->Duplicate)));
IFOK(s, nats_JSONGetStr(json, "domain", &(pa->Domain)));
if (s == NATS_OK)
*new_puback = pa;
else
jsPubAck_Destroy(pa);
}
}
js_freeApiRespContent(&ar);
nats_JSONDestroy(json);
}
natsMsg_Destroy(resp);
return NATS_UPDATE_ERR_STACK(s);
}
void
jsPubAck_Destroy(jsPubAck *pa)
{
if (pa == NULL)
return;
NATS_FREE(pa->Stream);
NATS_FREE(pa->Domain);
NATS_FREE(pa);
}
static void
_freePubAck(jsPubAck *pa)
{
if (pa == NULL)
return;
NATS_FREE(pa->Stream);
NATS_FREE(pa->Domain);
}
static natsStatus
_parsePubAck(natsMsg *msg, jsPubAck *pa, jsPubAckErr *pae, char *errTxt, size_t errTxtSize)
{
natsStatus s = NATS_OK;
jsErrCode jerr = 0;
if (natsMsg_isTimeout(msg))
{
s = NATS_TIMEOUT;
}
else if (natsMsg_IsNoResponders(msg))
{
s = NATS_NO_RESPONDERS;
}
else
{
nats_JSON *json = NULL;
jsApiResponse ar;
// Now unmarshal the API response and check if there was an error.
s = js_unmarshalResponse(&ar, &json, msg);
if (s == NATS_OK)
{
if (js_apiResponseIsErr(&ar))
{
s = NATS_ERR;
jerr = (jsErrCode) ar.Error.ErrCode;
snprintf(errTxt, errTxtSize, "%s", ar.Error.Description);
}
// If it is not an error and caller wants to decode the jsPubAck...
else if (pa != NULL)
{
memset(pa, 0, sizeof(jsPubAck));
s = nats_JSONGetStr(json, "stream", &(pa->Stream));
IFOK(s, nats_JSONGetULong(json, "seq", &(pa->Sequence)));
IFOK(s, nats_JSONGetBool(json, "duplicate", &(pa->Duplicate)));
IFOK(s, nats_JSONGetStr(json, "domain", &(pa->Domain)));
}
js_freeApiRespContent(&ar);
nats_JSONDestroy(json);
}
}
// This will handle the no responder or timeout cases, or if we had errors
// trying to unmarshal the response.
if (s != NATS_OK)
{
// Set the error text only if not already done.
if (errTxt[0] == '\0')
snprintf(errTxt, errTxtSize, "%s", natsStatus_GetText(s));
memset(pae, 0, sizeof(jsPubAckErr));
pae->Err = s;
pae->ErrCode = jerr;
pae->ErrText = errTxt;
}
return s;
}
static void
_handleAsyncReply(natsConnection *nc, natsSubscription *sub, natsMsg *msg, void *closure)
{
const char *subject = natsMsg_GetSubject(msg);
char *id = NULL;
jsCtx *js = (jsCtx*) closure;
natsMsg *pmsg = NULL;
char errTxt[256] = {'\0'};
jsPubAckErr pae;
jsPubAck pa;
struct jsOptionsPublishAsync *opa = NULL;
if ((subject == NULL) || (int) strlen(subject) <= js->rpreLen)
{
natsMsg_Destroy(msg);
return;
}
id = (char*) (subject+js->rpreLen);
js_lock(js);
pmsg = natsStrHash_Remove(js->pm, id);
if (pmsg == NULL)
{
js_unlock(js);
natsMsg_Destroy(msg);
return;
}
opa = &(js->opts.PublishAsync);
if (opa->AckHandler)
{
jsPubAckErr *ppae = NULL;
jsPubAck *ppa = NULL;
// If _parsePubAck returns an error, we will set the pointer ppae to
// our stack variable 'pae', otherwise, set the pointer ppa to the
// stack variable 'pa', which is the jsPubAck (positive ack).
if (_parsePubAck(msg, &pa, &pae, errTxt, sizeof(errTxt)) != NATS_OK)
ppae = &pae;
else
ppa = &pa;
// Invoke the handler with pointer to either jsPubAck or jsPubAckErr.
js_unlock(js);
(opa->AckHandler)(js, pmsg, ppa, ppae, opa->AckHandlerClosure);
js_lock(js);
_freePubAck(ppa);
// Set pmsg to NULL because user was responsible for destroying the message.
pmsg = NULL;
}
else if ((opa->ErrHandler != NULL) && (_parsePubAck(msg, NULL, &pae, errTxt, sizeof(errTxt)) != NATS_OK))
{
// We will invoke CB only if there is any kind of error.
// Associate the message with the pubAckErr object.
pae.Msg = pmsg;
js_unlock(js);
(opa->ErrHandler)(js, &pae, opa->ErrHandlerClosure);
js_lock(js);
// If the user resent the message, pae->Msg will have been cleared.
// In this case, do not destroy the message. Do not blindly destroy
// an address that could have been set, so destroy only if pmsg
// is same value than pae->Msg.
if (pae.Msg != pmsg)
pmsg = NULL;
}
// Now that the callback has returned, decrement the number of pending messages.
js->pmcount--;
// If there are callers waiting for async pub completion, or stalled async
// publish calls and we are now below max pending, broadcast to unblock them.
if (((js->pacw > 0) && (js->pmcount == 0))
|| ((js->stalled > 0) && (js->pmcount <= opa->MaxPending)))
{
natsCondition_Broadcast(js->cond);
}
js_unlock(js);
natsMsg_Destroy(pmsg);
natsMsg_Destroy(msg);
}
static void
_subComplete(void *closure)
{
js_release((jsCtx*) closure);
}
static natsStatus
_newAsyncReply(char *reply, jsCtx *js)
{
natsStatus s = NATS_OK;
// Create the internal objects if it is the first time that we are doing
// an async publish.
if (js->rsub == NULL)
{
s = natsCondition_Create(&(js->cond));
IFOK(s, natsStrHash_Create(&(js->pm), 64));
if (s == NATS_OK)
{
js->rpre = NATS_MALLOC(js->rpreLen+1);
if (js->rpre == NULL)
s = nats_setDefaultError(NATS_NO_MEMORY);
else
{
char nuid[NUID_BUFFER_LEN+1];
s = natsNUID_Next(nuid, sizeof(nuid));
if (s == NATS_OK)
{
memcpy(js->rpre, js->nc->inboxPfx, js->nc->inboxPfxLen);
memcpy(js->rpre+js->nc->inboxPfxLen, nuid+((int)strlen(nuid)-jsReplyTokenSize), jsReplyTokenSize);
js->rpre[js->rpreLen-1] = '.';
js->rpre[js->rpreLen] = '\0';
}
}
}
if (s == NATS_OK)
{
char *subj = NULL;
if (nats_asprintf(&subj, "%s*", js->rpre) < 0)
s = nats_setDefaultError(NATS_NO_MEMORY);
else
s = natsConn_subscribeNoPool(&(js->rsub), js->nc, subj, _handleAsyncReply, (void*) js);
if (s == NATS_OK)
{
_retain(js);
natsSubscription_SetPendingLimits(js->rsub, -1, -1);
natsSubscription_SetOnCompleteCB(js->rsub, _subComplete, (void*) js);
}
NATS_FREE(subj);
}
if (s != NATS_OK)
{
// Undo the things we created so we retry again next time.
// It is either that or we have to always check individual
// objects to know if we have to create them.
NATS_FREE(js->rpre);
js->rpre = NULL;
natsStrHash_Destroy(js->pm);
js->pm = NULL;
natsCondition_Destroy(js->cond);
js->cond = NULL;
}
}
if (s == NATS_OK)
{
int64_t l;
int i;
memcpy(reply, js->rpre, js->rpreLen);
l = nats_Rand64();
for (i=0; i < jsReplyTokenSize; i++)
{
reply[js->rpreLen+i] = jsDigits[l%jsBase];
l /= jsBase;
}
reply[js->rpreLen+jsReplyTokenSize] = '\0';
}
return NATS_UPDATE_ERR_STACK(s);
}
static void
_timeoutPubAsync(natsTimer *t, void *closure)
{
jsCtx *js = (jsCtx*) closure;
pmInfo *pm = NULL;
int64_t now = nats_Now();
int64_t next= 0;
js_lock(js);
if (js->closed)
{
js_unlock(js);
return;
}
while (((pm = js->pmHead) != NULL) && (pm->deadline <= now))
{
natsMsg *m = NULL;
if (natsMsg_Create(&m, pm->subject, NULL, NULL, 0) != NATS_OK)
break;
natsMsg_setTimeout(m);
// Best attempt, ignore NATS_SLOW_CONSUMER errors which may be returned
// here.
nats_lockSubAndDispatcher(js->rsub);
natsSub_enqueueUserMessage(js->rsub, m);
nats_unlockSubAndDispatcher(js->rsub);
js->pmHead = pm->next;
_destroyPMInfo(pm);
}
if (js->pmHead == NULL)
{
if (js->pmTail != NULL)
js->pmTail = NULL;
next = 60*60*1000;
}
else
{
next = js->pmHead->deadline - now;
if (next <= 0)
next = 1;
}
natsTimer_Reset(js->pmtmr, next);
js_unlock(js);
}
static void
_timeoutPubAsyncComplete(natsTimer *t, void *closure)
{
jsCtx *js = (jsCtx*) closure;
js_release(js);
}
static natsStatus
_trackPublishAsyncTimeout(jsCtx *js, char *subject, int64_t mw)
{
natsStatus s = NATS_OK;
pmInfo *pm = NULL;
pmInfo *pmi = NATS_CALLOC(1, sizeof(pmInfo));
if (pmi == NULL)
return nats_setDefaultError(NATS_NO_MEMORY);
pmi->subject = NATS_STRDUP(subject);
if (pmi->subject == NULL)
{
NATS_FREE(pmi);
return nats_setDefaultError(NATS_NO_MEMORY);
}
pmi->deadline = nats_Now() + mw;
// Check if we can add at the end of the list
if (((pm = js->pmTail) != NULL) && (pmi->deadline >= pm->deadline))
{
js->pmTail->next = pmi;
js->pmTail = pmi;
}
// Or before the first
else if (((pm = js->pmHead) != NULL) && (pmi->deadline < pm->deadline))
{
pmi->next = js->pmHead;
js->pmHead = pmi;
natsTimer_Reset(js->pmtmr, mw);
}
// If the list was empty
else if (js->pmHead == NULL)
{
js->pmHead = pmi;
js->pmTail = pmi;
if (js->pmtmr == NULL)
{
s = natsTimer_Create(&js->pmtmr, _timeoutPubAsync, _timeoutPubAsyncComplete, mw, (void*) js);
if (s == NATS_OK)
js_retain(js);
}
else
natsTimer_Reset(js->pmtmr, mw);
}
else
{
// Guaranteed to be somewhere in the list (not first, not last, and at
// least 2 elements).
pm = js->pmHead;
while ((pm != NULL) && (pm->next != NULL) && (pmi->deadline > pm->next->deadline))
pm = pm->next;
pmi->next = pm->next;
pm->next = pmi;
}
if (s != NATS_OK)
_destroyPMInfo(pmi);
return NATS_UPDATE_ERR_STACK(s);
}
static natsStatus
_registerPubMsg(natsConnection **nc, char *reply, jsCtx *js, natsMsg *msg, int64_t mw)
{
natsStatus s = NATS_OK;
char *id = NULL;
bool release = false;
int64_t maxp = 0;
js_lock(js);
maxp = js->opts.PublishAsync.MaxPending;
js->pmcount++;
s = _newAsyncReply(reply, js);
if (s == NATS_OK)
id = reply+js->rpreLen;
if ((s == NATS_OK)
&& (maxp > 0)
&& (js->pmcount > maxp))
{
int64_t target = nats_setTargetTime(js->opts.PublishAsync.StallWait);
_retain(js);
js->stalled++;
while ((s != NATS_TIMEOUT) && (js->pmcount > maxp))
s = natsCondition_AbsoluteTimedWait(js->cond, js->mu, target);
js->stalled--;
if (s == NATS_TIMEOUT)
s = nats_setError(s, "%s", "stalled with too many outstanding async published messages");
release = true;
}
if ((s == NATS_OK) && (mw > 0))
s = _trackPublishAsyncTimeout(js, reply, mw);
if (s == NATS_OK)
s = natsStrHash_Set(js->pm, id, true, msg, NULL);
if (s == NATS_OK)
*nc = js->nc;
else
js->pmcount--;
if (release)
js_unlockAndRelease(js);
else
js_unlock(js);
return NATS_UPDATE_ERR_STACK(s);
}
natsStatus
js_PublishAsync(jsCtx *js, const char *subj, const void *data, int dataLen,
jsPubOptions *opts)
{
natsStatus s;
natsMsg *msg = NULL;
s = natsMsg_Create(&msg, subj, NULL, (const char*) data, dataLen);
IFOK(s, js_PublishMsgAsync(js, &msg, opts));