7611600f530c214fa5446caa35edf3faf1837f59
[src/app-framework-binder.git] / doc / writing-afb-plugins.md
1 HOWTO WRITE a PLUGIN for AFB-DAEMON
2 ===================================
3     version: 1
4     Date:    25 May 2016
5     Author:  José Bollo
6
7 TABLE-OF-CONTENT-HERE
8
9 Summary
10 -------
11
12 The binder afb-daemon serves files through
13 the HTTP protocol and offers access to API's through
14 HTTP or WebSocket protocol.
15
16 The plugins are used to add API's to afb-daemon.
17 This part describes how to write a plugin for afb-daemon.
18 Excepting this summary, this part is intended to be read
19 by developpers.
20
21 Before going into details, through a tiny example,
22 a short overview plugins basis is needed.
23
24 ### Nature of a plugin
25
26 A plugin is a separate piece of code made of a shared library.
27 The plugin is loaded and activated by afb-daemon when afb-daemon
28 starts.
29
30 Technically, a plugin is not linked to any library of afb-daemon.
31
32 ### Kinds of plugins
33
34 There is two kinds of plugins: application plugins and service
35 plugins.
36
37 #### Application plugins
38
39 Application plugins are intended to be instanciated for each
40 application: when an application using that plugin is started,
41 its binder starts a new instance of the plugin.
42
43 It means that the application plugins mainly have only one
44 context to manage for one client.
45
46 #### Service plugins
47
48 Service plugins are intended to be instanciated only one time
49 only and connected to many clients.
50
51 So either it does not manage context at all or otherwise,
52 if it manages context, it should be able to manage one context
53 per client.
54
55 In details, it may be useful to have service plugins at a user
56 level.
57  
58 ### Live cycle of a plugin within afb-daemon
59
60 The plugins are loaded and activated when afb-daemon starts.
61
62 At start, the plugin initialise itself.
63 If it fails to initialise then afb-daemon stops.
64
65 Conversely, if it success to initialize, it must declare
66 a name, that must be unique, and a list of API's verbs.
67
68 When initialized, the functions implementing the API's verbs
69 of the plugin are activated on call.
70
71 At the end, nothing special is done by afb-daemon.
72 Consequently, developpers of plugins should use 'atexit'
73 or 'on_exit' during initialisation if they need to
74 perform specific actions when stopping.
75
76 ### Content of a plugin
77
78 For afb-daemon, a plugin contains 2 different
79 things: names and functions.
80
81 There is two kind of names:
82  - the name of the plugin,
83  - the names of the verbs.
84
85 There is two kind of functions:
86  - the initialisation function
87  - functions implementing verbs
88
89 Afb-daemon translates the name of the method that is
90 invoked to a pair of API and verb names. For example,
91 the method named **foo/bar** translated to the API
92 name **foo** and the verb name **bar**.
93 To serve it, afb-daemon search the plugin that record
94 the name **foo** and if it also recorded the verb **bar**,
95 it calls the implementation function declared for this verb.
96
97 Afb-daemon make no distinction between lower case
98 and upper case when searching for a method.
99 Thus, The names **TicTacToe/Board** and **tictactoe/borad**
100 are equals.
101
102 #### The name of the plugin
103
104 The name of the plugin is also known as the name
105 of the API that defines the plugin.
106
107 This name is also known as the prefix.
108
109 The name of a plugin MUST be unique within afb-daemon.
110
111 For example, when a client of afb-daemon
112 calls a method named **foo/bar**. Afb-daemon
113 extracts the prefix **foo** and the suffix **bar**.
114 **foo** is the API name and must match a plugin name,
115 the plugin that implements the verb **bar**.
116
117 #### Names of verbs
118
119 Each plugin exposes a set of verbs that can be called
120 by client of afb-daemon.
121
122 The name of a verb MUST be unique within a plugin.
123
124 Plugins link verbs to functions that are called
125 when clients emit requests for that verb.
126
127 For example, when a client of afb-daemon
128 calls a method named **foo/bar**.
129
130 #### The initialisation function
131
132 The initialisation function serves several purposes.
133
134 1. It allows afb-daemon to check the version
135 of the plugin using the name of the initialisation
136 functions that it found. Currently, the initialisation
137 function is named **pluginAfbV1Register**. It identifies
138 the first version of plugins.
139
140 2. It allows the plugin to initialise itself.
141
142 3. It serves to the plugin to declare names, descriptions,
143 requirements and implmentations of the verbs that it exposes.
144
145 #### Functions implementing verbs
146
147 When a method is called, afb-daemon constructs a request
148 object and pass it to the implementation function for verb
149 within the plugin of the API.
150
151 An implementation function receives a request object that
152 is used to get arguments of the request, to send
153 answer, to store session data.
154
155 A plugin MUST send an answer to the request.
156
157 But it is not mandatory to send the answer
158 before to return from the implementing function.
159 This behaviour is important for implementing
160 asynchronous actions.
161
162 Implementation functions that always reply to the request
163 before returning are named *synchronous implementations*.
164 Those that don't always reply to the request before
165 returning are named *asynchronous implementations*.
166
167 Asynchronous implementations typically initiate an
168 asynchronous action and record to send the reply
169 on completion of this action.
170
171 The Tic-Tac-Toe example
172 -----------------------
173
174 This part explains how to write an afb-plugin.
175 For the sake of being practical we will use many
176 examples from the tic-tac-toe example.
177 This plugin example is in *plugins/samples/tic-tac-toe.c*.
178
179 This plugin is named ***tictactoe***.
180
181 Choosing names
182 --------------
183
184 The designer of a plugin must defines names for its plugin
185 (or its API) and for the verbs of its API. He also
186 must defines names for arguments given by name.
187
188 While forging names, the designer should take into account
189 the rules for making valid names and some rules that make
190 the names easy to use across plaforms.
191
192 The names and strings used ALL are UTF-8 encoded.
193
194 ### Names for API (plugin)
195
196 The names of the API are checked.
197 All characters are authorised except:
198
199 - the control characters (\u0000 .. \u001f)
200 - the characters of the set { ' ', '"', '#', '%', '&',
201   '\'', '/', '?', '`', '\x7f' }
202
203 In other words the set of forbidden characters is
204 { \u0000..\u0020, \u0022, \u0023, \u0025..\u0027,
205   \u002f, \u003f, \u0060, \u007f }.
206
207 Afb-daemon make no distinction between lower case
208 and upper case when searching for an API by its name.
209
210 ### Names for verbs
211
212 The names of the verbs are not checked.
213
214 However, the validity rules for verb's names are the
215 same as for API's names except that the dot (.) character
216 is forbidden.
217
218 Afb-daemon make no distinction between lower case
219 and upper case when searching for an API by its name.
220
221 ### Names for arguments
222
223 The names for arguments are not restricted and can be
224 anything.
225
226 The arguments are searched with the case sensitive
227 string comparison. Thus the names "index" and "Index"
228 are not the same.
229
230 ### Forging names widely available
231
232 The key names of javascript object can be almost
233 anything using the arrayed notation:
234
235         object[key] = value
236
237 That is not the case with the dot notation:
238
239         object.key = value
240
241 Using the dot notation, the key must be a valid javascript
242 identifier.
243
244 For this reason, the chosen names should better be
245 valid javascript identifier.
246
247 It is also a good practice, even for arguments, to not
248 rely on the case sensitivity and to avoid the use of
249 names different only by the case.
250
251 Options to set when compiling plugins
252 -------------------------------------
253
254 Afb-daemon provides a configuration file for *pkg-config*.
255 Typing the command
256
257         pkg-config --cflags afb-daemon
258
259 will print the flags to use for compiling, like this:
260
261         $ pkg-config --cflags afb-daemon
262         -I/opt/local/include -I/usr/include/json-c 
263
264 For linking, you should use
265
266         $ pkg-config --libs afb-daemon
267         -ljson-c
268
269 As you see, afb-daemon automatically includes dependency to json-c.
270 This is done through the **Requires** keyword of pkg-config.
271
272 If this behaviour is a problem, let us know.
273
274 Header files to include
275 -----------------------
276
277 The plugin *tictactoe* has the following lines for its includes:
278
279         #define _GNU_SOURCE
280         #include <stdio.h>
281         #include <string.h>
282         #include <json-c/json.h>
283         #include <afb/afb-plugin.h>
284
285 The header *afb/afb-plugin.h* includes all the features that a plugin
286 needs except two foreign header that must be included by the plugin
287 if it needs it:
288
289 - *json-c/json.h*: this header must be include to handle json objects;
290 - *systemd/sd-event.h*: this must be include to access the main loop;
291 - *systemd/sd-bus.h*: this may be include to use dbus connections.
292
293 The *tictactoe* plugin does not use systemd features so it is not included.
294
295 When including *afb/afb-plugin.h*, the macro **_GNU_SOURCE** must be
296 defined.
297
298 Writing a synchronous verb implementation
299 -----------------------------------------
300
301 The verb **tictactoe/board** is a synchronous implementation.
302 Here is its listing:
303
304         /*
305          * get the board
306          */
307         static void board(struct afb_req req)
308         {
309                 struct board *board;
310                 struct json_object *description;
311
312                 /* retrieves the context for the session */
313                 board = board_of_req(req);
314                 INFO(afbitf, "method 'board' called for boardid %d", board->id);
315
316                 /* describe the board */
317                 description = describe(board);
318
319                 /* send the board's description */
320                 afb_req_success(req, description, NULL);
321         }
322
323 This examples show many aspects of writing a synchronous
324 verb implementation. Let summarize it:
325
326 1. The function **board_of_req** retrieves the context stored
327 for the plugin: the board.
328
329 2. The macro **INFO** sends a message of kind *INFO*
330 to the logging system. The global variable named **afbitf**
331 used represents the interface to afb-daemon.
332
333 3. The function **describe** creates a json_object representing
334 the board.
335
336 4. The function **afb_req_success** sends the reply, attaching to
337 it the object *description*.
338
339 ### The incoming request
340
341 For any implementation, the request is received by a structure of type
342 **struct afb_req**.
343
344 > Note that this is a PLAIN structure, not a pointer to a structure.
345
346 The definition of **struct afb_req** is:
347
348         /*
349          * Describes the request by plugins from afb-daemon
350          */
351         struct afb_req {
352                 const struct afb_req_itf *itf;  /* the interfacing functions */
353                 void *closure;                  /* the closure for functions */
354         };
355
356 It contains two pointers: one, *itf*, points to the functions needed
357 to handle the internal request represented by the second pointer, *closure*.
358
359 > The structure must never be used directly.
360 > Insted, use the intended functions provided
361 > by afb-daemon and described here.
362
363 *req* is used to get arguments of the request, to send
364 answer, to store session data.
365
366 This object and its interface is defined and documented
367 in the file names *afb/afb-req-itf.h*
368
369 The above example uses 2 times the request object *req*.
370
371 The first time, it is used for retrieving the board attached to
372 the session of the request.
373
374 The second time, it is used to send the reply: an object that
375 describes the current board.
376
377 ### Associating a context to the session
378
379 When the plugin *tic-tac-toe* receives a request, it musts regain
380 the board that describes the game associated to the session.
381
382 For a plugin, having data associated to a session is a common case.
383 This data is called the context of the plugin for the session.
384 For the plugin *tic-tac-toe*, the context is the board.
385
386 The requests *afb_req* offer four functions for
387 storing and retrieving the context associated to the session.
388
389 These functions are:
390
391 - **afb_req_context_get**:
392   retrieves the context data stored for the plugin.
393
394 - **afb_req_context_set**:
395   store the context data of the plugin.
396
397 - **afb_req_context**:
398   retrieves the context data of the plugin,
399   if needed, creates the context and store it.
400
401 - **afb_req_context_clear**:
402   reset the stored data.
403
404 The plugin *tictactoe* use a convenient function to retrieve
405 its context: the board. This function is *board_of_req*:
406
407         /*
408          * retrieves the board of the request
409          */
410         static inline struct board *board_of_req(struct afb_req req)
411         {
412                 return afb_req_context(req, (void*)get_new_board, (void*)release_board);
413         }
414
415 The function **afb_req_context** ensure an existing context
416 for the session of the request.
417 Its two last arguments are functions. Here, the casts are required
418 to avoid a warning when compiling.
419
420 Here is the definition of the function **afb_req_context**
421
422         /*
423          * Gets the pointer stored by the plugin for the session of 'req'.
424          * If the stored pointer is NULL, indicating that no pointer was
425          * already stored, afb_req_context creates a new context by calling
426          * the function 'create_context' and stores it with the freeing function
427          * 'free_context'.
428          */
429         static inline void *afb_req_context(struct afb_req req, void *(*create_context)(), void (*free_context)(void*))
430         {
431                 void *result = afb_req_context_get(req);
432                 if (result == NULL) {
433                         result = create_context();
434                         afb_req_context_set(req, result, free_context);
435                 }
436                 return result;
437         }
438
439 The second argument if the function that creates the context.
440 For the plugin *tic-tac-toe* it is the function **get_new_board**.
441 The function **get_new_board** creates a new board and set its
442 count of use to 1. The boards are counting their count of use
443 to free there ressources when no more used.
444
445 The third argument if the function that frees the context.
446 For the plugin *tic-tac-toe* it is the function **release_board**.
447 The function **release_board** decrease the the count of use of
448 the board given as argument. If the use count decrease to zero,
449 the board data are freed.
450
451 The definition of the other functions for dealing with contexts are:
452
453         /*
454          * Gets the pointer stored by the plugin for the session of 'req'.
455          * When the plugin has not yet recorded a pointer, NULL is returned.
456          */
457         void *afb_req_context_get(struct afb_req req);
458
459         /*
460          * Stores for the plugin the pointer 'context' to the session of 'req'.
461          * The function 'free_context' will be called when the session is closed
462          * or if plugin stores an other pointer.
463          */
464         void afb_req_context_set(struct afb_req req, void *context, void (*free_context)(void*));
465
466         /*
467          * Frees the pointer stored by the plugin for the session of 'req'
468          * and sets it to NULL.
469          *
470          * Shortcut for: afb_req_context_set(req, NULL, NULL)
471          */
472         static inline void afb_req_context_clear(struct afb_req req)
473         {
474                 afb_req_context_set(req, NULL, NULL);
475         }
476
477 ### Sending the reply to a request
478
479 Two kinds of replies can be made: successful replies and
480 failure replies.
481
482 > Sending a reply to a request must be done at most one time.
483
484 The two functions to send a reply of kind "success" are
485 **afb_req_success** and **afb_req_success_f**.
486
487         /*
488          * Sends a reply of kind success to the request 'req'.
489          * The status of the reply is automatically set to "success".
490          * Its send the object 'obj' (can be NULL) with an
491          * informationnal comment 'info (can also be NULL).
492          */
493         void afb_req_success(struct afb_req req, struct json_object *obj, const char *info);
494
495         /*
496          * Same as 'afb_req_success' but the 'info' is a formatting
497          * string followed by arguments.
498          */
499         void afb_req_success_f(struct afb_req req, struct json_object *obj, const char *info, ...);
500
501 The two functions to send a reply of kind "failure" are
502 **afb_req_fail** and **afb_req_fail_f**.
503
504         /*
505          * Sends a reply of kind failure to the request 'req'.
506          * The status of the reply is set to 'status' and an
507          * informationnal comment 'info' (can also be NULL) can be added.
508          *
509          * Note that calling afb_req_fail("success", info) is equivalent
510          * to call afb_req_success(NULL, info). Thus even if possible it
511          * is strongly recommanded to NEVER use "success" for status.
512          */
513         void afb_req_fail(struct afb_req req, const char *status, const char *info);
514
515         /*
516          * Same as 'afb_req_fail' but the 'info' is a formatting
517          * string followed by arguments.
518          */
519         void afb_req_fail_f(struct afb_req req, const char *status, const char *info, ...);
520
521 Getting argument of invocation
522 ------------------------------
523
524 Many verbs expect arguments. Afb-daemon let plugins
525 retrieve their arguments by name not by position.
526
527 Arguments are given by the requests either through HTTP
528 or through WebSockets.
529
530 For example, the verb **join** of the plugin **tic-tac-toe**
531 expects one argument: the *boardid* to join. Here is an extract:
532
533         /*
534          * Join a board
535          */
536         static void join(struct afb_req req)
537         {
538                 struct board *board, *new_board;
539                 const char *id;
540
541                 /* retrieves the context for the session */
542                 board = board_of_req(req);
543                 INFO(afbitf, "method 'join' called for boardid %d", board->id);
544
545                 /* retrieves the argument */
546                 id = afb_req_value(req, "boardid");
547                 if (id == NULL)
548                         goto bad_request;
549                 ...
550
551 The function **afb_req_value** search in the request *req*
552 for an argument whose name is given. When no argument of the
553 given name was passed, **afb_req_value** returns NULL.
554
555 > The search is case sensitive. So the name *boardid* is not the
556 > same name than *BoardId*. But this must not be assumed so two
557 > expected names of argument should not differ only by case.
558
559 ### Basic functions for querying arguments
560
561 The function **afb_req_value** is defined as below:
562
563         /*
564          * Gets from the request 'req' the string value of the argument of 'name'.
565          * Returns NULL if when there is no argument of 'name'.
566          * Returns the value of the argument of 'name' otherwise.
567          *
568          * Shortcut for: afb_req_get(req, name).value
569          */
570         static inline const char *afb_req_value(struct afb_req req, const char *name)
571         {
572                 return afb_req_get(req, name).value;
573         }
574
575 It is defined as a shortcut to call the function **afb_req_get**.
576 That function is defined as below:
577
578         /*
579          * Gets from the request 'req' the argument of 'name'.
580          * Returns a PLAIN structure of type 'struct afb_arg'.
581          * When the argument of 'name' is not found, all fields of result are set to NULL.
582          * When the argument of 'name' is found, the fields are filled,
583          * in particular, the field 'result.name' is set to 'name'.
584          *
585          * There is a special name value: the empty string.
586          * The argument of name "" is defined only if the request was made using
587          * an HTTP POST of Content-Type "application/json". In that case, the
588          * argument of name "" receives the value of the body of the HTTP request.
589          */
590         struct afb_arg afb_req_get(struct afb_req req, const char *name);
591
592 That function takes 2 parameters: the request and the name
593 of the argument to retrieve. It returns a PLAIN structure of
594 type **struct afb_arg**.
595
596 There is a special name that is defined when the request is
597 of type HTTP/POST with a Content-Type being application/json.
598 This name is **""** (the empty string). In that case, the value
599 of this argument of empty name is the string received as a body
600 of the post and is supposed to be a JSON string.
601
602 The definition of **struct afb_arg** is:
603
604         /*
605          * Describes an argument (or parameter) of a request
606          */
607         struct afb_arg {
608                 const char *name;       /* name of the argument or NULL if invalid */
609                 const char *value;      /* string representation of the value of the argument */
610                                         /* original filename of the argument if path != NULL */
611                 const char *path;       /* if not NULL, path of the received file for the argument */
612                                         /* when the request is finalized this file is removed */
613         };
614
615 The structure returns the data arguments that are known for the
616 request. This data include a field named **path**. This **path**
617 can be accessed using the function **afb_req_path** defined as
618 below:
619
620         /*
621          * Gets from the request 'req' the path for file attached to the argument of 'name'.
622          * Returns NULL if when there is no argument of 'name' or when there is no file.
623          * Returns the path of the argument of 'name' otherwise.
624          *
625          * Shortcut for: afb_req_get(req, name).path
626          */
627         static inline const char *afb_req_path(struct afb_req req, const char *name)
628         {
629                 return afb_req_get(req, name).path;
630         }
631
632 The path is only defined for HTTP/POST requests that send file.
633
634 ### Arguments for received files
635
636 As it is explained just above, clients can send files using
637 HTTP/POST requests.
638
639 Received files are attached to a arguments. For example, the
640 following HTTP fragment (from test/sample-post.html)
641 will send an HTTP/POST request to the method
642 **post/upload-image** with 2 arguments named *file* and
643 *hidden*.
644
645         <h2>Sample Post File</h2>
646         <form enctype="multipart/form-data">
647             <input type="file" name="file" />
648             <input type="hidden" name="hidden" value="bollobollo" />
649             <br>
650             <button formmethod="POST" formaction="api/post/upload-image">Post File</button>
651         </form>
652
653 In that case, the argument named **file** has its value and its
654 path defined and not NULL.
655
656 The value is the name of the file as it was
657 set by the HTTP client and is generally the filename on the
658 client side.
659
660 The path is the path of the file saved on the temporary local storage
661 area of the application. This is a randomly generated and unic filename
662 not linked in any way with the original filename on the client.
663
664 The plugin can use the file at the given path the way that it wants:
665 read, write, remove, copy, rename...
666 But when the reply is sent and the query is terminated, the file at
667 this path is destroyed if it still exist.
668
669 ### Arguments as a JSON object
670
671 Plugins can get all the arguments as one single object.
672 This feature is provided by the function **afb_req_json**
673 that is defined as below:
674
675         /*
676          * Gets from the request 'req' the json object hashing the arguments.
677          * The returned object must not be released using 'json_object_put'.
678          */
679         struct json_object *afb_req_json(struct afb_req req);
680
681 It returns a json object. This object depends on how the request was
682 made:
683
684 - For HTTP requests, this is an object whose keys are the names of the
685 arguments and whose values are either a string for common arguments or
686 an object like { "file": "...", "path": "..." }
687
688 - For WebSockets requests, the returned object is the object
689 given by the client transparently transported.
690
691 > In fact, for Websockets requests, the function **afb_req_value**
692 > can be seen as a shortcut to
693 > *json_object_get_string(json_object_object_get(afb_req_json(req), name))*
694
695 Sending messages to the log system
696 ----------------------------------
697
698 How to build a plugin
699 ---------------------
700
701 Afb-daemon provides a *pkg-config* configuration file.
702
703