Debian Codegraph @

guides/dev/writing-code.md

raw symbols SCIP
1 # Writing code in aws-crt-python
2
3 `aws-crt-python` provides "language bindings", allowing Python to use the
4 C libraries which make up the AWS SDK Common Runtime (CRT).
5
6 You **MUST** read both [Extending Python with C](https://docs.python.org/3/extending/extending.html)
7 and [Coding Guidelines for the aws-c Libraries](https://github.com/awslabs/aws-c-common#coding-guidelines)
8 from top to bottom before going any further in this guide.
9
10 This is not easy code to write. You must know Python. You must know C.
11 You must learn how the aws-c libraries do error handling and memory management,
12 you must learn how the Python C API does error handling and memory management,
13 and you must mix the two styles together. This code is multithreaded and asynchronous.
14 Buckle up.
15
16 ### Table of Contents
17
18 * [Useful Links](#useful-links)
19 * [Writing Python Code](#writing-python-code)
20 * [General](#general-python-rules)
21 * [Naming Conventions](#python-naming-conventions)
22 * [Use Type Hints](#use-type-hints)
23 * [Forward and Backward Compatibility](#forward-and-backward-compatibility)
24 * [Functions with Lots of Arguments](#functions-with-lots-of-arguments)
25 * [Use `None` for Optional Arguments](#use-none-as-the-default-value-for-optional-arguments)
26 * [Callback Signatures](#callback-signatures)
27 * [Be Careful When Adding](#be-careful-when)
28 * [Asynchronous APIs](#asynchronous-apis)
29 * [Don't Add Features](#dont-add-features)
30 * [Lifetime Management](#lifetime-management)
31 * [Terminology](#terminology)
32 * [Strong References / Reference Counting](#strong-references--reference-counting)
33 * [Reference Cycle](#reference-cycle)
34 * [Capsule](#capsule)
35 * [Bindings Design](#bindings-design)
36 * [A More Complex Example](#a-more-complex-example)
37 * [The Wrong Way to Build it](#the-wrong-way-to-build-it)
38 * [Option 1 - Pass Callbacks to C](#option-1---pass-callbacks-to-c)
39 * [Option 2 - Private Core Class](#option-2---private-core-class)
40 * [Writing C Code](#writing-c-code)
41
42 ## Useful Links
43 * Required reading:
44 * [Extending Python with C](https://docs.python.org/3/extending/extending.html)
45 * [Coding Guidelines for the aws-c Libraries](https://github.com/awslabs/aws-c-common#coding-guidelines)
46 * Reference pages you'll visit 3x per day:
47 * [Format strings: Python -> C](https://docs.python.org/3/c-api/arg.html) -
48 Used by [PyArg_ParseTuple()](https://docs.python.org/3/c-api/arg.html#c.PyArg_ParseTuple)
49 * [Format strings: C -> Python](https://docs.python.org/3/c-api/arg.html#c.Py_BuildValue) -
50 Used by [Py_BuildValue()](https://docs.python.org/3/c-api/arg.html#c.Py_BuildValue),
51 [PyObject_CallMethod()](https://docs.python.org/3/c-api/call.html#c.PyObject_CallMethod), and
52 [PyObject_CallFunction()](https://docs.python.org/3/c-api/call.html#c.PyObject_CallFunction)
53
54 # Writing Python Code
55
56 Follow these conventions unless you have a very convincing reason not to.
57 We acknowledge that our existing code isn't 100% consistent at following them.
58 Some features we recommend now weren't available in older versions of
59 Python that we used to support. Some conventions are due to lessons learned
60 when we had a hard time making changes to something without breaking its API.
61 And sometimes naming is inconsistent because the code had different authors
62 and our conventions weren't written down yet. But going forward
63 let's do it right.
64
65 ## General Python Rules
66
67 ### Python Naming Conventions
68
69 * Modules (files and folders) - `lowercase`
70 * Smoosh words together, if it's not too confusing.
71 * Example - `awscrt.eventstream` (NOT `aws_crt.event_stream`)
72 * Classes - `UpperCamelCase`
73 * For acronyms three letters or longer, only capitalize the first letter
74 * Example: `TlsContext` (NOT `TLSContext`)
75 * Don't repeat words in the full path.
76 * Example: `awscrt.mqtt.Client` (NOT `awscrt.mqtt.MqttClient`)
77 * Member variables - `snake_case`
78 * Functions - `snake_case()`
79 * Anything private - prefix with underscore
80 * Constants and Enum values - `ALL_CAPS`
81 * Example: `MessageType.PING`
82 * Time values - suffix with `_ms`, `_sec`, etc
83
84 ### Use Type Hints
85
86 Use [type hints](https://docs.python.org/3/library/typing.html) in your APIs.
87 They help users and make it easier to write documentation.
88 Sadly, most of our existing code isn't using type hints because it was written
89 back when we supported older versions of Python
90 (TODO: add type hints to all our APIs).
91 Because type hints are newer, pay close attention in the docs before you use a feature,
92 to ensure it's available in our minimum supported Python version.
93 (TODO: add CI tests that would catch such errors)
94
95 ## Forward and Backward compatibility
96
97 We need to design our APIs so that they don't break when we inevitably
98 add a few more configuration options to a class.
99 Follow these rules so we can gracefully alter the API without breaking it.
100
101 ### Functions with Lots of Arguments
102
103 For functions with a lot of configuration options,
104 such as class `__init__()` functions, use one of the techniques below.
105 Complex functions inevitably get more optional arguments added over time.
106 Sometimes an argument even changes from required to optional.
107
108 TECHNIQUE 1 - Use [keyword-only](https://docs.python.org/3/tutorial/controlflow.html#keyword-only-arguments) arguments.
109 These let you introduce more arguments over time,
110 and they let you change an argument from required to optional.
111 They can also make user code more clear (i.e. `do_a_thing(ignore_errors=True)` vs `do_a_thing(True)`).
112 Example:
113 ```py
114 class Client:
115 def __init__(self, *,
116 hostname: str, # this is required, but must be passed by keyword
117 port: int, # again, required
118 bootstrap: ClientBootstrap = None, # optional
119 connect_timeout_ms: int = None): # optional
120 ```
121
122 TECHNIQUE 2 - Use an "options class", and pass that as the only argument.
123 It's easy to build these as a [dataclass](https://docs.python.org/3/library/dataclasses.html).
124 Example:
125 ```py
126 @dataclass
127 class ClientOptions:
128 hostname: str
129 port: int
130 bootstrap: ClientBootstrap = None
131 connect_timeout_ms: int = None
132
133 class Client:
134 def __init__(self, options: ClientOptions):
135 ```
136
137 The jury's currently out on which technique is better. Keyword arguments are graceful,
138 but "options classes" let us easily nest one set of options inside another set of options.
139
140 ### Use `None` as the Default Value for Optional Arguments
141
142 Note in the examples above that `connect_timeout_ms` had a default value of `=None`,
143 instead of something concrete like `=5000`. This is a common in Python,
144 and a good practice besides. Default values sometimes change.
145 There are many aws-crt language bindings, and the fewer places something is hardcoded,
146 the easier it is to change. Ideally, all language bindings use `None` or similar
147 to represent "defaults please", which results in passing `0` or `NULL` down to C to
148 represent "defaults please", and then in a single location in C we set the actual default.
149
150 In documentation, just say "a default value is used" instead of writing in the actual value,
151 because the odds are good that the documentation will get out of sync with reality.
152
153 ### Callback Signatures
154
155 Similar to how we build `__init__()` functions so that more options can be added over time,
156 we need to build callbacks so that more info can be passed to them in the future.
157
158 Public callbacks should take a single argument, which is built as a `dataclass`.
159 This gives us freedom to add members to the class in the future.
160
161 Example:
162 ```py
163 @dataclass
164 class Message:
165 topic: str
166 payload: bytes
167
168 class Client:
169 def __init__(self, *,
170 ...,
171 on_message_received: Callable[[Message], None] = None,
172 ...)
173
174 # and then user code looks like:
175 def my_on_message_received_callback(msg):
176 print(f'Yay I got a Message: {msg}')
177 ```
178
179 NOTE: Most of our existing code uses a different pattern for callbacks.
180 Instead of a single `dataclass` argument, multiple arguments are passed by keyword.
181 In documentation, we instruct the user to add `**kwargs` as the last argument in their function,
182 so that we are free to add more arguments over time without breaking user code.
183 This is weirder and more fragile than passing a single object.
184 Don't use this pattern unless you're adding to a class where it's already in use.
185
186 ### Be careful when adding
187
188 1) When adding arguments to a function that is NOT using keyword-only arguments,
189 you MUST add new arguments to the end of the argument list.
190 Otherwise you may break user code that passes arguments by position.
191
192 2) When adding new members to a `dataclass`, you MUST add new members at the end.
193 Otherwise you may break user code that initializes the class using positional arguments.
194 (in Python 3.10+ there's a `kw_only` feature for `dataclass`,
195 but we can't use it since we support older Python versions)
196
197 ## Asynchronous APIs
198
199 TODO: document when to use future vs callback
200
201 ## Don't Add Features
202
203 When binding an API from the aws-c libraries, don't start adding extra features.
204 If you're tempted to add any "special logic" that would be valuable to the other aws-crt language bindings,
205 add that logic in the underlying aws-c library so that every other language can benefit.
206
207 Even for trivial things like picking nice default values, put it in the underlying aws-c library.
208 (see [Use `None` for Optional Arguments](#use-none-as-the-default-value-for-optional-arguments)).
209
210 # Lifetime Management
211
212 ## Terminology
213
214 ### Strong References / Reference Counting
215
216 A "strong reference" is one that keeps an object alive by incrementing its reference count.
217 To "release" the reference is to decrement the object's reference count.
218 When all references to an object are released, its reference count goes to zero and it gets cleaned up.
219
220 In pure Python code, every variable is a strong reference to an object.
221 When the variable goes away, the reference is released.
222
223 In C code, reference counts on Python objects are controlled using `Py_INCREF(x)` and `Py_DECREF(x)`.
224 Structs from the aws-c libraries have `_acquire(x)` and `_release(x)` calls to control their reference counts.
225 We'll talk more about this [later](#reference-counting-in-c).
226
227 ### Reference Cycle
228
229 A "reference cycle" is when a circle of strong references is created.
230 Reference cycles cause memory to leak because the reference counts never get to zero.
231
232 Python has a [garbage collector](https://devguide.python.org/internals/garbage-collector)
233 that can detect and clean up reference cycles among normal Python objects.
234 HOWEVER, any cycle involving a `Py_INCREF(x)` from C creates an undetectable cycle.
235 You MUST NOT create reference cycles when designing bindings.
236
237 ### Capsule
238
239 [PyCapsule](https://docs.python.org/3/extending/extending.html#using-capsules)
240 lets us bind the lifetime of a C struct to the lifetime of a Python object.
241 It's a Python object that holds a C pointer and a "destructor" function pointer.
242 When Python cleans up the `PyCapsule`, the destructor function will be called.
243
244 ## Bindings Design
245
246 Let's look at the bindings for `aws_event_loop_group` (our I/O thread pool).
247 This diagram shows the strong references between objects in Python and C:
248
249 ![Diagram of Simple Binding](./binding-simple.svg)
250
251 Description of parts (from bottom to top):
252 * `aws_event_loop_group` - The underlying native implementation struct,
253 which knows nothing about Python.
254 * Lives in C library: [aws-c-io](https://github.com/awslabs/aws-c-io)
255 * Git submodule location: [crt/aws-c-io](/crt/aws-c-io)
256 * Header file: [<aws/io/event_loop.h>](https://github.com/awslabs/aws-c-io/blob/main/include/aws/io/event_loop.h)
257 * `event_loop_group_binding` - The "bindings" struct.
258 Holds a strong reference to the underlying native implementation (usually in a member variable named "native")
259 * Lives in Python/C extension module: `_awscrt`
260 * Source file: [source/io.c](/source/io.c)
261 * `PyCapsule` - The Python object which "owns" the pointer to `event_loop_group_binding`.
262 * `EventLoopGroup` - The Python class that users create and interact with.
263 Holds a reference to the `PyCapsule` in a member variable named "_binding".
264 * Lives in Python module: `awscrt.io`
265 * Source File: [awscrt/io.py](/awscrt/io.py)
266
267 Creation goes like this:
268 * User's Python code creates an `EventLoopGroup`:
269 ```py
270 elg = EventLoopGroup()
271 ```
272 * `EventLoopGroup` initializer looks something like:
273 ```py
274 class EventLoopGroup:
275 def __init__(self, ...):
276 self._binding = _awscrt.event_loop_group_new(...)
277 ```
278 * `_awscrt.event_loop_group_new(...)` is Python calling down into C.
279 The C function looks something like:
280 ```C
281 PyObject *aws_py_event_loop_group_new(PyObject *self, PyObject *args) {
282 // ...parse arguments...
283
284 // allocate memory for binding struct
285 struct event_loop_group_binding *binding = aws_mem_calloc(...);
286
287 // create underlying implementation
288 binding->native = aws_event_loop_group_new(...);
289
290 // create PyCapsule which owns the binding struct.
291 // pass in "destructor" function that runs when
292 // PyCapsule is cleaned up by the garbage collector.
293 PyObject *capsule = PyCapsule_New(binding, on_capsule_destroyed_fn);
294 return capsule;
295 }
296 ```
297 * Things stay alive because:
298 * The user's `elg` variable keeps the `EventLoopGroup` object alive.
299 * Member variable `EventLoopGroup._binding` keeps the `PyCapsule` alive.
300 * The `PyCapsule` keeps the `struct event_loop_group_binding` alive.
301 * The `event_loop_group_binding.native` pointer is a "strong reference" that keeps
302 `struct aws_event_loop_group` alive.
303
304
305 Destruction goes like this (it's actually more complex, we'll cover that later):
306 * When the user's Python code has no references to `elg`, the `EventLoopGroup` instance...
307 * The garbage collector cleans up the `EventLoopGroup`,
308 and the `PyCapsule` referenced by `EventLoopGroup._binding`.
309 * The `PyCapsule`'s destructor function runs, which looks something like:
310 ```C
311 static on_capsule_destroyed_fn(PyObject *capsule) {
312 struct event_loop_group_binding *binding = PyCapsule_GetPointer(capsule);
313
314 // release reference to underlying implementation
315 aws_event_loop_group_release(binding->native)
316
317 // free binding struct's memory
318 aws_mem_release(binding);
319 }
320 ```
321 * IF nothing else has a strong reference to `struct aws_event_loop_group`:
322 * then it begins its shutdown process, and its memory is cleaned up when shutdown completes.
323 * ELSE something else has a strong reference to `struct aws_event_loop_group`:
324 * so it won't begin its shutdown until the last reference is released.
325
326 Note: In the past, the aws-c libraries didn't have reference counting for any C structs.
327 You will still find older code in our Python bindings that tries to keep the entire dependency trees
328 of Python objects alive via `Py_INCREF(x)` (TODO: remove needless complexity).
329 You can't always look at existing code to see "the right way" of doing things.
330
331 ## A More Complex Example
332
333 The sample above is simplified, it only shows Python calling into C.
334 But `aws_event_loop_group` has a callback that fires when it finishes shutting down.
335 That means C needs to call into Python AFTER the Python `EventLoopGroup` object has been cleaned up.
336
337 For C to call into Python, it must reference a Python object
338 (the function itself, or an object with a member function).
339 This means our binding needs to store a strong reference and
340 keep that Python object alive until the callback has fired.
341
342 ### The Wrong Way to Build it
343
344 You MUST NOT create a reference cycle!
345
346 You might be tempted to give `event_loop_group_binding` a strong reference to the `EventLoopGroup` instance.
347 Then C could simply call a private member function like `EventLoopGroup._on_shutdown_complete()`.
348 But this design creates a reference cycle (see image below):
349
350 ![Diagram of bad binding with reference cycle](./binding-bad-cycle.svg)
351
352 ### Option 1 - Pass Callbacks to C
353
354 Most of our bindings work like this:
355
356 ![Diagram where C References callbacks](binding-callbacks.svg)
357
358 Creation is similar to the [simple binding](#bindings-design), except:
359 * Within `EventLoopGroup.__init__()` a "callable" is defined and passed down to C.
360 The code looks something like:
361 ```py
362 class EventLoopGroup:
363 def __init__(self, ...):
364
365 # define callable local function
366 def shutdown_callback():
367 ...do stuff...
368
369 self._binding = _awscrt.event_loop_group_new(shutdown_callback, ...)
370 ```
371 * `event_loop_group_binding` keeps a strong reference to this Python object.
372 The extra code looks something like:
373 ```C
374 PyObject *aws_py_event_loop_group_new(PyObject *self, PyObject *args) {
375 // ...parse arguments, creating binding struct, etc same as before...
376
377 // store strong reference to callable
378 binding->py_shutdown_callback = Py_INCREF(py_shutdown_callback);
379 ```
380
381 When the final shutdown callback happens in C, the Python callable
382 is invoked, and then the reference is released via `Py_DECREF(x)`.
383
384 Destruction goes like this:
385 * When the Python code has no references to `elg`, the `EventLoopGroup` instance...
386 * The garbage collector cleans up the `EventLoopGroup`,
387 and the `PyCapsule` referenced by `EventLoopGroup._binding`.
388 * The `PyCapsule` runs its destructor function.
389 * The destructor function calls `aws_event_loop_group_release(binding->native)`,
390 but doesn't delete the `event_loop_group_binding` struct yet.
391 * The `aws_event_loop_group` won't shutdown until nothing else is referencing it.
392 Even when the final reference is released, it still needs to wait for the threads
393 in its thread-pool to finish their shutdown process.
394 * Finally, shutdown completes and the C callback is invoked.
395 * The C callback invokes the Python `callable`, then releases it via `Py_DECREF(x)`.
396 * Now the garbage collector can clean up the `callable` object.
397 * The C callback finally deletes the `event_loop_group_binding`.
398 This struct only existed to keep two strong references,
399 but now they've both been released.
400
401 ### Option 2 - Private Core Class
402
403 Another option is to build a private `_Core` class containing anything
404 that may need to outlive the main Python object:
405
406 ![Diagram with private Core class](./binding-private-core.svg)
407
408 This is similar to [Option 1](#option-1---pass-callbacks-to-c),
409 but we write callbacks as member functions on the `_Core` class,
410 instead of defining local functions within the body of `EventLoopGroup.__init__(self)`.
411 Code looks something like:
412 ```py
413 class EventLoopGroup:
414 def __init__(self, ...):
415 core = _EventLoopGroupCore()
416 self._binding = _awscrt.event_loop_group_new(core, ...)
417
418 class _EventLoopGroupCore:
419 def shutdown_callback(self):
420 ...do stuff...
421 ```
422
423 This technique hasn't actually been used, but the author of this doc
424 thinks it might be a graceful way to build in the future.
425
426 # Writing C Code
427
428 ## Reference Counting in C
429
430 Read python.org's guide to [Extending Python with C](https://docs.python.org/3/extending/extending.html)
431 from top to bottom. It does an excellent job teaching about reference counts.
432
433 Great, now you know what "strong references" and "borrowed references"
434 are, all about `Py_INCREF(x)` and `Py_DECREF(x)` and when you do an do not
435 need to call them. You know that you must be EXTREMELY CAREFUL with reference
436 counts, because if you don't do it PERFECTLY then you will leak memory,
437 or crash due to double-free, or crash due use-after-free.
438 Thanks for reading that guide in full.
439
440 Read the docs for EVERY SINGLE Python API call you make in C,
441 to see whether it returns a new reference or borrowed reference.
442 You should add `/* new reference */` and `/* borrowed reference */` comments
443 next to these calls so it's clear to any future people that touch this code.
444
445 You are also encouraged to use [Py_XDECREF(x)](https://docs.python.org/3/c-api/refcounting.html#c.Py_XDECREF)
446 and [Py_CLEAR(x)](https://docs.python.org/3/c-api/refcounting.html#c.Py_CLEAR),
447 which are safer versions of the basic `Py_DECREF(x)`.
448
449 In the aws-c libraries, reference counting on structs is done using `_acquire(x)` and `_release(x)` functions.
450 Structs will keep each other alive as long as necessary using these functions.
451 For example, `struct aws_http_connection` needs `struct aws_event_loop_group` (an I/O thread pool)
452 to exist for the duration of the connection.
453 Therefore, the connection's creation function takes a pointer to the thread pool
454 and calls `aws_event_loop_group_acquire(x)` to keep it alive.
455 When the connection dies it calls `aws_event_loop_group_release(x)` to release
456 the thread pool.
457
458 Not every struct in the aws-c libraries has `_acquire(x)` and `_release(x)` functions
459 (simple datastructures like `struct aws_byte_buf` are not reference counted).
460 Only heap-allocated structs with complex or unpredictable lifetimes have these functions.
461 Every struct bound to a Python class is considered to have an unpredictable lifetime
462 because we don't know what our users' Python code will look like.
463 We can't assume a Python programmer will carefully store variables to each item
464 in a tree of dependencies, ensuring everything stays alive for "the right" length of time.
465 Python programmers just don't work that way, and they shouldn't.
466 Python is a garbage collected language. Garbage collected languages exist
467 to free programmers from wasting their time on that kind of tedium.
468
469 TODO:
470 Talk about how our tests can and cannot check for leaks.
471 Talk about which classes require a `close()` function, and which don't.
472 Suggest writing as little C code as possible.
473 Recommend error-handling strategies.
474 Talk about the allocators (tracked vs untracked)
475 Talk about logging. Consider making it easier to turn on logging.
476 Talk about sloppy shutdown.