forked from synopse/mORMot2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmormot.soa.codegen.pas
More file actions
1268 lines (1180 loc) · 44.9 KB
/
Copy pathmormot.soa.codegen.pas
File metadata and controls
1268 lines (1180 loc) · 44.9 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
/// Interface-based SOA Code and Documentation Generator
// - this unit is a part of the Open Source Synopse mORMot framework 2,
// licensed under a MPL/GPL/LGPL three license - see LICENSE.md
unit mormot.soa.codegen;
{
*****************************************************************************
SOA API Code and Documentation Generation
- ORM and SOA Logic Extraction from RTTI
- Doc/CodeGen wrapper Functions on Server Side
- FPC Dedicated Generators
- Compute Asynchronous Code from Synchronous Interface
- Generate Code and Doc from Command-Line
*****************************************************************************
}
interface
{$I ..\mormot.defines.inc}
uses
sysutils,
classes,
variants,
{$ifdef ISDELPHI}
typinfo, // for proper Delphi inlining
{$endif ISDELPHI}
mormot.core.base,
mormot.core.os,
mormot.core.buffers,
mormot.core.unicode,
mormot.core.text,
mormot.core.variants,
mormot.core.data,
mormot.core.datetime,
mormot.core.rtti,
mormot.core.json,
mormot.core.interfaces,
mormot.core.mustache,
mormot.orm.base,
mormot.orm.core,
mormot.orm.rest,
mormot.soa.core,
mormot.soa.server,
mormot.rest.core,
mormot.rest.server,
mormot.rest.memserver;
{ ************ ORM and SOA Logic Extraction from RTTI }
/// compute the Model information, ready to be exported as JSON
// - will publish the ORM and SOA properties
// - to be used e.g. for client code generation via Mustache templates
// - optional aSourcePath parameter may be used to retrieve additional description
// from the comments of the source code of the unit - this text content may
// also be injected by WRAPPER_RESOURCENAME
// - you may specify a description file (as generated by FillDescriptionFromSource)
function ContextFromModel(aServer: TRestServer;
const aSourcePath: TFileName = '';
const aDescriptions: TFileName = ''): variant;
{ ************ Doc/CodeGen wrapper Functions on Server Side }
/// generate a code/doc wrapper for a given Model and Mustache template content
// - will use all ORM and SOA properties of the supplied server
// - aFileName will be transmitted as {{filename}}, e.g. 'mORMotClient'
// - you should also specify a "fake" HTTP port e.g. 888
// - the template content could be retrieved from a file via StringFromFile()
// - you may optionally retrieve a copy of the data context as TDocVariant
// - this function may be used to generate the client at build time, directly
// from a just built server, in an automated manner
// - you may specify custom helpers (e.g. via TSynMustache.HelpersGetStandardList)
// and retrieve the generated data context after generation (if aContext is
// a TDocVariant object, its fields would be added to the rendering context),
// or a custom description file (as generated by FillDescriptionFromSource)
function WrapperFromModel(aServer: TRestServer;
const aMustacheTemplate, aFileName: RawUtf8; aPort: integer;
aHelpers: TSynMustacheHelpers = nil;
aContext: PVariant = nil;
const aDescriptions: TFileName = ''): RawUtf8;
/// generate a code/doc wrapper for a given set of types and Mustache template content
// - will use aTables[] to define the ORM information, and supplied aSharedServices[]
// aSharedServicesContract[] for SOA definition of a shared API (expected to
// be called from TRestClientUri.ServiceDefineSharedApi)
// - aFileName will be transmitted as {{filename}}, e.g. 'mORMotClient'
// - you should also specify a "fake" HTTP port e.g. 888
// - the template content could be retrieved from a file via StringFromFile()
// - you may optionally retrieve a copy of the data context as TDocVariant
// - this function may be used to generate the client at build time, directly
// from a just built server, in an automated manner
// - you may specify custom helpers (e.g. via TSynMustache.HelpersGetStandardList)
// and retrieve the generated data context after generation (if aContext is
// a TDocVariant object, its fields would be added to the rendering context),
// or a custom description file (as generated by FillDescriptionFromSource)
function WrapperForPublicAPI(const aTables: array of TOrmClass;
const aRoot, aMustacheTemplate, aFileName: RawUtf8;
const aSharedServices: array of TGuid;
const aSharedServicesContract: array of RawUtf8;
aResultAsJsonObjectWithoutResult: boolean; aPort: integer;
aHelpers: TSynMustacheHelpers = nil; aContext: PVariant = nil;
const aDescriptions: TFileName = ''): RawUtf8;
/// instantiate a TRest server instance, including supplied ORM and SOA definitions
// - will use aTables[] to define the ORM information, and supplied aSharedServices[]
// aSharedServicesContract[] for SOA definition of a shared API, implemented as
// abstract classes using TInterfaceStub
// - as used e.g. by WrapperForPublicAPI() to generate some code/doc wrappers
function WrapperFakeServer(const aTables: array of TOrmClass;
const aRoot: RawUtf8;
const aSharedServices: array of TGuid;
const aSharedServicesContract: array of RawUtf8;
aResultAsJsonObjectWithoutResult: boolean): TRestServerFullMemory;
/// you can call this procedure within a method-based service allow
// code-generation of an ORM and SOA client from a web browser
// - you have to specify one or several client *.mustache file paths
// - the first path containing any *.mustache file will be used as templates
// - for instance:
// ! procedure TCustomServer.Wrapper(Ctxt: TRestServerUriContext);
// ! begin // search in the current path
// ! WrapperMethod(Ctxt,['.']);
// ! end;
// - optional SourcePath parameter may be used to retrieve additional description
// from the comments of the source code of the unit
// - you may specify a description file (as generated by FillDescriptionFromSource)
procedure WrapperMethod(Ctxt: TRestServerUriContext;
const Path: array of TFileName;
const SourcePath: TFileName = '';
const Descriptions: TFileName = '');
/// you can call this procedure to add a 'Wrapper' method-based service
// to a given server, to allow code-generation of an ORM and SOA client
// - you have to specify one or several client *.mustache file paths
// - the first path containing any *.mustache file will be used as templates
// - if no path is specified (i.e. as []), it will search in the .exe folder
// - the root/wrapper URI will be accessible without authentication (i.e.
// from any plain browser)
// - for instance:
// ! aServer := TRestServerFullMemory.Create(aModel,'test.json',false,true);
// ! AddToServerWrapperMethod(aServer,['..']);
// - optional SourcePath parameter may be used to retrieve additional description
// from the comments of the source code of the unit
procedure AddToServerWrapperMethod(Server: TRestServer;
const Path: array of TFileName;
const SourcePath: TFileName = '');
{ ************ FPC Dedicated Generators }
/// you can call this procedure to generate the mORMotServer.pas unit needed
// to compile a given server source code using FPC
// - will locate FPCServer-mORMotServer.pas.mustache in the given Path[] array
// - will write the unit using specified file name or to mORMotServer.pas in the
// current directory if DestFileName is '', or to a sub-folder of the matching
// Path[] if DestFileName starts with '\' (to allow relative folder use)
// - the missing RTTI for records and interfaces would be defined, together
// with some patch comments for published record support (if any) for the ORM
procedure ComputeFPCServerUnit(Server: TRestServer;
const Path: array of TFileName; DestFileName: TFileName = '');
/// you can call this procedure to generate the mORMotInterfaces.pas unit needed
// to register all needed interface RTTI for FPC
// - to circumvent http://bugs.freepascal.org/view.php?id=26774 unresolved issue
// - will locate FPC-mORMotInterfaces.pas.mustache in the given Path[] array
// - will write the unit using specified file name or to mORMotInterfaces.pas in
// the current directory if DestFileName is '', or to a sub-folder of the
// matching Path[] if DestFileName starts with '\' (to allow relative folder use)
// - all used interfaces will be exported, including SOA and mocking/stubing
// types: so you may have to run this function AFTER all process is done
procedure ComputeFPCInterfacesUnit(const Path: array of TFileName;
DestFileName: TFileName = '');
{ ************ Compute Asynchronous Code from Synchronous Interface }
/// this function would generate a pascal unit defining asynchronous
// (non-blocking) types from a DDD's blocking dual-phase Select/Command service
// - you should specify the services to be converted, as an array - note that
// due to how RTTI is stored by the compiler, all "pure input" parameters should
// be defined explicitly as "const", otherwise the generated class won't match
// - optionally, the TCQRSServiceClass implementing the first Select() phase of
// the blocking service may be specified in queries array; a set of unit names
// in which those TCQRSServiceClass are defined may be specified
// - a Mustache template content should be provided - e.g. asynch.pas.mustache
// as published in SQLite3\DDD\dom folder of the source code repository
// - FileName would contain the resulting unit filename (without the .pas)
// - ProjectName would be written in the main unit comment
// - CallType should be the type used at Domain level to identify each
// asynchronous call - this type should be an integer, or a function may be
// supplied as CallFunction (matching VariantToInteger signature)
// - the first phase of the service should have set Key: KeyType, which would be
// used to create a single shared asynchronous service instance for all keys
// - ExceptionType may be customize, mainly to use a Domain-specific class
// - blocking execution may reach some timeout waiting for the asynchronous
// acknowledgement: a default delay (in ms) is to be supplied, and some custom
// delays may be specified as trios, e.g. ['IMyInterface', 'Method', 10000, ...]
function GenerateAsynchServices(const services: array of TGuid;
const queries: array of TClass;
const units: array of const;
const additionalcontext: array of const;
Template, FileName, ProjectName, CallType, CallFunction,
Key, KeyType, ExceptionType: RawUtf8;
DefaultDelay: integer; const CustomDelays: array of const): RawUtf8;
{ ************ Generate Code and Doc from Command-Line }
type
/// the options retrieved during a ExecuteFromCommandLine() call
TServiceClientCommandLineOptions = set of (
cloPrompt,
cloNoColor,
cloPipe,
cloHeaders,
cloVerbose,
cloNoExpand,
cloNoBody);
/// event handler to let ExecuteFromCommandLine call a remote server
// - before call, aParams.InBody will be set with the expected JSON content
TOnCommandLineCall = procedure(aOptions: TServiceClientCommandLineOptions;
const aService: TInterfaceFactory; aMethod: PInterfaceMethod;
var aParams: TRestUriParams) of object;
const
/// help information displayed by ExecuteFromCommandLine() with no command
// - note that Windows and POSIX don't handle the double quotes similarly,
// so putting JSON on the command line could be tricky and needs ' escaping
EXECUTEFROMCOMMANDLINEHELP =
' % help -> show all services (interfaces)'#13#10 +
' % [service] [help] -> show all methods of a given service'#13#10 +
' % [service] [method] help -> show parameters of a given method'#13#10 +
' % [options] [service] [method] [parameters] -> call a given method ' +
{$ifdef OSWINDOWS}
'with [parameters] being name=value or name=""value with spaces"" or ' +
'name:={""some"":""json""}' +
' and [options] as /nocolor /pipe /headers /verbose /noexpand /nobody';
{$else}
'with [parameters] being name=value or name=''"value with spaces"'' or ' +
'name:=''{"some":"json"}''' +
' and [options] as --nocolor --pipe --headers --verbose --noexpand --nobody';
{$endif OSWINDOWS}
/// command-line SOA remote access to mORMot interface-based services
// - supports the EXECUTEFROMCOMMANDLINEHELP commands
// - you shall have registered the aServices interface(s) by a previous call to
// the overloaded Get(TypeInfo(IMyInterface)) method or RegisterInterfaces()
// - you may specify an optional description file, as previously generated
// by mormot.soa.codegen.pas' FillDescriptionFromSource function - a local
// 'WrappersDescription' resource will also be checked
// - to actually call the remote server, aOnCall should be supplied
procedure ExecuteFromCommandLine(
const aServices: array of TGuid;
const aOnCall: TOnCommandLineCall;
const aDescriptions: TFileName = '');
implementation
{ ************ ORM and SOA Logic Extraction from RTTI }
type
/// a cross-platform published property kind
// - does not match mormot.orm.core.pas TOrmFieldType: here we recognize only
// types which may expect a special behavior in SynCrossPlatformREST.pas unit
// - should match TOrmFieldKind order in SynCrossPlatformREST.pas
TCrossPlatformOrmFieldKind = (
cpkDefault,
cpkDateTime,
cpkTimeLog,
cpkBlob,
cpkModTime,
cpkCreateTime,
cpkRecord,
cpkVariant);
const
/// those text values should match TOrmFieldKind in SynCrossPlatformREST.pas
// - was previously named sft* in mORMot 1.18
CROSSPLATFORMKIND_TEXT: array[TCrossPlatformOrmFieldKind] of RawUtf8 = (
'oftUnspecified',
'oftDateTime',
'oftTimeLog',
'oftBlob',
'oftModTime',
'oftCreateTime',
'oftRecord',
'oftVariant');
const
CROSSPLATFORM_KIND: array[TOrmFieldType] of TCrossPlatformOrmFieldKind =(
cpkDefault, // oftUnknown
cpkDefault, // oftAnsiText
cpkDefault, // oftUtf8Text
cpkDefault, // oftEnumerate
cpkDefault, // oftSet
cpkDefault, // oftInteger
cpkDefault, // oftID
cpkDefault, // oftRecord
cpkDefault, // oftBoolean
cpkDefault, // oftFloat
cpkDateTime, // oftDateTime
cpkTimeLog, // oftTimeLog
cpkDefault, // oftCurrency
cpkDefault, // oftObject
cpkVariant, // oftVariant
cpkVariant, // oftNullable
cpkBlob, // oftBlob
cpkDefault, // oftBlobDynArray
cpkDefault, // oftBlobCustom
cpkRecord, // oftUtf8Custom
cpkDefault, // oftMany
cpkModTime, // oftModTime
cpkCreateTime, // oftCreateTime
cpkDefault, // oftTID
cpkDefault, // oftRecordVersion
cpkDefault, // oftSessionUserID
cpkDateTime, // oftDateTimeMS
cpkDefault, // oftUnixTime
cpkDefault); // oftUnixMSTime
TYPES_ORM: array[TOrmFieldType] of TWrapperType = (
wUnknown, // oftUnknown
wString, // oftAnsiText
wRawUtf8, // oftUtf8Text
wEnum, // oftEnumerate
wSet, // oftSet
wUnknown, // oftInteger - wUnknown to force exact type
wORM, // oftID
wReference, // oftRecord
wBoolean, // oftBoolean
wUnknown, // oftFloat - wUnknown to force exact type
wDateTime, // oftDateTime
wTimeLog, // oftTimeLog
wCurrency, // oftCurrency
wObject, // oftObject
wVariant, // oftVariant
wVariant, // oftNullable
wBlob, // oftBlob
wArray, // oftBlobDynArray - with specific code below
wRecord, // oftBlobCustom
wRecord, // oftUtf8Custom
wUnknown, // oftMany
wModTime, // oftModTime
wCreateTime, // oftCreateTime
wID, // oftID
wRecordVersion, // oftRecordVersion
wID, // oftSessionUserID
wDateTime, // oftDateTimeMS
wUnknown, // oftUnixTime
wUnknown); // oftUnixMSTime
type
TWrapperContextRest = class(TWrapperContext)
protected
fServer: TRestServer;
fHasAnyRecord: boolean; // identify TOrmPropInfoRecordTyped
function CustomType(rtti: TRttiCustom): TWrapperType; override;
public
constructor CreateFromModel(aServer: TRestServer;
const aSourcePath: TFileName; const aDescriptions: TFileName);
function Context: variant; override;
end;
{ TWrapperContextRest }
constructor TWrapperContextRest.CreateFromModel(aServer: TRestServer;
const aSourcePath, aDescriptions: TFileName);
var
t, f, s: PtrInt;
nfoList: TOrmPropInfoList;
nfo: TOrmPropInfo;
nfoOrmFieldRttiTypeName: RawUtf8;
kind: TCrossPlatformOrmFieldKind;
hasRecord: boolean;
fields, services: TDocVariantData;
field, rec: variant;
srv: TServiceFactoryServer;
uri: RawUtf8;
begin
Create(aSourcePath, aDescriptions);
fServer := aServer;
TDocVariant.NewFast([
@fields,
@services]);
// compute ORM information
for t := 0 to fServer.Model.TablesMax do
begin
nfoList := fServer.Model.TableProps[t].Props.Fields;
fields.Clear;
fields.Init;
hasRecord := false;
for f := 0 to nfoList.Count - 1 do
begin
nfo := nfoList.List[f];
nfoOrmFieldRttiTypeName := nfo.SqlFieldRttiTypeName;
if nfo.InheritsFrom(TOrmPropInfoRtti) then
field := ContextFromRtti(TYPES_ORM[nfo.OrmFieldType],
TOrmPropInfoRtti(nfo).PropRtti, nfoOrmFieldRttiTypeName)
else if nfo.InheritsFrom(TOrmPropInfoRecordTyped) then
begin
hasRecord := true;
fHasAnyRecord := true;
field := ContextFromRtti(wRecord,
Rtti.RegisterType(TOrmPropInfoRecordTyped(nfo).TypeInfo),
nfoOrmFieldRttiTypeName);
end
else
EWrapperContext.RaiseUtf8('Unexpected type % for %.%',
[nfo, fServer.Model.Tables[t], nfo.Name]);
kind := CROSSPLATFORM_KIND[nfo.OrmFieldType];
_ObjAddProps(['index', f + 1,
'name', nfo.Name,
'camelName', LowerCamelCase(nfo.Name),
'snakeName', SnakeCase(nfo.Name),
'sql', ord(nfo.OrmFieldType),
'sqlName', nfo.OrmFieldTypeName^,
'typeKind', ord(kind),
'typeKindName', CROSSPLATFORMKIND_TEXT[kind],
'attr', byte(nfo.Attributes)], field);
if aIsUnique in nfo.Attributes then
_ObjAddProp('unique', true, field);
if nfo.FieldWidth > 0 then
_ObjAddProp('width', nfo.FieldWidth, field);
if f < nfoList.Count - 1 then
_ObjAddPropU('comma', ',', field)
else
// may conflict with rec.comma otherwise
_ObjAddProp('comma', null, field);
fields.AddItem(field);
end;
with fServer.Model.TableProps[t] do
rec := _JsonFastFmt('{tableName:?,className:?,classParent:?,' +
'fields:?,isInMormotPas:%,unitName:?,comma:%}',
[NULL_OR_TRUE[(Props.Table = TAuthGroup) or
(Props.Table = TAuthUser)],
NULL_OR_COMMA[t < fServer.Model.TablesMax]],
[Props.SqlTableName, ClassNameShort(Props.Table)^,
ClassNameShort(Props.Table.ClassParent)^,
Variant(fields),
Props.TableRtti.Info.RttiClass^.UnitName]);
if hasRecord then
rec.hasRecords := true;
fORM.AddItem(rec);
end;
// compute SOA information
if fServer.Services.Count > 0 then
begin
for s := 0 to fServer.Services.Count - 1 do
begin
srv := fServer.Services.Index(s) as TServiceFactoryServer;
if fServer.Services.ExpectMangledUri then
uri := srv.InterfaceMangledUri
else
uri := srv.InterfaceUri;
with srv do
rec := _ObjFast([
'uri', uri,
'interfaceUri', InterfaceUri,
'interfaceMangledUri', InterfaceMangledUri,
'interfaceName', InterfaceFactory.InterfaceRtti.Name,
'camelName', LowerCamelCase(InterfaceFactory.InterfaceUri),
'snakeName', SnakeCase(InterfaceFactory.InterfaceUri),
'GUID', GuidToRawUtf8(InterfaceFactory.InterfaceGuid^),
'contractExpected', UnQuoteSqlString(ContractExpected),
'instanceCreation', ord(InstanceCreation),
'instanceCreationName', GetEnumNameTrimed(
TypeInfo(TServiceInstanceImplementation), ord(InstanceCreation)),
'methods', ContextFromMethods(InterfaceFactory),
'bypassAuthentication', ByPassAuthentication,
'resultAsJsonObject', ResultAsJsonObject,
'resultAsJsonObjectWithoutResult',
ResultAsJsonObjectWithoutResult and
(InstanceCreation in SERVICE_IMPLEMENTATION_NOID),
'resultAsXMLObject', ResultAsXMLObject,
'timeoutSec', TimeoutSec,
'serviceDescription',
fDescriptions.GetValueOrNull(InterfaceFactory.InterfaceName)
]);
if srv.InstanceCreation = sicClientDriven then
rec.isClientDriven := true;
services.AddItem(rec);
end;
fSOA.InitObject(['enabled', true,
'services', variant(services),
'expectMangledUri', fServer.Services.ExpectMangledUri], JSON_FAST);
end;
end;
function TWrapperContextRest.CustomType(rtti: TRttiCustom): TWrapperType;
begin
result := TYPES_ORM[GetOrmFieldType(rtti.Info)];
end;
function TWrapperContextRest.Context: variant;
var
s: PtrInt;
authClass: TClass;
begin
result := inherited Context;
// append TRestServer specific information
if fServer = nil then
exit;
if fHasAnyRecord then
_ObjAddProp('ORMWithRecords', true, result);
// add the first supported authentication class type as default
for s := 0 to fServer.AuthenticationSchemesCount - 1 do
begin
authClass := PClass(fServer.AuthenticationSchemes[s])^;
if (authClass = TRestServerAuthenticationDefault) or
(authClass = TRestServerAuthenticationNone) then
begin
_ObjAddProp('authClass', ToText(authClass), result);
break;
end;
end;
end;
function ContextFromModel(aServer: TRestServer;
const aSourcePath, aDescriptions: TFileName): variant;
begin
with TWrapperContextRest.CreateFromModel(aServer, aSourcePath, aDescriptions) do
try
result := Context;
finally
Free;
end;
end;
{ ************ Doc/CodeGen wrapper Functions on Server Side }
procedure WrapperMethod(Ctxt: TRestServerUriContext;
const Path: array of TFileName; const SourcePath, Descriptions: TFileName);
var
root, templateName, templateTitle, savedName,
templateExt, unitName, template, result, host, uri, head: RawUtf8;
context: variant;
SR: TSearchRec;
i, templateFound, port: PtrInt;
begin
// URI is e.g. GET http://localhost:888/root/wrapper/Delphi/UnitName.pas
if (Ctxt.Method <> mGET) or
(high(Path) < 0) then
exit;
templateFound := -1;
for i := 0 to high(Path) do
if FindFirst(MakePath([Path[i], '*.mustache']), faAnyFile, SR) = 0 then
begin
templateFound := i;
break;
end;
if templateFound < 0 then
Ctxt.Error(
'Please copy some .mustache files in the expected folder (e.g. %)',
[Path[0]])
else
try
context := ContextFromModel(Ctxt.Server, SourcePath, Descriptions);
context.uri := Ctxt.UriWithoutSignature;
if llfHttps in Ctxt.Call^.LowLevelConnectionFlags then
_ObjAddProps(['protocol', 'https',
'https', true], context)
else
_ObjAddPropU('protocol', 'http', context);
host := Ctxt.InHeader['host'];
if host <> '' then
_ObjAddPropU('host', host, context);
port := GetInteger(pointer(split(host, ':', host)));
if port = 0 then
port := 80;
_ObjAddProp('port', port, context);
if PropNameEquals(Ctxt.UriMethodPath, 'context') then
begin
Ctxt.ReturnsJson(context, 200, {304=}true, twNone, {humanreadable=}true);
exit;
end;
root := Ctxt.Server.Model.Root;
if Ctxt.UriMethodPath = '' then
begin
result := '<!DOCTYPE html><html><title>mORMot Wrappers</title>' +
'<body style="font-family:verdana;"><h1>Generated Code/Doc Wrappers</h1>' +
'<hr><h2>Available Templates:</h2><ul>';
repeat
Split(StringToUtf8(SR.Name), '.', templateName, templateExt);
templateTitle := templateName;
i := PosExChar('-', templateName);
if i > 0 then
begin
SetLength(templateTitle, i - 1);
savedName := copy(templateName, i + 1, maxInt);
end
else
savedName := 'mORMotClient';
Split(templateExt, '.', templateExt);
uri := FormatUtf8('<a href=/%/wrapper/%/%.%',
[root, templateName, savedName, templateExt]);
result := FormatUtf8(
'%<li><b>%</b><br><i>%.%</i> - %>download as file</a> - ' +
'%.txt>see as text</a> - %.mustache>see template</a></li><br>',
[result, templateTitle, savedName, templateExt, uri, uri, uri]);
until FindNext(SR) <> 0;
result := FormatUtf8('%</ul><p>You can also retrieve the corresponding ' +
'<a href=/%/wrapper/context>template context</a>.<hr><p>Generated by a ' +
'<a href=http://mormot.net>Synopse <i>mORMot</i> ' +
SYNOPSE_FRAMEWORK_VERSION + '</a> server.', [result, root]);
Ctxt.Returns(result, HTTP_SUCCESS, HTML_CONTENT_TYPE_HEADER);
exit;
end;
finally
FindClose(SR);
end;
Split(Ctxt.UriMethodPath, '/', templateName, unitName);
Split(unitName, '.', unitName, templateExt);
if PosExChar('.', templateExt) > 0 then
begin
// see as text
if PropNameEquals(Split(templateExt, '.', templateExt), 'mustache') then
// force return .mustache
unitName := '';
head := TEXT_CONTENT_TYPE_HEADER;
end
else
// download as file
head := HEADER_CONTENT_TYPE + 'application/' + LowerCase(templateExt);
templateName := templateName + '.' + templateExt + '.mustache';
template := RawUtf8FromFile(MakePath([Path[templateFound], templateName]));
if template = '' then
begin
Ctxt.Error(templateName, HTTP_NOTFOUND);
exit;
end;
if unitName = '' then
result := template // asked for .mustache template
else
begin
_ObjAddProps(['templateName', templateName,
'filename', unitName], context);
result := TSynMustache.Parse(template).Render(
context, nil, TSynMustache.HelpersGetStandardList, nil, true);
end;
Ctxt.Returns(result, HTTP_SUCCESS, head);
end;
function WrapperFromModel(aServer: TRestServer;
const aMustacheTemplate, aFileName: RawUtf8; aPort: integer;
aHelpers: TSynMustacheHelpers; aContext: PVariant;
const aDescriptions: TFileName): RawUtf8;
var
context: variant;
begin
// no context.uri nor context.host here
context := ContextFromModel(aServer, '', aDescriptions);
with _Safe(context)^ do
begin
if aPort <> 0 then
i['port'] := aPort;
U['filename'] := aFileName;
if aContext <> nil then
begin
AddFrom(aContext^);
aContext^ := context;
end;
end;
if aHelpers = nil then
aHelpers := TSynMustache.HelpersGetStandardList;
result := TSynMustache.Parse(aMustacheTemplate).Render(
context, nil, aHelpers, nil, true);
end;
function WrapperFakeServer(const aTables: array of TOrmClass;
const aRoot: RawUtf8; const aSharedServices: array of TGuid;
const aSharedServicesContract: array of RawUtf8;
aResultAsJsonObjectWithoutResult: boolean): TRestServerFullMemory;
var
contract: RawUtf8;
fake: IInterface;
i: PtrInt;
begin
result := TRestServerFullMemory.CreateWithOwnModel(aTables, false, aRoot);
for i := 0 to high(aSharedServices) do
begin
if i <= high(aSharedServicesContract) then
contract := aSharedServicesContract[i]
else
contract := '';
result.ServiceDefine(
TInterfaceStub.Create(aSharedServices[i], fake).LastInterfacedObjectFake,
[aSharedServices[i]], contract).
ResultAsJsonObjectWithoutResult := aResultAsJsonObjectWithoutResult;
end;
end;
function WrapperForPublicAPI(const aTables: array of TOrmClass;
const aRoot, aMustacheTemplate, aFileName: RawUtf8;
const aSharedServices: array of TGuid;
const aSharedServicesContract: array of RawUtf8;
aResultAsJsonObjectWithoutResult: boolean; aPort: integer;
aHelpers: TSynMustacheHelpers; aContext: PVariant;
const aDescriptions: TFileName): RawUtf8;
var
server: TRestServer;
begin
server := WrapperFakeServer(aTables, aRoot, aSharedServices,
aSharedServicesContract, aResultAsJsonObjectWithoutResult);
try
result := WrapperFromModel(server, aMustacheTemplate, aFileName, aPort,
aHelpers, aContext, aDescriptions);
finally
server.Free;
end;
end;
{ TWrapperMethodHook }
type
TWrapperMethodHook = class(TPersistent)
public
SearchPath: TFileNameDynArray;
SourcePath: TFileName;
published
procedure Wrapper(Ctxt: TRestServerUriContext);
end;
procedure TWrapperMethodHook.Wrapper(Ctxt: TRestServerUriContext);
begin
WrapperMethod(Ctxt, SearchPath, SourcePath);
end;
procedure ComputeSearchPath(const Path: array of TFileName;
out SearchPath: TFileNameDynArray);
var
i: PtrInt;
begin
if length(Path) = 0 then
begin
// use .exe path
SetLength(SearchPath, 1);
SearchPath[0] := Executable.ProgramFilePath;
end
else
begin
SetLength(SearchPath, length(Path));
for i := 0 to high(Path) do
// also convert \ if needed on FPC
SearchPath[i] := ExpandFileName(Path[i]);
end;
end;
procedure AddToServerWrapperMethod(Server: TRestServer;
const Path: array of TFileName; const SourcePath: TFileName);
var
hook: TWrapperMethodHook;
begin
if Server = nil then
exit;
hook := TWrapperMethodHook.Create;
Server.PrivateGarbageCollector.Add(hook); // Server.Free will call hook.Free
ComputeSearchPath(Path, hook.SearchPath);
hook.SourcePath := SourcePath;
Server.ServiceMethodRegisterPublishedMethods('', hook);
Server.ServiceMethodByPassAuthentication('wrapper');
end;
function FindTemplate(const TemplateName: TFileName;
const Path: array of TFileName): TFileName;
var
SearchPath: TFileNameDynArray;
i: PtrInt;
begin
ComputeSearchPath(Path, SearchPath);
for i := 0 to High(SearchPath) do
begin
result := MakePath([SearchPath[i], TemplateName]);
if FileExists(result) then
exit;
end;
result := '';
end;
{ ************ FPC Dedicated Generators }
procedure ComputeFPCServerUnit(Server: TRestServer;
const Path: array of TFileName; DestFileName: TFileName);
var
TemplateName: TFileName;
begin
TemplateName := FindTemplate('FPCServer-mORMotServer.pas.mustache', Path);
if TemplateName = '' then
exit;
if DestFileName = '' then
DestFileName := 'mORMotServer.pas'
else if DestFileName[1] = PathDelim then
DestFileName := ExtractFilePath(TemplateName) + DestFileName;
FileFromString(WrapperFromModel(Server, RawUtf8FromFile(TemplateName),
StringToUtf8(ExtractFileName(DestFileName)), 0), DestFileName);
end;
procedure ComputeFPCInterfacesUnit(const Path: array of TFileName;
DestFileName: TFileName);
const
TEMPLATE_NAME = 'FPC-mORMotInterfaces.pas.mustache';
var
TemplateName: TFileName;
ctxt: variant;
begin
TemplateName := FindTemplate(TEMPLATE_NAME, Path);
if TemplateName = '' then
exit;
if DestFileName = '' then
DestFileName := 'mORMotInterfaces.pas'
else if DestFileName[1] = PathDelim then
DestFileName := ExtractFilePath(TemplateName) + DestFileName;
with TWrapperContext.CreateFromUsedInterfaces('', '') do
try
ctxt := context;
finally
Free;
end;
ctxt.fileName := GetFileNameWithoutExtOrPath(DestFileName);
FileFromString(TSynMustache.Parse(RawUtf8FromFile(TemplateName)).
Render(ctxt, nil, nil, nil, true), DestFileName);
end;
{ ************ Compute Asynchronous Code from Synchronous Interface }
{$ifdef ISDELPHI20062007}
{$WARNINGS OFF} // circumvent Delphi 2007 false positive warning
{$endif}
function GenerateAsynchServices(const services: array of TGuid;
const queries: array of TClass; const units: array of const;
const additionalcontext: array of const;
Template, FileName, ProjectName, CallType, CallFunction, Key,
KeyType, ExceptionType: RawUtf8;
DefaultDelay: integer; const CustomDelays: array of const): RawUtf8;
var
server: TRestServerFullMemory;
stub: IInvokable;
context: variant;
service, method: PDocVariantData;
pas, intf, meth: RawUtf8;
delay: Int64;
i: PtrInt;
begin
result := '';
if high(services) < 0 then
exit;
if FileName = '' then
FileName := 'ServicesAsynch';
if CallType = '' then
CallType := 'TBlockingProcessPoolCall';
if ExceptionType = '' then
ExceptionType := 'EServiceException';
server := TRestServerFullMemory.CreateWithOwnModel([]);
try
for i := 0 to high(services) do
server.ServiceDefine(
TInterfaceStub.Create(services[i], stub).LastInterfacedObjectFake,
[services[i]]);
context := ContextFromModel(server);
_ObjAddProps([
'filename', FileName,
'projectname', ProjectName,
'exeName', Executable.ProgramName,
'User', Executable.User,
'calltype', CallType,
'callfunction', CallFunction,
'exception', ExceptionType,
'defaultdelay', DefaultDelay], context);
if high(units) >= 0 then
_Safe(context)^.O['units']^.AddItems(units);
if Key <> '' then
_ObjAddProps(['asynchkey', Key,
'asynchkeytype', KeyType], context);
_ObjAddProps(additionalcontext, context);
for i := 0 to high(services) do
if i < length(queries) then
begin
intf := ToUtf8(TInterfaceFactory.Guid2TypeInfo(services[i])^.RawName);
if _Safe(context.soa.services)^.
GetDocVariantByProp('interfaceName', intf, false, service) then
service^.AddValue('query', ClassNameShort(queries[i])^)
else
EWrapperContext.RaiseUtf8('CustomDelays: unknown %', [intf]);
end;
i := 0;
while i + 2 <= high(CustomDelays) do
begin
if VarRecToUtf8IsString(CustomDelays[i], intf) and
VarRecToUtf8IsString(CustomDelays[i + 1], meth) and
VarRecToInt64(@CustomDelays[i + 2], delay) then
if _Safe(context.soa.services)^.
GetDocVariantByProp('interfaceName', intf, false, service) and
service^.GetAsDocVariantSafe('methods')^.
GetDocVariantByProp('methodName', meth, false, method) then
method^.I['asynchdelay'] := delay
else
EWrapperContext.RaiseUtf8('CustomDelays: unknown %.%', [intf, meth]);
inc(i, 3);
end;
pas := TSynMustache.Parse(Template).
Render(context, nil, TSynMustache.HelpersGetStandardList);
result := StringReplaceAll(pas, ['();', ';', '():', ':']);
//FileFromString(_Safe(context)^.ToJson('','',jsonUnquotedPropName),FileName+'.json');
finally
server.Free;
end;
end;
{$ifdef ISDELPHI20062007}
{$WARNINGS ON} // circumvent Delphi 2007 false positive warning
{$endif}
{ ************ Generate Code and Doc from Command-Line }
{ TServiceClientCommandLine }
type
/// a class implementing ExecuteFromCommandLine()
TServiceClientCommandLine = class(TSynPersistent)
protected
fExe: RawUtf8;
fOptions: TServiceClientCommandLineOptions;
fServices: array of TInterfaceFactory;
fDescriptions: TDocVariantData;
fOnCall: TOnCommandLineCall;
procedure ToConsole(const Fmt: RawUtf8; const Args: array of const;
Color: TConsoleColor = ccLightGray; NoLineFeed: boolean = false);
function Find(const name: RawUtf8; out service: TInterfaceFactory): boolean;
procedure WriteDescription(desc: RawUtf8; color: TConsoleColor;
firstline: boolean);
procedure ShowHelp;
procedure ShowAllServices;
procedure ShowService(service: TInterfaceFactory);
procedure ShowMethod(service: TInterfaceFactory; method: PInterfaceMethod);
procedure ExecuteMethod(service: TInterfaceFactory;
method: PInterfaceMethod; firstparam: integer);
public
constructor Create(const aServices: array of TGuid;
const aOnCall: TOnCommandLineCall;
const aDescriptions: TFileName); reintroduce;
procedure Execute;
end;
procedure TServiceClientCommandLine.ToConsole(const Fmt: RawUtf8;
const Args: array of const; Color: TConsoleColor; NoLineFeed: boolean);
var
txt: RawUtf8;
begin
FormatUtf8(Fmt, Args, txt);
ConsoleWrite(txt, Color, NoLineFeed, cloNoColor in fOptions);
end;
function TServiceClientCommandLine.Find(const name: RawUtf8;
out service: TInterfaceFactory): boolean;
var
s: PtrInt;
begin
for s := 0 to high(fServices) do
if IdemPropNameU(fServices[s].InterfaceUri, name) then // good FPC inlining
begin
service := fServices[s];
result := true;
exit;
end;
result := false;
end;
procedure TServiceClientCommandLine.WriteDescription(desc: RawUtf8;
color: TConsoleColor; firstline: boolean);
var
line: RawUtf8;
P: PUtf8Char;
i, j, k, l: PtrInt;
begin
if not (cloNoColor in fOptions) then
TextColor(color);
if firstline then
SetLength(desc, PosExChar(#13, desc) - 1);
if desc = '' then
exit;
P := pointer(desc);
repeat
line := GetNextLine(P, P);
if line = '' then
continue;