Debian Codegraph @

lib/Rinci/function.pod

raw
1 # no code
2 ## no critic: RequireUseStrict
3 package Rinci::function; # just to make PodWeaver happy
4
5 # AUTHORITY
6 # DATE
7 our $DIST = 'Rinci'; # DIST
8 # VERSION
9
10 1;
11 # ABSTRACT: Metadata for your functions/methods
12
13 __END__
14
15 =pod
16
17 =encoding UTF-8
18
19 =head1 NAME
20
21 Rinci::function - Metadata for your functions/methods
22
23 =head1 SPECIFICATION VERSION
24
25 1.1
26
27 =head1 VERSION
28
29 This document describes version 1.1.104 of Rinci::function (from Perl distribution Rinci), released on 2023-09-30.
30
31 =head1 INTRODUCTION
32
33 This document describes metadata for functions/methods. Since the metadata
34 properties describe features and the way a function works, this document also
35 describes how a function should support those properties.
36
37 This specification is part of L<Rinci>. Please do a read up on it first, if you
38 have not already done so.
39
40 =head1 SPECIFICATION
41
42 =head2 Enveloped result
43
44 Function should return an enveloped result to express error code/message as well
45 as actual result. The envelope can be produced by the function itself, or added
46 by a wrapper tool. Result envelope is modeled after HTTP or L<PSGI> response; it
47 is an array in the following format:
48
49 [STATUS*, MESSAGE, RESULT, META]
50
51 STATUS is a 3-digit integer and is the only required element, much like HTTP
52 response status code and is explained further in L</"Envelope status codes">.
53 MESSAGE is a string containing error message. RESULT (or PAYLOAD) is the actual
54 content to be returned and can be omitted or set to undef if the function does
55 not need to return anything. META is called result metadata, a defhash
56 containing extra data, analogous to HTTP response headers. Result metadata is
57 specified further in L<Rinci::resmeta>.
58
59 Some example of an enveloped results:
60
61 [200]
62 [200, "OK", 42]
63 [404, "Not found"]
64 [200, "Account created", {id=>9323}, {}]
65 [500, "Can't delete foo: permission denied", undef,
66 {"cmdline.exit_code"=>300, perm_err=>1}]
67
68 As mentioned, an enveloped result can contain error code/message as well as the
69 actual result. It can also be easily converted to HTTP response message. And it
70 can also contain extra data, useful for things like the transaction protocol
71 (explained in L<Rinci::Transaction>).
72
73 =head2 Special arguments
74
75 Special arguments are some known arguments that start with dash (C<->) and serve
76 special purposes. You need not specify them in the C<args> metadata property.
77 Examples of special arguments include C<-dry_run>, C<-tx_action>, C<-action>,
78 C<-confirm/*>, C<-arg_part_start>, C<-arg_part_len>, C<-res_part_start>,
79 C<-res_part_len>. Many of them will be explained in other related
80 sections/documents, but some will be described here:
81
82 =over
83
84 =item * -content_type_ARGNAME
85
86 This special argument can be used to describe the MIME content type of an
87 argument, where C<ARGNAME> is the argument name. For example, if you are
88 creating a function that accepts data upload (in Perl):
89
90 upload(data => '...', -content_type_data => 'image/jpeg');
91
92 =back
93
94 =head2 Functions vs methods
95
96 Since in many programming languages (like Perl 5, Python, Ruby, PHP) static
97 functions are not that differentiated from methods, functions and methods share
98 the same Rinci spec. But there are certain properties that can be used to
99 declare if a function is (also) a method or not. See C<is_func>, C<is_meth>,
100 C<is_class_meth> properties below for details.
101
102 =head2 Multiple dispatch
103
104 This specification also does not (yet) have any recommendation on how to best
105 handle functions in languages that support multiple dispatch, like Perl 6:
106 whether we should create multiple metadata or just one. It is more up to the
107 tool and what you want to do with the metadata.
108
109 =head2 Envelope status codes
110
111 In general, status codes map directly to HTTP response status codes. Below are
112 the suggestion on which codes to use (or avoid). An asterisk (C<*>) marks which
113 codes are not defined in HTTP specification and introduced by this
114 specification.
115
116 =over
117
118 =item * 1xx code
119
120 Currently not used. Some tools like L<Perinci::CmdLine> assumes that status code
121 is always C<< >= 200 >>, so you should perhaps never used status less than 200.
122
123 =item * 2xx code - success
124
125 200 should be used to mean success.
126
127 201 (created) can be used to signal success when creating something.
128
129 204 (no content) can also be used when there is no content to show. In HTTP,
130 browsers won't clear current page if response is 206 (instead of showing a blank
131 page if response is 200). Currently in Rinci there is no difference between 200
132 and 204.
133
134 206 (partial content) can be used to signal partial content. See C<partial>
135 property in the C<result> function property.
136
137 207 (multistatus) can be used to signal partial success, for example a function
138 which processed 5 items wanted to report that it successfully processed 2 items
139 but failed to process the rest 3 items. For each item's statuses, you can use
140 result metadata property C<results>. Note: 207 is used by WebDAV. Note: When all
141 functions instead of only some/partial items fail, you might want to return 4xx
142 or 5xx instead of 207.
143
144 =item * 3xx code - further actions needs to be taken by user agent (caller)
145
146 301 (moved) can be used to redirect callers to alternate location, although this
147 is very rare.
148
149 304 (not modified, nothing done). Used for example by setup functions to
150 indicate that nothing is being modified or no modifying action has been
151 performed (see Setup::* modules in CPAN).
152
153 331* (confirmation required). Function requires confirmation, for example if
154 action to be taken is dangerous or requires user's attention. Confirmation
155 message/prompt from function can be returned in the message, or in the
156 C<confirm_prompt> property (e.g. to provide translations). Confirmation from
157 caller is in the form of special argument C<-confirm> with boolean value of true
158 (TODO: A more detailed confirmation for different actions can be specified later
159 in the form of C<-confirm_XXX> special arguments.) For an example of application
160 of this, see L<Perinci::Tx::Manager>.
161
162 =item * 4xx code - client (caller) side error
163
164 400 (bad request, bad arguments) should be returned when the function encounters
165 invalid input. A function wrapper can return this code when the function
166 arguments fail the argument schema validation (specified in the C<args>
167 property).
168
169 401 (authentication required).
170
171 403 (forbidden, access denied, authorization failed).
172
173 404 (not found). Can be used for example by an object-retrieval functions (like
174 C<get_user()>) and the object is not found.
175
176 For object-listing functions (like C<list_users()>), when there are no users
177 found matching the requested criteria, 200 code should still be returned with an
178 empty result (like an empty array or hash).
179
180 Also in general, an object-deletion function (like C<delete_user()>) should also
181 return 200 (or perhaps 304, but 200 is preferred) instead of 404 when the object
182 specified to be deleted is not found, since the goal of the delete function is
183 reached anyway.
184
185 408 (request timeout).
186
187 409 (conflict). Can be used for example by a C<create_user()> function when
188 receiving an already existing username.
189
190 412 (precondition failed). Similar to 409, but can be used to indicate lack of
191 resources, like disk space or bandwidth. For lacking authentication and
192 authorization, use 401 and 403 respectively.
193
194 413 (request range not satisfiable). When client requests partial result outside
195 the range of available. See the C<partial> property in C<result> property for
196 examples.
197
198 429 (too many requests).
199
200 (EXPERIMENTAL) 44x* codes are reserved for function-specific codes. Each
201 function is free to define what each number means. However, this is not really
202 encouraged and should only be used if necessary. Function should perhaps stick
203 to predefined codes here. To return more detailed status, result metadata can be
204 used.
205
206 480* is general transaction error, e.g. transaction status is aborted so further
207 requests for this transaction is ignored until transaction is aborted.
208
209 484* (no such transaction).
210
211 =item * 5xx code - server (callee) side error
212
213 500 is the general code to use when a failure occurs during the execution of a
214 function. for example when a C<delete_file()> function fails to delete specified
215 file (though in this case it can also choose to return 403 instead, which is
216 more specific).
217
218 501 (not implemented)
219
220 503 (service unavailable). You can use this when service is temporarily
221 unavailable, e.g. when system load is too high, a required service is down, etc.
222 Users should try again at a later time.
223
224 507 (insufficient storage)
225
226 521 (maximum retries reached)
227
228 531* (bad metadata) is used when there is something wrong with the metadata.
229
230 532* (failure in recording transaction) when there is a failure in updating
231 transaction status or in preparing/committing/rolling back the transaction.
232
233 (EXPERIMENTAL) 54x* codes are reserved for function-specific codes. Each
234 function is free to define what each number means. However, this is not really
235 encouraged and should only be used if necessary. Function should perhaps stick
236 to predefined codes here. To return more detailed status, result metadata can be
237 used.
238
239 Try not to use code greater than 555, as some tools use (CODE-300) for error
240 codes that must fit in one unsigned byte (like L<Perinci::CmdLine>).
241
242 =back
243
244 =head2 is_func
245
246 Bool. Specify that the function can be called as a static function (i.e.
247 procedural, not as a method). Default is true if unspecified, but becomes false
248 if is_meth or is_class_meth is set to true.
249
250 Example:
251
252 # specify that function can be called a method *as well as* a static function
253 is_meth => 1
254 is_func => 1 # if not specified, will default to false after is_meth set to 1
255
256 =head2 is_meth
257
258 Bool. Specify that the function can be called as an instance (object) method.
259 Default is false.
260
261 Example:
262
263 # specify that function is a method
264 is_meth => 1
265
266 =head2 is_class_meth
267
268 Bool. Specify that the function can be called as a class method. Examples of
269 class methods include the constructor, but there are others. Default is false.
270
271 Example:
272
273 # specify that function is a class method
274 is_class_meth => 1
275
276 =head2 args (function property)
277
278 Hash. Specify arguments. Property value is defhash of argument names and
279 argument specification. Argument name must only contain letters, numbers, and
280 underscores (and do not start with a number).
281
282 Argument specification is a hash containing these keys:
283
284 =head3 schema (argument property)
285
286 L<Data::Sah> schema for argument value.
287
288 =head3 default
289
290 Any. Give default value for argument. This takes precedence over schema, which
291 can also specify default value. This is useful if you want to share a common
292 schema over several arguments but want to have different default for each
293 argument. For example, you have a C<ticket_status> schema. In C<create_ticket>
294 function you want the default C<status> argument to be C<new>, while in
295 C<reply_ticket> you want the default C<status> to be C<answered>.
296
297 =head3 summary (argument property)
298
299 Str. From DefHash. A one-line plaintext summary, much like the C<summary>
300 property in variable metadata.
301
302 =head3 req
303
304 Bool. Specify that argument is required (although its value can be undef/null).
305 Default is false.
306
307 =head3 description (argument property)
308
309 Str. From DefHash. A longer description of marked up text, much like the
310 C<description> property. It is suggested to format the text to 74 columns.
311
312 =head3 tags (argument property)
313
314 Array of (str|hash). From DefHash. An array of tags, can be used by tools to
315 categorize arguments. Not unlike the C<tags> property.
316
317 =head3 pos
318
319 Non-negative integer. Argument position when specified in an ordered fashion,
320 e.g. in an array. Starts from zero.
321
322 =head3 slurpy
323
324 Bool. Only relevant if B<pos> is specified, specify whether argument should
325 gobble up all remaining values in an ordered argument list into an array.
326
327 Old alias: L</greedy>
328
329 =head3 greedy
330
331 Old alias for L</slurpy>. Will be removed in Rinci 1.2.
332
333 =head3 partial (argument property)
334
335 Bool. Whether or not argument value can be sent partially. Only argument types
336 that have a length notion can be set as partial (e.g. C<str> where the unit is
337 character, C<buf> where the unit is byte, and C<array> where the unit is
338 element).
339
340 There should at most be one argument with this property set to true.
341
342 To send partial argument, you can use the special arguments C<-arg_len> (total
343 argument length), C<-arg_part_start> (start position of the part that is being
344 sent), C<-arg_part_len> (length of part that is being sent). Example (in Perl):
345
346 # function metadata
347 {
348 v => 1.1,
349 summary => "Upload a file",
350 args => {
351 name => {schema=>"str*", req=>1},
352 data => {schema=>"buf*", req=>1, partial=>1},
353 },
354 }
355
356 # function usage example: send the first 10MiB of data
357 upload_file(name=>"myvideo.mp4", data=>substr($data, 0, 10_000_000),
358 -arg_len => 24_500_000,
359 -arg_part_start => 0,
360 -arg_part_len => 10_000_000);
361 # send the next 10MiB
362 upload_file(name=>"myvideo.mp4", data=>substr($data, 10_000_000, 10_000_000),
363 -arg_len => 24_500_000,
364 -arg_part_start => 10_000_000,
365 -arg_part_len => 10_000_000);
366 # send the last 4.5 MiB
367 upload_file(name=>"myvideo.mp4", data=>substr($data, 20_000_000),
368 -arg_len => 24_500_000,
369 -arg_part_start => 20_000_000,
370 -arg_part_len => 4_500_000);
371
372 =head3 stream (argument property)
373
374 Bool. By setting this property to true, function can specify that it accepts
375 streaming data for this argument. It is useful when argument value is large or
376 of undetermined/infinite length. To send value as a stream, caller must send a
377 subroutine reference (callback) instead which the function will call repeatedly
378 until it gets undef to signify exhaustion of data.
379
380 =head3 cmdline_aliases
381
382 Hash. Specify aliases for use in command-line options (or other possibly
383 suitable situation where arguments are parsed from command-line-like options).
384 Keys are alias names, values are itself hashes (alias specification). Valid
385 alias specification keys: C<summary> (a string, optional), C<schema> (optional,
386 defaults to argument's schema), C<is_flag> (bool, optional, if set to 1 then it
387 is a shortcut for specifying C<schema> to C<< ["bool", {"is":1}] >>), C<code> (a
388 code to set argument value, optional, will be given C<< (\%args, $val) >>); if
389 not set, the default behavior is simply to set the argument value).
390
391 =head3 cmdline_on_getopt
392
393 Code. A hook that will be called when argument is specified as a command-line
394 option. In Perl, hook will be called with a hash argument containing this key:
395 C<arg> (str, argument name), C<value> (str, option value), C<args> (hash, the
396 argument hash defined so far).
397
398 This can be useful if you want to process a command-line option directly on a
399 per-option basis instead of getting the final resulting argument value. For
400 example (in Perl):
401
402 args => {
403 library => {
404 schema => ['array*' => of => 'str*'],
405 cmdline_aliases => { I => {} },
406 cmdline_on_getopt => sub {
407 my %args = @_;
408 require lib;
409 lib->import($args{value});
410 },
411 },
412 module => {
413 schema => ['array*' => of => 'str*'],
414 cmdline_aliases => { M => {} },
415 cmdline_on_getopt => sub {
416 my %args = @_;
417 require Module::Load;
418 Module::Load::load($args{value});
419 },
420 },
421 }
422
423 With command-line argument like this:
424
425 -I dir1 -M mod1 -I dir2 -M mod2
426
427 Without any C<cmdline_on_getopt> hooks, the function will receive this argument
428 hash:
429
430 { library => ['dir1', 'dir2'], module => ['mod1', 'mod2'] }
431
432 but there is no way to know the order of options being specified in the
433 command-line. With the hooks, the function can load modules correctly (e.g.
434 loading C<mod1> won't search in C<dir2> as that directory has not been added by
435 -I).
436
437 =head3 completion (argument property)
438
439 Code. A code to supply argument value completion. Will be explained in the
440 examples.
441
442 =head3 index_completion
443
444 Code. A code to supply argument element index completion. Applicable to the
445 following argument types:
446
447 B<hash>: for completing hash pair keys. (See also C<element_completion> for
448 completing hash pair values).
449
450 See examples for how to use this property.
451
452 =head3 element_completion
453
454 Code. A code to supply argument element value completion. Applicable to the
455 following argument types:
456
457 B<array>: for completing array element values.
458
459 B<hash>: for completing hash pair values. (See also C<index_completion> for
460 completing hash keys).
461
462 See examples for how to use this property.
463
464 =head3 is_password
465
466 Experimental. Bool. Describe that argument holds password. Programs can react to
467 this in several ways, for example they can turn off echoing to terminal when
468 asking value from standard input. Or they can redact values to C<****> when
469 logging.
470
471 =head3 cmdline_src
472
473 Str. Normally in a command-line program, command-line options and arguments will
474 map to function arguments, e.g. C<--arg 2> will set the C<foo> argument to C<2>
475 and positional arguments (argument which specifies the C<pos> property and
476 optionally also a C<slurpy> property with true value) will get or slurp
477 command-line arguments.
478
479 In some cases, this is not convenient. When supplying larger amount of data, a
480 complex structures, or a stream, we might want to use other sources. The
481 C<cmdline_src> property can be set to one of the following value for this
482 purpose:
483
484 =over
485
486 =item * file
487
488 Command-line option/argument value will be treated as filename and function
489 argument will be set to content of the file (or in the case of streaming
490 argument, to a callback which can be used to get the file's content).
491
492 =item * stdin
493
494 This means that program should get function argument from the whole standard
495 input until EOF.
496
497 Note that only one argument can have its source set to C<stdin> or
498 C<stdin_or_file> or C<stdin_or_files> or C<stdin_or_args>.
499
500 =item * stdin_or_file
501
502 This means that program should get argument value from content of file (the name
503 of which is given from the first remaining command-line argument after all other
504 arguments/options have been processed), or, if none is provided, from standard
505 input.
506
507 =item * stdin_or_files
508
509 This means that program should get argument value from content of files (the
510 names of which are taken from the remaining command-line arguments after all
511 other arguments/options have been processed), or, or if no command-line argument
512 remains, from standard input. This behavior is similar to the C<< <> >> (diamond
513 operator) in Perl.
514
515 =item * stdin_or_args
516
517 This means that program should get argument value from remaining command-line
518 argument(s), or if no command-line argument remains, from standard input.
519
520 =item * stdin_line
521
522 This means that program should get argument value from a line of standard input;
523 newline ending will be removed from the argument value.
524
525 Arguments with C<cmdline_src> of C<stdin_line> will be processed before
526 C<stdin>/C<stdin_or_file>/C<stdin_or_files>/C<stdin_or_args>.
527
528 =back
529
530 Other sources might be defined in the future.
531
532 TODO: Define C<web_src> property?
533
534 TODO: A way to define record separator?
535
536 =head3 cmdline_prompt
537
538 Str. String to display when asking for argument value from stdin (if
539 C<cmdline_src> property value is C<stdin_line>.
540
541 TODO: cmdline_prompt_template?
542
543 =head3 meta
544
545 Experimental. Hash. This allows specifying argument submetadata, used e.g. when
546 dealing with forms (a form field/widget can be a subform). Value is Rinci
547 function metadata.
548
549 =head3 element_meta
550
551 Experimental. Hash. This allows specifying argument element submetadata, used
552 e.g. when dealing with forms (a form field/widget can contain an array of
553 records/subforms). Value is Rinci function metadata.
554
555 =head3 deps (argument property)
556
557 Hash. This property specifies argument's dependencies to other arguments (but
558 possibly to other things too, in the future). This is similar to function's
559 L</"deps (function property)"> property. It is a hash or dep types and values.
560 The most important dep type is C<arg> (dependency to another argument). Some dep
561 types are special: C<all>, C<any>, C<none>. Example:
562
563 # function metadata property
564 args => {
565 delete => {
566 schema=>'bool',
567 },
568 force => {
569 summary => 'Force deletion',
570 schema => 'bool',
571 deps => {arg=>'delete'},
572 },
573 ...
574 },
575
576 The above example states that argument C<force> "depends on" C<delete>. What it
577 means (usually) is that specifying C<force> only makes sense when C<delete> is
578 also specified. In a CLI context:
579
580 % prog --delete --force
581
582 Specifying C<--force> without C<--delete> doesn't make sense.
583
584 To depend on any one of several arguments, use the dep type C<any>, e.g.:
585
586 # function metadata property
587 args => {
588 delete => {
589 schema=>'bool',
590 },
591 replace => {
592 schema=>'bool',
593 },
594 force => {
595 summary => 'Force deletion',
596 schema => 'bool',
597 deps => {any => [
598 {arg=>'delete'},
599 {arg=>'replace'},
600 ]},
601 },
602 ...
603 },
604
605 In CLI context, this means C<--force> can be specified when C<--delete> or
606 C<--replace> is specified.
607
608 To depend on several arguments, use the dep type C<all>, e.g.:
609
610 # function metadata property
611 args => {
612 red => {
613 schema=>'uint',
614 pos => 0,
615 },
616 green => {
617 schema=>'uint',
618 pos => 1,
619 },
620 blue => {
621 schema=>'uint',
622 pos => 2,
623 },
624 rgb16 => {
625 schema => 'Use 3x16bits = 48bits to represent RGB value instead of the default 3x8 = 24bits',
626 deps => {all => [
627 {arg=>'red'},
628 {arg=>'green'},
629 {arg=>'blue'},
630 ]},
631 },
632 ...
633 },
634
635 In CLI context, this means specifying C<--rgb16> only makes sense when all of
636 C<--ed>, C<--green>, C<--blue> are specified.
637
638 =head3 filters
639
640 Experimental. Array of string, or code. Filters to apply before argument is
641 converted from text and validated.
642
643 =head3 examples (argument property)
644
645 Array. Each element is sample argument values. But if it is a hash, will be
646 assumed as a DefHash with the actual value put in the C<value> property (so if
647 your sample argument is a hash like C<{}> (in JSON), you have to specify it as
648 C<< {"value":{}, "summary":"Optional summary..."} >> (in JSON).
649
650 Note that a Sah schema can also have an L<examples|Sah::Type/"examples"> clause
651 which you can use to put examples in. And Rinci function metadata also has
652 L<examples|/"examples (function property)"> property too.
653
654 Example function metadata and its implementation in Perl:
655
656 $SPEC{multiply2} = {
657 v => 1.1,
658 summary => 'Multiple two numbers',
659 args => {
660 a => {
661 summary => 'The first operand',
662 description => '... a longer description ...',
663 schema=>['float*', {
664 examples => [1, -10, 0, 3.333],
665 }],
666 pos => 0,
667 tags => ['category:operand'],
668 },
669 b => {
670 summary => 'The second operand',
671 description => '... a longer description ...',
672 schema => 'float*',
673 pos => 1,
674 tags => ['category:operand'],
675 examples => [
676 1, -10, 0, 3.333,
677 {value => 1e-10, summary => 'Blah blah'},
678 ],
679 },
680 round => {
681 summary => 'Whether to round result',
682 description => '... a longer description ...',
683 schema => [bool => {default=>0}],
684 pos => 2,
685 tags => ['category:options'],
686 cmdline_aliases => {
687 r=>{},
688 R=>{summary=>'Equivalent to --round=0',
689 code=>sub { my ($args, $val) = @_; $args->{round}=0 }},
690 },
691 },
692 }
693 };
694 sub multiply2 {
695 my %args = @_;
696 my $res = $args{a} * $args{b};
697 $res = int($res) if $round;
698 [200, "OK", $res];
699 }
700
701 By default, without any wrapper, the function is called with a named hash style:
702
703 multiply2(a=>4, b=>3); # 12
704
705 But with the information from the metadata, a wrapper tool like
706 Perinci::Sub::Wrapper is able to change the calling style to positional:
707
708 multiply2(4, 3.1, 1); # 12
709
710 A command-line tool will also enable the function to be called named options as
711 well as positional arguments:
712
713 % multiply2 --a 2 --b 3
714 % multiply2 2 --b 3
715 % multiply2 2 3
716
717 As mentioned earlier, C<cmdline_alises> is parsed by command-line option parser:
718
719 % multiply2 2 3.5 -r ; # equivalent to multiply2 2 3 --round
720 % multiply2 2 3.5 -R ; # equivalent to multiply2 2 3 --noround (--round=0)
721
722 Aliases in C<cmdline_aliases> are not recognized as real arguments:
723
724 multiply2(a=>4, b=>3, r=>0); # unknown argument r
725
726 Another example (demonstrates C<cmdline_aliases>):
727
728 $SPEC{smtpd} = {
729 v => 1.1,
730 summary => 'Control SMTP daemon',
731 args => {
732 action => {
733 schema => ['str*' => {in=>[qw/status start stop restart/]}],
734 pos => 0,
735 req => 1,
736 cmdline_aliases => {
737 status => {
738 schema => [bool=>{is=>1}],
739 summary => 'Alias for setting action=status',
740 code => sub { $_[0]{action} = 'status' },
741 },
742 start => {
743 schema => [bool=>{is=>1}],
744 summary => 'Alias for setting action=start',
745 code => sub { $_[0]{action} = 'start' },
746 },
747 stop => {
748 schema => [bool=>{is=>1}],
749 summary => 'Alias for setting action=stop',
750 code => sub { $_[0]{action} = 'stop' },
751 },
752 restart => {
753 schema => [bool=>{is=>1}],
754 summary => 'Alias for setting action=restart',
755 code => sub { $_[0]{action} = 'restart' },
756 },
757 },
758 },
759 force => {
760 schema => 'bool',
761 },
762 },
763 };
764
765 Another example (demonstrates B<slurpy>):
766
767 $SPEC{multiply_many} = {
768 v => 1.1,
769 summary => 'Multiple numbers',
770 args => {
771 nums => {
772 schema => ['array*' => {of=>'num*', min_len=>1}],
773 pos => 0,
774 slurpy => 1
775 },
776 },
777 };
778 sub multiply_many {
779 my %args = @_;
780 my $nums = $args{nums};
781
782 my $ans = 1;
783 $ans *= $_ for @$nums;
784 [200, "OK", $ans];
785 }
786
787 After wrapping, in positional mode it can then be called:
788
789 multiply_many(2, 3, 4); # 24
790
791 which is the same as (in normal named-argument style):
792
793 multiply_many(nums => [2, 3, 4]); # 24
794
795 In command-line:
796
797 % multiply-many 2 3 4
798
799 in addition to the normal:
800
801 % multiply-many --nums '[2, 3, 4]'
802
803 B<completion>. This argument specification key specifies how to complete
804 argument value (e.g. in shell or L<Riap::HTTP>) and is supplied an anonymous
805 function as value. The function will be called with arguments: word=>... (which
806 is the formed word so far, ci=>0|1 (whether completion should be done
807 case-insensitively). The function should return an array containing a list of
808 possible candidates, or a hash containing these keys: C<completion> (array, list
809 of possible candidates) and extra keys for formatting hints e.g. C<is_path>
810 (bool, whether the list of completion is path-like, meaning it can be
811 traversed/dug to multiple levels) C<path_sep> (string, path separator
812 character), C<type> (string, either C<filename>, C<env>, or other types). For an
813 example of implementation for this, see L<Perinci::Sub::Complete> in Perl which
814 provides tab completion for argument values. Example:
815
816 $SPEC{delete_user} = {
817 v => 1.1,
818 args => {
819 username => {
820 schema => 'str*',
821 pos => 0,
822 completion => sub {
823 my %args = @_;
824 my $word = $args{word} // "";
825
826 # find users beginning with $word
827 local $CWD = "/home";
828 return [grep {-d && $_ ~~ /^\Q$word/} <*>];
829 },
830 },
831 force => {schema=>[bool => {default=>0}]},
832 },
833 };
834
835 When C<delete_user> is executed over the command line and the Tab key is
836 pressed:
837
838 $ delete-user --force --username fo<tab>
839 $ delete-user fo<tab>
840
841 then B<bash> will try to complete with usernames starting with C<fo>.
842
843 B<element_completion>. This is like B<completion>, but for array or hash
844 elements. Argument type must be C<array> or C<hash>. Example for array:
845
846 $SPEC{delete_users} = {
847 v => 1.1,
848 args => {
849 usernames => {
850 schema => ['array*' => of => 'str*'],
851 req => 1,
852 pos => 0,
853 slurpy => 1,
854 element_completion => sub {
855 my %args = @_;
856 my $word = $args{word} // "";
857
858 # find users beginning with $word
859 local $CWD = "/home";
860 my $res = [grep {-d && $_ ~~ /^\Q$word/} <*>];
861
862 # exclude users already mentioned by user
863 my $ary = $args{args}{usernames};
864 $res = [grep {!($_ ~~ @$ary)}] @$res;
865
866 return $res;
867 },
868 },
869 },
870 };
871
872 When C<delete_users> is executed over the command line:
873
874 $ delete-users c<tab> ; # will complete with all users beginning with c
875 $ delete-users charlie c<tab> ; # will complete with users but exclude charlie
876 $ delete-users charlie chucky <tab> ; # and so on
877
878 Example for hash (as well as B<index_completion> property to complete hash
879 keys):
880
881 $SPEC{create_file} = {
882 v => 1.1,
883 args => {
884 filename => {
885 schema => 'str*',
886 req => 1,
887 pos => 0,
888 },
889 content => {
890 schema => 'buf*',
891 req => 1,
892 pos => 1,
893 },
894 mode => {
895 summary => 'Permission mode',
896 schema => 'posint*',
897 },
898 extra_attrs => {
899 'x.name.is_plural' => 1,
900 'x.name.singular' => 'extra_attr',
901 schema => ['hash*' => of => 'str*'],
902 index_completion => sub {
903 # complete with list of known attributes
904 my %args = @_;
905 require Complete::Util;
906 Complete::Util::complete_array_elem(
907 word => $args{word},
908 array => [qw/mtime ctime owner group/],
909 );
910 },
911 element_completion => sub {
912 my %args = @_;
913 my $word = $args{word} // "";
914 my $index = $args{index};
915
916 if ($index eq 'owner') {
917 require Complete::Unix;
918 return Complete::Unix::complete_user(word=>$word);
919 } elsif ($index eq 'group') {
920 require Complete::Unix;
921 return Complete::Unix::complete_group(word=>$word);
922 } else {
923 return undef;
924 }
925 },
926 },
927 },
928 };
929
930 When C<create_file> is executed over the command line:
931
932 $ create-file file1 "hello filesystem" --extra-attr <tab>; # will complete with list of known attributes
933 $ create-file file1 "hello filesystem" --extra-attr owner=<tab>; # will complete with list of Unix users
934
935 =head2 args_rels
936
937 Hash. This property is used to expression relationships between arguments. The
938 value is actually L<Sah> schema hash clause set (see hash type in L<Sah::Type>).
939 The arguments are represented as a hash, and you can use the various Sah clauses
940 to express relationships between the arguments (hash keys) because the Sah hash
941 type supports such clauses, e.g. C<choose_one>, C<choose_all>, C<req_one>,
942 C<req_all>, C<dep_any>, C<dep_all>, C<req_dep_any>, C<req_dep_all>.
943
944 Examples:
945
946 args_rels => {
947 choose_one => ['delete', 'add', 'edit'],
948 choose_all => ['red', 'green', 'blue'],
949 }
950
951 The above example says that only one of C<delete>, C<add>, C<edit> can be
952 specified. And if any of C<red>, C<green>, C<blue> is specified then all must be
953 specified. In CLI context this translates to:
954
955 % prog --delete item
956 % prog --delete --add item ; # error, both --delete and --add specified
957
958 % prog --red 255 --green 255 --blue 0
959 % prog --red 255 --blue 0 ; # error, --green is missing
960
961 Another example:
962
963 XXX
964
965 =head2 args_as
966
967 Str. Specify in what form the function expects the arguments. The value is
968 actually implementation-specific since it describes the function implementation.
969 For example in L<Perinci> for Perl, these values are recognized: C<array>,
970 C<hash>, C<arrayref>, C<hashref>. This property is useful for wrapper to be able
971 to convert one form to another.
972
973 The default value is also left to the implementation.
974
975 For interimplementation communication (e.g. via L<Riap::HTTP> or L<Riap::TCP>),
976 named arguments are always used so this property is irrelevant.
977
978 =head2 result
979
980 DefHash. Specify function return value. It is a defhash containing keys:
981
982 =over 4
983
984 =item * summary (result property)
985
986 From DefHash. Like the C<summary> property in variable metadata.
987
988 =item * description (result property)
989
990 From DefHash. Like the C<description> property. Suggested to be formatted to 78
991 columns.
992
993 =item * schema (result property)
994
995 A Sah schema to validate the result (the third element in the envelope result).
996 This schema should only be tested if status is 200. See also: C<statuses>.
997
998 =item * statuses
999
1000 Hash. Can be used to specify different result schema for different statuses. For
1001 example:
1002
1003 statuses => {
1004 206 => {
1005 schema => 'str*',
1006 },
1007 }
1008
1009 =item * stream (result property)
1010
1011 Bool. Specify that function returns streaming output. Note that function can
1012 also signify streaming output by setting result metadata property C<stream> to
1013 true.
1014
1015 Function must then return a subroutine reference (callback) as its actual result
1016 which the caller can call repeatedly until it gets undef to signify exhaustion.
1017
1018 =item * partial (result property)
1019
1020 Bool. If set to true, specify that it is possible to request partial result. An
1021 example is in a function that reads contents from (potentially large) files:
1022
1023 # function metadata
1024 {
1025 v => 1.1,
1026 summary => 'Read file contents',
1027 args => {
1028 name => {
1029 summary => 'File name',
1030 schema => 'str*',
1031 req => 1,
1032 },
1033 },
1034 result => {schema=>'buf*', partial=>1},
1035 }
1036
1037 # example function usage: request to read first 10MiB of file content,
1038 # -result_part_start defaults to 0.
1039 my $res = read_file(name=>'myvideo.mp4', -res_part_len=>10000000);
1040 # => [206, "Partial content", "data...", {len=>24500000, part_start=>0, part_len=>10000000}]
1041
1042 # request the next 10MiB
1043 my $res = read_file(name=>'myvideo.mp4', -res_part_start=>10000000, -res_part_len=>10000000);
1044 # => [206, "Partial content", "data...", {len=>24500000, part_start=>10000000, part_len=>10000000}]
1045
1046 # request the next 10MiB, since this actual file size is only 24500000,
1047 # function should return 416 status
1048 my $res = read_file(name=>'myvideo.mp4', -res_part_start=>20000000, -res_part_len=>10000000);
1049 # => [416, "Request range not satisfiable, file size is only 24500000"]
1050
1051 # request the next 4.5MiB, this time succeeds
1052 my $res = read_file(name=>'myvideo.mp4', -res_part_start=>20000000, -res_part_len=>4500000);
1053 # => [206, "Partial content", "data...", {len=>24500000, part_start=>20000000, part_len=>4500000}]
1054
1055 Partial result request to a function which does not support partial result might
1056 have the effect of the whole content being returned (status 200) or status 416.
1057
1058 =back
1059
1060 Note that since functions normally return enveloped result, instead of
1061 returning:
1062
1063 RESULT
1064
1065 your functions normally have to return an enveloped result:
1066
1067 [STATUS, MESSAGE, RESULT, METADATA]
1068
1069 Examples:
1070
1071 # result is an integer
1072 result => {schema => 'int*'}
1073
1074 # result is an integer starting from zero
1075 result => {schema => ['int*' => {ge=>0}]}
1076
1077 # result is an array of records
1078 result => {
1079 summary => 'Matching addressbook entries',
1080 schema => ['array*' => {
1081 summary => 'blah blah blah ...',
1082 of => ['hash*' => {allowed_keys=>[qw/name age address/]} ]
1083 }]
1084 }
1085
1086 =head2 result_naked
1087
1088 Bool. If set to true, specify that function does not envelope its results. The
1089 default is false, to encourage functions to create envelopes. However, wrapper
1090 should be able to create or strip envelope if needed. For example, if you have
1091 "traditional" functions which does not do envelopes, you can set this property
1092 to true, and the wrapper can generate the envelope for the functions.
1093
1094 =head2 examples (function property)
1095
1096 Array. This property allows you to put examples in a detailed and structured
1097 way, as an alternative to putting everything in C<description>.
1098
1099 Each example is a defhash, it specifies what arguments are used, what the
1100 results are, and some description. It can be used when generating API/usage
1101 documentation, as well as for testing data. It can also be used for testing
1102 (function will be run with specified arguments and the result will be matched
1103 against expected result). Known properties:
1104
1105 =over 4
1106
1107 =item * args (function example property)
1108
1109 Hash. Arguments used to produce result. Can be converted to C<argv> by tool,
1110 e.g. when displaying command-line examples.
1111
1112 =item * argv
1113
1114 Array. An alternative to C<args>, for example when function is run from the
1115 command-line. Can be converted to C<args> most of the time when wanting to
1116 display examples in Perl instead of command-line.
1117
1118 =item * src
1119
1120 Str. An alternative to C<args> or C<argv>, to provide raw source code. See also:
1121 C<src_plang>. This can be used to show more general examples. For example, you
1122 can show how a function is used in an expression or code block, or how a
1123 command-line program is used in a shell script.
1124
1125 Exactly one of C<args>, C<argv>, or C<src> must be specified.
1126
1127 =item * src_plang
1128
1129 Str. The programming language the examples source code C<src> is written in.
1130 Valid values include: C<perl>, C<bash>.
1131
1132 Command-line interface tools will typically only show examples written in
1133 C<bash> or other shells, while Perl module tools will typically only show
1134 C<perl> examples.
1135
1136 Required if C<src> is specified.
1137
1138 =item * status
1139
1140 Int. Status from envelope. If unspecified, assumed to be 200.
1141
1142 =item * result
1143
1144 Any. Expected result.
1145
1146 =item * env_result
1147
1148 Array. Expected enveloped result.
1149
1150 =item * naked_result
1151
1152 Any. Expected naked result (payload).
1153
1154 =item * summary (function example property)
1155
1156 From DefHash. A one-line summary of the example You should describe, in one
1157 phrase or sentence, what the example tries to demonstrate. You can skip the
1158 summary if the example is pretty basic or things are already clear from the
1159 C<args> alone.
1160
1161 =item * description (function example property)
1162
1163 From DefHash. Longer marked up text about the example (e.g. discussion or things
1164 to note), suggested to be formatted to 72 columns.
1165
1166 =item * tags (function example property)
1167
1168 From DefHash.
1169
1170 =item * test
1171
1172 Bool. Defaults to true. Whether to actually test example or not. Examples are by
1173 default run as tests by a test module (e.g. Perl module L<Test::Rinci>. Setting
1174 this to 0 disables this example from being included in a test.
1175
1176 TODO: more detailed testing instruction (e.g. only test in release candidate,
1177 or under certain environment flag, etc).
1178
1179 =back
1180
1181 Example:
1182
1183 # part of metadata for Math::is_prime function
1184 examples => [
1185 {
1186 args => {num=>10},
1187 result => 0,
1188 # summary no needed here, already clear.
1189 },
1190 {
1191 args => {},
1192 result => 400,
1193 summary => 'Num argument is required',
1194 },
1195
1196 {
1197 argv => [-5],
1198 result => 1,
1199 summary => 'Also works for negative integers',
1200 },
1201 ],
1202
1203 Another example demonstrating C<src> for a function called C<list_countries>:
1204
1205 examples => [
1206 {
1207 src => 'for c in `list-countries`; do wget http://flags.org/country/$c; done',
1208 src_plang => 'bash',
1209 },
1210 {
1211 src => <<'EOT',
1212 my $res = list_countries(detail => 1, sort=>['-popsize']);
1213 die "Can't list countries: $res->[0] - $res->[1]" unless $res->[0] == 200;
1214 my $i = 0;
1215 for my $c (@{ $res->[2] }) { $i++; say "$i. $_->{name}'s population: $_->{popsize}";
1216 EOT
1217 src_plang => 'perl',
1218 },
1219 ],
1220
1221 =head2 features
1222
1223 DefHash. Allows functions to express their features. Each hash key contains
1224 feature name, which must only contain letters/numbers/underscores.
1225
1226 Below is the list of defined features. New feature names may be defined by
1227 extension.
1228
1229 =over 4
1230
1231 =item * reverse
1232
1233 Bool. Default: false. If set to true, specifies that function supports reverse
1234 operation. To reverse, caller can add special argument C<-reverse>. For example:
1235
1236 $SPEC{triple} = {
1237 v => 1.1,
1238 args => {num=>{schema=>'num*'}},
1239 features => {reverse=>1}
1240 };
1241 sub triple {
1242 my %args = @_;
1243 my $num = $args{num};
1244 [200, "OK", $args{-reverse} ? $num/3 : $num*3];
1245 }
1246
1247 triple(num=>12); # => 36
1248 triple(num=>12, -reverse=>1); # => 4
1249
1250 =item * tx
1251
1252 Hash. Default is none. Specify transactional support, as specified in
1253 L<Rinci::Transaction>. Value is a hash containing these keys: C<v> (int,
1254 protocol version, default if not specified is 1).
1255
1256 Please see Rinci::Transaction for more details on transaction.
1257
1258 =item * dry_run
1259
1260 Bool, or hash. If set to a true value, specifies that function supports dry-run
1261 (simulation) mode. Can also be set to a hash like this: C<<{default=>1}>> to
1262 mean that function supports dry-run and the default is dry-run mode. Example:
1263
1264 use Log::ger;
1265
1266 $SPEC{rmre} = {
1267 summary => 'Delete files in curdir matching a regex',
1268 args => {re=>{schema=>'str*'}},
1269 features => {dry_run=>1}
1270 };
1271 sub rmre {
1272 my %args = @_;
1273 my $re = qr/$args{re}/;
1274 my $dry_run = $args{-dry_run};
1275
1276 opendir my($dir), ".";
1277 while (my $f = readdir($dir)) {
1278 next unless $f =~ $re;
1279 log_info "Deleting $f ...";
1280 next if $dry_run;
1281 unlink $f;
1282 }
1283 [200, "OK"];
1284 }
1285
1286 The above Perl function delete files, but if passed argument C<-dry_run> => 1
1287 (simulation mode), will not actually delete files, only display what files match
1288 the criteria and would have be deleted.
1289
1290 Specifying a function as supporting dry_run means, among others:
1291
1292 =over 4
1293
1294 =item * If dry_run is requested, function will have no side effects
1295
1296 It will behave like a pure function, and thus have the properties of a pure
1297 function.
1298
1299 =back
1300
1301 =item * pure
1302
1303 Bool. Default: false. If set to true, specifies that function is "pure" and has
1304 no "side effects" (these are terms from functional programming / computer
1305 science). Having a side effect means changing something, somewhere (e.g. setting
1306 the value of a global variable, modifies its arguments, writing some data to
1307 disk, changing system date/time, etc.) Specifying a function as pure means,
1308 among others:
1309
1310 =over 4
1311
1312 =item * it can safely be inculded in transaction without recording in journal;
1313
1314 =item * it can safely be included during dry run;
1315
1316 =back
1317
1318 =item * immutable
1319
1320 Bool. Default is false. If set to true, specifies that function always returns
1321 the same result when given the same argument values. This enables optimization
1322 like memoization. An example of an immutable function is C<sub { $_[0]+$_[1] }>
1323 where its results only depend on the arguments. Example of a mutable function
1324 would be C<rand()> or C<read()> that reads contents from a file.
1325
1326 =item * idempotent
1327
1328 Bool. Default is false. If set to true, specifies that function is idempotent.
1329 Idempotency means that repeated invocation of a function (each with the same
1330 arguments) will have the same effect as a single invocation. In other words,
1331 extra invocation will not have any effect.
1332
1333 Some operations, like reading a database row or a file's content, is inherently
1334 idempotent (or to be exact nullipotent). Another example is setting or updating
1335 an entity to some specific value, or deleting some entity. Repeated invocation
1336 of the operation will still sets the entity to the same value, or still deletes
1337 the entity.
1338
1339 Some other operations are inherently non-idempotent, for example sending an
1340 email. Repeated invocation will cause multiple emails to be sent.
1341
1342 Yet some other operations are non-idempotent, but can be made idempotent simply
1343 by checking whether the target object(s) has (have) reached the final desired
1344 state, (optionally additionally also checking whether they are in the correct
1345 original state to begin with). For example, a function that renames a file can
1346 record the original file that was renamed (its MD5 checksum, size, or what not)
1347 or perhaps record the action in a history database or flag file, and refuse to
1348 rename again if the file to be renamed is not the original file.
1349
1350 =item * check_arg
1351
1352 Bool. Default is false. If set to true, specifies that function supports the
1353 action of checking only a single argument. Usually useful when doing form
1354 processing, where we want to check only a single form field (function argument).
1355 To check a single argument, one passes C<-action> special argument with the
1356 value of C<check_arg> and also passes the argument she wants to check. Function
1357 should check that argument and immediately return 200 status upon success, or
1358 400 upon validation failure.
1359
1360 =back
1361
1362 =head2 deps (function property)
1363
1364 Hash. This property specifies function's dependencies to various things. It is a
1365 hash of dep types and values. Some dep types are special: C<all>, C<any>, and
1366 C<none>.
1367
1368 deps => {
1369 DEPTYPE => DEPVALUE,
1370 ...,
1371 all => [
1372 {DEPTYPE=>DEPVALUE, ...},
1373 ...,
1374 },
1375 any => [
1376 {DEPTYPE => DEPVALUE, ...},
1377 ...,
1378 ],
1379 none => [
1380 {DEPTYPE => DEPVALUE, ...},
1381 ....,
1382 ],
1383 }
1384
1385 A dependency can be of any type: another function, environment variables,
1386 programs, OS software packages, etc. It is up to the dependency checker library
1387 to make use of this information.
1388
1389 For the dependencies to be declared as satisfied, all of the clauses must be
1390 satisfied.
1391
1392 Below is the list of defined dependency types. New dependency type may be
1393 defined by an extension.
1394
1395 =over 4
1396
1397 =item * env
1398
1399 Str. Require that an environment variable exists and is true, where true is in
1400 the Perl sense (not an empty string or "0"; " " and "0.0" are both true).
1401 Example:
1402
1403 env => 'HTTPS'
1404
1405 =item * prog
1406
1407 Str of defhash. Require that a program exists and is executable. If STR doesn't
1408 contain path separator character '/' it will be searched in PATH. Windows
1409 filesystem should also use Unix-style path, e.g. "C:/Program Files/Foo/Bar.exe".
1410
1411 prog => 'rsync' # any rsync found on PATH
1412 prog => '/bin/su' # won't accept any other su
1413
1414 As an alternative to just a string, the dep value can also be a defhash.
1415 Currently known properties for the defhash: C<name> (program name or path, str,
1416 required), C<path> (program path, str, optional), C<min_version> (minimum
1417 version, dotted number version str, optional).
1418
1419 =item * pkg
1420
1421 Str. Specify dependency on a L<Riap> package. STR must be a valid Riap package
1422 URI string. Checker can check that requesting C<info> on this URI succeeds and
1423 the type is indeed C<package>. Example:
1424
1425 pkg => '/Foo/'
1426
1427 =item * func
1428
1429 Str. Specify dependency on a L<Riap> function. STR must be a valid Riap function
1430 URI string. Checker can check that requesting C<info> on this URI succeeds and
1431 the type is indeed C<package>. Example:
1432
1433 pkg => '/Foo/somefunc'
1434 pkg => 'http://gudangapi.com/ga/list_ubuntu_releases'
1435
1436 =item * code
1437
1438 Code. Require that anonymous function returns a true value after called, where
1439 the notion of true depends on the host language. Example in Perl:
1440
1441 code => sub {$>} # i am not being run as root
1442
1443 Example in Ruby:
1444
1445 "code" => Proc.new { Process.euid > 0 } # i am not being run as root
1446
1447 =item * tmp_dir
1448
1449 Bool. If set to 1, specify that function requires temporary directory. Caller
1450 should provide path to this using special argument C<-tmp_dir>.
1451
1452 =item * trash_dir
1453
1454 Bool. If set to 1, specify that function requires trash directory. Trash is not
1455 unlike a temporary directory. Caller should provide path to trash directory
1456 using special argument C<-trash_dir>.
1457
1458 Trash directory can be provided, e.g. by transaction manager (see
1459 L<Rinci::Transaction>).
1460
1461 =item * all
1462
1463 Array of deps. A "meta" type that allows several dependencies to be joined
1464 together in a logical-AND fashion. All dependency hashes must be satisfied. For
1465 example, to declare a dependency to several programs and an environment
1466 variable:
1467
1468 all => [
1469 {prog => 'rsync'},
1470 {prog => 'tar'},
1471 {env => 'FORCE'},
1472 ],
1473
1474 =item * any
1475
1476 Array of deps. Like C<all>, but specify a logical-OR relationship. Any one of
1477 the dependencies will suffice. For example, to specify requirement to
1478 alternative Perl modules:
1479
1480 or => [
1481 {perl_module => 'HTTP::Daemon'},
1482 {perl_module => 'HTTP::Daemon::SSL'},
1483 ],
1484
1485 =item * none
1486
1487 Array of deps. Specify that none of the dependencies must be satisfied for this
1488 type to be satisfied. Example, to specify that the function not run under SUDO
1489 or by root:
1490
1491 none => [
1492 {env => 'SUDO_USER' },
1493 {code => sub {$> != 0} },
1494 ],
1495
1496 Note that the above is not equivalent to below:
1497
1498 none => [
1499 {env => 'SUDO_USER', code => sub {$> != 0} },
1500 ],
1501
1502 which means that if none or only one of 'env'/'code' is satisfied, the whole
1503 dependency becomes a success (since it is negated by 'none'). Probably not what
1504 you want.
1505
1506 =back
1507
1508 If you add a new language-specific dependency type, please prefix it with the
1509 language code, e.g. C<perl_module>, C<perl_func>, C<ruby_gem>, C<python_egg>.
1510 These dependency types have also been defined by some existing tools: C<deb>
1511 (dependency to a Debian package), C<rpm> (dependency to an RPM package),
1512 C<js_url> (loading a remote JavaScript script URL), C<file> (existence of a),
1513 C<perl_run_func> (running a Perl subroutine and getting a successful enveloped
1514 result). Some of these might be declared as part of the core dependency types in
1515 the future.
1516
1517 =head1 FAQ
1518
1519 =head2 What is the difference between C<summary> or C<description> in the Sah schema and arg specification?
1520
1521 Example:
1522
1523 {
1524 args => {
1525 src => {
1526 summary => "Source path",
1527 description => "...",
1528 schema => ["str*", {
1529 summary => "...",
1530 description => "...",
1531 ...
1532 }],
1533 ...
1534 },
1535 dest => {
1536 summary => "Target path",
1537 description => "...",
1538 schema => ["str*", {
1539 summary => "...",
1540 description => "...",
1541 ...
1542 }],
1543 ...
1544 },
1545 ...
1546 },
1547 }
1548
1549 As you can see, each argument has a C<summary> and C<description>, but the
1550 schema for each argument also has a C<summary> and C<description> schema
1551 clauses. What is the difference and which should be put into which?
1552
1553 The argument specification's C<summary> (and C<description>) describe the
1554 argument itself, in this example it says that C<src> means "The source path" and
1555 C<dest> means "The target path". The argument schema's C<summary> (and
1556 C<description>) describe the data type and valid values. In this example it
1557 could say, e.g., "a Unix-path string with a maximum length of 255 characters".
1558 In fact, C<src> and C<dest> are probably of the same type ("Unix path") and can
1559 share schema.
1560
1561 {
1562 ...
1563 args => {
1564 src => {
1565 ...
1566 schema => "unix_path",
1567 },
1568 dest => {
1569 ...
1570 schema => "unix_path",
1571 },
1572 ...
1573 },
1574 }
1575
1576 =head2 What is the difference between setting req=>1 in the argument specification and req=>1 in schema?
1577
1578 Example:
1579
1580 # Note: remember that in Sah, str* is equivalent to [str => {req=>1}]
1581 args => {
1582 a => { schema=>"str" },
1583 b => { schema=>"str*" },
1584 c => { req=>1, schema=>"str" },
1585 d => { req=>1, schema=>"str*" },
1586 }
1587
1588 In particular look at C<b> and C<c>. C<b> is not a required argument (no req=>1
1589 in the argument spec) but if it is specified, than it cannot be undef/null
1590 (since the schema says [str=>{req=>1}], a.k.a "str*"). On the other hand, C<c>
1591 is a required argument (req=>1 in the argument spec) but you can specify
1592 undef/null as the value. The following are valid:
1593
1594 func(c=>undef, d=>1);
1595
1596 But the following are not:
1597
1598 func(b=>1, d=>1); # c is not specified
1599 func(b=>undef, c=>1, d=>1); # b has undef value
1600 func(b=>1, c=>1, d=>undef); # d has undef value
1601
1602 =head2 Should I add a new metadata property, or add a new feature name to the C<features> property, or add a new dependency type to the C<deps> property?
1603
1604 If your property describes a dependency to something, it should definitely be a
1605 new dependency type. If your property only describes what the function can do
1606 and does not include any wrapper code, then it probably goes into C<features>.
1607 Otherwise, it should probably become a new metadata property.
1608
1609 For example, if you want to declare that your function can only be run under a
1610 certain moon phase (e.g. full moon), it should definitely go as a new dependency
1611 type, so it becomes: deps => { moon_phase => 'full' }.
1612
1613 Another example, C<reverse> is a feature name, because it just states that if we
1614 pass C<-reverse> => 1 special argument to a reversible function, it can do a
1615 reverse operation. It doesn't include any wrapper code, all functionality is
1616 realized by the function itself. On the other hand, C<timeout> is a metadata
1617 property because it involves adding adding some wrapping code (a timeout
1618 mechanism, e.g. an eval() block and alarm() in Perl).
1619
1620 =head1 HOMEPAGE
1621
1622 Please visit the project's homepage at L<https://metacpan.org/release/Rinci>.
1623
1624 =head1 SOURCE
1625
1626 Source repository is at L<https://github.com/perlancar/perl-Rinci>.
1627
1628 =head1 SEE ALSO
1629
1630 Related specifications: L<Sah>, HTTP/1.1 (RFC 2068)
1631
1632 L<Rinci>
1633
1634 =head1 AUTHOR
1635
1636 perlancar <[email protected]>
1637
1638 =head1 CONTRIBUTING
1639
1640
1641 To contribute, you can send patches by email/via RT, or send pull requests on
1642 GitHub.
1643
1644 Most of the time, you don't need to build the distribution yourself. You can
1645 simply modify the code, then test via:
1646
1647 % prove -l
1648
1649 If you want to build the distribution (e.g. to try to install it locally on your
1650 system), you can install L<Dist::Zilla>,
1651 L<Dist::Zilla::PluginBundle::Author::PERLANCAR>,
1652 L<Pod::Weaver::PluginBundle::Author::PERLANCAR>, and sometimes one or two other
1653 Dist::Zilla- and/or Pod::Weaver plugins. Any additional steps required beyond
1654 that are considered a bug and can be reported to me.
1655
1656 =head1 COPYRIGHT AND LICENSE
1657
1658 This software is copyright (c) 2023, 2022, 2021, 2020, 2019, 2018, 2017, 2016, 2015, 2014, 2013, 2012 by perlancar <[email protected]>.
1659
1660 This is free software; you can redistribute it and/or modify it under
1661 the same terms as the Perl 5 programming language system itself.
1662
1663 =head1 BUGS
1664
1665 Please report any bugs or feature requests on the bugtracker website L<https://rt.cpan.org/Public/Dist/Display.html?Name=Rinci>
1666
1667 When submitting a bug or request, please include a test-file or a
1668 patch to an existing test-file that illustrates the bug or desired
1669 feature.
1670
1671 =cut