Compiled and tested examples¶
These listings are included directly from sources compiled or executed by CI.
C quickstart¶
1#include <postproject/postproject.h>
2
3#include <stdio.h>
4
5static void print_asset_id(const pp_asset_id_t *id) {
6 for (size_t index = 0; index < sizeof(id->bytes); ++index) {
7 printf("%02x", id->bytes[index]);
8 }
9 putchar('\n');
10}
11
12int main(int argc, char **argv) {
13 if (argc != 3) {
14 fprintf(stderr,
15 "usage: postproject-c-example OUTPUT_PRODUCTION MEDIA_FILE\n");
16 return 2;
17 }
18
19 /* Every handle starts as NULL and is released exactly once at the end.
20 * Release functions accept NULL, so one cleanup path serves every outcome. */
21 pp_production_t *production = NULL;
22 pp_transaction_t *transaction = NULL;
23 pp_representation_set_t *representations = NULL;
24 pp_error_t *error = NULL;
25 pp_asset_id_t asset_id = {{0}};
26 pp_representation_id_t representation_id = {{0}};
27
28 /* Each fallible call returns a status code. On failure it transfers a
29 * caller-owned error handle, so the chain stops at the first failure and
30 * never overwrites an error that still has to be released. */
31 pp_error_code_t status =
32 pp_production_create(argv[1], "C quickstart", &production, &error);
33 if (status == PP_OK) {
34 status = pp_production_begin_edit(production, NULL, NULL, &transaction, &error);
35 }
36 /* A media source describes the file to import; the transaction borrows it
37 * only for the call. */
38 if (status == PP_OK) {
39 status = pp_transaction_import_file(transaction, argv[2], NULL, &asset_id, &representation_id, &error);
40 }
41 /* Staged work becomes durable only on commit. Releasing a transaction that
42 * was not committed discards everything staged in it. */
43 if (status == PP_OK) {
44 pp_commit_receipt_t commit_receipt;
45 status = pp_transaction_commit(transaction, &commit_receipt, &error);
46 }
47 /* The result set is caller-owned; strings read from it borrow the set. */
48 if (status == PP_OK) {
49 status = pp_production_representation(production, representation_id,
50 &representations, &error);
51 }
52 pp_locator_id_t locator_id = {{0}};
53 const char *uri = NULL;
54 pp_locator_availability_t availability = 0;
55 uint8_t has_last_seen = 0;
56 int64_t last_seen = 0;
57 uint8_t has_sequence_naming = 0;
58 pp_sequence_naming_t sequence_naming;
59 if (status == PP_OK) {
60 status = pp_representation_set_get_locator(
61 representations, 0, 0, 0, &locator_id, &uri, &availability,
62 &has_last_seen, &last_seen, &has_sequence_naming, &sequence_naming,
63 &error);
64 }
65
66 if (status != PP_OK) {
67 /* Branch on the code; the message is diagnostic text for people. The
68 * message is borrowed from the error handle. */
69 fprintf(stderr, "operation failed (%u): %s\n", status,
70 error != NULL ? pp_error_message(error) : "no details");
71 } else {
72 print_asset_id(&asset_id);
73 printf("representations: %llu\n",
74 (unsigned long long)pp_representation_set_count(representations));
75 /* Use borrowed strings before releasing the set that owns them. */
76 printf("location: %s\n", uri);
77 }
78 pp_error_release(error);
79 pp_representation_set_release(representations);
80 pp_transaction_release(transaction);
81 pp_production_release(production);
82 return status == PP_OK ? 0 : 1;
83}
C++17 quickstart¶
1#include <postproject/postproject.hpp>
2
3#include <iostream>
4#include <string>
5#include <utility>
6
7namespace {
8
9constexpr const char *editorial = "https://example.com/ns/editorial/1";
10
11// code() is stable to branch on; message() is diagnostic text for people.
12void report(const postproject::Error &error) {
13 std::cerr << "operation failed (" << static_cast<unsigned>(error.code())
14 << "): " << error.message() << '\n';
15}
16
17// Passes every failure on to its caller, one line per call, so it also builds
18// with -fno-exceptions. POSTPROJECT_TRY_ASSIGN returns the error of a failed
19// Result and otherwise declares the value; POSTPROJECT_TRY does the same for
20// Result<void>.
21postproject::Result<postproject::AssetId> import_media(const std::string &output,
22 const std::string &media) {
23 // Owned handles are move-only; the macro moves the value out of its Result.
24 POSTPROJECT_TRY_ASSIGN(
25 auto production,
26 postproject::Production::create(output, "C++ quickstart"));
27 POSTPROJECT_TRY_ASSIGN(auto transaction, production.edit());
28 // A failure returns here and destroys the open transaction, which discards
29 // its work.
30 POSTPROJECT_TRY_ASSIGN(const auto imported,
31 transaction.importMedia(media, "Quickstart media"));
32 POSTPROJECT_TRY(transaction.commit());
33 return imported.asset_id;
34} // The production handle closes here.
35
36// Invalid input does not fail when it is built; the consuming call reports it.
37bool rejects_invalid_metadata(postproject::Production &production,
38 const postproject::AssetId &asset_id) {
39 const auto duration = postproject::MetadataValue::decimal("twelve", 2);
40 auto transaction = production.edit();
41 if (!transaction.has_value()) {
42 report(transaction.error());
43 return false;
44 }
45 const postproject::ObjectRef asset = postproject::ObjectRef::asset(asset_id);
46 const auto added =
47 transaction->addMetadataValue(asset, editorial, "duration", duration);
48 return !added.has_value() &&
49 added.error().code() == postproject::ErrorCode::invalid_argument;
50} // Never committed: releasing the transaction rolls it back.
51
52} // namespace
53
54int main(int argc, char **argv) {
55 if (argc != 3) {
56 std::cerr
57 << "usage: postproject-cpp-example OUTPUT_PRODUCTION MEDIA_FILE\n";
58 return 2;
59 }
60
61 // Check a Result explicitly where the failure is handled.
62 const auto asset_id = import_media(argv[1], argv[2]);
63 if (!asset_id.has_value()) {
64 report(asset_id.error());
65 return 1;
66 }
67
68 // Where exceptions are enabled, value() unwraps a Result and throws
69 // postproject::Exception on failure.
70 try {
71 auto production = postproject::Production::open(argv[1]).value();
72 std::cout << "representations: "
73 << production.representations(*asset_id).value().size() << '\n';
74 if (!rejects_invalid_metadata(production, *asset_id)) {
75 std::cerr << "invalid metadata input was accepted\n";
76 return 1;
77 }
78 } catch (const postproject::Exception &error) {
79 report(error.error());
80 return 1;
81 }
82}
Python quickstart¶
1"""Create a production and import one opaque media fixture."""
2
3from __future__ import annotations
4
5import argparse
6from concurrent.futures import ThreadPoolExecutor
7from pathlib import Path
8
9from postproject import OriginIdentity, Production
10
11
12class Cancelled(Exception):
13 """Raised to abandon a change before it is committed."""
14
15
16def main() -> None:
17 parser = argparse.ArgumentParser()
18 parser.add_argument("production", type=Path)
19 parser.add_argument("media", type=Path)
20 parser.add_argument(
21 "--library",
22 type=Path,
23 help="native library to load instead of POSTPROJECT_LIBRARY",
24 )
25 args = parser.parse_args()
26
27 # library_path=None falls back to the POSTPROJECT_LIBRARY variable. The
28 # binding never searches the working directory or the loader path.
29 with Production.create(
30 args.production, "Python quickstart", library_path=args.library
31 ) as production:
32 # Commit explicitly; an uncommitted context always rolls back.
33 with production.edit(
34 origin=OriginIdentity("org.postproject:python-quickstart"),
35 message="Import quickstart media",
36 ) as transaction:
37 asset_id = transaction.import_media(
38 args.media, display_name="Quickstart media"
39 ).asset_id
40 transaction.commit()
41
42 # An exception escaping the context rolls the transaction back.
43 try:
44 with production.edit() as transaction:
45 transaction.add_media_root("proxies")
46 raise Cancelled
47 except Cancelled:
48 pass
49 assert production.media_roots == ()
50
51 # Threads may share one production; calls on it serialize internally.
52 with ThreadPoolExecutor(max_workers=4) as pool:
53 counts = list(
54 pool.map(lambda _: len(production.representations[asset_id]), range(4))
55 )
56 print(f"representations: {counts[0]}")
57
58 # A separately opened handle does not wait for calls on the first one,
59 # such as a long commit.
60 reader = Production.open(args.production, library_path=args.library)
61 assert reader.asset_exists(asset_id)
62 reader.close()
63
64 production.close() # The context closed it already; this is harmless.
65
66
67if __name__ == "__main__":
68 main()